code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if os.path.exists(headers_path):
header_parser = BlockHeaderSerializer()
sb = os.stat( headers_path )
if sb.st_size < BLOCK_HEADER_SIZE * block_height:
# beyond EOF
if allow_none:
return None
... | def read_header(cls, headers_path, block_height, allow_none=False) | Get a block header at a particular height from disk.
Return the header if found
Return None if not. | 4.029288 | 4.028041 | 1.00031 |
if chain is None:
chain = [] # Do not use mutables as default values!
max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
if index == 0:
return 0x1d00ffff, max_target
first = SPVClient.read_header( path, (index-1)*BLOCK_DIFF... | def get_target(cls, path, index, chain=None) | Calculate the target difficulty at a particular difficulty interval (index).
Return (bits, target) on success | 3.561175 | 3.296329 | 1.080346 |
prev_header = cls.read_header( headers_path, block_id - 1 )
prev_hash = prev_header['hash']
return bits.block_header_verify( block_header, prev_hash, block_hash ) | def block_header_verify( cls, headers_path, block_id, block_hash, block_header ) | Given the block's numeric ID, its hash, and the bitcoind-returned block_data,
use the SPV header chain to verify the block's integrity.
block_header must be a dict with the following structure:
* version: protocol version (int)
* prevhash: previous block hash (hex str)
* merkler... | 3.317671 | 3.883102 | 0.854387 |
block_data = {
'merkleroot': verified_block_header['merkleroot'],
'tx': block_txids
}
return bits.block_verify( block_data ) | def block_verify( cls, verified_block_header, block_txids ) | Given the block's verified header structure (see block_header_verify) and
its list of transaction IDs (as hex strings), verify that the transaction IDs are legit.
Return True on success
Return False on error. | 4.880646 | 4.595054 | 1.062152 |
tx_hex = bits.btc_bitcoind_tx_serialize( tx )
tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex')
return tx_hash | def tx_hash( cls, tx ) | Calculate the hash of a transction structure given by bitcoind | 4.923636 | 4.33547 | 1.135664 |
tx_hash = cls.tx_hash( tx )
return tx_hash in verified_block_txids | def tx_verify( cls, verified_block_txids, tx ) | Given the block's verified block txids, verify that a transaction is legit.
@tx must be a dict with the following fields:
* locktime: int
* version: int
* vin: list of dicts with:
* vout: int,
* hash: hex str
* sequence: int (optional)
* script... | 3.632207 | 4.217048 | 0.861315 |
tx_hash = cls.tx_hash( verified_tx )
return verified_block_txids.index( tx_hash ) | def tx_index( cls, verified_block_txids, verified_tx ) | Given a block's verified block txids and a verified transaction,
find out where it is in the list of txids (i.e. what's its index)? | 3.236178 | 2.574424 | 1.25705 |
with open( path, "rb" ) as f:
chain_raw = f.read()
for blk in xrange(0, len(chain_raw) / (BLOCK_HEADER_SIZE)):
if chain_raw[blk * BLOCK_HEADER_SIZE : blk * BLOCK_HEADER_SIZE + BLOCK_HEADER_SIZE] == block_header:
return blk
return -1 | def block_header_index( cls, path, block_header ) | Given a block's serialized header, go and find out what its
block ID is (if it is present at all).
Return the >= 0 index on success
Return -1 if not found.
NOTE: this is slow | 2.851944 | 2.752162 | 1.036256 |
if chain is None:
chain = SPVClient.load_header_chain( path )
prev_header = chain[0]
for i in xrange(1, len(chain)):
header = chain[i]
height = header.get('block_height')
prev_hash = prev_header.get('hash')
if prev_ha... | def verify_header_chain(cls, path, chain=None) | Verify that a given chain of block headers
has sufficient proof of work. | 2.603139 | 2.509943 | 1.037131 |
current_block_id = SPVClient.height( path )
if current_block_id is None:
assert USE_TESTNET
current_block_id = -1
assert (current_block_id >= 0 and USE_MAINNET) or USE_TESTNET
if current_block_id < last_block_id:
if USE_MAINNET:
... | def sync_header_chain(cls, path, bitcoind_server, last_block_id ) | Synchronize our local block headers up to the last block ID given.
@last_block_id is *inclusive*
@bitcoind_server is host:port or just host | 2.951392 | 2.882603 | 1.023863 |
'''Helper method used by :meth:`Message.from_email_message` to
convert dates from rfc822 format to iso 8601.
:param datestr: string containing a date in rfc822 format
:returns: string with date in iso 8601 format
'''
time_tuple = email.utils.parsedate_tz(datestr)
if time_tuple is None:
... | def parse_mail_date(datestr) | Helper method used by :meth:`Message.from_email_message` to
convert dates from rfc822 format to iso 8601.
:param datestr: string containing a date in rfc822 format
:returns: string with date in iso 8601 format | 2.771046 | 1.634876 | 1.694958 |
try:
precision = {16: 11, 32: 24, 64: 53, 128: 113}[bitwidth]
except KeyError:
if not (bitwidth >= 128 and bitwidth % 32 == 0):
raise ValueError("nonstandard bitwidth: bitwidth should be "
"16, 32, 64, 128, or k*32 for some k >= 4")
# The for... | def IEEEContext(bitwidth) | Return IEEE 754-2008 context for a given bit width.
The IEEE 754 standard specifies binary interchange formats with bitwidths
16, 32, 64, 128, and all multiples of 32 greater than 128. This function
returns the context corresponding to the interchange format for the given
bitwidth.
See section 3.... | 4.810722 | 4.643334 | 1.036049 |
try:
molecule.view(viewer=viewer, use_curr_dir=use_curr_dir)
except AttributeError:
if pd.api.types.is_list_like(molecule):
cartesian_list = molecule
else:
raise ValueError('Argument is neither list nor Cartesian.')
if use_curr_dir:
TEMP_D... | def view(molecule, viewer=settings['defaults']['viewer'], use_curr_dir=False) | View your molecule or list of molecules.
.. note:: This function writes a temporary file and opens it with
an external viewer.
If you modify your molecule afterwards you have to recall view
in order to see the changes.
Args:
molecule: Can be a cartesian, or a list of cartesians... | 2.983919 | 2.898567 | 1.029446 |
if sort_index:
cartesian_list = [molecule.sort_index() for molecule in cartesian_list]
give_header = ("[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(len(cartesian_list)) + "\n"
+ '[GEOCONV]\n'
+ 'energy\n{energy}'
... | def to_molden(cartesian_list, buf=None, sort_index=True,
overwrite=True, float_format='{:.6f}'.format) | Write a list of Cartesians into a molden file.
.. note:: Since it permamently writes a file, this function
is strictly speaking **not sideeffect free**.
The list to be written is of course not changed.
Args:
cartesian_list (list):
buf (str): StringIO-like, optional buffer to wr... | 3.108607 | 3.432041 | 0.90576 |
message = 'Will be removed in the future. Please use to_molden().'
with warnings.catch_warnings():
warnings.simplefilter("always")
warnings.warn(message, DeprecationWarning)
return to_molden(*args, **kwargs) | def write_molden(*args, **kwargs) | Deprecated, use :func:`~chemcoord.xyz_functions.to_molden` | 3.246504 | 2.74062 | 1.184587 |
from chemcoord.cartesian_coordinates.cartesian_class_main import Cartesian
with open(inputfile, 'r') as f:
found = False
while not found:
line = f.readline()
if '[N_GEO]' in line:
found = True
number_of_molecules = int(f.readline().str... | def read_molden(inputfile, start_index=0, get_bonds=True) | Read a molden file.
Args:
inputfile (str):
start_index (int):
Returns:
list: A list containing :class:`~chemcoord.Cartesian` is returned. | 2.910637 | 2.833134 | 1.027356 |
coords = ['x', 'y', 'z']
if not (set(a.index) == set(b.index)
and np.alltrue(a.loc[:, 'atom'] == b.loc[a.index, 'atom'])):
message = 'Can only compare molecules with the same atoms and labels'
raise ValueError(message)
if align:
a = a.get_inertia()['transformed_Cart... | def isclose(a, b, align=False, rtol=1.e-5, atol=1.e-8) | Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing.
rtol (float): Relative tolerance for the numerical eq... | 4.178977 | 4.064114 | 1.028263 |
return np.alltrue(isclose(a, b, align=align, rtol=rtol, atol=atol)) | def allclose(a, b, align=False, rtol=1.e-5, atol=1.e-8) | Compare two molecules for numerical equality.
Args:
a (Cartesian):
b (Cartesian):
align (bool): a and b are
prealigned along their principal axes of inertia and moved to their
barycenters before comparing.
rtol (float): Relative tolerance for the numerical eq... | 2.774429 | 5.324769 | 0.521042 |
frames = [molecule._frame for molecule in cartesians]
new = pd.concat(frames, ignore_index=ignore_index, keys=keys,
verify_integrity=True)
if type(ignore_index) is bool:
new = pd.concat(frames, ignore_index=ignore_index, keys=keys,
verify_integrity=T... | def concat(cartesians, ignore_index=False, keys=None) | Join list of cartesians into one molecule.
Wrapper around the :func:`pandas.concat` function.
Default values are the same as in the pandas function except for
``verify_integrity`` which is set to true in case of this library.
Args:
ignore_index (sequence, bool, int): If it is a boolean, it
... | 2.391425 | 2.289202 | 1.044655 |
try:
result = A.__matmul__(B)
if result is NotImplemented:
result = B.__rmatmul__(A)
except AttributeError:
result = B.__rmatmul__(A)
return result | def dot(A, B) | Matrix multiplication between A and B
This function is equivalent to ``A @ B``, which is unfortunately
not possible under python 2.x.
Args:
A (sequence):
B (sequence):
Returns:
sequence: | 3.367955 | 4.50386 | 0.747793 |
axis = normalize(np.array(axis))
if not (np.array([1, 1, 1]).shape) == (3, ):
raise ValueError('axis.shape has to be 3')
angle = float(angle)
return _jit_get_rotation_matrix(axis, angle) | def get_rotation_matrix(axis, angle) | Returns the rotation matrix.
This function returns a matrix for the counterclockwise rotation
around the given axis.
The Input angle is in radians.
Args:
axis (vector):
angle (float):
Returns:
Rotation matrix (np.array): | 4.406702 | 4.980169 | 0.88485 |
axis = _jit_normalize(axis)
a = m.cos(angle / 2)
b, c, d = axis * m.sin(angle / 2)
rot_matrix = np.empty((3, 3))
rot_matrix[0, 0] = a**2 + b**2 - c**2 - d**2
rot_matrix[0, 1] = 2. * (b * c - a * d)
rot_matrix[0, 2] = 2. * (b * d + a * c)
rot_matrix[1, 0] = 2. * (b * c + a * d)
r... | def _jit_get_rotation_matrix(axis, angle) | Returns the rotation matrix.
This function returns a matrix for the counterclockwise rotation
around the given axis.
The Input angle is in radians.
Args:
axis (vector):
angle (float):
Returns:
Rotation matrix (np.array): | 1.344863 | 1.412787 | 0.951922 |
v1, v2 = basis[:, 0], basis[:, 1]
e1 = normalize(v1)
e3 = normalize(np.cross(e1, v2))
e2 = normalize(np.cross(e3, e1))
return np.array([e1, e2, e3]).T | def orthonormalize_righthanded(basis) | Orthonormalizes righthandedly a given 3D basis.
This functions returns a right handed orthonormalize_righthandedd basis.
Since only the first two vectors in the basis are used, it does not matter
if you give two or three vectors.
Right handed means, that:
.. math::
\\vec{e_1} \\times \\v... | 2.163426 | 2.298535 | 0.94122 |
# Naming of variables follows the wikipedia article:
# http://en.wikipedia.org/wiki/Kabsch_algorithm
A = np.dot(np.transpose(P), Q)
# One can't initialize an array over its transposed
V, S, W = np.linalg.svd(A) # pylint:disable=unused-variable
W = W.T
d = np.linalg.det(np.dot(W, V.T))
... | def get_kabsch_rotation(Q, P) | Calculate the optimal rotation from ``P`` unto ``Q``.
Using the Kabsch algorithm the optimal rotation matrix
for the rotation of ``other`` unto ``self`` is calculated.
The algorithm is described very well in
`wikipedia <http://en.wikipedia.org/wiki/Kabsch_algorithm>`_.
Args:
other (Cartesi... | 4.229159 | 4.599957 | 0.919391 |
if (construction_table.index != cart_dist.index).any():
message = "construction_table and cart_dist must use the same index"
raise ValueError(message)
X_dist = cart_dist.loc[:, ['x', 'y', 'z']].values.T
C_dist = np.tensordot(grad_C, X_dist, axes=([3, 2], [0, 1])).T
if C_dist.dtype =... | def apply_grad_zmat_tensor(grad_C, construction_table, cart_dist) | Apply the gradient for transformation to Zmatrix space onto cart_dist.
Args:
grad_C (:class:`numpy.ndarray`): A ``(3, n, n, 3)`` array.
The mathematical details of the index layout is explained in
:meth:`~chemcoord.Cartesian.get_grad_zmat()`.
construction_table (pandas.DataF... | 3.111907 | 2.980604 | 1.044052 |
'''Remove a node or attribute. For multipart XPaths that are
constructible by :mod:`eulxml.xmlmap`, the corresponding nodes
will be removed if they are empty (other than predicates specified
in the XPath).
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param ... | def _remove_xml(xast, node, context, if_empty=False) | Remove a node or attribute. For multipart XPaths that are
constructible by :mod:`eulxml.xmlmap`, the corresponding nodes
will be removed if they are empty (other than predicates specified
in the XPath).
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: l... | 5.349177 | 3.119246 | 1.714894 |
'''Remove a child node based on the specified xpath.
:param node: lxml element relative to which the xpath will be
interpreted
:param context: any context required for the xpath (e.g.,
namespace definitions)
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
... | def _remove_child_node(node, context, xast, if_empty=False) | Remove a child node based on the specified xpath.
:param node: lxml element relative to which the xpath will be
interpreted
:param context: any context required for the xpath (e.g.,
namespace definitions)
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param ... | 6.172967 | 2.445542 | 2.524171 |
'''Remove any constructible predicates specified in the xpath
relative to the specified node.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element which predicates will be removed from
:param context: any context required for the xpath (e.g.,
... | def _remove_predicates(xast, node, context) | Remove any constructible predicates specified in the xpath
relative to the specified node.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element which predicates will be removed from
:param context: any context required for the xpath (e.g.,
name... | 7.26659 | 4.523655 | 1.606354 |
'''Check if a node is empty (no child nodes or attributes) except
for any predicates defined in the specified xpath.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element to check
:param context: any context required for the xpath (e.g.,
nam... | def _empty_except_predicates(xast, node, context) | Check if a node is empty (no child nodes or attributes) except
for any predicates defined in the specified xpath.
:param xast: parsed xpath (xpath abstract syntax tree) from
:mod:`eulxml.xpath`
:param node: lxml element to check
:param context: any context required for the xpath (e.g.,
namespace ... | 5.695494 | 2.039361 | 2.792784 |
if i is None:
i = len(self) - 1
val = self[i]
del(self[i])
return val | def pop(self, i=None) | Remove the item at the given position in the list, and return it.
If no index is specified, removes and returns the last item in the list. | 2.631744 | 2.457428 | 1.070934 |
if i == len(self): # end of list or empty list: append
self.append(x)
elif len(self.matches) > i:
# create a new xml node at the requested position
insert_index = self.matches[i].getparent().index(self.matches[i])
_create_xml_node(self.xast, self... | def insert(self, i, x) | Insert an item (x) at a given position (i). | 6.017081 | 5.758357 | 1.04493 |
type = schema.get_type(self.schema_type)
logger.debug('Found schema type %s; base type %s, restricted values %s' % \
(self.schema_type, type.base_type(), type.restricted_values))
kwargs = {}
if type.restricted_values:
# field has a restriction wi... | def get_field(self, schema) | Get the requested type definition from the schema and return the
appropriate :class:`~eulxml.xmlmap.fields.Field`.
:param schema: instance of :class:`eulxml.xmlmap.core.XsdSchema`
:rtype: :class:`eulxml.xmlmap.fields.Field` | 7.073292 | 6.583935 | 1.074326 |
"roundrobin('ABC', 'D', 'EF') --> A D E B F C"
# Recipe credited to George Sakkis
pending = len(iterables)
nexts = itertools.cycle(iter(it).next for it in iterables)
while pending:
try:
for next in nexts:
yield next()
except StopIteration:
pend... | def roundrobin(*iterables) | roundrobin('ABC', 'D', 'EF') --> A D E B F C | 2.362236 | 2.204885 | 1.071365 |
classes = unionfind.classes(constraints)
return dict((x, tuple(c)) for x, c in classes.iteritems()) | def get_scc_from_tuples(constraints) | Given set of equivalences, return map of transitive equivalence classes.
>> constraints = [(1,2), (2,3)]
>> get_scc_from_tuples(constraints)
{
1: (1, 2, 3),
2: (1, 2, 3),
3: (1, 2, 3),
} | 10.496394 | 9.698956 | 1.082219 |
field_parts = (name.split('.') for name in fieldnames)
return _collect_fields(field_parts, include_parents) | def _parse_field_list(fieldnames, include_parents=False) | Parse a list of field names, possibly including dot-separated subform
fields, into an internal ParsedFieldList object representing the base
fields and subform listed.
:param fieldnames: a list of field names as strings. dot-separated names
are interpreted as subform fields.
:param include_paren... | 5.550835 | 9.250557 | 0.600054 |
fields = []
subpart_lists = defaultdict(list)
for parts in field_parts_list:
field, subparts = parts[0], parts[1:]
if subparts:
if include_parents and field not in fields:
fields.append(field)
subpart_lists[field].append(subparts)
else:
... | def _collect_fields(field_parts_list, include_parents) | utility function to enable recursion in _parse_field_list() | 2.442497 | 2.28764 | 1.067693 |
data = {}
# convert prefix to combining form for convenience
if prefix:
prefix = '%s-' % prefix
else:
prefix = ''
for name, field in six.iteritems(instance._fields):
# not editable?
if fields and not name in fields:
continue
if exclude and na... | def xmlobject_to_dict(instance, fields=None, exclude=None, prefix='') | Generate a dictionary based on the data in an XmlObject instance to pass as
a Form's ``initial`` keyword argument.
:param instance: instance of :class:`~eulxml.xmlmap.XmlObject`
:param fields: optional list of fields - if specified, only the named fields
will be included in the data returned
... | 2.590511 | 2.739912 | 0.945472 |
attrs = {'model': model}
if fields is not None:
attrs['fields'] = fields
if exclude is not None:
attrs['exclude'] = exclude
if widgets is not None:
attrs['widgets'] = widgets
if max_num is not None:
attrs['max_num'] = max_num
if extra is not None:
at... | def xmlobjectform_factory(model, form=XmlObjectForm, fields=None, exclude=None,
widgets=None, max_num=None, label=None, can_delete=True,
extra=None, can_order=False) | Dynamically generate a new :class:`XmlObjectForm` class using the
specified :class:`eulxml.xmlmap.XmlObject` class.
Based on django's modelform_factory. | 3.071399 | 3.173817 | 0.96773 |
# NOTE: django model form has a save method - not applicable here,
# since an XmlObject by itself is not expected to have a save method
# (only likely to be saved in context of a fedora or exist object)
if hasattr(self, 'cleaned_data'): # possible to have an empty object/no ... | def update_instance(self) | Save bound form data into the XmlObject model instance and return the
updated instance. | 6.384826 | 5.9669 | 1.070041 |
old_subinstance = getattr(self.instance, name)
new_subinstance = subform.update_instance()
# if our instance previously had no node for the subform AND the
# updated one has data, then attach the new node.
if old_subinstance is None and not new_subinstance.is_empty():
... | def _update_subinstance(self, name, subform) | Save bound data for a single subform into the XmlObject model
instance. | 3.106874 | 2.910384 | 1.067514 |
valid = super(XmlObjectForm, self).is_valid() and \
all(s.is_valid() for s in six.itervalues(self.subforms)) and \
all(s.is_valid() for s in six.itervalues(self.formsets))
# schema validation can only be done after regular validation passes,
# because xml... | def is_valid(self) | Returns True if this form and all subforms (if any) are valid.
If all standard form-validation tests pass, uses :class:`~eulxml.xmlmap.XmlObject`
validation methods to check for schema-validity (if a schema is associated)
and reporting errors. Additonal notes:
* schema validation req... | 5.203898 | 4.425332 | 1.175934 |
parts = []
parts.append(super(XmlObjectForm, self)._html_output(normal_row, error_row, row_ender,
help_text_html, errors_on_separate_row))
def _subform_output(subform):
return subform._html_output(normal_row, error_row, row_ender,
... | def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row) | Extend BaseForm's helper function for outputting HTML. Used by as_table(), as_ul(), as_p().
Combines the HTML version of the main form's fields with the HTML content
for any subforms. | 3.244953 | 3.248078 | 0.999038 |
from .bitcoin_blockchain import AuthServiceProxy
global do_wrap_socket, create_ssl_authproxy
log.debug("[%s] Connect to bitcoind at %s://%s@%s:%s, timeout=%s" % (os.getpid(), 'https' if use_https else 'http', rpc_username, server, port, timeout) )
protocol = 'https' if use_https... | def create_bitcoind_connection( rpc_username, rpc_password, server, port, use_https, timeout ) | Creates an RPC client to a bitcoind instance.
It will have ".opts" defined as a member, which will be a dict that stores the above connection options. | 3.083904 | 3.069651 | 1.004643 |
if 'bitcoind_port' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_port'] is None:
log.error("No port given")
raise ValueError("No RPC port given (bitcoind_port)")
if 'bitcoind_timeout' not in bitcoind_opts.keys() or bitcoind_opts['bitcoind_timeout'] is None:
# default
... | def connect_bitcoind_impl( bitcoind_opts ) | Create a connection to bitcoind, using a dict of config options. | 1.886553 | 1.854228 | 1.017433 |
if bitcoind_opts is None and config_path is None:
raise ValueError("Need bitcoind opts or config path")
bitcoind_opts = get_bitcoind_config(config_file=config_path)
log.debug("Connect to bitcoind at %s:%s (%s)" % (bitcoind_opts['bitcoind_server'], bitcoind_opts['bitcoind_port'], config_path))
... | def get_bitcoind_client(config_path=None, bitcoind_opts=None) | Connect to bitcoind | 2.906985 | 2.78984 | 1.04199 |
if compressed is None:
compressed = False
if privkey_str is not None:
if len(privkey_str) == 66 and privkey_str[-2:] == '01':
compressed = True
return _ECPrivateKey(privkey_str, compressed=compressed) | def ecdsa_private_key(privkey_str=None, compressed=None) | Make a private key, but enforce the following rule:
* unless the key's hex encoding specifically ends in '01', treat it as uncompressed. | 2.603536 | 2.62465 | 0.991956 |
if compressed == True:
pubkey_str = keylib.key_formatting.compress(pubkey_str)
elif compressed == False:
pubkey_str = keylib.key_formatting.decompress(pubkey_str)
return _ECPublicKey(pubkey_str) | def ecdsa_public_key(pubkey_str, compressed=None) | Make a public key object, but enforce the following rule:
* if compressed is True or False, make the key compressed/uncompressed.
* otherwise, return whatever the hex encoding is | 3.245443 | 3.568043 | 0.909586 |
if len(privkey) != 64 and len(privkey) != 66:
raise ValueError("expected 32-byte private key as a hex string")
# compressed?
if compressed and len(privkey) == 64:
privkey += '01'
if not compressed and len(privkey) == 66:
if privkey[-2:] != '01':
raise ValueErro... | def set_privkey_compressed(privkey, compressed=True) | Make sure the private key given is compressed or not compressed | 2.658111 | 2.619292 | 1.01482 |
if not isinstance(privatekey_hex, (str, unicode)):
raise ValueError("private key is not a hex string but {}".format(str(type(privatekey_hex))))
# remove 'compressed' hint
if len(privatekey_hex) > 64:
if privatekey_hex[-2:] != '01':
raise ValueError("private key does not end... | def get_pubkey_hex( privatekey_hex ) | Get the uncompressed hex form of a private key | 2.389364 | 2.391904 | 0.998938 |
if not isinstance(privkey_str, (str, unicode)):
raise ValueError("private key given is not a string")
pk = ecdsa_private_key(str(privkey_str))
pk_hex = pk.to_hex()
# force uncompressed
if len(pk_hex) > 64:
if pk_hex[-2:] != '01':
raise ValueError("private key does ... | def get_uncompressed_private_and_public_keys( privkey_str ) | Get the private and public keys from a private key string.
Make sure the both are *uncompressed* | 3.0107 | 2.979614 | 1.010433 |
if not isinstance(privkey_hex, (str, unicode)):
raise ValueError("private key is not a string")
# force uncompressed
priv = str(privkey_hex)
if len(priv) > 64:
if priv[-2:] != '01':
raise ValueError("private key does not end in '01'")
priv = priv[:64]
pk_i... | def decode_privkey_hex(privkey_hex) | Decode a private key for ecdsa signature | 3.539926 | 3.501883 | 1.010864 |
if not isinstance(pubkey_hex, (str, unicode)):
raise ValueError("public key is not a string")
pubk = keylib.key_formatting.decompress(str(pubkey_hex))
assert len(pubk) == 130
pubk_raw = pubk[2:]
pubk_i = (int(pubk_raw[:64], 16), int(pubk_raw[64:], 16))
return pubk_i | def decode_pubkey_hex(pubkey_hex) | Decode a public key for ecdsa verification | 3.949853 | 3.735074 | 1.057503 |
# enforce low-s
if sig_s * 2 >= SECP256k1_order:
log.debug("High-S to low-S")
sig_s = SECP256k1_order - sig_s
sig_bin = '{:064x}{:064x}'.format(sig_r, sig_s).decode('hex')
assert len(sig_bin) == 64
sig_b64 = base64.b64encode(sig_bin)
return sig_b64 | def encode_signature(sig_r, sig_s) | Encode an ECDSA signature, with low-s | 2.880832 | 2.727056 | 1.056389 |
sig_bin = base64.b64decode(sigb64)
if len(sig_bin) != 64:
raise ValueError("Invalid base64 signature")
sig_hex = sig_bin.encode('hex')
sig_r = int(sig_hex[:64], 16)
sig_s = int(sig_hex[64:], 16)
return sig_r, sig_s | def decode_signature(sigb64) | Decode a signature into r, s | 1.917839 | 1.863153 | 1.029352 |
if not isinstance(raw_data, (str, unicode)):
raise ValueError("Data is not a string")
raw_data = str(raw_data)
si = ECSigner(privatekey_hex)
si.update(raw_data)
return si.finalize() | def sign_raw_data(raw_data, privatekey_hex) | Sign a string of data.
Returns signature as a base64 string | 3.882352 | 3.941665 | 0.984952 |
if not isinstance(raw_data, (str, unicode)):
raise ValueError("data is not a string")
raw_data = str(raw_data)
vi = ECVerifier(pubkey_hex, sigb64)
vi.update(raw_data)
return vi.verify() | def verify_raw_data(raw_data, pubkey_hex, sigb64) | Verify the signature over a string, given the public key
and base64-encode signature.
Return True on success.
Return False on error. | 3.833059 | 3.88783 | 0.985912 |
if not isinstance(hash_hex, (str, unicode)):
raise ValueError("hash hex is not a string")
hash_hex = str(hash_hex)
pk_i = decode_privkey_hex(privkey_hex)
privk = ec.derive_private_key(pk_i, ec.SECP256K1(), default_backend())
sig = privk.sign(hash_hex.decode('hex'), ec.ECDSA(utils.Pre... | def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256) | Given a digest and a private key, sign it.
Return the base64-encoded signature | 2.655067 | 2.621322 | 1.012873 |
if not isinstance(hash_hex, (str, unicode)):
raise ValueError("hash hex is not a string")
hash_hex = str(hash_hex)
pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
sig_r, sig_s = decode_signature(sigb64)
pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(ec.SE... | def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256) | Given a digest, public key (as hex), and a base64 signature,
verify that the public key signed the digest.
Return True if so
Return False if not | 2.666277 | 2.697141 | 0.988557 |
signature = self.signer.finalize()
sig_r, sig_s = decode_dss_signature(signature)
sig_b64 = encode_signature(sig_r, sig_s)
return sig_b64 | def finalize(self) | Get the base64-encoded signature itself.
Can only be called once. | 4.161521 | 3.165535 | 1.314634 |
try:
self.verifier.update(data)
except TypeError:
log.error("Invalid data: {} ({})".format(type(data), data))
raise | def update(self, data) | Update the hash used to generate the signature | 5.080623 | 4.820242 | 1.054018 |
(q, n), d = divmod(x.numerator, x.denominator), x.denominator
yield Fraction(q)
p0, q0, p1, q1 = 1, 0, q, 1
while n:
(q, n), d = divmod(d, n), n
for _ in range(q):
p0, q0 = p0+p1, q0+q1
yield Fraction(p0, q0)
p0, q0, p1, q1 = p1, q1, p0, q0 | def semiconvergents(x) | Semiconvergents of continued fraction expansion of a Fraction x. | 2.923709 | 2.539752 | 1.151179 |
with precision(p):
extra = 10
while True:
with precision(p+extra):
# use extra precision for intermediate step
log2upper = log2(n, RoundTowardPositive)
log2lower = log2(n, RoundTowardNegative)
lower = div(1, log2upper, Rou... | def logn2(n, p) | Best p-bit lower and upper bounds for log(2)/log(n), as Fractions. | 4.842998 | 4.303579 | 1.125342 |
if inplace:
self._frame.sort_values(
by, axis=axis, ascending=ascending,
inplace=inplace, kind=kind, na_position=na_position)
else:
new = self.__class__(self._frame.sort_values(
by, axis=axis, ascending=ascending, inplace=i... | def sort_values(self, by, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last') | Sort by the values along either axis
Wrapper around the :meth:`pandas.DataFrame.sort_values` method. | 1.814288 | 1.956949 | 0.9271 |
if inplace:
self._frame.replace(to_replace=to_replace, value=value,
inplace=inplace, limit=limit, regex=regex,
method=method, axis=axis)
else:
new = self.__class__(self._frame.replace(
to_rep... | def replace(self, to_replace=None, value=None, inplace=False,
limit=None, regex=False, method='pad', axis=None) | Replace values given in 'to_replace' with 'value'.
Wrapper around the :meth:`pandas.DataFrame.replace` method. | 1.712892 | 1.856213 | 0.922789 |
if drop is True:
try:
assert type(keys) is not str
dropped_cols = set(keys)
except (TypeError, AssertionError):
dropped_cols = set([keys])
if not self._required_cols <= (set(self.columns) - set(dropped_cols)):
... | def set_index(self, keys, drop=True, append=False,
inplace=False, verify_integrity=False) | Set the DataFrame index (row labels) using one or more existing
columns.
Wrapper around the :meth:`pandas.DataFrame.set_index` method. | 4.006515 | 4.373435 | 0.916102 |
if not isinstance(other, self.__class__):
raise ValueError('May only append instances of same type.')
if type(ignore_index) is bool:
new_frame = self._frame.append(other._frame,
ignore_index=ignore_index,
... | def append(self, other, ignore_index=False) | Append rows of `other` to the end of this frame, returning a new object.
Wrapper around the :meth:`pandas.DataFrame.append` method.
Args:
other (Cartesian):
ignore_index (sequence, bool, int): If it is a boolean, it
behaves like in the description of
... | 2.209062 | 2.17174 | 1.017185 |
return self.__class__(self._frame.apply(*args, **kwargs),
metadata=self.metadata,
_metadata=self._metadata) | def apply(self, *args, **kwargs) | Applies function along input axis of DataFrame.
Wrapper around the :meth:`pandas.DataFrame.apply` method. | 5.751563 | 5.265374 | 1.092337 |
return self.__class__(self._frame.applymap(*args, **kwargs),
metadata=self.metadata,
_metadata=self._metadata) | def applymap(self, *args, **kwargs) | Applies function elementwise
Wrapper around the :meth:`pandas.DataFrame.applymap` method. | 4.728057 | 4.657942 | 1.015053 |
endDate = end or date.today()
if type(endDate) is not date:
endDate = parse_date(end)
startDate = start or endDate - timedelta(30)
if type(startDate) is not date:
startDate = parse_date(start)
# If the user passes in a string as "articles", conv... | def article_views(
self, project, articles,
access='all-access', agent='all-agents', granularity='daily',
start=None, end=None) | Get pageview counts for one or more articles
See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\
#!/Pageviews_data/get_metrics_pageviews_per_article_project\\
_access_agent_article_granularity_start_end>`_
:Parameters:
project : str
... | 3.610172 | 3.225587 | 1.119229 |
endDate = end or date.today()
if type(endDate) is not date:
endDate = parse_date(end)
startDate = start or endDate - timedelta(30)
if type(startDate) is not date:
startDate = parse_date(start)
urls = [
'/'.join([
endp... | def project_views(
self, projects,
access='all-access', agent='all-agents', granularity='daily',
start=None, end=None) | Get pageview counts for one or more wikimedia projects
See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\
#!/Pageviews_data/get_metrics_pageviews_aggregate_project\\
_access_agent_granularity_start_end>`_
:Parameters:
project : list(str)
... | 3.178402 | 2.954655 | 1.075727 |
yesterday = date.today() - timedelta(days=1)
year = str(year or yesterday.year)
month = str(month or yesterday.month).rjust(2, '0')
day = str(day or yesterday.day).rjust(2, '0')
url = '/'.join([endpoints['top'], project, access, year, month, day])
try:
... | def top_articles(
self, project, access='all-access',
year=None, month=None, day=None, limit=1000) | Get pageview counts for one or more articles
See `<https://wikimedia.org/api/rest_v1/metrics/pageviews/?doc\\
#!/Pageviews_data/get_metrics_pageviews_top_project\\
_access_year_month_day>`_
:Parameters:
project : str
a wikimedia project such a... | 3.210625 | 3.214612 | 0.99876 |
if isinstance(excludes, six.string_types):
excludes = [excludes]
if excludes and only:
only = None
elif isinstance(only, six.string_types):
only = [only]
field_definition = {}
for col in model.__table__.columns:
if only:
if col.name not in only:
... | def marshal_with_model(model, excludes=None, only=None, extends=None) | With this decorator, you can return ORM model instance, or ORM query in view function directly.
We'll transform these objects to standard python data structures, like Flask-RESTFul's `marshal_with` decorator.
And, you don't need define fields at all.
You can specific columns to be returned, by `excludes` o... | 2.666892 | 2.818729 | 0.946133 |
@marshal_with_model(*args, **kwargs)
def fn(value):
return value
return fn | def quick_marshal(*args, **kwargs) | In some case, one view functions may return different model in different situation.
Use `marshal_with_model` to handle this situation was tedious.
This function can simplify this process.
Usage:
quick_marshal(args_to_marshal_with_model)(db_instance_or_query) | 8.437459 | 5.926615 | 1.423656 |
class WrappedField(field):
def output(self, key, obj):
value = _fields.get_value(key if self.attribute is None else self.attribute, obj)
# For all fields, when its value was null (None), return null directly,
# instead of return its default value (eg. int type's de... | def _wrap_field(field) | Improve Flask-RESTFul's original field type | 12.633897 | 11.027902 | 1.14563 |
doi = '10.7910/DVN/AFJNWJ'
fname = os.path.join(
data_dir(),
'lenz2017',
'ebv_lhd.hpx.fits')
fetch_utils.dataverse_download_doi(
doi, fname,
file_requirements={'filename': 'ebv_lhd.hpx.fits'}) | def fetch() | Downloads the Lenz, Hensley & Doré (2017) dust map, placing it in the
default :obj:`dustmaps` data directory. | 12.502939 | 10.921 | 1.144853 |
return super(Lenz2017Query, self).query(coords, **kwargs) | def query(self, coords, **kwargs) | Returns E(B-V), in mags, at the specified location(s) on the sky.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The coordinates to query.
Returns:
A float array of the reddening, in magnitudes of E(B-V), at the
selected coordinates. | 11.782783 | 18.322353 | 0.643082 |
config = configparser.ConfigParser()
config.read_dict(settings)
if os.path.isfile(filepath) and not overwrite:
try:
raise FileExistsError
except NameError: # because of python2
warn('File exists already and overwrite is False (default).')
else:
with... | def write_configuration_file(filepath=_give_default_file_path(),
overwrite=False) | Create a configuration file.
Writes the current state of settings into a configuration file.
.. note:: Since a file is permamently written, this function
is strictly speaking not sideeffect free.
Args:
filepath (str): Where to write the file.
The default is under both UNIX and... | 3.305232 | 3.859884 | 0.856303 |
config = configparser.ConfigParser()
config.read(filepath)
def get_correct_type(section, key, config):
def getstring(section, key, config):
return config[section][key]
def getinteger(section, key, config): # pylint:disable=unused-variable
return confi... | def read_configuration_file(filepath=_give_default_file_path()) | Read the configuration file.
.. note:: This function changes ``cc.settings`` inplace and is
therefore not sideeffect free.
Args:
filepath (str): Where to read the file.
The default is under both UNIX and Windows ``~/.chemcoordrc``.
Returns:
None: | 2.696579 | 2.890469 | 0.932921 |
'''Short-form of the unit title, excluding any unit date, as an instance
of :class:`~eulxml.xmlmap.eadmap.UnitTitle` . Can be used with formatting
anywhere the full form of the unittitle can be used.'''
# if there is no unitdate to remove, just return the current object
if not se... | def short(self) | Short-form of the unit title, excluding any unit date, as an instance
of :class:`~eulxml.xmlmap.eadmap.UnitTitle` . Can be used with formatting
anywhere the full form of the unittitle can be used. | 9.519983 | 3.743998 | 2.542732 |
if self.c and self.c[0] and ((self.c[0].level in ('series', 'subseries')) or
(self.c[0].c and self.c[0].c[0])):
return True
else:
return False | def hasSubseries(self) | Check if this component has subseries or not.
Determined based on level of first subcomponent (series or subseries)
or if first component has subcomponents present.
:rtype: boolean | 4.160464 | 3.334068 | 1.247864 |
if len(self.c) and (self.c[0].level == 'series' or (self.c[0].c and self.c[0].c[0])):
return True
else:
return False | def hasSeries(self) | Check if this finding aid has series/subseries.
Determined based on level of first component (series) or if first
component has subcomponents present.
:rtype: boolean | 4.505557 | 3.55499 | 1.26739 |
# FIXME: why is M_r passed?
arg_tuples = self.get_initialize_arg_tuples(
M_c, M_r, T, initialization, row_initialization, n_chains,
ROW_CRP_ALPHA_GRID, COLUMN_CRP_ALPHA_GRID, S_GRID, MU_GRID, N_GRID,
make_get_next_seed(seed),)
chain_tuples = self.map... | def initialize(
self, M_c, M_r, T, seed, initialization=b'from_the_prior',
row_initialization=-1, n_chains=1,
ROW_CRP_ALPHA_GRID=(), COLUMN_CRP_ALPHA_GRID=(),
S_GRID=(), MU_GRID=(), N_GRID=31,) | Sample a latent state from prior.
T, list of lists:
The data table in mapped representation (all floats, generated
by data_utils.read_data_objects)
:returns: X_L, X_D -- the latent state | 2.947965 | 2.972182 | 0.991852 |
if new_rows is None:
raise ValueError("new_row must exist")
if not isinstance(new_rows, list):
raise TypeError('new_rows must be list of lists')
if not isinstance(new_rows[0], list):
raise TypeError('new_rows must be list of lists')
... | def insert(
self, M_c, T, X_L_list, X_D_list, new_rows=None, N_GRID=31,
CT_KERNEL=0) | Insert mutates the data T. | 2.643679 | 2.579664 | 1.024815 |
get_next_seed = make_get_next_seed(seed)
samples = _do_simple_predictive_sample(
M_c, X_L, X_D, Y, Q, n, get_next_seed)
return samples | def simple_predictive_sample(self, M_c, X_L, X_D, Y, Q, seed, n=1) | Sample values from predictive distribution of the given latent state.
:param Y: A list of constraints to apply when sampling. Each constraint
is a triplet of (r, d, v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
... | 3.23559 | 4.48998 | 0.720625 |
return su.simple_predictive_probability(M_c, X_L, X_D, Y, Q) | def simple_predictive_probability(self, M_c, X_L, X_D, Y, Q) | Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r, d, v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
... | 3.366876 | 4.905819 | 0.686302 |
return su.simple_predictive_probability_multistate(
M_c, X_L_list, X_D_list, Y, Q) | def simple_predictive_probability_multistate(
self, M_c, X_L_list, X_D_list, Y, Q) | Calculate probability of a cell taking a value given a latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
:... | 2.449715 | 3.740523 | 0.654912 |
return su.predictive_probability(M_c, X_L, X_D, Y, Q) | def predictive_probability(self, M_c, X_L, X_D, Y, Q) | Calculate probability of cells jointly taking values given a
latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r, d, v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of ... | 3.641503 | 6.292725 | 0.578685 |
return su.predictive_probability_multistate(
M_c, X_L_list, X_D_list, Y, Q) | def predictive_probability_multistate(self, M_c, X_L_list, X_D_list, Y, Q) | Calculate probability of cells jointly taking values given a
latent state.
:param Y: A list of constraints to apply when querying. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of li... | 2.958004 | 4.431061 | 0.667561 |
get_next_seed = make_get_next_seed(seed)
return iu.mutual_information(
M_c, X_L_list, X_D_list, Q, get_next_seed, n_samples) | def mutual_information(
self, M_c, X_L_list, X_D_list, Q, seed, n_samples=1000) | Estimate mutual information for each pair of columns on Q given
the set of samples.
:param Q: List of tuples where each tuple contains the two column
indexes to compare
:type Q: list of two-tuples of ints
:param n_samples: the number of simple predictive samples to use
... | 2.918218 | 4.247055 | 0.687116 |
return su.row_structural_typicality(X_L_list, X_D_list, row_id) | def row_structural_typicality(self, X_L_list, X_D_list, row_id) | Returns the typicality (opposite of anomalousness) of given row.
:param row_id: id of the target row
:type row_id: int
:returns: float, the typicality, from 0 to 1 | 2.9594 | 4.007994 | 0.738374 |
return su.similarity(
M_c, X_L_list, X_D_list, given_row_id,
target_row_id, target_columns) | def similarity(
self, M_c, X_L_list, X_D_list, given_row_id, target_row_id,
target_columns=None) | Computes the similarity of the given row to the target row,
averaged over all the column indexes given by target_columns.
:param given_row_id: the id of one of the rows to measure similarity
between
:type given_row_id: int
:param target_row_id: the id of the other row to mea... | 2.558849 | 3.436225 | 0.744668 |
get_next_seed = make_get_next_seed(seed)
e = su.impute(M_c, X_L, X_D, Y, Q, n, get_next_seed)
return e | def impute(self, M_c, X_L, X_D, Y, Q, seed, n) | Impute values from predictive distribution of the given latent state.
:param Y: A list of constraints to apply when sampling. Each constraint
is a triplet of (r,d,v): r is the row index, d is the column
index and v is the value of the constraint
:type Y: list of lists
:... | 4.197209 | 5.966804 | 0.703427 |
get_next_seed = make_get_next_seed(seed)
if isinstance(X_L, (list, tuple)):
assert isinstance(X_D, (list, tuple))
# TODO: multistate impute doesn't exist yet
# e,confidence = su.impute_and_confidence_multistate(
# M_c, X_L, X_D, Y, Q, n, self.ge... | def impute_and_confidence(self, M_c, X_L, X_D, Y, Q, seed, n) | Impute values and confidence of the value from the predictive
distribution of the given latent state.
:param Y: A list of constraints to apply when sampling. Each constraint
is a triplet of (r, d, v): r is the row index, d is the column
index and v is the value of the constrain... | 2.60287 | 2.806098 | 0.927576 |
X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D)
if was_multistate:
num_states = len(X_L_list)
else:
num_states = 1
dependencies = [(c[0], c[1]) for c in dep_constraints if c[2]]
independencies = [(c[0], c[1]) for c in dep_con... | def ensure_col_dep_constraints(
self, M_c, M_r, T, X_L, X_D, dep_constraints,
seed, max_rejections=100) | Ensures dependencey or indepdendency between columns.
`dep_constraints` is a list of where each entry is an (int, int, bool)
tuple where the first two entries are column indices and the third entry
describes whether the columns are to be dependent (True) or independent
(False).
... | 2.348251 | 2.235382 | 1.050492 |
X_L_list, X_D_list, was_multistate = su.ensure_multistate(X_L, X_D)
if force:
raise NotImplementedError
else:
kernel_list = ('row_partition_assignements',)
for i, (X_L_i, X_D_i) in enumerate(zip(X_L_list, X_D_list)):
iters = 0
... | def ensure_row_dep_constraint(
self, M_c, T, X_L, X_D, row1, row2, dependent=True, wrt=None,
max_iter=100, force=False) | Ensures dependencey or indepdendency between rows with respect to
columns. | 2.960057 | 3.006206 | 0.984649 |
m = _parse_format_specifier_regex.match(specification)
if m is None:
raise ValueError(
"Invalid format specifier: {!r}".format(specification))
format_dict = m.groupdict('')
# Convert zero-padding into fill and alignment.
zeropad = format_dict.pop('zeropad')
if zeropad:
... | def parse_format_specifier(specification) | Parse the given format specification and return a dictionary
containing relevant values. | 2.4633 | 2.451624 | 1.004763 |
padding = spec['fill'] * (spec['minimumwidth'] - len(sign) - len(body))
align = spec['align']
if align == '<':
result = sign + body + padding
elif align == '>':
result = padding + sign + body
elif align == '=':
result = sign + padding + body
elif align == '^':
... | def format_align(sign, body, spec) | Given an unpadded, non-aligned numeric string 'body' and sign
string 'sign', add padding and alignment conforming to the given
format specifier dictionary 'spec' (as produced by
parse_format_specifier). | 2.652064 | 2.549508 | 1.040226 |
cols = ['x', 'y', 'z']
out = self.copy()
def get_subs_f(*args):
def subs_function(x):
if hasattr(x, 'subs'):
x = x.subs(*args)
try:
x = float(x)
except TypeError:
... | def subs(self, *args) | Substitute a symbolic expression in ``['x', 'y', 'z']``
This is a wrapper around the substitution mechanism of
`sympy <http://docs.sympy.org/latest/tutorial/basic_operations.html>`_.
Any symbolic expression in the columns
``['x', 'y', 'z']`` of ``self`` will be substituted
with ... | 3.028463 | 3.16925 | 0.955577 |
n = pos.shape[0]
bond_array = np.empty((n, n), dtype=nb.boolean)
for i in range(n):
for j in range(i, n):
D = 0
for h in range(3):
D += (pos[i, h] - pos[j, h])**2
B = (bond_radii[i] + bond_radii[j])**2
... | def _jit_give_bond_array(pos, bond_radii, self_bonding_allowed=False) | Calculate a boolean array where ``A[i,j] is True`` indicates a
bond between the i-th and j-th atom. | 1.94141 | 1.89964 | 1.021988 |
assert (isinstance(bond_dict, collections.defaultdict)
or bond_dict is None)
fragment_indices = list(fragment_indices)
if convert_index is None:
convert_index = dict(enumerate(fragment_indices))
if bond_dict is None:
bond_dict = collection... | def _update_bond_dict(self, fragment_indices,
positions,
bond_radii,
bond_dict=None,
self_bonding_allowed=False,
convert_index=None) | If bond_dict is provided, this function is not side effect free
bond_dict has to be a collections.defaultdict(set) | 2.49172 | 2.290191 | 1.087997 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.