repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
phac-nml/sistr_cmd | sistr/src/parsers.py | parse_fasta | def parse_fasta(filepath):
'''
Parse a fasta file returning a generator yielding tuples of fasta headers to sequences.
Note:
This function should give equivalent results to SeqIO from BioPython
.. code-block:: python
from Bio import SeqIO
# biopython to dict of hea... | python | def parse_fasta(filepath):
'''
Parse a fasta file returning a generator yielding tuples of fasta headers to sequences.
Note:
This function should give equivalent results to SeqIO from BioPython
.. code-block:: python
from Bio import SeqIO
# biopython to dict of hea... | [
"def",
"parse_fasta",
"(",
"filepath",
")",
":",
"with",
"open",
"(",
"filepath",
",",
"'r'",
")",
"as",
"f",
":",
"seqs",
"=",
"[",
"]",
"header",
"=",
"''",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"li... | Parse a fasta file returning a generator yielding tuples of fasta headers to sequences.
Note:
This function should give equivalent results to SeqIO from BioPython
.. code-block:: python
from Bio import SeqIO
# biopython to dict of header-seq
hseqs_bio = {r.desc... | [
"Parse",
"a",
"fasta",
"file",
"returning",
"a",
"generator",
"yielding",
"tuples",
"of",
"fasta",
"headers",
"to",
"sequences",
"."
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/parsers.py#L22-L61 |
phac-nml/sistr_cmd | sistr/src/parsers.py | fasta_format_check | def fasta_format_check(fasta_path, logger):
"""
Check that a file is valid FASTA format.
- First non-blank line needs to begin with a '>' header character.
- Sequence can only contain valid IUPAC nucleotide characters
Args:
fasta_str (str): FASTA file contents string
Raises:
... | python | def fasta_format_check(fasta_path, logger):
"""
Check that a file is valid FASTA format.
- First non-blank line needs to begin with a '>' header character.
- Sequence can only contain valid IUPAC nucleotide characters
Args:
fasta_str (str): FASTA file contents string
Raises:
... | [
"def",
"fasta_format_check",
"(",
"fasta_path",
",",
"logger",
")",
":",
"header_count",
"=",
"0",
"line_count",
"=",
"1",
"nt_count",
"=",
"0",
"with",
"open",
"(",
"fasta_path",
")",
"as",
"f",
":",
"for",
"l",
"in",
"f",
":",
"l",
"=",
"l",
".",
... | Check that a file is valid FASTA format.
- First non-blank line needs to begin with a '>' header character.
- Sequence can only contain valid IUPAC nucleotide characters
Args:
fasta_str (str): FASTA file contents string
Raises:
Exception: If invalid FASTA format | [
"Check",
"that",
"a",
"file",
"is",
"valid",
"FASTA",
"format",
"."
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/parsers.py#L64-L110 |
phac-nml/sistr_cmd | sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py | seq_int_arr | def seq_int_arr(seqs):
"""Convert list of ACGT strings to matix of 1-4 ints
Args:
seqs (list of str): nucleotide sequences with only 'ACGT' characters
Returns:
numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T
str: nucleotide sequence string
... | python | def seq_int_arr(seqs):
"""Convert list of ACGT strings to matix of 1-4 ints
Args:
seqs (list of str): nucleotide sequences with only 'ACGT' characters
Returns:
numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T
str: nucleotide sequence string
... | [
"def",
"seq_int_arr",
"(",
"seqs",
")",
":",
"return",
"np",
".",
"array",
"(",
"[",
"[",
"NT_TO_INT",
"[",
"c",
"]",
"for",
"c",
"in",
"x",
".",
"upper",
"(",
")",
"]",
"for",
"x",
"in",
"seqs",
"]",
")"
] | Convert list of ACGT strings to matix of 1-4 ints
Args:
seqs (list of str): nucleotide sequences with only 'ACGT' characters
Returns:
numpy.array of int: matrix of integers from 1 to 4 inclusive representing A, C, G, and T
str: nucleotide sequence string | [
"Convert",
"list",
"of",
"ACGT",
"strings",
"to",
"matix",
"of",
"1",
"-",
"4",
"ints"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L19-L29 |
phac-nml/sistr_cmd | sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py | group_alleles_by_start_end_Xbp | def group_alleles_by_start_end_Xbp(arr, bp=28):
"""Group alleles by matching ends
Args:
arr (numpy.array): 2D int matrix of alleles
bp (int): length of ends to group by
Returns:
dict of lists: key of start + end strings to list of indices of alleles with matching ends
"""
s... | python | def group_alleles_by_start_end_Xbp(arr, bp=28):
"""Group alleles by matching ends
Args:
arr (numpy.array): 2D int matrix of alleles
bp (int): length of ends to group by
Returns:
dict of lists: key of start + end strings to list of indices of alleles with matching ends
"""
s... | [
"def",
"group_alleles_by_start_end_Xbp",
"(",
"arr",
",",
"bp",
"=",
"28",
")",
":",
"starts",
"=",
"arr",
"[",
":",
",",
"0",
":",
"bp",
"]",
"ends",
"=",
"arr",
"[",
":",
",",
"-",
"bp",
":",
"]",
"starts_ends_idxs",
"=",
"defaultdict",
"(",
"lis... | Group alleles by matching ends
Args:
arr (numpy.array): 2D int matrix of alleles
bp (int): length of ends to group by
Returns:
dict of lists: key of start + end strings to list of indices of alleles with matching ends | [
"Group",
"alleles",
"by",
"matching",
"ends"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L32-L52 |
phac-nml/sistr_cmd | sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py | allele_clusters | def allele_clusters(dists, t=0.025):
"""Flat clusters from distance matrix
Args:
dists (numpy.array): pdist distance matrix
t (float): fcluster (tree cutting) distance threshold
Returns:
dict of lists: cluster number to list of indices of distances in cluster
"""
clusters =... | python | def allele_clusters(dists, t=0.025):
"""Flat clusters from distance matrix
Args:
dists (numpy.array): pdist distance matrix
t (float): fcluster (tree cutting) distance threshold
Returns:
dict of lists: cluster number to list of indices of distances in cluster
"""
clusters =... | [
"def",
"allele_clusters",
"(",
"dists",
",",
"t",
"=",
"0.025",
")",
":",
"clusters",
"=",
"fcluster",
"(",
"linkage",
"(",
"dists",
")",
",",
"0.025",
",",
"criterion",
"=",
"'distance'",
")",
"cluster_idx",
"=",
"defaultdict",
"(",
"list",
")",
"for",
... | Flat clusters from distance matrix
Args:
dists (numpy.array): pdist distance matrix
t (float): fcluster (tree cutting) distance threshold
Returns:
dict of lists: cluster number to list of indices of distances in cluster | [
"Flat",
"clusters",
"from",
"distance",
"matrix"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L55-L69 |
phac-nml/sistr_cmd | sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py | min_row_dist_sum_idx | def min_row_dist_sum_idx(dists):
"""Find the index of the row with the minimum row distance sum
This should return the index of the row index with the least distance overall
to all other rows.
Args:
dists (np.array): must be square distance matrix
Returns:
int: index of row wit... | python | def min_row_dist_sum_idx(dists):
"""Find the index of the row with the minimum row distance sum
This should return the index of the row index with the least distance overall
to all other rows.
Args:
dists (np.array): must be square distance matrix
Returns:
int: index of row wit... | [
"def",
"min_row_dist_sum_idx",
"(",
"dists",
")",
":",
"row_sums",
"=",
"np",
".",
"apply_along_axis",
"(",
"arr",
"=",
"dists",
",",
"axis",
"=",
"0",
",",
"func1d",
"=",
"np",
".",
"sum",
")",
"return",
"row_sums",
".",
"argmin",
"(",
")"
] | Find the index of the row with the minimum row distance sum
This should return the index of the row index with the least distance overall
to all other rows.
Args:
dists (np.array): must be square distance matrix
Returns:
int: index of row with min dist row sum | [
"Find",
"the",
"index",
"of",
"the",
"row",
"with",
"the",
"minimum",
"row",
"distance",
"sum"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L84-L97 |
phac-nml/sistr_cmd | sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py | find_centroid_alleles | def find_centroid_alleles(alleles, bp=28, t=0.025):
"""Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering
Workflow for finding centroid alleles:
- grouping by size (e.g. 100bp, 101bp, 103bp, etc)
- then grouped by `bp` nucleotides at end... | python | def find_centroid_alleles(alleles, bp=28, t=0.025):
"""Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering
Workflow for finding centroid alleles:
- grouping by size (e.g. 100bp, 101bp, 103bp, etc)
- then grouped by `bp` nucleotides at end... | [
"def",
"find_centroid_alleles",
"(",
"alleles",
",",
"bp",
"=",
"28",
",",
"t",
"=",
"0.025",
")",
":",
"centroid_alleles",
"=",
"set",
"(",
")",
"len_allele",
"=",
"group_alleles_by_size",
"(",
"alleles",
")",
"for",
"length",
",",
"seqs",
"in",
"len_alle... | Reduce list of alleles to set of centroid alleles based on size grouping, ends matching and hierarchical clustering
Workflow for finding centroid alleles:
- grouping by size (e.g. 100bp, 101bp, 103bp, etc)
- then grouped by `bp` nucleotides at ends matching
- size and ends grouped alleles hierarchical... | [
"Reduce",
"list",
"of",
"alleles",
"to",
"set",
"of",
"centroid",
"alleles",
"based",
"on",
"size",
"grouping",
"ends",
"matching",
"and",
"hierarchical",
"clustering"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/centroid_cgmlst_alleles.py#L112-L169 |
phac-nml/sistr_cmd | sistr/src/mash.py | mash_dist_trusted | def mash_dist_trusted(fasta_path):
"""
Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB.
Args:
mash_bin (str): Mash binary path
Returns:
(str): Mash STDOUT string
"""
args = [MASH_BIN,
'dist',
MASH_SKETCH_FILE,
fasta_... | python | def mash_dist_trusted(fasta_path):
"""
Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB.
Args:
mash_bin (str): Mash binary path
Returns:
(str): Mash STDOUT string
"""
args = [MASH_BIN,
'dist',
MASH_SKETCH_FILE,
fasta_... | [
"def",
"mash_dist_trusted",
"(",
"fasta_path",
")",
":",
"args",
"=",
"[",
"MASH_BIN",
",",
"'dist'",
",",
"MASH_SKETCH_FILE",
",",
"fasta_path",
"]",
"p",
"=",
"Popen",
"(",
"args",
",",
"stderr",
"=",
"PIPE",
",",
"stdout",
"=",
"PIPE",
")",
"(",
"st... | Compute Mash distances of sketch file of genome fasta to RefSeq sketch DB.
Args:
mash_bin (str): Mash binary path
Returns:
(str): Mash STDOUT string | [
"Compute",
"Mash",
"distances",
"of",
"sketch",
"file",
"of",
"genome",
"fasta",
"to",
"RefSeq",
"sketch",
"DB",
"."
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/mash.py#L14-L34 |
phac-nml/sistr_cmd | sistr/src/cgmlst/extras/hclust_cutree.py | nr_profiles | def nr_profiles(arr, genomes):
"""
Get a condensed cgMLST pairwise distance matrix for specified Genomes_
where condensed means redundant cgMLST profiles are only represented once in the distance matrix.
Args:
user_name (list): List of Genome_ names to retrieve condensed distance matrix for
... | python | def nr_profiles(arr, genomes):
"""
Get a condensed cgMLST pairwise distance matrix for specified Genomes_
where condensed means redundant cgMLST profiles are only represented once in the distance matrix.
Args:
user_name (list): List of Genome_ names to retrieve condensed distance matrix for
... | [
"def",
"nr_profiles",
"(",
"arr",
",",
"genomes",
")",
":",
"gs_collapse",
"=",
"[",
"]",
"genome_idx_dict",
"=",
"{",
"}",
"indices",
"=",
"[",
"]",
"patt_dict",
"=",
"{",
"}",
"for",
"i",
",",
"g",
"in",
"enumerate",
"(",
"genomes",
")",
":",
"p"... | Get a condensed cgMLST pairwise distance matrix for specified Genomes_
where condensed means redundant cgMLST profiles are only represented once in the distance matrix.
Args:
user_name (list): List of Genome_ names to retrieve condensed distance matrix for
Returns:
(numpy.array, list): tup... | [
"Get",
"a",
"condensed",
"cgMLST",
"pairwise",
"distance",
"matrix",
"for",
"specified",
"Genomes_",
"where",
"condensed",
"means",
"redundant",
"cgMLST",
"profiles",
"are",
"only",
"represented",
"once",
"in",
"the",
"distance",
"matrix",
"."
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/extras/hclust_cutree.py#L19-L45 |
phac-nml/sistr_cmd | sistr/src/serovar_prediction/__init__.py | overall_serovar_call | def overall_serovar_call(serovar_prediction, antigen_predictor):
"""
Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or lis... | python | def overall_serovar_call(serovar_prediction, antigen_predictor):
"""
Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or lis... | [
"def",
"overall_serovar_call",
"(",
"serovar_prediction",
",",
"antigen_predictor",
")",
":",
"assert",
"isinstance",
"(",
"serovar_prediction",
",",
"SerovarPrediction",
")",
"assert",
"isinstance",
"(",
"antigen_predictor",
",",
"SerovarPredictor",
")",
"h1",
"=",
"... | Predict serovar from cgMLST cluster membership analysis and antigen BLAST results.
SerovarPrediction object is assigned H1, H2 and Serogroup from the antigen BLAST results.
Antigen BLAST results will predict a particular serovar or list of serovars, however,
the cgMLST membership may be able to help narrow ... | [
"Predict",
"serovar",
"from",
"cgMLST",
"cluster",
"membership",
"analysis",
"and",
"antigen",
"BLAST",
"results",
".",
"SerovarPrediction",
"object",
"is",
"assigned",
"H1",
"H2",
"and",
"Serogroup",
"from",
"the",
"antigen",
"BLAST",
"results",
".",
"Antigen",
... | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/serovar_prediction/__init__.py#L434-L540 |
phac-nml/sistr_cmd | sistr/src/cgmlst/__init__.py | process_cgmlst_results | def process_cgmlst_results(df):
"""Append informative fields to cgMLST330 BLAST results DataFrame
The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format.
The `qseqid` parsed allele numbers and marker names are appended as new fields.
`is_perfect` column contai... | python | def process_cgmlst_results(df):
"""Append informative fields to cgMLST330 BLAST results DataFrame
The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format.
The `qseqid` parsed allele numbers and marker names are appended as new fields.
`is_perfect` column contai... | [
"def",
"process_cgmlst_results",
"(",
"df",
")",
":",
"assert",
"isinstance",
"(",
"df",
",",
"pd",
".",
"DataFrame",
")",
"markers",
"=",
"[",
"]",
"alleles",
"=",
"[",
"]",
"for",
"x",
"in",
"df",
"[",
"'qseqid'",
"]",
":",
"marker",
",",
"allele",... | Append informative fields to cgMLST330 BLAST results DataFrame
The `qseqid` column must contain cgMLST330 query IDs with `{marker name}|{allele number}` format.
The `qseqid` parsed allele numbers and marker names are appended as new fields.
`is_perfect` column contains boolean values for whether an allele... | [
"Append",
"informative",
"fields",
"to",
"cgMLST330",
"BLAST",
"results",
"DataFrame"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L40-L82 |
phac-nml/sistr_cmd | sistr/src/cgmlst/__init__.py | alleles_to_retrieve | def alleles_to_retrieve(df):
"""Alleles to retrieve from genome fasta
Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be
retrieved from the genome contig.
Args:
df (pandas.DataFrame): blastn results dataframe
Returns:
{str:... | python | def alleles_to_retrieve(df):
"""Alleles to retrieve from genome fasta
Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be
retrieved from the genome contig.
Args:
df (pandas.DataFrame): blastn results dataframe
Returns:
{str:... | [
"def",
"alleles_to_retrieve",
"(",
"df",
")",
":",
"contig_blastn_records",
"=",
"defaultdict",
"(",
"list",
")",
"markers",
"=",
"df",
".",
"marker",
".",
"unique",
"(",
")",
"for",
"m",
"in",
"markers",
":",
"dfsub",
"=",
"df",
"[",
"df",
".",
"marke... | Alleles to retrieve from genome fasta
Get a dict of the genome fasta contig title to a list of blastn results of the allele sequences that must be
retrieved from the genome contig.
Args:
df (pandas.DataFrame): blastn results dataframe
Returns:
{str:[pandas.Series]}: dict of contig tit... | [
"Alleles",
"to",
"retrieve",
"from",
"genome",
"fasta"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L85-L106 |
phac-nml/sistr_cmd | sistr/src/cgmlst/__init__.py | matches_to_marker_results | def matches_to_marker_results(df):
"""Perfect BLAST matches to marker results dict
Parse perfect BLAST matches to marker results dict.
Args:
df (pandas.DataFrame): DataFrame of perfect BLAST matches
Returns:
dict: cgMLST330 marker names to matching allele numbers
"""
assert i... | python | def matches_to_marker_results(df):
"""Perfect BLAST matches to marker results dict
Parse perfect BLAST matches to marker results dict.
Args:
df (pandas.DataFrame): DataFrame of perfect BLAST matches
Returns:
dict: cgMLST330 marker names to matching allele numbers
"""
assert i... | [
"def",
"matches_to_marker_results",
"(",
"df",
")",
":",
"assert",
"isinstance",
"(",
"df",
",",
"pd",
".",
"DataFrame",
")",
"from",
"collections",
"import",
"defaultdict",
"d",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"idx",
",",
"row",
"in",
"df",
... | Perfect BLAST matches to marker results dict
Parse perfect BLAST matches to marker results dict.
Args:
df (pandas.DataFrame): DataFrame of perfect BLAST matches
Returns:
dict: cgMLST330 marker names to matching allele numbers | [
"Perfect",
"BLAST",
"matches",
"to",
"marker",
"results",
"dict"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L186-L234 |
phac-nml/sistr_cmd | sistr/src/cgmlst/__init__.py | cgmlst_subspecies_call | def cgmlst_subspecies_call(df_relatives):
"""Call Salmonella subspecies based on cgMLST results
This method attempts to find the majority subspecies type within curated
public genomes above a cgMLST allelic profile distance threshold.
Note:
``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cg... | python | def cgmlst_subspecies_call(df_relatives):
"""Call Salmonella subspecies based on cgMLST results
This method attempts to find the majority subspecies type within curated
public genomes above a cgMLST allelic profile distance threshold.
Note:
``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cg... | [
"def",
"cgmlst_subspecies_call",
"(",
"df_relatives",
")",
":",
"closest_distance",
"=",
"df_relatives",
"[",
"'distance'",
"]",
".",
"min",
"(",
")",
"if",
"closest_distance",
">",
"CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD",
":",
"logging",
".",
"warning",
"(",
"'Mi... | Call Salmonella subspecies based on cgMLST results
This method attempts to find the majority subspecies type within curated
public genomes above a cgMLST allelic profile distance threshold.
Note:
``CGMLST_SUBSPECIATION_DISTANCE_THRESHOLD`` is the cgMLST distance
threshold used to determine... | [
"Call",
"Salmonella",
"subspecies",
"based",
"on",
"cgMLST",
"results"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L262-L300 |
phac-nml/sistr_cmd | sistr/src/cgmlst/__init__.py | run_cgmlst | def run_cgmlst(blast_runner, full=False):
"""Perform in silico cgMLST on an input genome
Args:
blast_runner (sistr.src.blast_wrapper.BlastRunner): blastn runner object with genome fasta initialized
Returns:
dict: cgMLST ref genome match, distance to closest ref genome, subspecies and serov... | python | def run_cgmlst(blast_runner, full=False):
"""Perform in silico cgMLST on an input genome
Args:
blast_runner (sistr.src.blast_wrapper.BlastRunner): blastn runner object with genome fasta initialized
Returns:
dict: cgMLST ref genome match, distance to closest ref genome, subspecies and serov... | [
"def",
"run_cgmlst",
"(",
"blast_runner",
",",
"full",
"=",
"False",
")",
":",
"from",
"sistr",
".",
"src",
".",
"serovar_prediction",
".",
"constants",
"import",
"genomes_to_serovar",
"df_cgmlst_profiles",
"=",
"ref_cgmlst_profiles",
"(",
")",
"logging",
".",
"... | Perform in silico cgMLST on an input genome
Args:
blast_runner (sistr.src.blast_wrapper.BlastRunner): blastn runner object with genome fasta initialized
Returns:
dict: cgMLST ref genome match, distance to closest ref genome, subspecies and serovar predictions
dict: marker allele match ... | [
"Perform",
"in",
"silico",
"cgMLST",
"on",
"an",
"input",
"genome"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/cgmlst/__init__.py#L303-L413 |
phac-nml/sistr_cmd | sistr/sistr_cmd.py | genome_name_from_fasta_path | def genome_name_from_fasta_path(fasta_path):
"""Extract genome name from fasta filename
Get the filename without directory and remove the file extension.
Example:
With fasta file path ``/path/to/genome_1.fasta``::
fasta_path = '/path/to/genome_1.fasta'
genome_name = genome... | python | def genome_name_from_fasta_path(fasta_path):
"""Extract genome name from fasta filename
Get the filename without directory and remove the file extension.
Example:
With fasta file path ``/path/to/genome_1.fasta``::
fasta_path = '/path/to/genome_1.fasta'
genome_name = genome... | [
"def",
"genome_name_from_fasta_path",
"(",
"fasta_path",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"fasta_path",
")",
"return",
"re",
".",
"sub",
"(",
"r'(\\.fa$)|(\\.fas$)|(\\.fasta$)|(\\.fna$)|(\\.\\w{1,}$)'",
",",
"''",
",",
"filename",
... | Extract genome name from fasta filename
Get the filename without directory and remove the file extension.
Example:
With fasta file path ``/path/to/genome_1.fasta``::
fasta_path = '/path/to/genome_1.fasta'
genome_name = genome_name_from_fasta_path(fasta_path)
print(... | [
"Extract",
"genome",
"name",
"from",
"fasta",
"filename"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/sistr_cmd.py#L234-L254 |
phac-nml/sistr_cmd | sistr/src/blast_wrapper/helpers.py | extend_subj_match_vec | def extend_subj_match_vec(df):
"""
Get the extended clipped (clamped) start and end subject sequence indices
Also get whether each match needs to be reverse complemented and whether each extended match would be truncated by
the end of the subject sequence.
Args:
df (pandas.DataFrame): blas... | python | def extend_subj_match_vec(df):
"""
Get the extended clipped (clamped) start and end subject sequence indices
Also get whether each match needs to be reverse complemented and whether each extended match would be truncated by
the end of the subject sequence.
Args:
df (pandas.DataFrame): blas... | [
"def",
"extend_subj_match_vec",
"(",
"df",
")",
":",
"needs_revcomp",
"=",
"df",
".",
"sstart",
">",
"df",
".",
"send",
"add_to_end",
"=",
"df",
".",
"qlen",
"-",
"df",
".",
"qend",
"add_to_start",
"=",
"df",
".",
"qstart",
"-",
"1",
"ssum2",
"=",
"(... | Get the extended clipped (clamped) start and end subject sequence indices
Also get whether each match needs to be reverse complemented and whether each extended match would be truncated by
the end of the subject sequence.
Args:
df (pandas.DataFrame): blastn results dataframe
Returns:
... | [
"Get",
"the",
"extended",
"clipped",
"(",
"clamped",
")",
"start",
"and",
"end",
"subject",
"sequence",
"indices"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/helpers.py#L10-L42 |
phac-nml/sistr_cmd | sistr/src/writers.py | listattrs | def listattrs(x):
"""Get all instance and class attributes for an object
Get all instance and class attributes for an object except those that start
with "__" (double underscore).
__dict__ of an object only reports the instance attributes while dir()
reports all of the attributes of an ob... | python | def listattrs(x):
"""Get all instance and class attributes for an object
Get all instance and class attributes for an object except those that start
with "__" (double underscore).
__dict__ of an object only reports the instance attributes while dir()
reports all of the attributes of an ob... | [
"def",
"listattrs",
"(",
"x",
")",
":",
"return",
"[",
"attr",
"for",
"attr",
"in",
"dir",
"(",
"x",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"\"__\"",
")",
"and",
"not",
"callable",
"(",
"getattr",
"(",
"x",
",",
"attr",
")",
")",
"]"
] | Get all instance and class attributes for an object
Get all instance and class attributes for an object except those that start
with "__" (double underscore).
__dict__ of an object only reports the instance attributes while dir()
reports all of the attributes of an object including private on... | [
"Get",
"all",
"instance",
"and",
"class",
"attributes",
"for",
"an",
"object",
"Get",
"all",
"instance",
"and",
"class",
"attributes",
"for",
"an",
"object",
"except",
"those",
"that",
"start",
"with",
"__",
"(",
"double",
"underscore",
")",
".",
"__dict__",... | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/writers.py#L5-L22 |
phac-nml/sistr_cmd | sistr/src/writers.py | to_dict | def to_dict(x, depth, exclude_keys=set(), depth_threshold=8):
"""Transform a nested object/dict/list into a regular dict
json.dump(s) and pickle don't like to un/serialize regular Python objects so
this function should handle arbitrarily nested objects to be serialized to
regular string, float, int... | python | def to_dict(x, depth, exclude_keys=set(), depth_threshold=8):
"""Transform a nested object/dict/list into a regular dict
json.dump(s) and pickle don't like to un/serialize regular Python objects so
this function should handle arbitrarily nested objects to be serialized to
regular string, float, int... | [
"def",
"to_dict",
"(",
"x",
",",
"depth",
",",
"exclude_keys",
"=",
"set",
"(",
")",
",",
"depth_threshold",
"=",
"8",
")",
":",
"if",
"x",
"is",
"None",
"or",
"isinstance",
"(",
"x",
",",
"(",
"str",
",",
"int",
",",
"float",
",",
"bool",
")",
... | Transform a nested object/dict/list into a regular dict
json.dump(s) and pickle don't like to un/serialize regular Python objects so
this function should handle arbitrarily nested objects to be serialized to
regular string, float, int, bool, None values.
This is a recursive function so by defa... | [
"Transform",
"a",
"nested",
"object",
"/",
"dict",
"/",
"list",
"into",
"a",
"regular",
"dict",
"json",
".",
"dump",
"(",
"s",
")",
"and",
"pickle",
"don",
"t",
"like",
"to",
"un",
"/",
"serialize",
"regular",
"Python",
"objects",
"so",
"this",
"functi... | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/writers.py#L25-L79 |
phac-nml/sistr_cmd | sistr/src/writers.py | _recur_flatten | def _recur_flatten(key, x, out, sep='.'):
"""Helper function to flatten_dict
Recursively flatten all nested values within a dict
Args:
key (str): parent key
x (object): object to flatten or add to out dict
out (dict): 1D output dict
sep (str): flattened key separato... | python | def _recur_flatten(key, x, out, sep='.'):
"""Helper function to flatten_dict
Recursively flatten all nested values within a dict
Args:
key (str): parent key
x (object): object to flatten or add to out dict
out (dict): 1D output dict
sep (str): flattened key separato... | [
"def",
"_recur_flatten",
"(",
"key",
",",
"x",
",",
"out",
",",
"sep",
"=",
"'.'",
")",
":",
"if",
"x",
"is",
"None",
"or",
"isinstance",
"(",
"x",
",",
"(",
"str",
",",
"int",
",",
"float",
",",
"bool",
")",
")",
":",
"out",
"[",
"key",
"]",... | Helper function to flatten_dict
Recursively flatten all nested values within a dict
Args:
key (str): parent key
x (object): object to flatten or add to out dict
out (dict): 1D output dict
sep (str): flattened key separator string
Returns:
dict: flattene... | [
"Helper",
"function",
"to",
"flatten_dict",
"Recursively",
"flatten",
"all",
"nested",
"values",
"within",
"a",
"dict",
"Args",
":",
"key",
"(",
"str",
")",
":",
"parent",
"key",
"x",
"(",
"object",
")",
":",
"object",
"to",
"flatten",
"or",
"add",
"to",... | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/writers.py#L82-L107 |
phac-nml/sistr_cmd | sistr/src/writers.py | flatten_dict | def flatten_dict(x):
"""Flatten a dict
Flatten an arbitrarily nested dict as output by to_dict
.. note::
Keys in the flattened dict may get very long.
Args:
x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values
Retu... | python | def flatten_dict(x):
"""Flatten a dict
Flatten an arbitrarily nested dict as output by to_dict
.. note::
Keys in the flattened dict may get very long.
Args:
x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values
Retu... | [
"def",
"flatten_dict",
"(",
"x",
")",
":",
"out",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"x",
".",
"items",
"(",
")",
":",
"out",
"=",
"_recur_flatten",
"(",
"k",
",",
"v",
",",
"out",
")",
"return",
"out"
] | Flatten a dict
Flatten an arbitrarily nested dict as output by to_dict
.. note::
Keys in the flattened dict may get very long.
Args:
x (dict): Arbitrarily nested dict (maybe resembling a tree) with literal/scalar leaf values
Returns:
dict: flattened... | [
"Flatten",
"a",
"dict",
"Flatten",
"an",
"arbitrarily",
"nested",
"dict",
"as",
"output",
"by",
"to_dict",
"..",
"note",
"::",
"Keys",
"in",
"the",
"flattened",
"dict",
"may",
"get",
"very",
"long",
".",
"Args",
":",
"x",
"(",
"dict",
")",
":",
"Arbitr... | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/writers.py#L110-L128 |
phac-nml/sistr_cmd | sistr/src/blast_wrapper/__init__.py | BlastReader.df_first_row_to_dict | def df_first_row_to_dict(df):
"""First DataFrame row to list of dict
Args:
df (pandas.DataFrame): A DataFrame with at least one row
Returns:
A list of dict that looks like:
[{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]
from a DataFrame that looks... | python | def df_first_row_to_dict(df):
"""First DataFrame row to list of dict
Args:
df (pandas.DataFrame): A DataFrame with at least one row
Returns:
A list of dict that looks like:
[{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]
from a DataFrame that looks... | [
"def",
"df_first_row_to_dict",
"(",
"df",
")",
":",
"if",
"df",
"is",
"not",
"None",
":",
"return",
"[",
"dict",
"(",
"r",
")",
"for",
"i",
",",
"r",
"in",
"df",
".",
"head",
"(",
"1",
")",
".",
"iterrows",
"(",
")",
"]",
"[",
"0",
"]"
] | First DataFrame row to list of dict
Args:
df (pandas.DataFrame): A DataFrame with at least one row
Returns:
A list of dict that looks like:
[{'C1': 'x'}, {'C2': 'y'}, {'C3': 'z'}]
from a DataFrame that looks like:
C1 C2 C3
... | [
"First",
"DataFrame",
"row",
"to",
"list",
"of",
"dict"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/__init__.py#L200-L219 |
phac-nml/sistr_cmd | sistr/src/blast_wrapper/__init__.py | BlastReader.is_blast_result_trunc | def is_blast_result_trunc(qstart, qend, sstart, send, qlen, slen):
"""Check if a query sequence is truncated by the end of a subject sequence
Args:
qstart (int): Query sequence start index
qend (int): Query sequence end index
sstart (int): Subject sequence start inde... | python | def is_blast_result_trunc(qstart, qend, sstart, send, qlen, slen):
"""Check if a query sequence is truncated by the end of a subject sequence
Args:
qstart (int): Query sequence start index
qend (int): Query sequence end index
sstart (int): Subject sequence start inde... | [
"def",
"is_blast_result_trunc",
"(",
"qstart",
",",
"qend",
",",
"sstart",
",",
"send",
",",
"qlen",
",",
"slen",
")",
":",
"q_match_len",
"=",
"abs",
"(",
"qstart",
"-",
"qend",
")",
"+",
"1",
"s_max",
"=",
"max",
"(",
"sstart",
",",
"send",
")",
... | Check if a query sequence is truncated by the end of a subject sequence
Args:
qstart (int): Query sequence start index
qend (int): Query sequence end index
sstart (int): Subject sequence start index
send (int): Subject sequence end index
qlen (int): Q... | [
"Check",
"if",
"a",
"query",
"sequence",
"is",
"truncated",
"by",
"the",
"end",
"of",
"a",
"subject",
"sequence"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/__init__.py#L222-L239 |
phac-nml/sistr_cmd | sistr/src/blast_wrapper/__init__.py | BlastReader.trunc | def trunc(qstart, qend, sstart, send, qlen, slen):
"""Check if a query sequence is truncated by the end of a subject sequence
Args:
qstart (int pandas.Series): Query sequence start index
qend (int pandas.Series): Query sequence end index
sstart (int pandas.Series): S... | python | def trunc(qstart, qend, sstart, send, qlen, slen):
"""Check if a query sequence is truncated by the end of a subject sequence
Args:
qstart (int pandas.Series): Query sequence start index
qend (int pandas.Series): Query sequence end index
sstart (int pandas.Series): S... | [
"def",
"trunc",
"(",
"qstart",
",",
"qend",
",",
"sstart",
",",
"send",
",",
"qlen",
",",
"slen",
")",
":",
"ssum2",
"=",
"(",
"send",
"+",
"sstart",
")",
"/",
"2.0",
"sabs2",
"=",
"np",
".",
"abs",
"(",
"send",
"-",
"sstart",
")",
"/",
"2.0",
... | Check if a query sequence is truncated by the end of a subject sequence
Args:
qstart (int pandas.Series): Query sequence start index
qend (int pandas.Series): Query sequence end index
sstart (int pandas.Series): Subject sequence start index
send (int pandas.Serie... | [
"Check",
"if",
"a",
"query",
"sequence",
"is",
"truncated",
"by",
"the",
"end",
"of",
"a",
"subject",
"sequence"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/__init__.py#L242-L261 |
phac-nml/sistr_cmd | sistr/src/blast_wrapper/__init__.py | BlastReader.perfect_matches | def perfect_matches(self):
"""
Return pandas DataFrame with perfect BLAST matches (100% identity and coverage)
Returns:
pandas.DataFrame or None: DataFrame of perfect BLAST matches or None if no perfect matches exist
"""
if self.is_missing:
return None
... | python | def perfect_matches(self):
"""
Return pandas DataFrame with perfect BLAST matches (100% identity and coverage)
Returns:
pandas.DataFrame or None: DataFrame of perfect BLAST matches or None if no perfect matches exist
"""
if self.is_missing:
return None
... | [
"def",
"perfect_matches",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_missing",
":",
"return",
"None",
"df_perfect_matches",
"=",
"self",
".",
"df",
"[",
"(",
"self",
".",
"df",
"[",
"'coverage'",
"]",
"==",
"1.0",
")",
"&",
"(",
"self",
".",
"df",... | Return pandas DataFrame with perfect BLAST matches (100% identity and coverage)
Returns:
pandas.DataFrame or None: DataFrame of perfect BLAST matches or None if no perfect matches exist | [
"Return",
"pandas",
"DataFrame",
"with",
"perfect",
"BLAST",
"matches",
"(",
"100%",
"identity",
"and",
"coverage",
")"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/__init__.py#L264-L277 |
phac-nml/sistr_cmd | sistr/src/blast_wrapper/__init__.py | BlastReader.top_result | def top_result(self):
"""Return top `blastn` result
Try to find a 100% identity and coverage result (perfect match).
If one does not exist, then retrieve the result with the highest bitscore.
Returns:
Ordered dict of BLASTN results or None if no BLASTN results generated
... | python | def top_result(self):
"""Return top `blastn` result
Try to find a 100% identity and coverage result (perfect match).
If one does not exist, then retrieve the result with the highest bitscore.
Returns:
Ordered dict of BLASTN results or None if no BLASTN results generated
... | [
"def",
"top_result",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_missing",
":",
"return",
"None",
"df_perfect_matches",
"=",
"self",
".",
"df",
"[",
"(",
"self",
".",
"df",
"[",
"'coverage'",
"]",
"==",
"1.0",
")",
"&",
"(",
"self",
".",
"df",
"[... | Return top `blastn` result
Try to find a 100% identity and coverage result (perfect match).
If one does not exist, then retrieve the result with the highest bitscore.
Returns:
Ordered dict of BLASTN results or None if no BLASTN results generated | [
"Return",
"top",
"blastn",
"result",
"Try",
"to",
"find",
"a",
"100%",
"identity",
"and",
"coverage",
"result",
"(",
"perfect",
"match",
")",
".",
"If",
"one",
"does",
"not",
"exist",
"then",
"retrieve",
"the",
"result",
"with",
"the",
"highest",
"bitscore... | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/src/blast_wrapper/__init__.py#L281-L309 |
phac-nml/sistr_cmd | sistr/misc/add_ref_genomes.py | sketch_fasta | def sketch_fasta(fasta_path, outdir):
"""Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path
"""
... | python | def sketch_fasta(fasta_path, outdir):
"""Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path
"""
... | [
"def",
"sketch_fasta",
"(",
"fasta_path",
",",
"outdir",
")",
":",
"genome_name",
"=",
"genome_name_from_fasta_path",
"(",
"fasta_path",
")",
"outpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outdir",
",",
"genome_name",
")",
"args",
"=",
"[",
"'mash'",
... | Create a Mash sketch from an input fasta file
Args:
fasta_path (str): input fasta file path. Genome name in fasta filename
outdir (str): output directory path to write Mash sketch file to
Returns:
str: output Mash sketch file path | [
"Create",
"a",
"Mash",
"sketch",
"from",
"an",
"input",
"fasta",
"file"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/misc/add_ref_genomes.py#L65-L85 |
phac-nml/sistr_cmd | sistr/misc/add_ref_genomes.py | merge_sketches | def merge_sketches(outdir, sketch_paths):
"""Merge new Mash sketches with current Mash sketches
Args:
outdir (str): output directory to write merged Mash sketch file
sketch_paths (list of str): Mash sketch file paths for input fasta files
Returns:
str: output path for Mash sketch f... | python | def merge_sketches(outdir, sketch_paths):
"""Merge new Mash sketches with current Mash sketches
Args:
outdir (str): output directory to write merged Mash sketch file
sketch_paths (list of str): Mash sketch file paths for input fasta files
Returns:
str: output path for Mash sketch f... | [
"def",
"merge_sketches",
"(",
"outdir",
",",
"sketch_paths",
")",
":",
"merge_sketch_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"outdir",
",",
"'sistr.msh'",
")",
"args",
"=",
"[",
"'mash'",
",",
"'paste'",
",",
"merge_sketch_path",
"]",
"for",
"x",
... | Merge new Mash sketches with current Mash sketches
Args:
outdir (str): output directory to write merged Mash sketch file
sketch_paths (list of str): Mash sketch file paths for input fasta files
Returns:
str: output path for Mash sketch file with new and old sketches | [
"Merge",
"new",
"Mash",
"sketches",
"with",
"current",
"Mash",
"sketches"
] | train | https://github.com/phac-nml/sistr_cmd/blob/4630fae72439723b354a94b94fbe76ad2f9f6295/sistr/misc/add_ref_genomes.py#L88-L107 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.delete | def delete(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.delete`.
If an exception occurs in either the cache or backing store, all are
passing on.
"""
self._dstore.delete(key)
self.cache.delete(key) | python | def delete(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.delete`.
If an exception occurs in either the cache or backing store, all are
passing on.
"""
self._dstore.delete(key)
self.cache.delete(key) | [
"def",
"delete",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_dstore",
".",
"delete",
"(",
"key",
")",
"self",
".",
"cache",
".",
"delete",
"(",
"key",
")"
] | Implementation of :meth:`~simplekv.KeyValueStore.delete`.
If an exception occurs in either the cache or backing store, all are
passing on. | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"delete",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L30-L37 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.get | def get(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.get`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted directly.
... | python | def get(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.get`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted directly.
... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"return",
"self",
".",
"cache",
".",
"get",
"(",
"key",
")",
"except",
"KeyError",
":",
"# cache miss or error, retrieve from backend",
"data",
"=",
"self",
".",
"_dstore",
".",
"get",
"(",
"ke... | Implementation of :meth:`~simplekv.KeyValueStore.get`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted directly.
It is possible for a c... | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"get",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L39-L62 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.get_file | def get_file(self, key, file):
"""Implementation of :meth:`~simplekv.KeyValueStore.get_file`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the retrieval cannot
proceed: If ``file`` was an op... | python | def get_file(self, key, file):
"""Implementation of :meth:`~simplekv.KeyValueStore.get_file`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the retrieval cannot
proceed: If ``file`` was an op... | [
"def",
"get_file",
"(",
"self",
",",
"key",
",",
"file",
")",
":",
"try",
":",
"return",
"self",
".",
"cache",
".",
"get_file",
"(",
"key",
",",
"file",
")",
"except",
"KeyError",
":",
"# cache miss, load into cache",
"fp",
"=",
"self",
".",
"_dstore",
... | Implementation of :meth:`~simplekv.KeyValueStore.get_file`.
If a cache miss occurs, the value is retrieved, stored in the cache and
returned.
If the cache raises an :exc:`~exceptions.IOError`, the retrieval cannot
proceed: If ``file`` was an open file, data maybe been written to it
... | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"get_file",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L64-L85 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.open | def open(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.open`.
If a cache miss occurs, the value is retrieved, stored in the cache,
then then another open is issued on the cache.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the b... | python | def open(self, key):
"""Implementation of :meth:`~simplekv.KeyValueStore.open`.
If a cache miss occurs, the value is retrieved, stored in the cache,
then then another open is issued on the cache.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the b... | [
"def",
"open",
"(",
"self",
",",
"key",
")",
":",
"try",
":",
"return",
"self",
".",
"cache",
".",
"open",
"(",
"key",
")",
"except",
"KeyError",
":",
"# cache miss, load into cache",
"fp",
"=",
"self",
".",
"_dstore",
".",
"open",
"(",
"key",
")",
"... | Implementation of :meth:`~simplekv.KeyValueStore.open`.
If a cache miss occurs, the value is retrieved, stored in the cache,
then then another open is issued on the cache.
If the cache raises an :exc:`~exceptions.IOError`, the cache is
ignored, and the backing store is consulted direct... | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"open",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L89-L111 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.copy | def copy(self, source, dest):
"""Implementation of :meth:`~simplekv.CopyMixin.copy`.
Copies the data in the backing store and removes the destination key from the cache,
in case it was already populated.
Does not work when the backing store does not implement copy.
""... | python | def copy(self, source, dest):
"""Implementation of :meth:`~simplekv.CopyMixin.copy`.
Copies the data in the backing store and removes the destination key from the cache,
in case it was already populated.
Does not work when the backing store does not implement copy.
""... | [
"def",
"copy",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"try",
":",
"k",
"=",
"self",
".",
"_dstore",
".",
"copy",
"(",
"source",
",",
"dest",
")",
"finally",
":",
"self",
".",
"cache",
".",
"delete",
"(",
"dest",
")",
"return",
"k"
] | Implementation of :meth:`~simplekv.CopyMixin.copy`.
Copies the data in the backing store and removes the destination key from the cache,
in case it was already populated.
Does not work when the backing store does not implement copy. | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"CopyMixin",
".",
"copy",
".",
"Copies",
"the",
"data",
"in",
"the",
"backing",
"store",
"and",
"removes",
"the",
"destination",
"key",
"from",
"the",
"cache",
"in",
"case",
"it",
"was",
"already"... | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L113-L124 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.put | def put(self, key, data):
"""Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
"""
try:
return self._dstore.pu... | python | def put(self, key, data):
"""Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
"""
try:
return self._dstore.pu... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"data",
")",
":",
"try",
":",
"return",
"self",
".",
"_dstore",
".",
"put",
"(",
"key",
",",
"data",
")",
"finally",
":",
"self",
".",
"cache",
".",
"delete",
"(",
"key",
")"
] | Implementation of :meth:`~simplekv.KeyValueStore.put`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it. | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"put",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L126-L136 |
mbr/simplekv | simplekv/cache.py | CacheDecorator.put_file | def put_file(self, key, file):
"""Implementation of :meth:`~simplekv.KeyValueStore.put_file`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
"""
try:
return self.... | python | def put_file(self, key, file):
"""Implementation of :meth:`~simplekv.KeyValueStore.put_file`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it.
"""
try:
return self.... | [
"def",
"put_file",
"(",
"self",
",",
"key",
",",
"file",
")",
":",
"try",
":",
"return",
"self",
".",
"_dstore",
".",
"put_file",
"(",
"key",
",",
"file",
")",
"finally",
":",
"self",
".",
"cache",
".",
"delete",
"(",
"key",
")"
] | Implementation of :meth:`~simplekv.KeyValueStore.put_file`.
Will store the value in the backing store. After a successful or
unsuccessful store, the cache will be invalidated by deleting the key
from it. | [
"Implementation",
"of",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"put_file",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/cache.py#L138-L148 |
mbr/simplekv | simplekv/__init__.py | KeyValueStore.get_file | def get_file(self, key, file):
"""Write contents of key to file
Like :meth:`.KeyValueStore.put_file`, this method allows backends to
implement a specialized function if data needs to be written to disk or
streamed.
If *file* is a string, contents of *key* are written to a newly... | python | def get_file(self, key, file):
"""Write contents of key to file
Like :meth:`.KeyValueStore.put_file`, this method allows backends to
implement a specialized function if data needs to be written to disk or
streamed.
If *file* is a string, contents of *key* are written to a newly... | [
"def",
"get_file",
"(",
"self",
",",
"key",
",",
"file",
")",
":",
"self",
".",
"_check_valid_key",
"(",
"key",
")",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"return",
"self",
".",
"_get_filename",
"(",
"key",
",",
"file",
")",
"else",
... | Write contents of key to file
Like :meth:`.KeyValueStore.put_file`, this method allows backends to
implement a specialized function if data needs to be written to disk or
streamed.
If *file* is a string, contents of *key* are written to a newly
created file with the filename *f... | [
"Write",
"contents",
"of",
"key",
"to",
"file"
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L77-L100 |
mbr/simplekv | simplekv/__init__.py | KeyValueStore.put_file | def put_file(self, key, file):
"""Store into key from file on disk
Stores data from a source into key. *file* can either be a string,
which will be interpretet as a filename, or an object with a *read()*
method.
If the passed object has a *fileno()* method, it may be used to sp... | python | def put_file(self, key, file):
"""Store into key from file on disk
Stores data from a source into key. *file* can either be a string,
which will be interpretet as a filename, or an object with a *read()*
method.
If the passed object has a *fileno()* method, it may be used to sp... | [
"def",
"put_file",
"(",
"self",
",",
"key",
",",
"file",
")",
":",
"# FIXME: shouldn't we call self._check_valid_key here?",
"if",
"isinstance",
"(",
"file",
",",
"str",
")",
":",
"return",
"self",
".",
"_put_filename",
"(",
"key",
",",
"file",
")",
"else",
... | Store into key from file on disk
Stores data from a source into key. *file* can either be a string,
which will be interpretet as a filename, or an object with a *read()*
method.
If the passed object has a *fileno()* method, it may be used to speed
up the operation.
The... | [
"Store",
"into",
"key",
"from",
"file",
"on",
"disk"
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L152-L179 |
mbr/simplekv | simplekv/__init__.py | KeyValueStore._check_valid_key | def _check_valid_key(self, key):
"""Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
"""
if not isinstance(key, key_type):
raise Va... | python | def _check_valid_key(self, key):
"""Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
"""
if not isinstance(key, key_type):
raise Va... | [
"def",
"_check_valid_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"key_type",
")",
":",
"raise",
"ValueError",
"(",
"'%r is not a valid key type'",
"%",
"key",
")",
"if",
"not",
"VALID_KEY_RE",
".",
"match",
"(",
"ke... | Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked | [
"Checks",
"if",
"a",
"key",
"is",
"valid",
"and",
"raises",
"a",
"ValueError",
"if",
"its",
"not",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L181-L192 |
mbr/simplekv | simplekv/__init__.py | KeyValueStore._get | def _get(self, key):
"""Implementation for :meth:`~simplekv.KeyValueStore.get`. The default
implementation will create a :class:`io.BytesIO`-buffer and then call
:meth:`~simplekv.KeyValueStore._get_file`.
:param key: Key of value to be retrieved
"""
buf = BytesIO()
... | python | def _get(self, key):
"""Implementation for :meth:`~simplekv.KeyValueStore.get`. The default
implementation will create a :class:`io.BytesIO`-buffer and then call
:meth:`~simplekv.KeyValueStore._get_file`.
:param key: Key of value to be retrieved
"""
buf = BytesIO()
... | [
"def",
"_get",
"(",
"self",
",",
"key",
")",
":",
"buf",
"=",
"BytesIO",
"(",
")",
"self",
".",
"_get_file",
"(",
"key",
",",
"buf",
")",
"return",
"buf",
".",
"getvalue",
"(",
")"
] | Implementation for :meth:`~simplekv.KeyValueStore.get`. The default
implementation will create a :class:`io.BytesIO`-buffer and then call
:meth:`~simplekv.KeyValueStore._get_file`.
:param key: Key of value to be retrieved | [
"Implementation",
"for",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"get",
".",
"The",
"default",
"implementation",
"will",
"create",
"a",
":",
"class",
":",
"io",
".",
"BytesIO",
"-",
"buffer",
"and",
"then",
"call",
":",
"meth",
":",
"~s... | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L201-L212 |
mbr/simplekv | simplekv/__init__.py | KeyValueStore._get_file | def _get_file(self, key, file):
"""Write key to file-like object file. Either this method or
:meth:`~simplekv.KeyValueStore._get_filename` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. Note that this method does
not accept strings.
:param key: Key to be retrieved
... | python | def _get_file(self, key, file):
"""Write key to file-like object file. Either this method or
:meth:`~simplekv.KeyValueStore._get_filename` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. Note that this method does
not accept strings.
:param key: Key to be retrieved
... | [
"def",
"_get_file",
"(",
"self",
",",
"key",
",",
"file",
")",
":",
"bufsize",
"=",
"1024",
"*",
"1024",
"# note: we do not use a context manager here or close the source.",
"# the source goes out of scope shortly after, taking care of the issue",
"# this allows us to support file-... | Write key to file-like object file. Either this method or
:meth:`~simplekv.KeyValueStore._get_filename` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. Note that this method does
not accept strings.
:param key: Key to be retrieved
:param file: File-like object to wri... | [
"Write",
"key",
"to",
"file",
"-",
"like",
"object",
"file",
".",
"Either",
"this",
"method",
"or",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"_get_filename",
"will",
"be",
"called",
"by",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore"... | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L214-L238 |
mbr/simplekv | simplekv/__init__.py | KeyValueStore._get_filename | def _get_filename(self, key, filename):
"""Write key to file. Either this method or
:meth:`~simplekv.KeyValueStore._get_file` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. This method only accepts
filenames and will open the file with a mode of ``wb``, then call
:me... | python | def _get_filename(self, key, filename):
"""Write key to file. Either this method or
:meth:`~simplekv.KeyValueStore._get_file` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. This method only accepts
filenames and will open the file with a mode of ``wb``, then call
:me... | [
"def",
"_get_filename",
"(",
"self",
",",
"key",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"dest",
":",
"return",
"self",
".",
"_get_file",
"(",
"key",
",",
"dest",
")"
] | Write key to file. Either this method or
:meth:`~simplekv.KeyValueStore._get_file` will be called by
:meth:`~simplekv.KeyValueStore.get_file`. This method only accepts
filenames and will open the file with a mode of ``wb``, then call
:meth:`~simplekv.KeyValueStore._get_file`.
:p... | [
"Write",
"key",
"to",
"file",
".",
"Either",
"this",
"method",
"or",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"_get_file",
"will",
"be",
"called",
"by",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"get_file",
".",
"This",
"... | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L240-L251 |
mbr/simplekv | simplekv/__init__.py | TimeToLiveMixin.put | def put(self, key, data, ttl_secs=None):
"""Like :meth:`~simplekv.KeyValueStore.put`, but with an additional
parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs... | python | def put(self, key, data, ttl_secs=None):
"""Like :meth:`~simplekv.KeyValueStore.put`, but with an additional
parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs... | [
"def",
"put",
"(",
"self",
",",
"key",
",",
"data",
",",
"ttl_secs",
"=",
"None",
")",
":",
"self",
".",
"_check_valid_key",
"(",
"key",
")",
"if",
"not",
"isinstance",
"(",
"data",
",",
"bytes",
")",
":",
"raise",
"IOError",
"(",
"\"Provided data is n... | Like :meth:`~simplekv.KeyValueStore.put`, but with an additional
parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs`` is invalid.
:raises exceptions.IOError... | [
"Like",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"put",
"but",
"with",
"an",
"additional",
"parameter",
":"
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L384-L398 |
mbr/simplekv | simplekv/__init__.py | TimeToLiveMixin.put_file | def put_file(self, key, file, ttl_secs=None):
"""Like :meth:`~simplekv.KeyValueStore.put_file`, but with an
additional parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ... | python | def put_file(self, key, file, ttl_secs=None):
"""Like :meth:`~simplekv.KeyValueStore.put_file`, but with an
additional parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ... | [
"def",
"put_file",
"(",
"self",
",",
"key",
",",
"file",
",",
"ttl_secs",
"=",
"None",
")",
":",
"if",
"ttl_secs",
"is",
"None",
":",
"ttl_secs",
"=",
"self",
".",
"default_ttl_secs",
"self",
".",
"_check_valid_key",
"(",
"key",
")",
"if",
"isinstance",
... | Like :meth:`~simplekv.KeyValueStore.put_file`, but with an
additional parameter:
:param ttl_secs: Number of seconds until the key expires. See above
for valid values.
:raises exceptions.ValueError: If ``ttl_secs`` is invalid. | [
"Like",
":",
"meth",
":",
"~simplekv",
".",
"KeyValueStore",
".",
"put_file",
"but",
"with",
"an",
"additional",
"parameter",
":"
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L400-L416 |
mbr/simplekv | simplekv/__init__.py | CopyMixin.copy | def copy(self, source, dest):
"""Copies a key. The destination is overwritten if does exist.
:param source: The source key to copy
:param dest: The destination for the copy
:returns: The destination key
:raises: exceptions.ValueError: If the source or target key are not valid
... | python | def copy(self, source, dest):
"""Copies a key. The destination is overwritten if does exist.
:param source: The source key to copy
:param dest: The destination for the copy
:returns: The destination key
:raises: exceptions.ValueError: If the source or target key are not valid
... | [
"def",
"copy",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"self",
".",
"_check_valid_key",
"(",
"source",
")",
"self",
".",
"_check_valid_key",
"(",
"dest",
")",
"return",
"self",
".",
"_copy",
"(",
"source",
",",
"dest",
")"
] | Copies a key. The destination is overwritten if does exist.
:param source: The source key to copy
:param dest: The destination for the copy
:returns: The destination key
:raises: exceptions.ValueError: If the source or target key are not valid
:raises: exceptions.KeyError: If ... | [
"Copies",
"a",
"key",
".",
"The",
"destination",
"is",
"overwritten",
"if",
"does",
"exist",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/__init__.py#L441-L453 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.open | def open(self):
"""Implementation of NAPALM method open."""
try:
if self.transport in ('http', 'https'):
connection = pyeapi.client.connect(
transport=self.transport,
host=self.hostname,
username=self.username,
... | python | def open(self):
"""Implementation of NAPALM method open."""
try:
if self.transport in ('http', 'https'):
connection = pyeapi.client.connect(
transport=self.transport,
host=self.hostname,
username=self.username,
... | [
"def",
"open",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"transport",
"in",
"(",
"'http'",
",",
"'https'",
")",
":",
"connection",
"=",
"pyeapi",
".",
"client",
".",
"connect",
"(",
"transport",
"=",
"self",
".",
"transport",
",",
"host",... | Implementation of NAPALM method open. | [
"Implementation",
"of",
"NAPALM",
"method",
"open",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L91-L118 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.compare_config | def compare_config(self):
"""Implementation of NAPALM method compare_config."""
if self.config_session is None:
return ''
else:
commands = ['show session-config named %s diffs' % self.config_session]
result = self.device.run_commands(commands, encoding='text')... | python | def compare_config(self):
"""Implementation of NAPALM method compare_config."""
if self.config_session is None:
return ''
else:
commands = ['show session-config named %s diffs' % self.config_session]
result = self.device.run_commands(commands, encoding='text')... | [
"def",
"compare_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"config_session",
"is",
"None",
":",
"return",
"''",
"else",
":",
"commands",
"=",
"[",
"'show session-config named %s diffs'",
"%",
"self",
".",
"config_session",
"]",
"result",
"=",
"self",
... | Implementation of NAPALM method compare_config. | [
"Implementation",
"of",
"NAPALM",
"method",
"compare_config",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L178-L188 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.commit_config | def commit_config(self):
"""Implementation of NAPALM method commit_config."""
commands = []
commands.append('copy startup-config flash:rollback-0')
commands.append('configure session {}'.format(self.config_session))
commands.append('commit')
commands.append('write memory'... | python | def commit_config(self):
"""Implementation of NAPALM method commit_config."""
commands = []
commands.append('copy startup-config flash:rollback-0')
commands.append('configure session {}'.format(self.config_session))
commands.append('commit')
commands.append('write memory'... | [
"def",
"commit_config",
"(",
"self",
")",
":",
"commands",
"=",
"[",
"]",
"commands",
".",
"append",
"(",
"'copy startup-config flash:rollback-0'",
")",
"commands",
".",
"append",
"(",
"'configure session {}'",
".",
"format",
"(",
"self",
".",
"config_session",
... | Implementation of NAPALM method commit_config. | [
"Implementation",
"of",
"NAPALM",
"method",
"commit_config",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L190-L199 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.discard_config | def discard_config(self):
"""Implementation of NAPALM method discard_config."""
if self.config_session is not None:
commands = []
commands.append('configure session {}'.format(self.config_session))
commands.append('abort')
self.device.run_commands(commands... | python | def discard_config(self):
"""Implementation of NAPALM method discard_config."""
if self.config_session is not None:
commands = []
commands.append('configure session {}'.format(self.config_session))
commands.append('abort')
self.device.run_commands(commands... | [
"def",
"discard_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"config_session",
"is",
"not",
"None",
":",
"commands",
"=",
"[",
"]",
"commands",
".",
"append",
"(",
"'configure session {}'",
".",
"format",
"(",
"self",
".",
"config_session",
")",
")",... | Implementation of NAPALM method discard_config. | [
"Implementation",
"of",
"NAPALM",
"method",
"discard_config",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L201-L208 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.rollback | def rollback(self):
"""Implementation of NAPALM method rollback."""
commands = []
commands.append('configure replace flash:rollback-0')
commands.append('write memory')
self.device.run_commands(commands) | python | def rollback(self):
"""Implementation of NAPALM method rollback."""
commands = []
commands.append('configure replace flash:rollback-0')
commands.append('write memory')
self.device.run_commands(commands) | [
"def",
"rollback",
"(",
"self",
")",
":",
"commands",
"=",
"[",
"]",
"commands",
".",
"append",
"(",
"'configure replace flash:rollback-0'",
")",
"commands",
".",
"append",
"(",
"'write memory'",
")",
"self",
".",
"device",
".",
"run_commands",
"(",
"commands"... | Implementation of NAPALM method rollback. | [
"Implementation",
"of",
"NAPALM",
"method",
"rollback",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L210-L215 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.get_facts | def get_facts(self):
"""Implementation of NAPALM method get_facts."""
commands = []
commands.append('show version')
commands.append('show hostname')
commands.append('show interfaces')
result = self.device.run_commands(commands)
version = result[0]
hostna... | python | def get_facts(self):
"""Implementation of NAPALM method get_facts."""
commands = []
commands.append('show version')
commands.append('show hostname')
commands.append('show interfaces')
result = self.device.run_commands(commands)
version = result[0]
hostna... | [
"def",
"get_facts",
"(",
"self",
")",
":",
"commands",
"=",
"[",
"]",
"commands",
".",
"append",
"(",
"'show version'",
")",
"commands",
".",
"append",
"(",
"'show hostname'",
")",
"commands",
".",
"append",
"(",
"'show interfaces'",
")",
"result",
"=",
"s... | Implementation of NAPALM method get_facts. | [
"Implementation",
"of",
"NAPALM",
"method",
"get_facts",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L217-L244 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.get_snmp_information | def get_snmp_information(self):
"""get_snmp_information() for EOS. Re-written to not use TextFSM"""
# Default values
snmp_dict = {
'chassis_id': '',
'location': '',
'contact': '',
'community': {}
}
commands = [
'show ... | python | def get_snmp_information(self):
"""get_snmp_information() for EOS. Re-written to not use TextFSM"""
# Default values
snmp_dict = {
'chassis_id': '',
'location': '',
'contact': '',
'community': {}
}
commands = [
'show ... | [
"def",
"get_snmp_information",
"(",
"self",
")",
":",
"# Default values",
"snmp_dict",
"=",
"{",
"'chassis_id'",
":",
"''",
",",
"'location'",
":",
"''",
",",
"'contact'",
":",
"''",
",",
"'community'",
":",
"{",
"}",
"}",
"commands",
"=",
"[",
"'show snmp... | get_snmp_information() for EOS. Re-written to not use TextFSM | [
"get_snmp_information",
"()",
"for",
"EOS",
".",
"Re",
"-",
"written",
"to",
"not",
"use",
"TextFSM"
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L1128-L1164 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.get_bgp_neighbors_detail | def get_bgp_neighbors_detail(self, neighbor_address=''):
"""Implementation of get_bgp_neighbors_detail"""
def _parse_per_peer_bgp_detail(peer_output):
"""This function parses the raw data per peer and returns a
json structure per peer.
"""
int_fields = ['... | python | def get_bgp_neighbors_detail(self, neighbor_address=''):
"""Implementation of get_bgp_neighbors_detail"""
def _parse_per_peer_bgp_detail(peer_output):
"""This function parses the raw data per peer and returns a
json structure per peer.
"""
int_fields = ['... | [
"def",
"get_bgp_neighbors_detail",
"(",
"self",
",",
"neighbor_address",
"=",
"''",
")",
":",
"def",
"_parse_per_peer_bgp_detail",
"(",
"peer_output",
")",
":",
"\"\"\"This function parses the raw data per peer and returns a\n json structure per peer.\n \"\"\"",... | Implementation of get_bgp_neighbors_detail | [
"Implementation",
"of",
"get_bgp_neighbors_detail"
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L1308-L1464 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.get_config | def get_config(self, retrieve="all"):
"""get_config implementation for EOS."""
get_startup = retrieve == "all" or retrieve == "startup"
get_running = retrieve == "all" or retrieve == "running"
get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_session
... | python | def get_config(self, retrieve="all"):
"""get_config implementation for EOS."""
get_startup = retrieve == "all" or retrieve == "startup"
get_running = retrieve == "all" or retrieve == "running"
get_candidate = (retrieve == "all" or retrieve == "candidate") and self.config_session
... | [
"def",
"get_config",
"(",
"self",
",",
"retrieve",
"=",
"\"all\"",
")",
":",
"get_startup",
"=",
"retrieve",
"==",
"\"all\"",
"or",
"retrieve",
"==",
"\"startup\"",
"get_running",
"=",
"retrieve",
"==",
"\"all\"",
"or",
"retrieve",
"==",
"\"running\"",
"get_ca... | get_config implementation for EOS. | [
"get_config",
"implementation",
"for",
"EOS",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L1517-L1560 |
napalm-automation/napalm-eos | napalm_eos/eos.py | EOSDriver.get_network_instances | def get_network_instances(self, name=''):
"""get_network_instances implementation for EOS."""
output = self._show_vrf()
vrfs = {}
all_vrf_interfaces = {}
for vrf in output:
if (vrf.get('route_distinguisher', '') == "<not set>" or
vrf.get('route_di... | python | def get_network_instances(self, name=''):
"""get_network_instances implementation for EOS."""
output = self._show_vrf()
vrfs = {}
all_vrf_interfaces = {}
for vrf in output:
if (vrf.get('route_distinguisher', '') == "<not set>" or
vrf.get('route_di... | [
"def",
"get_network_instances",
"(",
"self",
",",
"name",
"=",
"''",
")",
":",
"output",
"=",
"self",
".",
"_show_vrf",
"(",
")",
"vrfs",
"=",
"{",
"}",
"all_vrf_interfaces",
"=",
"{",
"}",
"for",
"vrf",
"in",
"output",
":",
"if",
"(",
"vrf",
".",
... | get_network_instances implementation for EOS. | [
"get_network_instances",
"implementation",
"for",
"EOS",
"."
] | train | https://github.com/napalm-automation/napalm-eos/blob/a3b37d6ee353e326ab9ea1a09ecc14045b12928b/napalm_eos/eos.py#L1581-L1630 |
mbr/simplekv | simplekv/net/botostore.py | map_boto_exceptions | def map_boto_exceptions(key=None, exc_pass=()):
"""Map boto-specific exceptions to the simplekv-API."""
from boto.exception import BotoClientError, BotoServerError, \
StorageResponseError
try:
yield
except StorageResponseError as e:
if e.code == 'NoSuchKey':
raise Key... | python | def map_boto_exceptions(key=None, exc_pass=()):
"""Map boto-specific exceptions to the simplekv-API."""
from boto.exception import BotoClientError, BotoServerError, \
StorageResponseError
try:
yield
except StorageResponseError as e:
if e.code == 'NoSuchKey':
raise Key... | [
"def",
"map_boto_exceptions",
"(",
"key",
"=",
"None",
",",
"exc_pass",
"=",
"(",
")",
")",
":",
"from",
"boto",
".",
"exception",
"import",
"BotoClientError",
",",
"BotoServerError",
",",
"StorageResponseError",
"try",
":",
"yield",
"except",
"StorageResponseEr... | Map boto-specific exceptions to the simplekv-API. | [
"Map",
"boto",
"-",
"specific",
"exceptions",
"to",
"the",
"simplekv",
"-",
"API",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/botostore.py#L11-L23 |
mbr/simplekv | simplekv/contrib/__init__.py | ExtendedKeyspaceMixin._check_valid_key | def _check_valid_key(self, key):
"""Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
"""
if not isinstance(key, key_type) and key is not None:
... | python | def _check_valid_key(self, key):
"""Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked
"""
if not isinstance(key, key_type) and key is not None:
... | [
"def",
"_check_valid_key",
"(",
"self",
",",
"key",
")",
":",
"if",
"not",
"isinstance",
"(",
"key",
",",
"key_type",
")",
"and",
"key",
"is",
"not",
"None",
":",
"raise",
"ValueError",
"(",
"'%r is not a valid key type'",
"%",
"key",
")",
"if",
"not",
"... | Checks if a key is valid and raises a ValueError if its not.
When in need of checking a key for validity, always use this
method if possible.
:param key: The key to be checked | [
"Checks",
"if",
"a",
"key",
"is",
"valid",
"and",
"raises",
"a",
"ValueError",
"if",
"its",
"not",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/contrib/__init__.py#L24-L35 |
mbr/simplekv | simplekv/net/azurestore.py | _file_md5 | def _file_md5(file_):
"""
Compute the md5 digest of a file in base64 encoding.
"""
md5 = hashlib.md5()
chunk_size = 128 * md5.block_size
for chunk in iter(lambda: file_.read(chunk_size), b''):
md5.update(chunk)
file_.seek(0)
byte_digest = md5.digest()
return base64.b64encode(... | python | def _file_md5(file_):
"""
Compute the md5 digest of a file in base64 encoding.
"""
md5 = hashlib.md5()
chunk_size = 128 * md5.block_size
for chunk in iter(lambda: file_.read(chunk_size), b''):
md5.update(chunk)
file_.seek(0)
byte_digest = md5.digest()
return base64.b64encode(... | [
"def",
"_file_md5",
"(",
"file_",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
")",
"chunk_size",
"=",
"128",
"*",
"md5",
".",
"block_size",
"for",
"chunk",
"in",
"iter",
"(",
"lambda",
":",
"file_",
".",
"read",
"(",
"chunk_size",
")",
",",
"... | Compute the md5 digest of a file in base64 encoding. | [
"Compute",
"the",
"md5",
"digest",
"of",
"a",
"file",
"in",
"base64",
"encoding",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L25-L35 |
mbr/simplekv | simplekv/net/azurestore.py | _byte_buffer_md5 | def _byte_buffer_md5(buffer_):
"""
Computes the md5 digest of a byte buffer in base64 encoding.
"""
md5 = hashlib.md5(buffer_)
byte_digest = md5.digest()
return base64.b64encode(byte_digest).decode() | python | def _byte_buffer_md5(buffer_):
"""
Computes the md5 digest of a byte buffer in base64 encoding.
"""
md5 = hashlib.md5(buffer_)
byte_digest = md5.digest()
return base64.b64encode(byte_digest).decode() | [
"def",
"_byte_buffer_md5",
"(",
"buffer_",
")",
":",
"md5",
"=",
"hashlib",
".",
"md5",
"(",
"buffer_",
")",
"byte_digest",
"=",
"md5",
".",
"digest",
"(",
")",
"return",
"base64",
".",
"b64encode",
"(",
"byte_digest",
")",
".",
"decode",
"(",
")"
] | Computes the md5 digest of a byte buffer in base64 encoding. | [
"Computes",
"the",
"md5",
"digest",
"of",
"a",
"byte",
"buffer",
"in",
"base64",
"encoding",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L46-L52 |
mbr/simplekv | simplekv/net/azurestore.py | map_azure_exceptions | def map_azure_exceptions(key=None, exc_pass=()):
"""Map Azure-specific exceptions to the simplekv-API."""
from azure.common import AzureMissingResourceHttpError, AzureHttpError,\
AzureException
try:
yield
except AzureMissingResourceHttpError as ex:
if ex.__class__.__name__ not in... | python | def map_azure_exceptions(key=None, exc_pass=()):
"""Map Azure-specific exceptions to the simplekv-API."""
from azure.common import AzureMissingResourceHttpError, AzureHttpError,\
AzureException
try:
yield
except AzureMissingResourceHttpError as ex:
if ex.__class__.__name__ not in... | [
"def",
"map_azure_exceptions",
"(",
"key",
"=",
"None",
",",
"exc_pass",
"=",
"(",
")",
")",
":",
"from",
"azure",
".",
"common",
"import",
"AzureMissingResourceHttpError",
",",
"AzureHttpError",
",",
"AzureException",
"try",
":",
"yield",
"except",
"AzureMissin... | Map Azure-specific exceptions to the simplekv-API. | [
"Map",
"Azure",
"-",
"specific",
"exceptions",
"to",
"the",
"simplekv",
"-",
"API",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L56-L73 |
mbr/simplekv | simplekv/net/azurestore.py | IOInterface.read | def read(self, size=-1):
"""Returns 'size' amount of bytes or less if there is no more data.
If no size is given all data is returned. size can be >= 0."""
if self.closed:
raise ValueError("I/O operation on closed file")
with map_azure_exceptions(key=self.key):
if... | python | def read(self, size=-1):
"""Returns 'size' amount of bytes or less if there is no more data.
If no size is given all data is returned. size can be >= 0."""
if self.closed:
raise ValueError("I/O operation on closed file")
with map_azure_exceptions(key=self.key):
if... | [
"def",
"read",
"(",
"self",
",",
"size",
"=",
"-",
"1",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"with",
"map_azure_exceptions",
"(",
"key",
"=",
"self",
".",
"key",
")",
":",
"if",
... | Returns 'size' amount of bytes or less if there is no more data.
If no size is given all data is returned. size can be >= 0. | [
"Returns",
"size",
"amount",
"of",
"bytes",
"or",
"less",
"if",
"there",
"is",
"no",
"more",
"data",
".",
"If",
"no",
"size",
"is",
"given",
"all",
"data",
"is",
"returned",
".",
"size",
"can",
"be",
">",
"=",
"0",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L231-L251 |
mbr/simplekv | simplekv/net/azurestore.py | IOInterface.seek | def seek(self, offset, whence=0):
"""Move to a new offset either relative or absolute. whence=0 is
absolute, whence=1 is relative, whence=2 is relative to the end.
Any relative or absolute seek operation which would result in a
negative position is undefined and that case can be ignored... | python | def seek(self, offset, whence=0):
"""Move to a new offset either relative or absolute. whence=0 is
absolute, whence=1 is relative, whence=2 is relative to the end.
Any relative or absolute seek operation which would result in a
negative position is undefined and that case can be ignored... | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"0",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ValueError",
"(",
"\"I/O operation on closed file\"",
")",
"if",
"whence",
"==",
"0",
":",
"if",
"offset",
"<",
"0",
":",
"raise",... | Move to a new offset either relative or absolute. whence=0 is
absolute, whence=1 is relative, whence=2 is relative to the end.
Any relative or absolute seek operation which would result in a
negative position is undefined and that case can be ignored
in the implementation.
Any ... | [
"Move",
"to",
"a",
"new",
"offset",
"either",
"relative",
"or",
"absolute",
".",
"whence",
"=",
"0",
"is",
"absolute",
"whence",
"=",
"1",
"is",
"relative",
"whence",
"=",
"2",
"is",
"relative",
"to",
"the",
"end",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/net/azurestore.py#L253-L278 |
mbr/simplekv | simplekv/git.py | _on_tree | def _on_tree(repo, tree, components, obj):
"""Mounts an object on a tree, using the given path components.
:param tree: Tree object to mount on.
:param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is
equivalent to '/foo/bar')
:param obj: Object to mount. If None... | python | def _on_tree(repo, tree, components, obj):
"""Mounts an object on a tree, using the given path components.
:param tree: Tree object to mount on.
:param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is
equivalent to '/foo/bar')
:param obj: Object to mount. If None... | [
"def",
"_on_tree",
"(",
"repo",
",",
"tree",
",",
"components",
",",
"obj",
")",
":",
"# pattern-matching:",
"if",
"len",
"(",
"components",
")",
"==",
"1",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Blob",
")",
":",
"mode",
"=",
"0o100644",
"elif",
... | Mounts an object on a tree, using the given path components.
:param tree: Tree object to mount on.
:param components: A list of strings of subpaths (i.e. ['foo', 'bar'] is
equivalent to '/foo/bar')
:param obj: Object to mount. If None, removes the object found at path
... | [
"Mounts",
"an",
"object",
"on",
"a",
"tree",
"using",
"the",
"given",
"path",
"components",
"."
] | train | https://github.com/mbr/simplekv/blob/fc46ee0b8ca9b071d6699f3f0f18a8e599a5a2d6/simplekv/git.py#L12-L62 |
tgbugs/pyontutils | nifstd/nifstd_tools/allen_transgenic_lines.py | AllenTransgenicLines.build_transgenic_lines | def build_transgenic_lines(self):
"""
init class | "transgenic_line_source_name":"stock_number" a Class
add superClass | rdfs:subClassOf ilxtr:transgenicLine
add *order* | ilxtr:useObjectProperty ilxtr:<order>
add name | rdfs:label "name"
add def |... | python | def build_transgenic_lines(self):
"""
init class | "transgenic_line_source_name":"stock_number" a Class
add superClass | rdfs:subClassOf ilxtr:transgenicLine
add *order* | ilxtr:useObjectProperty ilxtr:<order>
add name | rdfs:label "name"
add def |... | [
"def",
"build_transgenic_lines",
"(",
"self",
")",
":",
"allen_namespaces",
"=",
"{",
"'JAX'",
":",
"'http://jaxmice.jax.org/strain/'",
",",
"'MMRRC'",
":",
"'http://www.mmrrc.org/catalog/getSDS.jsp?mmrrc_id='",
",",
"'AIBS'",
":",
"'http://api.brain-map.org/api/v2/data/Transge... | init class | "transgenic_line_source_name":"stock_number" a Class
add superClass | rdfs:subClassOf ilxtr:transgenicLine
add *order* | ilxtr:useObjectProperty ilxtr:<order>
add name | rdfs:label "name"
add def | definition: "description"
add transtype | ... | [
"init",
"class",
"|",
"transgenic_line_source_name",
":",
"stock_number",
"a",
"Class",
"add",
"superClass",
"|",
"rdfs",
":",
"subClassOf",
"ilxtr",
":",
"transgenicLine",
"add",
"*",
"order",
"*",
"|",
"ilxtr",
":",
"useObjectProperty",
"ilxtr",
":",
"<order",... | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/allen_transgenic_lines.py#L34-L63 |
tgbugs/pyontutils | nifstd/nifstd_tools/parcellation/coco.py | genericPScheme.datagetter | def datagetter(cls):
""" example datagetter function, make any local modifications here """
with open('myfile', 'rt') as f:
rows = [r for r in csv.reader(f)]
dothing = lambda _: [i for i, v in enumerate(_)]
rows = [dothing(_) for _ in rows]
raise NotImplementedError('... | python | def datagetter(cls):
""" example datagetter function, make any local modifications here """
with open('myfile', 'rt') as f:
rows = [r for r in csv.reader(f)]
dothing = lambda _: [i for i, v in enumerate(_)]
rows = [dothing(_) for _ in rows]
raise NotImplementedError('... | [
"def",
"datagetter",
"(",
"cls",
")",
":",
"with",
"open",
"(",
"'myfile'",
",",
"'rt'",
")",
"as",
"f",
":",
"rows",
"=",
"[",
"r",
"for",
"r",
"in",
"csv",
".",
"reader",
"(",
"f",
")",
"]",
"dothing",
"=",
"lambda",
"_",
":",
"[",
"i",
"fo... | example datagetter function, make any local modifications here | [
"example",
"datagetter",
"function",
"make",
"any",
"local",
"modifications",
"here"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/parcellation/coco.py#L164-L171 |
tgbugs/pyontutils | nifstd/nifstd_tools/parcellation/coco.py | genericPScheme.dataproc | def dataproc(cls, graph, data):
""" example datagetter function, make any local modifications here """
for thing in data:
graph.add_trip(*thing)
raise NotImplementedError('You need to implement this yourlself!') | python | def dataproc(cls, graph, data):
""" example datagetter function, make any local modifications here """
for thing in data:
graph.add_trip(*thing)
raise NotImplementedError('You need to implement this yourlself!') | [
"def",
"dataproc",
"(",
"cls",
",",
"graph",
",",
"data",
")",
":",
"for",
"thing",
"in",
"data",
":",
"graph",
".",
"add_trip",
"(",
"*",
"thing",
")",
"raise",
"NotImplementedError",
"(",
"'You need to implement this yourlself!'",
")"
] | example datagetter function, make any local modifications here | [
"example",
"datagetter",
"function",
"make",
"any",
"local",
"modifications",
"here"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/nifstd/nifstd_tools/parcellation/coco.py#L179-L183 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._connect | def _connect(self):
"""Connect to ec2 resource."""
resource = None
try:
resource = boto3.resource(
'ec2',
aws_access_key_id=self.access_key_id,
aws_secret_access_key=self.secret_access_key,
region_name=self.region
... | python | def _connect(self):
"""Connect to ec2 resource."""
resource = None
try:
resource = boto3.resource(
'ec2',
aws_access_key_id=self.access_key_id,
aws_secret_access_key=self.secret_access_key,
region_name=self.region
... | [
"def",
"_connect",
"(",
"self",
")",
":",
"resource",
"=",
"None",
"try",
":",
"resource",
"=",
"boto3",
".",
"resource",
"(",
"'ec2'",
",",
"aws_access_key_id",
"=",
"self",
".",
"access_key_id",
",",
"aws_secret_access_key",
"=",
"self",
".",
"secret_acces... | Connect to ec2 resource. | [
"Connect",
"to",
"ec2",
"resource",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L168-L184 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._get_instance | def _get_instance(self):
"""Retrieve instance matching instance_id."""
resource = self._connect()
try:
instance = resource.Instance(self.running_instance_id)
except Exception:
raise EC2CloudException(
'Instance with ID: {instance_id} not found.'.f... | python | def _get_instance(self):
"""Retrieve instance matching instance_id."""
resource = self._connect()
try:
instance = resource.Instance(self.running_instance_id)
except Exception:
raise EC2CloudException(
'Instance with ID: {instance_id} not found.'.f... | [
"def",
"_get_instance",
"(",
"self",
")",
":",
"resource",
"=",
"self",
".",
"_connect",
"(",
")",
"try",
":",
"instance",
"=",
"resource",
".",
"Instance",
"(",
"self",
".",
"running_instance_id",
")",
"except",
"Exception",
":",
"raise",
"EC2CloudException... | Retrieve instance matching instance_id. | [
"Retrieve",
"instance",
"matching",
"instance_id",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L186-L198 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._get_instance_state | def _get_instance_state(self):
"""
Attempt to retrieve the state of the instance.
Raises:
EC2CloudException: If the instance cannot be found.
"""
instance = self._get_instance()
state = None
try:
state = instance.state['Name']
exc... | python | def _get_instance_state(self):
"""
Attempt to retrieve the state of the instance.
Raises:
EC2CloudException: If the instance cannot be found.
"""
instance = self._get_instance()
state = None
try:
state = instance.state['Name']
exc... | [
"def",
"_get_instance_state",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"state",
"=",
"None",
"try",
":",
"state",
"=",
"instance",
".",
"state",
"[",
"'Name'",
"]",
"except",
"Exception",
":",
"raise",
"EC2CloudExcept... | Attempt to retrieve the state of the instance.
Raises:
EC2CloudException: If the instance cannot be found. | [
"Attempt",
"to",
"retrieve",
"the",
"state",
"of",
"the",
"instance",
".",
"Raises",
":",
"EC2CloudException",
":",
"If",
"the",
"instance",
"cannot",
"be",
"found",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L200-L219 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._get_user_data | def _get_user_data(self):
"""
Return formatted bash script string.
The public ssh key is added by cloud init to the instance based on
the ssh user and private key file.
"""
key = ipa_utils.generate_public_ssh_key(
self.ssh_private_key_file
).decode()
... | python | def _get_user_data(self):
"""
Return formatted bash script string.
The public ssh key is added by cloud init to the instance based on
the ssh user and private key file.
"""
key = ipa_utils.generate_public_ssh_key(
self.ssh_private_key_file
).decode()
... | [
"def",
"_get_user_data",
"(",
"self",
")",
":",
"key",
"=",
"ipa_utils",
".",
"generate_public_ssh_key",
"(",
"self",
".",
"ssh_private_key_file",
")",
".",
"decode",
"(",
")",
"script",
"=",
"BASH_SSH_SCRIPT",
".",
"format",
"(",
"user",
"=",
"self",
".",
... | Return formatted bash script string.
The public ssh key is added by cloud init to the instance based on
the ssh user and private key file. | [
"Return",
"formatted",
"bash",
"script",
"string",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L221-L232 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._launch_instance | def _launch_instance(self):
"""Launch an instance of the given image."""
resource = self._connect()
instance_name = ipa_utils.generate_instance_name('ec2-ipa-test')
kwargs = {
'InstanceType': self.instance_type or EC2_DEFAULT_TYPE,
'ImageId': self.image_id,
... | python | def _launch_instance(self):
"""Launch an instance of the given image."""
resource = self._connect()
instance_name = ipa_utils.generate_instance_name('ec2-ipa-test')
kwargs = {
'InstanceType': self.instance_type or EC2_DEFAULT_TYPE,
'ImageId': self.image_id,
... | [
"def",
"_launch_instance",
"(",
"self",
")",
":",
"resource",
"=",
"self",
".",
"_connect",
"(",
")",
"instance_name",
"=",
"ipa_utils",
".",
"generate_instance_name",
"(",
"'ec2-ipa-test'",
")",
"kwargs",
"=",
"{",
"'InstanceType'",
":",
"self",
".",
"instanc... | Launch an instance of the given image. | [
"Launch",
"an",
"instance",
"of",
"the",
"given",
"image",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L240-L286 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._set_instance_ip | def _set_instance_ip(self):
"""
Retrieve instance ip and cache it.
Current preference is for public ipv4, ipv6 and private.
"""
instance = self._get_instance()
# ipv6
try:
ipv6 = instance.network_interfaces[0].ipv6_addresses[0]
except (IndexE... | python | def _set_instance_ip(self):
"""
Retrieve instance ip and cache it.
Current preference is for public ipv4, ipv6 and private.
"""
instance = self._get_instance()
# ipv6
try:
ipv6 = instance.network_interfaces[0].ipv6_addresses[0]
except (IndexE... | [
"def",
"_set_instance_ip",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"# ipv6",
"try",
":",
"ipv6",
"=",
"instance",
".",
"network_interfaces",
"[",
"0",
"]",
".",
"ipv6_addresses",
"[",
"0",
"]",
"except",
"(",
"Inde... | Retrieve instance ip and cache it.
Current preference is for public ipv4, ipv6 and private. | [
"Retrieve",
"instance",
"ip",
"and",
"cache",
"it",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L293-L313 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._start_instance | def _start_instance(self):
"""Start the instance."""
instance = self._get_instance()
instance.start()
self._wait_on_instance('running', self.timeout) | python | def _start_instance(self):
"""Start the instance."""
instance = self._get_instance()
instance.start()
self._wait_on_instance('running', self.timeout) | [
"def",
"_start_instance",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"instance",
".",
"start",
"(",
")",
"self",
".",
"_wait_on_instance",
"(",
"'running'",
",",
"self",
".",
"timeout",
")"
] | Start the instance. | [
"Start",
"the",
"instance",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L315-L319 |
SUSE-Enceladus/ipa | ipa/ipa_ec2.py | EC2Cloud._stop_instance | def _stop_instance(self):
"""Stop the instance."""
instance = self._get_instance()
instance.stop()
self._wait_on_instance('stopped', self.timeout) | python | def _stop_instance(self):
"""Stop the instance."""
instance = self._get_instance()
instance.stop()
self._wait_on_instance('stopped', self.timeout) | [
"def",
"_stop_instance",
"(",
"self",
")",
":",
"instance",
"=",
"self",
".",
"_get_instance",
"(",
")",
"instance",
".",
"stop",
"(",
")",
"self",
".",
"_wait_on_instance",
"(",
"'stopped'",
",",
"self",
".",
"timeout",
")"
] | Stop the instance. | [
"Stop",
"the",
"instance",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_ec2.py#L321-L325 |
tgbugs/pyontutils | pyontutils/process_fixed.py | _process_worker | def _process_worker(call_queue, result_queue):
""" This worker is wrapped to block KeyboardInterrupt """
signal.signal(signal.SIGINT, signal.SIG_IGN) #block ctrl-c
return _process_worker_base(call_queue, result_queue) | python | def _process_worker(call_queue, result_queue):
""" This worker is wrapped to block KeyboardInterrupt """
signal.signal(signal.SIGINT, signal.SIG_IGN) #block ctrl-c
return _process_worker_base(call_queue, result_queue) | [
"def",
"_process_worker",
"(",
"call_queue",
",",
"result_queue",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"#block ctrl-c",
"return",
"_process_worker_base",
"(",
"call_queue",
",",
"result_queue",
")"
... | This worker is wrapped to block KeyboardInterrupt | [
"This",
"worker",
"is",
"wrapped",
"to",
"block",
"KeyboardInterrupt"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/process_fixed.py#L6-L9 |
SUSE-Enceladus/ipa | ipa/ipa_distro.py | Distro._set_init_system | def _set_init_system(self, client):
"""Determine the init system of distribution."""
if not self.init_system:
try:
out = ipa_utils.execute_ssh_command(
client,
'ps -p 1 -o comm='
)
except Exception as e:
... | python | def _set_init_system(self, client):
"""Determine the init system of distribution."""
if not self.init_system:
try:
out = ipa_utils.execute_ssh_command(
client,
'ps -p 1 -o comm='
)
except Exception as e:
... | [
"def",
"_set_init_system",
"(",
"self",
",",
"client",
")",
":",
"if",
"not",
"self",
".",
"init_system",
":",
"try",
":",
"out",
"=",
"ipa_utils",
".",
"execute_ssh_command",
"(",
"client",
",",
"'ps -p 1 -o comm='",
")",
"except",
"Exception",
"as",
"e",
... | Determine the init system of distribution. | [
"Determine",
"the",
"init",
"system",
"of",
"distribution",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L36-L50 |
SUSE-Enceladus/ipa | ipa/ipa_distro.py | Distro.get_vm_info | def get_vm_info(self, client):
"""Return vm info."""
out = ''
self._set_init_system(client)
if self.init_system == 'systemd':
try:
out += 'systemd-analyze:\n\n'
out += ipa_utils.execute_ssh_command(
client,
... | python | def get_vm_info(self, client):
"""Return vm info."""
out = ''
self._set_init_system(client)
if self.init_system == 'systemd':
try:
out += 'systemd-analyze:\n\n'
out += ipa_utils.execute_ssh_command(
client,
... | [
"def",
"get_vm_info",
"(",
"self",
",",
"client",
")",
":",
"out",
"=",
"''",
"self",
".",
"_set_init_system",
"(",
"client",
")",
"if",
"self",
".",
"init_system",
"==",
"'systemd'",
":",
"try",
":",
"out",
"+=",
"'systemd-analyze:\\n\\n'",
"out",
"+=",
... | Return vm info. | [
"Return",
"vm",
"info",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L76-L103 |
SUSE-Enceladus/ipa | ipa/ipa_distro.py | Distro.install_package | def install_package(self, client, package):
"""Install package on instance."""
install_cmd = "{sudo} '{install} {package}'".format(
sudo=self.get_sudo_exec_wrapper(),
install=self.get_install_cmd(),
package=package
)
try:
out = ipa_utils.e... | python | def install_package(self, client, package):
"""Install package on instance."""
install_cmd = "{sudo} '{install} {package}'".format(
sudo=self.get_sudo_exec_wrapper(),
install=self.get_install_cmd(),
package=package
)
try:
out = ipa_utils.e... | [
"def",
"install_package",
"(",
"self",
",",
"client",
",",
"package",
")",
":",
"install_cmd",
"=",
"\"{sudo} '{install} {package}'\"",
".",
"format",
"(",
"sudo",
"=",
"self",
".",
"get_sudo_exec_wrapper",
"(",
")",
",",
"install",
"=",
"self",
".",
"get_inst... | Install package on instance. | [
"Install",
"package",
"on",
"instance",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L105-L127 |
SUSE-Enceladus/ipa | ipa/ipa_distro.py | Distro.reboot | def reboot(self, client):
"""Execute reboot command on instance."""
self._set_init_system(client)
reboot_cmd = "{sudo} '{stop_ssh};{reboot}'".format(
sudo=self.get_sudo_exec_wrapper(),
stop_ssh=self.get_stop_ssh_service_cmd(),
reboot=self.get_reboot_cmd()
... | python | def reboot(self, client):
"""Execute reboot command on instance."""
self._set_init_system(client)
reboot_cmd = "{sudo} '{stop_ssh};{reboot}'".format(
sudo=self.get_sudo_exec_wrapper(),
stop_ssh=self.get_stop_ssh_service_cmd(),
reboot=self.get_reboot_cmd()
... | [
"def",
"reboot",
"(",
"self",
",",
"client",
")",
":",
"self",
".",
"_set_init_system",
"(",
"client",
")",
"reboot_cmd",
"=",
"\"{sudo} '{stop_ssh};{reboot}'\"",
".",
"format",
"(",
"sudo",
"=",
"self",
".",
"get_sudo_exec_wrapper",
"(",
")",
",",
"stop_ssh",... | Execute reboot command on instance. | [
"Execute",
"reboot",
"command",
"on",
"instance",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L129-L148 |
SUSE-Enceladus/ipa | ipa/ipa_distro.py | Distro.update | def update(self, client):
"""Execute update command on instance."""
update_cmd = "{sudo} '{refresh};{update}'".format(
sudo=self.get_sudo_exec_wrapper(),
refresh=self.get_refresh_repo_cmd(),
update=self.get_update_cmd()
)
out = ''
try:
... | python | def update(self, client):
"""Execute update command on instance."""
update_cmd = "{sudo} '{refresh};{update}'".format(
sudo=self.get_sudo_exec_wrapper(),
refresh=self.get_refresh_repo_cmd(),
update=self.get_update_cmd()
)
out = ''
try:
... | [
"def",
"update",
"(",
"self",
",",
"client",
")",
":",
"update_cmd",
"=",
"\"{sudo} '{refresh};{update}'\"",
".",
"format",
"(",
"sudo",
"=",
"self",
".",
"get_sudo_exec_wrapper",
"(",
")",
",",
"refresh",
"=",
"self",
".",
"get_refresh_repo_cmd",
"(",
")",
... | Execute update command on instance. | [
"Execute",
"update",
"command",
"on",
"instance",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_distro.py#L150-L168 |
tgbugs/pyontutils | pyontutils/scigraph_client.py | Annotations.annotate | def annotate(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='text/plain; charset=utf-8'):
""" Annotate text from: /annotations
Arguments:
content: The content to annotate
... | python | def annotate(self, content, includeCat=None, excludeCat=None, minLength=None, longestOnly=None, includeAbbrev=None, includeAcronym=None, includeNumbers=None, output='text/plain; charset=utf-8'):
""" Annotate text from: /annotations
Arguments:
content: The content to annotate
... | [
"def",
"annotate",
"(",
"self",
",",
"content",
",",
"includeCat",
"=",
"None",
",",
"excludeCat",
"=",
"None",
",",
"minLength",
"=",
"None",
",",
"longestOnly",
"=",
"None",
",",
"includeAbbrev",
"=",
"None",
",",
"includeAcronym",
"=",
"None",
",",
"i... | Annotate text from: /annotations
Arguments:
content: The content to annotate
includeCat: A set of categories to include
excludeCat: A set of categories to exclude
minLength: The minimum number of characters in annotated entities
longestOnly: Shoul... | [
"Annotate",
"text",
"from",
":",
"/",
"annotations"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_client.py#L167-L189 |
tgbugs/pyontutils | pyontutils/scigraph_client.py | GraphBase.reachableFrom | def reachableFrom(self, id, hint=None, relationships=None, lbls=None, callback=None, output='application/json'):
""" Get all the nodes reachable from a starting point, traversing the provided edges. from: /graph/reachablefrom/{id}
Arguments:
id: The type of the edge
hint: A ... | python | def reachableFrom(self, id, hint=None, relationships=None, lbls=None, callback=None, output='application/json'):
""" Get all the nodes reachable from a starting point, traversing the provided edges. from: /graph/reachablefrom/{id}
Arguments:
id: The type of the edge
hint: A ... | [
"def",
"reachableFrom",
"(",
"self",
",",
"id",
",",
"hint",
"=",
"None",
",",
"relationships",
"=",
"None",
",",
"lbls",
"=",
"None",
",",
"callback",
"=",
"None",
",",
"output",
"=",
"'application/json'",
")",
":",
"if",
"id",
"and",
"id",
".",
"st... | Get all the nodes reachable from a starting point, traversing the provided edges. from: /graph/reachablefrom/{id}
Arguments:
id: The type of the edge
hint: A label hint to find the start node.
relationships: A list of relationships to traverse, in order. Supports cypher
... | [
"Get",
"all",
"the",
"nodes",
"reachable",
"from",
"a",
"starting",
"point",
"traversing",
"the",
"provided",
"edges",
".",
"from",
":",
"/",
"graph",
"/",
"reachablefrom",
"/",
"{",
"id",
"}"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_client.py#L652-L685 |
tgbugs/pyontutils | pyontutils/scigraph_client.py | Graph.ordered | def ordered(start, edges, predicate=None, inverse=False):
""" Depth first edges from a SciGraph response. """
s, o = 'sub', 'obj'
if inverse:
s, o = o, s
for edge in edges:
if predicate is not None and edge['pred'] != predicate:
print('scoop!')
... | python | def ordered(start, edges, predicate=None, inverse=False):
""" Depth first edges from a SciGraph response. """
s, o = 'sub', 'obj'
if inverse:
s, o = o, s
for edge in edges:
if predicate is not None and edge['pred'] != predicate:
print('scoop!')
... | [
"def",
"ordered",
"(",
"start",
",",
"edges",
",",
"predicate",
"=",
"None",
",",
"inverse",
"=",
"False",
")",
":",
"s",
",",
"o",
"=",
"'sub'",
",",
"'obj'",
"if",
"inverse",
":",
"s",
",",
"o",
"=",
"o",
",",
"s",
"for",
"edge",
"in",
"edges... | Depth first edges from a SciGraph response. | [
"Depth",
"first",
"edges",
"from",
"a",
"SciGraph",
"response",
"."
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/scigraph_client.py#L741-L753 |
tgbugs/pyontutils | pyontutils/hierarchies.py | tcsort | def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O
""" get len of transitive closure assume type items is tree... """
return len(item[1]) + sum(tcsort(kv) for kv in item[1].items()) | python | def tcsort(item): # FIXME SUCH WOW SO INEFFICIENT O_O
""" get len of transitive closure assume type items is tree... """
return len(item[1]) + sum(tcsort(kv) for kv in item[1].items()) | [
"def",
"tcsort",
"(",
"item",
")",
":",
"# FIXME SUCH WOW SO INEFFICIENT O_O",
"return",
"len",
"(",
"item",
"[",
"1",
"]",
")",
"+",
"sum",
"(",
"tcsort",
"(",
"kv",
")",
"for",
"kv",
"in",
"item",
"[",
"1",
"]",
".",
"items",
"(",
")",
")"
] | get len of transitive closure assume type items is tree... | [
"get",
"len",
"of",
"transitive",
"closure",
"assume",
"type",
"items",
"is",
"tree",
"..."
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L43-L45 |
tgbugs/pyontutils | pyontutils/hierarchies.py | get_node | def get_node(start, tree, pnames):
""" for each parent find a single branch to root """
def get_first_branch(node):
if node not in pnames: # one way to hit a root
return []
if pnames[node]: # mmmm names
fp = pnames[node][0]
if cycle_check(node, fp, pnames):
... | python | def get_node(start, tree, pnames):
""" for each parent find a single branch to root """
def get_first_branch(node):
if node not in pnames: # one way to hit a root
return []
if pnames[node]: # mmmm names
fp = pnames[node][0]
if cycle_check(node, fp, pnames):
... | [
"def",
"get_node",
"(",
"start",
",",
"tree",
",",
"pnames",
")",
":",
"def",
"get_first_branch",
"(",
"node",
")",
":",
"if",
"node",
"not",
"in",
"pnames",
":",
"# one way to hit a root",
"return",
"[",
"]",
"if",
"pnames",
"[",
"node",
"]",
":",
"# ... | for each parent find a single branch to root | [
"for",
"each",
"parent",
"find",
"a",
"single",
"branch",
"to",
"root"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L58-L80 |
tgbugs/pyontutils | pyontutils/hierarchies.py | dematerialize | def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves!
#FIXME still an issue: Fornix, Striatum, Diagonal Band
""" Remove nodes higher in the tree that occur further down the
SAME branch. If they occur down OTHER branchs leave them alone.
NOTE: modifies in ... | python | def dematerialize(parent_name, parent_node): # FIXME we need to demat more than just leaves!
#FIXME still an issue: Fornix, Striatum, Diagonal Band
""" Remove nodes higher in the tree that occur further down the
SAME branch. If they occur down OTHER branchs leave them alone.
NOTE: modifies in ... | [
"def",
"dematerialize",
"(",
"parent_name",
",",
"parent_node",
")",
":",
"# FIXME we need to demat more than just leaves!",
"#FIXME still an issue: Fornix, Striatum, Diagonal Band",
"lleaves",
"=",
"{",
"}",
"children",
"=",
"parent_node",
"[",
"parent_name",
"]",
"if",
"n... | Remove nodes higher in the tree that occur further down the
SAME branch. If they occur down OTHER branchs leave them alone.
NOTE: modifies in place! | [
"Remove",
"nodes",
"higher",
"in",
"the",
"tree",
"that",
"occur",
"further",
"down",
"the",
"SAME",
"branch",
".",
"If",
"they",
"occur",
"down",
"OTHER",
"branchs",
"leave",
"them",
"alone",
"."
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L115-L160 |
tgbugs/pyontutils | pyontutils/hierarchies.py | inv_edges | def inv_edges(json):
"""Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)"""
for edge in json['edges']:
sub, obj = edge['sub'], edge['obj']
edge['sub'] = obj
edge['obj'] = sub
edge['pred'] += 'INVERTED' | python | def inv_edges(json):
"""Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier)"""
for edge in json['edges']:
sub, obj = edge['sub'], edge['obj']
edge['sub'] = obj
edge['obj'] = sub
edge['pred'] += 'INVERTED' | [
"def",
"inv_edges",
"(",
"json",
")",
":",
"for",
"edge",
"in",
"json",
"[",
"'edges'",
"]",
":",
"sub",
",",
"obj",
"=",
"edge",
"[",
"'sub'",
"]",
",",
"edge",
"[",
"'obj'",
"]",
"edge",
"[",
"'sub'",
"]",
"=",
"obj",
"edge",
"[",
"'obj'",
"]... | Switch obj/sub for a set of edges (makes fixing known inverse edges MUCH easier) | [
"Switch",
"obj",
"/",
"sub",
"for",
"a",
"set",
"of",
"edges",
"(",
"makes",
"fixing",
"known",
"inverse",
"edges",
"MUCH",
"easier",
")"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/pyontutils/hierarchies.py#L554-L561 |
SUSE-Enceladus/ipa | ipa/ipa_controller.py | collect_results | def collect_results(results_file):
"""Return the result (pass/fail) for json file."""
with open(results_file, 'r') as results:
data = json.load(results)
return data | python | def collect_results(results_file):
"""Return the result (pass/fail) for json file."""
with open(results_file, 'r') as results:
data = json.load(results)
return data | [
"def",
"collect_results",
"(",
"results_file",
")",
":",
"with",
"open",
"(",
"results_file",
",",
"'r'",
")",
"as",
"results",
":",
"data",
"=",
"json",
".",
"load",
"(",
"results",
")",
"return",
"data"
] | Return the result (pass/fail) for json file. | [
"Return",
"the",
"result",
"(",
"pass",
"/",
"fail",
")",
"for",
"json",
"file",
"."
] | train | https://github.com/SUSE-Enceladus/ipa/blob/0845eed0ea25a27dbb059ad1016105fa60002228/ipa/ipa_controller.py#L135-L139 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_sql.py | IlxSql.get_terms | def get_terms(self):
''' GROUP BY is a shortcut to only getting the first in every list of group '''
if not self.terms.empty:
return self.terms
if self.from_backup:
self.terms = open_pickle(TERMS_BACKUP_PATH)
return self.terms
engine = create_engine(se... | python | def get_terms(self):
''' GROUP BY is a shortcut to only getting the first in every list of group '''
if not self.terms.empty:
return self.terms
if self.from_backup:
self.terms = open_pickle(TERMS_BACKUP_PATH)
return self.terms
engine = create_engine(se... | [
"def",
"get_terms",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"terms",
".",
"empty",
":",
"return",
"self",
".",
"terms",
"if",
"self",
".",
"from_backup",
":",
"self",
".",
"terms",
"=",
"open_pickle",
"(",
"TERMS_BACKUP_PATH",
")",
"return",
"... | GROUP BY is a shortcut to only getting the first in every list of group | [
"GROUP",
"BY",
"is",
"a",
"shortcut",
"to",
"only",
"getting",
"the",
"first",
"in",
"every",
"list",
"of",
"group"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L67-L82 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_sql.py | IlxSql.get_terms_complete | def get_terms_complete(self) -> pd.DataFrame:
''' Gets complete entity data like term/view '''
if not self.terms_complete.empty:
return self.terms_complete
if self.from_backup:
self.terms_complete = open_pickle(TERMS_COMPLETE_BACKUP_PATH)
return self.terms_com... | python | def get_terms_complete(self) -> pd.DataFrame:
''' Gets complete entity data like term/view '''
if not self.terms_complete.empty:
return self.terms_complete
if self.from_backup:
self.terms_complete = open_pickle(TERMS_COMPLETE_BACKUP_PATH)
return self.terms_com... | [
"def",
"get_terms_complete",
"(",
"self",
")",
"->",
"pd",
".",
"DataFrame",
":",
"if",
"not",
"self",
".",
"terms_complete",
".",
"empty",
":",
"return",
"self",
".",
"terms_complete",
"if",
"self",
".",
"from_backup",
":",
"self",
".",
"terms_complete",
... | Gets complete entity data like term/view | [
"Gets",
"complete",
"entity",
"data",
"like",
"term",
"/",
"view"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L218-L240 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_sql.py | IlxSql.get_ilx2superclass | def get_ilx2superclass(self, clean:bool=True):
''' clean: for list of literals only '''
ilx2superclass = defaultdict(list)
header = ['Index'] + list(self.fetch_superclasses().columns)
for row in self.fetch_superclasses().itertuples():
row = {header[i]:val for i, val in enumer... | python | def get_ilx2superclass(self, clean:bool=True):
''' clean: for list of literals only '''
ilx2superclass = defaultdict(list)
header = ['Index'] + list(self.fetch_superclasses().columns)
for row in self.fetch_superclasses().itertuples():
row = {header[i]:val for i, val in enumer... | [
"def",
"get_ilx2superclass",
"(",
"self",
",",
"clean",
":",
"bool",
"=",
"True",
")",
":",
"ilx2superclass",
"=",
"defaultdict",
"(",
"list",
")",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"fetch_superclasses",
"(",
")",
".",
... | clean: for list of literals only | [
"clean",
":",
"for",
"list",
"of",
"literals",
"only"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L315-L329 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_sql.py | IlxSql.get_tid2annotations | def get_tid2annotations(self, clean:bool=True):
''' clean: for list of literals only '''
tid2annotations = defaultdict(list)
header = ['Index'] + list(self.fetch_annotations().columns)
for row in self.fetch_annotations().itertuples():
row = {header[i]:val for i, val in enumer... | python | def get_tid2annotations(self, clean:bool=True):
''' clean: for list of literals only '''
tid2annotations = defaultdict(list)
header = ['Index'] + list(self.fetch_annotations().columns)
for row in self.fetch_annotations().itertuples():
row = {header[i]:val for i, val in enumer... | [
"def",
"get_tid2annotations",
"(",
"self",
",",
"clean",
":",
"bool",
"=",
"True",
")",
":",
"tid2annotations",
"=",
"defaultdict",
"(",
"list",
")",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"fetch_annotations",
"(",
")",
".",
... | clean: for list of literals only | [
"clean",
":",
"for",
"list",
"of",
"literals",
"only"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L331-L347 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_sql.py | IlxSql.get_tid2synonyms | def get_tid2synonyms(self, clean:bool=True):
''' clean: for list of literals only '''
tid2synonyms = {}
header = ['Index'] + list(self.fetch_synonyms().columns)
for row in self.fetch_synonyms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if cl... | python | def get_tid2synonyms(self, clean:bool=True):
''' clean: for list of literals only '''
tid2synonyms = {}
header = ['Index'] + list(self.fetch_synonyms().columns)
for row in self.fetch_synonyms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
if cl... | [
"def",
"get_tid2synonyms",
"(",
"self",
",",
"clean",
":",
"bool",
"=",
"True",
")",
":",
"tid2synonyms",
"=",
"{",
"}",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"fetch_synonyms",
"(",
")",
".",
"columns",
")",
"for",
"row",... | clean: for list of literals only | [
"clean",
":",
"for",
"list",
"of",
"literals",
"only"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L368-L379 |
tgbugs/pyontutils | ilxutils/ilxutils/interlex_sql.py | IlxSql.get_ilx2synonyms | def get_ilx2synonyms(self, clean:bool=True):
''' clean: for list of literals only '''
ilx2synonyms = defaultdict(list)
header = ['Index'] + list(self.fetch_synonyms().columns)
for row in self.fetch_synonyms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
... | python | def get_ilx2synonyms(self, clean:bool=True):
''' clean: for list of literals only '''
ilx2synonyms = defaultdict(list)
header = ['Index'] + list(self.fetch_synonyms().columns)
for row in self.fetch_synonyms().itertuples():
row = {header[i]:val for i, val in enumerate(row)}
... | [
"def",
"get_ilx2synonyms",
"(",
"self",
",",
"clean",
":",
"bool",
"=",
"True",
")",
":",
"ilx2synonyms",
"=",
"defaultdict",
"(",
"list",
")",
"header",
"=",
"[",
"'Index'",
"]",
"+",
"list",
"(",
"self",
".",
"fetch_synonyms",
"(",
")",
".",
"columns... | clean: for list of literals only | [
"clean",
":",
"for",
"list",
"of",
"literals",
"only"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/interlex_sql.py#L381-L392 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | superclasses_bug_fix | def superclasses_bug_fix(data):
''' PHP returns "id" in superclass but only accepts superclass_tid '''
for i, value in enumerate(data['superclasses']):
data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id')
return data | python | def superclasses_bug_fix(data):
''' PHP returns "id" in superclass but only accepts superclass_tid '''
for i, value in enumerate(data['superclasses']):
data['superclasses'][i]['superclass_tid'] = data['superclasses'][i].pop('id')
return data | [
"def",
"superclasses_bug_fix",
"(",
"data",
")",
":",
"for",
"i",
",",
"value",
"in",
"enumerate",
"(",
"data",
"[",
"'superclasses'",
"]",
")",
":",
"data",
"[",
"'superclasses'",
"]",
"[",
"i",
"]",
"[",
"'superclass_tid'",
"]",
"=",
"data",
"[",
"'s... | PHP returns "id" in superclass but only accepts superclass_tid | [
"PHP",
"returns",
"id",
"in",
"superclass",
"but",
"only",
"accepts",
"superclass_tid"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L47-L51 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | Client.log_info | def log_info(self, data):
''' Logs successful responses '''
info = 'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}'
info_filled = info.format(label = data['label'],
id = data['id'],
ilx = data['ilx'],... | python | def log_info(self, data):
''' Logs successful responses '''
info = 'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}'
info_filled = info.format(label = data['label'],
id = data['id'],
ilx = data['ilx'],... | [
"def",
"log_info",
"(",
"self",
",",
"data",
")",
":",
"info",
"=",
"'label={label}, id={id}, ilx={ilx}, superclass_tid={super_id}'",
"info_filled",
"=",
"info",
".",
"format",
"(",
"label",
"=",
"data",
"[",
"'label'",
"]",
",",
"id",
"=",
"data",
"[",
"'id'"... | Logs successful responses | [
"Logs",
"successful",
"responses"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L80-L88 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | Client.get | def get(self, url):
''' Requests data from database '''
req = r.get(url,
headers = self.headers,
auth = self.auth)
return self.process_request(req) | python | def get(self, url):
''' Requests data from database '''
req = r.get(url,
headers = self.headers,
auth = self.auth)
return self.process_request(req) | [
"def",
"get",
"(",
"self",
",",
"url",
")",
":",
"req",
"=",
"r",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"auth",
"=",
"self",
".",
"auth",
")",
"return",
"self",
".",
"process_request",
"(",
"req",
")"
] | Requests data from database | [
"Requests",
"data",
"from",
"database"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L95-L100 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | Client.post | def post(self, url, data):
''' Gives data to database '''
data.update({'key': self.APIKEY})
req = r.post(url,
data = json.dumps(data),
headers = self.headers,
auth = self.auth)
return self.process_request(req) | python | def post(self, url, data):
''' Gives data to database '''
data.update({'key': self.APIKEY})
req = r.post(url,
data = json.dumps(data),
headers = self.headers,
auth = self.auth)
return self.process_request(req) | [
"def",
"post",
"(",
"self",
",",
"url",
",",
"data",
")",
":",
"data",
".",
"update",
"(",
"{",
"'key'",
":",
"self",
".",
"APIKEY",
"}",
")",
"req",
"=",
"r",
".",
"post",
"(",
"url",
",",
"data",
"=",
"json",
".",
"dumps",
"(",
"data",
")",... | Gives data to database | [
"Gives",
"data",
"to",
"database"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L102-L109 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | Client.process_request | def process_request(self, req):
''' Checks to see if data returned from database is useable '''
# Check status code of request
req.raise_for_status() # if codes not in 200s; error raise
# Proper status code, but check if server returned a warning
try:
output = req.jso... | python | def process_request(self, req):
''' Checks to see if data returned from database is useable '''
# Check status code of request
req.raise_for_status() # if codes not in 200s; error raise
# Proper status code, but check if server returned a warning
try:
output = req.jso... | [
"def",
"process_request",
"(",
"self",
",",
"req",
")",
":",
"# Check status code of request",
"req",
".",
"raise_for_status",
"(",
")",
"# if codes not in 200s; error raise",
"# Proper status code, but check if server returned a warning",
"try",
":",
"output",
"=",
"req",
... | Checks to see if data returned from database is useable | [
"Checks",
"to",
"see",
"if",
"data",
"returned",
"from",
"database",
"is",
"useable"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L111-L128 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | Client.is_equal | def is_equal(self, string1, string2):
''' Simple string comparator '''
return string1.lower().strip() == string2.lower().strip() | python | def is_equal(self, string1, string2):
''' Simple string comparator '''
return string1.lower().strip() == string2.lower().strip() | [
"def",
"is_equal",
"(",
"self",
",",
"string1",
",",
"string2",
")",
":",
"return",
"string1",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")",
"==",
"string2",
".",
"lower",
"(",
")",
".",
"strip",
"(",
")"
] | Simple string comparator | [
"Simple",
"string",
"comparator"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L130-L132 |
tgbugs/pyontutils | ilxutils/ilxutils/simple_scicrunch_client.py | Client.get_data_from_ilx | def get_data_from_ilx(self, ilx_id):
''' Gets full meta data (expect their annotations and relationships) from is ILX ID '''
ilx_id = self.fix_ilx(ilx_id)
url_base = self.base_path + "ilx/search/identifier/{identifier}?key={APIKEY}"
url = url_base.format(identifier=ilx_id, APIKEY=self.AP... | python | def get_data_from_ilx(self, ilx_id):
''' Gets full meta data (expect their annotations and relationships) from is ILX ID '''
ilx_id = self.fix_ilx(ilx_id)
url_base = self.base_path + "ilx/search/identifier/{identifier}?key={APIKEY}"
url = url_base.format(identifier=ilx_id, APIKEY=self.AP... | [
"def",
"get_data_from_ilx",
"(",
"self",
",",
"ilx_id",
")",
":",
"ilx_id",
"=",
"self",
".",
"fix_ilx",
"(",
"ilx_id",
")",
"url_base",
"=",
"self",
".",
"base_path",
"+",
"\"ilx/search/identifier/{identifier}?key={APIKEY}\"",
"url",
"=",
"url_base",
".",
"form... | Gets full meta data (expect their annotations and relationships) from is ILX ID | [
"Gets",
"full",
"meta",
"data",
"(",
"expect",
"their",
"annotations",
"and",
"relationships",
")",
"from",
"is",
"ILX",
"ID"
] | train | https://github.com/tgbugs/pyontutils/blob/3d913db29c177db39151592909a4f56170ef8b35/ilxutils/ilxutils/simple_scicrunch_client.py#L152-L160 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.