text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def template_exists(template_name):
'''
Determine if a given template exists so that it can be loaded
if so, or a default alternative can be used if not.
'''
try:
template.loader.get_template(template_name)
return True
except template.TemplateDoesNotExist:
return... | 0.003067 |
def build_vep_annotation(csq_info, reference, alternatives, vep_columns):
"""
Build a dictionary with the vep information from the vep annotation.
Indels are handled different by vep depending on the number of
alternative alleles there is for a variant.
If only one alternative:
... | 0.009238 |
def show_shortcuts(self):
"""Print all shortcuts."""
gui_name = self.gui.name
actions_name = self.name
name = ('{} - {}'.format(gui_name, actions_name)
if actions_name else gui_name)
_show_shortcuts(self.shortcuts, name) | 0.007246 |
def is_parseable (self):
"""Check if content is parseable for recursion.
@return: True if content is parseable
@rtype: bool
"""
if self.is_directory():
return True
if firefox.has_sqlite and firefox.extension.search(self.url):
return True
i... | 0.007921 |
def run_and_measure(self, quil_program: Program, qubits: List[int] = None, trials: int = 1,
memory_map: Any = None) -> np.ndarray:
"""
Run a Quil program once to determine the final wavefunction, and measure multiple times.
Alternatively, consider using ``wavefunction`` ... | 0.009091 |
def multitaper_cross_spectrum(self, clm, slm, k, convention='power',
unit='per_l', **kwargs):
"""
Return the multitaper cross-spectrum estimate and standard error.
Usage
-----
mtse, sd = x.multitaper_cross_spectrum(clm, slm, k, [convention, unit... | 0.001061 |
def create_match_bool(words_as_string, eval_function, eval_function_args):
"""
Evaluates components of words_as_string step by step into a single boolean value using
eval_function to evaluate each separate component of words_as_string into booleans.
:param words_as_string: String to evaluate
:param ... | 0.00266 |
async def join(self):
"""Block until all items in the queue have been gotten and processed.
The count of unfinished tasks goes up whenever an item is added to the
queue. The count goes down whenever a consumer calls task_done() to
indicate that the item was retrieved and all work on it ... | 0.003268 |
def _make_intermediate_dirs(sftp_client, remote_directory):
"""
Create all the intermediate directories in a remote host
:param sftp_client: A Paramiko SFTP client.
:param remote_directory: Absolute Path of the directory containing the file
:return:
"""
if remote_directory == '/':
s... | 0.001453 |
def weather_update(station, pub_sites, interval):
'''
main execution loop. query weather data and post to online service.
'''
station.parse() # read weather data
# santity check weather data
if station.fields['TempOut'] > 200:
raise NoSensorException(
'Out of range temperature ... | 0.039201 |
def get_reservation_ports(session, reservation_id, model_name='Generic Traffic Generator Port'):
""" Get all Generic Traffic Generator Port in reservation.
:return: list of all Generic Traffic Generator Port resource objects in reservation
"""
reservation_ports = []
reservation = session.GetReserv... | 0.007366 |
def _set_circuit_type(self, v, load=False):
"""
Setter method for circuit_type, mapped from YANG variable /isis_state/interface_brief/isis_intf_brief/circuit_type (isis-circ-type)
If this variable is read-only (config: false) in the
source YANG file, then _set_circuit_type is considered as a private
... | 0.004826 |
def setup(app):
''' Required Sphinx extension setup function. '''
app.add_autodocumenter(ColorDocumenter)
app.add_autodocumenter(EnumDocumenter)
app.add_autodocumenter(PropDocumenter)
app.add_autodocumenter(ModelDocumenter) | 0.004115 |
def parse_source(self):
"""Parse source text to find executable lines, excluded lines, etc.
Return values are 1) a set of executable line numbers, and 2) a set of
excluded line numbers.
Reported line numbers are normalized to the first line of multi-line
statements.
""... | 0.003348 |
def _add_rule(self, state, rule):
"""Parse rule and add it to machine (for internal use)."""
if rule.strip() == "-":
parsed_rule = None
else:
parsed_rule = rule.split(',')
if (len(parsed_rule) != 3 or
parsed_rule[1] not in ['L', 'N', 'R'] or... | 0.004518 |
def string_to_char(l):
'''Convert 1-D list of strings to 2-D list of chars.'''
if not l:
return []
if l == ['']:
l = [' ']
maxlen = reduce(max, map(len, l))
ll = [x.ljust(maxlen) for x in l]
result = []
for s in ll:
result.append([x for x in s])
return result | 0.012579 |
def create_timeline(self, timeline, scope_identifier, hub_name, plan_id):
"""CreateTimeline.
:param :class:`<Timeline> <azure.devops.v5_0.task.models.Timeline>` timeline:
:param str scope_identifier: The project GUID to scope the request
:param str hub_name: The name of the server hub: "... | 0.006074 |
def parallel(fsms, test):
'''
Crawl several FSMs in parallel, mapping the states of a larger meta-FSM.
To determine whether a state in the larger FSM is final, pass all of the
finality statuses (e.g. [True, False, False] to `test`.
'''
alphabet = set().union(*[fsm.alphabet for fsm in fsms])
initial = dict([(... | 0.026337 |
def generate_querystring(params):
"""
Generate a querystring suitable for use in the v2 api.
The Requests library doesn't know how to generate querystrings that encode dictionaries using square brackets:
https://api.mollie.com/v2/methods?amount[value]=100.00&amount[currency]=USD
Note: we use `sort... | 0.003988 |
def _checkremove_que(self, word):
"""If word ends in -que and if word is not in pass list, strip -que"""
in_que_pass_list = False
que_pass_list = ['atque',
'quoque',
'neque',
'itaque',
'absque',
... | 0.02473 |
def get_generation_code(self):
"""Return python code that generates all drawn gates."""
if len(self.gates) < 1:
code = ''
else:
import_list = set([gate._gencode_gate_class for gate in self.gates])
import_list = 'from FlowCytometryTools import ' + ', '.join(imp... | 0.006202 |
def get_cfn_parameters(self):
"""Return a dictionary of variables with `type` :class:`CFNType`.
Returns:
dict: variables that need to be submitted as CloudFormation
Parameters.
"""
variables = self.get_variables()
output = {}
for key, value i... | 0.004237 |
def __generate_method(name):
"""
Wraps the DataFrame's original method by name to return the derived class instance.
"""
try:
func = getattr(DataFrame, name)
except AttributeError as e:
# PySpark version is too old
def func(self, *args, **kwarg... | 0.004556 |
def sentence_similarity(sentence1, sentence2):
""" compute the sentence similarity using Wordnet """
# Tokenize and tag
sentence1 = pos_tag(word_tokenize(sentence1))
sentence2 = pos_tag(word_tokenize(sentence2))
# Get the synsets for the tagged words
synsets1 = [tagged_to_synset(*tagged_word) f... | 0.005348 |
def ensure_us_time_resolution(val):
"""Convert val out of numpy time, for use in to_dict.
Needed because of numpy bug GH#7619"""
if np.issubdtype(val.dtype, np.datetime64):
val = val.astype('datetime64[us]')
elif np.issubdtype(val.dtype, np.timedelta64):
val = val.astype('timedelta64[us]... | 0.002967 |
def load(self, filename, append=False):
"""Load collection from pickled file *filename*.
*append* determines if the saved collection is added to the current one
or if it replaces the current content.
If no extension is provided, ".collection" is appended.
"""
tmp = cPic... | 0.004193 |
def render(self, xml, context, raise_on_errors=True):
"""Render xml string and apply XSLT transfomation with context"""
if xml:
self.xml = xml
# render XSL
self.render_xsl(self.root, context)
# create root XSL sheet
xsl_ns = self.namespaces[... | 0.004326 |
def from_msm(cls, msm, n_macrostates, filter=1.1, save_all_maps=True,
n_proc=1, chunk_size=100):
"""Create and fit lumped model from pre-existing MSM.
Parameters
----------
msm : MarkovStateModel
The input microstate msm to use.
n_macrostates : int
... | 0.003311 |
def create_superfile(cookie, path, block_list):
'''合并slice_upload()中产生的临时文件
path - 文件在服务器上的绝对路径
block_list - 这些文件分片的MD5列表
返回完整的文件pcs信息.
'''
url = ''.join([
const.PCS_URL_C,
'file?method=createsuperfile&app_id=250528',
'&path=', encoder.encode_uri_component(path),
... | 0.00155 |
def metrique_object(_oid, _id=None, _hash=None, _start=None, _end=None,
_e=None, _v=None, id=None, __v__=None, **kwargs):
'''
Function which takes a dictionary (Mapping) object as input
and returns return back a metrique object.
Special meta property are added to each object::
... | 0.001147 |
def user(self, message):
""" Creates a user log (if user logging is turned on)
Uses the log path defined by ``Debug.setUserLogFile()``. If no log file is
defined, sends to STDOUT
Note: Does *not* use Java string formatting like Sikuli.
Format your message with Python ``basestri... | 0.008565 |
def load_labware_by_name(
self, labware_name: str,
location: types.DeckLocation, label: str = None) -> Labware:
""" A convenience function to specify a piece of labware by name.
For labware already defined by Opentrons, this is a convient way
to collapse the two stages o... | 0.001674 |
def acquire(self, blocking=True,
delay=DELAY_INCREMENT, max_delay=MAX_DELAY,
timeout=None):
"""Attempt to acquire the given lock.
:param blocking: whether to wait forever to try to acquire the lock
:type blocking: bool
:param delay: when blocking this is ... | 0.002169 |
def sam_conversions(self, sam_file, depth=True):
"""
Convert sam files to bam files, then sort and index them for later use.
:param bool depth: also calculate coverage over each position
"""
cmd = self.tools.samtools + " view -bS " + sam_file + " > " + sam_file.replace(".sam", "... | 0.007926 |
def restore_env_from_file(env_file):
'''Restore the current environment from an environment stored in a yaml
yaml file.
:param env_file: Path to environment yaml file.
'''
with open(env_file, 'r') as f:
env_dict = yaml.load(f.read())
restore_env(env_dict) | 0.003448 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'text') and self.text is not None:
_dict['text'] = self.text
if hasattr(self, 'keywords') and self.keywords is not None:
_dict['keywords'] = [x._to_dict() for x... | 0.005571 |
def _fail(self, request_id, failure, duration):
"""Publish a CommandFailedEvent."""
self.listeners.publish_command_failure(
duration, failure, self.name,
request_id, self.sock_info.address, self.op_id) | 0.008299 |
def get(self, sid):
"""
Constructs a RecordingContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.api.v2010.account.recording.RecordingContext
:rtype: twilio.rest.api.v2010.account.recording.RecordingContext
"""
return Record... | 0.007519 |
def RdatasetsBM(database,host=rbiomart_host):
"""
Lists BioMart datasets through a RPY2 connection.
:param database: a database listed in RdatabasesBM()
:param host: address of the host server, default='www.ensembl.org'
:returns: nothing
"""
biomaRt = importr("biomaRt")
ensemblMart=bi... | 0.007519 |
def appendtsv(table, source=None, encoding=None, errors='strict',
write_header=False, **csvargs):
"""
Convenience function, as :func:`petl.io.csv.appendcsv` but with different
default dialect (tab delimited).
"""
csvargs.setdefault('dialect', 'excel-tab')
return appendcsv(table, ... | 0.002342 |
def moment(self, axis, channel=0, moment=1, *, resultant=None):
"""Take the nth moment the dataset along one axis, adding lower rank channels.
New channels have names ``<channel name>_<axis name>_moment_<moment num>``.
Moment 0 is the integral of the slice.
Moment 1 is the weighted ave... | 0.003655 |
def get_type(full_path):
"""Get the type (socket, file, dir, symlink, ...) for the provided path"""
status = {'type': []}
if os.path.ismount(full_path):
status['type'] += ['mount-point']
elif os.path.islink(full_path):
status['type'] += ['symlink']
if os.path.isfile(full_path):
... | 0.001013 |
def regex_replace(regex, repl, text):
r"""
thin wrapper around re.sub
regex_replace
MULTILINE and DOTALL are on by default in all util_regex functions
Args:
regex (str): pattern to find
repl (str): replace pattern with this
text (str): text to modify
Returns:
s... | 0.000782 |
def from_email_message(cls, message, local_id=None):
'''
Convert an :class:`email.message.Message` or compatible message
object into a CERP XML :class:`eulxml.xmlmap.cerp.Message`. If an
id is specified, it will be stored in the Message <LocalId>.
:param message: `email.message.... | 0.002984 |
def image_tasks(self):
"""
Returns a json-schema document that represents a container of tasks
entities.
"""
uri = "/%s/tasks" % self.uri_base
resp, resp_body = self.api.method_get(uri)
return resp_body | 0.007752 |
def html(self, text=TEXT):
""" Generate an HTML file from the report data. """
self.logger.debug("Generating the HTML report{}..."
.format(["", " (text only)"][text]))
html = []
for piece in self._pieces:
if isinstance(piece, string_types):
... | 0.003968 |
def delete(self, ids):
"""
Method to delete vrf's by their id's
:param ids: Identifiers of vrf's
:return: None
"""
url = build_uri_with_ids('api/v3/vrf/%s/', ids)
return super(ApiVrf, self).delete(url) | 0.007722 |
def get_job_errors(self, job_id):
"""GetJobErrors
https://apidocs.joyent.com/manta/api.html#GetJobErrors
"""
log.debug("GetJobErrors %r", job_id)
path = "/%s/jobs/%s/live/err" % (self.account, job_id)
res, content = self._request(path, "GET")
if res["status"] != "... | 0.00463 |
def retrieve_cluster(self, df, cluster_no):
"""
Extracts the cluster at the given index from the input dataframe
:param df: the dataframe that contains the clusters
:param cluster_no: the cluster number
:return: returns the extracted cluster
"""
if self.is_pyclus... | 0.003195 |
def OnPreferences(self, event):
"""Preferences event handler that launches preferences dialog"""
preferences = self.interfaces.get_preferences_from_user()
if preferences:
for key in preferences:
if type(config[key]) in (type(u""), type("")):
conf... | 0.003663 |
def fmt_repr(obj):
"""Print a orphaned string representation of an object without the
clutter of its parent object.
"""
items = ["%s = %r" % (k, v) for k, v in list(exclude_fields(obj).items())]
return "<%s: {%s}>" % (obj.__class__.__name__, ', '.join(items)) | 0.014815 |
def get_container_update_kwargs(self, action, container_name, update_values, kwargs=None):
"""
Generates keyword arguments for the Docker client to update the HostConfig of an existing container.
:param action: Action configuration.
:type action: ActionConfig
:param container_na... | 0.007384 |
def alloc(self):
"""
Allocate an ID value and return it.
Raises:
ValueError: Out of capacity in ID pool.
"""
if not self._free:
self._expand()
id = self._free.pop()
self._used.add(id)
return id | 0.007092 |
def remove_listener(self, registration_id):
"""
Removes the specified item listener. Returns silently if the specified listener was not added before.
:param registration_id: (str), id of the listener to be deleted.
:return: (bool), ``true`` if the item listener is removed, ``false`` oth... | 0.010893 |
def visual(title, X, activation):
'''create a grid of images and save it as a final image
title : grid image name
X : array of images
'''
assert len(X.shape) == 4
X = X.transpose((0, 2, 3, 1))
if activation == 'sigmoid':
X = np.clip((X)*(255.0), 0, 255).astype(np.uint8)
elif act... | 0.003063 |
def split_python_text_into_lines(text):
"""
# TODO: make it so this function returns text so one statment is on one
# line that means no splitting up things like function definitions into
# multiple lines
"""
#import jedi
#script = jedi.Script(text, line=1, column=None, path='')
def pare... | 0.004241 |
def clip_out_of_image(self):
"""
Clip off all parts from all bounding boxes that are outside of the image.
Returns
-------
imgaug.BoundingBoxesOnImage
Bounding boxes, clipped to fall within the image dimensions.
"""
bbs_cut = [bb.clip_out_of_image(se... | 0.008282 |
def delete_metadata(self, loadbalancer, keys=None, node=None):
"""
Deletes metadata items specified by the 'keys' parameter. If no value
for 'keys' is provided, all metadata is deleted. If 'node' is supplied,
the metadata for that node is deleted instead of the load balancer.
"""... | 0.001903 |
def getPointsForInterpolation(self,EndOfPrdvP,aLvlNow):
'''
Finds endogenous interpolation points (x,m) for the expenditure function.
Parameters
----------
EndOfPrdvP : np.array
Array of end-of-period marginal values.
aLvlNow : np.array
Array of e... | 0.025021 |
def get_debug_info():
"""Return a list of lines with backend info.
"""
from . import __version__
d = OrderedDict()
d['Version'] = '%s' % __version__
for key, val in PyVisaLibrary.get_session_classes().items():
key_name = '%s %s' % (key[0].name.upper(), key[1]... | 0.003752 |
def save_catalog(filename, catalog, meta=None, prefix=None):
"""
Save a catalogue of sources using filename as a model. Meta data can be written to some file types
(fits, votable).
Each type of source will be in a separate file:
- base_comp.ext :class:`AegeanTools.models.OutputSource`
- base_i... | 0.003655 |
def execute_one_to_many_job(parent_class=None,
get_unfinished_kwargs=None,
get_unfinished_limit=None,
parser_func=None,
parser_func_kwargs=None,
build_url_func_kwargs=None,
... | 0.000521 |
def _send_get_request(self, path, params, headers):
"""
Sends the GET request to the Route53 endpoint.
:param str path: The path to tack on to the endpoint URL for
the query.
:param dict params: Key/value pairs to send.
:param dict headers: A dict of headers to send ... | 0.003676 |
def erfcc(x):
"""Complementary error function."""
z = abs(x)
t = 1 / (1 + 0.5 * z)
r = t * math.exp(-z * z -
1.26551223 + t *
(1.00002368 + t *
(.37409196 + t *
(.09678418 + t *
(-.18628806 + t... | 0.001706 |
def read_method(self):
"""
Read a method from the peer.
"""
self._next_method()
m = self.queue.get()
if isinstance(m, Exception):
raise m
return m | 0.009302 |
def ravel(self, name=None):
"""
Convert 2D histogram into 1D histogram with the y-axis repeated along
the x-axis, similar to NumPy's ravel().
"""
nbinsx = self.nbins(0)
nbinsy = self.nbins(1)
left_edge = self.xedgesl(1)
right_edge = self.xedgesh(nbinsx)
... | 0.002692 |
def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
... | 0.004525 |
def send_once(remote, codes, count=None, device=None, address=None):
"""
All parameters are passed to irsend. See the man page for irsend
for details about their usage.
Parameters
----------
remote: str
codes: [str]
count: int
device: str
address: str
Notes
-----
No... | 0.001812 |
def write(name, value):
"""Write a raw env value.
A ``None`` value clears the environment variable.
Args:
name: The environment variable name
value: The value to write
"""
if value is not None:
environ[name] = builtins.str(value)
elif environ.get(name):
del envi... | 0.00304 |
def get_objectives(self):
"""Gets the objective list resulting from the search.
return: (osid.learning.ObjectiveList) - the objective list
raise: IllegalState - list already retrieved
*compliance: mandatory -- This method must be implemented.*
"""
if self.retrieved:
... | 0.004032 |
def get_mmol(code, mmol_number=None, outfile=None):
""" Get mmol file from PDBe and return its content as a string. Write to file if outfile given.
Parameters
----------
code : str
PDB code.
mmol_number : int
mmol number (biological assembly number) of file to download. Numbers from... | 0.004119 |
def latex(source: str):
"""
Add a mathematical equation in latex math-mode syntax to the display.
Instead of the traditional backslash escape character, the @ character is
used instead to prevent backslash conflicts with Python strings. For
example, \\delta would be @delta.
:param source:
... | 0.001592 |
def __complete_refers(self, value: str) -> Iterable[str]:
"""Return an iterable of possible completions matching the given
prefix from the list of referred Vars."""
return map(
lambda entry: f"{entry[0].name}",
filter(
Namespace.__completion_matcher(value)... | 0.007916 |
def Convert(self, wave, flux, target_units, area=None):
"""Perform unit conversion.
Parameters
----------
wave, flux : number or array_like
Wavelength and flux values to be used for conversion.
target_units : str
Unit to convert to.
area : numbe... | 0.002281 |
def tokenize_paragraphs(cls, text):
"""Convert an input string into a list of paragraphs."""
paragraphs = []
paragraphs_first_pass = text.split('\n')
for p in paragraphs_first_pass:
paragraphs_second_pass = re.split('\s{4,}', p)
paragraphs += paragraphs_second_pas... | 0.006834 |
def _parse_addr(self, addr):
''' Parses address and returns IP version. Raises exception on invalid argument '''
ipv = 0
try:
socket.inet_pton(socket.AF_INET6, addr)
# Convert ::FFFF:x.y.z.y to IPv4
if addr.lower().startswith('::ffff:'):
try:
... | 0.009901 |
def find_file(path):
"""
Given a path to a part in a zip file, return a path to the file and
the path to the part.
Assuming /foo.zipx exists as a file,
>>> find_file('/foo.zipx/dir/part') # doctest: +SKIP
('/foo.zipx', '/dir/part')
>>> find_file('/foo.zipx') # doctest: +SKIP
('/foo.zipx', '')
"""
path_comp... | 0.030014 |
def deserialize_organization(organization_dict):
"""
Organization dict-to-object serialization
"""
return models.Organization(
id=organization_dict.get('id'),
name=organization_dict.get('name', ''),
short_name=organization_dict.get('short_name', ''),
description=organizat... | 0.002469 |
def setReturnParameter(self, name, type, namespace=None, element_type=0):
"""Set the return parameter description for the call info."""
parameter = ParameterInfo(name, type, namespace, element_type)
self.retval = parameter
return parameter | 0.00738 |
def pch_emitter(target, source, env):
"""Adds the object file target."""
validate_vars(env)
pch = None
obj = None
for t in target:
if SCons.Util.splitext(str(t))[1] == '.pch':
pch = t
if SCons.Util.splitext(str(t))[1] == '.obj':
obj = t
if not obj:
... | 0.006211 |
def reduce_logsumexp(x, reduced_dim, extra_logit=None, name=None):
"""Numerically stable version of log(reduce_sum(exp(x))).
Unlike other reductions, the output has the same shape as the input.
Note: with a minor change, we could allow multiple reduced dimensions.
Args:
x: a Tensor
reduced_dim: a dime... | 0.006233 |
def _create_hidden_port(self, context, network_id, device_id, fixed_ips,
port_type=DEVICE_OWNER_ROUTER_INTF):
"""Creates port used specially for HA purposes."""
port = {'port': {
'tenant_id': '', # intentionally not set
'network_id': network_id,
... | 0.004981 |
def getProcessStats(self):
"""Return stats for running and blocked processes, forks,
context switches and interrupts.
@return: Dictionary of stats.
"""
info_dict = {}
try:
fp = open(cpustatFile, 'r')
data = fp.read()
... | 0.009126 |
def drag(self, node):
""" Drags given node to mouse location.
"""
dx = self.mouse.x - self.graph.x
dy = self.mouse.y - self.graph.y
# A dashed line indicates the drag vector.
s = self.graph.styles.default
self._ctx.nofill()
self._ctx.nostroke()
... | 0.012277 |
def copyto(self, other):
"""Copies the value of this array to another array.
If ``other`` is a ``NDArray`` object, then ``other.shape`` and
``self.shape`` should be the same. This function copies the value from
``self`` to ``other``.
If ``other`` is a context, a new ``NDArray``... | 0.003043 |
def main(*args):
r"""Bootstrap Python projects and libraries with virtualenv and pip.
Also check system requirements before bootstrap and run post bootstrap
hook if any.
:param \*args: Command line arguments list.
"""
# Create parser, read arguments from direct input or command line
with d... | 0.000597 |
def cdl_addmon(self, source_url, save_path = '/', timeout = 3600):
''' Usage: cdl_addmon <source_url> [save_path] [timeout] - add an offline (cloud) download task and monitor the download progress
source_url - the URL to download file from.
save_path - path on PCS to save file to. default is to save to root direc... | 0.028 |
def _transform_col(self, x, i):
"""Encode one categorical column into average target values.
Args:
x (pandas.Series): a categorical column to encode
i (int): column index
Returns:
x (pandas.Series): a column with labels.
"""
return x.fillna(NAN... | 0.007916 |
def join_path(self, *path):
""" Unite entries to generate a single path
:param path: path items to unite
:return: str
"""
path = self.directory_sep().join(path)
return self.normalize_path(path) | 0.038647 |
def runExperiment(args, model=None):
"""
Run a single OPF experiment.
.. note:: The caller is responsible for initializing python logging before
calling this function (e.g., import :mod:`nupic.support`;
:meth:`nupic.support.initLogging`)
See also: :meth:`.initExperimentPrng`.
:param args: (string... | 0.007583 |
def partitions_for_topic(self, topic):
"""Return set of all partitions for topic (whether available or not)
Arguments:
topic (str): topic to check for partitions
Returns:
set: {partition (int), ...}
"""
if topic not in self._partitions:
retur... | 0.005305 |
def calc_nfw(self, rbins, offsets=None, numTh=200, numRoff=200,
numRinner=20, factorRouter=3):
"""Calculates Sigma and DeltaSigma profiles.
Generates the surface mass density (sigma_nfw attribute of parent
object) and differential surface mass density (deltasigma_nfw
at... | 0.001004 |
def remove_exclude_regions(orig_bed, base_file, items, remove_entire_feature=False):
"""Remove centromere and short end regions from an existing BED file of regions to target.
"""
from bcbio.structural import shared as sshared
out_bed = os.path.join("%s-noexclude.bed" % (utils.splitext_plus(base_file)[0... | 0.007557 |
def archive_model(serialization_dir: str,
weights: str = _DEFAULT_WEIGHTS,
files_to_archive: Dict[str, str] = None,
archive_path: str = None) -> None:
"""
Archive the model weights, its training configuration, and its
vocabulary to `model.tar.gz`. Includ... | 0.002374 |
def remove_janitor(self, janitor):
"""Remove janitor from the room"""
if not self.owner and not self.admin:
raise RuntimeError("Not enough street creed to do this")
janitor = janitor.strip().lower()
if not janitor:
raise ValueError("Empty strings cannot be janit... | 0.00396 |
def set_orientation(self, orientation='landscape'):
"""Set the video orientation.
Return a coroutine.
"""
if orientation not in ALLOWED_ORIENTATIONS:
_LOGGER.debug('%s is not a valid orientation', orientation)
return False
return self.change_setting('orie... | 0.005848 |
def _subset(subset, superset):
"""True if subset is a subset of superset.
:param dict subset: subset to compare.
:param dict superset: superset to compare.
:return: True iif all pairs (key, value) of subset are in superset.
:rtype: bool
"""
result = True
for k in subset:
result... | 0.002358 |
def _patch_expand_paths(self, settings, name, value):
"""
Apply ``SettingsPostProcessor._patch_expand_path`` to each element in
list.
Args:
settings (dict): Current settings.
name (str): Setting name.
value (list): List of paths to patch.
Ret... | 0.004065 |
def call_async(func):
"""Decorates a function to be called async on the loop thread"""
@wraps(func)
def wrapper(self, *args, **kw):
"""Wraps instance method to be called on loop thread"""
def call():
"""Calls function on loop thread"""
try:
func(self... | 0.001783 |
def mathjax_for_markdown(pelicanobj, mathjax_script, mathjax_settings):
"""Instantiates a customized markdown extension for handling mathjax
related content"""
# Create the configuration for the markdown template
config = {}
config['mathjax_script'] = mathjax_script
config['math_tag_class'] = '... | 0.007049 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.