body
stringlengths
26
98.2k
body_hash
int64
-9,222,864,604,528,158,000
9,221,803,474B
docstring
stringlengths
1
16.8k
path
stringlengths
5
230
name
stringlengths
1
96
repository_name
stringlengths
7
89
lang
stringclasses
1 value
body_without_docstring
stringlengths
20
98.2k
@pytest.mark.integration def test_request_air_drop(stubbed_sender: Keypair, test_http_client: Client): 'Test air drop to stubbed_sender.' resp = test_http_client.request_airdrop(stubbed_sender.public_key, AIRDROP_AMOUNT) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) balance = test_http_client.get_balance(stubbed_sender.public_key) assert (balance['result']['value'] == AIRDROP_AMOUNT)
-2,291,647,084,779,964,700
Test air drop to stubbed_sender.
tests/integration/test_http_client.py
test_request_air_drop
01protocol/solana-py
python
@pytest.mark.integration def test_request_air_drop(stubbed_sender: Keypair, test_http_client: Client): resp = test_http_client.request_airdrop(stubbed_sender.public_key, AIRDROP_AMOUNT) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) balance = test_http_client.get_balance(stubbed_sender.public_key) assert (balance['result']['value'] == AIRDROP_AMOUNT)
@pytest.mark.integration def test_request_air_drop_prefetched_blockhash(stubbed_sender_prefetched_blockhash, test_http_client): 'Test air drop to stubbed_sender.' resp = test_http_client.request_airdrop(stubbed_sender_prefetched_blockhash.public_key, AIRDROP_AMOUNT) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) balance = test_http_client.get_balance(stubbed_sender_prefetched_blockhash.public_key) assert (balance['result']['value'] == AIRDROP_AMOUNT)
-640,933,554,603,742,000
Test air drop to stubbed_sender.
tests/integration/test_http_client.py
test_request_air_drop_prefetched_blockhash
01protocol/solana-py
python
@pytest.mark.integration def test_request_air_drop_prefetched_blockhash(stubbed_sender_prefetched_blockhash, test_http_client): resp = test_http_client.request_airdrop(stubbed_sender_prefetched_blockhash.public_key, AIRDROP_AMOUNT) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) balance = test_http_client.get_balance(stubbed_sender_prefetched_blockhash.public_key) assert (balance['result']['value'] == AIRDROP_AMOUNT)
@pytest.mark.integration def test_request_air_drop_cached_blockhash(stubbed_sender_cached_blockhash, test_http_client): 'Test air drop to stubbed_sender.' resp = test_http_client.request_airdrop(stubbed_sender_cached_blockhash.public_key, AIRDROP_AMOUNT) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) assert_valid_response(resp) balance = test_http_client.get_balance(stubbed_sender_cached_blockhash.public_key) assert (balance['result']['value'] == AIRDROP_AMOUNT)
-6,042,333,614,169,588,000
Test air drop to stubbed_sender.
tests/integration/test_http_client.py
test_request_air_drop_cached_blockhash
01protocol/solana-py
python
@pytest.mark.integration def test_request_air_drop_cached_blockhash(stubbed_sender_cached_blockhash, test_http_client): resp = test_http_client.request_airdrop(stubbed_sender_cached_blockhash.public_key, AIRDROP_AMOUNT) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) assert_valid_response(resp) balance = test_http_client.get_balance(stubbed_sender_cached_blockhash.public_key) assert (balance['result']['value'] == AIRDROP_AMOUNT)
@pytest.mark.integration def test_send_invalid_transaction(test_http_client): 'Test sending an invalid transaction to localnet.' with pytest.raises(RPCException) as exc_info: test_http_client.send_raw_transaction(b'foo') assert (exc_info.value.args[0].keys() == RPCError.__annotations__.keys())
-2,012,700,686,239,229,400
Test sending an invalid transaction to localnet.
tests/integration/test_http_client.py
test_send_invalid_transaction
01protocol/solana-py
python
@pytest.mark.integration def test_send_invalid_transaction(test_http_client): with pytest.raises(RPCException) as exc_info: test_http_client.send_raw_transaction(b'foo') assert (exc_info.value.args[0].keys() == RPCError.__annotations__.keys())
@pytest.mark.integration def test_send_transaction_and_get_balance(stubbed_sender, stubbed_receiver, test_http_client): 'Test sending a transaction to localnet.' transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender.public_key, to_pubkey=stubbed_receiver, lamports=1000))) resp = test_http_client.send_transaction(transfer_tx, stubbed_sender) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) resp = test_http_client.get_balance(stubbed_sender.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999994000) resp = test_http_client.get_balance(stubbed_receiver) assert_valid_response(resp) assert (resp['result']['value'] == 954)
-7,203,235,847,668,948,000
Test sending a transaction to localnet.
tests/integration/test_http_client.py
test_send_transaction_and_get_balance
01protocol/solana-py
python
@pytest.mark.integration def test_send_transaction_and_get_balance(stubbed_sender, stubbed_receiver, test_http_client): transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender.public_key, to_pubkey=stubbed_receiver, lamports=1000))) resp = test_http_client.send_transaction(transfer_tx, stubbed_sender) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) resp = test_http_client.get_balance(stubbed_sender.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999994000) resp = test_http_client.get_balance(stubbed_receiver) assert_valid_response(resp) assert (resp['result']['value'] == 954)
@pytest.mark.integration def test_send_transaction_prefetched_blockhash(stubbed_sender_prefetched_blockhash, stubbed_receiver_prefetched_blockhash, test_http_client): 'Test sending a transaction to localnet.' transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender_prefetched_blockhash.public_key, to_pubkey=stubbed_receiver_prefetched_blockhash, lamports=1000))) recent_blockhash = test_http_client.parse_recent_blockhash(test_http_client.get_recent_blockhash(Finalized)) resp = test_http_client.send_transaction(transfer_tx, stubbed_sender_prefetched_blockhash, recent_blockhash=recent_blockhash) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) resp = test_http_client.get_balance(stubbed_sender_prefetched_blockhash.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999994000) resp = test_http_client.get_balance(stubbed_receiver_prefetched_blockhash) assert_valid_response(resp) assert (resp['result']['value'] == 954)
2,934,369,432,220,612,000
Test sending a transaction to localnet.
tests/integration/test_http_client.py
test_send_transaction_prefetched_blockhash
01protocol/solana-py
python
@pytest.mark.integration def test_send_transaction_prefetched_blockhash(stubbed_sender_prefetched_blockhash, stubbed_receiver_prefetched_blockhash, test_http_client): transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender_prefetched_blockhash.public_key, to_pubkey=stubbed_receiver_prefetched_blockhash, lamports=1000))) recent_blockhash = test_http_client.parse_recent_blockhash(test_http_client.get_recent_blockhash(Finalized)) resp = test_http_client.send_transaction(transfer_tx, stubbed_sender_prefetched_blockhash, recent_blockhash=recent_blockhash) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) resp = test_http_client.get_balance(stubbed_sender_prefetched_blockhash.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999994000) resp = test_http_client.get_balance(stubbed_receiver_prefetched_blockhash) assert_valid_response(resp) assert (resp['result']['value'] == 954)
@pytest.mark.integration def test_send_transaction_cached_blockhash(stubbed_sender_cached_blockhash, stubbed_receiver_cached_blockhash, test_http_client_cached_blockhash): 'Test sending a transaction to localnet.' transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender_cached_blockhash.public_key, to_pubkey=stubbed_receiver_cached_blockhash, lamports=1000))) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) == 0) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) == 0) resp = test_http_client_cached_blockhash.send_transaction(transfer_tx, stubbed_sender_cached_blockhash) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) in (0, 1)) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) == 1) assert_valid_response(resp) test_http_client_cached_blockhash.confirm_transaction(resp['result']) resp = test_http_client_cached_blockhash.get_balance(stubbed_sender_cached_blockhash.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999994000) transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender_cached_blockhash.public_key, to_pubkey=stubbed_receiver_cached_blockhash, lamports=2000))) resp = test_http_client_cached_blockhash.get_balance(stubbed_receiver_cached_blockhash) assert_valid_response(resp) assert (resp['result']['value'] == 954) resp = test_http_client_cached_blockhash.send_transaction(transfer_tx, stubbed_sender_cached_blockhash) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) in (0, 1)) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) in (1, 2)) assert_valid_response(resp) test_http_client_cached_blockhash.confirm_transaction(resp['result']) resp = test_http_client_cached_blockhash.get_balance(stubbed_sender_cached_blockhash.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999987000) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) == 1) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) == 1)
-2,606,448,245,753,757,700
Test sending a transaction to localnet.
tests/integration/test_http_client.py
test_send_transaction_cached_blockhash
01protocol/solana-py
python
@pytest.mark.integration def test_send_transaction_cached_blockhash(stubbed_sender_cached_blockhash, stubbed_receiver_cached_blockhash, test_http_client_cached_blockhash): transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender_cached_blockhash.public_key, to_pubkey=stubbed_receiver_cached_blockhash, lamports=1000))) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) == 0) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) == 0) resp = test_http_client_cached_blockhash.send_transaction(transfer_tx, stubbed_sender_cached_blockhash) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) in (0, 1)) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) == 1) assert_valid_response(resp) test_http_client_cached_blockhash.confirm_transaction(resp['result']) resp = test_http_client_cached_blockhash.get_balance(stubbed_sender_cached_blockhash.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999994000) transfer_tx = Transaction().add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender_cached_blockhash.public_key, to_pubkey=stubbed_receiver_cached_blockhash, lamports=2000))) resp = test_http_client_cached_blockhash.get_balance(stubbed_receiver_cached_blockhash) assert_valid_response(resp) assert (resp['result']['value'] == 954) resp = test_http_client_cached_blockhash.send_transaction(transfer_tx, stubbed_sender_cached_blockhash) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) in (0, 1)) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) in (1, 2)) assert_valid_response(resp) test_http_client_cached_blockhash.confirm_transaction(resp['result']) resp = test_http_client_cached_blockhash.get_balance(stubbed_sender_cached_blockhash.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999987000) assert (len(test_http_client_cached_blockhash.blockhash_cache.unused_blockhashes) == 1) assert (len(test_http_client_cached_blockhash.blockhash_cache.used_blockhashes) == 1)
@pytest.mark.integration def test_send_raw_transaction_and_get_balance(stubbed_sender, stubbed_receiver, test_http_client): 'Test sending a raw transaction to localnet.' resp = test_http_client.get_recent_blockhash(Finalized) assert_valid_response(resp) recent_blockhash = resp['result']['value']['blockhash'] transfer_tx = Transaction(recent_blockhash=recent_blockhash).add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender.public_key, to_pubkey=stubbed_receiver, lamports=1000))) transfer_tx.sign(stubbed_sender) resp = test_http_client.send_raw_transaction(transfer_tx.serialize()) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) resp = test_http_client.get_balance(stubbed_sender.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999988000) resp = test_http_client.get_balance(stubbed_receiver) assert_valid_response(resp) assert (resp['result']['value'] == 1954)
-5,284,283,721,395,446,000
Test sending a raw transaction to localnet.
tests/integration/test_http_client.py
test_send_raw_transaction_and_get_balance
01protocol/solana-py
python
@pytest.mark.integration def test_send_raw_transaction_and_get_balance(stubbed_sender, stubbed_receiver, test_http_client): resp = test_http_client.get_recent_blockhash(Finalized) assert_valid_response(resp) recent_blockhash = resp['result']['value']['blockhash'] transfer_tx = Transaction(recent_blockhash=recent_blockhash).add(sp.transfer(sp.TransferParams(from_pubkey=stubbed_sender.public_key, to_pubkey=stubbed_receiver, lamports=1000))) transfer_tx.sign(stubbed_sender) resp = test_http_client.send_raw_transaction(transfer_tx.serialize()) assert_valid_response(resp) test_http_client.confirm_transaction(resp['result']) resp = test_http_client.get_balance(stubbed_sender.public_key) assert_valid_response(resp) assert (resp['result']['value'] == 9999988000) resp = test_http_client.get_balance(stubbed_receiver) assert_valid_response(resp) assert (resp['result']['value'] == 1954)
@pytest.mark.integration def test_confirm_bad_signature(test_http_client: Client) -> None: 'Test that RPCException is raised when trying to confirm an invalid signature.' with pytest.raises(RPCException) as exc_info: test_http_client.confirm_transaction('foo') err_object = exc_info.value.args[0] assert (err_object == {'code': (- 32602), 'message': 'Invalid param: WrongSize'})
-2,626,943,452,092,883,000
Test that RPCException is raised when trying to confirm an invalid signature.
tests/integration/test_http_client.py
test_confirm_bad_signature
01protocol/solana-py
python
@pytest.mark.integration def test_confirm_bad_signature(test_http_client: Client) -> None: with pytest.raises(RPCException) as exc_info: test_http_client.confirm_transaction('foo') err_object = exc_info.value.args[0] assert (err_object == {'code': (- 32602), 'message': 'Invalid param: WrongSize'})
@pytest.mark.integration def test_get_block_commitment(test_http_client): 'Test get block commitment.' resp = test_http_client.get_block_commitment(5) assert_valid_response(resp)
-2,038,116,871,298,546,000
Test get block commitment.
tests/integration/test_http_client.py
test_get_block_commitment
01protocol/solana-py
python
@pytest.mark.integration def test_get_block_commitment(test_http_client): resp = test_http_client.get_block_commitment(5) assert_valid_response(resp)
@pytest.mark.integration def test_get_block_time(test_http_client): 'Test get block time.' resp = test_http_client.get_block_time(5) assert_valid_response(resp)
3,209,524,844,837,406,700
Test get block time.
tests/integration/test_http_client.py
test_get_block_time
01protocol/solana-py
python
@pytest.mark.integration def test_get_block_time(test_http_client): resp = test_http_client.get_block_time(5) assert_valid_response(resp)
@pytest.mark.integration def test_get_cluster_nodes(test_http_client): 'Test get cluster nodes.' resp = test_http_client.get_cluster_nodes() assert_valid_response(resp)
3,587,021,986,804,595,700
Test get cluster nodes.
tests/integration/test_http_client.py
test_get_cluster_nodes
01protocol/solana-py
python
@pytest.mark.integration def test_get_cluster_nodes(test_http_client): resp = test_http_client.get_cluster_nodes() assert_valid_response(resp)
@pytest.mark.integration def test_get_confirmed_block(test_http_client): 'Test get confirmed block.' resp = test_http_client.get_confirmed_block(1) assert_valid_response(resp)
5,960,254,041,551,028,000
Test get confirmed block.
tests/integration/test_http_client.py
test_get_confirmed_block
01protocol/solana-py
python
@pytest.mark.integration def test_get_confirmed_block(test_http_client): resp = test_http_client.get_confirmed_block(1) assert_valid_response(resp)
@pytest.mark.integration def test_get_confirmed_block_with_encoding(test_http_client): 'Test get confrimed block with encoding.' resp = test_http_client.get_confirmed_block(1, encoding='base64') assert_valid_response(resp)
-8,159,208,998,341,799,000
Test get confrimed block with encoding.
tests/integration/test_http_client.py
test_get_confirmed_block_with_encoding
01protocol/solana-py
python
@pytest.mark.integration def test_get_confirmed_block_with_encoding(test_http_client): resp = test_http_client.get_confirmed_block(1, encoding='base64') assert_valid_response(resp)
@pytest.mark.integration def test_get_block(test_http_client): 'Test get block.' resp = test_http_client.get_block(1) assert_valid_response(resp)
2,361,608,624,563,062,000
Test get block.
tests/integration/test_http_client.py
test_get_block
01protocol/solana-py
python
@pytest.mark.integration def test_get_block(test_http_client): resp = test_http_client.get_block(1) assert_valid_response(resp)
@pytest.mark.integration def test_get_block_with_encoding(test_http_client): 'Test get block with encoding.' resp = test_http_client.get_block(1, encoding='base64') assert_valid_response(resp)
-5,002,716,983,983,073,000
Test get block with encoding.
tests/integration/test_http_client.py
test_get_block_with_encoding
01protocol/solana-py
python
@pytest.mark.integration def test_get_block_with_encoding(test_http_client): resp = test_http_client.get_block(1, encoding='base64') assert_valid_response(resp)
@pytest.mark.integration def test_get_block_height(test_http_client): 'Test get height.' resp = test_http_client.get_block_height() assert_valid_response(resp)
-7,453,831,949,045,148,000
Test get height.
tests/integration/test_http_client.py
test_get_block_height
01protocol/solana-py
python
@pytest.mark.integration def test_get_block_height(test_http_client): resp = test_http_client.get_block_height() assert_valid_response(resp)
@pytest.mark.integration def test_get_confirmed_blocks(test_http_client): 'Test get confirmed blocks.' resp = test_http_client.get_confirmed_blocks(5, 10) assert_valid_response(resp)
-8,608,567,078,484,479,000
Test get confirmed blocks.
tests/integration/test_http_client.py
test_get_confirmed_blocks
01protocol/solana-py
python
@pytest.mark.integration def test_get_confirmed_blocks(test_http_client): resp = test_http_client.get_confirmed_blocks(5, 10) assert_valid_response(resp)
@pytest.mark.integration def test_get_blocks(test_http_client): 'Test get blocks.' resp = test_http_client.get_blocks(5, 10) assert_valid_response(resp)
-2,450,099,047,604,030,500
Test get blocks.
tests/integration/test_http_client.py
test_get_blocks
01protocol/solana-py
python
@pytest.mark.integration def test_get_blocks(test_http_client): resp = test_http_client.get_blocks(5, 10) assert_valid_response(resp)
@pytest.mark.integration def test_get_confirmed_signature_for_address2(test_http_client): 'Test get confirmed signature for address2.' resp = test_http_client.get_confirmed_signature_for_address2('Vote111111111111111111111111111111111111111', limit=1) assert_valid_response(resp)
4,472,140,064,225,619,500
Test get confirmed signature for address2.
tests/integration/test_http_client.py
test_get_confirmed_signature_for_address2
01protocol/solana-py
python
@pytest.mark.integration def test_get_confirmed_signature_for_address2(test_http_client): resp = test_http_client.get_confirmed_signature_for_address2('Vote111111111111111111111111111111111111111', limit=1) assert_valid_response(resp)
@pytest.mark.integration def test_get_signatures_for_address(test_http_client): 'Test get signatures for addresses.' resp = test_http_client.get_signatures_for_address('Vote111111111111111111111111111111111111111', limit=1) assert_valid_response(resp)
3,295,932,103,030,722,000
Test get signatures for addresses.
tests/integration/test_http_client.py
test_get_signatures_for_address
01protocol/solana-py
python
@pytest.mark.integration def test_get_signatures_for_address(test_http_client): resp = test_http_client.get_signatures_for_address('Vote111111111111111111111111111111111111111', limit=1) assert_valid_response(resp)
@pytest.mark.integration def test_get_epoch_info(test_http_client): 'Test get epoch info.' resp = test_http_client.get_epoch_info() assert_valid_response(resp)
-4,050,810,740,689,471,500
Test get epoch info.
tests/integration/test_http_client.py
test_get_epoch_info
01protocol/solana-py
python
@pytest.mark.integration def test_get_epoch_info(test_http_client): resp = test_http_client.get_epoch_info() assert_valid_response(resp)
@pytest.mark.integration def test_get_epoch_schedule(test_http_client): 'Test get epoch schedule.' resp = test_http_client.get_epoch_schedule() assert_valid_response(resp)
-5,302,495,828,360,658,000
Test get epoch schedule.
tests/integration/test_http_client.py
test_get_epoch_schedule
01protocol/solana-py
python
@pytest.mark.integration def test_get_epoch_schedule(test_http_client): resp = test_http_client.get_epoch_schedule() assert_valid_response(resp)
@pytest.mark.integration def test_get_fee_calculator_for_blockhash(test_http_client): 'Test get fee calculator for blockhash.' resp = test_http_client.get_recent_blockhash(Finalized) assert_valid_response(resp) resp = test_http_client.get_fee_calculator_for_blockhash(resp['result']['value']['blockhash']) assert_valid_response(resp)
1,889,093,828,871,862,800
Test get fee calculator for blockhash.
tests/integration/test_http_client.py
test_get_fee_calculator_for_blockhash
01protocol/solana-py
python
@pytest.mark.integration def test_get_fee_calculator_for_blockhash(test_http_client): resp = test_http_client.get_recent_blockhash(Finalized) assert_valid_response(resp) resp = test_http_client.get_fee_calculator_for_blockhash(resp['result']['value']['blockhash']) assert_valid_response(resp)
@pytest.mark.integration def test_get_slot(test_http_client): 'Test get slot.' resp = test_http_client.get_slot() assert_valid_response(resp)
4,926,687,200,530,336,000
Test get slot.
tests/integration/test_http_client.py
test_get_slot
01protocol/solana-py
python
@pytest.mark.integration def test_get_slot(test_http_client): resp = test_http_client.get_slot() assert_valid_response(resp)
@pytest.mark.integration def test_get_fees(test_http_client): 'Test get fees.' resp = test_http_client.get_fees() assert_valid_response(resp)
-8,796,527,687,192,916,000
Test get fees.
tests/integration/test_http_client.py
test_get_fees
01protocol/solana-py
python
@pytest.mark.integration def test_get_fees(test_http_client): resp = test_http_client.get_fees() assert_valid_response(resp)
@pytest.mark.integration def test_get_first_available_block(test_http_client): 'Test get first available block.' resp = test_http_client.get_first_available_block() assert_valid_response(resp)
7,404,018,720,916,496,000
Test get first available block.
tests/integration/test_http_client.py
test_get_first_available_block
01protocol/solana-py
python
@pytest.mark.integration def test_get_first_available_block(test_http_client): resp = test_http_client.get_first_available_block() assert_valid_response(resp)
@pytest.mark.integration def test_get_genesis_hash(test_http_client): 'Test get genesis hash.' resp = test_http_client.get_genesis_hash() assert_valid_response(resp)
-3,014,610,449,644,556,000
Test get genesis hash.
tests/integration/test_http_client.py
test_get_genesis_hash
01protocol/solana-py
python
@pytest.mark.integration def test_get_genesis_hash(test_http_client): resp = test_http_client.get_genesis_hash() assert_valid_response(resp)
@pytest.mark.integration def test_get_identity(test_http_client): 'Test get identity.' resp = test_http_client.get_genesis_hash() assert_valid_response(resp)
8,470,280,543,798,683,000
Test get identity.
tests/integration/test_http_client.py
test_get_identity
01protocol/solana-py
python
@pytest.mark.integration def test_get_identity(test_http_client): resp = test_http_client.get_genesis_hash() assert_valid_response(resp)
@pytest.mark.integration def test_get_inflation_governor(test_http_client): 'Test get inflation governor.' resp = test_http_client.get_inflation_governor() assert_valid_response(resp)
1,220,144,173,495,274,500
Test get inflation governor.
tests/integration/test_http_client.py
test_get_inflation_governor
01protocol/solana-py
python
@pytest.mark.integration def test_get_inflation_governor(test_http_client): resp = test_http_client.get_inflation_governor() assert_valid_response(resp)
@pytest.mark.integration def test_get_inflation_rate(test_http_client): 'Test get inflation rate.' resp = test_http_client.get_inflation_rate() assert_valid_response(resp)
1,493,374,836,921,041,700
Test get inflation rate.
tests/integration/test_http_client.py
test_get_inflation_rate
01protocol/solana-py
python
@pytest.mark.integration def test_get_inflation_rate(test_http_client): resp = test_http_client.get_inflation_rate() assert_valid_response(resp)
@pytest.mark.integration def test_get_largest_accounts(test_http_client): 'Test get largest accounts.' resp = test_http_client.get_largest_accounts() assert_valid_response(resp)
-6,243,253,639,179,239,000
Test get largest accounts.
tests/integration/test_http_client.py
test_get_largest_accounts
01protocol/solana-py
python
@pytest.mark.integration def test_get_largest_accounts(test_http_client): resp = test_http_client.get_largest_accounts() assert_valid_response(resp)
@pytest.mark.integration def test_get_leader_schedule(test_http_client): 'Test get leader schedule.' resp = test_http_client.get_leader_schedule() assert_valid_response(resp)
-1,154,009,096,755,975,000
Test get leader schedule.
tests/integration/test_http_client.py
test_get_leader_schedule
01protocol/solana-py
python
@pytest.mark.integration def test_get_leader_schedule(test_http_client): resp = test_http_client.get_leader_schedule() assert_valid_response(resp)
@pytest.mark.integration def test_get_minimum_balance_for_rent_exemption(test_http_client): 'Test get minimum balance for rent exemption.' resp = test_http_client.get_minimum_balance_for_rent_exemption(50) assert_valid_response(resp)
-6,237,468,888,816,544,000
Test get minimum balance for rent exemption.
tests/integration/test_http_client.py
test_get_minimum_balance_for_rent_exemption
01protocol/solana-py
python
@pytest.mark.integration def test_get_minimum_balance_for_rent_exemption(test_http_client): resp = test_http_client.get_minimum_balance_for_rent_exemption(50) assert_valid_response(resp)
@pytest.mark.integration def test_get_slot_leader(test_http_client): 'Test get slot leader.' resp = test_http_client.get_slot_leader() assert_valid_response(resp)
3,957,112,803,738,973,700
Test get slot leader.
tests/integration/test_http_client.py
test_get_slot_leader
01protocol/solana-py
python
@pytest.mark.integration def test_get_slot_leader(test_http_client): resp = test_http_client.get_slot_leader() assert_valid_response(resp)
@pytest.mark.integration def test_get_supply(test_http_client): 'Test get slot leader.' resp = test_http_client.get_supply() assert_valid_response(resp)
7,186,734,567,476,955,000
Test get slot leader.
tests/integration/test_http_client.py
test_get_supply
01protocol/solana-py
python
@pytest.mark.integration def test_get_supply(test_http_client): resp = test_http_client.get_supply() assert_valid_response(resp)
@pytest.mark.integration def test_get_transaction_count(test_http_client): 'Test get transactinon count.' resp = test_http_client.get_transaction_count() assert_valid_response(resp)
-2,201,587,048,918,887,400
Test get transactinon count.
tests/integration/test_http_client.py
test_get_transaction_count
01protocol/solana-py
python
@pytest.mark.integration def test_get_transaction_count(test_http_client): resp = test_http_client.get_transaction_count() assert_valid_response(resp)
@pytest.mark.integration def test_get_version(test_http_client): 'Test get version.' resp = test_http_client.get_version() assert_valid_response(resp)
-8,646,969,108,004,914,000
Test get version.
tests/integration/test_http_client.py
test_get_version
01protocol/solana-py
python
@pytest.mark.integration def test_get_version(test_http_client): resp = test_http_client.get_version() assert_valid_response(resp)
@pytest.mark.integration def test_get_account_info(stubbed_sender, test_http_client): 'Test get_account_info.' resp = test_http_client.get_account_info(stubbed_sender.public_key) assert_valid_response(resp) resp = test_http_client.get_account_info(stubbed_sender.public_key, encoding='jsonParsed') assert_valid_response(resp) resp = test_http_client.get_account_info(stubbed_sender.public_key, data_slice=DataSliceOpt(1, 1)) assert_valid_response(resp)
-1,596,831,018,881,734,700
Test get_account_info.
tests/integration/test_http_client.py
test_get_account_info
01protocol/solana-py
python
@pytest.mark.integration def test_get_account_info(stubbed_sender, test_http_client): resp = test_http_client.get_account_info(stubbed_sender.public_key) assert_valid_response(resp) resp = test_http_client.get_account_info(stubbed_sender.public_key, encoding='jsonParsed') assert_valid_response(resp) resp = test_http_client.get_account_info(stubbed_sender.public_key, data_slice=DataSliceOpt(1, 1)) assert_valid_response(resp)
@pytest.mark.integration def test_get_multiple_accounts(stubbed_sender, test_http_client): 'Test get_multiple_accounts.' pubkeys = ([stubbed_sender.public_key] * 2) resp = test_http_client.get_multiple_accounts(pubkeys) assert_valid_response(resp) resp = test_http_client.get_multiple_accounts(pubkeys, encoding='jsonParsed') assert_valid_response(resp) resp = test_http_client.get_multiple_accounts(pubkeys, data_slice=DataSliceOpt(1, 1)) assert_valid_response(resp)
8,559,563,191,577,752,000
Test get_multiple_accounts.
tests/integration/test_http_client.py
test_get_multiple_accounts
01protocol/solana-py
python
@pytest.mark.integration def test_get_multiple_accounts(stubbed_sender, test_http_client): pubkeys = ([stubbed_sender.public_key] * 2) resp = test_http_client.get_multiple_accounts(pubkeys) assert_valid_response(resp) resp = test_http_client.get_multiple_accounts(pubkeys, encoding='jsonParsed') assert_valid_response(resp) resp = test_http_client.get_multiple_accounts(pubkeys, data_slice=DataSliceOpt(1, 1)) assert_valid_response(resp)
@pytest.mark.integration def test_get_token_largest_accounts(test_http_client): 'Test get token largest accounts.' resp = test_http_client.get_token_largest_accounts(WRAPPED_SOL_MINT) assert_valid_response(resp)
5,720,847,873,091,293,000
Test get token largest accounts.
tests/integration/test_http_client.py
test_get_token_largest_accounts
01protocol/solana-py
python
@pytest.mark.integration def test_get_token_largest_accounts(test_http_client): resp = test_http_client.get_token_largest_accounts(WRAPPED_SOL_MINT) assert_valid_response(resp)
@pytest.mark.integration def test_get_token_supply(test_http_client): 'Test get token supply.' resp = test_http_client.get_token_supply(WRAPPED_SOL_MINT) assert_valid_response(resp)
1,562,480,596,333,131,800
Test get token supply.
tests/integration/test_http_client.py
test_get_token_supply
01protocol/solana-py
python
@pytest.mark.integration def test_get_token_supply(test_http_client): resp = test_http_client.get_token_supply(WRAPPED_SOL_MINT) assert_valid_response(resp)
@pytest.mark.integration def test_get_vote_accounts(test_http_client): 'Test get vote accounts.' resp = test_http_client.get_vote_accounts() assert_valid_response(resp)
3,253,217,339,432,330,000
Test get vote accounts.
tests/integration/test_http_client.py
test_get_vote_accounts
01protocol/solana-py
python
@pytest.mark.integration def test_get_vote_accounts(test_http_client): resp = test_http_client.get_vote_accounts() assert_valid_response(resp)
def get_filename(dirname, n_node): '\n Get a filename unique to the test process ID and node.\n\n This file will contain a list of RPC commands covered.\n ' pid = str(os.getpid()) return os.path.join(dirname, ('coverage.pid%s.node%s.txt' % (pid, str(n_node))))
5,361,333,719,256,488,000
Get a filename unique to the test process ID and node. This file will contain a list of RPC commands covered.
qa/rpc-tests/test_framework/coverage.py
get_filename
Goosey13/bitcore-limtex-broteq
python
def get_filename(dirname, n_node): '\n Get a filename unique to the test process ID and node.\n\n This file will contain a list of RPC commands covered.\n ' pid = str(os.getpid()) return os.path.join(dirname, ('coverage.pid%s.node%s.txt' % (pid, str(n_node))))
def write_all_rpc_commands(dirname, node): '\n Write out a list of all RPC functions available in `bitcore-cli` for\n coverage comparison. This will only happen once per coverage\n directory.\n\n Args:\n dirname (str): temporary test dir\n node (AuthServiceProxy): client\n\n Returns:\n bool. if the RPC interface file was written.\n\n ' filename = os.path.join(dirname, REFERENCE_FILENAME) if os.path.isfile(filename): return False help_output = node.help().split('\n') commands = set() for line in help_output: line = line.strip() if (line and (not line.startswith('='))): commands.add(('%s\n' % line.split()[0])) with open(filename, 'w', encoding='utf8') as f: f.writelines(list(commands)) return True
-2,752,954,201,011,444,000
Write out a list of all RPC functions available in `bitcore-cli` for coverage comparison. This will only happen once per coverage directory. Args: dirname (str): temporary test dir node (AuthServiceProxy): client Returns: bool. if the RPC interface file was written.
qa/rpc-tests/test_framework/coverage.py
write_all_rpc_commands
Goosey13/bitcore-limtex-broteq
python
def write_all_rpc_commands(dirname, node): '\n Write out a list of all RPC functions available in `bitcore-cli` for\n coverage comparison. This will only happen once per coverage\n directory.\n\n Args:\n dirname (str): temporary test dir\n node (AuthServiceProxy): client\n\n Returns:\n bool. if the RPC interface file was written.\n\n ' filename = os.path.join(dirname, REFERENCE_FILENAME) if os.path.isfile(filename): return False help_output = node.help().split('\n') commands = set() for line in help_output: line = line.strip() if (line and (not line.startswith('='))): commands.add(('%s\n' % line.split()[0])) with open(filename, 'w', encoding='utf8') as f: f.writelines(list(commands)) return True
def __init__(self, auth_service_proxy_instance, coverage_logfile=None): '\n Kwargs:\n auth_service_proxy_instance (AuthServiceProxy): the instance\n being wrapped.\n coverage_logfile (str): if specified, write each service_name\n out to a file when called.\n\n ' self.auth_service_proxy_instance = auth_service_proxy_instance self.coverage_logfile = coverage_logfile
-4,981,508,551,377,925,000
Kwargs: auth_service_proxy_instance (AuthServiceProxy): the instance being wrapped. coverage_logfile (str): if specified, write each service_name out to a file when called.
qa/rpc-tests/test_framework/coverage.py
__init__
Goosey13/bitcore-limtex-broteq
python
def __init__(self, auth_service_proxy_instance, coverage_logfile=None): '\n Kwargs:\n auth_service_proxy_instance (AuthServiceProxy): the instance\n being wrapped.\n coverage_logfile (str): if specified, write each service_name\n out to a file when called.\n\n ' self.auth_service_proxy_instance = auth_service_proxy_instance self.coverage_logfile = coverage_logfile
def __call__(self, *args, **kwargs): '\n Delegates to AuthServiceProxy, then writes the particular RPC method\n called to a file.\n\n ' return_val = self.auth_service_proxy_instance.__call__(*args, **kwargs) rpc_method = self.auth_service_proxy_instance._service_name if self.coverage_logfile: with open(self.coverage_logfile, 'a+', encoding='utf8') as f: f.write(('%s\n' % rpc_method)) return return_val
-6,692,438,866,895,756,000
Delegates to AuthServiceProxy, then writes the particular RPC method called to a file.
qa/rpc-tests/test_framework/coverage.py
__call__
Goosey13/bitcore-limtex-broteq
python
def __call__(self, *args, **kwargs): '\n Delegates to AuthServiceProxy, then writes the particular RPC method\n called to a file.\n\n ' return_val = self.auth_service_proxy_instance.__call__(*args, **kwargs) rpc_method = self.auth_service_proxy_instance._service_name if self.coverage_logfile: with open(self.coverage_logfile, 'a+', encoding='utf8') as f: f.write(('%s\n' % rpc_method)) return return_val
@property def matcher(self): 'The matcher that this request was handled by.\n\n The matcher object is handled by a weakref. It will return the matcher\n object if it is still available - so if the mock is still in place. If\n the matcher is not available it will return None.\n ' return self._matcher()
6,548,309,379,002,083,000
The matcher that this request was handled by. The matcher object is handled by a weakref. It will return the matcher object if it is still available - so if the mock is still in place. If the matcher is not available it will return None.
venv/lib/python3.6/site-packages/requests_mock/request.py
matcher
Guillaume-Fernandez/PhishInspector
python
@property def matcher(self): 'The matcher that this request was handled by.\n\n The matcher object is handled by a weakref. It will return the matcher\n object if it is still available - so if the mock is still in place. If\n the matcher is not available it will return None.\n ' return self._matcher()
def has_more_questions(self): 'To check if the quiz has more questions' return (self.question_no < len(self.questions))
8,752,772,375,929,944,000
To check if the quiz has more questions
quiz_brain.py
has_more_questions
ashutoshkrris/GUI-Quiz-Tkinter
python
def has_more_questions(self): return (self.question_no < len(self.questions))
def next_question(self): 'Get the next question by incrementing the question number' self.current_question = self.questions[self.question_no] self.question_no += 1 q_text = self.current_question.question_text return f'Q.{self.question_no}: {q_text}'
-1,160,494,403,836,940,500
Get the next question by incrementing the question number
quiz_brain.py
next_question
ashutoshkrris/GUI-Quiz-Tkinter
python
def next_question(self): self.current_question = self.questions[self.question_no] self.question_no += 1 q_text = self.current_question.question_text return f'Q.{self.question_no}: {q_text}'
def check_answer(self, user_answer): 'Check the user answer against the correct answer and maintain the score' correct_answer = self.current_question.correct_answer if (user_answer.lower() == correct_answer.lower()): self.score += 1 return True else: return False
-5,160,888,627,997,631,000
Check the user answer against the correct answer and maintain the score
quiz_brain.py
check_answer
ashutoshkrris/GUI-Quiz-Tkinter
python
def check_answer(self, user_answer): correct_answer = self.current_question.correct_answer if (user_answer.lower() == correct_answer.lower()): self.score += 1 return True else: return False
def get_score(self): 'Get the number of correct answers, wrong answers and score percentage.' wrong = (self.question_no - self.score) score_percent = int(((self.score / self.question_no) * 100)) return (self.score, wrong, score_percent)
1,853,477,211,214,495,500
Get the number of correct answers, wrong answers and score percentage.
quiz_brain.py
get_score
ashutoshkrris/GUI-Quiz-Tkinter
python
def get_score(self): wrong = (self.question_no - self.score) score_percent = int(((self.score / self.question_no) * 100)) return (self.score, wrong, score_percent)
@classmethod def build_model(cls, cfg: Wav2Vec2CtcConfig, task: FairseqTask): 'Build a new model instance.' w2v_encoder = Wav2VecEncoder(cfg, task.target_dictionary) return cls(cfg, w2v_encoder)
9,168,060,348,673,678,000
Build a new model instance.
fairseq/models/wav2vec/wav2vec2_asr.py
build_model
227514/Supervised-Simultaneous-MT
python
@classmethod def build_model(cls, cfg: Wav2Vec2CtcConfig, task: FairseqTask): w2v_encoder = Wav2VecEncoder(cfg, task.target_dictionary) return cls(cfg, w2v_encoder)
def get_normalized_probs(self, net_output, log_probs): "Get normalized probabilities (or log probs) from a net's output." logits = net_output['encoder_out'] if log_probs: return utils.log_softmax(logits.float(), dim=(- 1)) else: return utils.softmax(logits.float(), dim=(- 1))
2,406,651,590,185,822,700
Get normalized probabilities (or log probs) from a net's output.
fairseq/models/wav2vec/wav2vec2_asr.py
get_normalized_probs
227514/Supervised-Simultaneous-MT
python
def get_normalized_probs(self, net_output, log_probs): logits = net_output['encoder_out'] if log_probs: return utils.log_softmax(logits.float(), dim=(- 1)) else: return utils.softmax(logits.float(), dim=(- 1))
@classmethod def build_model(cls, cfg: Wav2Vec2Seq2SeqConfig, task: FairseqTask): 'Build a new model instance.' (src_dict, tgt_dict) = (task.source_dictionary, task.target_dictionary) def build_embedding(dictionary, embed_dim): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) return emb decoder_embed_tokens = build_embedding(tgt_dict, cfg.decoder_embed_dim) encoder = cls.build_encoder(cfg) decoder = cls.build_decoder(cfg, tgt_dict, decoder_embed_tokens) return Wav2Vec2Seq2SeqModel(encoder, decoder)
-1,634,789,159,231,734,800
Build a new model instance.
fairseq/models/wav2vec/wav2vec2_asr.py
build_model
227514/Supervised-Simultaneous-MT
python
@classmethod def build_model(cls, cfg: Wav2Vec2Seq2SeqConfig, task: FairseqTask): (src_dict, tgt_dict) = (task.source_dictionary, task.target_dictionary) def build_embedding(dictionary, embed_dim): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) return emb decoder_embed_tokens = build_embedding(tgt_dict, cfg.decoder_embed_dim) encoder = cls.build_encoder(cfg) decoder = cls.build_decoder(cfg, tgt_dict, decoder_embed_tokens) return Wav2Vec2Seq2SeqModel(encoder, decoder)
def set_num_updates(self, num_updates): 'Set the number of parameters updates.' super().set_num_updates(num_updates) self.num_updates = num_updates
-4,456,253,483,006,223,000
Set the number of parameters updates.
fairseq/models/wav2vec/wav2vec2_asr.py
set_num_updates
227514/Supervised-Simultaneous-MT
python
def set_num_updates(self, num_updates): super().set_num_updates(num_updates) self.num_updates = num_updates
def max_positions(self): 'Maximum input length supported by the encoder.' return None
2,570,957,237,927,805,400
Maximum input length supported by the encoder.
fairseq/models/wav2vec/wav2vec2_asr.py
max_positions
227514/Supervised-Simultaneous-MT
python
def max_positions(self): return None
def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused): "\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n " prev_output_tokens = prev_output_tokens.long() (x, extra) = self.extract_features(prev_output_tokens, encoder_out, incremental_state) x = self.output_layer(x) return (x, extra)
1,204,137,243,606,383,000
Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` Returns: tuple: - the decoder's output of shape `(batch, tgt_len, vocab)` - a dictionary with any model-specific outputs
fairseq/models/wav2vec/wav2vec2_asr.py
forward
227514/Supervised-Simultaneous-MT
python
def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused): "\n Args:\n prev_output_tokens (LongTensor): previous decoder outputs of shape\n `(batch, tgt_len)`, for teacher forcing\n encoder_out (Tensor, optional): output from the encoder, used for\n encoder-side attention\n incremental_state (dict): dictionary used for storing state during\n :ref:`Incremental decoding`\n\n Returns:\n tuple:\n - the decoder's output of shape `(batch, tgt_len, vocab)`\n - a dictionary with any model-specific outputs\n " prev_output_tokens = prev_output_tokens.long() (x, extra) = self.extract_features(prev_output_tokens, encoder_out, incremental_state) x = self.output_layer(x) return (x, extra)
def extract_features(self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused): "\n Similar to *forward* but only return features.\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n " positions = (self.embed_positions(prev_output_tokens, incremental_state=incremental_state) if (self.embed_positions is not None) else None) if (incremental_state is not None): prev_output_tokens = prev_output_tokens[:, (- 1):] if (positions is not None): positions = positions[:, (- 1):] x = (self.embed_scale * self.embed_tokens(prev_output_tokens)) if (self.project_in_dim is not None): x = self.project_in_dim(x) if (positions is not None): x += positions x = F.dropout(x, p=self.dropout, training=self.training) x = x.transpose(0, 1) attn = None inner_states = [x] for layer in self.layers: dropout_probability = np.random.random() if ((not self.training) or (dropout_probability > self.layerdrop)): (x, attn, _) = layer(x, (encoder_out['encoder_out'] if (encoder_out is not None) else None), (encoder_out['encoder_padding_mask'] if (encoder_out is not None) else None), incremental_state, self_attn_mask=(self.buffered_future_mask(x) if (incremental_state is None) else None)) inner_states.append(x) if self.layer_norm: x = self.layer_norm(x) x = x.transpose(0, 1) return (x, {'attn': attn, 'inner_states': inner_states})
6,108,438,086,567,812,000
Similar to *forward* but only return features. Returns: tuple: - the decoder's features of shape `(batch, tgt_len, embed_dim)` - a dictionary with any model-specific outputs
fairseq/models/wav2vec/wav2vec2_asr.py
extract_features
227514/Supervised-Simultaneous-MT
python
def extract_features(self, prev_output_tokens, encoder_out=None, incremental_state=None, **unused): "\n Similar to *forward* but only return features.\n\n Returns:\n tuple:\n - the decoder's features of shape `(batch, tgt_len, embed_dim)`\n - a dictionary with any model-specific outputs\n " positions = (self.embed_positions(prev_output_tokens, incremental_state=incremental_state) if (self.embed_positions is not None) else None) if (incremental_state is not None): prev_output_tokens = prev_output_tokens[:, (- 1):] if (positions is not None): positions = positions[:, (- 1):] x = (self.embed_scale * self.embed_tokens(prev_output_tokens)) if (self.project_in_dim is not None): x = self.project_in_dim(x) if (positions is not None): x += positions x = F.dropout(x, p=self.dropout, training=self.training) x = x.transpose(0, 1) attn = None inner_states = [x] for layer in self.layers: dropout_probability = np.random.random() if ((not self.training) or (dropout_probability > self.layerdrop)): (x, attn, _) = layer(x, (encoder_out['encoder_out'] if (encoder_out is not None) else None), (encoder_out['encoder_padding_mask'] if (encoder_out is not None) else None), incremental_state, self_attn_mask=(self.buffered_future_mask(x) if (incremental_state is None) else None)) inner_states.append(x) if self.layer_norm: x = self.layer_norm(x) x = x.transpose(0, 1) return (x, {'attn': attn, 'inner_states': inner_states})
def output_layer(self, features, **kwargs): 'Project features to the vocabulary size.' if self.share_input_output_embed: return F.linear(features, self.embed_tokens.weight) else: return F.linear(features, self.embed_out)
-6,186,870,107,749,237,000
Project features to the vocabulary size.
fairseq/models/wav2vec/wav2vec2_asr.py
output_layer
227514/Supervised-Simultaneous-MT
python
def output_layer(self, features, **kwargs): if self.share_input_output_embed: return F.linear(features, self.embed_tokens.weight) else: return F.linear(features, self.embed_out)
def max_positions(self): 'Maximum output length supported by the decoder.' if (self.embed_positions is None): return self.max_target_positions return min(self.max_target_positions, self.embed_positions.max_positions)
984,214,153,396,268,000
Maximum output length supported by the decoder.
fairseq/models/wav2vec/wav2vec2_asr.py
max_positions
227514/Supervised-Simultaneous-MT
python
def max_positions(self): if (self.embed_positions is None): return self.max_target_positions return min(self.max_target_positions, self.embed_positions.max_positions)
def get_cfg() -> CfgNode: '\n Get a copy of the default config.\n\n Returns:\n a detectron2 CfgNode instance.\n ' from .defaults import _C return _C.clone()
2,179,725,166,255,358,700
Get a copy of the default config. Returns: a detectron2 CfgNode instance.
detectron2/config/config.py
get_cfg
873900204/datasets
python
def get_cfg() -> CfgNode: '\n Get a copy of the default config.\n\n Returns:\n a detectron2 CfgNode instance.\n ' from .defaults import _C return _C.clone()
def set_global_cfg(cfg: CfgNode) -> None: '\n Let the global config point to the given cfg.\n\n Assume that the given "cfg" has the key "KEY", after calling\n `set_global_cfg(cfg)`, the key can be accessed by:\n ::\n from detectron2.config import global_cfg\n print(global_cfg.KEY)\n\n By using a hacky global config, you can access these configs anywhere,\n without having to pass the config object or the values deep into the code.\n This is a hacky feature introduced for quick prototyping / research exploration.\n ' global global_cfg global_cfg.clear() global_cfg.update(cfg)
-3,685,885,688,445,195,000
Let the global config point to the given cfg. Assume that the given "cfg" has the key "KEY", after calling `set_global_cfg(cfg)`, the key can be accessed by: :: from detectron2.config import global_cfg print(global_cfg.KEY) By using a hacky global config, you can access these configs anywhere, without having to pass the config object or the values deep into the code. This is a hacky feature introduced for quick prototyping / research exploration.
detectron2/config/config.py
set_global_cfg
873900204/datasets
python
def set_global_cfg(cfg: CfgNode) -> None: '\n Let the global config point to the given cfg.\n\n Assume that the given "cfg" has the key "KEY", after calling\n `set_global_cfg(cfg)`, the key can be accessed by:\n ::\n from detectron2.config import global_cfg\n print(global_cfg.KEY)\n\n By using a hacky global config, you can access these configs anywhere,\n without having to pass the config object or the values deep into the code.\n This is a hacky feature introduced for quick prototyping / research exploration.\n ' global global_cfg global_cfg.clear() global_cfg.update(cfg)
def configurable(init_func=None, *, from_config=None): '\n Decorate a function or a class\'s __init__ method so that it can be called\n with a :class:`CfgNode` object using a :func:`from_config` function that translates\n :class:`CfgNode` to arguments.\n\n Examples:\n ::\n # Usage 1: Decorator on __init__:\n class A:\n @configurable\n def __init__(self, a, b=2, c=3):\n pass\n\n @classmethod\n def from_config(cls, cfg): # \'cfg\' must be the first argument\n # Returns kwargs to be passed to __init__\n return {"a": cfg.A, "b": cfg.B}\n\n a1 = A(a=1, b=2) # regular construction\n a2 = A(cfg) # construct with a cfg\n a3 = A(cfg, b=3, c=4) # construct with extra overwrite\n\n # Usage 2: Decorator on any function. Needs an extra from_config argument:\n @configurable(from_config=lambda cfg: {"a: cfg.A, "b": cfg.B})\n def a_func(a, b=2, c=3):\n pass\n\n a1 = a_func(a=1, b=2) # regular call\n a2 = a_func(cfg) # call with a cfg\n a3 = a_func(cfg, b=3, c=4) # call with extra overwrite\n\n Args:\n init_func (callable): a class\'s ``__init__`` method in usage 1. The\n class must have a ``from_config`` classmethod which takes `cfg` as\n the first argument.\n from_config (callable): the from_config function in usage 2. It must take `cfg`\n as its first argument.\n ' def check_docstring(func): if func.__module__.startswith('detectron2.'): assert ((func.__doc__ is not None) and ('experimental' in func.__doc__.lower())), f'configurable {func} should be marked experimental' if (init_func is not None): assert (inspect.isfunction(init_func) and (from_config is None) and (init_func.__name__ == '__init__')), 'Incorrect use of @configurable. Check API documentation for examples.' check_docstring(init_func) @functools.wraps(init_func) def wrapped(self, *args, **kwargs): try: from_config_func = type(self).from_config except AttributeError as e: raise AttributeError("Class with @configurable must have a 'from_config' classmethod.") from e if (not inspect.ismethod(from_config_func)): raise TypeError("Class with @configurable must have a 'from_config' classmethod.") if _called_with_cfg(*args, **kwargs): explicit_args = _get_args_from_config(from_config_func, *args, **kwargs) init_func(self, **explicit_args) else: init_func(self, *args, **kwargs) return wrapped else: if (from_config is None): return configurable assert inspect.isfunction(from_config), 'from_config argument of configurable must be a function!' def wrapper(orig_func): check_docstring(orig_func) @functools.wraps(orig_func) def wrapped(*args, **kwargs): if _called_with_cfg(*args, **kwargs): explicit_args = _get_args_from_config(from_config, *args, **kwargs) return orig_func(**explicit_args) else: return orig_func(*args, **kwargs) return wrapped return wrapper
2,694,034,848,503,018,000
Decorate a function or a class's __init__ method so that it can be called with a :class:`CfgNode` object using a :func:`from_config` function that translates :class:`CfgNode` to arguments. Examples: :: # Usage 1: Decorator on __init__: class A: @configurable def __init__(self, a, b=2, c=3): pass @classmethod def from_config(cls, cfg): # 'cfg' must be the first argument # Returns kwargs to be passed to __init__ return {"a": cfg.A, "b": cfg.B} a1 = A(a=1, b=2) # regular construction a2 = A(cfg) # construct with a cfg a3 = A(cfg, b=3, c=4) # construct with extra overwrite # Usage 2: Decorator on any function. Needs an extra from_config argument: @configurable(from_config=lambda cfg: {"a: cfg.A, "b": cfg.B}) def a_func(a, b=2, c=3): pass a1 = a_func(a=1, b=2) # regular call a2 = a_func(cfg) # call with a cfg a3 = a_func(cfg, b=3, c=4) # call with extra overwrite Args: init_func (callable): a class's ``__init__`` method in usage 1. The class must have a ``from_config`` classmethod which takes `cfg` as the first argument. from_config (callable): the from_config function in usage 2. It must take `cfg` as its first argument.
detectron2/config/config.py
configurable
873900204/datasets
python
def configurable(init_func=None, *, from_config=None): '\n Decorate a function or a class\'s __init__ method so that it can be called\n with a :class:`CfgNode` object using a :func:`from_config` function that translates\n :class:`CfgNode` to arguments.\n\n Examples:\n ::\n # Usage 1: Decorator on __init__:\n class A:\n @configurable\n def __init__(self, a, b=2, c=3):\n pass\n\n @classmethod\n def from_config(cls, cfg): # \'cfg\' must be the first argument\n # Returns kwargs to be passed to __init__\n return {"a": cfg.A, "b": cfg.B}\n\n a1 = A(a=1, b=2) # regular construction\n a2 = A(cfg) # construct with a cfg\n a3 = A(cfg, b=3, c=4) # construct with extra overwrite\n\n # Usage 2: Decorator on any function. Needs an extra from_config argument:\n @configurable(from_config=lambda cfg: {"a: cfg.A, "b": cfg.B})\n def a_func(a, b=2, c=3):\n pass\n\n a1 = a_func(a=1, b=2) # regular call\n a2 = a_func(cfg) # call with a cfg\n a3 = a_func(cfg, b=3, c=4) # call with extra overwrite\n\n Args:\n init_func (callable): a class\'s ``__init__`` method in usage 1. The\n class must have a ``from_config`` classmethod which takes `cfg` as\n the first argument.\n from_config (callable): the from_config function in usage 2. It must take `cfg`\n as its first argument.\n ' def check_docstring(func): if func.__module__.startswith('detectron2.'): assert ((func.__doc__ is not None) and ('experimental' in func.__doc__.lower())), f'configurable {func} should be marked experimental' if (init_func is not None): assert (inspect.isfunction(init_func) and (from_config is None) and (init_func.__name__ == '__init__')), 'Incorrect use of @configurable. Check API documentation for examples.' check_docstring(init_func) @functools.wraps(init_func) def wrapped(self, *args, **kwargs): try: from_config_func = type(self).from_config except AttributeError as e: raise AttributeError("Class with @configurable must have a 'from_config' classmethod.") from e if (not inspect.ismethod(from_config_func)): raise TypeError("Class with @configurable must have a 'from_config' classmethod.") if _called_with_cfg(*args, **kwargs): explicit_args = _get_args_from_config(from_config_func, *args, **kwargs) init_func(self, **explicit_args) else: init_func(self, *args, **kwargs) return wrapped else: if (from_config is None): return configurable assert inspect.isfunction(from_config), 'from_config argument of configurable must be a function!' def wrapper(orig_func): check_docstring(orig_func) @functools.wraps(orig_func) def wrapped(*args, **kwargs): if _called_with_cfg(*args, **kwargs): explicit_args = _get_args_from_config(from_config, *args, **kwargs) return orig_func(**explicit_args) else: return orig_func(*args, **kwargs) return wrapped return wrapper
def _get_args_from_config(from_config_func, *args, **kwargs): '\n Use `from_config` to obtain explicit arguments.\n\n Returns:\n dict: arguments to be used for cls.__init__\n ' signature = inspect.signature(from_config_func) if (list(signature.parameters.keys())[0] != 'cfg'): if inspect.isfunction(from_config_func): name = from_config_func.__name__ else: name = f'{from_config_func.__self__}.from_config' raise TypeError(f"{name} must take 'cfg' as the first argument!") support_var_arg = any(((param.kind in [param.VAR_POSITIONAL, param.VAR_KEYWORD]) for param in signature.parameters.values())) if support_var_arg: ret = from_config_func(*args, **kwargs) else: supported_arg_names = set(signature.parameters.keys()) extra_kwargs = {} for name in list(kwargs.keys()): if (name not in supported_arg_names): extra_kwargs[name] = kwargs.pop(name) ret = from_config_func(*args, **kwargs) ret.update(extra_kwargs) return ret
-356,159,426,803,261,950
Use `from_config` to obtain explicit arguments. Returns: dict: arguments to be used for cls.__init__
detectron2/config/config.py
_get_args_from_config
873900204/datasets
python
def _get_args_from_config(from_config_func, *args, **kwargs): '\n Use `from_config` to obtain explicit arguments.\n\n Returns:\n dict: arguments to be used for cls.__init__\n ' signature = inspect.signature(from_config_func) if (list(signature.parameters.keys())[0] != 'cfg'): if inspect.isfunction(from_config_func): name = from_config_func.__name__ else: name = f'{from_config_func.__self__}.from_config' raise TypeError(f"{name} must take 'cfg' as the first argument!") support_var_arg = any(((param.kind in [param.VAR_POSITIONAL, param.VAR_KEYWORD]) for param in signature.parameters.values())) if support_var_arg: ret = from_config_func(*args, **kwargs) else: supported_arg_names = set(signature.parameters.keys()) extra_kwargs = {} for name in list(kwargs.keys()): if (name not in supported_arg_names): extra_kwargs[name] = kwargs.pop(name) ret = from_config_func(*args, **kwargs) ret.update(extra_kwargs) return ret
def _called_with_cfg(*args, **kwargs): '\n Returns:\n bool: whether the arguments contain CfgNode and should be considered\n forwarded to from_config.\n ' if (len(args) and isinstance(args[0], _CfgNode)): return True if isinstance(kwargs.pop('cfg', None), _CfgNode): return True return False
3,960,451,647,599,272,000
Returns: bool: whether the arguments contain CfgNode and should be considered forwarded to from_config.
detectron2/config/config.py
_called_with_cfg
873900204/datasets
python
def _called_with_cfg(*args, **kwargs): '\n Returns:\n bool: whether the arguments contain CfgNode and should be considered\n forwarded to from_config.\n ' if (len(args) and isinstance(args[0], _CfgNode)): return True if isinstance(kwargs.pop('cfg', None), _CfgNode): return True return False
def dump(self, *args, **kwargs): '\n Returns:\n str: a yaml string representation of the config\n ' return super().dump(*args, **kwargs)
-1,488,916,298,614,346,200
Returns: str: a yaml string representation of the config
detectron2/config/config.py
dump
873900204/datasets
python
def dump(self, *args, **kwargs): '\n Returns:\n str: a yaml string representation of the config\n ' return super().dump(*args, **kwargs)
def build_report(report_name): ' Apply appropriate transformations to markdown files\n so that they can be compiled properly into a PDF report via\n LaTeX. ' with open('index.md', 'r') as f: lines = [transform_line(line) for line in f] with open('index_transformed.md', 'w') as f: f.writelines(lines) sp.call(['pandoc', '--template', '../pandoc_report_template.tex', '--pdf-engine', 'lualatex', '-V', f'reportname={report_name}', '-N', '-f', 'markdown+tex_math_dollars', 'index_transformed.md', '-o', f'{report_name}.tex']) sp.call(['latexmk', '-lualatex', f'{report_name}.tex']) os.remove('index_transformed.md')
-8,990,635,196,547,939,000
Apply appropriate transformations to markdown files so that they can be compiled properly into a PDF report via LaTeX.
documentation/deliverable_reports/build_report.py
build_report
mikiec84/automates
python
def build_report(report_name): ' Apply appropriate transformations to markdown files\n so that they can be compiled properly into a PDF report via\n LaTeX. ' with open('index.md', 'r') as f: lines = [transform_line(line) for line in f] with open('index_transformed.md', 'w') as f: f.writelines(lines) sp.call(['pandoc', '--template', '../pandoc_report_template.tex', '--pdf-engine', 'lualatex', '-V', f'reportname={report_name}', '-N', '-f', 'markdown+tex_math_dollars', 'index_transformed.md', '-o', f'{report_name}.tex']) sp.call(['latexmk', '-lualatex', f'{report_name}.tex']) os.remove('index_transformed.md')
def Optimize(node, builtins=None, lossy=False, use_abcs=False, max_union=7, remove_mutable=False, can_do_lookup=True): 'Optimize a PYTD tree.\n\n Tries to shrink a PYTD tree by applying various optimizations.\n\n Arguments:\n node: A pytd node to be optimized. It won\'t be modified - this function\n will return a new node.\n builtins: Definitions of all of the external types in node.\n lossy: Allow optimizations that change the meaning of the pytd.\n use_abcs: Use abstract base classes to represent unions like\n e.g. "float or int" as "Real".\n max_union: How many types we allow in a union before we simplify\n it to just "object".\n remove_mutable: Whether to simplify mutable parameters to normal\n parameters.\n can_do_lookup: True: We\'re either allowed to try to resolve NamedType\n instances in the AST, or the AST is already resolved. False: Skip any\n optimizations that would require NamedTypes to be resolved.\n\n Returns:\n An optimized node.\n ' node = node.Visit(RemoveDuplicates()) node = node.Visit(SimplifyUnions()) node = node.Visit(CombineReturnsAndExceptions()) node = node.Visit(Factorize()) node = node.Visit(ApplyOptionalArguments()) node = node.Visit(CombineContainers()) node = node.Visit(SimplifyContainers()) if builtins: superclasses = builtins.Visit(visitors.ExtractSuperClassesByName()) superclasses.update(node.Visit(visitors.ExtractSuperClassesByName())) if use_abcs: superclasses.update(abc_hierarchy.GetSuperClasses()) hierarchy = SuperClassHierarchy(superclasses) node = node.Visit(SimplifyUnionsWithSuperclasses(hierarchy)) if lossy: node = node.Visit(FindCommonSuperClasses(hierarchy)) if max_union: node = node.Visit(CollapseLongUnions(max_union)) node = node.Visit(AdjustReturnAndConstantGenericType()) if remove_mutable: node = node.Visit(AbsorbMutableParameters()) node = node.Visit(CombineContainers()) node = node.Visit(MergeTypeParameters()) node = node.Visit(visitors.AdjustSelf()) node = node.Visit(SimplifyContainers()) if (builtins and can_do_lookup): node = visitors.LookupClasses(node, builtins, ignore_late_types=True) node = node.Visit(RemoveInheritedMethods()) node = node.Visit(RemoveRedundantSignatures(hierarchy)) return node
2,509,103,242,135,620,000
Optimize a PYTD tree. Tries to shrink a PYTD tree by applying various optimizations. Arguments: node: A pytd node to be optimized. It won't be modified - this function will return a new node. builtins: Definitions of all of the external types in node. lossy: Allow optimizations that change the meaning of the pytd. use_abcs: Use abstract base classes to represent unions like e.g. "float or int" as "Real". max_union: How many types we allow in a union before we simplify it to just "object". remove_mutable: Whether to simplify mutable parameters to normal parameters. can_do_lookup: True: We're either allowed to try to resolve NamedType instances in the AST, or the AST is already resolved. False: Skip any optimizations that would require NamedTypes to be resolved. Returns: An optimized node.
pytype/pytd/optimize.py
Optimize
Jason-Cooke/pytype
python
def Optimize(node, builtins=None, lossy=False, use_abcs=False, max_union=7, remove_mutable=False, can_do_lookup=True): 'Optimize a PYTD tree.\n\n Tries to shrink a PYTD tree by applying various optimizations.\n\n Arguments:\n node: A pytd node to be optimized. It won\'t be modified - this function\n will return a new node.\n builtins: Definitions of all of the external types in node.\n lossy: Allow optimizations that change the meaning of the pytd.\n use_abcs: Use abstract base classes to represent unions like\n e.g. "float or int" as "Real".\n max_union: How many types we allow in a union before we simplify\n it to just "object".\n remove_mutable: Whether to simplify mutable parameters to normal\n parameters.\n can_do_lookup: True: We\'re either allowed to try to resolve NamedType\n instances in the AST, or the AST is already resolved. False: Skip any\n optimizations that would require NamedTypes to be resolved.\n\n Returns:\n An optimized node.\n ' node = node.Visit(RemoveDuplicates()) node = node.Visit(SimplifyUnions()) node = node.Visit(CombineReturnsAndExceptions()) node = node.Visit(Factorize()) node = node.Visit(ApplyOptionalArguments()) node = node.Visit(CombineContainers()) node = node.Visit(SimplifyContainers()) if builtins: superclasses = builtins.Visit(visitors.ExtractSuperClassesByName()) superclasses.update(node.Visit(visitors.ExtractSuperClassesByName())) if use_abcs: superclasses.update(abc_hierarchy.GetSuperClasses()) hierarchy = SuperClassHierarchy(superclasses) node = node.Visit(SimplifyUnionsWithSuperclasses(hierarchy)) if lossy: node = node.Visit(FindCommonSuperClasses(hierarchy)) if max_union: node = node.Visit(CollapseLongUnions(max_union)) node = node.Visit(AdjustReturnAndConstantGenericType()) if remove_mutable: node = node.Visit(AbsorbMutableParameters()) node = node.Visit(CombineContainers()) node = node.Visit(MergeTypeParameters()) node = node.Visit(visitors.AdjustSelf()) node = node.Visit(SimplifyContainers()) if (builtins and can_do_lookup): node = visitors.LookupClasses(node, builtins, ignore_late_types=True) node = node.Visit(RemoveInheritedMethods()) node = node.Visit(RemoveRedundantSignatures(hierarchy)) return node
def Update(self, signature): 'Add the return types / exceptions of a signature to this instance.' if (signature.return_type not in self.return_types): self.return_types.append(signature.return_type) self.exceptions.extend((exception for exception in signature.exceptions if (exception not in self.exceptions)))
-1,532,275,495,390,624,300
Add the return types / exceptions of a signature to this instance.
pytype/pytd/optimize.py
Update
Jason-Cooke/pytype
python
def Update(self, signature): if (signature.return_type not in self.return_types): self.return_types.append(signature.return_type) self.exceptions.extend((exception for exception in signature.exceptions if (exception not in self.exceptions)))
def _GroupByArguments(self, signatures): 'Groups signatures by arguments.\n\n Arguments:\n signatures: A list of function signatures (Signature instances).\n\n Returns:\n A dictionary mapping signatures (without return and exceptions) to\n a tuple of return values and exceptions.\n ' groups = collections.OrderedDict() for sig in signatures: stripped_signature = sig.Replace(return_type=None, exceptions=None) ret = groups.get(stripped_signature) if (not ret): ret = _ReturnsAndExceptions() groups[stripped_signature] = ret ret.Update(sig) return groups
-9,035,062,569,059,240,000
Groups signatures by arguments. Arguments: signatures: A list of function signatures (Signature instances). Returns: A dictionary mapping signatures (without return and exceptions) to a tuple of return values and exceptions.
pytype/pytd/optimize.py
_GroupByArguments
Jason-Cooke/pytype
python
def _GroupByArguments(self, signatures): 'Groups signatures by arguments.\n\n Arguments:\n signatures: A list of function signatures (Signature instances).\n\n Returns:\n A dictionary mapping signatures (without return and exceptions) to\n a tuple of return values and exceptions.\n ' groups = collections.OrderedDict() for sig in signatures: stripped_signature = sig.Replace(return_type=None, exceptions=None) ret = groups.get(stripped_signature) if (not ret): ret = _ReturnsAndExceptions() groups[stripped_signature] = ret ret.Update(sig) return groups
def VisitFunction(self, f): 'Merge signatures of a function.\n\n This groups signatures by arguments and then for each group creates a\n single signature that joins the return values / exceptions using "or".\n\n Arguments:\n f: A pytd.Function instance\n\n Returns:\n Function with simplified / combined signatures.\n ' groups = self._GroupByArguments(f.signatures) new_signatures = [] for (stripped_signature, ret_exc) in groups.items(): ret = pytd_utils.JoinTypes(ret_exc.return_types) exc = tuple(ret_exc.exceptions) new_signatures.append(stripped_signature.Replace(return_type=ret, exceptions=exc)) return f.Replace(signatures=tuple(new_signatures))
8,265,409,913,908,250,000
Merge signatures of a function. This groups signatures by arguments and then for each group creates a single signature that joins the return values / exceptions using "or". Arguments: f: A pytd.Function instance Returns: Function with simplified / combined signatures.
pytype/pytd/optimize.py
VisitFunction
Jason-Cooke/pytype
python
def VisitFunction(self, f): 'Merge signatures of a function.\n\n This groups signatures by arguments and then for each group creates a\n single signature that joins the return values / exceptions using "or".\n\n Arguments:\n f: A pytd.Function instance\n\n Returns:\n Function with simplified / combined signatures.\n ' groups = self._GroupByArguments(f.signatures) new_signatures = [] for (stripped_signature, ret_exc) in groups.items(): ret = pytd_utils.JoinTypes(ret_exc.return_types) exc = tuple(ret_exc.exceptions) new_signatures.append(stripped_signature.Replace(return_type=ret, exceptions=exc)) return f.Replace(signatures=tuple(new_signatures))
def _should_merge(self, pytd_type, union): 'Determine whether pytd_type values in the union should be merged.\n\n If the union contains the homogeneous flavor of pytd_type (e.g.,\n GenericType(base_type=tuple) when pytd_type is TupleType), or pytd_type\n values of different lengths, we want to turn all of the pytd_type values\n into homogeneous ones so that they can be merged into a single container.\n\n Args:\n pytd_type: The pytd type, either TupleType or CallableType.\n union: a pytd.UnionType\n\n Returns:\n True if the pytd_type values should be merged, False otherwise.\n ' names = self._CONTAINER_NAMES[pytd_type] length = None for t in union.type_list: if isinstance(t, pytd_type): if (length is None): length = len(t.parameters) elif (length != len(t.parameters)): return True elif (isinstance(t, pytd.GenericType) and (t.base_type.name in names)): return True return False
-7,666,861,207,979,777,000
Determine whether pytd_type values in the union should be merged. If the union contains the homogeneous flavor of pytd_type (e.g., GenericType(base_type=tuple) when pytd_type is TupleType), or pytd_type values of different lengths, we want to turn all of the pytd_type values into homogeneous ones so that they can be merged into a single container. Args: pytd_type: The pytd type, either TupleType or CallableType. union: a pytd.UnionType Returns: True if the pytd_type values should be merged, False otherwise.
pytype/pytd/optimize.py
_should_merge
Jason-Cooke/pytype
python
def _should_merge(self, pytd_type, union): 'Determine whether pytd_type values in the union should be merged.\n\n If the union contains the homogeneous flavor of pytd_type (e.g.,\n GenericType(base_type=tuple) when pytd_type is TupleType), or pytd_type\n values of different lengths, we want to turn all of the pytd_type values\n into homogeneous ones so that they can be merged into a single container.\n\n Args:\n pytd_type: The pytd type, either TupleType or CallableType.\n union: a pytd.UnionType\n\n Returns:\n True if the pytd_type values should be merged, False otherwise.\n ' names = self._CONTAINER_NAMES[pytd_type] length = None for t in union.type_list: if isinstance(t, pytd_type): if (length is None): length = len(t.parameters) elif (length != len(t.parameters)): return True elif (isinstance(t, pytd.GenericType) and (t.base_type.name in names)): return True return False
def VisitUnionType(self, union): 'Push unions down into containers.\n\n This collects similar container types in unions and merges them into\n single instances with the union type pushed down to the element_type level.\n\n Arguments:\n union: A pytd.Union instance. Might appear in a parameter, a return type,\n a constant type, etc.\n\n Returns:\n A simplified pytd.Union.\n ' if (not any((isinstance(t, pytd.GenericType) for t in union.type_list))): return union union = pytd_utils.JoinTypes(union.type_list) if (not isinstance(union, pytd.UnionType)): union = pytd.UnionType((union,)) merge_tuples = self._should_merge(pytd.TupleType, union) merge_callables = self._should_merge(pytd.CallableType, union) if (merge_tuples or merge_callables): type_list = [] for t in union.type_list: if (merge_tuples and isinstance(t, pytd.TupleType)): t = pytd.GenericType(base_type=t.base_type, parameters=(pytd.UnionType(t.parameters),)) elif (merge_callables and isinstance(t, pytd.CallableType)): t = pytd.GenericType(base_type=t.base_type, parameters=(pytd.AnythingType(), t.ret)) type_list.append(t) union = union.Replace(type_list=tuple(type_list)) collect = {} has_redundant_base_types = False for t in union.type_list: if isinstance(t, pytd.GenericType): key = self._key(t) if (key in collect): has_redundant_base_types = True collect[key] = tuple((pytd_utils.JoinTypes([p1, p2]) for (p1, p2) in zip(collect[key], t.parameters))) else: collect[key] = t.parameters if (not has_redundant_base_types): return union result = pytd.NothingType() done = set() for t in union.type_list: if isinstance(t, pytd.GenericType): key = self._key(t) if (key in done): continue parameters = collect[key] add = t.Replace(parameters=tuple((p.Visit(CombineContainers()) for p in parameters))) done.add(key) else: add = t result = pytd_utils.JoinTypes([result, add]) return result
3,989,119,320,059,164,700
Push unions down into containers. This collects similar container types in unions and merges them into single instances with the union type pushed down to the element_type level. Arguments: union: A pytd.Union instance. Might appear in a parameter, a return type, a constant type, etc. Returns: A simplified pytd.Union.
pytype/pytd/optimize.py
VisitUnionType
Jason-Cooke/pytype
python
def VisitUnionType(self, union): 'Push unions down into containers.\n\n This collects similar container types in unions and merges them into\n single instances with the union type pushed down to the element_type level.\n\n Arguments:\n union: A pytd.Union instance. Might appear in a parameter, a return type,\n a constant type, etc.\n\n Returns:\n A simplified pytd.Union.\n ' if (not any((isinstance(t, pytd.GenericType) for t in union.type_list))): return union union = pytd_utils.JoinTypes(union.type_list) if (not isinstance(union, pytd.UnionType)): union = pytd.UnionType((union,)) merge_tuples = self._should_merge(pytd.TupleType, union) merge_callables = self._should_merge(pytd.CallableType, union) if (merge_tuples or merge_callables): type_list = [] for t in union.type_list: if (merge_tuples and isinstance(t, pytd.TupleType)): t = pytd.GenericType(base_type=t.base_type, parameters=(pytd.UnionType(t.parameters),)) elif (merge_callables and isinstance(t, pytd.CallableType)): t = pytd.GenericType(base_type=t.base_type, parameters=(pytd.AnythingType(), t.ret)) type_list.append(t) union = union.Replace(type_list=tuple(type_list)) collect = {} has_redundant_base_types = False for t in union.type_list: if isinstance(t, pytd.GenericType): key = self._key(t) if (key in collect): has_redundant_base_types = True collect[key] = tuple((pytd_utils.JoinTypes([p1, p2]) for (p1, p2) in zip(collect[key], t.parameters))) else: collect[key] = t.parameters if (not has_redundant_base_types): return union result = pytd.NothingType() done = set() for t in union.type_list: if isinstance(t, pytd.GenericType): key = self._key(t) if (key in done): continue parameters = collect[key] add = t.Replace(parameters=tuple((p.Visit(CombineContainers()) for p in parameters))) done.add(key) else: add = t result = pytd_utils.JoinTypes([result, add]) return result
def _GroupByOmittedArg(self, signatures, i): 'Group functions that are identical if you ignore one of the arguments.\n\n Arguments:\n signatures: A list of function signatures\n i: The index of the argument to ignore during comparison.\n\n Returns:\n A list of tuples (signature, types). "signature" is a signature with\n argument i omitted, "types" is the list of types that argument was\n found to have. signatures that don\'t have argument i are represented\n as (original, None).\n ' groups = collections.OrderedDict() for sig in signatures: if (i >= len(sig.params)): groups[sig] = None continue if (sig.params[i].mutated_type is not None): groups[sig] = None continue params = list(sig.params) param_i = params[i] params[i] = param_i.Replace(type=None) stripped_signature = sig.Replace(params=tuple(params)) existing = groups.get(stripped_signature) if existing: existing.append(param_i.type) else: groups[stripped_signature] = [param_i.type] return groups.items()
-4,543,675,287,192,792,000
Group functions that are identical if you ignore one of the arguments. Arguments: signatures: A list of function signatures i: The index of the argument to ignore during comparison. Returns: A list of tuples (signature, types). "signature" is a signature with argument i omitted, "types" is the list of types that argument was found to have. signatures that don't have argument i are represented as (original, None).
pytype/pytd/optimize.py
_GroupByOmittedArg
Jason-Cooke/pytype
python
def _GroupByOmittedArg(self, signatures, i): 'Group functions that are identical if you ignore one of the arguments.\n\n Arguments:\n signatures: A list of function signatures\n i: The index of the argument to ignore during comparison.\n\n Returns:\n A list of tuples (signature, types). "signature" is a signature with\n argument i omitted, "types" is the list of types that argument was\n found to have. signatures that don\'t have argument i are represented\n as (original, None).\n ' groups = collections.OrderedDict() for sig in signatures: if (i >= len(sig.params)): groups[sig] = None continue if (sig.params[i].mutated_type is not None): groups[sig] = None continue params = list(sig.params) param_i = params[i] params[i] = param_i.Replace(type=None) stripped_signature = sig.Replace(params=tuple(params)) existing = groups.get(stripped_signature) if existing: existing.append(param_i.type) else: groups[stripped_signature] = [param_i.type] return groups.items()
def VisitFunction(self, f): 'Shrink a function, by factorizing cartesian products of arguments.\n\n Greedily groups signatures, looking at the arguments from left to right.\n This algorithm is *not* optimal. But it does the right thing for the\n typical cases.\n\n Arguments:\n f: An instance of pytd.Function. If this function has more\n than one signature, we will try to combine some of these signatures by\n introducing union types.\n\n Returns:\n A new, potentially optimized, instance of pytd.Function.\n\n ' max_argument_count = max((len(s.params) for s in f.signatures)) signatures = f.signatures for i in six.moves.xrange(max_argument_count): new_sigs = [] for (sig, types) in self._GroupByOmittedArg(signatures, i): if types: new_params = list(sig.params) new_params[i] = sig.params[i].Replace(type=pytd_utils.JoinTypes(types)) sig = sig.Replace(params=tuple(new_params)) new_sigs.append(sig) else: new_sigs.append(sig) signatures = new_sigs return f.Replace(signatures=tuple(signatures))
-2,093,395,296,062,262,300
Shrink a function, by factorizing cartesian products of arguments. Greedily groups signatures, looking at the arguments from left to right. This algorithm is *not* optimal. But it does the right thing for the typical cases. Arguments: f: An instance of pytd.Function. If this function has more than one signature, we will try to combine some of these signatures by introducing union types. Returns: A new, potentially optimized, instance of pytd.Function.
pytype/pytd/optimize.py
VisitFunction
Jason-Cooke/pytype
python
def VisitFunction(self, f): 'Shrink a function, by factorizing cartesian products of arguments.\n\n Greedily groups signatures, looking at the arguments from left to right.\n This algorithm is *not* optimal. But it does the right thing for the\n typical cases.\n\n Arguments:\n f: An instance of pytd.Function. If this function has more\n than one signature, we will try to combine some of these signatures by\n introducing union types.\n\n Returns:\n A new, potentially optimized, instance of pytd.Function.\n\n ' max_argument_count = max((len(s.params) for s in f.signatures)) signatures = f.signatures for i in six.moves.xrange(max_argument_count): new_sigs = [] for (sig, types) in self._GroupByOmittedArg(signatures, i): if types: new_params = list(sig.params) new_params[i] = sig.params[i].Replace(type=pytd_utils.JoinTypes(types)) sig = sig.Replace(params=tuple(new_params)) new_sigs.append(sig) else: new_sigs.append(sig) signatures = new_sigs return f.Replace(signatures=tuple(signatures))
def _HasShorterVersion(self, sig, optional_arg_sigs): "Find a shorter signature with optional arguments for a longer signature.\n\n Arguments:\n sig: The function signature we'd like to shorten\n optional_arg_sigs: A set of function signatures with optional arguments\n that will be matched against sig.\n\n Returns:\n True if there is a shorter signature that generalizes sig, but is not\n identical to sig.\n " param_count = len(sig.params) if (not sig.has_optional): param_count += 1 for i in six.moves.xrange(param_count): if (sig.params[0:i] in optional_arg_sigs): return True return False
-4,951,890,905,944,827,000
Find a shorter signature with optional arguments for a longer signature. Arguments: sig: The function signature we'd like to shorten optional_arg_sigs: A set of function signatures with optional arguments that will be matched against sig. Returns: True if there is a shorter signature that generalizes sig, but is not identical to sig.
pytype/pytd/optimize.py
_HasShorterVersion
Jason-Cooke/pytype
python
def _HasShorterVersion(self, sig, optional_arg_sigs): "Find a shorter signature with optional arguments for a longer signature.\n\n Arguments:\n sig: The function signature we'd like to shorten\n optional_arg_sigs: A set of function signatures with optional arguments\n that will be matched against sig.\n\n Returns:\n True if there is a shorter signature that generalizes sig, but is not\n identical to sig.\n " param_count = len(sig.params) if (not sig.has_optional): param_count += 1 for i in six.moves.xrange(param_count): if (sig.params[0:i] in optional_arg_sigs): return True return False
def VisitFunction(self, f): 'Remove all signatures that have a shorter version.\n\n We use signatures with optional argument (has_opt=True) as template\n and then match all signatures against those templates, removing those\n that match.\n\n Arguments:\n f: An instance of pytd.Function\n\n Returns:\n A potentially simplified instance of pytd.Function.\n ' optional_arg_sigs = frozenset((s.params for s in f.signatures if s.has_optional)) new_signatures = (s for s in f.signatures if (not self._HasShorterVersion(s, optional_arg_sigs))) return f.Replace(signatures=tuple(new_signatures))
6,061,147,039,077,619,000
Remove all signatures that have a shorter version. We use signatures with optional argument (has_opt=True) as template and then match all signatures against those templates, removing those that match. Arguments: f: An instance of pytd.Function Returns: A potentially simplified instance of pytd.Function.
pytype/pytd/optimize.py
VisitFunction
Jason-Cooke/pytype
python
def VisitFunction(self, f): 'Remove all signatures that have a shorter version.\n\n We use signatures with optional argument (has_opt=True) as template\n and then match all signatures against those templates, removing those\n that match.\n\n Arguments:\n f: An instance of pytd.Function\n\n Returns:\n A potentially simplified instance of pytd.Function.\n ' optional_arg_sigs = frozenset((s.params for s in f.signatures if s.has_optional)) new_signatures = (s for s in f.signatures if (not self._HasShorterVersion(s, optional_arg_sigs))) return f.Replace(signatures=tuple(new_signatures))
def _CollectSuperclasses(self, type_name, collect): "Recursively collect super classes for a type.\n\n Arguments:\n type_name: A string, the type's name.\n collect: A set() of strings, modified to contain all superclasses.\n " collect.add(type_name) superclasses = [name for name in self._superclasses.get(type_name, [])] for superclass in superclasses: self._CollectSuperclasses(superclass, collect)
2,694,874,249,978,737,000
Recursively collect super classes for a type. Arguments: type_name: A string, the type's name. collect: A set() of strings, modified to contain all superclasses.
pytype/pytd/optimize.py
_CollectSuperclasses
Jason-Cooke/pytype
python
def _CollectSuperclasses(self, type_name, collect): "Recursively collect super classes for a type.\n\n Arguments:\n type_name: A string, the type's name.\n collect: A set() of strings, modified to contain all superclasses.\n " collect.add(type_name) superclasses = [name for name in self._superclasses.get(type_name, [])] for superclass in superclasses: self._CollectSuperclasses(superclass, collect)
def ExpandSuperClasses(self, t): 'Generate a list of all (known) superclasses for a type.\n\n Arguments:\n t: A type name. E.g. "int".\n\n Returns:\n A set of types. This set includes t as well as all its superclasses. For\n example, this will return "bool", "int" and "object" for "bool".\n ' superclasses = set() self._CollectSuperclasses(t, superclasses) return superclasses
-3,164,347,053,816,719,000
Generate a list of all (known) superclasses for a type. Arguments: t: A type name. E.g. "int". Returns: A set of types. This set includes t as well as all its superclasses. For example, this will return "bool", "int" and "object" for "bool".
pytype/pytd/optimize.py
ExpandSuperClasses
Jason-Cooke/pytype
python
def ExpandSuperClasses(self, t): 'Generate a list of all (known) superclasses for a type.\n\n Arguments:\n t: A type name. E.g. "int".\n\n Returns:\n A set of types. This set includes t as well as all its superclasses. For\n example, this will return "bool", "int" and "object" for "bool".\n ' superclasses = set() self._CollectSuperclasses(t, superclasses) return superclasses
def ExpandSubClasses(self, t): 'Generate a set of all (known) subclasses for a type.\n\n Arguments:\n t: A type. E.g. NamedType("int").\n\n Returns:\n A set of types. This set includes t as well as all its subclasses. For\n example, this will return "int" and "bool" for "int".\n ' queue = [t] seen = set() while queue: item = queue.pop() if (item not in seen): seen.add(item) queue.extend(self._subclasses[item]) return seen
-5,729,315,633,066,633,000
Generate a set of all (known) subclasses for a type. Arguments: t: A type. E.g. NamedType("int"). Returns: A set of types. This set includes t as well as all its subclasses. For example, this will return "int" and "bool" for "int".
pytype/pytd/optimize.py
ExpandSubClasses
Jason-Cooke/pytype
python
def ExpandSubClasses(self, t): 'Generate a set of all (known) subclasses for a type.\n\n Arguments:\n t: A type. E.g. NamedType("int").\n\n Returns:\n A set of types. This set includes t as well as all its subclasses. For\n example, this will return "int" and "bool" for "int".\n ' queue = [t] seen = set() while queue: item = queue.pop() if (item not in seen): seen.add(item) queue.extend(self._subclasses[item]) return seen
def HasSubClassInSet(self, cls, known): 'Queries whether a subclass of a type is present in a given set.' return any(((sub in known) for sub in self._subclasses[cls]))
-8,018,859,527,486,962,000
Queries whether a subclass of a type is present in a given set.
pytype/pytd/optimize.py
HasSubClassInSet
Jason-Cooke/pytype
python
def HasSubClassInSet(self, cls, known): return any(((sub in known) for sub in self._subclasses[cls]))
def HasSuperClassInSet(self, cls, known): 'Queries whether a superclass of a type is present in a given set.' return any(((sub in known) for sub in self._superclasses[cls]))
-8,379,769,540,123,114,000
Queries whether a superclass of a type is present in a given set.
pytype/pytd/optimize.py
HasSuperClassInSet
Jason-Cooke/pytype
python
def HasSuperClassInSet(self, cls, known): return any(((sub in known) for sub in self._superclasses[cls]))
def VisitUnionType(self, union): 'Given a union type, try to find a simplification by using superclasses.\n\n This is a lossy optimization that tries to map a list of types to a common\n base type. For example, int and bool are both base classes of int, so it\n would convert "int or bool" to "int".\n\n Arguments:\n union: A union type.\n\n Returns:\n A simplified type, if available.\n ' intersection = self.hierarchy.ExpandSuperClasses(str(union.type_list[0])) for t in union.type_list[1:]: intersection.intersection_update(self.hierarchy.ExpandSuperClasses(str(t))) new_type_list = tuple((pytd.NamedType(cls) for cls in intersection if (not self.hierarchy.HasSubClassInSet(cls, intersection)))) if (not new_type_list): return union return pytd_utils.JoinTypes(new_type_list)
-1,763,532,200,732,307,200
Given a union type, try to find a simplification by using superclasses. This is a lossy optimization that tries to map a list of types to a common base type. For example, int and bool are both base classes of int, so it would convert "int or bool" to "int". Arguments: union: A union type. Returns: A simplified type, if available.
pytype/pytd/optimize.py
VisitUnionType
Jason-Cooke/pytype
python
def VisitUnionType(self, union): 'Given a union type, try to find a simplification by using superclasses.\n\n This is a lossy optimization that tries to map a list of types to a common\n base type. For example, int and bool are both base classes of int, so it\n would convert "int or bool" to "int".\n\n Arguments:\n union: A union type.\n\n Returns:\n A simplified type, if available.\n ' intersection = self.hierarchy.ExpandSuperClasses(str(union.type_list[0])) for t in union.type_list[1:]: intersection.intersection_update(self.hierarchy.ExpandSuperClasses(str(t))) new_type_list = tuple((pytd.NamedType(cls) for cls in intersection if (not self.hierarchy.HasSubClassInSet(cls, intersection)))) if (not new_type_list): return union return pytd_utils.JoinTypes(new_type_list)
def VisitClass(self, cls): 'Add superclass methods and constants to this Class.' if any((base for base in cls.parents if isinstance(base, pytd.NamedType))): raise AssertionError('AddInheritedMethods needs a resolved AST') bases = [base.cls for base in cls.parents if isinstance(base, pytd.ClassType)] names = ({m.name for m in cls.methods} | {c.name for c in cls.constants}) adjust_self = visitors.AdjustSelf(force=True) adjust_self.class_types.append(visitors.ClassAsType(cls)) new_methods = list(cls.methods) for base in bases: for m in base.methods: if (m.name not in names): new_methods.append(m.Visit(adjust_self)) new_constants = list(cls.constants) for base in bases: for c in base.constants: if (c.name not in names): new_constants.append(c) return cls.Replace(methods=tuple(new_methods), constants=tuple(new_constants))
-539,083,352,919,797,400
Add superclass methods and constants to this Class.
pytype/pytd/optimize.py
VisitClass
Jason-Cooke/pytype
python
def VisitClass(self, cls): if any((base for base in cls.parents if isinstance(base, pytd.NamedType))): raise AssertionError('AddInheritedMethods needs a resolved AST') bases = [base.cls for base in cls.parents if isinstance(base, pytd.ClassType)] names = ({m.name for m in cls.methods} | {c.name for c in cls.constants}) adjust_self = visitors.AdjustSelf(force=True) adjust_self.class_types.append(visitors.ClassAsType(cls)) new_methods = list(cls.methods) for base in bases: for m in base.methods: if (m.name not in names): new_methods.append(m.Visit(adjust_self)) new_constants = list(cls.constants) for base in bases: for c in base.constants: if (c.name not in names): new_constants.append(c) return cls.Replace(methods=tuple(new_methods), constants=tuple(new_constants))
def _StrippedSignatures(self, t): 'Given a class, list method name + signature without "self".\n\n Args:\n t: A pytd.TYPE.\n\n Returns:\n A set of name + signature tuples, with the self parameter of the\n signature removed.\n ' if (not isinstance(t, pytd.ClassType)): return {} stripped_signatures = {} for method in t.cls.methods: for sig in method.signatures: if (sig.params and (sig.params[0].name == 'self') and isinstance(sig.params[0].type, pytd.ClassType)): stripped_signatures[method.name] = (sig.Replace(params=sig.params[1:]), method.is_abstract) return stripped_signatures
-2,989,404,233,739,137,500
Given a class, list method name + signature without "self". Args: t: A pytd.TYPE. Returns: A set of name + signature tuples, with the self parameter of the signature removed.
pytype/pytd/optimize.py
_StrippedSignatures
Jason-Cooke/pytype
python
def _StrippedSignatures(self, t): 'Given a class, list method name + signature without "self".\n\n Args:\n t: A pytd.TYPE.\n\n Returns:\n A set of name + signature tuples, with the self parameter of the\n signature removed.\n ' if (not isinstance(t, pytd.ClassType)): return {} stripped_signatures = {} for method in t.cls.methods: for sig in method.signatures: if (sig.params and (sig.params[0].name == 'self') and isinstance(sig.params[0].type, pytd.ClassType)): stripped_signatures[method.name] = (sig.Replace(params=sig.params[1:]), method.is_abstract) return stripped_signatures
def _FindNameAndSig(self, classes, name, sig): 'Find a tuple(name, signature) in all methods of a type/class.' if classes: t = classes[0] classes = classes[1:] if (t not in self.class_to_stripped_signatures): self.class_to_stripped_signatures[t] = self._StrippedSignatures(t) if (name in self.class_to_stripped_signatures[t]): return (sig == self.class_to_stripped_signatures[t][name]) return self._FindNameAndSig(classes, name, sig) return False
5,557,215,247,641,223,000
Find a tuple(name, signature) in all methods of a type/class.
pytype/pytd/optimize.py
_FindNameAndSig
Jason-Cooke/pytype
python
def _FindNameAndSig(self, classes, name, sig): if classes: t = classes[0] classes = classes[1:] if (t not in self.class_to_stripped_signatures): self.class_to_stripped_signatures[t] = self._StrippedSignatures(t) if (name in self.class_to_stripped_signatures[t]): return (sig == self.class_to_stripped_signatures[t][name]) return self._FindNameAndSig(classes, name, sig) return False
def _MaybeRemoveSignature(self, name, sig, is_abstract): 'Visit a Signature and return None if we can remove it.' if ((not sig.params) or (sig.params[0].name != 'self') or (not isinstance(sig.params[0].type, pytd.ClassType))): return sig cls = sig.params[0].type.cls if (cls is None): return sig try: if self._FindNameAndSig(mro.GetBasesInMRO(cls), name, (sig.Replace(params=sig.params[1:]), is_abstract)): return None except mro.MROError: return sig return sig
-4,831,986,339,393,087,000
Visit a Signature and return None if we can remove it.
pytype/pytd/optimize.py
_MaybeRemoveSignature
Jason-Cooke/pytype
python
def _MaybeRemoveSignature(self, name, sig, is_abstract): if ((not sig.params) or (sig.params[0].name != 'self') or (not isinstance(sig.params[0].type, pytd.ClassType))): return sig cls = sig.params[0].type.cls if (cls is None): return sig try: if self._FindNameAndSig(mro.GetBasesInMRO(cls), name, (sig.Replace(params=sig.params[1:]), is_abstract)): return None except mro.MROError: return sig return sig
def _MaybeDeleteFunction(self, f): 'Visit a Function and return None if we can remove it.' signatures = tuple((self._MaybeRemoveSignature(f.name, sig, f.is_abstract) for sig in f.signatures)) if any(signatures): if signatures.count(None): return f.Replace(signatures=tuple((s for s in signatures if (s is not None)))) else: return f else: return None
-5,250,504,012,407,546,000
Visit a Function and return None if we can remove it.
pytype/pytd/optimize.py
_MaybeDeleteFunction
Jason-Cooke/pytype
python
def _MaybeDeleteFunction(self, f): signatures = tuple((self._MaybeRemoveSignature(f.name, sig, f.is_abstract) for sig in f.signatures)) if any(signatures): if signatures.count(None): return f.Replace(signatures=tuple((s for s in signatures if (s is not None)))) else: return f else: return None
def _HasSelf(self, sig): 'True if a signature has a self parameter.\n\n This only checks for the name, since the type can be too many different\n things (type of the method, type of the parent class, object, unknown etc.)\n and doesn\'t carry over to the simplified version, anyway.\n\n Arguments:\n sig: Function signature (instance of pytd.Signature)\n Returns:\n True if the signature has "self".\n ' return (sig.params and (sig.params[0].name == 'self'))
1,844,493,868,019,536,400
True if a signature has a self parameter. This only checks for the name, since the type can be too many different things (type of the method, type of the parent class, object, unknown etc.) and doesn't carry over to the simplified version, anyway. Arguments: sig: Function signature (instance of pytd.Signature) Returns: True if the signature has "self".
pytype/pytd/optimize.py
_HasSelf
Jason-Cooke/pytype
python
def _HasSelf(self, sig): 'True if a signature has a self parameter.\n\n This only checks for the name, since the type can be too many different\n things (type of the method, type of the parent class, object, unknown etc.)\n and doesn\'t carry over to the simplified version, anyway.\n\n Arguments:\n sig: Function signature (instance of pytd.Signature)\n Returns:\n True if the signature has "self".\n ' return (sig.params and (sig.params[0].name == 'self'))
def _LookupIfSimpleCall(self, t): 'Looks up the type if it has only one method, "__call__".' if (not isinstance(t, (pytd.NamedType, pytd.ClassType))): return None cls = self._MaybeLookup(t) if (not isinstance(cls, pytd.Class)): return None if ([f.name for f in cls.methods] != ['__call__']): return None (method,) = cls.methods return (cls if all((self._HasSelf(sig) for sig in method.signatures)) else None)
3,178,578,742,380,855,000
Looks up the type if it has only one method, "__call__".
pytype/pytd/optimize.py
_LookupIfSimpleCall
Jason-Cooke/pytype
python
def _LookupIfSimpleCall(self, t): if (not isinstance(t, (pytd.NamedType, pytd.ClassType))): return None cls = self._MaybeLookup(t) if (not isinstance(cls, pytd.Class)): return None if ([f.name for f in cls.methods] != ['__call__']): return None (method,) = cls.methods return (cls if all((self._HasSelf(sig) for sig in method.signatures)) else None)
def _CanDelete(self, cls): 'Checks whether this class can be deleted.\n\n Returns whether all occurences of this class as a type were due to\n constants we removed.\n\n Arguments:\n cls: A pytd.Class.\n Returns:\n True if we can delete this class.\n ' if (not self._processed_count[cls.name]): return False return (self._processed_count[cls.name] == self._total_count[cls.name])
-8,294,887,025,431,812,000
Checks whether this class can be deleted. Returns whether all occurences of this class as a type were due to constants we removed. Arguments: cls: A pytd.Class. Returns: True if we can delete this class.
pytype/pytd/optimize.py
_CanDelete
Jason-Cooke/pytype
python
def _CanDelete(self, cls): 'Checks whether this class can be deleted.\n\n Returns whether all occurences of this class as a type were due to\n constants we removed.\n\n Arguments:\n cls: A pytd.Class.\n Returns:\n True if we can delete this class.\n ' if (not self._processed_count[cls.name]): return False return (self._processed_count[cls.name] == self._total_count[cls.name])
def VisitClass(self, cls): 'Visit a class, and change constants to methods where possible.' new_constants = [] new_methods = list(cls.methods) adjust_self = visitors.AdjustSelf(force=True) adjust_self.class_types.append(visitors.ClassAsType(cls)) for const in cls.constants: c = self._LookupIfSimpleCall(const.type) if c: signatures = c.methods[0].signatures self._processed_count[c.name] += 1 new_method = pytd.Function(const.name, signatures, c.methods[0].kind) new_methods.append(new_method.Visit(adjust_self)) else: new_constants.append(const) return cls.Replace(constants=tuple(new_constants), methods=tuple(new_methods))
-273,893,617,038,268,100
Visit a class, and change constants to methods where possible.
pytype/pytd/optimize.py
VisitClass
Jason-Cooke/pytype
python
def VisitClass(self, cls): new_constants = [] new_methods = list(cls.methods) adjust_self = visitors.AdjustSelf(force=True) adjust_self.class_types.append(visitors.ClassAsType(cls)) for const in cls.constants: c = self._LookupIfSimpleCall(const.type) if c: signatures = c.methods[0].signatures self._processed_count[c.name] += 1 new_method = pytd.Function(const.name, signatures, c.methods[0].kind) new_methods.append(new_method.Visit(adjust_self)) else: new_constants.append(const) return cls.Replace(constants=tuple(new_constants), methods=tuple(new_methods))
def _AppendNew(self, l1, l2): 'Appends all items to l1 that are not in l2.' for e2 in l2: if (not any(((e1 is e2) for e1 in l1))): l1.append(e2)
-6,798,414,254,383,456,000
Appends all items to l1 that are not in l2.
pytype/pytd/optimize.py
_AppendNew
Jason-Cooke/pytype
python
def _AppendNew(self, l1, l2): for e2 in l2: if (not any(((e1 is e2) for e1 in l1))): l1.append(e2)
def _AllContaining(self, type_param, seen=None): 'Gets all type parameters that are in a union with the passed one.' seen = (seen or set()) result = [type_param] for other in self.type_param_union[type_param.name]: if (other in seen): continue seen.add(other) self._AppendNew(result, (self._AllContaining(other, seen) or [other])) return result
-4,771,300,443,293,036,000
Gets all type parameters that are in a union with the passed one.
pytype/pytd/optimize.py
_AllContaining
Jason-Cooke/pytype
python
def _AllContaining(self, type_param, seen=None): seen = (seen or set()) result = [type_param] for other in self.type_param_union[type_param.name]: if (other in seen): continue seen.add(other) self._AppendNew(result, (self._AllContaining(other, seen) or [other])) return result
def _ReplaceByOuterIfNecessary(self, item, substitutions): 'Potentially replace a function type param with a class type param.\n\n Args:\n item: A pytd.TemplateItem\n substitutions: A dictionary to update with what we replaced.\n Returns:\n Either [item] or [].\n ' containing_union = self._AllContaining(item.type_param) if (not containing_union): return [item] class_type_parameters = [type_param for type_param in containing_union if self.IsClassTypeParameter(type_param)] if class_type_parameters: substitutions[item.type_param] = pytd_utils.JoinTypes(class_type_parameters) return [] else: return [item]
1,268,466,235,160,067,000
Potentially replace a function type param with a class type param. Args: item: A pytd.TemplateItem substitutions: A dictionary to update with what we replaced. Returns: Either [item] or [].
pytype/pytd/optimize.py
_ReplaceByOuterIfNecessary
Jason-Cooke/pytype
python
def _ReplaceByOuterIfNecessary(self, item, substitutions): 'Potentially replace a function type param with a class type param.\n\n Args:\n item: A pytd.TemplateItem\n substitutions: A dictionary to update with what we replaced.\n Returns:\n Either [item] or [].\n ' containing_union = self._AllContaining(item.type_param) if (not containing_union): return [item] class_type_parameters = [type_param for type_param in containing_union if self.IsClassTypeParameter(type_param)] if class_type_parameters: substitutions[item.type_param] = pytd_utils.JoinTypes(class_type_parameters) return [] else: return [item]
def __init__(self, atoms=None, coordinates=None, read=None, molecule=None): '\n Create a trajectory object.\n\n Parameters\n ----------\n atoms : list or None\n List of elements of the molecule for each frame.\n coordinates : list or None\n List of atomic positions of the molecule for each frame.\n read : str or None\n File name to read molecule file (formats: xyz).\n molecule : Molecule\n Create a Trajectory with 1 frame from a Molecule object.\n\n ' self.name = 'Trajectory' if ((atoms is not None) and (coordinates is not None)): self.atoms = atoms self.coordinates = coordinates elif (read is not None): self.read(read) elif (molecule is not None): self.atoms = np.array([molecule.atoms]) self.coordinates = np.array([molecule.coordinates]) self.name = molecule.name else: self.atoms = [] self.coordinates = [] self.current_frame = 0
2,460,777,888,899,880,000
Create a trajectory object. Parameters ---------- atoms : list or None List of elements of the molecule for each frame. coordinates : list or None List of atomic positions of the molecule for each frame. read : str or None File name to read molecule file (formats: xyz). molecule : Molecule Create a Trajectory with 1 frame from a Molecule object.
angstrom/trajectory/trajectory.py
__init__
kbsezginel/angstrom
python
def __init__(self, atoms=None, coordinates=None, read=None, molecule=None): '\n Create a trajectory object.\n\n Parameters\n ----------\n atoms : list or None\n List of elements of the molecule for each frame.\n coordinates : list or None\n List of atomic positions of the molecule for each frame.\n read : str or None\n File name to read molecule file (formats: xyz).\n molecule : Molecule\n Create a Trajectory with 1 frame from a Molecule object.\n\n ' self.name = 'Trajectory' if ((atoms is not None) and (coordinates is not None)): self.atoms = atoms self.coordinates = coordinates elif (read is not None): self.read(read) elif (molecule is not None): self.atoms = np.array([molecule.atoms]) self.coordinates = np.array([molecule.coordinates]) self.name = molecule.name else: self.atoms = [] self.coordinates = [] self.current_frame = 0
def __repr__(self): '\n Returns basic trajectory info.\n\n ' return ('<Trajectory frames: %i | atoms: %i | dimensions: %i>' % tuple(np.shape(self.coordinates)))
2,124,043,638,457,202,000
Returns basic trajectory info.
angstrom/trajectory/trajectory.py
__repr__
kbsezginel/angstrom
python
def __repr__(self): '\n \n\n ' return ('<Trajectory frames: %i | atoms: %i | dimensions: %i>' % tuple(np.shape(self.coordinates)))
def __len__(self): '\n Returns number of frames.\n\n ' return len(self.atoms)
6,058,241,935,371,255,000
Returns number of frames.
angstrom/trajectory/trajectory.py
__len__
kbsezginel/angstrom
python
def __len__(self): '\n \n\n ' return len(self.atoms)
def __add__(self, traj): '\n Trajectory addition for joining the coordinates and elements into a new Trajectory object.\n\n Parameters\n ----------\n traj : Trajectory\n Trajectory object to be added\n\n Returns\n -------\n Trajectory\n Joined Trajectory object.\n\n ' new_traj = Trajectory(atoms=np.append(self.atoms, traj.atoms, axis=0), coordinates=np.append(self.coordinates, traj.coordinates, axis=0)) return new_traj
8,559,690,562,680,115,000
Trajectory addition for joining the coordinates and elements into a new Trajectory object. Parameters ---------- traj : Trajectory Trajectory object to be added Returns ------- Trajectory Joined Trajectory object.
angstrom/trajectory/trajectory.py
__add__
kbsezginel/angstrom
python
def __add__(self, traj): '\n Trajectory addition for joining the coordinates and elements into a new Trajectory object.\n\n Parameters\n ----------\n traj : Trajectory\n Trajectory object to be added\n\n Returns\n -------\n Trajectory\n Joined Trajectory object.\n\n ' new_traj = Trajectory(atoms=np.append(self.atoms, traj.atoms, axis=0), coordinates=np.append(self.coordinates, traj.coordinates, axis=0)) return new_traj