output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
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...
Implement a function in Python 3 to get pubmed xml for pmid and convert to JSON
You are a Python code analyst, evaluating scripts for potential improvements.
Enhance pubmed annotations with the same namespace IDs
How would you explain what the following Python 3 function does def enhance_pubmed_annotations(pubmed: Mapping[str, Any]) -> Mapping[str, Any]: text = pubmed["title"] + pubmed["abstract"] annotations = {} for nsarg in pubmed["annotations"]: url = f'{config["bel_api"]["servers"]["api_url"]}/terms/...
As a Python code composer, you craft elegant and concise scripts.
Get the pubmed document with the given Pubmed PMID and add entity types and annotation types to the pubmed document.
Explain what the following Python 3 code does def get_pubmed_for_beleditor(pmid: str) -> Mapping[str, Any]: pubmed = get_pubmed(pmid) pubtator = get_pubtator(pmid) pubmed["annotations"] = copy.deepcopy(pubtator["annotations"]) # Add entity types and annotation types to annotations pubmed = enhance...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get orthologs for given gene_id and species
Can you tell what is the following Python 3 function doing def get_orthologs(canonical_gene_id: str, species: list = []) -> List[dict]: 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"""...
As a python code expert, you are capable of creating scripts from specifications.
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
Write a Python 3 function that can normalize strings with booleans into Python types.
As a Python code translator, you convert algorithms and pseudocode into Python.
Normalizes the values in a dictionary recursivly.
Can you tell what is the following Python 3 function doing def normalize_dictionary_values(dictionary): for key, val in dictionary.iteritems(): if isinstance(val, dict): dictionary[key] = normalize_dictionary_values(val) elif isinstance(val, list): dictionary[key] = list...
You are a Python code analyst, evaluating scripts for potential improvements.
Wrapper for requests. get that handles timeout exceptions and returns the result object
Can you generate the documentation for the following Python 3 function def get_url(url: str, params: dict = {}, timeout: float = 5.0, cache: bool = True): try: if not cache: with requests_cache.disabled(): r = requests.get(url, params=params, timeout=timeout) else: ...
As a Python code composer, you craft elegant and concise scripts.
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
Can you create a Python 3 function that returns time in milliseconds from start_time
As a python code expert, you are capable of creating scripts from specifications.
Download file from url and return file object
Can you generate the documentation for the following Python 3 function def download_file(url): 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) ...
As a python code expert, you are capable of creating scripts from specifications.
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. """ # first_true([a,b,c], x) --> a or b or c or x # first_true([a,b...
How would you implement a function in Python 3 that returns the first true value in the iterable.
As a Python code analyst, you investigate and solve complex coding mysteries
Create hash Id from document
Can you generate a brief explanation for the following Python 3 code def _create_hash_from_doc(doc: Mapping[str, Any]) -> str: doc_string = json.dumps(doc, sort_keys=True) return _create_hash(doc_string)
You are a Python code architect, reviewing and designing scalable and efficient code
Return the elapsed time since the start of the current block.
Given the following Python 3 function, write the documentation def elapsed(self): 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 ...
As a Python code composer, you craft elegant and concise scripts.
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""" start_time = datetime.datetime.now() # Clean out edges for nanopub in edgestore query = f"...
Can you implement a function in Python 3 that loads edges into Arangodb
You are a Python code architect, reviewing and designing scalable and efficient code
Yields all documents from an edge for loading into ArangoDB
Can you generate a brief explanation for the following Python 3 code def edge_iterator(edges=[], edges_fn=None): 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"] = sub...
You are a Python code generator, capable of creating scripts from specifications.
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 """ hostname = urllib.parse.urlsplit(url)[1] start_dates_doc = ...
Implement a Python 3 function for updating nanopubstore start_dt in belapi. state_mgmt collection
You are a Python code analyst, evaluating scripts for potential improvements.
def get_nanopubstore_start_dt(url: str): """Get last start_dt recorded for getting new nanopub ID's""" 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"] ...
How would you code a function in Python 3 to get last start_dt recorded for getting new nanopub ID s
As a Python code translator, you convert algorithms and pseudocode into Python.
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': []} """ if not ns_root_url: ns...
How would you code a function in Python 3 to get modified and deleted nanopub urls
As a python code expert, you are capable of creating scripts from specifications.
Get Nanopub from nanopubstore given url
Can you generate the documentation for the following Python 3 function def get_nanopub(url): r = bel.utils.get_url(url, cache=False) if r and r.json(): return r.json() else: return {}
As a Python code translator, you convert algorithms and pseudocode into Python.
This function processes the BEL Nanopubs into BEL Edges and returns the result as a list of BEL Nanopubs.
Can you generate a brief explanation for the following Python 3 code def pipeline( ctx, input_fn, db_save, db_delete, output_fn, rules, species, namespace_targets, version, api, config_fn, ): """BEL Pipeline - BEL Nanopubs into BEL Edges This will process BEL Nanopub...
As a Python code analyst, you investigate and solve complex coding mysteries
Convert BEL script to nanopubs_bel format
Make a summary of the following Python 3 code def convert_belscript(ctx, input_fn, output_fn): try: ( out_fh, yaml_flag, jsonl_flag, json_flag, ) = bel.nanopub.files.create_nanopubs_fh(output_fn) if yaml_flag or json_flag: docs = ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
How would you implement a function in Python 3 that reformats between JSON YAML and JSONLines files.
As a python code expert, you are capable of creating scripts from specifications.
def nanopub_stats(ctx, input_fn): """Collect statistics on nanopub file input_fn can be json, jsonl or yaml and additionally gzipped """ counts = { "nanopubs": 0, "assertions": {"total": 0, "subject_only": 0, "nested": 0, "relations": {}}, } for np in bnf.read_nanopubs(input_f...
Create a Python 3 function to collect statistics on nanopub file input_fn can be json jsonl or yaml and additionally gzipped
As a Python code analyst, you investigate and solve complex coding mysteries
Create BEL Edges from BEL Statement
Explain what the following Python 3 code does def edges(ctx, statement, rules, species, namespace_targets, version, api, config_fn): 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...
You are a Python code generator, capable of creating scripts from specifications.
Validate nanopub against jsonschema for nanopub ArcGIS
Given the following Python 3 function, write the documentation def validate_to_schema(nanopub, schema) -> Tuple[bool, List[Tuple[str, str]]]: v = jsonschema.Draft4Validator(schema) messages = [] errors = sorted(v.iter_errors(nanopub), key=lambda e: e.path) for error in errors: for suberror in s...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Can you create a Python 3 function that creates CityHash64 from nanopub
You are a Python code analyst, evaluating scripts for potential improvements.
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 = ...
Can you create a Python 3 function that validates the nanopub dict using the nanopub schema.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 script to validate a context dictionary of type id and label.
As a python code expert, you are capable of creating scripts from specifications.
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,...
Implement a Python 3 function for creating BEL Edges from BEL nanopub.
You are a Python code generator, capable of creating scripts from specifications.
parse command line options and run commands
Here you have a function in Python 3, explain what it does 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.") ...
You are a Python code architect, reviewing and designing scalable and efficient code
def find_pyd_file(): """ Return path to .pyd after successful build command. :return: Path to .pyd file or None. """ 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.p...
How would you implement a function in Python 3 that finds the. pyd file in the build directory.
You are a Python code analyst, evaluating scripts for potential improvements.
Dereference the FFI result to a list of coordinates
Can you tell what is the following Python 3 function doing def _void_array_to_nested_list(res, _func, _args): 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(...
You are a Python code generator, capable of creating scripts from specifications.
Check if file is a json file.
How would you explain what the following Python 3 function does def is_json_file(abspath): 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(fn...
You are a Python code generator, capable of creating scripts from specifications.
Convert file extension to lowercase.
Can you tell what is the following Python 3 function doing def lower_ext(abspath): fname, ext = os.path.splitext(abspath) return fname + ext.lower()
As a Python code composer, you craft elegant and concise scripts.
Load a json file into a dict.
Can you generate a brief explanation for the following Python 3 code def load(abspath, default=None, enable_verbose=True): 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...
As a python code expert, you are capable of creating scripts from specifications.
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. ...
Write a Python 3 function that can dump a JSON serializable object to a file.
You are a Python code architect, reviewing and designing scalable and efficient code
A stable version of dump that does not overwrite existing file.
Here you have a function in Python 3, explain what it does 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 f...
You are a Python code analyst, evaluating scripts for potential improvements.
Return json string in pretty format.
Can you generate a brief explanation for the following Python 3 code def pretty_dumps(data): 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)
As a Python code translator, you convert algorithms and pseudocode into Python.
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 : ...
Can you create a Python 3 function that computes left and right padding values.
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 script for performing linear padding for complex array
You are a Python code generator, capable of creating scripts from specifications.
1D component of pad_add
How would you explain what the following Python 3 function does def _pad_add_1d(av, size, stlen): 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"): ...
As a python code expert, you are capable of creating scripts from specifications.
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 ...
How would you code a function in Python 3 to remove 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-padde...
You are a Python code generator, capable of creating scripts from specifications.
Send a file to virus total for assessment
Given the following Python 3 function, write the documentation def scan_file(self, filename, apikey): url = self.base_url + "file/scan" params = {'apikey': apikey} scanfile = {"file": open(filename, 'rb')} response = requests.post(url, files=scanfile, params=params) rate_limit_cl...
As a Python code analyst, you investigate and solve complex coding mysteries
retrieve report from file scan
How would you explain what the following Python 3 function does def binary_report(self, sha256sum, apikey): url = self.base_url + "file/report" params = {"apikey": apikey, "resource": sha256sum} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = requests.po...
As a Python code analyst, you investigate and solve complex coding mysteries
def send_ip(self, ipaddr, apikey): """ Send IP address for list of past malicous domain associations """ url = self.base_url + "ip-address/report" parameters = {"ip": ipaddr, "apikey": apikey} rate_limit_clear = self.rate_limit() if rate_limit_clear: r...
Write a Python 3 script to send IP address for list of past malicous domain associations
As a python code expert, you are capable of creating scripts from specifications.
def url_report(self, scan_url, apikey): """ Send URLS for list of past malicous associations """ url = self.base_url + "url/report" params = {"apikey": apikey, 'resource': scan_url} rate_limit_clear = self.rate_limit() if rate_limit_clear: response = r...
Implement a Python 3 function for sending URLS for list of past malicous associations
As a python code expert, you are capable of creating scripts from specifications.
def _read_requirements(filename, extra_packages): """Returns a list of package requirements read from the file.""" requirements_file = open(filename).read() hard_requirements = [] for line in requirements_file.splitlines(): if _is_requirement(line): if line.find(';') > -1: ...
Implement a Python 3 function for reading the requirements file and returns a list of packages that are hard and extra packages.
You are a Python code analyst, evaluating scripts for potential improvements.
def field(ctx, text, index, delimiter=' '): """ Reference a field in string separated by a delimiter """ 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) ...
Write a Python 3 function for returning the value of a field in a string separated by a delimiter
You are a Python code architect, reviewing and designing scalable and efficient code
def epoch(ctx, datetime): """ Converts the given date to the number of seconds since January 1st, 1970 UTC """ return conversions.to_decimal(str(conversions.to_datetime(datetime, ctx).timestamp()), ctx)
Can you write a function in Python 3 where it converts the given date to the number of seconds since January 1st 1970 UTC
You are a Python code generator, capable of creating scripts from specifications.
def read_digits(ctx, text): """ Formats digits in text for reading in TTS """ 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...
Write a Python 3 function that can read digits from text into TTS
You are a Python code analyst, evaluating scripts for potential improvements.
Removes the first word from the given text string
Explain what the following Python 3 code does def remove_first_word(ctx, text): text = conversions.to_string(text, ctx).lstrip() first = first_word(ctx, text) return text[len(first):].lstrip() if first else ''
As a Python code translator, you convert algorithms and pseudocode into Python.
Extracts the nth word from the given text string
How would you explain what the following Python 3 function does def word(ctx, text, number, by_spaces=False): return word_slice(ctx, text, number, conversions.to_integer(number, ctx) + 1, by_spaces)
As a Python code translator, you convert algorithms and pseudocode into Python.
Returns the number of words in the given text
Given the following Python 3 function, write the documentation def word_count(ctx, text, by_spaces=False): text = conversions.to_string(text, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) return len(__get_words(text, by_spaces))
You are a Python code generator, capable of creating scripts from specifications.
Extracts a substring spanning from start to stop.
Can you tell what is the following Python 3 function doing def word_slice(ctx, text, start, stop=0, by_spaces=False): text = conversions.to_string(text, ctx) start = conversions.to_integer(start, ctx) stop = conversions.to_integer(stop, ctx) by_spaces = conversions.to_boolean(by_spaces, ctx) if sta...
You are a Python code analyst, evaluating scripts for potential improvements.
Takes a single parameter as string and returns it in the format defined by the org
Can you generate the documentation for the following Python 3 function def format_date(ctx, text): dt = conversions.to_datetime(text, ctx) return dt.astimezone(ctx.timezone).strftime(ctx.get_date_format(True))
As a Python code translator, you convert algorithms and pseudocode into Python.
Takes a single parameter and returns the name of the leaf boundary
Explain what the following Python 3 code does def format_location(ctx, text): text = conversions.to_string(text, ctx) return text.split(">")[-1].strip()
As a Python code composer, you craft elegant and concise scripts.
Tries to match the text with the given pattern and returns the value of matching group_num
Here you have a function in Python 3, explain what it does def regex_group(ctx, text, pattern, group_num): text = conversions.to_string(text, ctx) pattern = conversions.to_string(pattern, ctx) group_num = conversions.to_integer(group_num, ctx) expression = regex.compile(pattern, regex.UNICODE | regex.I...
As a Python code translator, you convert algorithms and pseudocode into Python.
Round a number to num_digits decimal places.
How would you explain what the following Python 3 function does def decimal_round(number, num_digits, rounding=ROUND_HALF_UP): exp = Decimal(10) ** -num_digits if num_digits >= 0: return number.quantize(exp, rounding) else: return exp * (number / exp).to_integral_value(rounding)
You are a Python code architect, reviewing and designing scalable and efficient code
def parse_json_date(value): """ Parses an ISO8601 formatted datetime from a string value """ if not value: return None return datetime.datetime.strptime(value, JSON_DATETIME_FORMAT).replace(tzinfo=pytz.UTC)
How would you implement a function in Python 3 that parses an ISO8601 formatted datetime from a string value
You are a Python code analyst, evaluating scripts for potential improvements.
def format_json_date(value): """ Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z" """ if not value: return None # %f will include 6 microsecond digits micro_precision = value.astimezone(pytz.UTC).strftime(JSON_DATETIME_FORMAT) # only ...
Write a Python 3 script to format a datetime as ISO8601 in UTC with millisecond precision e. g. 2004 - 10 - 03T09 : 41.790Z
You are a Python code architect, reviewing and designing scalable and efficient code
def clean(ctx, text): """ Removes all non-printable characters from a text string """ text = conversions.to_string(text, ctx) return ''.join([c for c in text if ord(c) >= 32])
How would you implement a function in Python 3 that removes all non - printable characters from a text string
As a Python code translator, you convert algorithms and pseudocode into Python.
def concatenate(ctx, *text): """ Joins text strings into one text string """ result = '' for arg in text: result += conversions.to_string(arg, ctx) return result
Can you write a function in Python 3 where it joins the given text strings into one text string
You are a Python code analyst, evaluating scripts for potential improvements.
Formats the given number in decimal format using a period and commas
Here you have a function in Python 3, explain what it does def fixed(ctx, number, decimals=2, no_commas=False): value = _round(ctx, number, decimals) format_str = '{:f}' if no_commas else '{:,f}' return format_str.format(value)
As a Python code composer, you craft elegant and concise scripts.
Returns the first num_chars characters in a text string
Can you tell what is the following Python 3 function doing def left(ctx, text, num_chars): num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") return conversions.to_string(text, ctx)[0:num_chars]
You are a Python code generator, capable of creating scripts from specifications.
Repeats text a given number of times
Given the following Python 3 function, write the documentation def rept(ctx, text, number_times): if number_times < 0: raise ValueError("Number of times can't be negative") return conversions.to_string(text, ctx) * conversions.to_integer(number_times, ctx)
As a python code expert, you are capable of creating scripts from specifications.
Returns the last num_chars characters in a text string
How would you explain what the following Python 3 function does def right(ctx, text, num_chars): num_chars = conversions.to_integer(num_chars, ctx) if num_chars < 0: raise ValueError("Number of chars can't be negative") elif num_chars == 0: return '' else: return conversions.to_s...
As a Python code translator, you convert algorithms and pseudocode into Python.
Substitutes new_text for old_text in a text string
Explain what the following Python 3 code does def substitute(ctx, text, old_text, new_text, instance_num=-1): text = conversions.to_string(text, ctx) old_text = conversions.to_string(old_text, ctx) new_text = conversions.to_string(new_text, ctx) if instance_num < 0: return text.replace(old_text...
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a numeric code for the first character in a text string
Can you generate the documentation for the following Python 3 function def _unicode(ctx, text): text = conversions.to_string(text, ctx) if len(text) == 0: raise ValueError("Text can't be empty") return ord(text[0])
You are a Python code analyst, evaluating scripts for potential improvements.
def date(ctx, year, month, day): """ Defines a date value """ return _date(conversions.to_integer(year, ctx), conversions.to_integer(month, ctx), conversions.to_integer(day, ctx))
Can you create a Python 3 function that returns a date value
You are a Python code architect, reviewing and designing scalable and efficient code
def datedif(ctx, start_date, end_date, unit): """ Calculates the number of days, months, or years between two dates. """ start_date = conversions.to_date(start_date, ctx) end_date = conversions.to_date(end_date, ctx) unit = conversions.to_string(unit, ctx).lower() if start_date > end_date: ...
How would you code a function in Python 3 to calculate the number of days months or years between two dates.
As a Python code analyst, you investigate and solve complex coding mysteries
def edate(ctx, date, months): """ Moves a date by the given number of months """ return conversions.to_date_or_datetime(date, ctx) + relativedelta(months=conversions.to_integer(months, ctx))
Write a Python 3 function that can move a date by the given number of months
As a Python code analyst, you investigate and solve complex coding mysteries
def time(ctx, hours, minutes, seconds): """ Defines a time value """ return _time(conversions.to_integer(hours, ctx), conversions.to_integer(minutes, ctx), conversions.to_integer(seconds, ctx))
Write a Python 3 function for returning a time value
As a Python code composer, you craft elegant and concise scripts.
def _abs(ctx, number): """ Returns the absolute value of a number """ return conversions.to_decimal(abs(conversions.to_decimal(number, ctx)), ctx)
Write a Python 3 function that can return the absolute value of a number
As a python code expert, you are capable of creating scripts from specifications.
def _int(ctx, number): """ Rounds a number down to the nearest integer """ return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_FLOOR), ctx)
Can you create a Python 3 function that rounds a number down to the nearest integer
As a python code expert, you are capable of creating scripts from specifications.
def _max(ctx, *number): """ Returns the maximum value of all arguments """ if len(number) == 0: raise ValueError("Wrong number of arguments") result = conversions.to_decimal(number[0], ctx) for arg in number[1:]: arg = conversions.to_decimal(arg, ctx) if arg > result: ...
Write a Python 3 script for returning the maximum value of all arguments
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the remainder after number is divided by divisor
Explain what the following Python 3 code does def mod(ctx, number, divisor): number = conversions.to_decimal(number, ctx) divisor = conversions.to_decimal(divisor, ctx) return number - divisor * _int(ctx, number / divisor)
You are a Python code architect, reviewing and designing scalable and efficient code
def _power(ctx, number, power): """ Returns the result of a number raised to a power """ return decimal_pow(conversions.to_decimal(number, ctx), conversions.to_decimal(power, ctx))
Write a Python 3 function for returning the result of a number raised to a power
As a Python code composer, you craft elegant and concise scripts.
def randbetween(ctx, bottom, top): """ Returns a random integer number between the numbers you specify """ bottom = conversions.to_integer(bottom, ctx) top = conversions.to_integer(top, ctx) return random.randint(bottom, top)
Write a Python 3 script to return a random integer number between the numbers you specify
You are a Python code architect, reviewing and designing scalable and efficient code
Rounds a number to a specified number of digits
Make a summary of the following Python 3 code def _round(ctx, number, num_digits): number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_HALF_UP)
As a Python code composer, you craft elegant and concise scripts.
Rounds a number down toward zero
Given the following Python 3 function, write the documentation def rounddown(ctx, number, num_digits): number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_DOWN)
As a python code expert, you are capable of creating scripts from specifications.
def roundup(ctx, number, num_digits): """ Rounds a number up, away from zero """ number = conversions.to_decimal(number, ctx) num_digits = conversions.to_integer(num_digits, ctx) return decimal_round(number, num_digits, ROUND_UP)
Can you implement a function in Python 3 that rounds a number up away from zero
You are a Python code architect, reviewing and designing scalable and efficient code
Returns the sum of all arguments
Make a summary of the following Python 3 code def _sum(ctx, *number): if len(number) == 0: raise ValueError("Wrong number of arguments") result = Decimal(0) for arg in number: result += conversions.to_decimal(arg, ctx) return result
As a python code expert, you are capable of creating scripts from specifications.
def trunc(ctx, number): """ Truncates a number to an integer by removing the fractional part of the number """ return conversions.to_integer(conversions.to_decimal(number, ctx).to_integral_value(ROUND_DOWN), ctx)
Can you implement a function in Python 3 that truncates a number to an integer by removing the fractional part of the number
You are a Python code generator, capable of creating scripts from specifications.
def _and(ctx, *logical): """ Returns TRUE if and only if all its arguments evaluate to TRUE """ for arg in logical: if not conversions.to_boolean(arg, ctx): return False return True
Write a Python 3 function for returning TRUE if all its arguments evaluate to TRUE
You are a Python code architect, reviewing and designing scalable and efficient code
Returns one value if the condition evaluates to TRUE and another value if the condition evaluates to FALSE.
Given the following Python 3 function, write the documentation def _if(ctx, logical_test, value_if_true=0, value_if_false=False): return value_if_true if conversions.to_boolean(logical_test, ctx) else value_if_false
As a Python code composer, you craft elegant and concise scripts.
def _or(ctx, *logical): """ Returns TRUE if any argument is TRUE """ for arg in logical: if conversions.to_boolean(arg, ctx): return True return False
Can you implement a function in Python 3 that returns TRUE if any argument is TRUE
You are a Python code architect, reviewing and designing scalable and efficient code
Compute the sum1_ij and sum2_ij values given the input indices and data instances.
Can you generate the documentation for the following Python 3 function def compute_sum_values(i, j, data1, data2): sum1_ij = 1. for idx, d in zip([i,j], [data1, data2]): if isinstance(d, field): sum1_ij *= d.wvalue[idx] elif isinstance(d, points): sum1_ij *= d.weights[idx] else: ...
As a python code expert, you are capable of creating scripts from specifications.
def _setup(self): """ Set the binning info we need from the `edges` """ dtype = [('inv', 'f8'), ('min', 'f8'), ('max', 'f8'),('N', 'i4'), ('spacing','object')] dtype = numpy.dtype(dtype) self._info = numpy.empty(self.Ndim, dtype=dtype) self.min = self...
Can you implement a function in Python 3 that sets up the internal object variables for the internal object.
As a Python code translator, you convert algorithms and pseudocode into Python.
This method is used to update the sum1 and sum2 values for the current record.
How would you explain what the following Python 3 function does def update_sums(self, r, i, j, data1, data2, sum1, sum2, N=None, centers_sum=None): # the summation values for this (r,i,j) sum1_ij, sum2_ij = compute_sum_values(i, j, data1, data2) # digitize digr = self.digitize(r, i, j, ...
You are a Python code generator, capable of creating scripts from specifications.
def sum_shapes(self, data1, data2): """ Return the shapes of the summation arrays, given the input data and shape of the bins """ # the linear shape (put extra dimensions first) linearshape = [-1] + list(self.shape) # determine the full shape subshapes = ...
Write a Python 3 function for returning the shapes of the summation arrays linearshape fullshape
As a Python code translator, you convert algorithms and pseudocode into Python.
Update the mean coordinate sums
Can you tell what is the following Python 3 function doing def _update_mean_coords(self, dig, N, centers_sum, **paircoords): if N is None or centers_sum is None: return N.flat[:] += utils.bincount(dig, 1., minlength=N.size) for i, dim in enumerate(self.dims): size = centers_sum[i].s...
As a Python code analyst, you investigate and solve complex coding mysteries
Internal function that performs the pair - counting
How would you explain what the following Python 3 function does def work(self, i): n1, n2 = self.p[i] # initialize the total arrays for this process sum1 = numpy.zeros_like(self.sum1g) sum2 = 1. if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g) if self.compute_m...
You are a Python code architect, reviewing and designing scalable and efficient code
This function sums the results from various processors and updates the internal statistics of the internal statistics.
Can you generate a brief explanation for the following Python 3 code def reduce(self, sum1, sum2, *args): self.sum1g[...] += sum1 if not self.pts_only: self.sum2g[...] += sum2 if self.compute_mean_coords: N, centers_sum = args self.N[...] += N for i in range(...
As a Python code translator, you convert algorithms and pseudocode into Python.
Estimate the parameter values for the Generalized Pareto Distribution.
How would you explain what the following Python 3 function does def gpdfitnew(x, sort=True, sort_in_place=False, return_quadrature=False): if x.ndim != 1 or len(x) <= 1: raise ValueError("Invalid input array.") # check if x should be sorted if sort is True: if sort_in_place: x.s...
You are a Python code architect, reviewing and designing scalable and efficient code
def gpinv(p, k, sigma): """Inverse Generalised Pareto distribution function.""" x = np.empty(p.shape) x.fill(np.nan) if sigma <= 0: return x ok = (p > 0) & (p < 1) if np.all(ok): if np.abs(k) < np.finfo(float).eps: np.negative(p, out=x) np.log1p(x, out=x) ...
Implement a function in Python 3 to inverse Generalised Pareto distribution function.
As a python code expert, you are capable of creating scripts from specifications.
Sum of vector where numbers are represented by their logarithms.
Can you generate a brief explanation for the following Python 3 code def sumlogs(x, axis=None, out=None): maxx = x.max(axis=axis, keepdims=True) xnorm = x - maxx np.exp(xnorm, out=xnorm) out = np.sum(xnorm, axis=axis, out=out) if isinstance(out, np.ndarray): np.log(out, out=out) else: ...
You are a Python code architect, reviewing and designing scalable and efficient code
def add_library(self, library): """ Adds functions from a library module :param library: the library module :return: """ for fn in library.__dict__.copy().values(): # ignore imported methods and anything beginning __ if inspect.isfunction(fn) and i...
Write a Python 3 function for adding functions from a library module to the internal dictionary.
You are a Python code analyst, evaluating scripts for potential improvements.
Invoke the function with the given name and arguments.
Can you tell what is the following Python 3 function doing def invoke_function(self, ctx, name, arguments): from temba_expressions import EvaluationError, conversions # find function with given name func = self.get_function(name) if func is None: raise EvaluationError("Undef...
As a python code expert, you are capable of creating scripts from specifications.
def build_listing(self): """ Builds a listing of all functions sorted A-Z, with their names and descriptions """ def func_entry(name, func): args, varargs, defaults = self._get_arg_spec(func) # add regular arguments params = [{'name': str(a), 'optiona...
Create a Python 3 function for building a listing of all functions sorted A - Z with their names and descriptions.
You are a Python code architect, reviewing and designing scalable and efficient code
Gets the argument spec of the given function returning defaults as a dict of param names to values
Here you have a function in Python 3, explain what it does def _get_arg_spec(func): args, varargs, keywords, defaults = inspect.getargspec(func) # build a mapping from argument names to their default values, if any: if defaults is None: defaults = {} else: defaul...
As a Python code translator, you convert algorithms and pseudocode into Python.
Run ocrmypdf and confirmed that a valid file was created
Can you generate a brief explanation for the following Python 3 code def check_ocrmypdf(input_file, output_file, *args, env=None): "Run ocrmypdf and confirmed that a valid file was created" p, out, err = run_ocrmypdf(input_file, output_file, *args, env=env) if p.returncode != 0: print('stdout\n====...
As a Python code analyst, you investigate and solve complex coding mysteries