text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def getblock(self, hash: str) -> dict:
'''Returns information about the block with the given hash.'''
return cast(dict, self.api_fetch('getblock?hash=' + hash)) | 0.011299 |
def main():
"""Writes out newsfile if significant version bump"""
last_known = '0'
if os.path.isfile(metafile):
with open(metafile) as fh:
last_known = fh.read()
import mbed_cloud
current = mbed_cloud.__version__
# how significant a change in version scheme should trigger a... | 0.003964 |
def set_led(self, colorcode):
""" Set the LED Color of Herkulex
Args:
colorcode (int): The code for colors
(0x00-OFF
0x02-BLUE
0x03-CYAN
0x04-RED
... | 0.00458 |
def collapseBefore( self, handle ):
"""
Collapses the splitter before the inputed handle.
:param handle | <XSplitterHandle>
"""
self.setUpdatesEnabled(False)
# collapse all items after the current handle
if ( handle.isCollapsed() ):
... | 0.020053 |
def read_envfile(path=None, **overrides):
"""
Read a .env file (line delimited KEY=VALUE) into os.environ.
If not given a path to the file, recurses up the directory tree until
found.
Uses code from Honcho (github.com/nickstenning/honcho) for parsing the
file.
"... | 0.001059 |
def obj_deref(ref):
"""Returns the object identified by `ref`"""
from indico_livesync.models.queue import EntryType
if ref['type'] == EntryType.category:
return Category.get_one(ref['category_id'])
elif ref['type'] == EntryType.event:
return Event.get_one(ref['event_id'])
elif ref['t... | 0.001435 |
def _readFile(self, fileName):
"""
Returns the bytes of the file.
"""
with open(fileName, 'rb') as binFile:
b = binFile.read()
return to_ubyte_array(b) | 0.009662 |
def _generate_command(self, func, name=None, **kwargs):
"""Generates a command parser for given func.
:param func: func to generate related command parser
:param type: function
:param name: command name
:param type: str
:param **kwargs: keyword arguments those passed t... | 0.000897 |
def _process_coref_span_annotations_for_word(label: str,
word_index: int,
clusters: DefaultDict[int, List[Tuple[int, int]]],
coref_stacks: DefaultDict[int, List[int]]) -> No... | 0.006597 |
def handle_command(self, master, mpstate, args):
'''handle parameter commands'''
param_wildcard = "*"
usage="Usage: param <fetch|save|set|show|load|preload|forceload|diff|download|help>"
if len(args) < 1:
print(usage)
return
if args[0] == "fetch":
... | 0.002533 |
def child_allocation(self):
""" The sum of all child asset classes' allocations """
sum = Decimal(0)
if self.classes:
for child in self.classes:
sum += child.child_allocation
else:
# This is not a branch but a leaf. Return own allocation.
... | 0.005495 |
def parseSOAPMessage(data, ipAddr):
"parse raw XML data string, return a (minidom) xml document"
try:
dom = minidom.parseString(data)
except Exception:
#print('Failed to parse message from %s\n"%s": %s' % (ipAddr, data, ex), file=sys.stderr)
return None
if dom.getElementsByTagN... | 0.005005 |
def get_data(self, smoothed=True, masked=True, safe_copy=False):
"""Get the data in the image.
If save_copy is True, will perform a deep copy of the data and return it.
Parameters
----------
smoothed: (optional) bool
If True and self._smooth_fwhm > 0 will smooth the... | 0.005158 |
def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
"""
Get the anaconda server api class
"""
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_UR... | 0.002075 |
def query(self, query, param=None):
""" Perform a SQL based query
This will abort on a failure to communicate with
the database.
:query: string query
:params: parameters for the query
:return: RecordList from psycopg2
"""
with self.conn.cursor() as curs... | 0.002522 |
def VerifyScripts(verifiable):
"""
Verify the scripts of the provided `verifiable` object.
Args:
verifiable (neo.IO.Mixins.VerifiableMixin):
Returns:
bool: True if verification is successful. False otherwise.
"""
try:
hashes = verifia... | 0.004021 |
def accel_reset_terminal(self, *args):
# TODO KEYBINDINGS ONLY
"""Callback to reset and clean the terminal"""
HidePrevention(self.window).prevent()
current_term = self.get_notebook().get_current_terminal()
current_term.reset(True, True)
HidePrevention(self.window).allow()... | 0.008824 |
def to_meshpoint(meshcode, lat_multiplier, lon_multiplier):
"""地域メッシュコードから緯度経度を算出する。
下記のメッシュに対応している。
1次(80km四方):1
40倍(40km四方):40000
20倍(20km四方):20000
16倍(16km四方):16000
2次(10km四方):2
8倍(8km四方):8000
... | 0.001148 |
def from_string(cls, cl_function, dependencies=(), nmr_constraints=None):
"""Parse the given CL function into a SimpleCLFunction object.
Args:
cl_function (str): the function we wish to turn into an object
dependencies (list or tuple of CLLibrary): The list of CL libraries this ... | 0.006878 |
def parse_question_container(html_question):
"""Parse the question info container of a given HTML question.
The method parses the information available in the question information
container. The container can have up to 2 elements: the first one
contains the information related with the... | 0.003928 |
def iter_relation(self, relation, **kwargs):
"""
Generic method to iterate relation from any resource.
Query the client with the object's known parameters
and try to retrieve the provided relation type. This
is not meant to be used directly by a client, it's more
a helpe... | 0.003086 |
def send_success_response(self, msgid, methodname):
"""Send a CIM-XML response message back to the WBEM server that
indicates success."""
resp_xml = cim_xml.CIM(
cim_xml.MESSAGE(
cim_xml.SIMPLEEXPRSP(
cim_xml.EXPMETHODRESPONSE(
... | 0.001929 |
def locate_unlinked(gn, size=100, step=20, threshold=.1, blen=None):
"""Locate variants in approximate linkage equilibrium, where r**2 is
below the given `threshold`.
Parameters
----------
gn : array_like, int8, shape (n_variants, n_samples)
Diploid genotypes at biallelic variants, coded as... | 0.000561 |
def flasher(msg, severity=None):
"""Flask's flash if available, logging call if not"""
try:
flash(msg, severity)
except RuntimeError:
if severity == 'danger':
logging.error(msg)
else:
logging.info(msg) | 0.003831 |
def decode_complex(data, complex_names=(None, None)):
""" Decodes possibly complex data read from an HDF5 file.
Decodes possibly complex datasets read from an HDF5 file. HDF5
doesn't have a native complex type, so they are stored as
H5T_COMPOUND types with fields such as 'r' and 'i' for the real and
... | 0.000863 |
def AgregarBalanceLitrosPorcentajesSolidos(self, litros_remitidos, litros_decomisados,
kg_grasa, kg_proteina, **kwargs):
"Agrega balance litros y porcentajes sólidos a la liq. (obligatorio)"
d = {'litrosRemitidos': litros_remitidos,
'litrosDec... | 0.012346 |
def get_details(self, ids):
"""
Locu Venue Details API Call Wrapper
Args:
list of ids : ids of a particular venues to get insights about. Can process up to 5 ids
"""
if isinstance(ids, list):
if len(ids) > 5:
ids = ids[:5]
... | 0.006906 |
def eth_getBlockHeaderByNumber(self, number):
"""Get block header by block number.
:param number:
:return:
"""
block_hash = self.reader._get_block_hash(number)
block_number = _format_block_number(number)
return self.reader._get_block_header(block_hash, block_numb... | 0.006192 |
def fetch_submissions(self, submissions_callback, *args):
"""Wrap the submissions_callback function."""
logger.debug('Fetching submissions')
submissions_callback(*args)
logger.info('Found {} submissions'.format(len(self.submissions)))
if not self.submissions:
return... | 0.003663 |
def _setEndpoint(self, location):
'''
Set the endpoint after when Salesforce returns the URL after successful login()
'''
# suds 0.3.7+ supports multiple wsdl services, but breaks setlocation :(
# see https://fedorahosted.org/suds/ticket/261
try:
self._sforce.set_options(location = locatio... | 0.016706 |
def stat( self, *args ):
'''Check process completion and consume pending I/O data'''
self.pipe.poll()
if not self.pipe.returncode is None:
'''cleanup handlers and timeouts'''
if not self.expiration is None:
self.ioloop.remove_timeout(self.expiration)
... | 0.010976 |
def create_user(self, username, email, password, active=False,
send_email=True):
"""
A simple wrapper that creates a new :class:`User`.
:param username:
String containing the username of the new user.
:param email:
String containing the email... | 0.005839 |
def eval_hessian(self, *args, **kwargs):
"""
:return: Hessian evaluated at the specified point.
"""
# Evaluate the hessian model and use the resulting Ans namedtuple as a
# dict. From this, take the relevant components.
eval_hess_dict = self.hessian_model(*args, **kwargs)... | 0.006054 |
def get_host_name():
"""Get host name provide by operating system
"""
if sys.platform == 'win32':
host = os.getenv('COMPUTERNAME')
else:
host = os.uname()[1]
return host | 0.009615 |
def get_dev_asset_details(ipaddress, auth, url):
"""Takes in ipaddress as input to fetch device assett details from HP IMC RESTFUL API
:param ipaddress: IP address of the device you wish to gather the asset details
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:p... | 0.006311 |
def dispatch(self, *args, **kwargs):
"""
Decorate the view dispatcher with csrf_exempt.
"""
return super(EntryTrackback, self).dispatch(*args, **kwargs) | 0.01087 |
def _get_pubkey_hash(cert):
'''
Returns the sha1 hash of the modulus of a public key in a cert
Used for generating subject key identifiers
'''
sha_hash = hashlib.sha1(cert.get_pubkey().get_modulus()).hexdigest()
return _pretty_hex(sha_hash) | 0.003788 |
def set_execution_mode(self, execution_mode, notify=True):
""" An observed setter for the execution mode of the state machine status. This is necessary for the
monitoring client to update the local state machine in the same way as the root state machine of the server.
:param execution_mode: the... | 0.006865 |
def pl2nvp(plane):
"""
Return a unit normal vector and point that define a specified plane.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/pl2nvp_c.html
:param plane: A SPICE plane.
:type plane: supporttypes.Plane
:return: A unit normal vector and point that define plane.
:rtype:... | 0.001692 |
def solve(self):
""" Runs dynamic simulation.
@rtype: dict
@return: Solution dictionary with the following keys:
- C{angles} - generator angles
- C{speeds} - generator speeds
- C{eq_tr} - q component of transient voltage behind
... | 0.000941 |
def details_handler(args):
"""usage: {program} details <anchor-id> [<path>]
Get the details of a single anchor.
"""
repo = _open_repo(args)
_, anchor = _get_anchor(repo, args['<anchor-id>'])
print("""path: {file_path}
encoding: {encoding}
[before]
{before}
--------------
[topic]
{topic}
---... | 0.001458 |
def main():
"""The Main function/pipeline for GSEApy."""
# Parse options...
argparser = prepare_argparser()
args = argparser.parse_args()
subcommand = args.subcommand_name
if subcommand == "replot":
# reproduce plots using GSEAPY
from .gsea import Replot
rep = Replot(in... | 0.006215 |
def _post_login_page(self):
"""Login to Janrain."""
# Prepare post data
data = {
"form": "signInForm",
"client_id": JANRAIN_CLIENT_ID,
"redirect_uri": "https://www.fido.ca/pages/#/",
"response_type": "token",
"locale": "en-US",
... | 0.002469 |
def find_inspectable_lines(lines, pos):
"""Find lines in home that are inspectable.
Walk back from the err line up to 3 lines, but don't walk back over
changes in indent level.
Walk forward up to 3 lines, counting \ separated lines as 1. Don't walk
over changes in indent level (unless part of ... | 0.00399 |
def node_restart(self):
"""Restarts device"""
log.info('Restart')
res = self.__exchange('node.restart()')
log.info(res)
return res | 0.011765 |
def make_vec_env(env_id, env_type, num_env, seed,
wrapper_kwargs=None,
start_index=0,
reward_scale=1.0,
flatten_dict_observations=True,
gamestate=None):
"""
Create a wrapped, monitored SubprocVecEnv for Atari and MuJoCo.
""... | 0.002646 |
def _component_of(name):
"""Get the root package or module of the passed module.
"""
# Get the registered package this model belongs to.
segments = name.split('.')
while segments:
# Is this name a registered package?
test = '.'.join(segments)
if test in settings.get('COMPONE... | 0.001359 |
def load_result_json(result_path, json_file_name):
"""load_result_json."""
json_path = os.path.join(result_path, json_file_name)
_list = []
if os.path.isfile(json_path):
with open(json_path) as json_data:
try:
_list = json.load(json_data)
except ValueErro... | 0.002217 |
def version(**kwargs):
"""
Detects the new version according to git log and semver. Writes the new version
number and commits it, unless the noop-option is True.
"""
retry = kwargs.get("retry")
if retry:
click.echo('Retrying publication of the same version...')
else:
click.ec... | 0.002083 |
def create_auth_manifest(**kwargs):
"""
Creates a basic authentication manifest for logging in, logging out and
registering new accounts.
"""
class AuthProgram(Program):
pre_input_middleware = [AuthenticationMiddleware]
def register(username, password, password2):
"""
De... | 0.002039 |
def alpha_shape(points, alpha):
"""
Compute the alpha shape (concave hull) of a set
of points.
@param points: Iterable container of points.
@param alpha: alpha value to influence the
gooeyness of the border. Smaller numbers
don't fall inward as much as larger numbers.
Too lar... | 0.002256 |
def _prttex_summary_cnts(self, prt, cnts):
"""Write summary of level and depth counts for active GO Terms."""
# Count level(shortest path to root) and depth(longest path to root)
# values for all unique GO Terms.
prt.write("\n\n% LaTeX Table for GO counts at each level and depth in the G... | 0.003871 |
def save(self, obj):
"""Required functionality."""
if not obj.id:
obj.id = uuid()
stored_data = {
'_id': obj.id,
'value': json.loads(obj.to_data())
}
index_vals = obj.indexes() or {}
for key in obj.__class__.index_names() or []:
... | 0.003795 |
def iteritems_breadth_first(a_mapping, include_dicts=False):
"""a generator that returns all the keys in a set of nested
Mapping instances. The keys take the form X.Y.Z"""
subordinate_mappings = []
for key, value in six.iteritems(a_mapping):
if isinstance(value, collections.Mapping):
... | 0.001563 |
def get_core(self):
"""
Get an unsatisfiable core if the formula was previously
unsatisfied.
"""
if self.minisat and self.status == False:
return pysolvers.minisatgh_core(self.minisat) | 0.012245 |
def parse_variant_playlist(cls, session_, url, name_key="name",
name_prefix="", check_streams=False,
force_restart=False, name_fmt=None,
start_offset=0, duration=None,
**request_params):
"... | 0.002645 |
def distances(a, b, shape, squared=False, axis=1):
'''
distances(a, b, (n,d)) yields a potential function whose output is equivalent to the row-norms
of reshape(a(x), (n,d)) - reshape(b(x), (n,d)).
The shape argument (n,m) may alternately be a matrix of parameter indices, as can be passed to
... | 0.010321 |
def AllTypes():
"""
Get a list of all available asset types.
Returns:
list: of AssetType items.
"""
return [AssetType.CreditFlag, AssetType.DutyFlag, AssetType.GoverningToken,
AssetType.UtilityToken, AssetType.Currency, AssetType.Share,
... | 0.008403 |
def GenerateLibSig(short_name):
"""Generates a library signature suitable for a user agent field.
Args:
short_name: The short, product-specific string name for the library.
Returns:
A library signature string to append to user-supplied user-agent value.
"""
with _UTILITY_LOCK:
utilities_used = ',... | 0.007386 |
def skip_if(self, condition: bool, default: Any = None) -> 'Question':
"""Skip the question if flag is set and return the default instead."""
self.should_skip_question = condition
self.default = default
return self | 0.008097 |
def reference_id_from_html(html):
"""\
Extracts the cable's reference identifier from the provided HTML string.
`html`
The HTML page of the cable.
"""
m = _REFERENCE_ID_FROM_HTML_PATTERN.search(html)
if m:
return m.group(1)
raise ValueError("Cannot extract the cable's refere... | 0.003049 |
def StoreCSRFCookie(user, response):
"""Decorator for WSGI handler that inserts CSRF cookie into response."""
csrf_token = GenerateCSRFToken(user, None)
response.set_cookie(
"csrftoken", csrf_token, max_age=CSRF_TOKEN_DURATION.seconds) | 0.016129 |
def update(self):
"""
Updates the bundle
"""
with self._lock:
# Was it active ?
restart = self._state == Bundle.ACTIVE
# Send the update event
self._fire_bundle_event(BundleEvent.UPDATE_BEGIN)
try:
# Stop the b... | 0.001252 |
def monday_of_week(year, week):
"""
Returns a datetime for the monday of the given week of the given year.
"""
str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')
date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,
day=str_time.tm_mda... | 0.001779 |
def rerun(client, revision, roots, siblings, inputs, paths):
"""Recreate files generated by a sequence of ``run`` commands."""
graph = Graph(client)
outputs = graph.build(paths=paths, revision=revision)
# Check or extend siblings of outputs.
outputs = siblings(graph, outputs)
output_paths = {no... | 0.000567 |
async def search_and_download(album, artist, format, size, out_filepath, *, size_tolerance_prct, amazon_tlds, no_lq_sources,
async_loop):
""" Search and download a cover, return True if success, False instead. """
# register sources
source_args = (size, size_tolerance_prct)
cover_s... | 0.015827 |
def visit_shapes(self, expr: ShExJ.shapeExpr, f: Callable[[Any, ShExJ.shapeExpr, "Context"], None], arg_cntxt: Any,
visit_center: _VisitorCenter = None, follow_inner_shapes: bool=True) -> None:
"""
Visit expr and all of its "descendant" shapes.
:param expr: root shape expre... | 0.006188 |
def execute_command(self, command, cwd=None, stdout_captured=None):
"""Execute a command at cwd, saving its normal output at
stdout_captured. Errors, defined as nonzero return code or a failure
to start execution, will raise a CompilerError exception with a
description of the cause. They... | 0.002931 |
def contains_variables_from_set(expression, variables):
"""Returns True iff the expression contains any of the variables from the given set."""
if hasattr(expression, 'variable_name') and expression.variable_name in variables:
return True
if isinstance(expression, Operation):
return any(cont... | 0.009901 |
def export_xml_file(self, directory, filename):
"""
Exports diagram inner graph to BPMN 2.0 XML file (with Diagram Interchange data).
:param directory: strings representing output directory,
:param filename: string representing output file name.
"""
bpmn_export.BpmnDiagr... | 0.010638 |
def apply_calibration(self, strain):
"""Apply calibration model
This applies cubic spline calibration to the strain.
Parameters
----------
strain : FrequencySeries
The strain to be recalibrated.
Return
------
strain_adjusted : FrequencySerie... | 0.001706 |
def keyevent_to_keyseq(self, event):
"""Return a QKeySequence representation of the provided QKeyEvent."""
self.keyPressEvent(event)
event.accept()
return self.keySequence() | 0.009569 |
def parse(self, scope):
"""Parse node
args:
scope (Scope): current scope
raises:
SyntaxError
returns:
parsed
"""
if not self.parsed:
self.parsed = ''.join(self.process(self.tokens, scope))
return self.parsed | 0.006431 |
def _parse_validators(valids):
"""Parse a list of validator names or n-tuples, checking for errors.
Returns:
list((func_name, [args...])): A list of validator function names and a
potentially empty list of optional parameters for each function.
"""
outvals = []
for val in vali... | 0.002911 |
def fir_remez_bsf(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop,
fs = 1.0, N_bump=5):
"""
Design an FIR bandstop filter using remez with order
determination. The filter order is determined based on
f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the
desired passba... | 0.010999 |
def forward_transform_fn(bijector):
"""Makes a function which applies a list of Bijectors' `forward`s."""
if not mcmc_util.is_list_like(bijector):
bijector = [bijector]
def fn(transformed_state_parts):
return [b.forward(sp) for b, sp in zip(bijector, transformed_state_parts)]
return fn | 0.016447 |
def kraus_iscomplete(kraus: Kraus) -> bool:
"""Returns True if the collection of (weighted) Kraus operators are
complete. (Which is necessary for a CPTP map to preserve trace)
"""
qubits = kraus.qubits
N = kraus.qubit_nb
ident = Gate(np.eye(2**N), qubits) # FIXME
tensors = [(op.H @ op @ i... | 0.001898 |
def adjacent(labels):
'''Return a binary mask of all pixels which are adjacent to a pixel of
a different label.
'''
high = labels.max()+1
if high > np.iinfo(labels.dtype).max:
labels = labels.astype(np.int)
image_with_high_background = labels.copy()
image_with_high_backgr... | 0.017647 |
def convert(self, vroot, entry_variables):
"""
All functions are replaced with the same `new` function.
Args:
vroot (:obj:`Variable`): NNabla Variable
entry_variables (:obj:`Variable`): Entry variable from which the conversion starts.
"""
self.graph_info ... | 0.00308 |
def to_export(export):
"""Serializes export to id string
:param export: object to serialize
:return: string id
"""
from sevenbridges.models.storage_export import Export
if not export:
raise SbgError('Export is required!')
elif isinstance(export, Export... | 0.004016 |
def basic(username, password):
"""Add basic authentication to the requests of the clients."""
none()
_config.username = username
_config.password = password | 0.005814 |
def rl_force_redisplay() -> None: # pragma: no cover
"""
Causes readline to display the prompt and input text wherever the cursor is and start
reading input from this location. This is the proper way to restore the input line after
printing to the screen
"""
if not sys.stdout.isatty():
... | 0.004866 |
def _get_match(self, key):
"""
Gets a MatchObject for the given key.
Args:
key (str): Key of the property to look-up.
Return:
MatchObject: The discovered match.
"""
return self._get_string_match(key=key) or \
self._get_non_string_mat... | 0.006042 |
def set_tag(tag, value):
"""
Set the tag 'tag' to the value True or False.
:param value: should be a boolean
:param tag: should be the id of the tag. Can not starts with '*auto-tag-'
"""
if not tag.startswith("*auto-tag-"):
rdict = load_feedback()
tests = rdict.setdefault("te... | 0.01519 |
def flux_matrix(T, pi, qminus, qplus, netflux=True):
r"""Compute the flux.
Parameters
----------
T : (M, M) scipy.sparse matrix
Transition matrix
pi : (M,) ndarray
Stationary distribution corresponding to T
qminus : (M,) ndarray
Backward comittor
qplus : (M,) ndarray... | 0.001139 |
def propagate_astrometry_and_covariance_matrix(self, a0, c0, t0, t1):
"""
Propagate the covariance matrix of the astrometric parameters and radial proper motion of a
source from epoch t0 to epoch t1.
Code based on the Hipparcos Fortran implementation by Lennart Lindegren.
Param... | 0.01827 |
def _ParseSourcePathOption(self, options):
"""Parses the source path option.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid.
"""
self._source_path = self.ParseStringOption(options, self._SOURCE_OPTION)
if not self._so... | 0.004454 |
def _assert_ssl_exc_contains(exc, *msgs):
"""Check whether SSL exception contains either of messages provided."""
if len(msgs) < 1:
raise TypeError(
'_assert_ssl_exc_contains() requires '
'at least one message to be passed.',
)
err_msg_lower = str(exc).lower()
ret... | 0.00271 |
def to_dict(self):
"""Get a dictionary representation of this item, formatted for Elasticsearch"""
out = {}
fields = self.__class__.search_objects.mapping.properties.properties
for key in fields:
# TODO: What if we've mapped the property to a different name? Will we allow t... | 0.004484 |
def get_events(self):
"""Returns a list of all ``KindleEvent``s held in the store
"""
with open(self._path, 'r') as file_:
file_lines = file_.read().splitlines()
event_lines = [line for line in file_lines if line]
events = []
for event_line in event_lines:... | 0.002999 |
def get_first(self):
"""Return snmp value for the first OID."""
try: # Nested try..except because of Python 2.4
self.lock.acquire()
try:
return self.get(self.data_idx[0])
except (IndexError, ValueError):
return "NONE"
finally:
self.lock.release() | 0.044118 |
def compute_information_gain(ann_inter, est_inter, est_file, bins):
"""Computes the information gain of the est_file from the annotated
intervals and the estimated intervals."""
ann_times = utils.intervals_to_times(ann_inter)
est_times = utils.intervals_to_times(est_inter)
return mir_eval.beat.infor... | 0.002747 |
def open_mfdataset(path_to_lsm_files,
lat_var,
lon_var,
time_var,
lat_dim,
lon_dim,
time_dim,
lon_to_180=False,
coords_projected=False,
loader=None,
... | 0.000226 |
def per_installer_data(self):
"""
Return download data by installer name and version.
:return: dict of cache data; keys are datetime objects, values are
dict of installer name/version (str) to count (int).
:rtype: dict
"""
ret = {}
for cache_date in sel... | 0.002317 |
def water(target, temperature='pore.temperature', salinity='pore.salinity'):
r"""
Calculates surface tension of pure water or seawater at atmospheric
pressure using Eq. (28) given by Sharqawy et al. Values at
temperature higher than the normal boiling temperature are calculated at
the saturation pre... | 0.000596 |
def main():
"""
This generates the research document based on the results of
the various programs and includes RST imports for introduction
and summary
"""
print("Generating research notes...")
if os.path.exists(fname):
os.remove(fname)
append_rst('===============================... | 0.008673 |
def conflicting_deps(tree):
"""Returns dependencies which are not present or conflict with the
requirements of other packages.
e.g. will warn if pkg1 requires pkg2==2.0 and pkg2==1.0 is installed
:param tree: the requirements tree (dict)
:returns: dict of DistPackage -> list of unsatisfied/unknown... | 0.001818 |
def remove_node_by_value(self, value):
"""
Delete all nodes in ``self.node_list`` with the value ``value``.
Args:
value (Any): The value to find and delete owners of.
Returns: None
Example:
>>> from blur.markov.node import Node
>>> node_1 = ... | 0.002491 |
def get_fact_cache(self, host):
'''
Get the entire fact cache only if the fact_cache_type is 'jsonfile'
'''
if self.config.fact_cache_type != 'jsonfile':
raise Exception('Unsupported fact cache type. Only "jsonfile" is supported for reading and writing facts from ansible-run... | 0.00566 |
def train_image(self):
"""Return the Docker image to use for training.
The :meth:`~sagemaker.estimator.EstimatorBase.fit` method, which does the model training,
calls this method to find the image to use for model training.
Returns:
str: The URI of the Docker image.
... | 0.005208 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.