code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
_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 | def split_path_and_file(s) | Given a full path to a file, split and return a path and filename
:param str s: Path
:return str _path: Directory Path
:return str _filename: Filename | 3.249897 | 3.011877 | 1.079027 |
# keep processing until all nesting is removed
process = True
# fail safe: cap the loops at 20, so we don't run into an error and loop infinitely.
# if it takes more than 20 loops then there is a problem with the data given.
loops = 25
while process and loops > 0:
try:
#... | 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 | 5.283574 | 5.160551 | 1.023839 |
logger_ts.info("enter extract_main")
_root = {}
_ts = {}
# _switch = {"paleoData": "chronData", "chronData": "paleoData"}
_pc = "paleoData"
if mode == "chron":
_pc = "chronData"
_root["mode"] = _pc
_root["time_id"] = time
try:
# Build the root level data.
... | def extract(d, whichtables, mode, time) | LiPD Version 1.3
Main function to initiate LiPD to TSOs conversion.
Each object has a
"paleoNumber" or "chronNumber"
"tableNumber"
"modelNumber"
"time_id"
"mode" - chronData or paleoData
"tableType" - "meas" "ens" "summ"
:param dict d: Metadata for one LiPD file
:param str whi... | 4.608371 | 4.092277 | 1.126114 |
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 | def _extract_fund(l, _root) | Creates flat funding dictionary.
:param list l: Funding entries | 5.136279 | 5.197181 | 0.988282 |
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_meanLat', 'geo_meanElev']
# Iterate through geo dictionary
for k, v in d.items():
# Case 1: Coordinates special nam... | def _extract_geo(d, _root) | Extract geo data from input
:param dict d: Geo
:return dict _root: Root data | 4.645255 | 4.619633 | 1.005546 |
logger_ts.info("enter _extract_pub")
# For each publication entry
for idx, pub in enumerate(l):
logger_ts.info("processing publication #: {}".format(idx))
# Get author data first, since that's the most ambiguously structured data.
_root = _extract_authors(pub, idx, _root)
... | def _extract_pub(l, _root) | Extract publication data from one or more publication entries.
:param list l: Publication
:return dict _root: Root data | 5.103494 | 4.852443 | 1.051737 |
logger_ts.info("enter extract_authors")
try:
# DOI Author data. We'd prefer to have this first.
names = pub['author']
except KeyError as e:
try:
# Manually entered author data. This is second best.
names = pub['authors']
except KeyError as e:
... | 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 | 5.584371 | 5.427153 | 1.028969 |
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":
for _table_name1, _table_data1 in v["measurementTable"].items():
_ts = _extract_table(_tab... | def _extract_pc(d, root, pc, whichtables) | Extract all data from a PaleoData dictionary.
:param dict d: PaleoData dictionary
:param dict root: Time series root data
:param str pc: paleoData or chronData
:param str whichtables: all, meas, summ, or ens
:return list _ts: Time series | 2.817949 | 2.534065 | 1.112027 |
_method = {}
for k,v in method.items():
_method["method_" + k] = v
return _method | def _extract_method(method) | Make a timeseries-formatted version of model method data
:param dict method: Method data
:return dict _method: Method data, formatted | 4.092636 | 4.635562 | 0.882878 |
logger_ts.info("enter extract_special")
try:
# Add age, year, and depth columns to ts_root where possible
for k, v in table_data['columns'].items():
s = ""
# special case for year bp, or any variation of it. Translate key to "age""
if "bp" in k.lower():
... | 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: | 6.042314 | 5.693398 | 1.061284 |
logger_ts.info("enter extract_table_root")
try:
for k, v in d.items():
if isinstance(v, str):
current[pc + '_' + k] = v
except Exception as e:
logger_ts.error("extract_table_root: {}".format(e))
return current | 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 | 3.515304 | 3.580447 | 0.981806 |
try:
if tt in ["summ", "ens"]:
m = re.match(re_sheet, table_data["tableName"])
if m:
_pc_num= m.group(1) + "Number"
current[_pc_num] = m.group(2)
current["modelNumber"] = m.group(4)
current["tableNumber"] = m.group(... | 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 | 5.766607 | 4.511818 | 1.278112 |
current["tableType"] = tt
# Get root items for this table
current = _extract_table_root(table_data, current, pc)
# Add in modelNumber and tableNumber if this is "ens" or "summ" table
current = _extract_table_model(table_data, current, tt)
# Add age, depth, and year columns to root if availa... | 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)
:param bool summary: Summary Table or not
:return list ts: Time ... | 7.041466 | 6.724602 | 1.04712 |
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():
tmp_tso[n] = m
else:
# Assume if it's not a special nested case, then it'... | def _extract_columns(d, tmp_tso, pc) | Extract data from one paleoData column
:param dict d: Column dictionary
:param dict tmp_tso: TSO dictionary with only root items
:return dict: Finished TSO | 4.661635 | 5.079694 | 0.9177 |
logger_ts.info("enter collapse")
# LiPD data (in progress), sorted dataset name
_master = {}
_dsn = ""
try:
# Determine if we're collapsing a paleo or chron time series
_pc = l[0]["mode"]
# Loop the time series
for entry in l:
# Get notable keys
... | def collapse(l, raw) | LiPD Version 1.3
Main function to initiate time series to LiPD conversion
Each object has a:
"paleoNumber" or "chronNumber"
"tableNumber"
"modelNumber"
"time_id"
"mode" - chronData or paleoData
"tableType" - "meas" "ens" "summ"
:param list l: Time series
:return dict _master: L... | 6.318305 | 5.190174 | 1.217359 |
_table_name = ""
_variable_name = ""
# Get key info
try:
_table_name = current['{}_tableName'.format(pc)]
_variable_name = current['{}_variableName'.format(pc)]
except Exception as e:
print("Error: Unable to collapse time series: {}, {}".format(dsn, e))
logger_ts... | def _get_current_names(current, dsn, pc) | Get the table name and variable name from the given time series entry
:param dict current: Time series entry
:param str pc: paleoData or chronData
:return str _table_name:
:return str _variable_name: | 4.895226 | 4.03048 | 1.214552 |
logger_ts.info("enter collapse_author")
l = []
authors = s.split(';')
for author in authors:
l.append({'name': author})
return l | 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 | 7.060353 | 6.971593 | 1.012732 |
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_number, _table_name)
# Is this a summary table or a measurement table?
_switch = {"mea... | def _collapse_pc(master, current, dsn, pc) | Collapse the paleo or chron for the current time series entry
:param dict master: LiPD data (so far)
:param dict current: Current time series entry
:param str dsn: Dataset name
:param str pc: paleoData or chronData
:return dict master: | 3.40727 | 3.301811 | 1.03194 |
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():
# These are the main table keys that we should be looking for
for i in ['filename', 'googleW... | def _collapse_table_root(current, dsn, pc) | Create a table with items in root given the current time series entry
:param dict current: Current time series entry
:param str dsn: Dataset name
:param str pc: paleoData or chronData
:return dict _tmp_table: Table data | 6.33997 | 6.012143 | 1.054527 |
_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 any(i in k for i in ["tableName", "google", "filename", "md5", "MD5"]):
# ['paleoData', 'key']
... | def _collapse_column(current, pc) | Collapse the column data and
:param current:
:param pc:
:return: | 5.256225 | 5.229808 | 1.005051 |
phrase = ""
if ec == "extract":
if mode=="chron":
phrase = "extracting chronData..."
else:
phrase = "extracting paleoData..."
elif ec == "collapse":
if ts[0]["mode"] == "chronData":
phrase = "collapsing chronData"
else:
phr... | def mode_ts(ec, mode="", ts=None) | Get string for the mode
:param str ec: extract or collapse
:param str mode: "paleo" or "chron" mode
:param list ts: Time series (for collapse)
:return str phrase: Phrase | 5.210207 | 3.122311 | 1.668702 |
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:])
if tmp[1] in COMPARISONS:
tmp[1] = COMPARISONS[tmp[1]]
... | def translate_expression(expression) | Check if the expression is valid, then check turn it into an expression that can be used for filtering.
:return list of lists: One or more matches. Each list has 3 strings. | 3.408434 | 3.179246 | 1.072089 |
logger_ts.info("enter get_matches")
new_ts = []
idxs = []
match = False
try:
for idx, ts_data in enumerate(ts):
for expr in expr_lst:
try:
val = ts_data[expr[0]]
# Check what comparison operator is being used
... | 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 | 3.80826 | 3.602045 | 1.057249 |
if isinstance(hosts, str):
hosts = hosts.replace(',', ' ').split()
return [_to_http_uri(i) for i in hosts] | 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:4200')
['http://n1:4200', 'http://n2:4200']
>>> _to_http_hosts('n1... | 3.501299 | 5.017023 | 0.697884 |
if callable(obj):
return obj()
elif isinstance(obj, types.GeneratorType):
return next(obj)
else:
return obj | 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'
>>> def _args():
... ret... | 3.092367 | 4.265762 | 0.724927 |
p = urlparse(hosts)
try:
user_and_pw, netloc = p.netloc.split('@', maxsplit=1)
except ValueError:
netloc = p.netloc
user_and_pw = 'crate'
try:
host, port = netloc.split(':', maxsplit=1)
except ValueError:
host = netloc
port = 5432
dbname = p.p... | 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')
'postgres://hoschi:pw... | 2.358461 | 2.145329 | 1.099347 |
for host in hosts:
query = parse_qs(urlparse(host).query)
if 'verify_ssl' in query:
return _to_boolean(query['verify_ssl'][0])
return True | 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=False',
... 'https://h2:4200/?ve... | 3.399596 | 3.489721 | 0.974174 |
_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"
"3: ensemble (under development)\n"
"4: distribution (und... | def addTable(D) | Add any table type to the given dataset. Use prompts to determine index locations and table type.
:param dict D: Metadata (dataset)
:param dict dat: Metadata (table)
:return dict D: Metadata (dataset) | 5.697573 | 5.466262 | 1.042316 |
_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():
# looking for open spots for measurement tables
if tt == "measurement"... | def _get_available_placements(D, tt) | Called from: _prompt_placement()
Get a list of possible places that we can put the new model data into.
If no model exists yet, we'll use something like chron0model0. If other models exist,
we'll go for the n+1 entry.
ex: chron0model0 already exists, so we'll look to chron0model1 next.
:param dict... | 5.943348 | 5.445682 | 1.091387 |
_model_name = ""
# There wasn't a table name match, so we need prompts to fix it
_placement_options = _get_available_placements(D, tt)
print("Please choose where you'd like to place this model:")
for _idx, _opt in enumerate(_placement_options):
print("({}) {}".format(_idx, _opt))
_c... | 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 | 5.399148 | 4.993706 | 1.081191 |
try:
# print("Placing table: {}".format(name))
table["tableName"] = name
m = re.match(re_table_name, name)
if m:
_pc = m.group(1) + "Data"
_section = m.group(1) + m.group(2)
# place a measurement table
if m.group(3) == "measuremen... | 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 | 4.846307 | 4.473496 | 1.083338 |
for _tabletype in ["summary", "distribution", "ensemble"]:
_ttname = "{}Table".format(_tabletype)
if _ttname in dat:
_new_tables = OrderedDict()
_idx = 0
# change all the top level table names
for k,v in dat[_ttname].items():
_new_... | def _update_table_names(name, dat) | Model placement is subject to change. That means all names within the model (names are path-dependent) are also
subject to change. Whichever name is decided, the inner data needs to match it.
:param dict dat: Metadata
:param str name: Table name
:return dict dat: Metadata | 4.722297 | 4.850552 | 0.973559 |
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, _model_name)
if _m:
D = _put_model(D, _model_name, _model_data, ... | def addModel(D, models) | Insert model data into a LiPD dataset
Examples of model naming:
chron0model0
chron0model1
chron1model0
Example of 'models' variable:
{
chron0model0: {
"method": {...},
"summaryTable": [...],
"ensembleTable": [...],
... | 4.776733 | 4.796961 | 0.995783 |
try:
# print("Placing model: {}".format(name))
_pc = m.group(1) + "Data"
_section = m.group(1) + m.group(2)
if _pc not in D:
# Section missing entirely? Can't continue
print("{} not found in the provided dataset. Please try again".format(_pc))
... | 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) | 3.85773 | 3.530633 | 1.092645 |
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 all registered functions for supporting dynamic need values.
env.needs_functions = {}
... | def prepare_env(app, env, docname) | Prepares the sphinx environment to store sphinx-needs internal data. | 5.652803 | 5.37229 | 1.052215 |
invalid_chars = "-=!#$%^&*[](){}/~'`<>:;"
for char in invalid_chars:
name = name.replace(char, "_")
return name | def make_entity_name(name) | Creates a valid PlantUML entity name from the given value. | 6.306586 | 5.545995 | 1.137142 |
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.noaa_data_sorted["File_Last_Modified_Date"]["Modified_Date"] = generate_times... | def main(self) | Load in the template file, and run through the parser
:return none: | 11.809252 | 11.837125 | 0.997645 |
_earliest = float(self.noaa_data_sorted["Data_Collection"]["Earliest_Year"])
_recent = float(self.noaa_data_sorted["Data_Collection"]["Most_Recent_Year"])
try:
_unit = self.noaa_data_sorted["Data_Collection"]["Time_Unit"]
except Exception:
_unit = ""
... | 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: | 2.150553 | 1.93012 | 1.114207 |
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 Exception:
logger_lpd_noaa.warn("lpd_noaa: convert_keys_section: ran into... | def __convert_keys_2(header, d) | Convert lpd to noaa keys for this one section
:param str header: Section header
:param dict d: Metadata
:return dict: Metadata w/ converted keys | 4.293951 | 3.585687 | 1.197525 |
d2 = {}
try:
for k, v in d.items():
try:
d2[self.__get_noaa_key_w_context(header, k)] = v
except KeyError:
pass
except Exception:
return d
return d2 | def __convert_keys_1(self, header, d) | Loop over keys in a dictionary and replace the lipd keys with noaa keys
:return: | 4.574654 | 3.735125 | 1.224766 |
try:
for key in NOAA_KEYS_BY_SECTION[section_name]:
if key not in d:
# Key not in our dict. Create the blank entry.
d[key] = ""
except Exception:
logger_lpd_noaa.error("lpd_noaa: create_blanks: must section: {}, key... | 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 our dict.
:param str section_name: Retrieve data fr... | 7.919611 | 7.824535 | 1.012151 |
try:
for entry in ["climateInterpretation", "calibration"]:
if entry in d:
for k, v in d[entry].items():
d[k] = v
del d[entry]
except AttributeError:
pass
return d | def __flatten_col(d) | Flatten column so climateInterpretation and calibration are not nested.
:param d:
:return: | 5.643232 | 3.112091 | 1.813325 |
study_name = ""
_exist = False
try:
if self.noaa_data_sorted["Top"]["Study_Name"]:
_exist = True
except KeyError:
pass
if not _exist:
try:
_site = self.noaa_data_sorted["Site_Information"]["properties"]... | def __generate_study_name(self) | When a study name is not given, generate one with the format of " author - site name - year "
:return str study_name: generated study name | 3.489379 | 3.287208 | 1.061502 |
# ["archive_type", "sensor_genus", "sensor_species", "investigator"]
if self.lsts_tmp["archive"]:
self.noaa_data_sorted["Top"]["Archive"] = ",".join(self.lsts_tmp["archive"])
if self.lsts_tmp["species"]:
self.noaa_data_sorted["Species"]["Species_Name"] = ",".join... | def __lists_to_str(self) | There are some data lists that we collected across the dataset that need to be concatenated into a single
string before writing to the text file.
:return none: | 3.998566 | 4.046941 | 0.988046 |
# datasetDOI is a string. parse, validate and return a list of DOIs
if isinstance(x, str):
# regex cleans string, and returns a list with 1 entry for each regex doi match
m = clean_doi(x)
# make sure m is not an empty list
if m:
# ... | 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 | 5.080707 | 4.901288 | 1.036606 |
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:]
out.append(key)
out.append(val)
if ('-' in key) and... | def __split_path(string) | Used in the path_context function. Split the full path into a list of steps
:param str string: Path string ("geo-elevation-height")
:return list out: Path as a list of strings. One entry per path step.(["geo", "elevation", "height"]) | 4.969651 | 4.653172 | 1.068014 |
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(e))
except Exception as e:
logger_lpd_noaa.warn("values... | def _values_exist(table) | Check that values exist in this table, and we can write out data columns
:param dict table: Table data
:return bool: Values exist or not exist | 4.53155 | 4.304757 | 1.052684 |
logger_lpd_noaa.info("enter reorganize")
# NOAA files are organized in sections differently than NOAA. try to translate these sections.
for key, value in self.lipd_data.items():
# if this key has a noaa match, it'll be returned. otherwise, empty string for no match
... | 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: | 6.902879 | 6.673237 | 1.034412 |
try:
for idx, pub in enumerate(self.noaa_data_sorted["Publication"]):
if "author" in pub:
_str = pub["author"]
if " and " in _str:
self.noaa_data_sorted["Publication"][idx]["author"] = _str.replace(" and ", "; "... | def __reorganize_author(self) | LiPD delimits author names by "and". Noaa wants them to be semi-colon delimited.
:return none: | 3.030204 | 2.755876 | 1.099543 |
try:
l = self.noaa_data_sorted["Site_Information"]['geometry']['coordinates']
locations = ["Northernmost_Latitude", "Southernmost_Latitude", "Easternmost_Longitude",
"Westernmost_Longitude", "Elevation"]
logger_lpd_noaa.info("coordinates: {} ... | def __reorganize_coordinates(self) | GEOJSON FORMAT : [ LONGITUDE, LATITUDE, ELEVATION]
Reorganize coordinates based on how many values are available.
:return: | 3.949808 | 3.910241 | 1.010119 |
_map = {"agency": "Funding_Agency_Name", "grant": "Grant"}
try:
_l = []
for item in self.noaa_data_sorted["Funding_Agency"]:
_tmp = {}
for lpd_name, noaa_name in _map.items():
val = ""
if lpd_name in... | def __reorganize_funding(self) | Funding gets added to noaa_data_sorted with LiPD keys. Change those keys to NOAA
:return none: | 3.719756 | 3.090908 | 1.203451 |
logger_lpd_noaa.info("enter reorganize_geo")
try:
# Geo -> Properties
for k, v in self.noaa_data_sorted["Site_Information"]['properties'].items():
noaa_key = self.__get_noaa_key(k)
self.noaa_geo[noaa_key] = v
except KeyError:
... | 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: | 4.789908 | 4.016159 | 1.192659 |
_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"]:
if len(name) == 4 and name.isupper():
_code.append(name)
... | def __reorganize_sensor(self) | We have raw sensorGenus, and sensorSpecies in self, now clean and sort
:return none: | 3.877214 | 3.592198 | 1.079343 |
_combined = {}
for idx, name in enumerate(names):
# Use the variableName, and the column data from the same index
_combined[name] = cols[idx]
return _combined | 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: | 12.378197 | 7.799954 | 1.586958 |
if "year" in d:
D = OrderedDict()
# store the year column first
D["year"] = d["year"]
for k,v in d.items():
if k != "year":
# store the other columns
D[k] = v
return D
else:
... | def __put_year_col_first(d) | Always write year column first. Reorder dictionary so that year is first
:param dict d: data
:return dict: Reordered data | 3.477957 | 3.383685 | 1.027861 |
citations = []
# Before writing, remove any duplicate "Full_Citations" that are found
for idx, pub in enumerate(self.noaa_data_sorted["Publication"]):
try:
citations.append(pub[key])
except KeyError:
# Key was not found. Enter a bl... | def __rm_duplicate_citation_2(self, key) | Remove exact duplicate entries for abstract or citation fields. Check all publication entries.
:return: | 5.901647 | 5.838347 | 1.010842 |
_names = []
_data = []
for name, data in d.items():
_names.append(name)
_data.append(data)
return _names, _data | def __rm_names_on_csv_cols(d) | Remove the variableNames from the columns.
:param dict d: Named csv data
:return list list: One list for names, one list for column data | 2.851581 | 2.375271 | 1.200529 |
_author = ""
if isinstance(author, str):
try:
# example: 'Ahmed, Moinuddin and Anchukaitis, Kevin J and ...'
# If this is a list of authors, try to split it and just get the first author.
if " and " in author:
_au... | 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 | 4.011974 | 3.882901 | 1.033241 |
_author = ""
try:
for pub in self.noaa_data_sorted["Publication"]:
if "author" in pub:
if pub["author"]:
_author_src = pub["author"]
if isinstance(_author_src, str):
try:
... | def __create_author_investigator_str(self) | When investigators is empty, try to get authors from the first publication instead.
:return str author: Author names | 3.13027 | 2.990535 | 1.046726 |
try:
filename = table['filename']
except KeyError as e:
filename = ""
logger_lpd_noaa.warning("get_filename: KeyError: Table missing filename, {}".format(e))
except TypeError:
try:
filename = table[0]["filename"]
... | def __get_filename(table) | Get filename from a data table
:param dict table:
:return str: | 4.637939 | 4.289686 | 1.081184 |
doi = ""
# Doi location: d["pub"][idx]["identifier"][0]["id"]
try:
doi = pub["DOI"][0]["id"]
doi = clean_doi(doi)
except KeyError:
logger_lpd_noaa.info("get_dois: KeyError: missing a doi key")
except Exception:
logger_lpd_n... | def __get_doi(pub) | Get DOI from this ONE publication entry.
:param dict pub: Single publication entry
:return: | 5.909936 | 6.174425 | 0.957164 |
try:
noaa_key = LIPD_NOAA_MAP_BY_SECTION[header][lipd_key]
except KeyError:
return lipd_key
return noaa_key | def __get_noaa_key_w_context(header, lipd_key) | Use the section header and key to get the proper noaa key.
:param str header:
:param str lipd_key:
:return: | 4.77378 | 4.019097 | 1.187774 |
if isinstance(x, dict):
if "sensorGenus" in x:
if x["sensorGenus"] and x["sensorGenus"] not in self.lsts_tmp["genus"]:
self.lsts_tmp["genus"].append(x["sensorGenus"])
if "sensorSpecies" in x:
if x["sensorSpecies"] and x["sensor... | def __get_overall_data(self, x) | (recursive) Collect all "sensorGenus" and "sensorSpecies" fields, set data to self
:param any x: Any data type
:return none: | 1.840684 | 1.616557 | 1.138645 |
try:
# find the values and units we need to calculate
vals, units = self.__get_max_min_time_2(table, ["age", "yearbp", "yrbp"], True)
if not vals and not units:
vals, units = self.__get_max_min_time_2(table, ["year", "yr"], True)
if not ... | 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 | 3.878126 | 3.717542 | 1.043196 |
vals = []
unit = ""
try:
for k, v in table["columns"].items():
if exact:
if k.lower() in terms:
try:
vals = v["values"]
unit = v["units"]
... | def __get_max_min_time_2(table, terms, exact) | 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
:param list terms: age, yearbp, yrbp, or year, yr
:param bool exact: Look for exact key match, or no... | 3.311735 | 3.157653 | 1.048796 |
# loop once for each publication entry
for pub in l:
try:
# at the moment, these are the only keys of interest inside of dataCitation. Check each.
for key in ["url", "investigators"]:
if pub["type"] == "dataCitation" and key in pub... | def __get_data_citation(self, l) | If originalDataURL / investigators not in root data, check for a dataCitation pub entry.
:return: | 7.16527 | 6.286737 | 1.139744 |
# if there is only one file, use the normal filename with nothing appended.
if len(self.noaa_data_sorted["Data"]) == 1:
self.output_filenames.append(self.filename_txt)
# if there are multiple files that need to be written out, (multiple data table pairs), then append number... | def __get_output_filenames(self) | Set up the output filenames. If more than one file is being written out, we need appended filenames.
:return: | 6.24404 | 5.541901 | 1.126696 |
try:
for _idx, _p in enumerate(self.data_paleos):
_c = {}
try:
_c = self.data_chrons[_idx]
except IndexError:
pass
# create entry in self object collection of data tables
... | 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: | 8.969993 | 6.005548 | 1.493618 |
_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.
for pd_name, pd_data in self.lipd_data["paleoData"].items():
for section_name, se... | def __get_table_count(self) | Check how many tables are in the json
:return int: | 8.100698 | 7.747081 | 1.045645 |
_idx = 1
try:
# start adding the filenames to the JSON and adding the tables to the self tables
for pd_name, pd_data in self.lipd_data[keys[1]].items():
for table_name, table_data in pd_data[keys[2]].items():
if self.append_filenames:
... | def __put_tables_in_self(self, keys) | Metadata is sorted-by-name. Use this to put the table data into the object self.
:param list keys: Paleo or Chron keys
:return none: | 3.572365 | 3.415626 | 1.045889 |
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+")
# self.noaa_file_output[filename] = ""
... | def __create_file(self) | Open text file. Write one section at a time. Close text file. Move completed file to dir_root/noaa/
:return none: | 4.432302 | 4.12511 | 1.074469 |
logger_lpd_noaa.info("writing section: {}".format("top"))
self.__create_blanks("Top", self.noaa_data_sorted["Top"])
# Start writing the NOAA file section by section, starting at the very top of the template.
self.noaa_txt += "# {}".format(self.noaa_data_sorted["Top"]['Study_Nam... | def __write_top(self, filename_txt) | Write the top section of the txt file.
:param int section_num: Section number
:return none: | 5.84099 | 5.777495 | 1.01099 |
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(header)
for key in NOAA_KEYS_BY_SECTION[header]:
key = self.__get_noaa_key_w_contex... | def __write_generic(self, header, d=None) | Write a generic section to the .txt. This function is reused for multiple sections.
:param str header: Header title for this section
:param int section_num:
:param dict d: Section from steps_dict
:return none: | 7.678154 | 7.672194 | 1.000777 |
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"]:
self.noaa_data_sorted["Publication"].append({"pubYear": ""... | def __write_pub(self) | Write pub section. There may be multiple, so write a generic section for each one.
:return none: | 6.299791 | 5.977236 | 1.053964 |
self.__reorganize_funding()
# if funding is empty, insert a blank entry so that it'll still write the empty section on the template.
if not self.noaa_data_sorted["Funding_Agency"]:
self.noaa_data_sorted["Funding_Agency"].append({"grant": "", "agency": ""})
for idx, e... | def __write_funding(self) | Write funding section. There are likely multiple entries.
:param dict d:
:return none: | 6.852111 | 6.49884 | 1.054359 |
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"]
# loop once for paleo, once for chron
for pc in lst_pc:
... | def __write_data(self, idx) | Write out the measurement tables found in paleoData and chronData
:return: | 6.630328 | 5.813252 | 1.140554 |
logger_lpd_noaa.info("writing section: {}".format("Variables"))
# Write the template lines first
self.__write_template_variable()
try:
self.noaa_txt += '#'
# Special NOAA Request: Write the "year" column first always, if available
# write y... | def __write_variables_1(self, table) | Retrieve variables from data table(s) and write to Variables section of txt file.
:param dict table: Paleodata
:return none: | 9.397484 | 8.991767 | 1.045121 |
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 better way of handling this in the future. Need a strict list for this section.
... | def __write_variables_2(self, col) | Use one column of data, to write one line of data in the variables section.
:return none: | 6.349385 | 6.2487 | 1.016113 |
logger_lpd_noaa.info("writing section: data, csv values from file")
# get filename for this table's csv data
# filename = self.__get_filename(table)
# logger_lpd_noaa.info("processing csv file: {}".format(filename))
# # get missing value for this table
# # mv = s... | 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: | 7.34977 | 6.829967 | 1.076106 |
if top:
self.noaa_txt += "\n#"
if multi:
for item in v:
if indent:
self.noaa_txt += "\n# {}: {}".format(str(k), str(item))
else:
self.noaa_txt += "\n# {}: {}".format(str(k), str(item))
el... | def __write_k_v(self, k, v, top=False, bot=False, multi=False, indent=False) | Write a key value pair to the output file. If v is a list, write multiple lines.
:param k: Key
:param v: Value
:param bool top: Write preceding empty line
:param bool bot: Write following empty line
:param bool multi: v is a list
:return none: | 1.875485 | 1.874705 | 1.000416 |
if top:
self.noaa_txt += "\n#"
if nl:
self.noaa_txt += "\n"
self.noaa_txt += "#------------------\n"
if bot:
self.noaa_txt += "\n#"
return | def __write_divider(self, top=False, bot=False, nl=True) | Write a divider line
:return none: | 3.640203 | 3.835313 | 0.949128 |
count = len(l)
if pc == "chron":
self.noaa_txt += "# "
for name in l:
# last column - spacing not important
if count == 1:
self.noaa_txt += "{}\t".format(name)
# all [:-1] columns - fixed spacing to preserve alignment
... | def __write_data_col_header(self, l, pc) | Write the variableNames that are the column header in the "Data" section
:param list l: variableNames
:return none: | 7.214776 | 7.387122 | 0.976669 |
# 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 columns
_count = len(ll)
self.noaa_txt += "# "
... | def __write_data_col_vals(self, ll, pc) | Loop over value arrays and write index by index, to correspond to the rows of a txt file
:param list ll: List of lists, column data
:return: | 5.963492 | 6.21313 | 0.959821 |
if need_id is not None:
need = needs[need_id]
return need[option] | def copy(app, need, needs, option, need_id=None) | Copies the value of one need option to another
.. code-block:: jinja
.. req:: copy-example
:id: copy_1
:tags: tag_1, tag_2, tag_3
:status: open
.. spec:: copy-example implementation
:id: copy_2
:status: [[copy("status", "copy_1")]]
... | 4.679874 | 8.402304 | 0.556975 |
if not links_only:
check_needs = needs.values()
else:
check_needs = []
for link in need["links"]:
check_needs.append(needs[link])
calculated_sum = 0
for check_need in check_needs:
if filter is not None:
try:
if not filter_sin... | 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
:id: sum_input_1
:hours: 7
:collapse: False
.. spec:: Do th... | 3.253027 | 3.401994 | 0.956212 |
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))
return mode | def noaa_prompt() | Convert between NOAA and LiPD file formats.
:return: | 7.711969 | 7.14572 | 1.079243 |
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 | def noaa_prompt_1() | For converting LiPD files to NOAA, we need a couple more pieces of information to create the WDS links
:return str _project: Project name
:return float _version: Version number | 6.515024 | 3.826009 | 1.702825 |
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"]))))
print("Found {} NOAA txt file(s)".format(str(len(files[".txt"]))))
# Process each available file of the specified .lpd or .t... | def noaa_to_lpd(files) | Convert NOAA format to LiPD format
:param dict files: Files metadata
:return None: | 5.233306 | 5.133455 | 1.019451 |
logger_noaa.info("enter process_lpd")
d = D
try:
dsn = get_dsn(D)
# Remove all the characters that are not allowed here. Since we're making URLs, they have to be compliant.
dsn = re.sub(r'[^A-Za-z-.0-9]', '', dsn)
# project = re.sub(r'[^A-Za-z-.0-9]', '', project)
... | 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 | 4.665318 | 4.667105 | 0.999617 |
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 problem writing the NOAA text file: {}: {}".format(filename, e))
return | def __write_noaas(dat, path) | Use the filename - text data pairs to write the data as NOAA text files
:param dict dat: NOAA data to be written
:return none: | 2.847507 | 2.779497 | 1.024469 |
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)
return (version[1], version[2], int(snd))
else:
return parse_version(version_str) | def _parse_java_version(line: str) -> tuple | Return the version number found in the first line of `java -version`
>>> _parse_java_version('openjdk version "11.0.2" 2018-10-16')
(11, 0, 2) | 3.431524 | 3.215568 | 1.06716 |
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_JVM11:
return _find_matching_java_home(lambda ver: ver[0] == 8)
else:
return _find_matching_java_hom... | def find_java_home(cratedb_version: tuple) -> str | Return a path to a JAVA_HOME suites for the given CrateDB version | 4.400138 | 4.035639 | 1.09032 |
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', root_dir=root_dir, base_dir=name)
# drop the .zip extension. only keep .lpd
os.rename("{}.zip".form... | def zipper(root_dir="", name="", path_name_ext="") | Zips up directory back to the original location
:param str root_dir: Root directory of the archive
:param str name: <datasetname>.lpd
:param str path_name_ext: /path/to/filename.lpd | 5.545842 | 4.991062 | 1.111155 |
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.debug("unzip: FileNotFound: {}, {}".format(filename, e))
shutil.rmtree(dir_tmp)
lo... | def unzipper(filename, dir_tmp) | Unzip .lpd file contents to tmp directory.
:param str filename: filename.lpd
:param str dir_tmp: Tmp folder to extract contents to
:return None: | 3.411681 | 3.660357 | 0.932062 |
size = len(sorted_values)
idx = (p / 100.0) * size - 0.5
if idx < 0 or idx > size:
raise ValueError('Too few data points ({}) for {}th percentile'.format(size, p))
return sorted_values[int(idx)] | 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) for 90th percentile | 3.175853 | 2.815555 | 1.127967 |
if sample_mode == 'all':
return All
mode = sample_mode.split(':')
if mode[0] == 'reservoir':
if len(mode) == 2:
return partial(UniformReservoir, size=int(mode[1]))
else:
return UniformReservoir
raise TypeError(f'Invalid sample_mode: {sample_mode}') | 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) | 3.285604 | 2.53425 | 1.29648 |
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.get('formats', 'json')
timezone = opts.get('timezone', 'UTC')
time_from = op... | def query(self, criteria, **opts) | Returns a dict of the query, including the results
:param critera: string of search criteria
:param **opts:
:formats: json/xml (default: json)
:timezone: timezone to use (default: UTC)
:time_from: 15m ago from now (datetime)
:time_t... | 2.35856 | 2.139609 | 1.102332 |
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 in workbook.sheet_names():
# Use this for when we are dealing with older naming styles... | def _get_sheet_metadata(workbook, name) | Get worksheet metadata. The sheet names tell us what type of table it is and where in the LiPD structure the data
should be placed.
Example VALID sheet name:
paleo1measurement1
paleo1model1ensemble1
paleo1model1distribution1
Example INVALID sheet names:
paleo1measurement
paleo1ensemble... | 4.46587 | 4.456594 | 1.002081 |
cont = True
# Loop until valid sheet name is built, or user gives up
while cont:
try:
pc = input("Is this a (p)aleo or (c)hronology sheet?").lower()
if pc in ("p", "c", "paleo", "chron", "chronology"):
tt = input("Is this a (d)istribution, (e)nsemble, (m)... | 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 of paleoData tables
:param int ct_chron: Running count of chronData tables
:ret... | 2.895936 | 2.853494 | 1.014874 |
try:
idx_model = None
idx_table = None
pc = m.group(1)
# Get the model idx number from string if it exists
if m.group(3):
idx_model = int(m.group(4))
# check if there's an index (for distribution tables)
if m.group(6):
idx_table = ... | 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
:param str name: Data set name
:param int ct_paleo: Running count of paleoData ta... | 3.771907 | 3.663313 | 1.029644 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.