Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def flatten_template_loaders(templates): for loader in templates: if not isinstance(loader, string_types): for subloader in flatten_template_loaders(loader): yield subloader else: yield loader
[ "\n Given a collection of template loaders, unwrap them into one flat iterable.\n\n :param templates: template loaders to unwrap\n :return: template loaders as an iterable of strings.\n :rtype: generator expression\n " ]
Please provide a description of the function:def template_choices(templates, display_names=None, suffix=False): # allow for global template names, as well as usage-local ones. if display_names is None: display_names = getattr(settings, 'TEMPLATEFINDER_DISPLAY_NAMES', {}) to_space_re = re.compi...
[ "\n Given an iterable of `templates`, calculate human-friendly display names\n for each of them, optionally using the `display_names` provided, or a\n global dictionary (`TEMPLATEFINDER_DISPLAY_NAMES`) stored in the Django\n project's settings.\n\n .. note:: As the resulting iterable is a lazy genera...
Please provide a description of the function:def readlines(self, sizehint=None): wrapped = self.wrapped try: readlines = wrapped.readlines except AttributeError: lines = [] while 1: line = wrapped.readline() if line: ...
[ "Reads until EOF using :meth:`readline()`.\n\n :param sizehint: if it's present, instead of reading up to EOF,\n whole lines totalling approximately ``sizehint``\n bytes (or more to accommodate a final whole line)\n :type sizehint: :class:`numbers.Integr...
Please provide a description of the function:def seek(self, offset, whence=os.SEEK_SET): self.wrapped.seek(offset, whence)
[ "Sets the file's current position.\n\n :param offset: the offset to set\n :type offset: :class:`numbers.Integral`\n :param whence: see the docs of :meth:`file.seek()`.\n default is :const:`os.SEEK_SET`\n\n " ]
Please provide a description of the function:def get_current_context_id(): global get_current_context_id if greenlet is not None: if stackless is None: get_current_context_id = greenlet.getcurrent return greenlet.getcurrent() return greenlet.getcurrent(), stackless.g...
[ "Identifis which context it is (greenlet, stackless, or thread).\n\n :returns: the identifier of the current context.\n\n " ]
Please provide a description of the function:def store_context(store): if not isinstance(store, Store): raise TypeError('store must be an instance of sqlalchemy_imageattach.' 'store.Store, not ' + repr(store)) push_store_context(store) yield store pop_store_context()
[ "Sets the new (nested) context of the current image storage::\n\n with store_context(store):\n print current_store\n\n It could be set nestedly as well::\n\n with store_context(store1):\n print current_store # store1\n with store_context(store2):\n p...
Please provide a description of the function:def migrate(session, declarative_base, source, destination): if not isinstance(session, Session): raise TypeError('session must be an instance of sqlalchemy.orm.' 'session.Session, not ' + repr(session)) elif not isinstance(declar...
[ "Migrate all image data from ``source`` storage to ``destination``\n storage. All data in ``source`` storage are *not* deleted.\n\n It does not execute migration by itself alone. You need to\n :meth:`~MigrationPlan.execute()` the plan it returns::\n\n migrate(session, Base, source, destination).ex...
Please provide a description of the function:def migrate_class(session, cls, source, destination): if not isinstance(session, Session): raise TypeError('session must be an instance of sqlalchemy.orm.' 'session.Session, not ' + repr(session)) elif not isinstance(cls, Declarat...
[ "Migrate all image data of ``cls`` from ``source`` storage to\n ``destination`` storage. All data in ``source`` storage are *not*\n deleted.\n\n It does not execute migration by itself alone. You need to\n :meth:`~MigrationPlan.execute()` the plan it returns::\n\n migrate_class(session, UserPic...
Please provide a description of the function:def execute(self, callback=None): if callback is None: for _ in self: pass elif not callable(callback): raise TypeError('callback must be callable, not ' + repr(callback)) el...
[ "Execute the plan. If optional ``callback`` is present,\n it is invoked with an :class:`~sqlalchemy_imageattach.entity.Image`\n instance for every migrated image.\n\n :param callback: an optional callback that takes\n an :class:`~sqlalchemy_imageattach.entity.Image`\n ...
Please provide a description of the function:def put_file(self, file, object_type, object_id, width, height, mimetype, reproducible): raise NotImplementedError('put_file() has to be implemented')
[ "Puts the ``file`` of the image.\n\n :param file: the image file to put\n :type file: file-like object, :class:`file`\n :param object_type: the object type of the image to put\n e.g. ``'comics.cover'``\n :type object_type: :class:`str`\n :param object_id...
Please provide a description of the function:def store(self, image, file): from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sqlalchemy_imageattach.entity.' 'Image instance, not ' + repr(image)) elif not c...
[ "Stores the actual data ``file`` of the given ``image``.\n ::\n\n with open(imagefile, 'rb') as f:\n store.store(image, f)\n\n :param image: the image to store its actual data file\n :type image: :class:`sqlalchemy_imageattach.entity.Image`\n :param file: the im...
Please provide a description of the function:def delete(self, image): from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sqlalchemy_imageattach.entity.' 'Image instance, not ' + repr(image)) self.delete_fil...
[ "Delete the file of the given ``image``.\n\n :param image: the image to delete\n :type image: :class:`sqlalchemy_imageattach.entity.Image`\n\n " ]
Please provide a description of the function:def open(self, image, use_seek=False): from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sqlalchemy_imageattach.entity.' 'Image instance, not ' + repr(image)) e...
[ "Opens the file-like object of the given ``image``.\n Returned file-like object guarantees:\n\n - context manager protocol\n - :class:`collections.abc.Iterable` protocol\n - :class:`collections.abc.Iterator` protocol\n - :meth:`~io.RawIOBase.read()` method\n - :meth:`~io.IO...
Please provide a description of the function:def locate(self, image): from .entity import Image if not isinstance(image, Image): raise TypeError('image must be a sqlalchemy_imageattach.entity.' 'Image instance, not ' + repr(image)) url = self.get_...
[ "Gets the URL of the given ``image``.\n\n :param image: the image to get its url\n :type image: :class:`sqlalchemy_imageattach.entity.Image`\n :returns: the url of the image\n :rtype: :class:`str`\n\n " ]
Please provide a description of the function:def get_minimum_indent(docstring, ignore_before=1): r indent_re = re.compile(r'^\s*') indents = [indent_re.match(line).group(0) for line in docstring.splitlines()[ignore_before:] if line.strip()] return min(indents, key=len) if i...
[ "Gets the minimum indent string from the ``docstring``:\n\n >>> get_minimum_indent('Hello')\n ''\n >>> get_minimum_indent('Hello\\n world::\\n yeah')\n ' '\n\n :param docstring: the docstring to find its minimum indent\n :type docstring: :class:`str`\n :param ignore_before: ignore ...
Please provide a description of the function:def append_docstring(docstring, *lines): shallowest = get_minimum_indent(docstring) appender = [] for line in lines: appender.append('\n') if line.strip(): appender.append(shallowest) appender.append(line) return d...
[ "Appends the ``docstring`` with given ``lines``::\n\n function.__doc__ = append_docstring(\n function.__doc__,\n '.. note::'\n '',\n ' Appended docstring!'\n )\n\n :param docstring: a docstring to be appended\n :param \\*lines: lines of trailing docs...
Please provide a description of the function:def append_docstring_attributes(docstring, locals): docstring = docstring or '' for attr, val in locals.items(): doc = val.__doc__ if not doc: continue doc = get_minimum_indent(doc) + doc lines = [' ' + l for l in te...
[ "Manually appends class' ``docstring`` with its attribute docstrings.\n For example::\n\n class Entity(object):\n # ...\n\n __doc__ = append_docstring_attributes(\n __doc__,\n dict((k, v) for k, v in locals()\n if isinstance(v,...
Please provide a description of the function:def image_attachment(*args, **kwargs): if kwargs.get('uselist', False): kwargs.setdefault('query_class', MultipleImageSet) else: kwargs.setdefault('query_class', SingleImageSet) kwargs['uselist'] = True kwargs.setdefault('lazy', 'dynamic'...
[ "The helper function, decorates raw\n :func:`~sqlalchemy.orm.relationship()` function, sepcialized for\n relationships between :class:`Image` subtypes.\n\n It takes the same parameters as :func:`~sqlalchemy.orm.relationship()`.\n\n If ``uselist`` is :const:`True`, it becomes possible to attach multiple\...
Please provide a description of the function:def object_id(self): pk = self.identity_attributes() if len(pk) == 1: pk_value = getattr(self, pk[0]) if isinstance(pk_value, numbers.Integral): return pk_value elif isinstance(pk_value, uuid.UUID):...
[ "(:class:`numbers.Integral`) The identifier number of the image.\n It uses the primary key if it's integer, but can be overridden,\n and must be implemented when the primary key is not integer or\n composite key.\n\n .. versionchanged:: 1.1.0\n Since 1.1.0, it provides a more d...
Please provide a description of the function:def identity_attributes(cls): columns = inspect(cls).primary_key names = [c.name for c in columns if c.name not in ('width', 'height')] return names
[ "A list of the names of primary key fields.\n\n :returns: A list of the names of primary key fields\n :rtype: :class:`typing.Sequence`\\ [:class:`str`]\n\n .. versionadded:: 1.0.0\n\n " ]
Please provide a description of the function:def identity_map(self): pk = self.identity_attributes() values = {} for name in pk: values[name] = getattr(self, name) return values
[ "(:class:`typing.Mapping`\\ [:class:`str`, :class:`object`])\n A dictionary of the values of primary key fields with their names.\n\n .. versionadded:: 1.0.0\n\n " ]
Please provide a description of the function:def make_blob(self, store=current_store): with self.open_file(store) as f: return f.read()
[ "Gets the byte string of the image from the ``store``.\n\n :param store: the storage which contains the image.\n :data:`~sqlalchemy_imageattach.context.current_store`\n by default\n :type store: :class:`~sqlalchemy_imageattach.store.Store`\n :returns: t...
Please provide a description of the function:def open_file(self, store=current_store, use_seek=False): if not isinstance(store, Store): raise TypeError('store must be an instance of ' 'sqlalchemy_imageattach.store.Store, not ' + repr(s...
[ "Opens the file-like object which is a context manager\n (that means it can used for :keyword:`with` statement).\n\n If ``use_seek`` is :const:`True` (though :const:`False` by default)\n it guarentees the returned file-like object is also seekable\n (provides :meth:`~file.seek()` method)...
Please provide a description of the function:def locate(self, store=current_store): if not isinstance(store, Store): raise TypeError('store must be an instance of ' 'sqlalchemy_imageattach.store.Store, not ' + repr(store)) retu...
[ "Gets the URL of the image from the ``store``.\n\n :param store: the storage which contains the image.\n :data:`~sqlalchemy_imageattach.context.current_store`\n by default\n :type store: :class:`~sqlalchemy_imageattach.store.Store`\n :returns: the url o...
Please provide a description of the function:def _mark_image_file_stored(cls, mapper, connection, target): try: file_ = target.file except AttributeError: raise TypeError('sqlalchemy_imageattach.entity.Image which is ' 'to be inserted must hav...
[ "When the session flushes, stores actual image files into\n the storage. Note that these files could be deleted back\n if the ongoing transaction has done rollback. See also\n :meth:`_delete_image_file()`.\n\n " ]
Please provide a description of the function:def _mark_image_file_deleted(cls, mapper, connection, target): cls._deleted_images.add((target, get_current_store()))
[ "When the session flushes, marks images as deleted.\n The files of this marked images will be actually deleted\n in the image storage when the ongoing transaction succeeds.\n If it fails the :attr:`_deleted_images` queue will be just\n empty.\n\n " ]
Please provide a description of the function:def _images_failed(cls, session, previous_transaction): for image, store in cls._stored_images: store.delete(image) cls._stored_images.clear() cls._deleted_images.clear()
[ "Deletes the files of :attr:`_stored_images` back and clears\n the :attr:`_stored_images` and :attr:`_deleted_images` set\n when the ongoing transaction has done rollback.\n\n " ]
Please provide a description of the function:def _images_succeeded(cls, session): for image, store in cls._deleted_images: for stored_image, _ in cls._stored_images: if stored_image.object_type == image.object_type and \ stored_image.object_id == image.obj...
[ "Clears the :attr:`_stored_images` set and deletes actual\n files that are marked as deleted in the storage\n if the ongoing transaction has committed.\n\n " ]
Please provide a description of the function:def _original_images(self, **kwargs): def test(image): if not image.original: return False for filter, value in kwargs.items(): if getattr(image, filter) != value: return False ...
[ "A list of the original images.\n\n :returns: A list of the original images.\n :rtype: :class:`typing.Sequence`\\ [:class:`Image`]\n " ]
Please provide a description of the function:def from_raw_file(self, raw_file, store=current_store, size=None, mimetype=None, original=True, extra_args=None, extra_kwargs=None): query = self.query cls = query.column_descriptions[0]['type'] if ...
[ "Similar to :meth:`from_file()` except it's lower than that.\n It assumes that ``raw_file`` is readable and seekable while\n :meth:`from_file()` only assumes the file is readable.\n Also it doesn't make any in-memory buffer while\n :meth:`from_file()` always makes an in-memory buffer and...
Please provide a description of the function:def from_blob(self, blob, store=current_store, extra_args=None, extra_kwargs=None): data = io.BytesIO(blob) return self.from_raw_file(data, store, original=True, extra_args=extra_args, ...
[ "Stores the ``blob`` (byte string) for the image\n into the ``store``.\n\n :param blob: the byte string for the image\n :type blob: :class:`str`\n :param store: the storage to store the image data.\n :data:`~sqlalchemy_imageattach.context.current_store`\n ...
Please provide a description of the function:def from_file(self, file, store=current_store, extra_args=None, extra_kwargs=None): if isinstance(file, cgi.FieldStorage): file = file.file data = io.BytesIO() shutil.copyfileobj(file, data) data.seek(0...
[ "Stores the ``file`` for the image into the ``store``.\n\n :param file: the readable file of the image\n :type file: file-like object, :class:`file`\n :param store: the storage to store the file.\n :data:`~sqlalchemy_imageattach.context.current_store`\n ...
Please provide a description of the function:def generate_thumbnail(self, ratio=None, width=None, height=None, filter='undefined', store=current_store, _preprocess_image=None, _postprocess_image=None): params = ratio, width, height param_cou...
[ "Resizes the :attr:`original` (scales up or down) and\n then store the resized thumbnail into the ``store``.\n\n :param ratio: resize by its ratio. if it's greater than 1\n it scales up, and if it's less than 1 it scales\n down. exclusive for ``width`` and `...
Please provide a description of the function:def original(self): images = self.query._original_images(**self.identity_map) if images: return images[0]
[ "(:class:`Image`) The original image. It could be :const:`None`\n if there are no stored images yet.\n\n " ]
Please provide a description of the function:def find_thumbnail(self, width=None, height=None): if width is None and height is None: raise TypeError('required width and/or height') q = self if width is not None: q = q.filter_by(width=width) if height is n...
[ "Finds the thumbnail of the image with the given ``width``\n and/or ``height``.\n\n :param width: the thumbnail width\n :type width: :class:`numbers.Integral`\n :param height: the thumbnail height\n :type height: :class:`numbers.Integral`\n :returns: the thumbnail image\n ...
Please provide a description of the function:def open_file(self, store=current_store, use_seek=False): original = self.require_original() return original.open_file(store, use_seek)
[ "The shorthand of :meth:`~Image.open_file()` for\n the :attr:`original`.\n\n :param store: the storage which contains the image files\n :data:`~sqlalchemy_imageattach.context.current_store`\n by default\n :type store: :class:`~sqlalchemy_imageattach.sto...
Please provide a description of the function:def image_sets(self): images = self._original_images() for image in images: yield ImageSubset(self, **image.identity_map)
[ "(:class:`typing.Iterable`\\ [:class:`ImageSubset`]) The set of\n attached image sets.\n\n " ]
Please provide a description of the function:def wsgi_middleware(self, app, cors=False): _app = StaticServerMiddleware(app, '/' + self.prefix, self.path, cors=self.cors) def app(environ, start_response): if not hasattr(self, 'host_url'): ...
[ "WSGI middlewares that wraps the given ``app`` and serves\n actual image files. ::\n\n fs_store = HttpExposedFileSystemStore('userimages', 'images/')\n app = fs_store.wsgi_middleware(app)\n\n :param app: the wsgi app to wrap\n :type app: :class:`~typing.Callable`\\ [[],\n ...
Please provide a description of the function:def clear_database(self) -> None: self._next_entity_id = 0 self._dead_entities.clear() self._components.clear() self._entities.clear() self.clear_cache()
[ "Remove all Entities and Components from the World." ]
Please provide a description of the function:def add_processor(self, processor_instance: Processor, priority=0) -> None: assert issubclass(processor_instance.__class__, Processor) processor_instance.priority = priority processor_instance.world = self self._processors.append(proc...
[ "Add a Processor instance to the World.\n\n :param processor_instance: An instance of a Processor,\n subclassed from the Processor class\n :param priority: A higher number is processed first.\n " ]
Please provide a description of the function:def remove_processor(self, processor_type: Processor) -> None: for processor in self._processors: if type(processor) == processor_type: processor.world = None self._processors.remove(processor)
[ "Remove a Processor from the World, by type.\n\n :param processor_type: The class type of the Processor to remove.\n " ]
Please provide a description of the function:def get_processor(self, processor_type: Type[P]) -> P: for processor in self._processors: if type(processor) == processor_type: return processor
[ "Get a Processor instance, by type.\n\n This method returns a Processor instance by type. This could be\n useful in certain situations, such as wanting to call a method on a\n Processor, from within another Processor.\n\n :param processor_type: The type of the Processor you wish to retri...
Please provide a description of the function:def create_entity(self, *components) -> int: self._next_entity_id += 1 # TODO: duplicate add_component code here for performance for component in components: self.add_component(self._next_entity_id, component) # self.cle...
[ "Create a new Entity.\n\n This method returns an Entity ID, which is just a plain integer.\n You can optionally pass one or more Component instances to be\n assigned to the Entity.\n\n :param components: Optional components to be assigned to the\n entity on creation.\n :ret...
Please provide a description of the function:def delete_entity(self, entity: int, immediate=False) -> None: if immediate: for component_type in self._entities[entity]: self._components[component_type].discard(entity) if not self._components[component_type]: ...
[ "Delete an Entity from the World.\n\n Delete an Entity and all of it's assigned Component instances from\n the world. By default, Entity deletion is delayed until the next call\n to *World.process*. You can request immediate deletion, however, by\n passing the \"immediate=True\" paramete...
Please provide a description of the function:def component_for_entity(self, entity: int, component_type: Type[C]) -> C: return self._entities[entity][component_type]
[ "Retrieve a Component instance for a specific Entity.\n\n Retrieve a Component instance for a specific Entity. In some cases,\n it may be necessary to access a specific Component instance.\n For example: directly modifying a Component to handle user input.\n\n Raises a KeyError if the gi...
Please provide a description of the function:def components_for_entity(self, entity: int) -> Tuple[C, ...]: return tuple(self._entities[entity].values())
[ "Retrieve all Components for a specific Entity, as a Tuple.\n\n Retrieve all Components for a specific Entity. The method is probably\n not appropriate to use in your Processors, but might be useful for\n saving state, or passing specific Components between World instances.\n Unlike most...
Please provide a description of the function:def has_component(self, entity: int, component_type: Any) -> bool: return component_type in self._entities[entity]
[ "Check if a specific Entity has a Component of a certain type.\n\n :param entity: The Entity you are querying.\n :param component_type: The type of Component to check for.\n :return: True if the Entity has a Component of this type,\n otherwise False\n " ]
Please provide a description of the function:def add_component(self, entity: int, component_instance: Any) -> None: component_type = type(component_instance) if component_type not in self._components: self._components[component_type] = set() self._components[component_type...
[ "Add a new Component instance to an Entity.\n\n Add a Component instance to an Entiy. If a Component of the same type\n is already assigned to the Entity, it will be replaced.\n\n :param entity: The Entity to associate the Component with.\n :param component_instance: A Component instance...
Please provide a description of the function:def remove_component(self, entity: int, component_type: Any) -> int: self._components[component_type].discard(entity) if not self._components[component_type]: del self._components[component_type] del self._entities[entity][compo...
[ "Remove a Component instance from an Entity, by type.\n\n A Component instance can be removed by providing it's type.\n For example: world.delete_component(enemy_a, Velocity) will remove\n the Velocity instance from the Entity enemy_a.\n\n Raises a KeyError if either the given entity or ...
Please provide a description of the function:def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]: entity_db = self._entities for entity in self._components.get(component_type, []): yield entity, entity_db[entity][component_type]
[ "Get an iterator for Entity, Component pairs.\n\n :param component_type: The Component type to retrieve.\n :return: An iterator for (Entity, Component) tuples.\n " ]
Please provide a description of the function:def _get_components(self, *component_types: Type)-> Iterable[Tuple[int, ...]]: entity_db = self._entities comp_db = self._components try: for entity in set.intersection(*[comp_db[ct] for ct in component_types]): y...
[ "Get an iterator for Entity and multiple Component sets.\n\n :param component_types: Two or more Component types.\n :return: An iterator for Entity, (Component1, Component2, etc)\n tuples.\n " ]
Please provide a description of the function:def try_component(self, entity: int, component_type: Type): if component_type in self._entities[entity]: yield self._entities[entity][component_type] else: return None
[ "Try to get a single component type for an Entity.\n \n This method will return the requested Component if it exists, but\n will pass silently if it does not. This allows a way to access optional\n Components that may or may not exist.\n\n :param entity: The En...
Please provide a description of the function:def _clear_dead_entities(self): for entity in self._dead_entities: for component_type in self._entities[entity]: self._components[component_type].discard(entity) if not self._components[component_type]: ...
[ "Finalize deletion of any Entities that are marked dead.\n \n In the interest of performance, this method duplicates code from the\n `delete_entity` method. If that method is changed, those changes should\n be duplicated here as well.\n " ]
Please provide a description of the function:def _timed_process(self, *args, **kwargs): for processor in self._processors: start_time = _time.process_time() processor.process(*args, **kwargs) process_time = int(round((_time.process_time() - start_time) * 1000, 2)) ...
[ "Track Processor execution time for benchmarking." ]
Please provide a description of the function:def process(self, *args, **kwargs): self._clear_dead_entities() self._process(*args, **kwargs)
[ "Call the process method on all Processors, in order of their priority.\n\n Call the *process* method on all assigned Processors, respecting their\n optional priority setting. In addition, any Entities that were marked\n for deletion since the last call to *World.process*, will be deleted\n ...
Please provide a description of the function:def texture_from_image(renderer, image_name): soft_surface = ext.load_image(image_name) texture = SDL_CreateTextureFromSurface(renderer.renderer, soft_surface) SDL_FreeSurface(soft_surface) return texture
[ "Create an SDL2 Texture from an image file" ]
Please provide a description of the function:def setup_tree(ctx, verbose=None, root=None, tree_dir=None, modules_dir=None): ''' Sets up the SDSS tree enviroment ''' print('Setting up the tree') ctx.run('python bin/setup_tree.py -t {0} -r {1} -m {2}'.format(tree_dir, root, modules_dir))
[]
Please provide a description of the function:def set_roots(self, uproot_with=None): ''' Set the roots of the tree in the os environment Parameters: uproot_with (str): A new TREE_DIR path used to override an existing TREE_DIR environment variable ''' # Check...
[]
Please provide a description of the function:def load_config(self, config=None): ''' loads a config file Parameters: config (str): Optional name of manual config file to load ''' # Read the config file cfgname = (config or self.config_name) c...
[]
Please provide a description of the function:def branch_out(self, limb=None): ''' Set the individual section branches This adds the various sections of the config file into the tree environment for access later. Optically can specify a specific branch. This does not yet load them into ...
[]
Please provide a description of the function:def add_limbs(self, key=None): ''' Add a new section from the tree into the existing os environment Parameters: key (str): The section name to grab from the environment ''' self.branch_out(limb=key) self.a...
[]
Please provide a description of the function:def get_paths(self, key): ''' Retrieve a set of environment paths from the config Parameters: key (str): The section name to grab from the environment Returns: self.environ[newkey] (OrderedDict): ...
[]
Please provide a description of the function:def add_paths_to_os(self, key=None, update=None): ''' Add the paths in tree environ into the os environ This code goes through the tree environ and checks for existence in the os environ, then adds them Parameters: key (str): ...
[]
Please provide a description of the function:def check_paths(self, paths, update=None): ''' Check if the path is in the os environ, and if not add it Paramters: paths (OrderedDict): An ordered dict containing all of the paths from the a given section, as key:...
[]
Please provide a description of the function:def replant_tree(self, config=None, exclude=None): ''' Replant the tree with a different config setup Parameters: config (str): The config name to reload exclude (list): A list of environment variables ...
[]
Please provide a description of the function:def print_exception_formatted(type, value, tb): tbtext = ''.join(traceback.format_exception(type, value, tb)) lexer = get_lexer_by_name('pytb', stripall=True) formatter = TerminalFormatter() sys.stderr.write(highlight(tbtext, lexer, formatter))
[ "A custom hook for printing tracebacks with colours." ]
Please provide a description of the function:def colored_formatter(record): colours = {'info': ('blue', 'normal'), 'debug': ('magenta', 'normal'), 'warning': ('yellow', 'normal'), 'print': ('green', 'normal'), 'error': ('red', 'bold')} levelname...
[ "Prints log messages with colours." ]
Please provide a description of the function:def _catch_exceptions(self, exctype, value, tb): # Now we log it. self.error('Uncaught exception', exc_info=(exctype, value, tb)) # First, we print to stdout with some colouring. print_exception_formatted(exctype, value, tb)
[ "Catches all exceptions and logs them." ]
Please provide a description of the function:def _set_defaults(self, log_level=logging.INFO, redirect_stdout=False): # Remove all previous handlers for handler in self.handlers[:]: self.removeHandler(handler) # Set levels self.setLevel(logging.DEBUG) # Set...
[ "Reset logger to its initial state." ]
Please provide a description of the function:def start_file_logger(self, name, log_file_level=logging.DEBUG, log_file_path='./'): log_file_path = os.path.expanduser(log_file_path) / '{}.log'.format(name) logdir = log_file_path.parent try: logdir.mkdir(parents=True, exist_o...
[ "Start file logging." ]
Please provide a description of the function:def create_index_table(environ, envdir): ''' create an html table Parameters: environ (dict): A tree environment dictionary envdir (str): The filepath for the env directory Returns: An html table definition str...
[ "<table id=\"list\" cellpadding=\"0.1em\" cellspacing=\"0\">\n<colgroup><col width=\"55%\"/><col width=\"20%\"/><col width=\"25%\"/></colgroup>\n<thead>\n <tr><th><a href=\"?C=N&O=A\">File Name</a>&nbsp;<a href=\"?C=N&O=D\">&nbsp;&darr;&nbsp;</a></th><th><a href=\"?C=S&O=A\">File Size</a>&nbsp;<a href=\"?C=S&O=D...
Please provide a description of the function:def create_index_page(environ, defaults, envdir): ''' create the env index html page Builds the index.html page containing a table of symlinks to datamodel directories Parameters: environ (dict): A tree environment dictionary ...
[ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head><meta name=\"viewport\" content=\"width=device-width\"/><meta http-equiv=\"content-type\" content=\"tex...
Please provide a description of the function:def create_env(environ, mirror=None, verbose=None): ''' create the env symlink directory structure Creates the env folder filled with symlinks to datamodel directories for a given tree config file. Parameters: environ (dict): A tre...
[]
Please provide a description of the function:def check_sas_base_dir(root=None): ''' Check for the SAS_BASE_DIR environment variable Will set the SAS_BASE_DIR in your local environment or prompt you to define one if is undefined Parameters: root (str): Optional override of the SAS_B...
[]
Please provide a description of the function:def write_header(term='bash', tree_dir=None, name=None): ''' Write proper file header in a given shell format Parameters: term (str): The type of shell header to write, can be "bash", "tsch", or "modules" tree_dir (str): The p...
[ "# Set up tree/{0} for {1}\n{2} TREE_DIR {3}\n{2} TREE_VER {1}\n{2} PATH $TREE_DIR/bin:$PATH\n{2} PYTHONPATH $TREE_DIR/python:$PYTHONPATH\n ", "#%Module1.0\nproc ModulesHelp {{ }} {{\n global product version\n puts stderr \"This module adds $product/$version to various paths\"\n}}\nset name t...
Please provide a description of the function:def write_file(environ, term='bash', out_dir=None, tree_dir=None): ''' Write a tree environment file Loops over the tree environ and writes them out to a bash, tsch, or modules file Parameters: environ (dict): The tree dictionary environ...
[]
Please provide a description of the function:def get_tree(config=None): ''' Get the tree for a given config Parameters: config (str): The name of the tree config to load Returns: a Python Tree instance ''' path = os.path.dirname(os.path.abspath(__file__)) pypath = o...
[]
Please provide a description of the function:def copy_modules(filespath=None, modules_path=None, verbose=None): ''' Copy over the tree module files into your path ''' # find or define a modules path if not modules_path: modulepath = os.getenv("MODULEPATH") if not modulepath: mod...
[]
Please provide a description of the function:def parse_args(): ''' Parse the arguments ''' parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]') parser.add_argument('-v', '--verbose', action='store_true', dest='verbose', help='Print extra information.'...
[]
Please provide a description of the function:def _indent(text, level=1): ''' Does a proper indenting for Sphinx rst ''' prefix = ' ' * (4 * level) def prefixed_lines(): for line in text.splitlines(True): yield (prefix + line if line.strip() else line) return ''.join(prefixed_lines...
[]
Please provide a description of the function:def _format_command(name, envvars, base=None): ''' Creates a list-table directive for a set of defined environment variables Parameters: name (str): The name of the config section envvars (dict): A dictionary of the envir...
[]
Please provide a description of the function:def _generate_section(self, name, config, cfg_section='default', remove_sasbase=False): # the source name source_name = name # Title section = nodes.section( '', nodes.title(text=cfg_section), ids...
[ "Generate the relevant Sphinx nodes.\n\n Generates a section for the Tree datamodel. Formats a tree section\n as a list-table directive.\n\n Parameters:\n name (str):\n The name of the config to be documented, e.g. 'sdsswork'\n config (dict):\n ...
Please provide a description of the function:def get_requirements(opts): ''' Get the proper requirements file based on the optional argument ''' if opts.dev: name = 'requirements_dev.txt' elif opts.doc: name = 'requirements_doc.txt' else: name = 'requirements.txt' requireme...
[]
Please provide a description of the function:def remove_args(parser): ''' Remove custom arguments from the parser ''' arguments = [] for action in list(parser._get_optional_actions()): if '--help' not in action.option_strings: arguments += action.option_strings for arg in arguments...
[]
Please provide a description of the function:def clean(ctx): ctx.run(f'python setup.py clean') dist = ROOT.joinpath('dist') print(f'[clean] Removing {dist}') if dist.exists(): shutil.rmtree(str(dist))
[ "Clean previously built package artifacts.\n " ]
Please provide a description of the function:def _render_log(): config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, definitions, ) rendere...
[ "Totally tap into Towncrier internals to get an in-memory result.\n " ]
Please provide a description of the function:def adjust_name_for_printing(name): if name is not None: name2 = name name = name.replace(" ", "_").replace(".", "_").replace("-", "_m_") name = name.replace("+", "_p_").replace("!", "_I_") name = name.replace("**", "_xx_").replace("*...
[ "\n Make sure a name can be printed, alongside used as a variable name.\n " ]
Please provide a description of the function:def name(self, name): from_name = self.name assert isinstance(name, str) self._name = name if self.has_parent(): self._parent_._name_changed(self, from_name)
[ "\n Set the name of this object.\n Tell the parent if the name has changed.\n " ]
Please provide a description of the function:def hierarchy_name(self, adjust_for_printing=True): if adjust_for_printing: adjust = lambda x: adjust_name_for_printing(x) else: adjust = lambda x: x if self.has_parent(): return self._parent_.hierarchy_name() + "." + adjust(self....
[ "\n return the name for this object with the parents names attached by dots.\n\n :param bool adjust_for_printing: whether to call :func:`~adjust_for_printing()`\n on the names, recursively\n \n " ]
Please provide a description of the function:def link_parameter(self, param, index=None): if param in self.parameters and index is not None: self.unlink_parameter(param) return self.link_parameter(param, index) # elif param.has_parent(): # raise HierarchyError...
[ "\n :param parameters: the parameters to add\n :type parameters: list of or one :py:class:`paramz.param.Param`\n :param [index]: index of where to put parameters\n\n Add all parameters to this param class, you can insert parameters\n at any given index using the :func:`list...
Please provide a description of the function:def unlink_parameter(self, param): if not param in self.parameters: try: raise HierarchyError("{} does not belong to this object {}, remove parameters directly from their respective parents".format(param._short(), self.name)) ...
[ "\n :param param: param object to remove from being a parameter of this parameterized object.\n " ]
Please provide a description of the function:def grep_param_names(self, regexp): if not isinstance(regexp, _pattern_type): regexp = compile(regexp) found_params = [] def visit(innerself, regexp): if (innerself is not self) and regexp.match(innerself.hierarchy_name().partitio...
[ "\n create a list of parameters, matching regular expression regexp\n " ]
Please provide a description of the function:def _repr_html_(self, header=True): name = adjust_name_for_printing(self.name) + "." names = self.parameter_names() desc = self._description_str iops = OrderedDict() for opname in self._index_operations: iop = [] ...
[ "Representation of the parameters in html for notebook display.", "<style type=\"text/css\">\n.tg {font-family:\"Courier New\", Courier, monospace !important;padding:2px 3px;word-break:normal;border-collapse:collapse;border-spacing:0;border-color:#DCDCDC;margin:0px auto;width:100%;}\n.tg td{font-family:\"Courier...
Please provide a description of the function:def build_pydot(self, G=None): # pragma: no cover import pydot # @UnresolvedImport iamroot = False if G is None: G = pydot.Dot(graph_type='digraph', bgcolor=None) iamroot=True node = pydot.Node(id(self), shape...
[ "\n Build a pydot representation of this model. This needs pydot installed.\n\n Example Usage::\n\n np.random.seed(1000)\n X = np.random.normal(0,1,(20,2))\n beta = np.random.uniform(0,1,(2,1))\n Y = X.dot(beta)\n m = RidgeRegression(X, Y)\n ...
Please provide a description of the function:def gradient(self): if getattr(self, '_gradient_array_', None) is None: self._gradient_array_ = np.empty(self._realshape_, dtype=np.float64) return self._gradient_array_
[ "\n Return a view on the gradient, which is in the same shape as this parameter is.\n Note: this is not the real gradient array, it is just a view on it.\n\n To work on the real gradient array use: self.full_gradient\n " ]
Please provide a description of the function:def _setup_observers(self): if self.has_parent(): self.add_observer(self._parent_, self._parent_._pass_through_notify_observers, -np.inf)
[ "\n Setup the default observers\n\n 1: pass through to parent, if present\n " ]
Please provide a description of the function:def _repr_html_(self, indices=None, iops=None, lx=None, li=None, lls=None): filter_ = self._current_slice_ vals = self.flat if indices is None: indices = self._indices(filter_) if iops is None: ravi = self._raveled_index(f...
[ "Representation of the parameter in html for notebook display.", "\n<tr>\n <th><b>{i}</b></th>\n <th><b>{x}</b></th>\n <th><b>{iops}</b></th>\n</tr>", "<style type=\"text/css\">\n.tg {padding:2px 3px;word-break:normal;border-collapse:collapse;border-spacing:0;border-color:#DCDCDC;margin:0px auto;width:100%;...
Please provide a description of the function:def build_pydot(self,G): # pragma: no cover import pydot node = pydot.Node(id(self), shape='trapezium', label=self.name)#, fontcolor='white', color='white') G.add_node(node) for _, o, _ in self.observers: label = o.name if...
[ "\n Build a pydot representation of this model. This needs pydot installed.\n\n Example Usage:\n\n np.random.seed(1000)\n X = np.random.normal(0,1,(20,2))\n beta = np.random.uniform(0,1,(2,1))\n Y = X.dot(beta)\n m = RidgeRegression(X, Y)\n G = m.build_pydot()...
Please provide a description of the function:def add_observer(self, observer, callble, priority=0): self.observers.add(priority, observer, callble)
[ "\n Add an observer `observer` with the callback `callble`\n and priority `priority` to this observers list.\n " ]
Please provide a description of the function:def remove_observer(self, observer, callble=None): to_remove = [] for poc in self.observers: _, obs, clble = poc if callble is not None: if (obs is observer) and (callble == clble): to_remov...
[ "\n Either (if callble is None) remove all callables,\n which were added alongside observer,\n or remove callable `callble` which was added alongside\n the observer `observer`.\n " ]