Search is not available for this dataset
text
stringlengths
75
104k
def cli_help(context, command_name, general_parser, command_parsers): """ Outputs help information. See :py:mod:`swiftly.cli.help` for context usage information. See :py:class:`CLIHelp` for more information. :param context: The :py:class:`swiftly.cli.context.CLIContext` to use. :param...
def read(self, size=-1): """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter...
def readline(self, size=-1): """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ if ...
def readlines(self, sizehint=-1): """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines retur...
def is_empty(self): """ Check whether the "file" is empty reading the single byte. """ something = self.read(1) if something: if self.buf: self.buf = something + self.buf else: self.buf = something return False ...
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...
def get_build_commits(app, repo_config): """ Determine the value for BUILD_COMMITS from the app and repository config. Resolves the previous BUILD_ALL_COMMITS = True/False option to BUILD_COMMITS = 'ALL'/'LAST' respectively. """ build_commits = repo_config.get("build_commits") build_all_comm...
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...
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...
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: ...
def write(self, obj, resource_id=None): """Write obj in elasticsearch. :param obj: value to be written in elasticsearch. :param resource_id: id for the resource. :return: id of the transaction. """ self.logger.debug('elasticsearch::write::{}'.format(resource_id)) ...
def read(self, resource_id): """Read object in elasticsearch using the resource_id. :param resource_id: id of the object to be read. :return: object value from elasticsearch. """ self.logger.debug('elasticsearch::read::{}'.format(resource_id)) return self.driver._es.get( ...
def update(self, obj, resource_id): """Update object in elasticsearch using the resource_id. :param metadata: new metadata for the transaction. :param resource_id: id of the object to be updated. :return: id of the object. """ self.logger.debug('elasticsearch::update::{}'...
def delete(self, resource_id): """Delete an object from elasticsearch. :param resource_id: id of the object to be deleted. :return: """ self.logger.debug('elasticsearch::delete::{}'.format(resource_id)) if self.driver._es.exists( index=self.driver._index, ...
def list(self, search_from=None, search_to=None, limit=None): """List all the objects saved elasticsearch. :param search_from: start offset of objects to return. :param search_to: last offset of objects to return. :param limit: max number of values to be returned. :return: li...
def query(self, search_model: QueryModel): """Query elasticsearch for objects. :param search_model: object of QueryModel. :return: list of objects that match the query. """ query_parsed = query_parser(search_model.query) self.logger.debug(f'elasticsearch::query::{query_pa...
def text_query(self, search_model: FullTextModel): """Query elasticsearch for objects. :param search_model: object of FullTextModel :return: list of objects that match the query. """ self.logger.debug('elasticsearch::text_query::{}'.format(search_model.text)) if search_mo...
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()
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
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, }
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()
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()
def writer_acquire(self): """Acquire the lock to write""" self._order_mutex.acquire() self._access_mutex.acquire() self._order_mutex.release()
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...
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...
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...
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
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
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...
def metadata(func): """Add metadata to an item. Decorator that adds metadata to Perceval items such as the identifier of the job that generated it or the version of the system. The contents from the original item will be stored under the 'data' keyword. Take into account that this function onl...
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`...
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...
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...
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 ...
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) ...
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...
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')
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)
def add(self): """Add tasks""" payload = cherrypy.request.json logger.debug("Reading tasks...") for task_data in payload['tasks']: try: category = task_data['category'] backend_args = task_data['backend_args'] archive_args = t...
def remove(self): """Remove tasks""" payload = cherrypy.request.json logger.debug("Reading tasks to remove...") task_ids = {} for task_data in payload['tasks']: task_id = task_data['task_id'] removed = super().remove_task(task_id) task_ids[t...
def tasks(self): """List tasks""" logger.debug("API 'tasks' method called") result = [task.to_dict() for task in self._tasks.tasks] result = {'tasks': result} logger.debug("Tasks registry read") return result
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: ...
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.", ...
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: ...
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...
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: ...
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...
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=(...
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...
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())
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...
def schedule(self): """Start scheduling jobs.""" if self.async_mode: self._scheduler.start() self._listener.start() else: self._scheduler.schedule()
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...
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...
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...
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)
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...
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(...
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)
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. ...
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...
def get_url_name(self, action_url_name="list"): """ Get full namespaced url name to use for reverse() """ url_name = "{}-{}".format(self.basename, action_url_name) namespace = self.request.resolver_match.namespace if namespace: url_name = "{}:{}".format(names...
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...
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 =...
def get_summary_and_description(self): """ Compat: drf-yasg 1.12+ """ summary = self.get_summary() _, description = super().get_summary_and_description() return summary, description
def get_summary(self): """ Compat: drf-yasg 1.11 """ title = None method_name = getattr(self.view, "action", self.method.lower()) action = getattr(self.view, method_name, None) action_kwargs = getattr(action, "kwargs", None) if action_kwargs: ...
def get_versioned_viewname(self, viewname, request): """ Prefix viewname with full namespace bananas:vX.Y: """ namespace = request.resolver_match.namespace if namespace: viewname = "{}:{}".format(namespace, viewname) return viewname
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,...
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...
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...
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' ...
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') >>...
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...
def list(self, request): """ Retrieve logged in user info """ serializer = self.get_serializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK)
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...
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) ...
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 ...
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)
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...
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_"...
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...
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...
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...
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...
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...
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...
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....
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'...
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 ...
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
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...
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...
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...
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_...
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. ...
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
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...
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...
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)...
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...