docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Add a residue number or numbers to an NGLWidget view object. Args: view (NGLWidget): NGLWidget view object structure_resnums (int, list): Residue number(s) to highlight, structure numbering chain (str, list): Chain ID or IDs of which residues are a part of. If not provided, all chains in th...
def add_residues_highlight_to_nglview(view, structure_resnums, chain, res_color='red'): chain = ssbio.utils.force_list(chain) if isinstance(structure_resnums, list): structure_resnums = list(set(structure_resnums)) elif isinstance(structure_resnums, int): structure_resnums = ssbio.util...
548,654
Add select features from the selected SeqProp object to an NGLWidget view object. Currently parsing for: * Single residue features (ie. metal binding sites) * Disulfide bonds Args: view (NGLWidget): NGLWidget view object seqprop (SeqProp): SeqProp object structprop (StructProp)...
def add_features_to_nglview(view, structure_resnums, chain_id): # Parse and store chain seq if not already stored if not structprop.chains.has_id(chain_id): structprop.parse_structure() if not structprop.chains.has_id(chain_id): raise ValueError('Chain {} not present in structur...
548,655
Download the KEGG flatfile for a KEGG ID and return the path. Args: gene_id: KEGG gene ID (with organism code), i.e. "eco:1244" outdir: optional output directory of metadata Returns: Path to metadata file
def download_kegg_gene_metadata(gene_id, outdir=None, force_rerun=False): if not outdir: outdir = '' # Replace colon with dash in the KEGG gene ID outfile = op.join(outdir, '{}.kegg'.format(custom_slugify(gene_id))) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): ra...
548,656
Parse the KEGG flatfile and return a dictionary of metadata. Dictionary keys are: refseq uniprot pdbs taxonomy Args: infile: Path to KEGG flatfile Returns: dict: Dictionary of metadata
def parse_kegg_gene_metadata(infile): metadata = defaultdict(str) with open(infile) as mf: kegg_parsed = bs_kegg.parse(mf.read()) # TODO: additional fields can be parsed if 'DBLINKS' in kegg_parsed.keys(): if 'UniProt' in kegg_parsed['DBLINKS']: unis = str(kegg_parsed...
548,657
Map all of an organism's gene IDs to the target database. This is faster than supplying a specific list of genes to map, plus there seems to be a limit on the number you can map with a manual REST query anyway. Args: organism_code: the three letter KEGG code of your organism target_db: ncb...
def map_kegg_all_genes(organism_code, target_db): mapping = bs_kegg.conv(target_db, organism_code) # strip the organism code from the keys and the identifier in the values new_mapping = {} for k,v in mapping.items(): new_mapping[k.replace(organism_code + ':', '')] = str(v.split(':')[1]) ...
548,658
Provide pointers to the paths of the metadata file Args: m_path: Path to metadata file
def metadata_path(self, m_path): if not m_path: self.metadata_dir = None self.metadata_file = None else: if not op.exists(m_path): raise OSError('{}: file does not exist!'.format(m_path)) if not op.dirname(m_path): ...
548,660
Make the BLAST database for a genome file. Args: infile (str): path to genome FASTA file dbtype (str): "nucl" or "prot" - what format your genome files are in outdir (str): path to directory to output database files (default is original folder) Returns: Paths to BLAST databases...
def run_makeblastdb(infile, dbtype, outdir=''): # TODO: add force_rerun option # TODO: rewrite using utils function command # Output location og_dir, name, ext = utils.split_folder_and_path(infile) if not outdir: outdir = og_dir outfile_basename = op.join(outdir, name) # Check...
548,670
Write torque submission files for running bidirectional blast on a server and print execution command. Args: reference (str): Path to "reference" genome, aka your "base strain" other_genome (str): Path to other genome which will be BLASTed to the reference dbtype (str): "nucl" or "prot" - w...
def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir): # TODO: add force_rerun option if dbtype == 'nucl': command = 'blastn' elif dbtype == 'prot': command = 'blastp' else: raise ValueError('dbtype must be "nucl" or "prot"') r_folder, r_name, r_ex...
548,672
Calculate the best bidirectional BLAST hits (BBH) and save a dataframe of results. Args: blast_results_1 (str): BLAST results for reference vs. other genome blast_results_2 (str): BLAST results for other vs. reference genome r_name: Name of reference genome g_name: Name of other gen...
def calculate_bbh(blast_results_1, blast_results_2, r_name=None, g_name=None, outdir=''): # TODO: add force_rerun option cols = ['gene', 'subject', 'PID', 'alnLength', 'mismatchCount', 'gapOpenCount', 'queryStart', 'queryEnd', 'subjectStart', 'subjectEnd', 'eVal', 'bitScore'] if not r_nam...
548,673
Exposes methods in the Bio.Struct.Protein module. Parameters: - filter_residues boolean; removes non-aa residues through Bio.PDB.Polypeptide is_aa function [Default: True] Returns a new structure object.
def as_protein(structure, filter_residues=True): from ssbio.biopython.Bio.Struct.Protein import Protein return Protein.from_structure(structure, filter_residues)
548,675
Return a string representation of a Seq or SeqRecord. Args: obj (str, Seq, SeqRecord): Biopython Seq or SeqRecord Returns: str: String representation of the sequence
def cast_to_str(obj): if isinstance(obj, str): return obj if isinstance(obj, Seq): return str(obj) if isinstance(obj, SeqRecord): return str(obj.seq) else: raise ValueError('Must provide a string, Seq, or SeqRecord object.')
548,704
Return a Seq representation of a string or SeqRecord object. Args: obj (str, Seq, SeqRecord): Sequence string or Biopython SeqRecord object alphabet: See Biopython SeqRecord docs Returns: Seq: Seq representation of the sequence
def cast_to_seq(obj, alphabet=IUPAC.extended_protein): if isinstance(obj, Seq): return obj if isinstance(obj, SeqRecord): return obj.seq if isinstance(obj, str): obj = obj.upper() return Seq(obj, alphabet) else: raise ValueError('Must provide a string, Seq, ...
548,705
Write a FASTA file for a SeqRecord or a list of SeqRecord objects. Args: seq_records (SeqRecord, list): SeqRecord or a list of SeqRecord objects outname: Name of the output file which will have outext appended to it outdir: Path to directory to output sequences to outext: Extension ...
def write_fasta_file(seq_records, outname, outdir=None, outext='.faa', force_rerun=False): if not outdir: outdir = '' outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): SeqIO.writ...
548,707
Write a FASTA file for a dictionary of IDs and their sequence strings. Args: indict: Input dictionary with keys as IDs and values as sequence strings outname: Name of the output file which will have outext appended to it outdir: Path to directory to output sequences to outext: Exten...
def write_fasta_file_from_dict(indict, outname, outdir=None, outext='.faa', force_rerun=False): if not outdir: outdir = '' outfile = ssbio.utils.outfile_maker(inname='', outname=outname, outdir=outdir, outext=outext) if ssbio.utils.force_rerun(flag=force_rerun, outfile=outfile): seqs ...
548,708
Write a sequence as a temporary FASTA file Args: seq (str, Seq, SeqRecord): Sequence string, Biopython Seq or SeqRecord object Returns: str: Path to temporary FASTA file (located in system temporary files directory)
def write_seq_as_temp_fasta(seq): sr = ssbio.protein.sequence.utils.cast_to_seq_record(seq, id='tempfasta') return write_fasta_file(seq_records=sr, outname='temp', outdir=tempfile.gettempdir(), force_rerun=True)
548,709
Load a FASTA file and return the sequences as a list of SeqRecords Args: filename (str): Path to the FASTA file to load Returns: list: list of all sequences in the FASTA file as Biopython SeqRecord objects
def load_fasta_file(filename): with open(filename, "r") as handle: records = list(SeqIO.parse(handle, "fasta")) return records
548,710
Load a FASTA file and return the sequences as a dict of {ID: sequence string} Args: filename (str): Path to the FASTA file to load Returns: dict: Dictionary of IDs to their sequence strings
def load_fasta_file_as_dict_of_seqs(filename): results = {} records = load_fasta_file(filename) for r in records: results[r.id] = str(r.seq) return results
548,711
Load a FASTA file and return the sequences as a dict of {ID: SeqRecord} Args: filename (str): Path to the FASTA file to load Returns: dict: Dictionary of IDs to their SeqRecords
def load_fasta_file_as_dict_of_seqrecords(filename): results = {} records = load_fasta_file(filename) for r in records: results[r.id] = r return results
548,712
Check equality of a FASTA file to another FASTA file Args: seq_file1: Path to a FASTA file seq_file2: Path to another FASTA file Returns: bool: If the sequences are the same
def fasta_files_equal(seq_file1, seq_file2): # Load already set representative sequence seq1 = SeqIO.read(open(seq_file1), 'fasta') # Load kegg sequence seq2 = SeqIO.read(open(seq_file2), 'fasta') # Test equality if str(seq1.seq) == str(seq2.seq): return True else: re...
548,713
Checks for missing atoms based on a template. Default: Searches for missing heavy atoms (not Hydrogen) based on Bio.Struct.protein_residues Arguments: - template, dictionary, keys are residue names, values list of atom names. - ha_only, boolean, default True, restrict check ...
def check_missing_atoms(self, template=None, ha_only=True): missing_atoms = {} if not template: import protein_residues template = protein_residues.normal # Don't care for terminal residues here.. for residue in self.get_residues():...
548,722
Reduces the protein structure complexity to a few (pseudo-)atoms per residue. Parameters: - cg_type: CA_TRACE (Ca-only) [Default] ENCAD_3P (CA, O, SC Beads) MARTINI (CA, O, SC Beads) Returns a new struct...
def coarse_grain(self, cg_type="CA_TRACE"): # Import CG Types import CG_Models CG_Library = { "CA_TRACE": CG_Models.CA_TRACE, "ENCAD_3P": CG_Models.ENCAD_3P, "MARTINI": CG_Models.MARTINI } CG...
548,723
Initialize the AMYLPRED object with your email and password used to login here. Args: email (str): Account email password (str): Account password
def __init__(self, email, password): self.email = email self.password = password
548,725
Run all methods on the AMYLPRED2 web server for an amino acid sequence and gather results. Result files are cached in ``/path/to/outdir/AMYLPRED2_results``. Args: seq (str): Amino acid sequence as a string outdir (str): Directory to where output files should be saved ...
def run_amylpred2(self, seq, outdir, run_amylmuts=False): outdir_amylpred = op.join(outdir, 'AMYLPRED2_results') if not op.exists(outdir_amylpred): os.mkdir(outdir_amylpred) url = "http://aias.biol.uoa.gr/AMYLPRED2/login.php" cj = CookieJar() opener = build_...
548,727
Get NMR prize pool for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defaults to 1 Returns: decimal.Decimal: prize pool i...
def get_nmr_prize_pool(self, round_num=0, tournament=1): tournaments = self.get_competitions(tournament) tournaments.sort(key=lambda t: t['number']) if round_num == 0: t = tournaments[-1] else: tournaments = [t for t in tournaments if t['number'] == round...
548,843
Compute staking cutoff for the given round and tournament. Args: round_num (int, optional): The round you are interested in, defaults to current round. tournament (int, optional): ID of the tournament, defaults to 1 Returns: decimal.Decimal: cutoff p...
def get_staking_cutoff(self, round_num=0, tournament=1): query = arguments = {'number': round_num, 'tournament': tournament} result = self.raw_query(query, arguments) result = result['data']['rounds'][0]['selection'] key = 'bCutoff' if round_num >= 154 or round_num == 0...
548,844
Get number of the current active round. Args: tournament (int): ID of the tournament (optional, defaults to 1) Returns: int: number of the current active round Example: >>> NumerAPI().get_current_round() 104
def get_current_round(self, tournament=1): # zero is an alias for the current round! query = arguments = {'tournament': tournament} data = self.raw_query(query, arguments)['data']['rounds'][0] if data is None: return None round_num = data["number"] ...
548,846
Get dict with username->submission_id mapping. Args: tournament (int): ID of the tournament (optional, defaults to 1) Returns: dict: username->submission_id mapping, string->string Example: >>> NumerAPI().get_submission_ids() {'1337ai': '93c4685...
def get_submission_ids(self, tournament=1): query = arguments = {'tournament': tournament} data = self.raw_query(query, arguments)['data']['rounds'][0] if data is None: return None mapping = {item['username']: item['submissionId'] for item...
548,851
Upload predictions from file. Args: file_path (str): CSV file with predictions that will get uploaded tournament (int): ID of the tournament (optional, defaults to 1) Returns: str: submission_id Example: >>> api = NumerAPI(secret_key="..", publi...
def upload_predictions(self, file_path, tournament=1): self.logger.info("uploading predictions...") auth_query = arguments = {'filename': os.path.basename(file_path), 'tournament': tournament} submission_resp = self.raw_query(auth_query, arguments, ...
548,857
Check if a new round has started within the last `hours`. Args: hours (int, optional): timeframe to consider, defaults to 24 tournament (int): ID of the tournament (optional, defaults to 1) Returns: bool: True if a new round has started, False otherwise. Ex...
def check_new_round(self, hours=24, tournament=1): query = arguments = {'tournament': tournament} raw = self.raw_query(query, arguments)['data']['rounds'][0] if raw is None: return False open_time = utils.parse_datetime_string(raw['openTime']) now = ...
548,859
Translate tournament number to tournament name. Args: number (int): tournament number to translate Returns: name (str): name of the tournament or `None` if unknown. Examples: >>> NumerAPI().tournament_number2name(4) 'delta' >>> Numer...
def tournament_number2name(self, number): tournaments = self.get_tournaments() d = {t['tournament']: t['name'] for t in tournaments} return d.get(number, None)
548,861
Translate tournament name to tournament number. Args: name (str): tournament name to translate Returns: number (int): number of the tournament or `None` if unknown. Examples: >>> NumerAPI().tournament_name2number('delta') 4 >>> Numer...
def tournament_name2number(self, name): tournaments = self.get_tournaments() d = {t['name']: t['tournament'] for t in tournaments} return d.get(name, None)
548,862
Installs javascript and exporting server extensions in Jupyter notebook. Args: nb_path (string): Path to notebook module. server_config (boolean): Install exporting server extensions. DEBUG (boolean): Verbose mode.
def install_bootstrapped_files(nb_path=None, server_config=True, DEBUG=False): install_path = None print('Starting hide_code.js install...') current_dir = path.abspath(path.dirname(__file__)) config_dirs = j_path.jupyter_config_path() notebook_module_path = Utils.get_notebook_module_dir() ...
548,884
Iterate through a grid of tiles. Args: x (int): x start-coordinate y (int): y start-coordinate ncol (int): number of tile columns nrow (int): number of tile rows. If not specified, this defaults to ncol, s.t. a quadratic region is generated step (int)...
def griditer(x, y, ncol, nrow=None, step=1): if nrow is None: nrow = ncol yield from itertools.product(range(x, x + ncol, step), range(y, y + nrow, step))
548,989
Generate a PDF at the given position. Args: map_source (str): id of the map source to print. zoom (int): zoom-level to print x (float): Center of the Map in mercator projection (EPSG:4326), x-coordinate y (float): Center of the Map in mercator projection (EPSG:4326), y-coordinate ...
def map_to_pdf(map_source, zoom, x, y, width, height): map_source = app.config["mapsources"][map_source] pdf_file = print_map(map_source, x=float(x), y=float(y), zoom=int(zoom), width=float(width), height=float(height), format='pdf') return send_file(pdf_file, ...
549,020
Create a unique element name for KML Args: grid_coords (GridCoordinate): elem_id (str): >>> kml_element_name(GridCoordinate(zoom=5, x=42, y=60), elem_id="NL") 'NL_5_42_60'
def kml_element_name(grid_coords, elem_id="KML"): return "_".join(str(x) for x in [elem_id, grid_coords.zoom, grid_coords.x, grid_coords.y])
549,027
Create the north/south/east/west tags for a <LatLonBox> or <LatLonAltBox> Bounding Box Args: geo_bb (GeographicBB): Returns: Tuple: (<north>, <south>, <east>, <west>) KMLElements
def kml_lat_lon_box(geo_bb): return ( KML.north(geo_bb.max.lat), KML.south(geo_bb.min.lat), KML.east(geo_bb.max.lon), KML.west(geo_bb.min.lon) )
549,028
Create the KML <Region> tag with the appropriate geographic coordinates Args: region_coords (RegionCoordinate): min_lod_pixels (int): see `kml_lod` max_lod_pixels (int): see `kml_lod` Returns: KMLElement: the KML <Region>
def kml_region(region_coords, min_lod_pixels=DEFAULT_MIN_LOD_PIXELS, max_lod_pixels=DEFAULT_MAX_LOD_PIXELS): bbox = region_coords.geographic_bounds() return KML.Region( kml_lod(min_lod_pixels=min_lod_pixels, max_lod_pixels=max_lod_pixels), KML.LatLonAltBox( *kml_l...
549,030
Create the KML <NetworkLink> Tag for a certain Region in the RegionGrid. Args: region_coords (RegionCoordinate): href (str): the href attribute of the NetworkLink name (str): KML <name> visible (bool): If true the network link will appear as 'visible' (i.e. checked) in G...
def kml_network_link(href, name=None, region_coords=None, visible=True): nl = KML.NetworkLink() if name is None and region_coords is not None: name = kml_element_name(region_coords, "NL") if name is not None: nl.append(KML.name(name)) if region_coords is not None: min_lod_pi...
549,031
Create a KML <GroundOverlay> for a certain TileCoordinate. Args: tile_coords (TileCoordinate): TileCoordinate tile_url (str): web-url to the actual tile image. Returns: KMLElement: the KML <GroundOverlay>
def kml_ground_overlay(tile_coords, tile_url): return KML.GroundOverlay( KML.name(kml_element_name(tile_coords, "GO")), KML.drawOrder(tile_coords.zoom), KML.Icon( KML.href(tile_url) ), KML.LatLonBox( *kml_lat_lon_box(tile_coords.geographic_bounds(...
549,032
Create a KML master document. Args: mapsources (list of MapSource):
def __init__(self, url_formatter, mapsources): super().__init__(url_formatter) self.map_folders = { root: { "folders": folders, "maps": maps } for root, folders, maps in walk_mapsources(mapsources) } self.add_maps(parent=se...
549,037
Recursively add maps in a folder hierarchy. Args: parent (KMLElement): KMLElement to which we want to append child folders or maps respectively root_path (str): path of 'parent'
def add_maps(self, parent, root_path=""): for mapsource in self.map_folders[root_path]['maps']: parent.append(self.get_network_link(mapsource)) for folder in self.map_folders[root_path]['folders']: kml_folder_obj = kml_folder(folder) parent.append(kml_folder_...
549,038
Download a given tile from the tile server. Args: map_layer (MapLayer): MapLayer object which provides the tile-url. zoom (int): zoom level x (int): Tile-x-coordinate y (int): Tile-y-coordinate Returns: file: temporary file containing the downloaded image.
def download_tile(map_layer, zoom, x, y): try: tile_url = map_layer.get_tile_url(zoom, x, y) tmp_file, headers = urllib.request.urlretrieve(tile_url) return (x, y), tmp_file except URLError as e: app.logger.info("Error downloading tile x={}, y={}, z={} for layer {}: {}".form...
549,049
Download tiles. Args: map_source (MapSource): bbox (TileBB): Bounding box delimiting the map n_workers (int): number of threads to used for downloading. Returns: dict of file: Dictionary mapping coordinates to temporary files. Example:: { (...
def get_tiles(map_layer, bbox, n_workers=N_DOWNLOAD_WORKERS): p = Pool(n_workers) tiles = {} for (x, y), tmp_file in p.imap_unordered(_download_tile_wrapper, zip(itertools.repeat(map_layer), itertools.repeat(bbox.zoom), ...
549,050
Merge tiles together into one image. Args: tiles (list of dict of file): tiles for each layer width (float): page width in mm height (height): page height in mm dpi (dpi): resolution in dots per inch Returns: PIL.Image: merged map.
def stitch_map(tiles, width, height, bbox, dpi): size = (int(width * dpi_to_dpmm(dpi)), int(height * dpi_to_dpmm(dpi))) background = Image.new('RGBA', size, (255, 255, 255)) for layer in tiles: layer_img = Image.new("RGBA", size) for (x, y), tile_path in layer.items(): tile ...
549,051
Add a scales bar to the map. Calculates the resolution at the current latitude and inserts the corresponding scales bar on the map. Args: img (Image): Image object to which the scales bar will be added. bbox (TileBB): boundaries of the map
def add_scales_bar(img, bbox): tc = TileCoordinate(bbox.min.zoom, bbox.min.x, bbox.min.y) meters_per_pixel = tc.resolution() one_km_bar = int(1000 * (1 / meters_per_pixel)) col_black = (0, 0, 0) line_start = (100, img.size[1] - 100) # px line_end = (line_start[0] + one_km_bar, line_start[...
549,052
Load all xml map sources from a given directory. Args: maps_dir: path to directory to search for maps Returns: dict of MapSource:
def load_maps(maps_dir): maps_dir = os.path.abspath(maps_dir) maps = {} for root, dirnames, filenames in os.walk(maps_dir): for filename in filenames: if filename.endswith(".xml"): xml_file = os.path.join(root, filename) map = MapSource.from_xml(xml_f...
549,056
Get the geographic bounds from an XML element Args: xml_region (Element): The <region> tag as XML Element Returns: GeographicBB:
def parse_xml_boundary(xml_region): try: bounds = {} for boundary in xml_region.getchildren(): bounds[boundary.tag] = float(boundary.text) bbox = GeographicBB(min_lon=bounds["west"], max_lon=bounds["east"], min_lat=boun...
549,063
Get the MapLayers from an XML element Args: xml_layers (Element): The <layers> tag as XML Element Returns: list of MapLayer:
def parse_xml_layers(xml_layers): layers = [] for custom_map_source in xml_layers.getchildren(): layers.append(MapSource.parse_xml_layer(custom_map_source)) return layers
549,064
Get one MapLayer from an XML element Args: xml_custom_map_source (Element): The <customMapSource> element tag wrapped in a <layers> tag as XML Element Returns: MapLayer:
def parse_xml_layer(xml_custom_map_source): map_layer = MapLayer() try: for elem in xml_custom_map_source.getchildren(): if elem.tag == 'url': map_layer.tile_url = elem.text elif elem.tag == 'minZoom': map_layer...
549,065
Build the example for the given definition. Args: def_name: Name of the definition. Returns: True if the example has been created, False if an error occured.
def build_one_definition_example(self, def_name): if def_name in self.definitions_example.keys(): # Already processed return True elif def_name not in self.specification['definitions'].keys(): # Def does not exist return False self.definitions_example[def_name...
550,962
Check if the value is in the type given in type_def. Args: value: the var to test. type_def: string representing the type in swagger. Returns: True if the type is correct, False otherwise.
def check_type(value, type_def): if type_def == 'integer': try: # We accept string with integer ex: '123' int(value) return True except ValueError: return isinstance(value, six.integer_types) and not isinstance(valu...
550,963
Return an example value from a property specification. Args: prop_spec: the specification of the property. from_allof: whether these properties are part of an allOf section Returns: An example value
def get_example_from_prop_spec(self, prop_spec, from_allof=False): # Read example directly from (X-)Example or Default value easy_keys = ['example', 'x-example', 'default'] for key in easy_keys: if key in prop_spec.keys() and self.use_example: return prop_spe...
550,964
Get example from the properties of an object defined inline. Args: prop_spec: property specification you want an example of. Returns: An example for the given spec A boolean, whether we had additionalProperties in the spec, or not
def _get_example_from_properties(self, spec): local_spec = deepcopy(spec) # Handle additionalProperties if they exist # we replace additionalProperties with two concrete # properties so that examples can be generated additional_property = False if 'additionalPro...
550,965
Get example from the given type. Args: type: the type you want an example of. Returns: An array with two example values of the given type.
def _get_example_from_basic_type(type): if type == 'integer': return [42, 24] elif type == 'number': return [5.5, 5.5] elif type == 'string': return ['string', 'string2'] elif type == 'datetime': return ['2015-08-28T09:02:57.481Z',...
550,966
Generates a swagger definition json from a given example Works only for simple types in the dict Args: example: The example for which we want a definition Type is DICT Returns: A dict that is the swagger definition json
def _definition_from_example(example): assert isinstance(example, dict) def _has_simple_type(value): accepted = (str, int, float, bool) return isinstance(value, accepted) definition = { 'type': 'object', 'properties': {}, } ...
550,967
Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict
def _example_from_allof(self, prop_spec): example_dict = {} for definition in prop_spec['allOf']: update = self.get_example_from_prop_spec(definition, True) example_dict.update(update) return example_dict
550,968
Get an example from a property specification linked to a definition. Args: prop_spec: specification of the property you want an example of. Returns: An example.
def _example_from_definition(self, prop_spec): # Get value from definition definition_name = self.get_definition_name_from_ref(prop_spec['$ref']) if self.build_one_definition_example(definition_name): example_dict = self.definitions_example[definition_name] if n...
550,969
Get an example from a property specification. In case there is no "type" key in the root of the dictionary. Args: prop_spec: property specification you want an example of. Returns: An example.
def _example_from_complex_def(self, prop_spec): if 'schema' not in prop_spec: return [{}] elif 'type' not in prop_spec['schema']: definition_name = self.get_definition_name_from_ref(prop_spec['schema']['$ref']) if self.build_one_definition_example(definition_...
550,970
Get an example from a property specification of an array. Args: prop_spec: property specification you want an example of. Returns: An example array.
def _example_from_array_spec(self, prop_spec): # if items is a list, then each item has its own spec if isinstance(prop_spec['items'], list): return [self.get_example_from_prop_spec(item_prop_spec) for item_prop_spec in prop_spec['items']] # Standard types in array e...
550,971
Get the definition name of the given dict. Args: dict: dict to test. get_list: if set to true, return a list of definition that match the body. if False, only return the first. Returns: The definition name or None if the dict does not match any...
def get_dict_definition(self, dict, get_list=False): list_def_candidate = [] for definition_name in self.specification['definitions'].keys(): if self.validate_definition(definition_name, dict): if not get_list: return definition_name ...
550,972
Validate the given dict according to the given definition. Args: definition_name: name of the the definition. dict_to_test: dict to test. Returns: True if the given dict match the definition, False otherwise.
def validate_definition(self, definition_name, dict_to_test, definition=None): if (definition_name not in self.specification['definitions'].keys() and definition is None): # reject unknown definition return False # Check all required in dict_to_test ...
550,974
Validate the given value with the given property spec. Args: properties_dict: specification of the property to check (From definition not route). value: value to check. Returns: True if the value is valid for the given spec.
def _validate_type(self, properties_spec, value): if 'type' not in properties_spec.keys(): # Validate sub definition def_name = self.get_definition_name_from_ref(properties_spec['$ref']) return self.validate_definition(def_name, value) # Validate array ...
550,975
Populates the given parameter map with the list of parameters provided, resolving any reference objects encountered. Args: parameter_map: mapping from parameter names to parameter objects parameter_list: list of either parameter objects or reference objects
def _add_parameters(self, parameter_map, parameter_list): for parameter in parameter_list: if parameter.get('$ref'): # expand parameter from $ref if not specified inline parameter = self.specification['parameters'].get(parameter.get('$ref').split('/')[-1]) ...
550,977
Get the definition name of the given $ref value(Swagger value). Args: ref: ref value (ex: "#/definitions/CustomDefinition") Returns: The definition name corresponding to the ref.
def get_definition_name_from_ref(ref): p = re.compile('#\/definitions\/(.*)') definition_name = re.sub(p, r'\1', ref) return definition_name
550,978
Get the specification matching with the given path. Args: path: path we want the specification. action: get the specification for the given action. Returns: A tuple with the base name of the path and the specification. Or (None, None) if no specification...
def get_path_spec(self, path, action=None): # Get the specification of the given path path_spec = None path_name = None for base_path in self.paths.keys(): if path == base_path: path_spec = self.paths[base_path] path_name = base_path ...
550,979
Check the query parameter for the action specification. Args: query: query parameter to check. action_spec: specification of the action. Returns: True if the query is valid.
def _validate_query_parameters(self, query, action_spec): processed_params = [] for param_name, param_value in query.items(): if param_name in action_spec['parameters'].keys(): processed_params.append(param_name) # Check array if acti...
550,981
Check the body parameter for the action specification. Args: body: body parameter to check. action_spec: specification of the action. Returns: True if the body is valid. A string containing an error msg in case the body did not validate, othe...
def _validate_body_parameters(self, body, action_spec): processed_params = [] for param_name, param_spec in action_spec['parameters'].items(): if param_spec['in'] == 'body': processed_params.append(param_name) # Check type if 'type' i...
550,982
Get the default data and status code of the given path + action request. Args: path: path of the request. action: action of the request(get, post, delete...) body: body sent, used to sent it back for post request. Returns: A tuple with the default respon...
def get_request_data(self, path, action, body=None): body = body or '' path_name, path_spec = self.get_path_spec(path) response = {} # Get all status code if path_spec is not None and action in path_spec.keys(): for status_code in path_spec[action]['response...
550,984
Get an example body which is correct to send to the given path with the given action. Args: path: path of the request action: action of the request (get, post, put, delete) Returns: A dict representing a correct body for the request or None if no body is...
def get_send_request_correct_body(self, path, action): path_name, path_spec = self.get_path_spec(path) if path_spec is not None and action in path_spec.keys(): for name, spec in path_spec[action]['parameters'].items(): if spec['in'] == 'body': # Get body pa...
550,985
Constructs a new Tool description. Parameters: name: the name of the tool. image: the name of Docker image for this tool. environment: a dictionary of environment variables that should be injected upon loading the tool inside the container.
def __init__(self, name: str, image: str, environment: Dict[str, str], source: Optional[str] = None ) -> None: self.__name = name self.__image = image self.__environment = environment self.__sou...
551,137
Checks that a given bug successfully builds, and that it produces an expected set of test suite outcomes. Parameters: verbose: toggles verbosity of output. If set to `True`, the outcomes of each test will be printed to the standard output. Returns: `True...
def validate(self, bug: Bug, verbose: bool = True) -> bool: # attempt to rebuild -- don't worry, Docker's layer caching prevents us # from actually having to rebuild everything from scratch :-) try: self.build(bug, force=True, quiet=True) except docker.errors.BuildEr...
551,175
Provides coverage information for each test within the test suite for the program associated with this bug. Parameters: bug: the bug for which to compute coverage. Returns: a test suite coverage report for the given bug.
def coverage(self, bug: Bug) -> TestSuiteCoverage: # determine the location of the coverage map on disk fn = os.path.join(self.__installation.coverage_path, "{}.coverage.yml".format(bug.name)) # is the coverage already cached? if so, load. if os.path.e...
551,176
Deletes a running container with a given UID. Parameters: uid: the unique identifier of the container. Raises: KeyError: if no container was found with the given UID.
def __delitem__(self, uid: str) -> None: logger.debug("deleting container: %s", uid) try: container = self.__containers[uid] self.__dockerc[uid].remove(force=True) for container_tool in self.__dockerc_tools[uid]: container_tool.remove(force=T...
551,179
Provisions and returns a container for a given bug. Parameters: bug: the bug that should be used to provision a container. uid: a unique identifier (UID) for the container. If no UID is provided then one will be automatically generated. Returns: a de...
def provision(self, bug: Bug, uid: str = None, tools: Optional[List[Tool]] = None, volumes: Optional[Dict[str, str]] = None, network_mode: str = 'bridge', ports: Optional[Dict[int, int]] = None, ...
551,181
Attempts to compile the program inside a given container. Params: verbose: specifies whether to print the stdout and stderr produced by the compilation command to the stdout. If `True`, then the stdout and stderr will be printed. Returns: a summa...
def compile(self, container: Container, verbose: bool = False ) -> CompilationOutcome: # TODO use container name bug = self.__installation.bugs[container.bug] return bug.compiler.compile(self, container, verbose=verbose)
551,190
Persists the state of a given container to a BugZoo image on this server. Parameters: container: the container to persist. image: the name of the Docker image that should be created. Raises: ImageAlreadyExists: if the image name is already in use by another ...
def persist(self, container: Container, image: str) -> None: logger_c = logger.getChild(container.uid) logger_c.debug("Persisting container as a Docker image: %s", image) try: docker_container = self.__dockerc[container.uid] except KeyError: logger_c.exce...
551,195
Launches an ephemeral server instance that will be immediately close when no longer in context. Parameters: port: the port that the server should run on. verbose: if set to True, the server will print its output to the stdout, otherwise it will remain silent. Returns: a...
def ephemeral(*, port: int = 6060, timeout_connection: int = 30, verbose: bool = False ) -> Iterator[Client]: url = "http://127.0.0.1:{}".format(port) cmd = ["bugzood", "--debug", "-p", str(port)] try: stdout = None if verbose else subproc...
551,197
Computes line coverage information for a given set of tests. Parameters: tests: the tests for which coverage should be computed. instrument: if set to True, calls prepare and cleanup before and after running the tests. If set to False, prepare and cleanup...
def run(self, tests: Iterable[TestCase], *, instrument: bool = True ) -> TestSuiteCoverage: container = self.container logger.debug("computing coverage for container: %s", container.uid) try: if instrument: log...
551,232
Constructs a new client for communicating with a BugZoo server. Parameters: base_url: the base URL of the BugZoo server. timeout_connection: the maximum number of seconds to wait whilst attempting to connect to the server before declaring the connection t...
def __init__(self, base_url: str = None, *, timeout_connection: int = 30 ) -> None: if base_url is None: base_url = "http://127.0.0.1:6060" self.__api = APIClient(base_url, timeout_connection=timeout_connection) ...
551,278
Fetches a container by its ID. Parameters: uid: the ID of the container. Returns: the container with the given ID. Raises: KeyError: if no container is found with the given ID.
def __getitem__(self, uid: str) -> Container: r = self.__api.get('containers/{}'.format(uid)) if r.status_code == 200: return Container.from_dict(r.json()) if r.status_code == 404: raise KeyError("no container found with given UID: {}".format(uid)) sel...
551,284
Instruments the program inside the container for computing test suite coverage. Params: container: the container that should be instrumented.
def instrument(self, container: Container ) -> None: path = "containers/{}/instrument".format(container.uid) r = self.__api.post(path) if r.status_code != 204: logger.info("failed to instrument container: %s", container.uid) ...
551,293
Executes a given test inside a container. Parameters: container: the container in which the test should be conducted. test: the test that should be executed. Returns: a summary of the outcome of the test execution. Raises: KeyError: if the conta...
def test(self, container: Container, test: TestCase ) -> TestOutcome: path = "containers/{}/test/{}".format(container.uid, test.name) r = self.__api.post(path) if r.status_code == 200: return TestOutcome.from_dict(r.json()) sel...
551,295
Computes complete test suite coverage for a given container. Parameters: container: the container for which coverage should be computed. rebuild: if set to True, the program will be rebuilt before coverage is computed.
def coverage(self, container: Container, *, instrument: bool = True ) -> TestSuiteCoverage: uid = container.uid logger.info("Fetching coverage information for container: %s", uid) uri = 'containers/{...
551,296
Persists the state of a given container as a Docker image on the server. Parameters: container: the container that should be persisted. image_name: the name of the Docker image that should be created. Raises: ContainerNotFound: if the given container does no...
def persist(self, container: Container, image_name: str) -> None: logger.debug("attempting to persist container (%s) to image (%s).", container.id, image_name) path = "containers/{}/persist/{}".format(container.id, image_name) r = self.__api.put...
551,299
Deletes a Docker image with a given name. Parameters: name: the name of the Docker image.
def delete_image(self, name: str) -> None: logger.debug("deleting Docker image: %s", name) path = "docker/images/{}".format(name) response = self.__api.delete(path) if response.status_code != 204: try: self.__api.handle_erroneous_response(response) ...
551,328
Indicates a given Docker image is installed on this server. Parameters: name: the name of the Docker image. Returns: `True` if installed; `False` if not.
def is_installed(self, name: str) -> bool: assert name is not None try: self.__docker.images.get(name) return True except docker.errors.ImageNotFound: return False
551,374
Attempts to download a given Docker image. If `force=True`, then any previously installed version of the image (described by the instructions) will be replaced by the image on DockerHub. Parameters: name: the name of the Docker image. Returns: `True` if successf...
def download(self, name: str, force: bool = False ) -> bool: try: self.__docker.images.pull(name) return True except docker.errors.NotFound: print("Failed to locate image on DockerHub: {}".format(name)) ...
551,377
Attempts to upload a given Docker image from this server to DockerHub. Parameters: name: the name of the Docker image. Returns: `True` if successfully uploaded, otherwise `False`.
def upload(self, name: str) -> bool: try: out = self.__docker.images.push(name, stream=True) for line in out: line = line.strip().decode('utf-8') jsn = json.loads(line) if 'progress' in jsn: line = "{}. {}.".for...
551,378
Initialize a new port server. Args: ports_to_serve: A sequence of unique port numbers to test and offer up to clients.
def __init__(self, ports_to_serve): self._port_pool = _PortPool() self._total_allocations = 0 self._denied_allocations = 0 self._client_request_errors = 0 for port in ports_to_serve: self._port_pool.add_port_to_free_pool(port)
551,468
Given a port request body, parse it and respond appropriately. Args: client_data: The request bytes from the client. writer: The asyncio Writer for the response to be written to.
def _handle_port_request(self, client_data, writer): try: pid = int(client_data) except ValueError as error: self._client_request_errors += 1 log.warning('Could not parse request: %s', error) return log.info('Request on behalf of pid %d.'...
551,470
Convert kwargs to CSV string. Args: kwargs (dict): Key-word arguments.
def __init__(self, kwargs): PanCloudError.__init__( self, "{}".format(", ".join(kwargs.keys())) )
551,542
Resolve credential from envars or credentials store. Args: credential (str): Credential to resolve. Returns: str or None: Resolved credential or ``None``.
def _resolve_credential(self, credential): if self._credentials_found_in_instance: return elif self._credentials_found_in_envars(): return os.getenv('PAN_' + credential.upper()) else: return self.storage.fetch_credential( credential=cr...
551,549
Extract payload field from JWT. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: dict: JSON object that contains the claims conveyed by the JWT.
def decode_jwt_payload(self, access_token=None): c = self.get_credentials() jwt = access_token or c.access_token try: _, payload, _ = jwt.split('.') # header, payload, sig rem = len(payload) % 4 if rem > 0: # add padding payload += '...
551,550
Extract exp field from access token. Args: access_token (str): Access token to decode. Defaults to ``None``. Returns: int: JWT expiration in epoch seconds.
def _decode_exp(self, access_token=None): c = self.get_credentials() jwt = access_token or c.access_token x = self.decode_jwt_payload(jwt) if 'exp' in x: try: exp = int(x['exp']) except ValueError: raise PanCloudError( ...
551,551
Exchange authorization code for token. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. client_secret (str): OAuth2 client secret. Defaults to ``None``. code (str): Authorization code. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults...
def fetch_tokens(self, client_id=None, client_secret=None, code=None, redirect_uri=None, **kwargs): client_id = client_id or self.client_id client_secret = client_secret or self.client_secret redirect_uri = redirect_uri or self.redirect_uri data = { ...
551,552
Generate authorization URL. Args: client_id (str): OAuth2 client ID. Defaults to ``None``. instance_id (str): App Instance ID. Defaults to ``None``. redirect_uri (str): Redirect URI. Defaults to ``None``. region (str): App Region. Defaults to ``None``. ...
def get_authorization_url(self, client_id=None, instance_id=None, redirect_uri=None, region=None, scope=None, state=None): client_id = client_id or self.client_id instance_id = instance_id or self.instance_id redirect_uri = red...
551,553
Validate JWT access token expiration. Args: access_token (str): Access token to validate. Defaults to ``None``. leeway (float): Time in seconds to adjust for local clock skew. Defaults to 0. Returns: bool: ``True`` if expired, otherwise ``False``.
def jwt_is_expired(self, access_token=None, leeway=0): if access_token is not None: exp = self._decode_exp(access_token) else: exp = self.jwt_exp now = time() if exp < (now - leeway): return True return False
551,555
Refresh access and refresh tokens. Args: access_token (str): Access token to refresh. Defaults to ``None``. Returns: str: Refreshed access token.
def refresh(self, access_token=None, **kwargs): if not self.token_lock.locked(): with self.token_lock: if access_token == self.access_token or access_token is None: if self.developer_token is not None: r = self._httpclient.request(...
551,556
Parameters: session (HTTPClient): :class:`~pancloud.httpclient.HTTPClient` object. Defaults to ``None``. url (str): URL to send API requests to. Later combined with ``port`` and :meth:`~request` ``path`` parameter. Args: **kwargs: Supported :class:`~pancloud.httpclient.HTTPC...
def __init__(self, **kwargs): self.kwargs = kwargs.copy() # used for __repr__ self.session = kwargs.pop('session', None) self._httpclient = self.session or HTTPClient(**kwargs) self.url = self._httpclient.url self._debug = logging.getLogger(__name__).debug
551,559
Fetch credential from credentials file. Args: credential (str): Credential to fetch. profile (str): Credentials profile. Defaults to ``'default'``. Returns: str, None: Fetched credential or ``None``.
def fetch_credential(self, credential=None, profile=None): q = self.db.get(self.query.profile == profile) if q is not None: return q.get(credential)
551,567