text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def _checkblk(name):
'''
Check if the blk exists and return its fstype if ok
'''
blk = __salt__['cmd.run']('blkid -o value -s TYPE {0}'.format(name),
ignore_retcode=True)
return '' if not blk else blk | 0.003984 |
def ignore(self, argument_dest, **kwargs):
""" Register an argument with type knack.arguments.ignore_type (hidden/ignored)
:param argument_dest: The destination argument to apply the ignore type to
:type argument_dest: str
"""
self._check_stale()
if not self._applicable(... | 0.01 |
def read_archive(self,header,prepend=None):
""" Extract a copy of WCS keywords from an open file header,
if they have already been created and remember the prefix
used for those keywords. Otherwise, setup the current WCS
keywords as the archive values.
"""
# S... | 0.003605 |
def _ls_print_listing(dir_: str, recursive: bool, all_: bool, long: bool) -> List[Tuple[str, dict, TrainingTrace]]:
"""
Print names of the train dirs contained in the given dir.
:param dir_: dir to be listed
:param recursive: walk recursively in sub-directories, stop at train dirs (--recursive option)
... | 0.005351 |
def uniq(args):
"""
%prog uniq fastqfile
Retain only first instance of duplicate reads. Duplicate is defined as
having the same read name.
"""
p = OptionParser(uniq.__doc__)
p.set_outfile()
opts, args = p.parse_args(args)
if len(args) != 1:
sys.exit(not p.print_help())
... | 0.002561 |
def inhull(self, xyz, pore, tol=1e-7):
r"""
Tests whether points lie within a convex hull or not.
Computes a tesselation of the hull works out the normals of the facets.
Then tests whether dot(x.normals) < dot(a.normals) where a is the the
first vertex of the facets
"""
... | 0.000815 |
def get_value(self, sid, dt, field):
"""
Parameters
----------
sid : int
The asset identifier.
day : datetime64-like
Midnight of the day for which data is requested.
colname : string
The price field. e.g. ('open', 'high', 'low', 'close'... | 0.002112 |
def change_function_style(self, stripped_record, func_decl_style):
"""Converts a function definition syntax from the 'func_decl_style' to the one that has been
set in self.apply_function_style and returns the string with the converted syntax."""
if func_decl_style is None:
return ... | 0.005517 |
def fire_lifecycle_event(self, new_state):
"""
Called when instance's state changes.
:param new_state: (Lifecycle State), the new state of the instance.
"""
if new_state == LIFECYCLE_STATE_SHUTTING_DOWN:
self.is_live = False
self.state = new_state
se... | 0.007776 |
def get_os_file_names(files):
"""
returns file names
:param files: list of strings and\\or :class:`file_configuration_t`
instances.
:type files: list
"""
fnames = []
for f in files:
if utils.is_str(f):
fnames.app... | 0.002933 |
def ParseFileObject(self, parser_mediator, file_object):
"""Parses an ASL file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): file-like object.
Raises:
Unabl... | 0.007051 |
def send_media(self, path, chatid, caption):
"""
converts the file to base64 and sends it using the sendImage function of wapi.js
:param path: file path
:param chatid: chatId to be sent
:param caption:
:return:
"""
imgBase64 = self.convert_to_base64(pa... | 0.008909 |
def create_parser():
"""Creat a commandline parser for epubcheck
:return Argumentparser:
"""
parser = ArgumentParser(
prog='epubcheck',
description="EpubCheck v%s - Validate your ebooks" % __version__
)
# Arguments
parser.add_argument(
'path',
nargs='?',
... | 0.000981 |
def delete_external_account(resource_root, name):
"""
Delete an external account by name
@param resource_root: The root Resource object.
@param name: Account name
@return: The deleted ApiExternalAccount object
"""
return call(resource_root.delete,
EXTERNAL_ACCOUNT_FETCH_PATH % ("delete", name,),
... | 0.014327 |
def convert_coco_stuff_mat(data_dir, out_dir):
"""Convert to png and save json with path. This currently only contains
the segmentation labels for objects+stuff in cocostuff - if we need to
combine with other labels from original COCO that will be a TODO."""
sets = ['train', 'val']
categories = []
... | 0.0011 |
def louvain(adjacency_matrix):
"""
Performs community embedding using the LOUVAIN method.
Introduced in: Blondel, V. D., Guillaume, J. L., Lambiotte, R., & Lefebvre, E. (2008).
Fast unfolding of communities in large networks.
Journal of Statistical Mechanics: Theory an... | 0.004467 |
def parse_shebang_from_file(path):
"""Parse the shebang given a file path."""
if not os.path.lexists(path):
raise ValueError('{} does not exist.'.format(path))
if not os.access(path, os.X_OK):
return ()
with open(path, 'rb') as f:
return parse_shebang(f) | 0.00339 |
def author_notes(soup):
"""
Find the fn tags included in author-notes
"""
author_notes = []
author_notes_section = raw_parser.author_notes(soup)
if author_notes_section:
fn_nodes = raw_parser.fn(author_notes_section)
for tag in fn_nodes:
if 'fn-type' in tag.attrs:
... | 0.002198 |
def add_health_monitor(self, type, delay=10, timeout=10,
attemptsBeforeDeactivation=3, path="/", statusRegex=None,
bodyRegex=None, hostHeader=None):
"""
Adds a health monitor to the load balancer. If a monitor already
exists, it is updated with the supplied settings.
... | 0.011254 |
def ExamineEvent(self, mediator, event):
"""Analyzes an event.
Args:
mediator (AnalysisMediator): mediates interactions between
analysis plugins and other components, such as storage and dfvfs.
event (EventObject): event to examine.
"""
# This event requires an URL attribute.
... | 0.010957 |
def parse_config(self, config_file):
"""
Given a configuration file, read in and interpret the results
:param config_file:
:return:
"""
with open(config_file, 'r') as f:
config = json.load(f)
self.params = config
if self.params['proxy']['prox... | 0.004237 |
def to_dict(cls, network=None, phases=[], element=['pore', 'throat'],
interleave=True, flatten=True, categorize_by=[]):
r"""
Returns a single dictionary object containing data from the given
OpenPNM objects, with the keys organized differently depending on
optional argume... | 0.000461 |
def _convert_to_namecheap(self, record):
""" converts from lexicon format record to namecheap format record,
suitable to sending through the api to namecheap"""
name = record['name']
if name.endswith('.'):
name = name[:-1]
short_name = name[:name.find(self.domain) -... | 0.003484 |
def restart_kernel(self):
"""Restart kernel of current client."""
client = self.get_current_client()
if client is not None:
self.switch_to_plugin()
client.restart_kernel() | 0.008929 |
def _getStringStream(self, filename, prefer='unicode'):
"""Gets a string representation of the requested filename.
Checks for both ASCII and Unicode representations and returns
a value if possible. If there are both ASCII and Unicode
versions, then the parameter /prefer/ specifies which... | 0.002053 |
def set_implementation(impl):
"""
Sets the implementation of this module
Parameters
----------
impl : str
One of ["python", "c"]
"""
global __impl__
if impl.lower() == 'python':
__impl__ = __IMPL_PYTHON__
elif impl.lower() == 'c':
__impl__ = __IMPL_C__
e... | 0.004098 |
def generateSimpleSequences(nCoinc=10, seqLength=[5,6,7], nSeq=100):
"""
Generate a set of simple sequences. The elements of the sequences will be
integers from 0 to 'nCoinc'-1. The length of each sequence will be
randomly chosen from the 'seqLength' list.
Parameters:
--------------------------------------... | 0.012951 |
def _are_nearby_parallel_boxes(self, b1, b2):
"Are two boxes nearby, parallel, and similar in width?"
if not self._are_aligned_angles(b1.angle, b2.angle):
return False
# Otherwise pick the smaller angle and see whether the two boxes are close according to the "up" direction wrt that ... | 0.008576 |
def describe_pipelines(pipeline_ids, region=None, key=None, keyid=None, profile=None):
'''
Retrieve metadata about one or more pipelines.
CLI example:
.. code-block:: bash
salt myminion boto_datapipeline.describe_pipelines ['my_pipeline_id']
'''
client = _get_client(region, key, keyid... | 0.005348 |
def load_client_ca(self, cafile):
"""
Load the trusted certificates that will be sent to the client. Does
not actually imply any of the certificates are trusted; that must be
configured separately.
:param bytes cafile: The path to a certificates file in PEM format.
:ret... | 0.003552 |
def drop(self, format_p, action):
"""Informs the source that a drop event occurred for a pending
drag and drop operation.
in format_p of type str
The mime type the data must be in.
in action of type :class:`DnDAction`
The action to use.
return progress ... | 0.005447 |
def restful(self, path, params):
"""
Allows you to make a direct REST call if you know the path
Arguments:
:param path: The path of the request. Example: sobjects/User/ABC123/password'
:param params: dict of parameters to pass to the path
"""
url = self._get_norm... | 0.005944 |
def post_db_dump(self):
"""
Runs methods services that have requested to be run before each
database dump.
"""
for service in self.genv.services:
service = service.strip().upper()
funcs = common.service_post_db_dumpers.get(service)
if funcs:
... | 0.006494 |
def clean_old_jobs():
'''
Called in the master's event loop every loop_interval. Archives and/or
deletes the events and job details from the database.
:return:
'''
if __opts__.get('keep_jobs', False) and int(__opts__.get('keep_jobs', 0)) > 0:
try:
with _get_serv() as cur:
... | 0.0044 |
def clear(self):
"""
Clears all the data in the object, keeping original data
"""
self.__modified_data__ = {}
self.__deleted_fields__ = [field for field in self.__original_data__.keys()] | 0.013274 |
def linewidth(self, linewidth=None):
"""Returns or sets (if a value is provided) the width of the series'
line.
:param Number linewidth: If given, the series' linewidth will be set to\
this.
:rtype: ``Number``"""
if linewidth is None:
return self._linewidth
... | 0.005587 |
def delayed_close(self):
"""Delayed close - won't close immediately, but on next ioloop tick."""
self.state = CLOSING
self.server.io_loop.add_callback(self.close) | 0.010753 |
def parse(cls, fptr, offset, length):
"""Parse component definition box.
Parameters
----------
fptr : file
Open file object.
offset : int
Start position of box in bytes.
length : int
Length of the box in bytes.
Returns
... | 0.001826 |
def _operator_generator(index, conj):
"""
Internal method to generate the appropriate operator
"""
pterm = PauliTerm('I', 0, 1.0)
Zstring = PauliTerm('I', 0, 1.0)
for j in range(index):
Zstring = Zstring*PauliTerm('Z', j, 1.0)
pterm1 = Zstring*PauliTe... | 0.003802 |
def _validate_metadata(metadata_props):
'''
Validate metadata properties and possibly show warnings or throw exceptions.
:param metadata_props: A dictionary of metadata properties, with property names and values (see :func:`~onnxmltools.utils.metadata_props.add_metadata_props` for examples)
'''
if ... | 0.005563 |
def _get_passwordkey(self):
"""This method just hashes self.password."""
sha = SHA256.new()
sha.update(self.password.encode('utf-8'))
return sha.digest() | 0.010753 |
def _int_size_to_type(size):
"""
Return the Catalyst datatype from the size of integers.
"""
if size <= 8:
return ByteType
if size <= 16:
return ShortType
if size <= 32:
return IntegerType
if size <= 64:
return LongType | 0.003584 |
def convert_gemm(params, w_name, scope_name, inputs, layers, weights, names):
"""
Convert Linear.
Args:
params: dictionary with layer parameters
w_name: name prefix in state_dict
scope_name: pytorch scope name
inputs: pytorch node inputs
layers: dictionary with keras... | 0.00163 |
def getPostStates(self):
'''
Slightly extends the base version of this method by recalculating aLvlNow to account for the
consumer's (potential) misperception about their productivity level.
Parameters
----------
None
Returns
-------
None
... | 0.008772 |
def getImageForExpression(self, retina_name, body, image_scalar=2, plot_shape="circle", image_encoding="base64/png", sparsity=1.0):
"""Get images for expressions
Args:
retina_name, str: The retina name (required)
body, ExpressionOperation: The JSON encoded expression to be evalua... | 0.005364 |
def discoverLangs(self,domain="*"):
"""
Generates a list of languages based on files found on disk.
The optional ``domain`` argument may specify a domain to use when checking
for files. By default, all domains are checked.
This internally uses the :py:mod:`glob`... | 0.012833 |
def getRootJobs(self):
"""
:return: The roots of the connected component of jobs that contains this job. \
A root is a job with no predecessors.
:rtype : set of toil.job.Job instances
"""
roots = set()
visited = set()
#Function to get the roots of a job
... | 0.010922 |
def _from_binary_attrlist_e(cls, binary_stream):
"""See base class."""
'''
Attribute type - 4
Length of a particular entry - 2
Length of the name - 1 (in characters)
Offset to name - 1
Starting VCN - 8
File reference - 8
Attribute ID - 1
Name (unic... | 0.005562 |
def buffer(self):
'''
Get a copy of the buffer that this is reading from. Returns a
buffer object
'''
return buffer(self._input, self._start_pos,
(self._end_pos - self._start_pos)) | 0.008264 |
def add_server(self, name, prefer=False):
"""Add or update an NTP server entry to the node config
Args:
name (string): The IP address or FQDN of the NTP server.
prefer (bool): Sets the NTP server entry as preferred if True.
Returns:
True if the operation suc... | 0.0032 |
def apply_noise(data, noise):
"""
Applies noise to a sparse matrix. Noise can be an integer between 0 and
100, indicating the percentage of ones in the original input to move, or
a float in [0, 1), indicating the same thing.
The input matrix is modified in-place, and nothing is returned.
This operation doe... | 0.018519 |
def _get_config(**api_opts):
'''
Return configuration
user passed api_opts override salt config.get vars
'''
config = {
'api_sslverify': True,
'api_url': 'https://INFOBLOX/wapi/v1.2.1',
'api_user': '',
'api_key': '',
}
if '__salt__' in globals():
confi... | 0.001786 |
def hilbertrot(n, x, y, rx, ry):
"""Rotates and flips a quadrant appropriately for the Hilbert scan
generator. See https://en.wikipedia.org/wiki/Hilbert_curve.
"""
if ry == 0:
if rx == 1:
x = n - 1 - x
y = n - 1 - y
return y, x
return x, y | 0.003344 |
def snip_string(string, max_len=20, snip_string='...', snip_point=0.5):
"""
Snips a string so that it is no longer than max_len, replacing deleted
characters with the snip_string.
The snip is done at snip_point, which is a fraction between 0 and 1,
indicating relatively where along the string to sni... | 0.004762 |
def staticmap(ctx, mapid, output, features, lat, lon, zoom, size):
"""
Generate static map images from existing Mapbox map ids.
Optionally overlay with geojson features.
$ mapbox staticmap --features features.geojson mapbox.satellite out.png
$ mapbox staticmap --lon -61.7 --lat 12.1 --zoom 12 m... | 0.001899 |
def data(self, index, role = QtCore.Qt.DisplayRole):
"""Reimplemented from QtCore.QAbstractItemModel
The value gets validated and is red if validation fails
and green if it passes.
"""
if not index.isValid():
return None
if role == QtCore.Qt.DisplayRole or ro... | 0.002959 |
def telnet_config(self, status):
"""
status:
false - Telnet is disabled
true - Telnet is enabled
"""
ret = self.command(
'configManager.cgi?action=setConfig&Telnet.Enable={0}'.format(
status)
)
return ret.content.decode... | 0.006079 |
def get_list(self, key, default=UndefinedKey):
"""Return list representation of value found at key
:param key: key to use (dot separated). E.g., a.b.c
:type key: basestring
:param default: default value if key not found
:type default: list
:return: list value
:ty... | 0.003941 |
def getRow(self, key):
"""
Get a row by value of the indexing columns. If the index is not
specified, gets the only row of a dataframe with no indexing columns.
Args:
key: Tuple representing the index of the desired row.
Returns:
The row.
"""
... | 0.005376 |
def calculate_permute_output_shapes(operator):
'''
Allowed input/output patterns are
1. [N, C, H, W] ---> [N', C', H', W']
Note that here [N', C', H', W'] means all possible permutations of [N, C, H, W]
'''
check_input_and_output_numbers(operator, input_count_range=1, output_count_range=1)
... | 0.006468 |
def getAttachment(self, oid, attachment_id, out_folder=None):
"""
downloads a feature's attachment.
Inputs:
oid - object id of the feature
attachment_id - ID of the attachment. Should be an integer.
out_folder - save path of the file
Output:
... | 0.00402 |
def safe_nested_val(key_tuple, dict_obj, default_value=None):
"""Return a value from nested dicts by the order of the given keys tuple.
Parameters
----------
key_tuple : tuple
The keys to use for extraction, in order.
dict_obj : dict
The outer-most dict to extract from.
default_... | 0.00106 |
def powernodes_containing(self, name, directly=False) -> iter:
"""Yield all power nodes containing (power) node of given *name*.
If *directly* is True, will only yield the direct parent of given name.
"""
if directly:
yield from (node for node in self.all_in(name)
... | 0.001783 |
def has_reduction(expr):
"""Does `expr` contain a reduction?
Parameters
----------
expr : ibis.expr.types.Expr
An ibis expression
Returns
-------
truth_value : bool
Whether or not there's at least one reduction in `expr`
Notes
-----
The ``isinstance(op, ops.Tab... | 0.001239 |
def to_root(df, path, key='my_ttree', mode='w', store_index=True, *args, **kwargs):
"""
Write DataFrame to a ROOT file.
Parameters
----------
path: string
File path to new ROOT file (will be overwritten)
key: string
Name of tree that the DataFrame will be saved as
mode: stri... | 0.001408 |
def rm_op(l, name, op):
"""Remove an opcode. This is used when basing a new Python release off
of another one, and there is an opcode that is in the old release
that was removed in the new release.
We are pretty aggressive about removing traces of the op.
"""
# opname is an array, so we need to... | 0.012017 |
def group_add_user_action(model, request):
"""Add user to group.
"""
user_id = request.params.get('id')
if not user_id:
user_ids = request.params.getall('id[]')
else:
user_ids = [user_id]
try:
group = model.model
validate_add_users_to_groups(model, user_ids, [grou... | 0.000625 |
def to_sql(self):
"""
This function build a sql condition string (those used in the 'WHERE' clause) based on given condition
Supported match pattern:
{a: 1} -> a == 1
{a: {$gt: 1}} -> a > 1
{a: {$gte: 1}} ... | 0.004814 |
def ces(subsystem, mechanisms=False, purviews=False, cause_purviews=False,
effect_purviews=False, parallel=False):
"""Return the conceptual structure of this subsystem, optionally restricted
to concepts with the mechanisms and purviews given in keyword arguments.
If you don't need the full |CauseEf... | 0.000625 |
def extract_args(self, data):
"""
It extracts irc msg arguments.
"""
args = []
data = data.strip(' ')
if ':' in data:
lhs, rhs = data.split(':', 1)
if lhs: args.extend(lhs.rstrip(' ').split(' '))
args.append(rhs)
else:
... | 0.015831 |
def __validate_arguments(self):
"""!
@brief Check input arguments of CLIQUE algorithm and if one of them is not correct then appropriate exception
is thrown.
"""
if len(self.__data) == 0:
raise ValueError("Empty input data. Data should contain at lea... | 0.008499 |
def run(self):
"""
Blocking method that run the server.
"""
if self.tasks:
logger.info('Registered tasks: %s' % ', '.join(self.tasks))
else:
logger.info('No tasks registered')
logger.info('Listening on %s ...' % self.bind)
self.socket.bind(... | 0.001165 |
def __fetch_crate_versions(self, crate_id):
"""Get crate versions data"""
raw_versions = self.client.crate_attribute(crate_id, "versions")
version_downloads = json.loads(raw_versions)
return version_downloads | 0.00823 |
def histograms(self, analytes=None, bins=25, logy=False,
filt=False, colourful=True):
"""
Plot histograms of analytes.
Parameters
----------
analytes : optional, array_like or str
The analyte(s) to plot. Defaults to all analytes.
bins : int... | 0.002297 |
def run(self):
'''
Gather currently connected minions and update the cache
'''
new_mins = list(salt.utils.minions.CkMinions(self.opts).connected_ids())
cc = cache_cli(self.opts)
cc.get_cached()
cc.put_cache([new_mins])
log.debug('ConCache CacheWorker updat... | 0.009036 |
def get(
self: 'Option[Mapping[K,V]]',
key: K,
default=None
) -> 'Option[V]':
"""
Gets a mapping value by key in the contained value or returns
``default`` if the key doesn't exist.
Args:
key: The mapping key.
default: The ... | 0.003099 |
def validate(self):
"""Validate the parameters of the run. Raises self.Error if invalid parameters."""
errors = []
app = errors.append
if not self.hint_cores >= self.mpi_procs * self.omp_threads >= self.min_cores:
app("self.hint_cores >= mpi_procs * omp_threads >= self.min_c... | 0.007692 |
def strip(self, text, *args, **kwargs):
"""
Try to maintain parity with what is extracted by extract since strip
will most likely be used in conjunction with extract
"""
if OEMBED_DEFAULT_PARSE_HTML:
extracted = self.extract_oembeds_html(text, *args, **kwargs)
... | 0.008347 |
def matching(self):
"""Return found matching SBo packages
"""
for sbo in self.package_not_found:
for pkg in self.data:
if sbo in pkg and pkg not in self.blacklist:
self.package_found.append(pkg) | 0.007519 |
def append(self, clause, weight=None):
"""
Add one more clause to WCNF formula. This method additionally
updates the number of variables, i.e. variable ``self.nv``, used in
the formula.
The clause can be hard or soft depending on the ``weight``
argume... | 0.002451 |
def approve(self, peer_jid):
"""
(Pre-)approve a subscription request from `peer_jid`.
:param peer_jid: The peer to (pre-)approve.
This sends a ``"subscribed"`` presence to the peer; if the peer has
previously asked for a subscription, this will seal the deal and create
... | 0.002367 |
def crop(self, cropping):
"""
Set `a:srcRect` child to crop according to *cropping* values.
"""
srcRect = self._add_srcRect()
srcRect.l, srcRect.t, srcRect.r, srcRect.b = cropping | 0.009132 |
def allowed_target_sdp_states(self):
"""Return a list of allowed target states for the current state."""
_current_state = self._sdp_state.current_state
_allowed_target_states = self._sdp_state.allowed_target_states[
_current_state]
return json.dumps(dict(allowed_target_sdp_st... | 0.007874 |
def count_exceptions(self, c, broker):
"""
Count exceptions as processing proceeds
"""
if c in broker.exceptions:
self.counts['exception'] += len(broker.exceptions[c])
return self | 0.008658 |
def _get_accepted(self, graph):
"""
Find the accepted states
Args:
graph (DFA): The DFA states
Return:
list: Returns the list of the accepted states
"""
accepted = []
for state in graph.states:
if state.final != TropicalWeight(f... | 0.005051 |
def emit(self, record):
"""Send a LogRecord to the callback function, after preparing it
for serialization."""
try:
self._callback(self.prepare(record))
except Exception:
self.handleError(record) | 0.007968 |
def to_dict(self):
"""Return a dictionary representation of the SemI."""
make = lambda pair: (pair[0], pair[1].to_dict())
return dict(
variables=dict(make(v) for v in self.variables.items()),
properties=dict(make(p) for p in self.properties.items()),
roles=dic... | 0.006834 |
def get_page_tags_from_request(request, page_lookup, lang, site, title=False):
"""
Get the list of tags attached to a Page or a Title from a request from usual
`page_lookup` parameters.
:param request: request object
:param page_lookup: a valid page_lookup argument
:param lang: a language code... | 0.002131 |
def _wait_for_transfer_threads(self, terminate):
# type: (SyncCopy, bool) -> None
"""Wait for download threads
:param SyncCopy self: this
:param bool terminate: terminate threads
"""
if terminate:
self._synccopy_terminate = terminate
for thr in self._t... | 0.007916 |
def djfrontend_jquery(version=None):
"""
Returns jQuery JavaScript file according to version number.
TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback.
Included in HTML5 Boilerplate.
"""
if version is None:
version = getattr(settings, '... | 0.008363 |
def strand_unknown(db, transcript):
"""
for unstranded data with novel transcripts single exon genes
will have no strand information. single exon novel genes are also
a source of noise in the Cufflinks assembly so this removes them
"""
features = list(db.children(transcript))
strand = featur... | 0.002469 |
def open_file(path, grib_errors='warn', **kwargs):
"""Open a GRIB file as a ``cfgrib.Dataset``."""
if 'mode' in kwargs:
warnings.warn("the `mode` keyword argument is ignored and deprecated", FutureWarning)
kwargs.pop('mode')
stream = messages.FileStream(path, message_class=cfmessage.CfMessag... | 0.007389 |
def parse(self,fileName,offset):
'''Parses synset from file <fileName>
from offset <offset>
'''
p = Parser()
p.file = open(fileName, 'rb')
a = p.parse_synset(offset=offset)
p.file.close()
self.__dict__.update(a.__dict__) | 0.014085 |
def generate_password(length=8, lower=True, upper=True, number=True):
"""
generates a simple password. We should not really use this in production.
:param length: the length of the password
:param lower: True of lower case characters are allowed
:param upper: True if upper case characters are allowe... | 0.001878 |
def RawBytesToScriptHash(raw):
"""
Get a hash of the provided raw bytes using the ripemd160 algorithm.
Args:
raw (bytes): byte array of raw bytes. e.g. b'\xAA\xBB\xCC'
Returns:
UInt160:
"""
rawh = binascii.unhexlify(raw)
rawhashstr = bina... | 0.007126 |
def overlaps(self,junc,tolerance=0):
"""see if junction overlaps with tolerance"""
if not self.left.overlaps(junc.left,padding=tolerance): return False
if not self.right.overlaps(junc.right,padding=tolerance): return False
return True | 0.028 |
def list_file_extensions(path: str, reportevery: int = 1) -> List[str]:
"""
Returns a sorted list of every file extension found in a directory
and its subdirectories.
Args:
path: path to scan
reportevery: report directory progress after every *n* steps
Returns:
sorted list ... | 0.001416 |
def copy(string, **kwargs):
"""Copy given string into system clipboard."""
window = Tk()
window.withdraw()
window.clipboard_clear()
window.clipboard_append(string)
window.destroy()
return | 0.004651 |
def get_port_for_ip_address(context, ip_id, id, fields=None):
"""Retrieve a port.
: param context: neutron api request context
: param id: UUID representing the port to fetch.
: param fields: a list of strings that are valid keys in a
port dictionary as listed in the RESOURCE_ATTRIBUTE_MAP
... | 0.001067 |
def next_channel_from_routes(
available_routes: List['RouteState'],
channelidentifiers_to_channels: Dict,
transfer_amount: PaymentWithFeeAmount,
lock_timeout: BlockTimeout,
) -> Optional[NettingChannelState]:
""" Returns the first route that may be used to mediated the transfer.
... | 0.001542 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.