INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Waits until all of the specified elements are not found on the page.
def wait_until_page_does_not_contain_these_elements(self, timeout, *locators): """Waits until all of the specified elements are not found on the page. | *Argument* | *Description* | *Example* | | timeout | maximum time to wait, if set to ${None} it will use Selenium's default timeout | 5s | | *locators | Selen...
Presses the specified key. The complementKey defines the key to hold when pressing the specified key. For example you could use $ { VK_TAB } as key and use $ { VK_SHIFT } as complementKey in order to press Shift + Tab ( back tab )
def tap_key(self, key, complementKey=None) : """Presses the specified `key`. The `complementKey` defines the key to hold when pressing the specified `key`. For example, you could use ${VK_TAB} as `key` and use ${VK_SHIFT} as `complementKey' in order to press Shift + Tab (back tab) | =Argument= | =Description= ...
Clicks the element specified by locator until the operation succeeds. This should be used with buttons that are generated in real - time and that don t have their click handling available immediately. This keyword avoids unclickable element exceptions.
def wait_until_element_is_clickable(self, locator, timeout=None): """Clicks the element specified by `locator` until the operation succeeds. This should be used with buttons that are generated in real-time and that don't have their click handling available immediately. This keyword avoids unclickable element exce...
Actual visitor method implementation.
def _visitor_impl(self, arg): """Actual visitor method implementation.""" if (_qualname(type(self)), type(arg)) in _methods: method = _methods[(_qualname(type(self)), type(arg))] return method(self, arg) else: # if no visitor method found for this arg type, # search in parent...
Decorator that creates a visitor method.
def visitor(arg_type): """Decorator that creates a visitor method.""" def decorator(fn): declaring_class = _declaring_class(fn) _methods[(declaring_class, arg_type)] = fn # Replace all decorated methods with _visitor_impl return _visitor_impl return decorator
Returns a full absolute URL based on the request host.
def absolute(parser, token): ''' Returns a full absolute URL based on the request host. This template tag takes exactly the same paramters as url template tag. ''' node = url(parser, token) return AbsoluteUrlNode( view_name=node.view_name, args=node.args, kwargs=node.kwa...
Returns a full absolute URL based on the current site.
def site(parser, token): ''' Returns a full absolute URL based on the current site. This template tag takes exactly the same paramters as url template tag. ''' node = url(parser, token) return SiteUrlNode( view_name=node.view_name, args=node.args, kwargs=node.kwargs, ...
This replaces the method from Selenium2Library to fix the major logic error in it
def _wait_until_exp(self, timeout, error, function, *args): """This replaces the method from Selenium2Library to fix the major logic error in it""" error = error.replace('<TIMEOUT>', self._format_timeout(timeout)) def wait_func(): return None if function(*args) else error self._wait_until_no_error_ex...
This replaces the method from Selenium2Library to fix the major logic error in it
def _wait_until_no_error_exp(self, timeout, wait_func, *args): """This replaces the method from Selenium2Library to fix the major logic error in it""" timeout = robot.utils.timestr_to_secs(timeout) if timeout is not None else self._timeout_in_secs maxtime = time.time() + timeout while True: try: ...
Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code - block directive
def rst(filename): ''' Load rst file and sanitize it for PyPI. Remove unsupported github tags: - code-block directive ''' content = open(filename).read() return re.sub(r'\.\.\s? code-block::\s*(\w|\+)+', '::', content)
Returns a dictionary of callable methods of object obj.
def get_callable_method_dict(obj): """Returns a dictionary of callable methods of object `obj`. @param obj: ZOS API Python COM object @return: a dictionary of callable methods Notes: the function only returns the callable attributes that are listed by dir() function. Properties are not r...
Replicate callable methods from a srcObj to dstObj ( generally a wrapper object ).
def replicate_methods(srcObj, dstObj): """Replicate callable methods from a `srcObj` to `dstObj` (generally a wrapper object). @param srcObj: source object @param dstObj: destination object of the same type. @return : none Implementer notes: 1. Once the methods are mapped from the `s...
Returns a lists of properties bound to the object zos_obj
def get_properties(zos_obj): """Returns a lists of properties bound to the object `zos_obj` @param zos_obj: ZOS API Python COM object @return prop_get: list of properties that are only getters @return prop_set: list of properties that are both getters and setters """ prop_get = set(zos_obj._pro...
Creates and returns a wrapper class of a ZOS object exposing the ZOS objects methods and propertis and patching custom specialized attributes
def managed_wrapper_class_factory(zos_obj): """Creates and returns a wrapper class of a ZOS object, exposing the ZOS objects methods and propertis, and patching custom specialized attributes @param zos_obj: ZOS API Python COM object """ cls_name = repr(zos_obj).split()[0].split('.')[-1] disp...
Helper function to wrap ZOS API COM objects.
def wrapped_zos_object(zos_obj): """Helper function to wrap ZOS API COM objects. @param zos_obj : ZOS API Python COM object @return: instance of the wrapped ZOS API class. If the input object is not a ZOS-API COM object or if it is already wrapped, then the object is returned without ...
<Purpose > Generate a pair of ECDSA public and private keys with one of the supported external cryptography libraries. The public and private keys returned conform to securesystemslib. formats. PEMECDSA_SCHEMA and securesystemslib. formats. PEMECDSA_SCHEMA respectively.
def generate_public_and_private(scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate a pair of ECDSA public and private keys with one of the supported, external cryptography libraries. The public and private keys returned conform to 'securesystemslib.formats.PEMECDSA_SCHEMA' and 'securesystemslib....
<Purpose > Return a ( signature scheme ) tuple.
def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Return a (signature, scheme) tuple. >>> requested_scheme = 'ecdsa-sha2-nistp256' >>> public, private = generate_public_and_private(requested_scheme) >>> data = b'The quick brown fox jumps over the lazy ...
<Purpose > Verify that signature was produced by the private key associated with public_key.
def verify_signature(public_key, scheme, signature, data): """ <Purpose> Verify that 'signature' was produced by the private key associated with 'public_key'. >>> scheme = 'ecdsa-sha2-nistp256' >>> public, private = generate_public_and_private(scheme) >>> data = b'The quick brown fox jumps over...
<Purpose > Create public and private ECDSA keys from a private pem. The public and private keys are strings in PEM format:
def create_ecdsa_public_and_private_from_pem(pem, password=None): """ <Purpose> Create public and private ECDSA keys from a private 'pem'. The public and private keys are strings in PEM format: public: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----', private: '-----BEGIN EC PRIVATE KEY--...
<Purpose > Return a string in PEM format where the private part of the ECDSA key is encrypted. The private part of the ECDSA key is encrypted as done by pyca/ cryptography: Encrypt using the best available encryption for a given key s backend. This is a curated encryption choice and the algorithm may change over time.
def create_ecdsa_encrypted_pem(private_pem, passphrase): """ <Purpose> Return a string in PEM format, where the private part of the ECDSA key is encrypted. The private part of the ECDSA key is encrypted as done by pyca/cryptography: "Encrypt using the best available encryption for a given key's back...
Clean any processing data and prepare object for reuse
def reset(self): """Clean any processing data, and prepare object for reuse """ self.current_table = None self.tables = [] self.data = [{}] self.additional_data = {} self.lines = [] self.set_state('document') self.current_file = None self.s...
Parse single line ( or more if particular keyword actually demands it )
def _parse_line(self, file): """Parse single line (or more if particular keyword actually demands it) :param file: :type file: file """ line = self._strip_comments(file.readline()) # check if the file ended if not line: return False # line w...
Set current parsing state to table create new table object and add it to tables collection
def _set_table(self, data): """Set current parsing state to 'table', create new table object and add it to tables collection """ self.set_state('table') self.current_table = HEPTable(index=len(self.tables) + 1) self.tables.append(self.current_table) self.data.appe...
Parse dataset data of the original HEPData format
def _parse_table_data(self, data): """Parse dataset data of the original HEPData format :param data: header of the table to be parsed :raise ValueError: """ header = data.split(':') self.current_table.data_header = header for i, h in enumerate(header): ...
Transform a square matrix into a format with two independent variables and one dependent variable.
def _reformat_matrix(self): """Transform a square matrix into a format with two independent variables and one dependent variable. """ nxax = len(self.current_table.data['independent_variables']) nyax = len(self.current_table.data['dependent_variables']) npts = len(self.current_ta...
Parse qual attribute of the old HEPData format
def _parse_qual(self, data): """Parse qual attribute of the old HEPData format example qual: *qual: RE : P P --> Z0 Z0 X :param data: data to be parsed :type data: str """ list = [] headers = data.split(':') name = headers[0].strip() nam...
Parse header ( xheader or yheader )
def _parse_header(self, data): """Parse header (xheader or yheader) :param data: data to be parsed :type data: str :return: list with header's data :rtype: list """ return_list = [] headers = data.split(':') for header in headers: he...
Processes line stripping any comments from it
def _strip_comments(line): """Processes line stripping any comments from it :param line: line to be processed :type line: str :return: line with removed comments :rtype: str """ if line == '': return line r = re.search('(?P<line>[^#]*)(#(?P<co...
Reads multiline symbols ( ususally comments )
def _read_multiline(self, init_data): """Reads multiline symbols (ususally comments) :param init_data: initial data (parsed from the line containing keyword) :return: parsed value of the multiline symbol :rtype: str """ result = init_data first = True wh...
Returns parsing function which will parse data as text and add it to the table metatadata dictionary with the provided key
def _bind_set_table_metadata(self, key, multiline=False): """Returns parsing function which will parse data as text, and add it to the table metatadata dictionary with the provided key :param key: dictionary key under which parsed data will be added to table.metadata :type key: str ...
Returns parsing function which will parse data as text and add it to the table additional data dictionary with the provided key
def _bind_parse_additional_data(self, key, multiline=False): """Returns parsing function which will parse data as text, and add it to the table additional data dictionary with the provided key :param key: dictionary key under which parsed data will be added to table.metadata :type key: ...
If an error is a percentage we convert to a float then calculate the percentage of the supplied value.
def error_value_processor(value, error): """ If an error is a percentage, we convert to a float, then calculate the percentage of the supplied value. :param value: base value, e.g. 10 :param error: e.g. 20.0% :return: the absolute error, e.g. 12 for the above case. """ if isinstance(err...
<Purpose > To get file s length and hash information. The hash is computed using the sha256 algorithm. This function is used in the signerlib. py and updater. py modules.
def get_file_details(filepath, hash_algorithms=['sha256']): """ <Purpose> To get file's length and hash information. The hash is computed using the sha256 algorithm. This function is used in the signerlib.py and updater.py modules. <Arguments> filepath: Absolute file path of a file. ...
<Purpose > To ensure existence of the parent directory of filename. If the parent directory of name does not exist create it.
def ensure_parent_dir(filename): """ <Purpose> To ensure existence of the parent directory of 'filename'. If the parent directory of 'name' does not exist, create it. Example: If 'filename' is '/a/b/c/d.txt', and only the directory '/a/b/' exists, then directory '/a/b/c/d/' will be created. <Ar...
<Purpose > Check if the directory containing filepath is in the list/ tuple of confined_directories.
def file_in_confined_directories(filepath, confined_directories): """ <Purpose> Check if the directory containing 'filepath' is in the list/tuple of 'confined_directories'. <Arguments> filepath: A string representing the path of a file. The following example path strings are viewed as fi...
<Purpose > Find the index if any of a role with a given name in a list of roles.
def find_delegated_role(roles, delegated_role): """ <Purpose> Find the index, if any, of a role with a given name in a list of roles. <Arguments> roles: The list of roles, each of which must have a 'name' attribute. delegated_role: The name of the role to be found in the list of roles. ...
<Purpose > Ensure that the list of targets specified by rolename are allowed ; this is determined by inspecting the delegations field of the parent role of rolename. If a target specified by rolename is not found in the delegations field of metadata_object_of_parent raise an exception. The top - level role targets is a...
def ensure_all_targets_allowed(rolename, list_of_targets, parent_delegations): """ <Purpose> Ensure that the list of targets specified by 'rolename' are allowed; this is determined by inspecting the 'delegations' field of the parent role of 'rolename'. If a target specified by 'rolename' is not found i...
<Purpose > Determine whether a list of paths are consistent with their alleged path hash prefixes. By default the SHA256 hash function is used.
def paths_are_consistent_with_hash_prefixes(paths, path_hash_prefixes): """ <Purpose> Determine whether a list of paths are consistent with their alleged path hash prefixes. By default, the SHA256 hash function is used. <Arguments> paths: A list of paths for which their hashes will be checked. ...
<Purpose > Compute the hash of target_filepath. This is useful in conjunction with the path_hash_prefixes attribute in a delegated targets role which tells us which paths it is implicitly responsible for.
def get_target_hash(target_filepath): """ <Purpose> Compute the hash of 'target_filepath'. This is useful in conjunction with the "path_hash_prefixes" attribute in a delegated targets role, which tells us which paths it is implicitly responsible for. The repository may optionally organize targets i...
<Purpose > Tries to import json module. We used to fall back to the simplejson module but we have dropped support for that module. We are keeping this interface intact for backwards compatibility.
def import_json(): """ <Purpose> Tries to import json module. We used to fall back to the simplejson module, but we have dropped support for that module. We are keeping this interface intact for backwards compatibility. <Arguments> None. <Exceptions> ImportError: on failure to import the j...
<Purpose > Deserialize data ( JSON string ) to a Python object.
def load_json_string(data): """ <Purpose> Deserialize 'data' (JSON string) to a Python object. <Arguments> data: A JSON string. <Exceptions> securesystemslib.exceptions.Error, if 'data' cannot be deserialized to a Python object. <Side Effects> None. <Returns> Deserialized o...
<Purpose > Deserialize a JSON object from a file containing the object.
def load_json_file(filepath): """ <Purpose> Deserialize a JSON object from a file containing the object. <Arguments> filepath: Absolute path of JSON file. <Exceptions> securesystemslib.exceptions.FormatError: If 'filepath' is improperly formatted. securesystemslib.exceptions.Error: ...
<Purpose > While protecting against timing attacks compare the hexadecimal arguments and determine if they are equal.
def digests_are_equal(digest1, digest2): """ <Purpose> While protecting against timing attacks, compare the hexadecimal arguments and determine if they are equal. <Arguments> digest1: The first hexadecimal string value to compare. digest2: The second hexadecimal string value to compa...
__init__ helper.
def _default_temporary_directory(self, prefix): """__init__ helper.""" try: self.temporary_file = tempfile.NamedTemporaryFile(prefix=prefix) except OSError as err: # pragma: no cover logger.critical('Cannot create a system temporary directory: '+repr(err)) raise securesystemslib.exception...
<Purpose > Read specified number of bytes. If size is not specified then the whole file is read and the file pointer is placed at the beginning of the file.
def read(self, size=None): """ <Purpose> Read specified number of bytes. If size is not specified then the whole file is read and the file pointer is placed at the beginning of the file. <Arguments> size: Number of bytes to be read. <Exceptions> securesystemslib.except...
<Purpose > Writes a data string to the file.
def write(self, data, auto_flush=True): """ <Purpose> Writes a data string to the file. <Arguments> data: A string containing some data. auto_flush: Boolean argument, if set to 'True', all data will be flushed from internal buffer. <Exceptions> None. ...
<Purpose > Copies self. temporary_file to a non - temp file at destination_path and closes self. temporary_file so that it is removed.
def move(self, destination_path): """ <Purpose> Copies 'self.temporary_file' to a non-temp file at 'destination_path' and closes 'self.temporary_file' so that it is removed. <Arguments> destination_path: Path to store the file in. <Exceptions> None. <Return> ...
<Purpose > To decompress a compressed temp file object. Decompression is performed on a temp file object that is compressed this occurs after downloading a compressed file. For instance if a compressed version of some meta file in the repository is downloaded the temp file containing the compressed meta file will be de...
def decompress_temp_file_object(self, compression): """ <Purpose> To decompress a compressed temp file object. Decompression is performed on a temp file object that is compressed, this occurs after downloading a compressed file. For instance if a compressed version of some meta file in...
<Purpose > Closes the temporary file object. close_temp_file mimics usual file. close () however temporary file destroys itself when close_temp_file is called. Further if compression is set second temporary file instance self. _orig_file is also closed so that no open temporary files are left open.
def close_temp_file(self): """ <Purpose> Closes the temporary file object. 'close_temp_file' mimics usual file.close(), however temporary file destroys itself when 'close_temp_file' is called. Further if compression is set, second temporary file instance 'self._orig_file' is also closed ...
<Purpose > Return True if object matches this schema False if it doesn t. If the caller wishes to signal an error on a failed match check_match () should be called which will raise a exceptions. FormatError exception.
def matches(self, object): """ <Purpose> Return True if 'object' matches this schema, False if it doesn't. If the caller wishes to signal an error on a failed match, check_match() should be called, which will raise a 'exceptions.FormatError' exception. """ try: self.check_match(...
Return a single event object or block until an event is received and return it. - etypes ( str ): If defined Slack event type ( s ) not matching the filter will be ignored. See https:// api. slack. com/ events for a listing of valid event types. - timeout ( int ): Max time in seconds to block waiting for new event
def get_event(self, *etypes, timeout=None): """ Return a single event object or block until an event is received and return it. - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of...
returns a blocking generator yielding Slack event objects params: - etypes ( str ): If defined Slack event type ( s ) not matching the filter will be ignored. See https:// api. slack. com/ events for a listing of valid event types. - idle_timeout ( int ): optional maximum amount of time ( in seconds ) to wait between e...
def events(self, *etypes, idle_timeout=None): """ returns a blocking generator yielding Slack event objects params: - etypes(str): If defined, Slack event type(s) not matching the filter will be ignored. See https://api.slack.com/events for a listing of valid event...
Send a message to a channel or group via Slack RTM socket returning the resulting message object
def send_msg(self, text, channel, confirm=True): """ Send a message to a channel or group via Slack RTM socket, returning the resulting message object params: - text(str): Message text to send - channel(Channel): Target channel - confirm(bool): If True, wait f...
Extend event object with User and Channel objects
def _process_event(self, event): """ Extend event object with User and Channel objects """ if event.get('user'): event.user = self.lookup_user(event.get('user')) if event.get('channel'): event.channel = self.lookup_channel(event.get('channel')) if self.user.id i...
Converts a supported input_format ( * oldhepdata * * yaml * ) to a supported output_format ( * csv * * root * * yaml * * yoda * ).
def convert(input, output=None, options={}): """Converts a supported ``input_format`` (*oldhepdata*, *yaml*) to a supported ``output_format`` (*csv*, *root*, *yaml*, *yoda*). :param input: location of input file for *oldhepdata* format or input directory for *yaml* format :param output: location of out...
This is kind of legacy function - this functionality may be useful for some people so even though now the default of writing CSV is writing unpacked data ( divided by independent variable ) this method is still available and accessible if pack flag is specified in Writer s options
def _write_packed_data(self, data_out, table): """This is kind of legacy function - this functionality may be useful for some people, so even though now the default of writing CSV is writing unpacked data (divided by independent variable) this method is still available and accessible if ```pack`...
<Purpose > Provide the caller with the ability to create digest objects without having to worry about crypto library availability or which library to use. The caller also has the option of specifying which hash algorithm and/ or library to use.
def digest(algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY): """ <Purpose> Provide the caller with the ability to create digest objects without having to worry about crypto library availability or which library to use. The caller also has the option of specifying which hash algorith...
<Purpose > Generate a digest object given a file object. The new digest object is updated with the contents of file_object prior to returning the object to the caller.
def digest_fileobject(file_object, algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY, normalize_line_endings=False): """ <Purpose> Generate a digest object given a file object. The new digest object is updated with the contents of 'file_object' prior to returning the object to the...
<Purpose > Generate a digest object update its hash using a file object specified by filename and then return it to the caller.
def digest_filename(filename, algorithm=DEFAULT_HASH_ALGORITHM, hash_library=DEFAULT_HASH_LIBRARY, normalize_line_endings=False): """ <Purpose> Generate a digest object, update its hash using a file object specified by filename, and then return it to the caller. <Arguments> filename: The fi...
Get the antlr token stream.
def get_token_stream(source: str) -> CommonTokenStream: """ Get the antlr token stream. """ lexer = LuaLexer(InputStream(source)) stream = CommonTokenStream(lexer) return stream
Returns a Evolution Stone object containing the details about the evolution stone.
def get_evolution_stone(self, slug): """ Returns a Evolution Stone object containing the details about the evolution stone. """ endpoint = '/evolution-stone/' + slug return self.make_request(self.BASE_URL + endpoint)
Returns a Pokemon League object containing the details about the league.
def get_league(self, slug): """ Returns a Pokemon League object containing the details about the league. """ endpoint = '/league/' + slug return self.make_request(self.BASE_URL + endpoint)
Returns an array of Pokemon objects containing all the forms of the Pokemon specified the name of the Pokemon.
def get_pokemon_by_name(self, name): """ Returns an array of Pokemon objects containing all the forms of the Pokemon specified the name of the Pokemon. """ endpoint = '/pokemon/' + str(name) return self.make_request(self.BASE_URL + endpoint)
Returns an array of Pokemon objects containing all the forms of the Pokemon specified the Pokedex number.
def get_pokemon_by_number(self, number): """ Returns an array of Pokemon objects containing all the forms of the Pokemon specified the Pokedex number. """ endpoint = '/pokemon/' + str(number) return self.make_request(self.BASE_URL + endpoint)
<Purpose > Generate public and private RSA keys with modulus length bits. The public and private keys returned conform to securesystemslib. formats. PEMRSA_SCHEMA and have the form:
def generate_rsa_public_and_private(bits=_DEFAULT_RSA_KEY_BITS): """ <Purpose> Generate public and private RSA keys with modulus length 'bits'. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ...' or ...
<Purpose > Generate a scheme signature. The signature and the signature scheme used is returned as a ( signature scheme ) tuple.
def create_rsa_signature(private_key, data, scheme='rsassa-pss-sha256'): """ <Purpose> Generate a 'scheme' signature. The signature, and the signature scheme used, is returned as a (signature, scheme) tuple. The signing process will use 'private_key' to generate the signature of 'data'. RFC34...
<Purpose > Determine whether the corresponding private key of public_key produced signature. verify_signature () will use the public key signature scheme and data to complete the verification.
def verify_rsa_signature(signature, signature_scheme, public_key, data): """ <Purpose> Determine whether the corresponding private key of 'public_key' produced 'signature'. verify_signature() will use the public key, signature scheme, and 'data' to complete the verification. >>> public, private = ...
<Purpose > Return a string in PEM format ( TraditionalOpenSSL ) where the private part of the RSA key is encrypted using the best available encryption for a given key s backend. This is a curated ( by cryptography. io ) encryption choice and the algorithm may change over time.
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the ...
<Purpose > Generate public and private RSA keys from an optionally encrypted PEM. The public and private keys returned conform to securesystemslib. formats. PEMRSA_SCHEMA and have the form:
def create_rsa_public_and_private_from_pem(pem, passphrase=None): """ <Purpose> Generate public and private RSA keys from an optionally encrypted PEM. The public and private keys returned conform to 'securesystemslib.formats.PEMRSA_SCHEMA' and have the form: '-----BEGIN RSA PUBLIC KEY----- ... ---...
<Purpose > Return a string containing key_object in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key () function can be applied to the encrypted string to restore the original key object. key_object is a TUF key ( e. g. RSAKEY_SCHEMA ED25519KEY_SCHEMA ). This function calls...
def encrypt_key(key_object, password): """ <Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a TUF...
<Purpose > Return a string containing encrypted_key in non - encrypted form. The decrypt_key () function can be applied to the encrypted string to restore the original key object a TUF key ( e. g. RSAKEY_SCHEMA ED25519KEY_SCHEMA ). This function calls the appropriate cryptography module ( i. e. pyca_crypto_keys. py ) t...
def decrypt_key(encrypted_key, password): """ <Purpose> Return a string containing 'encrypted_key' in non-encrypted form. The decrypt_key() function can be applied to the encrypted string to restore the original key object, a TUF key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls the ...
Generate a derived key by feeding password to the Password - Based Key Derivation Function ( PBKDF2 ). pyca/ cryptography s PBKDF2 implementation is used in this module. salt may be specified so that a previous derived key may be regenerated otherwise _SALT_SIZE is used by default. iterations is the number of SHA - 256...
def _generate_derived_key(password, salt=None, iterations=None): """ Generate a derived key by feeding 'password' to the Password-Based Key Derivation Function (PBKDF2). pyca/cryptography's PBKDF2 implementation is used in this module. 'salt' may be specified so that a previous derived key may be regenerate...
Encrypt key_data using the Advanced Encryption Standard ( AES - 256 ) algorithm. derived_key_information should contain a key strengthened by PBKDF2. The key size is 256 bits and AES s mode of operation is set to CTR ( CounTeR Mode ). The HMAC of the ciphertext is generated to ensure the ciphertext has not been modifie...
def _encrypt(key_data, derived_key_information): """ Encrypt 'key_data' using the Advanced Encryption Standard (AES-256) algorithm. 'derived_key_information' should contain a key strengthened by PBKDF2. The key size is 256 bits and AES's mode of operation is set to CTR (CounTeR Mode). The HMAC of the ciphert...
The corresponding decryption routine for _encrypt ().
def _decrypt(file_contents, password): """ The corresponding decryption routine for _encrypt(). 'securesystemslib.exceptions.CryptoError' raised if the decryption fails. """ # Extract the salt, iterations, hmac, initialization vector, and ciphertext # from 'file_contents'. These five values are delimited...
Creates a new environment in home_dir.
def create_environment(home_dir, site_packages=True, clear=False, unzip_setuptools=False, use_distribute=False): """ Creates a new environment in ``home_dir``. If ``site_packages`` is true (the default) then the global ``site-packages/`` directory will be on the path. If ``c...
Return the path locations for the environment ( where libraries are where scripts go etc )
def path_locations(home_dir): """Return the path locations for the environment (where libraries are, where scripts go, etc)""" # XXX: We'd use distutils.sysconfig.get_python_inc/lib but its # prefix arg is broken: http://bugs.python.org/issue3386 if sys.platform == 'win32': # Windows has lot...
Install just the base environment no distutils patches etc
def install_python(home_dir, lib_dir, inc_dir, bin_dir, site_packages, clear): """Install just the base environment, no distutils patches etc""" if sys.executable.startswith(bin_dir): print 'Please use the *system* python to run this script' return if clear: rmtree(lib_dir) ...
Some platforms ( particularly Gentoo on x64 ) put things in lib64/ pythonX. Y instead of lib/ pythonX. Y. If this is such a platform we ll just create a symlink so lib64 points to lib
def fix_lib64(lib_dir): """ Some platforms (particularly Gentoo on x64) put things in lib64/pythonX.Y instead of lib/pythonX.Y. If this is such a platform we'll just create a symlink so lib64 points to lib """ if [p for p in distutils.sysconfig.get_config_vars().values() if isinstance(p...
If the executable given isn t an absolute path search $PATH for the interpreter
def resolve_interpreter(exe): """ If the executable given isn't an absolute path, search $PATH for the interpreter """ if os.path.abspath(exe) != exe: paths = os.environ.get('PATH', '').split(os.pathsep) for path in paths: if os.path.exists(os.path.join(path, exe)): ...
Makes the already - existing environment use relative paths and takes out the #! - based environment selection in scripts.
def make_environment_relocatable(home_dir): """ Makes the already-existing environment use relative paths, and takes out the #!-based environment selection in scripts. """ activate_this = os.path.join(home_dir, 'bin', 'activate_this.py') if not os.path.exists(activate_this): logger.fatal...
<Purpose > Generate public and private RSA keys with modulus length bits. In addition a keyid identifier for the RSA key is generated. The object returned conforms to securesystemslib. formats. RSAKEY_SCHEMA and has the form:
def generate_rsa_key(bits=_DEFAULT_RSA_KEY_BITS, scheme='rsassa-pss-sha256'): """ <Purpose> Generate public and private RSA keys, with modulus length 'bits'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has t...
<Purpose > Generate public and private ECDSA keys with NIST P - 256 + SHA256 ( for hashing ) being the default scheme. In addition a keyid identifier for the ECDSA key is generated. The object returned conforms to securesystemslib. formats. ECDSAKEY_SCHEMA and has the form:
def generate_ecdsa_key(scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate public and private ECDSA keys, with NIST P-256 + SHA256 (for hashing) being the default scheme. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECD...
<Purpose > Generate public and private ED25519 keys both of length 32 - bytes although they are hexlified to 64 bytes. In addition a keyid identifier generated for the returned ED25519 object. The object returned conforms to securesystemslib. formats. ED25519KEY_SCHEMA and has the form:
def generate_ed25519_key(scheme='ed25519'): """ <Purpose> Generate public and private ED25519 keys, both of length 32-bytes, although they are hexlified to 64 bytes. In addition, a keyid identifier generated for the returned ED25519 object. The object returned conforms to 'securesystemslib.formats...
<Purpose > Return a dictionary conformant to securesystemslib. formats. KEY_SCHEMA. If private is True include the private key. The dictionary returned has the form:
def format_keyval_to_metadata(keytype, scheme, key_value, private=False): """ <Purpose> Return a dictionary conformant to 'securesystemslib.formats.KEY_SCHEMA'. If 'private' is True, include the private key. The dictionary returned has the form: {'keytype': keytype, 'scheme' : scheme, 'k...
<Purpose > Construct a key dictionary ( e. g. securesystemslib. formats. RSAKEY_SCHEMA ) according to the keytype of key_metadata. The dict returned by this function has the exact format as the dict returned by one of the key generations functions like generate_ed25519_key (). The dict returned has the form:
def format_metadata_to_key(key_metadata): """ <Purpose> Construct a key dictionary (e.g., securesystemslib.formats.RSAKEY_SCHEMA) according to the keytype of 'key_metadata'. The dict returned by this function has the exact format as the dict returned by one of the key generations functions, like ge...
Return the keyid of key_value.
def _get_keyid(keytype, scheme, key_value, hash_algorithm = 'sha256'): """Return the keyid of 'key_value'.""" # 'keyid' will be generated from an object conformant to KEY_SCHEMA, # which is the format Metadata files (e.g., root.json) store keys. # 'format_keyval_to_metadata()' returns the object needed by _get...
<Purpose > Return a signature dictionary of the form: { keyid: f30a0870d026980100c0573bd557394f8c1bbd6... sig:... }.
def create_signature(key_dict, data): """ <Purpose> Return a signature dictionary of the form: {'keyid': 'f30a0870d026980100c0573bd557394f8c1bbd6...', 'sig': '...'}. The signing process will use the private key in key_dict['keyval']['private'] and 'data' to generate the signature. The fol...
<Purpose > Determine whether the private key belonging to key_dict produced signature. verify_signature () will use the public key found in key_dict the sig objects contained in signature and data to complete the verification.
def verify_signature(key_dict, signature, data): """ <Purpose> Determine whether the private key belonging to 'key_dict' produced 'signature'. verify_signature() will use the public key found in 'key_dict', the 'sig' objects contained in 'signature', and 'data' to complete the verification. >>...
<Purpose > Import the private RSA key stored in pem and generate its public key ( which will also be included in the returned rsakey object ). In addition a keyid identifier for the RSA key is generated. The object returned conforms to securesystemslib. formats. RSAKEY_SCHEMA and has the form:
def import_rsakey_from_private_pem(pem, scheme='rsassa-pss-sha256', password=None): """ <Purpose> Import the private RSA key stored in 'pem', and generate its public key (which will also be included in the returned rsakey object). In addition, a keyid identifier for the RSA key is generated. The objec...
<Purpose > Generate an RSA key object from pem. In addition a keyid identifier for the RSA key is generated. The object returned conforms to securesystemslib. formats. RSAKEY_SCHEMA and has the form:
def import_rsakey_from_public_pem(pem, scheme='rsassa-pss-sha256'): """ <Purpose> Generate an RSA key object from 'pem'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', ...
<Purpose > Extract only the portion of the pem that includes the header and footer with any leading and trailing characters removed. The string returned has the following form:
def extract_pem(pem, private_pem=False): """ <Purpose> Extract only the portion of the pem that includes the header and footer, with any leading and trailing characters removed. The string returned has the following form: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' or '----...
<Purpose > Return a string containing key_object in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key () function can be applied to the encrypted string to restore the original key object. key_object is a key ( e. g. RSAKEY_SCHEMA ED25519KEY_SCHEMA ). This function relies on...
def encrypt_key(key_object, password): """ <Purpose> Return a string containing 'key_object' in encrypted form. Encrypted strings may be safely saved to a file. The corresponding decrypt_key() function can be applied to the encrypted string to restore the original key object. 'key_object' is a key...
<Purpose > Return a string containing encrypted_key in non - encrypted form. The decrypt_key () function can be applied to the encrypted string to restore the original key object a key ( e. g. RSAKEY_SCHEMA ED25519KEY_SCHEMA ). This function calls pyca_crypto_keys. py to perform the actual decryption.
def decrypt_key(encrypted_key, passphrase): """ <Purpose> Return a string containing 'encrypted_key' in non-encrypted form. The decrypt_key() function can be applied to the encrypted string to restore the original key object, a key (e.g., RSAKEY_SCHEMA, ED25519KEY_SCHEMA). This function calls pyca_...
<Purpose > Return a string in PEM format ( TraditionalOpenSSL ) where the private part of the RSA key is encrypted using the best available encryption for a given key s backend. This is a curated ( by cryptography. io ) encryption choice and the algorithm may change over time.
def create_rsa_encrypted_pem(private_key, passphrase): """ <Purpose> Return a string in PEM format (TraditionalOpenSSL), where the private part of the RSA key is encrypted using the best available encryption for a given key's backend. This is a curated (by cryptography.io) encryption choice and the ...
<Purpose > Checks if a passed PEM formatted string is a PUBLIC key by looking for the following pattern:
def is_pem_public(pem): """ <Purpose> Checks if a passed PEM formatted string is a PUBLIC key, by looking for the following pattern: '-----BEGIN PUBLIC KEY----- ... -----END PUBLIC KEY-----' >>> rsa_key = generate_rsa_key() >>> public = rsa_key['keyval']['public'] >>> private = rsa_key['ke...
<Purpose > Checks if a passed PEM formatted string is a PRIVATE key by looking for the following patterns:
def is_pem_private(pem, keytype='rsa'): """ <Purpose> Checks if a passed PEM formatted string is a PRIVATE key, by looking for the following patterns: '-----BEGIN RSA PRIVATE KEY----- ... -----END RSA PRIVATE KEY-----' '-----BEGIN EC PRIVATE KEY----- ... -----END EC PRIVATE KEY-----' >>> rsa_k...
<Purpose > Import the private ECDSA key stored in pem and generate its public key ( which will also be included in the returned ECDSA key object ). In addition a keyid identifier for the ECDSA key is generated. The object returned conforms to:
def import_ecdsakey_from_private_pem(pem, scheme='ecdsa-sha2-nistp256', password=None): """ <Purpose> Import the private ECDSA key stored in 'pem', and generate its public key (which will also be included in the returned ECDSA key object). In addition, a keyid identifier for the ECDSA key is generated....
<Purpose > Generate an ECDSA key object from pem. In addition a keyid identifier for the ECDSA key is generated. The object returned conforms to securesystemslib. formats. ECDSAKEY_SCHEMA and has the form:
def import_ecdsakey_from_public_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Generate an ECDSA key object from 'pem'. In addition, a keyid identifier for the ECDSA key is generated. The object returned conforms to 'securesystemslib.formats.ECDSAKEY_SCHEMA' and has the form: {'keytype': '...
<Purpose > Import either a public or private ECDSA PEM. In contrast to the other explicit import functions ( import_ecdsakey_from_public_pem and import_ecdsakey_from_private_pem ) this function is useful for when it is not known whether pem is private or public.
def import_ecdsakey_from_pem(pem, scheme='ecdsa-sha2-nistp256'): """ <Purpose> Import either a public or private ECDSA PEM. In contrast to the other explicit import functions (import_ecdsakey_from_public_pem and import_ecdsakey_from_private_pem), this function is useful for when it is not known whe...
If success return a tuple ( args body )
def parse_func_body(self): """If success, return a tuple (args, body)""" self.save() self._expected = [] if self.next_is_rc(Tokens.OPAR, False): # do not render right hidden self.handle_hidden_right() # render hidden after new level args = self.parse_param_list(...