text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def new_module(self):
''' Make a fresh module to run in.
Returns:
Module
'''
self.reset_run_errors()
if self._code is None:
return None
module_name = 'bk_script_' + make_id().replace('-', '')
module = ModuleType(str(module_name)) # str ... | 0.007059 |
def cf_dictionary_to_dict(dictionary):
"""
Converts a CFDictionary object into a python dictionary
:param dictionary:
The CFDictionary to convert
:return:
A python dict
"""
dict_length = CoreFoundation.CFDictionaryGetCount(dictionary)
k... | 0.004121 |
def get_tokens(max_value):
"""Defines tokens.
Args:
max_value: the maximum numeric range for the token.
Returns:
list of string tokens in vocabulary.
"""
vocab = [str(i) for i in range(max_value)]
vocab = set(vocab)
vocab.update(CodeOp.LITERALS)
vocab.update(CodeOp.KEYWORDS)
vocab |= set("".... | 0.022535 |
def get_valid_kwargs(func, potential_kwargs):
"""
Return valid kwargs to function func
"""
kwargs = {}
for name in get_kwarg_names(func):
with suppress(KeyError):
kwargs[name] = potential_kwargs[name]
return kwargs | 0.003876 |
def Reload(self):
"""Call `Reload` on every `EventAccumulator`."""
logger.info('Beginning EventMultiplexer.Reload()')
self._reload_called = True
# Build a list so we're safe even if the list of accumulators is modified
# even while we're reloading.
with self._accumulators_mutex:
items = li... | 0.006742 |
def extractFieldsFromResult(data):
'''
Method that parses Infobel textual information to return a series of attributes.
:return: a list of i3visio-like objects.
'''
entities = []
# Defining the objects to extract
fieldsRegExp = {}
fieldsRegExp["i3visio.full... | 0.012521 |
def getColorHSV(name):
"""Retrieve the hue, saturation, value triple of a color name.
Returns:
a triple (degree, percent, percent). If not found (-1, -1, -1) is returned.
"""
try:
x = getColorInfoList()[getColorList().index(name.upper())]
except:
return (-1, -1, -1)
... | 0.008235 |
def longitude(self, longitude):
"""Setter for longitude."""
if not (-180 <= longitude <= 180):
raise ValueError('longitude was {}, but has to be in [-180, 180]'
.format(longitude))
self._longitude = longitude | 0.007326 |
def get_relationship_form_for_update(self, relationship_id=None):
"""Gets the relationship form for updating an existing relationship.
A new relationship form should be requested for each update
transaction.
arg: relationship_id (osid.id.Id): the ``Id`` of the
``Rela... | 0.002322 |
def check(codeString, filename, reporter=None):
"""
Check the Python source given by C{codeString} for flakes.
@param codeString: The Python source to check.
@type codeString: C{str}
@param filename: The name of the file the source came from, used to report
errors.
@type filename: C{st... | 0.000456 |
def search_terms(q):
'''Takes a search string and parses it into a list of keywords and
phrases.'''
tokens = parse_search_terms(q)
# iterate through all the tokens and make a list of token values
# (which are the actual words and phrases)
values = []
for t in tokens:
# word/phrase
... | 0.002628 |
def get_condition(self, service_id, version_number, name):
"""Gets a specified condition."""
content = self._fetch("/service/%s/version/%d/condition/%s" % (service_id, version_number, name))
return FastlyCondition(self, content) | 0.025641 |
def t_escaped_LINE_FEED_CHAR(self, t):
r'\x6E' # 'n'
t.lexer.pop_state()
t.value = unichr(0x000a)
return t | 0.014388 |
def board_fen(self, *, promoted: Optional[bool] = False) -> str:
"""
Gets the board FEN.
"""
builder = []
empty = 0
for square in SQUARES_180:
piece = self.piece_at(square)
if not piece:
empty += 1
else:
... | 0.002436 |
def unparse_qs(qs, sort=False, reverse=False):
"""Reverse conversion for parse_qs"""
result = []
items = qs.items()
if sort:
items = sorted(items, key=lambda x: x[0], reverse=reverse)
for keys, values in items:
query_name = quote(keys)
for value in values:
result.... | 0.002584 |
def refresh_plugin(self):
"""Refresh tabwidget."""
nb = None
if self.tabwidget.count():
client = self.tabwidget.currentWidget()
nb = client.notebookwidget
nb.setFocus()
else:
nb = None
self.update_notebook_actions() | 0.00641 |
def get_aggregate_check(self, check, age=None):
"""
Returns the list of aggregates for a given check
"""
data = {}
if age:
data['max_age'] = age
result = self._request('GET', '/aggregates/{}'.format(check),
data=json.dumps(data)... | 0.005714 |
def setNreps(self, nreps):
"""Sets the number of reps before the raster plot resets"""
for plot in self.responsePlots.values():
plot.setNreps(nreps) | 0.011364 |
def mean_squared_logarithmic_error(pred:Tensor, targ:Tensor)->Rank0Tensor:
"Mean squared logarithmic error between `pred` and `targ`."
pred,targ = flatten_check(pred,targ)
return F.mse_loss(torch.log(1 + pred), torch.log(1 + targ)) | 0.024691 |
def plot_diode_fold(dio_cross,bothfeeds=True,feedtype='l',min_samp=-500,max_samp=7000,legend=True,**kwargs):
'''
Plots the calculated average power and time sampling of ON (red) and
OFF (blue) for a noise diode measurement over the observation time series
'''
#Get full stokes data of ND measurement
... | 0.027342 |
def resolve(self, key):
"""
Resolves the requested key to an object instance, raising a KeyError if the key is missing
"""
registration = self._registrations.get(key)
if registration is None:
raise KeyError("Unknown key: '{0}'".format(key))
return registrati... | 0.008798 |
def get_args():
"""
Get and parse arguments.
"""
import argparse
parser = argparse.ArgumentParser(
description="Swift Navigation SBP Example.")
parser.add_argument(
"-s",
"--serial-port",
default=[DEFAULT_SERIAL_PORT],
nargs=1,
help="specify the se... | 0.001172 |
def ignored_corner(
intersection, tangent_s, tangent_t, edge_nodes1, edge_nodes2
):
"""Check if an intersection is an "ignored" corner.
.. note::
This is a helper used only by :func:`classify_intersection`.
An "ignored" corner is one where the surfaces just "kiss" at
the point of intersect... | 0.000475 |
def kill(self, signal=None):
"""
Kill or send a signal to the container.
Args:
signal (str or int): The signal to send. Defaults to ``SIGKILL``
Raises:
:py:class:`docker.errors.APIError`
If the server returns an error.
"""
return... | 0.005479 |
def admin_create_user(self, username, temporary_password='', attr_map=None, **kwargs):
"""
Create a user using admin super privileges.
:param username: User Pool username
:param temporary_password: The temporary password to give the user.
Leave blank to make Cognito generate a te... | 0.003236 |
def plot_irm(fignum, B, M, title):
"""
function to plot IRM backfield curves
Parameters
_________
fignum : matplotlib figure number
B : list or array of field values
M : list or array of magnetizations
title : string title for plot
"""
rpars = {}
Mnorm = []
backfield = 0... | 0.000466 |
def compose(self, *args):
"""
Returns a function that is the composition of a list of functions, each
consuming the return value of the function that follows.
"""
args = list(args)
def composed(*ar, **kwargs):
lastRet = self.obj(*ar, **kwargs)
for... | 0.004619 |
def classify_harmonic(self, partial_labels, use_CMN=True):
'''Harmonic function method for semi-supervised classification,
also known as the Gaussian Mean Fields algorithm.
partial_labels: (n,) array of integer labels, -1 for unlabeled.
use_CMN : when True, apply Class Mass Normalization
From "Sem... | 0.006975 |
def check_child_friendly(self, name):
"""
Check if a module is a container and so can have children
"""
name = name.split()[0]
if name in self.container_modules:
return
root = os.path.dirname(os.path.realpath(__file__))
module_path = os.path.join(root,... | 0.001443 |
def unassign_authorization_from_vault(self, authorization_id, vault_id):
"""Removes an ``Authorization`` from a ``Vault``.
arg: authorization_id (osid.id.Id): the ``Id`` of the
``Authorization``
arg: vault_id (osid.id.Id): the ``Id`` of the ``Vault``
raise: NotFou... | 0.001741 |
def setup(self, phase=None, quantity='', diffusive_conductance='',
hydraulic_conductance='', pressure='', s_scheme='', **kwargs):
r"""
"""
if phase:
self.settings['phase'] = phase.name
if quantity:
self.settings['quantity'] = quantity
if dif... | 0.004317 |
def get_schema(frame, name, keys=None, con=None, dtype=None):
"""
Get the SQL db table schema for the given frame.
Parameters
----------
frame : DataFrame
name : string
name of SQL table
keys : string or sequence, default: None
columns to use a primary key
con: an open S... | 0.00114 |
def getOption(self, name):
"""
Get the current value of the specified option. If the option does not
exist, returns None.
Args:
name: Option name.
Returns:
Value of the option.
Raises:
InvalidArgumet: if the option name is not val... | 0.002625 |
def loss(self, xs, ys):
"""Computes the loss of the network."""
return float(
self.sess.run(
self.cross_entropy, feed_dict={
self.x: xs,
self.y_: ys
})) | 0.007937 |
def get(obj):
"""
Determines file format and picks suitable file types, extensions and MIME types
Takes:
obj (bytes) -> byte sequence (128 bytes are enough)
Returns:
(<class 'fleep.Info'>) -> Class instance
"""
if not isinstance(obj, bytes):
raise TypeError("object typ... | 0.002921 |
def drawBackground(self, painter, rect):
"""When an area of the window is exposed, we just copy out of the
server-side, off-screen pixmap to that area.
"""
if not self.pixmap:
return
x1, y1, x2, y2 = rect.getCoords()
width = x2 - x1 + 1
height = y2 - y... | 0.004193 |
def _ppf(self, q, dist, cache):
"""Point percentile function."""
return -evaluation.evaluate_inverse(dist, 1-q, cache=cache) | 0.014286 |
def HumanReadableStartType(self):
"""Return a human readable string describing the start type value.
Returns:
str: human readable description of the start type value.
"""
if isinstance(self.start_type, py2to3.STRING_TYPES):
return self.start_type
return human_readable_service_enums.SERV... | 0.004988 |
def subdict_match(data,
expr,
delimiter=DEFAULT_TARGET_DELIM,
regex_match=False,
exact_match=False):
'''
Check for a match in a dictionary using a delimiter character to denote
levels of subdicts, and also allowing the delimiter charact... | 0.000176 |
def pykeyword(operation='list', keywordtotest=None):
"""
Check if a keyword exists in the Python keyword dictionary.
:type operation: string
:param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'.
:type keywordtotest: string
:param keywordtotest: The keyw... | 0.001869 |
def append(self, png, **options):
"""Append one frame.
:arg PNG png: Append a :class:`PNG` as a frame.
:arg dict options: The options for :class:`FrameControl`.
"""
if not isinstance(png, PNG):
raise TypeError("Expect an instance of `PNG` but got `{}`".format(png))
control = FrameControl(**options)
... | 0.03397 |
def countByValueAndWindow(self, windowDuration, slideDuration, numPartitions=None):
"""
Return a new DStream in which each RDD contains the count of distinct elements in
RDDs in a sliding window over this DStream.
@param windowDuration: width of the window; must be a multiple of this DS... | 0.009221 |
def convert_list_elements(self):
"""
A sequence of two or more items, which may or may not be ordered.
The <list> element has an optional <label> element and optional <title>
element, followed by one or more <list-item> elements. This is element
is recursive as the <list-item> e... | 0.00636 |
def _startDPDrag(self):
"""Callback for item menu."""
dp = self._dp_menu_on
if dp and dp.archived:
drag = QDrag(self)
mimedata = QMimeData()
mimedata.setUrls([QUrl.fromLocalFile(dp.fullpath)])
drag.setMimeData(mimedata)
drag.exec_(Qt.Co... | 0.005797 |
def cee_map_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
cee_map = ET.SubElement(config, "cee-map", xmlns="urn:brocade.com:mgmt:brocade-cee-map")
name = ET.SubElement(cee_map, "name")
name.text = kwargs.pop('name')
callback = kwa... | 0.007752 |
def propose_live(self):
"""Return a live point/axes to be used by other sampling methods."""
# Copy a random live point.
i = self.rstate.randint(self.nlive)
u = self.live_u[i, :]
# Check for ellipsoid overlap.
ell_idxs = self.mell.within(u)
nidx = len(ell_idxs)
... | 0.001944 |
def _ask_local_config(self):
""" Ask some parameters about the local configuration """
options = {"backend": "local", "local-config": {}}
# Concurrency
while True:
concurrency = self._ask_with_default(
"Maximum concurrency (number of tasks running simultaneou... | 0.004632 |
def ensure():
"""
Makes sure the current working directory is a Git repository.
"""
LOGGER.debug('checking repository')
if not os.path.exists('.git'):
LOGGER.error('This command is meant to be ran in a Git repository.')
sys.exit(-1)
LOGGER.debug('r... | 0.008982 |
def _expected_reads(run_info_file):
"""Parse the number of expected reads from the RunInfo.xml file.
"""
reads = []
if os.path.exists(run_info_file):
tree = ElementTree()
tree.parse(run_info_file)
read_elem = tree.find("Run/Reads")
reads = read_elem.findall("Read")
re... | 0.002985 |
def is_alpha_number(number):
"""Checks if the number is a valid vanity (alpha) number such as 800
MICROSOFT. A valid vanity number will start with at least 3 digits and
will have three or more alpha characters. This does not do region-specific
checks - to work out if this number is actually valid for a ... | 0.001166 |
def haversine(point1, point2, unit='km'):
""" Calculate the great-circle distance between two points on the Earth surface.
:input: two 2-tuples, containing the latitude and longitude of each point
in decimal degrees.
Keyword arguments:
unit -- a string containing the initials of a unit of measurem... | 0.003472 |
def experiments_predictions_create(self, experiment_id, model_id, argument_defs, name, arguments=None, properties=None):
"""Create new model run for given experiment.
Parameters
----------
experiment_id : string
Unique experiment identifier
model_id : string
... | 0.002375 |
def create(cls, session, record, imported=False, auto_reply=False):
"""Create a conversation.
Please note that conversation cannot be created with more than 100
threads, if attempted the API will respond with HTTP 412.
Args:
session (requests.sessions.Session): Authenticate... | 0.001446 |
def p_route(self, p):
"""route : ROUTE route_name route_version route_io route_deprecation NL \
INDENT docsection attrssection DEDENT
| ROUTE route_name route_version route_io route_deprecation NL"""
p[0] = AstRouteDef(self.path, p.lineno(1), p.lexpos(1), p[2], p... | 0.007989 |
def free(self):
"""Remove the lock on the connection if the connection is not active
:raises: ConnectionBusyError
"""
LOGGER.debug('Connection %s freeing', self.id)
if self.handle.isexecuting():
raise ConnectionBusyError(self)
with self._lock:
se... | 0.005128 |
def saltpath():
'''
Return the path of the salt module
'''
# Provides:
# saltpath
salt_path = os.path.abspath(os.path.join(__file__, os.path.pardir))
return {'saltpath': os.path.dirname(salt_path)} | 0.004405 |
def can_download(self, dist, force=False):
"""
Can download if location/file does not exist or if force=True
:param dist:
:param force:
:return: True/False
"""
return not os.path.exists(os.path.join(self.output, dist['basename'])) or force | 0.010169 |
def trimRight(self, amount):
"""
Trim this fastqSequence in-place by removing <amount> nucleotides from
the 3' end (right end).
:param amount: the number of nucleotides to trim from the right-side of
this sequence.
"""
if amount == 0:
return
self.sequenceDat... | 0.005063 |
def update_line(s, bold=False, underline=False, blinking=False, color=None, bgcolor=None):
"""
Overwrites the output of the current line and prints s on the same line
without a new line.
"""
s = get_line(s, bold=bold, underline=underline, blinking=blinking,
color=color, bgcolor=bgc... | 0.005495 |
def _http_error_handler(http_error):
''' Simple error handler for azure.'''
message = str(http_error)
if http_error.respbody is not None:
message += '\n' + http_error.respbody.decode('utf-8-sig')
raise AzureHttpError(message, http_error.status) | 0.003731 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ModelBuildContext for this ModelBuildInstance
:rtype: twilio.rest.autopilot.v1.assistant.model_bu... | 0.008143 |
def readOne(stream, validate=False, transform=True, ignoreUnreadable=False,
allowQP=False):
"""
Return the first component from stream.
"""
return next(readComponents(stream, validate, transform, ignoreUnreadable,
allowQP)) | 0.003546 |
def dt2ts(dt, drop_micro=False):
''' convert datetime objects to timestamp seconds (float) '''
is_true(HAS_DATEUTIL, "`pip install python_dateutil` required")
if is_empty(dt, except_=False):
ts = None
elif isinstance(dt, (int, long, float)): # its a ts already
ts = float(dt)
elif is... | 0.001116 |
def sort(records: Sequence[Record]) -> List[Record]:
"Sort records into a canonical order, suitable for comparison."
return sorted(records, key=_record_key) | 0.006098 |
def get_dev_at_mountpoint(mntpoint):
"""
Retrieves the device mounted at mntpoint, or raises
MountError if none.
"""
results = util.subp(['findmnt', '-o', 'SOURCE', mntpoint])
if results.return_code != 0:
raise MountError('No device mounted at %s' % mntpoint)
... | 0.004396 |
def true_num_genes(model, custom_spont_id=None):
"""Return the number of genes in a model ignoring spontaneously labeled genes.
Args:
model (Model):
custom_spont_id (str): Optional custom spontaneous ID if it does not match the regular expression ``[Ss](_|)0001``
Returns:
int: Numb... | 0.005725 |
def get_lat_long(self, callsign, timestamp=timestamp_now):
""" Returns Latitude and Longitude for a callsign
Args:
callsign (str): Amateur Radio callsign
timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC)
Returns:
dict: Containing Latitude and... | 0.003723 |
def finalize(self):
"""
Finalize the visualization to create an "origin grid" feel instead of
the default matplotlib feel. Set the title, remove spines, and label
the grid with components. This function also adds a legend from the
sizes if required.
"""
# Set the ... | 0.001998 |
def continuous_decode_on_train_data(self):
"""Decode from dataset on new checkpoint."""
for _ in next_checkpoint(self._hparams.model_dir,
self._decode_hparams.decode_timeout_mins):
self.decode(dataset_split=tf.estimator.ModeKeys.TRAIN) | 0.007194 |
def _build_units(indep_units, dep_units, op):
"""Build unit math operations."""
if (not dep_units) and (not indep_units):
return ""
if dep_units and (not indep_units):
return dep_units
if (not dep_units) and indep_units:
return (
remove_extra_delims("1{0}({1})".format... | 0.003831 |
def safe_index(cls, unique_id):
""" Return a valid elastic index generated from unique_id """
index = unique_id
if unique_id:
index = unique_id.replace("/", "_").lower()
return index | 0.00885 |
def end_of_history(event):
"""
Move to the end of the input history, i.e., the line currently being entered.
"""
event.current_buffer.history_forward(count=10**100)
buff = event.current_buffer
buff.go_to_history(len(buff._working_lines) - 1) | 0.007547 |
def show(fig=None, path='_map.html', **kwargs):
"""
Convert a Matplotlib Figure to a Leaflet map. Open in a browser
Parameters
----------
fig : figure, default gcf()
Figure used to convert to map
path : string, default '_map.html'
Filename where output html will be saved
Se... | 0.001795 |
def get_next_grade(self):
"""Gets the next ``Grade`` in this list.
return: (osid.grading.Grade) - the next ``Grade`` in this list.
The ``has_next()`` method should be used to test that a
next ``Grade`` is available before calling this method.
raise: IllegalState... | 0.002497 |
def stdio_mgr(in_str=""):
r"""Subsitute temporary text buffers for `stdio` in a managed context.
Context manager.
Substitutes empty :cls:`~io.StringIO`\ s for
:cls:`sys.stdout` and :cls:`sys.stderr`,
and a :cls:`TeeStdin` for :cls:`sys.stdin` within the managed context.
Upon exiting the conte... | 0.00073 |
def set_session_info(self, info):
'''
:type info: :class:`~kitty.data.data_manager.SessionInfo`
:param info: info to set
'''
if not self.info:
self.info = SessionInfo()
info_d = self.info.as_dict()
ks = []
vs = []
for k,... | 0.003738 |
def package_installed(self,
package,
shutit_pexpect_child=None,
note=None,
loglevel=logging.DEBUG):
"""Returns True if we can be sure the package is installed.
@param package: Package as a string, eg 'wget'.
@param shut... | 0.039474 |
def executeOnController(self, clusterId, script, lang):
"""
Parameters:
- clusterId
- script
- lang
"""
self.send_executeOnController(clusterId, script, lang)
return self.recv_executeOnController() | 0.007576 |
def mapped_read_count(self, force=False):
"""
Counts total reads in a BAM file.
If a file self.bam + '.scale' exists, then just read the first line of
that file that doesn't start with a "#". If such a file doesn't exist,
then it will be created with the number of reads as the ... | 0.001119 |
def _ast_to_code(self, node, **kwargs):
"""Convert an abstract syntax tree to python source code."""
if isinstance(node, OptreeNode):
return self._ast_optree_node_to_code(node, **kwargs)
elif isinstance(node, Identifier):
return self._ast_identifier_to_code(node, **kwargs)
elif isinstance(no... | 0.010381 |
def setup():
""" Returns the attributes of this family if using in a probabilistic model
Notes
----------
- scale notes whether family has a variance parameter (sigma)
- shape notes whether family has a tail thickness parameter (nu)
- skewness notes whether family has a ... | 0.006557 |
def user_timeline(self, delegate, user=None, params={}, extra_args=None):
"""Get the most recent updates for a user.
If no user is specified, the statuses for the authenticating user are
returned.
See search for example of how results are returned."""
if user:
param... | 0.004228 |
def trigger(self, events, *args, **kwargs):
"""
Fires the given *events* (string or list of strings). All callbacks
associated with these *events* will be called and if their respective
objects have a *times* value set it will be used to determine when to
remove the associated c... | 0.001619 |
def _gen_csv_data(self, f, dialect):
"""
Yields (column data, row number) tuples from the given csv file
handler, using the given Dialect named tuple instance. Depends on
self.ipa_col being correctly set.
Helper for the gen_ipa_data method.
"""
reader = self._get_csv_reader(f, dialect)
for line in rea... | 0.031683 |
def infer_x(self, y, sigma=None, k=None, **kwargs):
"""Infer probable x from input y
@param y the desired output for infered x.
@param k how many neighbors to consider for the average
this value override the class provided one on a per
method call basis.
... | 0.011392 |
def get_service_state(self, service_id: str) -> str:
"""Get the state of the service.
Only the manager nodes can retrieve service state
Args:
service_id (str): Service id
Returns:
str, state of the service
"""
# Get service
service = se... | 0.003802 |
def remove_pool_snapshot(service, pool_name, snapshot_name):
"""
Remove a snapshot from a RADOS pool in ceph.
:param service: six.string_types. The Ceph user name to run the command under
:param pool_name: six.string_types
:param snapshot_name: six.string_types
:return: None. Can raise CalledPr... | 0.005964 |
def _data(self):
"""A deep copy NDArray of the data array associated with the BaseSparseNDArray.
This function blocks. Do not use it in performance critical code.
"""
self.wait_to_read()
hdl = NDArrayHandle()
check_call(_LIB.MXNDArrayGetDataNDArray(self.handle, ctypes.by... | 0.011173 |
def easy_train_and_evaluate(hyper_params, Model=None, create_loss=None,
training_data=None, validation_data=None,
inline_plotting=False, session_config=None, log_suffix=None,
continue_training=False, continue_with_specific_checkpointpa... | 0.004344 |
def gg_ipython(plot, data, width=IPYTHON_IMAGE_SIZE, height=None,
*args, **kwargs):
"""Render pygg in an IPython notebook
Allows one to say things like:
import pygg
p = pygg.ggplot('diamonds', pygg.aes(x='carat', y='price', color='clarity'))
p += pygg.geom_point(alpha=0.5, size = 2)... | 0.001094 |
def verify_raw_data(raw_data, pubkey_hex, sigb64):
"""
Verify the signature over a string, given the public key
and base64-encode signature.
Return True on success.
Return False on error.
"""
if not isinstance(raw_data, (str, unicode)):
raise ValueError("data is not a string")
r... | 0.00232 |
def __on_message(self, client, userdata, msg):
# pylint: disable=W0613
"""
A message has been received from a server
:param client: Client that received the message
:param userdata: User data (unused)
:param msg: A MQTTMessage bean
"""
# Notify the caller... | 0.005566 |
def create(server_context, domain_definition, container_path=None):
# type: (ServerContext, dict, str) -> Domain
"""
Create a domain
:param server_context: A LabKey server context. See utils.create_server_context.
:param domain_definition: A domain definition.
:param container_path: labkey conta... | 0.005222 |
def set_motion_detect(self, enable):
"""Set motion detection."""
if enable:
return api.request_motion_detection_enable(self.sync.blink,
self.network_id,
self.camera_id)
retur... | 0.003906 |
def softplus_inverse(x, name=None):
"""Computes the inverse softplus, i.e., x = softplus_inverse(softplus(x)).
Mathematically this op is equivalent to:
```none
softplus_inverse = log(exp(x) - 1.)
```
Args:
x: `Tensor`. Non-negative (not enforced), floating-point.
name: A name for the operation (o... | 0.00199 |
def file_matches_regexps(filename, patterns):
"""Does this filename match any of the regular expressions?"""
return any(re.match(pat, filename) for pat in patterns) | 0.005814 |
def email(self, client_id, email, send='link', auth_params=None):
"""Start flow sending an email.
Given the user email address, it will send an email with:
- A link (default, send:"link"). You can then authenticate with
this user opening the link and he will be automatically logg... | 0.001504 |
def encode_utf8(s, f):
"""UTF-8 encodes string `s` to file-like object `f` according to
the MQTT Version 3.1.1 specification in section 1.5.3.
The maximum length for the encoded string is 2**16-1 (65535) bytes.
An assertion error will result if the encoded string is longer.
Parameters
--------... | 0.001099 |
def match(self, methods, request_method):
"""Check for a method match.
:param methods: A method or tuple of methods to match against.
:param request_method: The method to check for a match.
:returns: An empty :class:`dict` in the case of a match, or ``None``
if there is no m... | 0.002933 |
def build_lst(a, b):
""" function to be folded over a list (with initial value `None`)
produces one of:
1. `None`
2. A single value
3. A list of all values
"""
if type(a) is list:
return a + [b]
elif a:
return [a, b]
else:
return b | 0.003247 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.