uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
86a9b39ca1aec7181b621657 | train | class | class Help(Command):
def __init__(self):
super().__init__()
self.help = "/help — показать справку\n"
self.full_help = "/help — показать справку обо всех командах\n" \
"/help [команда] — показать полную справку по команде\n"
def on_message(self, event, vk):
... | class Help(Command):
| def __init__(self):
super().__init__()
self.help = "/help — показать справку\n"
self.full_help = "/help — показать справку обо всех командах\n" \
"/help [команда] — показать полную справку по команде\n"
def on_message(self, event, vk):
message = Message(... | from Message import Message
from api import send_message
from command.Command import Command, commands
class Help(Command):
| 23 | 64 | 167 | 4 | 18 | unkSonert/Vk-Bot-Uni-Dubna | command/Help.py | Python | Help | Help | 6 | 27 | 6 | 6 | e6cd242553fdd55bcebce10202bb48d7aa098815 | bigcode/the-stack | train |
06d6e460e6420e916dda2c38 | train | class | class TestCases(unittest.TestCase):
test_input_config = {
'path': 'test_path_%(_ts_month)s',
'table': 'test_table',
'schema': 'test_schema',
'mode': 'append',
'format': 'csv',
'csv': {
'delimiter': ';',
'skip': 9,
'strict': False,
'quote': '"'
},
}
test_pipeli... | class TestCases(unittest.TestCase):
| test_input_config = {
'path': 'test_path_%(_ts_month)s',
'table': 'test_table',
'schema': 'test_schema',
'mode': 'append',
'format': 'csv',
'csv': {
'delimiter': ';',
'skip': 9,
'strict': False,
'quote': '"'
},
}
test_pipeline_config = {
'input': test_input... | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2017 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... | 183 | 256 | 6,111 | 7 | 175 | freyrsae/pydatalab | tests/bigquery/pipeline_tests.py | Python | TestCases | TestCases | 23 | 719 | 23 | 24 | 9667b2084cc986906ec85408ebbbb0935c7df116 | bigcode/the-stack | train |
fcd7529e5738c46df24b7017 | train | function | def test_super_tensor_property():
"""
Tensor: Super_tensor correctly tensors on underlying spaces.
"""
U1 = rand_unitary(3)
U2 = rand_unitary(5)
U = tensor(U1, U2)
S_tens = to_super(U)
S_supertens = super_tensor(to_super(U1), to_super(U2))
assert S_tens == S_supertens
assert S... | def test_super_tensor_property():
| """
Tensor: Super_tensor correctly tensors on underlying spaces.
"""
U1 = rand_unitary(3)
U2 = rand_unitary(5)
U = tensor(U1, U2)
S_tens = to_super(U)
S_supertens = super_tensor(to_super(U1), to_super(U2))
assert S_tens == S_supertens
assert S_supertens.superrep == 'super'
| ).isherm
def test_super_tensor_operket():
"""
Tensor: Checks that super_tensor respects states.
"""
rho1, rho2 = rand_dm(5), rand_dm(7)
operator_to_vector(rho1)
operator_to_vector(rho2)
def test_super_tensor_property():
| 64 | 64 | 104 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_super_tensor_property | test_super_tensor_property | 764 | 777 | 764 | 764 | 2b3d14b984c4a6c8d619bdf5b77e82ca6a65ff9f | bigcode/the-stack | train |
3739f09ec9ff1b97852802ae | train | function | def test_composite_vec():
"""
Composite: Tests compositing states and density operators.
"""
k1 = rand_ket(5)
k2 = rand_ket(7)
r1 = operator_to_vector(ket2dm(k1))
r2 = operator_to_vector(ket2dm(k2))
r3 = operator_to_vector(rand_dm(3))
r4 = operator_to_vector(rand_dm(4))
assert ... | def test_composite_vec():
| """
Composite: Tests compositing states and density operators.
"""
k1 = rand_ket(5)
k2 = rand_ket(7)
r1 = operator_to_vector(ket2dm(k1))
r2 = operator_to_vector(ket2dm(k2))
r3 = operator_to_vector(rand_dm(3))
r4 = operator_to_vector(rand_dm(4))
assert composite(k1, k2) == tenso... | , U2)
assert composite(S3, S4) == super_tensor(S3, S4)
assert composite(U1, S4) == super_tensor(S1, S4)
assert composite(S3, U2) == super_tensor(S3, S2)
def test_composite_vec():
| 64 | 64 | 164 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_composite_vec | test_composite_vec | 798 | 813 | 798 | 798 | 4c1a19873dc050886b470ee06731b8f19e1de149 | bigcode/the-stack | train |
e44e2dae86773a24c7f25a1a | train | function | def test_cosm():
"""
Test Qobj: cosm
"""
A = rand_herm(5)
B = A.cosm().full()
C = la.cosm(A.full())
assert np.all((B-C) < 1e-14)
| def test_cosm():
| """
Test Qobj: cosm
"""
A = rand_herm(5)
B = A.cosm().full()
C = la.cosm(A.full())
assert np.all((B-C) < 1e-14)
| ([3./5, 1./2, 7./20, 1./10, -11./20])),
'sgs',
Qobj(np.diag([9./20, 7./20, 1./5, 0, 0])))
def test_cosm():
| 63 | 64 | 59 | 5 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_cosm | test_cosm | 853 | 863 | 853 | 853 | b63d281cecc74c935374a5d9d7ff8da9367bb225 | bigcode/the-stack | train |
84a0087275d6eed5ac2920d2 | train | function | def test_Qobj_sqrtm():
"Qobj sqrtm"
data = _random_not_singular(5)
A = Qobj(data)
B = A.sqrtm()
assert A == B * B
| def test_Qobj_sqrtm():
| "Qobj sqrtm"
data = _random_not_singular(5)
A = Qobj(data)
B = A.sqrtm()
assert A == B * B
| ).all()
def test_QobjExpmZeroOper():
"Qobj expm zero_oper (#493)"
A = Qobj(np.zeros((5, 5), dtype=complex))
B = A.expm()
assert B == qeye(5)
def test_Qobj_sqrtm():
| 64 | 64 | 48 | 8 | 56 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_Qobj_sqrtm | test_Qobj_sqrtm | 507 | 512 | 507 | 507 | 3bc5c46e0455414b5f782246773f00c22e1ce8d7 | bigcode/the-stack | train |
e937a516468cfb5e8aefd480 | train | function | def test_Qobj_Spmv():
"Qobj mult ndarray right"
A = rand_herm(5)
b = rand_ket(5).full()
C = A*b
D = A.full().dot(b)
assert np.all((C-D) < 1e-14)
| def test_Qobj_Spmv():
| "Qobj mult ndarray right"
A = rand_herm(5)
b = rand_ket(5).full()
C = A*b
D = A.full().dot(b)
assert np.all((C-D) < 1e-14)
| opket2.isoperket
opbra1 = operator_to_vector(fock_dm(2)).dag()
opbra2 = opbra1 * sop
assert opbra2.isoperbra
assert opbra2.dag() == opket2
def test_Qobj_Spmv():
| 64 | 64 | 67 | 8 | 55 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_Qobj_Spmv | test_Qobj_Spmv | 414 | 420 | 414 | 414 | 0b85ef95781393476b51e0b628f0505ac6b1dfa7 | bigcode/the-stack | train |
a174d61f8a078d58e5b3a8e0 | train | function | def test_QobjExpmExplicitlySparse():
"Qobj expm (sparse)"
data = _random_not_singular(15)
A = Qobj(data)
B = A.expm(method='sparse')
assert (B.full() - la.expm(data) < 1e-10).all()
| def test_QobjExpmExplicitlySparse():
| "Qobj expm (sparse)"
data = _random_not_singular(15)
A = Qobj(data)
B = A.expm(method='sparse')
assert (B.full() - la.expm(data) < 1e-10).all()
| "Qobj expm (dense)"
data = _random_not_singular(15)
A = Qobj(data)
B = A.expm()
assert (B.full() - la.expm(data) < 1e-10).all()
def test_QobjExpmExplicitlySparse():
| 64 | 64 | 70 | 10 | 54 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjExpmExplicitlySparse | test_QobjExpmExplicitlySparse | 492 | 497 | 492 | 492 | 6bf4adac0c6d3b06045298ce41f766dbd367b964 | bigcode/the-stack | train |
78dda0c7bbb6af8456a70320 | train | function | def test_QobjUnitaryOper():
"Qobj unitarity"
# Check some standard operators
Sx = sigmax()
Sy = sigmay()
assert_unitarity(qeye(4), True)
assert_unitarity(Sx, True)
assert_unitarity(Sy, True)
assert_unitarity(sigmam(), False)
assert_unitarity(destroy(10), False)
# Check multiplcat... | def test_QobjUnitaryOper():
| "Qobj unitarity"
# Check some standard operators
Sx = sigmax()
Sy = sigmay()
assert_unitarity(qeye(4), True)
assert_unitarity(Sx, True)
assert_unitarity(Sy, True)
assert_unitarity(sigmam(), False)
assert_unitarity(destroy(10), False)
# Check multiplcation of unitary is unitary
... | assert oper.isunitary == unitarity
# Force a reset of the cached value for isunitary.
oper._isunitary = None
# Force a recalculation of isunitary.
assert oper.isunitary == unitarity
def test_QobjUnitaryOper():
| 64 | 64 | 176 | 8 | 55 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjUnitaryOper | test_QobjUnitaryOper | 139 | 156 | 139 | 139 | 611900223e3647feb5cc357e346232fbe15d208a | bigcode/the-stack | train |
a51f0dd9a5bf1d5710bbea6a | train | function | def test_QobjExpmZeroOper():
"Qobj expm zero_oper (#493)"
A = Qobj(np.zeros((5, 5), dtype=complex))
B = A.expm()
assert B == qeye(5)
| def test_QobjExpmZeroOper():
| "Qobj expm zero_oper (#493)"
A = Qobj(np.zeros((5, 5), dtype=complex))
B = A.expm()
assert B == qeye(5)
| m (sparse)"
data = _random_not_singular(15)
A = Qobj(data)
B = A.expm(method='sparse')
assert (B.full() - la.expm(data) < 1e-10).all()
def test_QobjExpmZeroOper():
| 64 | 64 | 53 | 9 | 55 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjExpmZeroOper | test_QobjExpmZeroOper | 500 | 504 | 500 | 500 | f32d9421e62c56f40ba761196d2e00278ee17c64 | bigcode/the-stack | train |
151be09d1102db417a6c8f54 | train | function | def test_QobjEigenEnergies():
"Qobj eigenenergies"
data = np.eye(5)
A = Qobj(data)
b = A.eigenenergies()
assert np.all(b - np.ones(5) == 0)
data = np.diag(np.arange(10))
A = Qobj(data)
b = A.eigenenergies()
assert np.all(b - np.arange(10) == 0)
data = np.diag(np.arange(10))
... | def test_QobjEigenEnergies():
| "Qobj eigenenergies"
data = np.eye(5)
A = Qobj(data)
b = A.eigenenergies()
assert np.all(b - np.ones(5) == 0)
data = np.diag(np.arange(10))
A = Qobj(data)
b = A.eigenenergies()
assert np.all(b - np.arange(10) == 0)
data = np.diag(np.arange(10))
A = 5 * Qobj(data)
b = A.... |
def test_QobjDiagonals():
"Qobj diagonals"
data = _random_not_singular(5)
A = Qobj(data)
b = A.diag()
assert np.all(b - np.diag(data) == 0)
def test_QobjEigenEnergies():
| 64 | 64 | 145 | 8 | 56 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjEigenEnergies | test_QobjEigenEnergies | 453 | 468 | 453 | 453 | ce399935507465412d90d99a414b58195f4faf18 | bigcode/the-stack | train |
58bed47c783e38a83e56e58f | train | function | def test_Qobj_inv():
"Qobj inv"
data = _random_not_singular(5)
A = Qobj(data)
B = A.inv()
assert qeye(5) == A * B
assert qeye(5) == B * A
B = A.inv(sparse=True)
assert qeye(5) == A * B
assert qeye(5) == B * A
| def test_Qobj_inv():
| "Qobj inv"
data = _random_not_singular(5)
A = Qobj(data)
B = A.inv()
assert qeye(5) == A * B
assert qeye(5) == B * A
B = A.inv(sparse=True)
assert qeye(5) == A * B
assert qeye(5) == B * A
| ()
assert B == qeye(5)
def test_Qobj_sqrtm():
"Qobj sqrtm"
data = _random_not_singular(5)
A = Qobj(data)
B = A.sqrtm()
assert A == B * B
def test_Qobj_inv():
| 64 | 64 | 93 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_Qobj_inv | test_Qobj_inv | 515 | 524 | 515 | 515 | e8f279a0a15c17fcf24c4e16aa050c6142bc66b2 | bigcode/the-stack | train |
f4b1f20787aef5d6a3bed062 | train | function | def test_QobjNorm():
"Qobj norm"
# vector L2-norm test
N = 20
x = np.random.random(N) + 1j * np.random.random(N)
A = Qobj(x)
assert np.abs(A.norm() - la.norm(A.data.data, 2)) < 1e-12
# vector max (inf) norm test
assert np.abs(A.norm('max') - la.norm(A.data.data, np.inf)) < 1e-12
# op... | def test_QobjNorm():
| "Qobj norm"
# vector L2-norm test
N = 20
x = np.random.random(N) + 1j * np.random.random(N)
A = Qobj(x)
assert np.abs(A.norm() - la.norm(A.data.data, 2)) < 1e-12
# vector max (inf) norm test
assert np.abs(A.norm('max') - la.norm(A.data.data, np.inf)) < 1e-12
# operator frobius norm
... | (sparse=True)
assert qeye(5) == A * B
assert qeye(5) == B * A
def test_QobjFull():
"Qobj full"
data = _random_not_singular(15)
A = Qobj(data)
b = A.full()
assert np.all(b - data == 0)
def test_QobjNorm():
| 81 | 81 | 271 | 6 | 75 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjNorm | test_QobjNorm | 535 | 552 | 535 | 535 | dd68e188d3582bdd7c4efc169ef359ba47f462fb | bigcode/the-stack | train |
114f450773e4a70e91323c34 | train | function | def test_QobjDivision():
"Qobj division"
data = _random_not_singular(5)
q = Qobj(data)
randN = 10 * np.random.random()
q = q / randN
assert np.allclose(q.full(), data / randN)
| def test_QobjDivision():
| "Qobj division"
data = _random_not_singular(5)
q = Qobj(data)
randN = 10 * np.random.random()
q = q / randN
assert np.allclose(q.full(), data / randN)
| ]])
data3 = np.dot(data1, data2)
q1 = Qobj(data1)
q2 = Qobj(data2)
q3 = Qobj(data3)
q4 = q1 * q2
assert q3 == q4
def test_QobjDivision():
| 64 | 64 | 62 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjDivision | test_QobjDivision | 296 | 302 | 296 | 296 | 72edd161062f28ed04eb71fce38e27a3601e0047 | bigcode/the-stack | train |
c854b4ff85a7d5b16530899e | train | function | @pytest.mark.parametrize("sub_dimensions", ([2], [2, 2], [2, 3], [3, 5, 2]))
def test_dual_channel(sub_dimensions, n_trials=50):
"""
Qobj: dual_chan() preserves inner products with arbitrary density ops.
"""
S = rand_super_bcsz(np.prod(sub_dimensions))
S.dims = [[sub_dimensions, sub_dimensions],
... | @pytest.mark.parametrize("sub_dimensions", ([2], [2, 2], [2, 3], [3, 5, 2]))
def test_dual_channel(sub_dimensions, n_trials=50):
| """
Qobj: dual_chan() preserves inner products with arbitrary density ops.
"""
S = rand_super_bcsz(np.prod(sub_dimensions))
S.dims = [[sub_dimensions, sub_dimensions],
[sub_dimensions, sub_dimensions]]
S = to_super(S)
left_dims, right_dims = S.dims
# Assume for the purpose... |
"""
A = rand_herm(5)
B = A.sinm().full()
C = la.sinm(A.full())
assert np.all((B-C) < 1e-14)
@pytest.mark.parametrize("sub_dimensions", ([2], [2, 2], [2, 3], [3, 5, 2]))
def test_dual_channel(sub_dimensions, n_trials=50):
| 90 | 90 | 301 | 44 | 46 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_dual_channel | test_dual_channel | 879 | 911 | 879 | 880 | 59f468bc1caae469342aedf7ad3a7018f31c6977 | bigcode/the-stack | train |
a2878d74fb96ed9c5b10abcd | train | function | def test_QobjPermute():
"Qobj permute"
A = basis(3, 0)
B = basis(5, 4)
C = basis(4, 2)
psi = tensor(A, B, C)
psi2 = psi.permute([2, 0, 1])
assert psi2 == tensor(C, A, B)
psi_bra = psi.dag()
psi2_bra = psi_bra.permute([2, 0, 1])
assert psi2_bra == tensor(C, A, B).dag()
A = f... | def test_QobjPermute():
| "Qobj permute"
A = basis(3, 0)
B = basis(5, 4)
C = basis(4, 2)
psi = tensor(A, B, C)
psi2 = psi.permute([2, 0, 1])
assert psi2 == tensor(C, A, B)
psi_bra = psi.dag()
psi2_bra = psi_bra.permute([2, 0, 1])
assert psi2_bra == tensor(C, A, B).dag()
A = fock_dm(3, 0)
B = foc... | test_QobjPurity():
"Tests the purity method of `Qobj`"
psi = basis(2, 1)
# check purity of pure ket state
assert np.allclose(psi.purity(), 1)
# check purity of pure ket state (superposition)
psi2 = basis(2, 0)
psi_tot = (psi+psi2).unit()
assert np.allclose(psi_tot.purity(), 1)
# che... | 186 | 186 | 622 | 7 | 179 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjPermute | test_QobjPermute | 571 | 626 | 571 | 571 | 539e240ac4eec11d47b8dc646d9aabe05629379a | bigcode/the-stack | train |
974656a059c1ac761d07b520 | train | function | def test_QobjConjugate():
"Qobj conjugate"
data = _random_not_singular(5)
A = Qobj(data)
B = A.conj()
assert np.all(B.full() == data.conj())
assert A.isherm == B.isherm
assert A.type == B.type
assert A.superrep == B.superrep
| def test_QobjConjugate():
| "Qobj conjugate"
data = _random_not_singular(5)
A = Qobj(data)
B = A.conj()
assert np.all(B.full() == data.conj())
assert A.isherm == B.isherm
assert A.type == B.type
assert A.superrep == B.superrep
| obj mult ndarray right"
A = rand_herm(5)
b = rand_ket(5).full()
C = A*b
D = A.full().dot(b)
assert np.all((C-D) < 1e-14)
def test_QobjConjugate():
| 64 | 64 | 82 | 8 | 56 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjConjugate | test_QobjConjugate | 423 | 431 | 423 | 423 | 4ecc0945eaeb7b6220ba351ede52c70ad5a02af3 | bigcode/the-stack | train |
86f392e73a6fcc7713b4fcca | train | function | def _random_not_singular(N):
"""
return a N*N complex array with determinant not 0.
"""
data = np.zeros((1, 1))
while np.linalg.det(data) == 0:
data = np.random.random((N, N)) + \
1j * np.random.random((N, N)) - (0.5 + 0.5j)
return data
| def _random_not_singular(N):
| """
return a N*N complex array with determinant not 0.
"""
data = np.zeros((1, 1))
while np.linalg.det(data) == 0:
data = np.random.random((N, N)) + \
1j * np.random.random((N, N)) - (0.5 + 0.5j)
return data
| _to_vector,
vector_to_operator)
from qutip.superop_reps import to_super, to_choi, to_chi
from qutip.tensor import tensor, super_tensor, composite
from operator import add, mul, truediv, sub
import pytest
def _random_not_singular(N):
| 64 | 64 | 89 | 8 | 55 | quantshah/qutip | qutip/tests/test_qobj.py | Python | _random_not_singular | _random_not_singular | 19 | 27 | 19 | 19 | d044aa728f2882cc939e135ef35e85f42dd0b144 | bigcode/the-stack | train |
9a31c8775fcbaad300d49faa | train | function | def test_QobjPurity():
"Tests the purity method of `Qobj`"
psi = basis(2, 1)
# check purity of pure ket state
assert np.allclose(psi.purity(), 1)
# check purity of pure ket state (superposition)
psi2 = basis(2, 0)
psi_tot = (psi+psi2).unit()
assert np.allclose(psi_tot.purity(), 1)
# ... | def test_QobjPurity():
| "Tests the purity method of `Qobj`"
psi = basis(2, 1)
# check purity of pure ket state
assert np.allclose(psi.purity(), 1)
# check purity of pure ket state (superposition)
psi2 = basis(2, 0)
psi_tot = (psi+psi2).unit()
assert np.allclose(psi_tot.purity(), 1)
# check purity of density... | tr().real)
b = rand_herm(10, 0.25) - 1j*rand_herm(10, 0.25)
assert np.allclose(b.norm(), (b*b.dag()).sqrtm().tr().real)
def test_QobjPurity():
| 64 | 64 | 180 | 7 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjPurity | test_QobjPurity | 555 | 568 | 555 | 555 | 26226cdf855daaa69af5b4267284125591195405 | bigcode/the-stack | train |
5060529a97d73853bc2ea94a | train | function | def test_OperType():
"Qobj operator type"
psi = basis(2, 1)
rho = psi * psi.dag()
assert not rho.isket
assert not rho.isbra
assert rho.isoper
assert not rho.issuper
| def test_OperType():
| "Qobj operator type"
psi = basis(2, 1)
rho = psi * psi.dag()
assert not rho.isket
assert not rho.isbra
assert rho.isoper
assert not rho.issuper
| assert not psi.issuper
psi = tensor(basis(2, 1).dag(), basis(2, 0).dag())
assert not psi.isket
assert psi.isbra
assert not psi.isoper
assert not psi.issuper
def test_OperType():
| 64 | 64 | 60 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_OperType | test_OperType | 665 | 674 | 665 | 665 | 053ba63c6a263789286224fc353e03df42380854 | bigcode/the-stack | train |
30753695fbfd4f49630df8ea | train | function | def test_QobjType():
"Qobj type"
N = int(np.ceil(10.0 * np.random.random())) + 5
ket_data = np.random.random((N, 1))
ket_qobj = Qobj(ket_data)
assert ket_qobj.type == 'ket'
assert ket_qobj.isket
bra_data = np.random.random((1, N))
bra_qobj = Qobj(bra_data)
assert bra_qobj.type == '... | def test_QobjType():
| "Qobj type"
N = int(np.ceil(10.0 * np.random.random())) + 5
ket_data = np.random.random((N, 1))
ket_qobj = Qobj(ket_data)
assert ket_qobj.type == 'ket'
assert ket_qobj.isket
bra_data = np.random.random((1, N))
bra_qobj = Qobj(bra_data)
assert bra_qobj.type == 'bra'
assert bra_q... | # check if data is a csr_matrix if originally csr_matrix
assert sp.isspmatrix_csr(q2.data)
data3 = 1
q3 = Qobj(data3)
# check if data is a csr_matrix if originally int
assert sp.isspmatrix_csr(q3.data)
def test_QobjType():
| 74 | 74 | 248 | 6 | 68 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjType | test_QobjType | 61 | 88 | 61 | 61 | c505876a84b77cfa7896c07e9724e27a31abbcd8 | bigcode/the-stack | train |
bdbc00260339bfaf7a1becff | train | function | def test_QobjDagger():
"Qobj adjoint (dagger)"
data = _random_not_singular(5)
A = Qobj(data)
B = A.dag()
assert np.all(B.full() == data.conj().T)
assert A.isherm == B.isherm
assert A.type == B.type
assert A.superrep == B.superrep
| def test_QobjDagger():
| "Qobj adjoint (dagger)"
data = _random_not_singular(5)
A = Qobj(data)
B = A.dag()
assert np.all(B.full() == data.conj().T)
assert A.isherm == B.isherm
assert A.type == B.type
assert A.superrep == B.superrep
| )
A = Qobj(data)
B = A.conj()
assert np.all(B.full() == data.conj())
assert A.isherm == B.isherm
assert A.type == B.type
assert A.superrep == B.superrep
def test_QobjDagger():
| 64 | 64 | 86 | 7 | 56 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjDagger | test_QobjDagger | 434 | 442 | 434 | 434 | 23c20e90cd1811492892b2a814ba57b536fb8fa7 | bigcode/the-stack | train |
b71a93c15249638a70723fea | train | function | def assert_hermicity(oper, hermicity):
# Check the cached isherm, if any exists.
assert oper.isherm == hermicity
# Force a reset of the cached value for isherm.
oper._isherm = None
# Force a recalculation of isherm.
assert oper.isherm == hermicity
| def assert_hermicity(oper, hermicity):
# Check the cached isherm, if any exists.
| assert oper.isherm == hermicity
# Force a reset of the cached value for isherm.
oper._isherm = None
# Force a recalculation of isherm.
assert oper.isherm == hermicity
| np.random.random((N, N)) + \
1j * np.random.random((N, N)) - (0.5 + 0.5j)
return data
def assert_hermicity(oper, hermicity):
# Check the cached isherm, if any exists.
| 64 | 64 | 78 | 25 | 38 | quantshah/qutip | qutip/tests/test_qobj.py | Python | assert_hermicity | assert_hermicity | 30 | 36 | 30 | 31 | 852169ea99d004eeb3fb271e17d2808e2238ba63 | bigcode/the-stack | train |
a786cf029ed727b7588a2d9d | train | function | def test_QobjMulNonsquareDims():
"""
Qobj: multiplication w/ non-square qobj.dims
Checks for regression of #331.
"""
data = np.array([[0, 1], [1, 0]])
q1 = Qobj(data)
q1.dims[0].append(1)
q2 = Qobj(data)
assert (q1 * q2).dims == [[2, 1], [2]]
assert (q2 * q1.dag()).dims == [[2... | def test_QobjMulNonsquareDims():
| """
Qobj: multiplication w/ non-square qobj.dims
Checks for regression of #331.
"""
data = np.array([[0, 1], [1, 0]])
q1 = Qobj(data)
q1.dims[0].append(1)
q2 = Qobj(data)
assert (q1 * q2).dims == [[2, 1], [2]]
assert (q2 * q1.dag()).dims == [[2], [2, 1]]
# Note that this ... | 0.5j)
q1 = Qobj(data)
assert q1.dims == [[10], [1]]
assert q1.shape == (10, 1)
data = _random_not_singular(4)
q1 = Qobj(data, dims=[[2, 2], [2, 2]])
assert q1.dims == [[2, 2], [2, 2]]
assert q1.shape == (4, 4)
def test_QobjMulNonsquareDims():
| 111 | 111 | 372 | 10 | 101 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjMulNonsquareDims | test_QobjMulNonsquareDims | 181 | 212 | 181 | 181 | e919da4430c7ef825bf09e3f4b16c4e6b6bbf4dc | bigcode/the-stack | train |
3fef0c1e99361816bfa91144 | train | function | def test_QobjNeg():
"Qobj negation"
data = _random_not_singular(5)
q = Qobj(data)
x = -q
assert np.all(x.full() + data == 0)
assert q.isherm == x.isherm
assert q.type == x.type
| def test_QobjNeg():
| "Qobj negation"
data = _random_not_singular(5)
q = Qobj(data)
x = -q
assert np.all(x.full() + data == 0)
assert q.isherm == x.isherm
assert q.type == x.type
| q2.full() - np.linalg.matrix_power(data, 2) < 1e-12).all()
q3 = q ** 3
assert (q3.full() - np.linalg.matrix_power(data, 3) < 1e-12).all()
def test_QobjNeg():
| 64 | 64 | 70 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjNeg | test_QobjNeg | 317 | 324 | 317 | 317 | 8d0457f2c9b7f980c11c634630ad3a5a9b7d8f96 | bigcode/the-stack | train |
aec4611d3a3f22d96ec971c0 | train | function | def test_QobjEigenStates():
"Qobj eigenstates"
data = np.eye(5)
A = Qobj(data)
b, c = A.eigenstates()
assert np.all(b - np.ones(5) == 0)
kets = [basis(5, k) for k in range(5)]
for k in range(5):
assert c[k] == kets[k]
| def test_QobjEigenStates():
| "Qobj eigenstates"
data = np.eye(5)
A = Qobj(data)
b, c = A.eigenstates()
assert np.all(b - np.ones(5) == 0)
kets = [basis(5, k) for k in range(5)]
for k in range(5):
assert c[k] == kets[k]
| np.arange(10) == 0)
data = np.diag(np.arange(10))
A = 5 * Qobj(data)
b = A.eigenenergies()
assert np.all(b - 5 * np.arange(10) == 0)
def test_QobjEigenStates():
| 64 | 64 | 90 | 7 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjEigenStates | test_QobjEigenStates | 471 | 481 | 471 | 471 | 554cf99b0288e44c16b913cc7d04839ec619720f | bigcode/the-stack | train |
9c917327d4a1f6d014704d5f | train | function | def test_QobjGetItem():
"Qobj getitem"
data = _random_not_singular(5)
q = Qobj(data)
assert q[0, 0] == data[0, 0]
assert q[-1, 2] == data[-1, 2]
| def test_QobjGetItem():
| "Qobj getitem"
data = _random_not_singular(5)
q = Qobj(data)
assert q[0, 0] == data[0, 0]
assert q[-1, 2] == data[-1, 2]
| _random_not_singular(5)
q1 = Qobj(data)
q2 = Qobj(data)
assert q1 == q2
q1 = Qobj(data)
q2 = Qobj(-data)
assert q1 != q2
def test_QobjGetItem():
| 64 | 64 | 66 | 7 | 56 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjGetItem | test_QobjGetItem | 339 | 344 | 339 | 339 | fc18b642a01c4b24c143b116b2dcb27cdb227794 | bigcode/the-stack | train |
040b8e4b04d14ae2059b92d3 | train | function | def test_QobjDiagonals():
"Qobj diagonals"
data = _random_not_singular(5)
A = Qobj(data)
b = A.diag()
assert np.all(b - np.diag(data) == 0)
| def test_QobjDiagonals():
| "Qobj diagonals"
data = _random_not_singular(5)
A = Qobj(data)
b = A.diag()
assert np.all(b - np.diag(data) == 0)
| = Qobj(data)
B = A.dag()
assert np.all(B.full() == data.conj().T)
assert A.isherm == B.isherm
assert A.type == B.type
assert A.superrep == B.superrep
def test_QobjDiagonals():
| 64 | 64 | 55 | 8 | 55 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjDiagonals | test_QobjDiagonals | 445 | 450 | 445 | 445 | b5245941226fcedbe897353b4c183a10b628f5f0 | bigcode/the-stack | train |
d1a050ec143df57d13d146cb | train | function | def test_composite_oper():
"""
Composite: Tests compositing unitaries and superoperators.
"""
U1 = rand_unitary(3)
U2 = rand_unitary(5)
S1 = to_super(U1)
S2 = to_super(U2)
S3 = rand_super(4)
S4 = rand_super(7)
assert composite(U1, U2) == tensor(U1, U2)
assert composite(S3, ... | def test_composite_oper():
| """
Composite: Tests compositing unitaries and superoperators.
"""
U1 = rand_unitary(3)
U2 = rand_unitary(5)
S1 = to_super(U1)
S2 = to_super(U2)
S3 = rand_super(4)
S4 = rand_super(7)
assert composite(U1, U2) == tensor(U1, U2)
assert composite(S3, S4) == super_tensor(S3, S4)... | 1, U2)
S_tens = to_super(U)
S_supertens = super_tensor(to_super(U1), to_super(U2))
assert S_tens == S_supertens
assert S_supertens.superrep == 'super'
def test_composite_oper():
| 64 | 64 | 150 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_composite_oper | test_composite_oper | 780 | 795 | 780 | 780 | 7137ad9ab90e5bc5db9613e446d0ea47ec25bd9e | bigcode/the-stack | train |
b2a51b00e6f00445982c2595 | train | function | def test_QobjPower():
"Qobj power"
data = _random_not_singular(5)
q = Qobj(data)
q2 = q ** 2
assert (q2.full() - np.linalg.matrix_power(data, 2) < 1e-12).all()
q3 = q ** 3
assert (q3.full() - np.linalg.matrix_power(data, 3) < 1e-12).all()
| def test_QobjPower():
| "Qobj power"
data = _random_not_singular(5)
q = Qobj(data)
q2 = q ** 2
assert (q2.full() - np.linalg.matrix_power(data, 2) < 1e-12).all()
q3 = q ** 3
assert (q3.full() - np.linalg.matrix_power(data, 3) < 1e-12).all()
| Division():
"Qobj division"
data = _random_not_singular(5)
q = Qobj(data)
randN = 10 * np.random.random()
q = q / randN
assert np.allclose(q.full(), data / randN)
def test_QobjPower():
| 64 | 64 | 100 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjPower | test_QobjPower | 305 | 314 | 305 | 305 | 9a67616077eedf34c3787f277ac7c3cc354fec75 | bigcode/the-stack | train |
d8b5702d943fec5368e40252 | train | function | def test_unit():
"""
Test Qobj: unit
"""
psi = (10*np.random.randn()*basis(2, 0)
- 10j*np.random.randn()*basis(2, 1))
psi2 = psi.unit()
psi.unit(inplace=True)
assert psi == psi2
assert np.allclose(np.linalg.norm(psi.full()), 1.0)
| def test_unit():
| """
Test Qobj: unit
"""
psi = (10*np.random.randn()*basis(2, 0)
- 10j*np.random.randn()*basis(2, 1))
psi2 = psi.unit()
psi.unit(inplace=True)
assert psi == psi2
assert np.allclose(np.linalg.norm(psi.full()), 1.0)
| * B).tr()
assert np.allclose(A.overlap(B), ans)
assert np.allclose(Ad.overlap(B), ans)
assert np.allclose(Ad.overlap(Bd), ans)
assert np.allclose(A.overlap(Bd), np.conj(ans))
def test_unit():
| 64 | 64 | 84 | 4 | 60 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_unit | test_unit | 1,002 | 1,011 | 1,002 | 1,002 | 502281f3823609ddead0be866e8e5b9fd7265578 | bigcode/the-stack | train |
1c41951b22dbb06daff3935c | train | function | def test_QobjData():
"Qobj data"
N = 10
data1 = _random_not_singular(N)
q1 = Qobj(data1)
# check if data is a csr_matrix if originally array
assert sp.isspmatrix_csr(q1.data)
# check if dense ouput is exactly equal to original data
assert np.all(q1.full() == data1)
data2 = _random_n... | def test_QobjData():
| "Qobj data"
N = 10
data1 = _random_not_singular(N)
q1 = Qobj(data1)
# check if data is a csr_matrix if originally array
assert sp.isspmatrix_csr(q1.data)
# check if dense ouput is exactly equal to original data
assert np.all(q1.full() == data1)
data2 = _random_not_singular(N)
da... | , if any exists.
assert oper.isherm == hermicity
# Force a reset of the cached value for isherm.
oper._isherm = None
# Force a recalculation of isherm.
assert oper.isherm == hermicity
def test_QobjData():
| 64 | 64 | 190 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjData | test_QobjData | 39 | 58 | 39 | 39 | d2d70952b82154e1c85378a7098a606a760b8165 | bigcode/the-stack | train |
9fdfea4f7521f1e267d7d26d | train | function | def test_super_tensor_operket():
"""
Tensor: Checks that super_tensor respects states.
"""
rho1, rho2 = rand_dm(5), rand_dm(7)
operator_to_vector(rho1)
operator_to_vector(rho2)
| def test_super_tensor_operket():
| """
Tensor: Checks that super_tensor respects states.
"""
rho1, rho2 = rand_dm(5), rand_dm(7)
operator_to_vector(rho1)
operator_to_vector(rho2)
| ``isherm = True``.
"""
iH = 1j * rand_herm(5)
assert not iH.isherm
assert (iH * iH).isherm
assert tensor(iH, iH).isherm
def test_super_tensor_operket():
| 64 | 64 | 54 | 7 | 56 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_super_tensor_operket | test_super_tensor_operket | 755 | 761 | 755 | 755 | 2321da67958d716f8259dd302c0cfce43d02d5b4 | bigcode/the-stack | train |
3c3713514e893c3ed43d57a9 | train | function | def test_overlap():
"""
Test Qobj: Overlap (inner product)
"""
for _ in range(10):
N = 10
A = rand_ket(N, 0.75)
Ad = A.dag()
B = rand_ket(N, 0.75)
Bd = B.dag()
ans = (A.dag() * B).tr()
assert np.allclose(A.overlap(B), ans)
assert np.allcl... | def test_overlap():
| """
Test Qobj: Overlap (inner product)
"""
for _ in range(10):
N = 10
A = rand_ket(N, 0.75)
Ad = A.dag()
B = rand_ket(N, 0.75)
Bd = B.dag()
ans = (A.dag() * B).tr()
assert np.allclose(A.overlap(B), ans)
assert np.allclose(Ad.overlap(B), a... | 0.75), rand_ket(N, 0.75))
B = K.dag()
ans = K * K.dag()
out1 = K.proj()
out2 = B.proj()
assert out1 == ans
assert out2 == ans
def test_overlap():
| 64 | 64 | 141 | 4 | 59 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_overlap | test_overlap | 983 | 999 | 983 | 983 | a2c912445d71b7754ca411b03ea688b89178f53c | bigcode/the-stack | train |
dda23ac71a779b64910c1e7b | train | function | def test_KetType():
"Qobj ket type"
psi = basis(2, 1)
assert psi.isket
assert not psi.isbra
assert not psi.isoper
assert not psi.issuper
psi = tensor(basis(2, 1), basis(2, 0))
assert psi.isket
assert not psi.isbra
assert not psi.isoper
assert not psi.issuper
| def test_KetType():
| "Qobj ket type"
psi = basis(2, 1)
assert psi.isket
assert not psi.isbra
assert not psi.isoper
assert not psi.issuper
psi = tensor(basis(2, 1), basis(2, 0))
assert psi.isket
assert not psi.isbra
assert not psi.isoper
assert not psi.issuper
| , 1, 0])
S_tens = to_super(U)
S_tens_new = to_super(Unew)
assert S_tens_new == S_tens.permute([[2, 1, 0], [5, 4, 3]])
def test_KetType():
| 63 | 64 | 98 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_KetType | test_KetType | 629 | 644 | 629 | 629 | 86d2975a79af81121ae0972b3363f29c66be482c | bigcode/the-stack | train |
47b8df203b64c78a8b87da38 | train | function | def test_projection():
"""
Test Qobj: Projection operator
"""
for _ in range(10):
N = 5
K = tensor(rand_ket(N, 0.75), rand_ket(N, 0.75))
B = K.dag()
ans = K * K.dag()
out1 = K.proj()
out2 = B.proj()
assert out1 == ans
assert out2 == ans
| def test_projection():
| """
Test Qobj: Projection operator
"""
for _ in range(10):
N = 5
K = tensor(rand_ket(N, 0.75), rand_ket(N, 0.75))
B = K.dag()
ans = K * K.dag()
out1 = K.proj()
out2 = B.proj()
assert out1 == ans
assert out2 == ans
| et
out1 = H.matrix_element(Ld, R)
# ket-ket
out2 = H.matrix_element(Ld, R)
assert abs(ans-out1) < 1e-14
assert abs(ans-out2) < 1e-14
def test_projection():
| 64 | 64 | 100 | 4 | 59 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_projection | test_projection | 965 | 980 | 965 | 965 | b02f5bc100359906fb3413ff5d830b96b6d69d1b | bigcode/the-stack | train |
33af90b2eefe84c0f26a46d6 | train | function | def test_SuperType():
"Qobj superoperator type"
psi = basis(2, 1)
rho = psi * psi.dag()
sop = spre(rho)
assert not sop.isket
assert not sop.isbra
assert not sop.isoper
assert sop.issuper
sop = spost(rho)
assert not sop.isket
assert not sop.isbra
assert not sop.isoper... | def test_SuperType():
| "Qobj superoperator type"
psi = basis(2, 1)
rho = psi * psi.dag()
sop = spre(rho)
assert not sop.isket
assert not sop.isbra
assert not sop.isoper
assert sop.issuper
sop = spost(rho)
assert not sop.isket
assert not sop.isbra
assert not sop.isoper
assert sop.issupe... | _OperType():
"Qobj operator type"
psi = basis(2, 1)
rho = psi * psi.dag()
assert not rho.isket
assert not rho.isbra
assert rho.isoper
assert not rho.issuper
def test_SuperType():
| 64 | 64 | 104 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_SuperType | test_SuperType | 677 | 695 | 677 | 677 | 678e45ab07b7d620a6558637c87f8304ac03cfda | bigcode/the-stack | train |
426a995be1235f55a4ff1c47 | train | function | def test_QobjExpm():
"Qobj expm (dense)"
data = _random_not_singular(15)
A = Qobj(data)
B = A.expm()
assert (B.full() - la.expm(data) < 1e-10).all()
| def test_QobjExpm():
| "Qobj expm (dense)"
data = _random_not_singular(15)
A = Qobj(data)
B = A.expm()
assert (B.full() - la.expm(data) < 1e-10).all()
| = A.eigenstates()
assert np.all(b - np.ones(5) == 0)
kets = [basis(5, k) for k in range(5)]
for k in range(5):
assert c[k] == kets[k]
def test_QobjExpm():
| 64 | 64 | 62 | 7 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjExpm | test_QobjExpm | 484 | 489 | 484 | 484 | bb0b91b330d0ec221dc6cf88775cc4fe8e8a135b | bigcode/the-stack | train |
bda28a8a86e06a710ebf91df | train | class | class TestQobjHermicity:
def test_standard(self):
base = _random_not_singular(10)
assert not Qobj(base).isherm
assert Qobj(base + base.conj().T).isherm
q_a = destroy(5)
assert not q_a.isherm
q_ad = create(5)
assert not q_ad.isherm
def test_addition(self... | class TestQobjHermicity:
| def test_standard(self):
base = _random_not_singular(10)
assert not Qobj(base).isherm
assert Qobj(base + base.conj().T).isherm
q_a = destroy(5)
assert not q_a.isherm
q_ad = create(5)
assert not q_ad.isherm
def test_addition(self):
q_a, q_ad = de... | 9
super_data = np.random.random((N, N))
super_qobj = Qobj(super_data, dims=[[[3]], [[3]]])
assert super_qobj.type == 'super'
assert super_qobj.issuper
operket_qobj = operator_to_vector(oper_qobj)
assert operket_qobj.isoperket
assert operket_qobj.dag().isoperbra
class TestQobjHermicity:
| 97 | 97 | 326 | 7 | 89 | quantshah/qutip | qutip/tests/test_qobj.py | Python | TestQobjHermicity | TestQobjHermicity | 91 | 127 | 91 | 91 | a50e9e9c4713b898a6d8882880d4dfd09cfc48a5 | bigcode/the-stack | train |
7d172d04b1b3b8483404567a | train | class | class TestTruncNeg:
"""Test Qobj.trunc_neg for several different cases."""
def test_positive_operator(self):
trunc_neg_case(rand_dm(5), 'clip')
trunc_neg_case(rand_dm(5), 'sgs')
def test_diagonal_operator(self):
to_test = Qobj(np.diag([1.1, 0, -0.1]))
expected = Qobj(np.diag... | class TestTruncNeg:
| """Test Qobj.trunc_neg for several different cases."""
def test_positive_operator(self):
trunc_neg_case(rand_dm(5), 'clip')
trunc_neg_case(rand_dm(5), 'sgs')
def test_diagonal_operator(self):
to_test = Qobj(np.diag([1.1, 0, -0.1]))
expected = Qobj(np.diag([1.0, 0.0, 0.0]))
... | expected=None):
pos_qobj = qobj.trunc_neg(method=method)
assert all(energy > -1e-8 for energy in pos_qobj.eigenenergies())
assert np.allclose(pos_qobj.tr(), 1)
if expected is not None:
test_array = pos_qobj.full()
exp_array = expected.full()
assert np.allclose(test_array, exp_ar... | 92 | 92 | 307 | 6 | 86 | quantshah/qutip | qutip/tests/test_qobj.py | Python | TestTruncNeg | TestTruncNeg | 828 | 850 | 828 | 828 | 71ec7ceaefbda56ccbd6d237a53b0546fd984ceb | bigcode/the-stack | train |
9b4119b0eb7a517cb84905c3 | train | function | def assert_unitarity(oper, unitarity):
# Check the cached isunitary, if any exists.
assert oper.isunitary == unitarity
# Force a reset of the cached value for isunitary.
oper._isunitary = None
# Force a recalculation of isunitary.
assert oper.isunitary == unitarity
| def assert_unitarity(oper, unitarity):
# Check the cached isunitary, if any exists.
| assert oper.isunitary == unitarity
# Force a reset of the cached value for isunitary.
oper._isunitary = None
# Force a recalculation of isunitary.
assert oper.isunitary == unitarity
| Z = X * iY is correctly identified
# as Hermitian.
q = sigmax() * (1j * sigmay())
assert_hermicity(q, True)
def assert_unitarity(oper, unitarity):
# Check the cached isunitary, if any exists.
| 64 | 64 | 80 | 24 | 40 | quantshah/qutip | qutip/tests/test_qobj.py | Python | assert_unitarity | assert_unitarity | 130 | 136 | 130 | 131 | 215279937a3809bee3e1160a7174eed90b8cc391 | bigcode/the-stack | train |
d19dd31df7e65e312dd3bf6c | train | function | @pytest.mark.parametrize("dimension", [2, 4, 8])
@pytest.mark.parametrize("conversion", [to_super, to_choi, to_chi])
def test_dag_preserves_superrep(dimension, conversion):
"""
Checks that dag() preserves superrep.
"""
qobj = conversion(rand_super_bcsz(dimension))
assert qobj.superrep == qobj.dag().... | @pytest.mark.parametrize("dimension", [2, 4, 8])
@pytest.mark.parametrize("conversion", [to_super, to_choi, to_chi])
def test_dag_preserves_superrep(dimension, conversion):
| """
Checks that dag() preserves superrep.
"""
qobj = conversion(rand_super_bcsz(dimension))
assert qobj.superrep == qobj.dag().superrep
| .isbra
assert not sop.isoper
assert sop.issuper
@pytest.mark.parametrize("dimension", [2, 4, 8])
@pytest.mark.parametrize("conversion", [to_super, to_choi, to_chi])
def test_dag_preserves_superrep(dimension, conversion):
| 64 | 64 | 88 | 47 | 16 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_dag_preserves_superrep | test_dag_preserves_superrep | 698 | 705 | 698 | 700 | 9f3d38d75807b82aa9c1d5cd50801d90ec484575 | bigcode/the-stack | train |
4fd57b57178e746df1ac981b | train | function | def test_QobjMultiplication():
"Qobj multiplication"
data1 = np.array([[1, 2], [3, 4]])
data2 = np.array([[5, 6], [7, 8]])
data3 = np.dot(data1, data2)
q1 = Qobj(data1)
q2 = Qobj(data2)
q3 = Qobj(data3)
q4 = q1 * q2
assert q3 == q4
| def test_QobjMultiplication():
| "Qobj multiplication"
data1 = np.array([[1, 2], [3, 4]])
data2 = np.array([[5, 6], [7, 8]])
data3 = np.dot(data1, data2)
q1 = Qobj(data1)
q2 = Qobj(data2)
q3 = Qobj(data3)
q4 = q1 * q2
assert q3 == q4
| q2
data3 = data1 - data2
assert np.all(q3.full() == data3)
q4 = q2 - q1
data4 = data2 - data1
assert np.all(q4.full() == data4)
def test_QobjMultiplication():
| 64 | 64 | 106 | 7 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjMultiplication | test_QobjMultiplication | 280 | 293 | 280 | 280 | fdc6f3ac77e1502290b7fe1543bdffba8c9f5821 | bigcode/the-stack | train |
ff6a121eff91cd79c85b3cdb | train | function | @pytest.mark.parametrize("superrep", ["super", "choi", "chi"])
@pytest.mark.parametrize("operation,check_op,check_scalar",
[(add, True, True),
(sub, True, True),
(mul, True, True),
(truediv, False, True),
... | @pytest.mark.parametrize("superrep", ["super", "choi", "chi"])
@pytest.mark.parametrize("operation,check_op,check_scalar",
[(add, True, True),
(sub, True, True),
(mul, True, True),
(truediv, False, True),
... | """
Checks that binary ops preserve 'superrep'.
.. note::
The random superoperators are not chosen in a way that reflects the
structure of that superrep, but are simply random matrices.
"""
dims = [[[2], [2]], [[2], [2]]]
shape = (4, 4)
S1 = Qobj(np.random.random(shape), su... | @pytest.mark.parametrize("superrep", ["super", "choi", "chi"])
@pytest.mark.parametrize("operation,check_op,check_scalar",
[(add, True, True),
(sub, True, True),
(mul, True, True),
(truediv, False, True),
... | 91 | 86 | 289 | 91 | 0 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_arithmetic_preserves_superrep | test_arithmetic_preserves_superrep | 708 | 741 | 708 | 716 | de75fc4c776bd110a7958c92ef2fb85a41dbccd0 | bigcode/the-stack | train |
9457b05f02075fee1794e536 | train | function | def trunc_neg_case(qobj, method, expected=None):
pos_qobj = qobj.trunc_neg(method=method)
assert all(energy > -1e-8 for energy in pos_qobj.eigenenergies())
assert np.allclose(pos_qobj.tr(), 1)
if expected is not None:
test_array = pos_qobj.full()
exp_array = expected.full()
asser... | def trunc_neg_case(qobj, method, expected=None):
| pos_qobj = qobj.trunc_neg(method=method)
assert all(energy > -1e-8 for energy in pos_qobj.eigenenergies())
assert np.allclose(pos_qobj.tr(), 1)
if expected is not None:
test_array = pos_qobj.full()
exp_array = expected.full()
assert np.allclose(test_array, exp_array)
| 3, r4)
assert composite(k1, r4) == super_tensor(r1, r4)
assert composite(r3, k2) == super_tensor(r3, r2)
# TODO: move out to a more appropriate module.
def trunc_neg_case(qobj, method, expected=None):
| 64 | 64 | 95 | 12 | 52 | quantshah/qutip | qutip/tests/test_qobj.py | Python | trunc_neg_case | trunc_neg_case | 818 | 825 | 818 | 818 | 409a41e98aa590d275d92c290ffba36cae34a2f5 | bigcode/the-stack | train |
cd5d93a004eb2a55f1847d32 | train | function | def test_sinm():
"""
Test Qobj: sinm
"""
A = rand_herm(5)
B = A.sinm().full()
C = la.sinm(A.full())
assert np.all((B-C) < 1e-14)
| def test_sinm():
| """
Test Qobj: sinm
"""
A = rand_herm(5)
B = A.sinm().full()
C = la.sinm(A.full())
assert np.all((B-C) < 1e-14)
| test_cosm():
"""
Test Qobj: cosm
"""
A = rand_herm(5)
B = A.cosm().full()
C = la.cosm(A.full())
assert np.all((B-C) < 1e-14)
def test_sinm():
| 64 | 64 | 61 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_sinm | test_sinm | 866 | 876 | 866 | 866 | e6b00e06ff776045f9547f0f062acc9e5142f793 | bigcode/the-stack | train |
4ed50656b0936d7d6bdc5ac7 | train | function | def test_QobjDimsShape():
"Qobj shape"
N = 10
data = _random_not_singular(N)
q1 = Qobj(data)
assert q1.dims == [[10], [10]]
assert q1.shape == (10, 10)
data = np.random.random((N, 1)) + 1j*np.random.random((N, 1)) - (0.5+0.5j)
q1 = Qobj(data)
assert q1.dims == [[10], [1]]
asse... | def test_QobjDimsShape():
| "Qobj shape"
N = 10
data = _random_not_singular(N)
q1 = Qobj(data)
assert q1.dims == [[10], [10]]
assert q1.shape == (10, 10)
data = np.random.random((N, 1)) + 1j*np.random.random((N, 1)) - (0.5+0.5j)
q1 = Qobj(data)
assert q1.dims == [[10], [1]]
assert q1.shape == (10, 1)
... |
assert_unitarity(Sx+Sy, False)
assert_unitarity(4*Sx, False)
assert_unitarity(Sx*4, False)
assert_unitarity(4+Sx, False)
assert_unitarity(Sx+4, False)
def test_QobjDimsShape():
| 64 | 64 | 194 | 7 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjDimsShape | test_QobjDimsShape | 159 | 178 | 159 | 159 | 4b9d74d1d52ccd18b86f0339ee06c0a119c66ddc | bigcode/the-stack | train |
f07db41979ff0655c7c930fb | train | function | def test_CheckMulType():
"Qobj multiplication type"
# ket-bra and bra-ket multiplication
psi = basis(5)
dm = psi * psi.dag()
assert dm.isoper
assert dm.isherm
nrm = psi.dag() * psi
assert np.prod(nrm.shape) == 1
assert abs(nrm)[0, 0] == 1
# operator-operator multiplication
... | def test_CheckMulType():
| "Qobj multiplication type"
# ket-bra and bra-ket multiplication
psi = basis(5)
dm = psi * psi.dag()
assert dm.isoper
assert dm.isherm
nrm = psi.dag() * psi
assert np.prod(nrm.shape) == 1
assert abs(nrm)[0, 0] == 1
# operator-operator multiplication
H1 = rand_herm(3)
H2 ... |
def test_QobjEquals():
"Qobj equals"
data = _random_not_singular(5)
q1 = Qobj(data)
q2 = Qobj(data)
assert q1 == q2
q1 = Qobj(data)
q2 = Qobj(-data)
assert q1 != q2
def test_QobjGetItem():
"Qobj getitem"
data = _random_not_singular(5)
q = Qobj(data)
assert q[0, 0] =... | 145 | 145 | 484 | 6 | 139 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_CheckMulType | test_CheckMulType | 347 | 411 | 347 | 347 | fafdf0958585f647ade437f44e0c78967d3820e9 | bigcode/the-stack | train |
71c767e142440da52ce3017b | train | function | def test_QobjEquals():
"Qobj equals"
data = _random_not_singular(5)
q1 = Qobj(data)
q2 = Qobj(data)
assert q1 == q2
q1 = Qobj(data)
q2 = Qobj(-data)
assert q1 != q2
| def test_QobjEquals():
| "Qobj equals"
data = _random_not_singular(5)
q1 = Qobj(data)
q2 = Qobj(data)
assert q1 == q2
q1 = Qobj(data)
q2 = Qobj(-data)
assert q1 != q2
| "
data = _random_not_singular(5)
q = Qobj(data)
x = -q
assert np.all(x.full() + data == 0)
assert q.isherm == x.isherm
assert q.type == x.type
def test_QobjEquals():
| 64 | 64 | 72 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjEquals | test_QobjEquals | 327 | 336 | 327 | 327 | 15998fa7587a08a7c30e038c7d496ca12120b9ad | bigcode/the-stack | train |
4d56afde3e25d9bf8dfcdac1 | train | function | def test_QobjAddition():
"Qobj addition"
data1 = np.array([[1, 2], [3, 4]])
data2 = np.array([[5, 6], [7, 8]])
data3 = data1 + data2
q1 = Qobj(data1)
q2 = Qobj(data2)
q3 = Qobj(data3)
q4 = q1 + q2
q4_type = q4.type
q4_isherm = q4.isherm
q4._type = None
q4._isherm = No... | def test_QobjAddition():
| "Qobj addition"
data1 = np.array([[1, 2], [3, 4]])
data2 = np.array([[5, 6], [7, 8]])
data3 = data1 + data2
q1 = Qobj(data1)
q2 = Qobj(data2)
q3 = Qobj(data3)
q4 = q1 + q2
q4_type = q4.type
q4_isherm = q4.isherm
q4._type = None
q4._isherm = None # clear cached values... | .j],
[0.+0.j, 0.-1.j],
[0.+1.j, 0.+0.j],
[1.+0.j, 0.+0.j],
[0.+0.j, -1.+0.j]],
dims=[[4, 2], [2]])
assert (q1 * q2 * q1.dag()).dims == [[4, 2], [4, 2]]
def test_QobjAddition():
| 102 | 103 | 344 | 6 | 96 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjAddition | test_QobjAddition | 215 | 258 | 215 | 215 | 664386be1879a40b6d5b99a8a5a65de0fea49278 | bigcode/the-stack | train |
4a5a27c9796126b609aca493 | train | function | def test_QobjSubtraction():
"Qobj subtraction"
data1 = _random_not_singular(5)
q1 = Qobj(data1)
data2 = _random_not_singular(5)
q2 = Qobj(data2)
q3 = q1 - q2
data3 = data1 - data2
assert np.all(q3.full() == data3)
q4 = q2 - q1
data4 = data2 - data1
assert np.all(q4.full(... | def test_QobjSubtraction():
| "Qobj subtraction"
data1 = _random_not_singular(5)
q1 = Qobj(data1)
data2 = _random_not_singular(5)
q2 = Qobj(data2)
q3 = q1 - q2
data3 = data1 - data2
assert np.all(q3.full() == data3)
q4 = q2 - q1
data4 = data2 - data1
assert np.all(q4.full() == data4)
| 5))
q = Qobj(data)
x3 = q + data
x4 = data + q
data = 2.0 * data
assert np.all(x3.full() == data)
assert np.all(x4.full() == data)
def test_QobjSubtraction():
| 64 | 64 | 119 | 7 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjSubtraction | test_QobjSubtraction | 261 | 277 | 261 | 261 | b5a2a2e93f3c6cf0899d6a7e89ed9961714c23b0 | bigcode/the-stack | train |
f9e304ed40f115b8bbc23c04 | train | function | def test_call():
"""
Test Qobj: Call
"""
# Make test objects.
psi = rand_ket(3)
rho = rand_dm_ginibre(3)
U = rand_unitary(3)
S = rand_super_bcsz(3)
# Case 0: oper(ket).
assert U(psi) == U * psi
# Case 1: oper(oper). Should raise TypeError.
with pytest.raises(TypeError):... | def test_call():
| """
Test Qobj: Call
"""
# Make test objects.
psi = rand_ket(3)
rho = rand_dm_ginibre(3)
U = rand_unitary(3)
S = rand_super_bcsz(3)
# Case 0: oper(ket).
assert U(psi) == U * psi
# Case 1: oper(oper). Should raise TypeError.
with pytest.raises(TypeError):
U(rho)
... | (Y)
primals.append((X.dag() * S * Y)[0, 0])
duals.append((X.dag() * S_dual.dag() * Y)[0, 0])
np.testing.assert_array_almost_equal(primals, duals)
def test_call():
| 64 | 64 | 194 | 4 | 60 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_call | test_call | 914 | 939 | 914 | 914 | 139b317fdb865f782540a758d540f398eacbf9e2 | bigcode/the-stack | train |
d2d6aa1ae275fb0e048588ad | train | function | def test_matelem():
"""
Test Qobj: Compute matrix elements
"""
for _ in range(10):
N = 20
H = rand_herm(N, 0.2)
L = rand_ket(N, 0.3)
Ld = L.dag()
R = rand_ket(N, 0.3)
ans = (Ld * H * R).tr()
# bra-ket
out1 = H.matrix_element(Ld, R)
... | def test_matelem():
| """
Test Qobj: Compute matrix elements
"""
for _ in range(10):
N = 20
H = rand_herm(N, 0.2)
L = rand_ket(N, 0.3)
Ld = L.dag()
R = rand_ket(N, 0.3)
ans = (Ld * H * R).tr()
# bra-ket
out1 = H.matrix_element(Ld, R)
# ket-ket
... | 2dm(psi)))
# Case 3: super(oper).
assert S(rho) == vector_to_operator(S * operator_to_vector(rho))
# Case 4: super(super). Should raise TypeError.
with pytest.raises(TypeError):
S(S)
def test_matelem():
| 64 | 64 | 157 | 6 | 58 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_matelem | test_matelem | 942 | 962 | 942 | 942 | 920af1e552b082e4f22979b0d4cb6c7ddd4733ae | bigcode/the-stack | train |
7bf833b9ce3c9c4080428d1d | train | function | def test_QobjFull():
"Qobj full"
data = _random_not_singular(15)
A = Qobj(data)
b = A.full()
assert np.all(b - data == 0)
| def test_QobjFull():
| "Qobj full"
data = _random_not_singular(15)
A = Qobj(data)
b = A.full()
assert np.all(b - data == 0)
| ()
assert qeye(5) == A * B
assert qeye(5) == B * A
B = A.inv(sparse=True)
assert qeye(5) == A * B
assert qeye(5) == B * A
def test_QobjFull():
| 64 | 64 | 47 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_QobjFull | test_QobjFull | 527 | 532 | 527 | 527 | 68d2f3a81dc659f41ce1bc450cb756c9075d859f | bigcode/the-stack | train |
82120c4acf94d75faaf65445 | train | function | def test_BraType():
"Qobj bra type"
psi = basis(2, 1).dag()
assert not psi.isket
assert psi.isbra
assert not psi.isoper
assert not psi.issuper
psi = tensor(basis(2, 1).dag(), basis(2, 0).dag())
assert not psi.isket
assert psi.isbra
assert not psi.isoper
assert not psi.iss... | def test_BraType():
| "Qobj bra type"
psi = basis(2, 1).dag()
assert not psi.isket
assert psi.isbra
assert not psi.isoper
assert not psi.issuper
psi = tensor(basis(2, 1).dag(), basis(2, 0).dag())
assert not psi.isket
assert psi.isbra
assert not psi.isoper
assert not psi.issuper
| .isoper
assert not psi.issuper
psi = tensor(basis(2, 1), basis(2, 0))
assert psi.isket
assert not psi.isbra
assert not psi.isoper
assert not psi.issuper
def test_BraType():
| 64 | 64 | 104 | 6 | 57 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_BraType | test_BraType | 647 | 662 | 647 | 647 | 37164108902643e317b5ff5ab77cb7ef9fd8bfba | bigcode/the-stack | train |
223b76717a575124404adcf5 | train | function | def test_isherm_skew():
"""
mul and tensor of skew-Hermitian operators report ``isherm = True``.
"""
iH = 1j * rand_herm(5)
assert not iH.isherm
assert (iH * iH).isherm
assert tensor(iH, iH).isherm
| def test_isherm_skew():
| """
mul and tensor of skew-Hermitian operators report ``isherm = True``.
"""
iH = 1j * rand_herm(5)
assert not iH.isherm
assert (iH * iH).isherm
assert tensor(iH, iH).isherm
| if check_scalar:
check_list.append(operation(S1, x))
if check_op and check_scalar:
check_list.append(operation(x, S2))
for S in check_list:
assert S.type == "super"
assert S.superrep == superrep
def test_isherm_skew():
| 64 | 64 | 78 | 8 | 55 | quantshah/qutip | qutip/tests/test_qobj.py | Python | test_isherm_skew | test_isherm_skew | 744 | 752 | 744 | 744 | 80df8c131a6305d96a10ffc5d70e796ec3a0ff15 | bigcode/the-stack | train |
805aa77165b87cdbb56d6b76 | train | class | class DescribeScalingCommonConfigRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'Emr', '2016-04-08', 'DescribeScalingCommonConfig')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regiona... | class DescribeScalingCommonConfigRequest(RpcRequest):
| def __init__(self):
RpcRequest.__init__(self, 'Emr', '2016-04-08', 'DescribeScalingCommonConfig')
self.set_method('POST')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_dat... | OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkemr.endpoint import endpoint_data
class DescribeScalingCommonConfigRequest(RpcRequest):
| 64 | 64 | 195 | 10 | 53 | bricklayer-Liu/aliyun-openapi-python-sdk | aliyun-python-sdk-emr/aliyunsdkemr/request/v20160408/DescribeScalingCommonConfigRequest.py | Python | DescribeScalingCommonConfigRequest | DescribeScalingCommonConfigRequest | 23 | 44 | 23 | 24 | fc74af51caebaf783fe62cbedf162d59a30a3c3c | bigcode/the-stack | train |
0a7ccfb7ab0f7fb3231e61f3 | train | function | def module():
return Elisanne
| def module():
| return Elisanne
| import adv_test
from adv import *
from slot.a import *
def module():
| 16 | 64 | 8 | 3 | 13 | haukist/dl | adv/elisanne.py | Python | module | module | 5 | 6 | 5 | 5 | a499174a2e7cf38d79fd8f9c3b4bfd0ac481e4c6 | bigcode/the-stack | train |
ee8afa51c084eab343be716e | train | class | class Elisanne(Adv):
# comment = 'RR+Bellathorna'
a1 = ('bt',0.25)
conf = {}
conf['slots.a'] = RR() + HG()
| class Elisanne(Adv):
# comment = 'RR+Bellathorna'
| a1 = ('bt',0.25)
conf = {}
conf['slots.a'] = RR() + HG()
| import adv_test
from adv import *
from slot.a import *
def module():
return Elisanne
class Elisanne(Adv):
# comment = 'RR+Bellathorna'
| 38 | 64 | 44 | 17 | 20 | haukist/dl | adv/elisanne.py | Python | Elisanne | Elisanne | 8 | 13 | 8 | 9 | dcf611d409748627b0470311cc6bf8b4f69cce9d | bigcode/the-stack | train |
8b97585e1bb03623ccfdfad0 | train | class | @dataclass
class Visualizer:
analysis: Analysis
tetrads: List[Tetrad]
complete2d: bool
onz_dict: Dict[BasePair3D, ONZ] = field(init=False)
def __post_init__(self):
self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair in
[tetrad.pair_12, tetrad.pair_... | @dataclass
class Visualizer:
| analysis: Analysis
tetrads: List[Tetrad]
complete2d: bool
onz_dict: Dict[BasePair3D, ONZ] = field(init=False)
def __post_init__(self):
self.onz_dict = {pair: tetrad.onz for tetrad in self.tetrads for pair in
[tetrad.pair_12, tetrad.pair_23, tetrad.pair_34, tetrad.pa... | _letter_name
structure += dotbracket.get(nt, '.')
shifts[nt] = shift_value
chain = nt.chain
return sequence, structure, shifts
def __str__(self):
builder = f'Chain order: {" ".join(self.__chain_order())}\n'
for helix in self.helices:
builder +... | 210 | 211 | 705 | 7 | 203 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Visualizer | Visualizer | 948 | 1,004 | 948 | 949 | 4b72fd62d8b2fba2728b83a100112ebd7ae64fe1 | bigcode/the-stack | train |
41a86ef6692cc7f8e9a563a5 | train | class | @dataclass
class TetradPair:
tetrad1: Tetrad
tetrad2: Tetrad
stacked: Dict[Residue3D, Residue3D]
tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False)
direction: Direction = field(init=False)
rise: float = field(init=False)
twist: float = field(init=Fa... | @dataclass
class TetradPair:
| tetrad1: Tetrad
tetrad2: Tetrad
stacked: Dict[Residue3D, Residue3D]
tetrad2_nts_best_order: Tuple[Residue3D, Residue3D, Residue3D, Residue3D] = field(init=False)
direction: Direction = field(init=False)
rise: float = field(init=False)
twist: float = field(init=False)
def __post_init__(s... | return center_of_mass(self.outer_and_inner_atoms())
def outer_and_inner_atoms(self) -> List[Atom3D]:
return list(map(lambda residue: residue.outermost_atom, self.nucleotides)) + \
list(map(lambda residue: residue.innermost_atom, self.nucleotides))
def __ions_channel_str(self) -> str:
... | 193 | 194 | 647 | 9 | 184 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | TetradPair | TetradPair | 214 | 266 | 214 | 215 | 14a997d19d1d148728df6ca39359f649a40733da | bigcode/the-stack | train |
07cbdbae7a5d176ee106ea91 | train | function | def center_of_mass(atoms):
coords = [atom.coordinates() for atom in atoms]
xs = (coord[0] for coord in coords)
ys = (coord[1] for coord in coords)
zs = (coord[2] for coord in coords)
return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords)))
| def center_of_mass(atoms):
| coords = [atom.coordinates() for atom in atoms]
xs = (coord[0] for coord in coords)
ys = (coord[1] for coord in coords)
zs = (coord[2] for coord in coords)
return numpy.array((sum(xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords)))
| ]):
if Tetrad.is_valid(i, j, k, l, self.pair_dict):
tetrads.add(frozenset([i, j, k, l]))
if len(tetrads) > 1:
return True
return False
def center_of_mass(atoms):
| 64 | 64 | 86 | 7 | 56 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | center_of_mass | center_of_mass | 1,026 | 1,031 | 1,026 | 1,026 | d821440ef7668268acedb44ace6fdd259ba91679 | bigcode/the-stack | train |
c98e2c625f3817b6b28bf253 | train | class | @dataclass
class Analysis:
structure2d: Structure2D
structure3d: Structure3D
strict: bool
no_reorder: bool
stacking_mismatch: int
base_pairs: List[BasePair3D] = field(init=False)
base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False)
base_pair_dict: Dict[Tuple[Residue3D, R... | @dataclass
class Analysis:
| structure2d: Structure2D
structure3d: Structure3D
strict: bool
no_reorder: bool
stacking_mismatch: int
base_pairs: List[BasePair3D] = field(init=False)
base_pair_graph: Dict[Residue3D, List[Residue3D]] = field(init=False)
base_pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = fi... | self.__filter_tetrad_pairs(tetrads), self.structure3d))
return quadruplexes
def __filter_tetrad_pairs(self, tetrads: List[Tetrad]) -> List[TetradPair]:
chains = set()
for tetrad in tetrads:
chains.update(tetrad.chains())
def check_tetrad(t: Tetrad) -> bool:
... | 256 | 256 | 4,272 | 6 | 249 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Analysis | Analysis | 533 | 945 | 533 | 534 | d403f3b68c6271889c9de9195eac2a1db33bde56 | bigcode/the-stack | train |
2078a278c7811ec6e8e0e4de | train | class | @dataclass
class Helix:
tetrads: List[Tetrad]
tetrad_pairs: List[TetradPair]
structure3d: Structure3D
quadruplexes: List[Quadruplex] = field(init=False)
def __post_init__(self):
self.quadruplexes = self.__find_quadruplexes()
def __find_quadruplexes(self):
if len(self.tetrad_pai... | @dataclass
class Helix:
| tetrads: List[Tetrad]
tetrad_pairs: List[TetradPair]
structure3d: Structure3D
quadruplexes: List[Quadruplex] = field(init=False)
def __post_init__(self):
self.quadruplexes = self.__find_quadruplexes()
def __find_quadruplexes(self):
if len(self.tetrad_pairs) == 0:
re... | {len(self.tetrads)} tetrads\n'
builder += str(self.tetrad_pairs[0].tetrad1)
for tetrad_pair in self.tetrad_pairs:
builder += str(tetrad_pair)
builder += str(tetrad_pair.tetrad2)
if self.tracts:
builder += '\n Tracts:\n'
... | 149 | 149 | 498 | 7 | 141 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Helix | Helix | 480 | 530 | 480 | 481 | 579988c898426865f2236c4978fc95def23800c0 | bigcode/the-stack | train |
ba874d273d9daa1d24d55345 | train | function | def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool,
stacking_mismatch: int) -> Analysis:
return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch)
| def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool,
stacking_mismatch: int) -> Analysis:
| return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch)
| (xs) / len(coords), sum(ys) / len(coords), sum(zs) / len(coords)))
def eltetrado(structure2d: Structure2D, structure3d: Structure3D, strict: bool, no_reorder: bool,
stacking_mismatch: int) -> Analysis:
| 63 | 64 | 63 | 41 | 22 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | eltetrado | eltetrado | 1,034 | 1,036 | 1,034 | 1,035 | eb3916a3cd1d8831350eea6c92b73d3d0437a48c | bigcode/the-stack | train |
de54fe8321c7ad465b99003c | train | class | @dataclass
class Quadruplex:
tetrads: List[Tetrad]
tetrad_pairs: List[TetradPair]
structure3d: Structure3D
onzm: Optional[ONZM] = field(init=False)
gba_classes: List[GbaQuadruplexClassification] = field(init=False)
tracts: List[Tract] = field(init=False)
loops: List[Loop] = field(init=False)... | @dataclass
class Quadruplex:
| tetrads: List[Tetrad]
tetrad_pairs: List[TetradPair]
structure3d: Structure3D
onzm: Optional[ONZM] = field(init=False)
gba_classes: List[GbaQuadruplexClassification] = field(init=False)
tracts: List[Tract] = field(init=False)
loops: List[Loop] = field(init=False)
loop_class: Optional[Loo... | (v1)
v2 = nt2_1.find_atom("C1'").coordinates() - nt2_2.find_atom("C1'").coordinates()
v2 = v2 / numpy.linalg.norm(v2)
return math.degrees(numpy.arccos(numpy.clip(numpy.dot(v1, v2), -1.0, 1.0)))
def __str__(self):
return f' direction={self.direction.value} rise={round(self.rise,... | 255 | 256 | 2,103 | 8 | 247 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Quadruplex | Quadruplex | 287 | 477 | 287 | 288 | 3e6807676cae7c0b59df2f579e1af2bad091cf4e | bigcode/the-stack | train |
febf10f69fd08cba94f8ad8d | train | class | class AnalysisSimple:
def __init__(self, structure2d: Structure2D, structure3d: Structure3D):
self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d)
self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d)
self.pair_dict: Dict[Tuple[Residue3D, Resid... | class AnalysisSimple:
| def __init__(self, structure2d: Structure2D, structure3d: Structure3D):
self.pairs: List[BasePair3D] = structure3d.base_pairs(structure2d)
self.graph: Dict[Residue3D, List[Residue3D]] = structure3d.base_pair_graph(structure2d)
self.pair_dict: Dict[Tuple[Residue3D, Residue3D], BasePair3D] = s... | :
x, y = pair.nt1, pair.nt2
x, y = nucleotides.index(x) + 1 + shifts[x], nucleotides.index(y) + 1 + shifts[y]
helix.write(f'{x}\t{y}\t1\t8\n')
helix.flush()
return helix
class AnalysisSimple:
| 77 | 77 | 259 | 4 | 72 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | AnalysisSimple | AnalysisSimple | 1,007 | 1,023 | 1,007 | 1,007 | 54fd5a6cf54f1ed1357544e823342992cf8de170 | bigcode/the-stack | train |
8ca7beb49237141dafea1891 | train | class | @dataclass
class Loop:
nucleotides: List[Residue3D]
loop_type: Optional[LoopType]
def __str__(self):
return f' {self.loop_type.value if self.loop_type else "n/a"} ' \
f'{", ".join(map(lambda nt: nt.full_name, self.nucleotides))}'
| @dataclass
class Loop:
| nucleotides: List[Residue3D]
loop_type: Optional[LoopType]
def __str__(self):
return f' {self.loop_type.value if self.loop_type else "n/a"} ' \
f'{", ".join(map(lambda nt: nt.full_name, self.nucleotides))}'
| , 2)}\n'
@dataclass
class Tract:
nucleotides: List[Residue3D]
def __str__(self):
return f' {", ".join(map(lambda nt: nt.full_name, self.nucleotides))}'
@dataclass
class Loop:
| 63 | 64 | 76 | 6 | 57 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Loop | Loop | 277 | 284 | 277 | 278 | 3477d0cb23bec4f9feb4e7f1bf92174da3669f3d | bigcode/the-stack | train |
bbe5123b2b2650f631175ac4 | train | class | @dataclass
class Tract:
nucleotides: List[Residue3D]
def __str__(self):
return f' {", ".join(map(lambda nt: nt.full_name, self.nucleotides))}'
| @dataclass
class Tract:
| nucleotides: List[Residue3D]
def __str__(self):
return f' {", ".join(map(lambda nt: nt.full_name, self.nucleotides))}'
| (v1, v2), -1.0, 1.0)))
def __str__(self):
return f' direction={self.direction.value} rise={round(self.rise, 2)} twist={round(self.twist, 2)}\n'
@dataclass
class Tract:
| 64 | 64 | 50 | 7 | 57 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Tract | Tract | 269 | 274 | 269 | 270 | 1cfa863afd1da4a614193a6c61e9e7e2f6209690 | bigcode/the-stack | train |
b3f0ede796b684e7191b49c3 | train | class | @dataclass(order=True)
class Tetrad:
@staticmethod
def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D,
pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool:
lw1 = pair_dictionary[(nt1, nt2)].lw
lw2 = pair_dictionary[(nt2, nt3)].lw
... | @dataclass(order=True)
class Tetrad:
@staticmethod
| def is_valid(nt1: Residue3D, nt2: Residue3D, nt3: Residue3D, nt4: Residue3D,
pair_dictionary: Dict[Tuple[Residue3D, Residue3D], BasePair3D]) -> bool:
lw1 = pair_dictionary[(nt1, nt2)].lw
lw2 = pair_dictionary[(nt2, nt3)].lw
lw3 = pair_dictionary[(nt3, nt4)].lw
lw4 = ... | import itertools
import logging
import math
import os
import string
import subprocess
import tempfile
from collections import defaultdict, Counter
from dataclasses import dataclass, field
from typing import Dict, Iterable, List, Tuple, Optional, Set
import numpy
from eltetrado.model import Atom3D, Structure3D, Struct... | 149 | 256 | 2,833 | 14 | 135 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | Tetrad | Tetrad | 20 | 211 | 20 | 22 | 104ec2187ace2fc6b49563e8d45065f6b969d961 | bigcode/the-stack | train |
7dbd9cc3be85251819e71f3d | train | function | def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool:
structure = AnalysisSimple(structure2d, structure3d)
return structure.has_tetrads()
| def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool:
| structure = AnalysisSimple(structure2d, structure3d)
return structure.has_tetrads()
| , no_reorder: bool,
stacking_mismatch: int) -> Analysis:
return Analysis(structure2d, structure3d, strict, no_reorder, stacking_mismatch)
def has_tetrad(structure2d: Structure2D, structure3d: Structure3D) -> bool:
| 64 | 64 | 47 | 25 | 39 | tzok/el_tetrado | src/eltetrado/analysis.py | Python | has_tetrad | has_tetrad | 1,039 | 1,041 | 1,039 | 1,039 | b5c82911838e2480b28a3dfc8c64c7def603006f | bigcode/the-stack | train |
8da606b8e55c35c776572c76 | train | class | class OpenFlowSwitchMixin(object):
"""Mixin to provide common convenient routines for an openflow switch."""
@staticmethod
def _conv_args(kwargs):
for our_name, ovs_ofctl_name in _keywords.items():
if our_name in kwargs:
kwargs[ovs_ofctl_name] = kwargs.pop(our_name)
... | class OpenFlowSwitchMixin(object):
| """Mixin to provide common convenient routines for an openflow switch."""
@staticmethod
def _conv_args(kwargs):
for our_name, ovs_ofctl_name in _keywords.items():
if our_name in kwargs:
kwargs[ovs_ofctl_name] = kwargs.pop(our_name)
return kwargs
def dump_flo... | License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either expres... | 198 | 198 | 660 | 7 | 191 | osic-neutron/neutron-ipcapacity | neutron/plugins/ml2/drivers/openvswitch/agent/openflow/ovs_ofctl/ofswitch.py | Python | OpenFlowSwitchMixin | OpenFlowSwitchMixin | 35 | 110 | 35 | 35 | c6479d747184f67dbc88e6394e92225ef28edf2d | bigcode/the-stack | train |
10bdf7a28aa685b06d2bd84d | train | function | def neural_network_model(input, actions):
model = Sequential()
# Define CNN model
print(input)
model.add(Conv2D(64, kernel_size=(5, 5), input_shape=input))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))
model.add(Dropo... | def neural_network_model(input, actions):
| model = Sequential()
# Define CNN model
print(input)
model.add(Conv2D(64, kernel_size=(5, 5), input_shape=input))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))
model.add(Dropout(0.3))
model.add(Conv2D(128, kernel... | ].step_type == environment.StepType.LAST
episode_reward += r
return observation, r, done, {}
def reset(self):
global episode_reward
episode_reward = 0
super(Environment, self).reset()
return super(Environment, self).step([actions.FunctionCall(_SELECT_ARMY, [_SEL... | 90 | 90 | 303 | 8 | 81 | awesome-archive/pysc2_StarcraftII_codelab | pysc2_codelab_material/agent_CNN+LSTM.py | Python | neural_network_model | neural_network_model | 136 | 166 | 136 | 136 | 703d262509bca54c92ad3140e84994e1bfa0dcba | bigcode/the-stack | train |
ca7d31584a00a843399d88ac | train | function | def args_random(actfunc):
# E.g. of actfunc: pysc2.lib.actions.FUNCTIONS[81]
args_given = []
for arg in actfunc.args:
arg_values = []
for size in arg.sizes:
if size == 0:
arg_values.append(0)
else:
arg_values.append(np.random.randint(0,... | def args_random(actfunc):
# E.g. of actfunc: pysc2.lib.actions.FUNCTIONS[81]
| args_given = []
for arg in actfunc.args:
arg_values = []
for size in arg.sizes:
if size == 0:
arg_values.append(0)
else:
arg_values.append(np.random.randint(0, size))
args_given.append(arg_values)
return args_given
| (self, batch):
"""Processes an entire batch of states and returns it"""
batch = np.swapaxes(batch, 0, 1)
return batch[0]
def args_random(actfunc):
# E.g. of actfunc: pysc2.lib.actions.FUNCTIONS[81]
| 62 | 64 | 93 | 26 | 36 | awesome-archive/pysc2_StarcraftII_codelab | pysc2_codelab_material/agent_CNN+LSTM.py | Python | args_random | args_random | 85 | 96 | 85 | 86 | d47f482c0cf4d10a32088e17a08580fd9baef20f | bigcode/the-stack | train |
529d00fe39f4189142f84009 | train | class | class SC2Proc(Processor):
def process_observation(self, observation):
"""Process the observation as obtained from the environment for use an agent and returns it"""
obs = observation[0].observation["feature_screen"][_PLAYER_RELATIVE]
return np.expand_dims(obs, axis=2)
def process_state... | class SC2Proc(Processor):
| def process_observation(self, observation):
"""Process the observation as obtained from the environment for use an agent and returns it"""
obs = observation[0].observation["feature_screen"][_PLAYER_RELATIVE]
return np.expand_dims(obs, axis=2)
def process_state_batch(self, batch):
... | . Intended to help a programmer observe the effect of an action taken in real-time.")
flags.DEFINE_bool("visualize", True, "Visualize game")
flags.DEFINE_integer("steps_per_ep", 150, "steps per episode.")
FLAGS(sys.argv)
# Processor
class SC2Proc(Processor):
| 64 | 64 | 105 | 7 | 56 | awesome-archive/pysc2_StarcraftII_codelab | pysc2_codelab_material/agent_CNN+LSTM.py | Python | SC2Proc | SC2Proc | 72 | 81 | 72 | 72 | 0863b9305a11dccb9016a2ad60ea68965818d127 | bigcode/the-stack | train |
094998f20e87f2996119027b | train | function | def training_game():
env = Environment(map_name="DefeatRoaches", visualize=True, game_steps_per_episode=150,
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=32)
))
input_shape ... | def training_game():
| env = Environment(map_name="DefeatRoaches", visualize=True, game_steps_per_episode=150,
agent_interface_format=features.AgentInterfaceFormat(
feature_dimensions=features.Dimensions(screen=64, minimap=32)
))
input_shape = (_SIZE, _SIZE, 1)
... | (Dropout(0.3))
model.add(Conv2D(256, kernel_size=(3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2), strides=None, padding='valid', data_format=None))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Reshape((1, 256... | 158 | 159 | 530 | 4 | 153 | awesome-archive/pysc2_StarcraftII_codelab | pysc2_codelab_material/agent_CNN+LSTM.py | Python | training_game | training_game | 169 | 233 | 169 | 169 | 809dc99a4667dc10a1c64432dd37cdec60d8cbca | bigcode/the-stack | train |
0e669708a681a1d23b37930b | train | class | class Environment(sc2_env.SC2Env):
"""Starcraft II environmet. Implementation details in lib/features.py"""
def step(self, action):
"""Apply actions, step the world forward, and return observations"""
global episode_reward
global observation_cur
if observation_cur is None:
... | class Environment(sc2_env.SC2Env):
| """Starcraft II environmet. Implementation details in lib/features.py"""
def step(self, action):
"""Apply actions, step the world forward, and return observations"""
global episode_reward
global observation_cur
if observation_cur is None:
action = actions.FunctionCa... | arg_values = []
for size in arg.sizes:
if size == 0:
arg_values.append(0)
else:
arg_values.append(np.random.randint(0, size))
args_given.append(arg_values)
return args_given
# Define the environment
class Environment(sc2_env.SC2Env):
| 70 | 71 | 239 | 9 | 60 | awesome-archive/pysc2_StarcraftII_codelab | pysc2_codelab_material/agent_CNN+LSTM.py | Python | Environment | Environment | 104 | 131 | 104 | 104 | 8cdcd0c0794691f59c2add6b714a815af7c40326 | bigcode/the-stack | train |
d7c5e6070989bfe17fb15ad2 | train | class | class AutoLink(SphinxRole):
"""Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
def run(self) -> Tuple[List[Node], List[system_message]]:
pyobj_role = self.env.get_domain('py').role('obj')
objects, errors = ... | class AutoLink(SphinxRole):
| """Smart linking role.
Expands to ':obj:`text`' if `text` is an object that can be imported;
otherwise expands to '*text*'.
"""
def run(self) -> Tuple[List[Node], List[system_message]]:
pyobj_role = self.env.get_domain('py').role('obj')
objects, errors = pyobj_role('obj', self.rawte... | parent, modname
else:
return sys.modules[modname], None, modname
except (ValueError, ImportError, AttributeError, KeyError) as e:
raise ImportError(*e.args)
# -- :autolink: (smart default role) -------------------------------------------
class AutoLink(SphinxRole):
| 68 | 69 | 232 | 7 | 61 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | AutoLink | AutoLink | 626 | 650 | 626 | 626 | 3185db460f5a2025185bcd5963e215f324a0a379 | bigcode/the-stack | train |
ca518ac034768e4a481697fc | train | function | def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None:
pass
| def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None:
| pass
| (doctree)
def autosummary_toc_visit_html(self: nodes.NodeVisitor, node: autosummary_toc) -> None:
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None:
| 64 | 64 | 21 | 18 | 45 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | autosummary_noop | autosummary_noop | 136 | 137 | 136 | 136 | 7d393f97fb5ffbff53236403e7e3c66bd07aa80b | bigcode/the-stack | train |
4dd9b69460ba7d94a95435fa | train | function | def extract_summary(doc: List[str], document: Any) -> str:
"""Extract summary from docstring."""
# Skip a blank lines at the top
while doc and not doc[0].strip():
doc.pop(0)
# If there's a blank line, then we can assume the first sentence /
# paragraph has ended, so anything after shouldn'... | def extract_summary(doc: List[str], document: Any) -> str:
| """Extract summary from docstring."""
# Skip a blank lines at the top
while doc and not doc[0].strip():
doc.pop(0)
# If there's a blank line, then we can assume the first sentence /
# paragraph has ended, so anything after shouldn't be part of the
# summary
for i, piece in enumerat... | opts:
if not sig:
sig = "[%s]" % limited_join(", ", opts, max_chars=max_chars - 4)
elif len(sig) < max_chars - 4 - 2 - 3:
sig += "[, %s]" % limited_join(", ", opts,
max_chars=max_chars - len(sig) - 4 - 2)
return "(%s)" % sig
def ex... | 102 | 102 | 341 | 15 | 86 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | extract_summary | extract_summary | 469 | 514 | 469 | 469 | eb6e641df5d1f83089c9aa4bdf98a00580f0051a | bigcode/the-stack | train |
f60f0a46d07772ab98ecc116 | train | class | class Autosummary(SphinxDirective):
"""
Pretty table containing short signatures and summaries of functions etc.
autosummary can also optionally generate a hidden toctree:: node.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
has_content = True
... | class Autosummary(SphinxDirective):
| """
Pretty table containing short signatures and summaries of functions etc.
autosummary can also optionally generate a hidden toctree:: node.
"""
required_arguments = 0
optional_arguments = 0
final_argument_whitespace = False
has_content = True
option_spec = {
'caption': d... | *obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import DataDocumenter, ModuleDocumenter
if inspect.ismodule(obj):
# ModuleDocumenter.can_document_member always returns... | 256 | 256 | 1,629 | 7 | 249 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | Autosummary | Autosummary | 215 | 404 | 215 | 215 | 1d7a96af846b20756e3f50a45ab4a51c59250074 | bigcode/the-stack | train |
e2a35d29dd32518b3b9ea411 | train | function | def strip_arg_typehint(s: str) -> str:
"""Strip a type hint from argument definition."""
return s.split(':')[0].strip()
| def strip_arg_typehint(s: str) -> str:
| """Strip a type hint from argument definition."""
return s.split(':')[0].strip()
| (sig))
else:
col1 = ':%s:`%s <%s>`' % (qualifier, name, real_name)
col2 = summary
append_row(col1, col2)
return [table_spec, table]
def strip_arg_typehint(s: str) -> str:
| 64 | 64 | 32 | 12 | 52 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | strip_arg_typehint | strip_arg_typehint | 407 | 409 | 407 | 407 | 306c687280199499c8b5a29708130b7537066d9f | bigcode/the-stack | train |
7087529e83fbc399053d65d4 | train | function | def import_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, Any, Any, str]:
"""Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
tried = []
for prefix in prefixes:
try:
if prefix:
... | def import_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, Any, Any, str]:
| """Import a Python object that has the given *name*, under one of the
*prefixes*. The first name that succeeds is used.
"""
tried = []
for prefix in prefixes:
try:
if prefix:
prefixed_name = '.'.join([prefix, name])
else:
prefixed_name... | class:
if currmodule:
prefixes.insert(0, currmodule + "." + currclass)
else:
prefixes.insert(0, currclass)
return prefixes
def import_by_name(name: str, prefixes: List[str] = [None]) -> Tuple[str, Any, Any, str]:
| 64 | 64 | 161 | 27 | 36 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | import_by_name | import_by_name | 565 | 580 | 565 | 565 | bbd111d1bc15d5e8c3b84ac3a7ccd73a68fc3971 | bigcode/the-stack | train |
11cb04d3200d82d704bbced3 | train | class | class autosummary_table(nodes.comment):
pass
| class autosummary_table(nodes.comment):
| pass
| : autosummary_toc) -> None:
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None:
pass
# -- autosummary_table node ----------------------------------------------------
class autosummary_table(nodes.comment):
| 64 | 64 | 10 | 7 | 57 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | autosummary_table | autosummary_table | 142 | 143 | 142 | 142 | b79d8e0eda1a626d0b13a8ff8b76149d5a451979 | bigcode/the-stack | train |
cae0226f0ee7baf087ac4f0f | train | function | def limited_join(sep: str, items: List[str], max_chars: int = 30,
overflow_marker: str = "...") -> str:
"""Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_strin... | def limited_join(sep: str, items: List[str], max_chars: int = 30,
overflow_marker: str = "...") -> str:
| """Join a number of strings to one, limiting the length to *max_chars*.
If the string overflows this limit, replace the last fitting item by
*overflow_marker*.
Returns: joined_string
"""
full_str = sep.join(items)
if len(full_str) < max_chars:
return full_str
n_chars = 0
n... | ups
break
# strip literal notation mark ``::`` from tail of summary
summary = literal_re.sub('.', summary)
return summary
def limited_join(sep: str, items: List[str], max_chars: int = 30,
overflow_marker: str = "...") -> str:
| 64 | 64 | 180 | 32 | 31 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | limited_join | limited_join | 517 | 539 | 517 | 518 | 121a36a5e101558880f91c5be53cf62165579219 | bigcode/the-stack | train |
8bec443d7c16e0e7ecd4671b | train | function | def process_generate_options(app: Sphinx) -> None:
genfiles = app.config.autosummary_generate
if genfiles is True:
env = app.builder.env
genfiles = [env.doc2path(x, base=None) for x in env.found_docs
if os.path.isfile(env.doc2path(x))]
elif genfiles is False:
pas... | def process_generate_options(app: Sphinx) -> None:
| genfiles = app.config.autosummary_generate
if genfiles is True:
env = app.builder.env
genfiles = [env.doc2path(x, base=None) for x in env.found_docs
if os.path.isfile(env.doc2path(x))]
elif genfiles is False:
pass
else:
ext = list(app.config.source_su... | ...]:
parser_class = app.registry.get_source_parsers().get(suffix)
if parser_class is None:
return ('restructuredtext',)
return parser_class.supported
suffix = None # type: str
for suffix in app.config.source_suffix:
if 'restructuredtext' in get_supported_format(su... | 92 | 92 | 308 | 12 | 79 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | process_generate_options | process_generate_options | 668 | 702 | 668 | 668 | 955c15675937edc675811aac1aa8e528f91c55f0 | bigcode/the-stack | train |
db48103fb1aaeda6c0e92fda | train | class | class FakeDirective(DocumenterBridge):
def __init__(self) -> None:
settings = Struct(tab_width=8)
document = Struct(settings=settings)
state = Struct(document=document)
super().__init__({}, None, Options(), 0, state) # type: ignore
| class FakeDirective(DocumenterBridge):
| def __init__(self) -> None:
settings = Struct(tab_width=8)
document = Struct(settings=settings)
state = Struct(document=document)
super().__init__({}, None, Options(), 0, state) # type: ignore
| replace(" ", "\u00a0")
par[j] = nodes.Text(new_text)
except IndexError:
pass
# -- autodoc integration -------------------------------------------------------
# current application object (used in `get_documenter()`).
_app = None # type: Sphinx
class FakeDirective(DocumenterBridge):
| 64 | 64 | 61 | 7 | 56 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | FakeDirective | FakeDirective | 170 | 175 | 170 | 170 | 445757de6537f3795b259886954096545c2054ba | bigcode/the-stack | train |
b40f548ffe65a50b82c459ab | train | function | def get_import_prefixes_from_env(env: BuildEnvironment) -> List[str]:
"""
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None] # type: List[str]
currmodule = env.ref_context.get('py:module')
if currmodule:
prefixes.insert(0, currm... | def get_import_prefixes_from_env(env: BuildEnvironment) -> List[str]:
| """
Obtain current Python import prefixes (for `import_by_name`)
from ``document.env``
"""
prefixes = [None] # type: List[str]
currmodule = env.ref_context.get('py:module')
if currmodule:
prefixes.insert(0, currmodule)
currclass = env.ref_context.get('py:class')
if currcla... | if n_chars < max_chars - len(overflow_marker):
n_items += 1
else:
break
return sep.join(list(items[:n_items]) + [overflow_marker])
# -- Importing items -----------------------------------------------------------
def get_import_prefixes_from_env(env: BuildEnvironment) -> List[str]... | 63 | 64 | 133 | 16 | 47 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | get_import_prefixes_from_env | get_import_prefixes_from_env | 544 | 562 | 544 | 544 | f4a800dc5e469d27d380fd8c694d5fc6df1cceb7 | bigcode/the-stack | train |
458d11da2fd9850c02c4d305 | train | function | def get_documenter(app: Sphinx, obj: Any, parent: Any) -> "Type[Documenter]":
"""Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
... | def get_documenter(app: Sphinx, obj: Any, parent: Any) -> "Type[Documenter]":
| """Get an autodoc.Documenter class suitable for documenting the given
object.
*obj* is the Python object to be documented, and *parent* is an
another Python object (e.g. a module or a class) to which *obj*
belongs to.
"""
from sphinx.ext.autodoc import DataDocumenter, ModuleDocumenter
... | FakeDirective(DocumenterBridge):
def __init__(self) -> None:
settings = Struct(tab_width=8)
document = Struct(settings=settings)
state = Struct(document=document)
super().__init__({}, None, Options(), 0, state) # type: ignore
def get_documenter(app: Sphinx, obj: Any, parent: Any) -... | 85 | 85 | 284 | 25 | 59 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | get_documenter | get_documenter | 178 | 210 | 178 | 178 | ae7b94f3cf681a3ded48c2f407cdebbb3299f3c9 | bigcode/the-stack | train |
7044726ecc64aee337c36ca1 | train | function | def _import_by_name(name: str) -> Tuple[Any, Any, str]:
"""Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
mod = import_m... | def _import_by_name(name: str) -> Tuple[Any, Any, str]:
| """Import a Python object given its full name."""
try:
name_parts = name.split('.')
# try first interpret `name` as MODNAME.OBJ
modname = '.'.join(name_parts[:-1])
if modname:
try:
mod = import_module(modname)
return getattr(mod, name_... | join([prefix, name])
else:
prefixed_name = name
obj, parent, modname = _import_by_name(prefixed_name)
return prefixed_name, obj, parent, modname
except ImportError:
tried.append(prefixed_name)
raise ImportError('no module named %s' % ' or '.joi... | 93 | 93 | 310 | 17 | 76 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | _import_by_name | _import_by_name | 583 | 621 | 583 | 583 | 8002756679628edd26f32305d84878d3d3517159 | bigcode/the-stack | train |
66b3ebf87b90c2901f79dc24 | train | function | def autosummary_toc_visit_html(self: nodes.NodeVisitor, node: autosummary_toc) -> None:
"""Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
| def autosummary_toc_visit_html(self: nodes.NodeVisitor, node: autosummary_toc) -> None:
| """Hide autosummary toctree list in HTML output."""
raise nodes.SkipNode
| if not isinstance(subnode, nodes.section):
continue
if subnode not in crawled:
crawl_toc(subnode, depth + 1)
crawl_toc(doctree)
def autosummary_toc_visit_html(self: nodes.NodeVisitor, node: autosummary_toc) -> None:
| 64 | 64 | 42 | 23 | 41 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | autosummary_toc_visit_html | autosummary_toc_visit_html | 131 | 133 | 131 | 131 | 46d557e856acd76ecd8c00e30277ac68be59670a | bigcode/the-stack | train |
8eb8b9b6f963989fcaf716ad | train | function | def setup(app: Sphinx) -> Dict[str, Any]:
# I need autodoc
app.setup_extension('sphinx.ext.autodoc')
app.add_node(autosummary_toc,
html=(autosummary_toc_visit_html, autosummary_noop),
latex=(autosummary_noop, autosummary_noop),
text=(autosummary_noop, autos... | def setup(app: Sphinx) -> Dict[str, Any]:
# I need autodoc
| app.setup_extension('sphinx.ext.autodoc')
app.add_node(autosummary_toc,
html=(autosummary_toc_visit_html, autosummary_noop),
latex=(autosummary_noop, autosummary_noop),
text=(autosummary_noop, autosummary_noop),
man=(autosummary_noop, autosumma... | osummary.generate import generate_autosummary_docs
imported_members = app.config.autosummary_imported_members
with mock(app.config.autosummary_mock_imports):
generate_autosummary_docs(genfiles, suffix=suffix, base_path=app.srcdir,
app=app, imported_members=imported_mem... | 99 | 99 | 330 | 20 | 79 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | setup | setup | 705 | 730 | 705 | 706 | 5bd31b61b8f773ffab7466a261b935ccd32d0c9c | bigcode/the-stack | train |
499717d4aad5aa643c359c77 | train | function | def process_autosummary_toc(app: Sphinx, doctree: nodes.document) -> None:
"""Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
warnings.warn('process_autosummary_toc() is deprecated',
RemovedInSphinx50Warning, stacklevel=2)
env = ... | def process_autosummary_toc(app: Sphinx, doctree: nodes.document) -> None:
| """Insert items described in autosummary:: to the TOC tree, but do
not generate the toctree:: list.
"""
warnings.warn('process_autosummary_toc() is deprecated',
RemovedInSphinx50Warning, stacklevel=2)
env = app.builder.env
crawled = {}
def crawl_toc(node: Element, depth: i... | periods_re = re.compile(r'\.(?:\s+)')
literal_re = re.compile(r'::\s*$')
# -- autosummary_toc node ------------------------------------------------------
class autosummary_toc(nodes.comment):
pass
def process_autosummary_toc(app: Sphinx, doctree: nodes.document) -> None:
| 67 | 67 | 226 | 21 | 45 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | process_autosummary_toc | process_autosummary_toc | 105 | 128 | 105 | 105 | 61af900eaa2e39e7f204096e72ad85a212241093 | bigcode/the-stack | train |
ab119a8c28c0ee981692a8b2 | train | function | def mangle_signature(sig: str, max_chars: int = 30) -> str:
"""Reformat a function signature to a more compact form."""
# Strip return type annotation
s = re.sub(r"\)\s*->\s.*$", ")", sig)
# Remove parenthesis
s = re.sub(r"^\((.*)\)$", r"\1", s).strip()
# Strip literals (which can contain thin... | def mangle_signature(sig: str, max_chars: int = 30) -> str:
| """Reformat a function signature to a more compact form."""
# Strip return type annotation
s = re.sub(r"\)\s*->\s.*$", ")", sig)
# Remove parenthesis
s = re.sub(r"^\((.*)\)$", r"\1", s).strip()
# Strip literals (which can contain things that confuse the code below)
s = re.sub(r"\\\\", "", ... | except IndexError:
pass
row.append(nodes.entry('', node))
body.append(row)
for name, sig, summary, real_name in items:
qualifier = 'obj'
if 'nosignatures' not in self.options:
col1 = ':%s:`%s <%s>`\\ %s' % (qualifi... | 183 | 183 | 612 | 19 | 164 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | mangle_signature | mangle_signature | 412 | 466 | 412 | 412 | 2f4d0cd8d79a1394a9274d925948eb792b0a0e12 | bigcode/the-stack | train |
0e011fc65f7aede700c3d688 | train | function | def get_rst_suffix(app: Sphinx) -> str:
def get_supported_format(suffix: str) -> Tuple[str, ...]:
parser_class = app.registry.get_source_parsers().get(suffix)
if parser_class is None:
return ('restructuredtext',)
return parser_class.supported
suffix = None # type: str
f... | def get_rst_suffix(app: Sphinx) -> str:
| def get_supported_format(suffix: str) -> Tuple[str, ...]:
parser_class = app.registry.get_source_parsers().get(suffix)
if parser_class is None:
return ('restructuredtext',)
return parser_class.supported
suffix = None # type: str
for suffix in app.config.source_suffix:
... | arget'], prefixes)
except ImportError:
literal = cast(nodes.literal, pending_xref[0])
objects[0] = nodes.emphasis(self.rawtext, literal.astext(),
classes=literal['classes'])
return objects, errors
def get_rst_suffix(app: Sphinx) -> str:
| 64 | 64 | 106 | 12 | 51 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | get_rst_suffix | get_rst_suffix | 653 | 665 | 653 | 653 | 68a09c73478f81731e13d969ba25d31f3001223c | bigcode/the-stack | train |
6203a961067fef5aaa4fcf21 | train | function | def autosummary_table_visit_html(self: HTMLTranslator, node: autosummary_table) -> None:
"""Make the first column of the table non-breaking."""
try:
table = cast(nodes.table, node[0])
tgroup = cast(nodes.tgroup, table[0])
tbody = cast(nodes.tbody, tgroup[-1])
rows = cast(List[nod... | def autosummary_table_visit_html(self: HTMLTranslator, node: autosummary_table) -> None:
| """Make the first column of the table non-breaking."""
try:
table = cast(nodes.table, node[0])
tgroup = cast(nodes.tgroup, table[0])
tbody = cast(nodes.tbody, tgroup[-1])
rows = cast(List[nodes.row], tbody)
for row in rows:
col1_entry = cast(nodes.entry, row[0... | raise nodes.SkipNode
def autosummary_noop(self: nodes.NodeVisitor, node: Node) -> None:
pass
# -- autosummary_table node ----------------------------------------------------
class autosummary_table(nodes.comment):
pass
def autosummary_table_visit_html(self: HTMLTranslator, node: autosummary_table) -> None... | 64 | 64 | 172 | 20 | 43 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | autosummary_table_visit_html | autosummary_table_visit_html | 146 | 161 | 146 | 146 | 6f32ce2ebf4dcb4785f077a0516597f74094e591 | bigcode/the-stack | train |
f12fa80b8b00842cd66aafcd | train | class | class autosummary_toc(nodes.comment):
pass
| class autosummary_toc(nodes.comment):
| pass
| import Matcher
from sphinx.writers.html import HTMLTranslator
logger = logging.getLogger(__name__)
periods_re = re.compile(r'\.(?:\s+)')
literal_re = re.compile(r'::\s*$')
# -- autosummary_toc node ------------------------------------------------------
class autosummary_toc(nodes.comment):
| 64 | 64 | 11 | 8 | 56 | shimizukawa/sphinx | sphinx/ext/autosummary/__init__.py | Python | autosummary_toc | autosummary_toc | 101 | 102 | 101 | 101 | 1a4b431af10630b90d204fee4bfc1fed747f13a8 | bigcode/the-stack | train |
bcd3257b4b424a1179d5af61 | train | function | def on_message(client, userdata, msg):
logger.info("message received: {} - {}".format(msg.topic,msg.payload))
| def on_message(client, userdata, msg):
| logger.info("message received: {} - {}".format(msg.topic,msg.payload))
| (str(rc)))
if rc==0:
logger.info("connected OK. Returned code={}".format(rc))
else:
logger.error("Bad connection. Returned code={}".format(rc))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
| 64 | 64 | 25 | 9 | 55 | amit12cool/azure-iot-edge-identity-translation-lite | src/test/ptm-mqtt/sim_clients.py | Python | on_message | on_message | 83 | 84 | 83 | 83 | 1166e2d4df983045cad4de129505d9f701397b70 | bigcode/the-stack | train |
c7a589e5fe6b3996dd9c4b52 | train | function | def on_connect(client, userdata, flags, rc):
#logging.info("Connected with result code {}".formaty(str(rc)))
if rc==0:
logger.info("connected OK. Returned code={}".format(rc))
else:
logger.error("Bad connection. Returned code={}".format(rc))
| def on_connect(client, userdata, flags, rc):
#logging.info("Connected with result code {}".formaty(str(rc)))
| if rc==0:
logger.info("connected OK. Returned code={}".format(rc))
else:
logger.error("Bad connection. Returned code={}".format(rc))
| of the MQTT broker.\nDefault is 1883'
)
return parser.parse_args()
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
#logging.info("Connected with result code {}".formaty(str(rc)))
| 64 | 64 | 63 | 26 | 38 | amit12cool/azure-iot-edge-identity-translation-lite | src/test/ptm-mqtt/sim_clients.py | Python | on_connect | on_connect | 75 | 80 | 75 | 76 | 27534ce312ccd60a54b2ff3c715fe0155d9781fd | bigcode/the-stack | train |
51935508ee7385f01e768ea7 | train | function | def parse_cmdline_args():
example_text = 'Example:\n'
example_text += 'To create 10 clients with names "device0", "device1", ..., "device9" sending a random message every 0.5 seconds:\n'
example_text += '\n'
example_text += ' python sim_clients.py -c 10 -n device -i 0.5\n'
example_text += '\n'
... | def parse_cmdline_args():
| example_text = 'Example:\n'
example_text += 'To create 10 clients with names "device0", "device1", ..., "device9" sending a random message every 0.5 seconds:\n'
example_text += '\n'
example_text += ' python sim_clients.py -c 10 -n device -i 0.5\n'
example_text += '\n'
parser = argparse.Argu... | MIT license. See LICENSE file in the project root for full license information.
import paho.mqtt.client as mqtt
import time
import random
import json
import argparse
from argparse import RawTextHelpFormatter
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s.%(msecs)03d - %(levelname)s -... | 120 | 121 | 404 | 6 | 114 | amit12cool/azure-iot-edge-identity-translation-lite | src/test/ptm-mqtt/sim_clients.py | Python | parse_cmdline_args | parse_cmdline_args | 17 | 72 | 17 | 18 | 46cc959f7a45572af048a859a834d4cd6dd94d2a | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.