code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
ast_subject = ast_dict.get("subject", None)
ast_object = ast_dict.get("object", None)
bel_subject = None
bel_object = None
bel_relation = ast_dict.get("relation")
if ast_subject:
bel_subject = function_ast_to_objects(ast_subject, bel_obj)
if ast_object:
bel_object = f... | 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 | 2.219494 | 2.403769 | 0.923339 |
if not ast_obj:
ast_obj = self
bel_relation = None
if self.bel_relation and fmt == "short":
bel_relation = self.spec["relations"]["to_short"].get(
self.bel_relation, self.bel_relation
)
elif self.bel_relation:
bel... | 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
long = long function and long relation format
cano... | 2.108397 | 2.033898 | 1.036629 |
if not ast_obj:
ast_obj = self
if self.bel_subject and self.bel_relation and self.bel_object:
if self.bel_relation.startswith("has"):
bel_relation = self.bel_relation
elif fmt == "short":
bel_relation = self.spec["relations"]... | 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
long = long function and long relation format
Ret... | 2.190474 | 2.058554 | 1.064083 |
if not ast_obj:
ast_obj = self
if hasattr(self, "bel_subject"):
print("Subject:")
self.bel_subject.print_tree(self.bel_subject, indent=0)
if hasattr(self, "bel_relation"):
print("Relation:", self.bel_relation)
if hasattr(self, ... | def print_tree(self, ast_obj=None) | Convert AST object to tree view of BEL AST
Returns:
prints tree of BEL AST to STDOUT | 2.046503 | 1.948892 | 1.050085 |
arg_string = ", ".join([a.to_string(fmt=fmt) for a in self.args])
if fmt in ["short", "medium"]:
function_name = self.name_short
else:
function_name = self.name
return "{}({})".format(function_name, arg_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
short = short function and short relation format
medium = short function and long relation format
long = long function and long relation format
Returns... | 3.61919 | 3.826893 | 0.945725 |
for arg in self.args:
if arg.__class__.__name__ == "Function":
subcomponents.append(arg.to_string())
if arg.function_type == "primary":
arg.subcomponents(subcomponents)
else:
subcomponents.append(arg.to_string(... | 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 request
Returns:
List[str]: su... | 3.542627 | 3.582143 | 0.988969 |
self.namespace = namespace
self.value = value | def change_nsvalue(self, namespace, value) | Deprecated | 7.413031 | 6.362456 | 1.165121 |
if not (ns and val) and nsval:
(ns, val) = nsval.split(":", 1)
elif not (ns and val) and not nsval:
log.error("Did not update NSArg - no ns:val or nsval provided")
self.namespace = ns
self.value = val | 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 | 4.888253 | 4.830698 | 1.011915 |
if (
self.orthologs
and ortho_species_id in self.orthologs
and ortho_species_id != self.species_id
):
self.orthology_species = ortho_species_id
self.canonical = self.orthologs[ortho_species_id]["canonical"]
self.decanonica... | def orthologize(self, ortho_species_id, belast) | Decanonical ortholog name used | 3.049281 | 2.870858 | 1.06215 |
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('\s*"?\s*$', "", col)
new.append(col)
return new | def convert_csv_str_to_list(csv_str: str) -> list | Convert CSV str to list | 2.894862 | 2.735803 | 1.05814 |
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
)
# print(f'citation_type: {citation_type}, name: {name}, doc_id: {doc_id}, pub_date: {pub_date}, authors: {authors}... | def process_citation(citation_str: str) -> dict | Parse BEL Script Citation string into nanopub_bel citation object | 2.693464 | 2.529342 | 1.064887 |
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 bel statement into components at line number: {line_num} assertion: {stmt}"
)
return (stmt, None,... | def split_bel_stmt(stmt: str, line_num) -> tuple | Split bel statement into subject, relation, object tuple | 5.377989 | 4.99434 | 1.076817 |
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 = []
for anno_type in anno:
if isinstance(anno[anno_type], (list, tuple... | def yield_nanopub(assertions, annotations, line_num) | Yield nanopub object | 2.671658 | 2.673422 | 0.99934 |
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) | Process SET DOCUMENT line in BEL script | 3.825203 | 3.050377 | 1.25401 |
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 def_type == "annotation":
def_type == "annotations"
key = matches.gr... | def process_definition(line, nanopubs_metadata) | Process DEFINE line in BEL script | 1.734115 | 1.700426 | 1.019812 |
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 = convert_csv_str_to_list(val)
for val in vals:
annot... | def process_unset(line, annotations) | Process UNSET lines in BEL Script | 4.225428 | 3.982383 | 1.06103 |
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["statement_group"] = val
elif key == "Citation":
annotations["citation"] = process_citatio... | def process_set(line, annotations) | Convert annotations into nanopub_bel annotations format | 3.594017 | 3.526181 | 1.019238 |
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
elif set_flag and re.match("SET", line):
yield f"{' '.join(set_line)}\n"
set_line = [li... | def preprocess_belscript(lines) | Convert any multi-line SET statements into single line SET statements | 3.528998 | 3.189002 | 1.106615 |
nanopubs_metadata = {}
annotations = {}
assertions = []
# # Turn a list into an iterator
# if not isinstance(lines, collections.Iterator):
# lines = iter(lines)
line_num = 0
# for line in preprocess_belscript(lines):
for line in set_single_line(lines):
line_num ... | def parse_belscript(lines) | Lines from the BELScript - can be an iterator or list
yields Nanopubs in nanopubs_bel-1.0.0 format | 3.643021 | 3.478159 | 1.047399 |
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):
... | this method reference from httprunner | null | null | null | |
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"... | 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')) | null | null | null | |
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... | 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"... | null | null | null | |
jsonl_flag, json_flag, yaml_flag = False, False, False
if fn == "-" or "jsonl" in fn:
jsonl_flag = True
elif "json" in fn:
json_flag = True
elif re.search("ya?ml", fn):
yaml_flag = True
else:
log.error("Do not recognize nanopub file format - neither json nor jso... | 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 parsed as a YAML file
Args:
filename (str): filename t... | 2.528514 | 2.442831 | 1.035075 |
# output file
# set output flags
json_flag, jsonl_flag, yaml_flag = False, False, False
if output_fn:
if re.search("gz$", output_fn):
out_fh = gzip.open(output_fn, "wt")
else:
out_fh = click.open_file(output_fn, mode="wt")
if re.search("ya?ml", outp... | 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 file
If output fn has *.yaml* or *.yml*, wi... | 2.86001 | 2.342299 | 1.221027 |
pass | 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? | 433,853.84375 | 7,584.701172 | 57.201178 |
es.indices.put_alias(index=index_name, name=terms_alias) | def add_index_alias(es, index_name, alias_name) | Add index alias to index_name | 6.341001 | 5.504025 | 1.152066 |
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) | Delete the terms index | 4.617825 | 3.705075 | 1.246351 |
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 elasticsearch terms index: {e}") | def create_terms_index(es, index_name: str) | Create terms index | 3.275937 | 2.904202 | 1.127999 |
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_*") | Delete all terms indexes | 3.373609 | 2.985807 | 1.129882 |
chunk_size = 200
try:
results = elasticsearch.helpers.bulk(es, docs, chunk_size=chunk_size)
log.debug(f"Elasticsearch documents loaded: {results[0]}")
# elasticsearch.helpers.parallel_bulk(es, terms, chunk_size=chunk_size, thread_count=4)
if len(results[1]) > 0:
... | def bulk_load_docs(es, docs) | Bulk load docs
Args:
es: elasticsearch handle
docs: Iterator of doc objects - includes index_name | 3.581319 | 3.920769 | 0.913423 |
if bo.ast:
bo = validate_functions(bo.ast, bo) # No WARNINGs generated in this function
if error_level == "WARNING":
bo = validate_arg_values(bo.ast, bo) # validates NSArg and StrArg values
else:
bo.validation_messages.append(("ERROR", "Invalid BEL Statement - cannot... | 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
Args:
bo: main BEL language object
error_level: return ERRORs only or al... | 8.101726 | 7.32828 | 1.105543 |
if isinstance(ast, Function):
log.debug(f"Validating: {ast.name}, {ast.function_type}, {ast.args}")
function_signatures = bo.spec["functions"]["signatures"][ast.name]["signatures"]
function_name = ast.name
(valid_function, messages) = check_function_args(
ast.args,... | 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 needs to be sorted for
canonicalization, ... | 5.390171 | 4.954645 | 1.087903 |
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}/belbio_conf.yml",
f"{env_conf_dir}/belbio_conf.yaml",
f"{env_... | def get_belbio_conf_files() | Get belbio configuration from files | 1.929344 | 1.909195 | 1.010554 |
(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 = yaml.load(f, Loader=yaml.SafeLoader)
config[... | def load_configuration() | Load the configuration | 2.84302 | 2.824806 | 1.006448 |
# Collect bel package version
try:
import bel.__version__
config["bel"]["version"] = bel.__version__.__version__
except KeyError:
config["bel"] = {"version": bel.__version__.__version__}
except ModuleNotFoundError:
pass
# Collect bel_resources version
try:... | def get_versions(config) -> dict | Get versions of bel modules and tools | 2.809448 | 2.494761 | 1.126139 |
# 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.environ:
if re.match("BELBIO_", e):
val = os.environ.get(e)
if val:
e.replace("BELBIO_", "")
... | 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 dictionary.
Example:
BELBIO_BEL_API__SERVERS__API_URL=http:... | 7.992525 | 6.00426 | 1.331142 |
if override_config_fn:
with open(override_config_fn, "r") as f:
override_config = yaml.load(f, Loader=yaml.SafeLoader)
if not override_config:
log.info("Missing override_config")
return functools.reduce(rec_merge, (config, override_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:
config: original configuration
override_config: new configuration to override/extend current config
override_config_fn: new configuration filenam... | 3.098343 | 3.427052 | 0.904084 |
for k, v in d1.items():
if k in d2:
# this next check is the only difference!
if all(isinstance(e, collections.MutableMapping) for e in (v, d2[k])):
d2[k] = rec_merge(v, d2[k])
# we could further check types and merge as appropriate here.
d3 = d1... | 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)) | 3.683607 | 3.574984 | 1.030384 |
version = metadata["metadata"]["version"]
# LOAD TERMS INTO Elasticsearch
with timy.Timer("Load Terms") as timer:
es = bel.db.elasticsearch.get_client()
es_version = version.replace("T", "").replace("-", "").replace(":", "")
index_prefix = f"terms_{metadata['metadata']['names... | 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 containing the metadata for terminology
forceupdate: force f... | 3.661144 | 3.494064 | 1.047818 |
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.loads(line)
# skip if not term record (e.g. is a metadata record)
if "term" not in term:
... | def terms_iterator_for_elasticsearch(fo: IO, index_name: str) | Add index_name to term documents for bulk load | 3.013867 | 2.79185 | 1.079523 |
(ns, val) = term_id.split(":", maxsplit=1)
term_id = f"{ns}:{val.lower()}"
return 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 | 5.187125 | 5.245461 | 0.988879 |
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) | Needed for things like abstracts which have internal tags (see PMID:27822475) | 2.803619 | 2.4425 | 1.147848 |
r = get_url(PUBTATOR_TMPL.replace("PMID", pmid), timeout=10)
if r and r.status_code == 200:
pubtator = r.json()[0]
else:
log.error(
f"Cannot access Pubtator, status: {r.status_code} url: {PUBTATOR_TMPL.replace('PMID', pmid)}"
)
return None
known_types = ... | 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. | 2.017641 | 1.993456 | 1.012132 |
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 year:
pub_date = f"{year}-{mon}-{day}"
return pub_date | def process_pub_date(year, mon, day) | Create pub_date from what Pubmed provides in Journal PubDate entry | 2.653664 | 2.500124 | 1.061413 |
pubmed_url = PUBMED_TMPL.replace("PMID", str(pmid))
r = get_url(pubmed_url)
log.info(f"Getting Pubmed URL {pubmed_url}")
try:
root = etree.fromstring(r.content)
doc = {"abstract": ""}
doc["pmid"] = root.xpath("//PMID/text()")[0]
doc["title"] = next(iter(root.xpath("... | 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 getting pub_year at this point from the <PubDate> elem... | 2.245723 | 2.268393 | 0.990006 |
text = pubmed["title"] + pubmed["abstract"]
annotations = {}
for nsarg in pubmed["annotations"]:
url = f'{config["bel_api"]["servers"]["api_url"]}/terms/{url_path_param_quoting(nsarg)}'
log.info(f"URL: {url}")
r = get_url(url)
log.info(f"Result: {r}")
new_nsar... | 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 duplicated code with bel_api:api.services.pubmed
Args:
pubmed
Returns:... | 2.694235 | 2.580756 | 1.043971 |
pubmed = get_pubmed(pmid)
pubtator = get_pubtator(pmid)
pubmed["annotations"] = copy.deepcopy(pubtator["annotations"])
# Add entity types and annotation types to annotations
pubmed = enhance_pubmed_annotations(pubmed)
return pubmed | 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 | 4.493072 | 3.803882 | 1.18118 |
gene_id_key = bel.db.arangodb.arango_id_to_key(canonical_gene_id)
orthologs = {}
if species:
query_filter = f"FILTER vertex.tax_id IN {species}"
query = f
cursor = belns_db.aql.execute(query, batch_size=20)
results = cursor.pop()
for ortholog in results["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: target species for ortholog - tax id format TAX:<number>
Returns:
List[... | 5.945458 | 5.316514 | 1.1183 |
if val is not None:
if val.lower() == 'false':
val = False
elif val.lower() == 'true':
val = True
return val | def normalize_value(val) | Normalize strings with booleans into Python types. | 2.850513 | 2.48295 | 1.148035 |
for key, val in dictionary.iteritems():
if isinstance(val, dict):
dictionary[key] = normalize_dictionary_values(val)
elif isinstance(val, list):
dictionary[key] = list(val)
else:
dictionary[key] = normalize_value(val)
return dictionary | def normalize_dictionary_values(dictionary) | Normalizes the values in a dictionary recursivly. | 1.986941 | 1.933663 | 1.027553 |
try:
if not cache:
with requests_cache.disabled():
r = requests.get(url, params=params, timeout=timeout)
else:
r = requests.get(url, params=params, timeout=timeout)
log.debug(f"Response headers {r.headers} From cache {r.from_cache}")
r... | 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 unless this is false
Returns:
Requests Result obj or None if timed out | 2.669507 | 2.520808 | 1.058988 |
timespan = datetime.datetime.now() - start_time
timespan_ms = timespan.total_seconds() * 1000
return timespan_ms | def timespan(start_time) | Return time in milliseconds from start_time | 2.80285 | 2.291144 | 1.22334 |
response = requests.get(url, stream=True)
fp = tempfile.NamedTemporaryFile()
for chunk in response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
fp.write(chunk)
# log.info(f'Download file - tmp file: {fp.name} size: {fp.tell()}')
return fp | def download_file(url) | Download file | 2.697682 | 2.76367 | 0.976123 |
# first_true([a,b,c], x) --> a or b or c or x
# first_true([a,b], x, f) --> a if f(a) else b if f(b) else x
return next(filter(pred, iterable), default) | def first_true(iterable, default=False, pred=None) | Returns the first true value in the iterable.
If no true value is found, returns *default*
If *pred* is not None, returns the first item
for which pred(item) is true. | 2.496422 | 3.166912 | 0.788283 |
doc_string = json.dumps(doc, sort_keys=True)
return _create_hash(doc_string) | def _create_hash_from_doc(doc: Mapping[str, Any]) -> str | Create hash Id from edge record
Args:
edge (Mapping[str, Any]): edge record to create hash from
Returns:
str: Murmur3 128 bit hash | 4.457877 | 4.640267 | 0.960694 |
if self.end is None:
# if elapsed is called in the context manager scope
return (self() - self.start) * self.factor
else:
# if elapsed is called out of the context manager scope
return (self.end - self.start) * self.factor | def elapsed(self) | Return the current elapsed time since start
If the `elapsed` property is called in the context manager scope,
the elapsed time bewteen start and property access is returned.
However, if it is accessed outside of the context manager scope,
it returns the elapsed time bewteen entering and ... | 4.397377 | 3.046269 | 1.443529 |
start_time = datetime.datetime.now()
# Clean out edges for nanopub in edgestore
query = f
try:
edgestore_db.aql.execute(query)
except Exception as e:
log.debug(f"Could not remove nanopub-related edges: {query} msg: {e}")
end_time1 = datetime.datetime.now()
delta_ms ... | def load_edges_into_db(
nanopub_id: str,
nanopub_url: str,
edges: list = [],
edges_coll_name: str = edges_coll_name,
nodes_coll_name: str = nodes_coll_name,
) | Load edges into Edgestore | 1.917895 | 1.874957 | 1.022901 |
for edge in itertools.chain(edges, files.read_edges(edges_fn)):
subj = copy.deepcopy(edge["edge"]["subject"])
subj_id = str(utils._create_hash_from_doc(subj))
subj["_key"] = subj_id
obj = copy.deepcopy(edge["edge"]["object"])
obj_id = str(utils._create_hash_from_doc(o... | def edge_iterator(edges=[], edges_fn=None) | Yield documents from edge for loading into ArangoDB | 2.457852 | 2.356284 | 1.043105 |
hostname = urllib.parse.urlsplit(url)[1]
start_dates_doc = state_mgmt.get(start_dates_doc_key)
if not start_dates_doc:
start_dates_doc = {
"_key": start_dates_doc_key,
"start_dates": [{"nanopubstore": hostname, "start_dt": start_dt}],
}
state_mgmt.inser... | def update_nanopubstore_start_dt(url: str, start_dt: str) | Add nanopubstore start_dt to belapi.state_mgmt collection
Args:
url: url of nanopubstore
start_dt: datetime of last query against nanopubstore for new ID's | 2.102151 | 1.974986 | 1.064388 |
hostname = urllib.parse.urlsplit(url)[1]
start_dates_doc = state_mgmt.get(start_dates_doc_key)
if start_dates_doc and start_dates_doc.get("start_dates"):
date = [
dt["start_dt"]
for dt in start_dates_doc["start_dates"]
if dt["nanopubstore"] == hostname
... | def get_nanopubstore_start_dt(url: str) | Get last start_dt recorded for getting new nanopub ID's | 3.629983 | 3.212343 | 1.130011 |
if not ns_root_url:
ns_root_url = config["bel_api"]["servers"]["nanopubstore"]
url = f"{ns_root_url}/nanopubs/timed"
if not start_dt:
start_dt = get_nanopubstore_start_dt(ns_root_url)
params = {"startTime": start_dt, "published": True}
# TODO - this is coming back without a ... | def get_nanopub_urls(ns_root_url: str = None, start_dt: str = None) -> dict | Get modified and deleted nanopub urls
Limited by last datetime retrieved (start_dt). Modified includes new and updated nanopubs
Returns:
dict: {'modified': [], 'deleted': []} | 3.132406 | 3.040698 | 1.03016 |
r = bel.utils.get_url(url, cache=False)
if r and r.json():
return r.json()
else:
return {} | def get_nanopub(url) | Get Nanopub from nanopubstore given url | 6.491483 | 6.752502 | 0.961345 |
if config_fn:
config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn)
else:
config = ctx.config
api = utils.first_true(
[api, config["bel_api"]["servers"].get("api_url", None)], None
)
print(f"Running validate nanopubs using {api}") | def nanopub_validate(ctx, input_fn, output_fn, api, config_fn) | Validate nanopubs | 7.084285 | 6.417533 | 1.103895 |
try:
(
out_fh,
yaml_flag,
jsonl_flag,
json_flag,
) = bel.nanopub.files.create_nanopubs_fh(output_fn)
if yaml_flag or json_flag:
docs = []
# input file
if re.search("gz$", input_fn):
f = gzip.open(... | def convert_belscript(ctx, input_fn, output_fn) | Convert belscript to nanopubs_bel format
This will convert the OpenBEL BELScript file format to
nanopub_bel-1.0.0 format.
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
If output fn has *.gz, will written as a gzip file
If output fn has *.jso... | 3.20804 | 2.853873 | 1.1241 |
try:
(
out_fh,
yaml_flag,
jsonl_flag,
json_flag,
) = bel.nanopub.files.create_nanopubs_fh(output_fn)
if yaml_flag or json_flag:
docs = []
# input file
if re.search("gz$", input_fn):
f = gzip.open(... | def reformat(ctx, input_fn, output_fn) | Reformat between JSON, YAML, JSONLines formats
\b
input_fn:
If input fn has *.gz, will read as a gzip file
\b
output_fn:
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 writ... | 3.442363 | 3.318954 | 1.037183 |
counts = {
"nanopubs": 0,
"assertions": {"total": 0, "subject_only": 0, "nested": 0, "relations": {}},
}
for np in bnf.read_nanopubs(input_fn):
if "nanopub" in np:
counts["nanopubs"] += 1
counts["assertions"]["total"] += len(np["nanopub"]["assertions"])... | def nanopub_stats(ctx, input_fn) | Collect statistics on nanopub file
input_fn can be json, jsonl or yaml and additionally gzipped | 2.763696 | 2.770373 | 0.99759 |
if config_fn:
config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn)
else:
config = ctx.config
# Configuration - will return the first truthy result in list else the default option
if namespace_targets:
namespace_targets = json.loads(namespace_target... | def canonicalize(ctx, statement, namespace_targets, version, api, config_fn) | Canonicalize statement
Target namespaces can be provided in the following manner:
bel stmt canonicalize "<BELStmt>" --namespace_targets '{"HGNC": ["EG", "SP"], "CHEMBL": ["CHEBI"]}'
the value of target_namespaces must be JSON and embedded in single quotes
reserving double quotes fo... | 4.36159 | 4.100187 | 1.063754 |
if config_fn:
config = bel.db.Config.merge_config(ctx.config, override_config_fn=config_fn)
else:
config = ctx.config
# Configuration - will return the first truthy result in list else the default option
if namespace_targets:
namespace_targets = json.loads(namespace_target... | def edges(ctx, statement, rules, species, namespace_targets, version, api, config_fn) | Create BEL Edges from BEL Statement | 3.955869 | 3.808271 | 1.038757 |
if delete:
bel.db.elasticsearch.get_client(delete=True)
else:
bel.db.elasticsearch.get_client() | def elasticsearch(delete, index_name) | Setup Elasticsearch namespace indexes
This will by default only create the indexes and run the namespace index mapping
if the indexes don't exist. The --delete option will force removal of the
index if it exists.
The index_name should be aliased to the index 'terms' when it's ready | 6.828203 | 9.123816 | 0.748393 |
if delete:
client = bel.db.arangodb.get_client()
bel.db.arangodb.delete_database(client, db_name)
if db_name == "belns":
bel.db.arangodb.get_belns_handle(client)
elif db_name == "edgestore":
bel.db.arangodb.get_edgestore_handle(client) | def arangodb(delete, db_name) | Setup ArangoDB database
db_name: Either 'belns' or 'edgestore' - must be one or the other
This will create the database, collections and indexes on the collection if it doesn't exist.
The --delete option will force removal of the database if it exists. | 3.65989 | 2.665613 | 1.373001 |
v = jsonschema.Draft4Validator(schema)
messages = []
errors = sorted(v.iter_errors(nanopub), key=lambda e: e.path)
for error in errors:
for suberror in sorted(error.context, key=lambda e: e.schema_path):
print(list(suberror.schema_path), suberror.message, sep=", ")
... | def validate_to_schema(nanopub, schema) -> Tuple[bool, List[Tuple[str, str]]] | Validate nanopub against jsonschema for nanopub
Args:
nanopub (Mapping[str, Any]): nanopub dict
schema (Mapping[str, Any]): nanopub schema
Returns:
Tuple[bool, List[str]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if... | 2.533762 | 2.478594 | 1.022258 |
hash_list = []
# Type
hash_list.append(nanopub["nanopub"]["type"].get("name", "").strip())
hash_list.append(nanopub["nanopub"]["type"].get("version", "").strip())
# Citation
if nanopub["nanopub"]["citation"].get("database", False):
hash_list.append(
nanopub["nanopub"]... | def hash_nanopub(nanopub: Mapping[str, Any]) -> str | Create CityHash64 from nanopub for duplicate check
TODO - check that this hash value is consistent between C# and Python running on
laptop and server
Build string to hash
Collect flat array of (all values.strip()):
nanopub.type.name
nanopub.type.version
One of:
na... | 2.058229 | 1.634305 | 1.259391 |
# Validate nanopub
(is_valid, messages) = validate_to_schema(nanopub, self.nanopub_schema)
if not is_valid:
return messages
# Extract BEL Version
if nanopub["nanopub"]["type"]["name"].upper() == "BEL":
bel_version = nanopub["nanopub"]["type"]["v... | def validate(
self, nanopub: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]] | Validates using the nanopub schema
Args:
nanopub (Mapping[str, Any]): nanopub dict
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is ('ERROR|WAR... | 3.145422 | 3.073687 | 1.023338 |
url = f'{self.endpoint}/terms/{context["id"]}'
res = requests.get(url)
if res.status_code == 200:
return (True, [])
else:
return (False, [("WARNING", f'Context {context["id"]} not found at {url}')]) | def validate_context(
self, context: Mapping[str, Any]
) -> Tuple[bool, List[Tuple[str, str]]] | Validate context
Args:
context (Mapping[str, Any]): context dictionary of type, id and label
Returns:
Tuple[bool, List[Tuple[str, str]]]:
bool: Is valid? Yes = True, No = False
List[Tuple[str, str]]: Validation issues, empty if valid, tuple is (... | 3.338454 | 3.086011 | 1.081802 |
edges = bel.edge.edges.create_edges(
nanopub,
self.endpoint,
namespace_targets=namespace_targets,
rules=rules,
orthologize_target=orthologize_target,
)
return edges | def bel_edges(
self,
nanopub: Mapping[str, Any],
namespace_targets: Mapping[str, List[str]] = {},
rules: List[str] = [],
orthologize_target: str = None,
) -> List[Mapping[str, Any]] | Create BEL Edges from BEL nanopub
Args:
nanopub (Mapping[str, Any]): bel nanopub
namespace_targets (Mapping[str, List[str]]): what namespaces to canonicalize
rules (List[str]): which computed edge rules to process, default is all,
look at BEL Specification yam... | 2.984092 | 3.809098 | 0.783412 |
def main_hrun():
parser = argparse.ArgumentParser(description="Tools for http(s) test. Base on rtsf.")
parser.add_argument(
'--log-level', default='INFO',
help="Specify logging level, default is INFO.")
parser.add_argument(
'--log-file',
... | parse command line options and run commands. | null | null | null | |
if not os.path.isdir("./build"):
raise NotADirectoryError
for path, dirs, files in os.walk("./build"):
for file_name in files:
file_name_parts = os.path.splitext(file_name)
if file_name_parts[1] == ".pyd":
return path
return None | def find_pyd_file() | Return path to .pyd after successful build command.
:return: Path to .pyd file or None. | 2.774964 | 2.534659 | 1.094808 |
try:
shape = res.coords.len, 2
ptr = cast(res.coords.data, POINTER(c_double))
array = np.ctypeslib.as_array(ptr, shape)
return array.tolist()
finally:
drop_array(res.coords) | def _void_array_to_nested_list(res, _func, _args) | Dereference the FFI result to a list of coordinates | 5.719189 | 4.555739 | 1.255381 |
abspath = abspath.lower()
fname, ext = os.path.splitext(abspath)
if ext in [".json", ".js"]:
is_json = True
elif ext == ".gz":
is_json = False
elif ext == ".tmp":
return is_json_file(fname)
else:
raise JsonExtError(
"'%s' is not a valid json file.... | def is_json_file(abspath) | Parse file extension.
- *.json: uncompressed, utf-8 encode json file
- *.gz: compressed, utf-8 encode json file | 3.443779 | 3.257545 | 1.05717 |
fname, ext = os.path.splitext(abspath)
return fname + ext.lower() | def lower_ext(abspath) | Convert file extension to lowercase. | 3.064112 | 2.928063 | 1.046464 |
if default is None:
default = dict()
prt("\nLoad from '%s' ..." % abspath, enable_verbose)
abspath = lower_ext(str(abspath))
is_json = is_json_file(abspath)
if not os.path.exists(abspath):
prt(" File not found, use default value: %r" %
default, enable_verbose)
... | def load(abspath, default=None, enable_verbose=True) | Load Json from file. If file are not exists, returns ``default``.
:param abspath: file path. use absolute path as much as you can.
extension has to be ``.json`` or ``.gz`` (for compressed Json).
:type abspath: string
:param default: default ``dict()``, if ``abspath`` not exists, return the
... | 3.906303 | 3.458704 | 1.129412 |
prt("\nDump to '%s' ..." % abspath, enable_verbose)
abspath = lower_ext(str(abspath))
is_json = is_json_file(abspath)
if os.path.exists(abspath):
if not overwrite: # 存在, 并且overwrite=False
prt(" Stop! File exists and overwrite is not allowed",
enable_verbose... | def dump(data, abspath,
indent_format=False,
float_precision=None,
ensure_ascii=True,
overwrite=False,
enable_verbose=True) | Dump Json serializable object to file.
Provides multiple choice to customize the behavior.
:param data: Serializable python object.
:type data: dict or list
:param abspath: ``save as`` path, file extension has to be ``.json`` or ``.gz``
(for compressed Json)
:type abspath: string
:par... | 3.287921 | 3.177651 | 1.034702 |
abspath = lower_ext(str(abspath))
abspath_temp = "%s.tmp" % abspath
dump(data, abspath_temp,
indent_format=indent_format, float_precision=float_precision,
ensure_ascii=ensure_ascii,
overwrite=True, enable_verbose=enable_verbose)
shutil.move(abspath_temp, abspath) | def safe_dump(data, abspath,
indent_format=False,
float_precision=None,
ensure_ascii=True,
enable_verbose=True) | A stable version of :func:`dump`, this method will silently overwrite
existing file.
There's a issue with :func:`dump`: If your program is interrupted while
writing, you got an incomplete file, and you also lose the original file.
So this method write json to a temporary file first, then rename to wh... | 2.839907 | 3.051371 | 0.930699 |
try:
return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False)
except:
return json.dumps(data, sort_keys=True, indent=4, ensure_ascii=True) | def pretty_dumps(data) | Return json string in pretty format.
**中文文档**
将字典转化成格式化后的字符串。 | 1.783204 | 1.951846 | 0.913599 |
assert small < large, "Can only pad when new size larger than old size"
padsize = large - small
if padsize % 2 != 0:
leftpad = (padsize - 1)/2
else:
leftpad = padsize/2
rightpad = padsize-leftpad
return int(leftpad), int(rightpad) | def _get_pad_left_right(small, large) | Compute left and right padding values.
Here we use the convention that if the padding
size is odd, we pad the odd part to the right
and the even part to the left.
Parameters
----------
small : int
Old size of original 1D array
large : int
New size off padded 1D array
R... | 3.563537 | 3.742894 | 0.952081 |
if size is None:
size = list()
for s in av.shape:
size.append(int(2*s))
elif not hasattr(size, "__len__"):
size = [size]
assert len(av.shape) in [1, 2], "Only 1D and 2D arrays!"
assert len(av.shape) == len(
size), "`size` must have same length as `av.sha... | def pad_add(av, size=None, stlen=10) | Perform linear padding for complex array
The input array `av` is padded with a linear ramp starting at the
edges and going outwards to an average value computed from a band
of thickness `stlen` at the outer boundary of the array.
Pads will only be appended, not prepended to the array.
If the inpu... | 2.521695 | 2.500991 | 1.008278 |
assert len(size) == 1
padx = _get_pad_left_right(av.shape[0], size[0])
mask = np.zeros(av.shape, dtype=bool)
mask[stlen:-stlen] = True
border = av[~mask]
if av.dtype.name.count("complex"):
padval = np.average(np.abs(border)) * \
np.exp(1j*np.average(np.angle(border)))
... | def _pad_add_1d(av, size, stlen) | 2D component of `pad_add` | 3.231215 | 3.234813 | 0.998888 |
if size is None:
size = list()
for s in pv.shape:
assert s % 2 == 0, "Uneven size; specify correct size of output!"
size.append(int(s/2))
elif not hasattr(size, "__len__"):
size = [size]
assert len(pv.shape) in [1, 2], "Only 1D and 2D arrays!"
assert... | def pad_rem(pv, size=None) | Removes linear padding from array
This is a convenience function that does the opposite
of `pad_add`.
Parameters
----------
pv : 1D or 2D ndarray
The array from which the padding will be removed.
size : tuple of length 1 (1D) or 2 (2D), optional
The final size of the un-padded ... | 3.264276 | 3.131712 | 1.04233 |
rate_limited_msg = False
while True:
is_rate_limited = self.limit.is_rate_limited(uuid)
if is_rate_limited:
time.sleep(0.3) # save hammering redis
if not rate_limited_msg:
self.logger.info('Rate limit active..please w... | def rate_limit(self) | Simple rate limit function using redis | 4.855111 | 4.533495 | 1.070942 |
url = self.base_url + "file/scan"
params = {'apikey': apikey}
scanfile = {"file": open(filename, 'rb')}
response = requests.post(url, files=scanfile, params=params)
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
if response.status_code == s... | def scan_file(self, filename, apikey) | Sends a file to virus total for assessment | 2.958947 | 2.804602 | 1.055033 |
url = self.base_url + "file/rescan"
params = {
'apikey': apikey,
'resource': sha256hash
}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, params=params)
if response.status_code == se... | def rescan_file(self, filename, sha256hash, apikey) | just send the hash, check the date | 2.720792 | 2.65059 | 1.026485 |
url = self.base_url + "file/report"
params = {"apikey": apikey, "resource": sha256sum}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, data=params)
if response.status_code == self.HTTP_OK:
json_res... | def binary_report(self, sha256sum, apikey) | retrieve report from file scan | 3.122809 | 3.01486 | 1.035806 |
url = self.base_url + "ip-address/report"
parameters = {"ip": ipaddr, "apikey": apikey}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.get(url, params=parameters)
if response.status_code == self.HTTP_OK:
json... | def send_ip(self, ipaddr, apikey) | Send IP address for list of past malicous domain associations | 3.307656 | 3.295479 | 1.003695 |
url = self.base_url + "url/report"
params = {"apikey": apikey, 'resource': scan_url}
rate_limit_clear = self.rate_limit()
if rate_limit_clear:
response = requests.post(url, params=params, headers=self.headers)
if response.status_code == self.HTTP_OK:
... | def url_report(self, scan_url, apikey) | Send URLS for list of past malicous associations | 3.074894 | 3.015033 | 1.019854 |
requirements_file = open(filename).read()
hard_requirements = []
for line in requirements_file.splitlines():
if _is_requirement(line):
if line.find(';') > -1:
dep, condition = tuple(line.split(';'))
extra_packages[condition.strip()].append(dep.strip(... | def _read_requirements(filename, extra_packages) | Returns a list of package requirements read from the file. | 3.184448 | 3.059273 | 1.040917 |
splits = text.split(delimiter)
# remove our delimiters and whitespace
splits = [f for f in splits if f != delimiter and len(f.strip()) > 0]
index = conversions.to_integer(index, ctx)
if index < 1:
raise ValueError('Field index cannot be less than 1')
if index <= len(splits):
... | def field(ctx, text, index, delimiter=' ') | Reference a field in string separated by a delimiter | 4.074381 | 4.03925 | 1.008697 |
return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx) | def epoch(ctx, datetime) | Converts the given date to the number of seconds since January 1st, 1970 UTC | 13.411007 | 11.182727 | 1.199261 |
def chunk(value, chunk_size):
return [value[i: i + chunk_size] for i in range(0, len(value), chunk_size)]
text = conversions.to_string(text, ctx).strip()
if not text:
return ''
# trim off the plus for phone numbers
if text[0] == '+':
text = text[1:]
length = len(t... | def read_digits(ctx, text) | Formats digits in text for reading in TTS | 3.456875 | 3.412912 | 1.012881 |
text = conversions.to_string(text, ctx).lstrip()
first = first_word(ctx, text)
return text[len(first):].lstrip() if first else '' | def remove_first_word(ctx, text) | Removes the first word from the given text string | 5.684322 | 5.52106 | 1.029571 |
return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces) | def word(ctx, text, number, by_spaces=False) | Extracts the nth word from the given text string | 8.809388 | 8.655051 | 1.017832 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.