text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def get_bounds(self):
"""
Returns
-------
(start, end)
Datetime instants of beginning and end of data. If no data, will be: (None, None).
"""
start, end = None, None
if len(self._weather_series) == 0:
return start, end
for i in (0, -1... | 0.005006 |
def subset(self, interval: Interval,
flexibility: int = 2) -> "IntervalList":
"""
Returns an IntervalList that's a subset of this one, only containing
intervals that meet the "interval" parameter criterion. What "meet"
means is defined by the ``flexibility`` parameter.
... | 0.001766 |
async def update_pin(**payload):
"""Update the onboarding welcome message after recieving a "pin_added"
event from Slack. Update timestamp for welcome message as well.
"""
data = payload["data"]
web_client = payload["web_client"]
channel_id = data["channel_id"]
user_id = data["user"]
# ... | 0.0012 |
def complete_command_help(self, tokens: List[str], text: str, line: str, begidx: int, endidx: int) -> List[str]:
"""Supports the completion of sub-commands for commands through the cmd2 help command."""
for idx, token in enumerate(tokens):
if idx >= self._token_start_index:
i... | 0.007982 |
def delete(self):
"""Delete the workspace from FireCloud.
Note:
This action cannot be undone. Be careful!
"""
r = fapi.delete_workspace(self.namespace, self.name)
fapi._check_response_code(r, 202) | 0.008032 |
def _generate_instances(self):
"""
ListNode item generator. Will be used internally by __iter__ and __getitem__
Yields:
ListNode items (instances)
"""
for node in self.node_stack:
yield node
while self._data:
yield self._make_instance(... | 0.008876 |
def format_units(self, value, unit="B", optimal=5, auto=True, si=False):
"""
Takes a value and formats it for user output, we can choose the unit to
use eg B, MiB, kbits/second. This is mainly for use with bytes/bits it
converts the value into a human readable form. It has various
... | 0.000893 |
def cached(fn, size=32):
''' this decorator creates a type safe lru_cache
around the decorated function. Unlike
functools.lru_cache, this will not crash when
unhashable arguments are passed to the function'''
assert callable(fn)
assert isinstance(size, int)
return overload(fn)(lru_cache(size... | 0.002959 |
def values_from(self, base):
"""
A reusable generator for increasing pointer-sized values from an address
(usually the stack).
"""
word_bytes = self._cpu.address_bit_size // 8
while True:
yield base
base += word_bytes | 0.010381 |
def refractive_index(CASRN, T=None, AvailableMethods=False, Method=None,
full_info=True):
r'''This function handles the retrieval of a chemical's refractive
index. Lookup is based on CASRNs. Will automatically select a data source
to use if no Method is provided; returns None if the dat... | 0.00043 |
def set_char_callback(window, cbfun):
"""
Sets the Unicode character callback.
Wrapper for:
GLFWcharfun glfwSetCharCallback(GLFWwindow* window, GLFWcharfun cbfun);
"""
window_addr = ctypes.cast(ctypes.pointer(window),
ctypes.POINTER(ctypes.c_long)).contents.val... | 0.001272 |
def load_empty(cls, path:PathOrStr, fn:PathOrStr):
"Load the state in `fn` to create an empty `LabelList` for inference."
return cls.load_state(path, pickle.load(open(Path(path)/fn, 'rb'))) | 0.019512 |
def merge_pres_feats(pres, features):
"""
Helper function to merge pres and features to support legacy features argument
"""
sub = []
for psub, fsub in zip(pres, features):
exp = []
for pexp, fexp in zip(psub, fsub):
lst = []
for p, f in zip(pexp, fexp):
... | 0.004545 |
def register_default_prefixes(handler):
"""\
"""
for prefix, ns in _PREFIXES.iteritems():
handler.add_prefix(prefix, str(ns)) | 0.013793 |
def get_nonvaried_cfg_lbls(cfg_list, default_cfg=None, mainkey='_cfgname'):
r"""
TODO: this might only need to return a single value. Maybe not if the names
are different.
Args:
cfg_list (list):
default_cfg (None): (default = None)
Returns:
list: cfglbl_list
Comman... | 0.000775 |
def dist(self, src, tar, max_offset=5, max_distance=0):
"""Return the normalized "common" Sift4 distance between two terms.
This is Sift4 distance, normalized to [0, 1].
Parameters
----------
src : str
Source string for comparison
tar : str
Targe... | 0.00197 |
def get_v_distance(self, latlonalt1, latlonalt2):
'''get the horizontal distance between threat and vehicle'''
(lat1, lon1, alt1) = latlonalt1
(lat2, lon2, alt2) = latlonalt2
return alt2 - alt1 | 0.008889 |
def visit_Assign(self, node):
"""
Implement assignment walker.
Parse class properties defined via the property() function
"""
# [[[cog
# cog.out("print(pcolor('Enter assign visitor', 'magenta'))")
# ]]]
# [[[end]]]
# ###
# Class-level assi... | 0.001407 |
def mk_size(field):
"""Builds an identifier for a container type.
"""
name = field.type_id
if name == "string" and field.options.get('size', None):
return "%s[%d];" % (field.identifier, field.options.get('size').value)
elif name == "string":
return "%s[0];" % field.identifier
elif name == "array" an... | 0.014925 |
def to_sample_rdd(x, y, numSlices=None):
"""
Conver x and y into RDD[Sample]
:param x: ndarray and the first dimension should be batch
:param y: ndarray and the first dimension should be batch
:param numSlices:
:return:
"""
sc = get_spark_context()
from bigdl.util.common import Sampl... | 0.004107 |
def get_bulb(self, mac):
"""
Returns a Bulb object corresponding to the bulb with the mac address
`mac` (a 6-byte bytestring).
"""
return self.bulbs.get(mac, Bulb('Bulb %s' % _bytes(mac), mac)) | 0.008584 |
def cc(self) -> Optional[Sequence[AddressHeader]]:
"""The ``Cc`` header."""
try:
return cast(Sequence[AddressHeader], self[b'cc'])
except KeyError:
return None | 0.009662 |
async def Prune(self, max_history_mb, max_history_time):
'''
max_history_mb : int
max_history_time : int
Returns -> None
'''
# map input types to rpc msg
_params = dict()
msg = dict(type='ActionPruner',
request='Prune',
... | 0.003774 |
def execute_cleanup_tasks(ctx, cleanup_tasks, dry_run=False):
"""Execute several cleanup tasks as part of the cleanup.
REQUIRES: ``clean(ctx, dry_run=False)`` signature in cleanup tasks.
:param ctx: Context object for the tasks.
:param cleanup_tasks: Collection of cleanup tasks (as Colle... | 0.00155 |
def trainGP(self,fast=False,scales0=None,fixed0=None,lambd=None):
"""
Train the gp
Args:
fast: if true and the gp has not been initialized, initializes a kronSum gp
scales0: initial variance components params
fixed0: initial fixed effect para... | 0.021033 |
def impute_element(self, records=('ATOM', 'HETATM'), inplace=False):
"""Impute element_symbol from atom_name section.
Parameters
----------
records : iterable, default: ('ATOM', 'HETATM')
Coordinate sections for which the element symbols should be
imputed.
... | 0.002075 |
def get_appstruct(self):
""" return list of tuples keys and values corresponding to this model's
data """
result = []
for k in self._get_keys():
result.append((k, getattr(self, k)))
return result | 0.008097 |
def emoji(string):
'''emot.emoji is use to detect emoji from text
>>> text = "I love python 👨 :-)"
>>> emot.emoji(text)
>>> {'value': ['👨'], 'mean': [':man:'], 'location': [[14, 14]], 'flag': True}
'''
__entities = {}
__value = []
__mean = []
__location = []
flag =... | 0.008065 |
def _exclude_paths_from_environ(env_prefix=''):
"""Environment value via `/login;/register`"""
paths = os.environ.get(env_prefix + 'WSGI_AUTH_EXCLUDE_PATHS')
if not paths:
return []
return paths.split(';') | 0.004367 |
def connection(self):
""" Provide the connection parameters for kombu's ConsumerMixin.
The `Connection` object is a declaration of connection parameters
that is lazily evaluated. It doesn't represent an established
connection to the broker at this point.
"""
heartbeat = ... | 0.002392 |
def wait_for_host(self, host):
"""Throttle requests to one host."""
t = time.time()
if host in self.times:
due_time = self.times[host]
if due_time > t:
wait = due_time - t
time.sleep(wait)
t = time.time()
wait_time =... | 0.004808 |
def get_variable_str(self):
"""
Utility method to get the variable value or 'var_name=value' if name is not None.
Note that values with large string representations will not get printed
:return:
"""
if self.var_name is None:
prefix = ''
else:
... | 0.004518 |
def index():
"""Display list of the user's repositories."""
github = GitHubAPI(user_id=current_user.id)
token = github.session_token
ctx = dict(connected=False)
if token:
# The user is authenticated and the token we have is still valid.
if github.account.extra_data.get('login') is N... | 0.000634 |
def segment_length(curve, start, end, start_point, end_point,
error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH, depth=0):
"""Recursively approximates the length by straight lines"""
mid = (start + end)/2
mid_point = curve.point(mid)
length = abs(end_point - start_point)
first_half =... | 0.001152 |
def read_namespaced_pod(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod # noqa: E501
read the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread ... | 0.001471 |
def col2name(col_item):
"helper for SyntheticTable.columns. takes something from SelectX.cols, returns a string column name"
if isinstance(col_item, sqparse2.NameX): return col_item.name
elif isinstance(col_item, sqparse2.AliasX): return col_item.alias
else: raise TypeError(type(col_item), col_item) | 0.029221 |
def setup(app):
''' Required Sphinx extension setup function. '''
app.add_node(
bokehjs_content,
html=(
html_visit_bokehjs_content,
html_depart_bokehjs_content
)
)
app.add_directive('bokehjs-content', BokehJSContent) | 0.003571 |
def mirror_video(self, is_mirror, callback=None):
'''
Mirror video
``is_mirror``: 0 not mirror, 1 mirror
'''
params = {'isMirror': is_mirror}
return self.execute_command('mirrorVideo', params, callback=callback) | 0.007752 |
def plot_filter_transmissions(log, filterList):
"""
*Plot the filters on a single plot*
**Key Arguments:**
- ``log`` -- logger
- ``filterList`` -- list of absolute paths to plain text files containing filter transmission profiles
**Return:**
- None
"""
################ ... | 0.011127 |
def get_submission_filenames(self, tournament=None, round_num=None):
"""Get filenames of the submission of the user.
Args:
tournament (int): optionally filter by ID of the tournament
round_num (int): optionally filter round number
Returns:
list: list of user... | 0.001203 |
def export_coreml(self, filename):
"""
Export the model in Core ML format.
Parameters
----------
filename: str
A valid filename where the model can be saved.
Examples
--------
>>> model.export_coreml("MyModel.mlmodel")
"""
from ... | 0.007368 |
def _create_credentials(self, n):
"""
Create security credentials, if necessary.
"""
if not n:
return n
elif isinstance(n, SecurityCreds):
return n
elif isinstance(n, dict):
return SecurityCreds(**n)
else:
raise Type... | 0.004914 |
def _parse_spectra(self, line):
"""Parse and store the spectral details
"""
if line in ['\n', '\r\n', '//\n', '//\r\n', '', '//']:
self.start_spectra = False
self.current_id_meta += 1
self.collect_meta = True
return
splist = line.split()
... | 0.004121 |
async def addSignalHandlers(self):
'''
Register SIGINT signal handler with the ioloop to cancel the currently running cmdloop task.
'''
def sigint():
self.printf('<ctrl-c>')
if self.cmdtask is not None:
self.cmdtask.cancel()
self.loop.add... | 0.00838 |
def copy_w_id_suffix(elem, suffix="_copy"):
"""Make a deep copy of the provided tree, altering ids."""
mycopy = deepcopy(elem)
for id_elem in mycopy.xpath('//*[@id]'):
id_elem.set('id', id_elem.get('id') + suffix)
return mycopy | 0.003984 |
def quokka_heatmap(size=None, extract=None):
"""
Returns a heatmap (here: depth map) for the standard example quokka image.
Parameters
----------
size : None or float or tuple of int, optional
See :func:`imgaug.quokka`.
extract : None or 'square' or tuple of number or imgaug.BoundingBo... | 0.002736 |
def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem | 0.004525 |
def compute(self, xt1, yt1, xt, yt, theta1t1, theta2t1, theta1, theta2, learn):
"""
The main function to call.
If learn is False, it will print a prediction: (theta1, theta2)
"""
dx = xt - xt1
dy = yt - yt1
self.minDx = min(self.minDx, dx)
self.maxDx = max(self.maxDx, dx)
print >>s... | 0.01041 |
def get_cardinality(self, field=None):
"""
Create a cardinality aggregation object and add it to the aggregation dict
:param field: the field present in the index that is to be aggregated
:returns: self, which allows the method to be chainable with the other methods
"""
... | 0.010309 |
def parse_qs(qs):
"""Helper func to parse query string with py2/py3 compatibility
Ensures that dict keys are native strings.
"""
result = {}
qs = bstr(qs, 'latin1')
pairs = [s2 for s1 in qs.split(b'&') for s2 in s1.split(b';')]
uq = urlparse.unquote if PY2 else urlparse.unquote_to_bytes
... | 0.001299 |
def clean_new(self, value):
"""Return a new object instantiated with cleaned data."""
value = self.schema_class(value).full_clean()
return self.object_class(**value) | 0.010582 |
def parse_line_headers(self, line):
"""We must build headers carefully: there are multiple blank values
in the header row, and the instrument may just add more for all
we know.
"""
headers = line.split(",")
for i, v in enumerate(headers):
if v:
... | 0.004762 |
def select_good_pixel_region(hits, col_span, row_span, min_cut_threshold=0.2, max_cut_threshold=2.0):
'''Takes the hit array and masks all pixels with a certain occupancy.
Parameters
----------
hits : array like
If dim > 2 the additional dimensions are summed up.
min_cut_threshold : float
... | 0.004354 |
def stream_data(self, ostream):
"""Writes our data directly to the given output stream
:param ostream: File object compatible stream object.
:return: self"""
istream = self.repo.odb.stream(self.binsha)
stream_copy(istream, ostream)
return self | 0.006873 |
def user_active_directory_deactivate(user, attributes, created, updated):
"""
Deactivate user accounts based on Active Directory's
userAccountControl flags. Requires 'userAccountControl'
to be included in LDAP_SYNC_USER_EXTRA_ATTRIBUTES.
"""
try:
user_account_control = int(attribu... | 0.002179 |
def matches_rule(message, rule, destinations = None) :
"does Message message match against the specified rule."
if not isinstance(message, Message) :
raise TypeError("message must be a Message")
#end if
rule = unformat_rule(rule)
eavesdrop = rule.get("eavesdrop", "false") == "true"
def ... | 0.01549 |
def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
"""Store multiple lines as a single entry in history"""
# do nothing without readline or disabled multiline
if not self.has_readline or not self.multiline_history:
return hlen_before_cell
# windows rl has no... | 0.00271 |
def search(self, search, **kwargs):
"""
Search for Repository Configurations based on internal or external url, ignoring the protocol and \".git\" suffix. The matching is done using LIKE.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP reque... | 0.003147 |
def gaussian_window(t, params):
"""
Calculates a Gaussian window function in the time domain which will broaden
peaks in the frequency domain by params["line_broadening"] Hertz.
:param t:
:param params:
:return:
"""
window = suspect.basis.gaussian(t, 0, 0, params["line_broadening"])
... | 0.002049 |
def create_container_service(access_token, subscription_id, resource_group, service_name, \
agent_count, agent_vm_size, agent_dns, master_dns, admin_user, location, public_key=None,\
master_count=3, orchestrator='DCOS', app_id=None, app_secret=None, admin_password=None, \
ostype='Linux'):
'''Create a ne... | 0.005616 |
def scale_and_crop_with_subject_location(im, size, subject_location=False,
zoom=None, crop=False, upscale=False,
**kwargs):
"""
Like ``easy_thumbnails.processors.scale_and_crop``, but will use the
coordinates in ``subject_loca... | 0.00026 |
def readinto(self, b):
"""Read up to len(b) bytes into the writable buffer *b* and return
the number of bytes read. If the socket is non-blocking and no bytes
are available, None is returned.
If *b* is non-empty, a 0 return value indicates that the connection
was shutdown at th... | 0.00227 |
def disconnect_socket(self):
"""
Disconnect the underlying socket connection
"""
self.running = False
if self.socket is not None:
if self.__need_ssl():
#
# Even though we don't want to use the socket, unwrap is the only API method which... | 0.003679 |
def iter_nautilus(method):
""" Iterate NAUTILUS method either interactively, or using given preferences if given
Parameters
----------
method : instance of NAUTILUS subclass
Fully initialized NAUTILUS method instance
"""
solution = None
while method.current_iter:
preference... | 0.001735 |
async def extended_analog(self, pin, data):
"""
This method will send an extended-data analog write command to the
selected pin.
:param pin: 0 - 127
:param data: 0 - 0xfffff
:returns: No return value
"""
analog_data = [pin, data & 0x7f, (data >> 7) & 0x... | 0.007109 |
def binary(self):
"""
Get the object this function belongs to.
:return: The object this function belongs to.
"""
return self._project.loader.find_object_containing(self.addr, membership_check=False) | 0.012552 |
def clean_download_cache(self, args):
""" Deletes a download cache for recipes passed as arguments. If no
argument is passed, it'll delete *all* downloaded caches. ::
p4a clean_download_cache kivy,pyjnius
This does *not* delete the build caches or final distributions.
"""
... | 0.002871 |
def sign_in(self, timeout=60, safe=True, tries=1, channel=None):
'''
Send a sign in request to the master, sets the key information and
returns a dict containing the master publish interface to bind to
and the decrypted aes key for transport decryption.
:param int timeout: Numbe... | 0.003499 |
def _bsecurate_cli_view_graph(args):
'''Handles the view-graph subcommand'''
curate.view_graph(args.basis, args.version, args.data_dir)
return '' | 0.006329 |
def get_logger(name, log_level=logging.INFO, log_file=None, global_log_file=False, silence=False):
"""
Build a logger. All logs will be propagated up to the root logger if not silenced. If log_file is provided, logs will be written out to that file. If global_log_file is true, log_file will be handed th... | 0.005401 |
def VerifyStructure(self, parser_mediator, line):
"""Verify that this file is a Mac AppFirewall log file.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
line (str): line from a text file.
Returns:
b... | 0.007106 |
def _output_marc(output_complete, categories,
kw_field=None,
auth_field=None,
acro_field=None,
provenience='Classifier'):
"""Output the keywords in the MARCXML format.
:var skw_matches: list of single keywords
:var ckw_matches: list of com... | 0.000352 |
def validate_is_non_abstract_edge_type(self, edge_classname):
"""Validate that a edge classname corresponds to a non-abstract edge class."""
element = self.get_edge_schema_element_or_raise(edge_classname)
if element.abstract:
raise InvalidClassError(u'Expected a non-abstract vertex ... | 0.009828 |
def as_dict(self):
"""Dict representation of parsed VCF data"""
self_as_dict = {'chrom': self.chrom,
'start': self.start,
'ref_allele': self.ref_allele,
'alt_alleles': self.alt_alleles,
'alleles': [x.as_dict(... | 0.004175 |
def _get_seq2c_options(data):
"""Get adjustable, through resources, or default options for seq2c.
"""
cov2lr_possible_opts = ["-F"]
defaults = {}
ropts = config_utils.get_resources("seq2c", data["config"]).get("options", [])
assert len(ropts) % 2 == 0, "Expect even number of options for seq2c" %... | 0.004831 |
def get_version(self):
"""Get the DCNM version."""
url = '%s://%s/rest/dcnm-version' % (self.dcnm_protocol, self._ip)
payload = {}
try:
res = self._send_request('GET', url, payload, 'dcnm-version')
if res and res.status_code in self._resp_ok:
ret... | 0.003817 |
def get_derived_from(self, address):
"""Get the target the specified target was derived from.
If a Target was injected programmatically, e.g. from codegen, this allows us to trace its
ancestry. If a Target is not derived, default to returning itself.
:API: public
"""
parent_address = self._de... | 0.00489 |
def build(self, builder):
"""Build XML by appending to builder"""
builder.start("BasicDefinitions", {})
for child in self.measurement_units:
child.build(builder)
builder.end("BasicDefinitions") | 0.008439 |
def add_schemas(path, ext="json"):
"""Add schemas from files in 'path'.
:param path: Path with schema files. Schemas are named by their file,
with the extension stripped. e.g., if path is "/tmp/foo",
then the schema in "/tmp/foo/bar.json" will be named "bar".
:type path: s... | 0.00102 |
def solve(self):
'''
Solves a one period consumption saving problem with risky income, with
persistent income explicitly tracked as a state variable.
Parameters
----------
None
Returns
-------
solution : ConsumerSolution
The solution ... | 0.006823 |
def initialize_slot(obj, name, value):
"""Initalize an unitialized slot to a value.
If there is already a value for this slot, this is a nop.
Parameters
----------
obj : immutable
An immutable object.
name : str
The name of the slot to initialize.
value : any
The va... | 0.002326 |
def get_server_data(self, UUID):
"""
Return '/server/uuid' data in Python dict.
Creates object representations of any IP-address and Storage.
"""
data = self.get_request('/server/{0}'.format(UUID))
server = data['server']
# Populate subobjects
IPAddresse... | 0.006088 |
def get_bookmarks(self, **filters):
"""
Get Bookmarks for the current user.
Filters:
:param archive: Filter Bookmarks returned by archived status.
:param favorite: Filter Bookmarks returned by favorite status.
:param domain: Filter Bookmarks returned by a domain.
... | 0.004798 |
def load_graphs():
'''load graphs from mavgraphs.xml'''
mestate.graphs = []
gfiles = ['mavgraphs.xml']
if 'HOME' in os.environ:
for dirname, dirnames, filenames in os.walk(os.path.join(os.environ['HOME'], ".mavproxy")):
for filename in filenames:
if filename.lower().e... | 0.003717 |
def uninstall(ctx, plugin):
"""
Uninstall the given plugin.
"""
ensure_inside_venv(ctx)
if plugin not in get_installed_plugins():
echo_error("Plugin {} does not seem to be installed.".format(plugin))
sys.exit(1)
plugin_name = get_plugin_name(plugin)
try:
run_command... | 0.001397 |
def get_key_for_enctype(self, etype):
"""
Returns the encryption key bytes for the enctryption type.
"""
if etype == EncryptionType.AES256_CTS_HMAC_SHA1_96:
if self.kerberos_key_aes_256:
return bytes.fromhex(self.kerberos_key_aes_256)
if self.password is not None:
salt = (self.domain.upper() + sel... | 0.026836 |
def update_ip_address(context, id, ip_address):
"""Due to NCP-1592 ensure that address_type cannot change after update."""
LOG.info("update_ip_address %s for tenant %s" % (id, context.tenant_id))
ports = []
if 'ip_address' not in ip_address:
raise n_exc.BadRequest(resource="ip_addresses",
... | 0.000222 |
def reset(self):
"""Reset this instance. Loses all unprocessed data."""
self.rawdata = ''
self.lasttag = '???'
self.interesting = interesting_normal
self.cdata_elem = None
_markupbase.ParserBase.reset(self) | 0.007843 |
def render_item(self, all_posts):
"""
Renders the Post as HTML using the template specified in :attr:`html_template_path`.
:param all_posts: An optional :class:`PostCollection` containing all of the posts in the site.
:return: The rendered HTML as a string.
"""
index = a... | 0.004667 |
def stop(self, msg=None):
'''Stopping a run. Control for loops. Gentle stop/abort.
This event should provide a more gentle abort. The run should stop ASAP but the run is still considered complete.
'''
if not self.stop_run.is_set():
if msg:
logging.info('%s%s ... | 0.008386 |
def to_xml(self):
"""
Serialize all properties as XML
"""
ret = '<exif>'
for k in self.__dict__:
ret += '<%s>%s</%s>' % (k, self.__dict__[k], k)
ret += '</exif>'
return ret | 0.008333 |
def set_timezone(self, timezone: str):
""" sets the timezone for the AP. e.g. "Europe/Berlin"
Args:
timezone(str): the new timezone
"""
data = {"timezoneId": timezone}
return self._restCall("home/setTimezone", body=json.dumps(data)) | 0.010309 |
def flatten_all_paths(group, group_filter=lambda x: True,
path_filter=lambda x: True, path_conversions=CONVERSIONS,
group_search_xpath=SVG_GROUP_TAG):
"""Returns the paths inside a group (recursively), expressing the
paths in the base coordinates.
Note that if th... | 0.000322 |
def _mid(string, start, end=None):
"""
Returns a substring delimited by start and end position.
"""
if end is None:
end = len(string)
return string[start:start + end] | 0.005155 |
def get_or_create(cls, filter_key=None, with_status=False, **kwargs):
"""
Convenience method to retrieve an Element or create if it does not
exist. If an element does not have a `create` classmethod, then it
is considered read-only and the request will be redirected to :meth:`~get`.
... | 0.00347 |
def _prep_jid(self, clear_load, extra):
'''
Return a jid for this publication
'''
# the jid in clear_load can be None, '', or something else. this is an
# attempt to clean up the value before passing to plugins
passed_jid = clear_load['jid'] if clear_load.get('jid') else ... | 0.002041 |
def scaledBy(self, scale):
""" Return a new Selector with scale denominators scaled by a number.
"""
scaled = deepcopy(self)
for test in scaled.elements[0].tests:
if type(test.value) in (int, float):
if test.property == 'scale-denominator':
... | 0.008439 |
def w_diffuser_outer(sed_inputs=sed_dict):
"""Return the outer width of each diffuser in the sedimentation tank.
Parameters
----------
sed_inputs : dict
A dictionary of all of the constant inputs needed for sedimentation tank
calculations can be found in sed.yaml
Returns
-------
... | 0.004823 |
def _call(self, method, auth, arg, defer, notimeout=False):
"""Calls the Exosite One Platform RPC API.
If `defer` is False, result is a tuple with this structure:
(success (boolean), response)
Otherwise, the result is just True.
notimeout, if True, ignores th... | 0.003008 |
def is_number(string):
""" checks if a string is a number (int/float) """
string = str(string)
if string.isnumeric():
return True
try:
float(string)
return True
except ValueError:
return False | 0.004098 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.