text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def convert_meas(direction, Rec):
"""
converts measurments tables from magic 2 to 3 (direction=magic3)
or from model 3 to 2.5 (direction=magic2) [not available]
"""
if direction == 'magic3':
columns = meas_magic2_2_magic3_map
MeasRec = {}
for key in columns:
if ke... | 0.001852 |
def remove_rule(self, rule):
"""Remove rule from :attr:`R` and its corresponding weight from
:attr:`W`.
:param rule: rule to remove
:type rule:
:class:`~creamas.rules.rule.Rule` or
:class:`~creamas.rules.rule.RuleLeaf`
:raises TypeError:
If ru... | 0.003344 |
def get_page_number_from_request(
request, querystring_key=PAGE_LABEL, default=1):
"""Retrieve the current page number from *GET* or *POST* data.
If the page does not exists in *request*, or is not a number,
then *default* number is returned.
"""
try:
if request.method == 'POST':
... | 0.001838 |
def do_open(self, mode=None):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
Note: Copied from stdlib. Added option to override 'mode'
"""
if mode is None:
mode = self.mode
with self._alter_umask(... | 0.005338 |
def get_all_db_ids(language=DEFAULT_LANG):
"""
:return: A list with all the database IDs as integers
"""
_ids = []
json_path = DBVuln.get_json_path(language=language)
for _file in os.listdir(json_path):
if not _file.endswith('.json'):
continu... | 0.004878 |
def render_text(text, language=None):
"""
Render the text, reuses the template filters provided by Django.
"""
# Get the filter
text_filter = SUPPORTED_LANGUAGES.get(language, None)
if not text_filter:
raise ImproperlyConfigured("markup filter does not exist: {0}. Valid options are: {1}"... | 0.004444 |
def _root(self):
"""Attribute referencing the root node of the tree.
:returns: the root node of the tree containing this instance.
:rtype: Node
"""
_n = self
while _n.parent:
_n = _n.parent
return _n | 0.007463 |
def load_edges_into_db(
nanopub_id: str,
nanopub_url: str,
edges: list = [],
edges_coll_name: str = edges_coll_name,
nodes_coll_name: str = nodes_coll_name,
):
"""Load edges into Edgestore"""
start_time = datetime.datetime.now()
# Clean out edges for nanopub in edgestore
query = f"... | 0.000383 |
def add_arguments(parser):
"""
adds arguments for the deploy command
"""
parser.add_argument('-e', '--environment', help='Environment name', required=True)
parser.add_argument('-w', '--dont-wait', help='Skip waiting', action='store_true')
parser.add_argument('-a', '--archive', help='Archive file... | 0.007123 |
def _attach_dummy_intf_rtr(self, tenant_id, tenant_name, rtr_id):
"""Function to create a dummy router and interface. """
serv_obj = self.get_service_obj(tenant_id)
fw_dict = serv_obj.get_fw_dict()
fw_id = fw_dict.get('fw_id')
rtr_nwk = fw_id[0:4] + fw_const.DUMMY_SERVICE_NWK + (... | 0.001667 |
def which_users_can(self, name):
"""Which role can SendMail? """
_roles = self.which_roles_can(name)
result = [self.get_role_members(i.get('role')) for i in _roles]
return result | 0.014218 |
def _numpy_char_to_bytes(arr):
"""Like netCDF4.chartostring, but faster and more flexible.
"""
# based on: http://stackoverflow.com/a/10984878/809705
arr = np.array(arr, copy=False, order='C')
dtype = 'S' + str(arr.shape[-1])
return arr.view(dtype).reshape(arr.shape[:-1]) | 0.003378 |
def empty_file(file, mode="w", encoding='utf-8'):
"""empty file"""
with open(file, mode, encoding=encoding) as f:
f.truncate() | 0.007042 |
def convert_dict2tuple(value):
"""
convert dict type to tuple to solve unhashable problem.
"""
if isinstance(value, dict):
for _keys in value:
value[_keys] = convert_dict2tuple(value[_keys])
return tuple(sorted(value.items()))
else:
return value | 0.003322 |
def nlargest(self, n, columns, keep='first'):
"""
Return the first `n` rows ordered by `columns` in descending order.
Return the first `n` rows with the largest values in `columns`, in
descending order. The columns that are not specified are returned as
well, but not used for or... | 0.000444 |
def matches(self, txt: str) -> bool:
"""Determine whether txt matches pattern
:param txt: text to check
:return: True if match
"""
# rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape')
if r'\\u' in self.pattern_re.pattern:
txt = txt.encode('ut... | 0.004405 |
async def on_raw_quit(self, message):
""" QUIT command. """
nick, metadata = self._parse_user(message.source)
self._sync_user(nick, metadata)
if message.params:
reason = message.params[0]
else:
reason = None
await self.on_quit(nick, reason)
... | 0.003663 |
def load_adjustment_values(self, c):
"""load adjustment values for auto shape types in self"""
# retrieve auto shape types in const_name order --------
for mast in self:
# retriev adj vals for this auto shape type --------
c.execute(
' SELECT name, val\n'... | 0.003534 |
def onecmd_plus_hooks(self, line):
''' Trigger hooks after command. '''
if not line:
return self.emptyline()
return Cmd.onecmd_plus_hooks(self, line) | 0.010811 |
def update_api_key_description(apiKey, description, region=None, key=None, keyid=None, profile=None):
'''
update the given apiKey with the given description.
CLI Example:
.. code-block:: bash
salt myminion boto_apigateway.update_api_key_description api_key description
'''
try:
... | 0.006079 |
def execCommand(g, command, timeout=10):
"""
Executes a command by sending it to the rack server
Arguments:
g : hcam_drivers.globals.Container
the Container object of application globals
command : (string)
the command (see below)
Possible commands are:
start : s... | 0.000655 |
def _partialParseModifier(self, s, sourceTime):
"""
test if giving C{s} matched CRE_MODIFIER, used by L{parse()}
@type s: string
@param s: date/time text to evaluate
@type sourceTime: struct_time
@param sourceTime: C{struct_time} value to use as the b... | 0.001608 |
def _initialize_operation_name_to_id(self):
"""Initializer for _operation_name_to_id.
Returns:
a {string: int}, mapping operation names to their index in _operations.
"""
operation_name_to_id = {}
for i, operation in enumerate(self._operations):
operation_name_to_id[operation.name] = i
... | 0.005698 |
def parse_assign_target(self, with_tuple=True, name_only=False,
extra_end_rules=None, with_namespace=False):
"""Parse an assignment target. As Jinja2 allows assignments to
tuples, this function can parse all allowed assignment targets. Per
default assignments to tup... | 0.001952 |
def _get_mine(fun):
'''
Return the mine function from all the targeted minions.
Just a small helper to avoid redundant pieces of code.
'''
if fun in _CACHE and _CACHE[fun]:
return _CACHE[fun]
net_runner_opts = _get_net_runner_opts()
_CACHE[fun] = __salt__['mine.get'](net_runner_opts.... | 0.004141 |
def inverse(x, p, errorOnFail=False):
"""
Find the inverse of BigInt @x in a field of (prime) order @p.
"""
# Check types
assertType(x, BigInt)
# There are a number of ways in RELIC to compute this inverse, but
# for simplicity, we'll use the extended GCD algorithm because it
# involve... | 0.005097 |
def do_dq(self, arg):
"""
[~thread] dq <register> - show memory contents as qwords
[~thread] dq <register-register> - show memory contents as qwords
[~thread] dq <register> <size> - show memory contents as qwords
[~process] dq <address> - show memory contents as qwords
[~... | 0.003472 |
def render_template_directory(deck, arguments):
"""Render a template directory"""
output_directory = dir_name_from_title(deck.title)
if os.path.exists(output_directory):
if sys.stdout.isatty():
if ask(
'%s already exists, shall I delete it?' % output_directory,
... | 0.000797 |
def set(self, key, value, **kwargs):
"""
Set the value of a Parameter in the ParameterSet.
If :func:`get` would retrieve a Parameter, this will set the
value of that parameter.
Or you can provide 'value@...' or 'default_unit@...', etc
to specify what attribute to set.
... | 0.002838 |
def createFileParserCtxt(filename):
"""Create a parser context for a file content. Automatic
support for ZLIB/Compress compressed document is provided
by default if found at compile-time. """
ret = libxml2mod.xmlCreateFileParserCtxt(filename)
if ret is None:raise parserError('xmlCreateFileParse... | 0.008152 |
def add_download_task(self, source_url, remote_path,
rate_limit=None, timeout=60 * 60,
expires=None, callback='', **kwargs):
"""添加离线下载任务,实现单个文件离线下载.
:param source_url: 源文件的URL。
:param remote_path: 下载后的文件保存路径。
.. wa... | 0.00317 |
def inquire(self, name=True, lifetime=True, usage=True, mechs=True):
"""Inspect these credentials for information
This method inspects these credentials for information about them.
Args:
name (bool): get the name associated with the credentials
lifetime (bool): get the ... | 0.0018 |
def draw(self):
"""
Clear the terminal screen and redraw all of the sub-windows
"""
n_rows, n_cols = self.term.stdscr.getmaxyx()
if n_rows < self.term.MIN_HEIGHT or n_cols < self.term.MIN_WIDTH:
# TODO: Will crash when you try to navigate if the terminal is too
... | 0.003247 |
def user_info(self, verbose=False):
'''
Get information about the currently authenticated user
http://docs.opsview.com/doku.php?id=opsview4.6:restapi#user_information
'''
url = '{}/{}'.format(self.rest_url, 'user')
return self.__auth_req_get(url, verbose=verbose) | 0.006431 |
def on_episode_end(self, episode, logs):
""" Compute and print metrics at the end of each episode """
duration = timeit.default_timer() - self.starts[episode]
metrics = self.metrics[episode]
if np.isnan(metrics).all():
mean_metrics = np.array([np.nan for _ in self.metrics_n... | 0.003165 |
def index(self, state, code=None, error=None):
"""
Receive a Exist response containing a verification code. Use the code
to fetch the access_token.
"""
error = None
if code:
try:
auth_token = self.fetch_token(code, state)
except Mis... | 0.00222 |
def idxstats(in_bam, data):
"""Return BAM index stats for the given file, using samtools idxstats.
"""
index(in_bam, data["config"], check_timestamp=False)
AlignInfo = collections.namedtuple("AlignInfo", ["contig", "length", "aligned", "unaligned"])
samtools = config_utils.get_program("samtools", da... | 0.006033 |
def replication_state(self, repl_id):
"""
Retrieves the state for the given replication. Possible values are
``triggered``, ``completed``, ``error``, and ``None`` (meaning not yet
triggered).
:param str repl_id: Replication id used to identify the replication to
insp... | 0.003128 |
def tokens_required(service_list):
"""
Ensure the user has the necessary tokens for the specified services
"""
def decorator(func):
@wraps(func)
def inner(request, *args, **kwargs):
for service in service_list:
if service not in request.session["user_tokens"]:... | 0.002183 |
def sorted_members(self):
"""
Iterate over sorted members of shape in the same order in which
the members are declared except yielding the required members before
any optional members.
"""
members = collections.OrderedDict()
required_names = self.metadata.get("req... | 0.004587 |
def get_records(self, records=None, timeout=1.0):
"""Get NDEF message records from a SNEP Server.
.. versionadded:: 0.13
The :class:`ndef.Record` list given by *records* is encoded as
the request message octets input to :meth:`get_octets`. The
return value is an :class:`ndef.Re... | 0.002278 |
def make_postcard(self, npix=300, shape=(1070, 1132), buffer_size=15):
"""
Develop a "postcard" region around the target star.
Other stars in this postcard will be used as possible reference stars.
Args:
npix: The size of the postcard region. The region will be a sq... | 0.013402 |
def _docs(self):
"""
Since `self.docs` may yield documents that do not explicitly contain `_index` or `_type`,
add those attributes here, if necessary.
"""
iterdocs = iter(self.docs())
first = next(iterdocs)
needs_parsing = False
if isinstance(first, six.s... | 0.003663 |
def get_n_config_to_keep(self, n_suggestions, bracket_iteration):
"""Return the number of configs to keep and resume."""
n_configs = n_suggestions * (self.eta ** -bracket_iteration)
return int(n_configs / self.eta) | 0.008403 |
def _flatten_dicts(self, dicts):
"""Flatten a dict
:param dicts: Flatten a dict
:type dicts: list(dict)
"""
d = dict()
list_of_dicts = [d.get() for d in dicts or []]
return {k: v for d in list_of_dicts for k, v in d.items()} | 0.007117 |
def to_op(op, reversed=False):
'''
create a function that transforms a method to a binary op
often we need to convert a pseudo method
<receiver>.<message>(<z>) to a binary op
<receiver> <op> <message>
that's a decorator that helps for that
'''
def transformer(receiver, param, pseudo_typ... | 0.005348 |
def provideCustomerReferralCode(sender,**kwargs):
'''
If the vouchers app is installed and referrals are enabled, then the customer's profile page can show their voucher referral code.
'''
customer = kwargs.pop('customer')
if getConstant('vouchers__enableVouchers') and getConstant('referrals__e... | 0.008147 |
def interpolate_holes(self):
"""Linearly interpolate over holes in this collection to make it continuous.
Returns:
continuous_collection: A HourlyContinuousCollection with the same data
as this collection but with missing data filled by means of a
linear inte... | 0.003854 |
def update(self):
"""Fetch updated information about devices"""
if self.device_time_check():
if not self.in_process:
outlets, switches, fans = self.get_devices()
self.outlets = helpers.resolve_updates(self.outlets, outlets)
self.switches = h... | 0.003937 |
def sigmoidal(arr, contrast, bias):
r"""
Sigmoidal contrast is type of contrast control that
adjusts the contrast without saturating highlights or shadows.
It allows control over two factors:
the contrast range from light to dark, and where the middle value
of the mid-tones falls. The result is ... | 0.000359 |
def dispatch(self, command):
"""Pass a command along with its params to a suitable handler
If the command is blank, succeed silently
If the command has no handler, succeed silently
If the handler raises an exception, fail with the exception message
"""
log.info("... | 0.004657 |
def to_series(self, index=None, name=None):
"""
Create a Series with both index and values equal to the index keys
useful with map for returning an indexer based on an index.
Parameters
----------
index : Index, optional
index of resulting Series. If None, de... | 0.002472 |
def get_children(self, usage_id_filter=None):
"""
Return instantiated XBlocks for each of this blocks ``children``.
"""
if not self.has_children:
return []
return [
self.get_child(usage_id)
for usage_id in self.children
if usage_id... | 0.005348 |
def build_hgnc_gene(gene_info, build='37'):
"""Build a hgnc_gene object
Args:
gene_info(dict): Gene information
Returns:
gene_obj(dict)
{
'_id': ObjectId(),
# This is the hgnc id, required:
'hgnc_id': int,
... | 0.005984 |
def qualified_name(obj):
'''Returns the fully-qualified name of the given object'''
if not hasattr(obj, '__module__'):
obj = obj.__class__
module = obj.__module__
if module is None or module == str.__class__.__module__:
return obj.__qualname__
return '{}.{}'.format(module, obj.__qual... | 0.003058 |
def dist(ctx, devpi=False, egg=False, wheel=False, auto=True):
"""Distribute the project."""
config.load()
cmd = ["python", "setup.py", "sdist"]
# Automatically create wheels if possible
if auto:
egg = sys.version_info.major == 2
try:
import wheel as _
wheel ... | 0.001634 |
def _process_outgoing_msg(self, sink_iter):
"""For every message we construct a corresponding RPC message to be
sent over the given socket inside given RPC session.
This function should be launched in a new green thread as
it loops forever.
"""
LOG.debug('NetworkControll... | 0.001455 |
def parse_next(self, ptype, m):
"""
Parse the next packet.
:param ptype: The (string) type of the incoming packet
:param `.Message` m: The paket content
"""
if self.transport.server_mode and (ptype == MSG_KEXGSS_INIT):
return self._parse_kexgss_init(m)
... | 0.00224 |
def gen_gausprocess_se(ntrain, ntest, noise=1., lenscale=1., scale=1.,
xmin=-10, xmax=10):
"""
Generate a random (noisy) draw from a Gaussian Process with a RBF kernel.
"""
# Xtrain = np.linspace(xmin, xmax, ntrain)[:, np.newaxis]
Xtrain = np.random.rand(ntrain)[:, np.newaxis... | 0.001261 |
def send_request(self, worker_class_or_function, args, on_receive=None):
"""
Requests some work to be done by the backend. You can get notified of
the work results by passing a callback (on_receive).
:param worker_class_or_function: Worker class or function
:param args: worker a... | 0.001278 |
def _download_repodata(self, checked_repos):
"""Dowload repodata."""
self._files_downloaded = []
self._repodata_files = []
self.__counter = -1
if checked_repos:
for repo in checked_repos:
path = self._repo_url_to_path(repo)
self._files... | 0.00232 |
def cbpdn_relax(k):
"""Do relaxation for the cbpdn stage. The only parameter is the slice
index `k` and there are no return values; all inputs and outputs are
from and to global variables.
"""
mp_Z_X[k] = mp_xrlx * mp_Z_X[k] + (1 - mp_xrlx) * mp_Z_Y[k] | 0.003663 |
def batching(size):
"""Create a transducer which produces non-overlapping batches."""
if size < 1:
raise ValueError("batching() size must be at least 1")
def batching_transducer(reducer):
return Batching(reducer, size)
return batching_transducer | 0.003571 |
def get_hash(self, handle):
"""Return the hash."""
fpath = self._fpath_from_handle(handle)
return DiskStorageBroker.hasher(fpath) | 0.013072 |
def fill_predictive_missing_parameters(self):
"""define state with initial_state
:return: None
"""
if self.initial_state == 'w':
self.state = u'WARNING'
elif self.initial_state == 'u':
self.state = u'UNKNOWN'
elif self.initial_state == 'c':
... | 0.004651 |
def convolve2d_disk(fn, r, sig, nstep=200):
"""Evaluate the convolution f'(r) = f(r) * g(r) where f(r) is
azimuthally symmetric function in two dimensions and g is a
step function given by:
g(r) = H(1-r/s)
Parameters
----------
fn : function
Input function that takes a single radial... | 0.000786 |
def add_service(self, service):
"""Add a new service.
If the service already exists, it will be replaced.
"""
if service.protocol in self._services:
existing = self._services[service.protocol]
if not existing.superseeded_by(service):
return
... | 0.005479 |
def _drop(expr, data, axis=0, columns=None):
"""
Drop data from a DataFrame.
:param expr: collection to drop data from
:param data: data to be removed
:param axis: 0 for deleting rows, 1 for columns.
:param columns: columns of data to select, only useful when axis == 0
:return: collection
... | 0.002404 |
def get_related_ids(self):
"""
Get all of the IDs for the related models.
:rtype: list
"""
related = self.get_related()
full_key = related.get_qualified_key_name()
return self.get_query().select(full_key).lists(related.get_key_name()) | 0.006826 |
def do_execute(self):
"""
The actual execution of the actor.
:return: None if successful, otherwise error message
:rtype: str
"""
fname = str(self.input.payload)
spattern = str(self.resolve_option("regexp"))
pattern = None
if (spattern is not None... | 0.003752 |
def get_article(self, article_id):
"""
Get a single article represented by `article_id`.
:param article_id: ID of the article to retrieve.
"""
url = self._generate_url('articles/{0}'.format(article_id))
return self.get(url) | 0.007353 |
def merge(cls, first, second):
"""
Return an AttributeList that is the result of merging first with second.
"""
merged = AttributeList([], None)
assert (isinstance(first, AttributeList))
assert (isinstance(second, AttributeList))
merged._contents = first._content... | 0.007595 |
def prepare_threads(new_function):
"""Replaces threading._get_ident() function in order to notify
the waiting Condition."""
with _waitforthreads_lock:
if hasattr(threading, 'get_ident'):
old_function = threading.get_ident
threading.get_ident = new_function
else:
... | 0.002278 |
def value(self):
"""
Return the current value of a variable
"""
# Does the variable name have tags to parse?
if len(self._element):
var = ''.join(map(str, self.trigger.agentml.parse_tags(self._element, self.trigger)))
else:
var = self._element.text... | 0.005761 |
def get_percolation_threshold(self):
r"""
Find the invasion threshold at which a cluster spans from the inlet to
the outlet sites
"""
if np.sum(self['pore.inlets']) == 0:
raise Exception('Inlet pores must be specified first')
if np.sum(self['pore.outlets']) =... | 0.002522 |
def generate_supremacy_circuit_google_v2(qubits: Iterable[devices.GridQubit],
cz_depth: int,
seed: int) -> circuits.Circuit:
"""
Generates Google Random Circuits v2 as in github.com/sboixo/GRCS cz_v2.
See also https://arxiv.or... | 0.000402 |
def _variable_with_weight_decay(name, shape, stddev, wd):
"""Helper to create an initialized Variable with weight decay.
Note that the Variable is initialized with a truncated normal distribution.
A weight decay is added only if one is specified.
Args:
name: name of the variable
shape: list of ints
... | 0.006969 |
def lock(self, page):
"""Locks *page*."""
result = self._dokuwiki.send('dokuwiki.setLocks',
lock=[page], unlock=[])
if result['lockfail']:
raise DokuWikiError('unable to lock page') | 0.007874 |
def get_parent_directory(path):
"""Like os.path.dirname except it returns the absolute name of the parent
of the dirname directory. No symbolic link expansion (os.path.realpath)
or user expansion (os.path.expanduser) is done."""
if not os.path.isdir(path): path = os.path.dirname(path)
return os.pat... | 0.005479 |
def create(self, id, seq, resource): # pylint: disable=invalid-name,redefined-builtin
"""Create a highlight.
:param id: Result ID as an int.
:param seq: TestResult sequence ID as an int.
:param resource: :class:`highlights.Highlight <highlights.Highlight>` object
:return: :class... | 0.010504 |
def clean_link(self, url):
"""Makes sure a link is fully encoded. That is, if a ' ' shows up in
the link, it will be rewritten to %20 (while not over-quoting
% or other characters)."""
return self._clean_re.sub(lambda match: "%%%2x" % ord(match.group(0)), url) | 0.010239 |
def mfds2multimfd(mfds):
"""
Convert a list of MFD nodes into a single MultiMFD node
"""
_, kind = mfds[0].tag.split('}')
node = Node('multiMFD', dict(kind=kind, size=len(mfds)))
lengths = None
for field in mfd.multi_mfd.ASSOC[kind][1:]:
alias = mfd.multi_mfd.ALIAS.get(field, field)
... | 0.001008 |
def generate_event_set(ucerf, background_sids, src_filter, ses_idx, seed):
"""
Generates the event set corresponding to a particular branch
"""
serial = seed + ses_idx * TWO16
# get rates from file
with h5py.File(ucerf.source_file, 'r') as hdf5:
occurrences = ucerf.tom.sample_number_of_o... | 0.000661 |
def skip(self, content):
"""
Get whether to skip this I{content}.
Should be skipped when the content is optional and value is either None
or an empty list.
@param content: Content to skip.
@type content: L{Object}
@return: True if content is to be skipped.
... | 0.003503 |
def getItemByID(self, storeID, default=_noItem, autoUpgrade=True):
"""
Retrieve an item by its storeID, and return it.
Note: most of the failure modes of this method are catastrophic and
should not be handled by application code. The only one that
application programmers should... | 0.001031 |
def join_densities(*densities: Density) -> Density:
"""Join two mixed states into a larger qubit state"""
vectors = [rho.vec for rho in densities]
vec = reduce(outer_product, vectors)
memory = dict(ChainMap(*[rho.memory for rho in densities])) # TESTME
return Density(vec.tensor, vec.qubits, memory... | 0.003115 |
def load_parser_options_from_env(
parser_class: t.Type[BaseParser],
env: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, t.Any]:
"""
Extracts arguments from ``parser_class.__init__`` and populates them from environment variables.
Uses ``__init__`` argument type annot... | 0.004011 |
def compute_usage_requirements (self, subvariant):
""" Given the set of generated targets, and refined build
properties, determines and sets appripriate usage requirements
on those targets.
"""
assert isinstance(subvariant, virtual_target.Subvariant)
rproperties =... | 0.004943 |
def subsets(self):
"""Subsets that make up each split of the dataset for the language pair."""
source, target = self.builder_config.language_pair
filtered_subsets = {}
for split, ss_names in self._subsets.items():
filtered_subsets[split] = []
for ss_name in ss_names:
ds = DATASET_MAP... | 0.007496 |
def subdivide(length, parts=None, max_length=None):
"""Generates a list with start end stop indices of length parts, [(0, length/parts), ..., (.., length)]"""
if max_length:
i1 = 0
done = False
while not done:
i2 = min(length, i1 + max_length)
# print i1, i2
... | 0.004184 |
def get_containers_by_name(self, name):
"""
get all task which relative with task name
:param name: :class:`str`, task name
:return: :class:`list`, container list
"""
code, containers = self.get_containers()
if code != httplib.OK:
return []
... | 0.004425 |
def plot(self, plot_grouped=False):
"""
Plot the cumulative number of detections in time.
.. rubric:: Example
>>> family = Family(
... template=Template(name='a'), detections=[
... Detection(template_name='a', detect_time=UTCDateTime(0) + 200,
... ... | 0.000878 |
def get_account_info(self):
''' Get current account information
The information then will be saved in `self.account` so that you can
access the information like this:
>>> hsclient = HSClient()
>>> acct = hsclient.get_account_info()
>>> print acct.email_address
... | 0.003676 |
def _build_mask(self):
"""Build mask applied to O^{-1}, O for the matrix approx constraint"""
self.mask = torch.ones(self.d, self.d).byte()
for ci in self.c_data.values():
si, ei = ci["start_index"], ci["end_index"]
for cj in self.c_data.values():
sj, ej =... | 0.002963 |
def filter_osm_file():
""" Downloads (and compiles) osmfilter tool from web and
calls that osmfilter to only filter out only the road elements.
"""
print_info('Filtering OSM file...')
start_time = time.time()
if check_osmfilter():
# params = '--keep="highway=motorway =motorway... | 0.00627 |
def load(self, service_name, api_version=None, cached=True):
"""
Loads the desired JSON for a service. (uncached)
This will fall back through all the ``data_dirs`` provided to the
constructor, returning the **first** one it finds.
:param service_name: The name of the desired se... | 0.001276 |
def convert_bboxes_to_albumentations(bboxes, source_format, rows, cols, check_validity=False):
"""Convert a list bounding boxes from a format specified in `source_format` to the format used by albumentations
"""
return [convert_bbox_to_albumentations(bbox, source_format, rows, cols, check_validity) for bbox... | 0.012085 |
def collection(self, collection_id):
"""Create a sub-collection underneath the current document.
Args:
collection_id (str): The sub-collection identifier (sometimes
referred to as the "kind").
Returns:
~.firestore_v1beta1.collection.CollectionReference: ... | 0.004274 |
def datetime_value_renderer(value, **options):
"""Render datetime value with django formats, default is SHORT_DATETIME_FORMAT"""
datetime_format = options.get('datetime_format', 'SHORT_DATETIME_FORMAT')
return formats.date_format(timezone.localtime(value), datetime_format) | 0.007018 |
def _GetStatus(self):
"""Retrieves status information.
Returns:
dict[str, object]: status attributes, indexed by name.
"""
if self._analysis_mediator:
number_of_produced_event_tags = (
self._analysis_mediator.number_of_produced_event_tags)
number_of_produced_reports = (
... | 0.006274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.