Search is not available for this dataset
text stringlengths 75 104k |
|---|
def sat2in4(pos, neg=tuple(), vartype=dimod.BINARY, name='2-in-4'):
"""Two-in-four (2-in-4) satisfiability.
Args:
pos (iterable):
Variable labels, as an iterable, for non-negated variables of the constraint.
Exactly four variables are specified by `pos` and `neg` together.
... |
def random_2in4sat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):
"""Random two-in-four (2-in-4) constraint satisfaction problem.
Args:
num_variables (integer): Number of variables (at least four).
num_clauses (integer): Number of constraints that together constitute the
... |
def random_xorsat(num_variables, num_clauses, vartype=dimod.BINARY, satisfiable=True):
"""Random XOR constraint satisfaction problem.
Args:
num_variables (integer): Number of variables (at least three).
num_clauses (integer): Number of constraints that together constitute the
constr... |
def kwarg_decorator(func):
"""
Turns a function that accepts a single arg and some kwargs in to a
decorator that can optionally be called with kwargs:
.. code-block:: python
@kwarg_decorator
def my_decorator(func, bar=True, baz=None):
...
@my_decorator
def ... |
def signature_matches(func, args=(), kwargs={}):
"""
Work out if a function is callable with some args or not.
"""
try:
sig = inspect.signature(func)
sig.bind(*args, **kwargs)
except TypeError:
return False
else:
return True |
def last_arg_decorator(func):
"""
Allows a function to be used as either a decorator with args, or called as
a normal function.
@last_arg_decorator
def register_a_thing(foo, func, bar=True):
..
# Called as a decorator
@register_a_thing("abc", bar=False)
def my_func():
.... |
def register_chooser(self, chooser, **kwargs):
"""Adds a model chooser definition to the registry."""
if not issubclass(chooser, Chooser):
return self.register_simple_chooser(chooser, **kwargs)
self.choosers[chooser.model] = chooser(**kwargs)
return chooser |
def register_simple_chooser(self, model, **kwargs):
"""
Generates a model chooser definition from a model, and adds it to the
registry.
"""
name = '{}Chooser'.format(model._meta.object_name)
attrs = {'model': model}
attrs.update(kwargs)
chooser = type(nam... |
def instance_from_str(instance_str):
"""
Given an instance string in the form "app.Model:pk", returns a tuple of
``(model, instance)``. If the pk part is empty, ``instance`` will be
``None``. Raises ``ValueError`` on invalid model strings or missing
instances.
"""
match = instance_str_re.mat... |
def formatter(self, api_client, data, newval):
"""Get audio-related fields
Try to find fields for the audio url for specified preferred quality
level, or next-lowest available quality url otherwise.
"""
url_map = data.get("audioUrlMap")
audio_url = data.get("audioUrl")
... |
def formatter(self, api_client, data, newval):
"""Parse additional url fields and map them to inputs
Attempt to create a dictionary with keys being user input, and
response being the returned URL
"""
if newval is None:
return None
user_param = data['_paramAd... |
def from_json_list(cls, api_client, data):
"""Convert a list of JSON values to a list of models
"""
return [cls.from_json(api_client, item) for item in data] |
def populate_fields(api_client, instance, data):
"""Populate all fields of a model with data
Given a model with a PandoraModel superclass will enumerate all
declared fields on that model and populate the values of their Field
and SyntheticField classes. All declared fields will have a v... |
def from_json(cls, api_client, data):
"""Convert one JSON value to a model object
"""
self = cls(api_client)
PandoraModel.populate_fields(api_client, self, data)
return self |
def _base_repr(self, and_also=None):
"""Common repr logic for subclasses to hook
"""
items = [
"=".join((key, repr(getattr(self, key))))
for key in sorted(self._fields.keys())]
if items:
output = ", ".join(items)
else:
output = Non... |
def _send_cmd(self, cmd):
"""Write command to remote process
"""
self._process.stdin.write("{}\n".format(cmd).encode("utf-8"))
self._process.stdin.flush() |
def _ensure_started(self):
"""Ensure player backing process is started
"""
if self._process and self._process.poll() is None:
return
if not getattr(self, "_cmd"):
raise RuntimeError("Player command is not configured")
log.debug("Starting playback command... |
def play(self, song):
"""Play a new song from a Pandora model
Returns once the stream starts but does not shut down the remote audio
output backend process. Calls the input callback when the user has
input.
"""
self._callbacks.play(song)
self._load_track(song)
... |
def play_station(self, station):
"""Play the station until something ends it
This function will run forever until termintated by calling
end_station.
"""
for song in iterate_forever(station.get_playlist):
try:
self.play(song)
except StopIt... |
def _post_start(self):
"""Set stdout to non-blocking
VLC does not always return a newline when reading status so in order to
be lazy and still use the read API without caring about how much output
there is we switch stdout to nonblocking mode and just read a large
chunk of datin... |
def station_selection_menu(self, error=None):
"""Format a station menu and make the user select a station
"""
self.screen.clear()
if error:
self.screen.print_error("{}\n".format(error))
for i, station in enumerate(self.stations):
i = "{:>3}".format(i)
... |
def play(self, song):
"""Play callback
"""
if song.is_ad:
print("{} ".format(Colors.cyan("Advertisement")))
else:
print("{} by {}".format(Colors.cyan(song.song_name),
Colors.yellow(song.artist_name))) |
def input(self, input, song):
"""Input callback, handles key presses
"""
try:
cmd = getattr(self, self.CMD_MAP[input][1])
except (IndexError, KeyError):
return self.screen.print_error(
"Invalid command {!r}!".format(input))
cmd(song) |
def retries(max_tries, exceptions=(Exception,)):
"""Function decorator implementing retrying logic.
exceptions: A tuple of exception classes; default (Exception,)
The decorator will call the function up to max_tries times if it raises
an exception.
By default it catches instances of the Exception... |
def delay_exponential(base, growth_factor, attempts):
"""Calculate time to sleep based on exponential function.
The format is::
base * growth_factor ^ (attempts - 1)
If ``base`` is set to 'rand' then a random number between
0 and 1 will be used as the base.
Base must be greater than 0, oth... |
def iterate_forever(func, *args, **kwargs):
"""Iterate over a finite iterator forever
When the iterator is exhausted will call the function again to generate a
new iterator and keep iterating.
"""
output = func(*args, **kwargs)
while True:
try:
playlist_item = next(output)
... |
def get_integer(prompt):
"""Gather user input and convert it to an integer
Will keep trying till the user enters an interger or until they ^C the
program.
"""
while True:
try:
return int(input(prompt).strip())
except ValueError:
... |
def collect(self, dataset_readers_list):
"""collect results
Returns:
a list of results
"""
ret = [ ]
for i, collector in enumerate(self.components):
report = ProgressReport(name='collecting results', done=(i + 1), total=len(self.components))
... |
def open(self):
"""open the drop box
You need to call this method before starting putting packages.
Returns
-------
None
"""
self.workingArea.open()
self.runid_pkgidx_map = { }
self.runid_to_return = deque() |
def put(self, package):
"""put a task
This method places a task in the working area and have the
dispatcher execute it.
If you need to put multiple tasks, it can be much faster to
use `put_multiple()` than to use this method multiple times
depending of the dispatcher.
... |
def put_multiple(self, packages):
"""put tasks
This method places multiple tasks in the working area and have
the dispatcher execute them.
Parameters
----------
packages : list(callable)
A list of tasks
Returns
-------
list(int)
... |
def receive(self):
"""return pairs of package indices and results of all tasks
This method waits until all tasks finish.
Returns
-------
list
A list of pairs of package indices and results
"""
ret = [ ] # a list of (pkgid, result)
while Tru... |
def poll(self):
"""return pairs of package indices and results of finished tasks
This method does not wait for tasks to finish.
Returns
-------
list
A list of pairs of package indices and results
"""
self.runid_to_return.extend(self.dispatcher.poll... |
def receive_one(self):
"""return a pair of a package index and result of a task
This method waits until a tasks finishes. It returns `None` if
no task is running.
Returns
-------
tuple or None
A pair of a package index and result. `None` if no tasks
... |
def run_multiple(self, eventLoops):
"""run the event loops in the background.
Args:
eventLoops (list): a list of event loops to run
"""
self.nruns += len(eventLoops)
return self.communicationChannel.put_multiple(eventLoops) |
def poll(self):
"""Return pairs of run ids and results of finish event loops.
"""
ret = self.communicationChannel.receive_finished()
self.nruns -= len(ret)
return ret |
def receive_one(self):
"""Return a pair of a run id and a result.
This method waits until an event loop finishes.
This method returns None if no loop is running.
"""
if self.nruns == 0:
return None
ret = self.communicationChannel.receive_one()
if ret ... |
def receive(self):
"""Return pairs of run ids and results.
This method waits until all event loops finish
"""
ret = self.communicationChannel.receive_all()
self.nruns -= len(ret)
if self.nruns > 0:
import logging
logger = logging.getLogger(__name_... |
def end(self):
"""wait until all event loops end and returns the results.
"""
results = self.communicationChannel.receive()
if self.nruns != len(results):
import logging
logger = logging.getLogger(__name__)
# logger.setLevel(logging.DEBUG)
... |
def key_vals_dict_to_tuple_list(key_vals_dict, fill=float('nan')):
"""Convert ``key_vals_dict`` to `tuple_list``.
Args:
key_vals_dict (dict): The first parameter.
fill: a value to fill missing data
Returns:
A list of tuples
"""
tuple_list = [ ]
if not key_vals_dict: ... |
def open(self):
"""Open the working area
Returns
-------
None
"""
self.path = self._prepare_dir(self.topdir)
self._copy_executable(area_path=self.path)
self._save_logging_levels(area_path=self.path)
self._put_python_modules(modules=self.python_mo... |
def put_package(self, package):
"""Put a package
Parameters
----------
package :
a task package
Returns
-------
int
A package index
"""
self.last_package_index += 1
package_index = self.last_package_index
... |
def collect_result(self, package_index):
"""Collect the result of a task
Parameters
----------
package_index :
a package index
Returns
-------
obj
The result of the task
"""
result_fullpath = self.result_fullpath(package... |
def package_fullpath(self, package_index):
"""Returns the full path of the package
This method returns the full path to the package. This method
simply constructs the path based on the convention and doesn't
check if the package actually exists.
Parameters
----------
... |
def result_relpath(self, package_index):
"""Returns the relative path of the result
This method returns the path to the result relative to the
top dir of the working area. This method simply constructs the
path based on the convention and doesn't check if the result
actually exi... |
def result_fullpath(self, package_index):
"""Returns the full path of the result
This method returns the full path to the result. This method
simply constructs the path based on the convention and doesn't
check if the result actually exists.
Parameters
----------
... |
def run_multiple(self, workingArea, package_indices):
"""Submit multiple jobs
Parameters
----------
workingArea :
A workingArea
package_indices : list(int)
A list of package indices
Returns
-------
list(str)
The list o... |
def poll(self):
"""Return the run IDs of the finished jobs
Returns
-------
list(str)
The list of the run IDs of the finished jobs
"""
clusterids = clusterprocids2clusterids(self.clusterprocids_outstanding)
clusterprocid_status_list = query_status_fo... |
def wait(self):
"""Wait until all jobs finish and return the run IDs of the finished jobs
Returns
-------
list(str)
The list of the run IDs of the finished jobs
"""
sleep = 5
while True:
if self.clusterprocids_outstanding:
... |
def failed_runids(self, runids):
"""Provide the run IDs of failed jobs
Returns
-------
None
"""
# remove failed clusterprocids from self.clusterprocids_finished
# so that len(self.clusterprocids_finished)) becomes the number
# of the successfully finis... |
def atpbar(iterable, name=None):
"""Progress bar
"""
try:
len_ = len(iterable)
except TypeError:
logger = logging.getLogger(__name__)
logging.warning('length is unknown: {!r}'.format(iterable))
logging.warning('atpbar is turned off')
return iterable
if name ... |
def getArrays(self, tree, branchName):
"""return the array.array objects for the branch and its counter branch
This method returns a pair of the array.array objects. The first one is
for the given tree and branch name. The second one is for its counter
branch. The second one will be Non... |
def begin(self):
"""begin
"""
if self.isopen: return
self.dropbox.open()
self.isopen = True |
def put(self, task, *args, **kwargs):
"""put a task and its arguments
If you need to put multiple tasks, it can be faster to put
multiple tasks with `put_multiple()` than to use this method
multiple times.
Parameters
----------
task : a function
A fu... |
def put_multiple(self, task_args_kwargs_list):
"""put a list of tasks and their arguments
This method can be used to put multiple tasks at once. Calling
this method once with multiple tasks can be much faster than
calling `put()` multiple times.
Parameters
----------
... |
def receive_finished(self):
"""return a list of pairs of IDs and results of finished tasks.
This method doesn't wait for tasks to finish. It returns IDs
and results which have already finished.
Returns
-------
list
A list of pairs of IDs and results
... |
def receive_one(self):
"""return a pair of an ID and a result of a task.
This method waits for a task to finish.
Returns
-------
An ID and a result of a task. `None` if no task is running.
"""
if not self.isopen:
logger = logging.getLogger(__name__)... |
def receive_all(self):
"""return a list of pairs of IDs and results of all tasks.
This method waits for all tasks to finish.
Returns
-------
list
A list of pairs of IDs and results
"""
if not self.isopen:
logger = logging.getLogger(__nam... |
def receive(self):
"""return a list results of all tasks.
This method waits for all tasks to finish.
Returns
-------
list
A list of results of the tasks. The results are sorted in
the order in which the tasks are put.
"""
pkgidx_result_p... |
def end(self):
"""end
"""
if not self.isopen: return
self.dropbox.close()
self.isopen = False |
def expand_path_cfg(path_cfg, alias_dict={ }, overriding_kargs={ }):
"""expand a path config
Args:
path_cfg (str, tuple, dict): a config for path
alias_dict (dict): a dict for aliases
overriding_kargs (dict): to be used for recursive call
"""
if isinstance(path_cfg, str):
... |
def _expand_str(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a string
"""
if path_cfg in alias_dict:
# e.g., path_cfg = 'var_cut'
return _expand_str_alias(path_cfg, alias_dict, overriding_kargs)
# e.g., path_cfg = 'ev : {low} <= ev.var[0] < {high}'
ret... |
def _expand_str_alias(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a string
Args:
path_cfg (str): an alias
alias_dict (dict):
overriding_kargs (dict):
"""
# e.g.,
# path_cfg = 'var_cut'
new_path_cfg = alias_dict[path_cfg]
# e.g., ('ev :... |
def _expand_tuple(path_cfg, alias_dict, overriding_kargs):
"""expand a path config given as a tuple
"""
# e.g.,
# path_cfg = ('ev : {low} <= ev.var[0] < {high}', {'low': 10, 'high': 200})
# overriding_kargs = {'alias': 'var_cut', 'name': 'var_cut25', 'low': 25}
new_path_cfg = path_cfg[0]
... |
def poll(self):
"""check if the jobs are running and return a list of pids for
finished jobs
"""
finished_procs = [p for p in self.running_procs if p.poll() is not None]
self.running_procs = collections.deque([p for p in self.running_procs if p not in finished_procs])
f... |
def wait(self):
"""wait until all jobs finish and return a list of pids
"""
finished_pids = [ ]
while self.running_procs:
finished_pids.extend(self.poll())
return finished_pids |
def getVector(self, tree, branchName):
"""return the ROOT.vector object for the branch.
"""
if (tree, branchName) in self.__class__.addressDict:
return self.__class__.addressDict[(tree, branchName)]
itsVector = self._getVector(tree, branchName)
self.__class__.addre... |
def build_parallel(parallel_mode, quiet=True, processes=4,
user_modules=None, dispatcher_options=None):
"""initializes `Parallel`
Parameters
----------
parallel_mode : str
"multiprocessing" (default), "htcondor" or "subprocess"
quiet : bool, optional
if True, prog... |
def configure(self, component, all_dependencies):
''' Ensure all config-time files have been generated. Return a
dictionary of generated items.
'''
r = {}
builddir = self.buildroot
# only dependencies which are actually valid can contribute to the
# config d... |
def generateRecursive(self, component, all_components, builddir=None, modbuilddir=None, processed_components=None, application=None):
''' generate top-level CMakeLists for this component and its
dependencies: the CMakeLists are all generated in self.buildroot,
which MUST be out-of-source... |
def _validateListedSubdirsExist(self, component):
''' Return true if all the subdirectories which this component lists in
its module.json file exist (although their validity is otherwise
not checked).
If they don't, warning messages are printed.
'''
lib_subdi... |
def _listSubDirectories(self, component, toplevel):
''' return: {
manual: [list of subdirectories with manual CMakeLists],
auto: [list of pairs: (subdirectories name to autogenerate, a list of source files in that dir)],
bin: {dictionary of subdirectory name ... |
def _getConfigData(self, all_dependencies, component, builddir, build_info_header_path):
''' returns (path_to_config_header, cmake_set_definitions) '''
# ordered_json, , read/write ordered json, internal
from yotta.lib import ordered_json
add_defs_header = ''
set_definitions = ''... |
def getBuildInfo(self, sourcedir, builddir):
''' Write the build info header file, and return (path_to_written_header, set_cmake_definitions) '''
cmake_defs = ''
preproc_defs = '// yotta build info, #include YOTTA_BUILD_INFO_HEADER to access\n'
# standard library modules
import d... |
def generate(
self, builddir, modbuilddir, component, active_dependencies, immediate_dependencies, all_dependencies, application, toplevel
):
''' active_dependencies is the dictionary of components that need to be
built for this component, but will not already have been built for... |
def _handleAuth(fn):
''' Decorator to re-try API calls after asking the user for authentication. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
# if yotta is being run noninteractively, then we never retry, but we
# do call auth.authorizeUser, so that a login URL can be displayed:
... |
def _getTags(repo):
''' return a dictionary of {tag: tarball_url}'''
logger.debug('get tags for %s', repo)
g = Github(settings.getProperty('github', 'authtoken'))
repo = g.get_repo(repo)
tags = repo.get_tags()
logger.debug('tags for %s: %s', repo, [t.name for t in tags])
return {t.name: _ens... |
def _getTipArchiveURL(repo):
''' return a string containing a tarball url '''
g = Github(settings.getProperty('github', 'authtoken'))
repo = g.get_repo(repo)
return repo.get_archive_link('tarball') |
def _getCommitArchiveURL(repo, commit):
''' return a string containing a tarball url '''
g = Github(settings.getProperty('github', 'authtoken'))
repo = g.get_repo(repo)
return repo.get_archive_link('tarball', commit) |
def _getTarball(url, into_directory, cache_key, origin_info=None):
'''unpack the specified tarball url into the specified directory'''
try:
access_common.unpackFromCache(cache_key, into_directory)
except KeyError as e:
tok = settings.getProperty('github', 'authtoken')
headers = {}
... |
def createFromSource(cls, vs, name=None):
''' returns a github component for any github url (including
git+ssh:// git+http:// etc. or None if this is not a Github URL.
For all of these we use the github api to grab a tarball, because
that's faster.
Normally versi... |
def availableVersions(self):
''' return a list of Version objects, each with a tarball URL set '''
r = []
for t in self._getTags():
logger.debug("available version tag: %s", t)
# ignore empty tags:
if not len(t[0].strip()):
continue
... |
def availableTags(self):
''' return a list of GithubComponentVersion objects for all tags
'''
return [
GithubComponentVersion(
'', t[0], t[1], self.name, cache_key=_createCacheKey('tag', t[0], t[1], self.name)
) for t in self._getTags()
] |
def availableBranches(self):
''' return a list of GithubComponentVersion objects for the tip of each branch
'''
return [
GithubComponentVersion(
'', b[0], b[1], self.name, cache_key=None
) for b in _getBranchHeads(self.repo).items()
] |
def commitVersion(self):
''' return a GithubComponentVersion object for a specific commit if valid
'''
import re
commit_match = re.match('^[a-f0-9]{7,40}$', self.tagOrBranchSpec(), re.I)
if commit_match:
return GithubComponentVersion(
'', '', _getComm... |
def createFromSource(cls, vs, name=None):
''' returns a hg component for any hg:// url, or None if this is not
a hg component.
Normally version will be empty, unless the original url was of the
form 'hg+ssh://...#version', which can be used to grab a particular
t... |
def dropRootPrivs(fn):
''' decorator to drop su/sudo privilages before running a function on
unix/linux.
The *real* uid is modified, so privileges are permanently dropped for
the process. (i.e. make sure you don't need to do
If there is a SUDO_UID environment variable, then we drop ... |
def installAndBuild(args, following_args):
''' Perform the build command, but provide detailed error information.
Returns {status:0, build_status:0, generate_status:0, install_status:0} on success.
If status: is nonzero there was some sort of error. Other properties
are optional, and may not... |
def _returnRequestError(fn):
''' Decorator that captures requests.exceptions.RequestException errors
and returns them as an error message. If no error occurs the reture
value of the wrapped function is returned (normally None). '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
t... |
def _handleAuth(fn):
''' Decorator to re-try API calls after asking the user for authentication. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
# auth, , authenticate users, internal
from yotta.lib import auth
# if yotta is being run noninteractively, then we never retry, but... |
def _friendlyAuthError(fn):
''' Decorator to print a friendly you-are-not-authorised message. Use
**outside** the _handleAuth decorator to only print the message after
the user has been given a chance to login. '''
@functools.wraps(fn)
def wrapped(*args, **kwargs):
try:
r... |
def _raiseUnavailableFor401(message):
''' Returns a decorator to swallow a requests exception for modules that
are not accessible without logging in, and turn it into an Unavailable
exception.
'''
def __raiseUnavailableFor401(fn):
def wrapped(*args, **kwargs):
try:
... |
def publish(namespace, name, version, description_file, tar_file, readme_file,
readme_file_ext, registry=None):
''' Publish a tarblob to the registry, if the request fails, an exception
is raised, which either triggers re-authentication, or is turned into a
return value by the decorators... |
def unpublish(namespace, name, version, registry=None):
''' Try to unpublish a recently published version. Return any errors that
occur.
'''
registry = registry or Registry_Base_URL
url = '%s/%s/%s/versions/%s' % (
registry,
namespace,
name,
version
)
he... |
def listOwners(namespace, name, registry=None):
''' List the owners of a module or target (owners are the people with
permission to publish versions and add/remove the owners).
'''
registry = registry or Registry_Base_URL
url = '%s/%s/%s/owners' % (
registry,
namespace,
... |
def removeOwner(namespace, name, owner, registry=None):
''' Remove an owner for a module or target (owners are the people with
permission to publish versions and add/remove the owners).
'''
registry = registry or Registry_Base_URL
url = '%s/%s/%s/owners/%s' % (
registry,
namespa... |
def search(query='', keywords=[], registry=None):
''' generator of objects returned by the search endpoint (both modules and
targets).
Query is a full-text search (description, name, keywords), keywords
search only the module/target description keywords lists.
If both parameters ar... |
def setAPIKey(registry, api_key):
''' Set the api key for accessing a registry. This is only necessary for
development/test registries.
'''
if (registry is None) or (registry == Registry_Base_URL):
return
sources = _getSources()
source = None
for s in sources:
if _sourceM... |
def getPublicKey(registry=None):
''' Return the user's public key (generating and saving a new key pair if necessary) '''
registry = registry or Registry_Base_URL
pubkey_pem = None
if _isPublicRegistry(registry):
pubkey_pem = settings.getProperty('keys', 'public')
else:
for s in _get... |
def getAuthData(registry=None):
''' Poll the registry to get the result of a completed authentication
(which, depending on the authentication the user chose or was directed
to, will include a github or other access token)
'''
registry = registry or Registry_Base_URL
url = '%s/tokens' % (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.