output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
Compare the original pub dictionary with the fetched pub dictionary.
Can you generate the documentation for the following Python 3 function def compare_replace(pub_dict, fetch_dict): blank = [" ", "", None] for k, v in fetch_dict.items(): try: if fetch_dict[k] != blank: pub_dict[k] = fetch_dict[k] except KeyErro...
As a Python code analyst, you investigate and solve complex coding mysteries
Special instructions for moving NOAA data to the correct fields
Can you generate a brief explanation for the following Python 3 code def noaa_citation(self, doi_string): # Append location 1 if 'link' in self.root_dict['pub'][0]: self.root_dict['pub'][0]['link'].append({"url": doi_string}) else: self.root_dict['pub'][0]['link'] = [{"ur...
As a Python code translator, you convert algorithms and pseudocode into Python.
This method is called when a DOI string is not valid.
Here you have a function in Python 3, explain what it does def illegal_doi(self, doi_string): logger_doi_resolver.info("enter illegal_doi") # Ignores empty or irrelevant strings (blank, spaces, na, nan, ', others) if len(doi_string) > 5: # NOAA string if 'noaa' in doi_st...
As a python code expert, you are capable of creating scripts from specifications.
Loop over Raw and add selected items to Fetch with proper formatting
Given the following Python 3 function, write the documentation def compile_fetch(self, raw, doi_id): fetch_dict = OrderedDict() order = {'author': 'author', 'type': 'type', 'identifier': '', 'title': 'title', 'journal': 'container-title', 'pubYear': '', 'volume': 'volume', 'publisher': '...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_data(self, doi_id, idx): """ Resolve DOI and compile all attributes into one dictionary :param str doi_id: :param int idx: Publication index :return dict: Updated publication dictionary """ tmp_dict = self.root_dict['pub'][0].copy() try: ...
Write a Python 3 script to resolve DOI and compile all attributes into one dictionary
You are a Python code generator, capable of creating scripts from specifications.
def cast_values_csvs(d, idx, x): """ Attempt to cast string to float. If error, keep as a string. :param dict d: Data :param int idx: Index number :param str x: Data :return any: """ try: d[idx].append(float(x)) except ValueError: d[idx].append(x) # logger_mi...
Can you create a Python 3 function that attempts to cast string to float.
You are a Python code analyst, evaluating scripts for potential improvements.
Attempt to cleanup string or convert to number value.
Can you tell what is the following Python 3 function doing def cast_float(x): try: x = float(x) except ValueError: try: x = x.strip() except AttributeError as e: logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}".format(x, e)) retu...
As a Python code analyst, you investigate and solve complex coding mysteries
def cast_int(x): """ Cast unknown type into integer :param any x: :return int: """ try: x = int(x) except ValueError: try: x = x.strip() except AttributeError as e: logger_misc.warn("parse_str: AttributeError: String not number or word, {}, {}...
Write a Python 3 function that can cast unknown type into integer AttributeNames
As a Python code composer, you craft elegant and concise scripts.
This function takes a string containing a DOI string and returns a list of all the DOI ids.
Here you have a function in Python 3, explain what it does def clean_doi(doi_string): regex = re.compile(r'\b(10[.][0-9]{3,}(?:[.][0-9]+)*/(?:(?!["&\'<>,])\S)+)\b') try: # Returns a list of matching strings m = re.findall(regex, doi_string) except TypeError as e: # If doi_string is N...
You are a Python code generator, capable of creating scripts from specifications.
Change the precision of values before writing to CSV.
Make a summary of the following Python 3 code def decimal_precision(row): # _row = [] try: # Convert tuple to list for processing row = list(row) for idx, x in enumerate(row): x = str(x) # Is this a scientific notated float? Tear it apart with regex, round, and pi...
You are a Python code generator, capable of creating scripts from specifications.
def fix_coordinate_decimal(d): """ Coordinate decimal degrees calculated by an excel formula are often too long as a repeating decimal. Round them down to 5 decimals :param dict d: Metadata :return dict d: Metadata """ try: for idx, n in enumerate(d["geo"]["geometry"]["coordinates"]...
Create a Python 3 function to fix the coordinate decimal degrees calculated by an excel formula.
As a Python code composer, you craft elegant and concise scripts.
Generate a timestamp to mark when this file was last modified.
Explain what the following Python 3 code does def generate_timestamp(fmt=None): if fmt: time = dt.datetime.now().strftime(fmt) else: time = dt.date.today() return str(time)
As a Python code analyst, you investigate and solve complex coding mysteries
Generate a TSid string. Use the PYT prefix for traceability and 8 trailing generated characters.
Explain what the following Python 3 code does def generate_tsid(size=8): chars = string.ascii_uppercase + string.digits _gen = "".join(random.choice(chars) for _ in range(size)) return "PYT" + str(_gen)
As a python code expert, you are capable of creating scripts from specifications.
Returns the name of the variable with the number appended to the given column.
Here you have a function in Python 3, explain what it does def get_appended_name(name, columns): loop = 0 while name in columns: loop += 1 if loop > 10: logger_misc.warn("get_appended_name: Too many loops: Tried to get appended name but something looks wrong") break ...
As a Python code analyst, you investigate and solve complex coding mysteries
Take author or investigator data and convert it to a concatenated string of names.
Explain what the following Python 3 code does def get_authors_as_str(x): _authors = "" # if it's a string already, we're done if isinstance(x, str): return x # elif it's a list, keep going elif isinstance(x, list): # item in list is a str if isinstance(x[0], str): ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the dataset name from a record
Make a summary of the following Python 3 code def get_dsn(d): try: return d["dataSetName"] except Exception as e: logger_misc.warn("get_dsn: Exception: No datasetname found, unable to continue: {}".format(e)) exit(1)
As a Python code analyst, you investigate and solve complex coding mysteries
def get_ensemble_counts(d): """ Determine if this is a 1 or 2 column ensemble. Then determine how many columns and rows it has. :param dict d: Metadata (table) :return dict _rows_cols: Row and column counts """ _rows_cols = {"rows": 0, "cols": 0} try: if len(d) == 1: fo...
Write a Python 3 function that can determine if this is a 1 or 2 column ensemble. Then determine how many columns and rows it has.
As a Python code translator, you convert algorithms and pseudocode into Python.
Get the Missing Value entry from a table of data.
Make a summary of the following Python 3 code def get_missing_value_key(d): _mv = "nan" # Attempt to find a table-level missing value key try: # check for missing value key at the table root _mv = d["missingValue"] except KeyError as e: logger_misc.info("get_missing_value: No mi...
As a Python code analyst, you investigate and solve complex coding mysteries
Get the variable name from a table or column.
Here you have a function in Python 3, explain what it does def get_variable_name_col(d): var = "" try: var = d["variableName"] except KeyError: try: var = d["name"] except KeyError: num = "unknown" if "number" in d: num = d["number"...
As a Python code analyst, you investigate and solve complex coding mysteries
def get_table_key(key, d, fallback=""): """ Try to get a table name from a data table :param str key: Key to try first :param dict d: Data table :param str fallback: (optional) If we don't find a table name, use this as a generic name fallback. :return str var: Data table name """ try: ...
Write a Python 3 script for trying to get a table name from a data table
You are a Python code architect, reviewing and designing scalable and efficient code
def is_ensemble(d): """ Check if a table of data is an ensemble table. Is the first values index a list? ensemble. Int/float? not ensemble. :param dict d: Table data :return bool: Ensemble or not ensemble """ for var, data in d.items(): try: if isinstance(data["number"], lis...
How would you code a function in Python 3 to check if a table of data is an ensemble table.
As a Python code composer, you craft elegant and concise scripts.
def load_fn_matches_ext(file_path, file_type): """ Check that the file extension matches the target extension given. :param str file_path: Path to be checked :param str file_type: Target extension :return bool correct_ext: Extension match or does not match """ correct_ext = False curr_e...
Write a Python 3 function that can check that the file extension matches the target extension given.
As a python code expert, you are capable of creating scripts from specifications.
Compare two items. Compare a string operator to an operator function
Explain what the following Python 3 code does def match_operators(inp, relate, cut): logger_misc.info("enter match_operators") ops = {'>': operator.gt, '<': operator.lt, '>=': operator.ge, '<=': operator.le, '=': operator.eq } try: truth = ops[r...
You are a Python code architect, reviewing and designing scalable and efficient code
def match_arr_lengths(l): """ Check that all the array lengths match so that a DataFrame can be created successfully. :param list l: Nested arrays :return bool: Valid or invalid """ try: # length of first list. use as basis to check other list lengths against. inner_len = len(l[...
Can you create a Python 3 function that checks that all the array lengths match.
As a Python code composer, you craft elegant and concise scripts.
def mv_files(src, dst): """ Move all files from one directory to another :param str src: Source directory :param str dst: Destination directory :return none: """ # list the files in the src directory files = os.listdir(src) # loop for each file found for file in files: #...
Can you implement a function in Python 3 that moves all files from one directory to another directory
You are a Python code analyst, evaluating scripts for potential improvements.
def normalize_name(s): """ Remove foreign accents and characters to normalize the string. Prevents encoding errors. :param str s: String :return str s: String """ # Normalize the string into a byte string form s = unicodedata.normalize('NFKD', s).encode('ascii', 'ignore') # Remove the b...
Implement a function in Python 3 to normalize a string into a byte string form.
You are a Python code generator, capable of creating scripts from specifications.
Determines if given path is file directory or other. Compare with target to see if it s the type we wanted.
Can you tell what is the following Python 3 function doing def path_type(path, target): if os.path.isfile(path) and target == "file": return True elif os.path.isdir(path) and target == "directory": return True else: print("Error: Path given is not a {}: {}".format(target, path)) ...
As a Python code analyst, you investigate and solve complex coding mysteries
Print out lipd filename that is being read or written.
Given the following Python 3 function, write the documentation def print_filename(path): if os.path.basename(path): return os.path.basename(path) return path
You are a Python code analyst, evaluating scripts for potential improvements.
Prompt user if they would like to save pickle file as a dictionary or an object.
Explain what the following Python 3 code does def prompt_protocol(): stop = 3 ans = "" while True and stop > 0: ans = input("Save as (d)ictionary or (o)bject?\n" "* Note:\n" "Dictionaries are more basic, and are compatible with Python v2.7+.\n" ...
You are a Python code architect, reviewing and designing scalable and efficient code
Recursive function to remove all empty fields in the Unknown .
Here you have a function in Python 3, explain what it does def rm_empty_fields(x): # No logger here because the function is recursive. # Int types don't matter. Return as-is. if not isinstance(x, int) and not isinstance(x, float): if isinstance(x, str) or x is None: try: ...
As a Python code composer, you craft elegant and concise scripts.
Remove empty DOI from metadata.
Here you have a function in Python 3, explain what it does def rm_empty_doi(d): logger_misc.info("enter remove_empty_doi") try: # Check each publication dictionary for pub in d['pub']: # If no identifier, then we can quit here. If identifier, then keep going. if 'identifi...
You are a Python code architect, reviewing and designing scalable and efficient code
def rm_files(path, extension): """ Remove all files in the given directory with the given extension :param str path: Directory :param str extension: File type to remove :return none: """ files = list_files(extension, path) for file in files: if file.endswith(extension): ...
Implement a Python 3 function for removing all files in the given directory with the given extension
As a python code expert, you are capable of creating scripts from specifications.
def rm_missing_values_table(d): """ Loop for each table column and remove the missingValue key & data :param dict d: Metadata (table) :return dict d: Metadata (table) """ try: for k, v in d["columns"].items(): d["columns"][k] = rm_keys_from_dict(v, ["missingValue"]) exce...
Create a Python 3 function to remove the missingValue key from each column of the metadata
As a Python code analyst, you investigate and solve complex coding mysteries
def rm_keys_from_dict(d, keys): """ Given a dictionary and a key list, remove any data in the dictionary with the given keys. :param dict d: Metadata :param list keys: Keys to be removed :return dict d: Metadata """ # Loop for each key given for key in keys: # Is the key in the ...
Write a Python 3 script for giving a dictionary and a list of keys remove any data in the dictionary with the given keys.
As a Python code composer, you craft elegant and concise scripts.
Replace missing values in the given table column values with values that are not in use by the current user.
Make a summary of the following Python 3 code def _replace_missing_values_table(values, mv): for idx, column in enumerate(values): values[idx] = _replace_missing_values_column(column, mv) return values
You are a Python code analyst, evaluating scripts for potential improvements.
Replace missing values in the values list where applicable
Given the following Python 3 function, write the documentation def _replace_missing_values_column(values, mv): for idx, v in enumerate(values): try: if v in EMPTY or v == mv: values[idx] = "nan" elif math.isnan(float(v)): values[idx] = "nan" ...
As a python code expert, you are capable of creating scripts from specifications.
Given a full path to a file split and return a path and filename
Make a summary of the following Python 3 code def split_path_and_file(s): _path = s _filename = "" try: x = os.path.split(s) _path = x[0] _filename = x[1] except Exception: print("Error: unable to split path") return _path, _filename
As a Python code translator, you convert algorithms and pseudocode into Python.
def unwrap_arrays(l): """ Unwrap nested lists to be one "flat" list of lists. Mainly for prepping ensemble data for DataFrame() creation :param list l: Nested lists :return list l2: Flattened lists """ # keep processing until all nesting is removed process = True # fail safe: cap the lo...
Can you implement a function in Python 3 that unwraps nested lists to be one flat list of lists.
As a python code expert, you are capable of creating scripts from specifications.
This function extracts the LiPD data from one LiPD file and returns a list of TSOs objects.
Can you generate the documentation for the following Python 3 function def extract(d, whichtables, mode, time): logger_ts.info("enter extract_main") _root = {} _ts = {} # _switch = {"paleoData": "chronData", "chronData": "paleoData"} _pc = "paleoData" if mode == "chron": _pc = "chronData...
As a Python code analyst, you investigate and solve complex coding mysteries
Extracts the Funding entries from a list of Funding entries into a flat dictionary.
Can you generate the documentation for the following Python 3 function def _extract_fund(l, _root): logger_ts.info("enter _extract_funding") for idx, i in enumerate(l): for k, v in i.items(): _root['funding' + str(idx + 1) + '_' + k] = v return _root
As a Python code translator, you convert algorithms and pseudocode into Python.
def _extract_geo(d, _root): """ Extract geo data from input :param dict d: Geo :return dict _root: Root data """ logger_ts.info("enter ts_extract_geo") # May not need these if the key names are corrected in the future. # COORDINATE ORDER: [LON, LAT, ELEV] x = ['geo_meanLon', 'geo_mea...
Can you implement a function in Python 3 that extracts geo data from input geo dictionary d
As a Python code analyst, you investigate and solve complex coding mysteries
def _extract_pub(l, _root): """ Extract publication data from one or more publication entries. :param list l: Publication :return dict _root: Root data """ logger_ts.info("enter _extract_pub") # For each publication entry for idx, pub in enumerate(l): logger_ts.info("processing p...
Write a Python 3 function for extracting publication data from one or more publication entries.
You are a Python code architect, reviewing and designing scalable and efficient code
def _extract_authors(pub, idx, _root): """ Create a concatenated string of author names. Separate names with semi-colons. :param any pub: Publication author structure is ambiguous :param int idx: Index number of Pub """ logger_ts.info("enter extract_authors") try: # DOI Author data. ...
Create a Python 3 function to extract the authors from a publication author structure.
You are a Python code architect, reviewing and designing scalable and efficient code
Extract all data from a PaleoData dictionary.
Can you generate the documentation for the following Python 3 function def _extract_pc(d, root, pc, whichtables): logger_ts.info("enter extract_pc") _ts = [] try: # For each table in pc for k, v in d[pc].items(): if whichtables == "all" or whichtables == "meas": f...
As a Python code analyst, you investigate and solve complex coding mysteries
def _extract_method(method): """ Make a timeseries-formatted version of model method data :param dict method: Method data :return dict _method: Method data, formatted """ _method = {} for k,v in method.items(): _method["method_" + k] = v return _method
Implement a function in Python 3 to extract a timeseries - formatted version of model method data
You are a Python code generator, capable of creating scripts from specifications.
def _extract_special(current, table_data): """ Extract year, age, and depth column from table data :param dict table_data: Data at the table level :param dict current: Current data :return dict current: """ logger_ts.info("enter extract_special") try: # Add age, year, and depth c...
Can you create a Python 3 function that extracts year age and depth column from table data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _extract_table_root(d, current, pc): """ Extract data from the root level of a paleoData table. :param dict d: paleoData table :param dict current: Current root data :param str pc: paleoData or chronData :return dict current: Current root data """ logger_ts.info("enter extract_table_...
Create a Python 3 function for extracting data from the root level of a paleoData table.
As a Python code analyst, you investigate and solve complex coding mysteries
def _extract_table_model(table_data, current, tt): """ Add in modelNumber and summaryNumber fields if this is a summary table :param dict table_data: Table data :param dict current: LiPD root data :param str tt: Table type "summ", "ens", "meas" :return dict current: Current root data """ ...
Can you create a Python 3 function that extracts the modelNumber and summaryNumber fields from the table data.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _extract_table(table_data, current, pc, ts, tt): """ Use the given table data to create a time series entry for each column in the table. :param dict table_data: Table data :param dict current: LiPD root data :param str pc: paleoData or chronData :param list ts: Time series (so far) :pa...
Can you create a Python 3 function that creates a time series entry for each column in the table.
You are a Python code generator, capable of creating scripts from specifications.
Extract data from one paleoData column
Here you have a function in Python 3, explain what it does def _extract_columns(d, tmp_tso, pc): logger_ts.info("enter extract_columns") for k, v in d.items(): if isinstance(v, dict): flat_data = _extract_nested(pc + "_" + k, v, {}) for n,m in flat_data.items(): t...
As a Python code composer, you craft elegant and concise scripts.
Get the table name and variable name from the given time series entry
Given the following Python 3 function, write the documentation def _get_current_names(current, dsn, pc): _table_name = "" _variable_name = "" # Get key info try: _table_name = current['{}_tableName'.format(pc)] _variable_name = current['{}_variableName'.format(pc)] except Exception a...
You are a Python code generator, capable of creating scripts from specifications.
Collapses the root items of the current time series entry into a single item.
Explain what the following Python 3 code does def _collapse_root(master, current, dsn, pc): logger_ts.info("enter collapse_root") _tmp_fund = {} _tmp_pub = {} # The tmp lipd data that we'll place in master later _tmp_master = {'pub': [], 'geo': {'geometry': {'coordinates': []}, 'properties': {}}, 'f...
You are a Python code generator, capable of creating scripts from specifications.
def _collapse_author(s): """ Split author string back into organized dictionary :param str s: Formatted names string "Last, F.; Last, F.; etc.." :return list of dict: One dictionary per author name """ logger_ts.info("enter collapse_author") l = [] authors = s.split(';') for author i...
Write a Python 3 script to split author string back into organized dictionary
As a Python code composer, you craft elegant and concise scripts.
Collapse the paleo or chron for the current time series entry and return the LiPD data.
How would you explain what the following Python 3 function does def _collapse_pc(master, current, dsn, pc): logger_ts.info("enter collapse_paleo") _table_name, _variable_name = _get_current_names(current, dsn, pc) try: # Get the names we need to build the hierarchy _m = re.match(re_sheet_w_...
As a Python code analyst, you investigate and solve complex coding mysteries
Create a new table with items in root given the current time series entry and the dataset name.
Can you tell what is the following Python 3 function doing def _collapse_table_root(current, dsn, pc): logger_ts.info("enter collapse_table_root") _table_name, _variable_name = _get_current_names(current, dsn, pc) _tmp_table = {'columns': {}} try: for k, v in current.items(): # Thes...
You are a Python code architect, reviewing and designing scalable and efficient code
def _collapse_column(current, pc): """ Collapse the column data and :param current: :param pc: :return: """ _tmp_column = {} try: for k, v in current.items(): try: # We do not want to store these table keys at the column level. if not a...
Write a Python 3 function that can collapse the column data and return the new data structure
You are a Python code analyst, evaluating scripts for potential improvements.
Returns the string for the mode of the current node.
How would you explain what the following Python 3 function does def mode_ts(ec, mode="", ts=None): phrase = "" if ec == "extract": if mode=="chron": phrase = "extracting chronData..." else: phrase = "extracting paleoData..." elif ec == "collapse": if ts[0]["mo...
As a python code expert, you are capable of creating scripts from specifications.
Translate an expression into a list of lists.
Can you tell what is the following Python 3 function doing def translate_expression(expression): logger_ts.info("enter translate_expression") m = re_filter_expr.findall(expression) matches = [] if m: for i in m: logger_ts.info("parse match: {}".format(i)) tmp = list(i[1:]...
As a Python code composer, you craft elegant and concise scripts.
def get_matches(expr_lst, ts): """ Get a list of TimeSeries objects that match the given expression. :param list expr_lst: Expression :param list ts: TimeSeries :return list new_ts: Matched time series objects :return list idxs: Indices of matched objects """ logger_ts.info("enter get_ma...
Write a Python 3 function that can get a list of time series objects that match the given expression.
As a python code expert, you are capable of creating scripts from specifications.
def _to_http_hosts(hosts: Union[Iterable[str], str]) -> List[str]: """Convert a string of whitespace or comma separated hosts into a list of hosts. Hosts may also already be a list or other iterable. Each host will be prefixed with 'http://' if it is not already there. >>> _to_http_hosts('n1:4200,n2:4...
Can you implement a function in Python 3 that converts a string of whitespace or comma separated hosts into a list of hosts.
You are a Python code generator, capable of creating scripts from specifications.
def _plain_or_callable(obj): """Returns the value of the called object of obj is a callable, otherwise the plain object. Returns None if obj is None. >>> obj = None >>> _plain_or_callable(obj) >>> stmt = 'select * from sys.nodes' >>> _plain_or_callable(stmt) 'select * from sys.nodes' ...
Can you write a function in Python 3 where it returns the value of the called object of obj is a callable otherwise the plain object.
As a python code expert, you are capable of creating scripts from specifications.
def _to_dsn(hosts): """Convert a host URI into a dsn for aiopg. >>> _to_dsn('aiopg://myhostname:4242/mydb') 'postgres://crate@myhostname:4242/mydb' >>> _to_dsn('aiopg://myhostname:4242') 'postgres://crate@myhostname:4242/doc' >>> _to_dsn('aiopg://hoschi:pw@myhostname:4242/doc?sslmode=require'...
Write a Python 3 script to convert a host URI into a DSN for aiopg.
As a Python code translator, you convert algorithms and pseudocode into Python.
def _verify_ssl_from_first(hosts): """Check if SSL validation parameter is passed in URI >>> _verify_ssl_from_first(['https://myhost:4200/?verify_ssl=false']) False >>> _verify_ssl_from_first(['https://myhost:4200/']) True >>> _verify_ssl_from_first([ ... 'https://h1:4200/?verify_ssl...
Implement a Python 3 function for checking if SSL validation parameter is passed in URI
As a python code expert, you are capable of creating scripts from specifications.
Add any table type to the given dataset.
Given the following Python 3 function, write the documentation def addTable(D): _swap = { "1": "measurement", "2": "summary", "3": "ensemble", "4": "distribution" } print("What type of table would you like to add?\n" "1: measurement\n" "2: summary\n" ...
You are a Python code generator, capable of creating scripts from specifications.
Get a list of possible placements that can be put into the new model.
Given the following Python 3 function, write the documentation def _get_available_placements(D, tt): _options = [] try: for _pc in ["paleoData", "chronData"]: if _pc in D: # for each entry in pc for section_name, section_data in D[_pc].items(): ...
As a Python code analyst, you investigate and solve complex coding mysteries
def _prompt_placement(D, tt): """ Since automatic placement didn't work, find somewhere to place the model data manually with the help of the user. :param dict D: Metadata :param str tt: Table type :return str _model_name: Chosen model name for placement """ _model_name = "" # There was...
Create a Python 3 function to prompt user to choose model name based on the available placement options.
You are a Python code analyst, evaluating scripts for potential improvements.
def _put_table(D, name, table): """ Use the dataset and name to place the new table data into the dataset. :param dict D: Dataset :param str name: Table name / path to store new table :param dict table: Newly created table data :return dict D: Dataset """ try: # print("Placing ...
Can you write a function in Python 3 where it adds a new table into the dataset.
As a python code expert, you are capable of creating scripts from specifications.
Update the names of the tables in the metadata dictionary.
Can you generate a brief explanation for the following Python 3 code def _update_table_names(name, dat): for _tabletype in ["summary", "distribution", "ensemble"]: _ttname = "{}Table".format(_tabletype) if _ttname in dat: _new_tables = OrderedDict() _idx = 0 # cha...
As a Python code analyst, you investigate and solve complex coding mysteries
Insert model data into a LiPD dataset
Can you generate a brief explanation for the following Python 3 code def addModel(D, models): try: # Loop for each model that needs to be added for _model_name, _model_data in models.items(): # split the table name into a path that we can use _m = re.match(re_model_name, _mo...
As a Python code analyst, you investigate and solve complex coding mysteries
def _put_model(D, name, dat, m): """ Place the model data given, into the location (m) given. :param dict D: Metadata (dataset) :param str name: Model name (ex: chron0model0) :param dict dat: Model data :param regex m: Model name regex groups :return dict D: Metadata (dataset) """ t...
Create a Python 3 function for putting the model data given into the location given.
You are a Python code analyst, evaluating scripts for potential improvements.
Prepares the Sphinx environment to store the internal data for the given docname.
How would you explain what the following Python 3 function does def prepare_env(app, env, docname): if not hasattr(env, 'needs_all_needs'): # Used to store all needed information about all needs in document env.needs_all_needs = {} if not hasattr(env, 'needs_functions'): # Used to store...
You are a Python code generator, capable of creating scripts from specifications.
Creates a valid PlantUML entity name from the given value.
Here you have a function in Python 3, explain what it does def make_entity_name(name): invalid_chars = "-=!#$%^&*[](){}/~'`<>:;" for char in invalid_chars: name = name.replace(char, "_") return name
As a python code expert, you are capable of creating scripts from specifications.
This function is called by the parser class to load in the template file and run through the parser_noaa module.
Can you generate a brief explanation for the following Python 3 code def main(self): logger_lpd_noaa.info("enter main") # Starting Directory: dir_tmp/dir_bag/data/ # convert all lipd keys to noaa keys # timestamp the conversion of the file # MISC SETUP FUNCTIONS self.n...
You are a Python code analyst, evaluating scripts for potential improvements.
def __check_time_values(self): """ Rules 1. AD or CE units: bigger number is recent, smaller number is older 2. BP: bigger number is older, smaller number is recent. 3. No units: If max year is 1900-2017(current), then assume AD. Else, assume BP :return none: """...
Create a Python 3 function for checking the time values for the related noaa data.
As a Python code translator, you convert algorithms and pseudocode into Python.
Convert lpd to noaa keys for this one section
Given the following Python 3 function, write the documentation def __convert_keys_2(header, d): d_out = {} try: for k, v in d.items(): try: noaa_key = LIPD_NOAA_MAP_BY_SECTION[header][k] d_out[noaa_key] = v except Except...
You are a Python code architect, reviewing and designing scalable and efficient code
Loop over keys in a dictionary and replace the lipd keys with noaa keys
Can you generate the documentation for the following Python 3 function def __convert_keys_1(self, header, d): d2 = {} try: for k, v in d.items(): try: d2[self.__get_noaa_key_w_context(header, k)] = v except KeyError: pas...
As a Python code composer, you craft elegant and concise scripts.
def __create_blanks(section_name, d): """ All keys need to be written to the output, with or without a value. Furthermore, only keys that have values exist at this point. We need to manually insert the other keys with a blank value. Loop through the global list to see what's missing in o...
How would you code a function in Python 3 to create blanks for all keys in section_name.
As a Python code composer, you craft elegant and concise scripts.
Flatten the column so climateInterpretation and calibration are not nested.
Given the following Python 3 function, write the documentation def __flatten_col(d): try: for entry in ["climateInterpretation", "calibration"]: if entry in d: for k, v in d[entry].items(): d[k] = v del d[entry] ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Generate a study name for the current noaa class.
Can you tell what is the following Python 3 function doing def __generate_study_name(self): study_name = "" _exist = False try: if self.noaa_data_sorted["Top"]["Study_Name"]: _exist = True except KeyError: pass if not _exist: t...
You are a Python code analyst, evaluating scripts for potential improvements.
def __parse_dois(self, x): """ Parse the Dataset_DOI field. Could be one DOI string, or a list of DOIs :param any x: Str or List of DOI ids :return none: list is set to self """ # datasetDOI is a string. parse, validate and return a list of DOIs if isinstance(x, s...
Implement a Python 3 function for parsing the Dataset_DOI field. Could be one DOI string or a list of DOIs.
As a Python code analyst, you investigate and solve complex coding mysteries
Used in the path_context function. Splits the full path into a list of steps.
How would you explain what the following Python 3 function does def __split_path(string): out = [] position = string.find(':') if position != -1: # A position of 0+ means that ":" was found in the string key = string[:position] val = string[position+1:] ...
As a python code expert, you are capable of creating scripts from specifications.
Check that values exist in this table and we can write out data columns
Here you have a function in Python 3, explain what it does def _values_exist(table): try: for var, data in table["columns"].items(): if "values" in data: return True except KeyError as e: logger_lpd_noaa.warn("values_exist: KeyError: {}".format...
As a Python code composer, you craft elegant and concise scripts.
def __reorganize(self): """ Reorganize the keys into their proper section order for the NOAA output file DO NOT parse data tables (paleoData or chronData). We will do those separately. :param str key: :param any value: :return none: """ logger_lpd_noaa.inf...
How would you implement a function in Python 3 that reorganizes the keys into their proper section order for the NOAA output file.
As a Python code translator, you convert algorithms and pseudocode into Python.
Reorganizes author names by and and.
Given the following Python 3 function, write the documentation def __reorganize_author(self): try: for idx, pub in enumerate(self.noaa_data_sorted["Publication"]): if "author" in pub: _str = pub["author"] if " and " in _str: ...
You are a Python code generator, capable of creating scripts from specifications.
Reorganize the coordinates of the current object based on how many values are available.
Here you have a function in Python 3, explain what it does def __reorganize_coordinates(self): try: l = self.noaa_data_sorted["Site_Information"]['geometry']['coordinates'] locations = ["Northernmost_Latitude", "Southernmost_Latitude", "Easternmost_Longitude", "W...
As a Python code composer, you craft elegant and concise scripts.
def __reorganize_funding(self): """ Funding gets added to noaa_data_sorted with LiPD keys. Change those keys to NOAA :return none: """ _map = {"agency": "Funding_Agency_Name", "grant": "Grant"} try: _l = [] for item in self.noaa_data_sorted["Fundin...
Can you implement a function in Python 3 that reorganizes the Funding_Agency_Name and Grant keys.
As a Python code analyst, you investigate and solve complex coding mysteries
def __reorganize_geo(self): """ Concat geo value and units, and reorganize the rest References geo data from self.noaa_data_sorted Places new data into self.noaa_geo temporarily, and then back into self.noaa_data_sorted. :return: """ logger_lpd_noaa.info("enter re...
Write a Python 3 script for reorganizing the geo data from self. noaa_data_sorted
You are a Python code architect, reviewing and designing scalable and efficient code
Reorganize the sensor data into the noaa data
Can you generate a brief explanation for the following Python 3 code def __reorganize_sensor(self): _code = [] _name = [] # Check if any of the sensor data is misplaced, and create corrected lists. if self.lsts_tmp["genus"]: for name in self.lsts_tmp["genus"]: ...
As a Python code translator, you convert algorithms and pseudocode into Python.
def __put_names_on_csv_cols(names, cols): """ Put the variableNames with the corresponding column data. :param list names: variableNames :param list cols: List of Lists of column data :return dict: """ _combined = {} for idx, name in enumerate(names): ...
Create a Python 3 function to put the variableNames with the corresponding column data.
As a Python code composer, you craft elegant and concise scripts.
Always write year column first.
Can you generate the documentation for the following Python 3 function def __put_year_col_first(d): if "year" in d: D = OrderedDict() # store the year column first D["year"] = d["year"] for k,v in d.items(): if k != "year": # st...
You are a Python code analyst, evaluating scripts for potential improvements.
def __rm_duplicate_citation_2(self, key): """ Remove exact duplicate entries for abstract or citation fields. Check all publication entries. :return: """ citations = [] # Before writing, remove any duplicate "Full_Citations" that are found for idx, pub in enumerat...
How would you code a function in Python 3 to remove exact duplicate entries for abstract or citation fields. Check all publication entries.
You are a Python code generator, capable of creating scripts from specifications.
Remove the variableNames from the columns.
Given the following Python 3 function, write the documentation def __rm_names_on_csv_cols(d): _names = [] _data = [] for name, data in d.items(): _names.append(name) _data.append(data) return _names, _data
You are a Python code analyst, evaluating scripts for potential improvements.
def __get_author_last_name(author): """ Take a string of author(s), get the first author name, then get the first authors last name only. :param str author: Author(s) :return str _author: First author's last name """ _author = "" if isinstance(author, str): ...
How would you implement a function in Python 3 that takes a string of author names get the first author name then get the first authors last name only.
You are a Python code architect, reviewing and designing scalable and efficient code
def __create_author_investigator_str(self): """ When investigators is empty, try to get authors from the first publication instead. :return str author: Author names """ _author = "" try: for pub in self.noaa_data_sorted["Publication"]: if "auth...
Implement a Python 3 function for creating a string that can be used to get the authors from the first publication.
You are a Python code architect, reviewing and designing scalable and efficient code
def __get_filename(table): """ Get filename from a data table :param dict table: :return str: """ try: filename = table['filename'] except KeyError as e: filename = "" logger_lpd_noaa.warning("get_filename: KeyError: Table missi...
Write a Python 3 script to get filename from a data table
You are a Python code architect, reviewing and designing scalable and efficient code
def __get_doi(pub): """ Get DOI from this ONE publication entry. :param dict pub: Single publication entry :return: """ doi = "" # Doi location: d["pub"][idx]["identifier"][0]["id"] try: doi = pub["DOI"][0]["id"] doi = clean_doi(doi...
Implement a function in Python 3 to get DOI from this ONE publication entry.
You are a Python code generator, capable of creating scripts from specifications.
Get the proper noaa key for a given lipd key.
How would you explain what the following Python 3 function does def __get_noaa_key_w_context(header, lipd_key): try: noaa_key = LIPD_NOAA_MAP_BY_SECTION[header][lipd_key] except KeyError: return lipd_key return noaa_key
You are a Python code analyst, evaluating scripts for potential improvements.
def __get_max_min_time_1(self, table): """ Search for either Age or Year to calculate the max, min, and time unit for this table/file. Preference: Look for Age first, and then Year second (if needed) :param dict table: Table data :return dict: Max, min, and time unit """...
Can you write a function in Python 3 where it searches for either Age or Year to calculate the max, min, and time unit for this table/file. Preference: Look for Age first, and then Year second (if needed) :param dict table: Table data :return dict: Max, min, and time unit
You are a Python code generator, capable of creating scripts from specifications.
Get the max and min time for a given table and list of terms.
Explain what the following Python 3 code does def __get_max_min_time_2(table, terms, exact): vals = [] unit = "" try: for k, v in table["columns"].items(): if exact: if k.lower() in terms: try: va...
As a Python code translator, you convert algorithms and pseudocode into Python.
def __get_data_citation(self, l): """ If originalDataURL / investigators not in root data, check for a dataCitation pub entry. :return: """ # loop once for each publication entry for pub in l: try: # at the moment, these are the only keys of in...
Write a Python 3 script for looping over all publication entries and add data citation to self. data_citation
As a python code expert, you are capable of creating scripts from specifications.