_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q246300
remove_filtered_nodes
train
def remove_filtered_nodes(graph, node_predicates=None): """Remove nodes passing the given node predicates. :param pybel.BELGraph graph: A BEL graph
python
{ "resource": "" }
q246301
get_subgraph_by_neighborhood
train
def get_subgraph_by_neighborhood(graph, nodes: Iterable[BaseEntity]): """Get a BEL graph around the neighborhoods of the given nodes. Returns none if no nodes are in the graph. :param pybel.BELGraph graph: A BEL graph :param nodes: An iterable of BEL nodes :return: A BEL graph induced around the n...
python
{ "resource": "" }
q246302
get_gene_modification_language
train
def get_gene_modification_language(identifier_qualified: ParserElement) -> ParserElement: """Build a gene modification parser.""" gmod_identifier = MatchFirst([ identifier_qualified,
python
{ "resource": "" }
q246303
expand_dict
train
def expand_dict(flat_dict, sep='_'): """Expand a flattened dictionary. :param dict flat_dict: a nested dictionary that has been flattened so the keys are composite :param str sep: the separator between concatenated keys :rtype: dict
python
{ "resource": "" }
q246304
tokenize_version
train
def tokenize_version(version_string: str) -> Tuple[int, int, int]: """Tokenize a version string to a tuple. Truncates qualifiers like ``-dev``. :param version_string: A version string :return: A tuple representing the version string >>> tokenize_version('0.1.2-dev') (0, 1, 2) """ befo...
python
{ "resource": "" }
q246305
parse_datetime
train
def parse_datetime(s: str) -> datetime.date: """Try to parse a datetime object from a standard datetime format or date format.""" for fmt in (CREATION_DATE_FMT, PUBLISHED_DATE_FMT, PUBLISHED_DATE_FMT_2): try: dt = datetime.strptime(s, fmt) except
python
{ "resource": "" }
q246306
_get_edge_tuple
train
def _get_edge_tuple(source, target, edge_data: EdgeData, ) -> Tuple[str, str, str, Optional[str], Tuple[str, Optional[Tuple], Optional[Tuple]]]: """Convert an edge to a consistent tuple. :param BaseEntity source: The source BEL node :param BaseEnt...
python
{ "resource": "" }
q246307
hash_edge
train
def hash_edge(source, target, edge_data: EdgeData) -> str: """Convert an edge tuple to a SHA-512 hash. :param BaseEntity source: The source BEL node :param BaseEntity target: The target BEL node :param edge_data: The edge's data dictionary :return: A
python
{ "resource": "" }
q246308
subdict_matches
train
def subdict_matches(target: Mapping, query: Mapping, partial_match: bool = True) -> bool: """Check if all the keys in the query dict are in the target dict, and that their values match. 1. Checks that all keys in the query dict are in the target dict 2. Matches the values of the keys in the query dict ...
python
{ "resource": "" }
q246309
hash_dump
train
def hash_dump(data) -> str: """Hash an arbitrary JSON dictionary by dumping it in sorted order, encoding it in UTF-8, then hashing the bytes. :param data: An arbitrary JSON-serializable object :type
python
{ "resource": "" }
q246310
hash_evidence
train
def hash_evidence(text: str, type: str, reference: str) -> str: """Create a hash for an evidence and its citation. :param text: The evidence text :param type: The corresponding citation type :param reference: The citation reference
python
{ "resource": "" }
q246311
canonicalize_edge
train
def canonicalize_edge(edge_data: EdgeData) -> Tuple[str, Optional[Tuple], Optional[Tuple]]: """Canonicalize the edge to a tuple based on the relation, subject modifications, and object modifications.""" return (
python
{ "resource": "" }
q246312
_canonicalize_edge_modifications
train
def _canonicalize_edge_modifications(edge_data: EdgeData) -> Optional[Tuple]: """Return the SUBJECT or OBJECT entry of a PyBEL edge data dictionary as a canonical tuple.""" if edge_data is None: return modifier = edge_data.get(MODIFIER) location = edge_data.get(LOCATION) effect = edge_data....
python
{ "resource": "" }
q246313
get_subgraphs_by_citation
train
def get_subgraphs_by_citation(graph): """Stratify the graph based on citations. :type graph: pybel.BELGraph :rtype: dict[tuple[str,str],pybel.BELGraph] """ rv = defaultdict(graph.fresh_copy) for u, v, key, data in graph.edges(keys=True, data=True): if CITATION not in data:
python
{ "resource": "" }
q246314
ControlParser.raise_for_missing_citation
train
def raise_for_missing_citation(self, line: str, position: int) -> None: """Raise an exception if there is no citation present in the parser.
python
{ "resource": "" }
q246315
ControlParser.handle_annotation_key
train
def handle_annotation_key(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle an annotation key before parsing to validate that it's either enumerated or as a regex. :raise: MissingCitationException or UndefinedAnnotationWarning """ key =
python
{ "resource": "" }
q246316
ControlParser.handle_set_statement_group
train
def handle_set_statement_group(self, _, __, tokens: ParseResults) -> ParseResults:
python
{ "resource": "" }
q246317
ControlParser.handle_set_evidence
train
def handle_set_evidence(self, _, __, tokens: ParseResults) -> ParseResults:
python
{ "resource": "" }
q246318
ControlParser.handle_set_command
train
def handle_set_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle a ``SET X = "Y"`` statement.""" key, value = tokens['key'], tokens['value']
python
{ "resource": "" }
q246319
ControlParser.handle_unset_statement_group
train
def handle_unset_statement_group(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Unset the statement group, or raises an exception if it is not set. :raises: MissingAnnotationKeyWarning """ if self.statement_group is None:
python
{ "resource": "" }
q246320
ControlParser.handle_unset_citation
train
def handle_unset_citation(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Unset the citation, or raise an exception if it is not set. :raises: MissingAnnotationKeyWarning """ if not self.citation:
python
{ "resource": "" }
q246321
ControlParser.handle_unset_evidence
train
def handle_unset_evidence(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Unset the evidence, or throws an exception if it is not already set. The value for ``tokens[EVIDENCE]`` corresponds to which alternate of SupportingText or Evidence was used in the BEL script. ...
python
{ "resource": "" }
q246322
ControlParser.validate_unset_command
train
def validate_unset_command(self, line: str, position: int, annotation: str) -> None: """Raise an exception when trying to ``UNSET X`` if ``X`` is not already set. :raises: MissingAnnotationKeyWarning """ if annotation not in
python
{ "resource": "" }
q246323
ControlParser.handle_unset_command
train
def handle_unset_command(self, line: str, position: int, tokens: ParseResults) -> ParseResults: """Handle an ``UNSET X`` statement or raises an exception if it is not already set. :raises: MissingAnnotationKeyWarning """ key =
python
{ "resource": "" }
q246324
ControlParser.get_annotations
train
def get_annotations(self) -> Dict: """Get the current annotations.""" return { EVIDENCE: self.evidence,
python
{ "resource": "" }
q246325
ControlParser.get_missing_required_annotations
train
def get_missing_required_annotations(self) -> List[str]: """Return missing required annotations.""" return [ required_annotation
python
{ "resource": "" }
q246326
ControlParser.clear_citation
train
def clear_citation(self): """Clear the citation and if citation clearing is enabled, clear the evidence and annotations.""" self.citation.clear()
python
{ "resource": "" }
q246327
ControlParser.clear
train
def clear(self): """Clear the statement_group, citation, evidence, and annotations.""" self.statement_group = None
python
{ "resource": "" }
q246328
map_cbn
train
def map_cbn(d): """Pre-processes the JSON from the CBN. - removes statements without evidence, or with placeholder evidence :param dict d: Raw JGIF from the CBN :return: Preprocessed JGIF :rtype: dict """ for i, edge in enumerate(d['graph']['edges']): if 'metadata' not in d['graph'...
python
{ "resource": "" }
q246329
from_jgif
train
def from_jgif(graph_jgif_dict): """Build a BEL graph from a JGIF JSON object. :param dict graph_jgif_dict: The JSON object representing the graph in JGIF format :rtype: BELGraph """ graph = BELGraph() root = graph_jgif_dict['graph'] if 'label' in root: graph.name = root['label'] ...
python
{ "resource": "" }
q246330
to_jgif
train
def to_jgif(graph): """Build a JGIF dictionary from a BEL graph. :param pybel.BELGraph graph: A BEL graph :return: A JGIF dictionary :rtype: dict .. warning:: Untested! This format is not general purpose and is therefore time is not heavily invested. If you want to use Cytoscape.j...
python
{ "resource": "" }
q246331
get_subgraph
train
def get_subgraph(graph, seed_method: Optional[str] = None, seed_data: Optional[Any] = None, expand_nodes: Optional[List[BaseEntity]] = None, remove_nodes: Optional[List[BaseEntity]] = None, ): """Run a pipeline query on graph with ...
python
{ "resource": "" }
q246332
_remove_pathologies_oop
train
def _remove_pathologies_oop(graph): """Remove pathology nodes from the graph.""" rv = graph.copy() victims = [ node for node in rv
python
{ "resource": "" }
q246333
get_random_path
train
def get_random_path(graph) -> List[BaseEntity]: """Get a random path from the graph as a list of nodes. :param pybel.BELGraph graph: A BEL graph """ wg = graph.to_undirected() nodes = wg.nodes() def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]: """Get a pair of random nodes."""...
python
{ "resource": "" }
q246334
to_bytes
train
def to_bytes(graph: BELGraph, protocol: int = HIGHEST_PROTOCOL) -> bytes: """Convert a graph to bytes with pickle. Note that the pickle module has some incompatibilities between Python 2 and 3. To export a universally importable
python
{ "resource": "" }
q246335
from_pickle
train
def from_pickle(path: Union[str, BinaryIO], check_version: bool = True) -> BELGraph: """Read a graph from a pickle file. :param path: File or filename to read. Filenames ending in .gz
python
{ "resource": "" }
q246336
build_annotation_dict_all_filter
train
def build_annotation_dict_all_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: """Build an edge predicate for edges whose annotations are super-dictionaries of the given dictionary. If no annotations are given, will always evaluate to true. :param annotations: The annotation query dict t...
python
{ "resource": "" }
q246337
build_annotation_dict_any_filter
train
def build_annotation_dict_any_filter(annotations: Mapping[str, Iterable[str]]) -> EdgePredicate: """Build an edge predicate that passes for edges whose data dictionaries match the given dictionary. If the given dictionary is empty, will always evaluate to true. :param annotations: The annotation query dic...
python
{ "resource": "" }
q246338
build_upstream_edge_predicate
train
def build_upstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: """Build an edge predicate that pass for relations for which one of the given nodes is the object.""" nodes = set(nodes) def upstream_filter(graph: BELGraph, u: BaseEntity, v: BaseEntity, k: str) -> bool:
python
{ "resource": "" }
q246339
build_downstream_edge_predicate
train
def build_downstream_edge_predicate(nodes: Iterable[BaseEntity]) -> EdgePredicate: """Build an edge predicate that passes for edges for which one of the given nodes is the subject.""" nodes = set(nodes)
python
{ "resource": "" }
q246340
build_relation_predicate
train
def build_relation_predicate(relations: Strings) -> EdgePredicate: """Build an edge predicate that passes for edges with the given relation.""" if isinstance(relations, str): @edge_predicate def relation_predicate(edge_data: EdgeData) -> bool: """Pass for relations matching the enclo...
python
{ "resource": "" }
q246341
_register_function
train
def _register_function(name: str, func, universe: bool, in_place: bool): """Register a transformation function under the given name. :param name: Name to register the function under :param func: A function :param universe: :param in_place: :return: The same function, with additional properties ...
python
{ "resource": "" }
q246342
_build_register_function
train
def _build_register_function(universe: bool, in_place: bool): # noqa: D202 """Build a decorator function to tag transformation functions. :param universe: Does the first positional argument of this function correspond to a universe graph? :param in_place: Does this function return a new graph, or just mod...
python
{ "resource": "" }
q246343
register_deprecated
train
def register_deprecated(deprecated_name: str): """Register a function as deprecated. :param deprecated_name: The old name of the function :return: A decorator Usage: This function must be applied last, since it introspects on the definitions from before >>> @register_deprecated('my_function'...
python
{ "resource": "" }
q246344
get_transformation
train
def get_transformation(name: str): """Get a transformation function and error if its name is not registered. :param name: The name of a function to look up :return: A transformation function :raises MissingPipelineFunctionError: If the given function name is not registered
python
{ "resource": "" }
q246345
_random_edge_iterator
train
def _random_edge_iterator(graph, n_edges: int) -> Iterable[Tuple[BaseEntity, BaseEntity, int, Mapping]]: """Get a random set of edges from the graph and randomly samples a key from each. :type graph: pybel.BELGraph
python
{ "resource": "" }
q246346
get_graph_with_random_edges
train
def get_graph_with_random_edges(graph, n_edges: int): """Build a new graph from a seeding of edges. :type graph: pybel.BELGraph :param n_edges: Number of edges to randomly select from the given graph :rtype: pybel.BELGraph """
python
{ "resource": "" }
q246347
get_random_node
train
def get_random_node(graph, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool] = None, ) -> Optional[BaseEntity]: """Choose a node from the graph with probabilities based on their degrees. :type graph: networkx.Graph :param node_blackl...
python
{ "resource": "" }
q246348
_helper
train
def _helper(result, graph, number_edges_remaining: int, node_blacklist: Set[BaseEntity], invert_degrees: Optional[bool] = None, ): """Help build a random graph. :type result: networkx.Graph :type graph: networkx.Graph """ original_node_cou...
python
{ "resource": "" }
q246349
get_random_subgraph
train
def get_random_subgraph(graph, number_edges=None, number_seed_edges=None, seed=None, invert_degrees=None): """Generate a random subgraph based on weighted random walks from random seed edges. :type graph: pybel.BELGraph graph :param Optional[int] number_edges: Maximum number of edges. Defaults to :dat...
python
{ "resource": "" }
q246350
WeightedRandomGenerator.next_index
train
def next_index(self) -> int: """Get a random index.""" return
python
{ "resource": "" }
q246351
Author.from_name
train
def from_name(cls, name): """Create an author by name, automatically populating the hash."""
python
{ "resource": "" }
q246352
Author.has_name_in
train
def has_name_in(cls, names): """Build a filter if the author has any of the given names.""" return cls.sha512.in_({
python
{ "resource": "" }
q246353
raise_for_old_graph
train
def raise_for_old_graph(graph): """Raise an ImportVersionWarning if the BEL graph was produced by a legacy version of PyBEL. :raises ImportVersionWarning: If the BEL graph was produced by a legacy version of PyBEL """
python
{ "resource": "" }
q246354
nest
train
def nest(*content): """Define a delimited list by enumerating each element of the list.""" if len(content) == 0: raise ValueError('no arguments supplied')
python
{ "resource": "" }
q246355
triple
train
def triple(subject, relation, obj): """Build a simple triple in PyParsing that has a ``subject relation object`` format."""
python
{ "resource": "" }
q246356
get_truncation_language
train
def get_truncation_language() -> ParserElement: """Build a parser for protein truncations.""" l1 = truncation_tag + nest(amino_acid(AMINO_ACID) + ppc.integer(TRUNCATION_POSITION)) l1.setParseAction(_handle_trunc)
python
{ "resource": "" }
q246357
aliases_categories
train
def aliases_categories(chr): """Retrieves the script block alias and unicode category for a unicode character. >>> categories.aliases_categories('A') ('LATIN', 'L') >>> categories.aliases_categories('τ') ('GREEK', 'L') >>> categories.aliases_categories('-') ('COMMON', 'Pd') :param chr:...
python
{ "resource": "" }
q246358
is_mixed_script
train
def is_mixed_script(string, allowed_aliases=['COMMON']): """Checks if ``string`` contains mixed-scripts content, excluding script blocks aliases in ``allowed_aliases``. E.g. ``B. C`` is not considered mixed-scripts by default: it contains characters from **Latin** and **Common**, but **Common** is excl...
python
{ "resource": "" }
q246359
is_confusable
train
def is_confusable(string, greedy=False, preferred_aliases=[]): """Checks if ``string`` contains characters which might be confusable with characters from ``preferred_aliases``. If ``greedy=False``, it will only return the first confusable character found without looking at the rest of the string, ``gre...
python
{ "resource": "" }
q246360
generate_categories
train
def generate_categories(): """Generates the categories JSON data file from the unicode specification. :return: True for success, raises otherwise. :rtype: bool """ # inspired by https://gist.github.com/anonymous/2204527 code_points_ranges = [] iso_15924_aliases = [] categories = [] ...
python
{ "resource": "" }
q246361
docstring_to_markdown
train
def docstring_to_markdown(docstring): """Convert a Python object's docstring to markdown Parameters ---------- docstring : str The docstring body. Returns ---------- clean_lst : list The markdown formatted docstring as lines (str) in a Python list. """ new_docstrin...
python
{ "resource": "" }
q246362
object_to_markdownpage
train
def object_to_markdownpage(obj_name, obj, s=''): """Generate the markdown documentation of a Python object. Parameters ---------- obj_name : str Name of the Python object. obj : object Python object (class, method, function, ...) s : str (default: '') A string to which t...
python
{ "resource": "" }
q246363
import_package
train
def import_package(rel_path_to_package, package_name): """Imports a python package into the current namespace. Parameters ---------- rel_path_to_package : str Path to the package containing director relative from this script's directory. package_name : str The name of the pa...
python
{ "resource": "" }
q246364
get_functions_and_classes
train
def get_functions_and_classes(package): """Retun lists of functions and classes from a package. Parameters ---------- package : python package object Returns -------- list, list : list of classes and functions Each sublist consists of [name, member] sublists. """ classes, ...
python
{ "resource": "" }
q246365
generate_api_docs
train
def generate_api_docs(package, api_dir, clean=False, printlog=True): """Generate a module level API documentation of a python package. Description ----------- Generates markdown API files for each module in a Python package whereas the structure is as follows: `package/package.subpackage/packag...
python
{ "resource": "" }
q246366
summarize_methdods_and_functions
train
def summarize_methdods_and_functions(api_modules, out_dir, printlog=False, clean=True, str_above_header=''): """Generates subpacke-level summary files. Description ----------- A function to generate subpacke-level summary markdow...
python
{ "resource": "" }
q246367
PandasPdb.fetch_pdb
train
def fetch_pdb(self, pdb_code): """Fetches PDB file contents from the Protein Databank at rcsb.org. Parameters ---------- pdb_code : str A 4-letter PDB code, e.g., "3eiy". Returns ---------
python
{ "resource": "" }
q246368
PandasPdb.get
train
def get(self, s, df=None, invert=False, records=('ATOM', 'HETATM')): """Filter PDB DataFrames by properties Parameters ---------- s : str in {'main chain', 'hydrogen', 'c-alpha', 'heavy'} String to specify which entries to return. df : pandas.DataFrame, default: No...
python
{ "resource": "" }
q246369
PandasPdb.impute_element
train
def impute_element(self, records=('ATOM', 'HETATM'), inplace=False): """Impute element_symbol from atom_name section. Parameters ---------- records : iterable, default: ('ATOM', 'HETATM') Coordinate sections for which the element symbols should be imputed. ...
python
{ "resource": "" }
q246370
PandasPdb.rmsd
train
def rmsd(df1, df2, s=None, invert=False): """Compute the Root Mean Square Deviation between molecules. Parameters ---------- df1 : pandas.DataFrame DataFrame with HETATM, ATOM, and/or ANISOU entries. df2 : pandas.DataFrame Second DataFrame for RMSD compu...
python
{ "resource": "" }
q246371
PandasPdb._init_get_dict
train
def _init_get_dict(): """Initialize dictionary for filter operations.""" get_dict = {'main chain': PandasPdb._get_mainchain, 'hydrogen': PandasPdb._get_hydrogen, 'c-alpha': PandasPdb._get_calpha,
python
{ "resource": "" }
q246372
PandasPdb._read_pdb
train
def _read_pdb(path): """Read PDB file from local drive.""" r_mode = 'r' openf = open if path.endswith('.gz'): r_mode = 'rb' openf = gzip.open with openf(path, r_mode) as f: txt = f.read()
python
{ "resource": "" }
q246373
PandasPdb._fetch_pdb
train
def _fetch_pdb(pdb_code): """Load PDB file from rcsb.org.""" txt = None url = 'http://www.rcsb.org/pdb/files/%s.pdb' % pdb_code.lower() try: response = urlopen(url) txt = response.read() if sys.version_info[0] >= 3: txt = txt.decode('ut...
python
{ "resource": "" }
q246374
PandasPdb._parse_header_code
train
def _parse_header_code(self): """Extract header information and PDB code.""" code, header = '', '' if 'OTHERS' in self.df: header = (self.df['OTHERS'][self.df['OTHERS']['record_name'] == 'HEADER'])
python
{ "resource": "" }
q246375
PandasPdb._get_mainchain
train
def _get_mainchain(df, invert): """Return only main chain atom entries from a DataFrame""" if invert: mc = df[(df['atom_name'] != 'C') & (df['atom_name'] != 'O') & (df['atom_name'] != 'N') & (df['atom_name'] != 'CA')] else: ...
python
{ "resource": "" }
q246376
PandasPdb.amino3to1
train
def amino3to1(self, record='ATOM', residue_col='residue_name', fillna='?'): """Creates 1-letter amino acid codes from DataFrame Non-canonical amino-acids are converted as follows: ASH (protonated ASP) => D CYX (disulfide-bonded CYS) => C GLH (protonated GLU) =>...
python
{ "resource": "" }
q246377
PandasPdb.to_pdb
train
def to_pdb(self, path, records=None, gz=False, append_newline=True): """Write record DataFrames to a PDB file or gzipped PDB file. Parameters ---------- path : str A valid output path for the pdb file records : iterable, default: None A list of PDB recor...
python
{ "resource": "" }
q246378
split_multimol2
train
def split_multimol2(mol2_path): r""" Splits a multi-mol2 file into individual Mol2 file contents. Parameters ----------- mol2_path : str Path to the multi-mol2 file. Parses gzip files if the filepath ends on .gz. Returns ----------- A generator object for lists for every ex...
python
{ "resource": "" }
q246379
PandasMol2._load_mol2
train
def _load_mol2(self, mol2_lines, mol2_code, columns): """Load mol2 contents into assert_raise_message instance""" if columns is None: col_names = COLUMN_NAMES col_types = COLUMN_TYPES else: col_names, col_types = [], [] for i in range(len(columns))...
python
{ "resource": "" }
q246380
PandasMol2.read_mol2_from_list
train
def read_mol2_from_list(self, mol2_lines, mol2_code, columns=None): r"""Reads Mol2 file from a list into DataFrames Attributes ---------- mol2_lines : list A list of lines containing the mol2 file contents. For example, ['@<TRIPOS>MOLECULE\n', 'ZINC3...
python
{ "resource": "" }
q246381
PandasMol2._get_atomsection
train
def _get_atomsection(mol2_lst): """Returns atom section from mol2 provided as list of strings""" started = False for idx, s in enumerate(mol2_lst): if s.startswith('@<TRIPOS>ATOM'): first_idx = idx + 1
python
{ "resource": "" }
q246382
PandasMol2.rmsd
train
def rmsd(df1, df2, heavy_only=True): """Compute the Root Mean Square Deviation between molecules Parameters ---------- df1 : pandas.DataFrame DataFrame with HETATM, ATOM, and/or ANISOU entries df2 : pandas.DataFrame Second DataFrame for RMSD computation a...
python
{ "resource": "" }
q246383
PandasMol2.distance
train
def distance(self, xyz=(0.00, 0.00, 0.00)): """Computes Euclidean distance between atoms in self.df and a 3D point. Parameters ---------- xyz : tuple (0.00, 0.00, 0.00) X, Y, and Z coordinate of the reference center
python
{ "resource": "" }
q246384
ConfigYamlEnv.parse_yaml_file
train
def parse_yaml_file(self, path): """Parse yaml file at ``path`` and return a dict.""" with open(path, 'r') as fp: data = yaml.safe_load(fp) if not data: return {} def traverse(namespace, d): cfg = {} for key, val in d.items(): ...
python
{ "resource": "" }
q246385
import_class
train
def import_class(clspath): """Given a clspath, returns the class. Note: This is a really simplistic implementation. """ modpath, clsname = split_clspath(clspath)
python
{ "resource": "" }
q246386
upper_lower_none
train
def upper_lower_none(arg): """Validate arg value as "upper", "lower", or None.""" if not arg: return arg arg = arg.strip().lower() if arg in
python
{ "resource": "" }
q246387
setup
train
def setup(app): """Register domain and directive in Sphinx.""" app.add_domain(EverettDomain) app.add_directive('autocomponent', AutoComponentDirective)
python
{ "resource": "" }
q246388
EverettComponent.handle_signature
train
def handle_signature(self, sig, signode): """Create a signature for this thing.""" if sig != 'Configuration': signode.clear() # Add "component" which is the type of this thing signode += addnodes.desc_annotation('component ', 'component ') if '.' in sig:...
python
{ "resource": "" }
q246389
EverettComponent.add_target_and_index
train
def add_target_and_index(self, name, sig, signode): """Add a target and index for this thing.""" targetname = '%s-%s' % (self.objtype, name) if targetname not in self.state.document.ids: signode['names'].append(targetname) signode['ids'].append(targetname) si...
python
{ "resource": "" }
q246390
AutoComponentDirective.add_line
train
def add_line(self, line, source, *lineno): """Add a line to the result"""
python
{ "resource": "" }
q246391
AutoComponentDirective.generate_docs
train
def generate_docs(self, clspath, more_content): """Generate documentation for this configman class""" obj = import_class(clspath) sourcename = 'docstring of %s' % clspath all_options = [] indent = ' ' config = obj.get_required_config() if config.options: ...
python
{ "resource": "" }
q246392
qualname
train
def qualname(thing): """Return the dot name for a given thing. >>> import everett.manager >>> qualname(str) 'str' >>> qualname(everett.manager.parse_class) 'everett.manager.parse_class' >>> qualname(everett.manager) 'everett.manager' """ parts = [] # Add the module, unless...
python
{ "resource": "" }
q246393
parse_bool
train
def parse_bool(val): """Parse a bool value. Handles a series of values, but you should probably standardize on "true" and "false". >>> parse_bool('y') True >>> parse_bool('FALSE') False """ true_vals = ('t', 'true', 'yes', 'y', '1', 'on') false_vals = ('f', 'false', 'no', 'n',...
python
{ "resource": "" }
q246394
parse_env_file
train
def parse_env_file(envfile): """Parse the content of an iterable of lines as ``.env``. Return a dict of config variables. >>> parse_env_file(['DUDE=Abides']) {'DUDE': 'Abides'} """ data = {} for line_no, line in enumerate(envfile): line = line.strip() if not line or line.s...
python
{ "resource": "" }
q246395
parse_class
train
def parse_class(val): """Parse a string, imports the module and returns the class. >>> parse_class('hashlib.md5') <built-in function openssl_md5> """ module, class_name = val.rsplit('.', 1) module = importlib.import_module(module) try:
python
{ "resource": "" }
q246396
generate_uppercase_key
train
def generate_uppercase_key(key, namespace=None): """Given a key and a namespace, generates a final uppercase key.""" if namespace: namespace = [part for
python
{ "resource": "" }
q246397
get_key_from_envs
train
def get_key_from_envs(envs, key): """Return the value of a key from the given dict respecting namespaces. Data can also be a list of data dicts. """ # if it
python
{ "resource": "" }
q246398
ConfigManagerBase.with_options
train
def with_options(self, component): """Apply options component options to this configuration.""" options = component.get_required_config()
python
{ "resource": "" }
q246399
ConfigOverride.decorate
train
def decorate(self, fun): """Decorate a function for overriding configuration.""" @wraps(fun) def _decorated(*args, **kwargs): # Push the config, run the function and pop it afterwards. self.push_config()
python
{ "resource": "" }