INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
: param unicode source_filename: The source filename. Schemas: local ftp http
def _DoCopyFile(source_filename, target_filename, copy_symlink=True): ''' :param unicode source_filename: The source filename. Schemas: local, ftp, http :param unicode target_filename: Target filename. Schemas: local, ftp :param copy_symlink: @see _CopyFileLoca...
Copy a file locally to a directory.
def _CopyFileLocal(source_filename, target_filename, copy_symlink=True): ''' Copy a file locally to a directory. :param unicode source_filename: The filename to copy from. :param unicode target_filename: The filename to copy to. :param bool copy_symlink: If True and source...
Copy files from the given source to the target.
def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False): ''' Copy files from the given source to the target. :param unicode source_dir: A filename, URL or a file mask. Ex. x:\coilib50 x:\coilib50\* http://server/directory/file ...
Copies files into directories according to a file mapping
def CopyFilesX(file_mapping): ''' Copies files into directories, according to a file mapping :param list(tuple(unicode,unicode)) file_mapping: A list of mappings between the directory in the target and the source. For syntax, @see: ExtendedPathMask :rtype: list(tuple(unicode,unicode)) ...
: param unicode path: Path to a file ( local or ftp )
def IsFile(path): ''' :param unicode path: Path to a file (local or ftp) :raises NotImplementedProtocol: If checking for a non-local, non-ftp file :rtype: bool :returns: True if the file exists .. seealso:: FTP LIMITATIONS at this module's doc for performance issues in...
Determine the type of drive which can be one of the following values: DRIVE_UNKNOWN = 0 The drive type cannot be determined.
def GetDriveType(path): ''' Determine the type of drive, which can be one of the following values: DRIVE_UNKNOWN = 0 The drive type cannot be determined. DRIVE_NO_ROOT_DIR = 1 The root path is invalid; for example, there is no volume mounted at the specified path. ...
: param unicode directory: A path
def IsDir(directory): ''' :param unicode directory: A path :rtype: bool :returns: Returns whether the given path points to an existent directory. :raises NotImplementedProtocol: If the path protocol is not local or ftp .. seealso:: FTP LIMITATIONS at this module's doc ...
: rtype: bool: returns: True if the path already exists ( either a file or a directory )
def Exists(path): ''' :rtype: bool :returns: True if the path already exists (either a file or a directory) .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information ''' from six.moves.urllib.parse import urlparse path_url = urlparse(path) # Handle lo...
Recursively copy a directory tree.
def CopyDirectory(source_dir, target_dir, override=False): ''' Recursively copy a directory tree. :param unicode source_dir: Where files will come from :param unicode target_dir: Where files will go to :param bool override: If True and target_dir already exists, it will be...
Deletes the given local filename.
def DeleteFile(target_filename): ''' Deletes the given local filename. .. note:: If file doesn't exist this method has no effect. :param unicode target_filename: A local filename :raises NotImplementedForRemotePathError: If trying to delete a non-local path :raises FileOnlyAc...
Appends content to a local file.
def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False): ''' Appends content to a local file. :param unicode filename: :param unicode contents: :type eol_style: EOL_STYLE_XXX constant :param eol_style: Replaces the EOL by the appropriate EOL depen...
Moves a file.
def MoveFile(source_filename, target_filename): ''' Moves a file. :param unicode source_filename: :param unicode target_filename: :raises NotImplementedForRemotePathError: If trying to operate with non-local files. ''' _AssertIsLocal(source_filename) _AssertIsLocal(target_file...
Moves a directory.
def MoveDirectory(source_dir, target_dir): ''' Moves a directory. :param unicode source_dir: :param unicode target_dir: :raises NotImplementedError: If trying to move anything other than: Local dir -> local dir FTP dir -> FTP dir (same host) ''' if not IsDi...
Reads a file and returns its contents. Works for both local and remote files.
def GetFileContents(filename, binary=False, encoding=None, newline=None): ''' Reads a file and returns its contents. Works for both local and remote files. :param unicode filename: :param bool binary: If True returns the file as is, ignore any EOL conversion. :param unicode encoding: ...
Reads a file and returns its contents as a list of lines. Works for both local and remote files.
def GetFileLines(filename, newline=None, encoding=None): ''' Reads a file and returns its contents as a list of lines. Works for both local and remote files. :param unicode filename: :param None|''|'\n'|'\r'|'\r\n' newline: Controls universal newlines. See 'io.open' newline parameter d...
Open a file and returns it. Consider the possibility of a remote file ( HTTP HTTPS FTP )
def OpenFile(filename, binary=False, newline=None, encoding=None): ''' Open a file and returns it. Consider the possibility of a remote file (HTTP, HTTPS, FTP) :param unicode filename: Local or remote filename. :param bool binary: If True returns the file as is, ignore any EOL conv...
Lists the files in the given directory
def ListFiles(directory): ''' Lists the files in the given directory :type directory: unicode | unicode :param directory: A directory or URL :rtype: list(unicode) | list(unicode) :returns: List of filenames/directories found in the given directory. Returns None if the g...
Create a file with the given contents.
def CreateFile(filename, contents, eol_style=EOL_STYLE_NATIVE, create_dir=True, encoding=None, binary=False): ''' Create a file with the given contents. :param unicode filename: Filename and path to be created. :param unicode contents: The file contents as a string. :type eol_styl...
Replaces all occurrences of old by new in the given file.
def ReplaceInFile(filename, old, new, encoding=None): ''' Replaces all occurrences of "old" by "new" in the given file. :param unicode filename: The name of the file. :param unicode old: The string to search for. :param unicode new: Replacement string. :return unicode...
Create directory including any missing intermediate directory.
def CreateDirectory(directory): ''' Create directory including any missing intermediate directory. :param unicode directory: :return unicode|urlparse.ParseResult: Returns the created directory or url (see urlparse). :raises NotImplementedProtocol: If protocol is not local or FTP. ...
Deletes a directory.
def DeleteDirectory(directory, skip_on_error=False): ''' Deletes a directory. :param unicode directory: :param bool skip_on_error: If True, ignore any errors when trying to delete directory (for example, directory not found) :raises NotImplementedForRemotePathError: If try...
: param unicode path: Path to file or directory
def GetMTime(path): ''' :param unicode path: Path to file or directory :rtype: float :returns: Modification time for path. If this is a directory, the highest mtime from files inside it will be returned. @note: In some Linux distros (such as CentOs, or anything wit...
On Windows returns a list of mapped network drives
def ListMappedNetworkDrives(): ''' On Windows, returns a list of mapped network drives :return: tuple(string, string, bool) For each mapped netword drive, return 3 values tuple: - the local drive - the remote path- - True if the mapping is enabled (warning: not r...
Create a symbolic link at link_path pointing to target_path.
def CreateLink(target_path, link_path, override=True): ''' Create a symbolic link at `link_path` pointing to `target_path`. :param unicode target_path: Link target :param unicode link_path: Fullpath to link name :param bool override: If True and `link_path` already exists ...
: param unicode path: Path being tested
def IsLink(path): ''' :param unicode path: Path being tested :returns bool: True if `path` is a link ''' _AssertIsLocal(path) if sys.platform != 'win32': return os.path.islink(path) import jaraco.windows.filesystem return jaraco.windows.filesystem.islink(path)
Read the target of the symbolic link at path.
def ReadLink(path): ''' Read the target of the symbolic link at `path`. :param unicode path: Path to a symbolic link :returns unicode: Target of a symbolic link ''' _AssertIsLocal(path) if sys.platform != 'win32': return os.readlink(path) # @UndefinedVariable ...
Checks if a given path is local raise an exception if not.
def _AssertIsLocal(path): ''' Checks if a given path is local, raise an exception if not. This is used in filesystem functions that do not support remote operations yet. :param unicode path: :raises NotImplementedForRemotePathError: If the given path is not local ''' from six.move...
Replaces eol on each line by the given eol_style.
def _HandleContentsEol(contents, eol_style): ''' Replaces eol on each line by the given eol_style. :param unicode contents: :type eol_style: EOL_STYLE_XXX constant :param eol_style: ''' if eol_style == EOL_STYLE_NONE: return contents if eol_style == EOL_STYLE_UNIX: retu...
Call Windows NET command used to acquire/ configure network services settings.
def _CallWindowsNetCommand(parameters): ''' Call Windows NET command, used to acquire/configure network services settings. :param parameters: list of command line parameters :return: command output ''' import subprocess popen = subprocess.Popen(["net"] + parameters, stdout=subprocess.PIPE,...
Checks if the given target filename should be re - generated because the source has changed.: param source: the source filename.: param target: the target filename.: return bool: True if the target is out - dated False otherwise.
def CheckForUpdate(source, target): ''' Checks if the given target filename should be re-generated because the source has changed. :param source: the source filename. :param target: the target filename. :return bool: True if the target is out-dated, False otherwise. ''' return \ ...
Verifies if a filename match with given patterns.
def MatchMasks(filename, masks): ''' Verifies if a filename match with given patterns. :param str filename: The filename to match. :param list(str) masks: The patterns to search in the filename. :return bool: True if the filename has matched with one pattern, False otherwise. ''' im...
Searches for files in a given directory that match with the given patterns.
def FindFiles(dir_, in_filters=None, out_filters=None, recursive=True, include_root_dir=True, standard_paths=False): ''' Searches for files in a given directory that match with the given patterns. :param str dir_: the directory root, to search the files. :param list(str) in_filters: a list with pattern...
os. path. expanduser wrapper necessary because it cannot handle unicode strings properly.
def ExpandUser(path): ''' os.path.expanduser wrapper, necessary because it cannot handle unicode strings properly. This is not necessary in Python 3. :param path: .. seealso:: os.path.expanduser ''' if six.PY2: encoding = sys.getfilesystemencoding() path = path.encode(e...
Helper to iterate over the files in a directory putting those in the passed StringIO in ini format.
def DumpDirHashToStringIO(directory, stringio, base='', exclude=None, include=None): ''' Helper to iterate over the files in a directory putting those in the passed StringIO in ini format. :param unicode directory: The directory for which the hash should be done. :param StringIO stringio: ...
: param unicode filename: The file from which the md5 should be calculated. If the filename is given the contents should NOT be given.
def Md5Hex(filename=None, contents=None): ''' :param unicode filename: The file from which the md5 should be calculated. If the filename is given, the contents should NOT be given. :param unicode contents: The contents for which the md5 should be calculated. If the contents are give...
Iterator for random hexadecimal hashes
def IterHashes(iterator_size, hash_length=7): ''' Iterator for random hexadecimal hashes :param iterator_size: Amount of hashes return before this iterator stops. Goes on forever if `iterator_size` is negative. :param int hash_length: Size of each hash returned. :return ge...
A context manager to replace and restore a value using a getter and setter.
def PushPopItem(obj, key, value): ''' A context manager to replace and restore a value using a getter and setter. :param object obj: The object to replace/restore. :param object key: The key to replace/restore in the object. :param object value: The value to replace. Example:: with Push...
Splits the given path into their components: recursive dirname in_filters and out_filters
def Split(cls, extended_path_mask): ''' Splits the given path into their components: recursive, dirname, in_filters and out_filters :param str: extended_path_mask: The "extended path mask" to split :rtype: tuple(bool,bool,str,list(str),list(str)) :returns: ...
Gets all the messages from a specified file.
def GetMessages(self, files): """Gets all the messages from a specified file. This will find and resolve dependencies, failing if the descriptor pool cannot satisfy them. Args: files: The file names to extract messages from. Returns: A dictionary mapping proto names to the message cla...
** MultiNest Nested Sampling ** via PyMultiNest <http:// johannesbuchner. github. com/ PyMultiNest/ index. html > _.: param parameter_names: name of parameters ; not directly used here but for multinest_marginal. py plotting tool.
def multinest(parameter_names, transform, loglikelihood, output_basename, **problem): """ **MultiNest Nested Sampling** via `PyMultiNest <http://johannesbuchner.github.com/PyMultiNest/index.html>`_. :param parameter_names: name of parameters; not directly used here, but for multinest_marginal.py plotting too...
Return the database string for a database specifier. The database specifier takes a custom format for specifying local and remote databases. A local database is specified by the following format: local: <db_name > For example a database called sessions would be specified by the string local: sessions. Remote databases ...
def specifier_to_db(db_spec): """ Return the database string for a database specifier. The database specifier takes a custom format for specifying local and remote databases. A local database is specified by the following format: local:<db_name> For example, a database cal...
Return the database specifier for a database string. This accepts a database name or URL and returns a database specifier in the format accepted by specifier_to_db. It is recommended that you consult the documentation for that function for an explanation of the format.
def db_to_specifier(db_string): """ Return the database specifier for a database string. This accepts a database name or URL, and returns a database specifier in the format accepted by ``specifier_to_db``. It is recommended that you consult the documentation for that function for an explanation...
Return a CouchDB database instance from a database string.
def get_db_from_db(db_string): """Return a CouchDB database instance from a database string.""" server = get_server_from_db(db_string) local_match = PLAIN_RE.match(db_string) remote_match = URL_RE.match(db_string) # If this looks like a local specifier: if local_match: return server[loca...
Make sure a DB specifier exists creating it if necessary.
def ensure_specifier_exists(db_spec): """Make sure a DB specifier exists, creating it if necessary.""" local_match = LOCAL_RE.match(db_spec) remote_match = REMOTE_RE.match(db_spec) plain_match = PLAIN_RE.match(db_spec) if local_match: db_name = local_match.groupdict().get('database') ...
Exclude NoSet objec
def coerce(value1, value2, default=None): """Exclude NoSet objec .. code-block:: >>> coerce(NoSet, 'value') 'value' """ if value1 is not NoSet: return value1 elif value2 is not NoSet: return value2 else: return default
Returns all transactions and forged blocks by voters clustered around a single delegate_address
def get_events_vote_cluster(self, delegate_address): ''' Returns all transactions and forged blocks by voters clustered around a single delegate_address''' delegate_pubkey = self.account_details(address=delegate_address)['public_key'] plusvote = '+{delegate_pubkey}'.format(delegate_pubkey=dele...
This function doesn t work yet. Instead use legacy. trueshare () for a functional tbw script
def tbw(self, delegate_address, blacklist=None, share_fees=False, compound_interest=False): """This function doesn't work yet. Instead use legacy.trueshare() for a functional tbw script""" if not blacklist: blacklist = [] delegate_public_key = self.account_details(address=delegate_a...
** Classic optimization methods **
def classical(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000, method='neldermead', **args): """ **Classic optimization methods** :param start: start position vector (before transform) :param ftol: accuracy required to stop at optimum :param disp: verbosity :param...
** Convex optimization based on Brent s method ** A strict assumption of one optimum between the parameter limits is used. The bounds are narrowed until it is found i. e. the likelihood function is flat within the bounds. * If optimum outside bracket expands bracket until contained. * Thus guaranteed to return local op...
def onebyone(transform, loglikelihood, parameter_names, prior, start = 0.5, ftol=0.1, disp=0, nsteps=40000, parallel=False, find_uncertainties=False, **args): """ **Convex optimization based on Brent's method** A strict assumption of one optimum between the parameter limits is used. The bounds are narrowed until...
Parse a hub key into a dictionary of component parts
def parse_hub_key(key): """Parse a hub key into a dictionary of component parts :param key: str, a hub key :returns: dict, hub key split into parts :raises: ValueError """ if key is None: raise ValueError('Not a valid key') match = re.match(PATTERN, key) if not match: m...
Raise an exception if string doesn t match a part s regex
def match_part(string, part): """Raise an exception if string doesn't match a part's regex :param string: str :param part: a key in the PARTS dict :raises: ValueError, TypeError """ if not string or not re.match('^(' + PARTS[part] + ')$', string): raise ValueError('{} should match {}'.f...
Create and return an array of hub keys: param resolver_id: the service that can resolve this key: param hub_id: the unique id of the hub: param repository_id: the type of id that the provider recognises: param entity_type: the type of the entity to which the key refers.: param entity_id: ID of entity ( UUID ): returns:...
def generate_hub_key(resolver_id, hub_id, repository_id, entity_type, entity_id=None): """Create and return an array of hub keys :param resolver_id: the service that can resolve this key :param hub_id: the unique id of the hub :param repository_id: the type of id that the provider recognises :param ...
Compact a CouchDB database with optional synchronicity. The compact function will compact a CouchDB database stored on an running CouchDB server. By default this process occurs * asynchronously * meaning that the compaction will occur in the background. Often you ll want to know when the process has completed ; for thi...
def compact(db_spec, poll_interval=0): """ Compact a CouchDB database with optional synchronicity. The ``compact`` function will compact a CouchDB database stored on an running CouchDB server. By default, this process occurs *asynchronously*, meaning that the compaction will occur in the b...
apply default settings to commands not static shadow self in eval
def apply_defaults(self, commands): """ apply default settings to commands not static, shadow "self" in eval """ for command in commands: if 'action' in command and "()" in command['action']: command['action'] = eval("self.{}".format(command['action'])) ...
add commands to parser
def create_commands(self, commands, parser): """ add commands to parser """ self.apply_defaults(commands) def create_single_command(command): keys = command['keys'] del command['keys'] kwargs = {} for item in command: kwargs[item] =...
get config for subparser and create commands
def create_subparsers(self, parser): """ get config for subparser and create commands""" subparsers = parser.add_subparsers() for name in self.config['subparsers']: subparser = subparsers.add_parser(name) self.create_commands(self.config['subparsers'][name], subparser)
custom command line action to show version
def show_version(self): """ custom command line action to show version """ class ShowVersionAction(argparse.Action): def __init__(inner_self, nargs=0, **kw): super(ShowVersionAction, inner_self).__init__(nargs=nargs, **kw) def __call__(inner_self, parser, args, ...
custom command line action to check file exist
def check_path_action(self): """ custom command line action to check file exist """ class CheckPathAction(argparse.Action): def __call__(self, parser, args, value, option_string=None): if type(value) is list: value = value[0] user_value = v...
Return the consumer and oauth tokens with three - legged OAuth process and save in a yaml file in the user s home directory.
def new_user(yaml_path): ''' Return the consumer and oauth tokens with three-legged OAuth process and save in a yaml file in the user's home directory. ''' print 'Retrieve API Key from https://www.shirts.io/accounts/api_console/' api_key = raw_input('Shirts.io API Key: ') tokens = { ...
Adds properties for all fields in this protocol message type.
def _AddPropertiesForExtensions(descriptor, cls): """Adds properties for all fields in this protocol message type.""" extension_dict = descriptor.extensions_by_name for extension_name, extension_field in extension_dict.items(): constant_name = extension_name.upper() + "_FIELD_NUMBER" setattr(cls, constant...
Unpacks Any message and returns the unpacked message.
def _InternalUnpackAny(msg): """Unpacks Any message and returns the unpacked message. This internal method is differnt from public Any Unpack method which takes the target message as argument. _InternalUnpackAny method does not have target message type and need to find the message type in descriptor pool. A...