text
stringlengths
81
112k
Adds an IP alias to a specific interface Adds an ip address as an alias to the specified interface on Linux systems. :param ip_address: (str) IP address to set as an alias :param interface: (str) The interface number or full device name, if an int is provided assumes the device name is eth<i> ...
Configures the source IP address for a Linux interface :param source_ip_address: (str) Source IP address to change :param desired_source_ip_address: (str) IP address to configure as the source in outgoing packets :param device_num: (int) Integer interface device number to configure :return: None :r...
Перед сохранением в методе save вызывается этот метод :param some_object: сохраненный объект def save_logic(self, some_object): """ Перед сохранением в методе save вызывается этот метод :param some_object: сохраненный объект """ some_object.validate_model() some_...
Generate shell color opcodes from a pretty coloring syntax. def fmt(msg, *args, **kw): # type: (str, *Any, **Any) -> str """ Generate shell color opcodes from a pretty coloring syntax. """ global is_tty if len(args) or len(kw): msg = msg.format(*args, **kw) opcode_subst = '\x1b[\\1m' if i...
Print colored message to stdout. def cprint(msg, *args, **kw): # type: (str, *Any, **Any) -> None """ Print colored message to stdout. """ if len(args) or len(kw): msg = msg.format(*args, **kw) print(fmt('{}<0>'.format(msg)))
Run a shell command. Args: cmd (str): The shell command to execute. shell (bool): Same as in `subprocess.Popen`. capture (bool): If set to True, it will capture the standard input/error instead of just piping it to the caller stdout/stderr. ...
Extracts the request's payload information. This method will merge the URL parameter information and the JSON body of the request together to generate a dictionary of key<->value pairings. This method assumes that the JSON body being provided is also a key-value map, if it is not, then an HTTPBadRe...
Handles external calling for this module Execute this python module and provide the args shown below to external call this module to send email messages! :return: None def main(): """Handles external calling for this module Execute this python module and provide the args shown below to exter...
Send the cons3rt agent log file :return: def send_cons3rt_agent_logs(self): """Send the cons3rt agent log file :return: """ log = logging.getLogger(self.cls_logger + '.send_cons3rt_agent_logs') if self.cons3rt_agent_log_dir is None: log.warn('There is not ...
Sends an email with the contents of the provided text file :return: None def send_text_file(self, text_file, sender=None, recipient=None): """Sends an email with the contents of the provided text file :return: None """ log = logging.getLogger(self.cls_logger + '.send_text_file...
:param name: yesterday, last_month :param today: Optional current datetime. Default is now(). :param tz: Optional timezone. Default is UTC. :return: datetime (begin, end) def get_date_range_by_name(name: str, today: datetime=None, tz=None) -> (datetime, datetime): """ :param name: yesterday, last_m...
:param options: :param default_range: Default datetime range to return if no other selected :return: begin, end, [(begin1,end1), (begin2,end2), ...] def parse_date_range_arguments(options: dict, default_range='last_month') -> (datetime, datetime, list): """ :param options: :param default_range: Def...
S3: All energy and A values: Podobedova, Kelleher, and Wiese 2009, J. Phys. Chem. Ref. Data, Vol. def load_elements(self): #Set atomic data #atomicData.setDataFile('he_i_rec_Pal12-Pal13.fits') atomicData.setDataFile('s_iii_coll_HRS12.dat') #Default: 's_iii_atom_PKW09.dat' '...
Clones a git url :param url: (str) Git URL in https or ssh :param clone_dir: (str) Path to the desired destination dir :param branch: (str) branch to clone :param username: (str) username for the git repo :param password: (str) password for the git repo :param max_retries: (int) the number of a...
Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password def encode_password(password): """Performs URL encoding for passwords :param password: (str) password to encode :return: (str) encoded password """ log = logging.getLogger(mod_log...
Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character def encode_character(char): """Returns URL encoding for a single character :param char (str) Single character to encode :returns (str) URL-encoded character """ if...
Get different tags as dicts ready to use as dropdown lists. def search_tags_as_filters(tags): """Get different tags as dicts ready to use as dropdown lists.""" # set dicts actions = {} contacts = {} formats = {} inspire = {} keywords = {} licenses = {} md_types = dict() owners =...
:param verified: телефон или email (verified_entity) :param keygen: функция генерации ключа :return: def generate(self, verified, keygen): """ :param verified: телефон или email (verified_entity) :param keygen: функция генерации ключа :return: """ return ...
Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found / unsupported country def iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from IBAN number. :param v: IBAN account number :return: (BIC...
Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum def fi_payment_reference_number(num: str): """ Appends Finland reference number checksum to existing number. :param num: At least 3 digits :return: Number plus checksum ...
Validates ISO reference number checksum. :param v: Reference number def iso_payment_reference_validator(v: str): """ Validates ISO reference number checksum. :param v: Reference number """ num = '' v = STRIP_WHITESPACE.sub('', v) for ch in v[4:] + v[0:4]: x = ord(ch) if ...
Returns BIC code and bank name from FI IBAN number. :param v: IBAN account number :return: (BIC code, bank name) or ('', '') if not found def fi_iban_bank_info(v: str) -> (str, str): """ Returns BIC code and bank name from FI IBAN number. :param v: IBAN account number :return: (BIC code, bank n...
Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code :return: (Bank name, account digit count) or ('', None) if not found def se_clearing_code_bank_info(clearing: str) -> (str, int): """ Returns Sweden bank info by clearning code. :param clearing: 4-digit clearing code...
Helper to get bins for histplot. def _histplot_bins(column, bins=100): """Helper to get bins for histplot.""" col_min = np.min(column) col_max = np.max(column) return range(col_min, col_max + 2, max((col_max - col_min) // bins, 1))
Formats the @value in required HTTP style @value: :class:datetime.datetime, #int, #float, #str time-like object -> #str HTTP-style formatted date (c)2014, Marcel Hellkamp def http_date(value): """ Formats the @value in required HTTP style @value: :class:datetime.datetime, #int, ...
Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None (c)2014, Marcel Hellkamp def parse_auth(header): """ Parse rfc2617 HTTP authentication header string (basic) and return (user,pass) tuple or None (c)2014, Marcel Hellkamp """ try: ...
Generates identicon image based on passed data. Arguments: data - Data which should be used for generating an identicon. This data will be used in order to create a digest which is used for generating the identicon. If the data passed is a hex digest already, the digest will be used as-is....
Give the currently developed hotfix a new name. def rename(name): # type: (str) -> None """ Give the currently developed hotfix a new name. """ from peltak.extra.gitflow import logic if name is None: name = click.prompt('Hotfix name') logic.hotfix.rename(name)
Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size .. class Foo(object): def __init__(self, cache_size=5000): self._cache = OrderedDict() self._cache_size...
:func:functools.lru_cache wrapper which allows you to prevent object types outside of @types from being cached. The main use case for this is preventing unhashable type errors when you still want to cache some results. .. from vital.cache import typed_lru @typed...
Property that maps to a key in a local dict-like attribute. self._cache must be an OrderedDict self._cache_size must be defined as LRU size self._cache_ttl is the expiration time in seconds .. class Foo(object): def __init__(self, cache_size=5000, cache_ttl=600): ...
Get context value with the given name and optional default. Args: name (str): The name of the context value. *default (Any): If given and the key doesn't not exist, this will be returned instead. If it's not given and the context value doe...
Set context value. Args: name (str): The name of the context value to change. value (Any): The new value for the selected context value def set(self, name, value): """ Set context value. Args: name (str): The ...
Checks if an alias already exists in a keystore :param alias: :param keystore_path: :param keystore_password: :return: (bool) True when the alias already exists in the keystore :raises: OSError def alias_exists(alias, keystore_path=None, keystore_password='changeit'): """Checks if an alias alr...
Define the filter function that every node must to implement. :param query: The sqlalchemy query. :type query: Query :param entity: The entity model. :type entity: type :return: The filtered query. :rtype: Tuple[Query, Any] def filter(self, query: Query, entity: type)...
Split and return the list of relation(s) and the attribute. :param attribute: :type attribute: str :return: A tuple where the first element is the list of related entities and the second is the attribute. :rtype: Tuple[List[str], str] def _extract_relations(self, attribute...
Transform the list of relation to list of class. :param related_mode: The model of the query. :type related_mode: type :param relations: The relation list get from the `_extract_relations`. :type relations: List[str] :return: Tuple with the list of relations (class) and the se...
Method to make the join when relation is found. :param query: The sqlalchemy query. :type query: Query :param join_models: The list of joined models get from the method `_get_relation`. :type join_models: Optional[List[type]] :return: The new Query with the joined ...
Apply the `_method` to all childs of the node. :param query: The sqlachemy query. :type query: Query :param entity: The entity model of the query. :type entity: type :return: A tuple with in first place the updated query and in second place the list of filt...
Sends SMS via Kajala Group SMS API. Contact info@kajala.com for access. :param phone: Phone number :param message: Message to be esnd :param sender: Sender (max 11 characters) :param kw: Variable key-value pairs to be sent to SMS API :return: Response from requests.post def send_sms(phone: str, mes...
Just a meta func to get execution time def _meta_get_resource_sync(md_uuid): """Just a meta func to get execution time""" isogeo.resource(id_resource=md_uuid) elapsed = default_timer() - START_TIME time_completed_at = "{:5.2f}s".format(elapsed) print("{0:<30} {1:>20}".format(md_uuid, time_complete...
Setup properties from parent app on the command def setup(self, app): ''' Setup properties from parent app on the command ''' self.logger = app.logger self.shell.logger = self.logger if not self.command_name: raise EmptyCommandNameException() self.a...
Logs exception error message and sends email to ADMINS if hostname is not testserver and DEBUG=False. :param request: HttpRequest :param e: Exception def process_exception(self, request, e): """ Logs exception error message and sends email to ADMINS if hostname is not testserver and DEB...
Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing purposes, and an explicit naming is always going to be a better situation. def get_first_builder_window(builder): """Get the first toplevel widget in a Gtk.Builder hierarchy. This is mostly used for guessing pu...
Add a slave delegate def add_slave(self, slave, container_name="widget"): """Add a slave delegate """ cont = getattr(self, container_name, None) if cont is None: raise AttributeError( 'Container name must be a member of the delegate') cont.add(slave.w...
Get the toplevel widget from a Gtk.Builder file. The slave view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, the first toplevel widget is discovered in the Builder file, and it's immediate child is used as the to...
Show the main widget in a window and run the gtk loop def show_and_run(self): """Show the main widget in a window and run the gtk loop""" if not self._ui_ready: self.prepare_ui() self.display_widget = Gtk.Window() self.display_widget.add(self.widget) self.display_wid...
Get the toplevel widget from a Gtk.Builder file. The main view implementation first searches for the widget named as self.toplevel_name (which defaults to "main". If this is missing, or not a Gtk.Window, the first toplevel window found in the Gtk.Builder is used. def get_builder_toplev...
Round the number to the specified number of significant figures def round_sig(x, sig): """Round the number to the specified number of significant figures""" return round(x, sig - int(floor(log10(abs(x)))) - 1)
Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's opened in binary mode. def open_file(filename, as_text=False): """Open the file gunzipping it if it ends with .gz. If as_text the file is opened in text mode, otherwise the file's opene...
Create a simple writer suitable for writing flat data e.g. as BasicObject or TSV. def create_simple_writer(outputDef, defaultOutput, outputFormat, fieldNames, compress=True, valueClassMappings=None, datasetMetaProps=None, fieldMetaProps=None): """Create a simpl...
This is a temp hack to write the minimal metadata that Squonk needs. Will needs to be replaced with something that allows something more complete to be written. :param outputBase: Base name for the file to write to :param thinOutput: Write only new data, not structures. Result type will be BasicObject ...
Write the metrics data :param baseName: The base name of the output files. e.g. extensions will be appended to this base name :param values dictionary of values to write def write_metrics(baseName, values): """Write the metrics data :param baseName: The base name of the output fi...
Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of values (properties) for the MoleculeObject def generate_molecule_o...
Returns the module name of the caller's calling module. If a.py makes a call to b() in b.py, b() can get the name of the calling module (i.e. a) by calling get_undecorated_calling_module(). The module also includes its full path. As the name suggests, this does not work for decorated functions. def g...
Queries Nexus for an artifact :param query_url: (str) Query URL :param timeout_sec: (int) query timeout :param basic_auth (HTTPBasicAuth) object or none :return: requests.Response object :raises: RuntimeError def query_nexus(query_url, timeout_sec, basic_auth=None): """Queries Nexus for an art...
Retrieves an artifact from Nexus :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_url: (str) URL of the Nexus Server :param timeout_sec: (int) Number of seconds to wait before timing out the artifact retrieval. :param overwrite: (bool) True overwrites...
Retrieves an artifact from the Nexus 3 ReST API :param suppress_status: (bool) Set to True to suppress printing download status :param nexus_base_url: (str) Base URL of the Nexus Server (domain name portion only, see sample) :param repository: (str) Repository to query (e.g. snapshots) if not provided, wil...
Handles calling this module as a script :return: None def main(): """Handles calling this module as a script :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='This Python module retrieves artifacts from Nexus.') parser.add_argume...
Return a formated string containing documentation about the audio fields. def get_doc(additional_doc=False, field_prefix='$', field_suffix=':', indent=4): """Return a formated string containing documentation about the audio fields. """ if additional_doc: ...
List images stored in the registry. Returns: list[str]: List of image names. def list_images(self): # type: () -> List[str] """ List images stored in the registry. Returns: list[str]: List of image names. """ r = self.get(self.registry_url + '/v...
List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any values. Returns: list[str]: List of tags for that image. def l...
Checks asset structure validity :param asset_dir_path: (str) path to the directory containing the asset :return: (str) Asset name :raises: Cons3rtAssetStructureError def validate_asset_structure(asset_dir_path): """Checks asset structure validity :param asset_dir_path: (str) path to the directory...
Given an asset directory path, creates an asset zip file in the provided destination directory :param asset_dir_path: (str) path to the directory containing the asset :param destination_directory: (str) path to the destination directory for the asset :return: (str) Path to the asset zip fil...
Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int) def validate(asset_dir): """Command line call to validate an asset structure :param asset_dir: (full path to the asset dir) :return: (int) """ try: asset_name = validate_...
Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param dest_dir: (full path to the destination directory) :return: (int) def create(asset_dir, dest_dir): """Command line call to create an asset zip :param asset_dir: (full path to the asset dir) :param d...
Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() call :return: Object or None def get_object_or_none(cls, **kwargs): """ Returns model instance or None if not found. :param cls: Class or queryset :param kwargs: Filters for get() cal...
Returns model field label and value. :param instance: Model instance :param field_name: Model attribute name :return: (label, value) tuple def get_model_field_label_and_value(instance, field_name) -> (str, str): """ Returns model field label and value. :param instance: Model instance :param...
Assigns model fields to new object. Ignores exclude_fields list and attributes ending with pointer suffix (default '_ptr') :param instance: Instance to copy :param cls: Class name :param commit: Save or not :param exclude_fields: List of fields to exclude :param base_class_suffix: End of name fo...
This view should return a list of all the Identities for the supplied query parameters. The query parameters should be in the form: {"address_type": "address"} e.g. {"msisdn": "+27123"} {"email": "foo@bar.com"} A special query paramater "include_inactive" can als...
This view should return a list of all the addresses the identity has for the supplied query parameters. Currently only supports address_type and default params Always excludes addresses with optedout = True def get_queryset(self): """ This view should return a list of all the ad...
Test if an internet connection is operational. Src: http://stackoverflow.com/a/20913928/2556577. :param str remote_server: remote server used to check def check_internet_connection(self, remote_server: str = "api.isogeo.com") -> bool: """Test if an internet connection is operational. S...
Check API Bearer token validity. Isogeo ID delivers authentication bearers which are valid during a certain time. So this method checks the validity of the token with a 30 mn anticipation limit, and renews it if necessary. See: http://tools.ietf.org/html/rfc6750#section-2 FI: 2...
Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check def check_api_response(self, response): """Check API response and raise exceptions if needed. :param requests.models.Response response: request response to check """ ...
Check parameters passed to avoid errors and help debug. :param dict response: search request parameters def check_request_parameters(self, parameters: dict = dict): """Check parameters passed to avoid errors and help debug. :param dict response: search request parameters """ #...
Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check def check_is_uuid(self, uuid_str: str): """Check if it's an Isogeo UUID handling specific form. :param str uuid_str: UUID string to check """ # check uuid type if not isinsta...
Check if asked tab is part of Isogeo web form and reliable with metadata type. :param str tab: tab to check. Must be one one of EDIT_TABS attribute :param str md_type: metadata type. Must be one one of FILTER_TYPES def check_edit_tab(self, tab: str, md_type: str): """Check if asked tab...
Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to check def _check_filter_specific_md(self, specific_md: list): """Check if specific_md parameter is valid. :param list specific_md: list of specific metadata UUID to check """ if...
Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check def _check_filter_specific_tag(self, specific_tag: list): """Check if specific_tag parameter is valid. :param list specific_tag: list of specific tag to check """ if isinstance(sp...
Check if specific_resources parameter is valid. :param list includes: sub resources to check :param str resource: resource type to check sub resources. Must be one of: metadata | keyword. def _check_filter_includes(self, includes: list, resource: str = "metadata"): """Check if specifi...
Check if specific_resources parameter is valid. :param str resource: subresource to check. def _check_subresource(self, subresource: str): """Check if specific_resources parameter is valid. :param str resource: subresource to check. """ warnings.warn( "subresource ...
Metadata types are not consistent in Isogeo API. A vector dataset is defined as vector-dataset in query filter but as vectorDataset in resource (metadata) details. see: https://github.com/isogeo/isogeo-api-py-minsdk/issues/29 def _convert_md_type(self, type_to_convert: str): """Metad...
Show project version. Has sub commands. For this command to work you must specify where the project version is stored. You can do that with version_file conf variable. peltak supports multiple ways to store the project version. Right now you can store it in a python file using built-in __version__ vari...
Bump current project version without committing anything. No tags are created either. Examples: \b $ peltak version bump patch # Bump patch version component $ peltak version bump minor # Bump minor version component $ peltak version bump major ...
Creates a name for a log file that is meant to be used in a call to ``logging.FileHandler``. The log file name will incldue the path to the log directory given by the `p.LOG_DIR` constant. The format of the file name is: 'log_$HOST_$TAG.txt', where $HOST is the hostname part of the URL given by...
Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.models.RecordNotFound`: A record could not be found. def _get(self, rec_id=None, upstream=None): """ Fetches a record by the record's ID or upstream_identifier. Raises: `pulsarpy.mode...
Used to replace a foreign key reference using a name with an ID. Works by searching the record in Pulsar and expects to find exactly one hit. First, will check if the foreign key reference is an integer value and if so, returns that as it is presumed to be the foreign key. Raises: `...
Checks whether the model name in question is in the payload. If not, the entire payload is set as a value of a key by the name of the model. This method is useful when some server-side Rails API calls expect the parameters to include the parameterized model name. For example, server-side endpoi...
Deletes the record. def delete(self): """Deletes the record. """ res = requests.delete(url=self.record_url, headers=HEADERS, verify=False) #self.write_response_html_to_file(res,"bob_delete.html") if res.status_code == 204: #No content. Can't render json: ...
Searches the model in question by AND joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a dict. as well. Only the first hit is returned, and there is no particular ordering specified in the server-side API m...
Searches the model in question by OR joining the query parameters. Implements a Railsy way of looking for a record using a method by the same name and passing in the query as a string (for the OR operator joining to be specified). Only the first hit is returned, and there is not particular ord...
Fetches all records. Returns: `dict`. The JSON formatted response. Raises: `requests.exceptions.HTTPError`: The status code is not ok. def index(cls): """Fetches all records. Returns: `dict`. The JSON formatted response. Raises: ...
Patches current record and udpates the current instance's 'attrs' attribute to reflect the new changes. Args: payload - hash. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `requests.e...
Looks for any keys in the payload that end with either _id or _ids, signaling a foreign key field. For each foreign key field, checks whether the value is using the name of the record or the actual primary ID of the record (which may include the model abbreviation, i.e. B-1). If the former case,...
Posts the data to the specified record. Args: payload: `dict`. This will be JSON-formatted prior to sending the request. Returns: `dict`. The JSON formatted response. Raises: `Requests.exceptions.HTTPError`: The status code is not ok. `RecordNot...
Logs the provided error message to both the error logger and the debug logger logging instances. Args: msg: `str`. The error message to log. def log_error(cls, msg): """ Logs the provided error message to both the error logger and the debug logger logging instances....
An aid in troubleshooting internal application errors, i.e. <Response [500]>, to be mainly beneficial when developing the server-side API. This method will write the response HTML for viewing the error details in the browesr. Args: response: `requests.models.Response` instance. ...
Returns an array of parent Biosample IDs. If the current Biosample has a part_of relationship, the Biosampled referenced there will be returned. Otherwise, if the current Biosample was generated from a pool of Biosamples (pooled_from_biosample_ids), then those will be returned. Otherwise, the re...
Recursively looks at the part_of parent ancestry line (ignoring pooled_from parents) and returns a parent Biosample ID if its wild_type attribute is True. Args: with_ip: `bool`. True means to restrict the search to the first parental Wild Type that also has an Immunoblot l...
Args: path: `str`. The path to the document to upload. document_type: `str`. DocumentType identified by the value of its name attribute. is_protocol: `bool`. description: `str`. def upload(cls, path, document_type, is_protocol, description=""): """ Arg...