text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
async def process_message(self, message, wait=True):
"""Process a message to see if it wakes any waiters.
This will check waiters registered to see if they match the given
message. If so, they are awoken and passed the message. All matching
waiters will be woken.
This method ... | 0.002949 |
async def send_audio(self, url, user, options=None):
"""
send audio message
:param url: link to the audio file
:param user: target user
:param options:
:return:
"""
return await self.chat.send_audio(url, user, options) | 0.007067 |
def pack(self, data):
"""See :func:`~bitstruct.pack_dict()`.
"""
try:
return self.pack_any(data)
except KeyError as e:
raise Error('{} not found in data dictionary'.format(str(e))) | 0.008403 |
def derivative(self, x):
"""Derivative of the product space operator.
Parameters
----------
x : `domain` element
The point to take the derivative in
Returns
-------
adjoint : linear`ProductSpaceOperator`
The derivative
Examples
... | 0.000897 |
def make_color_tuple(color):
"""
turn something like "#000000" into 0,0,0
or "#FFFFFF into "255,255,255"
"""
R = color[1:3]
G = color[3:5]
B = color[5:7]
R = int(R, 16)
G = int(G, 16)
B = int(B, 16)
return R, G, B | 0.003861 |
def cnmf(S, rank, niter=500, hull=False):
"""(Convex) Non-Negative Matrix Factorization.
Parameters
----------
S: np.array(p, N)
Features matrix. p row features and N column observations.
rank: int
Rank of decomposition
niter: int
Number of iterations to be used
Ret... | 0.001389 |
def crop(self, data):
'''Crop a data dictionary down to its common time
Parameters
----------
data : dict
As produced by pumpp.transform
Returns
-------
data_cropped : dict
Like `data` but with all time-like axes truncated to the
... | 0.002976 |
def _get_stack_frame(stacklevel):
"""
utility functions to get a stackframe, skipping internal frames.
"""
stacklevel = stacklevel + 1
if stacklevel <= 1 or _is_internal_frame(sys._getframe(1)):
# If frame is too small to care or if the warning originated in
# internal code, then do ... | 0.001497 |
def plot_pseudodepths(configs, nr_electrodes, spacing=1, grid=None,
ctypes=None, dd_merge=False, **kwargs):
"""Plot pseudodepths for the measurements. If grid is given, then the
actual electrode positions are used, and the parameter 'spacing' is
ignored'
Parameters
----------
... | 0.000192 |
def manage_view(request, semester, profile=None):
"""
View all members' preferences. This view also includes forms to create an
entire semester's worth of weekly workshifts.
"""
page_name = "Manage Workshift"
pools = WorkshiftPool.objects.filter(semester=semester)
full_management = utils.can... | 0.00067 |
def random_rademacher(shape, dtype=tf.float32, seed=None, name=None):
"""Generates `Tensor` consisting of `-1` or `+1`, chosen uniformly at random.
For more details, see [Rademacher distribution](
https://en.wikipedia.org/wiki/Rademacher_distribution).
Args:
shape: Vector-shaped, `int` `Tensor` representi... | 0.003046 |
def aes_cbc_no_padding_decrypt(key, data, iv):
"""
Decrypts AES ciphertext in CBC mode using a 128, 192 or 256 bit key and no
padding.
:param key:
The encryption key - a byte string either 16, 24 or 32 bytes long
:param data:
The ciphertext - a byte string
:param iv:
T... | 0.002593 |
def run(self):
"""The thread's main activity. Call start() instead."""
self._create_socket()
self._running = True
self._beating = True
while self._running:
if self._pause:
# just sleep, and skip the rest of the loop
time.sleep... | 0.004313 |
def cancelMktData(self, contract: Contract):
"""
Unsubscribe from realtime streaming tick data.
Args:
contract: The exact contract object that was used to
subscribe with.
"""
ticker = self.ticker(contract)
reqId = self.wrapper.endTicker(ticker... | 0.003861 |
def findElementsWithId(node, elems=None):
"""
Returns all elements with id attributes
"""
if elems is None:
elems = {}
id = node.getAttribute('id')
if id != '':
elems[id] = node
if node.hasChildNodes():
for child in node.childNodes:
# from http://www.w3.or... | 0.001808 |
def free_data(self):
"""
clear buffer
:return: bool
"""
command = const.CMD_FREE_DATA
cmd_response = self.__send_command(command)
if cmd_response.get('status'):
return True
else:
raise ZKErrorResponse("can't free data") | 0.006494 |
def find_all(s, sub, start=0, end=0, limit=-1, reverse=False):
"""
Find all indexes of sub in s.
:param s: the string to search
:param sub: the string to search for
:param start: the index in s at which to begin the search (same as in ''.find)
:param end: the index in s at which to stop searchi... | 0.001686 |
def validateOpfJsonValue(value, opfJsonSchemaFilename):
"""
Validate a python object against an OPF json schema file
:param value: target python object to validate (typically a dictionary)
:param opfJsonSchemaFilename: (string) OPF json schema filename containing the
json schema object. (e.g., opfTask... | 0.010914 |
def _get_marker_output(self, asset_quantities, metadata):
"""
Creates a marker output.
:param list[int] asset_quantities: The asset quantity list.
:param bytes metadata: The metadata contained in the output.
:return: An object representing the marker output.
:rtype: Tran... | 0.005338 |
def iter_annotation_values(graph, annotation: str) -> Iterable[str]:
"""Iterate over all of the values for an annotation used in the graph.
:param pybel.BELGraph graph: A BEL graph
:param str annotation: The annotation to grab
"""
return (
value
for _, _, data in graph.edges(data=Tr... | 0.002331 |
def update_password(self, password: str) -> bool:
"""
修改登入密碼
"""
try:
# 操作所需資訊
payload = {
'pass': password,
'submit': 'sumit'
}
# 修改密碼
response = self.__session.post(
self.__url +... | 0.004967 |
def get_input_files(dirname, *ext):
"""Returns files in passed directory, filtered by extension.
- dirname - path to input directory
- *ext - list of arguments describing permitted file extensions
"""
filelist = [f for f in os.listdir(dirname) if
os.path.splitext(f)[-1] in ext]
... | 0.002695 |
def insert_strain_option_group_multi_ifo(parser):
"""
Adds the options used to call the pycbc.strain.from_cli function to an
optparser as an OptionGroup. This should be used if you
want to use these options in your code.
Parameters
-----------
parser : object
OptionParser instance.
... | 0.012428 |
def getDetailInfo(self, CorpNum, MgtKeyType, MgtKey):
""" 상세정보 확인
args
CorpNum : 회원 사업자 번호
MgtKeyType : 관리번호 유형 one of ['SELL','BUY','TRUSTEE']
MgtKey : 파트너 관리번호
return
처리결과. consist of code and message
raise
... | 0.005848 |
def get_gradebook_columns_by_genus_type(self, gradebook_column_genus_type):
"""Gets a ``GradebookColumnList`` corresponding to the given gradebook column genus ``Type`` which does not include gradebook columns of genus types derived from the specified ``Type``.
In plenary mode, the returned list contai... | 0.002438 |
def setup_experiment(debug=True, verbose=False, app=None):
"""Check the app and, if it's compatible with Wallace, freeze its state."""
print_header()
# Verify that the package is usable.
log("Verifying that directory is compatible with Wallace...")
if not verify_package(verbose=verbose):
ra... | 0.000487 |
def builtin(cls, name):
"""
Generate a default legend.
Args:
name (str): The name of the legend you want. Not case sensitive.
'nsdoe': Nova Scotia Dept. of Energy
'canstrat': Canstrat
'nagmdm__6_2': USGS N. Am. Geol. Map Data Model ... | 0.001959 |
def sum_dice(spec):
""" Replace the dice roll arrays from roll_dice in place with summations of
the rolls. """
if spec[0] == 'c': return spec[1]
elif spec[0] == 'r': return sum(spec[1])
elif spec[0] == 'x':
return [sum_dice(r) for r in spec[1]]
elif spec[0] in ops:
return (spec[0... | 0.009592 |
def ToTimedelta(self):
"""Converts Duration to timedelta."""
return timedelta(
seconds=self.seconds, microseconds=_RoundTowardZero(
self.nanos, _NANOS_PER_MICROSECOND)) | 0.005102 |
def on_success(self, fn, *args, **kwargs):
"""
Call the given callback if or when the connected deferred succeeds.
"""
self._callbacks.append((fn, args, kwargs))
result = self._resulted_in
if result is not _NOTHING_YET:
self._succeed(result=result) | 0.006431 |
def nodes_map(self):
"""
Build a mapping from node type to a list of nodes.
A typed mapping helps avoid polymorphism at non-persistent layers.
"""
dct = dict()
for node in self.nodes.values():
cls = next(base for base in getmro(node.__class__) if "__tablenam... | 0.00625 |
def stop(self):
"""
Stop the Runner if it's running.
Called as a classmethod, stop the running instance if any.
"""
if self.is_running:
log.info('Stopping')
self.is_running = False
self.__class__._INSTANCE = None
try:
... | 0.005758 |
def add_creg(self, creg):
"""Add all wires in a classical register."""
if not isinstance(creg, ClassicalRegister):
raise DAGCircuitError("not a ClassicalRegister instance.")
if creg.name in self.cregs:
raise DAGCircuitError("duplicate register %s" % creg.name)
sel... | 0.004785 |
def getChatAdministrators(self, chat_id):
""" See: https://core.telegram.org/bots/api#getchatadministrators """
p = _strip(locals())
return self._api_request('getChatAdministrators', _rectify(p)) | 0.009132 |
def directive_SPACE(self, label, params):
"""
label SPACE num
Allocate space on the stack. `num` is the number of bytes to allocate
"""
# TODO allow equations
params = params.strip()
try:
self.convert_to_integer(params)
except ValueError:
... | 0.003378 |
def p_attr_field(self, p):
"""attr_field : ID EQ primitive NL
| ID EQ tag_ref NL"""
if p[3] is NullToken:
p[0] = AstAttrField(
self.path, p.lineno(1), p.lexpos(1), p[1], None)
else:
p[0] = AstAttrField(
self.path, p.li... | 0.005666 |
def angle(vec1, vec2):
"""Returns the angle between two vectors"""
dot_vec = dot(vec1, vec2)
mag1 = vec1.length()
mag2 = vec2.length()
result = dot_vec / (mag1 * mag2)
return math.acos(result) | 0.00463 |
def keras_tuples(stream, inputs=None, outputs=None):
"""Reformat data objects as keras-compatible tuples.
For more detail: https://keras.io/models/model/#fit
Parameters
----------
stream : iterable
Stream of data objects.
inputs : string or iterable of strings, None
Keys to us... | 0.000481 |
def _validate_parse_dates_arg(parse_dates):
"""
Check whether or not the 'parse_dates' parameter
is a non-boolean scalar. Raises a ValueError if
that is the case.
"""
msg = ("Only booleans, lists, and "
"dictionaries are accepted "
"for the 'parse_dates' parameter")
if... | 0.001736 |
def _renameClasses(classes, prefix):
"""
Replace class IDs with nice strings.
"""
renameMap = {}
for classID, glyphList in classes.items():
if len(glyphList) == 0:
groupName = "%s_empty_lu.%d_st.%d_cl.%d" % (prefix, classID[0], classID[1], classID[2])
elif len(glyphList) ... | 0.003731 |
def _to_original_callable(obj):
"""
Find the Python object that contains the source code of the object.
This is useful to find the place in the source code (file and line
number) where a docstring is defined. It does not currently work for
all cases, but it should help find some... | 0.002301 |
def QueueMessages(self, messages):
"""Push messages to the input queue."""
# Push all the messages to our input queue
for message in messages:
self._in_queue.put(message, block=True) | 0.01 |
def read(self, n):
"""Read n bytes."""
self.bitcount = self.bits = 0
return self.input.read(n) | 0.016949 |
def import_image_tags(self, name, tags, repository, insecure=False):
"""Import image tags from specified container repository.
:param name: str, name of ImageStream object
:param tags: iterable, tags to be imported
:param repository: str, remote location of container image
... | 0.002291 |
def metasound(text: str, length: int = 4) -> str:
"""
Thai MetaSound
:param str text: Thai text
:param int length: preferred length of the MetaSound (default is 4)
:return: MetaSound for the text
**Example**::
>>> from pythainlp.metasound import metasound
>>> metasound("ลัก")
... | 0.000614 |
def infer_map(value: Mapping[GenericAny, GenericAny]) -> Map:
"""Infer the :class:`~ibis.expr.datatypes.Map` type of `value`."""
if not value:
return Map(null, null)
return Map(
highest_precedence(map(infer, value.keys())),
highest_precedence(map(infer, value.values())),
) | 0.003195 |
def republish(self, hash, count=None, sources=None, destinations=None):
"""
Rebroadcast blocks starting at **hash** to the network
:param hash: Hash of block to start rebroadcasting from
:type hash: str
:param count: Max number of blocks to rebroadcast
:type count: int
... | 0.003232 |
def set_circulating(self, param):
"""
Sets whether to circulate - in effect whether the heater is on.
:param param: The mode to set, must be 0 or 1.
:return: Empty string.
"""
if param == 0:
self.is_circulating = param
self.circulate_commanded = F... | 0.004435 |
def FindByName(cls, name):
"""Find a specific installed auth provider by name."""
reg = ComponentRegistry()
for _, entry in reg.load_extensions('iotile.auth_provider', name_filter=name):
return entry | 0.012712 |
def write_question(self, question):
"""Writes a question to the packet"""
self.write_name(question.name)
self.write_short(question.type)
self.write_short(question.clazz) | 0.00995 |
def unassign_objective_from_objective_bank(self, objective_id, objective_bank_id):
"""Removes an ``Objective`` from an ``ObjectiveBank``.
arg: objective_id (osid.id.Id): the ``Id`` of the
``Objective``
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
... | 0.004068 |
def query(
self,
filters=None,
order_column="",
order_direction="",
page=None,
page_size=None,
select_columns=None,
):
"""
QUERY
:param filters:
dict with filters {<col_name>:<value,...}
:param order_... | 0.002387 |
def _prepare_env(self, kwargs):
"""Returns a modifed copy of kwargs['env'], and a copy of kwargs with 'env' removed.
If there is no 'env' field in the kwargs, os.environ.copy() is used.
env['PATH'] is set/modified to contain the Node distribution's bin directory at the front.
:param kwargs: The origin... | 0.006421 |
def register_target_artifact_metadata(self, target: str, metadata: dict):
"""Register the artifact metadata dictionary for a built target."""
with self.context_lock:
self.artifacts_metadata[target.name] = metadata | 0.008299 |
def get_random(self, n, l=None):
""" Return n random sequences from this Fasta object """
random_f = Fasta()
if l:
ids = self.ids[:]
random.shuffle(ids)
i = 0
while (i < n) and (len(ids) > 0):
seq_id = ids.pop()
if (... | 0.004561 |
def removeContour(self, contour):
"""
Remove ``contour`` from the glyph.
>>> glyph.removeContour(contour)
``contour`` may be a :ref:`BaseContour` or an :ref:`type-int`
representing a contour index.
"""
if isinstance(contour, int):
index = contour... | 0.00349 |
def is_prime(n):
"""
is_prime returns True if N is a prime number, False otherwise
Parameters:
Input, integer N, the number to be checked.
Output, boolean value, True or False
"""
if n != int(n) or n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 ... | 0.00318 |
def set_options_from_dict(self, data_dict, filename=None):
"""Load options from a dictionary.
:param dict data_dict: Dictionary with the options to load.
:param str filename: If provided, assume that non-absolute
paths provided are in reference to the file.
"""
if fi... | 0.001182 |
def nl_cb_set(cb, type_, kind, func, arg):
"""Set up a callback. Updates `cb` in place.
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/handlers.c#L293
Positional arguments:
cb -- nl_cb class instance.
type_ -- callback to modify (integer).
kind -- kind of implementation (integer).
f... | 0.002601 |
def load(self, **kwargs):
"""Loads a given resource
Loads a given resource provided a 'name' and an optional 'slot'
parameter. The 'slot' parameter is not a required load parameter
because it is provided as an optional way of constructing the
correct 'name' of the vCMP resource.... | 0.004065 |
def help_cli_basic(self):
""" Help for Workbench CLI Basics """
help = '%sWorkbench: Getting started...' % (color.Yellow)
help += '\n%sLoad in a sample:' % (color.Green)
help += '\n\t%s> load_sample /path/to/file' % (color.LightBlue)
help += '\n\n%sNotice the prompt now shows t... | 0.013064 |
def label_const(self, const:Any=0, label_cls:Callable=None, **kwargs)->'LabelList':
"Label every item with `const`."
return self.label_from_func(func=lambda o: const, label_cls=label_cls, **kwargs) | 0.051643 |
def remove(self, index):
"""Removes specified item from the model.
:index: Should have a form "<itemref>.<subitemref...>" (e.g. "1.1").
:index: Item's index.
"""
data = self.data
index = self._split(index)
for j, c in enumerate(index):
i = int(c) - ... | 0.003623 |
def query_package_version_metrics(self, package_version_id_query, feed_id, package_id, project=None):
"""QueryPackageVersionMetrics.
[Preview API]
:param :class:`<PackageVersionMetricsQuery> <azure.devops.v5_1.feed.models.PackageVersionMetricsQuery>` package_version_id_query:
:param str ... | 0.007496 |
def start_scan(self, scan_id, targets, parallel=1):
""" Handle N parallel scans if 'parallel' is greater than 1. """
os.setsid()
multiscan_proc = []
logger.info("%s: Scan started.", scan_id)
target_list = targets
if target_list is None or not target_list:
rai... | 0.002706 |
def get_interfaces(self, socket_connection=None):
"""Returns the a list of Interface objects the service implements."""
if not socket_connection:
socket_connection = self.open_connection()
close_socket = True
else:
close_socket = False
# noinspection ... | 0.005199 |
def delete_module(modname):
"""
Delete module and sub-modules from `sys.module`
"""
try:
_ = sys.modules[modname]
except KeyError:
raise ValueError("Module not found in sys.modules: '{}'".format(modname))
for module in list(sys.modules.keys()):
if module and module.start... | 0.005391 |
def dist_euclidean(src, tar, qval=2, alphabet=None):
"""Return the normalized Euclidean distance between two strings.
This is a wrapper for :py:meth:`Euclidean.dist`.
Parameters
----------
src : str
Source string (or QGrams/Counter objects) for comparison
tar : str
Target strin... | 0.001067 |
def flatten(value):
"""value can be any nesting of tuples, arrays, dicts.
returns 1D numpy array and an unflatten function."""
if isinstance(value, np.ndarray):
def unflatten(vector):
return np.reshape(vector, value.shape)
return np.ravel(value), unflatten
elif isinstance... | 0.000451 |
def set_n_gram(self, value):
''' setter '''
if isinstance(value, Ngram):
self.__n_gram = value
else:
raise TypeError("The type of n_gram must be Ngram.") | 0.00995 |
def _round_to(dt, hour, minute, second):
"""
Route the given datetime to the latest time with the hour, minute, second
before it.
"""
new_dt = dt.replace(hour=hour, minute=minute, second=second)
if new_dt == dt:
return new_dt
elif new_dt < dt:
before = new_dt
after = ... | 0.001704 |
def __make_request_method(self, teststep_dict, entry_json):
""" parse HAR entry request method, and make teststep method.
"""
method = entry_json["request"].get("method")
if not method:
logging.exception("method missed in request.")
sys.exit(1)
teststep_d... | 0.005666 |
def iter_comments(self, number=-1):
"""Iterate over the comments on this issue.
:param int number: (optional), number of comments to iterate over
:returns: iterator of
:class:`IssueComment <github3.issues.comment.IssueComment>`\ s
"""
url = self._build_url('comments'... | 0.007519 |
def _getRegisteredExecutable(exeName):
"""Windows allow application paths to be registered in the registry."""
registered = None
if sys.platform.startswith('win'):
if os.path.splitext(exeName)[1].lower() != '.exe':
exeName += '.exe'
import _winreg
try:
key = "... | 0.002894 |
def created_slices(self, user_id=None):
"""List of slices created by this user"""
if not user_id:
user_id = g.user.id
Slice = models.Slice # noqa
qry = (
db.session.query(Slice)
.filter(
sqla.or_(
Slice.created_by_f... | 0.002558 |
def sync_firmware(self):
"""Syncs the emulator's firmware version and the DLL's firmware.
This method is useful for ensuring that the firmware running on the
J-Link matches the firmware supported by the DLL.
Args:
self (JLink): the ``JLink`` instance
Returns:
... | 0.001103 |
def read_coordinates(self, where=None, start=None, stop=None, **kwargs):
"""select coordinates (row numbers) from a table; return the
coordinates object
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
... | 0.002278 |
def django_object_from_row(row, model, field_names=None, ignore_fields=('id', 'pk'), ignore_related=True, strip=True, ignore_errors=True, verbosity=0):
"""Construct Django model instance from values provided in a python dict or Mapping
Args:
row (list or dict): Data (values of any type) to be assigned to... | 0.010888 |
def get_media_detail_output_interface_interface_name(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
output = ET.SubElement(get_media_detail, "output")
interface ... | 0.002821 |
def enum(description, **kwargs) -> typing.Type:
"""Create a :class:`~doctor.types.Enum` type.
:param description: A description of the type.
:param kwargs: Can include any attribute defined in
:class:`~doctor.types.Enum`
"""
kwargs['description'] = description
return type('Enum', (Enum,... | 0.00303 |
def loop(self):
"""Lazy event loop initialization"""
if not self._loop:
self._loop = IOLoop.current()
return self._loop
return self._loop | 0.010811 |
def openstack_exception(func):
'''
Openstack exceptions decorator
'''
async def wrap(*args, **kwargs):
try:
return await func(*args, **kwargs)
except Exception as e:
logging.error(e)
raise IaasException
r... | 0.006061 |
def invalidate(*tables_or_models, **kwargs):
"""
Clears what was cached by django-cachalot implying one or more SQL tables
or models from ``tables_or_models``.
If ``tables_or_models`` is not specified, all tables found in the database
(including those outside Django) are invalidated.
If ``cache... | 0.000541 |
def watch_run_status(server, project, run, apikey, timeout=None, update_period=1):
"""
Monitor a linkage run and yield status updates. Will immediately yield an update and then
only yield further updates when the status object changes. If a timeout is provided and the
run hasn't entered a terminal state... | 0.003906 |
def _set_conf(self):
"""
Set configuration parameters from the Conf object into the detector
object.
Time values are converted to samples, and amplitude values are in mV.
"""
self.rr_init = 60 * self.fs / self.conf.hr_init
self.rr_max = 60 * self.fs / self.conf.h... | 0.002478 |
def zip_strip_namespace(zip_src, namespace, logger=None):
""" Given a namespace, strips 'namespace__' from all files and filenames
in the zip
"""
namespace_prefix = "{}__".format(namespace)
lightning_namespace = "{}:".format(namespace)
zip_dest = zipfile.ZipFile(io.BytesIO(), "w", zipfile.ZI... | 0.001606 |
def add_context(
self,
name,
cluster_name=None,
user_name=None,
namespace_name=None,
**attrs
):
"""Add a context to config."""
if self.context_exists(name):
raise KubeConfError("context with the given name already exists.")
con... | 0.00612 |
def equal_set(self, a, b):
"See if a and b have the same elements"
if len(a) != len(b):
return 0
if a == b:
return 1
return self.subset(a, b) and self.subset(b, a) | 0.009132 |
def create_api_vrf(self):
"""Get an instance of Api Vrf services facade."""
return ApiVrf(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | 0.009217 |
def order_by(self, field_path, direction=ASCENDING):
"""Modify the query to add an order clause on a specific field.
See :meth:`~.firestore_v1beta1.client.Client.field_path` for
more information on **field paths**.
Successive :meth:`~.firestore_v1beta1.query.Query.order_by` calls
... | 0.001191 |
def append_system_paths(self):
"""Append system paths to $PATH."""
from rez.shells import Shell, create_shell
sh = self.interpreter if isinstance(self.interpreter, Shell) \
else create_shell()
paths = sh.get_syspaths()
paths_str = os.pathsep.join(paths)
self.... | 0.00578 |
def save(self, path, overWrite):
"""
save OptimMethod
:param path path
:param overWrite whether to overwrite
"""
method=self.value
return callBigDlFunc(self.bigdl_type, "saveOptimMethod", method, path, overWrite) | 0.014652 |
def decode_wireformat_uuid(rawguid):
"""Decode a wire format UUID
It handles the rather particular scheme where half is little endian
and half is big endian. It returns a string like dmidecode would output.
"""
if isinstance(rawguid, list):
rawguid = bytearray(rawguid)
lebytes = struct... | 0.001751 |
def _leu16(ins):
''' Compares & pops top 2 operands out of the stack, and checks
if the 1st operand <= 2nd operand (top of the stack).
Pushes 0 if False, 1 if True.
16 bit unsigned version
'''
output = _16bit_oper(ins.quad[2], ins.quad[3], reversed=True)
output.append('or a')
... | 0.001961 |
def list_aliases():
'''
Return the aliases found in the aliases file in this format::
{'alias': 'target'}
CLI Example:
.. code-block:: bash
salt '*' aliases.list_aliases
'''
ret = dict((alias, target) for alias, target, comment in __parse_aliases() if alias)
return ret | 0.006309 |
def load_glossary(file_path: str, read_json=False) -> List[str]:
"""
A glossary is a text file, one entry per line.
Args:
file_path (str): path to a text file containing a glossary.
read_json (bool): set True if the glossary is in json format
Returns: List of the... | 0.003484 |
def best_score(self, seqs, scan_rc=True, normalize=False):
"""
give the score of the best match of each motif in each sequence
returns an iterator of lists containing floats
"""
self.set_threshold(threshold=0.0)
if normalize and len(self.meanstd) == 0:
self.se... | 0.004093 |
def generateRandomSDR(numSDR, numDims, numActiveInputBits, seed=42):
"""
Generate a set of random SDR's
@param numSDR:
@param nDim:
@param numActiveInputBits:
"""
randomSDRs = np.zeros((numSDR, numDims), dtype=uintType)
indices = np.array(range(numDims))
np.random.seed(seed)
for i in range(numSDR):
... | 0.014675 |
def request(self, method: str, path: str, content: Optional[Union[dict, bytes, str]] = None,
timestamp: Optional[int] = None, external_url: Optional[str] = None,
headers: Optional[Dict[str, str]] = None,
query_params: Optional[Dict[str, Any]] = None,
api_p... | 0.004882 |
def _user_path(self, subdir, basename=''):
'''
Gets the full path to the 'subdir/basename' file in the user binwalk directory.
@subdir - Subdirectory inside the user binwalk directory.
@basename - File name inside the subdirectory.
Returns the full path to the 'subdir/basenam... | 0.007055 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.