code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
global settings
start = clock()
__write_lipd(dat, path)
end = clock()
logger_benchmark.info(log_benchmark("writeLipd", start, end))
return | def writeLipd(dat, path="") | Write LiPD data to file(s)
:param dict dat: Metadata
:param str path: Destination (optional)
:return none: | 8.689067 | 10.234362 | 0.849009 |
global files, cwd, settings
# check that we are using the correct function to load this file type. (i.e. readNoaa for a .txt file)
correct_ext = load_fn_matches_ext(file_path, file_type)
# Check that this path references a file
valid_path = path_type(file_path, "file")
# is the path a fi... | def __universal_read(file_path, file_type) | Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none: | 5.968078 | 5.606708 | 1.064453 |
# is there a file path specified ?
if usr_path:
# Is this a URL? Download the file and return the local path
is_url = re.match(re_url, usr_path)
if is_url:
# The usr_path will now be a local path to a single file. It will trigger the "elif" statement below
us... | def __read(usr_path, file_type) | Determine what path needs to be taken to read in file(s)
:param str usr_path: Path (optional)
:param str file_type: File type to read
:return none: | 3.981311 | 3.962917 | 1.004642 |
global files, settings
_d = {}
try:
if len(files[".lpd"]) == 1:
_d = lipd_read(files[".lpd"][0]["full_path"])
if settings["verbose"]:
print("Finished read: 1 record")
else:
for file in files[".lpd"]:
_d[file["filename_n... | def __read_lipd_contents() | Use the file metadata to read in the LiPD file contents as a dataset library
:return dict: Metadata | 3.342362 | 3.447559 | 0.969487 |
global files
# no path provided. start gui browse
if not usr_path:
# src files could be a list of one, or a list of many. depending how many files the user selects
src_dir, src_files = get_src_or_dst("read", "file")
# check if src_files is a list of multiple files
if sr... | def __read_file(usr_path, file_type) | Universal read file. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none: | 6.157962 | 6.070809 | 1.014356 |
# no path provided. start gui browse
if not usr_path:
# got dir path
usr_path, src_files = get_src_or_dst("read", "directory")
# Check if this is a valid directory path
valid_path = path_type(usr_path, "directory")
# If dir path is valid
if valid_path:
# List all f... | def __read_directory(usr_path, file_type) | Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none: | 5.130409 | 5.123793 | 1.001291 |
global settings
# no path provided. start gui browse
if not usr_path:
# got dir path
usr_path, _ignore = get_src_or_dst("write", "directory")
# Check if this is a valid directory path
valid_path = path_type(usr_path, "directory")
# If dir path is valid
if valid_path:
... | def __write_lipd(dat, usr_path) | Write LiPD data to file, provided an output directory and dataset name.
:param dict dat: Metadata
:param str usr_path: Destination path
:param str dsn: Dataset name of one specific file to write
:return none: | 4.416816 | 4.54784 | 0.97119 |
global settings
if opt is "update":
print("Disclaimer: LiPD files may be updated and modified to adhere to standards\n")
settings["note_update"] = False
if opt is "validate":
print("Note: Use lipd.validate() or www.LiPD.net/create "
"to ensure that your new LiPD fi... | def __disclaimer(opt="") | Print the disclaimers once. If they've already been shown, skip over.
:return none: | 12.058076 | 12.429921 | 0.970085 |
data_file = filename
static_data_file = os.path.join("_static", data_file)
if data_file.split(".")[-1] == "js":
if hasattr(app.builder, "script_files") and static_data_file not in app.builder.script_files:
app.add_javascript(data_file)
elif data_file.split(".")[-1] == "css":
... | def safe_add_file(filename, app) | Adds files to builder resources only, if the given filename was not already registered.
Needed mainly for tests to avoid multiple registration of the same file and therefore also multiple execution
of e.g. a javascript file during page load.
:param filename: filename to remove
:param app: app object
... | 2.571221 | 2.600458 | 0.988757 |
data_file = filename
static_data_file = os.path.join("_static", data_file)
if data_file.split(".")[-1] == "js":
if hasattr(app.builder, "script_files") and static_data_file in app.builder.script_files:
app.builder.script_files.remove(static_data_file)
elif data_file.split(".")[... | def safe_remove_file(filename, app) | Removes a given resource file from builder resources.
Needed mostly during test, if multiple sphinx-build are started.
During these tests js/cass-files are not cleaned, so a css_file from run A is still registered in run B.
:param filename: filename to remove
:param app: app object
:return: None | 2.018497 | 2.035595 | 0.9916 |
if self._shreds is None:
shreds = []
_, contours, _ = cv2.findContours(self._foreground_mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
... | def get_shreds(self, feature_extractors, sheet_name) | Detects shreds in the current sheet and constructs Shred instances.
Caches the results for further invocations.
Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature assignment.
sheet_name: string, included in shred attri... | 1.99072 | 2.123554 | 0.937447 |
assert isinstance(sides, int)
if distance is None:
distance = self.random_int(100, 1000)
else:
# 6371 => earth radius in km
# assert that shape radius is maximum half of earth's circumference
assert isinstance(distance, int)
a... | def geo_shape(self, sides=5, center=None, distance=None) | Return a WKT string for a POLYGON with given amount of sides.
The polygon is defined by its center (random point if not provided) and
the distance (random distance if not provided; in km) of the points to
its center. | 3.789794 | 3.61552 | 1.048202 |
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
executor = Executor(
track_dir=os.path.dirname(track),
log=log,
result_hosts=result_hosts,
crate_root=crate_root,
... | def run_track(track,
result_hosts=None,
crate_root=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
failfast=False,
sample_mode='reservoir') | Execute a track file | 2.568089 | 2.479261 | 1.035828 |
logger_noaa_lpd.info("enter main")
# Run the file through the parser
# Sets self.metadata, Creates CSVs in dir_tmp
os.chdir(self.dir_tmp)
os.mkdir("bag")
os.chdir(self.dir_root)
self.__parse()
os.chdir(self.dir_bag)
# Dump Metadata JSON to... | def main(self) | Convert a NOAA text file into a lipds file.
CSV files will be created if chronology or data sections are available.
:return dict: Metadata Dictionary | 7.277232 | 6.702337 | 1.085775 |
# Format: what, material, error, units, seasonality, archive, detail, method,
# C or N for Character or Numeric data, direction of relation to climate (positive or negative)
d = OrderedDict()
d['number'] = col_count
for idx, var_name in enumerate(NOAA_KEYS_BY_SECTION["Va... | def __create_paleo_col(l, col_count) | Receive split list from separate_data_vars, and turn it into a dictionary for that column
:param list l:
:param int col_count:
:return dict: | 9.974372 | 9.92362 | 1.005114 |
combine = []
if '#' in line:
line = line.replace("#", "")
line = line.lstrip()
if line not in NOAA_EMPTY and line not in EMPTY:
m = re.match(re_var_split, line)
if m:
combine.append(m.group(1))
attr = m.grou... | def __separate_data_vars(line) | For the variables section, clean up the line and return a list of each of the 10 items
:param str line:
:return str: | 4.041422 | 4.036519 | 1.001215 |
try:
return float(number)
except ValueError as e:
logger_noaa_lpd.warn("convert_num: ValueError: {}".format(e))
return number | def __convert_num(number) | All path items are automatically strings. If you think it's an int or float, this attempts to convert it.
:param str number:
:return float or str: | 8.762673 | 8.772324 | 0.9989 |
word = word.lower()
if '_' in word:
split_word = word.split('_')
else:
split_word = word.split()
if len(split_word) > 0:
for i, word in enumerate(split_word):
if i > 0:
split_word[i] = word.title()
s... | def __camel_case(word) | Convert underscore naming into camel case naming
:param str word:
:return str: | 2.388947 | 2.581607 | 0.925372 |
value = ""
unit = ""
r = re.findall(re_name_unit, word)
try:
value = r[0][0]
except IndexError as e:
logger_noaa_lpd.warn("name_unit_regex: IndexError: value: {}, {}, {}".format(word, r, e))
try:
unit = r[0][1]
# Re... | def __name_unit_regex(word) | Split a name and unit that are bunched together (i.e. '250m')
:param str word:
:return str str: | 2.837531 | 2.846647 | 0.996797 |
vals = []
unit = ''
if line != '' or line != ' ':
# If there are parenthesis, remove them
line = line.replace('(', '').replace(')', '')
# When value and units are a range (i.e. '100 m - 200 m').
if re.match(re_name_unit_range, line):
... | def __split_name_unit(self, line) | Split a string that has value and unit as one.
:param str line:
:return str str: | 3.908824 | 3.788297 | 1.031816 |
if '#' in line:
line = line.replace("#", "")
line = line.strip()
if '-----------' in line:
line = ''
return line | def __str_cleanup(line) | Remove the unnecessary characters in the line that we don't want
:param str line:
:return str: | 4.393348 | 4.96253 | 0.885304 |
position = line.find(":")
# If value is -1, that means the item was not found in the string.
if position != -1:
key = line[:position]
value = line[position + 1:]
value = value.lstrip()
return key, value
else:
key = line... | def __slice_key_val(line) | Get the key and value items from a line by looking for and lines that have a ":"
:param str line:
:return str str: Key, Value | 3.338788 | 3.216228 | 1.038107 |
# Sort lat an lon in numerical order
lat.sort()
lon.sort()
geo_dict = {}
# 4 coordinate values
if len(lat) == 2 and len(lon) == 2:
# Matching coordinate pairs. Not 4 unique values.
if lat[0] == lat[1] and lon[0] == lon[1]:
... | def __create_coordinates(self, lat, lon, elev) | GeoJSON standard:
Use to determine 2-point or 4-point coordinates
:param list lat:
:param list lon:
:return dict: | 2.711058 | 2.622957 | 1.033588 |
logger_noaa_lpd.info("enter geo_multipoint")
geo_dict = OrderedDict()
geometry_dict = OrderedDict()
coordinates = []
# bbox = []
temp = [None, None]
# 4 unique values
# # Creates bounding box
# for index, point in enumerate(lat):
#... | def __geo_multipoint(lat, lon, elev) | GeoJSON standard:
Create a geoJson MultiPoint-type dictionary
:param list lat:
:param list lon:
:return dict: | 4.029866 | 4.085151 | 0.986467 |
logger_noaa_lpd.info("enter geo_point")
coordinates = []
geo_dict = OrderedDict()
geometry_dict = OrderedDict()
for index, point in enumerate(lat):
coordinates.append(lat[index])
coordinates.append(lon[index])
if elev:
coordina... | def __geo_point(lat, lon, elev) | GeoJSON standard:
Create a geoJson Point-type dictionary
:param list lat:
:param list lon:
:return dict: | 3.551157 | 3.566712 | 0.995639 |
doi_out = ""
doi_list = []
rm = ["doiId", "doi", "doiUrl"]
# Check if both entries exist
if "doi" and "doiId" in temp_pub:
if temp_pub["doi"] == temp_pub["doiId"]:
# If the entries are the same, then pick one to use
doi_out = t... | def __reorganize_doi(temp_pub) | Create a valid bib json entry for the DOI information.
"DOI" is technically the only valid DOI key, but there are sometimes a doi_id and doi_url entry.
Check for all three and compare them, then keep whichever seems best.
:param dict temp_pub:
:return dict: | 3.659545 | 3.532331 | 1.036014 |
chron_col_list = []
chron_col_ct = 1
for variableName, unit in metadata.items():
temp_dict = OrderedDict()
temp_dict['column'] = chron_col_ct
temp_dict['variableName'] = variableName
temp_dict['unit'] = unit
chron_col_list.appe... | def __create_chron_cols(metadata) | Use to collected chron metadata to create the chron columns
:param dict metadata: key: variable, val: unit (optional)
:return list: list of one dict per column | 2.551301 | 2.424026 | 1.052506 |
d = {}
# Header variables should be tab-delimited. Use regex to split by tabs
m = re.split(re_tab_split, line)
# If there was an output match from the line, then keep going
if m:
# Loop once for each variable in the line
for s in m:
... | def __reorganize_chron_header(line) | Reorganize the list of variables. If there are units given, log them.
:param str line:
:return dict: key: variable, val: units (optional) | 4.766674 | 4.524646 | 1.053491 |
# String SHOULD be semi-colon separated names.
l = []
s = authors.split(";")
for author in s:
try:
l.append({"name": author.strip()})
except AttributeError:
logger_noaa_lpd.warning("reorganize_authors: AttributeError: autho... | def __reorganize_authors(authors) | Separate the string of authors and put it into a BibJSON compliant list
:param str authors:
:return list: List of dictionaries of author names. | 9.776307 | 8.576124 | 1.139945 |
# Keys that we don't want. Reassign data to 'doi' key
_dois = ["DOI", "Doi"]
# Loop for each publication entry
for pub in L["pub"]:
try:
# Is there an identifier in this publication?
if "identifier" in pub:
# Attempt to grab the doi from the id locati... | def fix_doi(L) | DOIs are commonly stored in the BibJson format under "identifier". We want to move these to the root
of the publication under "doi". Make the reassignments necessary and also remove duplicate and unwanted
Doi/DOI keys.
:param dict L: Metadata
:return dict L: Metdata | 5.447021 | 5.077202 | 1.072839 |
version = 1.0
_keys = ["LipdVersion", "LiPDVersion", "lipdVersion", "liPDVersion"]
for _key in _keys:
if _key in L:
version = L[_key]
# Cast the version number to a float
try:
version = float(version)
except AttributeError:
... | def get_lipd_version(L) | Check what version of LiPD this file is using. If none is found, assume it's using version 1.0
:param dict L: Metadata
:return float: | 4.155557 | 4.114464 | 1.009987 |
# Get the lipd version number.
L, version = get_lipd_version(L)
# Update from (N/A or 1.0) to 1.1
if version in [1.0, "1.0"]:
L = update_lipd_v1_1(L)
version = 1.1
# Update from 1.1 to 1.2
if version in [1.1, "1.1"]:
L = update_lipd_v1_2(L)
version = 1.2
... | def update_lipd_version(L) | Metadata is indexed by number at this step.
Use the current version number to determine where to start updating from. Use "chain versioning" to make it
modular. If a file is a few versions behind, convert to EACH version until reaching current. If a file is one
version behind, it will only convert once to ... | 2.440827 | 2.513402 | 0.971125 |
logger_versions.info("enter update_lipd_v1_1")
tmp_all = []
try:
# ChronData is the only structure update
if "chronData" in d:
# As of v1.1, ChronData should have an extra level of abstraction.
# No longer shares the same structure of paleoData
# If... | def update_lipd_v1_1(d) | Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:param dict d: Metadata v1.0
:return... | 4.78943 | 4.07905 | 1.174153 |
# sub routine (recursive): changes all the key names and merges interpretation
d = update_lipd_v1_3_names(d)
# sub routine: changes ensemble and summary table structure
d = update_lipd_v1_3_structure(d)
d["lipdVersion"] = 1.3
if "LiPDVersion" in d:
del d["LiPDVersion"]
return d | def update_lipd_v1_3(d) | Update LiPD v1.2 to v1.3
- Added 'createdBy' key
- Top-level folder inside LiPD archives are named "bag". (No longer <datasetname>)
- .jsonld file is now generically named 'metadata.jsonld' (No longer <datasetname>.lpd )
- All "paleo" and "chron" prefixes are removed from "paleoMeasurementTable", "paleo... | 7.539441 | 6.278011 | 1.200928 |
try:
if isinstance(d, dict):
for k, v in d.items():
# dive down for dictionaries
d[k] = update_lipd_v1_3_names(v)
# see if the key is in the remove list
if k in VER_1_3["swap"]:
# replace the key in the dic... | def update_lipd_v1_3_names(d) | Update the key names and merge interpretation data
:param dict d: Metadata
:return dict d: Metadata | 3.786512 | 3.690486 | 1.02602 |
for key in ["paleoData", "chronData"]:
if key in d:
for entry1 in d[key]:
if "model" in entry1:
for entry2 in entry1["model"]:
for key_table in ["summaryTable", "ensembleTable"]:
if key_table in entry2:
... | def update_lipd_v1_3_structure(d) | Update the structure for summary and ensemble tables
:param dict d: Metadata
:return dict d: Metadata | 3.3795 | 3.093427 | 1.092478 |
logger_csvs.info("enter merge_csv_metadata")
# Add CSV to paleoData
if "paleoData" in d:
d["paleoData"] = _merge_csv_section(d["paleoData"], "paleo", csvs)
# Add CSV to chronData
if "chronData" in d:
d["chronData"] = _merge_csv_section(d["chronData"], "chron", csvs)
logge... | def merge_csv_metadata(d, csvs) | Using the given metadata dictionary, retrieve CSV data from CSV files, and insert the CSV
values into their respective metadata columns. Checks for both paleoData and chronData tables.
:param dict d: Metadata
:return dict: Modified metadata dictionary | 2.910934 | 2.417912 | 1.203904 |
logger_csvs.info("enter merge_csv_section")
try:
# Loop through each table_data in paleoData
for _name, _section in sections.items():
if "measurementTable" in _section:
sections[_name]["measurementTable"] = _merge_csv_table(_section["measurementTable"], pc, csv... | def _merge_csv_section(sections, pc, csvs) | Add csv data to all paleo data tables
:param dict sections: Metadata
:return dict sections: Metadata | 3.646086 | 3.319975 | 1.098227 |
logger_csvs.info("enter merge_csv_model")
try:
for _name, _model in models.items():
if "summaryTable" in _model:
models[_name]["summaryTable"] = _merge_csv_table(_model["summaryTable"], pc, csvs)
if "ensembleTable" in _model:
models[_name][... | def _merge_csv_model(models, pc, csvs) | Add csv data to each column in chron model
:param dict models: Metadata
:return dict models: Metadata | 2.286762 | 2.293672 | 0.996987 |
# Start putting CSV data into corresponding column "values" key
try:
ensemble = is_ensemble(table["columns"])
if ensemble:
# realization columns
if len(table["columns"]) == 1:
for _name, _column in table["columns"].items():
_colum... | def _merge_csv_column(table, csvs) | Add csv data to each column in a list of columns
:param dict table: Table metadata
:param str crumbs: Hierarchy crumbs
:param str pc: Paleo or Chron table type
:return dict: Table metadata with csv "values" entry
:return bool ensemble: Ensemble data or not ensemble data | 5.575527 | 5.182714 | 1.075793 |
logger_csvs.info("enter read_csv_from_file")
d = {}
l = []
try:
logger_csvs.info("open file: {}".format(filename))
with open(filename, 'r') as f:
r = csv.reader(f, delimiter=',')
# Create a dict with X lists corresponding to X columns
for idx, co... | def read_csv_from_file(filename) | Opens the target CSV file and creates a dictionary with one list for each CSV column.
:param str filename:
:return list of lists: column values | 3.929124 | 3.847227 | 1.021287 |
logger_csvs.info("enter write_csv_to_file")
try:
for filename, data in d.items():
try:
l_columns = _reorder_csv(data, filename)
rows = zip(*l_columns)
with open(filename, 'w+') as f:
w = csv.writer(f)
... | def write_csv_to_file(d) | Writes columns of data to a target CSV file.
:param dict d: A dictionary containing one list for every data column. Keys: int, Values: list
:return None: | 5.000703 | 5.043886 | 0.991439 |
logger_csvs.info("enter get_csv_from_metadata")
_csvs = OrderedDict()
_d = copy.deepcopy(d)
try:
if "paleoData" in _d:
# Process paleoData section
_d["paleoData"], _csvs = _get_csv_from_section(_d["paleoData"], "{}.paleo".format(dsn), _csvs)
if "chronData" ... | def get_csv_from_metadata(dsn, d) | Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files.
:param str dsn: Dataset name
:param dict d: Metadata
:return dict _csvs: Csv | 2.572337 | 2.478153 | 1.038006 |
logger_csvs.info("enter get_csv_from_section: {}".format(crumbs))
_idx = 0
try:
# Process the tables in section
for _name, _section in sections.items():
# Process each entry sub-table below if they exist
if "measurementTable" in _section:
section... | def _get_csv_from_section(sections, crumbs, csvs) | Get table name, variable name, and column values from paleo metadata
:param dict sections: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict sections: Metadata
:return dict csvs: Csv | 3.084036 | 3.080992 | 1.000988 |
logger_csvs.info("enter get_csv_from_model: {}".format(crumbs))
_idx = 0
try:
for _name, _model in models.items():
if "distributionTable" in _model:
models[_name]["distributionTable"], csvs = _get_csv_from_table(_model["distributionTable"], "{}{}{}".format(crumbs, _i... | def _get_csv_from_model(models, crumbs, csvs) | Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv | 2.155136 | 2.134599 | 1.009621 |
csvs[filename] = OrderedDict()
try:
if "columns" in table:
try:
for _name, _column in table["columns"].items():
csvs[filename][_name] = {"number": _column["number"], "values": _column["values"]}
except KeyError as ke:
print... | def _get_csv_from_columns(table, filename, csvs) | Search a data tables for column values. Return a dict of column values
:param dict d: Table data
:return dict: Column values. ref by var name | 2.365258 | 2.496912 | 0.947273 |
try:
filename = table["filename"]
except KeyError:
logger_csvs.info("get_filename: KeyError: missing filename for a table")
print("Error: Missing filename for a table")
filename = ""
except Exception as e:
logger_csvs.error("get_filename: {}".format(e))
f... | def _get_filename(table) | Get the filename from a data table. If it doesn't exist, create a new one based on table hierarchy in metadata file.
format: <dataSetName>.<section><idx><table><idx>.csv
example: ODP1098B.Chron1.ChronMeasurementTable.csv
:param dict table: Table data
:param str crumbs: Crumbs
:return str filename: ... | 4.401893 | 4.597095 | 0.957538 |
_ensemble = is_ensemble(d)
_d2 = []
try:
if _ensemble:
# 1 column ensemble: realizations
if len(d) == 1:
for var, data in d.items():
if "values" in data:
_d2 = data["values"]
# 2 column ensemble: dep... | def _reorder_csv(d, filename="") | Preserve the csv column ordering before writing back out to CSV file. Keep column data consistent with JSONLD
column number alignment.
{ "var1" : {"number": 1, "values": [] }, "var2": {"number": 1, "values": [] } }
:param dict d: csv data
:param str filename: Filename
:return dict: csv data | 5.111243 | 4.890638 | 1.045107 |
for l in ll:
try:
if any(math.isnan(float(i)) or isinstance(i, str) for i in l):
return False
# if not all(isinstance(i, (int, float)) or math.isnan(float(i)) for i in l):
# # There is an entry that is a non-numeric entry in this list
... | def _is_numeric_data(ll) | List of lists of csv values data
:param list ll:
:return bool: True, all lists are numeric lists, False, data contains at least one numeric list. | 5.285529 | 5.066124 | 1.043308 |
try:
# Loop for each column available
for num in col_nums:
# first column number in col_nums is usually "2", so backtrack once since ensemble already has one entry
# col_vals is 0-indexed, so backtrack 2 entries
ensemble[num-1] = col_vals[num - 2]
except... | def _merge_ensemble(ensemble, col_nums, col_vals) | The second column is not typical.
"number" is a list of column numbers and "values" is an array of column values.
Before we can write this to csv, it has to match the format the writer expects.
:param dict ensemble: First column data
:param list col_nums: Second column numbers. list of ints
:param l... | 9.978608 | 10.472033 | 0.952882 |
_api_data = []
_j, _csvs = get_csv_from_metadata(L["dataSetName"], L)
_j = rm_values_fields(copy.deepcopy(L))
_j = idx_name_to_num(_j)
# All the filenames being processed
_filenames = ["metadata.jsonld", "bagit.txt", "bag-info.txt", "manifest-md5.txt", "tagmanifest-md5.txt"]\
... | def get_validator_format(L) | Format the LIPD data in the layout that the Lipd.net validator accepts.
'_format' example:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
:param dict L: Metadata
... | 4.415369 | 3.970363 | 1.112082 |
string = ""
# Validation Response output
# string += "VALIDATION RESPONSE\n"
string += "STATUS: {}\n".format(result["status"])
if result["feedback"]:
string += "WARNINGS: {}\n".format(len(result["feedback"]["wrnMsgs"]))
# Loop through and output the Warnings
for msg in r... | def create_detailed_results(result) | Use the result from the API call to create an organized single string output for printing to the console.
:param dict result: Results from API call for one file
:return str string: Organized results for printing | 3.124039 | 3.173202 | 0.984507 |
# print("\nVALIDATOR RESULTS")
# print("======================\n")
if not detailed:
print('FILENAME......................................... STATUS..........')
for entry in results:
try:
if detailed:
print("\n{}".format(entry["filename"]))
... | def display_results(results, detailed=False) | Display the results from the validator in a brief or detailed output
:param list results: API results, sorted by dataset name (multiple)
:param bool detailed: Detailed results on or off
:return none: | 5.4193 | 5.022257 | 1.079057 |
_filename = dsn + ".lpd"
try:
# Contact server and send LiPD metadata as the payload
# print("Sending request to LiPD.net validator...\n")
api_data = json.dumps(api_data)
# The payload that is going to be sent with the JSON request
payload = {'json_payload': api_da... | def call_validator_api(dsn, api_data) | Single call to the lipd.net validator API
'api_data' format:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
Result format:
{"dat": <dict>, "feedback": <dict>, ... | 3.243048 | 2.888029 | 1.122928 |
if current_needlist["sort_by"] is not None:
if current_needlist["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needlist["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs_by_options = []... | def procces_filters(all_needs, current_needlist) | Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters | 2.345472 | 2.32671 | 1.008064 |
if filter_string is None or filter_string == "":
return needs
found_needs = []
for filter_need in needs:
try:
if filter_single_need(filter_need, filter_string):
found_needs.append(filter_need)
except Exception as e:
logger.warning("Filt... | def filter_needs(needs, filter_string="", filter_parts=True, merge_part_with_parent=True) | Filters given needs based on a given filter string.
Returns all needs, which pass the given filter.
:param merge_part_with_parent: If True, need_parts inherit options from their parent need
:param filter_parts: If True, need_parts get also filtered
:param filter_string: strings, which gets evaluated ag... | 2.846648 | 3.044162 | 0.935117 |
filter_context = need.copy()
filter_context["search"] = re.search
result = False
try:
result = bool(eval(filter_string, None, filter_context))
except Exception as e:
raise NeedInvalidFilter("Filter {0} not valid: Error: {1}".format(filter_string, e))
return result | def filter_single_need(need, filter_string="") | Checks if a single need/need_part passes a filter_string
:param need: need or need_part
:param filter_string: string, which is used as input for eval()
:return: True, if need as passed the filter_string, else False | 5.023893 | 4.933136 | 1.018398 |
level = logging.INFO
if debug:
level = logging.DEBUG
return level | def get_logging_level(debug) | Returns logging level based on boolean | 2.949646 | 2.720049 | 1.084409 |
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
do_run_spec(
spec=spec,
benchmark_hosts=benchmark_hosts,
log=log,
result_hosts=result_hosts,
action=action,
... | def run_spec(spec,
benchmark_hosts,
result_hosts=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
action=None,
fail_if=None,
sample_mode='reservoir') | Run a spec file, executing the statements on the benchmark_hosts.
Short example of a spec file:
[setup]
statement_files = ["sql/create_table.sql"]
[[setup.data_files]]
target = "t"
source = "data/t.json"
[[queries]]
statement = "select count(*)... | 1.933787 | 2.47641 | 0.780883 |
dst_path = ""
if "MD982181" not in src_url:
dsn = input("Please enter the dataset name for this file (Name.Location.Year) : ")
dst_path = os.path.join(dst_dir, dsn + ".lpd")
try:
print("downloading file from url...")
urllib.request.urlretrieve(src_url, dst_pa... | def download_from_url(src_url, dst_dir) | Use the given URL and destination to download and save a file
:param str src_url: Direct URL to lipd file download
:param str dst_path: Local path to download file to, including filename and ext. ex. /path/to/filename.lpd
:return none: | 5.609284 | 5.412009 | 1.036451 |
logger_doi_main.info("enter doi_main")
print("Found {0} {1} file(s)".format(str(len(files[".lpd"])), 'LiPD'))
force = prompt_force()
for file in files[".lpd"]:
# Unzip file and get tmp directory path
dir_tmp = create_tmp_dir()
unzipper(file["filename_ext"], dir_tmp)
... | def doi_main(files) | Main function that controls the script. Take in directory containing the .lpd file(s). Loop for each file.
:return None: | 3.246807 | 3.173202 | 1.023196 |
logger_doi_main.info("enter process_lpd")
dir_root = os.getcwd()
dir_bag = os.path.join(dir_tmp, name)
dir_data = os.path.join(dir_bag, 'data')
# Navigate down to jLD file
# dir : dir_root -> dir_data
os.chdir(dir_data)
# Open jld file and read in the contents. Execute DOI Resolve... | def process_lpd(name, dir_tmp) | Opens up json file, invokes doi_resolver, closes file, updates changelog, cleans directory, and makes new bag.
:param str name: Name of current .lpd file
:param str dir_tmp: Path to tmp directory
:return none: | 6.506062 | 5.504209 | 1.182016 |
logger_doi_main.info("enter prompt_force")
count = 0
print("Do you want to force updates for previously resolved files? (y/n)")
while True:
force = input("> ")
try:
if count == 2:
return True
elif force.lower() in ('y', 'yes'):
... | def prompt_force() | Ask the user if they want to force update files that were previously resolved
:return bool: response | 3.621554 | 3.169038 | 1.142793 |
sections = []
current_node = need_info['target_node']
while current_node:
if isinstance(current_node, nodes.section):
title = current_node.children[0].astext()
# If using auto-section numbering, then Sphinx inserts
# multiple non-breaking space unicode charac... | def get_sections(need_info) | Gets the hierarchy of the section nodes as a list starting at the
section of the current need and then its parent sections | 5.037155 | 5.004033 | 1.006619 |
if not hasattr(env, 'needs_all_needs'):
return
env.needs_all_needs = {key: need for key, need in env.needs_all_needs.items() if need['docname'] != docname} | def purge_needs(app, env, docname) | Gets executed, if a doc file needs to be purged/ read in again.
So this code delete all found needs for the given docname. | 2.572999 | 2.637356 | 0.975598 |
needs = getattr(app.builder.env, 'needs_all_needs', {})
for key, need_info in needs.items():
sections = get_sections(need_info)
need_info['sections'] = sections
need_info['section_name'] = sections[0] if sections else "" | def add_sections(app, doctree, fromdocname) | Add section titles to the needs as additional attributes that can
be used in tables and filters | 4.641121 | 3.83953 | 1.208773 |
if not app.config.needs_include_needs:
for node in doctree.traverse(Need):
node.parent.remove(node)
return
env = app.builder.env
# If no needs were defined, we do not need to do anything
if not hasattr(env, "needs_all_needs"):
return
needs = env.needs_all_... | def process_need_nodes(app, doctree, fromdocname) | Event handler to add title meta data (status, tags, links, ...) information to the Need node.
:param app:
:param doctree:
:param fromdocname:
:return: | 4.011719 | 4.066923 | 0.986426 |
if env.needs_workflow['backlink_creation']:
return
needs = env.needs_all_needs
for key, need in needs.items():
for link in need["links"]:
link_main = link.split('.')[0]
try:
link_part = link.split('.')[1]
except IndexError:
... | def create_back_links(env) | Create back-links in all found needs.
But do this only once, as all needs are already collected and this sorting is for all
needs and not only for the ones of the current document.
:param env: sphinx enviroment
:return: None | 2.835391 | 2.618545 | 1.082811 |
# need title calculation
title_type = '{}: '.format(need_data["type_name"])
title_headline = need_data["title"]
title_id = "{}".format(need_data["id"])
title_spacer = " "
# need title
node_type = nodes.inline(title_type, title_type, classes=["needs-type"])
node_title = nodes.inline... | def construct_headline(need_data, app) | Constructs the node-structure for the headline/title container
:param need_data: need_info container
:return: node | 2.707003 | 2.675236 | 1.011874 |
open_func_string = False
new_list = []
for element in list:
if '[[' in element:
open_func_string = True
new_link = [element]
elif ']]' in element:
new_link.append(element)
open_func_string = False
element = ",".join(new_link)
... | def _fix_list_dyn_func(list) | This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function fixes the above list to the following:
... | 2.451064 | 2.24698 | 1.090826 |
self.body.append(self.starttag(node, 'div', '', CLASS='need')) | def html_visit(self, node) | Visitor method for Need-node of builder 'html'.
Does only wrap the Need-content into an extra <div> with class=need | 6.476747 | 3.544995 | 1.827011 |
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extra options with empty value to need_info.
# Needed for filters, which need to access these empty/not use... | def merge_extra_options(self, needs_info) | Add any extra options introduced via options_ext to needs_info | 4.548318 | 4.263093 | 1.066906 |
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already exists in needs_info, this global_option got overwritten manually in current need
... | def merge_global_options(self, needs_info) | Add all global defined options to needs_info | 4.579756 | 4.164012 | 1.099842 |
if len(self.arguments) > 0: # a title was passed
if 'title_from_content' in self.options:
self.log.warning(
'Needs: need "{}" has :title_from_content: set, '
'but a title was provided. (see file {})'
.format(se... | def _get_full_title(self) | Determines the title for the need in order of precedence:
directive argument, first sentence of requirement (if
`:title_from_content:` was set, and '' if no title is to be derived. | 5.553538 | 3.986892 | 1.392949 |
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
# Ok, this is really dirty.
# If we replace a node, docutils checks, if it will not lose any attributes.
# But this is here the case, because we are using the at... | def process_needlist(app, doctree, fromdocname) | Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location. | 3.151165 | 3.164829 | 0.995683 |
if not version:
return None
parts = version.split('.')
missing = 3 - len(parts)
return tuple(int(i) for i in parts + ([0] * missing)) | def parse_version(version: str) -> tuple | Parse a string formatted X[.Y.Z] version number into a tuple
>>> parse_version('10.2.3')
(10, 2, 3)
>>> parse_version('12')
(12, 0, 0) | 3.535776 | 3.69489 | 0.956937 |
parts = fq_table.split('.')
if len(parts) == 1:
return 'doc', parts[0]
elif len(parts) == 2:
return parts[0], parts[1]
else:
raise ValueError | def parse_table(fq_table: str) -> Tuple[str, str] | Parse a tablename into tuple(<schema>, <table>).
Schema defaults to doc if the table name doesn't contain a schema.
>>> parse_table('x.users')
('x', 'users')
>>> parse_table('users')
('doc', 'users') | 2.378212 | 2.293986 | 1.036716 |
stmt_dict = defaultdict(list)
for stmt, args in queries:
bulk_args = stmt_dict[stmt]
bulk_args.append(args)
if len(bulk_args) == bulk_size:
yield stmt, bulk_args
del stmt_dict[stmt]
for stmt, bulk_args in stmt_dict.items():
yield stmt, bulk_args | def as_bulk_queries(queries, bulk_size) | Group a iterable of (stmt, args) by stmt into (stmt, bulk_args).
bulk_args will be a list of the args grouped by stmt.
len(bulk_args) will be <= bulk_size | 2.305847 | 1.880917 | 1.225917 |
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line | def get_lines(filename: str) -> Iterator[str] | Create an iterator that returns the lines of a utf-8 encoded file. | 1.691128 | 1.52534 | 1.108689 |
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield ' '.join(parts)
parts.clear()
if parts:
yield ' '.join(par... | def as_statements(lines: Iterator[str]) -> Iterator[str] | Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['... | 2.146895 | 2.71874 | 0.789665 |
sublist = []
for i in iterable:
if pred(i):
yield sublist
sublist = []
else:
sublist.append(i)
yield sublist | def break_iterable(iterable, pred) | Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]] | 2.229143 | 3.239875 | 0.688034 |
logger_bagit.info("enter create_bag")
# if not dir_bag:
# dir_bag = os.getcwd()
try:
bag = bagit.make_bag(dir_bag, {'Name': 'LiPD Project', 'Reference': 'www.lipds.net', 'DOI-Resolved': 'True'})
logger_bagit.info("created bag")
return bag
except FileNotFoundError as ... | def create_bag(dir_bag) | Create a Bag out of given files.
:param str dir_bag: Directory that contains csv, jsonld, and changelog files.
:return obj: Bag | 4.388031 | 4.617478 | 0.950309 |
logger_bagit.info("enter open_bag")
try:
bag = bagit.Bag(dir_bag)
logger_bagit.info("opened bag")
return bag
except Exception as e:
print("Error: failed to open bagit bag")
logger_bagit.debug("failed to open bag, {}".format(e))
return None | def open_bag(dir_bag) | Open Bag at the given path
:param str dir_bag: Path to Bag
:return obj: Bag | 3.92417 | 4.603518 | 0.852429 |
logger_bagit.info("validate_md5")
if bag.is_valid():
print("Valid md5")
# for path, fixity in bag.entries.items():
# print("path:{}\nmd5:{}\n".format(path, fixity["md5"]))
else:
print("Invalid md5")
logger_bagit.debug("invalid bag")
return | def validate_md5(bag) | Check if Bag is valid
:param obj bag: Bag
:return None: | 4.774278 | 5.050514 | 0.945305 |
if 'DOI-Resolved' in bag.info:
logger_bagit.info("bagit resolved_flag: true")
return True
logger_bagit.info("bagit resolved_flag: false")
return False | def resolved_flag(bag) | Check DOI flag in bag.info to see if doi_resolver has been previously run
:param obj bag: Bag
:return bool: Flag | 6.339163 | 4.73901 | 1.337655 |
logger_bagit.info("enter finish_bag")
# Create a bag for the 3 files
new_bag = create_bag(dir_bag)
open_bag(dir_bag)
new_bag.save(manifests=True)
logger_bagit.info("exit finish_bag")
return | def finish_bag(dir_bag) | Closing steps for creating a bag
:param obj dir_bag:
:return None: | 5.781664 | 6.19301 | 0.933579 |
batch = True
invalid = True
_option = ""
try:
while invalid:
print("\nChoose a loading option:\n1. Select specific file(s)\n2. Load entire folder")
_option = input("Option: ")
# these are the only 2 valid options. if this is true, then stop prompting
... | def _ask_how_many() | Ask user if they want to load in one file or do a batch process of a whole directory. Default to batch "m" mode.
:return str: Path or none | 8.765304 | 8.123304 | 1.079032 |
_go_to_package()
logger_directory.info("enter browse_dialog")
_path_bytes = subprocess.check_output(['python', 'gui_dir_browse.py'], shell=False)
_path = _fix_path_bytes(_path_bytes, file=False)
if len(_path) >= 1:
_path = _path[0]
else:
_path = ""
logger_directory.info(... | def browse_dialog_dir() | Open up a GUI browse dialog window and let to user pick a target directory.
:return str: Target directory path | 4.821555 | 4.983398 | 0.967524 |
logger_directory.info("enter browse_dialog")
# We make files a list, because the user can multi-select files.
_files = []
_path = ""
try:
_go_to_package()
_path_bytes = subprocess.check_output(['python', 'gui_file_browse.py'])
_path = _fix_path_bytes(_path_bytes)
... | def browse_dialog_file() | Open up a GUI browse dialog window and let to user select one or more files
:return str _path: Target directory path
:return list _files: List of selected files | 4.759046 | 4.588182 | 1.03724 |
logger_directory.info("enter check_file_age")
# Multiply days given by time for one day.
t = days * 60 * 60 * 24
now = time.time()
specified_time = now - t
try:
if os.path.getctime(filename) < specified_time:
# File found and out of date
logger_directory.info... | def check_file_age(filename, days) | Check if the target file has an older creation date than X amount of time.
i.e. One day: 60*60*24
:param str filename: Target filename
:param int days: Limit in number of days
:return bool: True - older than X time, False - not older than X time | 3.013841 | 3.094067 | 0.974071 |
obj = {}
try:
os.chdir(cwd)
# Special case: User uses gui to mult-select 2+ files. You'll be given a list of file paths.
if new_files:
for full_path in new_files:
# Create the file metadata for one file, and append it to the existing files.
... | def collect_metadata_files(cwd, new_files, existing_files) | Collect all files from a given path. Separate by file type, and return one list for each type
If 'files' contains specific
:param str cwd: Directory w/ target files
:param list new_files: Specific new files to load
:param dict existing_files: Files currently loaded, separated by type
:return list: A... | 6.453496 | 6.143855 | 1.050398 |
fne = os.path.basename(full_path)
fn = os.path.splitext(fne)[0]
obj = {"full_path": full_path, "filename_ext": fne, "filename_no_ext": fn, "dir": os.path.dirname(full_path)}
return obj | def collect_metadata_file(full_path) | Create the file metadata and add it to the appropriate section by file-type
:param str full_path:
:param dict existing_files:
:return dict existing files: | 2.891783 | 3.54207 | 0.81641 |
logger_directory.info("enter dir_cleanup")
# dir : dir_data -> dir_bag
os.chdir(dir_bag)
# Delete files in dir_bag
for file in os.listdir(dir_bag):
if file.endswith('.txt'):
os.remove(os.path.join(dir_bag, file))
logger_directory.info("deleted files in dir_bag")
# M... | def dir_cleanup(dir_bag, dir_data) | Moves JSON and csv files to bag root, then deletes all the metadata bag files. We'll be creating a new bag with
the data files, so we don't need the other text files and such.
:param str dir_bag: Path to root of Bag
:param str dir_data: Path to Bag /data subdirectory
:return None: | 2.51198 | 2.613479 | 0.961163 |
head, tail = ntpath.split(path)
return head, tail or ntpath.basename(head) | def filename_from_path(path) | Extract the file name from a given file path.
:param str path: File path
:return str: File name with extension | 3.110699 | 5.382808 | 0.577895 |
_dir = os.getcwd()
_files = os.listdir()
# Look for a jsonld file
for _file in _files:
if _file.endswith(".jsonld"):
return os.getcwd()
# No jsonld file found, try to chdir into "bag" (LiPD v1.3)
if "bag" in _files:
os.chdir("bag")
_dir = find_files()
... | def find_files() | Search for the directory containing jsonld and csv files. chdir and then quit.
:return none: | 4.934411 | 4.566796 | 1.080497 |
filenames = []
try:
filenames = d.keys()
if name:
filenames = [os.path.join(name, "data", filename) for filename in filenames]
if csvs:
lst = [i for i in csvs if not i.endswith("csv")]
filenames = lst + filenames
except Exception as e:
... | def get_filenames_generated(d, name="", csvs="") | Get the filenames that the LiPD utilities has generated (per naming standard), as opposed to the filenames that
originated in the LiPD file (that possibly don't follow the naming standard)
:param dict d: Data
:param str name: LiPD dataset name to prefix
:param list csvs: Filenames list to merge with
... | 3.705104 | 3.817037 | 0.970675 |
_filenames = []
try:
# in the top level, list all files and skip the "data" directory
_top = [os.path.join(name, f) for f in os.listdir(path) if f != "data"]
# in the data directory, list all files
_dir_data = [os.path.join(name, "data", f) for f in os.listdir(os.path.join(p... | def get_filenames_in_lipd(path, name="") | List all the files contained in the LiPD archive. Bagit, JSON, and CSV
:param str path: Directory to be listed
:param str name: LiPD dataset name, if you want to prefix it to show file hierarchy
:return list: Filenames found | 2.909338 | 2.935526 | 0.991079 |
logger_directory.info("enter set_src_or_dst")
_path = ""
_files = ""
invalid = True
count = 0
# Did you forget to enter a mode?
if not mode:
invalid = False
# Special case for gui reading a single or multi-select file(s).
elif mode == "read" and path_type == "file":
... | def get_src_or_dst(mode, path_type) | User sets the path to a LiPD source location
:param str mode: "read" or "write" mode
:param str path_type: "directory" or "file"
:return str path: dir path to files
:return list files: files chosen | 7.093487 | 6.773027 | 1.047314 |
_words = {"read": "from", "write": "to"}
# print(os.getcwd())
prompt = "Where would you like to {} your file(s) {}?\n" \
"1. Desktop ({})\n" \
"2. Downloads ({})\n" \
"3. Current ({})\n" \
"4. Browse".format(mode, _words[mode],
... | def get_src_or_dst_prompt(mode) | String together the proper prompt based on the mode
:param str mode: "read" or "write"
:return str prompt: The prompt needed | 3.984328 | 4.025204 | 0.989845 |
_path = ""
print(prompt)
option = input("Option: ")
print("\n")
if option == '1':
# Set the path to the system desktop folder.
logger_directory.info("1: desktop")
_path = os.path.expanduser('~/Desktop')
elif option == '2':
# Set the path to the system downloa... | def get_src_or_dst_path(prompt, count) | Let the user choose a path, and store the value.
:return str _path: Target directory
:return str count: Counter for attempted prompts | 3.70362 | 3.502048 | 1.057559 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.