code stringlengths 75 104k | docstring stringlengths 1 46.9k |
|---|---|
def find_all(im_source, im_search, maxcnt=0):
'''
优先Template,之后Sift
@ return [(x,y), ...]
'''
result = find_all_template(im_source, im_search, maxcnt=maxcnt)
if not result:
result = find_all_sift(im_source, im_search, maxcnt=maxcnt)
if not result:
return []
return [match[... | 优先Template,之后Sift
@ return [(x,y), ...] |
def uniform_labels(self, mol1, mol2):
"""
Pair the geometrically equivalent atoms of the molecules.
Calculate RMSD on all possible isomorphism mappings and return mapping
with the least RMSD
Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object.
... | Pair the geometrically equivalent atoms of the molecules.
Calculate RMSD on all possible isomorphism mappings and return mapping
with the least RMSD
Args:
mol1: First molecule. OpenBabel OBMol or pymatgen Molecule object.
mol2: Second molecule. OpenBabel OBMol or pymatge... |
def loadFile(self, fileName):
"""
Display the file associated with the appletID.
"""
# Assign QFile object with the current name.
self.file = QtCore.QFile(fileName)
if self.file.exists():
self.qteText.append(open(fileName).read())
else:
ms... | Display the file associated with the appletID. |
def validate_email(email, check_mx=False, verify=False, debug=False, smtp_timeout=10):
"""Indicate whether the given string is a valid email address
according to the 'addr-spec' portion of RFC 2822 (see section
3.4.1). Parts of the spec that are marked obsolete are *not*
included in this test, and cert... | Indicate whether the given string is a valid email address
according to the 'addr-spec' portion of RFC 2822 (see section
3.4.1). Parts of the spec that are marked obsolete are *not*
included in this test, and certain arcane constructions that
depend on circular definitions in the spec may not pass, but... |
def touch(self):
"""
Touch all of the related models for the relationship.
"""
column = self.get_related().get_updated_at_column()
self.raw_update({column: self.get_related().fresh_timestamp()}) | Touch all of the related models for the relationship. |
def _get_colors(self):
"""Returns a tuple of two integers representing current colors: (foreground, background)."""
try:
csbi = _WindowsCSBI.get_info(self.win32_stream_handle)
return csbi['fg_color'], csbi['bg_color']
except IOError:
return 7, 0 | Returns a tuple of two integers representing current colors: (foreground, background). |
def valid_username(user):
'''
Validates a username based on the guidelines in `useradd(8)`
'''
if not isinstance(user, six.string_types):
return False
if len(user) > 32:
return False
return VALID_USERNAME.match(user) is not None | Validates a username based on the guidelines in `useradd(8)` |
def load_adjustments(self,
dates,
assets,
should_include_splits,
should_include_mergers,
should_include_dividends,
adjustment_type):
"""
Load collection o... | Load collection of Adjustment objects from underlying adjustments db.
Parameters
----------
dates : pd.DatetimeIndex
Dates for which adjustments are needed.
assets : pd.Int64Index
Assets for which adjustments are needed.
should_include_splits : bool
... |
def get_pokemon_by_name(self, name):
"""
Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the name of the Pokemon.
"""
endpoint = '/pokemon/' + str(name)
return self.make_request(self.BASE_URL + endpoint) | Returns an array of Pokemon objects containing all the forms of the
Pokemon specified the name of the Pokemon. |
def salt_proxy():
'''
Start a proxy minion.
'''
import salt.cli.daemons
import salt.utils.platform
import multiprocessing
if '' in sys.path:
sys.path.remove('')
if salt.utils.platform.is_windows():
proxyminion = salt.cli.daemons.ProxyMinion()
proxyminion.start()
... | Start a proxy minion. |
def remove_game_containers(name_filter: str) -> None:
"""
:raises docker.exceptions.APIError
"""
for container in docker_client.containers.list(filters={"name": name_filter}, all=True):
container.stop()
container.remove() | :raises docker.exceptions.APIError |
def extent_count(self):
"""
Returns the volume group extent count.
"""
self.open()
count = lvm_vg_get_extent_count(self.handle)
self.close()
return count | Returns the volume group extent count. |
def getPhysicalMinimum(self,chn=None):
"""
Returns the minimum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>>... | Returns the minimum physical value of signal edfsignal.
Parameters
----------
chn : int
channel number
Examples
--------
>>> import pyedflib
>>> f = pyedflib.data.test_generator()
>>> f.getPhysicalMinimum(0)==-1000.0
True
>>> ... |
def sbytes2ilines(stream, encoding="utf8", closer=None):
"""
CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS
TO A LINE (CR-DELIMITED) GENERATOR
"""
def read():
try:
while True:
bytes_ = stream.read(4096)
if not bytes_:
... | CONVERT A STREAM (with read() method) OF (ARBITRARY-SIZED) byte BLOCKS
TO A LINE (CR-DELIMITED) GENERATOR |
def _disconnect(self):
"""Disconnect from all MongoDB Clients."""
for cluster in self._clusters:
if 'connection' in cluster:
connection = cluster.pop('connection')
connection.close()
# Remove all attributes that are database names so that next time
... | Disconnect from all MongoDB Clients. |
def _on_process_stdout_ready(self):
""" Logs process output """
if not self:
return
o = self.readAllStandardOutput()
try:
output = bytes(o).decode(self._encoding)
except TypeError:
output = bytes(o.data()).decode(self._encoding)
for lin... | Logs process output |
def main(argv=None):
"""Run the pywhich command as if invoked with arguments `argv`.
If `argv` is `None`, arguments from `sys.argv` are used.
"""
if argv is None:
argv = sys.argv
parser = OptionParser()
parser.add_option('-v', '--verbose', dest="verbose", action="count",
defa... | Run the pywhich command as if invoked with arguments `argv`.
If `argv` is `None`, arguments from `sys.argv` are used. |
def import_by_path(dotted_path, error_prefix=''):
"""
Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImproperlyConfigured if something goes
wrong. This has come straight from Django 1.6
"""
try:
module_path, class_name = dotted_p... | Import a dotted module path and return the attribute/class designated by
the last name in the path. Raise ImproperlyConfigured if something goes
wrong. This has come straight from Django 1.6 |
def id_to_extended_id(item_id, item_class):
"""Return the extended ID from an ID.
:param item_id: The ID of the music library item
:type item_id: str
:param cls: The class of the music service item
:type cls: Sub-class of
:py:class:`soco.data_structures.MusicServiceI... | Return the extended ID from an ID.
:param item_id: The ID of the music library item
:type item_id: str
:param cls: The class of the music service item
:type cls: Sub-class of
:py:class:`soco.data_structures.MusicServiceItem`
The extended id can be something like 000... |
def _compute(self, windows, dates, assets, mask):
"""
Call the user's `compute` function on each window with a pre-built
output array.
"""
format_inputs = self._format_inputs
compute = self.compute
params = self.params
ndim = self.ndim
shape = (le... | Call the user's `compute` function on each window with a pre-built
output array. |
def string_to_genomic_range(rstring):
""" Convert a string to a genomic range
:param rstring: string representing a genomic range chr1:801-900
:type rstring:
:returns: object representing the string
:rtype: GenomicRange
"""
m = re.match('([^:]+):(\d+)-(\d+)',rstring)
if not m:
sys.stderr.write("ER... | Convert a string to a genomic range
:param rstring: string representing a genomic range chr1:801-900
:type rstring:
:returns: object representing the string
:rtype: GenomicRange |
def _new_instance(self):
"""
Constructs a new copy of the current object, preserving any tagging
:return:
An Asn1Value object
"""
new_obj = self.__class__()
new_obj.class_ = self.class_
new_obj.tag = self.tag
new_obj.implicit = self.implicit
... | Constructs a new copy of the current object, preserving any tagging
:return:
An Asn1Value object |
def read_tabular(filepath):
"""Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl'
"""
_, fn, ext = splitext2(filepath)
if ext == '.h5':
return _read_tabular_h5(filepath)
elif ext == '.pkl':
return _read_t... | Read tabular object in HDF5 or pickle format
Args:
filepath (path-like): path to read to; must end in '.h5' or '.pkl' |
def has_permission(
permission,
context=None,
):
"""Decorator that restricts access only for authorized users
with correct permissions.
If user is not authorized - raises HTTPUnauthorized,
if user is authorized and does not have permission -
raises HTTPForbidden.
"""
def wrapper(fn)... | Decorator that restricts access only for authorized users
with correct permissions.
If user is not authorized - raises HTTPUnauthorized,
if user is authorized and does not have permission -
raises HTTPForbidden. |
def _validate_generic_parameters(self, args):
"""Validate the generic request parameters.
@param args: Parsed schema arguments.
@raises APIError: In the following cases:
- Action is not included in C{self.actions}
- SignatureVersion is not included in C{self.signature_ve... | Validate the generic request parameters.
@param args: Parsed schema arguments.
@raises APIError: In the following cases:
- Action is not included in C{self.actions}
- SignatureVersion is not included in C{self.signature_versions}
- Expires and Timestamp are present
... |
def elementMaker(name, *children, **attrs):
"""
Construct a string from the HTML element description.
"""
formattedAttrs = ' '.join('{}={}'.format(key, _gvquote(str(value)))
for key, value in sorted(attrs.items()))
formattedChildren = ''.join(children)
return u'<{na... | Construct a string from the HTML element description. |
def _get_remote_field(field):
"""
Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field')
"""
if hasattr(field, 'remote_field'):
return field.remote_field
elif hasattr(field, 'related'):
return field.related
else:
return None | Compatible with Django 1.8~1.10 ('related' was renamed to 'remote_field') |
def import_lib(self):
"""Import the lib.py file into the bundle module"""
try:
import ambry.build
module = sys.modules['ambry.build']
except ImportError:
module = imp.new_module('ambry.build')
sys.modules['ambry.build'] = module
bf = self... | Import the lib.py file into the bundle module |
def cleanup():
"""Saves all the open databases to JSON so that the kernel can be shut down
without losing in-memory collections.
"""
failed = {}
success = []
for dbname, db in dbs.items():
try:
#Force the database save, even if the time hasn't elapsed yet.
db.save... | Saves all the open databases to JSON so that the kernel can be shut down
without losing in-memory collections. |
def set_limit(self, identifier, expires_at, blocking=False):
"""
Set a new global trigger or response limit
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:param expires_at: The limit expiration as ... | Set a new global trigger or response limit
:param identifier: The Trigger or Response object
:type identifier: parser.trigger.Trigger or parser.trigger.response.Response
:param expires_at: The limit expiration as a Unix timestamp
:type expires_at: float
:param blocking: When ... |
def update_extend(dst, src):
"""Update the `dst` with the `src`, extending values where lists.
Primiarily useful for integrating results from `get_library_config`.
"""
for k, v in src.items():
existing = dst.setdefault(k, [])
for x in v:
if x not in existing:
... | Update the `dst` with the `src`, extending values where lists.
Primiarily useful for integrating results from `get_library_config`. |
def get_subnets(self, vlan):
"""Return the subnets for the `vlan`."""
return vlan._origin.Subnets([
subnet
for subnet in self.subnets
if subnet.vlan.id == vlan.id
]) | Return the subnets for the `vlan`. |
def regex_replace(regex, repl, text):
r"""
thin wrapper around re.sub
regex_replace
MULTILINE and DOTALL are on by default in all util_regex functions
Args:
regex (str): pattern to find
repl (str): replace pattern with this
text (str): text to modify
Returns:
s... | r"""
thin wrapper around re.sub
regex_replace
MULTILINE and DOTALL are on by default in all util_regex functions
Args:
regex (str): pattern to find
repl (str): replace pattern with this
text (str): text to modify
Returns:
str: modified text
Example1:
>... |
def Receive(self, replytype, chain=None, **kw):
"""This method allows code to act in a synchronous manner, it waits to
return until the deferred fires but it doesn't prevent other queued
calls from being executed. Send must be called first, which sets up
the chain/factory.
... | This method allows code to act in a synchronous manner, it waits to
return until the deferred fires but it doesn't prevent other queued
calls from being executed. Send must be called first, which sets up
the chain/factory.
WARNING: If defer is set to True, must either call... |
def dec(data, **kwargs):
'''
Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default)
'''
if 'keyfile' in kwargs:
salt.utils.versions.warn_until(
'Neon',
'The \'keyfile\' argument has been deprecated and will be removed in Salt '
'{version}. ... | Alias to `{box_type}_decrypt`
box_type: secretbox, sealedbox(default) |
def save_overall_config(self, time_out=0):
"""
Schedules a save after given time_out
:param time_out: The amount of seconds it should wait before saving
:return:
"""
def save():
if not os.path.exists(self.overall_config_path):
return
... | Schedules a save after given time_out
:param time_out: The amount of seconds it should wait before saving
:return: |
def add_word(self, word):
"""
Add a word to the GADDAG.
Args:
word: A word to be added to the GADDAG.
"""
word = word.lower()
if not (word.isascii() and word.isalpha()):
raise ValueError("Invalid character in word '{}'".format(word))
wor... | Add a word to the GADDAG.
Args:
word: A word to be added to the GADDAG. |
def get_folders(self, limit=None, *, query=None, order_by=None, batch=None):
""" Returns a list of child folders matching the query
:param int limit: max no. of folders to get. Over 999 uses batch.
:param query: applies a filter to the request such as
"displayName eq 'HelloFolder'"
... | Returns a list of child folders matching the query
:param int limit: max no. of folders to get. Over 999 uses batch.
:param query: applies a filter to the request such as
"displayName eq 'HelloFolder'"
:type query: Query or str
:param order_by: orders the result set based on th... |
def count_indents(self, spacecount, tabs=0, offset=0):
"""Counts the number of indents that can be tabs or spacecount
number of spaces in a row from the current line.
"""
if not self.has_space(offset=offset):
return 0
spaces = 0
indents = 0
for char in... | Counts the number of indents that can be tabs or spacecount
number of spaces in a row from the current line. |
def merge_option_and_config_str(cls, option_name, config, options):
"""
Utility method to merge an option and config, with the option taking "
precedence
"""
opt = getattr(options, option_name, None)
if opt:
config.set(CONFIG_SECTION_NAME, option_name, opt)
... | Utility method to merge an option and config, with the option taking "
precedence |
def _retry(n, f, *args, **kwargs):
'''Try to call f(*args, **kwargs) "n" times before giving up. Wait
2**n seconds before retries.'''
for i in range(n):
try:
return f(*args, **kwargs)
except Exception as exc:
if i == n - 1:
log.error(
... | Try to call f(*args, **kwargs) "n" times before giving up. Wait
2**n seconds before retries. |
def glob(dpath, pattern=None, recursive=False, with_files=True, with_dirs=True,
maxdepth=None, exclude_dirs=[], fullpath=True, **kwargs):
r"""
Globs directory for pattern
DEPRICATED:
use pathlib.glob instead
Args:
dpath (str): directory path or pattern
pattern (str or ... | r"""
Globs directory for pattern
DEPRICATED:
use pathlib.glob instead
Args:
dpath (str): directory path or pattern
pattern (str or list): pattern or list of patterns
(use only if pattern is not in dpath)
recursive (bool): (default = False)
with_files (bo... |
def get_structure(atoms, cls=None):
"""
Returns pymatgen structure from ASE Atoms.
Args:
atoms: ASE Atoms object
cls: The Structure class to instantiate (defaults to pymatgen structure)
Returns:
Equivalent pymatgen.core.structure.Structure
""... | Returns pymatgen structure from ASE Atoms.
Args:
atoms: ASE Atoms object
cls: The Structure class to instantiate (defaults to pymatgen structure)
Returns:
Equivalent pymatgen.core.structure.Structure |
def convert_items(self, items):
"""Generator like `convert_iterable`, but for 2-tuple iterators."""
return ((key, self.convert(value, self)) for key, value in items) | Generator like `convert_iterable`, but for 2-tuple iterators. |
def cli(verbose):
"""
Floyd CLI interacts with FloydHub server and executes your commands.
More help is available under each command listed below.
"""
floyd.floyd_host = floyd.floyd_web_host = "https://dev.floydhub.com"
floyd.tus_server_endpoint = "https://upload-v2-dev.floydhub.com/api/v1/uploa... | Floyd CLI interacts with FloydHub server and executes your commands.
More help is available under each command listed below. |
def _layout_position(elem):
""" Return either (), (0, alignment), (row, column, rowspan, colspan) or
(row, column, rowspan, colspan, alignment) depending on the type of layout
and its configuration. The result will be suitable to use as arguments to
the layout.
"""
row = elem.attrib.get('row')... | Return either (), (0, alignment), (row, column, rowspan, colspan) or
(row, column, rowspan, colspan, alignment) depending on the type of layout
and its configuration. The result will be suitable to use as arguments to
the layout. |
def parse(self, filelike, filename):
"""Parse the given file-like object and return its Module object."""
self.log = log
self.source = filelike.readlines()
src = "".join(self.source)
# This may raise a SyntaxError:
compile(src, filename, "exec")
self.stream = Toke... | Parse the given file-like object and return its Module object. |
def download_to_shared_memory(self, slices, location=None):
"""
Download images to a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are respon... | Download images to a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for managing the lifecycle of the
shared memory. CloudVolum... |
def upgrade(self): # pragma: no cover
""" Upgrade account to life time member
"""
assert callable(self.blockchain.upgrade_account)
return self.blockchain.upgrade_account(account=self) | Upgrade account to life time member |
def sample_t(self,n):
"""
NAME:
sample_t
PURPOSE:
generate a stripping time (time since stripping); simple implementation could be replaced by more complicated distributions in sub-classes of streamdf
INPUT:
n - number of points to return
OUTPUT:... | NAME:
sample_t
PURPOSE:
generate a stripping time (time since stripping); simple implementation could be replaced by more complicated distributions in sub-classes of streamdf
INPUT:
n - number of points to return
OUTPUT:
array of n stripping times
... |
def minimum_distance2(hull_a, center_a, hull_b, center_b):
'''Return the minimum distance or 0 if overlap between 2 convex hulls
hull_a - list of points in clockwise direction
center_a - a point within the hull
hull_b - list of points in clockwise direction
center_b - a point within the hull
... | Return the minimum distance or 0 if overlap between 2 convex hulls
hull_a - list of points in clockwise direction
center_a - a point within the hull
hull_b - list of points in clockwise direction
center_b - a point within the hull |
def switch_types(self):
"""
Gets the SwitchTypes API client.
Returns:
SwitchTypes:
"""
if not self.__switch_types:
self.__switch_types = SwitchTypes(self.__connection)
return self.__switch_types | Gets the SwitchTypes API client.
Returns:
SwitchTypes: |
def process(self, metric):
"""
Process a metric and send it to RMQ pub socket
"""
for rmq_server in self.connections.keys():
try:
if ((self.connections[rmq_server] is None or
self.connections[rmq_server].is_open is False)):
... | Process a metric and send it to RMQ pub socket |
def _generate_div_id_chart(prefix="chart_id", digits=8):
"""Generate a random id for div chart.
"""
choices = (random.randrange(0, 52) for _ in range(digits))
return prefix + "".join((string.ascii_letters[x] for x in choices)) | Generate a random id for div chart. |
def as_list(self):
"""
Return an *ordered* list of the source attributes
"""
self._sanitise()
l = []
for name in self.names:
l.append(getattr(self, name))
return l | Return an *ordered* list of the source attributes |
def shutdown(self, save=False, nosave=False):
"""Shutdown the Redis server. If Redis has persistence configured,
data will be flushed before shutdown. If the "save" option is set,
a data flush will be attempted even if there is no persistence
configured. If the "nosave" option is set,... | Shutdown the Redis server. If Redis has persistence configured,
data will be flushed before shutdown. If the "save" option is set,
a data flush will be attempted even if there is no persistence
configured. If the "nosave" option is set, no data flush will be
attempted. The "save" and... |
def _AddWebPageCriteria(client, ad_group_id):
"""Adds a web page criterion to target Dynamic Search Ads.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID of the ad group the criteria is being added to.
"""
ad_group_criterion_service = client.GetService('AdGroupCriterionService',
... | Adds a web page criterion to target Dynamic Search Ads.
Args:
client: an AdWordsClient instance.
ad_group_id: an integer ID of the ad group the criteria is being added to. |
def to_float(*args):
"""
cast numpy arrays to float32
if there's more than one, return an array
"""
floats = [np.array(a, dtype=np.float32) for a in args]
return floats[0] if len(floats) == 1 else floats | cast numpy arrays to float32
if there's more than one, return an array |
def _render_filenames(filenames, zip_file, saltenv, template):
'''
Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the
files under the paths they ultimately point to) according to the markup
format provided by :param:`template`.
'''
if not template:
return (f... | Process markup in the :param:`filenames` and :param:`zipfile` variables (NOT the
files under the paths they ultimately point to) according to the markup
format provided by :param:`template`. |
def emit_code_from_ir(ir_blocks, compiler_metadata):
"""Return a MATCH query string from a list of IR blocks."""
gremlin_steps = (
block.to_gremlin()
for block in ir_blocks
)
# OutputSource blocks translate to empty steps.
# Discard such empty steps so we don't end up with an incorr... | Return a MATCH query string from a list of IR blocks. |
def get_security_repository(self):
""" Security repository """
from .repositories import SecurityRepository
if not self.security_repo:
self.security_repo = SecurityRepository(self.session)
return self.security_repo | Security repository |
def _sufficient_gaps(self,
startdate: datetime.date,
enddate: datetime.date,
requiredgaps: List[datetime.timedelta],
flexibility: int) -> Tuple[bool, Optional[Interval]]:
"""
Are there sufficient gaps (sp... | Are there sufficient gaps (specified by ``requiredgaps``) in the date
range specified? This is a worker function for :meth:`sufficient_gaps`. |
def info(name):
'''
Return user information
CLI Example:
.. code-block:: bash
salt '*' user.info root
'''
ret = {}
try:
data = pwd.getpwnam(name)
ret['gid'] = data.pw_gid
ret['groups'] = list_groups(name)
ret['home'] = data.pw_dir
ret['name'... | Return user information
CLI Example:
.. code-block:: bash
salt '*' user.info root |
def async_or_fail(self, **options):
"""
Attempt to call self.apply_async, but if that fails with an exception,
we fake the task completion using the exception as the result. This
allows us to seamlessly handle errors on task creation the same way we
handle errors when a task runs... | Attempt to call self.apply_async, but if that fails with an exception,
we fake the task completion using the exception as the result. This
allows us to seamlessly handle errors on task creation the same way we
handle errors when a task runs, simplifying the user interface. |
def _find_attrNS(E, namespaceURI, localName):
'''namespaceURI
localName
'''
try:
v = E.getAttributeNS(namespaceURI, localName)
if v: return v
except: pass
return None | namespaceURI
localName |
def _reshape_n_vecs(self):
"""return list of arrays, each array represents a different m mode"""
lst = []
sl = slice(None, None, None)
lst.append(self.__getitem__((sl, 0)))
for m in xrange(1, self.mmax + 1):
lst.append(self.__getitem__((sl, -m)))
... | return list of arrays, each array represents a different m mode |
def _propagate_incompatibility(
self, incompatibility
): # type: (Incompatibility) -> Union[str, _conflict, None]
"""
If incompatibility is almost satisfied by _solution, adds the
negation of the unsatisfied term to _solution.
If incompatibility is satisfied by _solution, r... | If incompatibility is almost satisfied by _solution, adds the
negation of the unsatisfied term to _solution.
If incompatibility is satisfied by _solution, returns _conflict. If
incompatibility is almost satisfied by _solution, returns the
unsatisfied term's package name.
Otherw... |
def max_runs_reached(self):
"""
:return: whether all file paths have been processed max_runs times
"""
if self._max_runs == -1: # Unlimited runs.
return False
for file_path in self._file_paths:
if self._run_count[file_path] < self._max_runs:
... | :return: whether all file paths have been processed max_runs times |
def init_module(filesystem):
"""Initializes the fake module with the fake file system."""
# pylint: disable=protected-access
FakePath.filesystem = filesystem
FakePathlibModule.PureWindowsPath._flavour = _FakeWindowsFlavour(
filesystem)
FakePathlibModule.PurePosixPath._flavour = _FakePosixFla... | Initializes the fake module with the fake file system. |
def retry_on_exception(func, max_retries, exception_types, backoff_func=lambda n: 0):
"""Retry a callable against a set of exceptions, optionally sleeping between retries.
:param callable func: The callable to retry.
:param int max_retries: The maximum number of times to attempt running the function.
:param tu... | Retry a callable against a set of exceptions, optionally sleeping between retries.
:param callable func: The callable to retry.
:param int max_retries: The maximum number of times to attempt running the function.
:param tuple exception_types: The types of exceptions to catch for retry.
:param callable backoff_... |
def reject(self):
"""Sets current s value to the last accepted value"""
self.stochastic.revert()
# Increment rejected count
self.rejected[self.current_kernel] += 1
if self.verbose > 1:
print_(
self._id,
"rejected, reverting to value =... | Sets current s value to the last accepted value |
def of_directory(directory: str, root_directory: str = None) -> dict:
"""
Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param ro... | Returns a dictionary containing status entries recursively for all files
within the specified directory and its descendant directories.
:param directory:
The directory in which to retrieve status information
:param root_directory:
Directory relative to which all file status paths are relate... |
def s3_request(func: Callable):
"""
Wrapper function for s3 requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except ClientError as exc:
if int(exc.resp... | Wrapper function for s3 requests in order to create more helpful error
messages. |
def gen_tokens(self):
"""
>>> list(Program("ls").gen_tokens())
['ls']
>>> list(Program("ls -a").gen_tokens())
['ls', '-a']
>>> list(Program("cd /; pwd").gen_tokens())
['cd', '/', None, 'pwd']
>>> list(Program("'cd /; pwd'").gen_tokens())
['cd /; pw... | >>> list(Program("ls").gen_tokens())
['ls']
>>> list(Program("ls -a").gen_tokens())
['ls', '-a']
>>> list(Program("cd /; pwd").gen_tokens())
['cd', '/', None, 'pwd']
>>> list(Program("'cd /; pwd'").gen_tokens())
['cd /; pwd'] |
def fetch(backend_class, backend_args, category, filter_classified=False,
manager=None):
"""Fetch items using the given backend.
Generator to get items using the given backend class. When
an archive manager is given, this function will store
the fetched items in an `Archive`. If an exception ... | Fetch items using the given backend.
Generator to get items using the given backend class. When
an archive manager is given, this function will store
the fetched items in an `Archive`. If an exception is raised,
this archive will be removed to avoid corrupted archives.
The parameters needed to ini... |
def load_config_file(self, location):
"""
Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object.
"""
location = coerce_location(loca... | Load a rotation scheme and other options from a configuration file.
:param location: Any value accepted by :func:`coerce_location()`.
:returns: The configured or given :class:`Location` object. |
def document_path_path(cls, project, database, document_path):
"""Return a fully-qualified document_path string."""
return google.api_core.path_template.expand(
"projects/{project}/databases/{database}/documents/{document_path=**}",
project=project,
database=database,... | Return a fully-qualified document_path string. |
def delete_parent(sender, instance, **kwargs):
"""
When the given task instance is deleted, delete also the corresponding item
relations.
"""
ItemRelation.objects.filter(child_id=instance.item_id).delete() | When the given task instance is deleted, delete also the corresponding item
relations. |
def toggle_comments(self):
"""
Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool
"""
if not self.__comment_marker:
return True
cursor = self.textCursor()
if not cursor.hasSelection():
cursor.m... | Toggles comments on the document selected lines.
:return: Method success.
:rtype: bool |
def get(self, key):
"""
Retrieve object indexed by <key>
"""
try:
try:
obj = self.bucket.get(key)
except couchbase.exception.MemcachedError, inst:
if str(inst) == "Memcached error #1: Not found":
# for some reason the py cb client raises an error when
... | Retrieve object indexed by <key> |
def priority(self):
"""
Applicable for all platforms, where the schemes, that are integrated
with your environment, does not fit.
"""
try:
__import__('argon2.low_level')
except ImportError: # pragma: no cover
raise RuntimeError("argon2_cffi pac... | Applicable for all platforms, where the schemes, that are integrated
with your environment, does not fit. |
def _walk_librispeech_dir(directory):
"""Walk a Librispeech directory and yield examples."""
directory = os.path.join(directory, "LibriSpeech")
for path, _, files in tf.io.gfile.walk(directory):
if not files:
continue
transcript_file = [f for f in files if f.endswith(".txt")]
if not transcript_... | Walk a Librispeech directory and yield examples. |
def onecmd_plus_hooks(self, line):
''' Trigger hooks after command. '''
if not line:
return self.emptyline()
return Cmd.onecmd_plus_hooks(self, line) | Trigger hooks after command. |
def wkb(self):
"""
Get the geometry as an (E)WKB.
"""
return self._to_wkb(use_srid=True, dimz=self.dimz, dimm=self.dimm) | Get the geometry as an (E)WKB. |
def GetUnreachableHosts(hostnames, ssh_key):
""" Returns list of hosts unreachable via ssh. """
ssh_status = AreHostsReachable(hostnames, ssh_key)
assert(len(hostnames) == len(ssh_status))
nonresponsive_hostnames = [host for (host, ssh_ok) in
zip(hostnames, ssh_status) if not ssh_ok... | Returns list of hosts unreachable via ssh. |
def _make_fits(self):
"""Generates the data fits for any variables set for fitting in the shell."""
a = self.tests[self.active]
args = self.curargs
#We need to generate a fit for the data if there are any fits specified.
if len(args["fits"]) > 0:
for fit in list(args[... | Generates the data fits for any variables set for fitting in the shell. |
def geometric_sums(self, beta, x_t):
r"""
Forecast the geometric sums
.. math::
S_x := E \Big[ \sum_{j=0}^{\infty} \beta^j x_{t+j} | x_t \Big]
S_y := E \Big[ \sum_{j=0}^{\infty} \beta^j y_{t+j} | x_t \Big]
Parameters
----------
beta : scalar(fl... | r"""
Forecast the geometric sums
.. math::
S_x := E \Big[ \sum_{j=0}^{\infty} \beta^j x_{t+j} | x_t \Big]
S_y := E \Big[ \sum_{j=0}^{\infty} \beta^j y_{t+j} | x_t \Big]
Parameters
----------
beta : scalar(float)
Discount factor, in [0, 1)
... |
def _solve_msm_eigensystem(transmat, k):
"""Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:... | Find the dominant eigenpairs of an MSM transition matrix
Parameters
----------
transmat : np.ndarray, shape=(n_states, n_states)
The transition matrix
k : int
The number of eigenpairs to find.
Notes
-----
Normalize the left (:math:`\phi`) and right (:math:``\psi``) eigenfun... |
def run_parallel(self):
"""Perform the computation in parallel, reading results from the output
queue and passing them to ``process_result``.
"""
try:
self.start_parallel()
result = self.empty_result(*self.context)
while self.num_processes > 0:
... | Perform the computation in parallel, reading results from the output
queue and passing them to ``process_result``. |
def axis_bounds(self) -> Dict[str, Tuple[float, float]]:
""" The (minimum, maximum) bounds for each axis. """
return {ax: (0, pos+.05) for ax, pos
in self._smoothie_driver.homed_position.items()
if ax not in 'BC'} | The (minimum, maximum) bounds for each axis. |
def categories_to_fetch(self, categories_to_fetch):
"""Sets the categories_to_fetch of this GCPConfiguration.
A list of Google Cloud Platform (GCP) services (such as ComputeEngine, PubSub, etc) from which to pull metrics. Allowable values are APPENGINE, BIGQUERY, BIGTABLE, CLOUDFUNCTIONS, CLOUDIOT, CL... | Sets the categories_to_fetch of this GCPConfiguration.
A list of Google Cloud Platform (GCP) services (such as ComputeEngine, PubSub, etc) from which to pull metrics. Allowable values are APPENGINE, BIGQUERY, BIGTABLE, CLOUDFUNCTIONS, CLOUDIOT, CLOUDSQL, CLOUDTASKS, COMPUTE, CONTAINER, DATAFLOW, DATASTORE, FI... |
def smooth(x,window_len,window='bartlett'):
"""smooth the data using a sliding window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by padding the beginning and the end of the signal
with average of the first (last) ten values of... | smooth the data using a sliding window with requested size.
This method is based on the convolution of a scaled window with the signal.
The signal is prepared by padding the beginning and the end of the signal
with average of the first (last) ten values of the signal, to evoid jumps
at the beggining/en... |
def _analyze_pages_with_partial_read(self):
"""! @brief Estimate how many pages are the same by reading data.
Pages are analyzed by reading the first 32 bytes and comparing with data to be
programmed.
"""
# Quickly estimate how many pages are the same as current flash contents.
... | ! @brief Estimate how many pages are the same by reading data.
Pages are analyzed by reading the first 32 bytes and comparing with data to be
programmed. |
def env_check(self, *args, **kwargs):
"""
This method provides a common entry for any checks on the
environment (input / output dirs, etc)
"""
b_status = True
str_error = ''
if not len(self.str_outputDir):
b_status = False
str_error ... | This method provides a common entry for any checks on the
environment (input / output dirs, etc) |
def __join_connections(self):
"""Wait for all connections to close. There are no side-effects here.
We just want to try and leave -after- everything has closed, in
general.
"""
interval_s = nsq.config.client.CONNECTION_CLOSE_AUDIT_WAIT_S
graceful_wait_s = nsq.config.cl... | Wait for all connections to close. There are no side-effects here.
We just want to try and leave -after- everything has closed, in
general. |
def _estimate_param_scan_worker(estimator, params, X, evaluate, evaluate_args,
failfast, return_exceptions):
""" Method that runs estimation for several parameter settings.
Defined as a worker for parallelization
"""
# run estimation
model = None
try: # catch a... | Method that runs estimation for several parameter settings.
Defined as a worker for parallelization |
def calc_circuit_breaker_position(self, debug=False):
""" Calculates the optimal position of a circuit breaker on route.
Parameters
----------
debug: bool, defaults to False
If True, prints process information.
Returns
-------
int
... | Calculates the optimal position of a circuit breaker on route.
Parameters
----------
debug: bool, defaults to False
If True, prints process information.
Returns
-------
int
position of circuit breaker on route (index of last node ... |
def split_line(self, line):
""" Try to do pure shlex.split unless it can't parse the line. In that
case we trim the input line until shlex can split the args and tack the
unparsable portion on as the last argument. """
remainder = []
while True:
try:
a... | Try to do pure shlex.split unless it can't parse the line. In that
case we trim the input line until shlex can split the args and tack the
unparsable portion on as the last argument. |
def _token_list_matches_tree(self, token_list):
"""
Returns whether the token list matches the HTML tree
:param selector: A Token list to check
:type selector: list of Token objects
:returns: True if the token list has matches in self.tree
:rtype: bool
"""
... | Returns whether the token list matches the HTML tree
:param selector: A Token list to check
:type selector: list of Token objects
:returns: True if the token list has matches in self.tree
:rtype: bool |
def feed(self, data):
"""
Feed data to the parser.
"""
assert isinstance(data, binary_type)
for b in iterbytes(data):
self._parser.send(int2byte(b)) | Feed data to the parser. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.