code stringlengths 52 7.75k | docs stringlengths 1 5.85k |
|---|---|
def calculate_merkle_pairs(bin_hashes, hash_function=bin_double_sha256):
hashes = list(bin_hashes)
# if there are an odd number of hashes, double up the last one
if len(hashes) % 2 == 1:
hashes.append(hashes[-1])
new_hashes = []
for i in range(0, len(hashes), 2):
new_hashes.ap... | Calculate the parents of a row of a merkle tree.
Takes in a list of binary hashes, returns a binary hash.
The returned parents list is such that parents[i] == hash(bin_hashes[2*i] + bin_hashes[2*i+1]). |
def verify_merkle_path(merkle_root_hex, serialized_path, leaf_hash_hex, hash_function=bin_double_sha256):
merkle_root = hex_to_bin_reversed(merkle_root_hex)
leaf_hash = hex_to_bin_reversed(leaf_hash_hex)
path = MerkleTree.path_deserialize(serialized_path)
path = [{'order': p['order'], 'hash':... | Verify a merkle path. The given path is the path from two leaf nodes to the root itself.
merkle_root_hex is a little-endian, hex-encoded hash.
serialized_path is the serialized merkle path
path_hex is a list of little-endian, hex-encoded hashes.
Return True if the path is consistent with the merkle r... |
def path_serialize(cls, path):
# make it into a netstring
path_parts = ['{}-{}'.format(p['order'], p['hash']) for p in path]
path_ns_parts = ['{}:{},'.format(len(pp), pp) for pp in path_parts]
path_str = ''.join(path_ns_parts)
return '{}:{},'.format(len(path_str), path_s... | Given a list of [{'hash': ..., 'order': ...}], serialize it to a string. |
def path_deserialize(cls, serialized_path):
def _chomp_netstring_payload(s):
try:
ns_len_str, ns_body = s.split(':', 1)
ns_len = int(ns_len_str)
assert ns_body[ns_len] == ','
ns_payload = ns_body[:ns_len]
return... | Given a netstring of path parts, go and parse it back into [{'hash': ..., 'order': ...}] |
def _coords2vec(self, coords):
# c = coords.transform_to(self._frame)
# vec = np.empty((c.shape[0], 2), dtype='f8')
# vec[:,0] = coordinates.Longitude(coords.l, wrap_angle=360.*units.deg).deg[:]
# vec[:,1] = coords.b.deg[:]
# return np.radians(vec)
c = coords.t... | Converts from sky coordinates to unit vectors. Before conversion to unit
vectors, the coordiantes are transformed to the coordinate system used
internally by the :obj:`UnstructuredDustMap`, which can be set during
initialization of the class.
Args:
coords (:obj:`astropy.coor... |
def _coords2idx(self, coords):
x = self._coords2vec(coords)
idx = self._kd.query(x, p=self._metric_p,
distance_upper_bound=self._max_pix_scale)
return idx[1] | Converts from sky coordinates to pixel indices.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): Sky coordinates.
Returns:
Pixel indices of the coordinates, with the same shape as the input
coordinates. Pixels which are outside the map are given an index
... |
def _gal2idx(self, gal):
# Make sure that l is in domain [-180 deg, 180 deg)
l = coordinates.Longitude(gal.l, wrap_angle=180.*units.deg)
j = (self._inv_pix_scale * (l.deg - self._l_bounds[0])).astype('i4')
k = (self._inv_pix_scale * (gal.b.deg - self._b_bounds[0])).astype('i4'... | Converts from Galactic coordinates to pixel indices.
Args:
gal (:obj:`astropy.coordinates.SkyCoord`): Galactic coordinates. Must
store an array of coordinates (i.e., not be scalar).
Returns:
``j, k, mask`` - Pixel indices of the coordinates, as well as a mask
... |
def add_block_hash( self, block_hash ):
if len(self.block_hashes) > 2000:
raise Exception("A getheaders request cannot have over 2000 block hashes")
hash_num = int("0x" + block_hash, 16)
bh = BlockHash()
bh.block_hash = hash_num
self.block_hashes.a... | Append up to 2000 block hashes for which to get headers. |
def run( self ):
self.handshake()
try:
self.loop()
except socket.error, se:
if self.finished:
return True
else:
raise | Interact with the blockchain peer,
until we get a socket error or we
exit the loop explicitly.
Return True on success
Raise on error |
def send_getheaders( self, prev_block_hash ):
getheaders = GetHeaders()
getheaders.add_block_hash( prev_block_hash )
log.debug("send getheaders")
self.send_message( getheaders ) | Request block headers from a particular block hash.
Will receive up to 2000 blocks, starting with the block *after*
the given block hash (prev_block_hash) |
def handle_version(self, message_header, message):
log.debug("handle version")
verack = VerAck()
log.debug("send VerAck")
self.send_message(verack)
self.verack = True
# begin!
self.send_getheaders( self.first_block_hash ) | This method will handle the Version message and
will send a VerAck message when it receives the
Version message.
:param message_header: The Version message header
:param message: The Version message |
def handle_ping(self, message_header, message):
log.debug("handle ping")
pong = Pong()
pong.nonce = message.nonce
log.debug("send pong")
self.send_message(pong) | This method will handle the Ping message and then
will answer every Ping message with a Pong message
using the nonce received.
:param message_header: The header of the Ping message
:param message: The Ping message |
def init(cls, path):
if not os.path.exists( path ):
block_header_serializer = BlockHeaderSerializer()
genesis_block_header = BlockHeader()
if USE_MAINNET:
# we know the mainnet block header
# but we don't know the testnet/regtest blo... | Set up an SPV client.
If the locally-stored headers do not exist, then
create a stub headers file with the genesis block information. |
def height(cls, path):
if os.path.exists( path ):
sb = os.stat( path )
h = (sb.st_size / BLOCK_HEADER_SIZE) - 1
return h
else:
return None | Get the locally-stored block height |
def read_header_at( cls, f):
header_parser = BlockHeaderSerializer()
hdr = header_parser.deserialize( f )
h = {}
h['version'] = hdr.version
h['prev_block_hash'] = "%064x" % hdr.prev_block
h['merkle_root'] = "%064x" % hdr.merkle_root
h['timestamp'] = hdr.t... | Given an open file-like object, read a block header
from it and return it as a dict containing:
* version (int)
* prev_block_hash (hex str)
* merkle_root (hex str)
* timestamp (int)
* bits (int)
* nonce (ini)
* hash (hex str) |
def load_header_chain( cls, chain_path ):
header_parser = BlockHeaderSerializer()
chain = []
height = 0
with open(chain_path, "rb") as f:
h = SPVClient.read_header_at( f )
h['block_height'] = height
height += 1
chain.append(h)
... | Load the header chain from disk.
Each chain element will be a dictionary with:
* |
def read_header(cls, headers_path, block_height, allow_none=False):
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
... | Get a block header at a particular height from disk.
Return the header if found
Return None if not. |
def get_target(cls, path, index, chain=None):
if chain is None:
chain = [] # Do not use mutables as default values!
max_target = 0x00000000FFFF0000000000000000000000000000000000000000000000000000
if index == 0:
return 0x1d00ffff, max_target
first = SPV... | Calculate the target difficulty at a particular difficulty interval (index).
Return (bits, target) on success |
def block_header_verify( cls, headers_path, block_id, block_hash, block_header ):
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 ) | 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... |
def block_verify( cls, verified_block_header, block_txids ):
block_data = {
'merkleroot': verified_block_header['merkleroot'],
'tx': block_txids
}
return bits.block_verify( block_data ) | 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. |
def tx_hash( cls, tx ):
tx_hex = bits.btc_bitcoind_tx_serialize( tx )
tx_hash = hashing.bin_double_sha256(tx_hex.decode('hex'))[::-1].encode('hex')
return tx_hash | Calculate the hash of a transction structure given by bitcoind |
def tx_verify( cls, verified_block_txids, tx ):
tx_hash = cls.tx_hash( tx )
return tx_hash in verified_block_txids | 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... |
def tx_index( cls, verified_block_txids, verified_tx ):
tx_hash = cls.tx_hash( verified_tx )
return verified_block_txids.index( tx_hash ) | 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)? |
def block_header_index( cls, path, block_header ):
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:
... | 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 |
def verify_header_chain(cls, path, chain=None):
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 ... | Verify that a given chain of block headers
has sufficient proof of work. |
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
'''
time_tuple = email.utils.parsedate_tz(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 |
def IEEEContext(bitwidth):
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... | 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.... |
def view(molecule, viewer=settings['defaults']['viewer'], use_curr_dir=False):
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('Argume... | 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... |
def to_molden(cartesian_list, buf=None, sort_index=True,
overwrite=True, float_format='{:.6f}'.format):
if sort_index:
cartesian_list = [molecule.sort_index() for molecule in cartesian_list]
give_header = ("[MOLDEN FORMAT]\n"
+ "[N_GEO]\n"
+ str(... | 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... |
def write_molden(*args, **kwargs):
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) | Deprecated, use :func:`~chemcoord.xyz_functions.to_molden` |
def read_molden(inputfile, start_index=0, get_bonds=True):
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... | Read a molden file.
Args:
inputfile (str):
start_index (int):
Returns:
list: A list containing :class:`~chemcoord.Cartesian` is returned. |
def isclose(a, b, align=False, rtol=1.e-5, atol=1.e-8):
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)
... | 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... |
def allclose(a, b, align=False, rtol=1.e-5, atol=1.e-8):
return np.alltrue(isclose(a, b, align=align, rtol=rtol, atol=atol)) | 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... |
def concat(cartesians, ignore_index=False, keys=None):
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... | 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
... |
def dot(A, B):
try:
result = A.__matmul__(B)
if result is NotImplemented:
result = B.__rmatmul__(A)
except AttributeError:
result = B.__rmatmul__(A)
return result | 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: |
def get_rotation_matrix(axis, angle):
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) | 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): |
def _jit_get_rotation_matrix(axis, angle):
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)
ro... | 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): |
def orthonormalize_righthanded(basis):
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 | 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... |
def get_kabsch_rotation(Q, P):
# 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 =... | 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... |
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:... | 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 ... |
def pop(self, i=None):
if i is None:
i = len(self) - 1
val = self[i]
del(self[i])
return val | 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. |
def insert(self, i, x):
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_... | Insert an item (x) at a given position (i). |
def get_field(self, schema):
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:
... | 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` |
def roundrobin(*iterables):
"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 Sto... | roundrobin('ABC', 'D', 'EF') --> A D E B F C |
def get_scc_from_tuples(constraints):
classes = unionfind.classes(constraints)
return dict((x, tuple(c)) for x, c in classes.iteritems()) | 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),
} |
def _parse_field_list(fieldnames, include_parents=False):
field_parts = (name.split('.') for name in fieldnames)
return _collect_fields(field_parts, include_parents) | 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... |
def _collect_fields(field_parts_list, include_parents):
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)
... | utility function to enable recursion in _parse_field_list() |
def xmlobject_to_dict(instance, fields=None, exclude=None, prefix=''):
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... | 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
... |
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):
attrs = {'model': model}
if fields is not None:
attrs['fields'] = fields
if... | Dynamically generate a new :class:`XmlObjectForm` class using the
specified :class:`eulxml.xmlmap.XmlObject` class.
Based on django's modelform_factory. |
def update_instance(self):
# 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 ... | Save bound form data into the XmlObject model instance and return the
updated instance. |
def _update_subinstance(self, name, subform):
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... | Save bound data for a single subform into the XmlObject model
instance. |
def is_valid(self):
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,
... | 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... |
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
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):
... | 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. |
def connect_bitcoind_impl( bitcoind_opts ):
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['bitcoi... | Create a connection to bitcoind, using a dict of config options. |
def get_bitcoind_client(config_path=None, bitcoind_opts=None):
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['bi... | Connect to bitcoind |
def ecdsa_private_key(privkey_str=None, compressed=None):
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) | Make a private key, but enforce the following rule:
* unless the key's hex encoding specifically ends in '01', treat it as uncompressed. |
def ecdsa_public_key(pubkey_str, compressed=None):
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) | 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 |
def set_privkey_compressed(privkey, compressed=True):
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:
... | Make sure the private key given is compressed or not compressed |
def get_pubkey_hex( privatekey_hex ):
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':
rais... | Get the uncompressed hex form of a private key |
def get_uncompressed_private_and_public_keys( privkey_str ):
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[... | Get the private and public keys from a private key string.
Make sure the both are *uncompressed* |
def decode_privkey_hex(privkey_hex):
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'"... | Decode a private key for ecdsa signature |
def decode_pubkey_hex(pubkey_hex):
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... | Decode a public key for ecdsa verification |
def encode_signature(sig_r, sig_s):
# 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)
re... | Encode an ECDSA signature, with low-s |
def decode_signature(sigb64):
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 | Decode a signature into r, s |
def sign_raw_data(raw_data, privatekey_hex):
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() | Sign a string of data.
Returns signature as a base64 string |
def verify_raw_data(raw_data, pubkey_hex, sigb64):
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() | Verify the signature over a string, given the public key
and base64-encode signature.
Return True on success.
Return False on error. |
def sign_digest(hash_hex, privkey_hex, hashfunc=hashlib.sha256):
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())... | Given a digest and a private key, sign it.
Return the base64-encoded signature |
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
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(... | 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 |
def finalize(self):
signature = self.signer.finalize()
sig_r, sig_s = decode_dss_signature(signature)
sig_b64 = encode_signature(sig_r, sig_s)
return sig_b64 | Get the base64-encoded signature itself.
Can only be called once. |
def update(self, data):
try:
self.verifier.update(data)
except TypeError:
log.error("Invalid data: {} ({})".format(type(data), data))
raise | Update the hash used to generate the signature |
def semiconvergents(x):
(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 = ... | Semiconvergents of continued fraction expansion of a Fraction x. |
def logn2(n, p):
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(... | Best p-bit lower and upper bounds for log(2)/log(n), as Fractions. |
def sort_values(self, by, axis=0, ascending=True, inplace=False,
kind='quicksort', na_position='last'):
if inplace:
self._frame.sort_values(
by, axis=axis, ascending=ascending,
inplace=inplace, kind=kind, na_position=na_position)
e... | Sort by the values along either axis
Wrapper around the :meth:`pandas.DataFrame.sort_values` method. |
def replace(self, to_replace=None, value=None, inplace=False,
limit=None, regex=False, method='pad', axis=None):
if inplace:
self._frame.replace(to_replace=to_replace, value=value,
inplace=inplace, limit=limit, regex=regex,
... | Replace values given in 'to_replace' with 'value'.
Wrapper around the :meth:`pandas.DataFrame.replace` method. |
def set_index(self, keys, drop=True, append=False,
inplace=False, verify_integrity=False):
if drop is True:
try:
assert type(keys) is not str
dropped_cols = set(keys)
except (TypeError, AssertionError):
dropped_c... | Set the DataFrame index (row labels) using one or more existing
columns.
Wrapper around the :meth:`pandas.DataFrame.set_index` method. |
def append(self, other, ignore_index=False):
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,
ignor... | 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
... |
def apply(self, *args, **kwargs):
return self.__class__(self._frame.apply(*args, **kwargs),
metadata=self.metadata,
_metadata=self._metadata) | Applies function along input axis of DataFrame.
Wrapper around the :meth:`pandas.DataFrame.apply` method. |
def applymap(self, *args, **kwargs):
return self.__class__(self._frame.applymap(*args, **kwargs),
metadata=self.metadata,
_metadata=self._metadata) | Applies function elementwise
Wrapper around the :meth:`pandas.DataFrame.applymap` method. |
def top_articles(
self, project, access='all-access',
year=None, month=None, day=None, limit=1000):
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 yester... | 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... |
def quick_marshal(*args, **kwargs):
@marshal_with_model(*args, **kwargs)
def fn(value):
return value
return fn | 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) |
def _wrap_field(field):
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 ... | Improve Flask-RESTFul's original field type |
def fetch():
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'}) | Downloads the Lenz, Hensley & Doré (2017) dust map, placing it in the
default :obj:`dustmaps` data directory. |
def query(self, coords, **kwargs):
return super(Lenz2017Query, self).query(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. |
def write_configuration_file(filepath=_give_default_file_path(),
overwrite=False):
config = configparser.ConfigParser()
config.read_dict(settings)
if os.path.isfile(filepath) and not overwrite:
try:
raise FileExistsError
except NameError: # bec... | 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... |
def read_configuration_file(filepath=_give_default_file_path()):
config = configparser.ConfigParser()
config.read(filepath)
def get_correct_type(section, key, config):
"""Gives e.g. the boolean True for the string 'True'"""
def getstring(section, key, config):
return config... | 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: |
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.'''
# if there is no unitdate to remove, just return the current object
... | 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. |
def hasSubseries(self):
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 | 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 |
def hasSeries(self):
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 | 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 |
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,):
# FIXME: why is M_r passed?
arg_tuples = self.get_in... | 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 |
def insert(
self, M_c, T, X_L_list, X_D_list, new_rows=None, N_GRID=31,
CT_KERNEL=0):
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 ... | Insert mutates the data T. |
def simple_predictive_sample(self, M_c, X_L, X_D, Y, Q, seed, n=1):
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 | 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
... |
def simple_predictive_probability(self, M_c, X_L, X_D, Y, Q):
return su.simple_predictive_probability(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
... |
def simple_predictive_probability_multistate(
self, M_c, X_L_list, X_D_list, Y, Q):
return su.simple_predictive_probability_multistate(
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
:... |
def predictive_probability(self, M_c, X_L, X_D, Y, Q):
return su.predictive_probability(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 ... |
def predictive_probability_multistate(self, M_c, X_L_list, X_D_list, Y, Q):
return su.predictive_probability_multistate(
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... |
def mutual_information(
self, M_c, X_L_list, X_D_list, Q, seed, n_samples=1000):
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) | 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
... |
def row_structural_typicality(self, X_L_list, X_D_list, row_id):
return su.row_structural_typicality(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 |
def similarity(
self, M_c, X_L_list, X_D_list, given_row_id, target_row_id,
target_columns=None):
return su.similarity(
M_c, X_L_list, X_D_list, given_row_id,
target_row_id, target_columns) | 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... |
def impute(self, M_c, X_L, X_D, Y, Q, seed, n):
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 | 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
:... |
def impute_and_confidence(self, M_c, X_L, X_D, Y, Q, seed, n):
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_confide... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.