output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
def __get_output_filenames(self):
"""
Set up the output filenames. If more than one file is being written out, we need appended filenames.
:return:
"""
# if there is only one file, use the normal filename with nothing appended.
if len(self.noaa_data_sorted["Data"]) == 1:
... | Write a Python 3 function that can
set up the output filenames. | You are a Python code architect, reviewing and designing scalable and efficient code |
def __get_table_pairs(self):
"""
Use the tables in self.paleos and self.chrons (sorted by idx) to put in self.noaa_data_sorted.
:return:
"""
try:
for _idx, _p in enumerate(self.data_paleos):
_c = {}
try:
_c = self.da... | Write a Python 3 function that can
get the paleo tables and the chron tables. | As a Python code analyst, you investigate and solve complex coding mysteries |
def __get_table_count(self):
"""
Check how many tables are in the json
:return int:
"""
_count = 0
try:
keys = ["paleo", "paleoData", "paleoMeasurementTable"]
# get the count for how many tables we have. so we know to make appended filenames or not... | Create a Python 3 function for
checking how many tables are in the json and if so check if we have to make the append_filenames flag | You are a Python code architect, reviewing and designing scalable and efficient code |
Create a new noaa file. | Make a summary of the following Python 3 code
def __create_file(self):
logger_lpd_noaa.info("enter create_file")
self.__get_output_filenames()
for idx, filename in enumerate(self.output_filenames):
try:
# self.noaa_txt = open(os.path.join(self.path, filename), "w+")... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __write_top(self, filename_txt):
"""
Write the top section of the txt file.
:param int section_num: Section number
:return none:
"""
logger_lpd_noaa.info("writing section: {}".format("top"))
self.__create_blanks("Top", self.noaa_data_sorted["Top"])
# ... | Write a Python 3 script for
writing the top section of the txt file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Write a generic section to the. txt file. | Can you generate a brief explanation for the following Python 3 code
def __write_generic(self, header, d=None):
logger_lpd_noaa.info("writing section: {}".format(header))
if not d:
d = self.noaa_data_sorted[header]
d = self.__create_blanks(header, d)
self.__write_header_name(... | As a Python code analyst, you investigate and solve complex coding mysteries |
Write pub section. There may be multiple, so write a generic section for each one.
:return none: | How would you explain what the following Python 3 function does
def __write_pub(self):
try:
self.__reorganize_author()
# Check all publications, and remove possible duplicate Full_Citations
self.__rm_duplicate_citation_1()
if not self.noaa_data_sorted["Publication... | As a Python code composer, you craft elegant and concise scripts. |
def __write_funding(self):
"""
Write funding section. There are likely multiple entries.
:param dict d:
:return none:
"""
self.__reorganize_funding()
# if funding is empty, insert a blank entry so that it'll still write the empty section on the template.
i... | How would you implement a function in Python 3 that
writes funding section. There are likely multiple entries. :param dict d: :return none: | You are a Python code analyst, evaluating scripts for potential improvements. |
Write out the measurement tables found in paleoData and chronData. | Make a summary of the following Python 3 code
def __write_data(self, idx):
pair = self.noaa_data_sorted["Data"][idx]
# Run once for each pair (paleo+chron) of tables that was gathered earlier.
# for idx, pair in enumerate(self.noaa_data_sorted["Data"]):
lst_pc = ["chron", "paleo"]
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Write the variables section of txt file. | Given the following Python 3 function, write the documentation
def __write_variables_1(self, table):
logger_lpd_noaa.info("writing section: {}".format("Variables"))
# Write the template lines first
self.__write_template_variable()
try:
self.noaa_txt += '#'
# Sp... | As a python code expert, you are capable of creating scripts from specifications. |
Write the variables section. | How would you explain what the following Python 3 function does
def __write_variables_2(self, col):
col = self.__convert_keys_1("Variables", col)
# Write one line for each column. One line has all metadata for one column.
for entry in NOAA_KEYS_BY_SECTION["Variables"]:
# May need a ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def __write_columns(self, pc, table):
"""
Read numeric data from csv and write to the bottom section of the txt file.
:param dict table: Paleodata dictionary
:return none:
"""
logger_lpd_noaa.info("writing section: data, csv values from file")
# get filename for t... | Can you implement a function in Python 3 that
writes the numeric data to the bottom section of the txt file. | You are a Python code architect, reviewing and designing scalable and efficient code |
Write a key - value pair to the output file. | Explain what the following Python 3 code does
def __write_k_v(self, k, v, top=False, bot=False, multi=False, indent=False):
if top:
self.noaa_txt += "\n#"
if multi:
for item in v:
if indent:
self.noaa_txt += "\n# {}: {}".format(str(k), str(... | You are a Python code generator, capable of creating scripts from specifications. |
Write a divider line | How would you explain what the following Python 3 function does
def __write_divider(self, top=False, bot=False, nl=True):
if top:
self.noaa_txt += "\n#"
if nl:
self.noaa_txt += "\n"
self.noaa_txt += "#------------------\n"
if bot:
self.noaa_txt += "\n#... | You are a Python code generator, capable of creating scripts from specifications. |
Write the variableNames that are the column header in the Data section. | How would you explain what the following Python 3 function does
def __write_data_col_header(self, l, pc):
count = len(l)
if pc == "chron":
self.noaa_txt += "# "
for name in l:
# last column - spacing not important
if count == 1:
self.noaa_txt +... | You are a Python code architect, reviewing and designing scalable and efficient code |
Loop over value arrays and write index by index to correspond to the rows of a txt file. | Can you tell what is the following Python 3 function doing
def __write_data_col_vals(self, ll, pc):
# all columns should have the same amount of values. grab that number
try:
_items_in_cols = len(ll[0]["values"])
for idx in range(0, _items_in_cols):
# amount of c... | You are a Python code generator, capable of creating scripts from specifications. |
Copies the value of one need option to another need. | Explain what the following Python 3 code does
def copy(app, need, needs, option, need_id=None):
if need_id is not None:
need = needs[need_id]
return need[option] | As a python code expert, you are capable of creating scripts from specifications. |
def check_linked_values(app, need, needs, result, search_option, search_value, filter_string=None, one_hit=False):
"""
Returns a specific value, if for all linked needs a given option has a given value.
The linked needs can be filtered by using the ``filter`` option.
If ``one_hit`` is set to True, onl... | How would you implement a function in Python 3 that
checks if all linked needs have a given value. | As a python code expert, you are capable of creating scripts from specifications. |
def calc_sum(app, need, needs, option, filter=None, links_only=False):
"""
Sums the values of a given option in filtered needs up to single number.
Useful e.g. for calculating the amount of needed hours for implementation of all linked
specification needs.
**Input data**
.. spec:: Do this
... | Implement a function in Python 3 to
calculate the sum of the values of a given option in a given linked tree. | As a Python code analyst, you investigate and solve complex coding mysteries |
def noaa_prompt():
"""
Convert between NOAA and LiPD file formats.
:return:
"""
logger_noaa.info("enter noaa")
# Run lpd_noaa or noaa_lpd ?
print("Which conversion?\n1. LPD to NOAA\n2. NOAA to LPD\n")
mode = input("Option: ")
logger_noaa.info("chose option: {}".format(mode))
ret... | Can you write a function in Python 3 where it
prompts user for conversion between NOAA and LiPD file formats. | You are a Python code analyst, evaluating scripts for potential improvements. |
Prompt user for the project and version number of the WDS links. | Make a summary of the following Python 3 code
def noaa_prompt_1():
print("Enter the project information below. We'll use this to create the WDS URL")
print("What is the project name?")
_project = input(">")
print("What is the project version?")
_version = input(">")
return _project, _version | As a python code expert, you are capable of creating scripts from specifications. |
def noaa_to_lpd(files):
"""
Convert NOAA format to LiPD format
:param dict files: Files metadata
:return None:
"""
logger_noaa.info("enter process_noaa")
# only continue if the user selected a mode correctly
logger_noaa.info("Found {} NOAA txt file(s)".format(str(len(files[".txt"]))))
... | Can you create a Python 3 function that
converts NOAA format to LiPD format | You are a Python code generator, capable of creating scripts from specifications. |
def lpd_to_noaa(D, wds_url, lpd_url, version, path=""):
"""
Convert a LiPD format to NOAA format
:param dict D: Metadata
:return dict D: Metadata
"""
logger_noaa.info("enter process_lpd")
d = D
try:
dsn = get_dsn(D)
# Remove all the characters that are not allowed here. ... | Create a Python 3 function for
converting a LiPD format to NOAA format | You are a Python code architect, reviewing and designing scalable and efficient code |
Write the data as NOAA text files | How would you explain what the following Python 3 function does
def __write_noaas(dat, path):
for filename, text in dat.items():
try:
with open(os.path.join(path, filename), "w+") as f:
f.write(text)
except Exception as e:
print("write_noaas: There was a probl... | As a python code expert, you are capable of creating scripts from specifications. |
Parse the java version line. | Given the following Python 3 function, write the documentation
def _parse_java_version(line: str) -> tuple:
m = VERSION_RE.search(line)
version_str = m and m.group(0).replace('"', '') or '0.0.0'
if '_' in version_str:
fst, snd = version_str.split('_', maxsplit=2)
version = parse_version(fst)... | You are a Python code architect, reviewing and designing scalable and efficient code |
Find the JAVA_HOME suites for the given CrateDB version. | Can you generate the documentation for the following Python 3 function
def find_java_home(cratedb_version: tuple) -> str:
if MIN_VERSION_FOR_JVM11 <= cratedb_version < (4, 0):
# Supports 8 to 11+, use whatever is set
return os.environ.get('JAVA_HOME', '')
if cratedb_version < MIN_VERSION_FOR_JVM... | As a Python code composer, you craft elegant and concise scripts. |
Zip the entire tree of the current directory. | Can you tell what is the following Python 3 function doing
def zipper(root_dir="", name="", path_name_ext=""):
logger_zips.info("re_zip: name: {}, dir_tmp: {}".format(path_name_ext, root_dir))
# creates a zip archive in current directory. "somefile.lpd.zip"
shutil.make_archive(path_name_ext, format='zip', r... | As a Python code composer, you craft elegant and concise scripts. |
Unzip the contents of a single. lpd file into a tmp directory. | Given the following Python 3 function, write the documentation
def unzipper(filename, dir_tmp):
logger_zips.info("enter unzip")
# Unzip contents to the tmp directory
try:
with zipfile.ZipFile(filename) as f:
f.extractall(dir_tmp)
except FileNotFoundError as e:
logger_zips.deb... | You are a Python code generator, capable of creating scripts from specifications. |
def percentile(sorted_values, p):
"""Calculate the percentile using the nearest rank method.
>>> percentile([15, 20, 35, 40, 50], 50)
35
>>> percentile([15, 20, 35, 40, 50], 40)
20
>>> percentile([], 90)
Traceback (most recent call last):
...
ValueError: Too few data points (0... | Can you implement a function in Python 3 that
calculates the percentile using the nearest rank method. | As a Python code composer, you craft elegant and concise scripts. |
def get_sampler(sample_mode: str):
"""Return a sampler constructor
>>> get_sampler('all')
<class 'cr8.metrics.All'>
>>> get_sampler('reservoir')
<class 'cr8.metrics.UniformReservoir'>
>>> get_sampler('reservoir:100')
functools.partial(<class 'cr8.metrics.UniformReservoir'>, size=100)
... | Implement a function in Python 3 to
return a sampler constructor for the given sample_mode. | You are a Python code analyst, evaluating scripts for potential improvements. |
Query the cache for the given criteria | How would you explain what the following Python 3 function does
def query(self, criteria, **opts):
time_now = datetime.datetime.now().replace(second=0, microsecond=0)
right_now = time_now.isoformat()
minutes_ago = (time_now - datetime.timedelta(minutes=15)).isoformat()
formats = opts.ge... | As a python code expert, you are capable of creating scripts from specifications. |
Main function for parsing data from Excel spreadsheets into LiPD files. | How would you explain what the following Python 3 function does
def excel_main(file):
os.chdir(file["dir"])
name_ext = file["filename_ext"]
# Filename without extension
name = file["filename_no_ext"]
# remove foreign characters to prevent wiki uploading errors
name = normalize_name(name)
p... | You are a Python code analyst, evaluating scripts for potential improvements. |
Get the metadata for a single worksheet. | Can you tell what is the following Python 3 function doing
def _get_sheet_metadata(workbook, name):
ct_paleo = 1
ct_chron = 1
metadata_str = ""
sheets = []
skip_sheets = ["example", "sample", "lists", "guidelines"]
# Check what worksheets are available, so we know how to proceed.
for sheet ... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _sheet_meta_from_prompts(sheets, old_name, name, ct_paleo, ct_chron):
"""
Guide the user to create a proper, standardized sheet name
:param list sheets: Running list of sheet metadata
:param str old_name: Original sheet name
:param str name: Data set name
:param int ct_paleo: Running count o... | Implement a Python 3 function for
creating a proper standardized sheet name from prompts. | As a python code expert, you are capable of creating scripts from specifications. |
def _sheet_meta_from_regex(m, sheets, old_name, name, ct_paleo, ct_chron):
"""
Build metadata for a sheet. Receive valid regex match object and use that to create metadata.
:param obj m: Regex match object
:param list sheets: Running list of sheet metadata
:param str old_name: Original sheet name
... | Implement a function in Python 3 to
build metadata for a single sheet from a regex match object. | You are a Python code analyst, evaluating scripts for potential improvements. |
def _place_tables_section(skeleton_section, sheet, keys_section):
"""
Place data into skeleton for either a paleo or chron section.
:param dict skeleton_section: Empty or current progress of skeleton w/ data
:param dict sheet: Sheet metadata
:param list keys_section: Paleo or Chron specific keys
... | Create a Python 3 function for
placing data into the skeleton for either a measurement or distribution or summary tables. | As a Python code analyst, you investigate and solve complex coding mysteries |
Place tables into the main LiPD structure. | Given the following Python 3 function, write the documentation
def _place_tables_main(sheets, skeleton_paleo, skeleton_chron):
logger_excel.info("enter place_tables_main")
for sheet in sheets:
pc = sheet["paleo_chron"]
if pc == "paleo":
skeleton_paleo = _place_tables_section(skeleto... | As a Python code composer, you craft elegant and concise scripts. |
Loop through sheet metadata and count how many of each table type is needed at each index. | Can you tell what is the following Python 3 function doing
def _get_table_counts(sheet, num_section):
tt = sheet["table_type"]
idx_pc = sheet["idx_pc"]
idx_table = sheet["idx_table"]
idx_model = sheet["idx_model"]
# Have we started counters for this idx model yet??
if idx_pc not in num_section:... | As a Python code composer, you craft elegant and concise scripts. |
def _create_skeleton_3(pc, l, num_section):
"""
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict... | How would you implement a function in Python 3 that
creates the metadata skeleton for the current mode and the current paleo. | As a python code expert, you are capable of creating scripts from specifications. |
Create the main and main tables for the main section of the main section. | Can you tell what is the following Python 3 function doing
def _create_skeleton_2(l, pc, num_section, template):
logger_excel.info("enter create_skeleton_inner_1")
try:
# Create N number of paleoData/chronData tables.
l = [copy.deepcopy(template)] * len(num_section)
# Create the necessar... | As a python code expert, you are capable of creating scripts from specifications. |
def _create_skeleton_1(sheets):
"""
Top level: {"chronData", "paleoData"}
Fill in paleoData/chronData tables with N number of EMPTY measurement and models.
:return list: Blank list of N indices
"""
logger_excel.info("enter create_skeleton_main")
# Table template: paleoData
template_pal... | How would you code a function in Python 3 to
create a skeleton for the main table. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _parse_sheet(workbook, sheet):
"""
The universal spreadsheet parser. Parse chron or paleo tables of type ensemble/model/summary.
:param str name: Filename
:param obj workbook: Excel Workbook
:param dict sheet: Sheet path and naming info
:return dict dict: Table metadata and numeric data
... | Implement a function in Python 3 to
parse an universal spreadsheet sheet. | You are a Python code analyst, evaluating scripts for potential improvements. |
Parse a row from the data section of the sheet. | How would you explain what the following Python 3 function does
def _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv):
# Get row of data
row = temp_sheet.row(num_row)
# In case our row holds more cells than the amount of columns we have, slice the row
# We don't want to ha... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Replace Missing Values in the data rows where applicable
| Can you tell what is the following Python 3 function doing
def _replace_mvs(row, mv):
for idx, v in enumerate(row):
try:
if v.value.lower() in EMPTY or v.value.lower() == mv:
row[idx] = "nan"
else:
row[idx] = v.value
except AttributeError:
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _get_header_keys(row):
"""
Get the variable header keys from this special row
:return list: Header keys
"""
# Swap out NOAA keys for LiPD keys
for idx, key in enumerate(row):
key_low = key.value.lower()
# Simple case: Nothing fancy here, just map to the LiPD key counterpart.... | How would you code a function in Python 3 to
get the header keys from this special row | As a Python code analyst, you investigate and solve complex coding mysteries |
Removes units from a single variable name in a single section of the metadata and data structures. | Can you tell what is the following Python 3 function doing
def _rm_units_from_var_name_single(var):
# Use the regex to match the cell
m = re.match(re_var_w_units, var)
# Should always get a match, but be careful anyways.
if m:
# m.group(1): variableName
# m.group(2): units in parenthesis... | You are a Python code generator, capable of creating scripts from specifications. |
Wrapper around _rm_units_from_var_name_single for doing a list instead of a single cell. | Can you generate the documentation for the following Python 3 function
def _rm_units_from_var_names_multi(row):
l2 = []
# Check each var in the row
for idx, var in enumerate(row):
l2.append(_rm_units_from_var_name_single(row[idx].value))
return l2 | You are a Python code analyst, evaluating scripts for potential improvements. |
def _compile_interpretation(data):
"""
Compile the interpretation data into a list of multiples, based on the keys provided.
Disassemble the key to figure out how to place the data
:param dict data: Interpretation data (unsorted)
:return dict: Interpretation data (sorted)
"""
# KEY FORMAT : ... | Implement a Python 3 function for
compiling the interpretation data into a list of multiples based on the keys provided. | You are a Python code analyst, evaluating scripts for potential improvements. |
Compile column metadata from one excel row | Given the following Python 3 function, write the documentation
def _compile_column_metadata(row, keys, number):
# Store the variable keys by index in a dictionary
_column = {}
_interpretation = {}
_calibration = {}
_physical = {}
# Use the header keys to place the column data in the dictionary
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def _rm_cells_reverse(l):
"""
Remove the cells that are empty or template in reverse order. Stop when you hit data.
:param list l: One row from the spreadsheet
:return list: Modified row
"""
rm = []
# Iter the list in reverse, and get rid of empty and template cells
for idx, key in rever... | Can you create a Python 3 function that
removes the cells that are empty or template in reverse order. Stop when you hit data. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _write_data_csv(csv_data):
"""
CSV data has been parsed by this point, so take it and write it file by file.
:return:
"""
logger_excel.info("enter write_data_csv")
# Loop for each file and data that is stored
for file in csv_data:
for filename, data in file.items():
#... | Can you create a Python 3 function that
writes CSV data to file by file. | You are a Python code analyst, evaluating scripts for potential improvements. |
def geometry_linestring(lat, lon, elev):
"""
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
"""
logger_excel.info("enter geometry_linestring")
d = OrderedDict()
coordinates = []
temp... | Write a Python 3 script to
create a GeoJSON Linestring. Latitude and Longitude have 2 values each. | As a Python code analyst, you investigate and solve complex coding mysteries |
Returns a dictionary of coordinates for a single object. | How would you explain what the following Python 3 function does
def geometry_range(crd_range, elev, crd_type):
d = OrderedDict()
coordinates = [[] for i in range(len(crd_range))]
# latitude
if crd_type == "lat":
for idx, i in enumerate(crd_range):
coordinates[idx] = [crd_range[idx]... | You are a Python code generator, capable of creating scripts from specifications. |
Returns a GeoJSON point in the format of a series of coordinates. | Make a summary of the following Python 3 code
def geometry_point(lat, lon, elev):
logger_excel.info("enter geometry_point")
coordinates = []
point_dict = OrderedDict()
for idx, val in enumerate(lat):
try:
coordinates.append(lon[idx])
coordinates.append(lat[idx])
e... | You are a Python code generator, capable of creating scripts from specifications. |
def compile_geometry(lat, lon, elev):
"""
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter compile_geometry")
... | Implement a Python 3 function for
returning a dictionary of geometry values for the given latitude and longitude. | You are a Python code generator, capable of creating scripts from specifications. |
def compile_geo(d):
"""
Compile top-level Geography dictionary.
:param d:
:return:
"""
logger_excel.info("enter compile_geo")
d2 = OrderedDict()
# get max number of sites, or number of coordinate points given.
num_loc = _get_num_locations(d)
# if there's one more than one locat... | Can you implement a function in Python 3 that
compiles top - level Geography dictionary. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _get_num_locations(d):
"""
Find out how many locations are being parsed. Compare lengths of each
coordinate list and return the max
:param dict d: Geo metadata
:return int: Max number of locations
"""
lengths = []
for key in EXCEL_GEO:
try:
if key != "siteName":
... | Write a Python 3 function that can
find out how many locations are being parsed. Compare lengths of each ArcGIS metadata and return the maximal locations. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _parse_geo_location(d):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ... | Write a Python 3 script to
parse one geo location and return a dict of properties | You are a Python code architect, reviewing and designing scalable and efficient code |
def _parse_geo_locations(d, idx):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[k... | Create a Python 3 function to
parse one geo location in a dictionary | You are a Python code generator, capable of creating scripts from specifications. |
def compile_authors(cell):
"""
Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names
"""
logger_excel.info("enter compile_authors")
author_lst = []
s = cell.split(';')
for w in s:
author_lst.appe... | How would you implement a function in Python 3 that
splits the string of author names into the BibJSON format. | As a Python code composer, you craft elegant and concise scripts. |
Compiles temporary dictionaries for metadata. Adds a new entry to an existing dictionary. | Given the following Python 3 function, write the documentation
def compile_temp(d, key, value):
if not value:
d[key] = None
elif len(value) == 1:
d[key] = value[0]
else:
d[key] = value
return d | You are a Python code analyst, evaluating scripts for potential improvements. |
def compile_fund(workbook, sheet, row, col):
"""
Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list of dict: l
"""
logger_excel.info("enter compi... | Can you create a Python 3 function that
compiles the funding block. | As a Python code composer, you craft elegant and concise scripts. |
Check that the metadata variable names are the same as the data header variable names in the sheet name. | How would you explain what the following Python 3 function does
def __compare_vars(a1, a2, name):
try:
a1 = [i for i in a1 if i]
a2 = [i for i in a2 if i]
a3 = set(a1).symmetric_difference(set(a2))
if a3:
print("- Error: Variables are not entered correctly in sheet: {}\n\... | You are a Python code generator, capable of creating scripts from specifications. |
def __get_datasetname(d, filename):
"""
Get the filename based on the dataset name in the metadata
:param str filename: Filename.lpd
:return str: Filename
"""
try:
filename = d["dataSetName"]
except KeyError:
logger_excel.info("get_datasetname: KeyError: No dataSetName found.... | Implement a Python 3 function for
getting the filename based on the dataset name in the metadata | As a Python code composer, you craft elegant and concise scripts. |
def __set_sheet_filenames(sheets, n):
"""
Use the dataset name to build the filenames in the sheets metadata
:param list sheets: Sheet metadata
:param str n: Dataset Name
:return list: Sheet metadata
"""
try:
for idx, sheet in enumerate(sheets):
try:
sheet... | How would you code a function in Python 3 to
set the filenames in the sheets metadata | You are a Python code analyst, evaluating scripts for potential improvements. |
Convert formal titles to camelcase json_ld text that matches our context file | How would you explain what the following Python 3 function does
def name_to_jsonld(title_in):
title_out = ''
try:
title_in = title_in.lower()
title_out = EXCEL_LIPD_MAP_FLAT[title_in]
except (KeyError, AttributeError) as e:
if "(" in title_in:
title_in = title_in.split("(... | As a Python code analyst, you investigate and solve complex coding mysteries |
def instance_str(cell):
"""
Match data type and return string
:param any cell:
:return str:
"""
if isinstance(cell, str):
return 'str'
elif isinstance(cell, int):
return 'int'
elif isinstance(cell, float):
return 'float'
else:
return 'unknown' | Implement a Python 3 function for
matching data type and return string | You are a Python code architect, reviewing and designing scalable and efficient code |
def extract_units(string_in):
"""
Extract units from parenthesis in a string. i.e. "elevation (meters)"
:param str string_in:
:return str:
"""
start = '('
stop = ')'
return string_in[string_in.index(start) + 1:string_in.index(stop)] | How would you code a function in Python 3 to
extract units from parenthesis in a string. i. e. elevation meters | As a Python code analyst, you investigate and solve complex coding mysteries |
def cells_rt_meta_pub(workbook, sheet, row, col, pub_qty):
"""
Publication section is special. It's possible there's more than one publication.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param int pub_qty: Number of distinct publication sections in this file
... | Create a Python 3 function to
return a list of cells in a specific row with a specific publication section. | As a Python code analyst, you investigate and solve complex coding mysteries |
def cells_rt_meta(workbook, sheet, row, col):
"""
Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_m... | Implement a Python 3 function for
traversing all cells in a row and return a list of all the data in that row. | You are a Python code architect, reviewing and designing scalable and efficient code |
Traverse all cells in a column moving downward and create a new one. | Can you generate a brief explanation for the following Python 3 code
def cells_dn_meta(workbook, sheet, row, col, final_dict):
logger_excel.info("enter cells_dn_meta")
row_loop = 0
pub_cases = ['id', 'year', 'author', 'journal', 'issue', 'volume', 'title', 'pages',
'reportNumber', 'abstract... | You are a Python code architect, reviewing and designing scalable and efficient code |
Count the number of chron variables in a resource tree. | Can you tell what is the following Python 3 function doing
def count_chron_variables(temp_sheet):
total_count = 0
start_row = traverse_to_chron_var(temp_sheet)
while temp_sheet.cell_value(start_row, 0) != '':
total_count += 1
start_row += 1
return total_count | As a Python code composer, you craft elegant and concise scripts. |
def get_chron_var(temp_sheet, start_row):
"""
Capture all the vars in the chron sheet (for json-ld output)
:param obj temp_sheet:
:param int start_row:
:return: (list of dict) column data
"""
col_dict = OrderedDict()
out_list = []
column = 1
while (temp_sheet.cell_value(start_ro... | Write a Python 3 function that can
get all the vars in the chron sheet | As a Python code composer, you craft elegant and concise scripts. |
def traverse_to_chron_data(temp_sheet):
"""
Traverse down to the first row that has chron data
:param obj temp_sheet:
:return int: traverse_row
"""
traverse_row = traverse_to_chron_var(temp_sheet)
reference_var = temp_sheet.cell_value(traverse_row, 0)
# Traverse past all the short_names... | Write a Python 3 function for
traversing to the first row that has chron data | As a Python code translator, you convert algorithms and pseudocode into Python. |
def traverse_to_chron_var(temp_sheet):
"""
Traverse down to the row that has the first variable
:param obj temp_sheet:
:return int:
"""
row = 0
while row < temp_sheet.nrows - 1:
if 'Parameter' in temp_sheet.cell_value(row, 0):
row += 1
break
row += 1
... | Create a Python 3 function to
traverse down to the first variable . | As a python code expert, you are capable of creating scripts from specifications. |
def get_chron_data(temp_sheet, row, total_vars):
"""
Capture all data in for a specific chron data row (for csv output)
:param obj temp_sheet:
:param int row:
:param int total_vars:
:return list: data_row
"""
data_row = []
missing_val_list = ['none', 'na', '', '-']
for i in range... | Create a Python 3 function for
getting all data in for a specific chron data row | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove placeholders from coordinate lists and sort
| Here you have a function in Python 3, explain what it does
def _remove_geo_placeholders(l):
vals = []
for i in l:
if isinstance(i, list):
for k in i:
if isinstance(k, float) or isinstance(k, int):
vals.append(k)
elif isinstance(i, float) or isinsta... | As a Python code composer, you craft elegant and concise scripts. |
def read_jsonld():
"""
Find jsonld file in the cwd (or within a 2 levels below cwd), and load it in.
:return dict: Jsonld data
"""
_d = {}
try:
# Find a jsonld file in cwd. If none, fallback for a json file. If neither found, return empty.
_filename = [file for file in os.listdi... | Can you write a function in Python 3 where it
reads the jsonld file in the LiPD archive and returns it in the Jsonld format. | As a Python code composer, you craft elegant and concise scripts. |
Read the JSON data from a file. | Explain what the following Python 3 code does
def read_json_from_file(filename):
logger_jsons.info("enter read_json_from_file")
d = OrderedDict()
try:
# Load and decode
d = demjson.decode_file(filename, decode_float=float)
logger_jsons.info("successful read from json file")
excep... | You are a Python code architect, reviewing and designing scalable and efficient code |
Switch from index - by - number to index - by - name. | Given the following Python 3 function, write the documentation
def idx_num_to_name(L):
logger_jsons.info("enter idx_num_to_name")
try:
if "paleoData" in L:
L["paleoData"] = _import_data(L["paleoData"], "paleo")
if "chronData" in L:
L["chronData"] = _import_data(L["chronD... | As a Python code analyst, you investigate and solve complex coding mysteries |
def _import_data(sections, crumbs):
"""
Import the section metadata and change it to index-by-name.
:param list sections: Metadata
:param str pc: paleo or chron
:return dict _sections: Metadata
"""
logger_jsons.info("enter import_data: {}".format(crumbs))
_sections = OrderedDict()
t... | Write a Python 3 script for
importing the metadata and change it to index - by - name. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _import_model(models, crumbs):
"""
Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata
"""
logger_jsons.info("enter import_model".format(crumbs))
_models = OrderedDict()
... | How would you code a function in Python 3 to
import nested paleoModel data into a single metadata dictionary. | As a python code expert, you are capable of creating scripts from specifications. |
Import summary ensemble or distribution data. | How would you explain what the following Python 3 function does
def _idx_table_by_name(tables, crumbs):
_tables = OrderedDict()
try:
for _idx, _table in enumerate(tables):
# Use "name" as tableName
_name = "{}{}".format(crumbs, _idx)
# Call idx_table_by_name
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Get CSV values when mixed into json data. | How would you explain what the following Python 3 function does
def get_csv_from_json(d):
logger_jsons.info("enter get_csv_from_json")
csv_data = OrderedDict()
if "paleoData" in d:
csv_data = _get_csv_from_section(d, "paleoData", csv_data)
if "chronData" in d:
csv_data = _get_csv_from_... | As a Python code composer, you craft elegant and concise scripts. |
def _get_csv_from_section(d, pc, csv_data):
"""
Get csv from paleo and chron sections
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: running csv data
"""
logger_jsons.info("enter get_csv_from_section: {}".format(pc))
for table, table_content in d[pc].items():
... | Write a Python 3 function for
getting csv from paleo and chron sections | As a Python code translator, you convert algorithms and pseudocode into Python. |
Remove all CSV data entries from paleoData table in the JSON structure. | Can you generate the documentation for the following Python 3 function
def remove_csv_from_json(d):
logger_jsons.info("enter remove_csv_from_json")
# Check both sections
if "paleoData" in d:
d = _remove_csv_from_section(d, "paleoData")
if "chronData" in d:
d = _remove_csv_from_section(... | You are a Python code generator, capable of creating scripts from specifications. |
def _remove_csv_from_section(d, pc):
"""
Remove CSV from metadata in this section
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: Modified metadata
"""
logger_jsons.info("enter remove_csv_from_json: {}".format(pc))
for table, table_content in d[pc].items():
f... | Can you implement a function in Python 3 that
removes CSV from metadata in this section | You are a Python code analyst, evaluating scripts for potential improvements. |
Write all JSON in python dictionary to a new json file. | Can you generate a brief explanation for the following Python 3 code
def write_json_to_file(json_data, filename="metadata"):
logger_jsons.info("enter write_json_to_file")
json_data = rm_empty_fields(json_data)
# Use demjson to maintain unicode characters in output
json_bin = demjson.encode(json_data, en... | You are a Python code architect, reviewing and designing scalable and efficient code |
def idx_name_to_num(L):
"""
Switch from index-by-name to index-by-number.
:param dict L: Metadata
:return dict: Modified metadata
"""
logger_jsons.info("enter idx_name_to_num")
# Process the paleoData section
if "paleoData" in L:
L["paleoData"] = _export_section(L["paleoData"], ... | Create a Python 3 function for
switching from index - by - name to index - by - number. | You are a Python code architect, reviewing and designing scalable and efficient code |
def _export_section(sections, pc):
"""
Switch chron data to index-by-number
:param dict sections: Metadata
:return list _sections: Metadata
"""
logger_jsons.info("enter export_data: {}".format(pc))
_sections = []
for name, section in sections.items():
# Process chron models
... | How would you code a function in Python 3 to
switch chron data to index - by - number | As a Python code analyst, you investigate and solve complex coding mysteries |
Switch model tables to index - by - number | Can you generate a brief explanation for the following Python 3 code
def _export_model(models):
logger_jsons.info("enter export_model")
_models = []
try:
for name, model in models.items():
if "summaryTable" in model:
model["summaryTable"] = _idx_table_by_num(model["summa... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _idx_table_by_num(tables):
"""
Switch tables to index-by-number
:param dict tables: Metadata
:return list _tables: Metadata
"""
logger_jsons.info("enter idx_table_by_num")
_tables = []
for name, table in tables.items():
try:
# Get the modified table data
... | Write a Python 3 script to
switch tables to index - by - number | As a Python code analyst, you investigate and solve complex coding mysteries |
def _idx_col_by_num(table):
"""
Index columns by number instead of by name. Use "number" key in column to maintain order
:param dict table: Metadata
:return list _table: Metadata
"""
_columns = []
try:
# Create an empty list that matches the length of the column dictionary
_... | Create a Python 3 function to
index columns by number instead of by name. Use number key in column to maintain order | You are a Python code analyst, evaluating scripts for potential improvements. |
Create a bag from a given directory. | Can you generate a brief explanation for the following Python 3 code
def make_bag(bag_dir, bag_info=None, processes=1, checksum=None):
bag_dir = os.path.abspath(bag_dir)
logger.info("creating bag for directory %s", bag_dir)
# assume md5 checksum if not specified
if not checksum:
checksum = ['md5... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _calculate_file_hashes(full_path, f_hashers):
"""
Returns a dictionary of (algorithm, hexdigest) values for the provided
filename
"""
if not os.path.exists(full_path):
raise BagValidationError("%s does not exist" % full_path)
try:
with open(full_path, 'rb') as f:
... | How would you implement a function in Python 3 that
calculates the hash of the file at the provided path. | As a Python code composer, you craft elegant and concise scripts. |
def _parse_tags(tag_file):
"""Parses a tag file, according to RFC 2822. This
includes line folding, permitting extra-long
field values.
See http://www.faqs.org/rfcs/rfc2822.html for
more information.
"""
tag_name = None
tag_value = None
# Line folding is handled by yi... | How would you implement a function in Python 3 that
parses a tag file and yields a list of tuples. | As a Python code composer, you craft elegant and concise scripts. |
def _can_bag(test_dir):
"""returns (unwriteable files/folders)
"""
unwriteable = []
for inode in os.listdir(test_dir):
if not os.access(os.path.join(test_dir, inode), os.W_OK):
unwriteable.append(os.path.join(os.path.abspath(test_dir), inode))
return tuple(unwriteable) | Can you write a function in Python 3 where it
returns ( unwriteable files and folders | You are a Python code architect, reviewing and designing scalable and efficient code |
def _can_read(test_dir):
"""
returns ((unreadable_dirs), (unreadable_files))
"""
unreadable_dirs = []
unreadable_files = []
for dirpath, dirnames, filenames in os.walk(test_dir):
for dn in dirnames:
if not os.access(os.path.join(dirpath, dn), os.R_OK):
unreada... | Can you write a function in Python 3 where it
returns a tuple of tuples containing all directories and files that can be read from the test directory. | You are a Python code architect, reviewing and designing scalable and efficient code |
def compare_fetch_with_fs(self):
"""Compares the fetch entries with the files actually
in the payload, and returns a list of all the files
that still need to be fetched.
"""
files_on_fs = set(self.payload_files())
files_in_fetch = set(self.files_to_be_fetched())
... | Implement a function in Python 3 to
compare the files actually in the payload and returns a list of all the files that need to be fetched. | You are a Python code architect, reviewing and designing scalable and efficient code |
Save the current bag to the file system. | Given the following Python 3 function, write the documentation
def save(self, processes=1, manifests=False):
# Error checking
if not self.path:
raise BagError("Bag does not have a path.")
# Change working directory to bag directory so helper functions work
old_dir = os.path.... | 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.