output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Add argument types to the function data structure. | Given the following Python 3 function, write the documentation
def arg_types(parsed: Parsed, errors: Errors) -> Tuple[Parsed, Errors]:
func_pattern = re.compile(r"\s*[a-zA-Z]+\(")
nsarg_pattern = re.compile(r"^\s*([A-Z]+):(.*?)\s*$")
for span in parsed:
if parsed[span]["type"] != "Function" or "pa... | As a python code expert, you are capable of creating scripts from specifications. |
Parse BEL relations from BEL string into a nested BEL tree structure. | Can you generate a brief explanation for the following Python 3 code
def parse_relations(
belstr: str, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
"""Parse relations from BEL string
Args:
belstr: BEL string as one single string (not list of chars)
char_lo... | As a Python code analyst, you investigate and solve complex coding mysteries |
Parse nested BEL object. | Explain what the following Python 3 code does
def parse_nested(
bels: list, char_locs: CharLocs, parsed: Parsed, errors: Errors
) -> Tuple[Parsed, Errors]:
""" Parse nested BEL object """
for sp in char_locs[
"nested_parens"
]: # sp = start parenthesis, ep = end parenthesis
ep, level =... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Dump json when using tuples for dictionary keys
| Can you tell what is the following Python 3 function doing
def dump_json(d: dict) -> None:
import json
k = d.keys()
v = d.values()
k1 = [str(i) for i in k]
return json.dumps(dict(zip(*[k1, v])), indent=4) | You are a Python code analyst, evaluating scripts for potential improvements. |
Collect flattened list of spans of BEL syntax types
Provide simple list of BEL syntax type spans for highlighting. | Given the following Python 3 function, write the documentation
def collect_spans(ast: AST) -> List[Tuple[str, Tuple[int, int]]]:
spans = []
if ast.get("subject", False):
spans.extend(collect_spans(ast["subject"]))
if ast.get("object", False):
spans.extend(collect_spans(ast["object"]))
... | As a python code expert, you are capable of creating scripts from specifications. |
Create AST for top - level functions. | Here you have a function in Python 3, explain what it does
def parsed_function_to_ast(parsed: Parsed, parsed_key):
sub = parsed[parsed_key]
subtree = {
"type": "Function",
"span": sub["span"],
"function": {
"name": sub["name"],
"name_span": sub["name_span"],
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def parsed_top_level_errors(parsed, errors, component_type: str = "") -> Errors:
"""Check full parse for errors
Args:
parsed:
errors:
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
# Error ... | How would you implement a function in Python 3 that
checks full parse for errors | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert parsed data struct to a dictionary of weolecular hierarchy. | Given the following Python 3 function, write the documentation
def parsed_to_ast(parsed: Parsed, errors: Errors, component_type: str = ""):
ast = {}
sorted_keys = sorted(parsed.keys())
# Setup top-level tree
for key in sorted_keys:
if parsed[key]["type"] == "Nested":
nested_compone... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_ast_dict(belstr, component_type: str = ""):
"""Convert BEL string to AST dictionary
Args:
belstr: BEL string
component_type: Empty string or 'subject' or 'object' to indicate that we
are parsing the subject or object field input
"""
errors = []
parsed = {}
b... | How would you implement a function in Python 3 that
converts BEL string to BEL AST dictionary | As a python code expert, you are capable of creating scripts from specifications. |
def get_ast_obj(belstr, bel_version, component_type: str = ""):
"""Convert AST partialparse dict to BELAst"""
ast_dict, errors = get_ast_dict(belstr, component_type)
spec = bel_specification.get_specification(bel_version)
subj = ast_dict["subject"]
subj_ast = add_ast_fn(subj, spec)
relation ... | Can you create a Python 3 function that
converts BEL AST partialparse dict to BELAst object | You are a Python code generator, capable of creating scripts from specifications. |
def add_ast_fn(d, spec, parent_function=None):
"""Convert dict AST to object AST Function
Args:
ast_fn: AST object Function
d: AST as dictionary
spec: BEL Specification
Return:
ast_fn
"""
if d["type"] == "Function":
ast_fn = Function(d["function"]["name"], ... | Write a Python 3 script for
converting dict AST to BEL object AST Function | You are a Python code architect, reviewing and designing scalable and efficient code |
def convert_nsarg(
nsarg: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""[De]Canonicalize NSArg
Args:
nsarg (str): bel statement string or partial string (e.g. subject or object)
... | Write a Python 3 function for
converting NSArg to BEL - style format | You are a Python code generator, capable of creating scripts from specifications. |
def convert_namespaces_str(
bel_str: str,
api_url: str = None,
namespace_targets: Mapping[str, List[str]] = None,
canonicalize: bool = False,
decanonicalize: bool = False,
) -> str:
"""Convert namespace in string
Uses a regex expression to extract all NSArgs and replace them with the
up... | Can you implement a function in Python 3 that
converts BEL namespace in string Uses a regex expression to extract all NSArgs and replace them with the updated NSArg from BEL. bio API terms endpoint. | As a Python code analyst, you investigate and solve complex coding mysteries |
Recursively orthologize BEL Entities in BEL AST using API endpoint | Can you generate a brief explanation for the following Python 3 code
def orthologize(ast, bo, species_id: str):
# if species_id == 'TAX:9606' and str(ast) == 'MGI:Sult2a1':
# import pdb; pdb.set_trace()
if not species_id:
bo.validation_messages.append(
("WARNING", "No species id wa... | As a python code expert, you are capable of creating scripts from specifications. |
Recursively collect NSArg orthologs for BEL AST | Explain what the following Python 3 code does
def populate_ast_nsarg_orthologs(ast, species):
ortholog_namespace = "EG"
if isinstance(ast, NSArg):
if re.match(ortholog_namespace, ast.canonical):
orthologs = bel.terms.orthologs.get_orthologs(
ast.canonical, list(species.keys... | As a Python code analyst, you investigate and solve complex coding mysteries |
Clean up basic formatting of BEL statement as single string
| Here you have a function in Python 3, explain what it does
def preprocess_bel_stmt(stmt: str) -> str:
stmt = stmt.strip() # remove newline at end of stmt
stmt = re.sub(r",+", ",", stmt) # remove multiple commas
stmt = re.sub(r",", ", ", stmt) # add space after each comma
stmt = re.sub(r" +", " ", st... | You are a Python code architect, reviewing and designing scalable and efficient code |
Quoting nsarg value if needs quotes. | How would you explain what the following Python 3 function does
def quoting_nsarg(nsarg_value):
quoted = re.findall(r'^"(.*)"$', nsarg_value)
if re.search(
r"[),\s]", nsarg_value
): # quote only if it contains whitespace, comma or ')'
if quoted:
return nsarg_value
else:... | You are a Python code analyst, evaluating scripts for potential improvements. |
Dump a bel specification dictionary using YAML | Make a summary of the following Python 3 code
def _dump_spec(spec):
with open("spec.yaml", "w") as f:
yaml.dump(spec, f, Dumper=MyDumper, default_flow_style=False) | You are a Python code generator, capable of creating scripts from specifications. |
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 | Write a Python 3 script to
compute edges from BEL AST. | As a python code expert, you are capable of creating scripts from specifications. |
Processes a single computed edge rule and returns a new edge that is a single edge that is a descendant of the edge. | How would you explain what the following Python 3 function does
def process_rule(edges: Edges, ast: Function, rule: Mapping[str, Any], spec: BELSpec):
ast_type = ast.__class__.__name__
trigger_functions = rule.get("trigger_function", [])
trigger_types = rule.get("trigger_type", [])
rule_subject = rule.g... | You are a Python code generator, capable of creating scripts from specifications. |
Load orthologs into ArangoDB | Here you have a function in Python 3, explain what it does
def load_orthologs(fo: IO, metadata: dict):
version = metadata["metadata"]["version"]
# LOAD ORTHOLOGS INTO ArangoDB
with timy.Timer("Load Orthologs") as timer:
arango_client = arangodb.get_client()
belns_db = arangodb.get_belns_ha... | As a Python code composer, you craft elegant and concise scripts. |
Process nanopub into edges and load into EdgeStore | Can you generate the documentation for the following Python 3 function
def nanopub_to_edges(nanopub: dict = {}, rules: List[str] = [], orthologize_targets: list = []):
# Collect input values ####################################################
nanopub_url = nanopub.get("source_url", "")
edge_dt = utils.dt... | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Implement a function in Python 3 to
extract species from ast. species set of tuples | You are a Python code analyst, evaluating scripts for potential improvements. |
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)
... | Write a Python 3 script for
generating a list of edge info for a list of assertions given orthologization targets. | You are a Python code analyst, evaluating scripts for potential improvements. |
Migrate BEL 1 to BEL 2. 0. 0 | Given the following Python 3 function, write the documentation
def migrate(belstr: str) -> str:
bo.ast = bel.lang.partialparse.get_ast_obj(belstr, "2.0.0")
return migrate_ast(bo.ast).to_string() | You are a Python code analyst, evaluating scripts for potential improvements. |
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() | Can you implement a function in Python 3 that
migrates BEL1 assertion into BEL 2. 0. 0 SRO triple | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert BEL1 AST Function to BEL2 AST Function | Here you have a function in Python 3, explain what it does
def convert(ast):
if ast and ast.type == "Function":
# Activity function conversion
if (
ast.name != "molecularActivity"
and ast.name in spec["namespaces"]["Activity"]["list"]
):
print("name", ast... | As a python code expert, you are capable of creating scripts from specifications. |
Convert BEL1 tloc to BEL2 tloc | Explain what the following Python 3 code does
def convert_tloc(ast):
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 ... | As a python code expert, you are capable of creating scripts from specifications. |
Convert BEL1 activities to BEL2 act | Can you tell what is the following Python 3 function doing
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] # protein argument
print("p_arg", p_arg)
ma_arg = Function("ma", bo.spec)
ma_arg.ad... | You are a Python code analyst, evaluating scripts for potential improvements. |
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 | How would you code a function in Python 3 to
update BEL1 pmod object with new protein modification term | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert BEL1 fus to BEL2 fus | Can you tell what is the following Python 3 function doing
def convert_fus(ast):
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... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Implement a function in Python 3 to
convert BEL1 sub to BEL2 var | As a Python code translator, you convert algorithms and pseudocode into Python. |
Convert a truncated function to BEL1 var | How would you explain what the following Python 3 function does
def convert_trunc(trunc):
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... | As a Python code analyst, you investigate and solve complex coding mysteries |
Get username and password from provided username and password OR in config OR blank in that order | Here you have a function in Python 3, explain what it does
def get_user_creds(username, password):
username = utils.first_true(
[username, config["bel_api"]["servers"]["arangodb_username"]], default=""
)
password = utils.first_true(
[password, config["secrets"]["bel_api"]["servers"].get("ara... | You are a Python code generator, capable of creating scripts from specifications. |
Get arango client and edgestore db handle | Can you generate the documentation for the following Python 3 function
def get_client(host=None, port=None, username=None, password=None, enable_logging=True):
host = utils.first_true(
[host, config["bel_api"]["servers"]["arangodb_host"], "localhost"]
)
port = utils.first_true([port, config["bel_ap... | As a Python code translator, you convert algorithms and pseudocode into 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,
... | Write a Python 3 function that can
get the arangodb database handle for the given resource. | As a Python code translator, you convert algorithms and pseudocode into 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... | Create a Python 3 function for
getting BEL namespace arango db handle | You are a Python code architect, reviewing and designing scalable and efficient code |
Get BEL API arango db handle | Here you have a function in Python 3, explain what it does
def get_belapi_handle(client, username=None, password=None):
(username, password) = get_user_creds(username, password)
sys_db = client.db("_system", username=username, password=password)
# Create a new database named "belapi"
try:
if ... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Create a Python 3 function for
batching load documents from ArangoDB | You are a Python code generator, capable of creating scripts from specifications. |
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) > ... | How would you implement a function in Python 3 that
converts an arango id to a _key value | As a Python code composer, you craft elegant and concise scripts. |
Load a resource into the BEL API. | Can you generate a brief explanation for the following Python 3 code
def load_resource(resource_url: str, forceupdate: bool = False):
log.info(f"Loading resource {resource_url}")
try:
# Download resource
fo = bel.utils.download_file(resource_url)
if not fo:
log.error(f"Cou... | You are a Python code architect, reviewing and designing scalable and efficient code |
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}},
... | Write a Python 3 script to
get term list using term_id | You are a Python code architect, reviewing and designing scalable and efficient code |
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 = []
... | Create a Python 3 function for
getting the equivalents given a term id | As a Python code analyst, you investigate and solve complex coding mysteries |
Get normalized term id from equivalents list | Explain what the following Python 3 code does
def get_normalized_term(term_id: str, equivalents: list, namespace_targets: dict) -> str:
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[... | As a Python code composer, you craft elegant and concise scripts. |
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)
... | Write a Python 3 function for
getting term labels given term ids | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Write a Python 3 function for
getting normalized terms - canonical and decanonical forms | As a Python code composer, you craft elegant and concise scripts. |
Generates a hash based on the specific fields for the object. | Here you have a function in Python 3, explain what it does
def _generate_hash(self):
self.hash = None
str_hash = ''
for key, val in self._get_params().iteritems():
str_hash += smart_str(val)
# Append the encryption string
str_hash += self._s... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Can you create a Python 3 function that
makes the SOAP request and convert the result to a dictionary. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns the action for a keyboard combination. | Make a summary of the following Python 3 code
def get_combination_action(combination):
accepted_actions = ('link', 'js')
for action in accepted_actions:
if action in combination:
return {action: combination[action]}
return {} | As a python code expert, you are capable of creating scripts from specifications. |
Process passed dict with key combinations or HOTKEYS dict from settings. HOTKEYS settings. | Here you have a function in Python 3, explain what it does
def get_processed_hotkeys(hotkeys=None):
hotkeys = hotkeys or ks_settings.HOTKEYS
processed_hotkeys = AutoVivification()
if not hotkeys:
return processed_hotkeys
for combination in hotkeys:
key_codes = get_key_codes(combination[... | You are a Python code analyst, evaluating scripts for potential improvements. |
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:
... | Can you implement a function in Python 3 that
calculates the list of key codes from a string with key combinations. | You are a Python code architect, reviewing and designing scalable and efficient code |
Parses a BEL statement and returns a ParseObject which contains either an AST or an error message. | Given the following Python 3 function, write the documentation
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 semantical... | You are a Python code analyst, evaluating scripts for potential improvements. |
Returns a canonicalized BEL statement string. | Can you generate a brief explanation for the following Python 3 code
def canonicalize(self, namespace_targets: Mapping[str, List[str]] = None) -> "BEL":
# TODO Need to order position independent args
if not self.ast:
return self
# Collect canonical/decanonical NSArg values
... | As a python code expert, you are capable of creating scripts from specifications. |
Adds canonical and decanonical values to the AST object for canonicalization | Can you generate the documentation for the following Python 3 function
def collect_nsarg_norms(self):
start_time = datetime.datetime.now()
self.ast = bel_utils.populate_ast_nsarg_defaults(self.ast, self.ast)
self.ast.collected_nsarg_norms = True
if (
hasattr(self.ast, "bel_o... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Add NSArg orthologs to the AST for the given species. | Here you have a function in Python 3, explain what it does
def collect_orthologs(self, species: list) -> "BEL":
if not species:
return self
species_labels = bel.terms.terms.get_labels(species)
# Collect canonical/decanonical NSArg values
if not self.ast.collected_nsarg_nor... | You are a Python code analyst, evaluating scripts for potential improvements. |
Computes all edges from the primary BEL statement and returns a list of edges in the medium format. | Can you generate a brief explanation for the following Python 3 code
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 Specifi... | You are a Python code generator, capable of creating scripts from specifications. |
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
... | Write a Python 3 script for
converting the object to BEL triple format | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert AST object to tree view of BEL AST | Explain what the following Python 3 code does
def print_tree(self) -> str:
if self.ast:
return self.ast.print_tree(ast_obj=self.ast)
else:
return "" | As a Python code translator, you convert algorithms and pseudocode into 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 = ... | How would you code a function in Python 3 to
convert Tatsu AST dictionary to BEL AST object | You are a Python code analyst, evaluating scripts for potential improvements. |
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
... | Can you create a Python 3 function that
converts the BEL AST object to string version of BEL AST object. | As a Python code composer, you craft elegant and concise scripts. |
Convert BEL object to BEL triple | Make a summary of the following Python 3 code
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_object:
if self.bel_relation.startswith("has"):
bel_relation = self.bel_relation
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Convert BEL AST object to tree view of BEL AST object | Can you generate the documentation for the following Python 3 function
def print_tree(self, ast_obj=None):
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(s... | As a Python code analyst, you investigate and solve complex coding mysteries |
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... | Implement a function in Python 3 to
convert the object to string version of BEL AST. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Generate subcomponents of the BEL subject or object in the Edgestore. | How would you explain what the following Python 3 function does
def subcomponents(self, subcomponents):
for arg in self.args:
if arg.__class__.__name__ == "Function":
subcomponents.append(arg.to_string())
if arg.function_type == "primary":
arg.sub... | As a Python code analyst, you investigate and solve complex coding mysteries |
Change the namespace value of the current object. | Here you have a function in Python 3, explain what it does
def change_nsvalue(self, namespace, value):
self.namespace = namespace
self.value = value | As a Python code composer, you craft elegant and concise scripts. |
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, ... | How would you code a function in Python 3 to
update Namespace and valueast. | You are a Python code architect, reviewing and designing scalable and efficient code |
Convert CSV str to list | Given the following Python 3 function, write the documentation
def convert_csv_str_to_list(csv_str: str) -> 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*', "... | You are a Python code generator, capable of creating scripts from specifications. |
Parse BEL Script Citation string into nanopub_bel citation object | Can you generate the documentation for the following Python 3 function
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, authors, comment, *extra) = (
citation_list + [None] * 7
)
... | As a Python code composer, you craft elegant and concise scripts. |
Split bel statement into subject relation object tuple | Here you have a function in Python 3, explain what it does
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 (m.group(1), m.group(2), m.group(3))
else:
log.info(
f"Could not parse bel state... | As a Python code composer, you craft elegant and concise scripts. |
Process SET DOCUMENT line in BEL script | Explain what the following Python 3 code does
def process_documentline(line, nanopubs_metadata):
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 | You are a Python code generator, capable of creating scripts from specifications. |
Process DEFINE line in BEL script | Here you have a function in Python 3, explain what it does
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(1).lower()
if def_type == "namespace":
def_type = "namespaces"... | As a Python code composer, you craft elegant and concise scripts. |
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... | Can you write a function in Python 3 where it
processes UNSET lines in BEL Script | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Create a Python 3 function for
converting set line into nanopub_bel annotations format | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you implement a function in Python 3 that
converts any multi - line SET statements into single line SET statements | As a Python code analyst, you investigate and solve complex coding mysteries |
Yields Nanopubs in BEL Script statements section
| Make a summary of the following Python 3 code
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 = 0
# for line in preprocess_belscri... | As a Python code translator, you convert algorithms and pseudocode into Python. |
this method reference from httprunner | How would you explain what the following Python 3 function does
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_respons... | You are a Python code analyst, evaluating scripts for potential improvements. |
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"... | Can you create a Python 3 function that
sets dynamic value from the string data of response | As a Python code translator, you convert algorithms and pseudocode into 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... | How would you code a function in Python 3 to
set dynamic value from the json data of response | As a python code expert, you are capable of creating scripts from specifications. |
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... | Can you implement a function in Python 3 that
reads file and generate nanopubs in nanopub_bel JSON Schema format | As a python code expert, you are capable of creating scripts from specifications. |
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... | Can you implement a function in Python 3 that
creates Nanopubs output filehandle | As a Python code analyst, you investigate and solve complex coding mysteries |
Write edges to file
| Here you have a function in Python 3, explain what it does
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
fi... | You are a Python code architect, reviewing and designing scalable and efficient code |
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) | Write a Python 3 script to
add index alias to index_name | You are a Python code architect, reviewing and designing scalable and efficient code |
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 | Write a Python 3 script for
deleting the terms index | As a python code expert, you are capable of creating scripts from specifications. |
Delete all terms indexes | Can you generate the documentation for the following Python 3 function
def delete_terms_indexes(es, index_name: str = "terms_*"):
try:
es.indices.delete(index=index_name)
except Exception as e:
log.error(f"Could not delete all terms indices: {e}") | As a Python code analyst, you investigate and solve complex coding mysteries |
Bulk load a set of documents into the cache | Can you generate the documentation for the following Python 3 function
def bulk_load_docs(es, docs):
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_... | As a python code expert, you are capable of creating scripts from specifications. |
Semantically validate BEL AST | Here you have a function in Python 3, explain what it does
def validate(bo, error_level: str = "WARNING") -> Tuple[bool, List[Tuple[str, str]]]:
if bo.ast:
bo = validate_functions(bo.ast, bo) # No WARNINGs generated in this function
if error_level == "WARNING":
bo = validate_arg_values... | You are a Python code analyst, evaluating scripts for potential improvements. |
Recursively validate function signatures and return a BEL object containing only valid BEL functions. | Can you generate the documentation for the following Python 3 function
def validate_functions(ast: BELAst, bo):
if isinstance(ast, Function):
log.debug(f"Validating: {ast.name}, {ast.function_type}, {ast.args}")
function_signatures = bo.spec["functions"]["signatures"][ast.name]["signatures"]
... | As a python code expert, you are capable of creating scripts from specifications. |
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... | Implement a function in Python 3 to
check if function args don t match function signature | As a Python code analyst, you investigate and solve complex coding mysteries |
Recursively validate NSArg and StrArg values | Make a summary of the following Python 3 code
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 isinstance(ast, NSArg):
term_id = "{}:{}".format(ast.namespace, ast.value)
va... | You are a Python code architect, reviewing and designing scalable and efficient code |
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... | Can you create a Python 3 function that
gets BELBio configuration from files | As a Python code composer, you craft elegant and concise scripts. |
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... | Implement a function in Python 3 to
load the configuration from the belbio_conf_fp belbio_secrets_fp | As a python code expert, you are capable of creating scripts from specifications. |
Get versions of bel modules and tools | Explain what the following Python 3 code does
def get_versions(config) -> dict:
# Collect bel package version
try:
import bel.__version__
config["bel"]["version"] = bel.__version__.__version__
except KeyError:
config["bel"] = {"version": bel.__version__.__version__}
except Modu... | You are a Python code generator, capable of creating scripts from specifications. |
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... | Can you create a Python 3 function that
overrides config with environment variables | As a python code expert, you are capable of creating scripts from specifications. |
Override config with additional configuration in override_config or override_config_fn
Shipment Used in script to merge CLI options with Config
Shipment | Can you generate the documentation for the following Python 3 function
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... | You are a Python code architect, reviewing and designing scalable and efficient code |
Load terms into Elasticsearch and ArangoDB | Can you generate the documentation for the following Python 3 function
def load_terms(fo: IO, metadata: dict, forceupdate: bool):
version = metadata["metadata"]["version"]
# LOAD TERMS INTO Elasticsearch
with timy.Timer("Load Terms") as timer:
es = bel.db.elasticsearch.get_client()
es_ver... | As a Python code analyst, you investigate and solve complex coding mysteries |
Iterate over the terms in the file that are in elastic search. | Explain what the following Python 3 code does
def terms_iterator_for_elasticsearch(fo: IO, index_name: str):
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)... | As a python code expert, you are capable of creating scripts from specifications. |
Lowercase the term value | Can you tell what is the following Python 3 function doing
def lowercase_term_id(term_id: str) -> str:
(ns, val) = term_id.split(":", maxsplit=1)
term_id = f"{ns}:{val.lower()}"
return term_id | As a Python code translator, you convert algorithms and pseudocode into 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 | Can you write a function in Python 3 where it
returns the text of a node. | You are a Python code generator, capable of creating scripts from specifications. |
Get Pubtator Bioconcepts from Pubmed Abstract
ArcGIS | Explain what the following Python 3 code does
def get_pubtator(pmid):
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(... | As a python code expert, you are capable of creating scripts from specifications. |
Create pub_date from what Pubmed provides in Journal PubDate entry
| Explain what the following Python 3 code does
def process_pub_date(year, mon, day):
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... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.