text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def rectify_acquaintance_strategy(
circuit: circuits.Circuit,
acquaint_first: bool=True
) -> None:
"""Splits moments so that they contain either only acquaintance gates
or only permutation gates. Orders resulting moments so that the first one
is of the same type as the previous one.
... | 0.004559 |
def separate_into_sections(self, data_frame, labels_col='anno', labels_to_keep=[1,2], min_labels_in_sequence=100):
""" Helper function to separate a time series into multiple sections based on a labeled column.
:param data_frame: The data frame. It should have x, y, and z columns.
... | 0.011549 |
def view_page(name=None):
"""Serve a page name.
.. note:: this is a bottle view
* if the view is called with the POST method, write the new page
content to the file, commit the modification and then display the
html rendering of the restructured text file
* if the view is called with the ... | 0.000422 |
def coredump_configured(name, enabled, dump_ip, host_vnic='vmk0', dump_port=6500):
'''
Ensures a host's core dump configuration.
name
Name of the state.
enabled
Sets whether or not ESXi core dump collection should be enabled.
This is a boolean value set to ``True`` or ``False``... | 0.001179 |
def _random_weights(n_features, lam, lam_perturb, prng):
"""Generate a symmetric random matrix with zeros along the diagnoal and
non-zero elements take the value {lam * lam_perturb, lam / lam_perturb}
with probability 1/2.
"""
weights = np.zeros((n_features, n_features))
n_off_diag = int((n_feat... | 0.001517 |
def lines_iter(self):
'''
Returns contents of the Dockerfile as an array, where each line in the file is an element in the array.
:return: list
'''
# Convert unicode chars to string
byte_to_string = lambda x: x.strip().decode(u'utf-8') if isinstance(x, bytes) else x.strip... | 0.01083 |
def model_counts_map(self, name=None, exclude=None, use_mask=False):
"""Return the model expectation map for a single source, a set
of sources, or all sources in the ROI. The map will be
computed using the current model parameters.
Parameters
----------
name : str
... | 0.000915 |
def insert_point(self, x, y):
""" Inserts a point on the path at the mouse location.
We first need to check if the mouse location is on the path.
Inserting point is time intensive and experimental.
"""
try:
bezier = _ctx.ximport("b... | 0.006826 |
def send(self, tid, session, feature=None):
'''taobao.logistics.dummy.send 无需物流(虚拟)发货处理
用户调用该接口可实现无需物流(虚拟)发货,使用该接口发货,交易订单状态会直接变成卖家已发货'''
request = TOPRequest('taobao.logistics.dummy.send')
request['tid'] = tid
if feature!=None: request['feature'] = feature
self.c... | 0.015544 |
def generate_module_table_header(modules):
""" Generate header with module table entries for builtin modules.
:param List[(module_name, obj_module, enabled_define)] modules: module defs
:return: None
"""
# Print header file for all external modules.
mod_defs = []
print("// Automatically ge... | 0.001739 |
def popular(self, period=DAILY):
'''
Get popular songs.
:param period: time period
:rtype: a generator generates :class:`Song` objects
Time periods:
+---------------------------------+-----------------------------------+
| Constant | Mean... | 0.001982 |
def calloc(self, sim_nmemb, sim_size):
"""
A somewhat faithful implementation of libc `calloc`.
:param sim_nmemb: the number of elements to allocated
:param sim_size: the size of each element (in bytes)
:returns: the address of the allocation, or a NULL pointer if the a... | 0.009346 |
def largest_graph(mol):
"""Return a molecule which has largest graph in the compound
Passing single molecule object will results as same as molutil.clone
"""
mol.require("Valence")
mol.require("Topology")
m = clone(mol) # Avoid modification of original object
if m.isolated:
for k in... | 0.002469 |
def format_exc(*exc_info):
"""Show exception with traceback."""
typ, exc, tb = exc_info or sys.exc_info()
error = traceback.format_exception(typ, exc, tb)
return "".join(error) | 0.005208 |
def _set_tacacs_server(self, v, load=False):
"""
Setter method for tacacs_server, mapped from YANG variable /tacacs_server (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_tacacs_server is considered as a private
method. Backends looking to populate this v... | 0.005714 |
def organizations(self):
"""
| Comment: The ids of the organizations that have access
"""
if self.api and self.organization_ids:
return self.api._get_organizations(self.organization_ids) | 0.008658 |
def get_project(self) -> str:
""" Get the ihc project and make sure controller is ready before"""
with IHCController._mutex:
if self._project is None:
if self.client.get_state() != IHCSTATE_READY:
ready = self.client.wait_for_state_change(IHCSTATE_READY,
... | 0.003604 |
def combine_psf(kernel_list_new, kernel_old, sigma_bkg, factor=1, stacking_option='median', symmetry=1):
"""
updates psf estimate based on old kernel and several new estimates
:param kernel_list_new: list of new PSF kernels estimated from the point sources in the image
:param kernel_old:... | 0.003179 |
def colorize(text, ansi=True):
"""
If the client wants ansi, replace the tokens with ansi sequences --
otherwise, simply strip them out.
"""
if ansi:
text = text.replace('^^', '\x00')
for token, code in _ANSI_CODES:
text = text.replace(token, code)
text = text.rep... | 0.002488 |
def rich_item(self, method_name, value):
"""
Convert this value into the rich txkoji objects (if applicable)
"""
if value is None:
return None
if method_name == 'getAverageBuildDuration':
return timedelta(seconds=value)
types = (Build, Channel, Pac... | 0.002457 |
def get(self):
"""Get any clients ready to be used.
:returns: Iterable of redis clients
"""
now = time.time()
while self._clients and self._clients[0][0] < now:
_, (client, last_wait) = heapq.heappop(self._clients)
connect_start = time.time()
... | 0.004149 |
def GetSecurityToken(self, username, password):
"""
Grabs a security Token to authenticate to Office 365 services
"""
url = 'https://login.microsoftonline.com/extSTS.srf'
body = """
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
xm... | 0.00278 |
def validate_context(context):
"""
Set the key for the current context.
Args:
context: a populated EFVersionContext object
"""
# Service must exist in service registry
if not context.service_registry.service_record(context.service_name):
fail("service: {} not found in service registry: {}".for... | 0.014437 |
def pack_sidechains(pdb, sequence, path=False):
"""Packs sidechains onto a given PDB file or string.
Parameters
----------
pdb : str
PDB string or a path to a PDB file.
sequence : str
Amino acid sequence for SCWRL to pack in single-letter code.
path : bool, optional
True... | 0.001667 |
def post_data(api_key=None, name='OpsGenie Execution Module', reason=None,
action_type=None):
'''
Post data to OpsGenie. It's designed for Salt's Event Reactor.
After configuring the sls reaction file as shown above, you can trigger the
module with your designated tag (og-tag in this case... | 0.000771 |
def checksec_app(_parser, _, args): # pragma: no cover
"""
Check security features of an ELF file.
"""
import sys
import argparse
import csv
import os.path
def checksec(elf, path, fortifiable_funcs):
relro = 0
nx = False
pie = 0
rpath = False
ru... | 0.003429 |
def _parse_attr(cls, value, package_dir=None):
"""Represents value as a module attribute.
Examples:
attr: package.attr
attr: package.module.attr
:param str value:
:rtype: str
"""
attr_directive = 'attr:'
if not value.startswith(attr_direc... | 0.001357 |
def adjust_boxes(line_wave, box_widths, left_edge, right_edge,
max_iter=1000, adjust_factor=0.35,
factor_decrement=3.0, fd_p=0.75):
"""Ajdust given boxes so that they don't overlap.
Parameters
----------
line_wave: list or array of floats
Line wave lengths. The... | 0.000285 |
def onset_strength(y=None, sr=22050, S=None, lag=1, max_size=1,
ref=None,
detrend=False, center=True,
feature=None, aggregate=None,
centering=None,
**kwargs):
"""Compute a spectral flux onset strength envelope.
Onset... | 0.000619 |
def post_upgrade_checks(self, upgrades):
"""Run post-upgrade checks after applying all pending upgrades.
Post checks may be used to emit warnings encountered when applying an
upgrade, but post-checks can also be used to advice the user to run
re-indexing or similar long running processe... | 0.001617 |
def mint_token_if_balance_low(
token_contract: ContractProxy,
target_address: str,
min_balance: int,
fund_amount: int,
gas_limit: int,
mint_msg: str,
no_action_msg: str = None,
) -> Optional[TransactionHash]:
""" Check token balance and mint if below minimum "... | 0.004021 |
def remove_xml_element(name, tree):
""" Removes XML elements from an ElementTree content tree """
# root = tree.getroot()
remove = tree.findall(
".//{{http://soap.sforce.com/2006/04/metadata}}{}".format(name)
)
if not remove:
return tree
parent_map = {c: p for p in tree.iter() f... | 0.002304 |
def where_unique(cls, ip, object_id, location):
""" Get db model by username """
return cls.query.filter_by(
ip=ip,
object_id=object_id,
location=location).first() | 0.009091 |
def data_log_likelihood(self, successes, trials, beta):
'''Calculates the log-likelihood of a Polya tree bin given the beta values.'''
return binom.logpmf(successes, trials, 1.0 / (1 + np.exp(-beta))).sum() | 0.013514 |
def get_currentDim(self):
'''
returns the current dimensions of the object
'''
selfDim = self._dimensions.copy()
if not isinstance(selfDim,dimStr):
if selfDim.has_key('_ndims') : nself = selfDim.pop('_ndims')
else :
self.warning(1,... | 0.022727 |
def load_params(fname: str) -> Tuple[Dict[str, mx.nd.NDArray], Dict[str, mx.nd.NDArray]]:
"""
Loads parameters from a file.
:param fname: The file containing the parameters.
:return: Mapping from parameter names to the actual parameters for both the arg parameters and the aux parameters.
"""
sa... | 0.005004 |
def pubrec(self, mid):
"""Send PUBREC response to server."""
if self.sock == NC.INVALID_SOCKET:
return NC.ERR_NO_CONN
self.logger.info("Send PUBREC (msgid=%s)", mid)
pkt = MqttPkt()
pkt.command = NC.CMD_PUBREC
pkt.remaining_length = 2
ret = pkt.allo... | 0.006 |
def row(self, data):
"""Return a formatted row for the given data."""
for column in self.column_funcs:
if callable(column):
yield column(data)
else:
yield utils.lookup(data, *column) | 0.007874 |
def all(guideids=None, filter=None, order=None):
'''
Fetch all guides.
:param iterable guideids: Only return Guides corresponding to these ids.
:param string filter: Only return guides of this type. Choices:
installation, repair, disassembly, teardown,
... | 0.015793 |
def iflat_tasks_wti(self, status=None, op="==", nids=None):
"""
Generator to iterate over all the tasks of the `Flow`.
Yields:
(task, work_index, task_index)
If status is not None, only the tasks whose status satisfies
the condition (task.status op status) are selec... | 0.00638 |
def build_model_classes(metadata):
"""Generate a model class for any models contained in the specified spec file."""
i = importlib.import_module(metadata)
env = get_jinja_env()
model_template = env.get_template('model.py.jinja2')
for model in i.models:
with open(model_path(model.name.l... | 0.005013 |
def _cdf(self, xloc, left, right, cache):
"""
Cumulative distribution function.
Example:
>>> print(chaospy.Uniform().fwd([-0.5, 0.5, 1.5, 2.5]))
[0. 0.5 1. 1. ]
>>> print(chaospy.Pow(chaospy.Uniform(), 2).fwd([-0.5, 0.5, 1.5, 2.5]))
[0. ... | 0.003088 |
def _get_goslimids_norel(self, dagslim):
"""Get all GO slim GO IDs that do not have a relationship."""
go_slims = set()
go2obj = self.gosubdag.go2obj
for goid in dagslim:
goobj = go2obj[goid]
if not goobj.relationship:
go_slims.add(goobj.id)
... | 0.005935 |
def split_len(s, length):
"""split string *s* into list of strings no longer than *length*"""
return [s[i:i+length] for i in range(0, len(s), length)] | 0.006329 |
def qtePrepareToRun(self):
"""
This method is called by Qtmacs to prepare the macro for
execution.
It is probably a bad idea to overload this method as it only
administrates the macro execution and calls the ``qteRun``
method (which *should* be overloaded by the macro pr... | 0.00111 |
def has_a_matching_perm(self, perm_list, obj=None):
"""Returns True if the user has one of the specified permissions.
If object is passed, it checks if the user has any of the required
perms for this object.
"""
# If there are no permissions to check, just return true
if... | 0.003623 |
def login_service_description(self):
"""Login service description.
The login service description _MUST_ include the token service
description. The authentication pattern is indicated via the
profile URI which is built using self.auth_pattern.
"""
label = 'Login to ' + se... | 0.002786 |
def slice_hidden(self, x):
"""Slice encoder hidden state into block_dim.
Args:
x: Encoder hidden state of shape [-1, hidden_size].
Returns:
Sliced states of shape [-1, num_blocks, block_dim].
"""
x_sliced = tf.reshape(
x, shape=[-1, self.hparams.num_blocks, self.hparams.blo... | 0.002874 |
def deactivate_mfa_device(self, user_name, serial_number):
"""
Deactivates the specified MFA device and removes it from
association with the user.
:type user_name: string
:param user_name: The username of the user
:type serial_number: string
:param seria... | 0.008475 |
def _create_cifti_image(bold_file, label_file, annotation_files, gii_files,
volume_target, surface_target, tr):
"""
Generate CIFTI image in target space
Parameters
bold_file : 4D BOLD timeseries
label_file : label atlas
annotation_... | 0.001589 |
def _sort_by_indep(self, func='get_value', i=None, iunit=None, unit=None,
uncover=None, trail=None, linebreak=None,
sort_by_indep=None):
"""
must be called before (or within) _do_linebreak
"""
if sort_by_indep is None:
# TODO: a... | 0.004654 |
def ranking_metric(df, method, pos, neg, classes, ascending):
"""The main function to rank an expression table.
:param df: gene_expression DataFrame.
:param method: The method used to calculate a correlation or ranking. Default: 'log2_ratio_of_classes'.
Others methods are... | 0.007526 |
def required_types(self):
"""Set of names of types which the Command depends on.
"""
required_types = set(x.type for x in self.params)
required_types.add(self.type)
required_types.discard(None)
return required_types | 0.007605 |
def real(self):
"""Real part of the element.
The real part can also be set using ``x.real = other``, where ``other``
is array-like or scalar.
Examples
--------
>>> space = odl.ProductSpace(odl.cn(3), odl.cn(2))
>>> x = space.element([[1 + 1j, 2, 3 - 3j],
... | 0.00163 |
def _has_flaky_attributes(cls, test):
"""
Returns True if the test callable in question is marked as flaky.
:param test:
The test that is being prepared to run
:type test:
:class:`nose.case.Test` or :class:`Function`
:return:
:rtype:
`... | 0.004386 |
def _get_header(self):
"""Parse the SWF header."""
fh = self._src
obj = _make_object("Header")
# first part of the header
obj.Signature = sign = "".join(chr(unpack_ui8(fh)) for _ in range(3))
obj.Version = self._version = unpack_ui8(fh)
obj.FileLength = file_leng... | 0.00241 |
def change_password(self, user, password, send_email=None):
"""
Service method to change a user's password.
Sends signal `password_changed`.
:param user: The :class:`User`'s password to change.
:param password: The new password.
:param send_email: Whether or not to over... | 0.002962 |
def remove_file(filename, path=None):
"""
Remove file filename from path.
:param filename: Name of file to remove
:param path: Path where file is located
:return: True if successfull
:raises OSError if chdir or remove fails.
"""
cwd = os.getcwd()
try:
if path:
os... | 0.001996 |
def allocate(self):
"""
Arrange for a unique context ID to be allocated and associated with a
route leading to the active context. In masters, the ID is generated
directly, in children it is forwarded to the master via a
:data:`mitogen.core.ALLOCATE_ID` message.
"""
... | 0.004098 |
def show(self, display=None):
"""Removes the display style attribute.
If a display type is provided """
self._stable = False
if not display:
self.attrs["style"].pop("display")
else:
self.attrs["style"]["display"] = display
return self | 0.006536 |
def delete(self, client=None):
"""Deletes a blob from Cloud Storage.
If :attr:`user_project` is set on the bucket, bills the API request
to that project.
:type client: :class:`~google.cloud.storage.client.Client` or
``NoneType``
:param client: Optional. Th... | 0.002475 |
def create_function_f_i(self):
"""state reinitialization (reset) function"""
return ca.Function(
'f_i',
[self.t, self.x, self.y, self.m, self.p, self.c, self.pre_c, self.ng, self.nu],
[self.f_i],
['t', 'x', 'y', 'm', 'p', 'c', 'pre_c', 'ng', 'nu'], ['x_n']... | 0.011905 |
def optics(cls, data, eps, minpts, ccore=False):
"""
Constructor of OPTICS clustering.rst algorithm
:param data: Input data that is presented as a list of points (objects), where each point is represented by list or tuple
:param eps: Connectivity radius between points, points may be con... | 0.007505 |
def parse(cls, version_string, partial=False, coerce=False):
"""Parse a version string into a Version() object.
Args:
version_string (str), the version string to parse
partial (bool), whether to accept incomplete input
coerce (bool), whether to try to map the passed ... | 0.00286 |
def run_rollouts(
env, agent, initial_observations, step_limit=None, discount_factor=1.0,
log_every_steps=None, video_writers=(), color_bar=False,
many_rollouts_from_each_env=False
):
"""Runs a batch of rollouts from given initial observations."""
assert step_limit is not None or not many_rollouts_from_... | 0.010772 |
def _get_candidate_swap(resources, location,
l2v, vertices_resources, fixed_vertices, machine):
"""Given a chip location, select a set of vertices which would have to be
moved elsewhere to accommodate the arrival of the specified set of
resources.
Parameters
----------
r... | 0.000482 |
def plotfft(s, fmax, doplot=False):
""" This functions computes the fft of a signal, returning the frequency
and their magnitude values.
Parameters
----------
s: array-like
the input signal.
fmax: int
the sampling frequency.
doplot: boolean
a variable to indicate whether t... | 0.002717 |
def fftconv(a, b, axes=(0, 1)):
"""
Compute a multi-dimensional convolution via the Discrete Fourier
Transform. Note that the output has a phase shift relative to the
output of :func:`scipy.ndimage.convolve` with the default ``origin``
parameter.
Parameters
----------
a : array_like
... | 0.001121 |
def compile_template(instance, template, additionnal_context=None):
"""
Fill the given template with the instance's datas and return the odt file
For every instance class, common values are also inserted in the context
dict (and so can be used) :
* config values
:param obj instance: the i... | 0.00224 |
def execute_command(self, command):
"""
This method will execute the commands on the device without as if you were just connected to it (it will not
enter into any vdom). This method is not recommended unless you are 100% sure of what you are doing.
Args:
* **command** (str... | 0.003586 |
def createdb():
"""Create database tables from sqlalchemy models"""
manager.db.engine.echo = True
manager.db.create_all()
set_alembic_revision() | 0.00625 |
def is_marginable(self):
"""True if adding counts across this dimension axis is meaningful."""
return self.dimension_type not in {DT.CA, DT.MR, DT.MR_CAT, DT.LOGICAL} | 0.010989 |
def _read_para_unassigned(self, code, cbit, clen, *, desc, length, version):
"""Read HIP unassigned parameters.
Structure of HIP unassigned parameters [RFC 5201][RFC 7401]:
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 ... | 0.001203 |
def encode_request(username, password, uuid, owner_uuid, is_owner_connection, client_type, serialization_version, client_hazelcast_version):
""" Encode request into client_message"""
client_message = ClientMessage(payload_size=calculate_size(username, password, uuid, owner_uuid, is_owner_connection, client_type... | 0.002844 |
def find_version(*file_paths):
"""
read __init__.py
"""
file_path = os.path.join(*file_paths)
with open(file_path, 'r') as version_file:
line = version_file.readline()
while line:
if line.startswith('__version__'):
version_match = re.search(
... | 0.001621 |
def get_custom_level(regexp=None,description=None,skip_files=None,include_files=None):
'''get_custom_level will generate a custom level for the user,
based on a regular expression. If used outside the context of tarsum, the user
can generate their own named and described filters.
:param regexp: must be... | 0.01256 |
def refresh_tree(self, tree, items):
"""
refresh trees with current settings
Args:
tree: a QtWidgets.QTreeWidget object or a QtWidgets.QTreeView object
items: dictionary or Parameter items with which to populate the tree
show_all: boolean if true show all para... | 0.007267 |
def get_cluster_assignment(self):
"""Fetch the cluster layout in form of assignment from zookeeper"""
plan = self.get_cluster_plan()
assignment = {}
for elem in plan['partitions']:
assignment[
(elem['topic'], elem['partition'])
] = elem['replicas']... | 0.005764 |
def RfiltersBM(dataset,database,host=rbiomart_host):
"""
Lists BioMart filters through a RPY2 connection.
:param dataset: a dataset listed in RdatasetsBM()
:param database: a database listed in RdatabasesBM()
:param host: address of the host server, default='www.ensembl.org'
:returns: nothing
... | 0.009766 |
def pending():
"""Show the number of pending signals by signal type."""
signalbus = current_app.extensions['signalbus']
pending = []
total_pending = 0
for signal_model in signalbus.get_signal_models():
count = signal_model.query.count()
if count > 0:
pending.append((coun... | 0.002981 |
def get_request(self, request):
"""Sets token-based auth headers."""
request.headers['authenticate'] = {
'complexType': 'PortalLoginToken',
'userId': self.user_id,
'authToken': self.auth_token,
}
return request | 0.007194 |
def sanitize_tex(original_text):
"""Sanitize TeX text.
:param original_text: the text to sanitize for LaTeX.
:type original_text: str
:returns: the sanitize text.
Text is sanitized by following these steps:
1. Replaces ``\\` by ``\\textbackslash``
2. Escapes certain characters (such as ... | 0.001068 |
def get_daemon_stats(self, details=False):
"""Increase the stats provided by the Daemon base class
:return: stats dictionary
:rtype: dict
"""
# Call the base Daemon one
res = super(Broker, self).get_daemon_stats(details=details)
res.update({'name': self.name, 't... | 0.002604 |
def submit_row(context):
"""
Overrides 'django.contrib.admin.templatetags.admin_modify.submit_row'.
Manipulates the context going into that function by hiding all of the buttons
in the submit row if the key `readonly` is set in the context.
"""
ctx = original_submit_row(context)
if context... | 0.003289 |
def get_enrollments(self, course_id=None, usernames=None):
"""
List all course enrollments.
Args:
course_id (str, optional): If used enrollments will be filtered to the specified
course id.
usernames (list, optional): List of usernames to filter enrollmen... | 0.004271 |
def add(entry_point, all_entry_points, auto_write, scripts_path):
'''Add Scrim scripts for a python project'''
click.echo()
if not entry_point and not all_entry_points:
raise click.UsageError(
'Missing required option: --entry_point or --all_entry_points'
)
if not os.path.ex... | 0.000418 |
def check_satpy(readers=None, writers=None, extras=None):
"""Check the satpy readers and writers for correct installation.
Args:
readers (list or None): Limit readers checked to those specified
writers (list or None): Limit writers checked to those specified
extras (list or None): Limit... | 0.002553 |
def check_schema(self):
"""Check the schema exists and matches configuration"""
if self.valid_schema:
return
config = self.config
metadata = self.metadata()
if 'current_version' not in metadata:
raise GaugedSchemaError('Gauged schema not found, '
... | 0.001878 |
def links_to_dynamic(self, ext):
"""Return true if 'ext' links to a dynamic lib in the same package"""
# XXX this should check to ensure the lib is actually being built
# XXX as dynamic, and not just using a locally-found version or a
# XXX static-compiled version
libnames = dict... | 0.005545 |
def gene_variants(institute_id):
"""Display a list of SNV variants."""
page = int(request.form.get('page', 1))
institute_obj = institute_and_case(store, institute_id)
# populate form, conditional on request method
if(request.method == "POST"):
form = GeneVariantFiltersForm(request.form... | 0.003125 |
def make_refresh_on_demand_service(injector_component):
"""
create a refresh on demand service listening to refresh order on the component admin queue
:param injector_component: the injector_component to bind with the new refresh on demande service
:return: the created service
""... | 0.008547 |
def _gather_image_parts(self):
"""Load the image part collection with all the image parts in package."""
for rel in self.iter_rels():
if rel.is_external:
continue
if rel.reltype != RT.IMAGE:
continue
if rel.target_part in self.image_par... | 0.007481 |
def validate(self, tracking_number):
"Return True if this is a valid USPS tracking number."
tracking_num = tracking_number[:-1].replace(' ', '')
odd_total = 0
even_total = 0
for ii, digit in enumerate(tracking_num):
if ii % 2:
odd_total += int(digit)
... | 0.003766 |
def _get_space_character_free_column_resolvers(self):
"""Return the space character free column resolvers of a dataframe.
Column names with spaces are 'cleaned up' so that they can be referred
to by backtick quoting.
Used in :meth:`DataFrame.eval`.
"""
from pandas.core.c... | 0.004283 |
def get_selections(fetchempty=True):
'''
Answers to debconf questions for all packages in the following format::
{'package': [['question', 'type', 'value'], ...]}
CLI Example:
.. code-block:: bash
salt '*' debconf.get_selections
'''
selections = {}
cmd = 'debconf-get-sele... | 0.001553 |
def get_identities(self, item):
""" Return the identities from an item """
field = self.get_field_author()
yield self.get_sh_identity(item, field) | 0.011696 |
def add_ap(self, id_, label=None, addPrefix=True):
""" Add id_ as an owl:AnnotationProperty"""
self.add_trip(id_, rdf.type, owl.AnnotationProperty)
if label:
self.add_trip(id_, rdfs.label, label)
if addPrefix:
prefix = ''.join([s.capitalize() for s in labe... | 0.004651 |
def get_namespace_from_name(name):
"""
can be either
<namespace>/projects/<project_name>
or
<namespace>/<project_name>
"""
if not re.match(NAMESPACE_PATTERN, name):
sys.exit(("Argument '%s' doesn't match any recognized pattern:\n"
"\tfloyd [data] init <project_or_da... | 0.003623 |
def getTopologyInfo(self, topologyName, cluster, role, environ):
"""
Returns the JSON representation of a topology
by its name, cluster, environ, and an optional role parameter.
Raises exception if no such topology is found.
"""
# Iterate over the values to filter the desired topology.
for (... | 0.008258 |
def _get_global_include_abs_path(self, path):
"""
Get a value after converting to absolute path.
Becoming different from other parameter,
validation of `include` parameter is complex.
Before other validation(at first) this method is called to merge to
one configuration.
... | 0.003044 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.