text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_grid_qubits(arc: SquareGrid, nodes: Iterator[int]) -> List[cirq.GridQubit]:
"""Gets a list of :py:class:GridQubit` s corresponding to the qubit nodes provided on the given Architecture.
:param arc: The grid Architecture
:param nodes: An iterator of node index values
:return: The list ... | 0.007407 |
def expr(self):
"""
expr: term (('+' | '-') term)*
"""
node = self.term()
while self.token.nature in (Nature.PLUS, Nature.MINUS):
token = self.token
if token.nature == Nature.PLUS:
self._process(Nature.PLUS)
elif token.nature =... | 0.003817 |
def wrap_exception(exception, cause):
"""
Wraps another exception into specified application exception object.
If original exception is of ApplicationException type it is returned without changes.
Otherwise the original error is set as a cause to specified ApplicationException object.
... | 0.007474 |
def is_grammar_generating(grammar, remove=False):
# type: (Grammar, bool) -> bool
"""
Check if is grammar is generating.
Generating grammar generates at least one sentence.
:param grammar: Grammar to check.
:param remove: True to remove nongenerating symbols from the gram... | 0.005871 |
def get_keys(self):
"""
Return the keys of the instruction
:rtype: a list of long
"""
return [(self.first_key + i) for i in range(0, len(self.targets))] | 0.010363 |
def state_to_xarray(state):
'''Convert a dictionary of climlab.Field objects to xarray.Dataset
Input: dictionary of climlab.Field objects
(e.g. process.state or process.diagnostics dictionary)
Output: xarray.Dataset object with all spatial axes,
including 'bounds' axes indicating cell boundaries i... | 0.006019 |
def relogin(self):
"""Perform a re-login"""
try:
self.__auth = None # reset auth before relogin
self.login()
except ZabbixAPIException as e:
self.log(ERROR, 'Zabbix API relogin error (%s)', e)
self.__auth = None # logged_in() will always return F... | 0.005848 |
def download(name, course, github='SheffieldML/notebook/master/lab_classes/'):
"""Download a lab class from the relevant course
:param course: the course short name to download the class from.
:type course: string
:param reference: reference to the course for downloading the class.
:type reference: ... | 0.002882 |
def rake(strike, dip, rake_angle):
"""
Calculates the longitude and latitude of the linear feature(s) specified by
`strike`, `dip`, and `rake_angle`.
Parameters
----------
strike : number or sequence of numbers
The strike of the plane(s) in degrees, with dip direction indicated by
... | 0.000812 |
def inFileHierarchy(self):
'''
Whether or not this node should be included in the file view hierarchy. Helper
method for :func:`~exhale.graph.ExhaleNode.toHierarchy`. Sets the member
variable ``self.in_file_hierarchy`` to True if appropriate.
:Return (bool):
True i... | 0.006417 |
def _prepare_batch_request(self):
"""Prepares headers and body for a batch request.
:rtype: tuple (dict, str)
:returns: The pair of headers and body of the batch request to be sent.
:raises: :class:`ValueError` if no requests have been deferred.
"""
if len(self._requests... | 0.001969 |
def design(self):
"""Returns the designed values.
:returns: list of designed values (G, t, channel_W, obstacle_n)
:rtype: int
"""
floc_dict = {'channel_n': self.channel_n,
'channel_L': self.channel_L,
'channel_W': self.channel_W,
... | 0.003135 |
def uid(i):
"""
Input: {}
Output: {
Output from 'gen_uid' function
}
"""
o=i.get('out','')
r=gen_uid({})
if r['return']>0: return r
if o=='con':
out(r['data_uid'])
return r | 0.032258 |
def bounds(self, axis, view=None):
"""Get the bounds of the Visual
Parameters
----------
axis : int
The axis.
view : instance of VisualView
The view to use.
"""
if view is None:
view = self
if axis not in self._vshare.b... | 0.004545 |
def MakeOdds(self):
"""Transforms from probabilities to odds.
Values with prob=0 are removed.
"""
for hypo, prob in self.Items():
if prob:
self.Set(hypo, Odds(prob))
else:
self.Remove(hypo) | 0.007194 |
def vn_release(call=None, kwargs=None):
'''
Releases a virtual network lease that was previously on hold.
.. versionadded:: 2016.3.0
vn_id
The ID of the virtual network from which to release the lease. Can be
used instead of ``vn_name``.
vn_name
The name of the virtual net... | 0.001574 |
def notebook_for_kernel(self, kernel_id):
"""Return the notebook_id for a kernel_id or None."""
notebook_ids = [k for k, v in self._notebook_mapping.iteritems() if v == kernel_id]
if len(notebook_ids) == 1:
return notebook_ids[0]
else:
return None | 0.009901 |
def get_irradiance(self, surface_tilt, surface_azimuth,
solar_zenith, solar_azimuth, dni, ghi, dhi,
dni_extra=None, airmass=None, model='haydavies',
**kwargs):
"""
Uses the :func:`irradiance.get_total_irradiance` function to
ca... | 0.002006 |
def set_disk1(self, disk1):
"""
Sets the size (MB) for PCMCIA disk1.
:param disk1: disk1 size (integer)
"""
yield from self._hypervisor.send('vm set_disk1 "{name}" {disk1}'.format(name=self._name, disk1=disk1))
log.info('Router "{name}" [{id}]: disk1 updated from {old_... | 0.009309 |
def parse_s2bins(s2bins):
"""
parse ggKbase scaffold-to-bin mapping
- scaffolds-to-bins and bins-to-scaffolds
"""
s2b = {}
b2s = {}
for line in s2bins:
line = line.strip().split()
s, b = line[0], line[1]
if 'UNK' in b:
continue
if len(line) > 2... | 0.005607 |
def show_lbaas_l7policy(self, l7policy, **_params):
"""Fetches information of a certain listener's L7 policy."""
return self.get(self.lbaas_l7policy_path % l7policy,
params=_params) | 0.00905 |
def _read24(self, register):
"""Read an unsigned 24-bit value as a floating point and return it."""
ret = 0.0
for b in self._read_register(register, 3):
ret *= 256.0
ret += float(b & 0xFF)
return ret | 0.007843 |
def matrix_index(user):
"""
Returns the keys associated with each axis of the matrices.
The first key is always the name of the current user, followed by the
sorted names of all the correspondants.
"""
other_keys = sorted([k for k in user.network.keys() if k != user.name])
return [user.nam... | 0.002985 |
def find_ei(data, nb=1000, save=False, save_folder='.', fmt='svg',
site_correction=False, return_new_dirs=False):
"""
Applies series of assumed flattening factor and "unsquishes" inclinations assuming tangent function.
Finds flattening factor that gives elongation/inclination pair consistent wit... | 0.002559 |
def _compute_vectors(self):
"""Compute the star's position as an ICRF position and velocity."""
# Use 1 gigaparsec for stars whose parallax is zero.
parallax = self.parallax_mas
if parallax <= 0.0:
parallax = 1.0e-6
# Convert right ascension, declination, and paral... | 0.002729 |
def clearScreen(cls):
"""Clear the screen"""
if "win32" in sys.platform:
os.system('cls')
elif "linux" in sys.platform:
os.system('clear')
elif 'darwin' in sys.platform:
os.system('clear')
else:
cit.err("No clearScreen for " + sys.p... | 0.006098 |
def __create_checksum(self, p):
"""
Calculates the checksum of the packet to be sent to the time clock
Copied from zkemsdk.c
"""
l = len(p)
checksum = 0
while l > 1:
checksum += unpack('H', pack('BB', p[0], p[1]))[0]
p = p[2:]
i... | 0.005848 |
def find_atoms_within_distance(atoms, cutoff_distance, point):
"""Returns atoms within the distance from the point.
Parameters
----------
atoms : [ampal.atom]
A list of `ampal.atoms`.
cutoff_distance : float
Maximum distance from point.
point : (float, float, float)
Refe... | 0.00189 |
def get_prediction_score(self, node_id):
"""
Return the prediction score (if leaf node) or None if its an
intermediate node.
Parameters
----------
node_id: id of the node to get the prediction value.
Returns
-------
float or None: returns float v... | 0.003476 |
def tlog(x, th=1, r=_display_max, d=_l_mmax):
"""
Truncated log10 transform.
Parameters
----------
x : num | num iterable
values to be transformed.
th : num
values below th are transormed to 0.
Must be positive.
r : num (default = 10**4)
maximal transformed v... | 0.001497 |
def train_batch(self, batch_info: BatchInfo) -> None:
"""
Batch - the most atomic unit of learning.
For this reinforforcer, that involves:
1. Roll out the environmnent using current policy
2. Use that rollout to train the policy
"""
# Calculate environment rollo... | 0.00242 |
def _get_cpu_info_from_sysinfo_v2():
'''
Returns the CPU info gathered from sysinfo.
Returns {} if sysinfo is not found.
'''
try:
# Just return {} if there is no sysinfo
if not DataSource.has_sysinfo():
return {}
# If sysinfo fails return {}
returncode, output = DataSource.sysinfo_cpu()
if output == ... | 0.040765 |
def arbiter_priority(req_vec, gnt_vec=None, gnt_idx=None, gnt_vld=None):
""" Static priority arbiter: grants the request with highest priority, which is the lower index
req_vec - (i) vector of request signals, req_vec[0] is with the highest priority
gnt_vec - (o) optional, vector of grants, ... | 0.013821 |
def remove(self, contact_id, session):
'''taobao.logistics.address.remove 删除卖家地址库
用此接口删除卖家地址库'''
request = TOPRequest('taobao.logistics.address.remove')
request['contact_id'] = contact_id
self.create(self.execute(request, session))
return self.address_result | 0.009524 |
def set_pointer0d(subseqs):
"""Set_pointer function for 0-dimensional link sequences."""
print(' . set_pointer0d')
lines = Lines()
lines.add(1, 'cpdef inline set_pointer0d'
'(self, str name, pointerutils.PDouble value):')
for seq in subseqs:
... | 0.004415 |
def AdjustDescriptor(self, fields):
"""Payload-aware metadata processor."""
for f in fields:
if f.name == "args_rdf_name":
f.name = "payload_type"
if f.name == "args":
f.name = "payload"
return fields | 0.012346 |
def delete_object_async(self, path, **kwds):
"""DELETE an object.
Note: No payload argument is supported.
"""
return self.do_request_async(self.api_url + path, 'DELETE', **kwds) | 0.005155 |
def description(self):
"""This read-only attribute is a sequence of 7-item sequences.
Each of these sequences contains information describing one result column:
- name
- type_code
- display_size (None in current implementation)
- internal_size (None in current implement... | 0.006466 |
def define_request(
dataset, query=None, crs="epsg:4326", bounds=None, sortby=None, pagesize=10000
):
"""Define the getfeature request parameters required to download a dataset
References:
- http://www.opengeospatial.org/standards/wfs
- http://docs.geoserver.org/stable/en/user/services/wfs/vendor.h... | 0.00112 |
def save(self):
"""
Saves changes made to the locally cached DesignDocument object's data
structures to the remote database. If the design document does not
exist remotely then it is created in the remote database. If the object
does exist remotely then the design document is u... | 0.00197 |
def materialize_entity(ctx, etype, unique=None):
'''
Low-level routine for creating a BIBFRAME resource. Takes the entity (resource) type and a data mapping
according to the resource type. Implements the Libhub Resource Hash Convention
As a convenience, if a vocabulary base is provided in the context, c... | 0.006897 |
def to_pb(self):
"""Render a protobuf message.
Returns:
google.iam.policy_pb2.Policy: a message to be passed to the
``set_iam_policy`` gRPC API.
"""
return policy_pb2.Policy(
etag=self.etag,
version=self.version or 0,
bindings... | 0.004405 |
def reload(self, reload_timeout=300, save_config=True):
"""Reload the device.
CSM_DUT#reload
System configuration has been modified. Save? [yes/no]: yes
Building configuration...
[OK]
Proceed with reload? [confirm]
"""
response = "yes" if save_config els... | 0.004184 |
def xml(self, indent = ""):
"""Produce Template XML"""
xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
if self.formatclass.mimetype:
xml +=" mimetype=\""+self.formatclass.mimetype+"\""
if s... | 0.013474 |
def cloudwatch_connection(self):
""" Lazy create a connection to cloudwatch """
if self._cloudwatch_connection is None:
conn = self._session.create_client("cloudwatch", self.connection.region)
self._cloudwatch_connection = conn
return self._cloudwatch_connection | 0.009677 |
def _makedirs(self, path):
"""Make folders recursively for the given path and
check read and write permission on the path
Args:
path -- path to the leaf folder
"""
try:
oldmask = os.umask(0)
os.makedirs(path, self._conf['dmode'])
... | 0.005107 |
def markLoadingStarted(self):
"""
Marks this widget as loading records.
"""
if self.isThreadEnabled():
XLoaderWidget.start(self)
if self.showTreePopup():
tree = self.treePopupWidget()
tree.setCursor(Qt.WaitCursor)
... | 0.00675 |
def _list_function_infos(jvm):
"""
Returns a list of function information via JVM. Sorts wrapped expression infos by name
and returns them.
"""
jinfos = jvm.org.apache.spark.sql.api.python.PythonSQLUtils.listBuiltinFunctionInfos()
infos = []
for jinfo in jinfos:
name = jinfo.getName... | 0.003488 |
def _import_next_layer(self, proto, length):
"""Import next layer extractor.
Positional arguments:
* proto -- str, next layer protocol name
* length -- int, valid (not padding) length
Returns:
* bool -- flag if extraction of next layer succeeded
... | 0.002907 |
def _StackSummary_extract(frame_gen, limit=None, lookup_lines=True, capture_locals=False):
"""
Replacement for :func:`StackSummary.extract`.
Create a StackSummary from a traceback or stack object.
Very simplified copy of the original StackSummary.extract().
We want always to capture locals, that is... | 0.003192 |
def _chk_fld(self, ntd, name, qty_min=0, qty_max=None):
"""Further split a GAF value within a single field."""
vals = getattr(ntd, name)
num_vals = len(vals)
if num_vals < qty_min:
self.illegal_lines['MIN QTY'].append(
(-1, "FIELD({F}): MIN QUANTITY({Q}) WASN'... | 0.006309 |
def advance_for_next_slice(self, recovery_slice=False):
"""Advance self for next slice.
Args:
recovery_slice: True if this slice is running recovery logic.
See handlers.MapperWorkerCallbackHandler._attempt_slice_recovery
for more info.
"""
self.slice_start_time = None
self.sli... | 0.006237 |
def print_app_info (out=stderr):
"""Print system and application info (output defaults to stderr)."""
print(_("System info:"), file=out)
print(configuration.App, file=out)
print(_("Released on:"), configuration.ReleaseDate, file=out)
print(_("Python %(version)s on %(platform)s") %
... | 0.00625 |
def config():
'''
Shows the current configuration.
'''
config = get_config()
print('Client version: {0}'.format(click.style(__version__, bold=True)))
print('API endpoint: {0}'.format(click.style(str(config.endpoint), bold=True)))
print('API version: {0}'.format(click.style(config.version, bo... | 0.003807 |
def read(path, cfg={}, raise_on_error=False, silent=False, verbose=False, return_errors=False):
"""Wraps pandas.IO & odo to create a dictionary of pandas.DataFrames from multiple different sources
Parameters
----------
path : str
Location of file, folder or zip-file to be parsed. Can includ... | 0.008214 |
def is_message_enabled(self, msg_descr, line=None, confidence=None):
"""return true if the message associated to the given message id is
enabled
msgid may be either a numeric or symbolic message id.
"""
if self.config.confidence and confidence:
if confidence.name not... | 0.003326 |
def node_validate(node_dict, node_num, cmd_name):
"""Validate that command can be performed on target node."""
# cmd: [required-state, action-to-displayed, error-statement]
req_lu = {"run": ["stopped", "Already Running"],
"stop": ["running", "Already Stopped"],
"connect": ["runni... | 0.001225 |
def _get_branches(self):
"""Get branches from org/repo."""
if self.offline:
local_path = Path(LOCAL_PATH).expanduser() / self.org / self.repo
get_refs = f"git -C {shlex.quote(str(local_path))} show-ref --heads"
else:
get_refs = f"git ls-remote --heads https://... | 0.008489 |
def _gen_doc(cls, summary, full_name, identifier, example_call, doc_str,
show_examples):
"""Generate the documentation docstring for a PlotMethod"""
ret = docstrings.dedents("""
%s
This plotting method adds data arrays and plots them via
:class:`%s` ... | 0.005008 |
def add_headers(vcf_obj, nr_cases=None, sv=False):
"""Add loqus specific information to a VCF header
Args:
vcf_obj(cyvcf2.VCF)
"""
vcf_obj.add_info_to_header(
{
'ID':"Obs",
'Number': '1',
'Type': 'Integer',
'Description': "The number of o... | 0.004826 |
def read_local_config(cfg):
""" Parses local config file for override values
Args:
:local_file (str): filename of local config file
Returns:
dict object of values contained in local config file
"""
try:
if os.path.exists(cfg):
config = import_file_object(cfg)
... | 0.00152 |
def build(self, builder):
"""
Build XML by appending to builder
"""
if self.text is None:
raise ValueError("Text is not set.")
params = {}
if self.sponsor_or_site is not None:
params['SponsorOrSite'] = self.sponsor_or_site
builder.start("C... | 0.005013 |
def scheduled_status(self, id):
"""
Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | 0.00639 |
def isCommaList(inputFilelist):
"""Return True if the input is a comma separated list of names."""
if isinstance(inputFilelist, int) or isinstance(inputFilelist, np.int32):
ilist = str(inputFilelist)
else:
ilist = inputFilelist
if "," in ilist:
return True
return False | 0.003195 |
def themes_path():
"""
Retrieve the location of the themes directory from the location of this package
This is taken from Sphinx's theme documentation
"""
package_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(package_dir, 'themes') | 0.007168 |
def rollback(self):
"""Abandon the current transaction.
Rollback all messages published during the current transaction
session to the remote server.
Note that all messages published during this transaction session
will be lost, and will have to be published agai... | 0.00361 |
def decrypt_var(source, passphrase=None):
"""Attempts to decrypt a variable"""
cmd = [gnupg_bin(), "--decrypt", gnupg_home(), gnupg_verbose(),
passphrase_file(passphrase)]
return stderr_with_input(flatten(cmd), source) | 0.004132 |
def next_haab(month, jd):
'''For a given haab month and a julian day count, find the next start of that month on or after the JDC'''
if jd < EPOCH:
raise IndexError("Input day is before Mayan epoch.")
hday, hmonth = to_haab(jd)
if hmonth == month:
days = 1 - hday
else:
cou... | 0.003484 |
def a_href_finder(pipeline_index,
soup,
finder_image_urls=[],
*args, **kwargs):
"""
Find image URL in <a>'s href attribute
"""
now_finder_image_urls = []
for a in soup.find_all('a'):
href = a.get('href', None)
if href:
... | 0.005747 |
def push_irq_registers(self):
"""
push PC, U, Y, X, DP, B, A, CC on System stack pointer
"""
self.cycles += 1
self.push_word(self.system_stack_pointer, self.program_counter.value) # PC
self.push_word(self.system_stack_pointer, self.user_stack_pointer.value) # U
se... | 0.014608 |
def diff(self, summary1=None, summary2=None):
"""Compute diff between to summaries.
If no summary is provided, the diff from the last to the current
summary is used. If summary1 is provided the diff from summary1
to the current summary is used. If summary1 and summary2 are
provi... | 0.003311 |
def add_virtual_columns_cartesian_velocities_to_spherical(self, x="x", y="y", z="z", vx="vx", vy="vy", vz="vz", vr="vr", vlong="vlong", vlat="vlat", distance=None):
"""Concert velocities from a cartesian to a spherical coordinate system
TODO: errors
:param x: name of x column (input)
:... | 0.006575 |
def waypoint_clear_all_send(self):
'''wrapper for waypoint_clear_all_send'''
if self.mavlink10():
self.mav.mission_clear_all_send(self.target_system, self.target_component)
else:
self.mav.waypoint_clear_all_send(self.target_system, self.target_component) | 0.013245 |
def changelog_file_option_validator(ctx, param, value):
"""Checks that the given file path exists in the current working directory.
Returns a :class:`~pathlib.Path` object. If the file does not exist raises
a :class:`~click.UsageError` exception.
"""
path = Path(value)
if not path.exists():
... | 0.001832 |
def _bytype(self, action_type, action_spec=None):
'''Return the most recent date on which action_type occurred.
Action spec is a dictionary of key-value attrs to match.'''
for action in reversed(self.bill['actions']):
if action_type in action['type']:
for k, v in acti... | 0.004854 |
def fit(self, X, y=None, categorical=None):
"""Compute k-prototypes clustering.
Parameters
----------
X : array-like, shape=[n_samples, n_features]
categorical : Index of columns that contain categorical data
"""
if categorical is not None:
assert isi... | 0.002334 |
def get_or_add_video_media_part(self, video):
"""Return rIds for media and video relationships to media part.
A new |MediaPart| object is created if it does not already exist
(such as would occur if the same video appeared more than once in
a presentation). Two relationships to the med... | 0.002632 |
def _validate_inputs(self, inputdict):
""" Validate input links.
"""
# Check inputdict
try:
parameters = inputdict.pop(self.get_linkname('parameters'))
except KeyError:
raise InputValidationError("No parameters specified for this "
... | 0.001129 |
def complexidade(obj):
"""
Returns a value that indicates project health, currently FinancialIndicator
is used as this value, but it can be a result of calculation with other
indicators in future
"""
indicators = obj.indicator_set.all()
if not indicators:
value = 0.0
else:
... | 0.002695 |
def swipe_top(self, steps=10, *args, **selectors):
"""
Swipe the UI object with *selectors* from center to top
See `Swipe Left` for more details.
"""
self.device(**selectors).swipe.up(steps=steps) | 0.008439 |
def make_skip_list(cts):
"""
Return hand-defined list of place names to skip and not attempt to geolocate. If users would like to exclude
country names, this would be the function to do it with.
"""
# maybe make these non-country searches but don't discard, at least for
# some (esp. bodies of wa... | 0.012829 |
def decrypt(self, text, appid):
"""对解密后的明文进行补位删除
@param text: 密文
@return: 删除填充补位后的明文
"""
try:
cryptor = AES.new(self.key, self.mode, self.key[:16])
# 使用BASE64对密文进行解码,然后AES-CBC解密
plain_text = cryptor.decrypt(base64.b64decode(text))
exce... | 0.001959 |
def featurize(equity_data, n_sessions, **kwargs):
"""
Generate a raw (unnormalized) feature set from the input data.
The value at `column` on the given date is taken
as a feature, and each row contains values for n_sessions
Parameters
-----------
equity_data : DataFrame
data from wh... | 0.003926 |
def _generate_exact_author_query(self, author_name_or_bai):
"""Generates a term query handling authors and BAIs.
Notes:
If given value is a BAI, search for the provided value in the raw field variation of
`ElasticSearchVisitor.AUTHORS_BAI_FIELD`.
Otherwise, the value... | 0.006126 |
def archive_handler(unused_build_context, target, fetch, package_dir, tar):
"""Handle remote downloadable archive URI.
Download the archive and cache it under the private builer workspace
(unless already downloaded), extract it, and add the content to the
package tar.
TODO(itamar): Support re-down... | 0.000746 |
def _get_node(nodes, node_id, fuzzy=True):
"""
Returns a dispatcher node that match the given node id.
:param nodes:
Dispatcher nodes.
:type nodes: dict
:param node_id:
Node id.
:type node_id: str
:return:
The dispatcher node and its id.
:rtype: (str, dict)
... | 0.001567 |
def get_response_query_template(service, operation):
"""refers to definition of API in botocore, and autogenerates template
Assume that response format is xml when protocol is query
You can see example of elbv2 from link below.
https://github.com/boto/botocore/blob/develop/botocore/data/elbv2/2015-12... | 0.00191 |
def get_parent_logs(self, log_id):
"""Gets the parent logs of the given ``id``.
arg: log_id (osid.id.Id): the ``Id`` of the ``Log`` to query
return: (osid.logging.LogList) - the parent logs of the ``id``
raise: NotFound - a ``Log`` identified by ``Id is`` not found
raise: N... | 0.002132 |
def staff_member(view_func):
"""Performs user authentication check.
Similar to Django's `login_required` decorator, except that this throws
:exc:`~leonardo.exceptions.NotAuthenticated` exception if the user is not
signed-in.
"""
@functools.wraps(view_func, assigned=available_attrs(view_func))
... | 0.001845 |
def from_zone(zone):
'''Build a GeoID from a given zone'''
validity = zone.validity.start if zone.validity else None
return build(zone.level, zone.code, validity) | 0.005747 |
def md5hash(self):
"""Return the MD5 hash string of the file content"""
digest = hashlib.md5(self.content).digest()
return b64_string(digest) | 0.012121 |
def copy(value, **kwargs):
"""Return a copy of a **HasProperties** instance
A copy is produced by serializing the HasProperties instance then
deserializing it to a new instance. Therefore, if any properties
cannot be serialized/deserialized, :code:`copy` will fail. Any
keyword arguments will be pas... | 0.001302 |
def write(self, value):
"""Write a (new) value to this variable."""
assert self.num_write_waits > 0, self
self.num_write_waits -= 1
self.values.append(value)
if self.readable:
LOG.debug('%s is now readable', self.name) | 0.007407 |
def resp_set_location(self, resp, location=None):
"""Default callback for get_location/set_location
"""
if location:
self.location=location
elif resp:
self.location=resp.label.decode().replace("\x00", "") | 0.015385 |
def _check_err(resp, url_suffix, data, allow_pagination):
"""
Raise DataServiceError if the response wasn't successful.
:param resp: requests.Response back from the request
:param url_suffix: str url to include in an error message
:param data: data payload we sent
:param ... | 0.003168 |
def get_agents_with_name(name, stmts):
"""Return all agents within a list of statements with a particular name."""
return [ag for stmt in stmts for ag in stmt.agent_list()
if ag is not None and ag.name == name] | 0.004348 |
def detect_unicode_support():
''' Try to detect unicode (utf8?) support in the terminal.
Experimental, implementation idea is from the link below:
https://unix.stackexchange.com/questions/184345/detect-how-much-of-unicode-my-terminal-supports-even-through-screen
TODO:
needs ... | 0.001765 |
def _update_workflow_stages(stage_data: dict, workflow_stage: WorkflowStage,
docker: DockerSwarmClient):
"""Check and update the status of a workflow stage.
This function checks and updates the status of a workflow stage
specified by the parameters in the specified stage_data di... | 0.0005 |
def extend_safe(target, source):
"""
Extends source list to target list only if elements doesn't exists in target list.
:param target:
:type target: list
:param source:
:type source: list
"""
for elt in source:
if elt not in target:
target.append(elt) | 0.006601 |
def py_scanstring(s, end, encoding=None, strict=True,
_b=BACKSLASH, _m=STRINGCHUNK.match, _join=u('').join,
_PY3=PY3, _maxunicode=sys.maxunicode):
"""Scan the string s for a JSON string. End is the index of the
character in s after the quote that started the JSON string.
Unescapes all valid ... | 0.001149 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.