_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 information.
See :py:class:`CLIEncrypt` for more information.
"""
with context.io_manager.with_stdout() as stdout:
with context.io_manager.with_stdin() as stdin:
for chunk in aes_encrypt(key, stdin, preamble=AES256CBC):
stdout.write(chunk)
stdout.flush() | 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 of the owner/repo
:param sha: SHA for the status we are looking for
:return: returns json response of status
"""
url = get_api_url(app, repo_config, github_status_url).format(
repo_name=repo_name, sha=sha)
logging.debug("Getting status for %s %s", repo_name, sha)
s = get_session_for_repo(app, repo_config)
response = s.get(url)
if not response.ok:
raise Exception("Unable to get status: {}".format(response.status_code))
return response | 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}}/pulls/{0}".format(pull_request))
if not response.ok:
raise Exception("Unable to get pull request: status code {}".format(response.status_code))
return response.json | 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:
raise Exception("Unable to get pull requests: status code {}".format(response.status_code))
return (item for item in response.json) | 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` exception will be raised.
:param task_id: identifier of the task to add
:param backend: backend used to fetch data from the repository
:param category: category of the items to fetch
:param backend_args: dictionary of arguments required to run the backend
:param archiving_cfg: archiving config for the task, if needed
:param scheduling_cfg: scheduling config for the task, if needed
:returns: the new task added to the registry
:raises AlreadyExistsError: raised when the given task identifier
exists on the registry
"""
self._rwlock.writer_acquire()
if task_id in self._tasks:
self._rwlock.writer_release()
raise AlreadyExistsError(element=str(task_id))
task = Task(task_id, backend, category, backend_args,
archiving_cfg=archiving_cfg,
scheduling_cfg=scheduling_cfg)
self._tasks[task_id] = task
self._rwlock.writer_release()
logger.debug("Task %s added to the registry", str(task_id))
return task | 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: raised when the given task identifier
is not found on the registry
"""
try:
self._rwlock.writer_acquire()
del self._tasks[task_id]
except KeyError:
raise NotFoundError(element=str(task_id))
finally:
self._rwlock.writer_release()
logger.debug("Task %s removed from the registry", str(task_id)) | 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 NotFoundError: raised when the requested task is not
found on the registry
"""
try:
self._rwlock.reader_acquire()
task = self._tasks[task_id]
except KeyError:
raise NotFoundError(element=str(task_id))
finally:
self._rwlock.reader_release()
return task | 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 to create an instance of this object
:returns: a task config instance
:raises ValueError: when an invalid configuration parameter is found
"""
try:
obj = cls(**config)
except TypeError as e:
m = cls.KW_ARGS_ERROR_REGEX.match(str(e))
if m:
raise ValueError("unknown '%s' task config parameter" % m.group(1))
else:
raise e
else:
return obj | 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`, raw data will be stored
with the archive manager. The contents from the archive can
be retrieved setting the pameter `fetch_from_archive` to `True`,
too. Take into account this behaviour will be only available
when the backend supports the use of the archive. If archiving
is not supported, an `AttributeError` exception will be raised.
:param backend: backend to execute
:param bakend_args: dict of arguments for running the backend
:param qitems: name of the RQ queue used to store the items
:param task_id: identifier of the task linked to this job
:param category: category of the items to retrieve
:param archive_args: archive arguments
:param max_retries: maximum number of attempts this job can execute
before failing
:returns: a `JobResult` instance
:raises NotFoundError: raised when the backend is not found
:raises AttributeError: raised when archiving is not supported but
any of the archive parameters were set
"""
rq_job = rq.get_current_job()
job = PercevalJob(rq_job.id, task_id, backend, category,
rq_job.connection, qitems)
logger.debug("Running job #%s (task: %s) (%s) (cat:%s)",
job.job_id, task_id, backend, category)
if not job.has_archiving() and archive_args:
raise AttributeError("archive attributes set but archive is not supported")
run_job = True
resume = False
failures = 0
while run_job:
try:
job.run(backend_args, archive_args=archive_args, resume=resume)
except AttributeError as e:
raise e
except Exception as e:
logger.debug("Error running job %s (%s) - %s",
job.job_id, backend, str(e))
failures += 1
if not job.has_resuming() or failures >= max_retries:
logger.error("Cancelling job #%s (task: %s) (%s)",
job.job_id, task_id, backend)
raise e
logger.warning("Resuming job #%s (task: %s) (%s) due to a failure (n %s, max %s)",
job.job_id, task_id, backend, failures, max_retries)
resume = True
else:
# No failure, do not retry
run_job = False
result = job.result
logger.debug("Job #%s (task: %s) completed (%s) - %s items (%s) fetched",
result.job_id, task_id, result.backend, str(result.nitems), result.category)
return result | 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:
self.archive_manager = perceval.archive.ArchiveManager(archive_path) | 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
`result`. When `resume` is set, the job will start from
the last execution, overwriting 'from_date' and 'offset'
parameters, if needed.
Setting to `True` the parameter `fetch_from_archive`, items can
be fetched from the archive assigned to this job.
Any exception during the execution of the process will
be raised.
:param backend_args: parameters used to un the backend
:param archive_args: archive arguments
:param resume: fetch items starting where the last
execution stopped
"""
args = backend_args.copy()
if archive_args:
self.initialize_archive_manager(archive_args['archive_path'])
if not resume:
max_date = backend_args.get('from_date', None)
offset = backend_args.get('offset', None)
if max_date:
max_date = datetime_to_utc(max_date).timestamp()
self._result = JobResult(self.job_id, self.task_id, self.backend, self.category,
None, max_date, 0, offset=offset,
nresumed=0)
else:
if self.result.max_date:
args['from_date'] = unixtime_to_datetime(self.result.max_date)
if self.result.offset:
args['offset'] = self.result.offset
self._result.nresumed += 1
for item in self._execute(args, archive_args):
self.conn.rpush(self.qitems, pickle.dumps(item))
self._result.nitems += 1
self._result.last_uuid = item['uuid']
if not self.result.max_date or self.result.max_date < item['updated_on']:
self._result.max_date = item['updated_on']
if 'offset' in item:
self._result.offset = item['offset'] | 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 related to the execution of the backend
will be raised too.
This method will return an iterator of the items fetched
by the backend. These items will include some metadata
related to this job.
It will also be possible to retrieve the items from the
archive setting to `True` the parameter `fetch_from_archive`.
:param backend_args: arguments to execute the backend
:param archive_args: archive arguments
:returns: iterator of items fetched by the backend
:raises AttributeError: raised when any of the required
parameters is not found
"""
if not archive_args or not archive_args['fetch_from_archive']:
return perceval.backend.fetch(self._bklass, backend_args, self.category,
manager=self.archive_manager)
else:
return perceval.backend.fetch_from_archive(self._bklass, backend_args,
self.archive_manager, self.category,
archive_args['archived_after']) | 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)
if r.status_code != 200:
# The index does not exist
r = requests.put(idx_url)
if r.status_code != 200:
logger.info("Can't create index %s (%s)", idx_url, r.status_code)
cause = "Error creating Elastic Search index %s" % idx_url
raise ElasticSearchError(cause=cause)
logger.info("Index %s created", idx_url)
return True
elif r.status_code == 200 and clean:
requests.delete(idx_url)
requests.put(idx_url)
logger.info("Index deleted and created (index: %s)", idx_url)
return True
return False | 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 requests.exceptions.ConnectionError:
cause = "Error connecting to Elastic Search (index: %s, url: %s)" \
% (idx_url, mapping_url)
raise ElasticSearchError(cause=cause)
if r.status_code != 200:
reason = r.json()['error']
logger.info("Can't create mapping in %s. %s",
mapping_url, reason)
cause = "Error creating Elastic Search mapping %s. %s" % \
(mapping_url, reason)
raise ElasticSearchError(cause=cause)
else:
logger.info("Mapping created in %s", mapping_url) | 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: args needed to initialize the backend
:param archive_args: args needed to initialize the archive
:param sched_args: scheduling args for this task
:returns: the task created
"""
try:
archiving_cfg = self.__parse_archive_args(archive_args)
scheduling_cfg = self.__parse_schedule_args(sched_args)
self.__validate_args(task_id, backend, category, backend_args)
except ValueError as e:
raise e
try:
task = self._tasks.add(task_id, backend, category, backend_args,
archiving_cfg=archiving_cfg,
scheduling_cfg=scheduling_cfg)
except AlreadyExistsError as e:
raise e
self._scheduler.schedule_task(task.task_id)
return task | 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.",
task_id)
return False
else:
return True | 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:
item = pickle.loads(item)
yield item | 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 = "Missing backend for task '%s'" % task_id
raise ValueError(msg)
if backend_args and not isinstance(backend_args, dict):
msg = "Backend_args is not a dict, task '%s'" % task_id
raise ValueError(msg)
if not category or category.strip() == "":
msg = "Missing category for task '%s'" % task_id
raise ValueError(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:
archiving_args['archive_path'] = os.path.expanduser(ARCHIVES_DEFAULT_PATH)
return ArchivingTaskConfig.from_dict(archiving_args) | 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_value if job_status == 'finished' else None
data = {
'job_id': job.id,
'status': job_status,
'result': job_result
}
msg = pickle.dumps(data)
self.connection.publish(self.pubsub_channel, msg)
return result | 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=(queue_id, job_id, job_args,))
self._jobs[job_id] = event
self._tasks[task_id] = job_id
self._rwlock.writer_release()
logging.debug("Job #%s (task: %s) scheduled on %s (wait: %s)",
job_id, task_id, queue_id, delay)
return job_id | 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 %s set to be removed was not found",
task_id)
finally:
self._rwlock.writer_release() | 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 received of type %s", str(msg['type']))
if msg['type'] != 'message':
logger.debug("Ignoring job message")
continue
data = pickle.loads(msg['data'])
job_id = data['job_id']
job = rq.job.Job.fetch(job_id, connection=self.conn)
if data['status'] == 'finished':
logging.debug("Job #%s completed", job_id)
handler = self.result_handler
elif data['status'] == 'failed':
logging.debug("Job #%s failed", job_id)
handler = self.result_handler_err
else:
continue
if handler:
logging.debug("Calling handler for job #%s", job_id)
handler(job) | 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_arguments(task)
archiving_cfg = task.archiving_cfg
fetch_from_archive = False if not archiving_cfg else archiving_cfg.fetch_from_archive
# Schedule the job as soon as possible
queue = Q_ARCHIVE_JOBS if fetch_from_archive else Q_CREATION_JOBS
job_id = self._scheduler.schedule_job_task(queue,
task.task_id, job_args,
delay=0)
logger.info("Job #%s (task: %s) scheduled", job_id, task.task_id)
return job_id | 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_job_task(task_id)
logger.info("Task %s canceled", task_id) | 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 rescheduled",
task_id, job.id)
return
if task.archiving_cfg and task.archiving_cfg.fetch_from_archive:
logger.info("Job #%s (task: %s) successfully finished", job.id, task_id)
return
if result.nitems > 0:
task.backend_args['next_from_date'] = unixtime_to_datetime(result.max_date)
if result.offset:
task.backend_args['next_offset'] = result.offset
job_args = self._build_job_arguments(task)
delay = task.scheduling_cfg.delay if task.scheduling_cfg else WAIT_FOR_QUEUING
job_id = self._scheduler.schedule_job_task(Q_UPDATING_JOBS,
task_id, job_args,
delay=delay)
logger.info("Job #%s (task: %s, old job: %s) re-scheduled",
job_id, task_id, job.id) | 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(task.backend_args)
if 'next_from_date' in backend_args:
backend_args['from_date'] = backend_args.pop('next_from_date')
if 'next_offset' in backend_args:
backend_args['offset'] = backend_args.pop('next_offset')
job_args['backend_args'] = backend_args
# Category
job_args['category'] = task.category
# Archiving parameters
archiving_cfg = task.archiving_cfg
job_args['archive_args'] = archiving_cfg.to_dict() if archiving_cfg else None
# Scheduler parameters
sched_cfg = task.scheduling_cfg
job_args['max_retries'] = sched_cfg.max_retries if sched_cfg else MAX_JOB_RETRIES
return job_args | 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()
secret_path = os.path.join(secrets_dir, secret_name)
try:
with open(secret_path, "r") as secret_file:
return secret_file.read()
except OSError:
return default | 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.
:param admin_class: The ModelAdmin class to use for eg. permissions.
Defaults to bananas.admin.ModelAdminView.
Example:
@register # Or with args @register(admin_class=MyModelAdminSubclass)
class MyAdminView(bananas.admin.AdminView):
def get(self, request):
return self.render('template.html', {})
# Also possible:
register(MyAdminView, admin_class=MyModelAdminSublass)
"""
if not admin_site:
admin_site = site
def wrapped(inner_view):
module = inner_view.__module__
app_label = re.search(r"\.?(\w+)\.admin", module).group(1)
app_config = apps.get_app_config(app_label)
label = getattr(inner_view, "label", None)
if not label:
label = re.sub("(Admin)|(View)", "", inner_view.__name__).lower()
inner_view.label = label
model_name = label.capitalize()
verbose_name = getattr(inner_view, "verbose_name", model_name)
inner_view.verbose_name = verbose_name
access_perm_codename = "can_access_" + model_name.lower()
access_perm_name = _("Can access {verbose_name}").format(
verbose_name=verbose_name
)
# The first permission here is expected to be
# the general access permission.
permissions = tuple(
[(access_perm_codename, access_perm_name)]
+ list(getattr(inner_view, "permissions", []))
)
model = type(
model_name,
(Model,),
{
"__module__": module + ".__models__", # Fake
"View": inner_view,
"app_config": app_config,
"Meta": type(
"Meta",
(object,),
dict(
managed=False,
abstract=True,
app_label=app_config.label,
verbose_name=verbose_name,
verbose_name_plural=verbose_name,
permissions=permissions,
),
),
},
)
admin_site._registry[model] = admin_class(model, admin_site)
return inner_view
if view is None: # Used as a decorator
return wrapped
return wrapped(view) | 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().reverse_action(url_name, *args, **kwargs) | 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__
# Name may be set by some Views, such as a ViewSet.
if respect_name:
name = getattr(view, "name", None)
if name is not None:
return name
name = view.__name__
for suffix in ("ViewSet", "View", "API", "Admin"):
name = formatting.remove_trailing_string(name, suffix)
name = formatting.camelcase_to_spaces(name)
# Suffix may be set by some Views, such as a ViewSet.
suffix = getattr(view, "suffix", None)
if suffix:
name += " " + suffix
return name | 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 = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if version[2] == 0 else 3
main = ".".join(str(x) for x in version[:parts])
sub = ""
if version[3] != "final":
mapping = {"alpha": "a", "beta": "b", "rc": "c"}
sub = mapping[version[3]] + str(version[4])
return main + 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, Alias):
result = cursor[result.target]
return result
except KeyError:
raise KeyError("No matches for engine %s" % key) | 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], path[1:]
second = rest[0] if rest else None
engine = resolve(ENGINE_MAPPING, first)
# If the selected engine does not have a second level.
if not isinstance(engine, list):
# If second level engine was expected
if second:
raise KeyError("%s has no sub-engines" % first)
return engine
try:
engine, extra = engine
except ValueError:
# engine was not a list of length 2
raise ValueError(
"django-bananas.url' engine "
"configuration is invalid: %r" % ENGINE_MAPPING
)
# Get second-level engine
if second is not None:
engine = resolve(extra, second)
# Sanity-check the value before returning
assert not isinstance(
engine, (list, dict)
), "Only two levels of engines " "are allowed"
assert engine, "The returned engine is not truthy"
return engine | 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")
parts = path.strip("/").split("/")
database = unquote_plus(parts[0]) if len(parts) else None
schema = parts[1] if len(parts) > 1 else None
return database, schema | 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'
... '?hello=world')
>>> sorted(conf.items()) # doctest: +NORMALIZE_WHITESPACE
[('ENGINE', 'django.db.backends.postgresql_psycopg2'),
('HOST', '5monkeys.se'),
('NAME', 'tweets'),
('PARAMS', {'hello': 'world'}),
('PASSWORD', 'hunter2'),
('PORT', 4242),
('SCHEMA', 'tweetschema'),
('USER', 'joar')]
"""
return {key.upper(): val for key, val in parse_database_url(url)._asdict().items()} | 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')
>>> conf # doctest: +NORMALIZE_WHITESPACE
DatabaseInfo(engine='django.db.backends.postgresql_psycopg2',
name='tweets',
schema='tweetschema',
user='joar',
password='hunter2',
host='5monkeys.se',
port=4242,
params={'hello': 'world'})
"""
if url == "sqlite://:memory:":
raise Exception(
'Your url is "sqlite://:memory:", if you want '
'an sqlite memory database, just use "sqlite://"'
)
url_parts = urlsplit(url)
engine = get_engine(url_parts.scheme)
database, schema = parse_path(url_parts.path)
port = url_parts.port
host = url_parts.hostname
user = url_parts.username
password = url_parts.password
# Take the last element of every parameter list
params = {key: val.pop() for key, val in parse_qs(url_parts.query).items()}
return DatabaseInfo(
engine=engine,
name=database,
schema=schema,
user=user,
password=password,
host=host,
port=port,
params=params,
) | 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
# sensitive_post_parameters_m = method_decorator(sensitive_post_parameters())
login_form = AuthenticationForm(request, data=request.data)
if not login_form.is_valid():
raise serializers.ValidationError(login_form.errors)
auth_login(request, login_form.get_user())
serializer = UserSerializer(request.user)
return Response(serializer.data, status=status.HTTP_200_OK) | 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():
raise serializers.ValidationError(password_form.errors)
password_form.save()
update_session_auth_hash(request, password_form.user)
return Response(status=status.HTTP_204_NO_CONTENT) | 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)
view = self.root.context["view"]
kwargs["view_name"] = view.get_url_name("detail")
return field, kwargs | 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
else:
raise ValueError('Unable to parse boolean value "{}"'.format(value)) | 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_list,
set: parse_set,
}[typ]
except KeyError:
raise NotImplementedError("Unsupported setting type: %r", typ) | 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_")
for key, value in environ.items():
_, _, key = key.partition(prefix)
if key:
if key in UNSUPPORTED_ENV_SETTINGS:
raise ValueError(
'Django setting "{}" can not be '
"configured through environment.".format(key)
)
default_value = getattr(global_settings, key, UNDEFINED)
if default_value is not UNDEFINED:
if default_value is None and key in SETTINGS_TYPES.keys():
# Handle typed django settings defaulting to None
parse = get_parser(SETTINGS_TYPES[key])
else:
# Determine parser by django setting type
parse = get_parser(type(default_value))
value = parse(value)
settings[key] = value
return settings | 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 in model._meta.concrete_fields]
not_found = object()
for name, field in chain(zip(fields, fields), named_fields.items()):
_fields = field.split("__")
value = model
for i, _field in enumerate(_fields, start=1):
# NOTE: we don't want to rely on hasattr here
previous_value = value
value = getattr(previous_value, _field, not_found)
if value is not_found:
if _field in dir(previous_value):
raise ValueError(
"{!r}.{} had an AttributeError exception".format(
previous_value, _field
)
)
else:
raise AttributeError(
"{!r} does not have {!r} attribute".format(
previous_value, _field
)
)
elif value is None:
if name not in named_fields:
name = "__".join(_fields[:i])
break
d[name] = value
return d | 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.urlsafe_b64encode(s)
return first_pass.translate(bytes.maketrans(b"+/=", b"._-")) | 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_info)
params.pop('type')
return field_class.from_dict(params) | 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 None:
name = 'FromDictValidator'
attrs = {}
for field_name, field_info in six.iteritems(data_struct_dict):
field_type = field_info['type']
if field_type == DictField.FIELD_TYPE_NAME and isinstance(field_info.get('validator'), dict):
field_info['validator'] = create_validator(field_info['validator'])
attrs[field_name] = create_field(field_info)
name = force_str(name)
return type(name, (Validator, ), attrs) | 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 parameter_dict:
Dictionary containing parameter names as keys and iterables of data to explore.
:param combined_parameters:
Tuple of tuples. Defines the order of the parameters and parameters that are
linked together.
If an inner tuple contains only a single item, you can spare the
inner tuple brackets.
For example:
>>> print cartesian_product( {'param1': [42.0, 52.5], 'param2':['a', 'b'], 'param3' : [1,2,3]}, ('param3',('param1', 'param2')))
{param3':[1,1,2,2,3,3],'param1' : [42.0,52.5,42.0,52.5,42.0,52.5], 'param2':['a','b','a','b','a','b']}
:returns: Dictionary with cartesian product lists.
"""
if not combined_parameters:
combined_parameters = list(parameter_dict)
else:
combined_parameters = list(combined_parameters)
for idx, item in enumerate(combined_parameters):
if isinstance(item, str):
combined_parameters[idx] = (item,)
iterator_list = []
for item_tuple in combined_parameters:
inner_iterator_list = [parameter_dict[key] for key in item_tuple]
zipped_iterator = zip(*inner_iterator_list)
iterator_list.append(zipped_iterator)
result_dict = {}
for key in parameter_dict:
result_dict[key] = []
cartesian_iterator = itools.product(*iterator_list)
for cartesian_tuple in cartesian_iterator:
for idx, item_tuple in enumerate(combined_parameters):
for inneridx, key in enumerate(item_tuple):
result_dict[key].append(cartesian_tuple[idx][inneridx])
return result_dict | 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, first entry being the parameter values, second entry a list
containing the run position of the unique combination.
"""
ranges = [param.f_get_range(copy=False) for param in explored_parameters]
zipped_tuples = list(zip(*ranges))
try:
unique_elements = OrderedDict()
for idx, val_tuple in enumerate(zipped_tuples):
if val_tuple not in unique_elements:
unique_elements[val_tuple] = []
unique_elements[val_tuple].append(idx)
return list(unique_elements.items())
except TypeError:
logger = logging.getLogger('pypet.find_unique')
logger.error('Your parameter entries could not be hashed, '
'now I am sorting slowly in O(N**2).')
unique_elements = []
for idx, val_tuple in enumerate(zipped_tuples):
matches = False
for added_tuple, pos_list in unique_elements:
matches = True
for idx2, val in enumerate(added_tuple):
if not explored_parameters[idx2]._equal_values(val_tuple[idx2], val):
matches = False
break
if matches:
pos_list.append(idx)
break
if not matches:
unique_elements.append((val_tuple, [idx]))
return unique_elements | 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.pop('log_levels', logging.INFO)
log_multiproc = kwargs.pop('log_multiproc', True)
if not isinstance(logger_names, (tuple, list)):
logger_names = [logger_names]
if not isinstance(log_levels, (tuple, list)):
log_levels = [log_levels]
if len(log_levels) == 1:
log_levels = [log_levels[0] for _ in logger_names]
# We don't want to manipulate the original dictionary
dictionary = copy.deepcopy(LOGGING_DICT)
prefixes = ['']
if not log_multiproc:
for key in list(dictionary.keys()):
if key.startswith('multiproc_'):
del dictionary[key]
else:
prefixes.append('multiproc_')
# Add all handlers to all loggers
for prefix in prefixes:
for handler_dict in dictionary[prefix + 'handlers'].values():
if 'filename' in handler_dict:
filename = os.path.join(log_folder, handler_dict['filename'])
filename = os.path.normpath(filename)
handler_dict['filename'] = filename
dictionary[prefix + 'loggers'] = {}
logger_dict = dictionary[prefix + 'loggers']
for idx, logger_name in enumerate(logger_names):
logger_dict[logger_name] = {
'level': log_levels[idx],
'handlers': list(dictionary[prefix + 'handlers'].keys())
}
kwargs['log_config'] = dictionary | 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' in kwargs:
raise ValueError('Please do not specify `log_config` '
'if you want to use the simple '
'way of providing logging configuration '
'(i.e using `log_folder`, `logger_names` and/or `log_levels`).')
_change_logging_kwargs(kwargs)
return func(self, *args, **kwargs)
return new_func | 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 file handling, could not create dirs for '
'filename `%s` because of: %s' % (filename, repr(exc))) | 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 placements.
:const:`~pypet.pypetconstants.LOG_ENV` ($env) is replaces by the name of the
trajectory`s environment.
:const:`~pypet.pypetconstants.LOG_TRAJ` ($traj) is replaced by the name of the
trajectory.
:const:`~pypet.pypetconstants.LOG_RUN` ($run) is replaced by the name of the current
run. If the trajectory is not set to a run 'run_ALL' is used.
:const:`~pypet.pypetconstants.LOG_SET` ($set) is replaced by the name of the current
run set. If the trajectory is not set to a run 'run_set_ALL' is used.
:const:`~pypet.pypetconstants.LOG_PROC` ($proc) is replaced by the name fo the
current process.
:const:`~pypet.pypetconstant.LOG_HOST` ($host) is replaced by the name of the current host.
:param filename: A filename string
:param traj: A trajectory container, leave `None` if you provide all the parameters below
:param env_name: Name of environemnt, leave `None` to get it from `traj`
:param traj_name: Name of trajectory, leave `None` to get it from `traj`
:param set_name: Name of run set, leave `None` to get it from `traj`
:param run_name: Name of run, leave `None` to get it from `traj`
:param process_name:
The name of the desired process. If `None` the name of the current process is
taken determined by the multiprocessing module.
:param host_name:
Name of host, leave `None` to determine it automatically with the platform module.
:return: The new filename
"""
if pypetconstants.LOG_ENV in filename:
if env_name is None:
env_name = trajectory.v_environment_name
filename = filename.replace(pypetconstants.LOG_ENV, env_name)
if pypetconstants.LOG_TRAJ in filename:
if traj_name is None:
traj_name = trajectory.v_name
filename = filename.replace(pypetconstants.LOG_TRAJ, traj_name)
if pypetconstants.LOG_RUN in filename:
if run_name is None:
run_name = trajectory.f_wildcard('$')
filename = filename.replace(pypetconstants.LOG_RUN, run_name)
if pypetconstants.LOG_SET in filename:
if set_name is None:
set_name = trajectory.f_wildcard('$set')
filename = filename.replace(pypetconstants.LOG_SET, set_name)
if pypetconstants.LOG_PROC in filename:
if process_name is None:
process_name = multip.current_process().name + '-' + str(os.getpid())
filename = filename.replace(pypetconstants.LOG_PROC, process_name)
if pypetconstants.LOG_HOST in filename:
if host_name is None:
host_name = socket.getfqdn().replace('.', '-')
filename = filename.replace(pypetconstants.LOG_HOST, host_name)
return filename | 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 = logging.getLogger(name) | 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_wildcard('$') | 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_name)
if n == -1:
# Compute the number of digits and avoid log10(0)
digits = int(math.log10(total_runs + 0.1)) + 1
self._format_string = 'PROGRESS: Finished %' + '%d' % digits + 'd/%d runs '
fmt_string = self._format_string % (n + 1, total_runs) + '%s'
reprint = log_level == 0
progressbar(n, total_runs, percentage_step=percentage,
logger=logger, log_level=log_level,
fmt_string=fmt_string, reprint=reprint) | 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.
:param parser: A config parser
:param section: A config section
:param option: The section option
:param rename_func: A function to rename found files
:param make_dirs: If the directories of the file should be created.
"""
args = parser.get(section, option, raw=True)
strings = get_strings(args)
replace = False
for string in strings:
isfilename = any(x in string for x in FILENAME_INDICATORS)
if isfilename:
newstring = rename_func(string)
if make_dirs:
try_make_dirs(newstring)
# To work with windows path specifications we need this replacement:
raw_string = string.replace('\\', '\\\\')
raw_newstring = newstring.replace('\\', '\\\\')
args = args.replace(raw_string, raw_newstring)
replace = True
if replace:
parser.set(section, option, args) | 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('multiproc_') for section in sections):
return None
mp_parser = NoInterpolationParser()
for section in sections:
if section.startswith('multiproc_'):
new_section = section.replace('multiproc_', '')
mp_parser.add_section(new_section)
options = parser.options(section)
for option in options:
val = parser.get(section, option, raw=True)
mp_parser.set(new_section, option, val)
return mp_parser | 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()):
return None
mp_dictionary = {}
for key in dictionary.keys():
if key.startswith('multiproc_'):
new_key = key.replace('multiproc_', '')
mp_dictionary[new_key] = dictionary[key]
mp_dictionary['version'] = dictionary['version']
if 'disable_existing_loggers' in dictionary:
mp_dictionary['disable_existing_loggers'] = dictionary['disable_existing_loggers']
return mp_dictionary | 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)
elif isinstance(self.report_progress, (int, float)):
self.report_progress = (self.report_progress, 'pypet', logging.INFO)
elif isinstance(self.report_progress, str):
self.report_progress = (5, self.report_progress, logging.INFO)
elif len(self.report_progress) == 2:
self.report_progress = (self.report_progress[0], self.report_progress[1],
logging.INFO)
if self.log_config:
if self.log_config == pypetconstants.DEFAULT_LOGGING:
pypet_path = os.path.abspath(os.path.dirname(__file__))
init_path = os.path.join(pypet_path, 'logging')
self.log_config = os.path.join(init_path, 'default.ini')
if isinstance(self.log_config, str):
if not os.path.isfile(self.log_config):
raise ValueError('Could not find the logger init file '
'`%s`.' % self.log_config)
parser = NoInterpolationParser()
parser.read(self.log_config)
elif isinstance(self.log_config, cp.RawConfigParser):
parser = self.log_config
else:
parser = None
if parser is not None:
self._sp_config = self._parser_to_string_io(parser)
self._mp_config = self._find_multiproc_options(parser)
if self._mp_config is not None:
self._mp_config = self._parser_to_string_io(self._mp_config)
elif isinstance(self.log_config, dict):
self._sp_config = self.log_config
self._mp_config = self._find_multiproc_dict(self._sp_config)
if self.log_stdout:
if self.log_stdout is True:
self.log_stdout = ('STDOUT', logging.INFO)
if isinstance(self.log_stdout, str):
self.log_stdout = (self.log_stdout, logging.INFO)
if isinstance(self.log_stdout, int):
self.log_stdout = ('STDOUT', self.log_stdout) | 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()
parser.readfp(log_config)
rename_func = lambda string: rename_log_file(string,
env_name=self.env_name,
traj_name=self.traj_name,
set_name=self.set_name,
run_name=self.run_name)
sections = parser.sections()
for section in sections:
options = parser.options(section)
for option in options:
if option == 'args':
self._check_and_replace_parser_args(parser, section, option,
rename_func=rename_func)
return parser | 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':
filename = log_config[key]
filename = rename_log_file(filename,
env_name=self.env_name,
traj_name=self.traj_name,
set_name=self.set_name,
run_name=self.run_name)
new_dict[key] = filename
try_make_dirs(filename)
elif isinstance(log_config[key], dict):
inner_dict = self._handle_dict_config(log_config[key])
new_dict[key] = inner_dict
else:
new_dict[key] = log_config[key]
return new_dict | 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
if self.log_config:
if multiproc:
proc_log_config = self._mp_config
else:
proc_log_config = self._sp_config
if proc_log_config:
if isinstance(proc_log_config, dict):
new_dict = self._handle_dict_config(proc_log_config)
dictConfig(new_dict)
else:
parser = self._handle_config_parsing(proc_log_config)
memory_file = self._parser_to_string_io(parser)
fileConfig(memory_file, disable_existing_loggers=False)
if log_stdout:
# Create a logging mock for stdout
std_name, std_level = self.log_stdout
stdout = StdoutToLogger(std_name, log_level=std_level)
stdout.start()
self._tools.append(stdout) | 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):
if hasattr(config, 'close'):
config.close()
self._sp_config = None
self._mp_config = None
if remove_all_handlers:
self.tabula_rasa() | 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._recursion = False
else:
# If stderr is redirected to stdout we can avoid further recursion by
sys.__stderr__.write('ERROR: Recursion in Stream redirection!') | 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 not results.')
if a.v_is_parameter or b.v_is_parameter:
return False
if a.v_full_name != b.v_full_name:
return False
if hasattr(a, '_data') and not hasattr(b, '_data'):
return False
if hasattr(a, '_data'):
akeyset = set(a._data.keys())
bkeyset = set(b._data.keys())
if akeyset != bkeyset:
return False
for key in a._data:
val = a._data[key]
bval = b._data[key]
if not nested_equal(val, bval):
return False
return True | 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):
raise ValueError('Both inputs are not parameters')
if (not b.v_is_parameter or
not a.v_is_parameter):
return False
if a.v_full_name != b.v_full_name:
return False
if a.f_is_empty() and b.f_is_empty():
return True
if a.f_is_empty() != b.f_is_empty():
return False
if not a._values_of_same_type(a.f_get(), b.f_get()):
return False
if not a._equal_values(a.f_get(), b.f_get()):
return False
if a.f_has_range() != b.f_has_range():
return False
if a.f_has_range():
if a.f_get_range_length() != b.f_get_range_length():
return False
for myitem, bitem in zip(a.f_get_range(copy=False), b.f_get_range(copy=False)):
if not a._values_of_same_type(myitem, bitem):
return False
if not a._equal_values(myitem, bitem):
return False
return True | 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 more specialized functionality
during a single run.
:param store_meta_data:
If meta-data like runtime should be automatically stored
:param clean_up:
If all data added during the single run should be removed, only works
if ``turn_into_run=True``.
"""
def wrapper(func):
@functools.wraps(func)
def new_func(traj, *args, **kwargs):
do_wrap = not traj._run_by_environment
if do_wrap:
traj.f_start_run(turn_into_run=turn_into_run)
result = func(traj, *args, **kwargs)
if do_wrap:
traj.f_finalize_run(store_meta_data=store_meta_data,
clean_up=clean_up)
return result
return new_func
return wrapper | 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)
def new_func(*args, **kwargs):
warning_string = "Call to deprecated function or property `%s`." % func.__name__
warning_string = warning_string + ' ' + msg
warnings.warn(
warning_string,
category=DeprecationWarning,
)
return func(*args, **kwargs)
return new_func
return wrapper | 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_name in kwargs:
raise ValueError('You cannot specify `%s` and `%s` at the same time, '
'they are mutually exclusive.' % (param1_name, param2_name))
param2 = kwargs.pop(param2_name)
if map2to1 is not None:
param1 = map2to1(param2)
else:
param1 = param2
kwargs[param1_name] = param1
return func(*args, **kwargs)
return new_func
return wrapper | 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 the keyword argument
:param new_name:
New name of keyword argument
"""
def wrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
if old_name in kwargs:
if new_name is None:
warning_string = 'Using deprecated keyword argument `%s` in function `%s`. ' \
'This keyword is no longer supported, please don`t use it ' \
'anymore.' % (old_name, func.__name__)
else:
warning_string = 'Using deprecated keyword argument `%s` in function `%s`, ' \
'please use keyword `%s` instead.' % \
(old_name, func.__name__, new_name)
warnings.warn(warning_string, category=DeprecationWarning)
value = kwargs.pop(old_name)
if new_name is not None:
kwargs[new_name] = value
return func(*args, **kwargs)
return new_func
return wrapper | 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 to print the caught error.
"""
def wrapper(func):
@functools.wraps(func)
def new_func(*args, **kwargs):
retries = 0
while True:
try:
result = func(*args, **kwargs)
if retries and logger_name:
logger = logging.getLogger(logger_name)
logger.debug('Retry of `%s` successful' % func.__name__)
return result
except errors:
if retries >= n:
if logger_name:
logger = logging.getLogger(logger_name)
logger.exception('I could not execute `%s` with args %s and kwargs %s, '
'starting next try. ' % (func.__name__,
str(args),
str(kwargs)))
raise
elif logger_name:
logger = logging.getLogger(logger_name)
logger.debug('I could not execute `%s` with args %s and kwargs %s, '
'starting next try. ' % (func.__name__,
str(args),
str(kwargs)))
retries += 1
if wait:
time.sleep(wait)
return new_func
return wrapper | 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('Net.gL',30*nS)
traj.f_add_parameter('Net.EL',-70.6*mV)
traj.f_add_parameter('Net.VT',-50.4*mV)
traj.f_add_parameter('Net.DeltaT',2*mV)
traj.f_add_parameter('Net.tauw',40*ms)
traj.f_add_parameter('Net.a',4*nS)
traj.f_add_parameter('Net.b',0.08*nA)
traj.f_add_parameter('Net.I',.8*nA)
traj.f_add_parameter('Net.Vcut','vm > 0*mV') # practical threshold condition
traj.f_add_parameter('Net.N',50)
eqs='''
dvm/dt=(gL*(EL-vm)+gL*DeltaT*exp((vm-VT)/DeltaT)+I-w)/C : volt
dw/dt=(a*(vm-EL)-w)/tauw : amp
Vr:volt
'''
traj.f_add_parameter('Net.eqs', eqs)
traj.f_add_parameter('reset', 'vm=Vr;w+=b') | 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=traj.reset,
namespace=namespace)
neuron.vm=traj.EL
neuron.w=traj.a*(neuron.vm-traj.EL)
neuron.Vr=linspace(-48.3*mV,-47.7*mV,traj.N) # bifurcation parameter
# Run the network initially for 100 milliseconds
print('Initial Run')
net = Network(neuron)
net.run(100*ms, report='text') # we discard the first spikes
# Create a Spike Monitor
MSpike=SpikeMonitor(neuron)
net.add(MSpike)
# Create a State Monitor for the membrane voltage, record from neurons 1-3
MStateV = StateMonitor(neuron, variables=['vm'],record=[1,2,3])
net.add(MStateV)
# Now record for 500 milliseconds
print('Measurement run')
net.run(500*ms,report='text')
# Add the BRAIN monitors
traj.v_standard_result = Brian2MonitorResult
traj.f_add_result('SpikeMonitor',MSpike)
traj.f_add_result('StateMonitorV', MStateV) | 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
dimension = len(initial_conditions)
# This array will collect the results
result_array = np.zeros((steps,dimension))
# Get the function parameters stored into `traj` as a dictionary
# with the (short) names as keys :
func_params_dict = traj.func_params.f_to_dict(short_names=True, fast_access=True)
# Take initial conditions as first result
result_array[0] = initial_conditions
# Now we compute the Euler Scheme steps-1 times
for idx in range(1,steps):
result_array[idx] = diff_func(result_array[idx-1], **func_params_dict) * traj.dt + \
result_array[idx-1]
# Note the **func_params_dict unzips the dictionary, it's the reverse of **kwargs in function
# definitions!
#Finally we want to keep the results
traj.f_add_result('euler_evolution', data=result_array, comment='Our time series data!') | 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 simulate
# a 3-D differential equation, the Lorenz attractor.
traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]),
comment = 'Our initial conditions, as default we will start from'
' origin!')
# We will group all parameters of the Lorenz differential equation into the group 'func_params'
traj.f_add_parameter('func_params.sigma', 10.0)
traj.f_add_parameter('func_params.beta', 8.0/3.0)
traj.f_add_parameter('func_params.rho', 28.0)
#For the fun of it we will annotate the group
traj.func_params.v_annotations.info='This group contains as default the original values chosen ' \
'by Edward Lorenz in 1963. Check it out on wikipedia ' \
'(https://en.wikipedia.org/wiki/Lorenz_attractor)!' | 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
:return: 3d array of the Lorenz system evaluated at `value_array`
"""
diff_array = np.zeros(3)
diff_array[0] = sigma * (value_array[1]-value_array[0])
diff_array[1] = value_array[0] * (rho - value_array[2]) - value_array[1]
diff_array[2] = value_array[0] * value_array[1] - beta * value_array[2]
return diff_array | 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 = storage_service(**matching_kwargs)
unused_kwargs = set(kwargs.keys()) - set(matching_kwargs.keys())
return storage_service, unused_kwargs | 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
:param kwargs:
Arguments passed to the storage service
:return:
A storage service and a set of not used keyword arguments from kwargs
"""
if 'filename' in kwargs and storage_service is None:
filename = kwargs['filename']
_, ext = os.path.splitext(filename)
if ext in ('.hdf', '.h4', '.hdf4', '.he2', '.h5', '.hdf5', '.he5'):
storage_service = HDF5StorageService
else:
raise ValueError('Extension `%s` of filename `%s` not understood.' %
(ext, filename))
elif isinstance(storage_service, str):
class_name = storage_service.split('.')[-1]
storage_service = create_class(class_name, [storage_service, HDF5StorageService])
if inspect.isclass(storage_service):
return _create_storage(storage_service, trajectory, **kwargs)
else:
return storage_service, set(kwargs.keys()) | 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'`.
You can use parameter presetting to switch between the two cases.
:raises: A ValueError if `traj.diff_name` is none of the above
"""
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, since we will simulate
# a 3-D differential equation, that is the Roessler attractor
# (https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor)
traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]),
comment = 'Our initial conditions, as default we will start from'
' origin!')
# Per default we choose the name `'diff_lorenz'` as in the last example
traj.f_add_parameter('diff_name','diff_lorenz', comment= 'Name of our differential equation')
# We want some control flow depending on which name we really choose
if traj.diff_name == 'diff_lorenz':
# These parameters are for the Lorenz differential equation
traj.f_add_parameter('func_params.sigma', 10.0)
traj.f_add_parameter('func_params.beta', 8.0/3.0)
traj.f_add_parameter('func_params.rho', 28.0)
elif traj.diff_name == 'diff_roessler':
# If we use the Roessler system we need different parameters
traj.f_add_parameter('func_params.a', 0.1)
traj.f_add_parameter('func_params.c', 14.0)
else:
raise ValueError('I don\'t know what %s is.' % traj.diff_name) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.