INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Returns the current size of the terminal as tuple in the form ( width height ) in columns and rows. | def get_terminal_size():
"""Returns the current size of the terminal as tuple in the form
``(width, height)`` in columns and rows.
"""
# If shutil has get_terminal_size() (Python 3.3 and later) use that
if sys.version_info >= (3, 3):
import shutil
shutil_get_terminal_size = getattr(s... |
Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing reset = False. | def style(text, fg=None, bg=None, bold=None, dim=None, underline=None,
blink=None, reverse=None, reset=True):
"""Styles a text with ANSI styles and returns the new string. By
default the styling is self contained which means that at the end
of the string a reset code is issued. This can be preve... |
This function combines: func: echo and: func: style into one call. As such the following two calls are the same:: | def secho(text, file=None, nl=True, err=False, color=None, **styles):
"""This function combines :func:`echo` and :func:`style` into one
call. As such the following two calls are the same::
click.secho('Hello World!', fg='green')
click.echo(click.style('Hello World!', fg='green'))
All keyw... |
Determines appropriate setting for a given request taking into account the explicit setting on that request and the setting in the session. If a setting is a dictionary they will be merged together using dict_class | def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
"""
Determines appropriate setting for a given request, taking into account the
explicit setting on that request, and the setting in the session. If a
setting is a dictionary, they will be merged together using `dict_class`
... |
Receives a Response. Returns a generator of Responses. | def resolve_redirects(self, resp, req, stream=False, timeout=None,
verify=True, cert=None, proxies=None):
"""Receives a Response. Returns a generator of Responses."""
i = 0
hist = [] # keep track of history
while resp.is_redirect:
prepared_request ... |
Send a given PreparedRequest. | def send(self, request, **kwargs):
"""Send a given PreparedRequest."""
# Set defaults that the hooks can utilize to ensure they always have
# the correct parameters to reproduce the previous request.
kwargs.setdefault('stream', self.stream)
kwargs.setdefault('verify', self.verify... |
A generator wrapper for the read () method. A call will block until amt bytes have been read from the connection or until the connection is closed. | def stream(self, amt=2**16, decode_content=None):
"""
A generator wrapper for the read() method. A call will block until
``amt`` bytes have been read from the connection or until the
connection is closed.
:param amt:
How much of the content to read. The generator wil... |
Prepares the given HTTP method. | def prepare_method(self, method):
"""Prepares the given HTTP method."""
self.method = method
if self.method is not None:
self.method = self.method.upper() |
Prepares the given HTTP headers. | def prepare_headers(self, headers):
"""Prepares the given HTTP headers."""
if headers:
self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items())
else:
self.headers = CaseInsensitiveDict() |
Iterates over the response data. When stream = True is set on the request this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can take place. | def iter_content(self, chunk_size=1, decode_unicode=False):
"""Iterates over the response data. When stream=True is set on the
request, this avoids reading the content at once into memory for
large responses. The chunk size is the number of bytes it should
read into memory. This is no... |
Returns the json - encoded content of a response if any. | def json(self, **kwargs):
"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
"""
if not self.encoding and len(self.content) > 3:
# No encoding set. JSON RFC 4627 section 3 states we should expect
... |
Raises stored: class: HTTPError if one occurred. | def raise_for_status(self):
"""Raises stored :class:`HTTPError`, if one occurred."""
http_error_msg = ''
if 400 <= self.status_code < 500:
http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason)
elif 500 <= self.status_code < 600:
http_error_ms... |
Create a new: class: ConnectionPool based on host port and scheme. | def _new_pool(self, scheme, host, port):
"""
Create a new :class:`ConnectionPool` based on host, port and scheme.
This method is used to actually create the connection pools handed out
by :meth:`connection_from_url` and companion methods. It is intended
to be overridden for cust... |
Get a: class: ConnectionPool based on the host port and scheme. | def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on the host, port, and scheme.
If ``port`` isn't given, it will be derived from the ``scheme`` using
``urllib3.connectionpool.port_by_scheme``.
"""
if not host:
... |
To use in conjunction with a TestClass wrapped with @genty. | def genty_repeat(count):
"""
To use in conjunction with a TestClass wrapped with @genty.
Runs the wrapped test 'count' times:
@genty_repeat(count)
def test_some_function(self)
...
Can also wrap a test already decorated with @genty_dataset
@genty_repeat(3)
@g... |
A decorator to register a subcommand with the global Subcommands instance. | def command(name=None):
"""A decorator to register a subcommand with the global `Subcommands` instance.
"""
def decorator(f):
_commands.append((name, f))
return f
return decorator |
Top - level driver for creating subcommand - based programs. | def main(program=None,
version=None,
doc_template=None,
commands=None,
argv=None,
exit_at_end=True):
"""Top-level driver for creating subcommand-based programs.
Args:
program: The name of your program.
version: The version string for your program.
... |
Overridden process_response would pipe response. body through BeautifulSoup. | def process_response(self, request, response, spider):
"""Overridden process_response would "pipe" response.body through BeautifulSoup."""
return response.replace(body=str(BeautifulSoup(response.body, self.parser))) |
This decorator takes the information provided by @genty_dataset @genty_dataprovider and @genty_repeat and generates the corresponding test methods. | def genty(target_cls):
"""
This decorator takes the information provided by @genty_dataset,
@genty_dataprovider, and @genty_repeat and generates the corresponding
test methods.
:param target_cls:
Test class whose test methods have been decorated.
:type target_cls:
`class`
""... |
Generator producing test_methods with an optional dataset. | def _expand_datasets(test_functions):
"""
Generator producing test_methods, with an optional dataset.
:param test_functions:
Iterator over tuples of test name and test unbound function.
:type test_functions:
`iterator` of `tuple` of (`unicode`, `function`)
:return:
Generator... |
Generator producing test_methods with any repeat count unrolled. | def _expand_repeats(test_functions):
"""
Generator producing test_methods, with any repeat count unrolled.
:param test_functions:
Sequence of tuples of
- method_name : Name of the test method
- unbound function : Unbound function that will be the test method.
- dataset ... |
Various test runners allow one to run a specific test like so: python - m unittest - v <test_module >. <test_name > | def _is_referenced_in_argv(method_name):
"""
Various test runners allow one to run a specific test like so:
python -m unittest -v <test_module>.<test_name>
Return True is the given method name is so referenced.
:param method_name:
Base name of the method to add.
:type method_name:
... |
Return the suffix string to identify iteration X out of Y. | def _build_repeat_suffix(iteration, count):
"""
Return the suffix string to identify iteration X out of Y.
For example, with a count of 100, this will build strings like
"iteration_053" or "iteration_008".
:param iteration:
Current iteration.
:type iteration:
`int`
:param c... |
Return a nice human friendly name that almost looks like code. | def _build_final_method_name(
method_name,
dataset_name,
dataprovider_name,
repeat_suffix,
):
"""
Return a nice human friendly name, that almost looks like code.
Example: a test called 'test_something' with a dataset of (5, 'hello')
Return: "test_something(5, 'hell... |
Return a fabricated method that marshals the dataset into parameters for given method: param method: The underlying test method.: type method: callable: param dataset: Tuple or GentyArgs instance containing the args of the dataset.: type dataset: tuple or: class: GentyArgs: return: Return an unbound function that will ... | def _build_dataset_method(method, dataset):
"""
Return a fabricated method that marshals the dataset into parameters
for given 'method'
:param method:
The underlying test method.
:type method:
`callable`
:param dataset:
Tuple or GentyArgs instance containing the args of t... |
Return a fabricated method that calls the dataprovider with the given dataset and marshals the return value from that into params to the underlying test method.: param method: The underlying test method.: type method: callable: param dataset: Tuple or GentyArgs instance containing the args of the dataset.: type dataset... | def _build_dataprovider_method(method, dataset, dataprovider):
"""
Return a fabricated method that calls the dataprovider with the given
dataset, and marshals the return value from that into params to the
underlying test 'method'.
:param method:
The underlying test method.
:type method:
... |
Add the described method to the given class. | def _add_method_to_class(
target_cls,
method_name,
func,
dataset_name,
dataset,
dataprovider,
repeat_suffix,
):
"""
Add the described method to the given class.
:param target_cls:
Test class to which to add a method.
:type target_cls:
... |
Close any open window. | def close(self):
"""Close any open window.
Note that this only works with non-blocking methods.
"""
if self._process:
# Be nice first.
self._process.send_signal(signal.SIGINT)
# If it doesn't close itself promptly, be brutal.
# Python 3.... |
Internal API: run a blocking command with subprocess. | def _run_blocking(self, args, input=None):
"""Internal API: run a blocking command with subprocess.
This closes any open non-blocking dialog before running the command.
Parameters
----------
args: Popen constructor arguments
Command to run.
input: string
... |
Internal API: run a non - blocking command with subprocess. | def _run_nonblocking(self, args, input=None):
"""Internal API: run a non-blocking command with subprocess.
This closes any open non-blocking dialog before running the command.
Parameters
----------
args: Popen constructor arguments
Command to run.
input: str... |
Show an error window. | def error(self, message, rofi_args=None, **kwargs):
"""Show an error window.
This method blocks until the user presses a key.
Fullscreen mode is not supported for error windows, and if specified
will be ignored.
Parameters
----------
message: string
... |
Show a status message. | def status(self, message, rofi_args=None, **kwargs):
"""Show a status message.
This method is non-blocking, and intended to give a status update to
the user while something is happening in the background.
To close the window, either call the close() method or use any of the
dis... |
Show a list of options and return user selection. | def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs):
"""Show a list of options and return user selection.
This method blocks until the user makes their choice.
Parameters
----------
prompt: string
The prompt telling the user what the... |
A generic entry box. | def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs):
"""A generic entry box.
Parameters
----------
prompt: string
Text prompt for the entry.
validator: function, optional
A function to validate and convert the value ent... |
Prompt the user to enter a piece of text. | def text_entry(self, prompt, message=None, allow_blank=False, strip=True,
rofi_args=None, **kwargs):
"""Prompt the user to enter a piece of text.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Mes... |
Prompt the user to enter an integer. | def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter an integer.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display under the... |
Prompt the user to enter a floating point number. | def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter a floating point number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to displa... |
Prompt the user to enter a decimal number. | def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs):
"""Prompt the user to enter a decimal number.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
Message to display und... |
Prompt the user to enter a date. | def date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'],
show_example=False, rofi_args=None, **kwargs):
"""Prompt the user to enter a date.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
... |
Prompt the user to enter a time. | def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M',
'%I.%M'], show_example=False, rofi_args=None, **kwargs):
"""Prompt the user to enter a time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: stri... |
Prompt the user to enter a date and time. | def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False,
rofi_args=None, **kwargs):
"""Prompt the user to enter a date and time.
Parameters
----------
prompt: string
Prompt to display to the user.
message: string, optional
... |
Report an error and exit. | def exit_with_error(self, error, **kwargs):
"""Report an error and exit.
This raises a SystemExit exception to ask the interpreter to quit.
Parameters
----------
error: string
The error to report before quitting.
"""
self.error(error, **kwargs)
... |
Return a string of form: key = <value > | def format_kwarg(key, value):
"""
Return a string of form: "key=<value>"
If 'value' is a string, we want it quoted. The goal is to make
the string a named parameter in a method call.
"""
translator = repr if isinstance(value, six.string_types) else six.text_type
arg_value = translator(valu... |
: param value: Some value in a dataset.: type value: varies: return: unicode representation of that value: rtype: unicode | def format_arg(value):
"""
:param value:
Some value in a dataset.
:type value:
varies
:return:
unicode representation of that value
:rtype:
`unicode`
"""
translator = repr if isinstance(value, six.string_types) else six.text_type
return translator(value) |
: param string: The string to be encoded: type string: unicode or str: return: The encoded string: rtype: str | def encode_non_ascii_string(string):
"""
:param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str
"""
encoded_string = string.encode('utf-8', 'replace')
if six.PY3:
encoded_string = encoded_string... |
Decorator defining that this test gets parameters from the given build_function. | def genty_dataprovider(builder_function):
"""Decorator defining that this test gets parameters from the given
build_function.
:param builder_function:
A callable that returns parameters that will be passed to the method
decorated by this decorator.
If the builder_function returns a... |
Decorator defining data sets to provide to a test. | def genty_dataset(*args, **kwargs):
"""Decorator defining data sets to provide to a test.
Inspired by http://sebastian-bergmann.de/archives/
702-Data-Providers-in-PHPUnit-3.2.html
The canonical way to call @genty_dataset, with each argument each
representing a data set to be injected in the test m... |
Build the datasets into a dict where the keys are the name of the data set and the values are the data sets themselves. | def _build_datasets(*args, **kwargs):
"""Build the datasets into a dict, where the keys are the name of the
data set and the values are the data sets themselves.
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
:param kwargs:
Dict of pre-named data sets... |
Add data sets of the given args. | def _add_arg_datasets(datasets, args):
"""Add data sets of the given args.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param args:
Tuple of unnamed data sets.
:type args:
`tuple` of varies
"""
for dataset in args:
... |
Add data sets of the given kwargs. | def _add_kwarg_datasets(datasets, kwargs):
"""Add data sets of the given kwargs.
:param datasets:
The dict where to accumulate data sets.
:type datasets:
`dict`
:param kwargs:
Dict of pre-named data sets.
:type kwargs:
`dict` of `unicode` to varies
"""
for te... |
Removes the hanging dedent from all the first line of a string. | def dedent(s):
"""Removes the hanging dedent from all the first line of a string."""
head, _, tail = s.partition('\n')
dedented_tail = textwrap.dedent(tail)
result = "{head}\n{tail}".format(
head=head,
tail=dedented_tail)
return result |
The top - level documentation string for the program. | def top_level_doc(self):
"""The top-level documentation string for the program.
"""
return self._doc_template.format(
available_commands='\n '.join(sorted(self._commands)),
program=self.program) |
A decorator to add subcommands. | def command(self, name=None):
"""A decorator to add subcommands.
"""
def decorator(f):
self.add_command(f, name)
return f
return decorator |
Add a subcommand name which invokes handler. | def add_command(self, handler, name=None):
"""Add a subcommand `name` which invokes `handler`.
"""
if name is None:
name = docstring_to_subcommand(handler.__doc__)
# TODO: Prevent overwriting 'help'?
self._commands[name] = handler |
Create variations of the word based on letter combinations like oo sh etc. | def variations(word):
"""Create variations of the word based on letter combinations like oo,
sh, etc."""
if len(word) == 1:
return [[word[0]]]
elif word == 'aa':
return [['A']]
elif word == 'ee':
return [['i']]
elif word == 'ei':
return [['ei']]
elif word in ['oo... |
Convert a single word from Finglish to Persian. | def f2p_word(word, max_word_size=15, cutoff=3):
"""Convert a single word from Finglish to Persian.
max_word_size: Maximum size of the words to consider. Words larger
than this will be kept unchanged.
cutoff: The cut-off point. For each word, there could be many
possibilities. By default 3 of these... |
Convert a phrase from Finglish to Persian. | def f2p_list(phrase, max_word_size=15, cutoff=3):
"""Convert a phrase from Finglish to Persian.
phrase: The phrase to convert.
max_word_size: Maximum size of the words to consider. Words larger
than this will be kept unchanged.
cutoff: The cut-off point. For each word, there could be many
pos... |
Convert a Finglish phrase to the most probable Persian phrase. | def f2p(phrase, max_word_size=15, cutoff=3):
"""Convert a Finglish phrase to the most probable Persian phrase.
"""
results = f2p_list(phrase, max_word_size, cutoff)
return ' '.join(i[0][0] for i in results) |
try to get the version of the named distribution returs None on failure | def distribution_version(name):
"""try to get the version of the named distribution,
returs None on failure"""
from pkg_resources import get_distribution, DistributionNotFound
try:
dist = get_distribution(name)
except DistributionNotFound:
pass
else:
return dist.version |
initialize given package from the export definitions. | def initpkg(pkgname, exportdefs, attr=None, eager=False):
""" initialize given package from the export definitions. """
attr = attr or {}
oldmod = sys.modules.get(pkgname)
d = {}
f = getattr(oldmod, '__file__', None)
if f:
f = _py_abspath(f)
d['__file__'] = f
if hasattr(oldmod, '... |
imports a module then resolves the attrname on it | def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ['__doc__'])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:
retval = getattr(retval, x)
return retv... |
lazily compute value for name or raise AttributeError if unknown. | def __makeattr(self, name):
"""lazily compute value for name or raise AttributeError if unknown."""
# print "makeattr", self.__name__, name
target = None
if '__onfirstaccess__' in self.__map__:
target = self.__map__.pop('__onfirstaccess__')
importobj(*target)()
... |
Does actual HTTP request using requests library. | def _request(self, http_method, relative_url='', **kwargs):
"""Does actual HTTP request using requests library."""
# It could be possible to call api.resource.get('/index')
# but it would be non-intuitive that the path would resolve
# to root of domain
relative_url = self._remove... |
Create new Url which points to new url. | def _new_url(self, relative_url):
"""Create new Url which points to new url."""
return Url(
urljoin(self._base_url, relative_url),
**self._default_kwargs
) |
gets user groups | def roles(self):
"""gets user groups"""
result = AuthGroup.objects(creator=self.client).only('role')
return json.loads(result.to_json()) |
gets permissions of role | def get_permissions(self, role):
"""gets permissions of role"""
target_role = AuthGroup.objects(role=role, creator=self.client).first()
if not target_role:
return '[]'
targets = AuthPermission.objects(groups=target_role, creator=self.client).only('name')
return json.l... |
get permissions of a user | def get_user_permissions(self, user):
"""get permissions of a user"""
memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups')
results = []
for each in memberShipRecords:
for group in each.groups:
targetPermissionRecords = Auth... |
get permissions of a user | def get_user_roles(self, user):
"""get permissions of a user"""
memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups')
results = []
for each in memberShipRecords:
for group in each.groups:
results.append({'role':group.role})
... |
get permissions of a user | def get_role_members(self, role):
"""get permissions of a user"""
targetRoleDb = AuthGroup.objects(creator=self.client, role=role)
members = AuthMembership.objects(groups__in=targetRoleDb).only('user')
return json.loads(members.to_json()) |
Which role can SendMail? | def which_roles_can(self, name):
"""Which role can SendMail? """
targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first()
return [{'role': group.role} for group in targetPermissionRecords.groups] |
Which role can SendMail? | def which_users_can(self, name):
"""Which role can SendMail? """
_roles = self.which_roles_can(name)
result = [self.get_role_members(i.get('role')) for i in _roles]
return result |
Returns a role object | def get_role(self, role):
"""Returns a role object
"""
role = AuthGroup.objects(role=role, creator=self.client).first()
return role |
Creates a new group | def add_role(self, role, description=None):
""" Creates a new group """
new_group = AuthGroup(role=role, creator=self.client)
try:
new_group.save()
return True
except NotUniqueError:
return False |
deletes a group | def del_role(self, role):
""" deletes a group """
target = AuthGroup.objects(role=role, creator=self.client).first()
if target:
target.delete()
return True
else:
return False |
make user a member of a group | def add_membership(self, user, role):
""" make user a member of a group """
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
target = AuthMembership.objects(user=user, creator=self.client).first()
if not target:... |
dismember user from a group | def del_membership(self, user, role):
""" dismember user from a group """
if not self.has_membership(user, role):
return True
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return True
for group in targe... |
checks if user is member of a group | def has_membership(self, user, role):
""" checks if user is member of a group"""
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if targetRecord:
return role in [i.role for i in targetRecord.groups]
return False |
authorize a group for something | def add_permission(self, role, name):
""" authorize a group for something """
if self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
# Create or update
... |
revoke authorization of a group | def del_permission(self, role, name):
""" revoke authorization of a group """
if not self.has_permission(role, name):
return True
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
target = AuthPermission.objects(groups=targetGroup, name=name, creator=sel... |
verify user has permission | def user_has_permission(self, user, name):
""" verify user has permission """
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return False
for group in targetRecord.groups:
if self.has_permission(group.role, name)... |
patch: patch minor major | def bump_version(version, bump='patch'):
"""patch: patch, minor, major"""
try:
parts = map(int, version.split('.'))
except ValueError:
fail('Current version is not numeric')
if bump == 'patch':
parts[2] += 1
elif bump == 'minor':
parts[1] += 1
parts[2] = 0
... |
Signal decorator to allow use of callback functions as class decorators. | def handler(event):
"""Signal decorator to allow use of callback functions as class decorators."""
def decorator(fn):
def apply(cls):
event.connect(fn, sender=cls)
return cls
fn.apply = apply
return fn
return decorator |
dumps all valid jsons This is the latest after hook | def stringify(req, resp):
"""
dumps all valid jsons
This is the latest after hook
"""
if isinstance(resp.body, dict):
try:
resp.body = json.dumps(resp.body)
except(nameError):
resp.status = falcon.HTTP_500 |
Post - processing of the response ( after routing ). | def process_response(self, req, resp, resource):
"""Post-processing of the response (after routing).
Args:
req: Request object.
resp: Response object.
resource: Resource object to which the request was
routed. May be None if no route was found
... |
Run the given command. | def run(command=None, *arguments):
"""
Run the given command.
Parameters:
:param command: A string describing a command.
:param arguments: A list of strings describing arguments to the command.
"""
if command is None:
sys.exit('django-shortcuts: No argument was supplied, please spe... |
Create a ParamList instance for actual interpretation | def instantiate(self, scope, args, interp):
"""Create a ParamList instance for actual interpretation
:args: TODO
:returns: A ParamList object
"""
param_instances = []
BYREF = "byref"
# TODO are default values for function parameters allowed in 010?
for... |
get_experiments will return loaded json for all valid experiments from an experiment folder: param base: full path to the base folder with experiments inside: param load: if True returns a list of loaded config. json objects. If False ( default ) returns the paths to the experiments | def get_experiments(base, load=False):
''' get_experiments will return loaded json for all valid experiments from an experiment folder
:param base: full path to the base folder with experiments inside
:param load: if True, returns a list of loaded config.json objects. If False (default) returns the paths to... |
load_experiments a wrapper for load_experiment to read multiple experiments: param experiment_folders: a list of experiment folders to load full paths | def load_experiments(folders):
'''load_experiments
a wrapper for load_experiment to read multiple experiments
:param experiment_folders: a list of experiment folders to load, full paths
'''
experiments = []
if isinstance(folders,str):
folders = [experiment_folders]
for folder in fold... |
load_experiment: reads in the config. json for a folder returns None if not found.: param folder: full path to experiment folder: param return_path: if True don t load the config. json but return it | def load_experiment(folder, return_path=False):
'''load_experiment:
reads in the config.json for a folder, returns None if not found.
:param folder: full path to experiment folder
:param return_path: if True, don't load the config.json, but return it
'''
fullpath = os.path.abspath(folder)
co... |
we compare the basename ( the exp_id ) of the selection and available regardless of parent directories | def get_selection(available, selection, base='/scif/apps'):
'''we compare the basename (the exp_id) of the selection and available,
regardless of parent directories'''
if isinstance(selection, str):
selection = selection.split(',')
available = [os.path.basename(x) for x in available]
s... |
make_lookup returns dict object to quickly look up query experiment on exp_id: param experiment_list: a list of query ( dict objects ): param key_field: the key in the dictionary to base the lookup key ( str ): returns lookup: dict ( json ) with key as key_field from query_list | def make_lookup(experiment_list, key='exp_id'):
'''make_lookup returns dict object to quickly look up query experiment on exp_id
:param experiment_list: a list of query (dict objects)
:param key_field: the key in the dictionary to base the lookup key (str)
:returns lookup: dict (json) with key as "key_f... |
validate: param folder: full path to experiment folder with config. json. If path begins with https we assume to be starting from a repository. | def validate(folder=None, cleanup=False):
'''validate
:param folder: full path to experiment folder with config.json. If path begins
with https, we assume to be starting from a repository.
'''
from expfactory.validator import ExperimentValidator
cli = ExperimentValidator()
ret... |
return the raw library without parsing | def get_library(lookup=True, key='exp_id'):
''' return the raw library, without parsing'''
library = None
response = requests.get(EXPFACTORY_LIBRARY)
if response.status_code == 200:
library = response.json()
if lookup is True:
return make_lookup(library,key=key)
return li... |
Define the Int3 () function in the interpreter. Calling Int3 () will drop the user into an interactive debugger. | def int3(params, ctxt, scope, stream, coord, interp):
"""Define the ``Int3()`` function in the interpreter. Calling
``Int3()`` will drop the user into an interactive debugger.
"""
if interp._no_debug:
return
if interp._int3:
interp.debugger = PfpDbg(interp)
interp.debugger.c... |
initdb will check for writability of the data folder meaning that it is bound to the local machine. If the folder isn t bound expfactory runs in demo mode ( not saving data ) | def initdb(self):
'''initdb will check for writability of the data folder, meaning
that it is bound to the local machine. If the folder isn't bound,
expfactory runs in demo mode (not saving data)
'''
self.database = EXPFACTORY_DATABASE
bot.info("DATABASE: %s" %self... |
obtain database and filesystem preferences from defaults and compare with selection in container. | def setup(self):
''' obtain database and filesystem preferences from defaults,
and compare with selection in container.
'''
self.selection = EXPFACTORY_EXPERIMENTS
self.ordered = len(EXPFACTORY_EXPERIMENTS) > 0
self.data_base = EXPFACTORY_DATA
self.study_id =... |
return the name of the next experiment depending on the user s choice to randomize. We don t remove any experiments here that is done on finish in the case the user doesn t submit data ( and thus finish ). A return of None means the user has completed the battery of experiments. | def get_next(self, session):
'''return the name of the next experiment, depending on the user's
choice to randomize. We don't remove any experiments here, that is
done on finish, in the case the user doesn't submit data (and
thus finish). A return of None means the user has comp... |
remove an experiment from the list after completion. | def finish_experiment(self, session, exp_id):
'''remove an experiment from the list after completion.
'''
self.logger.debug('Finishing %s' %exp_id)
experiments = session.get('experiments', [])
experiments = [x for x in experiments if x != exp_id]
session['experiments'] = ... |
Return directories ( and sub ) starting from a base | def find_subdirectories(basepath):
'''
Return directories (and sub) starting from a base
'''
directories = []
for root, dirnames, filenames in os.walk(basepath):
new_directories = [d for d in dirnames if d not in directories]
directories = directories + new_directories
return dir... |
Return directories at one level specified by user ( not recursive ) | def find_directories(root,fullpath=True):
'''
Return directories at one level specified by user
(not recursive)
'''
directories = []
for item in os.listdir(root):
# Don't include hidden directories
if not re.match("^[.]",item):
if os.path.isdir(os.path.join(root, item... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.