Search is not available for this dataset
text
stringlengths
75
104k
def calculate_total_amt(self, items={}): """Returns the total amount/cost of items in the current invoice""" _items = items.items() or self.items.items() return sum(float(x[1].total_price) for x in _items)
def __encode_items(self, items): """Encodes the InvoiceItems into a JSON serializable format items = [('item_1',InvoiceItem(name='VIP Ticket', quantity=2, unit_price='3500', total_price='7000', description='VIP Tickets for party')),...] ...
def main(): """Sample usage for this python module This main method simply illustrates sample usage for this python module. :return: None """ log = logging.getLogger(mod_logger + '.main') parser = argparse.ArgumentParser(description='cons3rt deployment CLI') parser.add_argument('comman...
def set_deployment_home(self): """Sets self.deployment_home This method finds and sets deployment home, primarily based on the DEPLOYMENT_HOME environment variable. If not set, this method will attempt to determine deployment home. :return: None """ log = loggin...
def read_deployment_properties(self): """Reads the deployment properties file This method reads the deployment properties file into the "properties" dictionary object. :return: None :raises: DeploymentError """ log = logging.getLogger(self.cls_logger + '.read_de...
def get_property(self, regex): """Gets the name of a specific property This public method is passed a regular expression and returns the matching property name. If either the property is not found or if the passed string matches more than one property, this function will return ...
def get_matching_property_names(self, regex): """Returns a list of property names matching the provided regular expression :param regex: Regular expression to search on :return: (list) of property names matching the regex """ log = logging.getLogger(self.cls_logger + '.g...
def get_value(self, property_name): """Returns the value associated to the passed property This public method is passed a specific property as a string and returns the value of that property. If the property is not found, None will be returned. :param property_name (str) The na...
def set_cons3rt_role_name(self): """Set the cons3rt_role_name member for this system :return: None :raises: DeploymentError """ log = logging.getLogger(self.cls_logger + '.set_cons3rt_role_name') try: self.cons3rt_role_name = os.environ['CONS3RT_ROLE_NAME'] ...
def determine_cons3rt_role_name_linux(self): """Determines the CONS3RT_ROLE_NAME for this Linux system, and Set the cons3rt_role_name member for this system This method determines the CONS3RT_ROLE_NAME for this system in the deployment by first checking for the environment varia...
def set_asset_dir(self): """Returns the ASSET_DIR environment variable This method gets the ASSET_DIR environment variable for the current asset install. It returns either the string value if set or None if it is not set. :return: None """ log = logging.getLogge...
def set_scenario_role_names(self): """Populates the list of scenario role names in this deployment and populates the scenario_master with the master role Gets a list of deployment properties containing "isMaster" because there is exactly one per scenario host, containing the role name ...
def set_scenario_network_info(self): """Populates a list of network info for each scenario host from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_scenario_network_info') for scenario_host in self.scenario_role_names: ...
def set_deployment_name(self): """Sets the deployment name from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_name') self.deployment_name = self.get_value('cons3rt.deployment.name') log.info('Found deployment name: {n}...
def set_deployment_id(self): """Sets the deployment ID from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_id') deployment_id_val = self.get_value('cons3rt.deployment.id') if not deployment_id_val: log.debug...
def set_deployment_run_name(self): """Sets the deployment run name from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_run_name') self.deployment_run_name = self.get_value('cons3rt.deploymentRun.name') log.info('Found d...
def set_deployment_run_id(self): """Sets the deployment run ID from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_deployment_run_id') deployment_run_id_val = self.get_value('cons3rt.deploymentRun.id') if not deployment_run_id_val...
def set_virtualization_realm_type(self): """Sets the virtualization realm type from deployment properties :return: None """ log = logging.getLogger(self.cls_logger + '.set_virtualization_realm_type') self.virtualization_realm_type = self.get_value('cons3rt.deploymentRun.virtReal...
def update_hosts_file(self, ip, entry): """Updated the hosts file depending on the OS :param ip: (str) IP address to update :param entry: (str) entry to associate to the IP address :return: None """ log = logging.getLogger(self.cls_logger + '.update_hosts_file') ...
def set_scenario_hosts_file(self, network_name='user-net', domain_name=None): """Adds hosts file entries for each system in the scenario for the specified network_name provided :param network_name: (str) Name of the network to add to the hosts file :param domain_name: (str) Domain name ...
def set_hosts_file_entry_for_role(self, role_name, network_name='user-net', fqdn=None, domain_name=None): """Adds an entry to the hosts file for a scenario host given the role name and network name :param role_name: (str) role name of the host to add :param network_name: (str) Name of t...
def get_ip_on_network(self, network_name): """Given a network name, returns the IP address :param network_name: (str) Name of the network to search for :return: (str) IP address on the specified network or None """ return self.get_scenario_host_ip_on_network( scenari...
def get_scenario_host_ip_on_network(self, scenario_role_name, network_name): """Given a network name, returns the IP address :param network_name: (str) Name of the network to search for :param scenario_role_name: (str) role name to return the IP address for :return: (str) IP address on ...
def get_device_for_network_linux(self, network_name): """Given a cons3rt network name, return the network interface name on this Linux system :param network_name: (str) Name of the network to search for :return: (str) name of the network interface device or None """ log ...
def require_auth(request: Request, exceptions: bool=True) -> User: """ Returns authenticated User. :param request: HttpRequest :param exceptions: Raise (NotAuthenticated) exception. Default is True. :return: User """ if not request.user or not request.user.is_authenticated: if except...
def insertSaneDefaults(self): """ Add sane defaults rules to the raw and filter tables """ self.raw.insert(0, '-A OUTPUT -o lo -j NOTRACK') self.raw.insert(1, '-A PREROUTING -i lo -j NOTRACK') self.filters.insert(0, '-A INPUT -i lo -j ACCEPT') self.filters.insert(1, '-A OUTPUT -o lo -j ACCEPT') self.filters...
def appendDefaultDrop(self): """ Add a DROP policy at the end of the rules """ self.filters.append('-A INPUT -j DROP') self.filters.append('-A OUTPUT -j DROP') self.filters.append('-A FORWARD -j DROP') return self
def template(self): """ Create a rules file in iptables-restore format """ s = Template(self._IPTABLES_TEMPLATE) return s.substitute(filtertable='\n'.join(self.filters), rawtable='\n'.join(self.raw), mangletable='\n'.join(self.mangle), nattable='\n'.join(self.nat), date=datetime.today(...
def template(self): """ Create a rules file in ipset --restore format """ s = Template(self._IPSET_TEMPLATE) return s.substitute(sets='\n'.join(self.sets), date=datetime.today())
def query(self, base, filterstr, attrlist=None): """ wrapper to search_s """ return self.conn.search_s(base, ldap.SCOPE_SUBTREE, filterstr, attrlist)
def getUserByNumber(self, base, uidNumber): """ search for a user in LDAP and return its DN and uid """ res = self.query(base, "uidNumber="+str(uidNumber), ['uid']) if len(res) > 1: raise InputError(uidNumber, "Multiple users found. Expecting one.") return res[0][0], res[0][1]['uid'][0]
def getACLs(self, base, searchstr): """ Query LDAP to obtain the network ACLs of a given user, parse the ACLs, and return the results in a dict of the form acls[group][cidr] = description """ acls = dict() res = self.query(base, searchstr, ['cn', 'ipHostNumber']) for dn,attr in res: cn = attr['cn'...
def splitValues(textStr): """Splits a comma-separated number sequence into a list (of floats). """ vals = textStr.split(",") nums = [] for v in vals: nums.append(float(v)) return nums
def expandParameters(*args): """Expands parameters (presented as tuples of lists and symbolic names) so that each is returned in a new list where each contains the same number of values. Each `arg` is a tuple containing two items: a list of values and a symbolic name. """ count = 1 for ...
def expandValues(inputs, count, name): """Returns the input list with the length of `count`. If the list is [1] and the count is 3. [1,1,1] is returned. The list must be the count length or 1. Normally called from `expandParameters()` where `name` is the symbolic name of the input. """ if len(in...
def get_geo_ip(ip: str, exceptions: bool=False, timeout: int=10) -> dict: """ Returns geo IP info or empty dict if geoip query fails at http://ipstack.com. requires settings.IPSTACK_TOKEN set as valid access token to the API. Example replies: {'country_name': 'United States', 'country_code': 'US', ...
def get_ip_info(ip: str, exceptions: bool=False, timeout: int=10) -> tuple: """ Returns (ip, country_code, host) tuple of the IP address. :param ip: IP address :param exceptions: Raise Exception or not :param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host n...
def is_aws(): """Determines if this system is on AWS :return: bool True if this system is running on AWS """ log = logging.getLogger(mod_logger + '.is_aws') log.info('Querying AWS meta data URL: {u}'.format(u=metadata_url)) # Re-try logic for checking the AWS meta data URL retry_time_sec =...
def get_instance_id(): """Gets the instance ID of this EC2 instance :return: String instance ID or None """ log = logging.getLogger(mod_logger + '.get_instance_id') # Exit if not running on AWS if not is_aws(): log.info('This machine is not running in AWS, exiting...') return ...
def get_vpc_id_from_mac_address(): """Gets the VPC ID for this EC2 instance :return: String instance ID or None """ log = logging.getLogger(mod_logger + '.get_vpc_id') # Exit if not running on AWS if not is_aws(): log.info('This machine is not running in AWS, exiting...') retur...
def get_availability_zone(): """Gets the AWS Availability Zone ID for this system :return: (str) Availability Zone ID where this system lives """ log = logging.getLogger(mod_logger + '.get_availability_zone') # Exit if not running on AWS if not is_aws(): log.info('This machine is not r...
def get_region(): """Gets the AWS Region ID for this system :return: (str) AWS Region ID where this system lives """ log = logging.getLogger(mod_logger + '.get_region') # First get the availability zone availability_zone = get_availability_zone() if availability_zone is None: msg ...
def get_primary_mac_address(): """Determines the MAC address to use for querying the AWS meta data service for network related queries :return: (str) MAC address for the eth0 interface :raises: AWSMetaDataError """ log = logging.getLogger(mod_logger + '.get_primary_mac_address') log.debug('...
def attr_sep(self, new_sep: str) -> None: """Set the new value for the attribute separator. When the new value is assigned a new tree is generated. """ self._attr_sep = new_sep self._filters_tree = self._generate_filters_tree()
def url_equals(a: str, b: str) -> bool: """ Compares two URLs/paths and returns True if they point to same URI. For example, querystring parameters can be different order but URLs are still equal. :param a: URL/path :param b: URL/path :return: True if URLs/paths are equal """ from urllib...
def url_mod(url: str, new_params: dict) -> str: """ Modifies existing URL by setting/overriding specified query string parameters. Note: Does not support multiple querystring parameters with identical name. :param url: Base URL/path to modify :param new_params: Querystring parameters to set/override...
def url_host(url: str) -> str: """ Parses hostname from URL. :param url: URL :return: hostname """ from urllib.parse import urlparse res = urlparse(url) return res.netloc.split(':')[0] if res.netloc else ''
def ufloatDict_nominal(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.nominal_value, ufloat_dict.values())))
def ufloatDict_stdev(self, ufloat_dict): 'This gives us a dictionary of nominal values from a dictionary of uncertainties' return OrderedDict(izip(ufloat_dict.keys(), map(lambda x: x.std_dev, ufloat_dict.values())))
def docs(recreate, gen_index, run_doctests): # type: (bool, bool, bool) -> None """ Build the documentation for the project. Args: recreate (bool): If set to **True**, the build and output directories will be cleared prior to generating the docs. gen_index (bool): ...
def gen_ref_docs(gen_index=False): # type: (int, bool) -> None """ Generate reference documentation for the project. This will use **sphinx-refdoc** to generate the source .rst files for the reference documentation. Args: gen_index (bool): Set it to **True** if you want to gene...
def generate_id_name_map(sdk, reverse=False): """ Generate the ID-NAME map dict :param sdk: CloudGenix API constructor :param reverse: Generate reverse name-> ID map as well, return tuple with both. :return: ID Name dictionary """ global_id_name_dict = {} global_name_id_dict = {} #...
def revrank_dict(dict, key=lambda t: t[1], as_tuple=False): """ Reverse sorts a #dict by a given key, optionally returning it as a #tuple. By default, the @dict is sorted by it's value. @dict: the #dict you wish to sorts @key: the #sorted key to use @as_tuple: returns result as a #t...
def rank_dict(dict, key=lambda t: t[1], as_tuple=False): """ Sorts a #dict by a given key, optionally returning it as a #tuple. By default, the @dict is sorted by it's value. @dict: the #dict you wish to sorts @key: the #sorted key to use @as_tuple: returns result as a #tuple ((k, v...
def getitem_in(obj, name): """ Finds a key in @obj via a period-delimited string @name. @obj: (#dict) @name: (#str) |.|-separated keys to search @obj in .. obj = {'foo': {'bar': {'baz': True}}} getitem_in(obj, 'foo.bar.baz') .. |True| """ for p...
def start(component, exact): # type: (str) -> None """ Create a new release. It will bump the current version number and create a release branch called `release/<version>` with one new commit (the version bump). **Example Config**:: \b version_file: 'src/mypkg/__init__.py' **...
def tag_release(message): # type: (str, bool) -> None """ Tag the current commit with as the current version release. This should be the same commit as the one that's uploaded as the release (to pypi for example). **Example Config**:: \b version_file: 'src/mypkg/__init__.py' ...
def query_file_location(question, default_address): """ This function asks for a location file address from the command terminal it checks if the file exists before proceeding with the code "question" is a string that is presented to the user. "default_address" is the presumed file location. ""...
def declare_output_files(): """ This method establishes the output files from pycloudy grids For these simulations in which we are only want to calculate the emissivities from the hydrogen and helium lines most of the default files from pycloudy outputs are not required :return: """ #Exclu...
def format_full_name(first_name: str, last_name: str, max_length: int = 20): """ Limits name length to specified length. Tries to keep name as human-readable an natural as possible. :param first_name: First name :param last_name: Last name :param max_length: Maximum length :return: Full name of ...
def format_timedelta(dt: timedelta) -> str: """ Formats timedelta to readable format, e.g. 1h30min. :param dt: timedelta :return: str """ seconds = int(dt.total_seconds()) days, remainder = divmod(seconds, 86400) hours, remainder = divmod(remainder, 3600) minutes, seconds = divmod(re...
def format_xml(xml_str: str, exceptions: bool=False): """ Formats XML document as human-readable plain text. :param xml_str: str (Input XML str) :param exceptions: Raise exceptions on error :return: str (Formatted XML str) """ try: import xml.dom.minidom return xml.dom.minido...
def worker_allocator(self, async_loop, to_do, **kwargs): """ Handler starting the asyncio part. """ d = kwargs threading.Thread( target=self._asyncio_thread, args=(async_loop, to_do, d) ).start()
def send_mail(form, from_name): """ Sends a mail using the configured mail server for Pulsar. See mailgun documentation at https://documentation.mailgun.com/en/latest/user_manual.html#sending-via-api for specifics. Args: form: `dict`. The mail form fields, i.e. 'to', 'from', ... Returns:...
def get_exp_of_biosample(biosample_rec): """ Determines whether the biosample is part of a ChipseqExperiment or SingleCellSorting Experiment, and if so, returns the associated experiment as a models.Model instance that is one of those two classes. The biosample is determined to be part of a ChipseqExper...
def _clean_text(text): """ Clean up a multiple-line, potentially multiple-paragraph text string. This is used to extract the first paragraph of a string and eliminate line breaks and indentation. Lines will be joined together by a single space. :param text: The text string to clean up. It is...
def prog(text): """ Decorator used to specify the program name for the console script help message. :param text: The text to use for the program name. """ def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) adaptor.prog = text return func return decorato...
def usage(text): """ Decorator used to specify a usage string for the console script help message. :param text: The text to use for the usage. """ def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) adaptor.usage = text return func return decorator
def description(text): """ Decorator used to specify a short description of the console script. This can be used to override the default, which is derived from the docstring of the function. :param text: The text to use for the description. """ def decorator(func): adaptor = Scrip...
def epilog(text): """ Decorator used to specify an epilog for the console script help message. :param text: The text to use for the epilog. """ def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) adaptor.epilog = text return func return decorator
def formatter_class(klass): """ Decorator used to specify the formatter class for the console script. :param klass: The formatter class to use. """ def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) adaptor.formatter_class = klass return func return dec...
def argument(*args, **kwargs): """ Decorator used to specify an argument taken by the console script. Positional and keyword arguments have the same meaning as those given to ``argparse.ArgumentParser.add_argument()``. """ def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) ...
def argument_group(group, **kwargs): """ Decorator used to specify an argument group. Keyword arguments have the same meaning as those given to ``argparse.ArgumentParser.add_argument_group()``. Arguments may be placed in a given argument group by passing the ``group`` keyword argument to @argu...
def subparsers(**kwargs): """ Decorator used to specify alternate keyword arguments to pass to the ``argparse.ArgumentParser.add_subparsers()`` call. """ def decorator(func): adaptor = ScriptAdaptor._get_adaptor(func) adaptor.subkwargs = kwargs adaptor.do_subs = True ...
def load_subcommands(group): """ Decorator used to load subcommands from a given ``pkg_resources`` entrypoint group. Each function must be appropriately decorated with the ``cli_tools`` decorators to be considered an extension. :param group: The name of the ``pkg_resources`` entrypoint group. ...
def _collapse_subtree(self, name, recursive=True): """Collapse a sub-tree.""" oname = name children = self._db[name]["children"] data = self._db[name]["data"] del_list = [] while (len(children) == 1) and (not data): del_list.append(name) name = chi...
def _create_intermediate_nodes(self, name): """Create intermediate nodes if hierarchy does not exist.""" hierarchy = self._split_node_name(name, self.root_name) node_tree = [ self.root_name + self._node_separator + self._node_separator.join(hierarchy[: num + 1...
def _create_node(self, name, parent, children, data): """Create new tree node.""" self._db[name] = {"parent": parent, "children": children, "data": data}
def _delete_subtree(self, nodes): """ Delete subtree private method. No argument validation and usage of getter/setter private methods is used for speed """ nodes = nodes if isinstance(nodes, list) else [nodes] iobj = [ (self._db[node]["parent"], node...
def _find_common_prefix(self, node1, node2): """Find common prefix between two nodes.""" tokens1 = [item.strip() for item in node1.split(self.node_separator)] tokens2 = [item.strip() for item in node2.split(self.node_separator)] ret = [] for token1, token2 in zip(tokens1, tokens2...
def _prt(self, name, lparent, sep, pre1, pre2): """ Print a row (leaf) of tree. :param name: Full node name :type name: string :param lparent: Position in full node name of last separator before node to be printed :type lparent: integer ...
def _rename_node(self, name, new_name): """ Rename node private method. No argument validation and usage of getter/setter private methods is used for speed """ # Update parent if not self.is_root(name): parent = self._db[name]["parent"] se...
def _search_tree(self, name): """Search_tree for nodes that contain a specific hierarchy name.""" tpl1 = "{sep}{name}{sep}".format(sep=self._node_separator, name=name) tpl2 = "{sep}{name}".format(sep=self._node_separator, name=name) tpl3 = "{name}{sep}".format(sep=self._node_separator, n...
def _validate_node_name(self, var_value): """Validate NodeName pseudo-type.""" # pylint: disable=R0201 var_values = var_value if isinstance(var_value, list) else [var_value] for item in var_values: if (not isinstance(item, str)) or ( isinstance(item, str) ...
def _validate_nodes_with_data(self, names): """Validate NodeWithData pseudo-type.""" names = names if isinstance(names, list) else [names] if not names: raise RuntimeError("Argument `nodes` is not valid") for ndict in names: if (not isinstance(ndict, dict)) or ( ...
def add_nodes(self, nodes): # noqa: D302 r""" Add nodes to tree. :param nodes: Node(s) to add with associated data. If there are several list items in the argument with the same node name the resulting node data is a list with items ...
def collapse_subtree(self, name, recursive=True): # noqa: D302 r""" Collapse a sub-tree. Nodes that have a single child and no data are combined with their child as a single tree node :param name: Root of the sub-tree to collapse :type name: :ref:`NodeName` :...
def copy_subtree(self, source_node, dest_node): # noqa: D302 r""" Copy a sub-tree from one sub-node to another. Data is added if some nodes of the source sub-tree exist in the destination sub-tree :param source_name: Root node of the sub-tree to copy from :type source...
def delete_prefix(self, name): # noqa: D302 r""" Delete hierarchy levels from all nodes in the tree. :param nodes: Prefix to delete :type nodes: :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not a valid prefix) * RuntimeError (Argument \`nam...
def delete_subtree(self, nodes): # noqa: D302 r""" Delete nodes (and their sub-trees) from the tree. :param nodes: Node(s) to delete :type nodes: :ref:`NodeName` or list of :ref:`NodeName` :raises: * RuntimeError (Argument \`nodes\` is not valid) * RuntimeE...
def flatten_subtree(self, name): # noqa: D302 r""" Flatten sub-tree. Nodes that have children and no data are merged with each child :param name: Ending hierarchy node whose sub-trees are to be flattened :type name: :ref:`NodeName` :raises: ...
def get_children(self, name): r""" Get the children node names of a node. :param name: Parent node name :type name: :ref:`NodeName` :rtype: list of :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]...
def get_data(self, name): r""" Get the data associated with a node. :param name: Node name :type name: :ref:`NodeName` :rtype: any type or list of objects of any type :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[na...
def get_leafs(self, name): r""" Get the sub-tree leaf node(s). :param name: Sub-tree root node name :type name: :ref:`NodeName` :rtype: list of :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* no...
def get_node(self, name): r""" Get a tree node structure. The structure is a dictionary with the following keys: * **parent** (*NodeName*) Parent node name, :code:`''` if the node is the root node * **children** (*list of NodeName*) Children node names, an ...
def get_node_children(self, name): r""" Get the list of children structures of a node. See :py:meth:`ptrie.Trie.get_node` for details about the structure :param name: Parent node name :type name: :ref:`NodeName` :rtype: list :raises: * RuntimeError (...
def get_node_parent(self, name): r""" Get the parent structure of a node. See :py:meth:`ptrie.Trie.get_node` for details about the structure :param name: Child node name :type name: :ref:`NodeName` :rtype: dictionary :raises: * RuntimeError (Argument...
def get_subtree(self, name): # noqa: D302 r""" Get all node names in a sub-tree. :param name: Sub-tree root node name :type name: :ref:`NodeName` :rtype: list of :ref:`NodeName` :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeErro...
def in_tree(self, name): r""" Test if a node is in the tree. :param name: Node name to search for :type name: :ref:`NodeName` :rtype: boolean :raises: RuntimeError (Argument \`name\` is not valid) """ if self._validate_node_name(name): rais...
def is_leaf(self, name): r""" Test if a node is a leaf node (node with no children). :param name: Node name :type name: :ref:`NodeName` :rtype: boolean :raises: * RuntimeError (Argument \`name\` is not valid) * RuntimeError (Node *[name]* not in tre...