text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _child_allowed(self, child_rule):
"""Called to verify that the given rule can become a child of the
current node.
:raises AttributeError:
if the child is not allowed
"""
num_kids = self.node.children.count()
num_kids_allowed = len(self.rule.children)
... | 0.003964 |
def scan(self, ids=range(254)):
""" Pings all ids within the specified list, by default it finds all the motors connected to the bus. """
return [id for id in ids if self.ping(id)] | 0.015306 |
def close_thread_handles(self):
"""
Closes all open handles to threads in the snapshot.
"""
for aThread in self.iter_threads():
try:
aThread.close_handle()
except Exception:
try:
e = sys.exc_info()[1]
... | 0.003738 |
def apply_types(use_types, guess_type, line):
"""Apply the types on the elements of the line"""
new_line = {}
for k, v in line.items():
if use_types.has_key(k):
new_line[k] = force_type(use_types[k], v)
elif guess_type:
new_line[k] = determine_type(v)
else:
... | 0.005479 |
def json_export(self, dest, fieldnames=None, encoding="UTF-8"):
"""Exports the contents of the table to a JSON-formatted file.
@param dest: output file - if a string is given, the file with that name will be
opened, written, and closed; if a file object is given, then that object
... | 0.007092 |
def pop_empty_columns(self, empty=None):
"""
This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty
"""
empty = ['', None] if empty is None else empty
if len(self) == 0:
ret... | 0.003868 |
def migrate_keys(self, host, port, keys, dest_db, timeout, *,
copy=False, replace=False):
"""Atomically transfer keys from one Redis instance to another one.
Keys argument must be list/tuple of keys to migrate.
"""
if not isinstance(host, str):
raise Typ... | 0.002285 |
def uncrop(data, crinfo, orig_shape, resize=False, outside_mode="constant", cval=0):
"""
Put some boundary to input image.
:param data: input data
:param crinfo: array with minimum and maximum index along each axis
[[minX, maxX],[minY, maxY],[minZ, maxZ]]. If crinfo is None, the whole input im... | 0.002393 |
def OnMouseWheel(self, event):
"""Event handler for mouse wheel actions
Invokes zoom when mouse when Ctrl is also pressed
"""
if event.ControlDown():
if event.WheelRotation > 0:
post_command_event(self.grid, self.grid.ZoomInMsg)
else:
... | 0.001712 |
def __lstring(self,lstr):
"""
Returns a parsed lstring by stripping out and instances of
the escaped delimiter. Sometimes the raw lstring has whitespace
and a double quote at the beginning or end. If present, these
are removed.
"""
lstr = self.llsrx.sub('',lstr.encode('ascii'))
lstr = se... | 0.011655 |
def save_post(self, title, text, user_id, tags, draft=False,
post_date=None, last_modified_date=None, meta_data=None,
post_id=None):
"""
Persist the blog post data. If ``post_id`` is ``None`` or ``post_id``
is invalid, the post must be inserted into the storag... | 0.001282 |
def poke_16(library, session, address, data):
"""Write an 16-bit value from the specified address.
Corresponds to viPoke16 function of the VISA library.
:param library: the visa library wrapped by ctypes.
:param session: Unique logical identifier to a session.
:param address: Source address to rea... | 0.001862 |
def create_modules_toc_file(master_package, modules, opts, name='modules'):
"""
Create the module's index.
"""
text = format_heading(1, '%s Modules' % opts.header)
text += '.. toctree::\n'
text += ' :maxdepth: %s\n\n' % opts.maxdepth
modules.sort()
prev_module = ''
for module in m... | 0.001776 |
def urlencode_utf8(params):
"""
UTF-8 safe variant of urllib.urlencode.
http://stackoverflow.com/a/8152242
"""
if hasattr(params, 'items'):
params = params.items()
params = (
'='.join((
quote_plus(k.encode('utf8'), safe='/'),
quote_plus(v.encode('utf8'), s... | 0.002551 |
def _add_sample_measure(self, measure_params, num_samples):
"""Generate memory samples from current statevector.
Args:
measure_params (list): List of (qubit, cmembit) values for
measure instructions to sample.
num_samples (int): The number of m... | 0.001601 |
def scan_line(self, line, regex):
"""Checks if regex is in line, returns bool"""
return bool(re.search(regex, line, flags=re.IGNORECASE)) | 0.013072 |
def _pre_heat_deploy(self):
"""Setup before the Heat stack create or update has been done."""
clients = self.app.client_manager
compute_client = clients.compute
self.log.debug("Checking hypervisor stats")
if utils.check_hypervisor_stats(compute_client) is None:
raise... | 0.004751 |
def fit_transform(self, data):
"""
Fits and transforms the SFrame `data` using a fitted model.
Parameters
----------
data : SFrame
The data to be transformed.
Returns
-------
A transformed SFrame.
Returns
-------
out... | 0.005068 |
def ssn(self, min_age=18, max_age=90):
"""
Returns a 10 digit Swedish SSN, "Personnummer".
It consists of 10 digits in the form YYMMDD-SSGQ, where
YYMMDD is the date of birth, SSS is a serial number
and Q is a control character (Luhn checksum).
http://en.wikipedia.org/w... | 0.001425 |
def store(self, t, step):
"""
Record the state/algeb values at time t to self.vars
"""
max_cache = int(self.system.tds.config.max_cache)
if len(self.vars) >= max_cache > 0:
self.dump()
self.vars = list()
self.t = list()
self.k = lis... | 0.002048 |
def archive_context(filename):
"""
Unzip filename to a temporary directory, set to the cwd.
The unzipped target is cleaned up after.
"""
tmpdir = tempfile.mkdtemp()
log.warn('Extracting in %s', tmpdir)
old_wd = os.getcwd()
try:
os.chdir(tmpdir)
try:
with Cont... | 0.001138 |
def calc_constitutive_matrix(self):
"""Calculates the laminate constitutive matrix
This is the commonly called ``ABD`` matrix with ``shape=(6, 6)`` when
the classical laminated plate theory is used, or the ``ABDE`` matrix
when the first-order shear deformation theory is used, containing... | 0.003546 |
def in_region(rname, rstart, target_chr, target_start, target_end):
"""
Quick check if a point is within the target region.
"""
return (rname == target_chr) and \
(target_start <= rstart <= target_end) | 0.004386 |
def collect_population_best(self, best_chromosome, best_fitness_function):
"""!
@brief Stores the best chromosome for current specific iteration and its fitness function's value.
@param[in] best_chromosome (list): The best chromosome on specific iteration.
@param[in] best_fitnes... | 0.012739 |
def handle(self, *args, **options):
"""
get all the triggers that need to be handled
"""
from django.db import connection
connection.close()
failed_tries = settings.DJANGO_TH.get('failed_tries', 10)
trigger = TriggerService.objects.filter(
Q(provid... | 0.00226 |
def K(self):
"""Kernel matrix
Returns
-------
K : array-like, shape=[n_samples, n_samples]
kernel matrix defined as the adjacency matrix with
ones down the diagonal
"""
try:
return self._kernel
except AttributeError:
... | 0.005141 |
def from_jd(jd):
'''Return Gregorian date in a (Y, M, D) tuple'''
wjd = floor(jd - 0.5) + 0.5
depoch = wjd - EPOCH
quadricent = floor(depoch / INTERCALATION_CYCLE_DAYS)
dqc = depoch % INTERCALATION_CYCLE_DAYS
cent = floor(dqc / LEAP_SUPPRESSION_DAYS)
dcent = dqc % LEAP_SUPPRESSION_DAYS
... | 0.00104 |
def from_jd(jd):
'''Calculate Indian Civil date from Julian day
Offset in years from Saka era to Gregorian epoch'''
start = 80
# Day offset between Saka and Gregorian
jd = trunc(jd) + 0.5
greg = gregorian.from_jd(jd) # Gregorian date for Julian day
leap = isleap(greg[0]) # Is this a leap... | 0.000864 |
def get_event_attendees(self, id, **data):
"""
GET /events/:id/attendees/
Returns a :ref:`paginated <pagination>` response with a key of ``attendees``, containing a list of :format:`attendee`.
"""
return self.get("/events/{0}/attendees/".format(id), data=data) | 0.012945 |
def _load_text(handle, split=False, encoding="utf-8"):
"""Load and decode a string."""
string = handle.read().decode(encoding)
return string.splitlines() if split else string | 0.005376 |
def add(self, date_range, library_name):
"""
Adds the library with the given date range to the underlying collection of libraries used by this store.
The underlying libraries should not overlap as the date ranges are assumed to be CLOSED_CLOSED by this function
and the rest of the class.... | 0.007989 |
def setModelData( self, editor, model, index ):
"""
Sets the data for the given index from the editor's value.
:param editor | <QWidget>
model | <QAbstractItemModel>
index | <QModelIndex>
"""
tree = self.paren... | 0.016729 |
def add_prefix(self, prefix, flags, prf):
"""Add network prefix.
Args:
prefix (str): network prefix.
flags (str): network prefix flags, please refer thread documentation for details
prf (str): network prf, please refer thread documentation for details
"""
... | 0.009112 |
def pretty_print_model(devicemodel):
"""Prints out a device model in the terminal by parsing dict."""
PRETTY_PRINT_MODEL = """Device Model ID: %(deviceModelId)s
Project ID: %(projectId)s
Device Type: %(deviceType)s"""
logging.info(PRETTY_PRINT_MODEL % devicemodel)
if 'traits' in devicemo... | 0.002058 |
def is_scn(self):
"""Page contains Leica SCN XML in ImageDescription tag."""
if self.index > 1 or not self.description:
return False
d = self.description
return d[:14] == '<?xml version=' and d[-6:] == '</scn>' | 0.007874 |
def get_artifact(self):
"""Return the job artifact built by the parser."""
self.artifact[self.parser.name] = self.parser.get_artifact()
return self.artifact | 0.011111 |
def get_vars_dataframe(self, *varnames):
"""
Return pandas DataFrame with the value of the variables specified in `varnames`.
Can be used for task/works/flow. It's recursive!
.. example:
flow.get_vars_dataframe("ecut", "ngkpt")
work.get_vars_dataframe("acell", "... | 0.00504 |
def subtract_months(self, months: int) -> datetime:
""" Subtracts a number of months from the current value """
self.value = self.value - relativedelta(months=months)
return self.value | 0.009615 |
def _init_fcp_pool(self, fcp_list, assigner_id):
"""The FCP infomation got from smt(zthin) looks like :
host: FCP device number: xxxx
host: Status: Active
host: NPIV world wide port number: xxxxxxxx
host: Channel path ID: xx
host: Physical world wid... | 0.00105 |
def get_column(self, position, missing_seqs=MissingSequenceHandler.SKIP):
"""
return a column from an alignment as a dictionary indexed by seq. name.
:param position: the index to extract; these are in alignment
co-ordinates, which are one-based, so the first column
... | 0.005025 |
def account_products(self):
''' a method to retrieve a list of the account products
returns:
{
"error": "",
"code": 200,
"method": "GET",
"url": "https://...",
"headers": { },
"jso... | 0.008578 |
def _map_sextuple_to_phenotype(
self, superterm1_id, subterm1_id, quality_id, superterm2_id,
subterm2_id, modifier):
"""
This will take the 6-part EQ-style annotation
used by ZFIN and return the ZP id.
Currently relies on an external mapping file,
but the ... | 0.00131 |
def refresh_client(self, from_dt=None, to_dt=None):
"""
Refreshes the ContactsService endpoint, ensuring that the
contacts data is up-to-date.
"""
params_contacts = dict(self.params)
params_contacts.update({
'clientVersion': '2.1',
'locale': 'en_US... | 0.002134 |
def noclip(args):
"""
%prog noclip bamfile
Remove clipped reads from BAM.
"""
p = OptionParser(noclip.__doc__)
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
bamfile, = args
noclipbam = bamfile.replace(".bam", ".noclip.bam")
cmd = "samt... | 0.001988 |
def sensors(self):
"""Return all known sensors.
:return: list of :class:`Sensor` instances.
"""
sensors = []
try:
while True:
sensor = self.lib.tdSensor()
sensors.append(Sensor(lib=self.lib, **sensor))
except TelldusError as e:... | 0.00464 |
def count_reads(self, l):
"""
Iterate over the reads on a particular genome in the bam file.
Parameters
----------
l : str
A location.
"""
if self.__paired:
cmd = [self.__samtools, 'view', '-c', '-f', '3', self.__bam, l]
... | 0.015528 |
def get_swagger_operation(self, context=default_context):
"""
get the swagger_schema operation representation.
"""
consumes = produces = context.contenttype_serializers.keys()
parameters = get_swagger_parameters(self.parameters, context)
responses = {
"400": R... | 0.001371 |
def check_topic_model_string_format(term_dict):
'''
Parameters
----------
term_dict: dict {metadataname: [term1, term2, ....], ...}
Returns
-------
None
'''
if type(term_dict) != dict:
raise TypeError("Argument for term_dict must be a dict, keyed on strings, and contain a li... | 0.003676 |
def import_object_ns(name_space, import_str, *args, **kwargs):
"""Tries to import object from default namespace.
Imports a class and return an instance of it, first by trying
to find the class in a default namespace, then failing back to
a full path if not found in the default namespace.
"""
im... | 0.001938 |
def build_all(self) -> BuildProcessStats:
"""
Build all the targets, very high level method
:return:
"""
stats = BuildProcessStats()
for builder in self.builders:
self.build_by_builder(
builder=builder,
stats=stats,
... | 0.005848 |
def _wait_for_files(path):
"""
Retry with backoff up to 1 second to delete files from a directory.
:param str path: The path to crawl to delete files from
:return: A list of remaining paths or None
:rtype: Optional[List[str]]
"""
timeout = 0.001
remaining = []
while timeout < 1.0:
... | 0.001075 |
def install(self, build_dir, install_dir=None, **kwargs):
"""This function builds the cmake install command."""
# pylint: disable=no-self-use
del kwargs
install_args = ["cmake", "--build", build_dir, "--target", "install"]
install_args.extend(self._get_build_flags())
if i... | 0.00463 |
def sanitize_latex(string):
"""
Sanitize a string for input to LaTeX.
Replacements taken from `Stack Overflow
<http://stackoverflow.com/questions/2627135/how-do-i-sanitize-latex-input>`_
**Parameters**
string: str
**Returns**
sanitized_string: str
"""
sanitized_string = stri... | 0.002208 |
def _read_credential_file(self, cfg):
"""
Implements the default (keystone) behavior.
"""
self.username = cfg.get("keystone", "username")
self.password = cfg.get("keystone", "password", raw=True)
self.tenant_id = cfg.get("keystone", "tenant_id") | 0.006826 |
def draw_salt_bridges(self,color="blue"):
"""
For each bond that has been determined to be important, a line gets drawn.
"""
self.draw_saltbridges=""
if self.saltbridges!=None:
for bond in self.saltbridges.saltbridges_for_drawing:
self.draw_saltbridges ="<g class='SaltBridges' transform='translate("+st... | 0.019858 |
def Run(self, arg):
"""Returns the client stats."""
if arg is None:
arg = rdf_client_action.GetClientStatsRequest()
proc = psutil.Process(os.getpid())
meminfo = proc.memory_info()
boot_time = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(psutil.boot_time())
create_time = rdfvalue.RDFDatetime... | 0.002735 |
def follow(self, delay=1.0):
"""\
Iterator generator that returns lines as data is added to the file.
Based on: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/157035
"""
# TODO: Handle log file rotation
self.trailing = True
unchanged_stats = 0
... | 0.004397 |
def original_failure(self):
"""
Return the underlying Failure object, if the result is an error.
If no result is yet available, or the result was not an error, None is
returned.
This method is useful if you want to get the original traceback for an
error result.
... | 0.003752 |
def unpack(self, unpacker):
"""
Unpacks the constant pool from an unpacker stream
"""
(count, ) = unpacker.unpack_struct(_H)
# first item is never present in the actual data buffer, but
# the count number acts like it would be.
items = [(None, None), ]
c... | 0.002081 |
def _prepend_name_prefix(self, name):
"""Return file name (ie. path) with the prefix directory prepended"""
if not self.name_prefix:
return name
base = self.name_prefix
if base[0] != '/':
base = '/' + base
if name[0] != '/':
name = '/' + name
... | 0.005797 |
def _handler_swagger_ui(self, request, spec, version):
"""
---
parameters:
- name: spec
in: query
type: string
- name: version
in: query
type: integer
enum: [2,3]
"""
version = version or self._versio... | 0.001639 |
def main(target_device):
"""Creates an interactive terminal to the target via RTT.
The main loop opens a connection to the JLink, and then connects
to the target device. RTT is started, the number of buffers is presented,
and then two worker threads are spawned: one for read, and one for write.
Th... | 0.001341 |
def write_to_ndef_service(self, data, *blocks):
"""Write block data to an NDEF compatible tag.
This is a convinience method to write block data to a tag that
has system code 0x12FC (NDEF). For other tags this method
simply does nothing. The *data* to write must be a string or
by... | 0.001918 |
def get_method(name):
"""Return the PSD method registered with the given name.
"""
# find method
name = _format_name(name)
try:
return METHODS[name]
except KeyError as exc:
exc.args = ("no PSD method registered with name {0!r}".format(name),)
raise | 0.003378 |
def build_environ(scope: Scope, body: bytes) -> dict:
"""
Builds a scope and request body into a WSGI environ object.
"""
environ = {
"REQUEST_METHOD": scope["method"],
"SCRIPT_NAME": scope.get("root_path", ""),
"PATH_INFO": scope["path"],
"QUERY_STRING": scope["query_str... | 0.001208 |
def _sampler_n_samples(self, n_samples):
""" Return (sampler, n_samplers) tuples """
sampler_indices = self.rng_.choice(range(len(self.samplers)),
size=n_samples,
replace=True,
... | 0.004367 |
def train(self, data_iterator):
"""Train a keras model on a worker
"""
optimizer = get_optimizer(self.master_optimizer)
self.model = model_from_yaml(self.yaml, self.custom_objects)
self.model.compile(optimizer=optimizer,
loss=self.master_loss, metrics=s... | 0.001791 |
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types):
"""
See :meth:`superclass method
<.base.GroundShakingIntensityModel.get_mean_and_stddevs>`
for spec of input and result values.
"""
# extracting dictionary of coefficients specific to required
#... | 0.002342 |
def track_download_request(download_url, download_title):
"""Track a download in Piwik"""
from indico_piwik.plugin import PiwikPlugin
if not download_url:
raise ValueError("download_url can't be empty")
if not download_title:
raise ValueError("download_title can't be empty")
reques... | 0.002139 |
def decrypt_or_cache(filename, **kwargs):
"""
Attempts to load a local version of decrypted secrets before making external api calls.
This is useful as it allows credkeep secrets to be used offline. Options for decrypt_filename can be passed to this
function.
:param filename: filename of encrypted ... | 0.005556 |
def date_created(self):
"""Date the Scopus record was created."""
date_created = self.xml.find('author-profile/date-created', ns)
try:
return (int(date_created.attrib['year']),
int(date_created.attrib['month']),
int(date_created.attrib['day']))... | 0.004843 |
def get_default_config_help(self):
"""
Return help text
"""
config_help = super(PassengerCollector, self).get_default_config_help()
config_help.update({
"bin": "The path to the binary",
"use_sudo": "Use sudo?",
"sudo_cmd": "Path t... | 0.00339 |
def _syntax_style_changed(self):
""" Set the style for the syntax highlighter.
"""
if self._highlighter is None:
# ignore premature calls
return
if self.syntax_style:
self._highlighter.set_style(self.syntax_style)
else:
self._highli... | 0.005571 |
def download_supplementary_files(self, directory='series',
download_sra=True, email=None,
sra_kwargs=None, nproc=1):
"""Download supplementary data.
.. warning::
Do not use parallel option (nproc > 1) in the interact... | 0.001987 |
def dhcp_configuration_from_querystring(querystring, option=u'DhcpConfiguration'):
"""
turn:
{u'AWSAccessKeyId': [u'the_key'],
u'Action': [u'CreateDhcpOptions'],
u'DhcpConfiguration.1.Key': [u'domain-name'],
u'DhcpConfiguration.1.Value.1': [u'example.com'],
u'DhcpConf... | 0.002004 |
def create(self, language, tagged_text, source_channel=values.unset):
"""
Create a new SampleInstance
:param unicode language: The ISO language-country string that specifies the language used for the new sample
:param unicode tagged_text: The text example of how end users might express ... | 0.006024 |
def get_nameserver_detail_output_show_nameserver_nameserver_connected_via_ag(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_nameserver_detail = ET.Element("get_nameserver_detail")
config = get_nameserver_detail
output = ET.SubElement(get_nam... | 0.007134 |
def guess_datetime_format(lines: Iterable[str], threshold: int=5) \
-> Tuple[Optional[str], Optional[bool]]:
'''Guess whether order of the year, month, day and 12/24 hour.
Returns:
tuple: First item is either str ``ymd``, ``dmy``, ``mdy``
or ``None``.
Second item is either True ... | 0.001629 |
def launcher(deploy_mode, args, working_dir=".", cleanup=True):
"""Initializes arguments and starts up pyspark with the correct deploy mode and environment.
Parameters
----------
deploy_mode : {"client", "cluster"}
args : list
Arguments to pass onwards to spark submit.
working_dir : str... | 0.004084 |
def connect(cls, region, session=None, access_key=None, secret_key=None,
host=None, port=80, is_secure=True, **kwargs):
"""
Connect to an AWS region.
Parameters
----------
region : str
Name of an AWS region
session : :class:`~botocore.session.... | 0.001989 |
def evaluate(data):
"""Provide evaluations for multiple callers split by structural variant type.
"""
work_dir = utils.safe_makedir(os.path.join(data["dirs"]["work"], "structural",
dd.get_sample_name(data), "validate"))
truth_sets = tz.get_in(["config", "al... | 0.007647 |
def rot_consts(geom, masses, units=_EURC.INV_INERTIA, on_tol=_DEF.ORTHONORM_TOL):
"""Rotational constants for a given molecular system.
Calculates the rotational constants for the provided system with numerical
value given in the units provided in `units`. The orthnormality tolerance
`on_tol` is requi... | 0.001702 |
def restrict(self, restriction):
"""
In-place restriction. Restricts the result to a specified subset of the input.
rel.restrict(restriction) is equivalent to rel = rel & restriction or rel &= restriction
rel.restrict(Not(restriction)) is equivalent to rel = rel - restriction or ... | 0.00509 |
def basic_set_of_users_exists_in_the_database(context):
"""
:type context: behave.runner.Context
"""
user_model = get_user_model()
user_model.objects.create(
username='administrator',
is_staff=True
)
user_model.objects.create(
username='allowed_user'
)
... | 0.002545 |
async def mount(self, device):
"""
Mount the device if not already mounted.
:param device: device object, block device path or mount path
:returns: whether the device is mounted.
"""
device = self._find_device(device)
if not self.is_handleable(device) or not devi... | 0.002151 |
def add_router_to_hosting_device(self, context, hosting_device_id,
router_id):
"""Add a (non-hosted) router to a hosting device."""
e_context = context.elevated()
r_hd_binding_db = self._get_router_binding_info(e_context, router_id)
if r_hd_binding_db... | 0.001992 |
def get_current_index(self):
""" Return currently selected index (or -1) """
# Need to convert to int; currently API returns a tuple of string
curSel = self.__lb.curselection()
if curSel and len(curSel) > 0:
return int(curSel[0])
else:
return -1 | 0.006452 |
def filter(cls, parent=None, **filters):
"""
Gets all resources of the given type and parent (if provided) which match the given filters.
This will trigger an api GET request.
:param parent ResourceBase: the parent of the resource - used for nesting the request url, optional
:par... | 0.00885 |
def read(self):
"""Read a Response, do some validation, and return it."""
if FLAGS.sc2_verbose_protocol:
self._log(" Reading response ".center(60, "-"))
start = time.time()
response = self._read()
if FLAGS.sc2_verbose_protocol:
self._log(" %0.1f msec\n" % (1000 * (time.time() - start))... | 0.010204 |
def get_cousins_treepos(self, treepos):
"""Given a treeposition, return the treeposition of its siblings."""
cousins_pos = []
mother_pos = self.get_parent_treepos(treepos)
if mother_pos is not None:
aunts_pos = self.get_siblings_treepos(mother_pos)
for aunt_pos i... | 0.009238 |
def add_image(self, image_path, annotations):
"""Adds an image and its bounding boxes to the current list of files
The bounding boxes are automatically estimated based on the given annotations.
**Parameters:**
``image_path`` : str
The file name of the image, including its full path
``annot... | 0.005944 |
def get_file(self):
"""
Load data into a file and return file path.
:return: path to file as string
"""
content = self._load()
if not content:
return None
filename = "temporary_file.bin"
with open(filename, "wb") as file_name:
file... | 0.005495 |
def redundancy_output_rd_mesg(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
redundancy = ET.Element("redundancy")
config = redundancy
output = ET.SubElement(redundancy, "output")
rd_mesg = ET.SubElement(output, "rd_mesg")
rd_mes... | 0.004535 |
def parse_args(argv):
"""
Use Argparse to parse command-line arguments.
:param argv: list of arguments to parse (``sys.argv[1:]``)
:type argv: :std:term:`list`
:return: parsed arguments
:rtype: :py:class:`argparse.Namespace`
"""
p = argparse.ArgumentParser(
description='webhook2... | 0.001091 |
def get_model_agents(self):
"""Return a list of all Agents from all Statements.
Returns
-------
agents : list[indra.statements.Agent]
A list of Agents that are in the model.
"""
model_stmts = self.get_statements()
agents = []
for stmt in model_... | 0.004357 |
async def fetch_room(self, room_id):
"""Lookup details for a given room id"""
url = "https://production.plum.technology/v2/getRoom"
data = {"rid": room_id}
return await self.__post(url, data) | 0.008969 |
def get_bgp_neighbors(self):
def generate_vrf_query(vrf_name):
"""
Helper to provide XML-query for the VRF-type we're interested in.
"""
if vrf_name == "global":
rpc_command = '<Get><Operational><BGP><InstanceTable><Instance><Naming>\
... | 0.004847 |
def save_related(self, request, form, formsets, change):
"""
Given the ``HttpRequest``, the parent ``ModelForm`` instance, the
list of inline formsets and a boolean value based on whether the
parent is being added or changed, save the related objects to the
database. Note that at... | 0.003759 |
def flatten(dic, keep_iter=False, position=None):
"""
Returns a flattened dictionary from a dictionary of nested dictionaries and lists.
`keep_iter` will treat iterables as valid values, while also flattening them.
"""
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
... | 0.004144 |
def Parse(self, raw_data):
"""Take the results and yield results that passed through the filters.
The output of each filter is used as the input for successive filters.
Args:
raw_data: An iterable series of rdf values.
Returns:
A list of rdf values that matched all filters.
"""
se... | 0.004598 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.