text stringlengths 78 104k | score float64 0 0.18 |
|---|---|
def tail(self, stack_name, cancel, log_func=_tail_print, sleep_time=5,
include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_eve... | 0.00365 |
def unzip(iterable):
"""The inverse of :func:`zip`, this function disaggregates the elements
of the zipped *iterable*.
The ``i``-th iterable contains the ``i``-th element from each element
of the zipped iterable. The first element is used to to determine the
length of the remaining elements.
... | 0.000567 |
def with_headers(self, headers=None, **params):
"""
Add headers to the request.
:param headers: A dict, or a list of key, value pairs
:param params: A dict of key value pairs
"""
if isinstance(headers, (tuple, list)):
headers = dict(head... | 0.010889 |
def post(self, request, *args, **kwargs):
"""
Method for handling POST requests.
If the formset is valid this will
loop through the formset and save each form.
A log is generated for each save. The user
is notified of the total number of changes
with a message. Re... | 0.003967 |
def check_basename_conflicts(self, targets):
"""Apps' basenames are used as bundle directory names. Ensure they are all unique."""
basename_seen = {}
for target in targets:
if target.basename in basename_seen:
raise self.BasenameConflictError('Basename must be unique, found two targets use '
... | 0.010309 |
def standard_aggregation(C):
"""Compute the sparsity pattern of the tentative prolongator.
Parameters
----------
C : csr_matrix
strength of connection matrix
Returns
-------
AggOp : csr_matrix
aggregation operator which determines the sparsity pattern
of the tentati... | 0.000382 |
def find_npolfile(flist,detector,filters):
""" Search a list of files for one that matches the configuration
of detector and filters used.
"""
npolfile = None
for f in flist:
fdet = fits.getval(f, 'detector', memmap=False)
if fdet == detector:
filt1 = fits.getval(f, '... | 0.006623 |
def parametrize_lines(mv_grid):
""" Set unparametrized branches to default branch type
Args
----
mv_grid: MVGridDing0
MV grid instance
Notes
-----
During the connection process of satellites, new branches are created -
these have to be parametrized.
"""
for branch... | 0.005376 |
def delete_all(self):
'''Deletes all feature collections.
This does not destroy the ES index, but instead only
deletes all FCs with the configured document type
(defaults to ``fc``).
'''
try:
self.conn.indices.delete_mapping(
index=self.index,... | 0.004032 |
def _get_query_result(query, raw_result, **kwargs):
""" Get query results helper. """
if raw_result:
return query(**kwargs)
if kwargs:
return QueryResult(query, **kwargs)
return query.result | 0.008097 |
def estimate_markov_model(dtrajs, lag, reversible=True, statdist=None,
count_mode='sliding', weights='empirical',
sparse=False, connectivity='largest',
dt_traj='1 step', maxiter=1000000, maxerr=1e-8,
score_method='VA... | 0.002175 |
def main(port, export, css, files):
"""
\b
Examples:
$ moo README.md # live preview README.md
$ moo -e *.md # export all markdown files
$ moo --no-css -e README.md # export README.md without CSS
$ cat README.md | moo -e - | less # export ST... | 0.004286 |
def to_posix_path(code_path):
"""
Change the code_path to be of unix-style if running on windows when supplied with an absolute windows path.
Parameters
----------
code_path : str
Directory in the host operating system that should be mounted within the container.
Returns
-------
... | 0.007075 |
def count_lightning(datain, time_step):
"""**Count lightning strikes detected within a defined time_step**
Generate time intervals according to the time_step defined and count
lightning strikes in these intervals. Statistics are also calculated for
lightning detection errors and the number of stations ... | 0.001229 |
def getSpec(cls):
"""
Return the Spec for ColumnPoolerRegion.
The parameters collection is constructed based on the parameters specified
by the various components (tmSpec and otherSpec)
"""
spec = dict(
description=ColumnPoolerRegion.__doc__,
singleNodeOnly=True,
inputs=dict(
... | 0.001613 |
def vlq2int(data):
"""Read one VLQ-encoded integer value from an input data stream."""
# The VLQ is little-endian.
byte = ord(data.read(1))
value = byte & 0x7F
shift = 1
while byte & 0x80 != 0:
byte = ord(data.read(1))
value = ((byte & 0x7F) << shift * 7) | value
shift +... | 0.005882 |
def refresh( self ):
"""
Refreshs the current user interface to match the latest settings.
"""
schemas = self.schemas()
self.blockSignals(True)
self.clear()
self.addItems([schema.name() for schema in schemas])
self.blockSignals(False) | 0.015924 |
def minimize(self, loss_fn, x, optim_state):
"""
Analogous to tf.Optimizer.minimize
:param loss_fn: tf Tensor, representing the loss to minimize
:param x: list of Tensor, analogous to tf.Optimizer's var_list
:param optim_state: A possibly nested dict, containing any optimizer state.
Returns:
... | 0.001795 |
def annotate_metadata_code(repo, files):
"""
Update metadata with the commit information
"""
package = repo.package
package['code'] = []
for p in files:
matching_files = glob2.glob("**/{}".format(p))
for f in matching_files:
absf = os.path.abspath(f)
prin... | 0.001585 |
def adapt(self, d, x):
"""
Adapt weights according one desired value and its input.
**Args:**
* `d` : desired value (float)
* `x` : input array (1-dimensional array)
"""
y = np.dot(self.w, x)
e = d - y
R1 = np.dot(np.dot(np.dot(self.R,x),x.T),se... | 0.014553 |
def dump_to_path(self, cnf, filepath, **kwargs):
"""
Dump config 'cnf' to a file 'filepath`.
:param cnf: Configuration data to dump
:param filepath: Config file path
:param kwargs: optional keyword parameters to be sanitized :: dict
"""
with self.wopen(filepath) ... | 0.005277 |
def set_memcached_backend(self, config):
"""
Select the most suitable Memcached backend based on the config and
on what's installed
"""
# This is the preferred backend as it is the fastest and most fully
# featured, so we use this by default
config['BACKEND'] = 'd... | 0.002429 |
def job_attempts(self, job_id):
"""
With the job attempts API, you can obtain a collection of resources
that represent a job attempt.
"""
path = '/ws/v1/history/mapreduce/jobs/{jobid}/jobattempts'.format(
jobid=job_id)
return self.request(path) | 0.006557 |
def clean_near_peaks(signal, peaks_, min_distance):
""" Given an array with all the peaks of the signal ('peaks') and a
distance value ('min_distance') and the signal, by argument, this function
erases all the unnecessary peaks and returns an array with only the maximum
peak for each period of the signa... | 0.005092 |
def encrypt_ctr(self, data, counter):
"""
Return an iterator that encrypts `data` using the Counter (CTR) mode of
operation.
CTR mode can operate on `data` of any length.
Each iteration, except the last, always returns a block-sized :obj:`bytes`
object (i.e. 8 bytes). The last iteratio... | 0.008816 |
def waiting(self, timeout=0):
"Return True if data is ready for the client."
if self.linebuffer:
return True
(winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout)
return winput != [] | 0.012 |
def _method_error_handler(self, response: Dict[str, Any]):
"""处理400~499段状态码,为对应的任务设置异常.
Parameters:
(response): - 响应的python字典形式数据
Return:
(bool): - 准确地说没有错误就会返回True
"""
exp = response.get('MESSAGE')
code = response.get("CODE")
ID = exp.g... | 0.005141 |
def to_escpos(self):
""" converts the current style to an escpos command string """
cmd = ''
ordered_cmds = self.cmds.keys()
ordered_cmds.sort(lambda x,y: cmp(self.cmds[x]['_order'], self.cmds[y]['_order']))
for style in ordered_cmds:
cmd += self.cmds[style][self.get(... | 0.011561 |
def symbol(self, index):
"""Generates symbol name from index"""
#if index is actually a string, just return it
if isinstance(index, str):
return index
elif (index < 0) or (index >= self.symtab.table_len):
self.error("symbol table index out of range")
... | 0.00663 |
def get_placeholders(arg, check_duplicates=False):
"""
Get all the placeholders' names in order.
Use the regex below to locate all the opening ({{) and closing brackets (}}).
After that, extract "stuff" inside the brackets.
Args:
arg: The word which this function performs searching on.
... | 0.002776 |
def write(self, fd, msg_fd=None):
"""write out module to file descriptor.
fd -- file descriptor to write out service description.
msg_fd -- optional file descriptor for messages module.
"""
# if msg_fd != None:
# print >>fd, self.messagesImports
# print >>msg... | 0.004525 |
def clone(self, **kw):
"""Copy this distribution, substituting in any changed keyword args"""
names = 'project_name version py_version platform location precedence'
for attr in names.split():
kw.setdefault(attr, getattr(self, attr, None))
kw.setdefault('metadata', self._provi... | 0.005556 |
def model_type(dtype):
"Return the torch type corresponding to `dtype`."
return (torch.float32 if np.issubdtype(dtype, np.floating) else
torch.int64 if np.issubdtype(dtype, np.integer)
else None) | 0.004405 |
def query_paths(self):
"""
RETURN A LIST OF ALL NESTED COLUMNS
"""
output = self.namespace.alias_to_query_paths.get(self.name)
if output:
return output
Log.error("Can not find index {{index|quote}}", index=self.name) | 0.007246 |
def resample(self, size, interpolation=gdalconst.GRA_NearestNeighbour):
"""Returns a new instance resampled to provided size.
Arguments:
size -- tuple of x,y image dimensions
"""
# Find the scaling factor for pixel size.
factors = (size[0] / float(self.RasterXSize),
... | 0.002782 |
def _run_code(code, run_globals, init_globals=None,
mod_name=None, mod_fname=None,
mod_loader=None, pkg_name=None):
"""Helper to run code in nominated namespace"""
if init_globals is not None:
run_globals.update(init_globals)
run_globals.update(__name__ = mod_name,
... | 0.017822 |
def unified(old, new):
"""
Returns a generator yielding a unified diff between `old` and `new`.
"""
for diff in difflib.ndiff(old.splitlines(), new.splitlines()):
if diff[0] == " ":
yield diff
elif diff[0] == "?":
continue
... | 0.007009 |
def get_all_parents(self):
"""Return all parent GO IDs."""
all_parents = set()
for parent in self.parents:
all_parents.add(parent.item_id)
all_parents |= parent.get_all_parents()
return all_parents | 0.007905 |
def from_environment_variables(cls):
"""
Construct OneViewClient using environment variables.
Allowed variables: ONEVIEWSDK_IP (required), ONEVIEWSDK_USERNAME (required), ONEVIEWSDK_PASSWORD (required),
ONEVIEWSDK_AUTH_LOGIN_DOMAIN, ONEVIEWSDK_API_VERSION, ONEVIEWSDK_IMAGE_STREAMER_IP, ... | 0.003793 |
def get_bbox(self, points=None):
"""
Get bounding box of this object.
Returns
-------
(p1, p2, p3, p4): a 4-tuple of the points in data coordinates,
beginning with the lower-left and proceeding counter-clockwise.
"""
if points is None:
x1, y1,... | 0.004167 |
def cut_by_plane(self, plane, inverted=False):
'''
Like cut_across_axis, but works with an arbitrary plane. Keeps
vertices that lie in front of the plane (i.e. in the direction
of the plane normal).
inverted: When `True`, invert the logic, to keep the vertices
that lie... | 0.005076 |
def get_host_health_power_supplies(self, data=None):
"""Request the health power supply information.
:param: the data to retrieve from the server, defaults to None.
:returns: the dictionary containing the power supply information.
:raises: IloConnectionError if failed connecting to the ... | 0.003448 |
def flat_map(self, func: Callable[[T], 'TOption[T]']) -> 'TOption[T]':
"""
Usage:
>>> TOption(3).flat_map(lambda x: TOption(x+1)).get()
4
>>> TOption(3).flat_map(lambda x: TOption(None)).get_or(999)
999
>>> TOption(None).flat_map(lambda x: TOp... | 0.004494 |
def to_python(self, value):
"""
"Called during deserialization and during the clean() method used
from forms.... [s]hould deal gracefully with... (*) an instance of
the correct type; (*) a string; (*) None (if the field allows
null=True)."
"For ``to_python()``, if anythi... | 0.002972 |
def modulo11(base):
"""Calcula o dígito verificador (DV) para o argumento usando "Módulo 11".
:param str base: String contendo os dígitos sobre os quais o DV será
calculado, assumindo que o DV não está incluído no argumento.
:return: O dígito verificador calculado.
:rtype: int
"""
pes... | 0.001961 |
def add(self):
'''Save an object to Instapaper after instantiating it.
Example::
folder = Folder(instapaper, title='stuff')
result = folder.add()
'''
# TODO validation per object type
submit_attribs = {}
for attrib in self.ATTRIBUTES:
... | 0.00365 |
def render_to_response(self, context, **response_kwargs):
'''
Compares requested format to supported formats and routes the response.
:attribute switcher: A dictionary of format types and their respective response methods.
'''
switcher = {
'json': self.return_json_re... | 0.004304 |
def similarity(self, d, d_):
"""
Compute a similarity score for two documents.
Optionally pass in a `term_sim_ref` dict-like, which should be able
to take `term1, term2` as args and return their similarity.
"""
es = set([e.name for e in d.entities])
es_ = set([e.... | 0.002006 |
def select_event(
event = None,
selection = "all",
required_variables = None,
ensure_required_variables_present = False,
verbose = True
):
"""
Select a HEP event.
"""
if required_variab... | 0.0054 |
def perform_bulk_pubmed_query(self):
"""
If 'bulk_pubmed_query' contains any content, perform a bulk PubMed query,
add the publications to the publication set, and save.
"""
if self.bulk_pubmed_query:
failed_queries = []
pmid_list = re.findall(r'(\d+)(?:[\... | 0.006936 |
def _parse_specs(specs, Ks):
'''
Set up the different functions we need to call.
Returns:
- a dict mapping base estimator functions to _FuncInfo objects.
If the function needs_alpha, then the alphas attribute is an array
of alpha values and pos is a corresponding array of indice... | 0.00027 |
def md5(filename:str)->str:
"""
Given a filename produce an md5 hash of the contents.
>>> import tempfile, os
>>> f = tempfile.NamedTemporaryFile(delete=False)
>>> f.write(b'Hello Wirld!')
12
>>> f.close()
>>> md5(f.name)
'997c62b6afe9712cad3baffb49cb8c8a'
>>> os.unlink(f.name)
... | 0.005859 |
def weld_cast_array(array, weld_type, to_weld_type):
"""Cast array to a different type.
Parameters
----------
array : numpy.ndarray or WeldObject
Input data.
weld_type : WeldType
Type of each element in the input array.
to_weld_type : WeldType
Desired type.
Returns
... | 0.002222 |
def _get_resource_view(self, resource_view):
# type: (Union[ResourceView,Dict]) -> ResourceView
"""Get resource view id
Args:
resource_view (Union[ResourceView,Dict]): ResourceView metadata from a ResourceView object or dictionary
Returns:
ResourceView: Resource... | 0.009132 |
def sendFuture(self, future):
"""Send a Future to be executed remotely."""
try:
if shared.getConst(hash(future.callable),
timeout=0):
# Enforce name reference passing if already shared
future.callable = SharedElementEncapsu... | 0.002732 |
def send_deferred(self, auth):
"""Send all deferred requests for a particular CIK/auth."""
if self.deferred.has_requests(auth):
method_arg_pairs = self.deferred.get_method_args_pairs(auth)
calls = self._composeCalls(method_arg_pairs)
# should this call be made with no... | 0.004132 |
def read_enabled(self):
"""Read enable repositories
"""
for line in self.conf.splitlines():
line = line.lstrip()
if self.tag in line:
self.tag_line = True
if (line and self.tag_line and not line.startswith("#") and
self.tag ... | 0.004938 |
def timescales_from_eigenvalues(evals, tau=1):
r"""Compute implied time scales from given eigenvalues
Parameters
----------
evals : eigenvalues
tau : lag time
Returns
-------
ts : ndarray
The implied time scales to the given eigenvalues, in the same order.
"""
"""Chec... | 0.002698 |
def _compute_mean(self, C, mag, rjb):
"""
Compute mean value according to equation 3, page 46.
"""
mean = (C['c1'] +
self._compute_term1(C, mag) +
self._compute_term2(C, mag, rjb))
return mean | 0.007576 |
def _parse_book_links(dom):
"""
Parse links to the details about publications from page with book list.
Args:
dom (obj): HTMLElement container of the page with book list.
Returns:
list: List of strings / absolute links to book details.
"""
links = []
picker = lambda x: x.pa... | 0.003378 |
def _decimal_to_json(value):
"""Coerce 'value' to a JSON-compatible representation."""
if isinstance(value, decimal.Decimal):
value = str(value)
return value | 0.00565 |
def limit(self, limit_value, key_func=None, per_method=False,
methods=None, error_message=None, exempt_when=None):
"""
decorator to be used for rate limiting individual routes.
:param limit_value: rate limit string or a callable that returns a string.
:ref:`ratelimit-stri... | 0.008929 |
def record(self):
# type: () -> bytes
'''
Generate a string representing the Rock Ridge Alternate Name record.
Parameters:
None.
Returns:
String containing the Rock Ridge record.
'''
if not self._initialized:
raise pycdlibexception.P... | 0.009747 |
def _draw_banner(self):
"""
Draw the banner with sorting options at the top of the page
"""
n_rows, n_cols = self.term.stdscr.getmaxyx()
window = self.term.stdscr.derwin(1, n_cols, self._row, 0)
window.erase()
window.bkgd(str(' '), self.term.attr('OrderBar'))
... | 0.002227 |
def logical_chassis_fwdl_status_output_cluster_fwdl_entries_fwdl_entries_index(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
logical_chassis_fwdl_status = ET.Element("logical_chassis_fwdl_status")
config = logical_chassis_fwdl_status
output = E... | 0.004237 |
def sorted_feed_cols(df):
"""
takes a dataframe's columns that would be of the form:
['feed003', 'failsafe_feed999', 'override_feed000', 'feed001', 'feed002']
and returns:
['override_feed000', 'feed001', 'feed002', 'feed003', 'failsafe_feed999']
"""
cols = df.columns
ind = [int(c.split("... | 0.004608 |
def configfile(f):
""" This decorator will parse a configuration file in YAML format
and store the dictionary in ``ctx.blockchain.config``
"""
@click.pass_context
def new_func(ctx, *args, **kwargs):
ctx.config = yaml.load(open(ctx.obj["configfile"]))
return ctx.invoke(f, *args, ... | 0.00271 |
def main():
"""
Entry point when used via command line.
Features are given using the environment variable ``PRODUCT_EQUATION``.
If it is not set, ``PRODUCT_EQUATION_FILENAME`` is tried: if it points
to an existing equation file that selection is used.
(if ``APE_PREPEND_FEATURES`` is given, tho... | 0.000701 |
def __buildDomainRanges(self, aProp):
"""
extract domain/range details and add to Python objects
"""
domains = chain(aProp.rdflib_graph.objects(
None, rdflib.term.URIRef(u'http://schema.org/domainIncludes')), aProp.rdflib_graph.objects(
None, rdflib.RDFS.domain))... | 0.005455 |
def subset(data, sel0=None, sel1=None, blen=None, storage=None, create='array',
**kwargs):
"""Return selected rows and columns of an array."""
# TODO refactor sel0 and sel1 normalization with ndarray.subset
# setup
storage = _util.get_storage(storage)
blen = _util.get_blen_array(data, b... | 0.000547 |
def chunkwise(self, func, *args, **kwargs):
"""Execute a function for each chunk in the dataset.
Order of excecution is not guaranteed.
Parameters
----------
func : function
Function to execute. First two arguments must be dataset,
slices.
args (... | 0.00221 |
def generate(args):
"""Generates the presentation and returns a list of files used"""
source_files = {args.presentation}
# Parse the template info
template_info = Template(args.template)
if args.css:
presentation_dir = os.path.split(args.presentation)[0]
target_path = os.path.relpa... | 0.003102 |
def verify_signature(self, signature, nonce, timestamp, signed_id):
"""
Verify the server response signature.
:param signature:
:param nonce:
:param timestamp:
:param signed_id: either transactionid, documentid or marketplacemerchantid
:return: true o... | 0.011321 |
def write_entries(self, entries, logger_name=None, resource=None, labels=None):
"""API call: log an entry resource via a POST request
:type entries: sequence of mapping
:param entries: the log entry resources to log.
:type logger_name: str
:param logger_name: name of default l... | 0.001889 |
def make_geojson(contents):
"""
Return a GeoJSON string from a variety of inputs.
See the documentation for make_url for the possible contents
input.
Returns
-------
GeoJSON string
"""
if isinstance(contents, six.string_types):
return contents
if hasattr(contents, '__g... | 0.00116 |
def filter_data(self, min_len, max_len):
"""
Preserves only samples which satisfy the following inequality:
min_len <= src sample sequence length <= max_len AND
min_len <= tgt sample sequence length <= max_len
:param min_len: minimum sequence length
:param max_le... | 0.002128 |
def _is_compress_filetype(self, inpath):
"""private method that performs magic number and size check on file to determine whether to compress the file"""
# check for common file type suffixes in order to avoid the need for file reads to check magic number for binary vs. text file
if self._is_com... | 0.006485 |
def run_migration(connection, queries, engine):
""" Apply a migration to the SQL server """
# Execute query
with connection.cursor() as cursorMig:
# Parse statements
queries = parse_statements(queries, engine)
for query in queries:
cursorMig.execute(query)
conne... | 0.002849 |
def _import_templates(force=False):
"""Import templates from disk into database
Reads all templates from disk and adds them to the database. By default, any template that has been modified by
the user will not be updated. This can however be changed by setting `force` to `True`, which causes all templates
... | 0.003371 |
def extract_http_metadata(wrapped, instance, args, kwargs, return_value):
"""Provide HTTP request metadata for improved visualization.
See documentation for this data structure:
http://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html#api-segmentdocuments-http
"""
response = r... | 0.001167 |
def define_log_renderer(fmt, fpath, quiet):
"""
the final log processor that structlog requires to render.
"""
# it must accept a logger, method_name and event_dict (just like processors)
# but must return the rendered string, not a dictionary.
# TODO tty logic
if fmt:
return struct... | 0.00354 |
def default(self, obj):
''' The required ``default`` method for ``JSONEncoder`` subclasses.
Args:
obj (obj) :
The object to encode. Anything not specifically handled in
this method is passed on to the default system JSON encoder.
'''
from .... | 0.001764 |
def split(values, separator=re.compile("[ ,]+")):
"""
Convert space-or-comma-separated values into a single list
Common use case for this is merging content of options with multiple
values allowed into a single list of strings thus allowing any of
the formats below and converts them into ['a', 'b',... | 0.001277 |
def plot(self, figsize=(12, 4), xscale='auto-gps', **kwargs):
"""Plot this flag on a segments projection.
Parameters
----------
**kwargs
all keyword arguments are passed to the
:class:`~gwpy.plot.Plot` constructor.
Returns
-------
figure ... | 0.0016 |
def users_me_merge(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/users#merge-self-with-another-user"
api_path = "/api/v2/users/me/merge.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | 0.011811 |
def get_values(self, keys):
"""
Return a list of values associated to a particular list of keys.
"""
if is_string(keys):
return [s.__dict__[keys] for s in self.sections]
else:
values = []
for k in keys:
values.append([s.__dict__... | 0.005348 |
def domain_delete(domain, logger, filesystem):
"""libvirt domain undefinition.
@raise: libvirt.libvirtError.
"""
if domain is not None:
try:
if domain.isActive():
domain.destroy()
except libvirt.libvirtError:
logger.exception("Unable to destroy t... | 0.001441 |
def partition_payload(data, key, thresh):
"""
Yield partitions of a payload
e.g. with a threshold of 2:
{ "dataElements": [1, 2, 3] }
-->
{ "dataElements": [1, 2] }
and
{ "dataElements": [3] }
:param data: the payload
:param key: the key of the dict to partition
:param ... | 0.001862 |
def write_pidfile(rundir, process_type=PROCESS_TYPE,
name=None, file=None): #@ReservedAssignment
"""
Write a pid file in the run directory, using the given process type
and process name for the filename.
@rtype: str
@returns: full path to the pid file that was written
"""
... | 0.004098 |
def convert_args(self, command, args):
"""
Converts ``str -> int`` or ``register -> int``.
"""
for wanted, arg in zip(command.argtypes(), args):
wanted = wanted.type_
if(wanted == "const"):
try:
yield to_int(arg)
except:
if(arg in self.processor.constants):
yield self.processor.co... | 0.042353 |
def num_samples(self):
"""
Return the total number of samples.
"""
with self.container.open_if_needed(mode='r') as cnt:
return cnt.get(self.key)[0].shape[0] | 0.01 |
def chunk_sequence(sequence, chunk_length):
"""Yield successive n-sized chunks from l."""
for index in range(0, len(sequence), chunk_length):
yield sequence[index:index + chunk_length] | 0.005 |
def doublewrap(f):
'''
a decorator decorator, allowing the decorator to be used as:
@decorator(with, arguments, and=kwargs)
or
@decorator
Ref: http://stackoverflow.com/questions/653368/how-to-create-a-python-decorator-that-can-be-used-either-with-or-without-paramet
'''
@functools.wraps(f... | 0.003215 |
def cmd(send, msg, args):
"""Find a path between two wikipedia articles.
Syntax: {command} [article] [article]
"""
parser = arguments.ArgParser(args['config'])
parser.add_argument('first', nargs='?')
parser.add_argument('second', nargs='?')
try:
cmdargs = parser.parse_args(msg)
... | 0.003454 |
def check_columns_fit(unoccupied_columns, row, offset, row_length):
"""
Checks if all the occupied columns in the row fit in the indices
given by free columns.
>>> check_columns_fit({0,1,2,3}, [(0, True), (2, True)], 0, 4)
True
>>> check_columns_fit({0,2,3}, [(2, True), (3, True)], 0, 4)
Tr... | 0.001321 |
def saturateHexColor(hexcolor, adjustment = 1.0):
'''Takes in an RGB color in 6-character hexadecimal with an optional preceding hash character.
Returns the RGB color in the same format adjusted by saturation by the second parameter.'''
assert(adjustment >= 0 and len(hexcolor) >= 1)
prefix = ""
if hexcolor[0] =... | 0.030451 |
def process_track(self, track, frame_size=400, hop_size=160, sr=None,
start=0, end=float('inf'), utterance=None, corpus=None):
"""
Process the track in **offline** mode, in one go.
Args:
track (Track): The track to process.
frame_size (int): The num... | 0.003302 |
def is_datafile_valid(datafile):
""" Given a datafile determine if it is valid or not.
Args:
datafile: JSON string representing the project.
Returns:
Boolean depending upon whether datafile is valid or not.
"""
try:
datafile_json = json.loads(datafile)
except:
return False
try:
jso... | 0.020833 |
def ConsultarCertificacionUltNroOrden(self, pto_emision=1):
"Consulta el último No de orden registrado para CG"
ret = self.client.cgConsultarUltimoNroOrden(
auth={
'token': self.Token, 'sign': self.Sign,
'cuit': self.Cuit, },
... | 0.003891 |
def dump(self, obj, context=None):
"""Serialize object with schema."""
return self.schema_class(context=context).dump(obj).data | 0.013986 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.