_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q273900 | cli_encrypt | test | def cli_encrypt(context, key):
"""
Encrypts context.io_manager's stdin and sends that to
context.io_manager's stdout.
This can be useful to encrypt to disk before attempting to
upload, allowing uploads retries and segmented encrypted objects.
See :py:mod:`swiftly.cli.encrypt` for context usage... | python | {
"resource": ""
} |
q273901 | get_status | test | def get_status(app, repo_config, repo_name, sha):
"""Gets the status of a commit.
.. note::
``repo_name`` might not ever be anything other than
``repo_config['github_repo']``.
:param app: Flask app for leeroy
:param repo_config: configuration for the repo
:param repo_name: The name... | python | {
"resource": ""
} |
q273902 | get_pull_request | test | def get_pull_request(app, repo_config, pull_request):
"""Data for a given pull request.
:param app: Flask app
:param repo_config: dict with ``github_repo`` key
:param pull_request: the pull request number
"""
response = get_api_response(
app, repo_config,
"/repos/{{repo_name}}/p... | python | {
"resource": ""
} |
q273903 | get_pull_requests | test | def get_pull_requests(app, repo_config):
"""Last 30 pull requests from a repository.
:param app: Flask app
:param repo_config: dict with ``github_repo`` key
:returns: id for a pull request
"""
response = get_api_response(app, repo_config, "/repos/{repo_name}/pulls")
if not response.ok:
... | python | {
"resource": ""
} |
q273904 | Migration.forwards | test | def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for title in orm['hero_slider.SliderItemTitle'].objects.all():
title.is_published = True
title.save() | python | {
"resource": ""
} |
q273905 | get_slider_items | test | def get_slider_items(context, amount=None):
"""Returns the published slider items."""
req = context.get('request')
qs = SliderItem.objects.published(req).order_by('position')
if amount:
qs = qs[:amount]
return qs | python | {
"resource": ""
} |
q273906 | render_hero_slider | test | def render_hero_slider(context):
"""
Renders the hero slider.
"""
req = context.get('request')
qs = SliderItem.objects.published(req).order_by('position')
return {
'slider_items': qs,
} | python | {
"resource": ""
} |
q273907 | RWLock.reader_acquire | test | def reader_acquire(self):
"""Acquire the lock to read"""
self._order_mutex.acquire()
self._readers_mutex.acquire()
if self._readers == 0:
self._access_mutex.acquire()
self._readers += 1
self._order_mutex.release()
self._readers_mutex.release() | python | {
"resource": ""
} |
q273908 | RWLock.reader_release | test | def reader_release(self):
"""Release the lock after reading"""
self._readers_mutex.acquire()
self._readers -= 1
if self._readers == 0:
self._access_mutex.release()
self._readers_mutex.release() | python | {
"resource": ""
} |
q273909 | RWLock.writer_acquire | test | def writer_acquire(self):
"""Acquire the lock to write"""
self._order_mutex.acquire()
self._access_mutex.acquire()
self._order_mutex.release() | python | {
"resource": ""
} |
q273910 | TaskRegistry.add | test | def add(self, task_id, backend, category, backend_args,
archiving_cfg=None, scheduling_cfg=None):
"""Add a task to the registry.
This method adds task using `task_id` as identifier. If a task
with the same identifier already exists on the registry, a
`AlreadyExistsError` exc... | python | {
"resource": ""
} |
q273911 | TaskRegistry.remove | test | def remove(self, task_id):
"""Remove a task from the registry.
To remove it, pass its identifier with `taks_id` parameter.
When the identifier is not found, a `NotFoundError` exception
is raised.
:param task_id: identifier of the task to remove
:raises NotFoundError: r... | python | {
"resource": ""
} |
q273912 | TaskRegistry.get | test | def get(self, task_id):
"""Get a task from the registry.
Retrieve a task from the registry using its task identifier. When
the task does not exist, a `NotFoundError` exception will be
raised.
:param task_id: task identifier
:returns: a task object
:raises NotF... | python | {
"resource": ""
} |
q273913 | TaskRegistry.tasks | test | def tasks(self):
"""Get the list of tasks"""
self._rwlock.reader_acquire()
tl = [v for v in self._tasks.values()]
tl.sort(key=lambda x: x.task_id)
self._rwlock.reader_release()
return tl | python | {
"resource": ""
} |
q273914 | _TaskConfig.to_dict | test | def to_dict(self):
"""Returns a dict with the representation of this task configuration object."""
properties = find_class_properties(self.__class__)
config = {
name: self.__getattribute__(name) for name, _ in properties
}
return config | python | {
"resource": ""
} |
q273915 | _TaskConfig.from_dict | test | def from_dict(cls, config):
"""Create an configuration object from a dictionary.
Key,value pairs will be used to initialize a task configuration
object. If 'config' contains invalid configuration parameters
a `ValueError` exception will be raised.
:param config: dictionary used... | python | {
"resource": ""
} |
q273916 | execute_perceval_job | test | def execute_perceval_job(backend, backend_args, qitems, task_id, category,
archive_args=None, max_retries=MAX_JOB_RETRIES):
"""Execute a Perceval job on RQ.
The items fetched during the process will be stored in a
Redis queue named `queue`.
Setting the parameter `archive_path`... | python | {
"resource": ""
} |
q273917 | PercevalJob.initialize_archive_manager | test | def initialize_archive_manager(self, archive_path):
"""Initialize the archive manager.
:param archive_path: path where the archive manager is located
"""
if archive_path == "":
raise ValueError("Archive manager path cannot be empty")
if archive_path:
sel... | python | {
"resource": ""
} |
q273918 | PercevalJob.run | test | def run(self, backend_args, archive_args=None, resume=False):
"""Run the backend with the given parameters.
The method will run the backend assigned to this job,
storing the fetched items in a Redis queue. The ongoing
status of the job, can be accessed through the property
`resu... | python | {
"resource": ""
} |
q273919 | PercevalJob._execute | test | def _execute(self, backend_args, archive_args):
"""Execute a backend of Perceval.
Run the backend of Perceval assigned to this job using the
given arguments. It will raise an `AttributeError` when any of
the required parameters to run the backend are not found.
Other exceptions ... | python | {
"resource": ""
} |
q273920 | ElasticItemsWriter.create_index | test | def create_index(idx_url, clean=False):
"""Configure the index to work with"""
try:
r = requests.get(idx_url)
except requests.exceptions.ConnectionError:
cause = "Error connecting to Elastic Search (index: %s)" % idx_url
raise ElasticSearchError(cause=cause)
... | python | {
"resource": ""
} |
q273921 | ElasticItemsWriter.create_mapping | test | def create_mapping(idx_url, mapping):
"""Create a mapping"""
mapping_url = idx_url + '/items/_mapping'
mapping = json.dumps(mapping)
try:
r = requests.put(mapping_url, data=mapping,
headers={'Content-Type': 'application/json'})
except re... | python | {
"resource": ""
} |
q273922 | json_encoder | test | def json_encoder(*args, **kwargs):
"""Custom JSON encoder handler"""
obj = cherrypy.serving.request._json_inner_handler(*args, **kwargs)
for chunk in JSONEncoder().iterencode(obj):
yield chunk.encode('utf-8') | python | {
"resource": ""
} |
q273923 | ArthurServer.write_items | test | def write_items(cls, writer, items_generator):
"""Write items to the queue
:param writer: the writer object
:param items_generator: items to be written in the queue
"""
while True:
items = items_generator()
writer.write(items)
time.sleep(1) | python | {
"resource": ""
} |
q273924 | Arthur.add_task | test | def add_task(self, task_id, backend, category, backend_args,
archive_args=None, sched_args=None):
"""Add and schedule a task.
:param task_id: id of the task
:param backend: name of the backend
:param category: category of the items to fecth
:param backend_args: ... | python | {
"resource": ""
} |
q273925 | Arthur.remove_task | test | def remove_task(self, task_id):
"""Remove and cancel a task.
:param task_id: id of the task to be removed
"""
try:
self._scheduler.cancel_task(task_id)
except NotFoundError as e:
logger.info("Cannot cancel %s task because it does not exist.",
... | python | {
"resource": ""
} |
q273926 | Arthur.items | test | def items(self):
"""Get the items fetched by the jobs."""
# Get and remove queued items in an atomic transaction
pipe = self.conn.pipeline()
pipe.lrange(Q_STORAGE_ITEMS, 0, -1)
pipe.ltrim(Q_STORAGE_ITEMS, 1, 0)
items = pipe.execute()[0]
for item in items:
... | python | {
"resource": ""
} |
q273927 | Arthur.__validate_args | test | def __validate_args(task_id, backend, category, backend_args):
"""Check that the task arguments received are valid"""
if not task_id or task_id.strip() == "":
msg = "Missing task_id for task"
raise ValueError(msg)
if not backend or backend.strip() == "":
msg... | python | {
"resource": ""
} |
q273928 | Arthur.__parse_archive_args | test | def __parse_archive_args(self, archive_args):
"""Parse the archive arguments of a task"""
if not archive_args:
return None
archiving_args = copy.deepcopy(archive_args)
if self.archive_path:
archiving_args['archive_path'] = self.archive_path
else:
... | python | {
"resource": ""
} |
q273929 | ArthurWorker.perform_job | test | def perform_job(self, job, queue):
"""Custom method to execute a job and notify of its result
:param job: Job object
:param queue: the queue containing the object
"""
result = super().perform_job(job, queue)
job_status = job.get_status()
job_result = job.return... | python | {
"resource": ""
} |
q273930 | _JobScheduler.schedule_job_task | test | def schedule_job_task(self, queue_id, task_id, job_args, delay=0):
"""Schedule a job in the given queue."""
self._rwlock.writer_acquire()
job_id = self._generate_job_id(task_id)
event = self._scheduler.enter(delay, 1, self._enqueue_job,
argument=(... | python | {
"resource": ""
} |
q273931 | _JobScheduler.cancel_job_task | test | def cancel_job_task(self, task_id):
"""Cancel the job related to the given task."""
try:
self._rwlock.writer_acquire()
job_id = self._tasks.get(task_id, None)
if job_id:
self._cancel_job(job_id)
else:
logger.warning("Task... | python | {
"resource": ""
} |
q273932 | _JobListener.run | test | def run(self):
"""Run thread to listen for jobs and reschedule successful ones."""
try:
self.listen()
except Exception as e:
logger.critical("JobListener instence crashed. Error: %s", str(e))
logger.critical(traceback.format_exc()) | python | {
"resource": ""
} |
q273933 | _JobListener.listen | test | def listen(self):
"""Listen for completed jobs and reschedule successful ones."""
pubsub = self.conn.pubsub()
pubsub.subscribe(self.pubsub_channel)
logger.debug("Listening on channel %s", self.pubsub_channel)
for msg in pubsub.listen():
logger.debug("New message re... | python | {
"resource": ""
} |
q273934 | Scheduler.schedule | test | def schedule(self):
"""Start scheduling jobs."""
if self.async_mode:
self._scheduler.start()
self._listener.start()
else:
self._scheduler.schedule() | python | {
"resource": ""
} |
q273935 | Scheduler.schedule_task | test | def schedule_task(self, task_id):
"""Schedule a task.
:param task_id: identifier of the task to schedule
:raises NotFoundError: raised when the requested task is not
found in the registry
"""
task = self.registry.get(task_id)
job_args = self._build_job_argu... | python | {
"resource": ""
} |
q273936 | Scheduler.cancel_task | test | def cancel_task(self, task_id):
"""Cancel or 'un-schedule' a task.
:param task_id: identifier of the task to cancel
:raises NotFoundError: raised when the requested task is not
found in the registry
"""
self.registry.remove(task_id)
self._scheduler.cancel_jo... | python | {
"resource": ""
} |
q273937 | Scheduler._handle_successful_job | test | def _handle_successful_job(self, job):
"""Handle successufl jobs"""
result = job.result
task_id = job.kwargs['task_id']
try:
task = self.registry.get(task_id)
except NotFoundError:
logger.warning("Task %s not found; related job #%s will not be reschedule... | python | {
"resource": ""
} |
q273938 | Scheduler._handle_failed_job | test | def _handle_failed_job(self, job):
"""Handle failed jobs"""
task_id = job.kwargs['task_id']
logger.error("Job #%s (task: %s) failed; cancelled",
job.id, task_id) | python | {
"resource": ""
} |
q273939 | Scheduler._build_job_arguments | test | def _build_job_arguments(task):
"""Build the set of arguments required for running a job"""
job_args = {}
job_args['qitems'] = Q_STORAGE_ITEMS
job_args['task_id'] = task.task_id
# Backend parameters
job_args['backend'] = task.backend
backend_args = copy.deepcopy... | python | {
"resource": ""
} |
q273940 | get_secret | test | def get_secret(secret_name, default=None):
"""
Gets contents of secret file
:param secret_name: The name of the secret present in BANANAS_SECRETS_DIR
:param default: Default value to return if no secret was found
:return: The secret or default if not found
"""
secrets_dir = get_secrets_dir(... | python | {
"resource": ""
} |
q273941 | register | test | def register(view): # Type[BananasAPI]
"""
Register the API view class in the bananas router.
:param BananasAPI view:
"""
meta = view.get_admin_meta()
prefix = meta.basename.replace(".", "/")
router.register(prefix, view, meta.basename) | python | {
"resource": ""
} |
q273942 | register | test | def register(view=None, *, admin_site=None, admin_class=ModelAdminView):
"""
Register a generic class based view wrapped with ModelAdmin and fake model
:param view: The AdminView to register.
:param admin_site: The AdminSite to register the view on.
Defaults to bananas.admin.ExtendedAdminSite.
... | python | {
"resource": ""
} |
q273943 | BananasAPI.reverse_action | test | def reverse_action(self, url_name, *args, **kwargs):
"""
Extended DRF with fallback to requested namespace if request.version is missing
"""
if self.request and not self.request.version:
return reverse(self.get_url_name(url_name), *args, **kwargs)
return super().reve... | python | {
"resource": ""
} |
q273944 | BananasAPI.get_view_name | test | def get_view_name(self, respect_name=True):
"""
Get or generate human readable view name.
Extended version from DRF to support usage from both class and instance.
"""
if isinstance(self, type):
view = self
else:
view = self.__class__
# Nam... | python | {
"resource": ""
} |
q273945 | get_version | test | def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ("alpha", "beta", "rc", "final")
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub =... | python | {
"resource": ""
} |
q273946 | resolve | test | def resolve(cursor, key):
"""
Get engine or raise exception, resolves Alias-instances to a sibling target.
:param cursor: The object so search in
:param key: The key to get
:return: The object found
"""
try:
result = cursor[key]
# Resolve alias
if isinstance(result,... | python | {
"resource": ""
} |
q273947 | get_engine | test | def get_engine(scheme):
"""
Perform a lookup in _ENGINE_MAPPING using engine_string.
:param scheme: '+'-separated string Maximum of 2 parts,
i.e "postgres+psycopg" is OK, "postgres+psycopg2+postgis" is NOT OK.
:return: Engine string
"""
path = scheme.split("+")
first, rest = path[0], pa... | python | {
"resource": ""
} |
q273948 | parse_path | test | def parse_path(path):
"""
Get database name and database schema from path.
:param path: "/"-delimited path, parsed as
"/<database name>/<database schema>"
:return: tuple with (database or None, schema or None)
"""
if path is None:
raise ValueError("path must be a string")
part... | python | {
"resource": ""
} |
q273949 | database_conf_from_url | test | def database_conf_from_url(url):
"""
Return a django-style database configuration based on ``url``.
:param url: Database URL
:return: Django-style database configuration dict
Example:
>>> conf = database_conf_from_url(
... 'pgsql://joar:hunter2@5monkeys.se:4242/tweets/tweetschema'
... | python | {
"resource": ""
} |
q273950 | parse_database_url | test | def parse_database_url(url):
"""
Parse a database URL and return a DatabaseInfo named tuple.
:param url: Database URL
:return: DatabaseInfo instance
Example:
>>> conf = parse_database_url(
... 'pgsql://joar:hunter2@5monkeys.se:4242/tweets/tweetschema'
... '?hello=world')
>>... | python | {
"resource": ""
} |
q273951 | LoginAPI.create | test | def create(self, request):
"""
Log in django staff user
"""
# TODO: Decorate api with sensitive post parameters as Django admin do?
# from django.utils.decorators import method_decorator
# from django.views.decorators.debug import sensitive_post_parameters
# sensi... | python | {
"resource": ""
} |
q273952 | MeAPI.list | test | def list(self, request):
"""
Retrieve logged in user info
"""
serializer = self.get_serializer(request.user)
return Response(serializer.data, status=status.HTTP_200_OK) | python | {
"resource": ""
} |
q273953 | ChangePasswordAPI.create | test | def create(self, request):
"""
Change password for logged in django staff user
"""
# TODO: Decorate api with sensitive post parameters as Django admin do?
password_form = PasswordChangeForm(request.user, data=request.data)
if not password_form.is_valid():
ra... | python | {
"resource": ""
} |
q273954 | UserDetailsSerializer.build_url_field | test | def build_url_field(self, field_name, model_class):
"""
This is needed due to DRF's model serializer uses the queryset to build url name
# TODO: Move this to own serializer mixin or fix problem elsewhere?
"""
field, kwargs = super().build_url_field(field_name, model_class)
... | python | {
"resource": ""
} |
q273955 | parse_bool | test | def parse_bool(value):
"""
Parse string to bool.
:param str value: String value to parse as bool
:return bool:
"""
boolean = parse_str(value).capitalize()
if boolean in ("True", "Yes", "On", "1"):
return True
elif boolean in ("False", "No", "Off", "0"):
return False
... | python | {
"resource": ""
} |
q273956 | parse_int | test | def parse_int(value):
"""
Parse numeric string to int. Supports oct formatted string.
:param str value: String value to parse as int
:return int:
"""
value = parse_str(value=value)
if value.startswith("0"):
return int(value.lstrip("0o"), 8)
else:
return int(value) | python | {
"resource": ""
} |
q273957 | get_parser | test | def get_parser(typ):
"""
Return appropriate parser for given type.
:param typ: Type to get parser for.
:return function: Parser
"""
try:
return {
str: parse_str,
bool: parse_bool,
int: parse_int,
tuple: parse_tuple,
list: parse... | python | {
"resource": ""
} |
q273958 | get_settings | test | def get_settings():
"""
Get and parse prefixed django settings from env.
TODO: Implement support for complex settings
DATABASES = {}
CACHES = {}
INSTALLED_APPS -> EXCLUDE_APPS ?
:return dict:
"""
settings = {}
prefix = environ.get("DJANGO_SETTINGS_PREFIX", "DJANGO_"... | python | {
"resource": ""
} |
q273959 | ModelDict.from_model | test | def from_model(cls, model, *fields, **named_fields):
"""
Work-in-progress constructor,
consuming fields and values from django model instance.
"""
d = ModelDict()
if not (fields or named_fields):
# Default to all fields
fields = [f.attname for f i... | python | {
"resource": ""
} |
q273960 | URLSecretField.y64_encode | test | def y64_encode(s):
"""
Implementation of Y64 non-standard URL-safe base64 variant.
See http://en.wikipedia.org/wiki/Base64#Variants_summary_table
:return: base64-encoded result with substituted
``{"+", "/", "="} => {".", "_", "-"}``.
"""
first_pass = base64.urls... | python | {
"resource": ""
} |
q273961 | create_field | test | def create_field(field_info):
"""
Create a field by field info dict.
"""
field_type = field_info.get('type')
if field_type not in FIELDS_NAME_MAP:
raise ValueError(_('not support this field: {}').format(field_type))
field_class = FIELDS_NAME_MAP.get(field_type)
params = dict(field_in... | python | {
"resource": ""
} |
q273962 | create_validator | test | def create_validator(data_struct_dict, name=None):
"""
create a Validator instance from data_struct_dict
:param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned.
:param name: name of Validator class
:return: Validator instance
"""
if name is... | python | {
"resource": ""
} |
q273963 | cartesian_product | test | def cartesian_product(parameter_dict, combined_parameters=()):
""" Generates a Cartesian product of the input parameter dictionary.
For example:
>>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]})
{'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]}
:param paramet... | python | {
"resource": ""
} |
q273964 | find_unique_points | test | def find_unique_points(explored_parameters):
"""Takes a list of explored parameters and finds unique parameter combinations.
If parameter ranges are hashable operates in O(N), otherwise O(N**2).
:param explored_parameters:
List of **explored** parameters
:return:
List of tuples, fir... | python | {
"resource": ""
} |
q273965 | _change_logging_kwargs | test | def _change_logging_kwargs(kwargs):
""" Helper function to turn the simple logging kwargs into a `log_config`."""
log_levels = kwargs.pop('log_level', None)
log_folder = kwargs.pop('log_folder', 'logs')
logger_names = kwargs.pop('logger_names', '')
if log_levels is None:
log_levels = kwargs.... | python | {
"resource": ""
} |
q273966 | simple_logging_config | test | def simple_logging_config(func):
"""Decorator to allow a simple logging configuration.
This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`.
"""
@functools.wraps(func)
def new_func(self, *args, **kwargs):
if use_simple_logging(kwargs):
if 'log_config'... | python | {
"resource": ""
} |
q273967 | try_make_dirs | test | def try_make_dirs(filename):
""" Tries to make directories for a given `filename`.
Ignores any error but notifies via stderr.
"""
try:
dirname = os.path.dirname(os.path.normpath(filename))
racedirs(dirname)
except Exception as exc:
sys.stderr.write('ERROR during log config ... | python | {
"resource": ""
} |
q273968 | get_strings | test | def get_strings(args):
"""Returns all valid python strings inside a given argument string."""
string_list = []
for elem in ast.walk(ast.parse(args)):
if isinstance(elem, ast.Str):
string_list.append(elem.s)
return string_list | python | {
"resource": ""
} |
q273969 | rename_log_file | test | def rename_log_file(filename, trajectory=None,
env_name=None,
traj_name=None,
set_name=None,
run_name=None,
process_name=None,
host_name=None):
""" Renames a given `filename` with valid wildcard p... | python | {
"resource": ""
} |
q273970 | HasLogger._set_logger | test | def _set_logger(self, name=None):
"""Adds a logger with a given `name`.
If no name is given, name is constructed as
`type(self).__name__`.
"""
if name is None:
cls = self.__class__
name = '%s.%s' % (cls.__module__, cls.__name__)
self._logger = lo... | python | {
"resource": ""
} |
q273971 | LoggingManager.extract_replacements | test | def extract_replacements(self, trajectory):
"""Extracts the wildcards and file replacements from the `trajectory`"""
self.env_name = trajectory.v_environment_name
self.traj_name = trajectory.v_name
self.set_name = trajectory.f_wildcard('$set')
self.run_name = trajectory.f_wildca... | python | {
"resource": ""
} |
q273972 | LoggingManager.show_progress | test | def show_progress(self, n, total_runs):
"""Displays a progressbar"""
if self.report_progress:
percentage, logger_name, log_level = self.report_progress
if logger_name == 'print':
logger = 'print'
else:
logger = logging.getLogger(logger_... | python | {
"resource": ""
} |
q273973 | LoggingManager._check_and_replace_parser_args | test | def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True):
""" Searches for parser settings that define filenames.
If such settings are found, they are renamed according to the wildcard
rules. Moreover, it is also tried to create the corresponding folders.
... | python | {
"resource": ""
} |
q273974 | LoggingManager._parser_to_string_io | test | def _parser_to_string_io(parser):
"""Turns a ConfigParser into a StringIO stream."""
memory_file = StringIO()
parser.write(memory_file)
memory_file.flush()
memory_file.seek(0)
return memory_file | python | {
"resource": ""
} |
q273975 | LoggingManager._find_multiproc_options | test | def _find_multiproc_options(parser):
""" Searches for multiprocessing options within a ConfigParser.
If such options are found, they are copied (without the `'multiproc_'` prefix)
into a new parser.
"""
sections = parser.sections()
if not any(section.startswith('multipr... | python | {
"resource": ""
} |
q273976 | LoggingManager._find_multiproc_dict | test | def _find_multiproc_dict(dictionary):
""" Searches for multiprocessing options in a given `dictionary`.
If found they are copied (without the `'multiproc_'` prefix)
into a new dictionary
"""
if not any(key.startswith('multiproc_') for key in dictionary.keys()):
retu... | python | {
"resource": ""
} |
q273977 | LoggingManager.check_log_config | test | def check_log_config(self):
""" Checks and converts all settings if necessary passed to the Manager.
Searches for multiprocessing options as well.
"""
if self.report_progress:
if self.report_progress is True:
self.report_progress = (5, 'pypet', logging.INFO)... | python | {
"resource": ""
} |
q273978 | LoggingManager._handle_config_parsing | test | def _handle_config_parsing(self, log_config):
""" Checks for filenames within a config file and translates them.
Moreover, directories for the files are created as well.
:param log_config: Config file as a stream (like StringIO)
"""
parser = NoInterpolationParser()
par... | python | {
"resource": ""
} |
q273979 | LoggingManager._handle_dict_config | test | def _handle_dict_config(self, log_config):
"""Recursively walks and copies the `log_config` dict and searches for filenames.
Translates filenames and creates directories if necessary.
"""
new_dict = dict()
for key in log_config.keys():
if key == 'filename':
... | python | {
"resource": ""
} |
q273980 | LoggingManager.make_logging_handlers_and_tools | test | def make_logging_handlers_and_tools(self, multiproc=False):
"""Creates logging handlers and redirects stdout."""
log_stdout = self.log_stdout
if sys.stdout is self._stdout_to_logger:
# If we already redirected stdout we don't neet to redo it again
log_stdout = False
... | python | {
"resource": ""
} |
q273981 | LoggingManager.finalize | test | def finalize(self, remove_all_handlers=True):
"""Finalizes the manager, closes and removes all handlers if desired."""
for tool in self._tools:
tool.finalize()
self._tools = []
self._stdout_to_logger = None
for config in (self._sp_config, self._mp_config):
... | python | {
"resource": ""
} |
q273982 | StdoutToLogger.start | test | def start(self):
"""Starts redirection of `stdout`"""
if sys.stdout is not self:
self._original_steam = sys.stdout
sys.stdout = self
self._redirection = True
if self._redirection:
print('Established redirection of `stdout`.') | python | {
"resource": ""
} |
q273983 | StdoutToLogger.write | test | def write(self, buf):
"""Writes data from buffer to logger"""
if not self._recursion:
self._recursion = True
try:
for line in buf.rstrip().splitlines():
self._logger.log(self._log_level, line.rstrip())
finally:
self.... | python | {
"resource": ""
} |
q273984 | results_equal | test | def results_equal(a, b):
"""Compares two result instances
Checks full name and all data. Does not consider the comment.
:return: True or False
:raises: ValueError if both inputs are no result instances
"""
if a.v_is_parameter and b.v_is_parameter:
raise ValueError('Both inputs are no... | python | {
"resource": ""
} |
q273985 | parameters_equal | test | def parameters_equal(a, b):
"""Compares two parameter instances
Checks full name, data, and ranges. Does not consider the comment.
:return: True or False
:raises: ValueError if both inputs are no parameter instances
"""
if (not b.v_is_parameter and
not a.v_is_parameter):
... | python | {
"resource": ""
} |
q273986 | manual_run | test | def manual_run(turn_into_run=True, store_meta_data=True, clean_up=True):
"""Can be used to decorate a function as a manual run function.
This can be helpful if you want the run functionality without using an environment.
:param turn_into_run:
If the trajectory should become a `single run` with mo... | python | {
"resource": ""
} |
q273987 | deprecated | test | def deprecated(msg=''):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emitted
when the function is used.
:param msg:
Additional message added to the warning.
"""
def wrapper(func):
@functools.wraps(func)
de... | python | {
"resource": ""
} |
q273988 | kwargs_mutual_exclusive | test | def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None):
""" If there exist mutually exclusive parameters checks for them and maps param2 to 1."""
def wrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
if param2_name in kwargs:
if param1_... | python | {
"resource": ""
} |
q273989 | kwargs_api_change | test | def kwargs_api_change(old_name, new_name=None):
"""This is a decorator which can be used if a kwarg has changed
its name over versions to also support the old argument name.
Issues a warning if the old keyword argument is detected and
converts call to new API.
:param old_name:
Old name of... | python | {
"resource": ""
} |
q273990 | retry | test | def retry(n, errors, wait=0.0, logger_name=None):
"""This is a decorator that retries a function.
Tries `n` times and catches a given tuple of `errors`.
If the `n` retries are not enough, the error is reraised.
If desired `waits` some seconds.
Optionally takes a 'logger_name' of a given logger t... | python | {
"resource": ""
} |
q273991 | prefix_naming | test | def prefix_naming(cls):
"""Decorate that adds the prefix naming scheme"""
if hasattr(cls, '__getattr__'):
raise TypeError('__getattr__ already defined')
cls.__getattr__ = _prfx_getattr_
cls.__setattr__ = _prfx_setattr_
return cls | python | {
"resource": ""
} |
q273992 | add_params | test | def add_params(traj):
"""Adds all necessary parameters to `traj`."""
# We set the BrianParameter to be the standard parameter
traj.v_standard_parameter=Brian2Parameter
traj.v_fast_access=True
# Add parameters we need for our network
traj.f_add_parameter('Net.C',281*pF)
traj.f_add_parameter... | python | {
"resource": ""
} |
q273993 | run_net | test | def run_net(traj):
"""Creates and runs BRIAN network based on the parameters in `traj`."""
eqs=traj.eqs
# Create a namespace dictionairy
namespace = traj.Net.f_to_dict(short_names=True, fast_access=True)
# Create the Neuron Group
neuron=NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset... | python | {
"resource": ""
} |
q273994 | euler_scheme | test | def euler_scheme(traj, diff_func):
"""Simulation function for Euler integration.
:param traj:
Container for parameters and results
:param diff_func:
The differential equation we want to integrate
"""
steps = traj.steps
initial_conditions = traj.initial_conditions
dimens... | python | {
"resource": ""
} |
q273995 | add_parameters | test | def add_parameters(traj):
"""Adds all necessary parameters to the `traj` container"""
traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate')
traj.f_add_parameter('dt', 0.01, comment='Step size')
# Here we want to add the initial conditions as an array parameter. We will simul... | python | {
"resource": ""
} |
q273996 | diff_lorenz | test | def diff_lorenz(value_array, sigma, beta, rho):
"""The Lorenz attractor differential equation
:param value_array: 3d array containing the x,y, and z component values.
:param sigma: Constant attractor parameter
:param beta: FConstant attractor parameter
:param rho: Constant attractor parameter
... | python | {
"resource": ""
} |
q273997 | _create_storage | test | def _create_storage(storage_service, trajectory=None, **kwargs):
"""Creates a service from a constructor and checks which kwargs are not used"""
kwargs_copy = kwargs.copy()
kwargs_copy['trajectory'] = trajectory
matching_kwargs = get_matching_kwargs(storage_service, kwargs_copy)
storage_service = st... | python | {
"resource": ""
} |
q273998 | storage_factory | test | def storage_factory(storage_service, trajectory=None, **kwargs):
"""Creates a storage service, to be extended if new storage services are added
:param storage_service:
Storage Service instance of constructor or a string pointing to a file
:param trajectory:
A trajectory instance
:pa... | python | {
"resource": ""
} |
q273999 | add_parameters | test | def add_parameters(traj):
"""Adds all necessary parameters to the `traj` container.
You can choose between two parameter sets. One for the Lorenz attractor and
one for the Roessler attractor.
The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for
`traj.diff_name=='diff_roessler'`.... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.