code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if btc_is_singlesig(privkey_info):
# one signature produces a scriptsig of ~71 bytes (signature) + pubkey + encoding (4)
log.debug("Single private key makes a ~73 byte signature")
pubkey = ecdsa_private_key(privkey_info).public_key().to_hex().decode('hex')
return 71 + len(pubkey... | def tx_estimate_signature_len(privkey_info) | Estimate how long a signature is going to be, given a private key.
privkey_info is a private key or a multisig/segwit bundle.
This accounts for both the scriptsig and witness data. The return
value is the number of actual *bytes* (not vbytes) that the signature
will count for in bitcoin (i.e. witness ... | 2.971658 | 2.969109 | 1.000858 |
if isinstance(e, HTTPException) and not hasattr(e, 'data'):
e.data = dict(message=e.description)
return super(ErrorHandledApi, self).handle_error(e) | def handle_error(self, e) | Resolve the problem about sometimes error message specified by programmer won't output to user.
Flask-RESTFul's error handler handling format different exceptions has different behavior.
If we raise an normal Exception, it will raise it again.
If we report error by `restful.abort()`,
... | 4.092639 | 4.539009 | 0.901659 |
my_session_factory = SignedCookieSessionFactory('itsaseekreet')
# Add session engine
config = Configurator(
settings=settings,
session_factory=my_session_factory
)
# Add static and templates
config.add_static_view(name='static', path='static')
config.include('pyramid_jin... | def main(global_settings, **settings) | Entrypoint for WSGI app. | 4.492072 | 4.436671 | 1.012487 |
# if requests isn't available, warn and bail out
if requests is None:
sys.stderr.write(req_requests_msg)
return
# short-hand name of the schema, based on uri
schema = os.path.basename(uri)
try:
req = requests.get(uri, stream=True)
req.raise_for_status()
... | def download_schema(uri, path, comment=None) | Download a schema from a specified URI and save it locally.
:param uri: url where the schema should be downloaded
:param path: local file path where the schema should be saved
:param comment: optional comment; if specified, will be added to
the downloaded schema
:returns: true on success, false... | 3.063364 | 3.038679 | 1.008124 |
# if requests isn't available, warn and bail out
if requests is None:
sys.stderr.write(req_requests_msg)
return
logger.debug("Generating a new XML catalog")
if xsd_schemas is None:
xsd_schemas = XSD_SCHEMAS
if xmlcatalog_file is None:
xmlcatalog_file = XMLCATAL... | def generate_catalog(xsd_schemas=None, xmlcatalog_dir=None, xmlcatalog_file=None) | Generating an XML catalog for use in resolving schemas
Creates the XML Catalog directory if it doesn't already exist.
Uses :meth:`download_schema` to save local copies of schemas,
adding a comment indicating the date downloaded by eulxml.
Generates a new catalog.xml file, with entries for all schemas
... | 3.789271 | 3.511659 | 1.079054 |
start_block = config.get_first_block_id(impl)
try:
current_block = get_blockchain_height(blockchain_name, blockchain_client)
except Exception, e:
log.exception(e)
return None, None
saved_block = StateEngine.get_lastblock(impl, working_dir)
if saved_block is None:
... | def get_index_range(blockchain_name, blockchain_client, impl, working_dir) | Get the range of block numbers that we need to fetch from the blockchain.
Requires virtualchain to have been configured with setup_virtualchain() if impl=None
Return None, None if we fail to connect to the blockchain | 3.091794 | 3.228208 | 0.957743 |
# find sqlite3
path = os.environ.get("PATH", None)
if path is None:
path = "/usr/local/bin:/usr/bin:/bin"
sqlite3_path = None
dirs = path.split(":")
for pathdir in dirs:
if len(pathdir) == 0:
continue
sqlite3_path = os.path.join(pathdir, 'sqlite3')
... | def sqlite3_find_tool() | Find the sqlite3 binary
Return the path to the binary on success
Return None on error | 2.0506 | 2.004645 | 1.022924 |
# find sqlite3
sqlite3_path = sqlite3_find_tool()
if sqlite3_path is None:
log.error("Failed to find sqlite3 tool")
return False
sqlite3_cmd = [sqlite3_path, '{}'.format(src_path), '.backup "{}"'.format(dest_path)]
rc = None
backoff = 1.0
out = None
err = None
... | def sqlite3_backup(src_path, dest_path) | Back up a sqlite3 database, while ensuring
that no ongoing queries are being executed.
Return True on success
Return False on error. | 2.808323 | 2.794459 | 1.004962 |
assert new_state_engine.lastblock + 1 == block_height, 'Block height mismatch: {} + 1 != {}'.format(new_state_engine.lastblock, block_height)
db_con = StateEngine.db_open(existing_state_engine.impl, existing_state_engine.working_dir)
chainstate_block = existing_state_engine.db_chainstate_get_bloc... | def state_engine_replay_block(existing_state_engine, new_state_engine, block_height, expected_snapshots={}) | Extract the existing chain state transactions from the existing state engine at a particular block height,
parse them using the new state engine, and process them using the new state engine.
Returns the consensus hash of the block on success. | 2.931785 | 2.832187 | 1.035167 |
assert hasattr(consensus_impl, 'get_opcodes')
assert hasattr(consensus_impl, 'get_magic_bytes')
assert hasattr(consensus_impl, 'get_opfields')
assert hasattr(consensus_impl, 'get_first_block_id')
consensus_opcodes = consensus_impl.get_opcodes()
consensus_magic_bytes = consensus_impl.g... | def state_engine_replay(consensus_impl, existing_working_dir, new_state_engine, target_block_height, start_block=None, initial_snapshots={}, expected_snapshots={}) | Given consensus rules, a target block height, and a path to an existing chainstate db, replay the chain state's virtual transactions
through the consensus rules into a given directory (working_dir).
Optionally check that the snapshots in @expected_snapshots match up as we verify.
@expected_snapshots maps s... | 3.19169 | 3.008771 | 1.060795 |
assert hasattr(consensus_impl, 'get_initial_snapshots')
final_consensus_hash = state_engine_replay(consensus_impl, untrusted_working_dir, new_state_engine, consensus_block_height, \
start_block=start_block, initial_snapshots=consensus_impl.get_initial_sn... | def state_engine_verify(trusted_consensus_hash, consensus_block_height, consensus_impl, untrusted_working_dir, new_state_engine, start_block=None, expected_snapshots={}) | Verify that a database is consistent with a
known-good consensus hash.
This algorithm works by creating a new database,
parsing the untrusted database, and feeding the untrusted
operations into the new database block-by-block. If we
derive the same consensus hash, then we can trust the
databas... | 3.321831 | 3.310556 | 1.003406 |
if self.db_exists(impl=self.impl, working_dir=self.working_dir):
# resuming from previous indexing
# read/write and unclean shutdown?
if not self.read_only and self.db_is_indexing(self.impl, self.working_dir):
log.error("Unclean shutdown detected on r... | def db_setup(self) | Set up the state engine database.
* If it doesn't exist, then create it.
* If it does exist, then check that it is in a clean state. If not, then recover from a known-good backup.
Return True on success
Return False if there was an unclean shutdown. The caller should call db_restore()... | 5.565604 | 5.434572 | 1.024111 |
restored = False
if block_number is not None:
# restore a specific backup
try:
self.backup_restore(block_number, self.impl, self.working_dir)
restored = True
except AssertionError:
log.error("Failed to restore s... | def db_restore(self, block_number=None) | Restore the database and clear the indexing lockfile.
Restore to a given block if given; otherwise use the most recent valid backup.
Return True on success
Return False if there is no state to restore
Raise exception on error | 2.828976 | 2.704129 | 1.046169 |
path = config.get_snapshots_filename(impl, working_dir)
return os.path.exists(path) | def db_exists(cls, impl, working_dir) | Does the chainstate db exist? | 6.762079 | 5.829434 | 1.159989 |
global VIRTUALCHAIN_DB_SCRIPT
log.debug("Setup chain state in {}".format(working_dir))
path = config.get_snapshots_filename(impl, working_dir)
if os.path.exists( path ):
raise Exception("Database {} already exists")
lines = [l + ";" for l in VIRTUA... | def db_create(cls, impl, working_dir) | Create a sqlite3 db at the given path.
Create all the tables and indexes we need.
Returns a db connection on success
Raises an exception on error | 7.08157 | 6.786139 | 1.043534 |
con = sqlite3.connect(path, isolation_level=None, timeout=2**30)
con.row_factory = StateEngine.db_row_factory
return con | def db_connect(cls, path) | connect to our chainstate db | 5.859495 | 5.709423 | 1.026285 |
path = config.get_snapshots_filename(impl, working_dir)
return cls.db_connect(path) | def db_open(cls, impl, working_dir) | Open a connection to our chainstate db | 9.324426 | 10.022896 | 0.930313 |
timeout = 1.0
if verbose:
log.debug(cls.db_format_query(query, values))
while True:
try:
ret = cur.execute(query, values)
return ret
except sqlite3.OperationalError as oe:
if oe.message == "database is... | def db_query_execute(cls, cur, query, values, verbose=True) | Execute a query.
Handle db timeouts.
Abort on failure. | 2.513886 | 2.562005 | 0.981218 |
missing = []
extra = []
for reqfield in CHAINSTATE_FIELDS:
if reqfield not in fields:
missing.append(reqfield)
for fieldname in fields:
if fieldname not in CHAINSTATE_FIELDS:
extra.append(fieldname)
if len(missing... | def db_chainstate_append(cls, cur, **fields) | Insert a row into the chain state.
Meant to be executed as part of a transaction.
Return True on success
Raise an exception if the fields are invalid
Abort on db error. | 2.394173 | 2.365113 | 1.012287 |
query = 'INSERT INTO snapshots (block_id,consensus_hash,ops_hash,timestamp) VALUES (?,?,?,?);'
args = (block_id,consensus_hash,ops_hash,timestamp)
cls.db_query_execute(cur, query, args)
return True | def db_snapshot_append(cls, cur, block_id, consensus_hash, ops_hash, timestamp) | Append hash info for the last block processed, and the time at which it was done.
Meant to be executed as part of a transaction.
Return True on success
Raise an exception on invalid block number
Abort on db error | 2.448957 | 2.528583 | 0.96851 |
query = 'SELECT * FROM chainstate WHERE block_id = ? ORDER BY vtxindex;'
args = (block_height,)
rows = cls.db_query_execute(cur, query, args, verbose=False)
ret = []
for r in rows:
rowdata = {
'txid': str(r['txid']),
'block_i... | def db_chainstate_get_block(cls, cur, block_height) | Get the list of virtualchain transactions accepted at a given block.
Returns the list of rows, where each row is a dict. | 2.776914 | 2.631678 | 1.055188 |
indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir)
if is_indexing:
# make sure this exists
with open(indexing_lockfile_path, 'w') as f:
pass
else:
# make sure it does not exist
try:
o... | def db_set_indexing(cls, is_indexing, impl, working_dir) | Set lockfile path as to whether or not the system is indexing.
NOT THREAD SAFE, USE ONLY FOR CRASH DETECTION. | 3.418553 | 3.053265 | 1.119638 |
indexing_lockfile_path = config.get_lockfile_filename(impl, working_dir)
return os.path.exists(indexing_lockfile_path) | def db_is_indexing(cls, impl, working_dir) | Is the system indexing?
Return True if so, False if not. | 4.594527 | 4.466718 | 1.028614 |
if not cls.db_exists(impl, working_dir):
return None
con = cls.db_open(impl, working_dir)
query = 'SELECT MAX(block_id) FROM snapshots;'
rows = cls.db_query_execute(con, query, (), verbose=False)
ret = None
for r in rows:
ret = r... | def get_lastblock(cls, impl, working_dir) | What was the last block processed?
Return the number on success
Return None on failure to read | 3.444802 | 3.525099 | 0.977221 |
if (start_block_height is None and end_block_height is not None) or (start_block_height is not None and end_block_height is None):
raise ValueError("Need either both or neither start/end block height")
we_opened = False
if db_con is not None:
con = db_con
... | def get_consensus_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None, db_con=None, completeness_check=True) | Read all consensus hashes into memory. They're write-once read-many,
so no need to worry about cache-coherency. | 2.392167 | 2.350794 | 1.0176 |
if (start_block_height is None and end_block_height is not None) or (start_block_height is not None and end_block_height is None):
raise ValueError("Need either both or neither start/end block height")
con = cls.db_open(impl, working_dir)
range_query = ' WHERE ops_hash IS N... | def get_ops_hashes(cls, impl, working_dir, start_block_height=None, end_block_height=None) | Read all consensus hashes into memory. They're write-once read-many,
so no need to worry about cache-coherency. | 2.372572 | 2.307819 | 1.028058 |
return [config.get_db_filename(impl, working_dir), config.get_snapshots_filename(impl, working_dir)] | def get_state_paths(cls, impl, working_dir) | Get the set of state paths that point to the current chain and state info.
Returns a list of paths. | 5.662177 | 6.207909 | 0.912091 |
ret = []
backup_dir = config.get_backups_directory(impl, working_dir)
if not os.path.exists(backup_dir):
return []
for name in os.listdir( backup_dir ):
if ".bak." not in name:
continue
suffix = name.split(".bak.")[-1]
... | def get_backup_blocks(cls, impl, working_dir) | Get the set of block IDs that were backed up | 3.320893 | 3.272125 | 1.014904 |
backup_dir = config.get_backups_directory(impl, working_dir)
backup_paths = []
for p in cls.get_state_paths(impl, working_dir):
pbase = os.path.basename(p)
backup_path = os.path.join( backup_dir, pbase + (".bak.%s" % block_id))
backup_paths.append( ba... | def get_backup_paths(cls, block_id, impl, working_dir) | Get the set of backup paths, given the virtualchain implementation module and block number | 2.89073 | 3.066181 | 0.942778 |
backup_dir = config.get_backups_directory(impl, working_dir)
backup_paths = cls.get_backup_paths(block_id, impl, working_dir)
for p in backup_paths:
assert os.path.exists(p), "No such backup file: {}".format(p)
for p in cls.get_state_paths(impl, working_dir):
... | def backup_restore(cls, block_id, impl, working_dir) | Restore from a backup, given the virutalchain implementation module and block number.
NOT THREAD SAFE. DO NOT CALL WHILE INDEXING.
Return True on success
Raise exception on error, i.e. if a backup file is missing | 2.918696 | 3.032178 | 0.962574 |
assert self.setup, "Not set up yet. Call .db_setup() first!"
# make a backup?
if self.backup_frequency is not None:
if (block_id % self.backup_frequency) == 0:
backup_dir = config.get_backups_directory(self.impl, self.working_dir)
if not os... | def make_backups(self, block_id) | If we're doing backups on a regular basis, then
carry them out here if it is time to do so.
This method does nothing otherwise.
Return None on success
Abort on failure | 3.076943 | 3.033477 | 1.014329 |
assert self.setup, "Not set up yet. Call .db_setup() first!"
if self.backup_max_age is None:
# never delete backups
return
# find old backups
backup_dir = config.get_backups_directory(self.impl, self.working_dir)
if not os.path.exists(backup_... | def clear_old_backups(self, block_id) | If we limit the number of backups we make, then clean out old ones
older than block_id - backup_max_age (given in the constructor)
This method does nothing otherwise.
Return None on success
Raise exception on error | 3.254084 | 3.159671 | 1.029881 |
assert self.setup, "Not set up yet. Call .db_setup() first!"
assert len(accepted_ops) == len(virtualchain_ops_hints)
if self.read_only:
log.error("FATAL: StateEngine is read only")
traceback.print_stack()
os.abort()
if block_id < self.lastb... | def save(self, block_id, consensus_hash, ops_hash, accepted_ops, virtualchain_ops_hints, backup=False) | Write out all state to the working directory.
Calls the implementation's 'db_save' method to store any state for this block.
Calls the implementation's 'db_continue' method at the very end, to signal
to the implementation that all virtualchain state has been saved. This method
can retur... | 2.830966 | 2.698108 | 1.049241 |
record_hashes = []
for serialized_op in serialized_ops:
record_hash = bin_double_sha256( serialized_op ).encode('hex')
record_hashes.append(record_hash)
if len(record_hashes) == 0:
record_hashes.append(bin_double_sha256("").encode('hex'))
# ... | def make_ops_snapshot( cls, serialized_ops ) | Generate a deterministic hash over the sequence of (serialized) operations. | 3.639128 | 3.489096 | 1.043 |
# mix into previous consensus hashes...
all_hashes = prev_consensus_hashes[:] + [record_root_hash]
all_hashes.sort()
all_hashes_merkle_tree = MerkleTree( all_hashes )
root_hash = all_hashes_merkle_tree.root()
consensus_hash = StateEngine.calculate_consensus_hash... | def make_snapshot_from_ops_hash( cls, record_root_hash, prev_consensus_hashes ) | Generate the consensus hash from the hash over the current ops, and
all previous required consensus hashes. | 4.1548 | 3.957857 | 1.04976 |
record_root_hash = StateEngine.make_ops_snapshot( serialized_ops )
log.debug("Snapshot('{}', {})".format(record_root_hash, prev_consensus_hashes))
return (cls.make_snapshot_from_ops_hash( record_root_hash, prev_consensus_hashes ), record_root_hash) | def make_snapshot( cls, serialized_ops, prev_consensus_hashes ) | Generate a consensus hash, using the tx-ordered list of serialized name
operations, and a list of previous consensus hashes that contains
the (k-1)th, (k-2)th; (k-3)th; ...; (k - (2**i - 1))th consensus hashes,
all the way back to the beginning of time (prev_consensus_hashes[i] is the
... | 4.815557 | 5.316487 | 0.905778 |
fields = opfields.get( opcode, None )
if fields is None:
log.error("BUG: unrecongnized opcode '%s'" % opcode )
return None
all_values = []
debug_all_values = []
missing = []
for field in fields:
if not opdata.has_key(field):
... | def serialize_op( cls, opcode, opdata, opfields, verbose=True ) | Given an opcode (byte), associated data (dict), and the operation
fields to serialize (opfields), convert it
into its canonical serialized form (i.e. in order to
generate a consensus hash.
opdata is allowed to have extra fields. They will be ignored
Return the canonical form... | 3.234154 | 3.259636 | 0.992183 |
assert self.setup, "Not set up yet. Call .db_setup() first!"
log.debug("Snapshotting block {}".format(block_id))
serialized_ops = []
for opdata in oplist:
serialized_record = StateEngine.serialize_op(opdata['virtualchain_opcode'], opdata, self.opfi... | def snapshot(self, block_id, oplist) | Given the currnet block ID and the set of operations committed,
find the consensus hash that represents the state of the virtual chain.
The consensus hash is calculated as a Merkle skip-list. It incorporates:
* block K's operations
* block K - 1's consensus hash
* blo... | 4.684241 | 3.985984 | 1.175178 |
assert virtualchain_field in RESERVED_KEYS, 'Invalid field name {} (choose from {})'.format(virtualchain_field, ','.join(RESERVED_KEYS))
opdata[virtualchain_field] = value | def set_virtualchain_field(cls, opdata, virtualchain_field, value) | Set a virtualchain field value.
Used by implementations that generate extra consensus data at the end of a block | 4.038698 | 4.307889 | 0.937512 |
data_hex = tx['nulldata']
inputs = tx['ins']
outputs = tx['outs']
senders = tx['senders']
fee = tx['fee']
txhex = tx['hex']
merkle_path = tx['tx_merkle_path']
if not is_hex(data_hex):
# should always work; the tx down... | def parse_transaction(self, block_id, tx) | Given a block ID and an data-bearing transaction,
try to parse it into a virtual chain operation.
Use the implementation's 'db_parse' method to do so.
Data transactions that do not have the magic bytes or a valid opcode
will be skipped automatically. The db_parse method does ... | 3.247999 | 2.729384 | 1.190012 |
ops = []
for i in range(0,len(txs)):
tx = txs[i]
op = self.parse_transaction(block_id, tx)
if op is not None:
ops.append( op )
return ops | def parse_block(self, block_id, txs) | Given the sequence of transactions in a block, turn them into a
sequence of virtual chain operations.
Return the list of successfully-parsed virtualchain transactions | 2.856383 | 2.770512 | 1.030995 |
sanitized = {}
reserved = {}
for k in op.keys():
if str(k) not in RESERVED_KEYS:
sanitized[str(k)] = copy.deepcopy(op[k])
else:
reserved[str(k)] = copy.deepcopy(op[k])
return sanitized, reserved | def remove_reserved_keys(self, op) | Remove reserved keywords from an op dict,
which can then safely be passed into the db.
Returns a new op dict, and the reserved fields | 2.700595 | 2.665351 | 1.013223 |
log.debug("ACCEPT op {} at ({}, {}) ({})".format(opcode, block_id, vtxindex, json.dumps(op_data, sort_keys=True))) | def log_accept(self, block_id, vtxindex, opcode, op_data) | Log an accepted operation | 4.713516 | 4.959878 | 0.950329 |
log.debug("Process block {} ({} virtual transactions)".format(block_id, len(ops)))
if expected_snapshots is None:
expected_snapshots = self.expected_snapshots
if expected_snapshots is None:
expected_snapshots = {}
new_ops = self.process... | def process_block(self, block_id, ops, backup=False, expected_snapshots=None) | Top-level block processing method.
Feed the block and its data transactions
through the implementation, to build up the
implementation's state. Cache the
resulting data to disk.
Return the (consensus hash, ops hash) for this block on success.
Exit on failure. | 3.706294 | 3.477355 | 1.065837 |
if not os.environ.get("BLOCKSTACK_TEST"):
raise Exception("This method is only available in the test framework")
global STATISTICS
return STATISTICS.get(block_id) | def get_block_statistics(cls, block_id) | Get block statistics.
Only works in test mode. | 7.344985 | 6.18906 | 1.186769 |
first_block_id = state_engine.lastblock + 1
if first_block_id >= end_block_id:
# built
log.debug("Up-to-date ({} >= {})".format(first_block_id, end_block_id))
return True
rc = True
batch_size = config.BLOCK_BATCH_SIZE
log.de... | def build( cls, blockchain_opts, end_block_id, state_engine, expected_snapshots={}, tx_filter=None ) | Top-level call to process all blocks in the blockchain.
Goes and fetches all data-bearing transactions in order,
and feeds them into the state engine implementation.
Note that this method can take some time (hours, days) to complete
when called from the first block.
... | 3.209716 | 3.197444 | 1.003838 |
query = 'SELECT consensus_hash FROM snapshots WHERE block_id = ?;'
args = (block_id,)
con = self.db_open(self.impl, self.working_dir)
rows = self.db_query_execute(con, query, args, verbose=False)
res = None
for r in rows:
res = r['consensus_hash']
... | def get_consensus_at(self, block_id) | Get the consensus hash at a given block.
Return the consensus hash if we have one for this block.
Return None if we don't | 4.599611 | 4.726097 | 0.973237 |
query = 'SELECT block_id FROM snapshots WHERE consensus_hash = ?;'
args = (consensus_hash,)
con = self.db_open(self.impl, self.working_dir)
rows = self.db_query_execute(con, query, args, verbose=False)
res = None
for r in rows:
res = r['block_id']
... | def get_block_from_consensus( self, consensus_hash ) | Get the block number with the given consensus hash.
Return None if there is no such block. | 4.824414 | 4.632239 | 1.041486 |
first_block_to_check = block_id - self.impl.get_valid_transaction_window()
query = 'SELECT consensus_hash FROM snapshots WHERE block_id >= ? AND block_id <= ?;'
args = (first_block_to_check,block_id)
valid_consensus_hashes = []
con = self.db_open(self.impl, se... | def get_valid_consensus_hashes( self, block_id ) | Get the list of valid consensus hashes for a given block. | 3.715498 | 3.586327 | 1.036018 |
theta = np.radians(90. - b)
phi = np.radians(l)
if not hasattr(l, '__len__'):
if (b < -90.) or (b > 90.):
return -1
pix_idx = hp.pixelfunc.ang2pix(nside, theta, phi, nest=nest)
return pix_idx
idx = (b >= -90.) & (b <= 90.)
pix_idx = np.empty(l.shape, dt... | def lb2pix(nside, l, b, nest=True) | Converts Galactic (l, b) to HEALPix pixel index.
Args:
nside (:obj:`int`): The HEALPix :obj:`nside` parameter.
l (:obj:`float`, or array of :obj:`float`): Galactic longitude, in degrees.
b (:obj:`float`, or array of :obj:`float`): Galactic latitude, in degrees.
nest (Optional[:obj:`... | 2.066319 | 2.131292 | 0.969515 |
doi = {
'bayestar2015': '10.7910/DVN/40C44C',
'bayestar2017': '10.7910/DVN/LCYHJG'
}
# Raise an error if the specified version of the map does not exist
try:
doi = doi[version]
except KeyError as err:
raise ValueError('Version "{}" does not exist. Valid version... | def fetch(version='bayestar2017') | Downloads the specified version of the Bayestar dust map.
Args:
version (Optional[:obj:`str`]): The map version to download. Valid versions are
:obj:`'bayestar2017'` (Green, Schlafly, Finkbeiner et al. 2018) and
:obj:`'bayestar2015'` (Green, Schlafly, Finkbeiner et al. 2015). Defaul... | 3.644006 | 3.283268 | 1.109872 |
valid_modes = [
'random_sample',
'random_sample_per_pix',
'samples',
'median',
'mean',
'best',
'percentile']
if mode not in valid_modes:
raise ValueError(
'"{}" is not a valid `mode`... | def _raise_on_mode(self, mode) | Checks that the provided query mode is one of the accepted values. If
not, raises a :obj:`ValueError`. | 4.592226 | 4.430981 | 1.03639 |
'''
>>> _silent_none(12)
12
>>> _silent_none(True)
True
>>> _silent_none(None)
''
>>> _silent_none('')
''
>>> _silent_none(False)
False
>>> _silent_none('None')
''
>>> _silent_none("foooooooo")
'foooooooo'
'''
if value is None:
return ''
if... | def _silent_none(value) | >>> _silent_none(12)
12
>>> _silent_none(True)
True
>>> _silent_none(None)
''
>>> _silent_none('')
''
>>> _silent_none(False)
False
>>> _silent_none('None')
''
>>> _silent_none("foooooooo")
'foooooooo' | 2.278677 | 1.619136 | 1.407341 |
def set_jinja2_silent_none(config): # pragma: no cover
config.commit()
jinja2_env = config.get_jinja2_environment()
jinja2_env.finalize = _silent_none | if variable is None print '' instead of 'None' | null | null | null | |
assert mpfr.mpfr_regular_p(x)
assert mpfr.mpfr_regular_p(y)
# Make copy of x with the exponent of y.
x2 = mpfr.Mpfr_t()
mpfr.mpfr_init2(x2, mpfr.mpfr_get_prec(x))
mpfr.mpfr_set(x2, x, mpfr.MPFR_RNDN)
mpfr.mpfr_set_exp(x2, mpfr.mpfr_get_exp(y))
# Compare x2 and y, disregarding the ... | def _quotient_exponent(x, y) | Given two positive finite MPFR instances x and y,
find the exponent of x / y; that is, the unique
integer e such that 2**(e-1) <= x / y < 2**e. | 3.736409 | 3.598015 | 1.038464 |
# There are various cases:
#
# 0. If either argument is a NaN, the result is NaN.
#
# 1. If x is infinite or y is zero, the result is NaN.
#
# 2. If y is infinite, return 0 with the sign of y if x is zero, x if x has
# the same sign as y, and infinity with the sign of y if it has... | def mpfr_mod(rop, x, y, rnd) | Given two MPRF numbers x and y, compute
x - floor(x / y) * y, rounded if necessary using the given
rounding mode. The result is placed in 'rop'.
This is the 'remainder' operation, with sign convention
compatible with Python's % operator (where x % y has
the same sign as y). | 2.773199 | 2.753934 | 1.006995 |
if blockchain == 'bitcoin':
return btc_script_hex_to_address(script_hex, **blockchain_opts)
else:
raise ValueError("Unknown blockchain '{}'".format(blockchain)) | def script_hex_to_address( script_hex, blockchain='bitcoin', **blockchain_opts) | High-level API call (meant to be blockchain agnostic)
Examine a script (hex-encoded) and extract an address.
Return the address on success
Return None on error | 2.443998 | 2.703405 | 0.904044 |
if blockchain == 'bitcoin':
return btc_make_payment_script(address, **blockchain_opts)
else:
raise ValueError("Unknown blockchain '{}'".format(blockchain)) | def make_payment_script(address, blockchain='bitcoin', **blockchain_opts) | High-level API call (meant to be blockchain agnostic)
Make a pay-to-address script. | 2.710901 | 3.169548 | 0.855296 |
if blockchain == 'bitcoin':
return btc_make_data_script(data, **blockchain_opts)
else:
raise ValueError("Unknown blockchain '{}'".format(blockchain)) | def make_data_script( data, blockchain='bitcoin', **blockchain_opts) | High-level API call (meant to be blockchain agnostic)
Make a data-bearing transaction output.
Data must be a hex string
Returns a hex string. | 2.704895 | 3.175291 | 0.851857 |
ref_dict = {
# column_name: (
# (predicate, arg1, ... argN),
# ...
# )
}
for column_names, predicate_refs in validate_rule.items():
for column_name in _to_tuple(column_names):
ref_dict[column_name] = \
ref_dict.get(column_name, t... | def complex_validates(validate_rule) | Quickly setup attributes validation by one-time, based on `sqlalchemy.orm.validates`.
Don't like `sqlalchemy.orm.validates`, you don't need create many model method,
as long as pass formatted validate rule.
(Cause of SQLAlchemy's validate mechanism, you need assignment this funciton's return value
to a... | 4.666178 | 4.088142 | 1.141393 |
# only does validate when attribute value is not None
# else, just return it, let sqlalchemy decide if the value was legal according to `nullable` argument's value
if value is not None:
for predicate_ref in predicate_refs:
predicate, predicate_name, predicate_args = _decode_predica... | def _validate_handler(column_name, value, predicate_refs) | handle predicate's return value | 4.776683 | 4.573542 | 1.044417 |
count = 0
assert len(X_L_list) == len(X_D_list)
for X_L, X_D in zip(X_L_list, X_D_list):
for r in range(len(X_D[0])):
for c in range(
len(X_L['column_partition']['assignments'])):
if X_D[X_L['column_partition']['assignments'][c]][r] == \
... | def row_structural_typicality(X_L_list, X_D_list, row_id) | Returns how typical the row is (opposite of how anomalous). | 2.336208 | 2.340312 | 0.998247 |
count = 0
for X_L in X_L_list:
for c in range(len(X_L['column_partition']['assignments'])):
if X_L['column_partition']['assignments'][col_id] ==\
X_L['column_partition']['assignments'][c]:
count += 1
return float(count) / \
(len(X_L_list) ... | def column_structural_typicality(X_L_list, col_id) | Returns how typical column is (opposite of how anomalous). | 2.478038 | 2.457924 | 1.008183 |
logprobs = [float(simple_predictive_probability(M_c, X_L, X_D, Y, Q))
for X_L, X_D in zip(X_L_list, X_D_list)]
return logmeanexp(logprobs) | def simple_predictive_probability_multistate(M_c, X_L_list, X_D_list, Y, Q) | Returns the simple predictive probability, averaged over each sample. | 2.53986 | 2.648242 | 0.959074 |
logprobs = [float(predictive_probability(M_c, X_L, X_D, Y, Q))
for X_L, X_D in zip(X_L_list, X_D_list)]
return logmeanexp(logprobs) | def predictive_probability_multistate(M_c, X_L_list, X_D_list, Y, Q) | Returns the predictive probability, averaged over each sample. | 2.650561 | 2.747063 | 0.964871 |
score = 0.0
# Set col_idxs: defaults to all columns.
if target_column:
if type(target_column) == str:
col_idxs = [M_c['name_to_idx'][target_column]]
elif type(target_column) == list:
col_idxs = target_column
else:
col_idxs = [target_column]
... | def similarity(
M_c, X_L_list, X_D_list, given_row_id, target_row_id,
target_column=None) | Returns the similarity of the given row to the target row, averaged over
all the column indexes given by col_idxs.
Similarity is defined as the proportion of times that two cells are in the same
view and category. | 2.563736 | 2.506998 | 1.022632 |
if bh_dir is None:
bh_dir = os.path.join(data_dir_default, 'bh')
fname = os.path.join(bh_dir, '{}.ascii')
f = h5py.File('bh.h5', 'w')
for region in ('hinorth', 'hisouth'):
data = np.loadtxt(fname.format(region), dtype='f4')
# Reshape and clip
data.shape = (210, ... | def ascii2h5(bh_dir=None) | Convert the Burstein & Heiles (1982) dust map from ASCII to HDF5. | 3.704293 | 3.419902 | 1.083158 |
# gal = coords.transform_to('galactic')
gal = coords
l = gal.l.deg
b = gal.b.deg
# Detect scalar input
scalar_input = not hasattr(l, '__len__')
if scalar_input:
l = np.array([l])
b = np.array([b])
# Fill return array with... | def query(self, coords) | Returns E(B-V) at the specified location(s) on the sky.
Args:
coords (`astropy.coordinates.SkyCoord`): The coordinates to query.
Returns:
A float array of reddening, in units of E(B-V), at the given
coordinates. The shape of the output is the same as the sha... | 2.352057 | 2.312292 | 1.017197 |
print "\nreference implementation of db_parse\n"
return None | def db_parse( block_id, opcode, op_payload, senders, inputs, outputs, fee, db_state=None ) | Given the block ID, and information from what looks like
an OP_RETURN transaction that is part of the virtual chain, parse the
transaction's OP_RETURN nulldata into a dict.
Return the dict if this is a valid op.
Return None if not.
NOTE: the virtual chain indexer reserves all keys that start wi... | 29.568552 | 28.174431 | 1.049482 |
print "\nreference implementation of db_check\n"
return False | def db_check( block_id, opcode, op, txid, vtxindex, checked, db_state=None ) | Given the block ID and a parsed operation, check to see if this is a *valid* operation
for the purposes of this virtual chain's database.
Return True if so; False if not. | 28.537975 | 20.00149 | 1.426792 |
return {
'paginator': Page(
context.all,
url_maker=lambda p: request.path_url + "?page=%s" % p,
page=int(request.params.get('page', 1)),
items_per_page=6
)
} | def admin_docker_list_view(context, request) | Show list of docker images. | 4.529577 | 4.407359 | 1.02773 |
items_list = request.POST.getall('selected_item')
for item in items_list:
try:
context.cli.remove_image(item)
request.session.flash(["deleted {}".format(item), "success"])
except docker.errors.APIError as e:
request.session.flash([e.explanation, "error"])... | def admin_docker_massaction_view(context, request) | Mass action view. | 5.179141 | 5.275015 | 0.981825 |
if coords.frame.name != frame:
c = coords.transform_to(frame)
else:
c = coords
if hasattr(c, 'ra'):
phi = c.ra.rad
theta = 0.5*np.pi - c.dec.rad
return hp.pixelfunc.ang2pix(nside, theta, phi, nest=nest)
elif hasattr(c, 'l'):
phi = c.l.rad
the... | def coord2healpix(coords, frame, nside, nest=True) | Calculate HEALPix indices from an astropy SkyCoord. Assume the HEALPix
system is defined on the coordinate frame ``frame``.
Args:
coords (:obj:`astropy.coordinates.SkyCoord`): The input coordinates.
frame (:obj:`str`): The frame in which the HEALPix system is defined.
nside (:obj:`int`)... | 2.109946 | 2.056581 | 1.025949 |
@wraps(f)
def _wrapper_func(self, coords, **kwargs):
if not isinstance(coords, coordinates.SkyCoord):
raise TypeError('`coords` must be an astropy.coordinates.SkyCoord object.')
return f(self, coords, **kwargs)
return _wrapper_func | def ensure_coord_type(f) | A decorator for class methods of the form
.. code-block:: python
Class.method(self, coords, **kwargs)
where ``coords`` is an :obj:`astropy.coordinates.SkyCoord` object.
The decorator raises a :obj:`TypeError` if the ``coords`` that gets passed to
``Class.method`` is not an :obj:`astropy.coor... | 2.690388 | 2.558974 | 1.051354 |
@wraps(f)
def _wrapper_func(self, coords, **kwargs):
# t0 = time.time()
if coords.frame.name != 'galactic':
gal = coords.transform_to('galactic')
else:
gal = coords
# t1 = time.time()
is_array = not coords.isscalar
if is_array:
... | def ensure_flat_galactic(f) | A decorator for class methods of the form
.. code-block:: python
Class.method(self, coords, **kwargs)
where ``coords`` is an :obj:`astropy.coordinates.SkyCoord` object.
The decorator ensures that the ``coords`` that gets passed to
``Class.method`` is a flat array of Galactic coordinates. It ... | 2.28054 | 2.22929 | 1.022989 |
if not isinstance(l, units.Quantity):
l = l * units.deg
if not isinstance(b, units.Quantity):
b = b * units.deg
if d is None:
coords = coordinates.SkyCoord(l, b, frame='galactic')
else:
if not isinstance(d, units.Quantity):
... | def query_gal(self, l, b, d=None, **kwargs) | Query using Galactic coordinates.
Args:
l (:obj:`float`, scalar or array-like): Galactic longitude, in degrees,
or as an :obj:`astropy.unit.Quantity`.
b (:obj:`float`, scalar or array-like): Galactic latitude, in degrees,
or as an :obj:`astropy.unit.Quant... | 1.888169 | 1.866078 | 1.011838 |
valid_frames = ['icrs', 'fk4', 'fk5', 'fk4noeterms']
if frame not in valid_frames:
raise ValueError(
'`frame` not understood. Must be one of {}.'.format(valid_frames))
if not isinstance(ra, units.Quantity):
ra = ra * units.deg
if not is... | def query_equ(self, ra, dec, d=None, frame='icrs', **kwargs) | Query using Equatorial coordinates. By default, the ICRS frame is used,
although other frames implemented by :obj:`astropy.coordinates` may also be
specified.
Args:
ra (:obj:`float`, scalar or array-like): Galactic longitude, in degrees,
or as an :obj:`astropy.unit.Q... | 2.058924 | 1.915946 | 1.074625 |
is_inst = _is_inst(model_or_inst)
if isinstance(excludes, six.string_types):
excludes = [excludes]
if excludes and only:
only = None
elif isinstance(only, six.string_types):
only = [only]
parser = RequestPopulator() if for_populate else reqparse.RequestParser()
for... | def make_request_parser(model_or_inst, excludes=None, only=None, for_populate=False) | Pass a `model class` or `model instance` to this function,
then, it will generate a `RequestParser` that extract user request data from `request.json`
according to the model class's definition.
Parameter `excludes` and `only` can be `str` or list of `str`,
then are used to specify which columns shou... | 3.658785 | 3.694207 | 0.990411 |
inst = model_or_inst if _is_inst(model_or_inst) else model_or_inst()
parser = make_request_parser(model_or_inst, excludes, only, for_populate=True)
req_args = parser.parse_args()
for key, value in req_args.items():
setattr(inst, key, value)
return inst | def populate_model(model_or_inst, excludes=None, only=None) | Call `make_request_parser()` to build a `RequestParser`, use it extract user request data,
and padding the data into model instance.
If user passed a model class, instead of model instance, create a new instance use the extracted data. | 3.088521 | 2.853056 | 1.082531 |
digits, exp = mpfr.mpfr_get_str(base, ndigits, op, rounding_mode)
negative = digits.startswith('-')
if negative:
digits = digits[1:]
return negative, digits, exp | def _mpfr_get_str2(base, ndigits, op, rounding_mode) | Variant of mpfr_get_str, for internal use: simply splits off the '-'
sign from the digit string, and returns a triple
(sign, digits, exp)
Also converts the byte-string produced by mpfr_get_str to Unicode. | 3.547989 | 3.468319 | 1.022971 |
# strip leading zeros
olddigits = digits
digits = digits.lstrip('0')
dot_pos -= len(olddigits) - len(digits)
# value is 0.digits * 10**dot_pos
use_exponent = dot_pos <= -4 or dot_pos > len(digits)
if use_exponent:
exp = dot_pos - 1 if digits else dot_pos
dot_pos -= exp... | def _format_finite(negative, digits, dot_pos) | Given a (possibly empty) string of digits and an integer
dot_pos indicating the position of the decimal point relative to
the start of that string, output a formatted numeric string with
the same value and same implicit exponent. | 3.422555 | 3.290849 | 1.040022 |
x = BigFloat._implicit_convert(x)
# make sure we don't alter any flags
with _saved_flags():
with (context if context is not None else EmptyContext):
with RoundTowardPositive:
# nan maps to itself
if is_nan(x):
return +x
... | def next_up(x, context=None) | next_up(x): return the least representable float that's
strictly greater than x.
This operation is quiet: flags are not affected. | 15.553316 | 14.790424 | 1.05158 |
x = BigFloat._implicit_convert(x)
# make sure we don't alter any flags
with _saved_flags():
with (context if context is not None else EmptyContext):
with RoundTowardNegative:
# nan maps to itself
if is_nan(x):
return +x
... | def next_down(x, context=None) | next_down(x): return the greatest representable float that's
strictly less than x.
This operation is quiet: flags are not affected. | 16.49337 | 15.382864 | 1.072191 |
if not flagset <= _all_flags:
raise ValueError("unrecognized flags in flagset")
for f in flagset:
set_flag(f)
for f in _all_flags - flagset:
clear_flag(f) | def set_flagstate(flagset) | Set all flags in ``flagset``, and clear all other flags. | 3.814822 | 3.471993 | 1.098741 |
s = s.strip()
ternary, endindex = mpfr.mpfr_strtofr(rop, s, base, rnd)
if len(s) != endindex:
raise ValueError("not a valid numeric string")
return ternary | def _set_from_whole_string(rop, s, base, rnd) | Helper function for set_str2: accept a string, set rop, and return the
appropriate ternary value. Raise ValueError if ``s`` doesn't represent
a valid string in the given base. | 8.792913 | 7.341895 | 1.197635 |
return _apply_function_in_current_context(
BigFloat,
_set_from_whole_string,
(s, base),
context,
) | def set_str2(s, base, context=None) | Convert the string ``s`` in base ``base`` to a BigFloat instance, rounding
according to the current context.
Raise ValueError if ``s`` doesn't represent a valid string in the given
base. | 12.275078 | 11.502987 | 1.067121 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_set,
(BigFloat._implicit_convert(x),),
context,
) | def pos(x, context=None) | Return ``x``.
As usual, the result is rounded to the current context. The ``pos``
function can be useful for rounding an intermediate result, computed with a
temporary increase in precision, back to the current context. For
example::
>>> from bigfloat import precision
>>> pow(3, 20) ... | 16.741587 | 21.56954 | 0.776168 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_add,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def add(x, y, context=None) | Return ``x`` + ``y``. | 7.53021 | 7.699203 | 0.978051 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sub,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def sub(x, y, context=None) | Return ``x`` - ``y``. | 7.444123 | 7.890003 | 0.943488 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_mul,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def mul(x, y, context=None) | Return ``x`` times ``y``. | 7.659428 | 7.477762 | 1.024294 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sqr,
(BigFloat._implicit_convert(x),),
context,
) | def sqr(x, context=None) | Return the square of ``x``. | 12.53608 | 12.943381 | 0.968532 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_div,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def div(x, y, context=None) | Return ``x`` divided by ``y``. | 7.396889 | 7.669186 | 0.964495 |
return _apply_function_in_current_context(
BigFloat,
mpfr_floordiv,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def floordiv(x, y, context=None) | Return the floor of ``x`` divided by ``y``.
The result is a ``BigFloat`` instance, rounded to the
context if necessary. Special cases match those of the
``div`` function. | 7.108122 | 7.0938 | 1.002019 |
return _apply_function_in_current_context(
BigFloat,
mpfr_mod,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def mod(x, y, context=None) | Return the remainder of x divided by y, with sign matching that of y. | 7.122227 | 6.840862 | 1.04113 |
return floordiv(x, y, context=context), mod(x, y, context=context) | def divmod(x, y, context=None) | Return the pair (floordiv(x, y, context), mod(x, y, context)).
Semantics for negative inputs match those of Python's divmod function. | 3.567983 | 4.152984 | 0.859137 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_sqrt,
(BigFloat._implicit_convert(x),),
context,
) | def sqrt(x, context=None) | Return the square root of ``x``.
Return -0 if x is -0, to be consistent with the IEEE 754 standard. Return
NaN if x is negative. | 12.734561 | 16.681103 | 0.763412 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_rec_sqrt,
(BigFloat._implicit_convert(x),),
context,
) | def rec_sqrt(x, context=None) | Return the reciprocal square root of x.
Return +Inf if x is ±0, +0 if x is +Inf, and NaN if x is negative. | 12.039619 | 14.564975 | 0.826615 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_cbrt,
(BigFloat._implicit_convert(x),),
context,
) | def cbrt(x, context=None) | Return the cube root of x.
For x negative, return a negative number. The cube root of -0 is defined
to be -0. | 10.785455 | 14.109438 | 0.764414 |
if k < 0:
raise ValueError("root function not implemented for negative k")
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_root,
(BigFloat._implicit_convert(x), k),
context,
) | def root(x, k, context=None) | Return the kth root of x.
For k odd and x negative (including -Inf), return a negative number.
For k even and x negative (including -Inf), return NaN.
The kth root of -0 is defined to be -0, whatever the parity of k.
This function is only implemented for nonnegative k. | 8.946256 | 8.980045 | 0.996237 |
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_pow,
(
BigFloat._implicit_convert(x),
BigFloat._implicit_convert(y),
),
context,
) | def pow(x, y, context=None) | Return ``x`` raised to the power ``y``.
Special values are handled as described in the ISO C99 and IEEE 754-2008
standards for the pow function.
* pow(±0, y) returns plus or minus infinity for y a negative odd integer.
* pow(±0, y) returns plus infinity for y negative and not an odd integer.
... | 7.229788 | 11.029331 | 0.655506 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.