text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def socket_close(self):
"""Close our socket."""
if self.sock != NC.INVALID_SOCKET:
self.sock.close()
self.sock = NC.INVALID_SOCKET | 0.012048 |
def unpack(self, fmt, length=1):
"""
Unpack the stream contents according to the specified format in `fmt`.
For more information about the `fmt` format see: https://docs.python.org/3/library/struct.html
Args:
fmt (str): format string.
length (int): amount of byte... | 0.004777 |
def login(self, username, password, email, url, config_path):
"""
If username and password are provided, authenticate with the registry.
Otherwise, check the config file for existing authentication data.
"""
if username and password:
try:
self.client.l... | 0.004748 |
def get_params(degrees, translate, scale_ranges, shears, img_size):
"""Get parameters for affine transformation
Returns:
sequence: params to be passed to the affine transformation
"""
angle = random.uniform(degrees[0], degrees[1])
if translate is not None:
... | 0.002181 |
def log_error(self, error, message, detail=None, strip=4):
"Add an error message and optional user message to the error list"
if message:
msg = message + ": " + error
else:
msg = error
tb = traceback.format_stack()
if sys.version_info >= (3, 0):
... | 0.003937 |
def optimize(self):
"""
Do an optimization.
"""
jmodel = callJavaFunc(self.value.optimize)
from bigdl.nn.layer import Layer
return Layer.of(jmodel) | 0.010256 |
def simxGetInMessageInfo(clientID, infoType):
'''
Please have a look at the function description/documentation in the V-REP user manual
'''
info = ct.c_int()
return c_GetInMessageInfo(clientID, infoType, ct.byref(info)), info.value | 0.007968 |
def write_yum_repo(content, filename='ceph.repo'):
"""add yum repo file in /etc/yum.repos.d/"""
repo_path = os.path.join('/etc/yum.repos.d', filename)
if not isinstance(content, str):
content = content.decode('utf-8')
write_file(repo_path, content.encode('utf-8')) | 0.003472 |
def est_entropy(self):
r"""
Estimates the entropy of the current particle distribution
as :math:`-\sum_i w_i \log w_i` where :math:`\{w_i\}`
is the set of particles with nonzero weight.
"""
nz_weights = self.particle_weights[self.particle_weights > 0]
return -np.s... | 0.005634 |
def memory(self):
"""Memory information in bytes
Example:
>>> print(ctx.device(0).memory())
{'total': 4238016512L, 'used': 434831360L, 'free': 3803185152L}
Returns:
total/used/free memory in bytes
"""
class GpuMemoryInfo(Structure):
... | 0.004286 |
def _update_ref(self, ref, delete=False):
"""Update a reference."""
cmd = ['git', 'update-ref']
if delete:
cmd.extend(['-d', ref.refname])
action = 'deleted'
else:
cmd.extend([ref.refname, ref.hash])
action = 'updated to %s' % ref.hash
... | 0.004071 |
def params(self):
"""Get the params of response data from the API.
Returns:
- d (dict): Dictionary mapping of all configuration values
"""
payload = self.payload
d = {}
for i, p in enumerate(payload["currentConfiguration"]):
type_name = p["typeNam... | 0.003813 |
def identify_denonavr_receivers():
"""
Identify DenonAVR using SSDP and SCPD queries.
Returns a list of dictionaries which includes all discovered Denon AVR
devices with keys "host", "modelName", "friendlyName", "presentationURL".
"""
# Sending SSDP broadcast message to get devices
devices ... | 0.001493 |
def solc_arguments(libraries=None, combined='bin,abi',
optimize=True, extra_args=None):
""" Build the arguments to call the solc binary. """
args = [
'--combined-json', combined,
]
def str_of(address):
"""cast address to string. py2/3 compatability. """
try:
... | 0.002982 |
def write_predictions(all_examples, all_features, all_results, n_best_size,
max_answer_length, do_lower_case, output_prediction_file,
output_nbest_file, output_null_log_odds_file, verbose_logging,
version_2_with_negative, null_score_diff_threshold):
... | 0.002503 |
def summarize(reintegrate=True, dist_tolerance=3, qranges=None,
samples=None, raw=False, late_radavg=True, graph_ncols=3,
std_multiplier=3, graph_extension='png',
graph_dpi=80, correlmatrix_colormap='coolwarm',
image_colormap='viridis', correlmatrix_logarithmic=Tr... | 0.002888 |
def node_has_namespace(node: BaseEntity, namespace: str) -> bool:
"""Pass for nodes that have the given namespace."""
ns = node.get(NAMESPACE)
return ns is not None and ns == namespace | 0.005102 |
def resolve_election_tie(self, candidates):
"""
call callback to resolve a tie between candidates
"""
sorted_candidate_ids = list(sorted(candidates, key=self.candidate_order_fn))
return sorted_candidate_ids[self.election_tie_cb(candidates)] | 0.010714 |
def checksum_creation_action(target, source, env):
"""Create a linker command file for patching an application checksum into a firmware image"""
# Important Notes:
# There are apparently many ways to calculate a CRC-32 checksum, we use the following options
# Initial seed value prepended to the input: ... | 0.005248 |
def reboot(self, timeout=None, wait_polling_interval=None):
"""Reboot the device, waiting for the adb connection to become stable.
:param timeout: Maximum time to wait for reboot.
:param wait_polling_interval: Interval at which to poll for device readiness.
"""
if timeout is Non... | 0.007788 |
def ipv6_acl_ipv6_access_list_standard_seq_action(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list")
ipv6 = ET.SubElement(ipv6_acl, "ipv6")
access_li... | 0.003601 |
def handle_message(self, msg, host):
"""Processes messages that have been delivered from the listener.
Args:
msg (string): The raw packet data delivered from the listener. This
data will be unserialized and then processed based on the packet's
method.
host (t... | 0.004149 |
def update_ssl_termination(self, loadbalancer, securePort=None, enabled=None,
secureTrafficOnly=None):
"""
Updates existing SSL termination information for the load balancer
without affecting the existing certificates/keys.
"""
ssl_info = self.get_ssl_termination(load... | 0.004367 |
def set_cells(self, cells_location):
"""
Set self.cells to function :cells in file pathname.py
:param cells_location: cells location, format 'pathname.py:cells'
:return:
"""
if ':' in cells_location:
pathname, func_name = cells_location.split(':')
els... | 0.003273 |
def exit(status=0):
"""
Terminate the program with the given status code.
"""
if status == 0:
lab.io.printf(lab.io.Colours.GREEN, "Done.")
else:
lab.io.printf(lab.io.Colours.RED, "Error {0}".format(status))
sys.exit(status) | 0.003802 |
def _get_default_value(self, value):
"""
Format a value so that it can be used in "default" clauses.
"""
if isinstance(value, QueryExpression):
return value
if isinstance(value, bool):
return "'%s'" % int(value)
return "'%s'" % value | 0.006515 |
def _handle_complete_reply(self, rep):
""" Handle replies for tab completion.
"""
self.log.debug("complete: %s", rep.get('content', ''))
cursor = self._get_cursor()
info = self._request_info.get('complete')
if info and info.id == rep['parent_header']['msg_id'] and \
... | 0.003623 |
def on_pre_execution(**kwargs):
"""
Calls callbacks before execution.
Note that any exception from callback will be logged but won't be propagated.
:param kwargs:
:return: None
"""
logging.debug("Calling callbacks: %s", __pre_exec_callbacks)
for cb in __pre_exec_callbacks:
try:
... | 0.004464 |
def send_magic_packet(*macs, **kwargs):
"""
Wake up computers having any of the given mac addresses.
Wake on lan must be enabled on the host device.
Args:
macs (str): One or more macaddresses of machines to wake.
Keyword Args:
ip_address (str): the ip address of the host to send t... | 0.00094 |
def insert(self, task, args=[], kwargs={}, delay_seconds=0):
"""
Insert a task into an existing queue.
"""
body = {
"payload": task.payload(),
"queueName": self._queue_name,
"groupByTag": True,
"tag": task.__class__.__name__
}
def cloud_insertion():
self._api.inser... | 0.005025 |
def json(self):
"""Load response body as json.
:raises: :class:`ContentDecodingError`
"""
try:
return json.loads(self.text)
except Exception as e:
raise ContentDecodingError(e) | 0.008299 |
def ConnectNoSSL(host='localhost', port=443, user='root', pwd='',
service="hostd", adapter="SOAP", namespace=None, path="/sdk",
version=None, keyFile=None, certFile=None, thumbprint=None,
b64token=None, mechanism='userpass'):
"""
Provides a standard method for co... | 0.007241 |
def _process_loaded_object(self, path):
"""process the :paramref:`path`.
:param str path: the path to load an svg from
"""
file_name = os.path.basename(path)
name = os.path.splitext(file_name)[0]
with open(path) as file:
string = file.read()
self.... | 0.005435 |
def csv_column_cleaner(rows):
"""
clean csv columns parsed omitting empty/dirty rows.
"""
# check columns if there was empty columns
result = [[] for x in range(0, len(rows))]
for i_index in range(0, len(rows[0])):
partial_values = []
for x_row in rows:
partial_val... | 0.001425 |
def get_tiles(self):
"""Get all TileCoordinates contained in the region"""
for x, y in griditer(self.root_tile.x, self.root_tile.y, ncol=self.tiles_per_row):
yield TileCoordinate(self.root_tile.zoom, x, y) | 0.012876 |
def make_related_protein_fasta_from_dataframe(self, input_df):
'''
DataFrame should have
'''
dirname = './group_fastas'
if not os.path.exists(dirname):
os.makedirs(dirname)
unique_hit_queries = set(input_df.hit_query)
for hq in unique_hit_queries... | 0.005308 |
def receive(
self,
request: RequestType,
user: UserType = None,
sender_key_fetcher: Callable[[str], str] = None,
skip_author_verification: bool = False) -> Tuple[str, dict]:
"""
Receive a request.
For testing purposes, `skip_author_ver... | 0.003927 |
def list_huisnummers_by_perceel(self, perceel, sort=1):
'''
List all `huisnummers` on a `Pereel`.
Generally there will only be one, but multiples are possible.
:param perceel: The :class:`Perceel` for which the \
`huisnummers` are wanted.
:rtype: A :class: `list` of... | 0.003019 |
def forward(node, analysis):
"""Perform a given analysis on all functions within an AST."""
if not isinstance(analysis, Forward):
raise TypeError('not a valid forward analysis object')
for succ in gast.walk(node):
if isinstance(succ, gast.FunctionDef):
cfg_obj = CFG.build_cfg(succ)
analysis.vi... | 0.019886 |
def nearest_int(x):
"""
Return nearest long integer to x
"""
if x == 0:
return np.int64(0)
elif x > 0:
return np.int64(x + 0.5)
else:
return np.int64(x - 0.5) | 0.004854 |
def closest_point(triangles, points):
"""
Return the closest point on the surface of each triangle for a
list of corresponding points.
Implements the method from "Real Time Collision Detection" and
use the same variable names as "ClosestPtPointTriangle" to avoid
being any more confusing.
... | 0.000253 |
def _FindInFileEntry(self, file_entry, find_specs, search_depth):
"""Searches for matching file entries within the file entry.
Args:
file_entry (FileEntry): file entry.
find_specs (list[FindSpec]): find specifications.
search_depth (int): number of location path segments to compare.
Yiel... | 0.011268 |
def map(self, func, axis=(0,), value_shape=None, dtype=None, with_keys=False):
"""
Apply a function across an axis.
Array will be aligned so that the desired set of axes
are in the keys, which may incur a swap.
Parameters
----------
func : function
F... | 0.003331 |
def _compute_distance(self, rup, dists, C):
"""
Compute the distance function, equation (5).
"""
rval = np.sqrt(dists.repi ** 2 + C['h'] ** 2)
return C['c1'] * np.log10(rval) | 0.009346 |
def subtract_params(param_list_left, param_list_right):
"""Subtract two lists of parameters
:param param_list_left: list of numpy arrays
:param param_list_right: list of numpy arrays
:return: list of numpy arrays
"""
res = []
for x, y in zip(param_list_left, param_list_right):
res.a... | 0.002882 |
def draw_clusters(data, clusters, noise = [], marker_descr = '.', hide_axes = False, axes = None, display_result = True):
"""!
@brief Displays clusters for data in 2D or 3D.
@param[in] data (list): Points that are described by coordinates represented.
@param[in] clusters (list): Clusters that ... | 0.026925 |
def transfer_matrix(self, superoperator):
"""
Compute the transfer matrix :math:`R_{jk} = \tr[P_j sop(P_k)]`.
:param qutip.Qobj superoperator: The superoperator to transform.
:return: The transfer matrix in sparse form.
:rtype: scipy.sparse.csr_matrix
"""
if not ... | 0.007339 |
def connect(self, protocolFactory):
"""Starts a process and connect a protocol to it.
"""
deferred = self._startProcess()
deferred.addCallback(self._connectRelay, protocolFactory)
deferred.addCallback(self._startRelay)
return deferred | 0.007092 |
def justify(texts, max_len, mode='right'):
"""
Perform ljust, center, rjust against string or list-like
"""
if mode == 'left':
return [x.ljust(max_len) for x in texts]
elif mode == 'center':
return [x.center(max_len) for x in texts]
else:
return [x.rjust(max_len) for x in... | 0.003058 |
def _update_linecache(self, path, data):
"""
The Python 2.4 linecache module, used to fetch source code for
tracebacks and :func:`inspect.getsource`, does not support PEP-302,
meaning it needs extra help to for Mitogen-loaded modules. Directly
populate its cache if a loaded modul... | 0.003419 |
def load_model_class(repo, content_type):
"""
Return a model class for a content type in a repository.
:param Repo repo:
The git repository.
:param str content_type:
The content type to list
:returns: class
"""
schema = get_schema(repo, content_type).to_json()
return des... | 0.00271 |
def generate_version_file(self, schema_filename, binding_filename):
"""Given a DataONE schema, generates a file that contains version information
about the schema."""
version_filename = binding_filename + '_version.txt'
version_path = os.path.join(self.binding_dir, version_filename)
... | 0.00607 |
def manage_initial_host_status_brok(self, b):
"""Prepare the known hosts cache"""
host_name = b.data['host_name']
logger.debug("got initial host status: %s", host_name)
self.hosts_cache[host_name] = {
'realm_name':
sanitize_name(b.data.get('realm_name', b.dat... | 0.004098 |
def sum_by_n(d, w, n):
"""A utility function to summarize a data array into n values
after weighting the array with another weight array w
Parameters
----------
d : array
(t, 1), numerical values
w : array
(t, 1), numerical values for weigh... | 0.002657 |
def create_module_rst_file(module_name):
"""Function for creating content in each .rst file for a module.
:param module_name: name of the module.
:type module_name: str
:returns: A content for auto module.
:rtype: str
"""
return_text = 'Module: ' + module_name
dash = '=' * len(return... | 0.002053 |
def fetch(self, max=None):
"""
Fetch all collection by pages of `max` items.
Parameters
----------
max : int, None (optional)
The number of item per page. If None, retrieve all collection.
Returns
-------
self Collection, the fetched collec... | 0.003231 |
def set_attr(obj, path, value):
"""
SAME AS object.__setattr__(), BUT USES DOT-DELIMITED path
RETURN OLD VALUE
"""
try:
return _set_attr(obj, split_field(path), value)
except Exception as e:
Log = get_logger()
if PATH_NOT_FOUND in e:
Log.warning(PATH_NOT_FOUND... | 0.002347 |
def Record(self, value, fields=None):
"""Records the given observation in a distribution."""
key = _FieldsToKey(fields)
metric_value = self._metric_values.get(key)
if metric_value is None:
metric_value = self._DefaultValue()
self._metric_values[key] = metric_value
metric_value.Record(val... | 0.009288 |
def to_bytes(value):
"""Get a byte array representing the value"""
if isinstance(value, unicode):
return value.encode('utf8')
elif not isinstance(value, str):
return str(value)
return value | 0.004525 |
def _find_local_signals(cls, signals, namespace):
"""Add name info to every "local" (present in the body of this class)
signal and add it to the mapping. Also complete signal
initialization as member of the class by injecting its name.
"""
from . import Signal
signaller... | 0.003122 |
def _median(imageObjectList, paramDict):
"""Create a median image from the list of image Objects
that has been given.
"""
newmasks = paramDict['median_newmasks']
comb_type = paramDict['combine_type'].lower()
nlow = paramDict['combine_nlow']
nhigh = paramDict['combine_nhigh']
grow = pa... | 0.000076 |
def aliased_as(self, name):
"""
Create an alias of this stream.
Returns an alias of this stream with name `name`.
When invocation of an SPL operator requires an
:py:class:`~streamsx.spl.op.Expression` against
an input port this can be used to ensure expression
ma... | 0.003839 |
def _new_stream(self, idx):
'''Randomly select and create a new stream.
Parameters
----------
idx : int, [0:n_streams - 1]
The stream index to replace
'''
# Don't activate the stream if the weight is 0 or None
if self.stream_weights_[idx]:
... | 0.003984 |
def iteration(self, node_status=True):
"""
Execute a single model iteration
:return: Iteration_id, Incremental node status (dictionary node->status)
"""
# One iteration changes the opinion of N agent pairs using the following procedure:
# - first one agent is selected
... | 0.006266 |
def qualified_note_rate(pianoroll, threshold=2):
"""Return the ratio of the number of the qualified notes (notes longer than
`threshold` (in time step)) to the total number of notes in a pianoroll."""
_validate_pianoroll(pianoroll)
if np.issubdtype(pianoroll.dtype, np.bool_):
pianoroll = pianoro... | 0.00157 |
def format_results(self, results):
"""
Format the ldap results object into somthing that is reasonable
"""
if not results:
return None
userdn = results[0][0]
userobj = results[0][1]
userobj['dn'] = userdn
keymap = self.config.get('KEY_MAP')
... | 0.013865 |
def twopercent(station_code):
"""Two percent high design temperature for a location.
Degrees in Celcius
Args:
station_code (str): Weather Station Code
Returns:
float degrees Celcius
"""
# (DB=>MWB) 2%, MaxDB=
temp = None
try:
fin = open('%s/%s' % (env.WEATHER_D... | 0.000816 |
def overrepresented_sequences (self):
"""Sum the percentages of overrepresented sequences and display them in a bar plot"""
data = dict()
for s_name in self.fastqc_data:
data[s_name] = dict()
try:
max_pcnt = max( [ float(d['percentage']) for d in self.f... | 0.012661 |
def tuple_to_schema(tuple_):
"""Convert a tuple representing an XML data structure into a schema tuple
that can be used in the ``.schema`` property of a sub-class of
PREMISElement.
"""
schema = []
for element in tuple_:
if isinstance(element, (tuple, list)):
try:
... | 0.001541 |
def colors(lang="en"):
"""This resource returns all dyes in the game, including localized names
and their color component information.
:param lang: The language to query the names for.
The response is a dictionary where color ids are mapped to an dictionary
containing the following properties:
... | 0.000771 |
def get_changelog(project_dir=os.curdir, bugtracker_url='', rpm_format=False):
"""
Retrieves the changelog, from the CHANGELOG file (if in a package) or
generates it from the git history. Optionally in rpm-compatible format.
:param project_dir: Path to the git repo of the project.
:type project_dir... | 0.000899 |
def main(command, argument, argument2, paths_to_mutate, backup, runner, tests_dir,
test_time_multiplier, test_time_base,
swallow_output, use_coverage, dict_synonyms, cache_only, version,
suspicious_policy, untested_policy, pre_mutation, post_mutation,
use_patch_file):
"""return e... | 0.002069 |
def live_scores(self, live_scores):
"""Store output of live scores to a CSV file"""
headers = ['League', 'Home Team Name', 'Home Team Goals',
'Away Team Goals', 'Away Team Name']
result = [headers]
result.extend([game['league'], game['homeTeamName'],
... | 0.004115 |
def new_inner_member(self, name=None, params=None):
"""Create a CheckModulation object and add it to items
:param name: CheckModulation name
:type name: str
:param params: parameters to init CheckModulation
:type params: dict
:return: None
TODO: Remove this defau... | 0.004491 |
def command(func_or_args=None):
"""Decorator to tell Skal that the method/function is a command.
"""
def decorator(f):
f.__args__ = args
return f
if type(func_or_args) == type(decorator):
args = {}
return decorator(func_or_args)
args = func_or_args
return decorat... | 0.003106 |
def data_manipulation_sh(network):
""" Adds missing components to run calculations with SH scenarios.
Parameters
----------
network : :class:`pypsa.Network
Overall container of PyPSA
"""
from shapely.geometry import Point, LineString, MultiLineString
from geoalchemy2.shap... | 0.001494 |
def EnumerateFilesystemsFromClient(args):
"""List all local filesystems mounted on this system."""
del args # Unused.
for fs_struct in client_utils_osx.GetFileSystems():
yield rdf_client_fs.Filesystem(
device=fs_struct.f_mntfromname,
mount_point=fs_struct.f_mntonname,
type=fs_struct.f... | 0.014231 |
def _check_items(items):
'''
Check:
- that the list of items is iterable and finite.
- that the list is not empty
'''
num_items = 0
# Check that the list is iterable and finite
try:
num_items = len(items)
except:
raise TypeError("The item list ({}) is not a finite i... | 0.006383 |
def add_user(self, group, username):
"""
Add a user to the specified LDAP group.
Args:
group: Name of group to update
username: Username of user to add
Raises:
ldap_tools.exceptions.InvalidResult:
Results of the query were invalid. T... | 0.002725 |
def release_node(self, node):
"""
release a single redis node
"""
# use the lua script to release the lock in a safe way
try:
node._release_script(keys=[self.resource], args=[self.lock_key])
except (redis.exceptions.ConnectionError, redis.exceptions.TimeoutErr... | 0.008798 |
def factorize(self):
""" Factorize s.t. CUR = data
Updated Values
--------------
.C : updated values for C.
.U : updated values for U.
.R : updated values for R.
"""
[prow, pcol] = self.sample_probability()
self._rid = self.s... | 0.004474 |
def delete_existing_policy(self, scaling_policy, server_group):
"""Given a scaling_policy and server_group, deletes the existing scaling_policy.
Scaling policies need to be deleted instead of upserted for consistency.
Args:
scaling_policy (json): the scaling_policy json from Spinnak... | 0.005634 |
def listing(self):
"Return a list of filename entries currently in the archive"
return ['.'.join([f,ext]) if ext else f for (f,ext) in self._files.keys()] | 0.029412 |
def shape(self):
"""Returns the shape of the data."""
# TODO cache
first = self.first().shape
shape = self._rdd.map(lambda x: x.shape[0]).sum()
return (shape,) + first[1:] | 0.009479 |
def mass_2d(self, r, rho0, Ra, Rs):
"""
mass enclosed projected 2d sphere of radius r
:param r:
:param rho0:
:param Ra:
:param Rs:
:return:
"""
Ra, Rs = self._sort_ra_rs(Ra, Rs)
sigma0 = self.rho2sigma(rho0, Ra, Rs)
m_2d = 2 * np.pi... | 0.006834 |
def debye_temperature(self, volume):
"""
Calculates the debye temperature.
Eq(6) in doi.org/10.1016/j.comphy.2003.12.001. Thanks to Joey.
Eq(6) above is equivalent to Eq(3) in doi.org/10.1103/PhysRevB.37.790
which does not consider anharmonic effects. Eq(20) in the same paper
... | 0.003605 |
def list_all_currencies(cls, **kwargs):
"""List Currencies
Return a list of Currencies
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_currencies(async=True)
>>> result = thre... | 0.002307 |
def files(self, absolute=False):
"""Returns an expanded list of all valid paths that were passed in."""
_paths = []
for arg in self.all:
for path in _expand_path(arg):
if os.path.exists(path):
if absolute:
_paths.append(os... | 0.004619 |
def revoke_token(self, token, token_type_hint, request, *args, **kwargs):
"""Revoke an access or refresh token.
"""
if token_type_hint:
tok = self._tokengetter(**{token_type_hint: token})
else:
tok = self._tokengetter(access_token=token)
if not tok:
... | 0.003091 |
def show_lbaas_l7rule(self, l7rule, l7policy, **_params):
"""Fetches information of a certain L7 policy's rule."""
return self.get(self.lbaas_l7rule_path % (l7policy, l7rule),
params=_params) | 0.008658 |
def add_pipers(self, pipers, *args, **kwargs):
"""
Adds a sequence of ``Pipers`` instances to the ``Dagger`` in the
specified order. Takes optional arguments for ``Dagger.add_piper``.
Arguments:
- pipers(sequence of valid ``add_piper`` arguments) Sequence of ... | 0.014311 |
def _flush_message_buffer(self):
"""
Loops through the transport message_buffer until there are no messages
left in the queue. Each response is assigned to the Request object
based on the message_id which are then available in
self.outstanding_requests
"""
while T... | 0.000838 |
async def get_capability_report(self):
"""
This method retrieves the Firmata capability report.
Refer to http://firmata.org/wiki/Protocol#Capability_Query
The command format is: {"method":"get_capability_report","params":["null"]}
:returns: {"method": "capability_report_reply"... | 0.008523 |
def _generate_citation_dict(graph: BELGraph) -> Mapping[str, Mapping[Tuple[BaseEntity, BaseEntity], str]]:
"""Prepare a citation data dictionary from a graph.
:return: A dictionary of dictionaries {citation type: {(source, target): citation reference}
"""
results = defaultdict(lambda: defaultdict(set))... | 0.007299 |
def to_short_time_string(self) -> str:
""" Return the iso time string only """
hour = self.time.hour
minute = self.time.minute
return f"{hour:02}:{minute:02}" | 0.010526 |
async def postback_send(msg: BaseMessage, platform: Platform) -> Response:
"""
Injects the POST body into the FSM as a Postback message.
"""
await platform.inject_message(msg)
return json_response({
'status': 'ok',
}) | 0.003984 |
def _defrag_list(lst, defrag, missfrag):
"""Internal usage only. Part of the _defrag_logic"""
p = lst[0]
lastp = lst[-1]
if p.frag > 0 or lastp.flags.MF: # first or last fragment missing
missfrag.append(lst)
return
p = p.copy()
if conf.padding_layer in p:
del(p[conf.padd... | 0.000752 |
def search(self, pattern="*", raw=True, search_raw=True,
output=False):
"""Search the database using unix glob-style matching (wildcards
* and ?).
Parameters
----------
pattern : str
The wildcarded pattern to matc... | 0.004673 |
def _get_current_context(self):
"""Returns the current ZipkinAttrs and generates new ones if needed.
:returns: (report_root_timestamp, zipkin_attrs)
:rtype: (bool, ZipkinAttrs)
"""
# This check is technically not necessary since only root spans will have
# sample_rate, z... | 0.002646 |
def long_to_bytes(n, blocksize=0):
"""Convert an integer to a byte string.
In Python 3.2+, use the native method instead::
>>> n.to_bytes(blocksize, 'big')
For instance::
>>> n = 80
>>> n.to_bytes(2, 'big')
b'\x00P'
If the optional :data:`blocksize` is provided and g... | 0.00082 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.