code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
mac = ''
for line in os.popen('/sbin/ifconfig'):
s = line.split()
if len(s) > 3:
if s[3] == 'HWaddr':
mac = s[4]
elif s[2] == ip:
break
return {'MAC': mac} | def mac_address(ip) | Get the MAC address | 3.158547 | 3.224761 | 0.979467 |
hwinfo = meminfo()
hwinfo.update(cpuinfo())
hwinfo.update(uname())
hwinfo.update(vgadata())
hwinfo.update(distro())
hwinfo.update(diskdata())
hwinfo.update(hostname())
hwinfo.update(serial_number())
ip = ip_address()
hwinfo.update(mac_address(ip))
hwinfo.update({'IP': ip... | def getallhwinfo() | Get all the hw info. | 3.846598 | 3.937409 | 0.976936 |
writer = csv.writer(sys.stdout)
writer.writerow(header_fields(h)) | def printheader(h=None) | Print the header for the CSV table. | 5.669526 | 6.04414 | 0.93802 |
hk = header_fields(h)
if (header):
printheader()
writer = csv.DictWriter(sys.stdout, hk, extrasaction='ignore')
writer.writerow(h) | def printtable(h, header) | Print as a table. | 5.651229 | 5.58929 | 1.011082 |
import xmlrpc.client
sp = xmlrpc.client.ServerProxy(server)
hw = getallhwinfo()
fields = header_fields()
for f in fields:
if not f in hw:
hw[f] = ''
try:
sp.puthwinfo(xmlrpc.client.dumps((hw,)))
except xmlrpc.client.Error as v:
print("ERROR occured: "... | def agent(server="http://localhost:8000") | Run in agent mode.
This gathers data, and sends it to a server given by the server argument. | 6.006456 | 6.075376 | 0.988656 |
N = len(states)
omega = [[2*Pi*(states[i].nu-states[j].nu)/Omega
for j in range(N)] for i in range(N)]
return omega | def calculate_omega_matrix(states, Omega=1) | Calculate the matrix of transition frequencies.
This function recieves a list of states and returns the corresponding
omega_ij matrix, rescaled to units of Omega. These are understood to be
absolute frequencies (as opposed angular frequencies). | 4.779093 | 5.459967 | 0.875297 |
r
N_magnetic = len(full_magnetic_states)
# We calculate the boundaries of the various detail levels
# First we will make a list of indices of that will tell where each fine
# level begins and ends.
fq = full_magnetic_states[0].quantum_numbers[:4]
index_list_fine = []; start_fine = 0
# A... | def calculate_boundaries(fine_states, full_magnetic_states) | r"""Calculate the boundary indices within a list of magnetic states.
This function calculates the boundary indices of each fine state
and each hyperfine state within a list of magnetic states. The output
is a list of tuples (a,b) with a the starting index of a state and
b it's ending index.
>>> g=... | 2.649719 | 2.54288 | 1.042015 |
Ne = len(omega)
excluded_indices = [i for i in range(Ne) if states[i] in excluded_states]
omega_new = []; gamma_new = []; r_new = [[], [], []]; Lij_new = []
for i in range(Ne):
row_om = []; row_ga = []; row_L = []
for j in range(Ne):
if j not in excluded_indices:
... | def exclude_states(omega, gamma, r, Lij, states, excluded_states) | Exclude states from matrices.
This function takes the matrices and excludes the states listed in
excluded_states. | 1.817412 | 1.89084 | 0.961166 |
'''This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states.'''
#We calculate the reduced matrix elements starting from the list of fine_states
#The factor composed of physical quantities.
factor=sqrt(3*c**3*me**2*e**2/(16*Pi*epsilon0*hbar**3))
#We read the databas... | def calculate_reduced_matrix_elements_0(fine_states) | This function calculates the reduced matrix elments <N,L,J||T^1(r)||N',L',J'> given a list of fine states. | 5.316882 | 4.313974 | 1.232479 |
r
if element == "Rb":
Tmelt = 39.30+273.15 # K.
if Temperature < Tmelt:
P = 10**(2.881+4.857-4215.0/Temperature) # Torr.
else:
P = 10**(2.881+4.312-4040.0/Temperature) # Torr.
elif element == "Cs":
Tmelt = 28.5 + 273.15 # K.
if Temperature ... | def vapour_pressure(Temperature, element) | r"""Return the vapour pressure of rubidium or cesium in Pascals.
This function receives as input the temperature in Kelvins and the
name of the element.
>>> print vapour_pressure(25.0 + 273.15,"Rb")
5.31769896107e-05
>>> print vapour_pressure(39.3 + 273.15,"Rb")
0.000244249795696
>>> print... | 3.053108 | 2.713028 | 1.125351 |
r
atom = Atom(element, isotope)
return sqrt(8*k_B*Temperature/atom.mass/pi) | def speed_average(Temperature,element,isotope) | r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
m is the mass of the atom (in kilograms).
... | 12.283867 | 10.438887 | 1.176741 |
r
atom = Atom(element, isotope)
return sqrt(3*Temperature*k_B/atom.mass) | def speed_rms(Temperature,element,isotope) | r"""This function calculates the average speed (in meters per second)
of an atom in a vapour assuming a Maxwell-Boltzmann velocity distribution.
This is simply
sqrt(8*k_B*T/m/pi)
where k_B is Boltzmann's constant, T is the temperature (in Kelvins) and
m is the mass of the atom (in kilograms).
... | 14.036377 | 22.210337 | 0.631975 |
r
atom=Atom(element,isotope)
sigma=pi*(2*atom.radius)**2
v=speed_average(Temperature,element,isotope)
n=vapour_number_density(Temperature,element)
return 2*pi*sigma*v*n | def collision_rate(Temperature, element, isotope) | r"""This function recieves the temperature of an atomic vapour (in Kelvin),
the element, and the isotope of the atoms, and returns the angular
frequency rate of collisions (in rad/s) in a vapour assuming a
Maxwell-Boltzmann velocity distribution, and taking the cross section
of the collision to be
... | 9.206697 | 7.138441 | 1.289735 |
r
def decays_from(fine_state, transitions):
states_below = []
for t in transitions:
if t.e2 == fine_state:
states_below += [t.e1]
return states_below
def iterate(states, transitions):
new_and_old_states = states... | def find_decays(self, fine_state) | r"""Find all possible decays from a given fine state.
This function finds all the states to which a given fine structure
state can decay (through electric dipole selection rules).
>>> atom=Atom("Cs",133)
>>> e=State("Cs",133,6,"P",3/Integer(2))
>>> atom.find_decays(e)
[... | 2.843701 | 2.890526 | 0.983801 |
r
if self.l == 0: l = 'S'
elif self.l == 1: l = 'P'
elif self.l == 2: l = 'D'
elif self.l == 3: l = 'F'
else: l = str(self.l)
if self.f is None:
s = '^{'+str(self.isotope)+'}\\mathrm{'+self.element+'}\\ '
s += str(self.n)+l+'_{'+str(self.j... | def _latex_(self) | r"""The LaTeX routine for states.
>>> State("Rb",85,5,0,1/Integer(2))._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}'
>>> State("Rb",85,5,0,1/Integer(2),2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{1/2}^{2}'
>>> State("Rb",85,5,0,1/Integer(2),2,2)._latex_()
'^{85}\\mathrm{Rb}\\ 5S_{... | 2.647527 | 2.254167 | 1.174503 |
r
if self.allowed:
return self.e1._latex_()+'\\ \\rightarrow \\ '+self.e2._latex_()
elif not self.allowed:
return self.e1._latex_()+'\\ \\nrightarrow \\ '+self.e2._latex_()
else:
return self.e1._latex_()+'\\ \\rightarrow^? \\ '+self.e2._latex_()
... | def _latex_(self) | r"""The representation routine for transitions.
>>> g1 = State("Cs", 133, 6, 0, 1/Integer(2),3)
>>> g2 = State("Cs", 133, 6, 0, 1/Integer(2),4)
>>> Transition(g2,g1)._latex_()
'^{133}\\mathrm{Cs}\\ 6S_{1/2}^{4}\\ \\nrightarrow \\ ^{133}\\mathrm{Cs}\\ 6S_{1/2}^{3}' | 3.593543 | 3.135765 | 1.145986 |
'''A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This way the function can be used in clas... | def uFuncConverter(variableIndex) | A decorator to convert python functions to numpy universal functions
A standard function of 1 variable is extended by a decorator to handle
all values in a list, tuple or numpy array
:param variableIndex: Specifies index for args to use as variable.
This way the function can be used in classes as ... | 4.391356 | 1.8883 | 2.325561 |
'''
:param x: x value to place in segment defined by the xData (instantiation)
:return: The lower index in the segment
'''
iLeft = 0
iRight = len(self.xData) - 1
while True:
if iRight - iLeft <= 1:
return iLeft
i = (iRight +... | def _findSegment(self, x) | :param x: x value to place in segment defined by the xData (instantiation)
:return: The lower index in the segment | 3.902285 | 1.905387 | 2.048028 |
r
Ne = len(states)
H0 = np.zeros((Ne, Ne), complex)
for i in range(Ne):
H0[i, i] = hbar*states[i].omega
return H0 | def unperturbed_hamiltonian(states) | r"""Return the unperturbed atomic hamiltonian for given states.
We calcualte the atomic hamiltonian in the basis of the ground states of \
rubidium 87 (in GHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2))
>>> magnetic_states = make_list_of_states([g], "magnetic")
>>> print(np.diag(unperturbed_hamil... | 4.807918 | 5.520365 | 0.870942 |
r
reduced_matrix_elements = [[reduced_matrix_element(ei, ej,
convention=convention)
for ej in fine_states]
for ei in fine_states]
return reduced_matrix_elements | def calculate_reduced_matrix_elements(fine_states, convention=1) | r"""Calculate the reduced matrix elements for a list of fine states.
This function calculates the reduced matrix elments
.. math::
\langle N,L,J||T^1(r)||N',L',J'\rangle
given a list of fine states.
We calculate the reduced matrix elements found in [SteckRb87]_ for the \
D1 and D2 lines ... | 4.861179 | 10.275907 | 0.473066 |
r
if q is None:
return [matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, qi,
numeric=numeric, convention=convention)
for qi in [-1, 0, 1]]
if numeric:
from numpy import sqrt as numsqrt
sqr... | def matrix_element(ji, fi, mi, jj, fj, mj,
II, reduced_matrix_element, q=None,
numeric=True, convention=1) | r"""Calculate a matrix element of the electric dipole (in the helicity
basis).
We calculate the matrix element for the cyclical transition of the D2 line
in Rb 87.
>>> from sympy import symbols
>>> red = symbols("r", positive=True)
>>> half = 1/Integer(2)
>>> II = 3*half
>>> matrix_ele... | 3.67037 | 3.704278 | 0.990846 |
r
# We check that all states belong to the same element and the same isotope.
iso = states[0].isotope
element = states[0].element
for state in states[1:]:
if state.element != element:
raise ValueError('All states must belong to the same element.')
if state.isotope != iso:... | def calculate_matrices(states, Omega=1) | r"""Calculate the matrices omega_ij, gamma_ij, r_pij.
This function calculates the matrices omega_ij, gamma_ij and r_pij given a
list of atomic states. The states can be arbitrarily in their fine,
hyperfine or magnetic detail. | 4.679247 | 3.962852 | 1.180778 |
r
atom = Atom(element, isotope)
if atom.isotope is None:
rho = 0.0
for iso in atom.isotopes:
atom = Atom(element, iso)
rho += vapour_number_density(Temperature, element) *\
atom.mass*atom.abundance
return rho
else:
return vapour_num... | def vapour_density(Temperature, element, isotope=None) | r"""This function returns the density in a rubidium or cesium
vapour in kg/m^-3. It receives as input the temperature in Kelvins, the
name of the element, and optionally the isotope. If no isotope is
specified, the density of a vapour with the natural abundances will
be returned.
This is calculated... | 3.850696 | 4.703549 | 0.818679 |
r
atom = Atom(transition.e1.element, transition.e1.isotope)
m = atom.mass
omega = transition.omega
return omega*np.log(8*np.sqrt(2))*np.sqrt(k_B*Temperature/m/c**2) | def doppler_width(transition, Temperature) | r"""Return the Doppler width of a transition at a given temperature
(in angular frequency).
The usual Doppler FWHM of the rubidium D2 line (in MHz).
>>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2)
>>> e = State("Rb", 87, 5, 1, 3/Integer(2))
>>> t = Transition(e, g)
>>> omega = doppler_width(t, ... | 9.274613 | 10.970703 | 0.845398 |
r
Ne = len(omega_level)
E = np.array([hbar*omega_level[i] for i in range(Ne)])
p = np.exp(-E/k_B/T)
p = p/sum(p)
if not return_diagonal:
return np.diag(p)
return p | def thermal_state(omega_level, T, return_diagonal=False) | r"""Return a thermal state for a given set of levels.
INPUT:
- ``omega_level`` - The angular frequencies of each state.
- ``T`` - The temperature of the ensemble (in Kelvin).
- ``return_diagonal`` - Whether to return only the populations.
>>> ground = State("Rb", 85, 5, 0, 1/Integer(2))
>>... | 3.85755 | 4.664259 | 0.827045 |
r
states = self.states()
transitions = states
transitions = []
for i in range(len(states)):
si = states[i]
for j in range(i):
sj = states[j]
t = Transition(sj, si)
if t.allowed:
transition... | def transitions(self, omega_min=None, omega_max=None) | r"""Find all allowed transitions.
This function finds all allowed transitions (by electric-dipole
selection rules) in the atom.
>>> atom=Atom("Rb",85)
>>> transitions=atom.transitions()
>>> print(len(transitions))
270
Arguments omega_min and omega_max can be us... | 2.595496 | 2.775767 | 0.935055 |
r
# We get the mass of the atom.
code = ""
code = "def maxwell_boltzmann(v, T):\n"
code += ' r\n'
code += " if hasattr(v, 'shape'):\n"
code += " d = 1\n"
code += " m = %s\n" % mass
code += " f = np.sqrt(m/2/np.pi/k_B_num/T)**d\n"
code += " f = f ... | def fast_maxwell_boltzmann(mass, file_name=None,
return_code=False) | r"""Return a function that returns values of a Maxwell-Boltzmann
distribution.
>>> from fast import Atom
>>> mass = Atom("Rb", 87).mass
>>> f = fast_maxwell_boltzmann(mass)
>>> print f(0, 273.15+20)
0.00238221482739
>>> import numpy as np
>>> v = np.linspace(-600, 600, 101)
>>> dis... | 2.059225 | 2.121984 | 0.970424 |
r
def marginal(f, rho):
remaining = len(f.shape)
if remaining == 0:
return rho
rho = sum([f[i]*rho[i] for i in range(rho.shape[0])])
f = np.sum(f, 0)
return marginal(f, rho)
return marginal(self.distribution, rho) | def average(self, rho) | r"""Return the average density matrix of an inhomogeneous ensemble. | 5.343783 | 4.998609 | 1.069054 |
r
self.__init__(self.shape, self.stds, T,
self.mass, self.detuning_knob, self.k,
self.omega_level, self.xi, self.theta, self.unfolding,
self.axes,
self.matrix_form) | def reset(self, T) | r"""Recalculate the doppler broadening for a given temperature. | 17.434357 | 17.318279 | 1.006703 |
r
jmin = abs(j1-j2)
jmax = j1+j2
return [jmin + i for i in range(jmax-jmin+1)] | def perm_j(j1, j2) | r"""Calculate the allowed total angular momenta.
>>> from sympy import Integer
>>> L = 1
>>> S = 1/Integer(2)
>>> perm_j(L, S)
[1/2, 3/2] | 4.640257 | 5.974529 | 0.776673 |
ur
# We calculate the quantum numbers for the uncoupled basis.
M1 = [-j1 + i for i in range(2*j1+1)]
M2 = [-j2 + i for i in range(2*j2+1)]
j1j2nums = [(j1, m1, j2, m2) for m1 in M1 for m2 in M2]
# We calculate the quantum numbers for the coupled basis.
Jper = perm_j(j1, j2)
jmjnums = [(... | def coupling_matrix_2j(j1, j2) | ur"""For angular momenta $j_1, j_2$ the unitary transformation from the \
uncoupled basis into the $j = j_1 \oplus j_2$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> pprint(coupling_matrix_2j(L, S))
⎡1 0⎤
⎢ ⎥
⎣0 1⎦
>>> L = 1
>>> S ... | 3.501534 | 3.519073 | 0.995016 |
ur
idj3 = eye(2*j3+1)
Jper = perm_j(j1, j2)
U_Jj3_list = [coupling_matrix_2j(J, j3) for J in Jper]
size = sum([U_Jj3_list[i].shape[0] for i in range(len(Jper))])
U_Jj3 = zeros(size, size)
ind0 = 0
for i, U_Jj3i in enumerate(U_Jj3_list):
sizeJ = U_Jj3i.shape[0]
indf = ind... | def coupling_matrix_3j(j1, j2, j3) | ur"""For angular momenta $j_1, j_2, j_3$ the unitary transformation from the \
uncoupled basis into the $j = (j_1 \oplus j_2)\oplus j_3$ coupled basis.
>>> from sympy import Integer, pprint
>>> L = 0
>>> S = 1/Integer(2)
>>> II = 3/Integer(2)
>>> pprint(coupling_matrix_3j(L, S, II))
⎡ ... | 3.646901 | 3.727914 | 0.978268 |
ur
keti = {(Ji, Mi): Matrix([KroneckerDelta(i, j)
for j in range(2*Ji+1)])
for i, Mi in enumerate(perm_m(Ji))}
braj = {(Jj, Mj): Matrix([KroneckerDelta(i, j)
for j in range(2*Jj+1)]).adjoint()
for i, Mj in enumerate(perm_m(Jj))}
if K not in perm_j(Ji, Jj... | def spherical_tensor(Ji, Jj, K, Q) | ur"""Return a matrix representation of the spherical tensor with quantum
numbers $J_i, J_j, K, Q$.
>>> from sympy import pprint
>>> pprint(spherical_tensor(1, 1, 1, 0))
⎡-√2 ⎤
⎢──── 0 0 ⎥
⎢ 2 ⎥
⎢ ⎥
⎢ 0 0 0 ⎥
⎢ ⎥
⎢ √2⎥
⎢ 0 0... | 3.608997 | 3.896332 | 0.926255 |
u
d = wigner_d_small(J, beta)
M = [J-i for i in range(2*J+1)]
D = [[exp(I*Mi*alpha)*d[i, j]*exp(I*Mj*gamma)
for j, Mj in enumerate(M)] for i, Mi in enumerate(M)]
return Matrix(D) | def wigner_d(J, alpha, beta, gamma) | u"""Return the Wigner D matrix for angular momentum J.
We use the general formula from [Edmonds74]_, equation 4.1.12.
The simplest possible example:
>>> from sympy import Integer, symbols, pprint
>>> half = 1/Integer(2)
>>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True)
>>> ppr... | 5.432961 | 5.548121 | 0.979243 |
r
size = sum([2*J+1 for J in J_values])
D = zeros(size, size)
ind0 = 0
for J in J_values:
DJ = wigner_d(J, alpha, beta, gamma)
sizeJ = 2*J+1
indf = ind0 + sizeJ
D[ind0: indf, ind0: indf] = DJ
ind0 += sizeJ
return D | def density_matrix_rotation(J_values, alpha, beta, gamma) | r"""Return a block-wise diagonal Wigner D matrix for that rotates
a density matrix of an ensemble of particles in definite total
angular momentum states given by J_values.
>>> from sympy import Integer, pi
>>> half = 1/Integer(2)
>>> J_values = [2*half, 0]
>>> density_matrix_rotation(J_values, ... | 3.745146 | 4.50806 | 0.830767 |
# Iterate over the required rows and cells. The for loops (x, y)
# give the coordinates of the top left-hand corner of each square:
#
# (x, y) +-----+ (x + 1, y)
# | |
# | |
# | |
# (x, y + 1) +-----+ (x + 1, y + 1)
#
fo... | def generate_unit_squares(image_width, image_height) | Generate coordinates for a tiling of unit squares. | 2.90327 | 2.896357 | 1.002387 |
# Our triangles lie with one side parallel to the x-axis. Let s be
# the length of one side, and h the height of the triangle.
#
# The for loops (x, y) gives the coordinates of the top left-hand corner
# of a pair of triangles:
#
# (x, y) +-----+ (x + 1, y)
# ... | def generate_unit_triangles(image_width, image_height) | Generate coordinates for a tiling of unit triangles. | 3.926307 | 3.860715 | 1.016989 |
global __DEFAULTS
__DEFAULTS.CACHE_DIR = defaults.CACHE_DIR
__DEFAULTS.SET_SEED = defaults.SET_SEED
__DEFAULTS.SEED = defaults.SEED
logging.info('Settings reverted to their default values.') | def restore_default_settings() | Restore settings to default values. | 5.505307 | 5.238005 | 1.051031 |
if not os.path.exists(config_file):
logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file))
return
## get user-level config in *.ini format
config = configparser.ConfigParser()
config.read(config_file)
if not config.has_section('main'):
... | def load_config(config_file='~/.stancache.ini') | Load config file into default settings | 3.042257 | 2.874697 | 1.058288 |
eft = EmailFromTemplate(name=name)
eft.subject = subject
eft.context = ctx_dict
eft.get_object()
eft.render_message()
eft.send_email(send_to=send_to, **kwargs) | def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs) | Shortcut function for EmailFromTemplate class
@return: None | 4.218416 | 3.821729 | 1.103798 |
level = (
level
if not is_str(level)
else int(LOGGING_LEVELS.get(level.upper(), level))
)
for handler in root.handlers:
handler.setLevel(level)
root.setLevel(level) | def set_level(cls, level) | :raises: ValueError | 4.038499 | 4.12281 | 0.97955 |
configfile = getenv(cls.CONFIGFILE_ENV_KEY, configfile)
if isfile(configfile):
with open(configfile, "r") as cf:
# noinspection PyBroadException
try:
dictConfig(load(cf))
except ValueError:
debug... | def load_config(cls, configfile="logging.yaml") | :raises: ValueError | 5.869601 | 5.611459 | 1.046003 |
'''
Parse a string to remove and replace all wiki markup tags
'''
self.string = string
self.string = self.wiki_re.sub('', self.string)
# search for lists
self.listmatch = re.search('^(\*+)', self.string)
if self.listmatch:
self.string = self.__... | def __parse(self, string='') | Parse a string to remove and replace all wiki markup tags | 5.073919 | 3.77838 | 1.342882 |
'''
Parse a string object to de-wikified text
'''
self.strings = string.splitlines(1)
self.strings = [self.__parse(line) for line in self.strings]
return ''.join(self.strings) | def parse_string(self, string='') | Parse a string object to de-wikified text | 7.624793 | 3.520044 | 2.166107 |
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the oscillation periods, and the shortest and half lives.
The results are lists ordered as:
``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_li... | def characteristic_times(path,name,Omega=1) | r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the oscillation periods, and the shortest and half lives.
The results are lists ordered as:
``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_liv... | 4.474829 | 2.452578 | 1.824541 |
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the shortest and longest oscillation period, and the shortest and
longest half life. The results are lists ordered as:
``[detunings, shortest_oscillations, longest_oscillations, ... | def analyze_eigenvalues(path,name,Ne) | r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues``
is set to ``True``. It will return the shortest and longest oscillation period, and the shortest and
longest half life. The results are lists ordered as:
``[detunings, shortest_oscillations, longest_oscillations, s... | 4.008723 | 1.455048 | 2.755045 |
def electric_field_amplitude_intensity(s0,Omega=1.0e6):
'''This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light.'''
e0=hbar*Omega/(e*a0) #T... | This function returns the value of E0 (the amplitude of the electric field)
at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the
saturation intensity of the D2 line of Rubidium for linearly polarized light. | null | null | null | |
'''
Retrieve unique hash in a cross-platform manner:
this is how calculation identity is determined
'''
if self._checksum:
return self._checksum
if not self._filename:
raise RuntimeError('Source calc file is required in order to properly save the ... | def get_checksum(self) | Retrieve unique hash in a cross-platform manner:
this is how calculation identity is determined | 3.39388 | 2.925524 | 1.160093 |
'''
NB only used for perovskite_tilting app
'''
try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance)
except Exception as ex:
self.error = 'Symmetry finder error: %s' % ex
e... | def refine_cell(self, tilde_obj) | NB only used for perovskite_tilting app | 5.713149 | 4.422959 | 1.291703 |
if self.data is None:
raise ValueError('No input data provided, unable to parse')
for line in self.data:
parts = line.strip().split()
try:
path = parts[0]
code = parts[1]
path, line, char = path.split(':')[:3]... | def parse(self) | Reads all lines from the current data source and yields each FileResult objects | 4.276977 | 4.103796 | 1.0422 |
if return_format:
return requests.get(''.join([__BASE_URL, function, return_format])).text
return requests.get(''.join([__BASE_URL, function, JSON])).json() | def _get(function, return_format=None) | Get and return data from the API.
:returns: A str, list, or dict, depending on the input values and API data. | 4.341904 | 5.981298 | 0.725913 |
uri = 'backscatter'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if rows:
uri = '/'.join([uri, str(rows)])
return _get(uri, return_format) | def backscatter(date=None, rows=None, return_format=None) | Returns possible backscatter data.
This report only includes "syn ack" data and is summarized by source port.
:param date: optional string (in Y-M-D format) or datetime.date() object
:param rows: optional number of rows returned (default 1000)
:returns: list -- backscatter data. | 2.38897 | 2.644321 | 0.903434 |
response = _get('ip/{address}'.format(address=ip_address), return_format)
if 'bad IP address' in str(response):
raise Error('Bad IP address, {address}'.format(address=ip_address))
else:
return response | def ip(ip_address, return_format=None) | Returns a summary of the information our database holds for a
particular IP address (similar to /ipinfo.html).
In the returned data:
Count: (also reports or records) total number of packets blocked from
this IP.
Attacks: (also targets) number of unique destination IP addresses for
these packet... | 3.976189 | 5.095268 | 0.780369 |
response = _get('port/{number}'.format(number=port_number), return_format)
if 'bad port number' in str(response):
raise Error('Bad port number, {number}'.format(number=port_number))
else:
return response | def port(port_number, return_format=None) | Summary information about a particular port.
In the returned data:
Records: Total number of records for a given date.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a string or integer port number | 3.833224 | 4.616607 | 0.830312 |
uri = 'portdate/{number}'.format(number=port_number)
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
response = _get(uri, return_format)
if 'bad port number' in str(response):
raise Err... | def portdate(port_number, date=None, return_format=None) | Information about a particular port at a particular date.
If the date is ommited, today's date is used.
:param port_number: a string or integer port number
:param date: an optional string in 'Y-M-D' format or datetime.date() object | 2.804532 | 3.205191 | 0.874997 |
uri = '/'.join(['topports', sort_by, str(limit)])
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | def topports(sort_by='records', limit=10, date=None, return_format=None) | Information about top ports for a particular date with return limit.
:param sort_by: one of 'records', 'targets', 'sources'
:param limit: number of records to be returned
:param date: an optional string in 'Y-M-D' format or datetime.date() object | 2.342801 | 2.64499 | 0.885751 |
uri = 'porthistory/{port}'.format(port=port_number)
if not start_date:
# default 30 days ago
start_date = datetime.datetime.now() - datetime.timedelta(days=30)
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, s... | def porthistory(port_number, start_date=None, end_date=None, return_format=None) | Returns port data for a range of dates.
In the return data:
Records: Total number of records for a given date range.
Targets: Number of unique destination IP addresses.
Sources: Number of unique originating IPs.
:param port_number: a valid port number (required)
:param start_date: string or d... | 2.220886 | 2.300923 | 0.965215 |
uri = 'asnum/{number}'.format(number=number)
if limit:
uri = '/'.join([uri, str(limit)])
return _get(uri, return_format) | def asnum(number, limit=None, return_format=None) | Returns a summary of the information our database holds for a
particular ASNUM (similar to /asdetailsascii.html) with return limit.
:param limit: number of records to be returned (max 2000) | 3.728985 | 4.847168 | 0.769312 |
uri = 'dailysummary'
if not start_date:
# default today
start_date = datetime.datetime.now()
try:
uri = '/'.join([uri, start_date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, start_date])
if end_date:
try:
uri = '/'.joi... | def dailysummary(start_date=None, end_date=None, return_format=None) | Returns daily summary totals of targets, attacks and sources. Limit to
30 days at a time. (Query 2002-01-01 to present)
In the return data:
Sources: Distinct source IP addresses the packets originate from.
Targets: Distinct target IP addresses the packets were sent to.
Reports: Number of packets r... | 2.107116 | 2.326842 | 0.905569 |
uri = 'daily404summary'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | def daily404summary(date, return_format=None) | Returns daily summary information of submitted 404 Error Page
Information.
:param date: string or datetime.date() (required) | 2.778749 | 3.372068 | 0.824049 |
uri = 'daily404detail'
if date:
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
if limit:
uri = '/'.join([uri, str(limit)])
return _get(uri, return_format) | def daily404detail(date, limit=None, return_format=None) | Returns detail information of submitted 404 Error Page Information.
:param date: string or datetime.date() (required)
:param limit: string or int, limit for number of returned items | 2.411424 | 2.836066 | 0.850271 |
uri = 'glossary'
if term:
uri = '/'.join([uri, term])
return _get(uri, return_format) | def glossary(term=None, return_format=None) | List of glossary terms and definitions.
:param term: a whole or parital word to "search" in the API | 3.797666 | 5.658313 | 0.671166 |
uri = 'webhoneypotsummary'
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | def webhoneypotsummary(date, return_format=None) | API data for `Webhoneypot: Web Server Log Project
<https://dshield.org/webhoneypot/>`_.
:param date: string or datetime.date() (required) | 2.981476 | 3.587318 | 0.831116 |
uri = 'webhoneypotbytype'
try:
uri = '/'.join([uri, date.strftime("%Y-%m-%d")])
except AttributeError:
uri = '/'.join([uri, date])
return _get(uri, return_format) | def webhoneypotbytype(date, return_format=None) | API data for `Webhoneypot: Attack By Type
<https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set
of regular expressions to determine the type of attack used to attack the
honeypot. Output is the top 30 attacks for the last month.
:param date: string or datetime.date() (required) | 2.887919 | 3.622621 | 0.79719 |
path = os.path.abspath(path)
if new_path == path:
return
sys.path.append(new_path) | def _append_path(new_path): # type: (str) -> None
for path in sys.path | Given a path string, append it to sys.path | 4.80083 | 3.670217 | 1.308051 |
if index >= len(stack):
raise RuntimeError("Cannot find import path")
frame = stack[index]
module = inspect.getmodule(frame[0])
index += 1
filename = module.__file__
path = os.path.dirname(os.path.realpath(filename))
return path | def _caller_path(index): # type: (int) -> str
module = None
stack = inspect.stack()
while not module | Get the caller's file path, by the index of the stack,
does not work when the caller is stdin through a CLI python | 3.670578 | 3.37532 | 1.087476 |
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
return path | def get_current_path(index=2): # type: (int) -> str
try | Get the caller's path to sys.path
If the caller is a CLI through stdin, the current working directory is used | 8.049564 | 9.953476 | 0.808719 |
git_path = os.path.join(path, '.git')
if os.path.isdir(git_path):
return path
if os.path.dirname(path) == path:
raise RuntimeError("Cannot find git root")
path = os.path.split(path)[0] | def get_git_root(index=3): # type: (int) -> str
path = get_current_path(index=index)
while True | Get the path of the git root directory of the caller's file
Raises a RuntimeError if a git repository cannot be found | 2.943818 | 2.865635 | 1.027283 |
path = _caller_path(index)
except RuntimeError:
path = os.getcwd()
path = os.path.abspath(os.path.join(path, os.pardir))
return path | def get_parent_path(index=2): # type: (int) -> str
try | Get the caller's parent path to sys.path
If the caller is a CLI through stdin, the parent of the current working
directory is used | 3.684417 | 4.157823 | 0.886141 |
t0=time()
params =str(N_iter)+'\n'
params+=str(dt)+'\n'
#We give the flag on wether to print each time step.
if print_steps:
params+='.true.\n'
else:
params+='.false.\n'
#We give the initial value of rho
N_vars=N_states*(N_states+1)/2-1
if rho0==None:
params+=''.join(['(0.0,0.0) ' for i in range(N_v... | def run_rk4(path,name,E0,laser_frequencies, N_iter,dt,N_states,
spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None,
rho0=None,print_steps=False,integrate=False,
save_systems=False) | This function runs the Runge-Kutta method compiled in path+name... | 2.571002 | 2.560381 | 1.004148 |
msg = self.get_message_object(send_to, attachment_paths, *args, **kwargs)
msg.content_subtype = self.content_subtype
try:
self.sent = msg.send()
except SMTPException, e:
if not fail_silently:
raise
logger.error(u'Problem sendi... | def send_email(self, send_to, attachment_paths=None, fail_silently=True, *args, **kwargs) | Sends email to recipient based on self object parameters.
@param fail_silently: When it’s False, msg.send() will raise an smtplib.SMTPException if an error occurs.
@param send_to: recipient email
@param args: additional args passed to EmailMessage
@param kwargs: kwargs passed to EmailMe... | 2.56218 | 2.861251 | 0.895475 |
self.get_object()
self.render_message()
self.send_email(to, attachment_paths, *args, **kwargs)
if self.sent:
logger.info(u"Mail has been sent to: %s ", to)
return self.sent | def send(self, to, attachment_paths=None, *args, **kwargs) | This function does all the operations on eft object, that are necessary to send email.
Usually one would use eft object like this:
eft = EmailFromTemplate(name='sth/sth.html')
eft.get_object()
eft.render_message()
eft.send_email(['email@example.... | 4.917894 | 2.647944 | 1.85725 |
tag = element.tag
if tag[0] == "{":
uri, tag = tag[1:].split("}")
return tag | def _tag(element) | Return element.tag with xmlns stripped away. | 3.419174 | 2.843677 | 1.202378 |
i = element.tag.find('}')
if i < 0:
return ""
return element.tag[:i+1] | def _uriPrefix(element) | Return xmlns prefix of the given element. | 3.873603 | 3.411434 | 1.135476 |
xmlns = _uriPrefix(elementTree)
if expectedTag is not None:
assert _tag(elementTree) == expectedTag, 'expected <%s>, got <%s>' % (expectedTag, _tag(elementTree))
parsed = []
for tagName in self.REQUIRED_ELEMENTS + self.OPTIONAL_ELEMENTS:
tags = elementTree.findall(xmlns + tagNam... | def _parseElements(self, elementTree, expectedTag = None) | Read REQUIRED_ELEMENTS and OPTIONAL_ELEMENTS and returns
the rest of the children. Every read child element's text
value will be filled into an attribute of the same name,
i.e. <description>Test</description> will lead to 'Test' being
assigned to self.description. Missing REQUIRED_ELEMENTS
result ... | 3.064872 | 2.745996 | 1.116124 |
arguments = []
options = []
outputs = []
for parameter in self.parameters():
if parameter.channel == 'output' and not parameter.isExternalType():
outputs.append(parameter)
elif parameter.index is not None:
arguments.append... | def classifyParameters(self) | Return (arguments, options, outputs) tuple. Together, the
three lists contain all parameters (recursively fetched from
all parameter groups), classified into optional parameters,
required ones (with an index), and simple output parameters
(that would get written to a file using
... | 4.002424 | 3.373155 | 1.186552 |
if self.isVector():
return list(map(self._pythonType, value.split(',')))
if self.typ == 'boolean':
return _parseBool(value)
return self._pythonType(value) | def parseValue(self, value) | Parse the given value and return result. | 5.597826 | 5.63077 | 0.994149 |
result = self.EXTERNAL_TYPES[self.typ]
if not self.fileExtensions:
return result
if result in self.fileExtensions:
return result
return self.fileExtensions[0] | def defaultExtension(self) | Return default extension for this parameter type, checked
against supported fileExtensions. If the default extension is
not within `fileExtensions`, return the first supported
extension. | 5.682981 | 4.235852 | 1.341638 |
if not X:
return ''
if not isinstance(X, str):
raise InvalidInputException('Input must be of type string.')
if seed is not None and len(seed) != 8:
raise InvalidSeedLength('The seed is not 8 bytes long, seed length: '+str(len(seed)))
ciphe... | def encode(self, X, seed=None) | Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n``
is the the maximum number of bytes that can be unranked w.r.t. the
capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input
``dfa``. | 3.523349 | 3.1992 | 1.101322 |
if not isinstance(covertext, str):
raise InvalidInputException('Input must be of type string.')
insufficient = (len(covertext) < self._fixed_slice)
if insufficient:
raise DecodeFailureError(
"Covertext is shorter than self._fixed_slice, can't de... | def decode(self, covertext) | Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. | 5.281661 | 5.047204 | 1.046453 |
r
if variables is None:
return Symbol(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)
else:
return Function(name+open_brace+str(i+1)+comma+str(j+1) +
close_brace, **kwds)(*variables) | def define_symbol(name, open_brace, comma, i, j,
close_brace, variables, **kwds) | r"""Define a nice symbol with matrix indices.
>>> name = "rho"
>>> from sympy import symbols
>>> t, x, y, z = symbols("t, x, y, z", positive=True)
>>> variables = [t, x, y, z]
>>> open_brace = ""
>>> comma = ""
>>> close_brace = ""
>>> i = 0
>>> j = 1
>>> f = define_symbol(name,... | 2.810587 | 3.319301 | 0.846741 |
if abstract:
Nl = symbols("N_l", integer=True)
if p == 1:
epsilon = Vector3D(IndexedBase("epsilonp", shape=(Nl,)))
else:
epsilon = Vector3D(IndexedBase("epsilonm", shape=(Nl,)))
return epsilon
epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0])
... | def polarization_vector(phi, theta, alpha, beta, p,
numeric=False, abstract=False) | This function returns a unitary vector describing the polarization
of plane waves.:
INPUT:
- ``phi`` - The spherical coordinates azimuthal angle of the wave vector\
k.
- ``theta`` - The spherical coordinates polar angle of the wave vector k.
- ``alpha`` - The rotation of a half-wave plate.
... | 2.673609 | 2.753071 | 0.971137 |
r
if numeric:
vector = list(vector)
vector[0] = nparray(vector[0])
vector[1] = nparray(vector[1])
vector[2] = nparray(vector[2])
v = [(vector[0]-1j*vector[1])/npsqrt(2),
vector[2],
-(vector[0]+1j*vector[1])/npsqrt(2)]
v = nparray(v)
... | def cartesian_to_helicity(vector, numeric=False) | r"""This function takes vectors from the cartesian basis to the helicity basis.
For instance, we can check what are the vectors of the helicity basis.
>>> from sympy import pi
>>> em=polarization_vector(phi=0, theta= 0, alpha=0, beta=-pi/8,p= 1)
>>> em
Matrix([
[ sqrt(2)/2],
[-sqrt(2)*I/2... | 2.600785 | 2.765363 | 0.940486 |
r
return Matrix([r[p][i, j] for p in range(3)]) | def vector_element(r, i, j) | r"""Extract an matrix element of a vector operator.
>>> r = define_r_components(2)
>>> vector_element(r, 1, 0)
Matrix([
[x_{21}],
[y_{21}],
[z_{21}]]) | 15.787805 | 14.828034 | 1.064727 |
u
omega_level = [Symbol('omega_'+str(i+1), real=True) for i in range(Ne)]
if Ne > 9:
opening = "\\"
comma = ","
open_brace = "{"
close_brace = "}"
else:
opening = r""
comma = ""
open_brace = ""
close_brace = ""
omega = []; gamma = []
... | def define_frequencies(Ne, explicitly_antisymmetric=False) | u"""Define all frequencies omega_level, omega, gamma.
>>> from sympy import pprint
>>> pprint(define_frequencies(2), use_unicode=True)
⎛ ⎡ 0 ω₁₂⎤ ⎡ 0 γ₁₂⎤⎞
⎜[ω₁, ω₂], ⎢ ⎥, ⎢ ⎥⎟
⎝ ⎣ω₂₁ 0 ⎦ ⎣γ₂₁ 0 ⎦⎠
We can make these matrices explicitly antisymmetric.
... | 1.859353 | 1.804687 | 1.030291 |
r
if i not in range(1, Ne+1):
raise ValueError("i must be in [1 .. Ne].")
return Matrix([KroneckerDelta(i-1, j) for j in range(Ne)]).transpose() | def bra(i, Ne) | r"""This function returns the transpose of the i-th element of the
canonical basis of a Hilbert space of dimension Ne (in the form of a
row vector).
>>> bra(2,4)
Matrix([[0, 1, 0, 0]])
This will return an error if i is not in [1 .. Ne]:
>>> bra(5,3)
Traceback (most recent call last):
... | 5.556299 | 4.827804 | 1.150896 |
r
if i not in range(1, Ne+1):
raise ValueError("i must be in [1 .. Ne].")
return Matrix([KroneckerDelta(i-1, j) for j in range(Ne)]) | def ket(i, Ne) | r"""This function returns the i-th element of the canonical basis
of a Hilbert space of dimension Ne (in the form of a column vector).
>>> ket(2,4)
Matrix([
[0],
[1],
[0],
[0]])
This will return an error if i is not in [1 .. Ne]:
>>> ket(5,3)
Traceback (most recent call last):... | 5.364223 | 4.943118 | 1.08519 |
return ket(i, Ne)*bra(j, Ne) | def ketbra(i, j, Ne) | This function returns the outer product :math:`|i><j|` where\
:math:`|i>` and :math:`|j>` are elements of the canonical basis of an\
Ne-dimensional Hilbert space (in matrix form).
>>> ketbra(2, 3, 3)
Matrix([
[0, 0, 0],
[0, 0, 1],
[0, 0, 0]]) | 5.106634 | 12.847727 | 0.397474 |
r
Ne = A.shape[0]
band = True
if sum(A) != 1:
band = False
a = None; b = None
for i in range(Ne):
for j in range(Ne):
if A[i, j] == 1:
a = i; b = j
elif A[i, j] != 0:
band = False
if band:
return a, b
else:
... | def sigma_operator_indices(A) | r"""If A is an outer-product type operator |a><b| return a, b.
>>> sig = ket(2, 3)*bra(1, 3)
>>> sigma_operator_indices(sig)
(1, 0)
>>> sigma_operator_indices(sig+sig.adjoint())
(None, None) | 3.522434 | 3.73693 | 0.942601 |
r
a, b = sigma_operator_indices(A)
# print(111, a, b)
if a is not None and b is not None:
Ne = A.shape[0]
L = zeros(Ne, Ne)
L[a, a] += rho[b, b]
for j in range(Ne):
L[b, j] += -rho[b, j]/2
for i in range(Ne):
L[i, b] += -rho[i, b]/2
... | def lindblad_operator(A, rho) | r"""This function returns the action of a Lindblad operator A on a density\
matrix rho. This is defined as :
.. math::
\mathcal{L}(A, \rho) = A \rho A^\dagger -
(A^\dagger A \rho + \rho A^\dagger A)/2.
>>> rho=define_density_matrix(3)
>>> lindblad_operator( ketbra(1,2,3) ,rho )
Matrix... | 3.906137 | 3.80114 | 1.027623 |
u
rho_vect = []
for mu in range(1, Ne**2):
i, j, s = IJ(mu, Ne)
i = i-1; j = j-1
rho_vect += [part_symbolic(rho[i, j], s)]
return Matrix(rho_vect) | def define_rho_vector(rho, Ne) | u"""Define the vectorized density matrix.
>>> from sympy import pprint
>>> rho = define_density_matrix(3)
>>> pprint(define_rho_vector(rho, 3), use_unicode=True)
⎡ ρ₂₂ ⎤
⎢ ⎥
⎢ ρ₃₃ ⎥
⎢ ⎥
⎢re(ρ₂₁)⎥
⎢ ⎥
⎢re(ρ₃₁)⎥
⎢ ⎥
⎢re(ρ₃₂)⎥
⎢ ⎥
⎢... | 6.69074 | 7.91476 | 0.84535 |
u
Ne = unfolding.Ne
Nrho = unfolding.Nrho
lower_triangular = unfolding.lower_triangular
rho = define_density_matrix(Ne, explicitly_hermitian=lower_triangular,
normalized=unfolding.normalized)
rho_vect = unfolding(rho)
if unfolding.real:
ss_comp = {rho... | def calculate_A_b(eqs, unfolding, verbose=0) | u"""Calculate the equations in matrix form.
>>> from sympy import symbols, pprint, I
>>> rho = define_density_matrix(2, explicitly_hermitian=True,
... normalized=True)
>>> Omega = symbols("Omega")
>>> delta = symbols("delta", real=True)
>>> hbar = symbols("hbar", po... | 5.501797 | 4.722812 | 1.164941 |
r
ph = find_phase_transformation(Ne, Nl, r, Lij)
return {phase[i]: sum([ph[i][j]*omega_laser[j] for j in range(Nl)])
for i in range(Ne)} | def phase_transformation(Ne, Nl, r, Lij, omega_laser, phase) | r"""Obtain a phase transformation to eliminate explicit time dependence.
>>> Ne = 2 | 5.551693 | 5.870428 | 0.945705 |
r
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
acoef = a.args[:aivect] + a.args[aivect+1:]
... | def dot(a, b) | r"""Dot product of two 3d vectors. | 2.476169 | 2.484297 | 0.996728 |
r
if isinstance(a, Mul):
a = a.expand()
avect = 1
aivect = -1
for ai, fact in enumerate(a.args):
if isinstance(fact, Vector3D):
avect = fact
aivect = ai
break
acoef = a.args[:aivect] + a.args[aivect+1:]
... | def cross(a, b) | r"""Cross product of two 3d vectors. | 2.215564 | 2.228558 | 0.994169 |
'''
Saves user's settings
@returns True on success
@returns False on failure
'''
if not os.access(DATA_DIR, os.W_OK): return False
try:
f = open(DATA_DIR + os.sep + SETTINGS_FILE, 'w')
f.writelines(json.dumps(settings, indent=0))
f.close()
os.chmod(os.path.abs... | def write_settings(settings) | Saves user's settings
@returns True on success
@returns False on failure | 3.883438 | 3.175858 | 1.222799 |
'''
Gets main mapping source according to what a data classification is made
Gets the hierarchy groups (only for GUI)
Gets the hierarchy values
'''
hierarchy, hierarchy_groups, hierarchy_values = [], [], {}
hgroup_ids, enumerated_vals = {}, set()
session = connect_database(settings)
... | def get_hierarchy(settings) | Gets main mapping source according to what a data classification is made
Gets the hierarchy groups (only for GUI)
Gets the hierarchy values | 3.937607 | 3.209706 | 1.226781 |
''' Determine if field is constant by group in df
'''
def num_unique(x):
return len(pd.unique(x))
num_distinct = df.groupby(group_col)[field_col].agg(num_unique)
return all(num_distinct == 1) | def is_field_unique_by_group(df, field_col, group_col) | Determine if field is constant by group in df | 4.529825 | 3.794003 | 1.193943 |
results = []
for dirname, subdirs, files in os.walk(path):
for name in files:
if fnmatch(name, pattern):
results.append(os.path.join(dirname, name))
return(results) | def _list_files_in_path(path, pattern="*.stan") | indexes a directory of stan files
returns as dictionary containing contents of files | 2.305207 | 2.303085 | 1.000921 |
'''
This generates a random valid perovskite structure in ASE format.
Useful for testing.
Binary and organic perovskites are not considered.
'''
if not lat:
lat = round(random.uniform(3.5, Perovskite_tilting.OCTAHEDRON_BOND_LENGTH_LIMIT*2), 3)
A_site = random.choice(Perovskite_Struct... | def generate_random_perovskite(lat=None) | This generates a random valid perovskite structure in ASE format.
Useful for testing.
Binary and organic perovskites are not considered. | 2.820945 | 2.349121 | 1.200851 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.