INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
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. | 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... |
Check if there is a Repository in path. | 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.
"""
... |
get directory info from the Repository. | 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.
... |
get parent directory info of a file or directory from the Repository. | 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.
... |
get file information dict from the repository given its relative path and name. | 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... |
Given an id get the corresponding file info as the following: \ n ( relative path joined with file name file info dict ) | 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... |
Given an id get the corresponding file info relative path joined with file name. | 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... |
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. | 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:
#... |
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. | 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 ... |
Remove directory from repository. | 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... |
Move a directory in the repository from one place to another. It insures moving all the files and subdirectories in the system. | 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... |
Rename a directory in the repository. It insures renaming the directory in the system. | 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.
... |
Rename a directory in the repository. It insures renaming the file in the system. | 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... |
Remove file from repository. | 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... |
Copy an exisitng system file to the repository. attribute in the Repository with utc timestamp. | 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):... |
Dump a file using its value to the system and creates its attribute in the Repository with utc timestamp. | 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... |
Update the value and the utc timestamp 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 missing in the system it will be regenerated as dump method is called. | 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... |
Pull a file s data from the Repository. | 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.... |
Ensure value is string. | def ensure_str(value):
"""
Ensure value is string.
"""
if isinstance(value, six.string_types):
return value
else:
return six.text_type(value) |
Pre - process input argument whether if it is: | 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... |
Stream reports to application logs | 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... |
Stream reports to application logs | def stream(self, report):
"""Stream reports to application logs"""
payload = {
"agent": {
"host": report['instance']['hostname'],
"version": "1.0.0"
},
"components": [
{
"name": self.name,
... |
Build per minute stats for each key | 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] = {}
... |
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 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`
... |
Loads all of the data from the files in directory location.: return: a origin map of all the loaded data | 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... |
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: return: the data contained within the map | 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
... |
Monitors data kept in files in the predefined directory in a new thread. | 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... |
Stops monitoring the predefined directory. | 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 ... |
Called when a file in the monitored directory has been created.: param event: the file system event | 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... |
Called when a file in the monitored directory has been modified.: param event: the file system event | 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... |
Called when a file in the monitored directory has been deleted.: param event: the file system event | 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... |
Called when a file in the monitored directory has been moved. | 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... |
Tears down all temp files and directories. | 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... |
Creates a temp directory.: param mkdtemp_kwargs: named arguments to be passed to tempfile. mkdtemp: return: the location of the temp directory | 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}
... |
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 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
"""
... |
Return a new: class: pathlib_mate. pathlib2. Path object with updated information. | 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.
... |
Test whether a file target is not exists or it exists but allow overwrite. | 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 |
An advanced: meth: pathlib_mate. pathlib2. Path. rename method provide ability to rename by each components of a path. A new Path instance will returns. | 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... |
Copy this file to other place. | 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... |
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 client to the daemon | 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... |
Clients a Docker client. | 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... |
Get dump function code string | 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)
... |
Get pull function code string | 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'):
... |
Decorate methods when repository path is required. | 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 !')
... |
clean repository given before and after states | 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... |
Get repository descriptive stats | 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... |
Reset repository instance. | 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... |
Check if there is a Repository in path. | 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.
... |
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. | 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... |
create a repository in a directory. This method insures the creation of the directory in the system if it is missing. \ n | 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... |
Remove all repository from path along with all repository tracked files. | 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... |
Save repository. pyreprepo to disk and create ( if missing ) or update ( if description is not None ). pyrepdirinfo. | 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.
... |
Get whether creating a file or a directory from the basenane of the given path is allowed | 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... |
Given a path return relative path to diretory | 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... |
Get a list representation of repository state along with useful information. List state is ordered relativeley to directories level | 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... |
Get file information dict from the repository given its relative path. | 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... |
Check whether a given relative path is a repository file path | 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... |
Walk the repository relative path and yield file relative/ full path. | 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... |
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_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.
... |
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 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... |
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. | 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 ... |
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 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.
... |
Remove directory from repository tracking. | 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.
#. ... |
Rename a directory in the repository. It insures renaming the directory in the system. | 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 ... |
Copy a directory in the repository. New directory must not exist. | 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
... |
Dump a file using its value to the system and creates its attribute in the Repository with utc timestamp. | 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 ... |
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 missing in the system it will be regenerated as dump method is called. Unlike dump_file update_file won t block the whole repository but only the file being updated. | 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... |
Pull a file s data from the Repository. | 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... |
Rename a file in the repository. It insures renaming the file in the system. | 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
... |
Remove file from repository. | 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... |
Renames an item in this collection as a transaction. | 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:... |
Use default hash method to return hash value of a piece of string default setting use utf - 8 encoding. | 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() |
Return md5 hash value of a piece of a file | 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 ... |
Return sha256 hash value of a piece of a file | 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... |
Return sha512 hash value of a piece of a file | 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... |
Registers an object notifying any listeners that may be interested in it.: param registerable: the object to register | 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... |
Unregisters an object notifying any listeners that may be interested in it.: param registerable: the object to unregister | 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.... |
Dynamically loads the python module at the given path.: param path: the path to load the module from | 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) |
- 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. | 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... |
A command line auto complete similar behavior. Find all item with same prefix of this one. | 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`.
"""
... |
Print top_n big dir in this dir. | 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,
)
... |
Print top_n big file in this dir. | 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,
)
... |
Print top_n big dir and top_n big file in each dir. | 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... |
Find out how many files directories and total size ( Include file in it s sub - folder ) it has for each folder and sub - folder. | 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"... |
Find out how many files directorys and total size ( Include file in it s sub - folder ). | 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}``
**中文文档**
返回一个目录中的文件, 文件... |
Create a new folder having exactly same structure with this directory. However all files are just empty file with same file name. | 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.
**... |
Execute every. py file as main script. | 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_... |
Trail white space at end of each line for every. py file. | 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... |
Auto convert your python code in a directory to pep8 styled code. | 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()... |
Notify event listeners passing them the given data ( if any ).: param data: the data to pass to the event listeners | 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... |
File size in bytes. | def size(self):
"""
File size in bytes.
"""
try:
return self._stat.st_size
except: # pragma: no cover
self._stat = self.stat()
return self.size |
Get most recent modify time in timestamp. | 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 |
Get most recent access time in timestamp. | 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 |
Get most recent create time in timestamp. | 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 |
Return current terminal size ( cols rows ) or a default if detect fails. | 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... |
Dumb helper for pulling metainfo from a script __doc__ string. Returns a metainfo dict with command description progname and the given keywords ( if present ). This function will only make minimal efforts to succeed. If you need anything else: roll your own. The docstring needs to be multiline and the closing quotes ne... | 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*(?... |
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. | 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... |
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 friendly sring describing where the parser got this data from. | 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... |
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 describing where the parser got this data from. | 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... |
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 None as. value or [] if recurring. | 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
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.