INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
make all pairwise genome comparisons to get rbhs rbh = {genome: {other_genome: {rbh_id: [rbh_match, pident, e, bit, norm_bit]]}}
def compare_genomes(fastas, id2desc, algorithm): """ make all pairwise genome comparisons to get rbhs rbh = {genome: {other_genome: {rbh_id: [rbh_match, pident, e, bit, norm_bit]]}} """ hits = {} for pair in itertools.permutations(fastas, 2): if pair[0] not in hits: hits[pair...
if thresholds are not specififed, calculate based on the distribution of normalized bit scores
def calc_thresholds(rbh, file_name, thresholds = [False, False, False, False], stdevs = 2): """ if thresholds are not specififed, calculate based on the distribution of normalized bit scores """ calc_threshold = thresholds[-1] norm_threshold = {} for pair in itertools.permutations([i for i in rb...
make the network based on rbhs and score thresholds
def rbh_network(id2desc, rbh, file_name, thresholds = [False, False, False, False]): """ make the network based on rbhs and score thresholds """ g = nx.Graph() # network graph for storing rbhs filtered = {} e_thresh, bit_thresh, length_thresh, norm_thresh = thresholds for genome in rbh: ...
make and split a rbh network
def neto(fastas, algorithm = 'usearch', e = 0.01, bit = 40, length = .65, norm_bit = False): """ make and split a rbh network """ thresholds = [e, bit, length, norm_bit] id2desc = get_descriptions(fastas) # get [fasta, description, length] for ORF id id2desc = self_compare(fastas, id...
make a rbh network for all pair-wise genome comparisons - filter network based on normalized bit score (default, automatic) or specified e-value / bit score - evaluate the scores for each genome pair compared - build second network that is filtered so that clusters have only one ORF per genome - evaluat...
def network(thresholds, fastas, algorithm = 'usearch'): """ make a rbh network for all pair-wise genome comparisons - filter network based on normalized bit score (default, automatic) or specified e-value / bit score - evaluate the scores for each genome pair compared - build second network that is ...
Returns the subdirectory in `userdata` which acts as the root of the user-specific filesystem in Steam (aka all user-specific files are stored under this directory)
def user_specific_data_directory(user_context): """Returns the subdirectory in `userdata` which acts as the root of the user-specific filesystem in Steam (aka all user-specific files are stored under this directory)""" return os.path.join( user_context.steam.userdata_directory, user_context.user_id )
OVERRIDDEN: Initialize required ISO-19115 data map with XPATHS and specialized functions
def _init_data_map(self): """ OVERRIDDEN: Initialize required ISO-19115 data map with XPATHS and specialized functions """ if self._data_map is not None: return # Initiation happens once # Parse and validate the ISO metadata root if self._xml_tree is None: iso...
Concatenates a list of Attribute Details data structures parsed from a remote file
def _parse_attribute_details(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ parsed_attributes = self._parse_attribute_details_file(prop) if parsed_attributes is None: # If not in the (official) remote location, try ...
Concatenates a list of Attribute Details data structures parsed from a remote file
def _parse_attribute_details_file(self, prop=ATTRIBUTES): """ Concatenates a list of Attribute Details data structures parsed from a remote file """ # Parse content from remote file URL, which may be stored in one of two places: # Starting at: contentInfo/MD_FeatureCatalogueDescription/featu...
Concatenates a list of Digital Form data structures parsed from the metadata
def _parse_digital_forms(self, prop=DIGITAL_FORMS): """ Concatenates a list of Digital Form data structures parsed from the metadata """ xpath_map = self._data_structures[prop] # Parse base digital form fields: 'name', 'content', 'decompression', 'version', 'specification' xpath_root =...
Parse type-specific keywords from the metadata: Theme or Place
def _parse_keywords(self, prop): """ Parse type-specific keywords from the metadata: Theme or Place """ keywords = [] if prop in KEYWORD_PROPS: xpath_root = self._data_map['_keywords_root'] xpath_map = self._data_structures[prop] xtype = xpath_map['keyword_...
Collapses multiple dimensions into a single raster_info complex struct
def _parse_raster_info(self, prop=RASTER_INFO): """ Collapses multiple dimensions into a single raster_info complex struct """ raster_info = {}.fromkeys(_iso_definitions[prop], u'') # Ensure conversion of lists to newlines is in place raster_info['dimensions'] = get_default_for_complex...
Update operation for ISO Attribute Details metadata: write to "MD_Metadata/featureType"
def _update_attribute_details(self, **update_props): """ Update operation for ISO Attribute Details metadata: write to "MD_Metadata/featureType" """ tree_to_update = update_props['tree_to_update'] xpath = self._data_map['_attr_citation'] # Cannot write to remote file: remove the featur...
Update operation for ISO Digital Forms metadata :see: gis_metadata.utils._complex_definitions[DIGITAL_FORMS]
def _update_digital_forms(self, **update_props): """ Update operation for ISO Digital Forms metadata :see: gis_metadata.utils._complex_definitions[DIGITAL_FORMS] """ digital_forms = wrap_value(update_props['values']) # Update all Digital Form properties: distributionFor...
Update operation for ISO type-specific Keywords metadata: Theme or Place
def _update_keywords(self, **update_props): """ Update operation for ISO type-specific Keywords metadata: Theme or Place """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = update_props['values'] keywords = [] if prop in KEYWORD_PRO...
Derives multiple dimensions from a single raster_info complex struct
def _update_raster_info(self, **update_props): """ Derives multiple dimensions from a single raster_info complex struct """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = update_props.pop('values') # Update number of dimensions at raster_in...
OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property
def update(self, use_template=False, **metadata_defaults): """ OVERRIDDEN: Prevents writing multiple CharacterStrings per XPATH property """ self.validate() tree_to_update = self._xml_tree if not use_template else self._get_template(**metadata_defaults) supported_props = self._metadata...
Removes primitive type tags from an XPATH
def _trim_xpath(self, xpath, prop): """ Removes primitive type tags from an XPATH """ xroot = self._get_xroot_for(prop) if xroot is None and isinstance(xpath, string_types): xtags = xpath.split(XPATH_DELIM) if xtags[-1] in _iso_tag_primitives: xroot = X...
Generates the app id for a given shortcut. Steam uses app ids as a unique identifier for games, but since shortcuts dont have a canonical serverside representation they need to be generated on the fly. The important part about this function is that it will generate the same app id as Steam does for a given shor...
def shortcut_app_id(shortcut): """ Generates the app id for a given shortcut. Steam uses app ids as a unique identifier for games, but since shortcuts dont have a canonical serverside representation they need to be generated on the fly. The important part about this function is that it will generate the same ...
Execute git config.
def _config(self): """Execute git config.""" cfg_wr = self.repo.config_writer() cfg_wr.add_section('user') cfg_wr.set_value('user', 'name', self.metadata.author) cfg_wr.set_value('user', 'email', self.metadata.email) cfg_wr.release()
Execute git remote add.
def _remote_add(self): """Execute git remote add.""" self.repo.create_remote( 'origin', 'git@github.com:{username}/{repo}.git'.format( username=self.metadata.username, repo=self.metadata.name))
Starts execution of the script
def start(self): ''' Starts execution of the script ''' # invoke the appropriate sub-command as requested from command-line try: self.args.func() except SystemExit as e: if e.code != 0: raise except KeyboardInterrupt: ...
Define basic command-line arguments required by the script. @parser is a parser object created using the `argparse` module. returns: None
def define_baseargs(self, parser): ''' Define basic command-line arguments required by the script. @parser is a parser object created using the `argparse` module. returns: None ''' parser.add_argument('--name', default=sys.argv[0], help='Name to identify this ...
Basically, turns payload that looks like ' \\n ' to ''. In the calling function, if this function returns '' no object is added for that payload.
def cleanup_payload(self, payload): """ Basically, turns payload that looks like ' \\n ' to ''. In the calling function, if this function returns '' no object is added for that payload. """ p = payload.replace('\n', '') p = p.rstrip() p = p.lstrip() ...
:return: a copy of xpath_map, but with XPATHs formatted with ordered or keyword values
def format_xpaths(xpath_map, *args, **kwargs): """ :return: a copy of xpath_map, but with XPATHs formatted with ordered or keyword values """ formatted = {}.fromkeys(xpath_map) for key, xpath in iteritems(xpath_map): formatted[key] = xpath.format(*args, **kwargs) return formatted
:return: the base of an XPATH: the part preceding any format keys or attribute references
def get_xpath_root(xpath): """ :return: the base of an XPATH: the part preceding any format keys or attribute references """ if xpath: if xpath.startswith('@'): xpath = '' else: index = xpath.find('/@' if '@' in xpath else '/{') xpath = xpath[:index] if index...
:return: the relative part of an XPATH: that which extends past the root provided
def get_xpath_branch(xroot, xpath): """ :return: the relative part of an XPATH: that which extends past the root provided """ if xroot and xpath and xpath.startswith(xroot): xpath = xpath[len(xroot):] xpath = xpath.lstrip(XPATH_DELIM) return xpath
:return: a tuple with the base of an XPATH followed by any format key or attribute reference
def get_xpath_tuple(xpath): """ :return: a tuple with the base of an XPATH followed by any format key or attribute reference """ xroot = get_xpath_root(xpath) xattr = None if xroot != xpath: xattr = get_xpath_branch(xroot, xpath).strip('@') return (xroot, xattr)
Ensures complex property types have the correct default values
def get_default_for(prop, value): """ Ensures complex property types have the correct default values """ prop = prop.strip('_') # Handle alternate props (leading underscores) val = reduce_value(value) # Filtering of value happens here if prop in _COMPLEX_LISTS: return wrap_value(val) ...
Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute. :return: True if xpath is present in the element along with any attribute referenced, otherwise False
def has_property(elem_to_parse, xpath): """ Parse xpath for any attribute reference "path/@attr" and check for root and presence of attribute. :return: True if xpath is present in the element along with any attribute referenced, otherwise False """ xroot, attr = get_xpath_tuple(xpath) if not x...
Creates and returns a Dictionary data structure parsed from the metadata. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: the XPATH location of the structure inside the parent element :param xpath_map: a dict of XPATHs corresponding to a complex definition ...
def parse_complex(tree_to_parse, xpath_root, xpath_map, complex_key): """ Creates and returns a Dictionary data structure parsed from the metadata. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: the XPATH location of the structure inside the parent eleme...
Creates and returns a list of Dictionary data structures parsed from the metadata. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: the XPATH location of each structure inside the parent element :param xpath_map: a dict of XPATHs corresponding to a complex def...
def parse_complex_list(tree_to_parse, xpath_root, xpath_map, complex_key): """ Creates and returns a list of Dictionary data structures parsed from the metadata. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: the XPATH location of each structure inside t...
Creates and returns a Dates Dictionary data structure given the parameters provided :param tree_to_parse: the XML tree from which to construct the Dates data structure :param xpath_map: a map containing the following type-specific XPATHs: multiple, range, range_begin, range_end, and single
def parse_dates(tree_to_parse, xpath_map): """ Creates and returns a Dates Dictionary data structure given the parameters provided :param tree_to_parse: the XML tree from which to construct the Dates data structure :param xpath_map: a map containing the following type-specific XPATHs: multiple, ...
Defines the default parsing behavior for metadata values. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: used to determine the relative XPATH location within the parent element :param xpath_map: a dict of XPATHs that may contain alternate locations for a pro...
def parse_property(tree_to_parse, xpath_root, xpath_map, prop): """ Defines the default parsing behavior for metadata values. :param tree_to_parse: the XML tree compatible with element_utils to be parsed :param xpath_root: used to determine the relative XPATH location within the parent element :para...
Either update the tree the default way, or call the custom updater Default Way: Existing values in the tree are overwritten. If xpaths contains a single path, then each value is written to the tree at that path. If xpaths contains a list of xpaths, then the values corresponding to each xpath index are writ...
def update_property(tree_to_update, xpath_root, xpaths, prop, values, supported=None): """ Either update the tree the default way, or call the custom updater Default Way: Existing values in the tree are overwritten. If xpaths contains a single path, then each value is written to the tree at that path. ...
Default update operation for a single parser property. If xpaths contains one xpath, then one element per value will be inserted at that location in the tree_to_update; otherwise, the number of values must match the number of xpaths.
def _update_property(tree_to_update, xpath_root, xpaths, values): """ Default update operation for a single parser property. If xpaths contains one xpath, then one element per value will be inserted at that location in the tree_to_update; otherwise, the number of values must match the number of xpaths. ...
Updates and returns the updated complex Element parsed from tree_to_update. :param tree_to_update: the XML tree compatible with element_utils to be updated :param xpath_root: the XPATH location of the root of the complex Element :param xpath_map: a Dictionary of XPATHs corresponding to the complex structure...
def update_complex(tree_to_update, xpath_root, xpath_map, prop, values): """ Updates and returns the updated complex Element parsed from tree_to_update. :param tree_to_update: the XML tree compatible with element_utils to be updated :param xpath_root: the XPATH location of the root of the complex Elemen...
Validates any metadata property, complex or simple (string or array)
def validate_any(prop, value, xpath_map=None): """ Validates any metadata property, complex or simple (string or array) """ if value is not None: if prop in (ATTRIBUTES, CONTACTS, DIGITAL_FORMS): validate_complex_list(prop, value, xpath_map) elif prop in (BOUNDING_BOX, LARGER_WORKS...
Updates and returns the list of updated complex Elements parsed from tree_to_update. :param tree_to_update: the XML tree compatible with element_utils to be updated :param xpath_root: the XPATH location of each complex Element :param xpath_map: a Dictionary of XPATHs corresponding to the complex structure d...
def update_complex_list(tree_to_update, xpath_root, xpath_map, prop, values): """ Updates and returns the list of updated complex Elements parsed from tree_to_update. :param tree_to_update: the XML tree compatible with element_utils to be updated :param xpath_root: the XPATH location of each complex Ele...
Default validation for single complex data structure
def validate_complex(prop, value, xpath_map=None): """ Default validation for single complex data structure """ if value is not None: validate_type(prop, value, dict) if prop in _complex_definitions: complex_keys = _complex_definitions[prop] else: complex_keys =...
Default validation for Attribute Details data structure
def validate_complex_list(prop, value, xpath_map=None): """ Default validation for Attribute Details data structure """ if value is not None: validate_type(prop, value, (dict, list)) if prop in _complex_definitions: complex_keys = _complex_definitions[prop] else: ...
Default validation for Date Types data structure
def validate_dates(prop, value, xpath_map=None): """ Default validation for Date Types data structure """ if value is not None: validate_type(prop, value, dict) date_keys = set(value) if date_keys: if DATE_TYPE not in date_keys or DATE_VALUES not in date_keys: ...
Default validation for Process Steps data structure
def validate_process_steps(prop, value): """ Default validation for Process Steps data structure """ if value is not None: validate_type(prop, value, (dict, list)) procstep_keys = set(_complex_definitions[prop]) for idx, procstep in enumerate(wrap_value(value)): ps_idx = p...
Ensures the key set contains the base supported properties for a Parser :param props: a set of property names to validate against those supported
def validate_properties(props, required): """ Ensures the key set contains the base supported properties for a Parser :param props: a set of property names to validate against those supported """ props = set(props) required = set(required or _supported_props) if len(required.intersection(p...
Default validation for all types
def validate_type(prop, value, expected): """ Default validation for all types """ # Validate on expected type(s), but ignore None: defaults handled elsewhere if value is not None and not isinstance(value, expected): _validation_error(prop, type(value).__name__, None, expected)
Default validation for updated properties
def _validation_error(prop, prop_type, prop_value, expected): """ Default validation for updated properties """ if prop_type is None: attrib = 'value' assigned = prop_value else: attrib = 'type' assigned = prop_type raise ValidationError( 'Invalid property {attr...
Calls the getter with no arguments and returns its value
def get_prop(self, prop): """ Calls the getter with no arguments and returns its value """ if self._parser is None: raise ConfigurationError('Cannot call ParserProperty."get_prop" with no parser configured') return self._parser(prop) if prop else self._parser()
Calls the setter with the specified keyword arguments for flexibility. :param setter_args: must contain tree_to_update, prop, values :return: None, or the value updated for complex values
def set_prop(self, **setter_args): """ Calls the setter with the specified keyword arguments for flexibility. :param setter_args: must contain tree_to_update, prop, values :return: None, or the value updated for complex values """ if self.xpath: setter_args['...
Given a list of commands (which are assumed groupable), return a new command which is a batch (multi) command. For ``set`` commands the outcome will be:: set_multi({key: value}, **kwargs) For ``get`` and ``delete`` commands, the outcome will be:: get_multi(list_of_keys, **kwargs) (O...
def grouped_command(commands): """ Given a list of commands (which are assumed groupable), return a new command which is a batch (multi) command. For ``set`` commands the outcome will be:: set_multi({key: value}, **kwargs) For ``get`` and ``delete`` commands, the outcome will be:: ...
Returns a boolean representing whether these commands can be grouped together or not. A few things are taken into account for this decision: For ``set`` commands: - Are all arguments other than the key/value the same? For ``delete`` and ``get`` commands: - Are all arguments other than the k...
def can_group_commands(command, next_command): """ Returns a boolean representing whether these commands can be grouped together or not. A few things are taken into account for this decision: For ``set`` commands: - Are all arguments other than the key/value the same? For ``delete`` and ...
Returns a list of tuples: [(command_to_run, [list, of, commands])] If the list of commands has a single item, the command was not grouped.
def regroup_commands(commands): """ Returns a list of tuples: [(command_to_run, [list, of, commands])] If the list of commands has a single item, the command was not grouped. """ grouped = [] pending = [] def group_pending(): if not pending: return new...
Usage: sugartex [OPTIONS] [TO] Reads from stdin and writes to stdout. Can have single argument/option only. When no args or the arg is not from options then run Pandoc SugarTeX filter that iterates over math blocks. Options: --kiwi Same as above but with kiwi flavor, --help Show ...
def cli(): """ Usage: sugartex [OPTIONS] [TO] Reads from stdin and writes to stdout. Can have single argument/option only. When no args or the arg is not from options then run Pandoc SugarTeX filter that iterates over math blocks. Options: --kiwi Same as above but with kiwi flavo...
define ribosomal proteins and location of curated databases
def find_databases(databases): """ define ribosomal proteins and location of curated databases """ # 16 ribosomal proteins in their expected order proteins = ['L15', 'L18', 'L6', 'S8', 'L5', 'L24', 'L14', 'S17', 'L16', 'S3', 'L22', 'S19', 'L2', 'L4', 'L3', 'S10'] # curated databases ...
get hits from each search against each RP scaffolds[scaffold] = # ORfs s2rp[scaffold] = {rp:[hits]}
def scaffold_hits(searches, fasta, max_hits): """ get hits from each search against each RP scaffolds[scaffold] = # ORfs s2rp[scaffold] = {rp:[hits]} """ # initialize ## scaffolds[scaffold] = # ORFs scaffolds = {} for seq in parse_fasta(fasta): scaffold = seq[0].split()[0].sp...
which protein has the best hit, the one to the 'right' or to the 'left?'
def find_next(start, stop, i2hits): """ which protein has the best hit, the one to the 'right' or to the 'left?' """ if start not in i2hits and stop in i2hits: index = stop elif stop not in i2hits and start in i2hits: index = start elif start not in i2hits and stop not in i2hits:...
determine which hits represent real ribosomal proteins, identify each in syntenic block max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold
def find_ribosomal(rps, scaffolds, s2rp, min_hits, max_hits_rp, max_errors): """ determine which hits represent real ribosomal proteins, identify each in syntenic block max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold """ for scaffold, proteins in list(s2rp.items()...
find ribosomal proteins max_hits = maximum number of blast hits to consider for an orf if 1, only consider best blast hit for each ORF max_hits_rp = maximum number of hits to consider per ribosomal protein per scaffold if 1, only consider best RP match to contig max_er...
def ribosomal(scaffolds, DBdir, min_hits, evalue_thresh, bit_thresh, \ method = 'usearch', threads = 6, \ max_hits = 1, max_hits_rp = 1, max_errors = 35): """ find ribosomal proteins max_hits = maximum number of blast hits to consider for an orf if 1, only c...
Parse the rep set file and remove all sequences not associated with unique OTUs. :@type inF: file :@param inF: The representative sequence set :@rtype: list :@return: The set of sequences associated with unique OTUs
def filter_rep_set(inF, otuSet): """ Parse the rep set file and remove all sequences not associated with unique OTUs. :@type inF: file :@param inF: The representative sequence set :@rtype: list :@return: The set of sequences associated with unique OTUs """ seqs = [] for record ...
OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions
def _init_data_map(self): """ OVERRIDDEN: Initialize required FGDC data map with XPATHS and specialized functions """ if self._data_map is not None: return # Initiation happens once # Parse and validate the ArcGIS metadata root if self._xml_tree is None: agis_...
Concatenates a list of Digital Form data structures parsed from the metadata
def _parse_digital_forms(self, prop=DIGITAL_FORMS): """ Concatenates a list of Digital Form data structures parsed from the metadata """ xpath_map = self._data_structures[prop] # Parse base digital form fields: 'name', 'content', 'decompression', 'version', 'specification' xpath_root =...
:return: the text for each element at the configured path if type attribute matches
def _parse_report_item(self, prop): """ :return: the text for each element at the configured path if type attribute matches""" item_type = None if prop == 'attribute_accuracy': item_type = 'DQQuanAttAcc' elif prop == 'dataset_completeness': item_type = 'DQCompOm...
Update operation for ArcGIS Dates metadata :see: gis_metadata.utils._complex_definitions[DATES]
def _update_dates(self, **update_props): """ Update operation for ArcGIS Dates metadata :see: gis_metadata.utils._complex_definitions[DATES] """ tree_to_update = update_props['tree_to_update'] xpath_root = self._data_map['_dates_root'] if self.dates: ...
Update the text for each element at the configured path if attribute matches
def _update_report_item(self, **update_props): """ Update the text for each element at the configured path if attribute matches """ tree_to_update = update_props['tree_to_update'] prop = update_props['prop'] values = wrap_value(update_props['values']) xroot = self._get_xroot_for...
Wait for a response to be ready (the provided ready bits are set). If the specified timeout (in seconds) is exceeded and error will be thrown.
def _wait_response(self, ready, timeout_sec): """Wait for a response to be ready (the provided ready bits are set). If the specified timeout (in seconds) is exceeded and error will be thrown. """ # Wait for the measurement to be ready (or a timeout elapses). start = time....
Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor.
def read_proximity(self, timeout_sec=1): """Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor. """ # Ask for a proximity measurement and wait for the response. self._device.write8(VCNL40xx_COMMAND, VCNL...
Read the ambient light sensor and return it as an unsigned 16-bit value.
def read_ambient(self, timeout_sec=1): """Read the ambient light sensor and return it as an unsigned 16-bit value. """ # Ask for an ambient measurement and wait for the response. self._device.write8(VCNL40xx_COMMAND, VCNL40xx_MEASUREAMBIENT) self._wait_response(VCNL40xx_AMBIENTRE...
Clear the specified interrupt bit in the interrupt status register.
def _clear_interrupt(self, intbit): """Clear the specified interrupt bit in the interrupt status register. """ int_status = self._device.readU8(VCNL4010_INTSTAT); int_status &= ~intbit; self._device.write8(VCNL4010_INTSTAT, int_status);
Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor.
def read_proximity(self, timeout_sec=1): """Read the sensor proximity and return it as an unsigned 16-bit value. The larger the value the closer an object is to the sensor. """ # Clear any interrupts. self._clear_interrupt(VCNL4010_INT_PROX_READY) # Call base class read_p...
Read the ambient light sensor and return it as an unsigned 16-bit value.
def read_ambient(self, timeout_sec=1): """Read the ambient light sensor and return it as an unsigned 16-bit value. """ # Clear any interrupts. self._clear_interrupt(VCNL4010_INT_ALS_READY) # Call base class read_ambient and return result. return super(VCNL4010, self).read...
Swaps two nodes
def move(self): """Swaps two nodes""" a = random.randint(0, len(self.state) - 1) b = random.randint(0, len(self.state) - 1) self.state[[a,b]] = self.state[[b,a]]
Detect a single core-periphery pair. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> rb = cp.Rombach(algorithm='ls') # label switching algorithm >>> rb....
def detect(self, G): """Detect a single core-periphery pair. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> rb = cp.Rombach(algorithm='ls') # label swi...
Detect a single core-periphery pair using the Borgatti-Everett algorithm. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> be = cpa.BE() >>> be.detect(G)
def detect(self, G): """Detect a single core-periphery pair using the Borgatti-Everett algorithm. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> be = c...
A bool - if the certificate should be self-signed.
def self_signed(self, value): """ A bool - if the certificate should be self-signed. """ self._self_signed = bool(value) if self._self_signed: self._issuer = None
An int representable in 160 bits or less - must uniquely identify this certificate when combined with the issuer name.
def serial_number(self, value): """ An int representable in 160 bits or less - must uniquely identify this certificate when combined with the issuer name. """ if not isinstance(value, int_types): raise TypeError(_pretty_message( ''' se...
A datetime.datetime object of when the certificate becomes valid.
def begin_date(self, value): """ A datetime.datetime object of when the certificate becomes valid. """ if not isinstance(value, datetime): raise TypeError(_pretty_message( ''' begin_date must be an instance of datetime.datetime, not %s ...
A datetime.datetime object of when the certificate is last to be considered valid.
def end_date(self, value): """ A datetime.datetime object of when the certificate is last to be considered valid. """ if not isinstance(value, datetime): raise TypeError(_pretty_message( ''' end_date must be an instance of datetime.dat...
An asn1crypto.x509.Certificate object of the issuer. Used to populate both the issuer field, but also the authority key identifier extension.
def issuer(self, value): """ An asn1crypto.x509.Certificate object of the issuer. Used to populate both the issuer field, but also the authority key identifier extension. """ is_oscrypto = isinstance(value, asymmetric.Certificate) if not isinstance(value, x509.Certificat...
Grabs the first URL out of a asn1crypto.x509.CRLDistributionPoints object :param distribution_points: The x509.CRLDistributionPoints object to pull the URL out of :return: A unicode string or None
def _get_crl_url(self, distribution_points): """ Grabs the first URL out of a asn1crypto.x509.CRLDistributionPoints object :param distribution_points: The x509.CRLDistributionPoints object to pull the URL out of :return: A unicode string or None ...
A bool - if the certificate should have the OCSP no check extension. Only applicable to certificates created for signing OCSP responses. Such certificates should normally be issued for a very short period of time since they are effectively whitelisted by clients.
def ocsp_no_check(self, value): """ A bool - if the certificate should have the OCSP no check extension. Only applicable to certificates created for signing OCSP responses. Such certificates should normally be issued for a very short period of time since they are effectively whit...
Validates the certificate information, constructs the ASN.1 structure and then signs it :param signing_private_key: An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey object for the private key to sign the certificate with. If the key is self-signed,...
def build(self, signing_private_key): """ Validates the certificate information, constructs the ASN.1 structure and then signs it :param signing_private_key: An asn1crypto.keys.PrivateKeyInfo or oscrypto.asymmetric.PrivateKey object for the private key to sign th...
Location of the OCSP responder for this certificate. Will be one of the following types: - None for no OCSP responder - A unicode string of the URL to the OCSP responder
def ocsp_url(self): """ Location of the OCSP responder for this certificate. Will be one of the following types: - None for no OCSP responder - A unicode string of the URL to the OCSP responder """ if self._authority_information_access is None: ret...
Detect a single core-periphery pair using the Borgatti-Everett algorithm. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> spr = cpa.Surprise() >>> spr.d...
def detect(self, G): """Detect a single core-periphery pair using the Borgatti-Everett algorithm. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> spr = ...
Removes empty line. Example usage:: {% emptylineless %} test1 test2 test3 {% endemptylineless %} This example would return this HTML:: test1 test2 test3
def emptylineless(parser, token): """ Removes empty line. Example usage:: {% emptylineless %} test1 test2 test3 {% endemptylineless %} This example would return this HTML:: test1 test2 test3 """ nodeli...
Passes a connection from the connection pool so that we can call .run() on a query without an explicit connection
def remodel_run(self, c=None, **global_optargs): """ Passes a connection from the connection pool so that we can call .run() on a query without an explicit connection """ if not c: with remodel.connection.get_conn() as conn: return run(self, conn, **global_optargs) else: ...
Detect a single core-periphery pair. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> lrc = cp.LowRankCore() >>> lrc.detect(G)
def detect(self, G): """Detect a single core-periphery pair. Parameters ---------- G : NetworkX graph object Examples -------- >>> import networkx as nx >>> import cpalgorithm as cpa >>> G = nx.karate_club_graph() # load the karate club network. >>> lrc = cp.LowRankCore() >>> lrc.detect(G) ...
Do an HTTP PURGE of the given asset. The URL is run through urlparse and must point to the varnish instance not the varnishadm
def http_purge_url(url): """ Do an HTTP PURGE of the given asset. The URL is run through urlparse and must point to the varnish instance not the varnishadm """ url = urlparse(url) connection = HTTPConnection(url.hostname, url.port or 80) path = url.path or '/' connection.request('PURGE',...
Non-threaded batch command runner returning output results
def run(addr, *commands, **kwargs): """ Non-threaded batch command runner returning output results """ results = [] handler = VarnishHandler(addr, **kwargs) for cmd in commands: if isinstance(cmd, tuple) and len(cmd)>1: results.extend([getattr(handler, c[0].replace('.','_'))(...
ping [timestamp] Ping the Varnish cache process, keeping the connection alive.
def ping(self, timestamp=None): """ ping [timestamp] Ping the Varnish cache process, keeping the connection alive. """ cmd = 'ping' if timestamp: cmd += ' %s' % timestamp return tuple(map(float, self.fetch(cmd)[1].split()[1:]))
help [command] Display a list of available commands. If the command is specified, display help for this command.
def help(self, command=None): """ help [command] Display a list of available commands. If the command is specified, display help for this command. """ cmd = 'help' if command: cmd += ' %s' % command return self.fetch(cmd)[1]
param.show [-l] [param] Display a list if run-time parameters and their values. If the -l option is specified, the list includes a brief explanation of each parameter. If a param is specified, display only the value and explanation for this parameter.
def param_show(self, param, l=False): """ param.show [-l] [param] Display a list if run-time parameters and their values. If the -l option is specified, the list includes a brief explanation of each parameter. If a param is specified, display only the value and ...
vcl.list List available configurations and their respective reference counts. The active configuration is indicated with an asterisk ("*").
def vcl_list(self): """ vcl.list List available configurations and their respective reference counts. The active configuration is indicated with an asterisk ("*"). """ vcls = {} for line in self.fetch('vcl.list')[1].splitlines(): a = line.sp...
add the content of the file(s) (or the text in string) in HTML body
def add_content(self, text=None, *markdown_files): """add the content of the file(s) (or the text in string) in HTML body""" for markdown_file in markdown_files: self.markdown_text += self._text_file(markdown_file) if text: self.markdown_text += text
add stylesheet files in HTML head
def add_stylesheets(self, *css_files): """add stylesheet files in HTML head""" for css_file in css_files: self.main_soup.style.append(self._text_file(css_file))
add javascripts files in HTML body
def add_javascripts(self, *js_files): """add javascripts files in HTML body""" # create the script tag if don't exists if self.main_soup.script is None: script_tag = self.main_soup.new_tag('script') self.main_soup.body.append(script_tag) for js_file in js_files: ...
return the object in a file
def export(self): """return the object in a file""" with open(self.export_url, 'w', encoding='utf-8') as file: file.write(self.build()) if self.open_browser: webbrowser.open_new_tab(self.export_url)
convert Markdown text as html. return the html file as string
def build(self): """convert Markdown text as html. return the html file as string""" markdown_html = markdown.markdown(self.markdown_text, extensions=[ TocExtension(), 'fenced_code', 'markdown_checklist.extension', 'markdown.extensions.tables']) markdown_soup = Be...
return the content of a file
def _text_file(self, url): """return the content of a file""" try: with open(url, 'r', encoding='utf-8') as file: return file.read() except FileNotFoundError: print('File `{}` not found'.format(url)) sys.exit(0)
create a graphviz graph from text
def _text_to_graphiz(self, text): """create a graphviz graph from text""" dot = Source(text, format='svg') return dot.pipe().decode('utf-8')
add js libraries and css files of mermaid js_file
def _add_mermaid_js(self): """add js libraries and css files of mermaid js_file""" self.add_javascripts('{}/js/jquery-1.11.3.min.js'.format(self.resources_path)) self.add_javascripts('{}/js/mermaid.min.js'.format(self.resources_path)) self.add_stylesheets('{}/css/mermaid.css'.format(self...
Transform NetworkX object to an edge list. Parameters ---------- G : Graph object. Returns ------- node_pairs : (M, 2) numpy array, where M is the number of edges. node_pairs[i,0] and node_pairs[i,1] are the endpoints of the ith edge. w : Mx1 numpy array. w[i] is the weight of the ith edge. ...
def _to_edge_list(self, G): """Transform NetworkX object to an edge list. Parameters ---------- G : Graph object. Returns ------- node_pairs : (M, 2) numpy array, where M is the number of edges. node_pairs[i,0] and node_pairs[i,1] are the endpoints of the ith edge. w : Mx1 numpy array. w[i]...