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 |
|---|---|---|---|---|---|---|---|---|---|---|
belbio/bel | bel/edge/computed.py | compute_edges | def compute_edges(ast: BELAst, spec: BELSpec) -> Edges:
"""Compute edges"""
edges = []
if ast.bel_object.__class__.__name__ == "BELAst":
edges.append(ast.bel_object)
process_ast(edges, ast, spec)
return edges | python | def compute_edges(ast: BELAst, spec: BELSpec) -> Edges:
"""Compute edges"""
edges = []
if ast.bel_object.__class__.__name__ == "BELAst":
edges.append(ast.bel_object)
process_ast(edges, ast, spec)
return edges | [
"def",
"compute_edges",
"(",
"ast",
":",
"BELAst",
",",
"spec",
":",
"BELSpec",
")",
"->",
"Edges",
":",
"edges",
"=",
"[",
"]",
"if",
"ast",
".",
"bel_object",
".",
"__class__",
".",
"__name__",
"==",
"\"BELAst\"",
":",
"edges",
".",
"append",
"(",
... | Compute edges | [
"Compute",
"edges"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/computed.py#L23-L31 |
belbio/bel | bel/edge/computed.py | process_rule | def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec):
"""Process computed edge rule
Recursively processes BELAst versus a single computed edge rule
Args:
edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs
ast (Function): BEL Function AS... | python | def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec):
"""Process computed edge rule
Recursively processes BELAst versus a single computed edge rule
Args:
edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs
ast (Function): BEL Function AS... | [
"def",
"process_rule",
"(",
"edges",
":",
"Edges",
",",
"ast",
":",
"Function",
",",
"rule",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"spec",
":",
"BELSpec",
")",
":",
"ast_type",
"=",
"ast",
".",
"__class__",
".",
"__name__",
"trigger_functio... | Process computed edge rule
Recursively processes BELAst versus a single computed edge rule
Args:
edges (List[Tuple[Union[Function, str], str, Function]]): BEL Edge ASTs
ast (Function): BEL Function AST
rule (Mapping[str, Any]: computed edge rule | [
"Process",
"computed",
"edge",
"rule"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/computed.py#L151-L224 |
belbio/bel | bel/resources/ortholog.py | load_orthologs | def load_orthologs(fo: IO, metadata: dict):
"""Load orthologs into ArangoDB
Args:
fo: file obj - orthologs file
metadata: dict containing the metadata for orthologs
"""
version = metadata["metadata"]["version"]
# LOAD ORTHOLOGS INTO ArangoDB
with timy.Timer("Load Orthologs") a... | python | def load_orthologs(fo: IO, metadata: dict):
"""Load orthologs into ArangoDB
Args:
fo: file obj - orthologs file
metadata: dict containing the metadata for orthologs
"""
version = metadata["metadata"]["version"]
# LOAD ORTHOLOGS INTO ArangoDB
with timy.Timer("Load Orthologs") a... | [
"def",
"load_orthologs",
"(",
"fo",
":",
"IO",
",",
"metadata",
":",
"dict",
")",
":",
"version",
"=",
"metadata",
"[",
"\"metadata\"",
"]",
"[",
"\"version\"",
"]",
"# LOAD ORTHOLOGS INTO ArangoDB",
"with",
"timy",
".",
"Timer",
"(",
"\"Load Orthologs\"",
")"... | Load orthologs into ArangoDB
Args:
fo: file obj - orthologs file
metadata: dict containing the metadata for orthologs | [
"Load",
"orthologs",
"into",
"ArangoDB"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/resources/ortholog.py#L19-L64 |
belbio/bel | bel/resources/ortholog.py | orthologs_iterator | def orthologs_iterator(fo, version):
"""Ortholog node and edge iterator"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
for line in f:
edge = json.loads(line)
if "metadata" in edge:
source = edg... | python | def orthologs_iterator(fo, version):
"""Ortholog node and edge iterator"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0)
with gzip.open(fo, "rt") as f:
for line in f:
edge = json.loads(line)
if "metadata" in edge:
source = edg... | [
"def",
"orthologs_iterator",
"(",
"fo",
",",
"version",
")",
":",
"species_list",
"=",
"config",
"[",
"\"bel_resources\"",
"]",
".",
"get",
"(",
"\"species_list\"",
",",
"[",
"]",
")",
"fo",
".",
"seek",
"(",
"0",
")",
"with",
"gzip",
".",
"open",
"(",... | Ortholog node and edge iterator | [
"Ortholog",
"node",
"and",
"edge",
"iterator"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/resources/ortholog.py#L67-L131 |
belbio/bel | bel/edge/edges.py | nanopub_to_edges | def nanopub_to_edges(nanopub: dict = {}, rules: List[str] = [], orthologize_targets: list = []):
"""Process nanopub into edges and load into EdgeStore
Args:
nanopub: BEL Nanopub
rules: list of compute rules to process
orthologize_targets: list of species in TAX:<int> format
Returns... | python | def nanopub_to_edges(nanopub: dict = {}, rules: List[str] = [], orthologize_targets: list = []):
"""Process nanopub into edges and load into EdgeStore
Args:
nanopub: BEL Nanopub
rules: list of compute rules to process
orthologize_targets: list of species in TAX:<int> format
Returns... | [
"def",
"nanopub_to_edges",
"(",
"nanopub",
":",
"dict",
"=",
"{",
"}",
",",
"rules",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
",",
"orthologize_targets",
":",
"list",
"=",
"[",
"]",
")",
":",
"# Collect input values ########################################... | Process nanopub into edges and load into EdgeStore
Args:
nanopub: BEL Nanopub
rules: list of compute rules to process
orthologize_targets: list of species in TAX:<int> format
Returns:
list: of edges
Edge object:
{
"edge": {
"subject": {
... | [
"Process",
"nanopub",
"into",
"edges",
"and",
"load",
"into",
"EdgeStore"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/edges.py#L33-L196 |
belbio/bel | bel/edge/edges.py | extract_ast_species | def extract_ast_species(ast):
"""Extract species from ast.species set of tuples (id, label)"""
species_id = "None"
species_label = "None"
species = [
(species_id, species_label) for (species_id, species_label) in ast.species if species_id
]
if len(species) == 1:
(species_id, sp... | python | def extract_ast_species(ast):
"""Extract species from ast.species set of tuples (id, label)"""
species_id = "None"
species_label = "None"
species = [
(species_id, species_label) for (species_id, species_label) in ast.species if species_id
]
if len(species) == 1:
(species_id, sp... | [
"def",
"extract_ast_species",
"(",
"ast",
")",
":",
"species_id",
"=",
"\"None\"",
"species_label",
"=",
"\"None\"",
"species",
"=",
"[",
"(",
"species_id",
",",
"species_label",
")",
"for",
"(",
"species_id",
",",
"species_label",
")",
"in",
"ast",
".",
"sp... | Extract species from ast.species set of tuples (id, label) | [
"Extract",
"species",
"from",
"ast",
".",
"species",
"set",
"of",
"tuples",
"(",
"id",
"label",
")"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/edges.py#L199-L217 |
belbio/bel | bel/edge/edges.py | generate_assertion_edge_info | def generate_assertion_edge_info(
assertions: List[dict],
orthologize_targets: List[str],
bel_version: str,
api_url: str,
nanopub_type: str = "",
) -> dict:
"""Create edges (SRO) for assertions given orthologization targets
Args:
assertions: list of BEL statements (SRO object)
... | python | def generate_assertion_edge_info(
assertions: List[dict],
orthologize_targets: List[str],
bel_version: str,
api_url: str,
nanopub_type: str = "",
) -> dict:
"""Create edges (SRO) for assertions given orthologization targets
Args:
assertions: list of BEL statements (SRO object)
... | [
"def",
"generate_assertion_edge_info",
"(",
"assertions",
":",
"List",
"[",
"dict",
"]",
",",
"orthologize_targets",
":",
"List",
"[",
"str",
"]",
",",
"bel_version",
":",
"str",
",",
"api_url",
":",
"str",
",",
"nanopub_type",
":",
"str",
"=",
"\"\"",
","... | Create edges (SRO) for assertions given orthologization targets
Args:
assertions: list of BEL statements (SRO object)
orthologize_targets: list of species in TAX:<int> format
bel_version: to be used for processing assertions
api_url: BEL API url endpoint to use for terminologies and... | [
"Create",
"edges",
"(",
"SRO",
")",
"for",
"assertions",
"given",
"orthologization",
"targets"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/edges.py#L221-L403 |
belbio/bel | bel/edge/edges.py | orthologize_context | def orthologize_context(
orthologize_target: str, annotations: Mapping[str, Any]
) -> Mapping[str, Any]:
"""Orthologize context
Replace Species context with new orthologize target and add a annotation type of OrthologizedFrom
"""
url = f'{config["bel_api"]["servers"]["api_url"]}/terms/{orthologize... | python | def orthologize_context(
orthologize_target: str, annotations: Mapping[str, Any]
) -> Mapping[str, Any]:
"""Orthologize context
Replace Species context with new orthologize target and add a annotation type of OrthologizedFrom
"""
url = f'{config["bel_api"]["servers"]["api_url"]}/terms/{orthologize... | [
"def",
"orthologize_context",
"(",
"orthologize_target",
":",
"str",
",",
"annotations",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"url",
"=",
"f'{config[\"bel_api\"][\"servers\"][\"api_url\"]}/terms/{orth... | Orthologize context
Replace Species context with new orthologize target and add a annotation type of OrthologizedFrom | [
"Orthologize",
"context"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/edge/edges.py#L429-L456 |
belbio/bel | bel/lang/migrate_1_2.py | migrate | def migrate(belstr: str) -> str:
"""Migrate BEL 1 to 2.0.0
Args:
bel: BEL 1
Returns:
bel: BEL 2
"""
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_string() | python | def migrate(belstr: str) -> str:
"""Migrate BEL 1 to 2.0.0
Args:
bel: BEL 1
Returns:
bel: BEL 2
"""
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_string() | [
"def",
"migrate",
"(",
"belstr",
":",
"str",
")",
"->",
"str",
":",
"bo",
".",
"ast",
"=",
"bel",
".",
"lang",
".",
"partialparse",
".",
"get_ast_obj",
"(",
"belstr",
",",
"\"2.0.0\"",
")",
"return",
"migrate_ast",
"(",
"bo",
".",
"ast",
")",
".",
... | Migrate BEL 1 to 2.0.0
Args:
bel: BEL 1
Returns:
bel: BEL 2 | [
"Migrate",
"BEL",
"1",
"to",
"2",
".",
"0",
".",
"0"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L26-L38 |
belbio/bel | bel/lang/migrate_1_2.py | migrate_into_triple | def migrate_into_triple(belstr: str) -> str:
"""Migrate BEL1 assertion into BEL 2.0.0 SRO triple"""
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_triple() | python | def migrate_into_triple(belstr: str) -> str:
"""Migrate BEL1 assertion into BEL 2.0.0 SRO triple"""
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_triple() | [
"def",
"migrate_into_triple",
"(",
"belstr",
":",
"str",
")",
"->",
"str",
":",
"bo",
".",
"ast",
"=",
"bel",
".",
"lang",
".",
"partialparse",
".",
"get_ast_obj",
"(",
"belstr",
",",
"\"2.0.0\"",
")",
"return",
"migrate_ast",
"(",
"bo",
".",
"ast",
")... | Migrate BEL1 assertion into BEL 2.0.0 SRO triple | [
"Migrate",
"BEL1",
"assertion",
"into",
"BEL",
"2",
".",
"0",
".",
"0",
"SRO",
"triple"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L41-L46 |
belbio/bel | bel/lang/migrate_1_2.py | convert | def convert(ast):
"""Convert BEL1 AST Function to BEL2 AST Function"""
if ast and ast.type == "Function":
# Activity function conversion
if (
ast.name != "molecularActivity"
and ast.name in spec["namespaces"]["Activity"]["list"]
):
print("name", ast.n... | python | def convert(ast):
"""Convert BEL1 AST Function to BEL2 AST Function"""
if ast and ast.type == "Function":
# Activity function conversion
if (
ast.name != "molecularActivity"
and ast.name in spec["namespaces"]["Activity"]["list"]
):
print("name", ast.n... | [
"def",
"convert",
"(",
"ast",
")",
":",
"if",
"ast",
"and",
"ast",
".",
"type",
"==",
"\"Function\"",
":",
"# Activity function conversion",
"if",
"(",
"ast",
".",
"name",
"!=",
"\"molecularActivity\"",
"and",
"ast",
".",
"name",
"in",
"spec",
"[",
"\"name... | Convert BEL1 AST Function to BEL2 AST Function | [
"Convert",
"BEL1",
"AST",
"Function",
"to",
"BEL2",
"AST",
"Function"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L65-L105 |
belbio/bel | bel/lang/migrate_1_2.py | convert_tloc | def convert_tloc(ast):
"""Convert BEL1 tloc() to BEL2"""
from_loc_arg = ast.args[1]
to_loc_arg = ast.args[2]
from_loc = Function("fromLoc", spec, parent_function=ast)
from_loc.add_argument(
NSArg(from_loc_arg.namespace, from_loc_arg.value, parent_function=from_loc)
)
to_loc = Functi... | python | def convert_tloc(ast):
"""Convert BEL1 tloc() to BEL2"""
from_loc_arg = ast.args[1]
to_loc_arg = ast.args[2]
from_loc = Function("fromLoc", spec, parent_function=ast)
from_loc.add_argument(
NSArg(from_loc_arg.namespace, from_loc_arg.value, parent_function=from_loc)
)
to_loc = Functi... | [
"def",
"convert_tloc",
"(",
"ast",
")",
":",
"from_loc_arg",
"=",
"ast",
".",
"args",
"[",
"1",
"]",
"to_loc_arg",
"=",
"ast",
".",
"args",
"[",
"2",
"]",
"from_loc",
"=",
"Function",
"(",
"\"fromLoc\"",
",",
"spec",
",",
"parent_function",
"=",
"ast",... | Convert BEL1 tloc() to BEL2 | [
"Convert",
"BEL1",
"tloc",
"()",
"to",
"BEL2"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L108-L125 |
belbio/bel | bel/lang/migrate_1_2.py | convert_activity | def convert_activity(ast):
"""Convert BEL1 activities to BEL2 act()"""
if len(ast.args) > 1:
log.error(f"Activity should not have more than 1 argument {ast.to_string()}")
p_arg = ast.args[0] # protein argument
print("p_arg", p_arg)
ma_arg = Function("ma", bo.spec)
ma_arg.add_argument(... | python | def convert_activity(ast):
"""Convert BEL1 activities to BEL2 act()"""
if len(ast.args) > 1:
log.error(f"Activity should not have more than 1 argument {ast.to_string()}")
p_arg = ast.args[0] # protein argument
print("p_arg", p_arg)
ma_arg = Function("ma", bo.spec)
ma_arg.add_argument(... | [
"def",
"convert_activity",
"(",
"ast",
")",
":",
"if",
"len",
"(",
"ast",
".",
"args",
")",
">",
"1",
":",
"log",
".",
"error",
"(",
"f\"Activity should not have more than 1 argument {ast.to_string()}\"",
")",
"p_arg",
"=",
"ast",
".",
"args",
"[",
"0",
"]",... | Convert BEL1 activities to BEL2 act() | [
"Convert",
"BEL1",
"activities",
"to",
"BEL2",
"act",
"()"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L128-L144 |
belbio/bel | bel/lang/migrate_1_2.py | convert_pmod | def convert_pmod(pmod):
"""Update BEL1 pmod() protein modification term"""
if pmod.args[0].value in spec["bel1_migration"]["protein_modifications"]:
pmod.args[0].value = spec["bel1_migration"]["protein_modifications"][
pmod.args[0].value
]
return pmod | python | def convert_pmod(pmod):
"""Update BEL1 pmod() protein modification term"""
if pmod.args[0].value in spec["bel1_migration"]["protein_modifications"]:
pmod.args[0].value = spec["bel1_migration"]["protein_modifications"][
pmod.args[0].value
]
return pmod | [
"def",
"convert_pmod",
"(",
"pmod",
")",
":",
"if",
"pmod",
".",
"args",
"[",
"0",
"]",
".",
"value",
"in",
"spec",
"[",
"\"bel1_migration\"",
"]",
"[",
"\"protein_modifications\"",
"]",
":",
"pmod",
".",
"args",
"[",
"0",
"]",
".",
"value",
"=",
"sp... | Update BEL1 pmod() protein modification term | [
"Update",
"BEL1",
"pmod",
"()",
"protein",
"modification",
"term"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L147-L155 |
belbio/bel | bel/lang/migrate_1_2.py | convert_fus | def convert_fus(ast):
"""Convert BEL1 fus() to BEL2 fus()"""
parent_fn_name = ast.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
fus1_ns = ast.args[0].namespace
fus1_val = ast.args[0].value
arg_fus = ast.args[1]
fus_args = [None, "?", "... | python | def convert_fus(ast):
"""Convert BEL1 fus() to BEL2 fus()"""
parent_fn_name = ast.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
fus1_ns = ast.args[0].namespace
fus1_val = ast.args[0].value
arg_fus = ast.args[1]
fus_args = [None, "?", "... | [
"def",
"convert_fus",
"(",
"ast",
")",
":",
"parent_fn_name",
"=",
"ast",
".",
"name_short",
"prefix_list",
"=",
"{",
"\"p\"",
":",
"\"p.\"",
",",
"\"r\"",
":",
"\"r.\"",
",",
"\"g\"",
":",
"\"c.\"",
"}",
"prefix",
"=",
"prefix_list",
"[",
"parent_fn_name"... | Convert BEL1 fus() to BEL2 fus() | [
"Convert",
"BEL1",
"fus",
"()",
"to",
"BEL2",
"fus",
"()"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L158-L208 |
belbio/bel | bel/lang/migrate_1_2.py | convert_sub | def convert_sub(sub):
"""Convert BEL1 sub() to BEL2 var()"""
args = sub.args
(ref_aa, pos, new_aa) = args
parent_fn_name = sub.parent_function.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
new_var_arg = f'"{prefix}{spec["namespaces"]["Amin... | python | def convert_sub(sub):
"""Convert BEL1 sub() to BEL2 var()"""
args = sub.args
(ref_aa, pos, new_aa) = args
parent_fn_name = sub.parent_function.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
new_var_arg = f'"{prefix}{spec["namespaces"]["Amin... | [
"def",
"convert_sub",
"(",
"sub",
")",
":",
"args",
"=",
"sub",
".",
"args",
"(",
"ref_aa",
",",
"pos",
",",
"new_aa",
")",
"=",
"args",
"parent_fn_name",
"=",
"sub",
".",
"parent_function",
".",
"name_short",
"prefix_list",
"=",
"{",
"\"p\"",
":",
"\"... | Convert BEL1 sub() to BEL2 var() | [
"Convert",
"BEL1",
"sub",
"()",
"to",
"BEL2",
"var",
"()"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L211-L227 |
belbio/bel | bel/lang/migrate_1_2.py | convert_trunc | def convert_trunc(trunc):
"""Convert BEL1 trunc() to BEL2 var()"""
parent_fn_name = trunc.parent_function.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
new_var_arg = f'"truncated at {trunc.args[0].value}"'
new_var = bel.lang.ast.Function("var"... | python | def convert_trunc(trunc):
"""Convert BEL1 trunc() to BEL2 var()"""
parent_fn_name = trunc.parent_function.name_short
prefix_list = {"p": "p.", "r": "r.", "g": "c."}
prefix = prefix_list[parent_fn_name]
new_var_arg = f'"truncated at {trunc.args[0].value}"'
new_var = bel.lang.ast.Function("var"... | [
"def",
"convert_trunc",
"(",
"trunc",
")",
":",
"parent_fn_name",
"=",
"trunc",
".",
"parent_function",
".",
"name_short",
"prefix_list",
"=",
"{",
"\"p\"",
":",
"\"p.\"",
",",
"\"r\"",
":",
"\"r.\"",
",",
"\"g\"",
":",
"\"c.\"",
"}",
"prefix",
"=",
"prefi... | Convert BEL1 trunc() to BEL2 var() | [
"Convert",
"BEL1",
"trunc",
"()",
"to",
"BEL2",
"var",
"()"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/migrate_1_2.py#L230-L243 |
belbio/bel | bel/db/arangodb.py | get_user_creds | def get_user_creds(username, password):
"""Get username/password
Use provided username and password OR in config OR blank in that order
"""
username = utils.first_true(
[username, config["bel_api"]["servers"]["arangodb_username"]], default=""
)
password = utils.first_true(
[pass... | python | def get_user_creds(username, password):
"""Get username/password
Use provided username and password OR in config OR blank in that order
"""
username = utils.first_true(
[username, config["bel_api"]["servers"]["arangodb_username"]], default=""
)
password = utils.first_true(
[pass... | [
"def",
"get_user_creds",
"(",
"username",
",",
"password",
")",
":",
"username",
"=",
"utils",
".",
"first_true",
"(",
"[",
"username",
",",
"config",
"[",
"\"bel_api\"",
"]",
"[",
"\"servers\"",
"]",
"[",
"\"arangodb_username\"",
"]",
"]",
",",
"default",
... | Get username/password
Use provided username and password OR in config OR blank in that order | [
"Get",
"username",
"/",
"password"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L46-L59 |
belbio/bel | bel/db/arangodb.py | get_client | def get_client(host=None, port=None, username=None, password=None, enable_logging=True):
"""Get arango client and edgestore db handle"""
host = utils.first_true(
[host, config["bel_api"]["servers"]["arangodb_host"], "localhost"]
)
port = utils.first_true([port, config["bel_api"]["servers"]["ara... | python | def get_client(host=None, port=None, username=None, password=None, enable_logging=True):
"""Get arango client and edgestore db handle"""
host = utils.first_true(
[host, config["bel_api"]["servers"]["arangodb_host"], "localhost"]
)
port = utils.first_true([port, config["bel_api"]["servers"]["ara... | [
"def",
"get_client",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"enable_logging",
"=",
"True",
")",
":",
"host",
"=",
"utils",
".",
"first_true",
"(",
"[",
"host",
",",
"config... | Get arango client and edgestore db handle | [
"Get",
"arango",
"client",
"and",
"edgestore",
"db",
"handle"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L62-L87 |
belbio/bel | bel/db/arangodb.py | get_edgestore_handle | def get_edgestore_handle(
client: arango.client.ArangoClient,
username=None,
password=None,
edgestore_db_name: str = edgestore_db_name,
edgestore_edges_name: str = edgestore_edges_name,
edgestore_nodes_name: str = edgestore_nodes_name,
edgestore_pipeline_name: str = edgestore_pipeline_name,
... | python | def get_edgestore_handle(
client: arango.client.ArangoClient,
username=None,
password=None,
edgestore_db_name: str = edgestore_db_name,
edgestore_edges_name: str = edgestore_edges_name,
edgestore_nodes_name: str = edgestore_nodes_name,
edgestore_pipeline_name: str = edgestore_pipeline_name,
... | [
"def",
"get_edgestore_handle",
"(",
"client",
":",
"arango",
".",
"client",
".",
"ArangoClient",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"edgestore_db_name",
":",
"str",
"=",
"edgestore_db_name",
",",
"edgestore_edges_name",
":",
"str",
... | Get Edgestore arangodb database handle
Args:
client (arango.client.ArangoClient): Description
username (None, optional): Description
password (None, optional): Description
edgestore_db_name (str, optional): Description
edgestore_edges_name (str, optional): Description
... | [
"Get",
"Edgestore",
"arangodb",
"database",
"handle"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L97-L186 |
belbio/bel | bel/db/arangodb.py | get_belns_handle | def get_belns_handle(client, username=None, password=None):
"""Get BEL namespace arango db handle"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belns"
try:
if username and pas... | python | def get_belns_handle(client, username=None, password=None):
"""Get BEL namespace arango db handle"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belns"
try:
if username and pas... | [
"def",
"get_belns_handle",
"(",
"client",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"get_user_creds",
"(",
"username",
",",
"password",
")",
"sys_db",
"=",
"client",
".",
"db",
"(",
... | Get BEL namespace arango db handle | [
"Get",
"BEL",
"namespace",
"arango",
"db",
"handle"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L189-L244 |
belbio/bel | bel/db/arangodb.py | get_belapi_handle | def get_belapi_handle(client, username=None, password=None):
"""Get BEL API arango db handle"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belapi"
try:
if username and passwor... | python | def get_belapi_handle(client, username=None, password=None):
"""Get BEL API arango db handle"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belapi"
try:
if username and passwor... | [
"def",
"get_belapi_handle",
"(",
"client",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"get_user_creds",
"(",
"username",
",",
"password",
")",
"sys_db",
"=",
"client",
".",
"db",
"(",... | Get BEL API arango db handle | [
"Get",
"BEL",
"API",
"arango",
"db",
"handle"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L247-L279 |
belbio/bel | bel/db/arangodb.py | delete_database | def delete_database(client, db_name, username=None, password=None):
"""Delete Arangodb database
"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
try:
return sys_db.delete_database(db_name)
except Excepti... | python | def delete_database(client, db_name, username=None, password=None):
"""Delete Arangodb database
"""
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
try:
return sys_db.delete_database(db_name)
except Excepti... | [
"def",
"delete_database",
"(",
"client",
",",
"db_name",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"(",
"username",
",",
"password",
")",
"=",
"get_user_creds",
"(",
"username",
",",
"password",
")",
"sys_db",
"=",
"client",
"... | Delete Arangodb database | [
"Delete",
"Arangodb",
"database"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L282-L294 |
belbio/bel | bel/db/arangodb.py | batch_load_docs | def batch_load_docs(db, doc_iterator, on_duplicate="replace"):
"""Batch load documents
Args:
db: ArangoDB client database handle
doc_iterator: function that yields (collection_name, doc_key, doc)
on_duplicate: defaults to replace, but can be error, update, replace or ignore
ht... | python | def batch_load_docs(db, doc_iterator, on_duplicate="replace"):
"""Batch load documents
Args:
db: ArangoDB client database handle
doc_iterator: function that yields (collection_name, doc_key, doc)
on_duplicate: defaults to replace, but can be error, update, replace or ignore
ht... | [
"def",
"batch_load_docs",
"(",
"db",
",",
"doc_iterator",
",",
"on_duplicate",
"=",
"\"replace\"",
")",
":",
"batch_size",
"=",
"100",
"counter",
"=",
"0",
"collections",
"=",
"{",
"}",
"docs",
"=",
"{",
"}",
"if",
"on_duplicate",
"not",
"in",
"[",
"\"er... | Batch load documents
Args:
db: ArangoDB client database handle
doc_iterator: function that yields (collection_name, doc_key, doc)
on_duplicate: defaults to replace, but can be error, update, replace or ignore
https://python-driver-for-arangodb.readthedocs.io/en/master/specs.html?h... | [
"Batch",
"load",
"documents"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L297-L340 |
belbio/bel | bel/db/arangodb.py | arango_id_to_key | def arango_id_to_key(_id):
"""Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed
"""
key = re.sub(r"[^a-zA-Z0-9\_\-\:\.\@\(\)\+\,\=\;\$\!\*\%]+", r"_", _id)
if len(key) > ... | python | def arango_id_to_key(_id):
"""Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed
"""
key = re.sub(r"[^a-zA-Z0-9\_\-\:\.\@\(\)\+\,\=\;\$\!\*\%]+", r"_", _id)
if len(key) > ... | [
"def",
"arango_id_to_key",
"(",
"_id",
")",
":",
"key",
"=",
"re",
".",
"sub",
"(",
"r\"[^a-zA-Z0-9\\_\\-\\:\\.\\@\\(\\)\\+\\,\\=\\;\\$\\!\\*\\%]+\"",
",",
"r\"_\"",
",",
"_id",
")",
"if",
"len",
"(",
"key",
")",
">",
"254",
":",
"log",
".",
"error",
"(",
... | Remove illegal chars from potential arangodb _key (id)
Args:
_id (str): id to be used as arangodb _key
Returns:
(str): _key value with illegal chars removed | [
"Remove",
"illegal",
"chars",
"from",
"potential",
"arangodb",
"_key",
"(",
"id",
")"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/arangodb.py#L343-L361 |
belbio/bel | bel/resources/resource.py | load_resource | def load_resource(resource_url: str, forceupdate: bool = False):
"""Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the ... | python | def load_resource(resource_url: str, forceupdate: bool = False):
"""Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the ... | [
"def",
"load_resource",
"(",
"resource_url",
":",
"str",
",",
"forceupdate",
":",
"bool",
"=",
"False",
")",
":",
"log",
".",
"info",
"(",
"f\"Loading resource {resource_url}\"",
")",
"try",
":",
"# Download resource",
"fo",
"=",
"bel",
".",
"utils",
".",
"d... | Load BEL Resource file
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
resource_url: URL from which to download the resource to load into the BEL API
forceupdate: force full update - e.g. don't leave Elasti... | [
"Load",
"BEL",
"Resource",
"file"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/resources/resource.py#L23-L61 |
belbio/bel | bel/terms/terms.py | get_terms | def get_terms(term_id):
"""Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids
"""
search_body = {
"query": {
"bool": {
"should": [
{"term": {"id": term_id}},
... | python | def get_terms(term_id):
"""Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids
"""
search_body = {
"query": {
"bool": {
"should": [
{"term": {"id": term_id}},
... | [
"def",
"get_terms",
"(",
"term_id",
")",
":",
"search_body",
"=",
"{",
"\"query\"",
":",
"{",
"\"bool\"",
":",
"{",
"\"should\"",
":",
"[",
"{",
"\"term\"",
":",
"{",
"\"id\"",
":",
"term_id",
"}",
"}",
",",
"{",
"\"term\"",
":",
"{",
"\"alt_ids\"",
... | Get term(s) using term_id - given term_id may match multiple term records
Term ID has to match either the id, alt_ids or obsolete_ids | [
"Get",
"term",
"(",
"s",
")",
"using",
"term_id",
"-",
"given",
"term_id",
"may",
"match",
"multiple",
"term",
"records"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/terms.py#L22-L46 |
belbio/bel | bel/terms/terms.py | get_equivalents | def get_equivalents(term_id: str) -> List[Mapping[str, Union[str, bool]]]:
"""Get equivalents given ns:id
Args:
term_id (str): term id
Returns:
List[Mapping[str, Union[str, bool]]]: e.g. [{'term_id': 'HGNC:5', 'namespace': 'HGNC'}, 'primary': False]
"""
try:
errors = []
... | python | def get_equivalents(term_id: str) -> List[Mapping[str, Union[str, bool]]]:
"""Get equivalents given ns:id
Args:
term_id (str): term id
Returns:
List[Mapping[str, Union[str, bool]]]: e.g. [{'term_id': 'HGNC:5', 'namespace': 'HGNC'}, 'primary': False]
"""
try:
errors = []
... | [
"def",
"get_equivalents",
"(",
"term_id",
":",
"str",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Union",
"[",
"str",
",",
"bool",
"]",
"]",
"]",
":",
"try",
":",
"errors",
"=",
"[",
"]",
"terms",
"=",
"get_terms",
"(",
"term_id",
")",
"... | Get equivalents given ns:id
Args:
term_id (str): term id
Returns:
List[Mapping[str, Union[str, bool]]]: e.g. [{'term_id': 'HGNC:5', 'namespace': 'HGNC'}, 'primary': False] | [
"Get",
"equivalents",
"given",
"ns",
":",
"id"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/terms.py#L49-L98 |
belbio/bel | bel/terms/terms.py | get_normalized_term | def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str:
"""Get normalized term"""
if equivalents and len(equivalents) > 0:
for start_ns in namespace_targets:
if re.match(start_ns, term_id):
for target_ns in namespace_targets[start_ns]:
... | python | def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str:
"""Get normalized term"""
if equivalents and len(equivalents) > 0:
for start_ns in namespace_targets:
if re.match(start_ns, term_id):
for target_ns in namespace_targets[start_ns]:
... | [
"def",
"get_normalized_term",
"(",
"term_id",
":",
"str",
",",
"equivalents",
":",
"list",
",",
"namespace_targets",
":",
"dict",
")",
"->",
"str",
":",
"if",
"equivalents",
"and",
"len",
"(",
"equivalents",
")",
">",
"0",
":",
"for",
"start_ns",
"in",
"... | Get normalized term | [
"Get",
"normalized",
"term"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/terms.py#L101-L113 |
belbio/bel | bel/terms/terms.py | get_labels | def get_labels(term_ids: list) -> dict:
"""Get term labels given term ids
This only takes the first term returned for a term_id so use the
unique term_id for a term not an alternate id that might not be unique.
"""
term_labels = {}
for term_id in term_ids:
term = get_terms(term_id)
... | python | def get_labels(term_ids: list) -> dict:
"""Get term labels given term ids
This only takes the first term returned for a term_id so use the
unique term_id for a term not an alternate id that might not be unique.
"""
term_labels = {}
for term_id in term_ids:
term = get_terms(term_id)
... | [
"def",
"get_labels",
"(",
"term_ids",
":",
"list",
")",
"->",
"dict",
":",
"term_labels",
"=",
"{",
"}",
"for",
"term_id",
"in",
"term_ids",
":",
"term",
"=",
"get_terms",
"(",
"term_id",
")",
"term_labels",
"[",
"term_id",
"]",
"=",
"term",
"[",
"0",
... | Get term labels given term ids
This only takes the first term returned for a term_id so use the
unique term_id for a term not an alternate id that might not be unique. | [
"Get",
"term",
"labels",
"given",
"term",
"ids"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/terms.py#L116-L127 |
belbio/bel | bel/terms/terms.py | get_normalized_terms | def get_normalized_terms(term_id: str) -> dict:
"""Get normalized terms - canonical/decanonical forms"""
canonical = term_id
decanonical = term_id
canonical_namespace_targets = config["bel"]["lang"]["canonical"]
decanonical_namespace_targets = config["bel"]["lang"]["decanonical"]
results = get... | python | def get_normalized_terms(term_id: str) -> dict:
"""Get normalized terms - canonical/decanonical forms"""
canonical = term_id
decanonical = term_id
canonical_namespace_targets = config["bel"]["lang"]["canonical"]
decanonical_namespace_targets = config["bel"]["lang"]["decanonical"]
results = get... | [
"def",
"get_normalized_terms",
"(",
"term_id",
":",
"str",
")",
"->",
"dict",
":",
"canonical",
"=",
"term_id",
"decanonical",
"=",
"term_id",
"canonical_namespace_targets",
"=",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"lang\"",
"]",
"[",
"\"canonical\"",
"]",
"... | Get normalized terms - canonical/decanonical forms | [
"Get",
"normalized",
"terms",
"-",
"canonical",
"/",
"decanonical",
"forms"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/terms.py#L130-L149 |
PayEx/pypayex | payex/handlers.py | BaseHandler._get_params | def _get_params(self):
"""
Generate SOAP parameters.
"""
params = {'accountNumber': self._service.accountNumber}
# Include object variables that are in field_order
for key, val in self.__dict__.iteritems():
if key in self.field_order:
... | python | def _get_params(self):
"""
Generate SOAP parameters.
"""
params = {'accountNumber': self._service.accountNumber}
# Include object variables that are in field_order
for key, val in self.__dict__.iteritems():
if key in self.field_order:
... | [
"def",
"_get_params",
"(",
"self",
")",
":",
"params",
"=",
"{",
"'accountNumber'",
":",
"self",
".",
"_service",
".",
"accountNumber",
"}",
"# Include object variables that are in field_order",
"for",
"key",
",",
"val",
"in",
"self",
".",
"__dict__",
".",
"iter... | Generate SOAP parameters. | [
"Generate",
"SOAP",
"parameters",
"."
] | train | https://github.com/PayEx/pypayex/blob/549ba7cc47f112a7aa3417fcf87ff07bc74cd9ab/payex/handlers.py#L26-L61 |
PayEx/pypayex | payex/handlers.py | BaseHandler._generate_hash | def _generate_hash(self):
"""
Generates a hash based on the specific fields for the method.
"""
self.hash = None
str_hash = ''
for key, val in self._get_params().iteritems():
str_hash += smart_str(val)
# Append the encryption... | python | def _generate_hash(self):
"""
Generates a hash based on the specific fields for the method.
"""
self.hash = None
str_hash = ''
for key, val in self._get_params().iteritems():
str_hash += smart_str(val)
# Append the encryption... | [
"def",
"_generate_hash",
"(",
"self",
")",
":",
"self",
".",
"hash",
"=",
"None",
"str_hash",
"=",
"''",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_get_params",
"(",
")",
".",
"iteritems",
"(",
")",
":",
"str_hash",
"+=",
"smart_str",
"(",
"val",... | Generates a hash based on the specific fields for the method. | [
"Generates",
"a",
"hash",
"based",
"on",
"the",
"specific",
"fields",
"for",
"the",
"method",
"."
] | train | https://github.com/PayEx/pypayex/blob/549ba7cc47f112a7aa3417fcf87ff07bc74cd9ab/payex/handlers.py#L63-L78 |
PayEx/pypayex | payex/handlers.py | BaseHandler._send_request | def _send_request(self):
"""
Make the SOAP request and convert the result to a dictionary.
"""
# Generate the hash variable and parameters
self._generate_hash()
params = self._get_params()
# Make the SOAP request
try:
resp = s... | python | def _send_request(self):
"""
Make the SOAP request and convert the result to a dictionary.
"""
# Generate the hash variable and parameters
self._generate_hash()
params = self._get_params()
# Make the SOAP request
try:
resp = s... | [
"def",
"_send_request",
"(",
"self",
")",
":",
"# Generate the hash variable and parameters",
"self",
".",
"_generate_hash",
"(",
")",
"params",
"=",
"self",
".",
"_get_params",
"(",
")",
"# Make the SOAP request",
"try",
":",
"resp",
"=",
"self",
".",
"_endpoint"... | Make the SOAP request and convert the result to a dictionary. | [
"Make",
"the",
"SOAP",
"request",
"and",
"convert",
"the",
"result",
"to",
"a",
"dictionary",
"."
] | train | https://github.com/PayEx/pypayex/blob/549ba7cc47f112a7aa3417fcf87ff07bc74cd9ab/payex/handlers.py#L80-L107 |
PayEx/pypayex | payex/handlers.py | BaseHandler.client_factory | def client_factory(self):
"""
Custom client factory to set proxy options.
"""
if self._service.production:
url = self.production_url
else:
url = self.testing_url
proxy_options = dict()
https_proxy_setting = os.environ.get(... | python | def client_factory(self):
"""
Custom client factory to set proxy options.
"""
if self._service.production:
url = self.production_url
else:
url = self.testing_url
proxy_options = dict()
https_proxy_setting = os.environ.get(... | [
"def",
"client_factory",
"(",
"self",
")",
":",
"if",
"self",
".",
"_service",
".",
"production",
":",
"url",
"=",
"self",
".",
"production_url",
"else",
":",
"url",
"=",
"self",
".",
"testing_url",
"proxy_options",
"=",
"dict",
"(",
")",
"https_proxy_sett... | Custom client factory to set proxy options. | [
"Custom",
"client",
"factory",
"to",
"set",
"proxy",
"options",
"."
] | train | https://github.com/PayEx/pypayex/blob/549ba7cc47f112a7aa3417fcf87ff07bc74cd9ab/payex/handlers.py#L109-L128 |
DNX/django-keyboard-shorcuts | keyboard_shortcuts/utils.py | get_combination_action | def get_combination_action(combination):
"""
Prepares the action for a keyboard combination, also filters another
"strange" actions declared by the user.
"""
accepted_actions = ('link', 'js')
for action in accepted_actions:
if action in combination:
return {action: combinatio... | python | def get_combination_action(combination):
"""
Prepares the action for a keyboard combination, also filters another
"strange" actions declared by the user.
"""
accepted_actions = ('link', 'js')
for action in accepted_actions:
if action in combination:
return {action: combinatio... | [
"def",
"get_combination_action",
"(",
"combination",
")",
":",
"accepted_actions",
"=",
"(",
"'link'",
",",
"'js'",
")",
"for",
"action",
"in",
"accepted_actions",
":",
"if",
"action",
"in",
"combination",
":",
"return",
"{",
"action",
":",
"combination",
"[",... | Prepares the action for a keyboard combination, also filters another
"strange" actions declared by the user. | [
"Prepares",
"the",
"action",
"for",
"a",
"keyboard",
"combination",
"also",
"filters",
"another",
"strange",
"actions",
"declared",
"by",
"the",
"user",
"."
] | train | https://github.com/DNX/django-keyboard-shorcuts/blob/dd853a410614c0dfb7cce803eafda9b5fa47be17/keyboard_shortcuts/utils.py#L14-L23 |
DNX/django-keyboard-shorcuts | keyboard_shortcuts/utils.py | get_processed_hotkeys | def get_processed_hotkeys(hotkeys=None):
"""
Process passed dict with key combinations or the HOTKEYS dict from
settings.
"""
hotkeys = hotkeys or ks_settings.HOTKEYS
processed_hotkeys = AutoVivification()
if not hotkeys:
return processed_hotkeys
for combination in hotkeys:
... | python | def get_processed_hotkeys(hotkeys=None):
"""
Process passed dict with key combinations or the HOTKEYS dict from
settings.
"""
hotkeys = hotkeys or ks_settings.HOTKEYS
processed_hotkeys = AutoVivification()
if not hotkeys:
return processed_hotkeys
for combination in hotkeys:
... | [
"def",
"get_processed_hotkeys",
"(",
"hotkeys",
"=",
"None",
")",
":",
"hotkeys",
"=",
"hotkeys",
"or",
"ks_settings",
".",
"HOTKEYS",
"processed_hotkeys",
"=",
"AutoVivification",
"(",
")",
"if",
"not",
"hotkeys",
":",
"return",
"processed_hotkeys",
"for",
"com... | Process passed dict with key combinations or the HOTKEYS dict from
settings. | [
"Process",
"passed",
"dict",
"with",
"key",
"combinations",
"or",
"the",
"HOTKEYS",
"dict",
"from",
"settings",
"."
] | train | https://github.com/DNX/django-keyboard-shorcuts/blob/dd853a410614c0dfb7cce803eafda9b5fa47be17/keyboard_shortcuts/utils.py#L26-L46 |
DNX/django-keyboard-shorcuts | keyboard_shortcuts/utils.py | get_key_codes | def get_key_codes(keys):
"""
Calculates the list of key codes from a string with key combinations.
Ex: 'CTRL+A' will produce the output (17, 65)
"""
keys = keys.strip().upper().split('+')
codes = list()
for key in keys:
code = ks_settings.KEY_CODES.get(key.strip())
if code:
... | python | def get_key_codes(keys):
"""
Calculates the list of key codes from a string with key combinations.
Ex: 'CTRL+A' will produce the output (17, 65)
"""
keys = keys.strip().upper().split('+')
codes = list()
for key in keys:
code = ks_settings.KEY_CODES.get(key.strip())
if code:
... | [
"def",
"get_key_codes",
"(",
"keys",
")",
":",
"keys",
"=",
"keys",
".",
"strip",
"(",
")",
".",
"upper",
"(",
")",
".",
"split",
"(",
"'+'",
")",
"codes",
"=",
"list",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"code",
"=",
"ks_settings",
".",
... | Calculates the list of key codes from a string with key combinations.
Ex: 'CTRL+A' will produce the output (17, 65) | [
"Calculates",
"the",
"list",
"of",
"key",
"codes",
"from",
"a",
"string",
"with",
"key",
"combinations",
".",
"Ex",
":",
"CTRL",
"+",
"A",
"will",
"produce",
"the",
"output",
"(",
"17",
"65",
")"
] | train | https://github.com/DNX/django-keyboard-shorcuts/blob/dd853a410614c0dfb7cce803eafda9b5fa47be17/keyboard_shortcuts/utils.py#L49-L60 |
belbio/bel | bel/lang/belobj.py | BEL.parse | def parse(
self,
assertion: Union[str, Mapping[str, str]],
strict: bool = False,
parseinfo: bool = False,
rule_name: str = "start",
error_level: str = "WARNING",
) -> "BEL":
"""Parse and semantically validate BEL statement
Parses a BEL statement given... | python | def parse(
self,
assertion: Union[str, Mapping[str, str]],
strict: bool = False,
parseinfo: bool = False,
rule_name: str = "start",
error_level: str = "WARNING",
) -> "BEL":
"""Parse and semantically validate BEL statement
Parses a BEL statement given... | [
"def",
"parse",
"(",
"self",
",",
"assertion",
":",
"Union",
"[",
"str",
",",
"Mapping",
"[",
"str",
",",
"str",
"]",
"]",
",",
"strict",
":",
"bool",
"=",
"False",
",",
"parseinfo",
":",
"bool",
"=",
"False",
",",
"rule_name",
":",
"str",
"=",
"... | Parse and semantically validate BEL statement
Parses a BEL statement given as a string and returns an AST, Abstract Syntax Tree (defined in ast.py)
if the statement is valid, self.parse_valid. Else, the AST attribute is None and there will be validation error messages
in self.validation_message... | [
"Parse",
"and",
"semantically",
"validate",
"BEL",
"statement"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L92-L184 |
belbio/bel | bel/lang/belobj.py | BEL.canonicalize | def canonicalize(self, namespace_targets: Mapping[str, List[str]] = None) -> "BEL":
"""
Takes an AST and returns a canonicalized BEL statement string.
Args:
namespace_targets (Mapping[str, List[str]]): override default canonicalization
settings of BEL.bio API api_url... | python | def canonicalize(self, namespace_targets: Mapping[str, List[str]] = None) -> "BEL":
"""
Takes an AST and returns a canonicalized BEL statement string.
Args:
namespace_targets (Mapping[str, List[str]]): override default canonicalization
settings of BEL.bio API api_url... | [
"def",
"canonicalize",
"(",
"self",
",",
"namespace_targets",
":",
"Mapping",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"\"BEL\"",
":",
"# TODO Need to order position independent args",
"if",
"not",
"self",
".",
"ast",
":",
"retu... | Takes an AST and returns a canonicalized BEL statement string.
Args:
namespace_targets (Mapping[str, List[str]]): override default canonicalization
settings of BEL.bio API api_url - see {api_url}/status to get default canonicalization settings
Returns:
BEL: retu... | [
"Takes",
"an",
"AST",
"and",
"returns",
"a",
"canonicalized",
"BEL",
"statement",
"string",
"."
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L202-L228 |
belbio/bel | bel/lang/belobj.py | BEL.collect_nsarg_norms | def collect_nsarg_norms(self):
"""Adds canonical and decanonical values to NSArgs in AST
This prepares the AST object for (de)canonicalization
"""
start_time = datetime.datetime.now()
self.ast = bel_utils.populate_ast_nsarg_defaults(self.ast, self.ast)
self.ast.collecte... | python | def collect_nsarg_norms(self):
"""Adds canonical and decanonical values to NSArgs in AST
This prepares the AST object for (de)canonicalization
"""
start_time = datetime.datetime.now()
self.ast = bel_utils.populate_ast_nsarg_defaults(self.ast, self.ast)
self.ast.collecte... | [
"def",
"collect_nsarg_norms",
"(",
"self",
")",
":",
"start_time",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"self",
".",
"ast",
"=",
"bel_utils",
".",
"populate_ast_nsarg_defaults",
"(",
"self",
".",
"ast",
",",
"self",
".",
"ast",
")",
"s... | Adds canonical and decanonical values to NSArgs in AST
This prepares the AST object for (de)canonicalization | [
"Adds",
"canonical",
"and",
"decanonical",
"values",
"to",
"NSArgs",
"in",
"AST"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L256-L277 |
belbio/bel | bel/lang/belobj.py | BEL.orthologize | def orthologize(self, species_id: str) -> "BEL":
"""Orthologize BEL AST to given species_id
Will return original entity (ns:value) if no ortholog found.
Args:
species_id (str): species id to convert genes/rna/proteins into
Returns:
BEL: returns self
"""... | python | def orthologize(self, species_id: str) -> "BEL":
"""Orthologize BEL AST to given species_id
Will return original entity (ns:value) if no ortholog found.
Args:
species_id (str): species id to convert genes/rna/proteins into
Returns:
BEL: returns self
"""... | [
"def",
"orthologize",
"(",
"self",
",",
"species_id",
":",
"str",
")",
"->",
"\"BEL\"",
":",
"if",
"not",
"self",
".",
"ast",
":",
"return",
"self",
"# Collect canonical/decanonical NSArg values",
"if",
"not",
"self",
".",
"ast",
".",
"collected_orthologs",
":... | Orthologize BEL AST to given species_id
Will return original entity (ns:value) if no ortholog found.
Args:
species_id (str): species id to convert genes/rna/proteins into
Returns:
BEL: returns self | [
"Orthologize",
"BEL",
"AST",
"to",
"given",
"species_id"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L279-L301 |
belbio/bel | bel/lang/belobj.py | BEL.collect_orthologs | def collect_orthologs(self, species: list) -> "BEL":
"""Add NSArg orthologs for given species (TAX:<number format)
This will add orthologs to the AST for all of the given species (as available).
NOTE: This will run self.collect_nsarg_norms() first if not already available
as we need th... | python | def collect_orthologs(self, species: list) -> "BEL":
"""Add NSArg orthologs for given species (TAX:<number format)
This will add orthologs to the AST for all of the given species (as available).
NOTE: This will run self.collect_nsarg_norms() first if not already available
as we need th... | [
"def",
"collect_orthologs",
"(",
"self",
",",
"species",
":",
"list",
")",
"->",
"\"BEL\"",
":",
"if",
"not",
"species",
":",
"return",
"self",
"species_labels",
"=",
"bel",
".",
"terms",
".",
"terms",
".",
"get_labels",
"(",
"species",
")",
"# Collect can... | Add NSArg orthologs for given species (TAX:<number format)
This will add orthologs to the AST for all of the given species (as available).
NOTE: This will run self.collect_nsarg_norms() first if not already available
as we need the canonical forms of the NSArgs | [
"Add",
"NSArg",
"orthologs",
"for",
"given",
"species",
"(",
"TAX",
":",
"<number",
"format",
")"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L303-L337 |
belbio/bel | bel/lang/belobj.py | BEL.compute_edges | def compute_edges(
self, rules: List[str] = None, ast_result=False, fmt="medium"
) -> List[Mapping[str, Any]]:
"""Computed edges from primary BEL statement
Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures.
Will run only the list of co... | python | def compute_edges(
self, rules: List[str] = None, ast_result=False, fmt="medium"
) -> List[Mapping[str, Any]]:
"""Computed edges from primary BEL statement
Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures.
Will run only the list of co... | [
"def",
"compute_edges",
"(",
"self",
",",
"rules",
":",
"List",
"[",
"str",
"]",
"=",
"None",
",",
"ast_result",
"=",
"False",
",",
"fmt",
"=",
"\"medium\"",
")",
"->",
"List",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"if",
"not",
"... | Computed edges from primary BEL statement
Takes an AST and generates all computed edges based on BEL Specification YAML computed signatures.
Will run only the list of computed edge rules if given.
Args:
rules (list): a list of rules to filter; only the rules in this list will be ap... | [
"Computed",
"edges",
"from",
"primary",
"BEL",
"statement"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L339-L372 |
belbio/bel | bel/lang/belobj.py | BEL.to_triple | def to_triple(self, fmt: str = "medium") -> dict:
"""Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | python | def to_triple(self, fmt: str = "medium") -> dict:
"""Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | [
"def",
"to_triple",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"\"medium\"",
")",
"->",
"dict",
":",
"if",
"self",
".",
"ast",
":",
"return",
"self",
".",
"ast",
".",
"to_triple",
"(",
"ast_obj",
"=",
"self",
".",
"ast",
",",
"fmt",
"=",
"fmt",
")... | Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Ret... | [
"Convert",
"AST",
"object",
"to",
"BEL",
"triple"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L390-L406 |
belbio/bel | bel/lang/belobj.py | BEL.print_tree | def print_tree(self) -> str:
"""Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST
"""
if self.ast:
return self.ast.print_tree(ast_obj=self.ast)
else:
return "" | python | def print_tree(self) -> str:
"""Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST
"""
if self.ast:
return self.ast.print_tree(ast_obj=self.ast)
else:
return "" | [
"def",
"print_tree",
"(",
"self",
")",
"->",
"str",
":",
"if",
"self",
".",
"ast",
":",
"return",
"self",
".",
"ast",
".",
"print_tree",
"(",
"ast_obj",
"=",
"self",
".",
"ast",
")",
"else",
":",
"return",
"\"\""
] | Convert AST object to tree view of BEL AST
Returns:
printed tree of BEL AST | [
"Convert",
"AST",
"object",
"to",
"tree",
"view",
"of",
"BEL",
"AST"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/belobj.py#L408-L418 |
belbio/bel | bel/lang/ast.py | ast_dict_to_objects | def ast_dict_to_objects(ast_dict: Mapping[str, Any], bel_obj) -> BELAst:
"""Convert Tatsu AST dictionary to BEL AST object
Args:
ast_dict (Mapping[str, Any])
Returns:
BELAst: object representing the BEL Statement AST
"""
ast_subject = ast_dict.get("subject", None)
ast_object = ... | python | def ast_dict_to_objects(ast_dict: Mapping[str, Any], bel_obj) -> BELAst:
"""Convert Tatsu AST dictionary to BEL AST object
Args:
ast_dict (Mapping[str, Any])
Returns:
BELAst: object representing the BEL Statement AST
"""
ast_subject = ast_dict.get("subject", None)
ast_object = ... | [
"def",
"ast_dict_to_objects",
"(",
"ast_dict",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"bel_obj",
")",
"->",
"BELAst",
":",
"ast_subject",
"=",
"ast_dict",
".",
"get",
"(",
"\"subject\"",
",",
"None",
")",
"ast_object",
"=",
"ast_dict",
".",
"g... | Convert Tatsu AST dictionary to BEL AST object
Args:
ast_dict (Mapping[str, Any])
Returns:
BELAst: object representing the BEL Statement AST | [
"Convert",
"Tatsu",
"AST",
"dictionary",
"to",
"BEL",
"AST",
"object"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L559-L583 |
belbio/bel | bel/lang/ast.py | BELAst.to_string | def to_string(self, ast_obj=None, fmt: str = "medium") -> str:
"""Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | python | def to_string(self, ast_obj=None, fmt: str = "medium") -> str:
"""Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | [
"def",
"to_string",
"(",
"self",
",",
"ast_obj",
"=",
"None",
",",
"fmt",
":",
"str",
"=",
"\"medium\"",
")",
"->",
"str",
":",
"if",
"not",
"ast_obj",
":",
"ast_obj",
"=",
"self",
"bel_relation",
"=",
"None",
"if",
"self",
".",
"bel_relation",
"and",
... | Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
cano... | [
"Convert",
"AST",
"object",
"to",
"string"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L105-L150 |
belbio/bel | bel/lang/ast.py | BELAst.to_triple | def to_triple(self, ast_obj=None, fmt="medium"):
"""Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | python | def to_triple(self, ast_obj=None, fmt="medium"):
"""Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | [
"def",
"to_triple",
"(",
"self",
",",
"ast_obj",
"=",
"None",
",",
"fmt",
"=",
"\"medium\"",
")",
":",
"if",
"not",
"ast_obj",
":",
"ast_obj",
"=",
"self",
"if",
"self",
".",
"bel_subject",
"and",
"self",
".",
"bel_relation",
"and",
"self",
".",
"bel_o... | Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Ret... | [
"Convert",
"AST",
"object",
"to",
"BEL",
"triple"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L152-L197 |
belbio/bel | bel/lang/ast.py | BELAst.print_tree | def print_tree(self, ast_obj=None):
"""Convert AST object to tree view of BEL AST
Returns:
prints tree of BEL AST to STDOUT
"""
if not ast_obj:
ast_obj = self
if hasattr(self, "bel_subject"):
print("Subject:")
self.bel_subject.pr... | python | def print_tree(self, ast_obj=None):
"""Convert AST object to tree view of BEL AST
Returns:
prints tree of BEL AST to STDOUT
"""
if not ast_obj:
ast_obj = self
if hasattr(self, "bel_subject"):
print("Subject:")
self.bel_subject.pr... | [
"def",
"print_tree",
"(",
"self",
",",
"ast_obj",
"=",
"None",
")",
":",
"if",
"not",
"ast_obj",
":",
"ast_obj",
"=",
"self",
"if",
"hasattr",
"(",
"self",
",",
"\"bel_subject\"",
")",
":",
"print",
"(",
"\"Subject:\"",
")",
"self",
".",
"bel_subject",
... | Convert AST object to tree view of BEL AST
Returns:
prints tree of BEL AST to STDOUT | [
"Convert",
"AST",
"object",
"to",
"tree",
"view",
"of",
"BEL",
"AST"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L204-L237 |
belbio/bel | bel/lang/ast.py | Function.to_string | def to_string(
self,
fmt: str = "medium",
canonicalize: bool = False,
decanonicalize: bool = False,
orthologize: str = None,
) -> str:
"""Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
sh... | python | def to_string(
self,
fmt: str = "medium",
canonicalize: bool = False,
decanonicalize: bool = False,
orthologize: str = None,
) -> str:
"""Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
sh... | [
"def",
"to_string",
"(",
"self",
",",
"fmt",
":",
"str",
"=",
"\"medium\"",
",",
"canonicalize",
":",
"bool",
"=",
"False",
",",
"decanonicalize",
":",
"bool",
"=",
"False",
",",
"orthologize",
":",
"str",
"=",
"None",
",",
")",
"->",
"str",
":",
"ar... | Convert AST object to string
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Returns... | [
"Convert",
"AST",
"object",
"to",
"string"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L315-L341 |
belbio/bel | bel/lang/ast.py | Function.subcomponents | def subcomponents(self, subcomponents):
"""Generate subcomponents of the BEL subject or object
These subcomponents are used for matching parts of a BEL
subject or Object in the Edgestore.
Args:
AST
subcomponents: Pass an empty list to start a new subcomponents ... | python | def subcomponents(self, subcomponents):
"""Generate subcomponents of the BEL subject or object
These subcomponents are used for matching parts of a BEL
subject or Object in the Edgestore.
Args:
AST
subcomponents: Pass an empty list to start a new subcomponents ... | [
"def",
"subcomponents",
"(",
"self",
",",
"subcomponents",
")",
":",
"for",
"arg",
"in",
"self",
".",
"args",
":",
"if",
"arg",
".",
"__class__",
".",
"__name__",
"==",
"\"Function\"",
":",
"subcomponents",
".",
"append",
"(",
"arg",
".",
"to_string",
"(... | Generate subcomponents of the BEL subject or object
These subcomponents are used for matching parts of a BEL
subject or Object in the Edgestore.
Args:
AST
subcomponents: Pass an empty list to start a new subcomponents request
Returns:
List[str]: su... | [
"Generate",
"subcomponents",
"of",
"the",
"BEL",
"subject",
"or",
"object"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L358-L380 |
belbio/bel | bel/lang/ast.py | NSArg.change_nsvalue | def change_nsvalue(self, namespace, value):
"""Deprecated"""
self.namespace = namespace
self.value = value | python | def change_nsvalue(self, namespace, value):
"""Deprecated"""
self.namespace = namespace
self.value = value | [
"def",
"change_nsvalue",
"(",
"self",
",",
"namespace",
",",
"value",
")",
":",
"self",
".",
"namespace",
"=",
"namespace",
"self",
".",
"value",
"=",
"value"
] | Deprecated | [
"Deprecated"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L430-L434 |
belbio/bel | bel/lang/ast.py | NSArg.update_nsval | def update_nsval(
self, *, nsval: str = None, ns: str = None, val: str = None
) -> None:
"""Update Namespace and valueast.
Args:
nsval: e.g. HGNC:AKT1
ns: namespace
val: value of entity
"""
if not (ns and val) and nsval:
(ns, ... | python | def update_nsval(
self, *, nsval: str = None, ns: str = None, val: str = None
) -> None:
"""Update Namespace and valueast.
Args:
nsval: e.g. HGNC:AKT1
ns: namespace
val: value of entity
"""
if not (ns and val) and nsval:
(ns, ... | [
"def",
"update_nsval",
"(",
"self",
",",
"*",
",",
"nsval",
":",
"str",
"=",
"None",
",",
"ns",
":",
"str",
"=",
"None",
",",
"val",
":",
"str",
"=",
"None",
")",
"->",
"None",
":",
"if",
"not",
"(",
"ns",
"and",
"val",
")",
"and",
"nsval",
"... | Update Namespace and valueast.
Args:
nsval: e.g. HGNC:AKT1
ns: namespace
val: value of entity | [
"Update",
"Namespace",
"and",
"valueast",
"."
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L436-L453 |
belbio/bel | bel/lang/ast.py | NSArg.orthologize | def orthologize(self, ortho_species_id, belast):
"""Decanonical ortholog name used"""
if (
self.orthologs
and ortho_species_id in self.orthologs
and ortho_species_id != self.species_id
):
self.orthology_species = ortho_species_id
self.... | python | def orthologize(self, ortho_species_id, belast):
"""Decanonical ortholog name used"""
if (
self.orthologs
and ortho_species_id in self.orthologs
and ortho_species_id != self.species_id
):
self.orthology_species = ortho_species_id
self.... | [
"def",
"orthologize",
"(",
"self",
",",
"ortho_species_id",
",",
"belast",
")",
":",
"if",
"(",
"self",
".",
"orthologs",
"and",
"ortho_species_id",
"in",
"self",
".",
"orthologs",
"and",
"ortho_species_id",
"!=",
"self",
".",
"species_id",
")",
":",
"self",... | Decanonical ortholog name used | [
"Decanonical",
"ortholog",
"name",
"used"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/ast.py#L483-L501 |
belbio/bel | bel/nanopub/belscripts.py | convert_csv_str_to_list | def convert_csv_str_to_list(csv_str: str) -> list:
"""Convert CSV str to list"""
csv_str = re.sub("^\s*{", "", csv_str)
csv_str = re.sub("}\s*$", "", csv_str)
r = csv.reader([csv_str])
row = list(r)[0]
new = []
for col in row:
col = re.sub('^\s*"?\s*', "", col)
col = re.sub(... | python | def convert_csv_str_to_list(csv_str: str) -> list:
"""Convert CSV str to list"""
csv_str = re.sub("^\s*{", "", csv_str)
csv_str = re.sub("}\s*$", "", csv_str)
r = csv.reader([csv_str])
row = list(r)[0]
new = []
for col in row:
col = re.sub('^\s*"?\s*', "", col)
col = re.sub(... | [
"def",
"convert_csv_str_to_list",
"(",
"csv_str",
":",
"str",
")",
"->",
"list",
":",
"csv_str",
"=",
"re",
".",
"sub",
"(",
"\"^\\s*{\"",
",",
"\"\"",
",",
"csv_str",
")",
"csv_str",
"=",
"re",
".",
"sub",
"(",
"\"}\\s*$\"",
",",
"\"\"",
",",
"csv_str... | Convert CSV str to list | [
"Convert",
"CSV",
"str",
"to",
"list"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L34-L47 |
belbio/bel | bel/nanopub/belscripts.py | process_citation | def process_citation(citation_str: str) -> dict:
"""Parse BEL Script Citation string into nanopub_bel citation object"""
citation_obj = {}
citation_list = convert_csv_str_to_list(citation_str)
(citation_type, name, doc_id, pub_date, authors, comment, *extra) = (
citation_list + [None] * 7
... | python | def process_citation(citation_str: str) -> dict:
"""Parse BEL Script Citation string into nanopub_bel citation object"""
citation_obj = {}
citation_list = convert_csv_str_to_list(citation_str)
(citation_type, name, doc_id, pub_date, authors, comment, *extra) = (
citation_list + [None] * 7
... | [
"def",
"process_citation",
"(",
"citation_str",
":",
"str",
")",
"->",
"dict",
":",
"citation_obj",
"=",
"{",
"}",
"citation_list",
"=",
"convert_csv_str_to_list",
"(",
"citation_str",
")",
"(",
"citation_type",
",",
"name",
",",
"doc_id",
",",
"pub_date",
","... | Parse BEL Script Citation string into nanopub_bel citation object | [
"Parse",
"BEL",
"Script",
"Citation",
"string",
"into",
"nanopub_bel",
"citation",
"object"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L50-L85 |
belbio/bel | bel/nanopub/belscripts.py | split_bel_stmt | def split_bel_stmt(stmt: str, line_num) -> tuple:
"""Split bel statement into subject, relation, object tuple"""
m = re.match(f"^(.*?\))\s+([a-zA-Z=\->\|:]+)\s+([\w(]+.*?)$", stmt, flags=0)
if m:
return (m.group(1), m.group(2), m.group(3))
else:
log.info(
f"Could not parse b... | python | def split_bel_stmt(stmt: str, line_num) -> tuple:
"""Split bel statement into subject, relation, object tuple"""
m = re.match(f"^(.*?\))\s+([a-zA-Z=\->\|:]+)\s+([\w(]+.*?)$", stmt, flags=0)
if m:
return (m.group(1), m.group(2), m.group(3))
else:
log.info(
f"Could not parse b... | [
"def",
"split_bel_stmt",
"(",
"stmt",
":",
"str",
",",
"line_num",
")",
"->",
"tuple",
":",
"m",
"=",
"re",
".",
"match",
"(",
"f\"^(.*?\\))\\s+([a-zA-Z=\\->\\|:]+)\\s+([\\w(]+.*?)$\"",
",",
"stmt",
",",
"flags",
"=",
"0",
")",
"if",
"m",
":",
"return",
"(... | Split bel statement into subject, relation, object tuple | [
"Split",
"bel",
"statement",
"into",
"subject",
"relation",
"object",
"tuple"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L94-L104 |
belbio/bel | bel/nanopub/belscripts.py | yield_nanopub | def yield_nanopub(assertions, annotations, line_num):
"""Yield nanopub object"""
if not assertions:
return {}
anno = copy.deepcopy(annotations)
evidence = anno.pop("evidence", None)
stmt_group = anno.pop("statement_group", None)
citation = anno.pop("citation", None)
anno_list = [... | python | def yield_nanopub(assertions, annotations, line_num):
"""Yield nanopub object"""
if not assertions:
return {}
anno = copy.deepcopy(annotations)
evidence = anno.pop("evidence", None)
stmt_group = anno.pop("statement_group", None)
citation = anno.pop("citation", None)
anno_list = [... | [
"def",
"yield_nanopub",
"(",
"assertions",
",",
"annotations",
",",
"line_num",
")",
":",
"if",
"not",
"assertions",
":",
"return",
"{",
"}",
"anno",
"=",
"copy",
".",
"deepcopy",
"(",
"annotations",
")",
"evidence",
"=",
"anno",
".",
"pop",
"(",
"\"evid... | Yield nanopub object | [
"Yield",
"nanopub",
"object"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L107-L142 |
belbio/bel | bel/nanopub/belscripts.py | process_documentline | def process_documentline(line, nanopubs_metadata):
"""Process SET DOCUMENT line in BEL script"""
matches = re.match('SET DOCUMENT\s+(\w+)\s+=\s+"?(.*?)"?$', line)
key = matches.group(1)
val = matches.group(2)
nanopubs_metadata[key] = val
return nanopubs_metadata | python | def process_documentline(line, nanopubs_metadata):
"""Process SET DOCUMENT line in BEL script"""
matches = re.match('SET DOCUMENT\s+(\w+)\s+=\s+"?(.*?)"?$', line)
key = matches.group(1)
val = matches.group(2)
nanopubs_metadata[key] = val
return nanopubs_metadata | [
"def",
"process_documentline",
"(",
"line",
",",
"nanopubs_metadata",
")",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"'SET DOCUMENT\\s+(\\w+)\\s+=\\s+\"?(.*?)\"?$'",
",",
"line",
")",
"key",
"=",
"matches",
".",
"group",
"(",
"1",
")",
"val",
"=",
"matches... | Process SET DOCUMENT line in BEL script | [
"Process",
"SET",
"DOCUMENT",
"line",
"in",
"BEL",
"script"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L145-L153 |
belbio/bel | bel/nanopub/belscripts.py | process_definition | def process_definition(line, nanopubs_metadata):
"""Process DEFINE line in BEL script"""
matches = re.match('DEFINE\s+(\w+)\s+(\w+)\s+AS\s+URL\s+"(.*?)"\s*$', line)
if matches:
def_type = matches.group(1).lower()
if def_type == "namespace":
def_type = "namespaces"
elif d... | python | def process_definition(line, nanopubs_metadata):
"""Process DEFINE line in BEL script"""
matches = re.match('DEFINE\s+(\w+)\s+(\w+)\s+AS\s+URL\s+"(.*?)"\s*$', line)
if matches:
def_type = matches.group(1).lower()
if def_type == "namespace":
def_type = "namespaces"
elif d... | [
"def",
"process_definition",
"(",
"line",
",",
"nanopubs_metadata",
")",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"'DEFINE\\s+(\\w+)\\s+(\\w+)\\s+AS\\s+URL\\s+\"(.*?)\"\\s*$'",
",",
"line",
")",
"if",
"matches",
":",
"def_type",
"=",
"matches",
".",
"group",
... | Process DEFINE line in BEL script | [
"Process",
"DEFINE",
"line",
"in",
"BEL",
"script"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L156-L192 |
belbio/bel | bel/nanopub/belscripts.py | process_unset | def process_unset(line, annotations):
"""Process UNSET lines in BEL Script"""
matches = re.match('UNSET\s+"?(.*?)"?\s*$', line)
if matches:
val = matches.group(1)
if val == "ALL" or val == "STATEMENT_GROUP":
annotations = {}
elif re.match("{", val):
vals = co... | python | def process_unset(line, annotations):
"""Process UNSET lines in BEL Script"""
matches = re.match('UNSET\s+"?(.*?)"?\s*$', line)
if matches:
val = matches.group(1)
if val == "ALL" or val == "STATEMENT_GROUP":
annotations = {}
elif re.match("{", val):
vals = co... | [
"def",
"process_unset",
"(",
"line",
",",
"annotations",
")",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"'UNSET\\s+\"?(.*?)\"?\\s*$'",
",",
"line",
")",
"if",
"matches",
":",
"val",
"=",
"matches",
".",
"group",
"(",
"1",
")",
"if",
"val",
"==",
"\... | Process UNSET lines in BEL Script | [
"Process",
"UNSET",
"lines",
"in",
"BEL",
"Script"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L195-L213 |
belbio/bel | bel/nanopub/belscripts.py | process_set | def process_set(line, annotations):
"""Convert annotations into nanopub_bel annotations format"""
matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line)
key = None
if matches:
key = matches.group(1)
val = matches.group(2)
if key == "STATEMENT_GROUP":
annotations["stat... | python | def process_set(line, annotations):
"""Convert annotations into nanopub_bel annotations format"""
matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line)
key = None
if matches:
key = matches.group(1)
val = matches.group(2)
if key == "STATEMENT_GROUP":
annotations["stat... | [
"def",
"process_set",
"(",
"line",
",",
"annotations",
")",
":",
"matches",
"=",
"re",
".",
"match",
"(",
"'SET\\s+(\\w+)\\s*=\\s*\"?(.*?)\"?\\s*$'",
",",
"line",
")",
"key",
"=",
"None",
"if",
"matches",
":",
"key",
"=",
"matches",
".",
"group",
"(",
"1",... | Convert annotations into nanopub_bel annotations format | [
"Convert",
"annotations",
"into",
"nanopub_bel",
"annotations",
"format"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L216-L238 |
belbio/bel | bel/nanopub/belscripts.py | preprocess_belscript | def preprocess_belscript(lines):
""" Convert any multi-line SET statements into single line SET statements"""
set_flag = False
for line in lines:
if set_flag is False and re.match("SET", line):
set_flag = True
set_line = [line.rstrip()]
# SET following SET
el... | python | def preprocess_belscript(lines):
""" Convert any multi-line SET statements into single line SET statements"""
set_flag = False
for line in lines:
if set_flag is False and re.match("SET", line):
set_flag = True
set_line = [line.rstrip()]
# SET following SET
el... | [
"def",
"preprocess_belscript",
"(",
"lines",
")",
":",
"set_flag",
"=",
"False",
"for",
"line",
"in",
"lines",
":",
"if",
"set_flag",
"is",
"False",
"and",
"re",
".",
"match",
"(",
"\"SET\"",
",",
"line",
")",
":",
"set_flag",
"=",
"True",
"set_line",
... | Convert any multi-line SET statements into single line SET statements | [
"Convert",
"any",
"multi",
"-",
"line",
"SET",
"statements",
"into",
"single",
"line",
"SET",
"statements"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L266-L288 |
belbio/bel | bel/nanopub/belscripts.py | parse_belscript | def parse_belscript(lines):
"""Lines from the BELScript - can be an iterator or list
yields Nanopubs in nanopubs_bel-1.0.0 format
"""
nanopubs_metadata = {}
annotations = {}
assertions = []
# # Turn a list into an iterator
# if not isinstance(lines, collections.Iterator):
# li... | python | def parse_belscript(lines):
"""Lines from the BELScript - can be an iterator or list
yields Nanopubs in nanopubs_bel-1.0.0 format
"""
nanopubs_metadata = {}
annotations = {}
assertions = []
# # Turn a list into an iterator
# if not isinstance(lines, collections.Iterator):
# li... | [
"def",
"parse_belscript",
"(",
"lines",
")",
":",
"nanopubs_metadata",
"=",
"{",
"}",
"annotations",
"=",
"{",
"}",
"assertions",
"=",
"[",
"]",
"# # Turn a list into an iterator",
"# if not isinstance(lines, collections.Iterator):",
"# lines = iter(lines)",
"line_num",... | Lines from the BELScript - can be an iterator or list
yields Nanopubs in nanopubs_bel-1.0.0 format | [
"Lines",
"from",
"the",
"BELScript",
"-",
"can",
"be",
"an",
"iterator",
"or",
"list"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/belscripts.py#L291-L353 |
RockFeng0/rtsf-http | httpdriver/actions.py | RequestTrackInfo.__stringify_body | def __stringify_body(self, request_or_response):
''' this method reference from httprunner '''
headers = self.__track_info['{}_headers'.format(request_or_response)]
body = self.__track_info.get('{}_body'.format(request_or_response))
if isinstance(body, CaseInsensitiveDict):
... | python | def __stringify_body(self, request_or_response):
''' this method reference from httprunner '''
headers = self.__track_info['{}_headers'.format(request_or_response)]
body = self.__track_info.get('{}_body'.format(request_or_response))
if isinstance(body, CaseInsensitiveDict):
... | [
"def",
"__stringify_body",
"(",
"self",
",",
"request_or_response",
")",
":",
"headers",
"=",
"self",
".",
"__track_info",
"[",
"'{}_headers'",
".",
"format",
"(",
"request_or_response",
")",
"]",
"body",
"=",
"self",
".",
"__track_info",
".",
"get",
"(",
"'... | this method reference from httprunner | [
"this",
"method",
"reference",
"from",
"httprunner"
] | train | https://github.com/RockFeng0/rtsf-http/blob/3280cc9a01b0c92c52d699b0ebc29e55e62611a0/httpdriver/actions.py#L73-L102 |
RockFeng0/rtsf-http | httpdriver/actions.py | Request.DyStrData | def DyStrData(cls,name, regx, index = 0):
''' set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123'))
'''
text = Markup(cls.__trackinfo["response_body"... | python | def DyStrData(cls,name, regx, index = 0):
''' set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123'))
'''
text = Markup(cls.__trackinfo["response_body"... | [
"def",
"DyStrData",
"(",
"cls",
",",
"name",
",",
"regx",
",",
"index",
"=",
"0",
")",
":",
"text",
"=",
"Markup",
"(",
"cls",
".",
"__trackinfo",
"[",
"\"response_body\"",
"]",
")",
".",
"unescape",
"(",
")",
"if",
"not",
"text",
":",
"return",
"i... | set dynamic value from the string data of response
@param name: glob parameter name
@param regx: re._pattern_type
e.g.
DyStrData("a",re.compile('123')) | [
"set",
"dynamic",
"value",
"from",
"the",
"string",
"data",
"of",
"response"
] | train | https://github.com/RockFeng0/rtsf-http/blob/3280cc9a01b0c92c52d699b0ebc29e55e62611a0/httpdriver/actions.py#L227-L245 |
RockFeng0/rtsf-http | httpdriver/actions.py | Request.DyJsonData | def DyJsonData(cls,name, sequence):
''' set dynamic value from the json data of response
@param name: glob parameter name
@param sequence: sequence for the json
e.g.
result={"a":1,
"b":[1,2,3,4],
"c":{"d":5,"e":6},
"f... | python | def DyJsonData(cls,name, sequence):
''' set dynamic value from the json data of response
@param name: glob parameter name
@param sequence: sequence for the json
e.g.
result={"a":1,
"b":[1,2,3,4],
"c":{"d":5,"e":6},
"f... | [
"def",
"DyJsonData",
"(",
"cls",
",",
"name",
",",
"sequence",
")",
":",
"text",
"=",
"Markup",
"(",
"cls",
".",
"__trackinfo",
"[",
"\"response_body\"",
"]",
")",
".",
"unescape",
"(",
")",
"if",
"not",
"text",
":",
"return",
"resp",
"=",
"json",
".... | set dynamic value from the json data of response
@param name: glob parameter name
@param sequence: sequence for the json
e.g.
result={"a":1,
"b":[1,2,3,4],
"c":{"d":5,"e":6},
"f":{"g":[7,8,9]},
"h":[{"i":10,"j"... | [
"set",
"dynamic",
"value",
"from",
"the",
"json",
"data",
"of",
"response"
] | train | https://github.com/RockFeng0/rtsf-http/blob/3280cc9a01b0c92c52d699b0ebc29e55e62611a0/httpdriver/actions.py#L248-L281 |
belbio/bel | bel/nanopub/files.py | read_nanopubs | def read_nanopubs(fn: str) -> Iterable[Mapping[str, Any]]:
"""Read file and generate nanopubs
If filename has *.gz, will read as a gzip file
If filename has *.jsonl*, will parsed as a JSONLines file
IF filename has *.json*, will be parsed as a JSON file
If filename has *.yaml* or *.yml*, will be p... | python | def read_nanopubs(fn: str) -> Iterable[Mapping[str, Any]]:
"""Read file and generate nanopubs
If filename has *.gz, will read as a gzip file
If filename has *.jsonl*, will parsed as a JSONLines file
IF filename has *.json*, will be parsed as a JSON file
If filename has *.yaml* or *.yml*, will be p... | [
"def",
"read_nanopubs",
"(",
"fn",
":",
"str",
")",
"->",
"Iterable",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"]",
":",
"jsonl_flag",
",",
"json_flag",
",",
"yaml_flag",
"=",
"False",
",",
"False",
",",
"False",
"if",
"fn",
"==",
"\"-\"",
"or",
... | Read file and generate nanopubs
If filename has *.gz, will read as a gzip file
If filename has *.jsonl*, will parsed as a JSONLines file
IF filename has *.json*, will be parsed as a JSON file
If filename has *.yaml* or *.yml*, will be parsed as a YAML file
Args:
filename (str): filename t... | [
"Read",
"file",
"and",
"generate",
"nanopubs"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/files.py#L23-L72 |
belbio/bel | bel/nanopub/files.py | create_nanopubs_fh | def create_nanopubs_fh(output_fn: str):
"""Create Nanopubs output filehandle
\b
If output fn is '-' will write JSONlines to STDOUT
If output fn has *.gz, will written as a gzip file
If output fn has *.jsonl*, will written as a JSONLines file
IF output fn has *.json*, will be written as a JSON f... | python | def create_nanopubs_fh(output_fn: str):
"""Create Nanopubs output filehandle
\b
If output fn is '-' will write JSONlines to STDOUT
If output fn has *.gz, will written as a gzip file
If output fn has *.jsonl*, will written as a JSONLines file
IF output fn has *.json*, will be written as a JSON f... | [
"def",
"create_nanopubs_fh",
"(",
"output_fn",
":",
"str",
")",
":",
"# output file",
"# set output flags",
"json_flag",
",",
"jsonl_flag",
",",
"yaml_flag",
"=",
"False",
",",
"False",
",",
"False",
"if",
"output_fn",
":",
"if",
"re",
".",
"search",
"(",
"\... | Create Nanopubs output filehandle
\b
If output fn is '-' will write JSONlines to STDOUT
If output fn has *.gz, will written as a gzip file
If output fn has *.jsonl*, will written as a JSONLines file
IF output fn has *.json*, will be written as a JSON file
If output fn has *.yaml* or *.yml*, wi... | [
"Create",
"Nanopubs",
"output",
"filehandle"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/files.py#L75-L111 |
belbio/bel | bel/nanopub/files.py | write_edges | def write_edges(
edges: Mapping[str, Any],
filename: str,
jsonlines: bool = False,
gzipflag: bool = False,
yaml: bool = False,
):
"""Write edges to file
Args:
edges (Mapping[str, Any]): in edges JSON Schema format
filename (str): filename to write
jsonlines (bool): o... | python | def write_edges(
edges: Mapping[str, Any],
filename: str,
jsonlines: bool = False,
gzipflag: bool = False,
yaml: bool = False,
):
"""Write edges to file
Args:
edges (Mapping[str, Any]): in edges JSON Schema format
filename (str): filename to write
jsonlines (bool): o... | [
"def",
"write_edges",
"(",
"edges",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"filename",
":",
"str",
",",
"jsonlines",
":",
"bool",
"=",
"False",
",",
"gzipflag",
":",
"bool",
"=",
"False",
",",
"yaml",
":",
"bool",
"=",
"False",
",",
")",... | Write edges to file
Args:
edges (Mapping[str, Any]): in edges JSON Schema format
filename (str): filename to write
jsonlines (bool): output in JSONLines format?
gzipflag (bool): create gzipped file?
yaml (bool): create yaml file? | [
"Write",
"edges",
"to",
"file"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/files.py#L153-L169 |
belbio/bel | bel/db/elasticsearch.py | add_index_alias | def add_index_alias(es, index_name, alias_name):
"""Add index alias to index_name"""
es.indices.put_alias(index=index_name, name=terms_alias) | python | def add_index_alias(es, index_name, alias_name):
"""Add index alias to index_name"""
es.indices.put_alias(index=index_name, name=terms_alias) | [
"def",
"add_index_alias",
"(",
"es",
",",
"index_name",
",",
"alias_name",
")",
":",
"es",
".",
"indices",
".",
"put_alias",
"(",
"index",
"=",
"index_name",
",",
"name",
"=",
"terms_alias",
")"
] | Add index alias to index_name | [
"Add",
"index",
"alias",
"to",
"index_name"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/elasticsearch.py#L25-L28 |
belbio/bel | bel/db/elasticsearch.py | delete_index | def delete_index(es, index_name: str):
"""Delete the terms index"""
if not index_name:
log.warn("No index name given to delete")
return None
result = es.indices.delete(index=index_name)
return result | python | def delete_index(es, index_name: str):
"""Delete the terms index"""
if not index_name:
log.warn("No index name given to delete")
return None
result = es.indices.delete(index=index_name)
return result | [
"def",
"delete_index",
"(",
"es",
",",
"index_name",
":",
"str",
")",
":",
"if",
"not",
"index_name",
":",
"log",
".",
"warn",
"(",
"\"No index name given to delete\"",
")",
"return",
"None",
"result",
"=",
"es",
".",
"indices",
".",
"delete",
"(",
"index"... | Delete the terms index | [
"Delete",
"the",
"terms",
"index"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/elasticsearch.py#L40-L48 |
belbio/bel | bel/db/elasticsearch.py | create_terms_index | def create_terms_index(es, index_name: str):
"""Create terms index"""
with open(mappings_terms_fn, "r") as f:
mappings_terms = yaml.load(f, Loader=yaml.SafeLoader)
try:
es.indices.create(index=index_name, body=mappings_terms)
except Exception as e:
log.error(f"Could not create... | python | def create_terms_index(es, index_name: str):
"""Create terms index"""
with open(mappings_terms_fn, "r") as f:
mappings_terms = yaml.load(f, Loader=yaml.SafeLoader)
try:
es.indices.create(index=index_name, body=mappings_terms)
except Exception as e:
log.error(f"Could not create... | [
"def",
"create_terms_index",
"(",
"es",
",",
"index_name",
":",
"str",
")",
":",
"with",
"open",
"(",
"mappings_terms_fn",
",",
"\"r\"",
")",
"as",
"f",
":",
"mappings_terms",
"=",
"yaml",
".",
"load",
"(",
"f",
",",
"Loader",
"=",
"yaml",
".",
"SafeLo... | Create terms index | [
"Create",
"terms",
"index"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/elasticsearch.py#L51-L61 |
belbio/bel | bel/db/elasticsearch.py | delete_terms_indexes | def delete_terms_indexes(es, index_name: str = "terms_*"):
"""Delete all terms indexes"""
try:
es.indices.delete(index=index_name)
except Exception as e:
log.error(f"Could not delete all terms indices: {e}") | python | def delete_terms_indexes(es, index_name: str = "terms_*"):
"""Delete all terms indexes"""
try:
es.indices.delete(index=index_name)
except Exception as e:
log.error(f"Could not delete all terms indices: {e}") | [
"def",
"delete_terms_indexes",
"(",
"es",
",",
"index_name",
":",
"str",
"=",
"\"terms_*\"",
")",
":",
"try",
":",
"es",
".",
"indices",
".",
"delete",
"(",
"index",
"=",
"index_name",
")",
"except",
"Exception",
"as",
"e",
":",
"log",
".",
"error",
"(... | Delete all terms indexes | [
"Delete",
"all",
"terms",
"indexes"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/elasticsearch.py#L64-L70 |
belbio/bel | bel/db/elasticsearch.py | bulk_load_docs | def bulk_load_docs(es, docs):
"""Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name
"""
chunk_size = 200
try:
results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)
log.debug(f"Elasticsearch documents lo... | python | def bulk_load_docs(es, docs):
"""Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name
"""
chunk_size = 200
try:
results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)
log.debug(f"Elasticsearch documents lo... | [
"def",
"bulk_load_docs",
"(",
"es",
",",
"docs",
")",
":",
"chunk_size",
"=",
"200",
"try",
":",
"results",
"=",
"elasticsearch",
".",
"helpers",
".",
"bulk",
"(",
"es",
",",
"docs",
",",
"chunk_size",
"=",
"chunk_size",
")",
"log",
".",
"debug",
"(",
... | Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name | [
"Bulk",
"load",
"docs"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/db/elasticsearch.py#L85-L103 |
belbio/bel | bel/lang/semantics.py | validate | def validate(bo, error_level: str = "WARNING") -> Tuple[bool, List[Tuple[str, str]]]:
"""Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
... | python | def validate(bo, error_level: str = "WARNING") -> Tuple[bool, List[Tuple[str, str]]]:
"""Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
... | [
"def",
"validate",
"(",
"bo",
",",
"error_level",
":",
"str",
"=",
"\"WARNING\"",
")",
"->",
"Tuple",
"[",
"bool",
",",
"List",
"[",
"Tuple",
"[",
"str",
",",
"str",
"]",
"]",
"]",
":",
"if",
"bo",
".",
"ast",
":",
"bo",
"=",
"validate_functions",
... | Semantically validate BEL AST
Add errors and warnings to bel_obj.validation_messages
Error Levels are similar to log levels - selecting WARNING includes both
WARNING and ERROR, selecting ERROR just includes ERROR
Args:
bo: main BEL language object
error_level: return ERRORs only or al... | [
"Semantically",
"validate",
"BEL",
"AST"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/semantics.py#L14-L43 |
belbio/bel | bel/lang/semantics.py | validate_functions | def validate_functions(ast: BELAst, bo):
"""Recursively validate function signatures
Determine if function matches one of the available signatures. Also,
1. Add entity types to AST NSArg, e.g. Abundance, ...
2. Add optional to AST Arg (optional means it is not a
fixed, required argument and n... | python | def validate_functions(ast: BELAst, bo):
"""Recursively validate function signatures
Determine if function matches one of the available signatures. Also,
1. Add entity types to AST NSArg, e.g. Abundance, ...
2. Add optional to AST Arg (optional means it is not a
fixed, required argument and n... | [
"def",
"validate_functions",
"(",
"ast",
":",
"BELAst",
",",
"bo",
")",
":",
"if",
"isinstance",
"(",
"ast",
",",
"Function",
")",
":",
"log",
".",
"debug",
"(",
"f\"Validating: {ast.name}, {ast.function_type}, {ast.args}\"",
")",
"function_signatures",
"=",
"bo",... | Recursively validate function signatures
Determine if function matches one of the available signatures. Also,
1. Add entity types to AST NSArg, e.g. Abundance, ...
2. Add optional to AST Arg (optional means it is not a
fixed, required argument and needs to be sorted for
canonicalization, ... | [
"Recursively",
"validate",
"function",
"signatures"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/semantics.py#L46-L88 |
belbio/bel | bel/lang/semantics.py | check_function_args | def check_function_args(args, signatures, function_name):
"""Check function args - return message if function args don't match function signature
Called from validate_functions
We have following types of arguments to validate:
1. Required, position_dependent arguments, e.g. p(HGNC:AKT1), NSArg HGN... | python | def check_function_args(args, signatures, function_name):
"""Check function args - return message if function args don't match function signature
Called from validate_functions
We have following types of arguments to validate:
1. Required, position_dependent arguments, e.g. p(HGNC:AKT1), NSArg HGN... | [
"def",
"check_function_args",
"(",
"args",
",",
"signatures",
",",
"function_name",
")",
":",
"messages",
"=",
"[",
"]",
"arg_types",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"arg_type",
"=",
"arg",
".",
"__class__",
".",
"__name__",
"if",
"arg_ty... | Check function args - return message if function args don't match function signature
Called from validate_functions
We have following types of arguments to validate:
1. Required, position_dependent arguments, e.g. p(HGNC:AKT1), NSArg HGNC:AKT1 is required and must be first argument
2. Optional... | [
"Check",
"function",
"args",
"-",
"return",
"message",
"if",
"function",
"args",
"don",
"t",
"match",
"function",
"signature"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/semantics.py#L91-L236 |
belbio/bel | bel/lang/semantics.py | validate_arg_values | def validate_arg_values(ast, bo):
"""Recursively validate arg (NSArg and StrArg) values
Check that NSArgs are found in BELbio API and match appropriate entity_type.
Check that StrArgs match their value - either default namespace or regex string
Generate a WARNING if not.
Args:
bo: bel obj... | python | def validate_arg_values(ast, bo):
"""Recursively validate arg (NSArg and StrArg) values
Check that NSArgs are found in BELbio API and match appropriate entity_type.
Check that StrArgs match their value - either default namespace or regex string
Generate a WARNING if not.
Args:
bo: bel obj... | [
"def",
"validate_arg_values",
"(",
"ast",
",",
"bo",
")",
":",
"if",
"not",
"bo",
".",
"api_url",
":",
"log",
".",
"info",
"(",
"\"No API endpoint defined\"",
")",
"return",
"bo",
"log",
".",
"debug",
"(",
"f\"AST: {ast}\"",
")",
"# Test NSArg terms",
"if",
... | Recursively validate arg (NSArg and StrArg) values
Check that NSArgs are found in BELbio API and match appropriate entity_type.
Check that StrArgs match their value - either default namespace or regex string
Generate a WARNING if not.
Args:
bo: bel object
Returns:
bel object | [
"Recursively",
"validate",
"arg",
"(",
"NSArg",
"and",
"StrArg",
")",
"values"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/lang/semantics.py#L239-L370 |
belbio/bel | bel/Config.py | get_belbio_conf_files | def get_belbio_conf_files():
"""Get belbio configuration from files
"""
home = os.path.expanduser("~")
cwd = os.getcwd()
belbio_conf_fp, belbio_secrets_fp = "", ""
env_conf_dir = os.getenv("BELBIO_CONF", "").rstrip("/")
conf_paths = [
f"{cwd}/belbio_conf.yaml",
f"{cwd}/be... | python | def get_belbio_conf_files():
"""Get belbio configuration from files
"""
home = os.path.expanduser("~")
cwd = os.getcwd()
belbio_conf_fp, belbio_secrets_fp = "", ""
env_conf_dir = os.getenv("BELBIO_CONF", "").rstrip("/")
conf_paths = [
f"{cwd}/belbio_conf.yaml",
f"{cwd}/be... | [
"def",
"get_belbio_conf_files",
"(",
")",
":",
"home",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"cwd",
"=",
"os",
".",
"getcwd",
"(",
")",
"belbio_conf_fp",
",",
"belbio_secrets_fp",
"=",
"\"\"",
",",
"\"\"",
"env_conf_dir",
"=",
"os... | Get belbio configuration from files | [
"Get",
"belbio",
"configuration",
"from",
"files"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/Config.py#L26-L66 |
belbio/bel | bel/Config.py | load_configuration | def load_configuration():
"""Load the configuration"""
(belbio_conf_fp, belbio_secrets_fp) = get_belbio_conf_files()
log.info(f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} ")
config = {}
if belbio_conf_fp:
with open(belbio_conf_fp, "r") as f:
config = ya... | python | def load_configuration():
"""Load the configuration"""
(belbio_conf_fp, belbio_secrets_fp) = get_belbio_conf_files()
log.info(f"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} ")
config = {}
if belbio_conf_fp:
with open(belbio_conf_fp, "r") as f:
config = ya... | [
"def",
"load_configuration",
"(",
")",
":",
"(",
"belbio_conf_fp",
",",
"belbio_secrets_fp",
")",
"=",
"get_belbio_conf_files",
"(",
")",
"log",
".",
"info",
"(",
"f\"Using conf: {belbio_conf_fp} and secrets files: {belbio_secrets_fp} \"",
")",
"config",
"=",
"{",
"}",
... | Load the configuration | [
"Load",
"the",
"configuration"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/Config.py#L69-L94 |
belbio/bel | bel/Config.py | get_versions | def get_versions(config) -> dict:
"""Get versions of bel modules and tools"""
# Collect bel package version
try:
import bel.__version__
config["bel"]["version"] = bel.__version__.__version__
except KeyError:
config["bel"] = {"version": bel.__version__.__version__}
except Mo... | python | def get_versions(config) -> dict:
"""Get versions of bel modules and tools"""
# Collect bel package version
try:
import bel.__version__
config["bel"]["version"] = bel.__version__.__version__
except KeyError:
config["bel"] = {"version": bel.__version__.__version__}
except Mo... | [
"def",
"get_versions",
"(",
"config",
")",
"->",
"dict",
":",
"# Collect bel package version",
"try",
":",
"import",
"bel",
".",
"__version__",
"config",
"[",
"\"bel\"",
"]",
"[",
"\"version\"",
"]",
"=",
"bel",
".",
"__version__",
".",
"__version__",
"except"... | Get versions of bel modules and tools | [
"Get",
"versions",
"of",
"bel",
"modules",
"and",
"tools"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/Config.py#L97-L130 |
belbio/bel | bel/Config.py | add_environment_vars | def add_environment_vars(config: MutableMapping[str, Any]):
"""Override config with environment variables
Environment variables have to be prefixed with BELBIO_
which will be stripped before splitting on '__' and lower-casing
the environment variable name that is left into keys for the
config dicti... | python | def add_environment_vars(config: MutableMapping[str, Any]):
"""Override config with environment variables
Environment variables have to be prefixed with BELBIO_
which will be stripped before splitting on '__' and lower-casing
the environment variable name that is left into keys for the
config dicti... | [
"def",
"add_environment_vars",
"(",
"config",
":",
"MutableMapping",
"[",
"str",
",",
"Any",
"]",
")",
":",
"# TODO need to redo config - can't add value to dictionary without recursively building up the dict",
"# check into config libraries again",
"for",
"e",
"in",
"os"... | Override config with environment variables
Environment variables have to be prefixed with BELBIO_
which will be stripped before splitting on '__' and lower-casing
the environment variable name that is left into keys for the
config dictionary.
Example:
BELBIO_BEL_API__SERVERS__API_URL=http:... | [
"Override",
"config",
"with",
"environment",
"variables"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/Config.py#L134-L168 |
belbio/bel | bel/Config.py | merge_config | def merge_config(
config: Mapping[str, Any],
override_config: Mapping[str, Any] = None,
override_config_fn: str = None,
) -> Mapping[str, Any]:
"""Override config with additional configuration in override_config or override_config_fn
Used in script to merge CLI options with Config
Args:
... | python | def merge_config(
config: Mapping[str, Any],
override_config: Mapping[str, Any] = None,
override_config_fn: str = None,
) -> Mapping[str, Any]:
"""Override config with additional configuration in override_config or override_config_fn
Used in script to merge CLI options with Config
Args:
... | [
"def",
"merge_config",
"(",
"config",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"override_config",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
"=",
"None",
",",
"override_config_fn",
":",
"str",
"=",
"None",
",",
")",
"->",
"Mapping",
"[",
"... | Override config with additional configuration in override_config or override_config_fn
Used in script to merge CLI options with Config
Args:
config: original configuration
override_config: new configuration to override/extend current config
override_config_fn: new configuration filenam... | [
"Override",
"config",
"with",
"additional",
"configuration",
"in",
"override_config",
"or",
"override_config_fn"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/Config.py#L171-L193 |
belbio/bel | bel/Config.py | rec_merge | def rec_merge(d1, d2):
""" Recursively merge two dictionaries
Update two dicts of dicts recursively,
if either mapping has leaves that are non-dicts,
the second's leaf overwrites the first's.
import collections
import functools
e.g. functools.reduce(rec_merge, (d1, d2, d3, d4))
"""
... | python | def rec_merge(d1, d2):
""" Recursively merge two dictionaries
Update two dicts of dicts recursively,
if either mapping has leaves that are non-dicts,
the second's leaf overwrites the first's.
import collections
import functools
e.g. functools.reduce(rec_merge, (d1, d2, d3, d4))
"""
... | [
"def",
"rec_merge",
"(",
"d1",
",",
"d2",
")",
":",
"for",
"k",
",",
"v",
"in",
"d1",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"d2",
":",
"# this next check is the only difference!",
"if",
"all",
"(",
"isinstance",
"(",
"e",
",",
"collections",
... | Recursively merge two dictionaries
Update two dicts of dicts recursively,
if either mapping has leaves that are non-dicts,
the second's leaf overwrites the first's.
import collections
import functools
e.g. functools.reduce(rec_merge, (d1, d2, d3, d4)) | [
"Recursively",
"merge",
"two",
"dictionaries"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/Config.py#L197-L218 |
belbio/bel | bel/resources/namespace.py | load_terms | def load_terms(fo: IO, metadata: dict, forceupdate: bool):
"""Load terms into Elasticsearch and ArangoDB
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
fo: file obj - terminology file
metadata: dict co... | python | def load_terms(fo: IO, metadata: dict, forceupdate: bool):
"""Load terms into Elasticsearch and ArangoDB
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
fo: file obj - terminology file
metadata: dict co... | [
"def",
"load_terms",
"(",
"fo",
":",
"IO",
",",
"metadata",
":",
"dict",
",",
"forceupdate",
":",
"bool",
")",
":",
"version",
"=",
"metadata",
"[",
"\"metadata\"",
"]",
"[",
"\"version\"",
"]",
"# LOAD TERMS INTO Elasticsearch",
"with",
"timy",
".",
"Timer"... | Load terms into Elasticsearch and ArangoDB
Forceupdate will create a new index in Elasticsearch regardless of whether
an index with the resource version already exists.
Args:
fo: file obj - terminology file
metadata: dict containing the metadata for terminology
forceupdate: force f... | [
"Load",
"terms",
"into",
"Elasticsearch",
"and",
"ArangoDB"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/resources/namespace.py#L27-L112 |
belbio/bel | bel/resources/namespace.py | terms_iterator_for_elasticsearch | def terms_iterator_for_elasticsearch(fo: IO, index_name: str):
"""Add index_name to term documents for bulk load"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0) # Seek back to beginning of file
with gzip.open(fo, "rt") as f:
for line in f:
term = json.... | python | def terms_iterator_for_elasticsearch(fo: IO, index_name: str):
"""Add index_name to term documents for bulk load"""
species_list = config["bel_resources"].get("species_list", [])
fo.seek(0) # Seek back to beginning of file
with gzip.open(fo, "rt") as f:
for line in f:
term = json.... | [
"def",
"terms_iterator_for_elasticsearch",
"(",
"fo",
":",
"IO",
",",
"index_name",
":",
"str",
")",
":",
"species_list",
"=",
"config",
"[",
"\"bel_resources\"",
"]",
".",
"get",
"(",
"\"species_list\"",
",",
"[",
"]",
")",
"fo",
".",
"seek",
"(",
"0",
... | Add index_name to term documents for bulk load | [
"Add",
"index_name",
"to",
"term",
"documents",
"for",
"bulk",
"load"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/resources/namespace.py#L206-L238 |
belbio/bel | bel/resources/namespace.py | lowercase_term_id | def lowercase_term_id(term_id: str) -> str:
"""Lowercase the term value (not the namespace prefix)
Args:
term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis
Returns:
str: lowercased, e.g. MESH:atherosclerosis
"""
(ns, val) = term_id.split(":", maxsplit=1... | python | def lowercase_term_id(term_id: str) -> str:
"""Lowercase the term value (not the namespace prefix)
Args:
term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis
Returns:
str: lowercased, e.g. MESH:atherosclerosis
"""
(ns, val) = term_id.split(":", maxsplit=1... | [
"def",
"lowercase_term_id",
"(",
"term_id",
":",
"str",
")",
"->",
"str",
":",
"(",
"ns",
",",
"val",
")",
"=",
"term_id",
".",
"split",
"(",
"\":\"",
",",
"maxsplit",
"=",
"1",
")",
"term_id",
"=",
"f\"{ns}:{val.lower()}\"",
"return",
"term_id"
] | Lowercase the term value (not the namespace prefix)
Args:
term_id (str): term identifier with namespace prefix, e.g. MESH:Atherosclerosis
Returns:
str: lowercased, e.g. MESH:atherosclerosis | [
"Lowercase",
"the",
"term",
"value",
"(",
"not",
"the",
"namespace",
"prefix",
")"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/resources/namespace.py#L241-L253 |
belbio/bel | bel/nanopub/pubmed.py | node_text | def node_text(node):
"""Needed for things like abstracts which have internal tags (see PMID:27822475)"""
if node.text:
result = node.text
else:
result = ""
for child in node:
if child.tail is not None:
result += child.tail
return result | python | def node_text(node):
"""Needed for things like abstracts which have internal tags (see PMID:27822475)"""
if node.text:
result = node.text
else:
result = ""
for child in node:
if child.tail is not None:
result += child.tail
return result | [
"def",
"node_text",
"(",
"node",
")",
":",
"if",
"node",
".",
"text",
":",
"result",
"=",
"node",
".",
"text",
"else",
":",
"result",
"=",
"\"\"",
"for",
"child",
"in",
"node",
":",
"if",
"child",
".",
"tail",
"is",
"not",
"None",
":",
"result",
... | Needed for things like abstracts which have internal tags (see PMID:27822475) | [
"Needed",
"for",
"things",
"like",
"abstracts",
"which",
"have",
"internal",
"tags",
"(",
"see",
"PMID",
":",
"27822475",
")"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/pubmed.py#L49-L59 |
belbio/bel | bel/nanopub/pubmed.py | get_pubtator | def get_pubtator(pmid):
"""Get Pubtator Bioconcepts from Pubmed Abstract
Re-configure the denotations into an annotation dictionary format
and collapse duplicate terms so that their spans are in a list.
"""
r = get_url(PUBTATOR_TMPL.replace("PMID", pmid), timeout=10)
if r and r.status_code == 2... | python | def get_pubtator(pmid):
"""Get Pubtator Bioconcepts from Pubmed Abstract
Re-configure the denotations into an annotation dictionary format
and collapse duplicate terms so that their spans are in a list.
"""
r = get_url(PUBTATOR_TMPL.replace("PMID", pmid), timeout=10)
if r and r.status_code == 2... | [
"def",
"get_pubtator",
"(",
"pmid",
")",
":",
"r",
"=",
"get_url",
"(",
"PUBTATOR_TMPL",
".",
"replace",
"(",
"\"PMID\"",
",",
"pmid",
")",
",",
"timeout",
"=",
"10",
")",
"if",
"r",
"and",
"r",
".",
"status_code",
"==",
"200",
":",
"pubtator",
"=",
... | Get Pubtator Bioconcepts from Pubmed Abstract
Re-configure the denotations into an annotation dictionary format
and collapse duplicate terms so that their spans are in a list. | [
"Get",
"Pubtator",
"Bioconcepts",
"from",
"Pubmed",
"Abstract"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/pubmed.py#L62-L135 |
belbio/bel | bel/nanopub/pubmed.py | process_pub_date | def process_pub_date(year, mon, day):
"""Create pub_date from what Pubmed provides in Journal PubDate entry
"""
pub_date = None
if year and re.match("[a-zA-Z]+", mon):
pub_date = datetime.datetime.strptime(
f"{year}-{mon}-{day}", "%Y-%b-%d"
).strftime("%Y-%m-%d")
elif ye... | python | def process_pub_date(year, mon, day):
"""Create pub_date from what Pubmed provides in Journal PubDate entry
"""
pub_date = None
if year and re.match("[a-zA-Z]+", mon):
pub_date = datetime.datetime.strptime(
f"{year}-{mon}-{day}", "%Y-%b-%d"
).strftime("%Y-%m-%d")
elif ye... | [
"def",
"process_pub_date",
"(",
"year",
",",
"mon",
",",
"day",
")",
":",
"pub_date",
"=",
"None",
"if",
"year",
"and",
"re",
".",
"match",
"(",
"\"[a-zA-Z]+\"",
",",
"mon",
")",
":",
"pub_date",
"=",
"datetime",
".",
"datetime",
".",
"strptime",
"(",
... | Create pub_date from what Pubmed provides in Journal PubDate entry | [
"Create",
"pub_date",
"from",
"what",
"Pubmed",
"provides",
"in",
"Journal",
"PubDate",
"entry"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/pubmed.py#L138-L150 |
belbio/bel | bel/nanopub/pubmed.py | get_pubmed | def get_pubmed(pmid: str) -> Mapping[str, Any]:
"""Get pubmed xml for pmid and convert to JSON
Remove MESH terms if they are duplicated in the compound term set
ArticleDate vs PubDate gets complicated: https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html see <ArticleDate> and <PubDate>
Only... | python | def get_pubmed(pmid: str) -> Mapping[str, Any]:
"""Get pubmed xml for pmid and convert to JSON
Remove MESH terms if they are duplicated in the compound term set
ArticleDate vs PubDate gets complicated: https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html see <ArticleDate> and <PubDate>
Only... | [
"def",
"get_pubmed",
"(",
"pmid",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"pubmed_url",
"=",
"PUBMED_TMPL",
".",
"replace",
"(",
"\"PMID\"",
",",
"str",
"(",
"pmid",
")",
")",
"r",
"=",
"get_url",
"(",
"pubmed_url",
")",
... | Get pubmed xml for pmid and convert to JSON
Remove MESH terms if they are duplicated in the compound term set
ArticleDate vs PubDate gets complicated: https://www.nlm.nih.gov/bsd/licensee/elements_descriptions.html see <ArticleDate> and <PubDate>
Only getting pub_year at this point from the <PubDate> elem... | [
"Get",
"pubmed",
"xml",
"for",
"pmid",
"and",
"convert",
"to",
"JSON"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/pubmed.py#L153-L239 |
belbio/bel | bel/nanopub/pubmed.py | enhance_pubmed_annotations | def enhance_pubmed_annotations(pubmed: Mapping[str, Any]) -> Mapping[str, Any]:
"""Enhance pubmed namespace IDs
Add additional entity and annotation types to annotations
Use preferred id for namespaces as needed
Add strings from Title, Abstract matching Pubtator BioConcept spans
NOTE - basically d... | python | def enhance_pubmed_annotations(pubmed: Mapping[str, Any]) -> Mapping[str, Any]:
"""Enhance pubmed namespace IDs
Add additional entity and annotation types to annotations
Use preferred id for namespaces as needed
Add strings from Title, Abstract matching Pubtator BioConcept spans
NOTE - basically d... | [
"def",
"enhance_pubmed_annotations",
"(",
"pubmed",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"text",
"=",
"pubmed",
"[",
"\"title\"",
"]",
"+",
"pubmed",
"[",
"\"abstract\"",
"]",
"annotations",... | Enhance pubmed namespace IDs
Add additional entity and annotation types to annotations
Use preferred id for namespaces as needed
Add strings from Title, Abstract matching Pubtator BioConcept spans
NOTE - basically duplicated code with bel_api:api.services.pubmed
Args:
pubmed
Returns:... | [
"Enhance",
"pubmed",
"namespace",
"IDs"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/pubmed.py#L242-L299 |
belbio/bel | bel/nanopub/pubmed.py | get_pubmed_for_beleditor | def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]:
"""Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary
"""
pubmed = get_pubmed(pmid)
pubtator = get_pubtator(pmid)
... | python | def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]:
"""Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary
"""
pubmed = get_pubmed(pmid)
pubtator = get_pubtator(pmid)
... | [
"def",
"get_pubmed_for_beleditor",
"(",
"pmid",
":",
"str",
")",
"->",
"Mapping",
"[",
"str",
",",
"Any",
"]",
":",
"pubmed",
"=",
"get_pubmed",
"(",
"pmid",
")",
"pubtator",
"=",
"get_pubtator",
"(",
"pmid",
")",
"pubmed",
"[",
"\"annotations\"",
"]",
"... | Get fully annotated pubmed doc with Pubtator and full entity/annotation_types
Args:
pmid: Pubmed PMID
Returns:
Mapping[str, Any]: pubmed dictionary | [
"Get",
"fully",
"annotated",
"pubmed",
"doc",
"with",
"Pubtator",
"and",
"full",
"entity",
"/",
"annotation_types"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/nanopub/pubmed.py#L302-L319 |
belbio/bel | bel/terms/orthologs.py | get_orthologs | def get_orthologs(canonical_gene_id: str, species: list = []) -> List[dict]:
"""Get orthologs for given gene_id and species
Canonicalize prior to ortholog query and decanonicalize
the resulting ortholog
Args:
canonical_gene_id: canonical gene_id for which to retrieve ortholog
species: ... | python | def get_orthologs(canonical_gene_id: str, species: list = []) -> List[dict]:
"""Get orthologs for given gene_id and species
Canonicalize prior to ortholog query and decanonicalize
the resulting ortholog
Args:
canonical_gene_id: canonical gene_id for which to retrieve ortholog
species: ... | [
"def",
"get_orthologs",
"(",
"canonical_gene_id",
":",
"str",
",",
"species",
":",
"list",
"=",
"[",
"]",
")",
"->",
"List",
"[",
"dict",
"]",
":",
"gene_id_key",
"=",
"bel",
".",
"db",
".",
"arangodb",
".",
"arango_id_to_key",
"(",
"canonical_gene_id",
... | Get orthologs for given gene_id and species
Canonicalize prior to ortholog query and decanonicalize
the resulting ortholog
Args:
canonical_gene_id: canonical gene_id for which to retrieve ortholog
species: target species for ortholog - tax id format TAX:<number>
Returns:
List[... | [
"Get",
"orthologs",
"for",
"given",
"gene_id",
"and",
"species"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/terms/orthologs.py#L16-L63 |
PayEx/pypayex | payex/utils.py | normalize_value | def normalize_value(val):
"""
Normalize strings with booleans into Python types.
"""
if val is not None:
if val.lower() == 'false':
val = False
elif val.lower() == 'true':
val = True
return val | python | def normalize_value(val):
"""
Normalize strings with booleans into Python types.
"""
if val is not None:
if val.lower() == 'false':
val = False
elif val.lower() == 'true':
val = True
return val | [
"def",
"normalize_value",
"(",
"val",
")",
":",
"if",
"val",
"is",
"not",
"None",
":",
"if",
"val",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"val",
"=",
"False",
"elif",
"val",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"val",
"=",
"True",... | Normalize strings with booleans into Python types. | [
"Normalize",
"strings",
"with",
"booleans",
"into",
"Python",
"types",
"."
] | train | https://github.com/PayEx/pypayex/blob/549ba7cc47f112a7aa3417fcf87ff07bc74cd9ab/payex/utils.py#L12-L23 |
PayEx/pypayex | payex/utils.py | normalize_dictionary_values | def normalize_dictionary_values(dictionary):
"""
Normalizes the values in a dictionary recursivly.
"""
for key, val in dictionary.iteritems():
if isinstance(val, dict):
dictionary[key] = normalize_dictionary_values(val)
elif isinstance(val, list):
dictionary[... | python | def normalize_dictionary_values(dictionary):
"""
Normalizes the values in a dictionary recursivly.
"""
for key, val in dictionary.iteritems():
if isinstance(val, dict):
dictionary[key] = normalize_dictionary_values(val)
elif isinstance(val, list):
dictionary[... | [
"def",
"normalize_dictionary_values",
"(",
"dictionary",
")",
":",
"for",
"key",
",",
"val",
"in",
"dictionary",
".",
"iteritems",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"dictionary",
"[",
"key",
"]",
"=",
"normalize_dictiona... | Normalizes the values in a dictionary recursivly. | [
"Normalizes",
"the",
"values",
"in",
"a",
"dictionary",
"recursivly",
"."
] | train | https://github.com/PayEx/pypayex/blob/549ba7cc47f112a7aa3417fcf87ff07bc74cd9ab/payex/utils.py#L25-L38 |
belbio/bel | bel/utils.py | get_url | def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True):
"""Wrapper for requests.get(url)
Args:
url: url to retrieve
params: query string parameters
timeout: allow this much time for the request and time it out if over
cache: Cache for up to a day unle... | python | def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True):
"""Wrapper for requests.get(url)
Args:
url: url to retrieve
params: query string parameters
timeout: allow this much time for the request and time it out if over
cache: Cache for up to a day unle... | [
"def",
"get_url",
"(",
"url",
":",
"str",
",",
"params",
":",
"dict",
"=",
"{",
"}",
",",
"timeout",
":",
"float",
"=",
"5.0",
",",
"cache",
":",
"bool",
"=",
"True",
")",
":",
"try",
":",
"if",
"not",
"cache",
":",
"with",
"requests_cache",
".",... | Wrapper for requests.get(url)
Args:
url: url to retrieve
params: query string parameters
timeout: allow this much time for the request and time it out if over
cache: Cache for up to a day unless this is false
Returns:
Requests Result obj or None if timed out | [
"Wrapper",
"for",
"requests",
".",
"get",
"(",
"url",
")"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L27-L56 |
belbio/bel | bel/utils.py | timespan | def timespan(start_time):
"""Return time in milliseconds from start_time"""
timespan = datetime.datetime.now() - start_time
timespan_ms = timespan.total_seconds() * 1000
return timespan_ms | python | def timespan(start_time):
"""Return time in milliseconds from start_time"""
timespan = datetime.datetime.now() - start_time
timespan_ms = timespan.total_seconds() * 1000
return timespan_ms | [
"def",
"timespan",
"(",
"start_time",
")",
":",
"timespan",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"-",
"start_time",
"timespan_ms",
"=",
"timespan",
".",
"total_seconds",
"(",
")",
"*",
"1000",
"return",
"timespan_ms"
] | Return time in milliseconds from start_time | [
"Return",
"time",
"in",
"milliseconds",
"from",
"start_time"
] | train | https://github.com/belbio/bel/blob/60333e8815625b942b4836903f3b618cf44b3771/bel/utils.py#L59-L64 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.