Search is not available for this dataset
text
stringlengths
75
104k
def create_package(self, path=None, name=None, mode=None): """ Create a tar file package of all the repository files and directories. Only files and directories that are stored in the repository info are stored in the package tar file. **N.B. On some systems packaging requires r...
def is_repository(self, path): """ Check if there is a Repository in path. :Parameters: #. path (string): The real path of the directory where to check if there is a repository. :Returns: #. result (boolean): Whether its a repository or not. """ ...
def get_directory_info(self, relativePath): """ get directory info from the Repository. :Parameters: #. relativePath (string): The relative to the repository path of the directory. :Returns: #. info (None, dictionary): The directory information dictionary. ...
def get_parent_directory_info(self, relativePath): """ get parent directory info of a file or directory from the Repository. :Parameters: #. relativePath (string): The relative to the repository path of the file or directory of which the parent directory info is requested. ...
def get_file_info(self, relativePath, name=None): """ get file information dict from the repository given its relative path and name. :Parameters: #. relativePath (string): The relative to the repository path of the directory where the file is. #. name (string): The file...
def get_file_info_by_id(self, id): """ Given an id, get the corresponding file info as the following:\n (relative path joined with file name, file info dict) Parameters: #. id (string): The file unique id string. :Returns: #. relativePath (string): The f...
def get_file_relative_path_by_id(self, id): """ Given an id, get the corresponding file info relative path joined with file name. Parameters: #. id (string): The file unique id string. :Returns: #. relativePath (string): The file relative path joined with file n...
def get_file_relative_path_by_name(self, name, skip=0): """ Get file relative path given the file name. If file name is redundant in different directories in the repository, this method ensures to return all or some of the files according to skip value. Parameters: #...
def add_directory(self, relativePath, info=None): """ Adds a directory in the repository and creates its attribute in the Repository with utc timestamp. It insures adding all the missing directories in the path. :Parameters: #. relativePath (string): The relative to ...
def remove_directory(self, relativePath, removeFromSystem=False): """ Remove directory from repository. :Parameters: #. relativePath (string): The relative to the repository path of the directory to remove from the repository. #. removeFromSystem (boolean): Whether to al...
def move_directory(self, relativePath, relativeDestination, replace=False, verbose=True): """ Move a directory in the repository from one place to another. It insures moving all the files and subdirectories in the system. :Parameters: #. relativePath (string): The relative t...
def rename_directory(self, relativePath, newName, replace=False, verbose=True): """ Rename a directory in the repository. It insures renaming the directory in the system. :Parameters: #. relativePath (string): The relative to the repository path of the directory to be renamed. ...
def rename_file(self, relativePath, name, newName, replace=False, verbose=True): """ Rename a directory in the repository. It insures renaming the file in the system. :Parameters: #. relativePath (string): The relative to the repository path of the directory where the file is locate...
def remove_file(self, relativePath, name=None, removeFromSystem=False): """ Remove file from repository. :Parameters: #. relativePath (string): The relative to the repository path of the directory where the file should be dumped. If relativePath does not exist, it wil...
def dump_copy(self, path, relativePath, name=None, description=None, replace=False, verbose=False): """ Copy an exisitng system file to the repository. attribute in the Repository with utc timestamp. :Parameters: #. path (str):...
def dump_file(self, value, relativePath, name=None, description=None, klass=None, dump=None, pull=None, replace=False, ACID=None, verbose=False): """ Dump a file using its value to the system and creates its attribute in the...
def update_file(self, value, relativePath, name=None, description=False, klass=False, dump=False, pull=False, ACID=None, verbose=False): """ Update the value and the utc timestamp of a file that is already in the Repository.\n...
def pull_file(self, relativePath, name=None, pull=None, update=True): """ Pull a file's data from the Repository. :Parameters: #. relativePath (string): The relative to the repository path of the directory where the file should be pulled. #. name (string): The file name....
def ensure_str(value): """ Ensure value is string. """ if isinstance(value, six.string_types): return value else: return six.text_type(value)
def ensure_list(path_or_path_list): """ Pre-process input argument, whether if it is: 1. abspath 2. Path instance 3. string 4. list or set of any of them It returns list of path. :return path_or_path_list: always return list of path in string **中文文档** 预处理输入参数。 """ if...
def stream(self, report): """Stream reports to application logs""" with self.ClientSession() as session: lines = [] for job in report['traces']: key = '%s:%s' % (self.name, job) for minute in report['traces'][job]: for k, v in r...
def stream(self, report): """Stream reports to application logs""" payload = { "agent": { "host": report['instance']['hostname'], "version": "1.0.0" }, "components": [ { "name": self.name, ...
def stats(cls, traces): """Build per minute stats for each key""" data = {} stats = {} # Group traces by key and minute for trace in traces: key = trace['key'] if key not in data: data[key] = [] stats[key] = {} ...
def no_error_extract_data_from_file(self, file_path: str) -> Iterable[DataSourceType]: """ Proxy for `extract_data_from_file` that suppresses any errors and instead just returning an empty list. :param file_path: see `extract_data_from_file` :return: see `extract_data_from_file` ...
def _load_all_in_directory(self) -> Dict[str, Iterable[DataSourceType]]: """ Loads all of the data from the files in directory location. :return: a origin map of all the loaded data """ origin_mapped_data = dict() # type: Dict[str, Iterable[DataSourceType]] for file_pa...
def _extract_data_from_origin_map(origin_mapped_data: Dict[str, Iterable[DataSourceType]]) \ -> Iterable[DataSourceType]: """ Extracts the data from a data origin map. :param origin_mapped_data: a map containing the origin of the data as the key string and the data as the value ...
def start(self): """ Monitors data kept in files in the predefined directory in a new thread. Note: Due to the underlying library, it may take a few milliseconds after this method is started for changes to start to being noticed. """ with self._status_lock: i...
def stop(self): """ Stops monitoring the predefined directory. """ with self._status_lock: if self._running: assert self._observer is not None self._observer.stop() self._running = False self._origin_mapped_data ...
def _on_file_created(self, event: FileSystemEvent): """ Called when a file in the monitored directory has been created. :param event: the file system event """ if not event.is_directory and self.is_data_file(event.src_path): assert event.src_path not in self._origin_m...
def _on_file_modified(self, event: FileSystemEvent): """ Called when a file in the monitored directory has been modified. :param event: the file system event """ if not event.is_directory and self.is_data_file(event.src_path): assert event.src_path in self._origin_map...
def _on_file_deleted(self, event: FileSystemEvent): """ Called when a file in the monitored directory has been deleted. :param event: the file system event """ if not event.is_directory and self.is_data_file(event.src_path): assert event.src_path in self._origin_mappe...
def _on_file_moved(self, event: FileSystemMovedEvent): """ Called when a file in the monitored directory has been moved. Breaks move down into a delete and a create (which it is sometimes detected as!). :param event: the file system event """ if not event.is_directory an...
def tear_down(self): """ Tears down all temp files and directories. """ while len(self._temp_directories) > 0: directory = self._temp_directories.pop() shutil.rmtree(directory, ignore_errors=True) while len(self._temp_files) > 0: file = self._t...
def create_temp_directory(self, **mkdtemp_kwargs) -> str: """ Creates a temp directory. :param mkdtemp_kwargs: named arguments to be passed to `tempfile.mkdtemp` :return: the location of the temp directory """ kwargs = {**self.default_mkdtemp_kwargs, **mkdtemp_kwargs} ...
def create_temp_file(self, **mkstemp_kwargs) -> Tuple[int, str]: """ Creates a temp file. :param mkstemp_kwargs: named arguments to be passed to `tempfile.mkstemp` :return: tuple where the first element is the file handle and the second is the location of the temp file """ ...
def change(self, new_abspath=None, new_dirpath=None, new_dirname=None, new_basename=None, new_fname=None, new_ext=None): """ Return a new :class:`pathlib_mate.pathlib2.Path` object with updated information. ...
def is_not_exist_or_allow_overwrite(self, overwrite=False): """ Test whether a file target is not exists or it exists but allow overwrite. """ if self.exists() and overwrite is False: return False else: # pragma: no cover return True
def moveto(self, new_abspath=None, new_dirpath=None, new_dirname=None, new_basename=None, new_fname=None, new_ext=None, overwrite=False, makedirs=False): """ An advanced :meth:`pathlib...
def copyto(self, new_abspath=None, new_dirpath=None, new_dirname=None, new_basename=None, new_fname=None, new_ext=None, overwrite=False, makedirs=False): """ Copy this file to other pl...
def _create_client(base_url: str, tls: TLSConfig=False) -> Optional[APIClient]: """ Creates a Docker client with the given details. :param base_url: the base URL of the Docker daemon :param tls: the Docker daemon's TLS config (if any) :return: the created client else None if unable to connect the cl...
def create_client() -> APIClient: """ Clients a Docker client. Will raise a `ConnectionError` if the Docker daemon is not accessible. :return: the Docker client """ global _client client = _client() if client is None: # First try looking at the environment variables for specific...
def get_dump_method(dump, protocol=-1): """Get dump function code string""" if dump is None: dump = 'pickle' if dump.startswith('pickle'): if dump == 'pickle': proto = protocol else: proto = dump.strip('pickle') try: proto = int(proto) ...
def get_pull_method(pull): """Get pull function code string""" if pull is None or pull.startswith('pickle'): code = """ import os try: import cPickle as pickle except: import pickle with open('$FILE_PATH', 'rb') as fd: PULLED_DATA = pickle.load( fd ) """ elif pull.startswith('dill'): ...
def path_required(func): """Decorate methods when repository path is required.""" @wraps(func) def wrapper(self, *args, **kwargs): if self.path is None: warnings.warn('Must load (Repository.load_repository) or initialize (Repository.create_repository) the repository first !') ...
def __clean_before_after(self, stateBefore, stateAfter, keepNoneEmptyDirectory=True): """clean repository given before and after states""" # prepare after for faster search errors = [] afterDict = {} [afterDict.setdefault(list(aitem)[0],[]).append(aitem) for aitem in stateAfte...
def get_stats(self): """ Get repository descriptive stats :Returns: #. numberOfDirectories (integer): Number of diretories in repository #. numberOfFiles (integer): Number of files in repository """ if self.__path is None: return 0,0 n...
def reset(self): """Reset repository instance. """ self.__path = None self.__repo = {'repository_unique_name': str(uuid.uuid1()), 'create_utctime': time.time(), 'last_update_utctime': None, 'pyrep_version': st...
def is_repository(self, path): """ Check if there is a Repository in path. :Parameters: #. path (string): The real path of the directory where to check if there is a repository. :Returns: #. result (boolean): Whether it's a repository or not. ...
def load_repository(self, path, verbose=True, ntrials=3): """ Load repository from a directory path and update the current instance. First, new repository still will be loaded. If failed, then old style repository load will be tried. :Parameters: #. path (string): Th...
def create_repository(self, path, info=None, description=None, replace=True, allowNoneEmpty=True, raiseError=True): """ create a repository in a directory. This method insures the creation of the directory in the system if it is missing.\n **N.B. If replace is True and existing reposito...
def remove_repository(self, path=None, removeEmptyDirs=True): """ Remove all repository from path along with all repository tracked files. :Parameters: #. path (None, string): The path the repository to remove. #. removeEmptyDirs (boolean): Whether to remove remaining em...
def save(self, description=None, raiseError=True, ntrials=3): """ Save repository '.pyreprepo' to disk and create (if missing) or update (if description is not None) '.pyrepdirinfo'. :Parameters: #. description (None, str): Repository main directory information. ...
def is_name_allowed(self, path): """ Get whether creating a file or a directory from the basenane of the given path is allowed :Parameters: #. path (str): The absolute or relative path or simply the file or directory name. :Returns: #. all...
def to_repo_relative_path(self, path, split=False): """ Given a path, return relative path to diretory :Parameters: #. path (str): Path as a string #. split (boolean): Whether to split path to its components :Returns: #. relativePath (str, list): Rel...
def get_repository_state(self, relaPath=None): """ Get a list representation of repository state along with useful information. List state is ordered relativeley to directories level :Parameters: #. relaPath (None, str): relative directory path from where to s...
def get_file_info(self, relativePath): """ Get file information dict from the repository given its relative path. :Parameters: #. relativePath (string): The relative to the repository path of the file. :Returns: #. info (None, dictionary): The fil...
def is_repository_file(self, relativePath): """ Check whether a given relative path is a repository file path :Parameters: #. relativePath (string): File relative path :Returns: #. isRepoFile (boolean): Whether file is a repository file. #. isFileOnD...
def walk_files_path(self, relativePath="", fullPath=False, recursive=False): """ Walk the repository relative path and yield file relative/full path. :parameters: #. relativePath (string): The relative path from which start the walk. #. fullPath (boolean): Whether to ret...
def walk_files_info(self, relativePath="", fullPath=False, recursive=False): """ Walk the repository relative path and yield tuple of two items where first item is file relative/full path and second item is file info. If file info is not found on disk, second item will be None. ...
def walk_directories_info(self, relativePath="", fullPath=False, recursive=False): """ Walk the repository relative path and yield tuple of two items where first item is directory relative/full path and second item is directory info. If directory file info is not found on disk, second it...
def create_package(self, path=None, name=None, mode=None): """ Create a tar file package of all the repository files and directories. Only files and directories that are tracked in the repository are stored in the package tar file. **N.B. On some systems packaging requires root ...
def add_directory(self, relativePath, description=None, clean=False, raiseError=True, ntrials=3): """ Add a directory in the repository and creates its attribute in the Repository with utc timestamp. It insures adding all the missing directories in the path. ...
def remove_directory(self, relativePath, clean=False, raiseError=True, ntrials=3): """ Remove directory from repository tracking. :Parameters: #. relativePath (string): The relative to the repository path of the directory to remove from the repository. #. ...
def rename_directory(self, relativePath, newName, raiseError=True, ntrials=3): """ Rename a directory in the repository. It insures renaming the directory in the system. :Parameters: #. relativePath (string): The relative to the repository path of the directory to be ...
def copy_directory(self, relativePath, newRelativePath, overwrite=False, raiseError=True, ntrials=3): """ Copy a directory in the repository. New directory must not exist. :Parameters: #. relativePath (string): The relative to the repository path of ...
def dump_file(self, value, relativePath, description=None, dump=None, pull=None, replace=False, raiseError=True, ntrials=3): """ Dump a file using its value to the system and creates its attribute in the Repository with utc ...
def update_file(self, value, relativePath, description=False, dump=False, pull=False, raiseError=True, ntrials=3): """ Update the value of a file that is already in the Repository.\n If file is not registered in repository, and error will be thrown.\n If file is...
def pull_file(self, relativePath, pull=None, update=True, ntrials=3): """ Pull a file's data from the Repository. :Parameters: #. relativePath (string): The relative to the repository path from where to pull the file. #. pull (None, string): The pulling me...
def rename_file(self, relativePath, newRelativePath, force=False, raiseError=True, ntrials=3): """ Rename a file in the repository. It insures renaming the file in the system. :Parameters: #. relativePath (string): The relative to the repository path of ...
def remove_file(self, relativePath, removeFromSystem=False, raiseError=True, ntrials=3): """ Remove file from repository. :Parameters: #. relativePath (string): The relative to the repository path of the file to remove. #. removeF...
def rename(self, key: Any, new_key: Any): """ Renames an item in this collection as a transaction. Will override if new key name already exists. :param key: the current name of the item :param new_key: the new name that the item should have """ if new_key == key:...
def get_text_fingerprint(text, hash_meth, encoding="utf-8"): # pragma: no cover """ Use default hash method to return hash value of a piece of string default setting use 'utf-8' encoding. """ m = hash_meth() m.update(text.encode(encoding)) return m.hexdigest()
def md5file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE): """ Return md5 hash value of a piece of a file Estimate processing time on: :param abspath: the absolute path to the file :param nbytes: only has first N bytes of the file. if 0 or None, hash all file CPU = i7-4600U 2.10GHz ...
def sha256file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE): """ Return sha256 hash value of a piece of a file Estimate processing time on: :param abspath: the absolute path to the file :param nbytes: only has first N bytes of the file. if 0 or None, hash all file """ return get...
def sha512file(abspath, nbytes=0, chunk_size=DEFAULT_CHUNK_SIZE): """ Return sha512 hash value of a piece of a file Estimate processing time on: :param abspath: the absolute path to the file :param nbytes: only has first N bytes of the file. if 0 or None, hash all file """ return get...
def register(registerable: Any): """ Registers an object, notifying any listeners that may be interested in it. :param registerable: the object to register """ listenable = registration_event_listenable_map[type(registerable)] event = RegistrationEvent(registerable, RegistrationEvent.Type.REGIST...
def unregister(registerable: Any): """ Unregisters an object, notifying any listeners that may be interested in it. :param registerable: the object to unregister """ listenable = registration_event_listenable_map[type(registerable)] event = RegistrationEvent(registerable, RegistrationEvent.Type....
def _load_module(path: str): """ Dynamically loads the python module at the given path. :param path: the path to load the module from """ spec = spec_from_file_location(os.path.basename(path), path) module = module_from_spec(spec) spec.loader.exec_module(module)
def is_empty(self, strict=True): """ - If it's a file, check if it is a empty file. (0 bytes content) - If it's a directory, check if there's no file and dir in it. But if ``strict = False``, then only check if there's no file in it. :param strict: only useful when it is a d...
def auto_complete_choices(self, case_sensitive=False): """ A command line auto complete similar behavior. Find all item with same prefix of this one. :param case_sensitive: toggle if it is case sensitive. :return: list of :class:`pathlib_mate.pathlib2.Path`. """ ...
def print_big_dir(self, top_n=5): """ Print ``top_n`` big dir in this dir. """ self.assert_is_dir_and_exists() size_table = sorted( [(p, p.dirsize) for p in self.select_dir(recursive=False)], key=lambda x: x[1], reverse=True, ) ...
def print_big_file(self, top_n=5): """ Print ``top_n`` big file in this dir. """ self.assert_is_dir_and_exists() size_table = sorted( [(p, p.size) for p in self.select_file(recursive=True)], key=lambda x: x[1], reverse=True, ) ...
def print_big_dir_and_big_file(self, top_n=5): """Print ``top_n`` big dir and ``top_n`` big file in each dir. """ self.assert_is_dir_and_exists() size_table1 = sorted( [(p, p.dirsize) for p in self.select_dir(recursive=False)], key=lambda x: x[1], rev...
def file_stat_for_all(self, filters=all_true): # pragma: no cover """ Find out how many files, directories and total size (Include file in it's sub-folder) it has for each folder and sub-folder. :returns: stat, a dict like ``{"directory path": { "file": number of files, "dir"...
def file_stat(self, filters=all_true): """Find out how many files, directorys and total size (Include file in it's sub-folder). :returns: stat, a dict like ``{"file": number of files, "dir": number of directorys, "size": total size in bytes}`` **中文文档** 返回一个目录中的文件, 文件...
def mirror_to(self, dst): # pragma: no cover """ Create a new folder having exactly same structure with this directory. However, all files are just empty file with same file name. :param dst: destination directory. The directory can't exists before you execute this. **...
def execute_pyfile(self, py_exe=None): # pragma: no cover """ Execute every ``.py`` file as main script. :param py_exe: str, python command or python executable path. **中文文档** 将目录下的所有Python文件作为主脚本用当前解释器运行。 """ import subprocess self.assert_is_dir_and_...
def trail_space(self, filters=lambda p: p.ext == ".py"): # pragma: no cover """ Trail white space at end of each line for every ``.py`` file. **中文文档** 将目录下的所有被选择的文件中行末的空格删除。 """ self.assert_is_dir_and_exists() for p in self.select_file(filters): tr...
def autopep8(self, **kwargs): # pragma: no cover """ Auto convert your python code in a directory to pep8 styled code. :param kwargs: arguments for ``autopep8.fix_code`` method. **中文文档** 将目录下的所有Python文件用pep8风格格式化。增加其可读性和规范性。 """ self.assert_is_dir_and_exists()...
def notify_listeners(self, data: Optional[_ListenableDataType]=_NO_DATA_MARKER): """ Notify event listeners, passing them the given data (if any). :param data: the data to pass to the event listeners """ for listener in self._listeners: if data is not Listenable._NO_D...
def size(self): """ File size in bytes. """ try: return self._stat.st_size except: # pragma: no cover self._stat = self.stat() return self.size
def mtime(self): """ Get most recent modify time in timestamp. """ try: return self._stat.st_mtime except: # pragma: no cover self._stat = self.stat() return self.mtime
def atime(self): """ Get most recent access time in timestamp. """ try: return self._stat.st_atime except: # pragma: no cover self._stat = self.stat() return self.atime
def ctime(self): """ Get most recent create time in timestamp. """ try: return self._stat.st_ctime except: # pragma: no cover self._stat = self.stat() return self.ctime
def get_terminal_size(default_cols=80, default_rows=25): """Return current terminal size (cols, rows) or a default if detect fails. This snippet comes from color ls by Chuck Blake: http://pdos.csail.mit.edu/~cblake/cls/cls.py """ def ioctl_GWINSZ(fd): """Get (cols, rows) from a putative fd...
def get_metainfo(scriptfile, keywords=['author', 'contact', 'copyright', 'download', 'git', 'subversion', 'version', 'website'], special={}, first_line_pattern=r'^(?P<progname>.+)(\s+v(?P<version>\S+))?', keyword_pattern_template=r'^\s*%(pretty)s:\s*(?...
def unusedoptions(self, sections): """Lists options that have not been used to format other values in their sections. Good for finding out if the user has misspelled any of the options. """ unused = set([]) for section in _list(sections): if not sel...
def parse(self, argv, usedname, location): """Consume and process arguments and store the result. ARGS: argv <list str>: The argument list to parse. usedname <str>: The string used by the user to invoke the option. location <str>: A user friend...
def parsestr(self, argsstr, usedname, location): """Parse a string lexically and store the result. ARGS: argsstr <str>: The string to parse. usedname <str>: The string used by the user to invoke the option. location <str>: A user friendly sring...
def parse(self, argv): """Consume and process arguments and store the result. argv is the list of arguments to parse (will be modified). Recurring PositionalArgumants get a list as .value. Optional PositionalArguments that do not get any arguments to parse get ...