repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | LPD_NOAA.__write_variables_2 | def __write_variables_2(self, col):
"""
Use one column of data, to write one line of data in the variables section.
:return none:
"""
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.
try:
# First entry: Add extra hash and tab
if entry == 'shortname':
# DEPRECATED: Fixed spacing for variable names.
# self.noaa_txt.write('{:<20}'.format('#' + str(col[entry])))
# Fluid spacing for variable names. Spacing dependent on length of variable names.
self.noaa_txt += '{}\t'.format('#' + str(col[entry]))
# Last entry: No space or comma
elif entry == "additional":
e = " "
for item in ["notes", "uncertainty"]:
try:
if col[item]:
e += str(col[item]).replace(",", ";") + "; "
except KeyError:
pass
self.noaa_txt += '{} '.format(e)
# elif entry == 'notes':
# self.noaa_txt.write('{} '.format(str(col[entry])))
else:
# This is for any entry that is not first or last in the line ordering
# Account for nested entries.
# if entry == "uncertainty":
# try:
# e = str(col["calibration"][entry])
# except KeyError:
# e = ""
if entry == "seasonality":
try:
e = str(col["climateInterpretation"][entry])
except KeyError:
e = ""
elif entry == "archive":
e = self.noaa_data_sorted["Top"]["Archive"]
elif entry == "dataType":
# Lipd uses real data types (floats, ints), NOAA wants C or N (character or numeric)
if col[entry] == "float":
e = "N"
else:
e = "C"
else:
e = str(col[entry])
try:
e = e.replace(",", ";")
except AttributeError as ee:
logger_lpd_noaa.warn("write_variables_2: AttributeError: {}, {}".format(e, ee))
self.noaa_txt += '{}, '.format(e)
except KeyError as e:
self.noaa_txt += '{:<0}'.format(',')
logger_lpd_noaa.info("write_variables: KeyError: missing {}".format(e))
self.noaa_txt += '\n#'
return | python | def __write_variables_2(self, col):
"""
Use one column of data, to write one line of data in the variables section.
:return none:
"""
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.
try:
# First entry: Add extra hash and tab
if entry == 'shortname':
# DEPRECATED: Fixed spacing for variable names.
# self.noaa_txt.write('{:<20}'.format('#' + str(col[entry])))
# Fluid spacing for variable names. Spacing dependent on length of variable names.
self.noaa_txt += '{}\t'.format('#' + str(col[entry]))
# Last entry: No space or comma
elif entry == "additional":
e = " "
for item in ["notes", "uncertainty"]:
try:
if col[item]:
e += str(col[item]).replace(",", ";") + "; "
except KeyError:
pass
self.noaa_txt += '{} '.format(e)
# elif entry == 'notes':
# self.noaa_txt.write('{} '.format(str(col[entry])))
else:
# This is for any entry that is not first or last in the line ordering
# Account for nested entries.
# if entry == "uncertainty":
# try:
# e = str(col["calibration"][entry])
# except KeyError:
# e = ""
if entry == "seasonality":
try:
e = str(col["climateInterpretation"][entry])
except KeyError:
e = ""
elif entry == "archive":
e = self.noaa_data_sorted["Top"]["Archive"]
elif entry == "dataType":
# Lipd uses real data types (floats, ints), NOAA wants C or N (character or numeric)
if col[entry] == "float":
e = "N"
else:
e = "C"
else:
e = str(col[entry])
try:
e = e.replace(",", ";")
except AttributeError as ee:
logger_lpd_noaa.warn("write_variables_2: AttributeError: {}, {}".format(e, ee))
self.noaa_txt += '{}, '.format(e)
except KeyError as e:
self.noaa_txt += '{:<0}'.format(',')
logger_lpd_noaa.info("write_variables: KeyError: missing {}".format(e))
self.noaa_txt += '\n#'
return | [
"def",
"__write_variables_2",
"(",
"self",
",",
"col",
")",
":",
"col",
"=",
"self",
".",
"__convert_keys_1",
"(",
"\"Variables\"",
",",
"col",
")",
"# Write one line for each column. One line has all metadata for one column.",
"for",
"entry",
"in",
"NOAA_KEYS_BY_SECTION"... | Use one column of data, to write one line of data in the variables section.
:return none: | [
"Use",
"one",
"column",
"of",
"data",
"to",
"write",
"one",
"line",
"of",
"data",
"in",
"the",
"variables",
"section",
".",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1344-L1406 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | LPD_NOAA.__write_columns | def __write_columns(self, pc, table):
"""
Read numeric data from csv and write to the bottom section of the txt file.
:param dict table: Paleodata dictionary
:return none:
"""
logger_lpd_noaa.info("writing section: data, csv values from file")
# get filename for 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 = self.__get_mv(table)
# # write template lines
# # self.__write_template_paleo(mv)
if pc == "paleo":
self.__write_template_paleo()
elif pc == "chron":
self.__write_template_chron()
# continue if csv exists
if self._values_exist(table):
# logger_lpd_noaa.info("_write_columns: csv data exists: {}".format(filename))
# sort the dictionary so the year column is first
_csv_data_by_name = self.__put_year_col_first(table["columns"])
# now split the sorted dictionary back into two lists (easier format to write to file)
_names, _data = self.__rm_names_on_csv_cols(_csv_data_by_name)
# write column variableNames
self.__write_data_col_header(_names, pc)
# write data columns index by index
self.__write_data_col_vals(_data, pc)
return | python | def __write_columns(self, pc, table):
"""
Read numeric data from csv and write to the bottom section of the txt file.
:param dict table: Paleodata dictionary
:return none:
"""
logger_lpd_noaa.info("writing section: data, csv values from file")
# get filename for 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 = self.__get_mv(table)
# # write template lines
# # self.__write_template_paleo(mv)
if pc == "paleo":
self.__write_template_paleo()
elif pc == "chron":
self.__write_template_chron()
# continue if csv exists
if self._values_exist(table):
# logger_lpd_noaa.info("_write_columns: csv data exists: {}".format(filename))
# sort the dictionary so the year column is first
_csv_data_by_name = self.__put_year_col_first(table["columns"])
# now split the sorted dictionary back into two lists (easier format to write to file)
_names, _data = self.__rm_names_on_csv_cols(_csv_data_by_name)
# write column variableNames
self.__write_data_col_header(_names, pc)
# write data columns index by index
self.__write_data_col_vals(_data, pc)
return | [
"def",
"__write_columns",
"(",
"self",
",",
"pc",
",",
"table",
")",
":",
"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(\"... | Read numeric data from csv and write to the bottom section of the txt file.
:param dict table: Paleodata dictionary
:return none: | [
"Read",
"numeric",
"data",
"from",
"csv",
"and",
"write",
"to",
"the",
"bottom",
"section",
"of",
"the",
"txt",
"file",
".",
":",
"param",
"dict",
"table",
":",
"Paleodata",
"dictionary",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1408-L1443 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | LPD_NOAA.__write_k_v | 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:
"""
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))
else:
if indent:
self.noaa_txt += "\n# {}: {}".format(str(k), str(v))
else:
self.noaa_txt += "\n# {}: {}".format(str(k), str(v))
if bot:
self.noaa_txt += "\n#"
return | python | 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:
"""
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))
else:
if indent:
self.noaa_txt += "\n# {}: {}".format(str(k), str(v))
else:
self.noaa_txt += "\n# {}: {}".format(str(k), str(v))
if bot:
self.noaa_txt += "\n#"
return | [
"def",
"__write_k_v",
"(",
"self",
",",
"k",
",",
"v",
",",
"top",
"=",
"False",
",",
"bot",
"=",
"False",
",",
"multi",
"=",
"False",
",",
"indent",
"=",
"False",
")",
":",
"if",
"top",
":",
"self",
".",
"noaa_txt",
"+=",
"\"\\n#\"",
"if",
"mult... | 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: | [
"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",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1499-L1524 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | LPD_NOAA.__write_divider | def __write_divider(self, top=False, bot=False, nl=True):
"""
Write a divider line
:return none:
"""
if top:
self.noaa_txt += "\n#"
if nl:
self.noaa_txt += "\n"
self.noaa_txt += "#------------------\n"
if bot:
self.noaa_txt += "\n#"
return | python | def __write_divider(self, top=False, bot=False, nl=True):
"""
Write a divider line
:return none:
"""
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",
")",
":",
"if",
"top",
":",
"self",
".",
"noaa_txt",
"+=",
"\"\\n#\"",
"if",
"nl",
":",
"self",
".",
"noaa_txt",
"+=",
"\"\\n\"",
"se... | Write a divider line
:return none: | [
"Write",
"a",
"divider",
"line",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1534-L1546 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | LPD_NOAA.__write_data_col_header | 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:
"""
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
else:
self.noaa_txt += "{:<15}".format(name)
count -= 1
self.noaa_txt += '\n' | python | 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:
"""
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
else:
self.noaa_txt += "{:<15}".format(name)
count -= 1
self.noaa_txt += '\n' | [
"def",
"__write_data_col_header",
"(",
"self",
",",
"l",
",",
"pc",
")",
":",
"count",
"=",
"len",
"(",
"l",
")",
"if",
"pc",
"==",
"\"chron\"",
":",
"self",
".",
"noaa_txt",
"+=",
"\"# \"",
"for",
"name",
"in",
"l",
":",
"# last column - spacing not imp... | Write the variableNames that are the column header in the "Data" section
:param list l: variableNames
:return none: | [
"Write",
"the",
"variableNames",
"that",
"are",
"the",
"column",
"header",
"in",
"the",
"Data",
"section",
":",
"param",
"list",
"l",
":",
"variableNames",
":",
"return",
"none",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1548-L1566 |
nickmckay/LiPD-utilities | Python/lipd/lpd_noaa.py | LPD_NOAA.__write_data_col_vals | 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:
"""
# 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 += "# "
for col in ll:
self.noaa_txt += "{}\t".format(str(col["values"][idx]))
_count -= 1
if (idx < _items_in_cols):
self.noaa_txt += '\n'
except IndexError:
logger_lpd_noaa("_write_data_col_vals: IndexError: couldn't get length of columns")
return | python | 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:
"""
# 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 += "# "
for col in ll:
self.noaa_txt += "{}\t".format(str(col["values"][idx]))
_count -= 1
if (idx < _items_in_cols):
self.noaa_txt += '\n'
except IndexError:
logger_lpd_noaa("_write_data_col_vals: IndexError: couldn't get length of columns")
return | [
"def",
"__write_data_col_vals",
"(",
"self",
",",
"ll",
",",
"pc",
")",
":",
"# all columns should have the same amount of values. grab that number",
"try",
":",
"_items_in_cols",
"=",
"len",
"(",
"ll",
"[",
"0",
"]",
"[",
"\"values\"",
"]",
")",
"for",
"idx",
"... | 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: | [
"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",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/lpd_noaa.py#L1568-L1591 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/functions/common.py | copy | 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")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
.. 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")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
:param option: Name of the option to copy
:param need_id: id of the need, which contains the source option. If None, current need is taken
:return: string of copied need option
"""
if need_id is not None:
need = needs[need_id]
return need[option] | python | 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")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
.. 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")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
:param option: Name of the option to copy
:param need_id: id of the need, which contains the source option. If None, current need is taken
:return: string of copied need option
"""
if need_id is not None:
need = needs[need_id]
return need[option] | [
"def",
"copy",
"(",
"app",
",",
"need",
",",
"needs",
",",
"option",
",",
"need_id",
"=",
"None",
")",
":",
"if",
"need_id",
"is",
"not",
"None",
":",
"need",
"=",
"needs",
"[",
"need_id",
"]",
"return",
"need",
"[",
"option",
"]"
] | 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")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
.. 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")]]
:links: copy_1
:comment: [[copy("id")]]
Copies status of ``copy_1`` to own status.
Sets also a comment, which copies the id of own need.
.. test:: test of specification and requirement
:id: copy_3
:links: copy_2; [[copy('links', 'copy_2')]]
:tags: [[copy('tags', 'copy_1')]]
Set own link to ``copy_2`` and also copies all links from it.
Also copies all tags from copy_1.
:param option: Name of the option to copy
:param need_id: id of the need, which contains the source option. If None, current need is taken
:return: string of copied need option | [
"Copies",
"the",
"value",
"of",
"one",
"need",
"option",
"to",
"another"
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/common.py#L33-L92 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/functions/common.py | check_linked_values | def check_linked_values(app, need, needs, result, search_option, search_value, filter_string=None, one_hit=False):
"""
Returns a specific value, if for all linked needs a given option has a given value.
The linked needs can be filtered by using the ``filter`` option.
If ``one_hit`` is set to True, only one linked need must have a positive match for the searched value.
**Examples**
**Needs used as input data**
.. code-block:: jinja
.. req:: Input A
:id: clv_A
:status: in progress
.. req:: Input B
:id: clv_B
:status: in progress
.. spec:: Input C
:id: clv_C
:status: closed
.. req:: Input A
:id: clv_A
:status: in progress
:collapse: False
.. req:: Input B
:id: clv_B
:status: in progress
:collapse: False
.. spec:: Input C
:id: clv_C
:status: closed
:collapse: False
**Example 1: Positive check**
Status gets set to *progress*.
.. code-block:: jinja
.. spec:: result 1: Positive check
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
.. spec:: result 1: Positive check
:id: clv_1
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 2: Negative check**
Status gets not set to *progress*, because status of linked need *clv_C* does not match *"in progress"*.
.. code-block:: jinja
.. spec:: result 2: Negative check
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
.. spec:: result 2: Negative check
:id: clv_2
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 3: Positive check thanks of used filter**
status gets set to *progress*, because linked need *clv_C* is not part of the filter.
.. code-block:: jinja
.. spec:: result 3: Positive check thanks of used filter
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
.. spec:: result 3: Positive check thanks of used filter
:id: clv_3
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
:collapse: False
**Example 4: Positive check thanks of one_hit option**
Even *clv_C* has not the searched status, status gets anyway set to *progress*.
That's because ``one_hit`` is used so that only one linked need must have the searched
value.
.. code-block:: jinja
.. spec:: result 4: Positive check thanks of one_hit option
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
.. spec:: result 4: Positive check thanks of one_hit option
:id: clv_4
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
:collapse: False
**Result 5: Two checks and a joint status**
Two checks are performed and both are positive. So their results get joined.
.. code-block:: jinja
.. spec:: result 5: Two checks and a joint status
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
.. spec:: result 5: Two checks and a joint status
:id: clv_5
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
:collapse: False
:param result: value, which gets returned if all linked needs have parsed the checks
:param search_option: option name, which is used n linked needs for the search
:param search_value: value, which an option of a linked need must match
:param filter_string: Checks are only performed on linked needs, which pass the defined filter
:param one_hit: If True, only one linked need must have a positive check
:return: result, if all checks are positive
"""
links = need["links"]
if not isinstance(search_value, list):
search_value = [search_value]
for link in links:
if filter_string is not None:
try:
if not filter_single_need(needs[link], filter_string):
continue
except Exception as e:
logger.warning("CheckLinkedValues: Filter {0} not valid: Error: {1}".format(filter_string, e))
if not one_hit and not needs[link][search_option] in search_value:
return None
elif one_hit and needs[link][search_option] in search_value:
return result
return result | python | def check_linked_values(app, need, needs, result, search_option, search_value, filter_string=None, one_hit=False):
"""
Returns a specific value, if for all linked needs a given option has a given value.
The linked needs can be filtered by using the ``filter`` option.
If ``one_hit`` is set to True, only one linked need must have a positive match for the searched value.
**Examples**
**Needs used as input data**
.. code-block:: jinja
.. req:: Input A
:id: clv_A
:status: in progress
.. req:: Input B
:id: clv_B
:status: in progress
.. spec:: Input C
:id: clv_C
:status: closed
.. req:: Input A
:id: clv_A
:status: in progress
:collapse: False
.. req:: Input B
:id: clv_B
:status: in progress
:collapse: False
.. spec:: Input C
:id: clv_C
:status: closed
:collapse: False
**Example 1: Positive check**
Status gets set to *progress*.
.. code-block:: jinja
.. spec:: result 1: Positive check
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
.. spec:: result 1: Positive check
:id: clv_1
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 2: Negative check**
Status gets not set to *progress*, because status of linked need *clv_C* does not match *"in progress"*.
.. code-block:: jinja
.. spec:: result 2: Negative check
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
.. spec:: result 2: Negative check
:id: clv_2
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 3: Positive check thanks of used filter**
status gets set to *progress*, because linked need *clv_C* is not part of the filter.
.. code-block:: jinja
.. spec:: result 3: Positive check thanks of used filter
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
.. spec:: result 3: Positive check thanks of used filter
:id: clv_3
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
:collapse: False
**Example 4: Positive check thanks of one_hit option**
Even *clv_C* has not the searched status, status gets anyway set to *progress*.
That's because ``one_hit`` is used so that only one linked need must have the searched
value.
.. code-block:: jinja
.. spec:: result 4: Positive check thanks of one_hit option
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
.. spec:: result 4: Positive check thanks of one_hit option
:id: clv_4
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
:collapse: False
**Result 5: Two checks and a joint status**
Two checks are performed and both are positive. So their results get joined.
.. code-block:: jinja
.. spec:: result 5: Two checks and a joint status
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
.. spec:: result 5: Two checks and a joint status
:id: clv_5
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
:collapse: False
:param result: value, which gets returned if all linked needs have parsed the checks
:param search_option: option name, which is used n linked needs for the search
:param search_value: value, which an option of a linked need must match
:param filter_string: Checks are only performed on linked needs, which pass the defined filter
:param one_hit: If True, only one linked need must have a positive check
:return: result, if all checks are positive
"""
links = need["links"]
if not isinstance(search_value, list):
search_value = [search_value]
for link in links:
if filter_string is not None:
try:
if not filter_single_need(needs[link], filter_string):
continue
except Exception as e:
logger.warning("CheckLinkedValues: Filter {0} not valid: Error: {1}".format(filter_string, e))
if not one_hit and not needs[link][search_option] in search_value:
return None
elif one_hit and needs[link][search_option] in search_value:
return result
return result | [
"def",
"check_linked_values",
"(",
"app",
",",
"need",
",",
"needs",
",",
"result",
",",
"search_option",
",",
"search_value",
",",
"filter_string",
"=",
"None",
",",
"one_hit",
"=",
"False",
")",
":",
"links",
"=",
"need",
"[",
"\"links\"",
"]",
"if",
"... | Returns a specific value, if for all linked needs a given option has a given value.
The linked needs can be filtered by using the ``filter`` option.
If ``one_hit`` is set to True, only one linked need must have a positive match for the searched value.
**Examples**
**Needs used as input data**
.. code-block:: jinja
.. req:: Input A
:id: clv_A
:status: in progress
.. req:: Input B
:id: clv_B
:status: in progress
.. spec:: Input C
:id: clv_C
:status: closed
.. req:: Input A
:id: clv_A
:status: in progress
:collapse: False
.. req:: Input B
:id: clv_B
:status: in progress
:collapse: False
.. spec:: Input C
:id: clv_C
:status: closed
:collapse: False
**Example 1: Positive check**
Status gets set to *progress*.
.. code-block:: jinja
.. spec:: result 1: Positive check
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
.. spec:: result 1: Positive check
:id: clv_1
:links: clv_A, clv_B
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 2: Negative check**
Status gets not set to *progress*, because status of linked need *clv_C* does not match *"in progress"*.
.. code-block:: jinja
.. spec:: result 2: Negative check
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
.. spec:: result 2: Negative check
:id: clv_2
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress' )]]
:collapse: False
**Example 3: Positive check thanks of used filter**
status gets set to *progress*, because linked need *clv_C* is not part of the filter.
.. code-block:: jinja
.. spec:: result 3: Positive check thanks of used filter
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
.. spec:: result 3: Positive check thanks of used filter
:id: clv_3
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', 'type == "req" ' )]]
:collapse: False
**Example 4: Positive check thanks of one_hit option**
Even *clv_C* has not the searched status, status gets anyway set to *progress*.
That's because ``one_hit`` is used so that only one linked need must have the searched
value.
.. code-block:: jinja
.. spec:: result 4: Positive check thanks of one_hit option
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
.. spec:: result 4: Positive check thanks of one_hit option
:id: clv_4
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]]
:collapse: False
**Result 5: Two checks and a joint status**
Two checks are performed and both are positive. So their results get joined.
.. code-block:: jinja
.. spec:: result 5: Two checks and a joint status
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
.. spec:: result 5: Two checks and a joint status
:id: clv_5
:links: clv_A, clv_B, clv_C
:status: [[check_linked_values('progress', 'status', 'in progress', one_hit=True )]] [[check_linked_values('closed', 'status', 'closed', one_hit=True )]]
:collapse: False
:param result: value, which gets returned if all linked needs have parsed the checks
:param search_option: option name, which is used n linked needs for the search
:param search_value: value, which an option of a linked need must match
:param filter_string: Checks are only performed on linked needs, which pass the defined filter
:param one_hit: If True, only one linked need must have a positive check
:return: result, if all checks are positive | [
"Returns",
"a",
"specific",
"value",
"if",
"for",
"all",
"linked",
"needs",
"a",
"given",
"option",
"has",
"a",
"given",
"value",
"."
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/common.py#L95-L244 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/functions/common.py | calc_sum | 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 that
:id: sum_input_2
:hours: 15
:collapse: False
.. spec:: Do too much
:id: sum_input_3
:hours: 110
:collapse: False
**Example 2**
.. code-block:: jinja
.. req:: Result 1
:amount: [[calc_sum("hours")]]
.. req:: Result 1
:amount: [[calc_sum("hours")]]
:collapse: False
**Example 2**
.. code-block:: jinja
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
:collapse: False
**Example 3**
.. code-block:: jinja
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
:collapse: False
**Example 4**
.. code-block:: jinja
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
:collapse: False
:param option: Options, from which the numbers shall be taken
:param filter: Filter string, which all needs must passed to get their value added.
:param links_only: If "True", only linked needs are taken into account.
:return: A float number
"""
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_single_need(check_need, filter):
continue
except ValueError as e:
pass
except NeedInvalidFilter as ex:
logger.warning('Given filter is not valid. Error: {}'.format(ex))
try:
calculated_sum += float(check_need[option])
except ValueError:
pass
return calculated_sum | python | 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 that
:id: sum_input_2
:hours: 15
:collapse: False
.. spec:: Do too much
:id: sum_input_3
:hours: 110
:collapse: False
**Example 2**
.. code-block:: jinja
.. req:: Result 1
:amount: [[calc_sum("hours")]]
.. req:: Result 1
:amount: [[calc_sum("hours")]]
:collapse: False
**Example 2**
.. code-block:: jinja
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
:collapse: False
**Example 3**
.. code-block:: jinja
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
:collapse: False
**Example 4**
.. code-block:: jinja
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
:collapse: False
:param option: Options, from which the numbers shall be taken
:param filter: Filter string, which all needs must passed to get their value added.
:param links_only: If "True", only linked needs are taken into account.
:return: A float number
"""
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_single_need(check_need, filter):
continue
except ValueError as e:
pass
except NeedInvalidFilter as ex:
logger.warning('Given filter is not valid. Error: {}'.format(ex))
try:
calculated_sum += float(check_need[option])
except ValueError:
pass
return calculated_sum | [
"def",
"calc_sum",
"(",
"app",
",",
"need",
",",
"needs",
",",
"option",
",",
"filter",
"=",
"None",
",",
"links_only",
"=",
"False",
")",
":",
"if",
"not",
"links_only",
":",
"check_needs",
"=",
"needs",
".",
"values",
"(",
")",
"else",
":",
"check_... | 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 that
:id: sum_input_2
:hours: 15
:collapse: False
.. spec:: Do too much
:id: sum_input_3
:hours: 110
:collapse: False
**Example 2**
.. code-block:: jinja
.. req:: Result 1
:amount: [[calc_sum("hours")]]
.. req:: Result 1
:amount: [[calc_sum("hours")]]
:collapse: False
**Example 2**
.. code-block:: jinja
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
.. req:: Result 2
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10")]]
:collapse: False
**Example 3**
.. code-block:: jinja
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
.. req:: Result 3
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", links_only="True")]]
:collapse: False
**Example 4**
.. code-block:: jinja
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
.. req:: Result 4
:links: sum_input_1; sum_input_3
:amount: [[calc_sum("hours", "hours.isdigit() and float(hours) > 10", "True")]]
:collapse: False
:param option: Options, from which the numbers shall be taken
:param filter: Filter string, which all needs must passed to get their value added.
:param links_only: If "True", only linked needs are taken into account.
:return: A float number | [
"Sums",
"the",
"values",
"of",
"a",
"given",
"option",
"in",
"filtered",
"needs",
"up",
"to",
"single",
"number",
"."
] | train | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/common.py#L247-L350 |
nickmckay/LiPD-utilities | Python/lipd/noaa.py | noaa_prompt | def noaa_prompt():
"""
Convert between NOAA and LiPD file formats.
:return:
"""
logger_noaa.info("enter noaa")
# Run lpd_noaa or noaa_lpd ?
print("Which conversion?\n1. LPD to NOAA\n2. NOAA to LPD\n")
mode = input("Option: ")
logger_noaa.info("chose option: {}".format(mode))
return mode | python | def noaa_prompt():
"""
Convert between NOAA and LiPD file formats.
:return:
"""
logger_noaa.info("enter noaa")
# Run lpd_noaa or noaa_lpd ?
print("Which conversion?\n1. LPD to NOAA\n2. NOAA to LPD\n")
mode = input("Option: ")
logger_noaa.info("chose option: {}".format(mode))
return mode | [
"def",
"noaa_prompt",
"(",
")",
":",
"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",
"... | Convert between NOAA and LiPD file formats.
:return: | [
"Convert",
"between",
"NOAA",
"and",
"LiPD",
"file",
"formats",
".",
":",
"return",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L16-L27 |
nickmckay/LiPD-utilities | Python/lipd/noaa.py | noaa_prompt_1 | 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
"""
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 | python | 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
"""
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",
"(",
")",
":",
"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 v... | 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 | [
"For",
"converting",
"LiPD",
"files",
"to",
"NOAA",
"we",
"need",
"a",
"couple",
"more",
"pieces",
"of",
"information",
"to",
"create",
"the",
"WDS",
"links"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L30-L42 |
nickmckay/LiPD-utilities | Python/lipd/noaa.py | noaa_to_lpd | def noaa_to_lpd(files):
"""
Convert NOAA format to LiPD format
:param dict files: Files metadata
:return None:
"""
logger_noaa.info("enter process_noaa")
# only continue if the user selected a mode correctly
logger_noaa.info("Found {} NOAA txt file(s)".format(str(len(files[".txt"]))))
print("Found {} NOAA txt file(s)".format(str(len(files[".txt"]))))
# Process each available file of the specified .lpd or .txt type
for file in files[".txt"]:
# try to filter out example files and stuff without real data
if "template" not in file["filename_ext"] and "example" not in file["filename_ext"]:
os.chdir(file["dir"])
print('processing: {}'.format(file["filename_ext"]))
logger_noaa.info("processing: {}".format(file["filename_ext"]))
# Unzip file and get tmp directory path
dir_tmp = create_tmp_dir()
try:
NOAA_LPD(file["dir"], dir_tmp, file["filename_no_ext"]).main()
except Exception as e:
print("Error: Unable to convert file: {}, {}".format(file["filename_no_ext"], e))
# Create the lipd archive in the original file's directory.
zipper(root_dir=dir_tmp, name="bag", path_name_ext=os.path.join(file["dir"], file["filename_no_ext"] + ".lpd"))
# Delete tmp folder and all contents
os.chdir(file["dir"])
try:
shutil.rmtree(dir_tmp)
except FileNotFoundError:
# directory is already gone. keep going.
pass
logger_noaa.info("exit noaa_to_lpd")
return | python | def noaa_to_lpd(files):
"""
Convert NOAA format to LiPD format
:param dict files: Files metadata
:return None:
"""
logger_noaa.info("enter process_noaa")
# only continue if the user selected a mode correctly
logger_noaa.info("Found {} NOAA txt file(s)".format(str(len(files[".txt"]))))
print("Found {} NOAA txt file(s)".format(str(len(files[".txt"]))))
# Process each available file of the specified .lpd or .txt type
for file in files[".txt"]:
# try to filter out example files and stuff without real data
if "template" not in file["filename_ext"] and "example" not in file["filename_ext"]:
os.chdir(file["dir"])
print('processing: {}'.format(file["filename_ext"]))
logger_noaa.info("processing: {}".format(file["filename_ext"]))
# Unzip file and get tmp directory path
dir_tmp = create_tmp_dir()
try:
NOAA_LPD(file["dir"], dir_tmp, file["filename_no_ext"]).main()
except Exception as e:
print("Error: Unable to convert file: {}, {}".format(file["filename_no_ext"], e))
# Create the lipd archive in the original file's directory.
zipper(root_dir=dir_tmp, name="bag", path_name_ext=os.path.join(file["dir"], file["filename_no_ext"] + ".lpd"))
# Delete tmp folder and all contents
os.chdir(file["dir"])
try:
shutil.rmtree(dir_tmp)
except FileNotFoundError:
# directory is already gone. keep going.
pass
logger_noaa.info("exit noaa_to_lpd")
return | [
"def",
"noaa_to_lpd",
"(",
"files",
")",
":",
"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"... | Convert NOAA format to LiPD format
:param dict files: Files metadata
:return None: | [
"Convert",
"NOAA",
"format",
"to",
"LiPD",
"format",
":",
"param",
"dict",
"files",
":",
"Files",
"metadata",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L45-L81 |
nickmckay/LiPD-utilities | Python/lipd/noaa.py | lpd_to_noaa | def lpd_to_noaa(D, wds_url, lpd_url, version, path=""):
"""
Convert a LiPD format to NOAA format
:param dict D: Metadata
:return dict D: Metadata
"""
logger_noaa.info("enter process_lpd")
d = D
try:
dsn = get_dsn(D)
# Remove all the characters that are not allowed here. 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)
version = re.sub(r'[^A-Za-z-.0-9]', '', version)
# Create the conversion object, and start the conversion process
_convert_obj = LPD_NOAA(D, dsn, wds_url, lpd_url, version, path)
_convert_obj.main()
# get our new, modified master JSON from the conversion object
d = _convert_obj.get_master()
noaas = _convert_obj.get_noaa_texts()
__write_noaas(noaas, path)
# remove any root level urls that are deprecated
d = __rm_wdc_url(d)
except Exception as e:
logger_noaa.error("lpd_to_noaa: {}".format(e))
print("Error: lpd_to_noaa: {}".format(e))
# logger_noaa.info("exit lpd_to_noaa")
return d | python | def lpd_to_noaa(D, wds_url, lpd_url, version, path=""):
"""
Convert a LiPD format to NOAA format
:param dict D: Metadata
:return dict D: Metadata
"""
logger_noaa.info("enter process_lpd")
d = D
try:
dsn = get_dsn(D)
# Remove all the characters that are not allowed here. 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)
version = re.sub(r'[^A-Za-z-.0-9]', '', version)
# Create the conversion object, and start the conversion process
_convert_obj = LPD_NOAA(D, dsn, wds_url, lpd_url, version, path)
_convert_obj.main()
# get our new, modified master JSON from the conversion object
d = _convert_obj.get_master()
noaas = _convert_obj.get_noaa_texts()
__write_noaas(noaas, path)
# remove any root level urls that are deprecated
d = __rm_wdc_url(d)
except Exception as e:
logger_noaa.error("lpd_to_noaa: {}".format(e))
print("Error: lpd_to_noaa: {}".format(e))
# logger_noaa.info("exit lpd_to_noaa")
return d | [
"def",
"lpd_to_noaa",
"(",
"D",
",",
"wds_url",
",",
"lpd_url",
",",
"version",
",",
"path",
"=",
"\"\"",
")",
":",
"logger_noaa",
".",
"info",
"(",
"\"enter process_lpd\"",
")",
"d",
"=",
"D",
"try",
":",
"dsn",
"=",
"get_dsn",
"(",
"D",
")",
"# Rem... | Convert a LiPD format to NOAA format
:param dict D: Metadata
:return dict D: Metadata | [
"Convert",
"a",
"LiPD",
"format",
"to",
"NOAA",
"format"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L84-L114 |
nickmckay/LiPD-utilities | Python/lipd/noaa.py | __write_noaas | 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:
"""
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 | python | 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:
"""
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",
")",
":",
"for",
"filename",
",",
"text",
"in",
"dat",
".",
"items",
"(",
")",
":",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filename",
")",
",",
"\"w+\""... | Use the filename - text data pairs to write the data as NOAA text files
:param dict dat: NOAA data to be written
:return none: | [
"Use",
"the",
"filename",
"-",
"text",
"data",
"pairs",
"to",
"write",
"the",
"data",
"as",
"NOAA",
"text",
"files"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L128-L141 |
mfussenegger/cr8 | cr8/java_magic.py | _parse_java_version | 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)
"""
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) | python | 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)
"""
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",
":",
"m",
"=",
"VERSION_RE",
".",
"search",
"(",
"line",
")",
"version_str",
"=",
"m",
"and",
"m",
".",
"group",
"(",
"0",
")",
".",
"replace",
"(",
"'\"'",
",",
"''",
")",
... | 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) | [
"Return",
"the",
"version",
"number",
"found",
"in",
"the",
"first",
"line",
"of",
"java",
"-",
"version"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/java_magic.py#L20-L33 |
mfussenegger/cr8 | cr8/java_magic.py | find_java_home | def find_java_home(cratedb_version: tuple) -> str:
""" Return a path to a JAVA_HOME suites for the given CrateDB version """
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_home(lambda ver: ver[0] >= 11) | python | def find_java_home(cratedb_version: tuple) -> str:
""" Return a path to a JAVA_HOME suites for the given CrateDB version """
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_home(lambda ver: ver[0] >= 11) | [
"def",
"find_java_home",
"(",
"cratedb_version",
":",
"tuple",
")",
"->",
"str",
":",
"if",
"MIN_VERSION_FOR_JVM11",
"<=",
"cratedb_version",
"<",
"(",
"4",
",",
"0",
")",
":",
"# Supports 8 to 11+, use whatever is set",
"return",
"os",
".",
"environ",
".",
"get... | Return a path to a JAVA_HOME suites for the given CrateDB version | [
"Return",
"a",
"path",
"to",
"a",
"JAVA_HOME",
"suites",
"for",
"the",
"given",
"CrateDB",
"version"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/java_magic.py#L57-L65 |
nickmckay/LiPD-utilities | Python/lipd/zips.py | zipper | 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
"""
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".format(path_name_ext), path_name_ext)
return | python | 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
"""
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".format(path_name_ext), path_name_ext)
return | [
"def",
"zipper",
"(",
"root_dir",
"=",
"\"\"",
",",
"name",
"=",
"\"\"",
",",
"path_name_ext",
"=",
"\"\"",
")",
":",
"logger_zips",
".",
"info",
"(",
"\"re_zip: name: {}, dir_tmp: {}\"",
".",
"format",
"(",
"path_name_ext",
",",
"root_dir",
")",
")",
"# cre... | 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 | [
"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_ex... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/zips.py#L10-L22 |
nickmckay/LiPD-utilities | Python/lipd/zips.py | unzipper | 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:
"""
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)
logger_zips.info("exit unzip")
return | python | 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:
"""
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)
logger_zips.info("exit unzip")
return | [
"def",
"unzipper",
"(",
"filename",
",",
"dir_tmp",
")",
":",
"logger_zips",
".",
"info",
"(",
"\"enter unzip\"",
")",
"# Unzip contents to the tmp directory",
"try",
":",
"with",
"zipfile",
".",
"ZipFile",
"(",
"filename",
")",
"as",
"f",
":",
"f",
".",
"ex... | Unzip .lpd file contents to tmp directory.
:param str filename: filename.lpd
:param str dir_tmp: Tmp folder to extract contents to
:return None: | [
"Unzip",
".",
"lpd",
"file",
"contents",
"to",
"tmp",
"directory",
".",
":",
"param",
"str",
"filename",
":",
"filename",
".",
"lpd",
":",
"param",
"str",
"dir_tmp",
":",
"Tmp",
"folder",
"to",
"extract",
"contents",
"to",
":",
"return",
"None",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/zips.py#L25-L41 |
mfussenegger/cr8 | cr8/metrics.py | percentile | 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
"""
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)] | python | 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
"""
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",
")",
":",
"size",
"=",
"len",
"(",
"sorted_values",
")",
"idx",
"=",
"(",
"p",
"/",
"100.0",
")",
"*",
"size",
"-",
"0.5",
"if",
"idx",
"<",
"0",
"or",
"idx",
">",
"size",
":",
"raise",
"ValueE... | 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 | [
"Calculate",
"the",
"percentile",
"using",
"the",
"nearest",
"rank",
"method",
"."
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/metrics.py#L10-L28 |
mfussenegger/cr8 | cr8/metrics.py | get_sampler | 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)
"""
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}') | python | 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)
"""
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",
")",
":",
"if",
"sample_mode",
"==",
"'all'",
":",
"return",
"All",
"mode",
"=",
"sample_mode",
".",
"split",
"(",
"':'",
")",
"if",
"mode",
"[",
"0",
"]",
"==",
"'reservoir'",
":",
"if",
"len",
"... | 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) | [
"Return",
"a",
"sampler",
"constructor"
] | train | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/metrics.py#L67-L87 |
sijis/sumologic-python | src/sumologic/search.py | Search.query | 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_to: right now (datetime)
"""
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 = opts.get('time_from', minutes_ago)
time_to = opts.get('time_to', right_now)
# setting up options
t_options = {
'q': criteria,
'format': formats,
'tz': timezone,
'from': time_from,
'to': time_to,
}
options = '&'.join(['{}={}'.format(k, v)
for k, v in t_options.items()])
req = requests.get('%s?%s' %
(self.url, options), auth=self.auth)
try:
data = req.json()
except json.decoder.JSONDecodeError:
data = []
return {
'data': data,
'response': req.status_code,
'reason': req.reason,
} | python | 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_to: right now (datetime)
"""
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 = opts.get('time_from', minutes_ago)
time_to = opts.get('time_to', right_now)
# setting up options
t_options = {
'q': criteria,
'format': formats,
'tz': timezone,
'from': time_from,
'to': time_to,
}
options = '&'.join(['{}={}'.format(k, v)
for k, v in t_options.items()])
req = requests.get('%s?%s' %
(self.url, options), auth=self.auth)
try:
data = req.json()
except json.decoder.JSONDecodeError:
data = []
return {
'data': data,
'response': req.status_code,
'reason': req.reason,
} | [
"def",
"query",
"(",
"self",
",",
"criteria",
",",
"*",
"*",
"opts",
")",
":",
"time_now",
"=",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
".",
"replace",
"(",
"second",
"=",
"0",
",",
"microsecond",
"=",
"0",
")",
"right_now",
"=",
"time_n... | 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_to: right now (datetime) | [
"Returns",
"a",
"dict",
"of",
"the",
"query",
"including",
"the",
"results",
":",
"param",
"critera",
":",
"string",
"of",
"search",
"criteria",
":",
"param",
"**",
"opts",
":",
":",
"formats",
":",
"json",
"/",
"xml",
"(",
"default",
":",
"json",
")",... | train | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/search.py#L28-L69 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | excel_main | def excel_main(file):
"""
Parse data from Excel spreadsheets into LiPD files.
:param dict file: File metadata (source, name, etc)
:return str dsn: Dataset name
"""
os.chdir(file["dir"])
name_ext = file["filename_ext"]
# Filename without extension
name = file["filename_no_ext"]
# remove foreign characters to prevent wiki uploading errors
name = normalize_name(name)
print("processing: {}".format(name_ext))
logger_excel.info("processing: {}".format(name_ext))
pending_csv = []
final = OrderedDict()
logger_excel.info("variables initialized")
# Create a temporary folder and set paths
dir_tmp = create_tmp_dir()
"""
EACH DATA TABLE WILL BE STRUCTURED LIKE THIS
"paleo_chron": "paleo",
"pc_idx": 1,
"model_idx": "",
"table_type": "measurement",
"table_idx": 1,
"name": sheet,
"filename": sheet,
"data": { column data }
"""
# Open excel workbook with filename
try:
workbook = xlrd.open_workbook(name_ext)
logger_excel.info("opened XLRD workbook")
except Exception as e:
# There was a problem opening a file with XLRD
print("Failed to open Excel workbook: {}".format(name))
workbook = None
logger_excel.debug("excel: xlrd failed to open workbook: {}, {}".format(name, e))
if workbook:
# Build sheets, but don't make full filenames yet. Need to parse metadata sheet first to get datasetname.
sheets, ct_paleo, ct_chron, metadata_str = _get_sheet_metadata(workbook, name)
# METADATA WORKSHEETS
# Parse Metadata sheet and add to output dictionary
if metadata_str:
logger_excel.info("parsing worksheet: {}".format(metadata_str))
final = cells_dn_meta(workbook, metadata_str, 0, 0, final)
# Now that we have the dataSetName, we can use it to build filenames
dsn = __get_datasetname(final, name)
filename = str(dsn) + ".lpd"
sheets = __set_sheet_filenames(sheets, dsn)
dir_bag = os.path.join(dir_tmp, "bag")
dir_data = os.path.join(dir_bag, 'data')
# Make folders in tmp
os.mkdir(os.path.join(dir_bag))
os.mkdir(os.path.join(dir_data))
# PALEO AND CHRON SHEETS
for sheet in sheets:
logger_excel.info("parsing data worksheet: {}".format(sheet["new_name"]))
sheet_meta, sheet_csv = _parse_sheet(workbook, sheet)
if sheet_csv and sheet_meta:
pending_csv.append(sheet_csv)
sheet["data"] = sheet_meta
# create the metadata skeleton where we will place the tables. dynamically add empty table blocks for data.
skeleton_paleo, skeleton_chron = _create_skeleton_1(sheets)
# Reorganize sheet metadata into LiPD structure
d_paleo, d_chron = _place_tables_main(sheets, skeleton_paleo, skeleton_chron)
# Add organized metadata into final dictionary
final['paleoData'] = d_paleo
final['chronData'] = d_chron
# OUTPUT
# Create new files and dump data in dir_data
os.chdir(dir_data)
# WRITE CSV
_write_data_csv(pending_csv)
# JSON-LD
# Invoke DOI Resolver Class to update publisher data
try:
logger_excel.info("invoking doi resolver")
final = DOIResolver(file["dir"], name, final).main()
except Exception as e:
print("Error: doi resolver failed: {}".format(name))
logger_excel.debug("excel: doi resolver failed: {}, {}".format(name, e))
# Dump final_dict to a json file.
final["lipdVersion"] = 1.2
final["createdBy"] = "excel"
write_json_to_file(final)
# Move files to bag root for re-bagging
# dir : dir_data -> dir_bag
logger_excel.info("start cleanup")
dir_cleanup(dir_bag, dir_data)
# Create a bag for the 3 files
finish_bag(dir_bag)
# dir: dir_tmp -> dir_root
os.chdir(file["dir"])
# Check if same lpd file exists. If so, delete so new one can be made
if os.path.isfile(filename):
os.remove(filename)
# Zip dir_bag. Creates in dir_root directory
logger_excel.info("re-zip and rename")
zipper(root_dir=dir_tmp, name="bag", path_name_ext=os.path.join(file["dir"], filename))
# Move back to dir_root for next loop.
os.chdir(file["dir"])
# Cleanup and remove tmp directory
shutil.rmtree(dir_tmp)
return dsn | python | def excel_main(file):
"""
Parse data from Excel spreadsheets into LiPD files.
:param dict file: File metadata (source, name, etc)
:return str dsn: Dataset name
"""
os.chdir(file["dir"])
name_ext = file["filename_ext"]
# Filename without extension
name = file["filename_no_ext"]
# remove foreign characters to prevent wiki uploading errors
name = normalize_name(name)
print("processing: {}".format(name_ext))
logger_excel.info("processing: {}".format(name_ext))
pending_csv = []
final = OrderedDict()
logger_excel.info("variables initialized")
# Create a temporary folder and set paths
dir_tmp = create_tmp_dir()
"""
EACH DATA TABLE WILL BE STRUCTURED LIKE THIS
"paleo_chron": "paleo",
"pc_idx": 1,
"model_idx": "",
"table_type": "measurement",
"table_idx": 1,
"name": sheet,
"filename": sheet,
"data": { column data }
"""
# Open excel workbook with filename
try:
workbook = xlrd.open_workbook(name_ext)
logger_excel.info("opened XLRD workbook")
except Exception as e:
# There was a problem opening a file with XLRD
print("Failed to open Excel workbook: {}".format(name))
workbook = None
logger_excel.debug("excel: xlrd failed to open workbook: {}, {}".format(name, e))
if workbook:
# Build sheets, but don't make full filenames yet. Need to parse metadata sheet first to get datasetname.
sheets, ct_paleo, ct_chron, metadata_str = _get_sheet_metadata(workbook, name)
# METADATA WORKSHEETS
# Parse Metadata sheet and add to output dictionary
if metadata_str:
logger_excel.info("parsing worksheet: {}".format(metadata_str))
final = cells_dn_meta(workbook, metadata_str, 0, 0, final)
# Now that we have the dataSetName, we can use it to build filenames
dsn = __get_datasetname(final, name)
filename = str(dsn) + ".lpd"
sheets = __set_sheet_filenames(sheets, dsn)
dir_bag = os.path.join(dir_tmp, "bag")
dir_data = os.path.join(dir_bag, 'data')
# Make folders in tmp
os.mkdir(os.path.join(dir_bag))
os.mkdir(os.path.join(dir_data))
# PALEO AND CHRON SHEETS
for sheet in sheets:
logger_excel.info("parsing data worksheet: {}".format(sheet["new_name"]))
sheet_meta, sheet_csv = _parse_sheet(workbook, sheet)
if sheet_csv and sheet_meta:
pending_csv.append(sheet_csv)
sheet["data"] = sheet_meta
# create the metadata skeleton where we will place the tables. dynamically add empty table blocks for data.
skeleton_paleo, skeleton_chron = _create_skeleton_1(sheets)
# Reorganize sheet metadata into LiPD structure
d_paleo, d_chron = _place_tables_main(sheets, skeleton_paleo, skeleton_chron)
# Add organized metadata into final dictionary
final['paleoData'] = d_paleo
final['chronData'] = d_chron
# OUTPUT
# Create new files and dump data in dir_data
os.chdir(dir_data)
# WRITE CSV
_write_data_csv(pending_csv)
# JSON-LD
# Invoke DOI Resolver Class to update publisher data
try:
logger_excel.info("invoking doi resolver")
final = DOIResolver(file["dir"], name, final).main()
except Exception as e:
print("Error: doi resolver failed: {}".format(name))
logger_excel.debug("excel: doi resolver failed: {}, {}".format(name, e))
# Dump final_dict to a json file.
final["lipdVersion"] = 1.2
final["createdBy"] = "excel"
write_json_to_file(final)
# Move files to bag root for re-bagging
# dir : dir_data -> dir_bag
logger_excel.info("start cleanup")
dir_cleanup(dir_bag, dir_data)
# Create a bag for the 3 files
finish_bag(dir_bag)
# dir: dir_tmp -> dir_root
os.chdir(file["dir"])
# Check if same lpd file exists. If so, delete so new one can be made
if os.path.isfile(filename):
os.remove(filename)
# Zip dir_bag. Creates in dir_root directory
logger_excel.info("re-zip and rename")
zipper(root_dir=dir_tmp, name="bag", path_name_ext=os.path.join(file["dir"], filename))
# Move back to dir_root for next loop.
os.chdir(file["dir"])
# Cleanup and remove tmp directory
shutil.rmtree(dir_tmp)
return dsn | [
"def",
"excel_main",
"(",
"file",
")",
":",
"os",
".",
"chdir",
"(",
"file",
"[",
"\"dir\"",
"]",
")",
"name_ext",
"=",
"file",
"[",
"\"filename_ext\"",
"]",
"# Filename without extension",
"name",
"=",
"file",
"[",
"\"filename_no_ext\"",
"]",
"# remove foreig... | Parse data from Excel spreadsheets into LiPD files.
:param dict file: File metadata (source, name, etc)
:return str dsn: Dataset name | [
"Parse",
"data",
"from",
"Excel",
"spreadsheets",
"into",
"LiPD",
"files",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L26-L162 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _get_sheet_metadata | 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
paleo1_measurement1
NOTE: since each model will only have one ensemble and one summary, they should not have a trailing index number.
:param obj workbook: Excel workbook
:param str name: Dataset name
:return dict int int str:
"""
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 of "data (qc), data, and chronology"
old = "".join(sheet.lower().strip().split())
# Don't parse example sheets. If these words are in the sheet, assume we skip them.
if not any(word in sheet.lower() for word in skip_sheets):
# Group the related sheets together, so it's easier to place in the metadata later.
if 'metadata' in sheet.lower():
metadata_str = sheet
# Skip the 'about' and 'proxy' sheets altogether. Proceed with all other sheets.
elif "about" not in sheet.lower() and "proxy" not in sheet.lower():
logger_excel.info("creating sheets metadata")
# If this is a valid sheet name, we will receive a regex object back.
m = re.match(re_sheet, sheet.lower())
# Valid regex object. This is a valid sheet name and we can use that to build the sheet metadata.
if m:
sheets, paleo_ct, chron_ct = _sheet_meta_from_regex(m, sheets, sheet, name, ct_paleo, ct_chron)
# Older excel template style: backwards compatibility. Hard coded for one sheet per table.
elif old == "data" or "data(qc)" in old or "data(original)" in old:
sheets.append({
"paleo_chron": "paleo",
"idx_pc": ct_paleo,
"idx_model": None,
"table_type": "measurement",
"idx_table": 1,
"old_name": sheet,
"new_name": sheet,
"filename": "paleo{}measurementTable1.csv".format(ct_paleo),
"table_name": "paleo{}measurementTable1".format(ct_paleo),
"data": ""
})
ct_paleo += 1
# Older excel template style: backwards compatibility. Hard coded for one sheet per table.
elif old == "chronology":
sheets.append({
"paleo_chron": "chron",
"idx_pc": ct_chron,
"idx_model": None,
"table_type": "measurement",
"idx_table": 1,
"old_name": sheet,
"new_name": sheet,
"filename": "chron{}measurementTable1.csv".format(ct_chron),
"table_name": "chron{}measurementTable1".format(ct_chron),
"data": ""
})
ct_chron += 1
else:
# Sheet name does not conform to standard. Guide user to create a standardized sheet name.
print("This sheet name does not conform to naming standard: {}".format(sheet))
sheets, paleo_ct, chron_ct = _sheet_meta_from_prompts(sheets, sheet, name, ct_paleo, ct_chron)
return sheets, ct_paleo, ct_chron, metadata_str | python | 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
paleo1_measurement1
NOTE: since each model will only have one ensemble and one summary, they should not have a trailing index number.
:param obj workbook: Excel workbook
:param str name: Dataset name
:return dict int int str:
"""
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 of "data (qc), data, and chronology"
old = "".join(sheet.lower().strip().split())
# Don't parse example sheets. If these words are in the sheet, assume we skip them.
if not any(word in sheet.lower() for word in skip_sheets):
# Group the related sheets together, so it's easier to place in the metadata later.
if 'metadata' in sheet.lower():
metadata_str = sheet
# Skip the 'about' and 'proxy' sheets altogether. Proceed with all other sheets.
elif "about" not in sheet.lower() and "proxy" not in sheet.lower():
logger_excel.info("creating sheets metadata")
# If this is a valid sheet name, we will receive a regex object back.
m = re.match(re_sheet, sheet.lower())
# Valid regex object. This is a valid sheet name and we can use that to build the sheet metadata.
if m:
sheets, paleo_ct, chron_ct = _sheet_meta_from_regex(m, sheets, sheet, name, ct_paleo, ct_chron)
# Older excel template style: backwards compatibility. Hard coded for one sheet per table.
elif old == "data" or "data(qc)" in old or "data(original)" in old:
sheets.append({
"paleo_chron": "paleo",
"idx_pc": ct_paleo,
"idx_model": None,
"table_type": "measurement",
"idx_table": 1,
"old_name": sheet,
"new_name": sheet,
"filename": "paleo{}measurementTable1.csv".format(ct_paleo),
"table_name": "paleo{}measurementTable1".format(ct_paleo),
"data": ""
})
ct_paleo += 1
# Older excel template style: backwards compatibility. Hard coded for one sheet per table.
elif old == "chronology":
sheets.append({
"paleo_chron": "chron",
"idx_pc": ct_chron,
"idx_model": None,
"table_type": "measurement",
"idx_table": 1,
"old_name": sheet,
"new_name": sheet,
"filename": "chron{}measurementTable1.csv".format(ct_chron),
"table_name": "chron{}measurementTable1".format(ct_chron),
"data": ""
})
ct_chron += 1
else:
# Sheet name does not conform to standard. Guide user to create a standardized sheet name.
print("This sheet name does not conform to naming standard: {}".format(sheet))
sheets, paleo_ct, chron_ct = _sheet_meta_from_prompts(sheets, sheet, name, ct_paleo, ct_chron)
return sheets, ct_paleo, ct_chron, metadata_str | [
"def",
"_get_sheet_metadata",
"(",
"workbook",
",",
"name",
")",
":",
"ct_paleo",
"=",
"1",
"ct_chron",
"=",
"1",
"metadata_str",
"=",
"\"\"",
"sheets",
"=",
"[",
"]",
"skip_sheets",
"=",
"[",
"\"example\"",
",",
"\"sample\"",
",",
"\"lists\"",
",",
"\"gui... | 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
paleo1_measurement1
NOTE: since each model will only have one ensemble and one summary, they should not have a trailing index number.
:param obj workbook: Excel workbook
:param str name: Dataset name
:return dict int int str: | [
"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",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L167-L253 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _sheet_meta_from_prompts | 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
:return sheets paleo_ct chron_ct: Updated sheets and counts
"""
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)easurement, or (s)ummary sheet?").lower()
if tt in EXCEL_SHEET_TYPES["distribution"] or tt in EXCEL_SHEET_TYPES["ensemble"] \
or tt in EXCEL_SHEET_TYPES["summary"] or tt in EXCEL_SHEET_TYPES["measurement"]:
# valid answer, keep going
if tt in EXCEL_SHEET_TYPES["distribution"]:
tt = "distribution"
elif tt in EXCEL_SHEET_TYPES["summary"]:
tt = "summary"
elif tt in EXCEL_SHEET_TYPES["ensemble"]:
tt = "ensemble"
elif tt in EXCEL_SHEET_TYPES["measurement"]:
tt = "measurement"
if pc in EXCEL_SHEET_TYPES["paleo"]:
if tt in ["ensemble", "summary"]:
sheet = "{}{}{}{}".format("paleo", ct_paleo, tt, 1)
else:
sheet = "{}{}{}".format("paleo", ct_paleo, tt)
elif pc in EXCEL_SHEET_TYPES["chron"]:
if tt in ["ensemble", "summary"]:
sheet = "{}{}{}{}".format("chron", ct_chron, tt, 1)
else:
sheet = "{}{}{}".format("chron", ct_chron, tt)
# Test the sheet that was built from the user responses.
# If it matches the Regex, then continue to build the sheet metadata. If not, try again or skip sheet.
m = re.match(re_sheet, sheet.lower())
if m:
sheets, ct_paleo, ct_chron = _sheet_meta_from_regex(m, sheets, old_name, name, ct_paleo, ct_chron)
print("Sheet created: {}".format(sheet))
cont = False
else:
resp = input("invalid sheet name. try again? (y/n): ")
if resp == "n":
print("No valid sheet name was created. Skipping sheet: {}".format(sheet))
cont = False
except Exception as e:
logger_excel.debug("excel: sheet_meta_from_prompts: error during prompts, {}".format(e))
cont = False
print("=====================================================")
return sheets, ct_paleo, ct_chron | python | 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
:return sheets paleo_ct chron_ct: Updated sheets and counts
"""
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)easurement, or (s)ummary sheet?").lower()
if tt in EXCEL_SHEET_TYPES["distribution"] or tt in EXCEL_SHEET_TYPES["ensemble"] \
or tt in EXCEL_SHEET_TYPES["summary"] or tt in EXCEL_SHEET_TYPES["measurement"]:
# valid answer, keep going
if tt in EXCEL_SHEET_TYPES["distribution"]:
tt = "distribution"
elif tt in EXCEL_SHEET_TYPES["summary"]:
tt = "summary"
elif tt in EXCEL_SHEET_TYPES["ensemble"]:
tt = "ensemble"
elif tt in EXCEL_SHEET_TYPES["measurement"]:
tt = "measurement"
if pc in EXCEL_SHEET_TYPES["paleo"]:
if tt in ["ensemble", "summary"]:
sheet = "{}{}{}{}".format("paleo", ct_paleo, tt, 1)
else:
sheet = "{}{}{}".format("paleo", ct_paleo, tt)
elif pc in EXCEL_SHEET_TYPES["chron"]:
if tt in ["ensemble", "summary"]:
sheet = "{}{}{}{}".format("chron", ct_chron, tt, 1)
else:
sheet = "{}{}{}".format("chron", ct_chron, tt)
# Test the sheet that was built from the user responses.
# If it matches the Regex, then continue to build the sheet metadata. If not, try again or skip sheet.
m = re.match(re_sheet, sheet.lower())
if m:
sheets, ct_paleo, ct_chron = _sheet_meta_from_regex(m, sheets, old_name, name, ct_paleo, ct_chron)
print("Sheet created: {}".format(sheet))
cont = False
else:
resp = input("invalid sheet name. try again? (y/n): ")
if resp == "n":
print("No valid sheet name was created. Skipping sheet: {}".format(sheet))
cont = False
except Exception as e:
logger_excel.debug("excel: sheet_meta_from_prompts: error during prompts, {}".format(e))
cont = False
print("=====================================================")
return sheets, ct_paleo, ct_chron | [
"def",
"_sheet_meta_from_prompts",
"(",
"sheets",
",",
"old_name",
",",
"name",
",",
"ct_paleo",
",",
"ct_chron",
")",
":",
"cont",
"=",
"True",
"# Loop until valid sheet name is built, or user gives up",
"while",
"cont",
":",
"try",
":",
"pc",
"=",
"input",
"(",
... | 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
:return sheets paleo_ct chron_ct: Updated sheets and counts | [
"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... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L256-L312 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _sheet_meta_from_regex | 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 tables
:param int ct_chron: Running count of chronData tables
:return sheets paleo_ct chron_ct: Updated sheets and counts
"""
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 = int(m.group(6))
# find out table type
if pc == "paleodata" or pc == "paleo":
pc = "paleo"
ct_paleo += 1
elif pc == "chrondata" or pc == "chron":
pc = "chron"
ct_chron += 1
# build filename and table name strings. build table name first, then make filename from the table_name
new_name = "{}{}".format(pc, m.group(2))
if idx_model:
new_name = "{}model{}".format(new_name, idx_model)
new_name = "{}{}".format(new_name, m.group(5))
if idx_table:
new_name = "{}{}".format(new_name, m.group(6))
filename = "{}.csv".format(new_name)
except Exception as e:
logger_excel.debug("excel: sheet_meta_from_regex: error during setup, {}".format(e))
# Standard naming. This matches the regex and the sheet name is how we want it.
# paleo/chron - idx - table_type - idx
# Not sure what to do with m.group(2) yet
# ex: m.groups() = [ paleo, 1, model, 1, ensemble, 1 ]
try:
sheets.append({
"old_name": old_name,
"new_name": new_name,
"filename": filename,
"paleo_chron": pc,
"idx_pc": int(m.group(2)),
"idx_model": idx_model,
"idx_table": idx_table,
"table_type": m.group(5),
"data": ""
})
except Exception as e:
print("error: build sheets")
logger_excel.debug("excel: build_sheet: unable to build sheet, {}".format(e))
return sheets, ct_paleo, ct_chron | python | 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 tables
:param int ct_chron: Running count of chronData tables
:return sheets paleo_ct chron_ct: Updated sheets and counts
"""
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 = int(m.group(6))
# find out table type
if pc == "paleodata" or pc == "paleo":
pc = "paleo"
ct_paleo += 1
elif pc == "chrondata" or pc == "chron":
pc = "chron"
ct_chron += 1
# build filename and table name strings. build table name first, then make filename from the table_name
new_name = "{}{}".format(pc, m.group(2))
if idx_model:
new_name = "{}model{}".format(new_name, idx_model)
new_name = "{}{}".format(new_name, m.group(5))
if idx_table:
new_name = "{}{}".format(new_name, m.group(6))
filename = "{}.csv".format(new_name)
except Exception as e:
logger_excel.debug("excel: sheet_meta_from_regex: error during setup, {}".format(e))
# Standard naming. This matches the regex and the sheet name is how we want it.
# paleo/chron - idx - table_type - idx
# Not sure what to do with m.group(2) yet
# ex: m.groups() = [ paleo, 1, model, 1, ensemble, 1 ]
try:
sheets.append({
"old_name": old_name,
"new_name": new_name,
"filename": filename,
"paleo_chron": pc,
"idx_pc": int(m.group(2)),
"idx_model": idx_model,
"idx_table": idx_table,
"table_type": m.group(5),
"data": ""
})
except Exception as e:
print("error: build sheets")
logger_excel.debug("excel: build_sheet: unable to build sheet, {}".format(e))
return sheets, ct_paleo, ct_chron | [
"def",
"_sheet_meta_from_regex",
"(",
"m",
",",
"sheets",
",",
"old_name",
",",
"name",
",",
"ct_paleo",
",",
"ct_chron",
")",
":",
"try",
":",
"idx_model",
"=",
"None",
"idx_table",
"=",
"None",
"pc",
"=",
"m",
".",
"group",
"(",
"1",
")",
"# Get the ... | 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 tables
:param int ct_chron: Running count of chronData tables
:return sheets paleo_ct chron_ct: Updated sheets and counts | [
"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... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L315-L374 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _place_tables_section | def _place_tables_section(skeleton_section, sheet, keys_section):
"""
Place data into skeleton for either a paleo or chron section.
:param dict skeleton_section: Empty or current progress of skeleton w/ data
:param dict sheet: Sheet metadata
:param list keys_section: Paleo or Chron specific keys
:return dict: Skeleton section full of data
"""
logger_excel.info("enter place_tables_section")
try:
logger_excel.info("excel: place_tables_section: placing table: {}".format(sheet["new_name"]))
new_name = sheet["new_name"]
logger_excel.info("placing_tables_section: {}".format(new_name))
# get all the sheet metadata needed for this function
idx_pc = sheet["idx_pc"] - 1
idx_model = sheet["idx_model"]
idx_table = sheet["idx_table"]
table_type = sheet["table_type"]
data = sheet["data"]
# paleoMeas or chronMeas key
key_1 = keys_section[0]
# paleoModel or chronModel key
key_2 = keys_section[1]
# Is this a measurement, or distribution table?
if idx_table:
# Yes, a table idx exists, so decrement it.
idx_table = sheet["idx_table"] - 1
# Is this a ensemble, dist, or summary table?
if idx_model:
# Yes, a model idx exists, so decrement it.
idx_model -= 1
except Exception as e:
logger_excel.debug("excel: place_tables_section: error during setup, {}".format(e))
# If it's measurement table, it goes in first.
try:
if table_type == "measurement":
skeleton_section[idx_pc][key_1][idx_table] = data
# Other types of tables go one step below
elif table_type in ["ensemble", "distribution", "summary"]:
if table_type == "summary":
skeleton_section[idx_pc][key_2][idx_model]["summaryTable"] = data
elif table_type == "ensemble":
skeleton_section[idx_pc][key_2][idx_model]["ensembleTable"] = data
elif table_type == "distribution":
skeleton_section[idx_pc][key_2][idx_model]["distributionTable"][idx_table] = data
except Exception as e:
logger_excel.warn("excel: place_tables_section: Unable to place table {}, {}".format(new_name, e))
logger_excel.info("exit place_tables_section")
return skeleton_section | python | def _place_tables_section(skeleton_section, sheet, keys_section):
"""
Place data into skeleton for either a paleo or chron section.
:param dict skeleton_section: Empty or current progress of skeleton w/ data
:param dict sheet: Sheet metadata
:param list keys_section: Paleo or Chron specific keys
:return dict: Skeleton section full of data
"""
logger_excel.info("enter place_tables_section")
try:
logger_excel.info("excel: place_tables_section: placing table: {}".format(sheet["new_name"]))
new_name = sheet["new_name"]
logger_excel.info("placing_tables_section: {}".format(new_name))
# get all the sheet metadata needed for this function
idx_pc = sheet["idx_pc"] - 1
idx_model = sheet["idx_model"]
idx_table = sheet["idx_table"]
table_type = sheet["table_type"]
data = sheet["data"]
# paleoMeas or chronMeas key
key_1 = keys_section[0]
# paleoModel or chronModel key
key_2 = keys_section[1]
# Is this a measurement, or distribution table?
if idx_table:
# Yes, a table idx exists, so decrement it.
idx_table = sheet["idx_table"] - 1
# Is this a ensemble, dist, or summary table?
if idx_model:
# Yes, a model idx exists, so decrement it.
idx_model -= 1
except Exception as e:
logger_excel.debug("excel: place_tables_section: error during setup, {}".format(e))
# If it's measurement table, it goes in first.
try:
if table_type == "measurement":
skeleton_section[idx_pc][key_1][idx_table] = data
# Other types of tables go one step below
elif table_type in ["ensemble", "distribution", "summary"]:
if table_type == "summary":
skeleton_section[idx_pc][key_2][idx_model]["summaryTable"] = data
elif table_type == "ensemble":
skeleton_section[idx_pc][key_2][idx_model]["ensembleTable"] = data
elif table_type == "distribution":
skeleton_section[idx_pc][key_2][idx_model]["distributionTable"][idx_table] = data
except Exception as e:
logger_excel.warn("excel: place_tables_section: Unable to place table {}, {}".format(new_name, e))
logger_excel.info("exit place_tables_section")
return skeleton_section | [
"def",
"_place_tables_section",
"(",
"skeleton_section",
",",
"sheet",
",",
"keys_section",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter place_tables_section\"",
")",
"try",
":",
"logger_excel",
".",
"info",
"(",
"\"excel: place_tables_section: placing table: {}\"... | Place data into skeleton for either a paleo or chron section.
:param dict skeleton_section: Empty or current progress of skeleton w/ data
:param dict sheet: Sheet metadata
:param list keys_section: Paleo or Chron specific keys
:return dict: Skeleton section full of data | [
"Place",
"data",
"into",
"skeleton",
"for",
"either",
"a",
"paleo",
"or",
"chron",
"section",
".",
":",
"param",
"dict",
"skeleton_section",
":",
"Empty",
"or",
"current",
"progress",
"of",
"skeleton",
"w",
"/",
"data",
":",
"param",
"dict",
"sheet",
":",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L377-L426 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _place_tables_main | def _place_tables_main(sheets, skeleton_paleo, skeleton_chron):
"""
All the data has been parsed, skeletons have been created, now put the data into the skeletons.
:param list sheets: All metadata needed to place sheet data into the LiPD structure
:param list skeleton_paleo: The empty skeleton where we will place data
:param list skeleton_chron: The empty skeleton where we will place data
:return:
"""
logger_excel.info("enter place_tables_main")
for sheet in sheets:
pc = sheet["paleo_chron"]
if pc == "paleo":
skeleton_paleo = _place_tables_section(skeleton_paleo, sheet, ["paleoMeasurementTable", "paleoModel"])
elif pc == "chron":
skeleton_chron = _place_tables_section(skeleton_chron, sheet, ["chronMeasurementTable", "chronModel"])
# when returning, these should no longer be skeletons. They should be tables filled with data
logger_excel.info("exit place_tables_main")
return skeleton_paleo, skeleton_chron | python | def _place_tables_main(sheets, skeleton_paleo, skeleton_chron):
"""
All the data has been parsed, skeletons have been created, now put the data into the skeletons.
:param list sheets: All metadata needed to place sheet data into the LiPD structure
:param list skeleton_paleo: The empty skeleton where we will place data
:param list skeleton_chron: The empty skeleton where we will place data
:return:
"""
logger_excel.info("enter place_tables_main")
for sheet in sheets:
pc = sheet["paleo_chron"]
if pc == "paleo":
skeleton_paleo = _place_tables_section(skeleton_paleo, sheet, ["paleoMeasurementTable", "paleoModel"])
elif pc == "chron":
skeleton_chron = _place_tables_section(skeleton_chron, sheet, ["chronMeasurementTable", "chronModel"])
# when returning, these should no longer be skeletons. They should be tables filled with data
logger_excel.info("exit place_tables_main")
return skeleton_paleo, skeleton_chron | [
"def",
"_place_tables_main",
"(",
"sheets",
",",
"skeleton_paleo",
",",
"skeleton_chron",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter place_tables_main\"",
")",
"for",
"sheet",
"in",
"sheets",
":",
"pc",
"=",
"sheet",
"[",
"\"paleo_chron\"",
"]",
"if",
... | All the data has been parsed, skeletons have been created, now put the data into the skeletons.
:param list sheets: All metadata needed to place sheet data into the LiPD structure
:param list skeleton_paleo: The empty skeleton where we will place data
:param list skeleton_chron: The empty skeleton where we will place data
:return: | [
"All",
"the",
"data",
"has",
"been",
"parsed",
"skeletons",
"have",
"been",
"created",
"now",
"put",
"the",
"data",
"into",
"the",
"skeletons",
".",
":",
"param",
"list",
"sheets",
":",
"All",
"metadata",
"needed",
"to",
"place",
"sheet",
"data",
"into",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L429-L448 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _get_table_counts | def _get_table_counts(sheet, num_section):
"""
Loop through sheet metadata and count how many of each table type is needed at each index.
Example: 'paleo 1' needs {'2 measurement tables', '1 model table, with 1 summary, 1 ensemble, and 3 distributions'}
:param dict sheet: Sheet metadata
:param dict num_section: Rolling number counts of table types for each index.
:return:
"""
tt = sheet["table_type"]
idx_pc = sheet["idx_pc"]
idx_table = sheet["idx_table"]
idx_model = sheet["idx_model"]
# Have we started counters for this idx model yet??
if idx_pc not in num_section:
# No, create the counters and start tracking table counts
num_section[idx_pc] = {"ct_meas": 0, "ct_model": 0, "ct_in_model": {}}
# Compare indices to get the highest index number for this table type
# If we have a higher number model index, then increment out models count
try:
# Is this a ens, dist, or summary table?
if idx_model:
# Yes it is.
# Is this model idx higher than ours?
if idx_model > num_section[idx_pc]["ct_model"]:
# Yes. Now, we have N number of model tables.
num_section[idx_pc]["ct_model"] = idx_model
# Have we started counters for this idx model yet??
if idx_model not in num_section[idx_pc]["ct_in_model"]:
# No, create the counters and start tracking table counts.
num_section[idx_pc]["ct_in_model"][idx_model] = {"ct_ens": 0, "ct_sum": 0, "ct_dist": 0}
except Exception as e:
logger_excel.debug("excel: get_table_counts: error incrementing model counts, ".format(e))
# Incrementer!
# For the given table type, track the highest index number.
# That number is how many tables we need to make of that type. Ex. 'measurement4', we need to make 4 empty tables
try:
if tt == "measurement":
# Is this meas table a higher idx?
if idx_table > num_section[idx_pc]["ct_meas"]:
# Yes, set this idx to the counter.
num_section[idx_pc]["ct_meas"] = idx_table
elif tt == "distribution":
# Is this dist table a higher idx?
if idx_table > num_section[idx_pc]["ct_in_model"][idx_model]["ct_dist"]:
# Yes, set this idx to the counter.
num_section[idx_pc]["ct_in_model"][idx_model]["ct_dist"] = idx_table
elif tt == "summary":
# Summary tables are not indexed. Only one per table.
num_section[idx_pc]["ct_in_model"][idx_model]["ct_sum"] = 1
elif tt == "ensemble":
# Ensemble tables are not indexed. Only one per table.
num_section[idx_pc]["ct_in_model"][idx_model]["ct_ens"] = 1
except Exception as e:
logger_excel.debug("excel: get_table_counts: error incrementing table count".format(e))
return num_section | python | def _get_table_counts(sheet, num_section):
"""
Loop through sheet metadata and count how many of each table type is needed at each index.
Example: 'paleo 1' needs {'2 measurement tables', '1 model table, with 1 summary, 1 ensemble, and 3 distributions'}
:param dict sheet: Sheet metadata
:param dict num_section: Rolling number counts of table types for each index.
:return:
"""
tt = sheet["table_type"]
idx_pc = sheet["idx_pc"]
idx_table = sheet["idx_table"]
idx_model = sheet["idx_model"]
# Have we started counters for this idx model yet??
if idx_pc not in num_section:
# No, create the counters and start tracking table counts
num_section[idx_pc] = {"ct_meas": 0, "ct_model": 0, "ct_in_model": {}}
# Compare indices to get the highest index number for this table type
# If we have a higher number model index, then increment out models count
try:
# Is this a ens, dist, or summary table?
if idx_model:
# Yes it is.
# Is this model idx higher than ours?
if idx_model > num_section[idx_pc]["ct_model"]:
# Yes. Now, we have N number of model tables.
num_section[idx_pc]["ct_model"] = idx_model
# Have we started counters for this idx model yet??
if idx_model not in num_section[idx_pc]["ct_in_model"]:
# No, create the counters and start tracking table counts.
num_section[idx_pc]["ct_in_model"][idx_model] = {"ct_ens": 0, "ct_sum": 0, "ct_dist": 0}
except Exception as e:
logger_excel.debug("excel: get_table_counts: error incrementing model counts, ".format(e))
# Incrementer!
# For the given table type, track the highest index number.
# That number is how many tables we need to make of that type. Ex. 'measurement4', we need to make 4 empty tables
try:
if tt == "measurement":
# Is this meas table a higher idx?
if idx_table > num_section[idx_pc]["ct_meas"]:
# Yes, set this idx to the counter.
num_section[idx_pc]["ct_meas"] = idx_table
elif tt == "distribution":
# Is this dist table a higher idx?
if idx_table > num_section[idx_pc]["ct_in_model"][idx_model]["ct_dist"]:
# Yes, set this idx to the counter.
num_section[idx_pc]["ct_in_model"][idx_model]["ct_dist"] = idx_table
elif tt == "summary":
# Summary tables are not indexed. Only one per table.
num_section[idx_pc]["ct_in_model"][idx_model]["ct_sum"] = 1
elif tt == "ensemble":
# Ensemble tables are not indexed. Only one per table.
num_section[idx_pc]["ct_in_model"][idx_model]["ct_ens"] = 1
except Exception as e:
logger_excel.debug("excel: get_table_counts: error incrementing table count".format(e))
return num_section | [
"def",
"_get_table_counts",
"(",
"sheet",
",",
"num_section",
")",
":",
"tt",
"=",
"sheet",
"[",
"\"table_type\"",
"]",
"idx_pc",
"=",
"sheet",
"[",
"\"idx_pc\"",
"]",
"idx_table",
"=",
"sheet",
"[",
"\"idx_table\"",
"]",
"idx_model",
"=",
"sheet",
"[",
"\... | Loop through sheet metadata and count how many of each table type is needed at each index.
Example: 'paleo 1' needs {'2 measurement tables', '1 model table, with 1 summary, 1 ensemble, and 3 distributions'}
:param dict sheet: Sheet metadata
:param dict num_section: Rolling number counts of table types for each index.
:return: | [
"Loop",
"through",
"sheet",
"metadata",
"and",
"count",
"how",
"many",
"of",
"each",
"table",
"type",
"is",
"needed",
"at",
"each",
"index",
".",
"Example",
":",
"paleo",
"1",
"needs",
"{",
"2",
"measurement",
"tables",
"1",
"model",
"table",
"with",
"1"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L451-L512 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _create_skeleton_3 | def _create_skeleton_3(pc, l, num_section):
"""
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict num_section:
:return dict:
"""
logger_excel.info("enter create_skeleton_inner_2")
# Table Template: Model
template_model = {"summaryTable": {}, "ensembleTable": {}, "distributionTable": []}
# Build string appropriate for paleo/chron mode
pc_meas = "{}MeasurementTable".format(pc)
pc_mod = "{}Model".format(pc)
# Loop for each table count
for idx1, table in num_section.items():
try:
# Create N number of empty measurement lists
l[idx1 - 1][pc_meas] = [None] * num_section[idx1]["ct_meas"]
# Create N number of empty model table lists
l[idx1 - 1][pc_mod] = [copy.deepcopy(template_model)] * num_section[idx1]["ct_model"]
# Create N number of empty model tables at list index
#
for idx2, nums in table["ct_in_model"].items():
dists = []
try:
# Create N number of empty distributions at list index
[dists.append({}) for i in range(0, nums["ct_dist"])]
except IndexError as e:
logger_excel.debug("excel: create_metadata_skeleton: paleo tables messed up, {}".format(e))
# Model template complete, insert it at list index
l[idx1 - 1][pc_mod][idx2-1] = {"summaryTable": {}, "ensembleTable": {}, "distributionTable": dists}
except IndexError as e:
logger_excel.warn("create_skeleton_inner_tables: IndexError: {}".format(e))
except KeyError as e:
logger_excel.warn("create_skeleton_inner_tables: KeyError: {}".format(e))
return l | python | def _create_skeleton_3(pc, l, num_section):
"""
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict num_section:
:return dict:
"""
logger_excel.info("enter create_skeleton_inner_2")
# Table Template: Model
template_model = {"summaryTable": {}, "ensembleTable": {}, "distributionTable": []}
# Build string appropriate for paleo/chron mode
pc_meas = "{}MeasurementTable".format(pc)
pc_mod = "{}Model".format(pc)
# Loop for each table count
for idx1, table in num_section.items():
try:
# Create N number of empty measurement lists
l[idx1 - 1][pc_meas] = [None] * num_section[idx1]["ct_meas"]
# Create N number of empty model table lists
l[idx1 - 1][pc_mod] = [copy.deepcopy(template_model)] * num_section[idx1]["ct_model"]
# Create N number of empty model tables at list index
#
for idx2, nums in table["ct_in_model"].items():
dists = []
try:
# Create N number of empty distributions at list index
[dists.append({}) for i in range(0, nums["ct_dist"])]
except IndexError as e:
logger_excel.debug("excel: create_metadata_skeleton: paleo tables messed up, {}".format(e))
# Model template complete, insert it at list index
l[idx1 - 1][pc_mod][idx2-1] = {"summaryTable": {}, "ensembleTable": {}, "distributionTable": dists}
except IndexError as e:
logger_excel.warn("create_skeleton_inner_tables: IndexError: {}".format(e))
except KeyError as e:
logger_excel.warn("create_skeleton_inner_tables: KeyError: {}".format(e))
return l | [
"def",
"_create_skeleton_3",
"(",
"pc",
",",
"l",
",",
"num_section",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter create_skeleton_inner_2\"",
")",
"# Table Template: Model",
"template_model",
"=",
"{",
"\"summaryTable\"",
":",
"{",
"}",
",",
"\"ensembleTabl... | Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict num_section:
:return dict: | [
"Bottom",
"level",
":",
"{",
"measurement",
":",
"[]",
"model",
":",
"[",
"{",
"summary",
"distributions",
"ensemble",
"}",
"]",
"}",
"Fill",
"in",
"measurement",
"and",
"model",
"tables",
"with",
"N",
"number",
"of",
"EMPTY",
"meas",
"summary",
"ensemble"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L515-L558 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _create_skeleton_2 | def _create_skeleton_2(l, pc, num_section, template):
"""
Mid level: {"measurement", "model"}
Fill in paleoData tables with N number of EMPTY measurement and models.
:param list l: paleoData or chronData list of tables
:param dict num_section: Number of tables needed for each table type
:param dict template: The empty template for the measurement and model top section.
:return list: paleoData or chronData list of tables - full skeleton
"""
logger_excel.info("enter create_skeleton_inner_1")
try:
# Create N number of paleoData/chronData tables.
l = [copy.deepcopy(template)] * len(num_section)
# Create the necessary tables inside of "model"
l = _create_skeleton_3(pc, l, num_section)
except Exception as e:
logger_excel.warn("excel: create_skeleton_inner_main: error duplicating template tables, {}".format(e))
return l | python | def _create_skeleton_2(l, pc, num_section, template):
"""
Mid level: {"measurement", "model"}
Fill in paleoData tables with N number of EMPTY measurement and models.
:param list l: paleoData or chronData list of tables
:param dict num_section: Number of tables needed for each table type
:param dict template: The empty template for the measurement and model top section.
:return list: paleoData or chronData list of tables - full skeleton
"""
logger_excel.info("enter create_skeleton_inner_1")
try:
# Create N number of paleoData/chronData tables.
l = [copy.deepcopy(template)] * len(num_section)
# Create the necessary tables inside of "model"
l = _create_skeleton_3(pc, l, num_section)
except Exception as e:
logger_excel.warn("excel: create_skeleton_inner_main: error duplicating template tables, {}".format(e))
return l | [
"def",
"_create_skeleton_2",
"(",
"l",
",",
"pc",
",",
"num_section",
",",
"template",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter create_skeleton_inner_1\"",
")",
"try",
":",
"# Create N number of paleoData/chronData tables.",
"l",
"=",
"[",
"copy",
".",
... | Mid level: {"measurement", "model"}
Fill in paleoData tables with N number of EMPTY measurement and models.
:param list l: paleoData or chronData list of tables
:param dict num_section: Number of tables needed for each table type
:param dict template: The empty template for the measurement and model top section.
:return list: paleoData or chronData list of tables - full skeleton | [
"Mid",
"level",
":",
"{",
"measurement",
"model",
"}",
"Fill",
"in",
"paleoData",
"tables",
"with",
"N",
"number",
"of",
"EMPTY",
"measurement",
"and",
"models",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L561-L580 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _create_skeleton_1 | def _create_skeleton_1(sheets):
"""
Top level: {"chronData", "paleoData"}
Fill in paleoData/chronData tables with N number of EMPTY measurement and models.
:return list: Blank list of N indices
"""
logger_excel.info("enter create_skeleton_main")
# Table template: paleoData
template_paleo = {"paleoMeasurementTable": [], "paleoModel": []}
template_chron = {"chronMeasurementTable": [], "chronModel": []}
num_chron = {}
num_paleo = {}
paleo = []
chron = []
# Get table counts for all table types.
# Table types: paleoData, chronData, model, meas, dist, summary, ensemble
for sheet in sheets:
pc = sheet["paleo_chron"]
# Tree for chron types
if pc == "chron":
num_chron = _get_table_counts(sheet, num_chron)
elif pc == "paleo":
num_paleo = _get_table_counts(sheet, num_paleo)
# Create metadata skeleton for using out table counts.
paleo = _create_skeleton_2(paleo, "paleo", num_paleo, template_paleo)
chron = _create_skeleton_2(chron, "chron", num_chron, template_chron)
logger_excel.info("exit create_skeleton_main")
return paleo, chron | python | def _create_skeleton_1(sheets):
"""
Top level: {"chronData", "paleoData"}
Fill in paleoData/chronData tables with N number of EMPTY measurement and models.
:return list: Blank list of N indices
"""
logger_excel.info("enter create_skeleton_main")
# Table template: paleoData
template_paleo = {"paleoMeasurementTable": [], "paleoModel": []}
template_chron = {"chronMeasurementTable": [], "chronModel": []}
num_chron = {}
num_paleo = {}
paleo = []
chron = []
# Get table counts for all table types.
# Table types: paleoData, chronData, model, meas, dist, summary, ensemble
for sheet in sheets:
pc = sheet["paleo_chron"]
# Tree for chron types
if pc == "chron":
num_chron = _get_table_counts(sheet, num_chron)
elif pc == "paleo":
num_paleo = _get_table_counts(sheet, num_paleo)
# Create metadata skeleton for using out table counts.
paleo = _create_skeleton_2(paleo, "paleo", num_paleo, template_paleo)
chron = _create_skeleton_2(chron, "chron", num_chron, template_chron)
logger_excel.info("exit create_skeleton_main")
return paleo, chron | [
"def",
"_create_skeleton_1",
"(",
"sheets",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter create_skeleton_main\"",
")",
"# Table template: paleoData",
"template_paleo",
"=",
"{",
"\"paleoMeasurementTable\"",
":",
"[",
"]",
",",
"\"paleoModel\"",
":",
"[",
"]",
... | Top level: {"chronData", "paleoData"}
Fill in paleoData/chronData tables with N number of EMPTY measurement and models.
:return list: Blank list of N indices | [
"Top",
"level",
":",
"{",
"chronData",
"paleoData",
"}",
"Fill",
"in",
"paleoData",
"/",
"chronData",
"tables",
"with",
"N",
"number",
"of",
"EMPTY",
"measurement",
"and",
"models",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L583-L617 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _parse_sheet | def _parse_sheet(workbook, sheet):
"""
The universal spreadsheet parser. Parse chron or paleo tables of type ensemble/model/summary.
:param str name: Filename
:param obj workbook: Excel Workbook
:param dict sheet: Sheet path and naming info
:return dict dict: Table metadata and numeric data
"""
logger_excel.info("enter parse_sheet: {}".format(sheet["old_name"]))
# Markers to track where we are on the sheet
ensemble_on = False
var_header_done = False
metadata_on = False
metadata_done = False
data_on = False
notes = False
# Open the sheet from the workbook
temp_sheet = workbook.sheet_by_name(sheet["old_name"])
filename = sheet["filename"]
# Store table metadata and numeric data separately
table_name = "{}DataTableName".format(sheet["paleo_chron"])
# Organize our root table data
table_metadata = OrderedDict()
table_metadata[table_name] = sheet["new_name"]
table_metadata['filename'] = filename
table_metadata['missingValue'] = 'nan'
if "ensemble" in sheet["new_name"]:
ensemble_on = True
# Store all CSV in here by rows
table_data = {filename: []}
# Master list of all column metadata
column_metadata = []
# Index tracks which cells are being parsed
num_col = 0
num_row = 0
nrows = temp_sheet.nrows
col_total = 0
# Tracks which "number" each metadata column is assigned
col_add_ct = 1
header_keys = []
variable_keys = []
variable_keys_lower = []
mv = ""
try:
# Loop for every row in the sheet
for i in range(0, nrows):
# Hold the contents of the current cell
cell = temp_sheet.cell_value(num_row, num_col)
row = temp_sheet.row(num_row)
# Skip all template lines
if isinstance(cell, str):
# Note and missing value entries are rogue. They are not close to the other data entries.
if cell.lower().strip() not in EXCEL_TEMPLATE:
if "notes" in cell.lower() and not metadata_on:
# Store at the root table level
nt = temp_sheet.cell_value(num_row, 1)
if nt not in EXCEL_TEMPLATE:
table_metadata["notes"] = nt
elif cell.lower().strip() in ALTS_MV:
# Store at the root table level and in our function
mv = temp_sheet.cell_value(num_row, 1)
# Add if not placeholder value
if mv not in EXCEL_TEMPLATE:
table_metadata["missingValue"] = mv
# Variable template header row
elif cell.lower() in EXCEL_HEADER and not metadata_on and not data_on:
# Grab the header line
row = temp_sheet.row(num_row)
header_keys = _get_header_keys(row)
# Turn on the marker
var_header_done = True
# Data section (bottom of sheet)
elif data_on:
# Parse the row, clean, and add to table_data
table_data = _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv)
# Metadata section. (top)
elif metadata_on:
# Reached an empty cell while parsing metadata. Mark the end of the section.
if cell in EMPTY:
metadata_on = False
metadata_done = True
# Create a list of all the variable names found
for entry in column_metadata:
try:
# var keys is used as the variableName entry in each column's metadata
variable_keys.append(entry["variableName"].strip())
# var keys lower is used for comparing and finding the data header row
variable_keys_lower.append(entry["variableName"].lower().strip())
except KeyError:
# missing a variableName key
pass
# Not at the end of the section yet. Parse the metadata
else:
# Get the row data
row = temp_sheet.row(num_row)
# Get column metadata
col_tmp = _compile_column_metadata(row, header_keys, col_add_ct)
# Append to master list
column_metadata.append(col_tmp)
col_add_ct += 1
# Variable metadata, if variable header exists
elif var_header_done and not metadata_done:
# Start piecing column metadata together with their respective variable keys
metadata_on = True
# Get the row data
row = temp_sheet.row(num_row)
# Get column metadata
col_tmp = _compile_column_metadata(row, header_keys, col_add_ct)
# Append to master list
column_metadata.append(col_tmp)
col_add_ct += 1
# Variable metadata, if variable header does not exist
elif not var_header_done and not metadata_done and cell:
# LiPD Version 1.1 and earlier: Chronology sheets don't have variable headers
# We could blindly parse, but without a header row_num we wouldn't know where
# to save the metadata
# Play it safe and assume data for first column only: variable name
metadata_on = True
# Get the row data
row = temp_sheet.row(num_row)
# Get column metadata
col_tmp = _compile_column_metadata(row, header_keys, col_add_ct)
# Append to master list
column_metadata.append(col_tmp)
col_add_ct += 1
# Data variable header row. Column metadata exists and metadata_done marker is on.
# This is where we compare top section variableNames to bottom section variableNames to see if
# we need to start parsing the column values
else:
try:
# Clean up variable_keys_lower so we all variable names change from "age(yrs BP)" to "age"
# Units in parenthesis make it too difficult to compare variables. Remove them.
row = _rm_units_from_var_names_multi(row)
if metadata_done and any(i in row for i in variable_keys_lower):
data_on = True
# Take the difference of the two lists. If anything exists, then that's a problem
__compare_vars(row, variable_keys_lower, sheet["old_name"])
# Ensemble columns are counted differently.
if ensemble_on:
# Get the next row, and count the data cells.
col_total = len(temp_sheet.row(num_row+1))
# If there's an empty row, between, then try the next row.
if col_total < 2:
col_total = temp_sheet.row(num_row + 2)
try:
ens_cols = []
[ens_cols.append(i+1) for i in range(0, col_total-1)]
column_metadata[1]["number"] = ens_cols
except IndexError:
logger_excel.debug("excel: parse_sheet: unable to add ensemble 'number' key")
except KeyError:
logger_excel.debug("excel: parse_sheet: unable to add ensemble 'number' list at key")
# All other cass, columns are the length of column_metadata
else:
col_total = len(column_metadata)
except AttributeError:
pass
# cell is not a string, and lower() was not a valid call.
# If this is a numeric cell, 99% chance it's parsing the data columns.
elif isinstance(cell, float) or isinstance(cell, int):
if data_on or metadata_done:
# Parse the row, clean, and add to table_data
table_data = _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv)
# Move on to the next row
num_row += 1
table_metadata["columns"] = column_metadata
except IndexError as e:
logger_excel.debug("parse_sheet: IndexError: sheet: {}, row_num: {}, col_num: {}, {}".format(sheet, num_row, num_col, e))
# If there isn't any data in this sheet, and nothing was parsed, don't let this
# move forward to final output.
if not table_data[filename]:
table_data = None
table_metadata = None
logger_excel.info("exit parse_sheet")
return table_metadata, table_data | python | def _parse_sheet(workbook, sheet):
"""
The universal spreadsheet parser. Parse chron or paleo tables of type ensemble/model/summary.
:param str name: Filename
:param obj workbook: Excel Workbook
:param dict sheet: Sheet path and naming info
:return dict dict: Table metadata and numeric data
"""
logger_excel.info("enter parse_sheet: {}".format(sheet["old_name"]))
# Markers to track where we are on the sheet
ensemble_on = False
var_header_done = False
metadata_on = False
metadata_done = False
data_on = False
notes = False
# Open the sheet from the workbook
temp_sheet = workbook.sheet_by_name(sheet["old_name"])
filename = sheet["filename"]
# Store table metadata and numeric data separately
table_name = "{}DataTableName".format(sheet["paleo_chron"])
# Organize our root table data
table_metadata = OrderedDict()
table_metadata[table_name] = sheet["new_name"]
table_metadata['filename'] = filename
table_metadata['missingValue'] = 'nan'
if "ensemble" in sheet["new_name"]:
ensemble_on = True
# Store all CSV in here by rows
table_data = {filename: []}
# Master list of all column metadata
column_metadata = []
# Index tracks which cells are being parsed
num_col = 0
num_row = 0
nrows = temp_sheet.nrows
col_total = 0
# Tracks which "number" each metadata column is assigned
col_add_ct = 1
header_keys = []
variable_keys = []
variable_keys_lower = []
mv = ""
try:
# Loop for every row in the sheet
for i in range(0, nrows):
# Hold the contents of the current cell
cell = temp_sheet.cell_value(num_row, num_col)
row = temp_sheet.row(num_row)
# Skip all template lines
if isinstance(cell, str):
# Note and missing value entries are rogue. They are not close to the other data entries.
if cell.lower().strip() not in EXCEL_TEMPLATE:
if "notes" in cell.lower() and not metadata_on:
# Store at the root table level
nt = temp_sheet.cell_value(num_row, 1)
if nt not in EXCEL_TEMPLATE:
table_metadata["notes"] = nt
elif cell.lower().strip() in ALTS_MV:
# Store at the root table level and in our function
mv = temp_sheet.cell_value(num_row, 1)
# Add if not placeholder value
if mv not in EXCEL_TEMPLATE:
table_metadata["missingValue"] = mv
# Variable template header row
elif cell.lower() in EXCEL_HEADER and not metadata_on and not data_on:
# Grab the header line
row = temp_sheet.row(num_row)
header_keys = _get_header_keys(row)
# Turn on the marker
var_header_done = True
# Data section (bottom of sheet)
elif data_on:
# Parse the row, clean, and add to table_data
table_data = _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv)
# Metadata section. (top)
elif metadata_on:
# Reached an empty cell while parsing metadata. Mark the end of the section.
if cell in EMPTY:
metadata_on = False
metadata_done = True
# Create a list of all the variable names found
for entry in column_metadata:
try:
# var keys is used as the variableName entry in each column's metadata
variable_keys.append(entry["variableName"].strip())
# var keys lower is used for comparing and finding the data header row
variable_keys_lower.append(entry["variableName"].lower().strip())
except KeyError:
# missing a variableName key
pass
# Not at the end of the section yet. Parse the metadata
else:
# Get the row data
row = temp_sheet.row(num_row)
# Get column metadata
col_tmp = _compile_column_metadata(row, header_keys, col_add_ct)
# Append to master list
column_metadata.append(col_tmp)
col_add_ct += 1
# Variable metadata, if variable header exists
elif var_header_done and not metadata_done:
# Start piecing column metadata together with their respective variable keys
metadata_on = True
# Get the row data
row = temp_sheet.row(num_row)
# Get column metadata
col_tmp = _compile_column_metadata(row, header_keys, col_add_ct)
# Append to master list
column_metadata.append(col_tmp)
col_add_ct += 1
# Variable metadata, if variable header does not exist
elif not var_header_done and not metadata_done and cell:
# LiPD Version 1.1 and earlier: Chronology sheets don't have variable headers
# We could blindly parse, but without a header row_num we wouldn't know where
# to save the metadata
# Play it safe and assume data for first column only: variable name
metadata_on = True
# Get the row data
row = temp_sheet.row(num_row)
# Get column metadata
col_tmp = _compile_column_metadata(row, header_keys, col_add_ct)
# Append to master list
column_metadata.append(col_tmp)
col_add_ct += 1
# Data variable header row. Column metadata exists and metadata_done marker is on.
# This is where we compare top section variableNames to bottom section variableNames to see if
# we need to start parsing the column values
else:
try:
# Clean up variable_keys_lower so we all variable names change from "age(yrs BP)" to "age"
# Units in parenthesis make it too difficult to compare variables. Remove them.
row = _rm_units_from_var_names_multi(row)
if metadata_done and any(i in row for i in variable_keys_lower):
data_on = True
# Take the difference of the two lists. If anything exists, then that's a problem
__compare_vars(row, variable_keys_lower, sheet["old_name"])
# Ensemble columns are counted differently.
if ensemble_on:
# Get the next row, and count the data cells.
col_total = len(temp_sheet.row(num_row+1))
# If there's an empty row, between, then try the next row.
if col_total < 2:
col_total = temp_sheet.row(num_row + 2)
try:
ens_cols = []
[ens_cols.append(i+1) for i in range(0, col_total-1)]
column_metadata[1]["number"] = ens_cols
except IndexError:
logger_excel.debug("excel: parse_sheet: unable to add ensemble 'number' key")
except KeyError:
logger_excel.debug("excel: parse_sheet: unable to add ensemble 'number' list at key")
# All other cass, columns are the length of column_metadata
else:
col_total = len(column_metadata)
except AttributeError:
pass
# cell is not a string, and lower() was not a valid call.
# If this is a numeric cell, 99% chance it's parsing the data columns.
elif isinstance(cell, float) or isinstance(cell, int):
if data_on or metadata_done:
# Parse the row, clean, and add to table_data
table_data = _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv)
# Move on to the next row
num_row += 1
table_metadata["columns"] = column_metadata
except IndexError as e:
logger_excel.debug("parse_sheet: IndexError: sheet: {}, row_num: {}, col_num: {}, {}".format(sheet, num_row, num_col, e))
# If there isn't any data in this sheet, and nothing was parsed, don't let this
# move forward to final output.
if not table_data[filename]:
table_data = None
table_metadata = None
logger_excel.info("exit parse_sheet")
return table_metadata, table_data | [
"def",
"_parse_sheet",
"(",
"workbook",
",",
"sheet",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter parse_sheet: {}\"",
".",
"format",
"(",
"sheet",
"[",
"\"old_name\"",
"]",
")",
")",
"# Markers to track where we are on the sheet",
"ensemble_on",
"=",
"False... | The universal spreadsheet parser. Parse chron or paleo tables of type ensemble/model/summary.
:param str name: Filename
:param obj workbook: Excel Workbook
:param dict sheet: Sheet path and naming info
:return dict dict: Table metadata and numeric data | [
"The",
"universal",
"spreadsheet",
"parser",
".",
"Parse",
"chron",
"or",
"paleo",
"tables",
"of",
"type",
"ensemble",
"/",
"model",
"/",
"summary",
".",
":",
"param",
"str",
"name",
":",
"Filename",
":",
"param",
"obj",
"workbook",
":",
"Excel",
"Workbook... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L623-L841 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _parse_sheet_data_row | def _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv):
"""
Parse a row from the data section of the sheet. Add the cleaned row data to the overall table data.
:param obj temp_sheet: Excel sheet
:param int num_row: Current sheet row
:param int col_total: Number of column variables in this sheet
:param dict table_data: Running record of table data
:param str filename: Filename for this table
:param str mv: Missing value
:return dict: Table data with appended row
"""
# Get row of data
row = temp_sheet.row(num_row)
# In case our row holds more cells than the amount of columns we have, slice the row
# We don't want to have extra empty cells in our output.
row = row[:col_total]
# Replace missing values where necessary
row = _replace_mvs(row, mv)
# Append row to list we will use to write out csv file later.
table_data[filename].append(row)
return table_data | python | def _parse_sheet_data_row(temp_sheet, num_row, col_total, table_data, filename, mv):
"""
Parse a row from the data section of the sheet. Add the cleaned row data to the overall table data.
:param obj temp_sheet: Excel sheet
:param int num_row: Current sheet row
:param int col_total: Number of column variables in this sheet
:param dict table_data: Running record of table data
:param str filename: Filename for this table
:param str mv: Missing value
:return dict: Table data with appended row
"""
# Get row of data
row = temp_sheet.row(num_row)
# In case our row holds more cells than the amount of columns we have, slice the row
# We don't want to have extra empty cells in our output.
row = row[:col_total]
# Replace missing values where necessary
row = _replace_mvs(row, mv)
# Append row to list we will use to write out csv file later.
table_data[filename].append(row)
return table_data | [
"def",
"_parse_sheet_data_row",
"(",
"temp_sheet",
",",
"num_row",
",",
"col_total",
",",
"table_data",
",",
"filename",
",",
"mv",
")",
":",
"# Get row of data",
"row",
"=",
"temp_sheet",
".",
"row",
"(",
"num_row",
")",
"# In case our row holds more cells than the... | Parse a row from the data section of the sheet. Add the cleaned row data to the overall table data.
:param obj temp_sheet: Excel sheet
:param int num_row: Current sheet row
:param int col_total: Number of column variables in this sheet
:param dict table_data: Running record of table data
:param str filename: Filename for this table
:param str mv: Missing value
:return dict: Table data with appended row | [
"Parse",
"a",
"row",
"from",
"the",
"data",
"section",
"of",
"the",
"sheet",
".",
"Add",
"the",
"cleaned",
"row",
"data",
"to",
"the",
"overall",
"table",
"data",
".",
":",
"param",
"obj",
"temp_sheet",
":",
"Excel",
"sheet",
":",
"param",
"int",
"num_... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L844-L868 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _replace_mvs | def _replace_mvs(row, mv):
"""
Replace Missing Values in the data rows where applicable
:param list row: Row
:return list: Modified row
"""
for idx, v in enumerate(row):
try:
if v.value.lower() in EMPTY or v.value.lower() == mv:
row[idx] = "nan"
else:
row[idx] = v.value
except AttributeError:
if v.value == mv:
row[idx] = "nan"
else:
row[idx] = v.value
return row | python | def _replace_mvs(row, mv):
"""
Replace Missing Values in the data rows where applicable
:param list row: Row
:return list: Modified row
"""
for idx, v in enumerate(row):
try:
if v.value.lower() in EMPTY or v.value.lower() == mv:
row[idx] = "nan"
else:
row[idx] = v.value
except AttributeError:
if v.value == mv:
row[idx] = "nan"
else:
row[idx] = v.value
return row | [
"def",
"_replace_mvs",
"(",
"row",
",",
"mv",
")",
":",
"for",
"idx",
",",
"v",
"in",
"enumerate",
"(",
"row",
")",
":",
"try",
":",
"if",
"v",
".",
"value",
".",
"lower",
"(",
")",
"in",
"EMPTY",
"or",
"v",
".",
"value",
".",
"lower",
"(",
"... | Replace Missing Values in the data rows where applicable
:param list row: Row
:return list: Modified row | [
"Replace",
"Missing",
"Values",
"in",
"the",
"data",
"rows",
"where",
"applicable",
":",
"param",
"list",
"row",
":",
"Row",
":",
"return",
"list",
":",
"Modified",
"row"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L871-L889 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _get_header_keys | def _get_header_keys(row):
"""
Get the variable header keys from this special row
:return list: Header keys
"""
# Swap out NOAA keys for LiPD keys
for idx, key in enumerate(row):
key_low = key.value.lower()
# Simple case: Nothing fancy here, just map to the LiPD key counterpart.
if key_low in EXCEL_LIPD_MAP_FLAT:
row[idx] = EXCEL_LIPD_MAP_FLAT[key_low]
# Nested data case: Check if this is a calibration, interpretation, or some other data that needs to be nested.
# elif key_low:
# pass
# Unknown key case: Store the key as-is because we don't have a LiPD mapping for it.
else:
try:
row[idx] = key.value
except AttributeError as e:
logger_excel.warn("excel_main: get_header_keys: unknown header key, unable to add: {}".format(e))
# Since we took a whole row of cells, we have to drop off the empty cells at the end of the row.
header_keys = _rm_cells_reverse(row)
return header_keys | python | def _get_header_keys(row):
"""
Get the variable header keys from this special row
:return list: Header keys
"""
# Swap out NOAA keys for LiPD keys
for idx, key in enumerate(row):
key_low = key.value.lower()
# Simple case: Nothing fancy here, just map to the LiPD key counterpart.
if key_low in EXCEL_LIPD_MAP_FLAT:
row[idx] = EXCEL_LIPD_MAP_FLAT[key_low]
# Nested data case: Check if this is a calibration, interpretation, or some other data that needs to be nested.
# elif key_low:
# pass
# Unknown key case: Store the key as-is because we don't have a LiPD mapping for it.
else:
try:
row[idx] = key.value
except AttributeError as e:
logger_excel.warn("excel_main: get_header_keys: unknown header key, unable to add: {}".format(e))
# Since we took a whole row of cells, we have to drop off the empty cells at the end of the row.
header_keys = _rm_cells_reverse(row)
return header_keys | [
"def",
"_get_header_keys",
"(",
"row",
")",
":",
"# Swap out NOAA keys for LiPD keys",
"for",
"idx",
",",
"key",
"in",
"enumerate",
"(",
"row",
")",
":",
"key_low",
"=",
"key",
".",
"value",
".",
"lower",
"(",
")",
"# Simple case: Nothing fancy here, just map to t... | Get the variable header keys from this special row
:return list: Header keys | [
"Get",
"the",
"variable",
"header",
"keys",
"from",
"this",
"special",
"row",
":",
"return",
"list",
":",
"Header",
"keys"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L892-L918 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _rm_units_from_var_name_single | def _rm_units_from_var_name_single(var):
"""
NOTE: USE THIS FOR SINGLE CELLS ONLY
When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections
However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes problems.
We're using this regex to match all variableName cells and remove the "(years BP)" where applicable.
:param str var: Variable name
:return str: Variable name
"""
# Use the regex to match the cell
m = re.match(re_var_w_units, var)
# Should always get a match, but be careful anyways.
if m:
# m.group(1): variableName
# m.group(2): units in parenthesis (may not exist).
try:
var = m.group(1).strip().lower()
# var = m.group(1).strip().lower()
except Exception:
# This must be a malformed cell somehow. This regex should match every variableName cell.
# It didn't work out. Return the original var as a fallback
pass
return var | python | def _rm_units_from_var_name_single(var):
"""
NOTE: USE THIS FOR SINGLE CELLS ONLY
When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections
However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes problems.
We're using this regex to match all variableName cells and remove the "(years BP)" where applicable.
:param str var: Variable name
:return str: Variable name
"""
# Use the regex to match the cell
m = re.match(re_var_w_units, var)
# Should always get a match, but be careful anyways.
if m:
# m.group(1): variableName
# m.group(2): units in parenthesis (may not exist).
try:
var = m.group(1).strip().lower()
# var = m.group(1).strip().lower()
except Exception:
# This must be a malformed cell somehow. This regex should match every variableName cell.
# It didn't work out. Return the original var as a fallback
pass
return var | [
"def",
"_rm_units_from_var_name_single",
"(",
"var",
")",
":",
"# Use the regex to match the cell",
"m",
"=",
"re",
".",
"match",
"(",
"re_var_w_units",
",",
"var",
")",
"# Should always get a match, but be careful anyways.",
"if",
"m",
":",
"# m.group(1): variableName",
... | NOTE: USE THIS FOR SINGLE CELLS ONLY
When parsing sheets, all variable names be exact matches when cross-referenceing the metadata and data sections
However, sometimes people like to put "age (years BP)" in one section, and "age" in the other. This causes problems.
We're using this regex to match all variableName cells and remove the "(years BP)" where applicable.
:param str var: Variable name
:return str: Variable name | [
"NOTE",
":",
"USE",
"THIS",
"FOR",
"SINGLE",
"CELLS",
"ONLY",
"When",
"parsing",
"sheets",
"all",
"variable",
"names",
"be",
"exact",
"matches",
"when",
"cross",
"-",
"referenceing",
"the",
"metadata",
"and",
"data",
"sections",
"However",
"sometimes",
"people... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L921-L943 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _rm_units_from_var_names_multi | def _rm_units_from_var_names_multi(row):
"""
Wrapper around "_rm_units_from_var_name_single" for doing a list instead of a single cell.
:param list row: Variable names
:return list: Variable names
"""
l2 = []
# Check each var in the row
for idx, var in enumerate(row):
l2.append(_rm_units_from_var_name_single(row[idx].value))
return l2 | python | def _rm_units_from_var_names_multi(row):
"""
Wrapper around "_rm_units_from_var_name_single" for doing a list instead of a single cell.
:param list row: Variable names
:return list: Variable names
"""
l2 = []
# Check each var in the row
for idx, var in enumerate(row):
l2.append(_rm_units_from_var_name_single(row[idx].value))
return l2 | [
"def",
"_rm_units_from_var_names_multi",
"(",
"row",
")",
":",
"l2",
"=",
"[",
"]",
"# Check each var in the row",
"for",
"idx",
",",
"var",
"in",
"enumerate",
"(",
"row",
")",
":",
"l2",
".",
"append",
"(",
"_rm_units_from_var_name_single",
"(",
"row",
"[",
... | Wrapper around "_rm_units_from_var_name_single" for doing a list instead of a single cell.
:param list row: Variable names
:return list: Variable names | [
"Wrapper",
"around",
"_rm_units_from_var_name_single",
"for",
"doing",
"a",
"list",
"instead",
"of",
"a",
"single",
"cell",
".",
":",
"param",
"list",
"row",
":",
"Variable",
"names",
":",
"return",
"list",
":",
"Variable",
"names"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L946-L956 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _compile_interpretation | def _compile_interpretation(data):
"""
Compile the interpretation data into a list of multiples, based on the keys provided.
Disassemble the key to figure out how to place the data
:param dict data: Interpretation data (unsorted)
:return dict: Interpretation data (sorted)
"""
# KEY FORMAT : "interpretation1_somekey"
_count = 0
# Determine how many entries we are going to need, by checking the interpretation index in the string
for _key in data.keys():
_key_low = _key.lower()
# Get regex match
m = re.match(re_interpretation, _key_low)
# If regex match was successful..
if m:
# Check if this interpretation count is higher than what we have.
_curr_count = int(m.group(1))
if _curr_count > _count:
# New max count, record it.
_count = _curr_count
# Create the empty list with X entries for the interpretation data
_tmp = [{} for i in range(0, _count)]
# Loop over all the interpretation keys and data
for k, v in data.items():
# Get the resulting regex data.
# EXAMPLE ENTRY: "interpretation1_variable"
# REGEX RESULT: ["1", "variable"]
m = re.match(re_interpretation, k)
# Get the interpretation index number
idx = int(m.group(1))
# Get the field variable
key = m.group(2)
# Place this data in the _tmp array. Remember to adjust given index number for 0-indexing
_tmp[idx-1][key] = v
# Return compiled interpretation data
return _tmp | python | def _compile_interpretation(data):
"""
Compile the interpretation data into a list of multiples, based on the keys provided.
Disassemble the key to figure out how to place the data
:param dict data: Interpretation data (unsorted)
:return dict: Interpretation data (sorted)
"""
# KEY FORMAT : "interpretation1_somekey"
_count = 0
# Determine how many entries we are going to need, by checking the interpretation index in the string
for _key in data.keys():
_key_low = _key.lower()
# Get regex match
m = re.match(re_interpretation, _key_low)
# If regex match was successful..
if m:
# Check if this interpretation count is higher than what we have.
_curr_count = int(m.group(1))
if _curr_count > _count:
# New max count, record it.
_count = _curr_count
# Create the empty list with X entries for the interpretation data
_tmp = [{} for i in range(0, _count)]
# Loop over all the interpretation keys and data
for k, v in data.items():
# Get the resulting regex data.
# EXAMPLE ENTRY: "interpretation1_variable"
# REGEX RESULT: ["1", "variable"]
m = re.match(re_interpretation, k)
# Get the interpretation index number
idx = int(m.group(1))
# Get the field variable
key = m.group(2)
# Place this data in the _tmp array. Remember to adjust given index number for 0-indexing
_tmp[idx-1][key] = v
# Return compiled interpretation data
return _tmp | [
"def",
"_compile_interpretation",
"(",
"data",
")",
":",
"# KEY FORMAT : \"interpretation1_somekey\"",
"_count",
"=",
"0",
"# Determine how many entries we are going to need, by checking the interpretation index in the string",
"for",
"_key",
"in",
"data",
".",
"keys",
"(",
")",
... | Compile the interpretation data into a list of multiples, based on the keys provided.
Disassemble the key to figure out how to place the data
:param dict data: Interpretation data (unsorted)
:return dict: Interpretation data (sorted) | [
"Compile",
"the",
"interpretation",
"data",
"into",
"a",
"list",
"of",
"multiples",
"based",
"on",
"the",
"keys",
"provided",
".",
"Disassemble",
"the",
"key",
"to",
"figure",
"out",
"how",
"to",
"place",
"the",
"data",
":",
"param",
"dict",
"data",
":",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L959-L999 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _compile_column_metadata | def _compile_column_metadata(row, keys, number):
"""
Compile column metadata from one excel row ("9 part data")
:param list row: Row of cells
:param list keys: Variable header keys
:return dict: Column metadata
"""
# Store the variable keys by index in a dictionary
_column = {}
_interpretation = {}
_calibration = {}
_physical = {}
# Use the header keys to place the column data in the dictionary
if keys:
for idx, key in enumerate(keys):
_key_low = key.lower()
# Special case: Calibration data
if re.match(re_calibration, _key_low):
m = re.match(re_calibration, _key_low)
if m:
_key = m.group(1)
_calibration[_key] = row[idx].value
# Special case: PhysicalSample data
elif re.match(re_physical, _key_low):
m = re.match(re_physical, _key_low)
if m:
_key = m.group(1)
_physical[_key] = row[idx].value
# Special case: Interpretation data
elif re.match(re_interpretation, _key_low):
# Put interpretation data in a tmp dictionary that we'll sort later.
_interpretation[_key_low] = row[idx].value
else:
try:
val = row[idx].value
except Exception:
logger_excel.info("compile_column_metadata: Couldn't get value from row cell")
val = "n/a"
try:
if key == "variableName":
val = _rm_units_from_var_name_single(row[idx].value)
except Exception:
# when a variableName fails to split, keep the name as-is and move on.
pass
_column[key] = val
_column["number"] = number
if _calibration:
_column["calibration"] = _calibration
# Only allow physicalSample on measured variableTypes. duh.
if _physical and _column["variableType"] == "measured":
_column["physicalSample"] = _physical
if _interpretation:
_interpretation_data = _compile_interpretation(_interpretation)
_column["interpretation"] = _interpretation_data
# If there are not keys, that means it's a header-less metadata section.
else:
# Assume we only have one cell, because we have no keys to know what data is here.
try:
val = row[0].value.lower()
except AttributeError:
val = row[0].value
except Exception:
logger_excel.info("compile_column_metadata: Couldn't get value from row cell")
val = "n/a"
val = _rm_units_from_var_name_single(val)
_column["variableName"] = val
_column["number"] = number
# Add this column to the overall metadata, but skip if there's no data present
_column = {k: v for k, v in _column.items() if v}
return _column | python | def _compile_column_metadata(row, keys, number):
"""
Compile column metadata from one excel row ("9 part data")
:param list row: Row of cells
:param list keys: Variable header keys
:return dict: Column metadata
"""
# Store the variable keys by index in a dictionary
_column = {}
_interpretation = {}
_calibration = {}
_physical = {}
# Use the header keys to place the column data in the dictionary
if keys:
for idx, key in enumerate(keys):
_key_low = key.lower()
# Special case: Calibration data
if re.match(re_calibration, _key_low):
m = re.match(re_calibration, _key_low)
if m:
_key = m.group(1)
_calibration[_key] = row[idx].value
# Special case: PhysicalSample data
elif re.match(re_physical, _key_low):
m = re.match(re_physical, _key_low)
if m:
_key = m.group(1)
_physical[_key] = row[idx].value
# Special case: Interpretation data
elif re.match(re_interpretation, _key_low):
# Put interpretation data in a tmp dictionary that we'll sort later.
_interpretation[_key_low] = row[idx].value
else:
try:
val = row[idx].value
except Exception:
logger_excel.info("compile_column_metadata: Couldn't get value from row cell")
val = "n/a"
try:
if key == "variableName":
val = _rm_units_from_var_name_single(row[idx].value)
except Exception:
# when a variableName fails to split, keep the name as-is and move on.
pass
_column[key] = val
_column["number"] = number
if _calibration:
_column["calibration"] = _calibration
# Only allow physicalSample on measured variableTypes. duh.
if _physical and _column["variableType"] == "measured":
_column["physicalSample"] = _physical
if _interpretation:
_interpretation_data = _compile_interpretation(_interpretation)
_column["interpretation"] = _interpretation_data
# If there are not keys, that means it's a header-less metadata section.
else:
# Assume we only have one cell, because we have no keys to know what data is here.
try:
val = row[0].value.lower()
except AttributeError:
val = row[0].value
except Exception:
logger_excel.info("compile_column_metadata: Couldn't get value from row cell")
val = "n/a"
val = _rm_units_from_var_name_single(val)
_column["variableName"] = val
_column["number"] = number
# Add this column to the overall metadata, but skip if there's no data present
_column = {k: v for k, v in _column.items() if v}
return _column | [
"def",
"_compile_column_metadata",
"(",
"row",
",",
"keys",
",",
"number",
")",
":",
"# Store the variable keys by index in a dictionary",
"_column",
"=",
"{",
"}",
"_interpretation",
"=",
"{",
"}",
"_calibration",
"=",
"{",
"}",
"_physical",
"=",
"{",
"}",
"# U... | Compile column metadata from one excel row ("9 part data")
:param list row: Row of cells
:param list keys: Variable header keys
:return dict: Column metadata | [
"Compile",
"column",
"metadata",
"from",
"one",
"excel",
"row",
"(",
"9",
"part",
"data",
")",
":",
"param",
"list",
"row",
":",
"Row",
"of",
"cells",
":",
"param",
"list",
"keys",
":",
"Variable",
"header",
"keys",
":",
"return",
"dict",
":",
"Column"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1002-L1080 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _rm_cells_reverse | def _rm_cells_reverse(l):
"""
Remove the cells that are empty or template in reverse order. Stop when you hit data.
:param list l: One row from the spreadsheet
:return list: Modified row
"""
rm = []
# Iter the list in reverse, and get rid of empty and template cells
for idx, key in reversed(list(enumerate(l))):
if key.lower() in EXCEL_TEMPLATE:
rm.append(idx)
elif key in EMPTY:
rm.append(idx)
else:
break
for idx in rm:
l.pop(idx)
return l | python | def _rm_cells_reverse(l):
"""
Remove the cells that are empty or template in reverse order. Stop when you hit data.
:param list l: One row from the spreadsheet
:return list: Modified row
"""
rm = []
# Iter the list in reverse, and get rid of empty and template cells
for idx, key in reversed(list(enumerate(l))):
if key.lower() in EXCEL_TEMPLATE:
rm.append(idx)
elif key in EMPTY:
rm.append(idx)
else:
break
for idx in rm:
l.pop(idx)
return l | [
"def",
"_rm_cells_reverse",
"(",
"l",
")",
":",
"rm",
"=",
"[",
"]",
"# Iter the list in reverse, and get rid of empty and template cells",
"for",
"idx",
",",
"key",
"in",
"reversed",
"(",
"list",
"(",
"enumerate",
"(",
"l",
")",
")",
")",
":",
"if",
"key",
... | Remove the cells that are empty or template in reverse order. Stop when you hit data.
:param list l: One row from the spreadsheet
:return list: Modified row | [
"Remove",
"the",
"cells",
"that",
"are",
"empty",
"or",
"template",
"in",
"reverse",
"order",
".",
"Stop",
"when",
"you",
"hit",
"data",
".",
":",
"param",
"list",
"l",
":",
"One",
"row",
"from",
"the",
"spreadsheet",
":",
"return",
"list",
":",
"Modif... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1083-L1101 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _write_data_csv | def _write_data_csv(csv_data):
"""
CSV data has been parsed by this point, so take it and write it file by file.
:return:
"""
logger_excel.info("enter write_data_csv")
# Loop for each file and data that is stored
for file in csv_data:
for filename, data in file.items():
# Make sure we're working with the right data types before trying to open and write a file
if isinstance(filename, str) and isinstance(data, list):
try:
with open(filename, 'w+') as f:
w = csv.writer(f)
for line in data:
w.writerow(line)
except Exception:
logger_excel.debug("write_data_csv: Unable to open/write file: {}".format(filename))
logger_excel.info("exit write_data_csv")
return | python | def _write_data_csv(csv_data):
"""
CSV data has been parsed by this point, so take it and write it file by file.
:return:
"""
logger_excel.info("enter write_data_csv")
# Loop for each file and data that is stored
for file in csv_data:
for filename, data in file.items():
# Make sure we're working with the right data types before trying to open and write a file
if isinstance(filename, str) and isinstance(data, list):
try:
with open(filename, 'w+') as f:
w = csv.writer(f)
for line in data:
w.writerow(line)
except Exception:
logger_excel.debug("write_data_csv: Unable to open/write file: {}".format(filename))
logger_excel.info("exit write_data_csv")
return | [
"def",
"_write_data_csv",
"(",
"csv_data",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter write_data_csv\"",
")",
"# Loop for each file and data that is stored",
"for",
"file",
"in",
"csv_data",
":",
"for",
"filename",
",",
"data",
"in",
"file",
".",
"items",
... | CSV data has been parsed by this point, so take it and write it file by file.
:return: | [
"CSV",
"data",
"has",
"been",
"parsed",
"by",
"this",
"point",
"so",
"take",
"it",
"and",
"write",
"it",
"file",
"by",
"file",
".",
":",
"return",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1107-L1127 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | geometry_linestring | def geometry_linestring(lat, lon, elev):
"""
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
"""
logger_excel.info("enter geometry_linestring")
d = OrderedDict()
coordinates = []
temp = ["", ""]
# Point type, Matching pairs.
if lat[0] == lat[1] and lon[0] == lon[1]:
logger_excel.info("matching geo coordinate")
lat.pop()
lon.pop()
d = geometry_point(lat, lon, elev)
else:
# Creates coordinates list
logger_excel.info("unique geo coordinates")
for i in lon:
temp[0] = i
for j in lat:
temp[1] = j
coordinates.append(copy.copy(temp))
if elev:
for i in coordinates:
i.append(elev)
# Create geometry block
d['type'] = 'Linestring'
d['coordinates'] = coordinates
logger_excel.info("exit geometry_linestring")
return d | python | def geometry_linestring(lat, lon, elev):
"""
GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict:
"""
logger_excel.info("enter geometry_linestring")
d = OrderedDict()
coordinates = []
temp = ["", ""]
# Point type, Matching pairs.
if lat[0] == lat[1] and lon[0] == lon[1]:
logger_excel.info("matching geo coordinate")
lat.pop()
lon.pop()
d = geometry_point(lat, lon, elev)
else:
# Creates coordinates list
logger_excel.info("unique geo coordinates")
for i in lon:
temp[0] = i
for j in lat:
temp[1] = j
coordinates.append(copy.copy(temp))
if elev:
for i in coordinates:
i.append(elev)
# Create geometry block
d['type'] = 'Linestring'
d['coordinates'] = coordinates
logger_excel.info("exit geometry_linestring")
return d | [
"def",
"geometry_linestring",
"(",
"lat",
",",
"lon",
",",
"elev",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter geometry_linestring\"",
")",
"d",
"=",
"OrderedDict",
"(",
")",
"coordinates",
"=",
"[",
"]",
"temp",
"=",
"[",
"\"\"",
",",
"\"\"",
"... | GeoJSON Linestring. Latitude and Longitude have 2 values each.
:param list lat: Latitude values
:param list lon: Longitude values
:return dict: | [
"GeoJSON",
"Linestring",
".",
"Latitude",
"and",
"Longitude",
"have",
"2",
"values",
"each",
".",
":",
"param",
"list",
"lat",
":",
"Latitude",
"values",
":",
"param",
"list",
"lon",
":",
"Longitude",
"values",
":",
"return",
"dict",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1132-L1166 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | geometry_range | def geometry_range(crd_range, elev, crd_type):
"""
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict:
"""
d = OrderedDict()
coordinates = [[] for i in range(len(crd_range))]
# latitude
if crd_type == "lat":
for idx, i in enumerate(crd_range):
coordinates[idx] = [crd_range[idx], "nan"]
if elev:
coordinates[idx].append(elev)
# longitude
elif crd_type == "lon":
for idx, i in enumerate(crd_range):
coordinates[idx] = ["nan", crd_range[idx]]
if elev:
coordinates[idx].append(elev)
d["type"] = "Range"
d["coordinates"] = coordinates
return d | python | def geometry_range(crd_range, elev, crd_type):
"""
Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict:
"""
d = OrderedDict()
coordinates = [[] for i in range(len(crd_range))]
# latitude
if crd_type == "lat":
for idx, i in enumerate(crd_range):
coordinates[idx] = [crd_range[idx], "nan"]
if elev:
coordinates[idx].append(elev)
# longitude
elif crd_type == "lon":
for idx, i in enumerate(crd_range):
coordinates[idx] = ["nan", crd_range[idx]]
if elev:
coordinates[idx].append(elev)
d["type"] = "Range"
d["coordinates"] = coordinates
return d | [
"def",
"geometry_range",
"(",
"crd_range",
",",
"elev",
",",
"crd_type",
")",
":",
"d",
"=",
"OrderedDict",
"(",
")",
"coordinates",
"=",
"[",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"crd_range",
")",
")",
"]",
"# latitude",
"if",
"crd_... | Range of coordinates. (e.g. 2 latitude coordinates, and 0 longitude coordinates)
:param crd_range: Latitude or Longitude values
:param elev: Elevation value
:param crd_type: Coordinate type, lat or lon
:return dict: | [
"Range",
"of",
"coordinates",
".",
"(",
"e",
".",
"g",
".",
"2",
"latitude",
"coordinates",
"and",
"0",
"longitude",
"coordinates",
")",
":",
"param",
"crd_range",
":",
"Latitude",
"or",
"Longitude",
"values",
":",
"param",
"elev",
":",
"Elevation",
"value... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1169-L1198 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | geometry_point | def geometry_point(lat, lon, elev):
"""
GeoJSON point. Latitude and Longitude only have one value each
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter geometry_point")
coordinates = []
point_dict = OrderedDict()
for idx, val in enumerate(lat):
try:
coordinates.append(lon[idx])
coordinates.append(lat[idx])
except IndexError as e:
print("Error: Invalid geo coordinates")
logger_excel.debug("geometry_point: IndexError: lat: {}, lon: {}, {}".format(lat, lon, e))
coordinates.append(elev)
point_dict['type'] = 'Point'
point_dict['coordinates'] = coordinates
logger_excel.info("exit geometry_point")
return point_dict | python | def geometry_point(lat, lon, elev):
"""
GeoJSON point. Latitude and Longitude only have one value each
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter geometry_point")
coordinates = []
point_dict = OrderedDict()
for idx, val in enumerate(lat):
try:
coordinates.append(lon[idx])
coordinates.append(lat[idx])
except IndexError as e:
print("Error: Invalid geo coordinates")
logger_excel.debug("geometry_point: IndexError: lat: {}, lon: {}, {}".format(lat, lon, e))
coordinates.append(elev)
point_dict['type'] = 'Point'
point_dict['coordinates'] = coordinates
logger_excel.info("exit geometry_point")
return point_dict | [
"def",
"geometry_point",
"(",
"lat",
",",
"lon",
",",
"elev",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter geometry_point\"",
")",
"coordinates",
"=",
"[",
"]",
"point_dict",
"=",
"OrderedDict",
"(",
")",
"for",
"idx",
",",
"val",
"in",
"enumerate"... | GeoJSON point. Latitude and Longitude only have one value each
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict: | [
"GeoJSON",
"point",
".",
"Latitude",
"and",
"Longitude",
"only",
"have",
"one",
"value",
"each",
":",
"param",
"list",
"lat",
":",
"Latitude",
"values",
":",
"param",
"list",
"lon",
":",
"Longitude",
"values",
":",
"param",
"float",
"elev",
":",
"Elevation... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1201-L1224 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | compile_geometry | def compile_geometry(lat, lon, elev):
"""
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter compile_geometry")
lat = _remove_geo_placeholders(lat)
lon = _remove_geo_placeholders(lon)
# 4 coordinate values
if len(lat) == 2 and len(lon) == 2:
logger_excel.info("found 4 coordinates")
geo_dict = geometry_linestring(lat, lon, elev)
# # 4 coordinate values
# if (lat[0] != lat[1]) and (lon[0] != lon[1]):
# geo_dict = geometry_polygon(lat, lon)
# # 3 unique coordinates
# else:
# geo_dict = geometry_multipoint(lat, lon)
#
# 2 coordinate values
elif len(lat) == 1 and len(lon) == 1:
logger_excel.info("found 2 coordinates")
geo_dict = geometry_point(lat, lon, elev)
# coordinate range. one value given but not the other.
elif (None in lon and None not in lat) or (len(lat) > 0 and len(lon) == 0):
geo_dict = geometry_range(lat, elev, "lat")
elif (None in lat and None not in lon) or (len(lon) > 0 and len(lat) == 0):
geo_dict = geometry_range(lat, elev, "lon")
# Too many points, or no points
else:
geo_dict = {}
logger_excel.warn("compile_geometry: invalid coordinates: lat: {}, lon: {}".format(lat, lon))
logger_excel.info("exit compile_geometry")
return geo_dict | python | def compile_geometry(lat, lon, elev):
"""
Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict:
"""
logger_excel.info("enter compile_geometry")
lat = _remove_geo_placeholders(lat)
lon = _remove_geo_placeholders(lon)
# 4 coordinate values
if len(lat) == 2 and len(lon) == 2:
logger_excel.info("found 4 coordinates")
geo_dict = geometry_linestring(lat, lon, elev)
# # 4 coordinate values
# if (lat[0] != lat[1]) and (lon[0] != lon[1]):
# geo_dict = geometry_polygon(lat, lon)
# # 3 unique coordinates
# else:
# geo_dict = geometry_multipoint(lat, lon)
#
# 2 coordinate values
elif len(lat) == 1 and len(lon) == 1:
logger_excel.info("found 2 coordinates")
geo_dict = geometry_point(lat, lon, elev)
# coordinate range. one value given but not the other.
elif (None in lon and None not in lat) or (len(lat) > 0 and len(lon) == 0):
geo_dict = geometry_range(lat, elev, "lat")
elif (None in lat and None not in lon) or (len(lon) > 0 and len(lat) == 0):
geo_dict = geometry_range(lat, elev, "lon")
# Too many points, or no points
else:
geo_dict = {}
logger_excel.warn("compile_geometry: invalid coordinates: lat: {}, lon: {}".format(lat, lon))
logger_excel.info("exit compile_geometry")
return geo_dict | [
"def",
"compile_geometry",
"(",
"lat",
",",
"lon",
",",
"elev",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter compile_geometry\"",
")",
"lat",
"=",
"_remove_geo_placeholders",
"(",
"lat",
")",
"lon",
"=",
"_remove_geo_placeholders",
"(",
"lon",
")",
"# ... | Take in lists of lat and lon coordinates, and determine what geometry to create
:param list lat: Latitude values
:param list lon: Longitude values
:param float elev: Elevation value
:return dict: | [
"Take",
"in",
"lists",
"of",
"lat",
"and",
"lon",
"coordinates",
"and",
"determine",
"what",
"geometry",
"to",
"create",
":",
"param",
"list",
"lat",
":",
"Latitude",
"values",
":",
"param",
"list",
"lon",
":",
"Longitude",
"values",
":",
"param",
"float",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1227-L1269 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | compile_geo | def compile_geo(d):
"""
Compile top-level Geography dictionary.
:param d:
:return:
"""
logger_excel.info("enter compile_geo")
d2 = OrderedDict()
# get max number of sites, or number of coordinate points given.
num_loc = _get_num_locations(d)
# if there's one more than one location put it in a collection
if num_loc > 1:
d2["type"] = "FeatureCollection"
features = []
for idx in range(0, num_loc):
# Do process for one site
site = _parse_geo_locations(d, idx)
features.append(site)
d2["features"] = features
# if there's only one location
elif num_loc == 1:
d2 = _parse_geo_location(d)
logger_excel.info("exit compile_geo")
return d2 | python | def compile_geo(d):
"""
Compile top-level Geography dictionary.
:param d:
:return:
"""
logger_excel.info("enter compile_geo")
d2 = OrderedDict()
# get max number of sites, or number of coordinate points given.
num_loc = _get_num_locations(d)
# if there's one more than one location put it in a collection
if num_loc > 1:
d2["type"] = "FeatureCollection"
features = []
for idx in range(0, num_loc):
# Do process for one site
site = _parse_geo_locations(d, idx)
features.append(site)
d2["features"] = features
# if there's only one location
elif num_loc == 1:
d2 = _parse_geo_location(d)
logger_excel.info("exit compile_geo")
return d2 | [
"def",
"compile_geo",
"(",
"d",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter compile_geo\"",
")",
"d2",
"=",
"OrderedDict",
"(",
")",
"# get max number of sites, or number of coordinate points given.",
"num_loc",
"=",
"_get_num_locations",
"(",
"d",
")",
"# if... | Compile top-level Geography dictionary.
:param d:
:return: | [
"Compile",
"top",
"-",
"level",
"Geography",
"dictionary",
".",
":",
"param",
"d",
":",
":",
"return",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1272-L1299 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _get_num_locations | def _get_num_locations(d):
"""
Find out how many locations are being parsed. Compare lengths of each
coordinate list and return the max
:param dict d: Geo metadata
:return int: Max number of locations
"""
lengths = []
for key in EXCEL_GEO:
try:
if key != "siteName":
lengths.append(len(d[key]))
except Exception:
lengths.append(1)
try:
num = max(lengths)
except ValueError:
num = 0
return num | python | def _get_num_locations(d):
"""
Find out how many locations are being parsed. Compare lengths of each
coordinate list and return the max
:param dict d: Geo metadata
:return int: Max number of locations
"""
lengths = []
for key in EXCEL_GEO:
try:
if key != "siteName":
lengths.append(len(d[key]))
except Exception:
lengths.append(1)
try:
num = max(lengths)
except ValueError:
num = 0
return num | [
"def",
"_get_num_locations",
"(",
"d",
")",
":",
"lengths",
"=",
"[",
"]",
"for",
"key",
"in",
"EXCEL_GEO",
":",
"try",
":",
"if",
"key",
"!=",
"\"siteName\"",
":",
"lengths",
".",
"append",
"(",
"len",
"(",
"d",
"[",
"key",
"]",
")",
")",
"except"... | Find out how many locations are being parsed. Compare lengths of each
coordinate list and return the max
:param dict d: Geo metadata
:return int: Max number of locations | [
"Find",
"out",
"how",
"many",
"locations",
"are",
"being",
"parsed",
".",
"Compare",
"lengths",
"of",
"each",
"coordinate",
"list",
"and",
"return",
"the",
"max",
":",
"param",
"dict",
"d",
":",
"Geo",
"metadata",
":",
"return",
"int",
":",
"Max",
"numbe... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1302-L1321 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _parse_geo_location | def _parse_geo_location(d):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ""
# Compile the geometry based on the info available.
d2['geometry'] = compile_geometry([d['latMin'], d['latMax']], [d['lonMin'], d['lonMax']], d['elevation'])
d2['properties'] = {'siteName': d['siteName']}
return d2 | python | def _parse_geo_location(d):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ""
# Compile the geometry based on the info available.
d2['geometry'] = compile_geometry([d['latMin'], d['latMax']], [d['lonMin'], d['lonMax']], d['elevation'])
d2['properties'] = {'siteName': d['siteName']}
return d2 | [
"def",
"_parse_geo_location",
"(",
"d",
")",
":",
"d2",
"=",
"OrderedDict",
"(",
")",
"filt",
"=",
"{",
"}",
"d2",
"[",
"'type'",
"]",
"=",
"'Feature'",
"# If the necessary keys are missing, put in placeholders so there's no KeyErrors.",
"for",
"key",
"in",
"EXCEL_G... | Parse one geo location
:param d:
:return: | [
"Parse",
"one",
"geo",
"location",
":",
"param",
"d",
":",
":",
"return",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1324-L1342 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _parse_geo_locations | def _parse_geo_locations(d, idx):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ""
for key in EXCEL_GEO:
try:
if key == "siteName" and isinstance(d["siteName"], str):
filt["siteName"] = d["siteName"]
else:
filt[key] = d[key][idx]
except KeyError:
filt[key] = None
except TypeError:
filt[key] = None
# Compile the geometry based on the info available.
d2['geometry'] = compile_geometry([filt['latMin'], filt['latMax']], [filt['lonMin'], filt['lonMax']], filt['elevation'])
d2['properties'] = {'siteName': filt['siteName']}
return d2 | python | def _parse_geo_locations(d, idx):
"""
Parse one geo location
:param d:
:return:
"""
d2 = OrderedDict()
filt = {}
d2['type'] = 'Feature'
# If the necessary keys are missing, put in placeholders so there's no KeyErrors.
for key in EXCEL_GEO:
if key not in d:
d[key] = ""
for key in EXCEL_GEO:
try:
if key == "siteName" and isinstance(d["siteName"], str):
filt["siteName"] = d["siteName"]
else:
filt[key] = d[key][idx]
except KeyError:
filt[key] = None
except TypeError:
filt[key] = None
# Compile the geometry based on the info available.
d2['geometry'] = compile_geometry([filt['latMin'], filt['latMax']], [filt['lonMin'], filt['lonMax']], filt['elevation'])
d2['properties'] = {'siteName': filt['siteName']}
return d2 | [
"def",
"_parse_geo_locations",
"(",
"d",
",",
"idx",
")",
":",
"d2",
"=",
"OrderedDict",
"(",
")",
"filt",
"=",
"{",
"}",
"d2",
"[",
"'type'",
"]",
"=",
"'Feature'",
"# If the necessary keys are missing, put in placeholders so there's no KeyErrors.",
"for",
"key",
... | Parse one geo location
:param d:
:return: | [
"Parse",
"one",
"geo",
"location",
":",
"param",
"d",
":",
":",
"return",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1345-L1374 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | compile_authors | def compile_authors(cell):
"""
Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names
"""
logger_excel.info("enter compile_authors")
author_lst = []
s = cell.split(';')
for w in s:
author_lst.append(w.lstrip())
logger_excel.info("exit compile_authors")
return author_lst | python | def compile_authors(cell):
"""
Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names
"""
logger_excel.info("enter compile_authors")
author_lst = []
s = cell.split(';')
for w in s:
author_lst.append(w.lstrip())
logger_excel.info("exit compile_authors")
return author_lst | [
"def",
"compile_authors",
"(",
"cell",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter compile_authors\"",
")",
"author_lst",
"=",
"[",
"]",
"s",
"=",
"cell",
".",
"split",
"(",
"';'",
")",
"for",
"w",
"in",
"s",
":",
"author_lst",
".",
"append",
... | Split the string of author names into the BibJSON format.
:param str cell: Data from author cell
:return: (list of dicts) Author names | [
"Split",
"the",
"string",
"of",
"author",
"names",
"into",
"the",
"BibJSON",
"format",
".",
":",
"param",
"str",
"cell",
":",
"Data",
"from",
"author",
"cell",
":",
"return",
":",
"(",
"list",
"of",
"dicts",
")",
"Author",
"names"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1377-L1389 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | compile_temp | def compile_temp(d, key, value):
"""
Compiles temporary dictionaries for metadata. Adds a new entry to an existing dictionary.
:param dict d:
:param str key:
:param any value:
:return dict:
"""
if not value:
d[key] = None
elif len(value) == 1:
d[key] = value[0]
else:
d[key] = value
return d | python | def compile_temp(d, key, value):
"""
Compiles temporary dictionaries for metadata. Adds a new entry to an existing dictionary.
:param dict d:
:param str key:
:param any value:
:return dict:
"""
if not value:
d[key] = None
elif len(value) == 1:
d[key] = value[0]
else:
d[key] = value
return d | [
"def",
"compile_temp",
"(",
"d",
",",
"key",
",",
"value",
")",
":",
"if",
"not",
"value",
":",
"d",
"[",
"key",
"]",
"=",
"None",
"elif",
"len",
"(",
"value",
")",
"==",
"1",
":",
"d",
"[",
"key",
"]",
"=",
"value",
"[",
"0",
"]",
"else",
... | Compiles temporary dictionaries for metadata. Adds a new entry to an existing dictionary.
:param dict d:
:param str key:
:param any value:
:return dict: | [
"Compiles",
"temporary",
"dictionaries",
"for",
"metadata",
".",
"Adds",
"a",
"new",
"entry",
"to",
"an",
"existing",
"dictionary",
".",
":",
"param",
"dict",
"d",
":",
":",
"param",
"str",
"key",
":",
":",
"param",
"any",
"value",
":",
":",
"return",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1395-L1409 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | compile_fund | def compile_fund(workbook, sheet, row, col):
"""
Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list of dict: l
"""
logger_excel.info("enter compile_fund")
l = []
temp_sheet = workbook.sheet_by_name(sheet)
while col < temp_sheet.ncols:
col += 1
try:
# Make a dictionary for this funding entry.
_curr = {
'agency': temp_sheet.cell_value(row, col),
'grant': temp_sheet.cell_value(row+1, col),
"principalInvestigator": temp_sheet.cell_value(row+2, col),
"country": temp_sheet.cell_value(row + 3, col)
}
# Make a list for all
_exist = [temp_sheet.cell_value(row, col), temp_sheet.cell_value(row+1, col),
temp_sheet.cell_value(row+2, col), temp_sheet.cell_value(row+3, col)]
# Remove all empty items from the list
_exist = [i for i in _exist if i]
# If we have all empty entries, then don't continue. Quit funding and return what we have.
if not _exist:
return l
# We have funding data. Add this funding block to the growing list.
l.append(_curr)
except IndexError as e:
logger_excel.debug("compile_fund: IndexError: sheet:{} row:{} col:{}, {}".format(sheet, row, col, e))
logger_excel.info("exit compile_fund")
return l | python | def compile_fund(workbook, sheet, row, col):
"""
Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list of dict: l
"""
logger_excel.info("enter compile_fund")
l = []
temp_sheet = workbook.sheet_by_name(sheet)
while col < temp_sheet.ncols:
col += 1
try:
# Make a dictionary for this funding entry.
_curr = {
'agency': temp_sheet.cell_value(row, col),
'grant': temp_sheet.cell_value(row+1, col),
"principalInvestigator": temp_sheet.cell_value(row+2, col),
"country": temp_sheet.cell_value(row + 3, col)
}
# Make a list for all
_exist = [temp_sheet.cell_value(row, col), temp_sheet.cell_value(row+1, col),
temp_sheet.cell_value(row+2, col), temp_sheet.cell_value(row+3, col)]
# Remove all empty items from the list
_exist = [i for i in _exist if i]
# If we have all empty entries, then don't continue. Quit funding and return what we have.
if not _exist:
return l
# We have funding data. Add this funding block to the growing list.
l.append(_curr)
except IndexError as e:
logger_excel.debug("compile_fund: IndexError: sheet:{} row:{} col:{}, {}".format(sheet, row, col, e))
logger_excel.info("exit compile_fund")
return l | [
"def",
"compile_fund",
"(",
"workbook",
",",
"sheet",
",",
"row",
",",
"col",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter compile_fund\"",
")",
"l",
"=",
"[",
"]",
"temp_sheet",
"=",
"workbook",
".",
"sheet_by_name",
"(",
"sheet",
")",
"while",
... | Compile funding entries. Iter both rows at the same time. Keep adding entries until both cells are empty.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list of dict: l | [
"Compile",
"funding",
"entries",
".",
"Iter",
"both",
"rows",
"at",
"the",
"same",
"time",
".",
"Keep",
"adding",
"entries",
"until",
"both",
"cells",
"are",
"empty",
".",
":",
"param",
"obj",
"workbook",
":",
":",
"param",
"str",
"sheet",
":",
":",
"p... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1412-L1450 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | __compare_vars | def __compare_vars(a1, a2, name):
"""
Check that the metadata variable names are the same as the data header variable names
:param list a1: Variable names
:param list a2: Variable names
:param str name: Sheet name
:return bool: Truth
"""
try:
a1 = [i for i in a1 if i]
a2 = [i for i in a2 if i]
a3 = set(a1).symmetric_difference(set(a2))
if a3:
print("- Error: Variables are not entered correctly in sheet: {}\n\tUnmatched variables: {}".format(name, a3))
except Exception as e:
logger_excel.error("compare_vars: {}".format(e))
return | python | def __compare_vars(a1, a2, name):
"""
Check that the metadata variable names are the same as the data header variable names
:param list a1: Variable names
:param list a2: Variable names
:param str name: Sheet name
:return bool: Truth
"""
try:
a1 = [i for i in a1 if i]
a2 = [i for i in a2 if i]
a3 = set(a1).symmetric_difference(set(a2))
if a3:
print("- Error: Variables are not entered correctly in sheet: {}\n\tUnmatched variables: {}".format(name, a3))
except Exception as e:
logger_excel.error("compare_vars: {}".format(e))
return | [
"def",
"__compare_vars",
"(",
"a1",
",",
"a2",
",",
"name",
")",
":",
"try",
":",
"a1",
"=",
"[",
"i",
"for",
"i",
"in",
"a1",
"if",
"i",
"]",
"a2",
"=",
"[",
"i",
"for",
"i",
"in",
"a2",
"if",
"i",
"]",
"a3",
"=",
"set",
"(",
"a1",
")",
... | Check that the metadata variable names are the same as the data header variable names
:param list a1: Variable names
:param list a2: Variable names
:param str name: Sheet name
:return bool: Truth | [
"Check",
"that",
"the",
"metadata",
"variable",
"names",
"are",
"the",
"same",
"as",
"the",
"data",
"header",
"variable",
"names",
":",
"param",
"list",
"a1",
":",
"Variable",
"names",
":",
"param",
"list",
"a2",
":",
"Variable",
"names",
":",
"param",
"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1453-L1469 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | __get_datasetname | def __get_datasetname(d, filename):
"""
Get the filename based on the dataset name in the metadata
:param str filename: Filename.lpd
:return str: Filename
"""
try:
filename = d["dataSetName"]
except KeyError:
logger_excel.info("get_datasetname: KeyError: No dataSetName found. Reverting to: {}".format(filename))
return filename | python | def __get_datasetname(d, filename):
"""
Get the filename based on the dataset name in the metadata
:param str filename: Filename.lpd
:return str: Filename
"""
try:
filename = d["dataSetName"]
except KeyError:
logger_excel.info("get_datasetname: KeyError: No dataSetName found. Reverting to: {}".format(filename))
return filename | [
"def",
"__get_datasetname",
"(",
"d",
",",
"filename",
")",
":",
"try",
":",
"filename",
"=",
"d",
"[",
"\"dataSetName\"",
"]",
"except",
"KeyError",
":",
"logger_excel",
".",
"info",
"(",
"\"get_datasetname: KeyError: No dataSetName found. Reverting to: {}\"",
".",
... | Get the filename based on the dataset name in the metadata
:param str filename: Filename.lpd
:return str: Filename | [
"Get",
"the",
"filename",
"based",
"on",
"the",
"dataset",
"name",
"in",
"the",
"metadata",
":",
"param",
"str",
"filename",
":",
"Filename",
".",
"lpd",
":",
"return",
"str",
":",
"Filename"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1472-L1482 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | __set_sheet_filenames | def __set_sheet_filenames(sheets, n):
"""
Use the dataset name to build the filenames in the sheets metadata
:param list sheets: Sheet metadata
:param str n: Dataset Name
:return list: Sheet metadata
"""
try:
for idx, sheet in enumerate(sheets):
try:
sheets[idx]["filename"] = "{}.{}".format(n, sheet["filename"])
except Exception as e:
logger_excel.error("set_sheet_filenames: inner: {}".format(e), exc_info=True)
except Exception as q:
logger_excel.error("set_sheet_filenames: outer: {}".format(q), exc_info=True)
return sheets | python | def __set_sheet_filenames(sheets, n):
"""
Use the dataset name to build the filenames in the sheets metadata
:param list sheets: Sheet metadata
:param str n: Dataset Name
:return list: Sheet metadata
"""
try:
for idx, sheet in enumerate(sheets):
try:
sheets[idx]["filename"] = "{}.{}".format(n, sheet["filename"])
except Exception as e:
logger_excel.error("set_sheet_filenames: inner: {}".format(e), exc_info=True)
except Exception as q:
logger_excel.error("set_sheet_filenames: outer: {}".format(q), exc_info=True)
return sheets | [
"def",
"__set_sheet_filenames",
"(",
"sheets",
",",
"n",
")",
":",
"try",
":",
"for",
"idx",
",",
"sheet",
"in",
"enumerate",
"(",
"sheets",
")",
":",
"try",
":",
"sheets",
"[",
"idx",
"]",
"[",
"\"filename\"",
"]",
"=",
"\"{}.{}\"",
".",
"format",
"... | Use the dataset name to build the filenames in the sheets metadata
:param list sheets: Sheet metadata
:param str n: Dataset Name
:return list: Sheet metadata | [
"Use",
"the",
"dataset",
"name",
"to",
"build",
"the",
"filenames",
"in",
"the",
"sheets",
"metadata",
":",
"param",
"list",
"sheets",
":",
"Sheet",
"metadata",
":",
"param",
"str",
"n",
":",
"Dataset",
"Name",
":",
"return",
"list",
":",
"Sheet",
"metad... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1485-L1500 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | name_to_jsonld | def name_to_jsonld(title_in):
"""
Convert formal titles to camelcase json_ld text that matches our context file
Keep a growing list of all titles that are being used in the json_ld context
:param str title_in:
:return str:
"""
title_out = ''
try:
title_in = title_in.lower()
title_out = EXCEL_LIPD_MAP_FLAT[title_in]
except (KeyError, AttributeError) as e:
if "(" in title_in:
title_in = title_in.split("(")[0].strip()
# try to find an exact match first.
try:
v = EXCEL_LIPD_MAP_FLAT[title_in]
return v
except KeyError:
pass
# if no exact match, find whatever is a closest match
for k, v in EXCEL_LIPD_MAP_FLAT.items():
if k in title_in:
return v
if not title_out:
logger_excel.debug("name_to_jsonld: No match found: {}".format(title_in))
return title_out | python | def name_to_jsonld(title_in):
"""
Convert formal titles to camelcase json_ld text that matches our context file
Keep a growing list of all titles that are being used in the json_ld context
:param str title_in:
:return str:
"""
title_out = ''
try:
title_in = title_in.lower()
title_out = EXCEL_LIPD_MAP_FLAT[title_in]
except (KeyError, AttributeError) as e:
if "(" in title_in:
title_in = title_in.split("(")[0].strip()
# try to find an exact match first.
try:
v = EXCEL_LIPD_MAP_FLAT[title_in]
return v
except KeyError:
pass
# if no exact match, find whatever is a closest match
for k, v in EXCEL_LIPD_MAP_FLAT.items():
if k in title_in:
return v
if not title_out:
logger_excel.debug("name_to_jsonld: No match found: {}".format(title_in))
return title_out | [
"def",
"name_to_jsonld",
"(",
"title_in",
")",
":",
"title_out",
"=",
"''",
"try",
":",
"title_in",
"=",
"title_in",
".",
"lower",
"(",
")",
"title_out",
"=",
"EXCEL_LIPD_MAP_FLAT",
"[",
"title_in",
"]",
"except",
"(",
"KeyError",
",",
"AttributeError",
")",... | Convert formal titles to camelcase json_ld text that matches our context file
Keep a growing list of all titles that are being used in the json_ld context
:param str title_in:
:return str: | [
"Convert",
"formal",
"titles",
"to",
"camelcase",
"json_ld",
"text",
"that",
"matches",
"our",
"context",
"file",
"Keep",
"a",
"growing",
"list",
"of",
"all",
"titles",
"that",
"are",
"being",
"used",
"in",
"the",
"json_ld",
"context",
":",
"param",
"str",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1503-L1530 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | instance_str | def instance_str(cell):
"""
Match data type and return string
:param any cell:
:return str:
"""
if isinstance(cell, str):
return 'str'
elif isinstance(cell, int):
return 'int'
elif isinstance(cell, float):
return 'float'
else:
return 'unknown' | python | def instance_str(cell):
"""
Match data type and return string
:param any cell:
:return str:
"""
if isinstance(cell, str):
return 'str'
elif isinstance(cell, int):
return 'int'
elif isinstance(cell, float):
return 'float'
else:
return 'unknown' | [
"def",
"instance_str",
"(",
"cell",
")",
":",
"if",
"isinstance",
"(",
"cell",
",",
"str",
")",
":",
"return",
"'str'",
"elif",
"isinstance",
"(",
"cell",
",",
"int",
")",
":",
"return",
"'int'",
"elif",
"isinstance",
"(",
"cell",
",",
"float",
")",
... | Match data type and return string
:param any cell:
:return str: | [
"Match",
"data",
"type",
"and",
"return",
"string",
":",
"param",
"any",
"cell",
":",
":",
"return",
"str",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1533-L1546 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | extract_units | def extract_units(string_in):
"""
Extract units from parenthesis in a string. i.e. "elevation (meters)"
:param str string_in:
:return str:
"""
start = '('
stop = ')'
return string_in[string_in.index(start) + 1:string_in.index(stop)] | python | def extract_units(string_in):
"""
Extract units from parenthesis in a string. i.e. "elevation (meters)"
:param str string_in:
:return str:
"""
start = '('
stop = ')'
return string_in[string_in.index(start) + 1:string_in.index(stop)] | [
"def",
"extract_units",
"(",
"string_in",
")",
":",
"start",
"=",
"'('",
"stop",
"=",
"')'",
"return",
"string_in",
"[",
"string_in",
".",
"index",
"(",
"start",
")",
"+",
"1",
":",
"string_in",
".",
"index",
"(",
"stop",
")",
"]"
] | Extract units from parenthesis in a string. i.e. "elevation (meters)"
:param str string_in:
:return str: | [
"Extract",
"units",
"from",
"parenthesis",
"in",
"a",
"string",
".",
"i",
".",
"e",
".",
"elevation",
"(",
"meters",
")",
":",
"param",
"str",
"string_in",
":",
":",
"return",
"str",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1568-L1576 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | cells_rt_meta_pub | def cells_rt_meta_pub(workbook, sheet, row, col, pub_qty):
"""
Publication section is special. It's possible there's more than one publication.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param int pub_qty: Number of distinct publication sections in this file
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_meta_pub")
col_loop = 0
cell_data = []
temp_sheet = workbook.sheet_by_name(sheet)
while col_loop < pub_qty:
col += 1
col_loop += 1
cell_data.append(temp_sheet.cell_value(row, col))
logger_excel.info("exit cells_rt_meta_pub")
return cell_data | python | def cells_rt_meta_pub(workbook, sheet, row, col, pub_qty):
"""
Publication section is special. It's possible there's more than one publication.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param int pub_qty: Number of distinct publication sections in this file
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_meta_pub")
col_loop = 0
cell_data = []
temp_sheet = workbook.sheet_by_name(sheet)
while col_loop < pub_qty:
col += 1
col_loop += 1
cell_data.append(temp_sheet.cell_value(row, col))
logger_excel.info("exit cells_rt_meta_pub")
return cell_data | [
"def",
"cells_rt_meta_pub",
"(",
"workbook",
",",
"sheet",
",",
"row",
",",
"col",
",",
"pub_qty",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter cells_rt_meta_pub\"",
")",
"col_loop",
"=",
"0",
"cell_data",
"=",
"[",
"]",
"temp_sheet",
"=",
"workbook"... | Publication section is special. It's possible there's more than one publication.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param int pub_qty: Number of distinct publication sections in this file
:return list: Cell data for a specific row | [
"Publication",
"section",
"is",
"special",
".",
"It",
"s",
"possible",
"there",
"s",
"more",
"than",
"one",
"publication",
".",
":",
"param",
"obj",
"workbook",
":",
":",
"param",
"str",
"sheet",
":",
":",
"param",
"int",
"row",
":",
":",
"param",
"int... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1592-L1611 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | cells_rt_meta | def cells_rt_meta(workbook, sheet, row, col):
"""
Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_meta")
col_loop = 0
cell_data = []
temp_sheet = workbook.sheet_by_name(sheet)
while col_loop < temp_sheet.ncols:
col += 1
col_loop += 1
try:
if temp_sheet.cell_value(row, col) != xlrd.empty_cell and temp_sheet.cell_value(row, col) != '':
cell_data.append(temp_sheet.cell_value(row, col))
except IndexError as e:
logger_excel.warn("cells_rt_meta: IndexError: sheet: {}, row: {}, col: {}, {}".format(sheet, row, col, e))
logger_excel.info("exit cells_right_meta")
return cell_data | python | def cells_rt_meta(workbook, sheet, row, col):
"""
Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row
"""
logger_excel.info("enter cells_rt_meta")
col_loop = 0
cell_data = []
temp_sheet = workbook.sheet_by_name(sheet)
while col_loop < temp_sheet.ncols:
col += 1
col_loop += 1
try:
if temp_sheet.cell_value(row, col) != xlrd.empty_cell and temp_sheet.cell_value(row, col) != '':
cell_data.append(temp_sheet.cell_value(row, col))
except IndexError as e:
logger_excel.warn("cells_rt_meta: IndexError: sheet: {}, row: {}, col: {}, {}".format(sheet, row, col, e))
logger_excel.info("exit cells_right_meta")
return cell_data | [
"def",
"cells_rt_meta",
"(",
"workbook",
",",
"sheet",
",",
"row",
",",
"col",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter cells_rt_meta\"",
")",
"col_loop",
"=",
"0",
"cell_data",
"=",
"[",
"]",
"temp_sheet",
"=",
"workbook",
".",
"sheet_by_name",
... | Traverse all cells in a row. If you find new data in a cell, add it to the list.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:return list: Cell data for a specific row | [
"Traverse",
"all",
"cells",
"in",
"a",
"row",
".",
"If",
"you",
"find",
"new",
"data",
"in",
"a",
"cell",
"add",
"it",
"to",
"the",
"list",
".",
":",
"param",
"obj",
"workbook",
":",
":",
"param",
"str",
"sheet",
":",
":",
"param",
"int",
"row",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1614-L1636 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | cells_dn_meta | def cells_dn_meta(workbook, sheet, row, col, final_dict):
"""
Traverse all cells in a column moving downward. Primarily created for the metadata sheet, but may use elsewhere.
Check the cell title, and switch it to.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param dict final_dict:
:return: none
"""
logger_excel.info("enter cells_dn_meta")
row_loop = 0
pub_cases = ['id', 'year', 'author', 'journal', 'issue', 'volume', 'title', 'pages',
'reportNumber', 'abstract', 'alternateCitation']
geo_cases = ['latMin', 'lonMin', 'lonMax', 'latMax', 'elevation', 'siteName', 'location']
funding_cases = ["agency", "grant", "principalInvestigator", "country"]
# Temp
pub_qty = 0
geo_temp = {}
general_temp = {}
pub_temp = []
funding_temp = []
temp_sheet = workbook.sheet_by_name(sheet)
# Loop until we hit the max rows in the sheet
while row_loop < temp_sheet.nrows:
try:
# Get cell value
cell = temp_sheet.cell_value(row, col)
# If there is content in the cell...
if cell not in EMPTY:
# Convert title to correct format, and grab the cell data for that row
title_formal = temp_sheet.cell_value(row, col)
title_json = name_to_jsonld(title_formal)
# If we don't have a title for it, then it's not information we want to grab
if title_json:
# Geo
if title_json in geo_cases:
cell_data = cells_rt_meta(workbook, sheet, row, col)
geo_temp = compile_temp(geo_temp, title_json, cell_data)
# Pub
# Create a list of dicts. One for each pub column.
elif title_json in pub_cases:
# Authors seem to be the only consistent field we can rely on to determine number of Pubs.
if title_json == 'author':
cell_data = cells_rt_meta(workbook, sheet, row, col)
pub_qty = len(cell_data)
for i in range(pub_qty):
author_lst = compile_authors(cell_data[i])
pub_temp.append({'author': author_lst, 'pubDataUrl': 'Manually Entered'})
else:
cell_data = cells_rt_meta_pub(workbook, sheet, row, col, pub_qty)
for pub in range(pub_qty):
if title_json == 'id':
pub_temp[pub]['identifier'] = [{"type": "doi", "id": cell_data[pub]}]
else:
pub_temp[pub][title_json] = cell_data[pub]
# Funding
elif title_json in funding_cases:
if title_json == "agency":
funding_temp = compile_fund(workbook, sheet, row, col)
# All other cases do not need fancy structuring
else:
cell_data = cells_rt_meta(workbook, sheet, row, col)
general_temp = compile_temp(general_temp, title_json, cell_data)
except IndexError as e:
logger_excel.debug("cells_dn_datasheets: IndexError: sheet: {}, row: {}, col: {}, {}".format(sheet, row, col, e))
row += 1
row_loop += 1
# Compile the more complicated items
geo = compile_geo(geo_temp)
logger_excel.info("compile metadata dictionary")
# Insert into final dictionary
final_dict['@context'] = "context.jsonld"
final_dict['pub'] = pub_temp
final_dict['funding'] = funding_temp
final_dict['geo'] = geo
# Add remaining general items
for k, v in general_temp.items():
final_dict[k] = v
logger_excel.info("exit cells_dn_meta")
return final_dict | python | def cells_dn_meta(workbook, sheet, row, col, final_dict):
"""
Traverse all cells in a column moving downward. Primarily created for the metadata sheet, but may use elsewhere.
Check the cell title, and switch it to.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param dict final_dict:
:return: none
"""
logger_excel.info("enter cells_dn_meta")
row_loop = 0
pub_cases = ['id', 'year', 'author', 'journal', 'issue', 'volume', 'title', 'pages',
'reportNumber', 'abstract', 'alternateCitation']
geo_cases = ['latMin', 'lonMin', 'lonMax', 'latMax', 'elevation', 'siteName', 'location']
funding_cases = ["agency", "grant", "principalInvestigator", "country"]
# Temp
pub_qty = 0
geo_temp = {}
general_temp = {}
pub_temp = []
funding_temp = []
temp_sheet = workbook.sheet_by_name(sheet)
# Loop until we hit the max rows in the sheet
while row_loop < temp_sheet.nrows:
try:
# Get cell value
cell = temp_sheet.cell_value(row, col)
# If there is content in the cell...
if cell not in EMPTY:
# Convert title to correct format, and grab the cell data for that row
title_formal = temp_sheet.cell_value(row, col)
title_json = name_to_jsonld(title_formal)
# If we don't have a title for it, then it's not information we want to grab
if title_json:
# Geo
if title_json in geo_cases:
cell_data = cells_rt_meta(workbook, sheet, row, col)
geo_temp = compile_temp(geo_temp, title_json, cell_data)
# Pub
# Create a list of dicts. One for each pub column.
elif title_json in pub_cases:
# Authors seem to be the only consistent field we can rely on to determine number of Pubs.
if title_json == 'author':
cell_data = cells_rt_meta(workbook, sheet, row, col)
pub_qty = len(cell_data)
for i in range(pub_qty):
author_lst = compile_authors(cell_data[i])
pub_temp.append({'author': author_lst, 'pubDataUrl': 'Manually Entered'})
else:
cell_data = cells_rt_meta_pub(workbook, sheet, row, col, pub_qty)
for pub in range(pub_qty):
if title_json == 'id':
pub_temp[pub]['identifier'] = [{"type": "doi", "id": cell_data[pub]}]
else:
pub_temp[pub][title_json] = cell_data[pub]
# Funding
elif title_json in funding_cases:
if title_json == "agency":
funding_temp = compile_fund(workbook, sheet, row, col)
# All other cases do not need fancy structuring
else:
cell_data = cells_rt_meta(workbook, sheet, row, col)
general_temp = compile_temp(general_temp, title_json, cell_data)
except IndexError as e:
logger_excel.debug("cells_dn_datasheets: IndexError: sheet: {}, row: {}, col: {}, {}".format(sheet, row, col, e))
row += 1
row_loop += 1
# Compile the more complicated items
geo = compile_geo(geo_temp)
logger_excel.info("compile metadata dictionary")
# Insert into final dictionary
final_dict['@context'] = "context.jsonld"
final_dict['pub'] = pub_temp
final_dict['funding'] = funding_temp
final_dict['geo'] = geo
# Add remaining general items
for k, v in general_temp.items():
final_dict[k] = v
logger_excel.info("exit cells_dn_meta")
return final_dict | [
"def",
"cells_dn_meta",
"(",
"workbook",
",",
"sheet",
",",
"row",
",",
"col",
",",
"final_dict",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter cells_dn_meta\"",
")",
"row_loop",
"=",
"0",
"pub_cases",
"=",
"[",
"'id'",
",",
"'year'",
",",
"'author'... | Traverse all cells in a column moving downward. Primarily created for the metadata sheet, but may use elsewhere.
Check the cell title, and switch it to.
:param obj workbook:
:param str sheet:
:param int row:
:param int col:
:param dict final_dict:
:return: none | [
"Traverse",
"all",
"cells",
"in",
"a",
"column",
"moving",
"downward",
".",
"Primarily",
"created",
"for",
"the",
"metadata",
"sheet",
"but",
"may",
"use",
"elsewhere",
".",
"Check",
"the",
"cell",
"title",
"and",
"switch",
"it",
"to",
".",
":",
"param",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1639-L1734 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | count_chron_variables | def count_chron_variables(temp_sheet):
"""
Count the number of chron variables
:param obj temp_sheet:
:return int: variable count
"""
total_count = 0
start_row = traverse_to_chron_var(temp_sheet)
while temp_sheet.cell_value(start_row, 0) != '':
total_count += 1
start_row += 1
return total_count | python | def count_chron_variables(temp_sheet):
"""
Count the number of chron variables
:param obj temp_sheet:
:return int: variable count
"""
total_count = 0
start_row = traverse_to_chron_var(temp_sheet)
while temp_sheet.cell_value(start_row, 0) != '':
total_count += 1
start_row += 1
return total_count | [
"def",
"count_chron_variables",
"(",
"temp_sheet",
")",
":",
"total_count",
"=",
"0",
"start_row",
"=",
"traverse_to_chron_var",
"(",
"temp_sheet",
")",
"while",
"temp_sheet",
".",
"cell_value",
"(",
"start_row",
",",
"0",
")",
"!=",
"''",
":",
"total_count",
... | Count the number of chron variables
:param obj temp_sheet:
:return int: variable count | [
"Count",
"the",
"number",
"of",
"chron",
"variables",
":",
"param",
"obj",
"temp_sheet",
":",
":",
"return",
"int",
":",
"variable",
"count"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1740-L1751 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | get_chron_var | def get_chron_var(temp_sheet, start_row):
"""
Capture all the vars in the chron sheet (for json-ld output)
:param obj temp_sheet:
:param int start_row:
:return: (list of dict) column data
"""
col_dict = OrderedDict()
out_list = []
column = 1
while (temp_sheet.cell_value(start_row, 0) != '') and (start_row < temp_sheet.nrows):
short_cell = temp_sheet.cell_value(start_row, 0)
units_cell = temp_sheet.cell_value(start_row, 1)
long_cell = temp_sheet.cell_value(start_row, 2)
# Fill the dictionary for this column
col_dict['number'] = column
col_dict['variableName'] = short_cell
col_dict['description'] = long_cell
col_dict['units'] = units_cell
out_list.append(col_dict.copy())
start_row += 1
column += 1
return out_list | python | def get_chron_var(temp_sheet, start_row):
"""
Capture all the vars in the chron sheet (for json-ld output)
:param obj temp_sheet:
:param int start_row:
:return: (list of dict) column data
"""
col_dict = OrderedDict()
out_list = []
column = 1
while (temp_sheet.cell_value(start_row, 0) != '') and (start_row < temp_sheet.nrows):
short_cell = temp_sheet.cell_value(start_row, 0)
units_cell = temp_sheet.cell_value(start_row, 1)
long_cell = temp_sheet.cell_value(start_row, 2)
# Fill the dictionary for this column
col_dict['number'] = column
col_dict['variableName'] = short_cell
col_dict['description'] = long_cell
col_dict['units'] = units_cell
out_list.append(col_dict.copy())
start_row += 1
column += 1
return out_list | [
"def",
"get_chron_var",
"(",
"temp_sheet",
",",
"start_row",
")",
":",
"col_dict",
"=",
"OrderedDict",
"(",
")",
"out_list",
"=",
"[",
"]",
"column",
"=",
"1",
"while",
"(",
"temp_sheet",
".",
"cell_value",
"(",
"start_row",
",",
"0",
")",
"!=",
"''",
... | Capture all the vars in the chron sheet (for json-ld output)
:param obj temp_sheet:
:param int start_row:
:return: (list of dict) column data | [
"Capture",
"all",
"the",
"vars",
"in",
"the",
"chron",
"sheet",
"(",
"for",
"json",
"-",
"ld",
"output",
")",
":",
"param",
"obj",
"temp_sheet",
":",
":",
"param",
"int",
"start_row",
":",
":",
"return",
":",
"(",
"list",
"of",
"dict",
")",
"column",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1754-L1779 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | traverse_to_chron_data | def traverse_to_chron_data(temp_sheet):
"""
Traverse down to the first row that has chron data
:param obj temp_sheet:
:return int: traverse_row
"""
traverse_row = traverse_to_chron_var(temp_sheet)
reference_var = temp_sheet.cell_value(traverse_row, 0)
# Traverse past all the short_names, until you hit a blank cell (the barrier)
while temp_sheet.cell_value(traverse_row, 0) != '':
traverse_row += 1
# Traverse past the empty cells until we hit the chron data area
while temp_sheet.cell_value(traverse_row, 0) == '':
traverse_row += 1
# Check if there is a header row. If there is, move past it. We don't want that data
if temp_sheet.cell_value(traverse_row, 0) == reference_var:
traverse_row += 1
logger_excel.info("traverse_to_chron_data: row:{}".format(traverse_row))
return traverse_row | python | def traverse_to_chron_data(temp_sheet):
"""
Traverse down to the first row that has chron data
:param obj temp_sheet:
:return int: traverse_row
"""
traverse_row = traverse_to_chron_var(temp_sheet)
reference_var = temp_sheet.cell_value(traverse_row, 0)
# Traverse past all the short_names, until you hit a blank cell (the barrier)
while temp_sheet.cell_value(traverse_row, 0) != '':
traverse_row += 1
# Traverse past the empty cells until we hit the chron data area
while temp_sheet.cell_value(traverse_row, 0) == '':
traverse_row += 1
# Check if there is a header row. If there is, move past it. We don't want that data
if temp_sheet.cell_value(traverse_row, 0) == reference_var:
traverse_row += 1
logger_excel.info("traverse_to_chron_data: row:{}".format(traverse_row))
return traverse_row | [
"def",
"traverse_to_chron_data",
"(",
"temp_sheet",
")",
":",
"traverse_row",
"=",
"traverse_to_chron_var",
"(",
"temp_sheet",
")",
"reference_var",
"=",
"temp_sheet",
".",
"cell_value",
"(",
"traverse_row",
",",
"0",
")",
"# Traverse past all the short_names, until you h... | Traverse down to the first row that has chron data
:param obj temp_sheet:
:return int: traverse_row | [
"Traverse",
"down",
"to",
"the",
"first",
"row",
"that",
"has",
"chron",
"data",
":",
"param",
"obj",
"temp_sheet",
":",
":",
"return",
"int",
":",
"traverse_row"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1782-L1802 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | traverse_to_chron_var | def traverse_to_chron_var(temp_sheet):
"""
Traverse down to the row that has the first variable
:param obj temp_sheet:
:return int:
"""
row = 0
while row < temp_sheet.nrows - 1:
if 'Parameter' in temp_sheet.cell_value(row, 0):
row += 1
break
row += 1
logger_excel.info("traverse_to_chron_var: row:{}".format(row))
return row | python | def traverse_to_chron_var(temp_sheet):
"""
Traverse down to the row that has the first variable
:param obj temp_sheet:
:return int:
"""
row = 0
while row < temp_sheet.nrows - 1:
if 'Parameter' in temp_sheet.cell_value(row, 0):
row += 1
break
row += 1
logger_excel.info("traverse_to_chron_var: row:{}".format(row))
return row | [
"def",
"traverse_to_chron_var",
"(",
"temp_sheet",
")",
":",
"row",
"=",
"0",
"while",
"row",
"<",
"temp_sheet",
".",
"nrows",
"-",
"1",
":",
"if",
"'Parameter'",
"in",
"temp_sheet",
".",
"cell_value",
"(",
"row",
",",
"0",
")",
":",
"row",
"+=",
"1",
... | Traverse down to the row that has the first variable
:param obj temp_sheet:
:return int: | [
"Traverse",
"down",
"to",
"the",
"row",
"that",
"has",
"the",
"first",
"variable",
":",
"param",
"obj",
"temp_sheet",
":",
":",
"return",
"int",
":"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1805-L1818 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | get_chron_data | def get_chron_data(temp_sheet, row, total_vars):
"""
Capture all data in for a specific chron data row (for csv output)
:param obj temp_sheet:
:param int row:
:param int total_vars:
:return list: data_row
"""
data_row = []
missing_val_list = ['none', 'na', '', '-']
for i in range(0, total_vars):
cell = temp_sheet.cell_value(row, i)
if isinstance(cell, str):
cell = cell.lower()
if cell in missing_val_list:
cell = 'nan'
data_row.append(cell)
return data_row | python | def get_chron_data(temp_sheet, row, total_vars):
"""
Capture all data in for a specific chron data row (for csv output)
:param obj temp_sheet:
:param int row:
:param int total_vars:
:return list: data_row
"""
data_row = []
missing_val_list = ['none', 'na', '', '-']
for i in range(0, total_vars):
cell = temp_sheet.cell_value(row, i)
if isinstance(cell, str):
cell = cell.lower()
if cell in missing_val_list:
cell = 'nan'
data_row.append(cell)
return data_row | [
"def",
"get_chron_data",
"(",
"temp_sheet",
",",
"row",
",",
"total_vars",
")",
":",
"data_row",
"=",
"[",
"]",
"missing_val_list",
"=",
"[",
"'none'",
",",
"'na'",
",",
"''",
",",
"'-'",
"]",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"total_vars",
"... | Capture all data in for a specific chron data row (for csv output)
:param obj temp_sheet:
:param int row:
:param int total_vars:
:return list: data_row | [
"Capture",
"all",
"data",
"in",
"for",
"a",
"specific",
"chron",
"data",
"row",
"(",
"for",
"csv",
"output",
")",
":",
"param",
"obj",
"temp_sheet",
":",
":",
"param",
"int",
"row",
":",
":",
"param",
"int",
"total_vars",
":",
":",
"return",
"list",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1821-L1838 |
nickmckay/LiPD-utilities | Python/lipd/excel.py | _remove_geo_placeholders | def _remove_geo_placeholders(l):
"""
Remove placeholders from coordinate lists and sort
:param list l: Lat or long list
:return list: Modified list
"""
vals = []
for i in l:
if isinstance(i, list):
for k in i:
if isinstance(k, float) or isinstance(k, int):
vals.append(k)
elif isinstance(i, float) or isinstance(i, int):
vals.append(i)
vals.sort()
return vals | python | def _remove_geo_placeholders(l):
"""
Remove placeholders from coordinate lists and sort
:param list l: Lat or long list
:return list: Modified list
"""
vals = []
for i in l:
if isinstance(i, list):
for k in i:
if isinstance(k, float) or isinstance(k, int):
vals.append(k)
elif isinstance(i, float) or isinstance(i, int):
vals.append(i)
vals.sort()
return vals | [
"def",
"_remove_geo_placeholders",
"(",
"l",
")",
":",
"vals",
"=",
"[",
"]",
"for",
"i",
"in",
"l",
":",
"if",
"isinstance",
"(",
"i",
",",
"list",
")",
":",
"for",
"k",
"in",
"i",
":",
"if",
"isinstance",
"(",
"k",
",",
"float",
")",
"or",
"i... | Remove placeholders from coordinate lists and sort
:param list l: Lat or long list
:return list: Modified list | [
"Remove",
"placeholders",
"from",
"coordinate",
"lists",
"and",
"sort",
":",
"param",
"list",
"l",
":",
"Lat",
"or",
"long",
"list",
":",
"return",
"list",
":",
"Modified",
"list"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L1841-L1856 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | read_jsonld | def read_jsonld():
"""
Find jsonld file in the cwd (or within a 2 levels below cwd), and load it in.
:return dict: Jsonld data
"""
_d = {}
try:
# Find a jsonld file in cwd. If none, fallback for a json file. If neither found, return empty.
_filename = [file for file in os.listdir() if file.endswith(".jsonld")][0]
if not _filename:
_filename = [file for file in os.listdir() if file.endswith(".json")][0]
if _filename:
try:
# Load and decode
_d = demjson.decode_file(_filename, decode_float=float)
logger_jsons.info("Read JSONLD successful: {}".format(_filename))
except FileNotFoundError as fnf:
print("Error: metadata file not found: {}".format(_filename))
logger_jsons.error("read_jsonld: FileNotFound: {}, {}".format(_filename, fnf))
except Exception:
try:
_d = demjson.decode_file(_filename, decode_float=float, encoding="latin-1")
logger_jsons.info("Read JSONLD successful: {}".format(_filename))
except Exception as e:
print("Error: unable to read metadata file: {}".format(e))
logger_jsons.error("read_jsonld: Exception: {}, {}".format(_filename, e))
else:
print("Error: metadata file (.jsonld) not found in LiPD archive")
except Exception as e:
print("Error: Unable to find jsonld file in LiPD archive. This may be a corrupt file.")
logger_jsons.error("Error: Unable to find jsonld file in LiPD archive. This may be a corrupt file.")
logger_jsons.info("exit read_json_from_file")
return _d | python | def read_jsonld():
"""
Find jsonld file in the cwd (or within a 2 levels below cwd), and load it in.
:return dict: Jsonld data
"""
_d = {}
try:
# Find a jsonld file in cwd. If none, fallback for a json file. If neither found, return empty.
_filename = [file for file in os.listdir() if file.endswith(".jsonld")][0]
if not _filename:
_filename = [file for file in os.listdir() if file.endswith(".json")][0]
if _filename:
try:
# Load and decode
_d = demjson.decode_file(_filename, decode_float=float)
logger_jsons.info("Read JSONLD successful: {}".format(_filename))
except FileNotFoundError as fnf:
print("Error: metadata file not found: {}".format(_filename))
logger_jsons.error("read_jsonld: FileNotFound: {}, {}".format(_filename, fnf))
except Exception:
try:
_d = demjson.decode_file(_filename, decode_float=float, encoding="latin-1")
logger_jsons.info("Read JSONLD successful: {}".format(_filename))
except Exception as e:
print("Error: unable to read metadata file: {}".format(e))
logger_jsons.error("read_jsonld: Exception: {}, {}".format(_filename, e))
else:
print("Error: metadata file (.jsonld) not found in LiPD archive")
except Exception as e:
print("Error: Unable to find jsonld file in LiPD archive. This may be a corrupt file.")
logger_jsons.error("Error: Unable to find jsonld file in LiPD archive. This may be a corrupt file.")
logger_jsons.info("exit read_json_from_file")
return _d | [
"def",
"read_jsonld",
"(",
")",
":",
"_d",
"=",
"{",
"}",
"try",
":",
"# Find a jsonld file in cwd. If none, fallback for a json file. If neither found, return empty.",
"_filename",
"=",
"[",
"file",
"for",
"file",
"in",
"os",
".",
"listdir",
"(",
")",
"if",
"file",... | Find jsonld file in the cwd (or within a 2 levels below cwd), and load it in.
:return dict: Jsonld data | [
"Find",
"jsonld",
"file",
"in",
"the",
"cwd",
"(",
"or",
"within",
"a",
"2",
"levels",
"below",
"cwd",
")",
"and",
"load",
"it",
"in",
".",
":",
"return",
"dict",
":",
"Jsonld",
"data"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L14-L48 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | read_json_from_file | def read_json_from_file(filename):
"""
Import the JSON data from target file.
:param str filename: Target File
:return dict: JSON data
"""
logger_jsons.info("enter read_json_from_file")
d = OrderedDict()
try:
# Load and decode
d = demjson.decode_file(filename, decode_float=float)
logger_jsons.info("successful read from json file")
except FileNotFoundError:
# Didn't find a jsonld file. Maybe it's a json file instead?
try:
d = demjson.decode_file(os.path.splitext(filename)[0] + '.json', decode_float=float)
except FileNotFoundError as e:
# No json or jsonld file. Exit
print("Error: jsonld file not found: {}".format(filename))
logger_jsons.debug("read_json_from_file: FileNotFound: {}, {}".format(filename, e))
except Exception:
print("Error: unable to read jsonld file")
if d:
d = rm_empty_fields(d)
logger_jsons.info("exit read_json_from_file")
return d | python | def read_json_from_file(filename):
"""
Import the JSON data from target file.
:param str filename: Target File
:return dict: JSON data
"""
logger_jsons.info("enter read_json_from_file")
d = OrderedDict()
try:
# Load and decode
d = demjson.decode_file(filename, decode_float=float)
logger_jsons.info("successful read from json file")
except FileNotFoundError:
# Didn't find a jsonld file. Maybe it's a json file instead?
try:
d = demjson.decode_file(os.path.splitext(filename)[0] + '.json', decode_float=float)
except FileNotFoundError as e:
# No json or jsonld file. Exit
print("Error: jsonld file not found: {}".format(filename))
logger_jsons.debug("read_json_from_file: FileNotFound: {}, {}".format(filename, e))
except Exception:
print("Error: unable to read jsonld file")
if d:
d = rm_empty_fields(d)
logger_jsons.info("exit read_json_from_file")
return d | [
"def",
"read_json_from_file",
"(",
"filename",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter read_json_from_file\"",
")",
"d",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"# Load and decode",
"d",
"=",
"demjson",
".",
"decode_file",
"(",
"filename",
",",
... | Import the JSON data from target file.
:param str filename: Target File
:return dict: JSON data | [
"Import",
"the",
"JSON",
"data",
"from",
"target",
"file",
".",
":",
"param",
"str",
"filename",
":",
"Target",
"File",
":",
"return",
"dict",
":",
"JSON",
"data"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L51-L77 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | idx_num_to_name | def idx_num_to_name(L):
"""
Switch from index-by-number to index-by-name.
:param dict L: Metadata
:return dict L: Metadata
"""
logger_jsons.info("enter idx_num_to_name")
try:
if "paleoData" in L:
L["paleoData"] = _import_data(L["paleoData"], "paleo")
if "chronData" in L:
L["chronData"] = _import_data(L["chronData"], "chron")
except Exception as e:
logger_jsons.error("idx_num_to_name: {}".format(e))
print("Error: idx_name_to_num: {}".format(e))
logger_jsons.info("exit idx_num_to_name")
return L | python | def idx_num_to_name(L):
"""
Switch from index-by-number to index-by-name.
:param dict L: Metadata
:return dict L: Metadata
"""
logger_jsons.info("enter idx_num_to_name")
try:
if "paleoData" in L:
L["paleoData"] = _import_data(L["paleoData"], "paleo")
if "chronData" in L:
L["chronData"] = _import_data(L["chronData"], "chron")
except Exception as e:
logger_jsons.error("idx_num_to_name: {}".format(e))
print("Error: idx_name_to_num: {}".format(e))
logger_jsons.info("exit idx_num_to_name")
return L | [
"def",
"idx_num_to_name",
"(",
"L",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter idx_num_to_name\"",
")",
"try",
":",
"if",
"\"paleoData\"",
"in",
"L",
":",
"L",
"[",
"\"paleoData\"",
"]",
"=",
"_import_data",
"(",
"L",
"[",
"\"paleoData\"",
"]",
"... | Switch from index-by-number to index-by-name.
:param dict L: Metadata
:return dict L: Metadata | [
"Switch",
"from",
"index",
"-",
"by",
"-",
"number",
"to",
"index",
"-",
"by",
"-",
"name",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L80-L99 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _import_data | def _import_data(sections, crumbs):
"""
Import the section metadata and change it to index-by-name.
:param list sections: Metadata
:param str pc: paleo or chron
:return dict _sections: Metadata
"""
logger_jsons.info("enter import_data: {}".format(crumbs))
_sections = OrderedDict()
try:
for _idx, section in enumerate(sections):
_tmp = OrderedDict()
# Process the paleo measurement table
if "measurementTable" in section:
_tmp["measurementTable"] = _idx_table_by_name(section["measurementTable"], "{}{}{}".format(crumbs, _idx, "measurement"))
# Process the paleo model
if "model" in section:
_tmp["model"] = _import_model(section["model"], "{}{}{}".format(crumbs, _idx, "model"))
# Get the table name from the first measurement table, and use that as the index name for this table
_table_name = "{}{}".format(crumbs, _idx)
# If we only have generic table names, and one exists already, don't overwrite. Create dynamic name
if _table_name in _sections:
_table_name = "{}_{}".format(_table_name, _idx)
# Put the final product into the output dictionary. Indexed by name
_sections[_table_name] = _tmp
except Exception as e:
logger_jsons.error("import_data: Exception: {}".format(e))
print("Error: import_data: {}".format(e))
logger_jsons.info("exit import_data: {}".format(crumbs))
return _sections | python | def _import_data(sections, crumbs):
"""
Import the section metadata and change it to index-by-name.
:param list sections: Metadata
:param str pc: paleo or chron
:return dict _sections: Metadata
"""
logger_jsons.info("enter import_data: {}".format(crumbs))
_sections = OrderedDict()
try:
for _idx, section in enumerate(sections):
_tmp = OrderedDict()
# Process the paleo measurement table
if "measurementTable" in section:
_tmp["measurementTable"] = _idx_table_by_name(section["measurementTable"], "{}{}{}".format(crumbs, _idx, "measurement"))
# Process the paleo model
if "model" in section:
_tmp["model"] = _import_model(section["model"], "{}{}{}".format(crumbs, _idx, "model"))
# Get the table name from the first measurement table, and use that as the index name for this table
_table_name = "{}{}".format(crumbs, _idx)
# If we only have generic table names, and one exists already, don't overwrite. Create dynamic name
if _table_name in _sections:
_table_name = "{}_{}".format(_table_name, _idx)
# Put the final product into the output dictionary. Indexed by name
_sections[_table_name] = _tmp
except Exception as e:
logger_jsons.error("import_data: Exception: {}".format(e))
print("Error: import_data: {}".format(e))
logger_jsons.info("exit import_data: {}".format(crumbs))
return _sections | [
"def",
"_import_data",
"(",
"sections",
",",
"crumbs",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter import_data: {}\"",
".",
"format",
"(",
"crumbs",
")",
")",
"_sections",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"for",
"_idx",
",",
"section",
"i... | Import the section metadata and change it to index-by-name.
:param list sections: Metadata
:param str pc: paleo or chron
:return dict _sections: Metadata | [
"Import",
"the",
"section",
"metadata",
"and",
"change",
"it",
"to",
"index",
"-",
"by",
"-",
"name",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L102-L139 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _import_model | def _import_model(models, crumbs):
"""
Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata
"""
logger_jsons.info("enter import_model".format(crumbs))
_models = OrderedDict()
try:
for _idx, model in enumerate(models):
# Keep the original dictionary, but replace the three main entries below
# Do a direct replacement of chronModelTable columns. No table name, no table work needed.
if "summaryTable" in model:
model["summaryTable"] = _idx_table_by_name(model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"))
# Do a direct replacement of ensembleTable columns. No table name, no table work needed.
if "ensembleTable" in model:
model["ensembleTable"] = _idx_table_by_name(model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"))
if "distributionTable" in model:
model["distributionTable"] = _idx_table_by_name(model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"))
_table_name = "{}{}".format(crumbs, _idx)
_models[_table_name] = model
except Exception as e:
logger_jsons.error("import_model: {}".format(e))
print("Error: import_model: {}".format(e))
logger_jsons.info("exit import_model: {}".format(crumbs))
return _models | python | def _import_model(models, crumbs):
"""
Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata
"""
logger_jsons.info("enter import_model".format(crumbs))
_models = OrderedDict()
try:
for _idx, model in enumerate(models):
# Keep the original dictionary, but replace the three main entries below
# Do a direct replacement of chronModelTable columns. No table name, no table work needed.
if "summaryTable" in model:
model["summaryTable"] = _idx_table_by_name(model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"))
# Do a direct replacement of ensembleTable columns. No table name, no table work needed.
if "ensembleTable" in model:
model["ensembleTable"] = _idx_table_by_name(model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"))
if "distributionTable" in model:
model["distributionTable"] = _idx_table_by_name(model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"))
_table_name = "{}{}".format(crumbs, _idx)
_models[_table_name] = model
except Exception as e:
logger_jsons.error("import_model: {}".format(e))
print("Error: import_model: {}".format(e))
logger_jsons.info("exit import_model: {}".format(crumbs))
return _models | [
"def",
"_import_model",
"(",
"models",
",",
"crumbs",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter import_model\"",
".",
"format",
"(",
"crumbs",
")",
")",
"_models",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"for",
"_idx",
",",
"model",
"in",
"e... | Change the nested items of the paleoModel data. Overwrite the data in-place.
:param list models: Metadata
:param str crumbs: Crumbs
:return dict _models: Metadata | [
"Change",
"the",
"nested",
"items",
"of",
"the",
"paleoModel",
"data",
".",
"Overwrite",
"the",
"data",
"in",
"-",
"place",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L142-L171 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _idx_table_by_name | def _idx_table_by_name(tables, crumbs):
"""
Import summary, ensemble, or distribution data.
:param list tables: Metadata
:return dict _tables: Metadata
"""
_tables = OrderedDict()
try:
for _idx, _table in enumerate(tables):
# Use "name" as tableName
_name = "{}{}".format(crumbs, _idx)
# Call idx_table_by_name
_tmp = _idx_col_by_name(_table)
if _name in _tables:
_name = "{}_{}".format(_name, _idx)
_tmp["tableName"] = _name
_tables[_name] = _tmp
except Exception as e:
logger_jsons.error("idx_table_by_name: {}".format(e))
print("Error: idx_table_by_name: {}".format(e))
return _tables | python | def _idx_table_by_name(tables, crumbs):
"""
Import summary, ensemble, or distribution data.
:param list tables: Metadata
:return dict _tables: Metadata
"""
_tables = OrderedDict()
try:
for _idx, _table in enumerate(tables):
# Use "name" as tableName
_name = "{}{}".format(crumbs, _idx)
# Call idx_table_by_name
_tmp = _idx_col_by_name(_table)
if _name in _tables:
_name = "{}_{}".format(_name, _idx)
_tmp["tableName"] = _name
_tables[_name] = _tmp
except Exception as e:
logger_jsons.error("idx_table_by_name: {}".format(e))
print("Error: idx_table_by_name: {}".format(e))
return _tables | [
"def",
"_idx_table_by_name",
"(",
"tables",
",",
"crumbs",
")",
":",
"_tables",
"=",
"OrderedDict",
"(",
")",
"try",
":",
"for",
"_idx",
",",
"_table",
"in",
"enumerate",
"(",
"tables",
")",
":",
"# Use \"name\" as tableName",
"_name",
"=",
"\"{}{}\"",
".",
... | Import summary, ensemble, or distribution data.
:param list tables: Metadata
:return dict _tables: Metadata | [
"Import",
"summary",
"ensemble",
"or",
"distribution",
"data",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L174-L196 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _idx_col_by_name | def _idx_col_by_name(table):
"""
Iter over columns list. Turn indexed-by-num list into an indexed-by-name dict. Keys are the variable names.
:param dict table: Metadata
:return dict _table: Metadata
"""
_columns = OrderedDict()
# Iter for each column in the list
try:
for _column in table["columns"]:
try:
_name = _column["variableName"]
if _name in _columns:
_name = get_appended_name(_name, _columns)
_columns[_name] = _column
except Exception as e:
print("Error: idx_col_by_name: inner: {}".format(e))
logger_jsons.info("idx_col_by_name: inner: {}".format(e))
table["columns"] = _columns
except Exception as e:
print("Error: idx_col_by_name: {}".format(e))
logger_jsons.error("idx_col_by_name: {}".format(e))
return table | python | def _idx_col_by_name(table):
"""
Iter over columns list. Turn indexed-by-num list into an indexed-by-name dict. Keys are the variable names.
:param dict table: Metadata
:return dict _table: Metadata
"""
_columns = OrderedDict()
# Iter for each column in the list
try:
for _column in table["columns"]:
try:
_name = _column["variableName"]
if _name in _columns:
_name = get_appended_name(_name, _columns)
_columns[_name] = _column
except Exception as e:
print("Error: idx_col_by_name: inner: {}".format(e))
logger_jsons.info("idx_col_by_name: inner: {}".format(e))
table["columns"] = _columns
except Exception as e:
print("Error: idx_col_by_name: {}".format(e))
logger_jsons.error("idx_col_by_name: {}".format(e))
return table | [
"def",
"_idx_col_by_name",
"(",
"table",
")",
":",
"_columns",
"=",
"OrderedDict",
"(",
")",
"# Iter for each column in the list",
"try",
":",
"for",
"_column",
"in",
"table",
"[",
"\"columns\"",
"]",
":",
"try",
":",
"_name",
"=",
"_column",
"[",
"\"variableN... | Iter over columns list. Turn indexed-by-num list into an indexed-by-name dict. Keys are the variable names.
:param dict table: Metadata
:return dict _table: Metadata | [
"Iter",
"over",
"columns",
"list",
".",
"Turn",
"indexed",
"-",
"by",
"-",
"num",
"list",
"into",
"an",
"indexed",
"-",
"by",
"-",
"name",
"dict",
".",
"Keys",
"are",
"the",
"variable",
"names",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L199-L225 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | get_csv_from_json | def get_csv_from_json(d):
"""
Get CSV values when mixed into json data. Pull out the CSV data and put it into a dictionary.
:param dict d: JSON with CSV values
:return dict: CSV values. (i.e. { CSVFilename1: { Column1: [Values], Column2: [Values] }, CSVFilename2: ... }
"""
logger_jsons.info("enter get_csv_from_json")
csv_data = OrderedDict()
if "paleoData" in d:
csv_data = _get_csv_from_section(d, "paleoData", csv_data)
if "chronData" in d:
csv_data = _get_csv_from_section(d, "chronData", csv_data)
logger_jsons.info("exit get_csv_from_json")
return csv_data | python | def get_csv_from_json(d):
"""
Get CSV values when mixed into json data. Pull out the CSV data and put it into a dictionary.
:param dict d: JSON with CSV values
:return dict: CSV values. (i.e. { CSVFilename1: { Column1: [Values], Column2: [Values] }, CSVFilename2: ... }
"""
logger_jsons.info("enter get_csv_from_json")
csv_data = OrderedDict()
if "paleoData" in d:
csv_data = _get_csv_from_section(d, "paleoData", csv_data)
if "chronData" in d:
csv_data = _get_csv_from_section(d, "chronData", csv_data)
logger_jsons.info("exit get_csv_from_json")
return csv_data | [
"def",
"get_csv_from_json",
"(",
"d",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter get_csv_from_json\"",
")",
"csv_data",
"=",
"OrderedDict",
"(",
")",
"if",
"\"paleoData\"",
"in",
"d",
":",
"csv_data",
"=",
"_get_csv_from_section",
"(",
"d",
",",
"\"p... | Get CSV values when mixed into json data. Pull out the CSV data and put it into a dictionary.
:param dict d: JSON with CSV values
:return dict: CSV values. (i.e. { CSVFilename1: { Column1: [Values], Column2: [Values] }, CSVFilename2: ... } | [
"Get",
"CSV",
"values",
"when",
"mixed",
"into",
"json",
"data",
".",
"Pull",
"out",
"the",
"CSV",
"data",
"and",
"put",
"it",
"into",
"a",
"dictionary",
".",
":",
"param",
"dict",
"d",
":",
"JSON",
"with",
"CSV",
"values",
":",
"return",
"dict",
":"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L231-L247 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _get_csv_from_section | def _get_csv_from_section(d, pc, csv_data):
"""
Get csv from paleo and chron sections
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: running csv data
"""
logger_jsons.info("enter get_csv_from_section: {}".format(pc))
for table, table_content in d[pc].items():
# Create entry for this table/CSV file (i.e. Asia-1.measTable.PaleoData.csv)
# Note: Each table has a respective CSV file.
csv_data[table_content['filename']] = OrderedDict()
for column, column_content in table_content['columns'].items():
# Set the "values" into csv dictionary in order of column "number"
csv_data[table_content['filename']][column_content['number']] = column_content['values']
logger_jsons.info("exit get_csv_from_section: {}".format(pc))
return csv_data | python | def _get_csv_from_section(d, pc, csv_data):
"""
Get csv from paleo and chron sections
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: running csv data
"""
logger_jsons.info("enter get_csv_from_section: {}".format(pc))
for table, table_content in d[pc].items():
# Create entry for this table/CSV file (i.e. Asia-1.measTable.PaleoData.csv)
# Note: Each table has a respective CSV file.
csv_data[table_content['filename']] = OrderedDict()
for column, column_content in table_content['columns'].items():
# Set the "values" into csv dictionary in order of column "number"
csv_data[table_content['filename']][column_content['number']] = column_content['values']
logger_jsons.info("exit get_csv_from_section: {}".format(pc))
return csv_data | [
"def",
"_get_csv_from_section",
"(",
"d",
",",
"pc",
",",
"csv_data",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter get_csv_from_section: {}\"",
".",
"format",
"(",
"pc",
")",
")",
"for",
"table",
",",
"table_content",
"in",
"d",
"[",
"pc",
"]",
"."... | Get csv from paleo and chron sections
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: running csv data | [
"Get",
"csv",
"from",
"paleo",
"and",
"chron",
"sections",
":",
"param",
"dict",
"d",
":",
"Metadata",
":",
"param",
"str",
"pc",
":",
"Paleo",
"or",
"chron",
":",
"return",
"dict",
":",
"running",
"csv",
"data"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L250-L268 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | remove_csv_from_json | def remove_csv_from_json(d):
"""
Remove all CSV data 'values' entries from paleoData table in the JSON structure.
:param dict d: JSON data - old structure
:return dict: Metadata dictionary without CSV values
"""
logger_jsons.info("enter remove_csv_from_json")
# Check both sections
if "paleoData" in d:
d = _remove_csv_from_section(d, "paleoData")
if "chronData" in d:
d = _remove_csv_from_section(d, "chronData")
logger_jsons.info("exit remove_csv_from_json")
return d | python | def remove_csv_from_json(d):
"""
Remove all CSV data 'values' entries from paleoData table in the JSON structure.
:param dict d: JSON data - old structure
:return dict: Metadata dictionary without CSV values
"""
logger_jsons.info("enter remove_csv_from_json")
# Check both sections
if "paleoData" in d:
d = _remove_csv_from_section(d, "paleoData")
if "chronData" in d:
d = _remove_csv_from_section(d, "chronData")
logger_jsons.info("exit remove_csv_from_json")
return d | [
"def",
"remove_csv_from_json",
"(",
"d",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter remove_csv_from_json\"",
")",
"# Check both sections",
"if",
"\"paleoData\"",
"in",
"d",
":",
"d",
"=",
"_remove_csv_from_section",
"(",
"d",
",",
"\"paleoData\"",
")",
"... | Remove all CSV data 'values' entries from paleoData table in the JSON structure.
:param dict d: JSON data - old structure
:return dict: Metadata dictionary without CSV values | [
"Remove",
"all",
"CSV",
"data",
"values",
"entries",
"from",
"paleoData",
"table",
"in",
"the",
"JSON",
"structure",
".",
":",
"param",
"dict",
"d",
":",
"JSON",
"data",
"-",
"old",
"structure",
":",
"return",
"dict",
":",
"Metadata",
"dictionary",
"withou... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L271-L287 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _remove_csv_from_section | def _remove_csv_from_section(d, pc):
"""
Remove CSV from metadata in this section
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: Modified metadata
"""
logger_jsons.info("enter remove_csv_from_json: {}".format(pc))
for table, table_content in d[pc].items():
for column, column_content in table_content['columns'].items():
try:
# try to delete the values key entry
del column_content['values']
except KeyError as e:
# if the key doesn't exist, keep going
logger_jsons.debug("remove_csv_from_json: KeyError: {}, {}".format(pc, e))
logger_jsons.info("exit remove_csv_from_json: {}".format(pc))
return d | python | def _remove_csv_from_section(d, pc):
"""
Remove CSV from metadata in this section
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: Modified metadata
"""
logger_jsons.info("enter remove_csv_from_json: {}".format(pc))
for table, table_content in d[pc].items():
for column, column_content in table_content['columns'].items():
try:
# try to delete the values key entry
del column_content['values']
except KeyError as e:
# if the key doesn't exist, keep going
logger_jsons.debug("remove_csv_from_json: KeyError: {}, {}".format(pc, e))
logger_jsons.info("exit remove_csv_from_json: {}".format(pc))
return d | [
"def",
"_remove_csv_from_section",
"(",
"d",
",",
"pc",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter remove_csv_from_json: {}\"",
".",
"format",
"(",
"pc",
")",
")",
"for",
"table",
",",
"table_content",
"in",
"d",
"[",
"pc",
"]",
".",
"items",
"("... | Remove CSV from metadata in this section
:param dict d: Metadata
:param str pc: Paleo or chron
:return dict: Modified metadata | [
"Remove",
"CSV",
"from",
"metadata",
"in",
"this",
"section",
":",
"param",
"dict",
"d",
":",
"Metadata",
":",
"param",
"str",
"pc",
":",
"Paleo",
"or",
"chron",
":",
"return",
"dict",
":",
"Modified",
"metadata"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L290-L309 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | write_json_to_file | def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param dict json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
logger_jsons.info("enter write_json_to_file")
json_data = rm_empty_fields(json_data)
# Use demjson to maintain unicode characters in output
json_bin = demjson.encode(json_data, encoding='utf-8', compactly=False)
# Write json to file
try:
open("{}.jsonld".format(filename), "wb").write(json_bin)
logger_jsons.info("wrote data to json file")
except FileNotFoundError as e:
print("Error: Writing json to file: {}".format(filename))
logger_jsons.debug("write_json_to_file: FileNotFound: {}, {}".format(filename, e))
logger_jsons.info("exit write_json_to_file")
return | python | def write_json_to_file(json_data, filename="metadata"):
"""
Write all JSON in python dictionary to a new json file.
:param dict json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None:
"""
logger_jsons.info("enter write_json_to_file")
json_data = rm_empty_fields(json_data)
# Use demjson to maintain unicode characters in output
json_bin = demjson.encode(json_data, encoding='utf-8', compactly=False)
# Write json to file
try:
open("{}.jsonld".format(filename), "wb").write(json_bin)
logger_jsons.info("wrote data to json file")
except FileNotFoundError as e:
print("Error: Writing json to file: {}".format(filename))
logger_jsons.debug("write_json_to_file: FileNotFound: {}, {}".format(filename, e))
logger_jsons.info("exit write_json_to_file")
return | [
"def",
"write_json_to_file",
"(",
"json_data",
",",
"filename",
"=",
"\"metadata\"",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter write_json_to_file\"",
")",
"json_data",
"=",
"rm_empty_fields",
"(",
"json_data",
")",
"# Use demjson to maintain unicode characters ... | Write all JSON in python dictionary to a new json file.
:param dict json_data: JSON data
:param str filename: Target filename (defaults to 'metadata.jsonld')
:return None: | [
"Write",
"all",
"JSON",
"in",
"python",
"dictionary",
"to",
"a",
"new",
"json",
"file",
".",
":",
"param",
"dict",
"json_data",
":",
"JSON",
"data",
":",
"param",
"str",
"filename",
":",
"Target",
"filename",
"(",
"defaults",
"to",
"metadata",
".",
"json... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L315-L334 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | idx_name_to_num | def idx_name_to_num(L):
"""
Switch from index-by-name to index-by-number.
:param dict L: Metadata
:return dict: Modified metadata
"""
logger_jsons.info("enter idx_name_to_num")
# Process the paleoData section
if "paleoData" in L:
L["paleoData"] = _export_section(L["paleoData"], "paleo")
# Process the chronData section
if "chronData" in L:
L["chronData"] = _export_section(L["chronData"], "chron")
logger_jsons.info("exit idx_name_to_num")
return L | python | def idx_name_to_num(L):
"""
Switch from index-by-name to index-by-number.
:param dict L: Metadata
:return dict: Modified metadata
"""
logger_jsons.info("enter idx_name_to_num")
# Process the paleoData section
if "paleoData" in L:
L["paleoData"] = _export_section(L["paleoData"], "paleo")
# Process the chronData section
if "chronData" in L:
L["chronData"] = _export_section(L["chronData"], "chron")
logger_jsons.info("exit idx_name_to_num")
return L | [
"def",
"idx_name_to_num",
"(",
"L",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter idx_name_to_num\"",
")",
"# Process the paleoData section",
"if",
"\"paleoData\"",
"in",
"L",
":",
"L",
"[",
"\"paleoData\"",
"]",
"=",
"_export_section",
"(",
"L",
"[",
"\"... | Switch from index-by-name to index-by-number.
:param dict L: Metadata
:return dict: Modified metadata | [
"Switch",
"from",
"index",
"-",
"by",
"-",
"name",
"to",
"index",
"-",
"by",
"-",
"number",
".",
":",
"param",
"dict",
"L",
":",
"Metadata",
":",
"return",
"dict",
":",
"Modified",
"metadata"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L337-L354 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _export_section | def _export_section(sections, pc):
"""
Switch chron data to index-by-number
:param dict sections: Metadata
:return list _sections: Metadata
"""
logger_jsons.info("enter export_data: {}".format(pc))
_sections = []
for name, section in sections.items():
# Process chron models
if "model" in section:
section["model"] = _export_model(section["model"])
# Process the chron measurement table
if "measurementTable" in section:
section["measurementTable"] = _idx_table_by_num(section["measurementTable"])
# Add only the table to the output list
_sections.append(section)
logger_jsons.info("exit export_data: {}".format(pc))
return _sections | python | def _export_section(sections, pc):
"""
Switch chron data to index-by-number
:param dict sections: Metadata
:return list _sections: Metadata
"""
logger_jsons.info("enter export_data: {}".format(pc))
_sections = []
for name, section in sections.items():
# Process chron models
if "model" in section:
section["model"] = _export_model(section["model"])
# Process the chron measurement table
if "measurementTable" in section:
section["measurementTable"] = _idx_table_by_num(section["measurementTable"])
# Add only the table to the output list
_sections.append(section)
logger_jsons.info("exit export_data: {}".format(pc))
return _sections | [
"def",
"_export_section",
"(",
"sections",
",",
"pc",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter export_data: {}\"",
".",
"format",
"(",
"pc",
")",
")",
"_sections",
"=",
"[",
"]",
"for",
"name",
",",
"section",
"in",
"sections",
".",
"items",
... | Switch chron data to index-by-number
:param dict sections: Metadata
:return list _sections: Metadata | [
"Switch",
"chron",
"data",
"to",
"index",
"-",
"by",
"-",
"number",
":",
"param",
"dict",
"sections",
":",
"Metadata",
":",
"return",
"list",
"_sections",
":",
"Metadata"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L357-L380 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _export_model | def _export_model(models):
"""
Switch model tables to index-by-number
:param dict models: Metadata
:return dict _models: Metadata
"""
logger_jsons.info("enter export_model")
_models = []
try:
for name, model in models.items():
if "summaryTable" in model:
model["summaryTable"] = _idx_table_by_num(model["summaryTable"])
# Process ensemble table (special two columns)
if "ensembleTable" in model:
model["ensembleTable"] = _idx_table_by_num(model["ensembleTable"])
if "distributionTable" in model:
model["distributionTable"] = _idx_table_by_num(model["distributionTable"])
_models.append(model)
except Exception as e:
logger_jsons.error("export_model: {}".format(e))
print("Error: export_model: {}".format(e))
logger_jsons.info("exit export_model")
return _models | python | def _export_model(models):
"""
Switch model tables to index-by-number
:param dict models: Metadata
:return dict _models: Metadata
"""
logger_jsons.info("enter export_model")
_models = []
try:
for name, model in models.items():
if "summaryTable" in model:
model["summaryTable"] = _idx_table_by_num(model["summaryTable"])
# Process ensemble table (special two columns)
if "ensembleTable" in model:
model["ensembleTable"] = _idx_table_by_num(model["ensembleTable"])
if "distributionTable" in model:
model["distributionTable"] = _idx_table_by_num(model["distributionTable"])
_models.append(model)
except Exception as e:
logger_jsons.error("export_model: {}".format(e))
print("Error: export_model: {}".format(e))
logger_jsons.info("exit export_model")
return _models | [
"def",
"_export_model",
"(",
"models",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter export_model\"",
")",
"_models",
"=",
"[",
"]",
"try",
":",
"for",
"name",
",",
"model",
"in",
"models",
".",
"items",
"(",
")",
":",
"if",
"\"summaryTable\"",
"i... | Switch model tables to index-by-number
:param dict models: Metadata
:return dict _models: Metadata | [
"Switch",
"model",
"tables",
"to",
"index",
"-",
"by",
"-",
"number"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L383-L411 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _idx_table_by_num | def _idx_table_by_num(tables):
"""
Switch tables to index-by-number
:param dict tables: Metadata
:return list _tables: Metadata
"""
logger_jsons.info("enter idx_table_by_num")
_tables = []
for name, table in tables.items():
try:
# Get the modified table data
tmp = _idx_col_by_num(table)
# Append it to the growing calibrated age list of tables
_tables.append(tmp)
except Exception as e:
logger_jsons.error("idx_table_by_num: {}".format(e))
logger_jsons.info("exit idx_table_by_num")
return _tables | python | def _idx_table_by_num(tables):
"""
Switch tables to index-by-number
:param dict tables: Metadata
:return list _tables: Metadata
"""
logger_jsons.info("enter idx_table_by_num")
_tables = []
for name, table in tables.items():
try:
# Get the modified table data
tmp = _idx_col_by_num(table)
# Append it to the growing calibrated age list of tables
_tables.append(tmp)
except Exception as e:
logger_jsons.error("idx_table_by_num: {}".format(e))
logger_jsons.info("exit idx_table_by_num")
return _tables | [
"def",
"_idx_table_by_num",
"(",
"tables",
")",
":",
"logger_jsons",
".",
"info",
"(",
"\"enter idx_table_by_num\"",
")",
"_tables",
"=",
"[",
"]",
"for",
"name",
",",
"table",
"in",
"tables",
".",
"items",
"(",
")",
":",
"try",
":",
"# Get the modified tabl... | Switch tables to index-by-number
:param dict tables: Metadata
:return list _tables: Metadata | [
"Switch",
"tables",
"to",
"index",
"-",
"by",
"-",
"number"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L414-L432 |
nickmckay/LiPD-utilities | Python/lipd/jsons.py | _idx_col_by_num | def _idx_col_by_num(table):
"""
Index columns by number instead of by name. Use "number" key in column to maintain order
:param dict table: Metadata
:return list _table: Metadata
"""
_columns = []
try:
# Create an empty list that matches the length of the column dictionary
_columns = [None for i in range(0, len(table["columns"]))]
# Loop and start placing data in the output list based on its "number" entry
for _name, _dat in table["columns"].items():
try:
# Special case for ensemble table "numbers" list
if isinstance(_dat["number"], list):
_columns.append(_dat)
# Place at list index based on its column number
else:
# cast number to int, just in case it's stored as a string.
n = int(_dat["number"])
_columns[n - 1] = _dat
except KeyError as ke:
print("Error: idx_col_by_num: {}".format(ke))
logger_jsons.error("idx_col_by_num: KeyError: missing number key: {}, {}".format(_name, ke))
except Exception as e:
print("Error: idx_col_by_num: {}".format(e))
logger_jsons.error("idx_col_by_num: Exception: {}".format(e))
table["columns"] = _columns
except Exception as e:
logger_jsons.error("idx_col_by_num: {}".format(e))
print("Error: idx_col_by_num: {}".format(e))
return table | python | def _idx_col_by_num(table):
"""
Index columns by number instead of by name. Use "number" key in column to maintain order
:param dict table: Metadata
:return list _table: Metadata
"""
_columns = []
try:
# Create an empty list that matches the length of the column dictionary
_columns = [None for i in range(0, len(table["columns"]))]
# Loop and start placing data in the output list based on its "number" entry
for _name, _dat in table["columns"].items():
try:
# Special case for ensemble table "numbers" list
if isinstance(_dat["number"], list):
_columns.append(_dat)
# Place at list index based on its column number
else:
# cast number to int, just in case it's stored as a string.
n = int(_dat["number"])
_columns[n - 1] = _dat
except KeyError as ke:
print("Error: idx_col_by_num: {}".format(ke))
logger_jsons.error("idx_col_by_num: KeyError: missing number key: {}, {}".format(_name, ke))
except Exception as e:
print("Error: idx_col_by_num: {}".format(e))
logger_jsons.error("idx_col_by_num: Exception: {}".format(e))
table["columns"] = _columns
except Exception as e:
logger_jsons.error("idx_col_by_num: {}".format(e))
print("Error: idx_col_by_num: {}".format(e))
return table | [
"def",
"_idx_col_by_num",
"(",
"table",
")",
":",
"_columns",
"=",
"[",
"]",
"try",
":",
"# Create an empty list that matches the length of the column dictionary",
"_columns",
"=",
"[",
"None",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"table",
"[",
... | Index columns by number instead of by name. Use "number" key in column to maintain order
:param dict table: Metadata
:return list _table: Metadata | [
"Index",
"columns",
"by",
"number",
"instead",
"of",
"by",
"name",
".",
"Use",
"number",
"key",
"in",
"column",
"to",
"maintain",
"order"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L435-L470 |
nickmckay/LiPD-utilities | Matlab/bagit.py | make_bag | def make_bag(bag_dir, bag_info=None, processes=1, checksum=None):
"""
Convert a given directory into a bag. You can pass in arbitrary
key/value pairs to put into the bag-info.txt metadata file as
the bag_info dictionary.
"""
bag_dir = os.path.abspath(bag_dir)
logger.info("creating bag for directory %s", bag_dir)
# assume md5 checksum if not specified
if not checksum:
checksum = ['md5']
if not os.path.isdir(bag_dir):
logger.error("no such bag directory %s", bag_dir)
raise RuntimeError("no such bag directory %s" % bag_dir)
old_dir = os.path.abspath(os.path.curdir)
os.chdir(bag_dir)
try:
unbaggable = _can_bag(os.curdir)
if unbaggable:
logger.error("no write permissions for the following directories and files: \n%s", unbaggable)
raise BagError("Not all files/folders can be moved.")
unreadable_dirs, unreadable_files = _can_read(os.curdir)
if unreadable_dirs or unreadable_files:
if unreadable_dirs:
logger.error("The following directories do not have read permissions: \n%s", unreadable_dirs)
if unreadable_files:
logger.error("The following files do not have read permissions: \n%s", unreadable_files)
raise BagError("Read permissions are required to calculate file fixities.")
else:
logger.info("creating data dir")
cwd = os.getcwd()
temp_data = tempfile.mkdtemp(dir=cwd)
for f in os.listdir('.'):
if os.path.abspath(f) == temp_data:
continue
new_f = os.path.join(temp_data, f)
logger.info("moving %s to %s", f, new_f)
os.rename(f, new_f)
logger.info("moving %s to %s", temp_data, 'data')
os.rename(temp_data, 'data')
# permissions for the payload directory should match those of the
# original directory
os.chmod('data', os.stat(cwd).st_mode)
for c in checksum:
logger.info("writing manifest-%s.txt", c)
Oxum = _make_manifest('manifest-%s.txt' % c, 'data', processes, c)
logger.info("writing bagit.txt")
txt = """BagIt-Version: 0.97\nTag-File-Character-Encoding: UTF-8\n"""
with open("bagit.txt", "w") as bagit_file:
bagit_file.write(txt)
logger.info("writing bag-info.txt")
if bag_info is None:
bag_info = {}
# allow 'Bagging-Date' and 'Bag-Software-Agent' to be overidden
if 'Bagging-Date' not in bag_info:
bag_info['Bagging-Date'] = date.strftime(date.today(), "%Y-%m-%d")
if 'Bag-Software-Agent' not in bag_info:
bag_info['Bag-Software-Agent'] = 'bagit.py <http://github.com/libraryofcongress/bagit-python>'
bag_info['Payload-Oxum'] = Oxum
_make_tag_file('bag-info.txt', bag_info)
for c in checksum:
_make_tagmanifest_file(c, bag_dir)
except Exception:
logger.exception("An error occurred creating the bag")
raise
finally:
os.chdir(old_dir)
return Bag(bag_dir) | python | def make_bag(bag_dir, bag_info=None, processes=1, checksum=None):
"""
Convert a given directory into a bag. You can pass in arbitrary
key/value pairs to put into the bag-info.txt metadata file as
the bag_info dictionary.
"""
bag_dir = os.path.abspath(bag_dir)
logger.info("creating bag for directory %s", bag_dir)
# assume md5 checksum if not specified
if not checksum:
checksum = ['md5']
if not os.path.isdir(bag_dir):
logger.error("no such bag directory %s", bag_dir)
raise RuntimeError("no such bag directory %s" % bag_dir)
old_dir = os.path.abspath(os.path.curdir)
os.chdir(bag_dir)
try:
unbaggable = _can_bag(os.curdir)
if unbaggable:
logger.error("no write permissions for the following directories and files: \n%s", unbaggable)
raise BagError("Not all files/folders can be moved.")
unreadable_dirs, unreadable_files = _can_read(os.curdir)
if unreadable_dirs or unreadable_files:
if unreadable_dirs:
logger.error("The following directories do not have read permissions: \n%s", unreadable_dirs)
if unreadable_files:
logger.error("The following files do not have read permissions: \n%s", unreadable_files)
raise BagError("Read permissions are required to calculate file fixities.")
else:
logger.info("creating data dir")
cwd = os.getcwd()
temp_data = tempfile.mkdtemp(dir=cwd)
for f in os.listdir('.'):
if os.path.abspath(f) == temp_data:
continue
new_f = os.path.join(temp_data, f)
logger.info("moving %s to %s", f, new_f)
os.rename(f, new_f)
logger.info("moving %s to %s", temp_data, 'data')
os.rename(temp_data, 'data')
# permissions for the payload directory should match those of the
# original directory
os.chmod('data', os.stat(cwd).st_mode)
for c in checksum:
logger.info("writing manifest-%s.txt", c)
Oxum = _make_manifest('manifest-%s.txt' % c, 'data', processes, c)
logger.info("writing bagit.txt")
txt = """BagIt-Version: 0.97\nTag-File-Character-Encoding: UTF-8\n"""
with open("bagit.txt", "w") as bagit_file:
bagit_file.write(txt)
logger.info("writing bag-info.txt")
if bag_info is None:
bag_info = {}
# allow 'Bagging-Date' and 'Bag-Software-Agent' to be overidden
if 'Bagging-Date' not in bag_info:
bag_info['Bagging-Date'] = date.strftime(date.today(), "%Y-%m-%d")
if 'Bag-Software-Agent' not in bag_info:
bag_info['Bag-Software-Agent'] = 'bagit.py <http://github.com/libraryofcongress/bagit-python>'
bag_info['Payload-Oxum'] = Oxum
_make_tag_file('bag-info.txt', bag_info)
for c in checksum:
_make_tagmanifest_file(c, bag_dir)
except Exception:
logger.exception("An error occurred creating the bag")
raise
finally:
os.chdir(old_dir)
return Bag(bag_dir) | [
"def",
"make_bag",
"(",
"bag_dir",
",",
"bag_info",
"=",
"None",
",",
"processes",
"=",
"1",
",",
"checksum",
"=",
"None",
")",
":",
"bag_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"bag_dir",
")",
"logger",
".",
"info",
"(",
"\"creating bag for... | Convert a given directory into a bag. You can pass in arbitrary
key/value pairs to put into the bag-info.txt metadata file as
the bag_info dictionary. | [
"Convert",
"a",
"given",
"directory",
"into",
"a",
"bag",
".",
"You",
"can",
"pass",
"in",
"arbitrary",
"key",
"/",
"value",
"pairs",
"to",
"put",
"into",
"the",
"bag",
"-",
"info",
".",
"txt",
"metadata",
"file",
"as",
"the",
"bag_info",
"dictionary",
... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L76-L156 |
nickmckay/LiPD-utilities | Matlab/bagit.py | _calculate_file_hashes | def _calculate_file_hashes(full_path, f_hashers):
"""
Returns a dictionary of (algorithm, hexdigest) values for the provided
filename
"""
if not os.path.exists(full_path):
raise BagValidationError("%s does not exist" % full_path)
try:
with open(full_path, 'rb') as f:
while True:
block = f.read(1048576)
if not block:
break
for i in list(f_hashers.values()):
i.update(block)
except IOError as e:
raise BagValidationError("could not read %s: %s" % (full_path, str(e)))
except OSError as e:
raise BagValidationError("could not read %s: %s" % (full_path, str(e)))
return dict(
(alg, h.hexdigest()) for alg, h in list(f_hashers.items())
) | python | def _calculate_file_hashes(full_path, f_hashers):
"""
Returns a dictionary of (algorithm, hexdigest) values for the provided
filename
"""
if not os.path.exists(full_path):
raise BagValidationError("%s does not exist" % full_path)
try:
with open(full_path, 'rb') as f:
while True:
block = f.read(1048576)
if not block:
break
for i in list(f_hashers.values()):
i.update(block)
except IOError as e:
raise BagValidationError("could not read %s: %s" % (full_path, str(e)))
except OSError as e:
raise BagValidationError("could not read %s: %s" % (full_path, str(e)))
return dict(
(alg, h.hexdigest()) for alg, h in list(f_hashers.items())
) | [
"def",
"_calculate_file_hashes",
"(",
"full_path",
",",
"f_hashers",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"full_path",
")",
":",
"raise",
"BagValidationError",
"(",
"\"%s does not exist\"",
"%",
"full_path",
")",
"try",
":",
"with",
... | Returns a dictionary of (algorithm, hexdigest) values for the provided
filename | [
"Returns",
"a",
"dictionary",
"of",
"(",
"algorithm",
"hexdigest",
")",
"values",
"for",
"the",
"provided",
"filename"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L624-L647 |
nickmckay/LiPD-utilities | Matlab/bagit.py | _parse_tags | def _parse_tags(tag_file):
"""Parses a tag file, according to RFC 2822. This
includes line folding, permitting extra-long
field values.
See http://www.faqs.org/rfcs/rfc2822.html for
more information.
"""
tag_name = None
tag_value = None
# Line folding is handled by yielding values only after we encounter
# the start of a new tag, or if we pass the EOF.
for num, line in enumerate(tag_file):
# If byte-order mark ignore it for now.
if num == 0:
if line.startswith(BOM):
line = line.lstrip(BOM)
# Skip over any empty or blank lines.
if len(line) == 0 or line.isspace():
continue
elif line[0].isspace() and tag_value is not None: # folded line
tag_value += line
else:
# Starting a new tag; yield the last one.
if tag_name:
yield (tag_name, tag_value.strip())
if ':' not in line:
raise BagValidationError("invalid line '%s' in %s" % (line.strip(),
os.path.basename(tag_file.name)))
parts = line.strip().split(':', 1)
tag_name = parts[0].strip()
tag_value = parts[1]
# Passed the EOF. All done after this.
if tag_name:
yield (tag_name, tag_value.strip()) | python | def _parse_tags(tag_file):
"""Parses a tag file, according to RFC 2822. This
includes line folding, permitting extra-long
field values.
See http://www.faqs.org/rfcs/rfc2822.html for
more information.
"""
tag_name = None
tag_value = None
# Line folding is handled by yielding values only after we encounter
# the start of a new tag, or if we pass the EOF.
for num, line in enumerate(tag_file):
# If byte-order mark ignore it for now.
if num == 0:
if line.startswith(BOM):
line = line.lstrip(BOM)
# Skip over any empty or blank lines.
if len(line) == 0 or line.isspace():
continue
elif line[0].isspace() and tag_value is not None: # folded line
tag_value += line
else:
# Starting a new tag; yield the last one.
if tag_name:
yield (tag_name, tag_value.strip())
if ':' not in line:
raise BagValidationError("invalid line '%s' in %s" % (line.strip(),
os.path.basename(tag_file.name)))
parts = line.strip().split(':', 1)
tag_name = parts[0].strip()
tag_value = parts[1]
# Passed the EOF. All done after this.
if tag_name:
yield (tag_name, tag_value.strip()) | [
"def",
"_parse_tags",
"(",
"tag_file",
")",
":",
"tag_name",
"=",
"None",
"tag_value",
"=",
"None",
"# Line folding is handled by yielding values only after we encounter",
"# the start of a new tag, or if we pass the EOF.",
"for",
"num",
",",
"line",
"in",
"enumerate",
"(",
... | Parses a tag file, according to RFC 2822. This
includes line folding, permitting extra-long
field values.
See http://www.faqs.org/rfcs/rfc2822.html for
more information. | [
"Parses",
"a",
"tag",
"file",
"according",
"to",
"RFC",
"2822",
".",
"This",
"includes",
"line",
"folding",
"permitting",
"extra",
"-",
"long",
"field",
"values",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L667-L706 |
nickmckay/LiPD-utilities | Matlab/bagit.py | _can_bag | def _can_bag(test_dir):
"""returns (unwriteable files/folders)
"""
unwriteable = []
for inode in os.listdir(test_dir):
if not os.access(os.path.join(test_dir, inode), os.W_OK):
unwriteable.append(os.path.join(os.path.abspath(test_dir), inode))
return tuple(unwriteable) | python | def _can_bag(test_dir):
"""returns (unwriteable files/folders)
"""
unwriteable = []
for inode in os.listdir(test_dir):
if not os.access(os.path.join(test_dir, inode), os.W_OK):
unwriteable.append(os.path.join(os.path.abspath(test_dir), inode))
return tuple(unwriteable) | [
"def",
"_can_bag",
"(",
"test_dir",
")",
":",
"unwriteable",
"=",
"[",
"]",
"for",
"inode",
"in",
"os",
".",
"listdir",
"(",
"test_dir",
")",
":",
"if",
"not",
"os",
".",
"access",
"(",
"os",
".",
"path",
".",
"join",
"(",
"test_dir",
",",
"inode",... | returns (unwriteable files/folders) | [
"returns",
"(",
"unwriteable",
"files",
"/",
"folders",
")"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L795-L802 |
nickmckay/LiPD-utilities | Matlab/bagit.py | _can_read | def _can_read(test_dir):
"""
returns ((unreadable_dirs), (unreadable_files))
"""
unreadable_dirs = []
unreadable_files = []
for dirpath, dirnames, filenames in os.walk(test_dir):
for dn in dirnames:
if not os.access(os.path.join(dirpath, dn), os.R_OK):
unreadable_dirs.append(os.path.join(dirpath, dn))
for fn in filenames:
if not os.access(os.path.join(dirpath, fn), os.R_OK):
unreadable_files.append(os.path.join(dirpath, fn))
return (tuple(unreadable_dirs), tuple(unreadable_files)) | python | def _can_read(test_dir):
"""
returns ((unreadable_dirs), (unreadable_files))
"""
unreadable_dirs = []
unreadable_files = []
for dirpath, dirnames, filenames in os.walk(test_dir):
for dn in dirnames:
if not os.access(os.path.join(dirpath, dn), os.R_OK):
unreadable_dirs.append(os.path.join(dirpath, dn))
for fn in filenames:
if not os.access(os.path.join(dirpath, fn), os.R_OK):
unreadable_files.append(os.path.join(dirpath, fn))
return (tuple(unreadable_dirs), tuple(unreadable_files)) | [
"def",
"_can_read",
"(",
"test_dir",
")",
":",
"unreadable_dirs",
"=",
"[",
"]",
"unreadable_files",
"=",
"[",
"]",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"test_dir",
")",
":",
"for",
"dn",
"in",
"dirnames",
... | returns ((unreadable_dirs), (unreadable_files)) | [
"returns",
"((",
"unreadable_dirs",
")",
"(",
"unreadable_files",
"))"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L805-L818 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag.compare_fetch_with_fs | def compare_fetch_with_fs(self):
"""Compares the fetch entries with the files actually
in the payload, and returns a list of all the files
that still need to be fetched.
"""
files_on_fs = set(self.payload_files())
files_in_fetch = set(self.files_to_be_fetched())
return list(files_in_fetch - files_on_fs) | python | def compare_fetch_with_fs(self):
"""Compares the fetch entries with the files actually
in the payload, and returns a list of all the files
that still need to be fetched.
"""
files_on_fs = set(self.payload_files())
files_in_fetch = set(self.files_to_be_fetched())
return list(files_in_fetch - files_on_fs) | [
"def",
"compare_fetch_with_fs",
"(",
"self",
")",
":",
"files_on_fs",
"=",
"set",
"(",
"self",
".",
"payload_files",
"(",
")",
")",
"files_in_fetch",
"=",
"set",
"(",
"self",
".",
"files_to_be_fetched",
"(",
")",
")",
"return",
"list",
"(",
"files_in_fetch",... | Compares the fetch entries with the files actually
in the payload, and returns a list of all the files
that still need to be fetched. | [
"Compares",
"the",
"fetch",
"entries",
"with",
"the",
"files",
"actually",
"in",
"the",
"payload",
"and",
"returns",
"a",
"list",
"of",
"all",
"the",
"files",
"that",
"still",
"need",
"to",
"be",
"fetched",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L236-L245 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag.save | def save(self, processes=1, manifests=False):
"""
save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set the manifests parameter to True. The default is False since you
wouldn't want a save to accidentally create a new manifest for
a corrupted bag.
If you want to control the number of processes that are used when
recalculating checksums use the processes parameter.
"""
# Error checking
if not self.path:
raise BagError("Bag does not have a path.")
# Change working directory to bag directory so helper functions work
old_dir = os.path.abspath(os.path.curdir)
os.chdir(self.path)
# Generate new manifest files
if manifests:
unbaggable = _can_bag(self.path)
if unbaggable:
logger.error("no write permissions for the following directories and files: \n%s", unbaggable)
raise BagError("Not all files/folders can be moved.")
unreadable_dirs, unreadable_files = _can_read(self.path)
if unreadable_dirs or unreadable_files:
if unreadable_dirs:
logger.error("The following directories do not have read permissions: \n%s", unreadable_dirs)
if unreadable_files:
logger.error("The following files do not have read permissions: \n%s", unreadable_files)
raise BagError("Read permissions are required to calculate file fixities.")
oxum = None
self.algs = list(set(self.algs)) # Dedupe
for alg in self.algs:
logger.info('updating manifest-%s.txt', alg)
oxum = _make_manifest('manifest-%s.txt' % alg, 'data', processes, alg)
# Update Payload-Oxum
logger.info('updating %s', self.tag_file_name)
if oxum:
self.info['Payload-Oxum'] = oxum
_make_tag_file(self.tag_file_name, self.info)
# Update tag-manifest for changes to manifest & bag-info files
for alg in self.algs:
_make_tagmanifest_file(alg, self.path)
# Reload the manifests
self._load_manifests()
os.chdir(old_dir) | python | def save(self, processes=1, manifests=False):
"""
save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set the manifests parameter to True. The default is False since you
wouldn't want a save to accidentally create a new manifest for
a corrupted bag.
If you want to control the number of processes that are used when
recalculating checksums use the processes parameter.
"""
# Error checking
if not self.path:
raise BagError("Bag does not have a path.")
# Change working directory to bag directory so helper functions work
old_dir = os.path.abspath(os.path.curdir)
os.chdir(self.path)
# Generate new manifest files
if manifests:
unbaggable = _can_bag(self.path)
if unbaggable:
logger.error("no write permissions for the following directories and files: \n%s", unbaggable)
raise BagError("Not all files/folders can be moved.")
unreadable_dirs, unreadable_files = _can_read(self.path)
if unreadable_dirs or unreadable_files:
if unreadable_dirs:
logger.error("The following directories do not have read permissions: \n%s", unreadable_dirs)
if unreadable_files:
logger.error("The following files do not have read permissions: \n%s", unreadable_files)
raise BagError("Read permissions are required to calculate file fixities.")
oxum = None
self.algs = list(set(self.algs)) # Dedupe
for alg in self.algs:
logger.info('updating manifest-%s.txt', alg)
oxum = _make_manifest('manifest-%s.txt' % alg, 'data', processes, alg)
# Update Payload-Oxum
logger.info('updating %s', self.tag_file_name)
if oxum:
self.info['Payload-Oxum'] = oxum
_make_tag_file(self.tag_file_name, self.info)
# Update tag-manifest for changes to manifest & bag-info files
for alg in self.algs:
_make_tagmanifest_file(alg, self.path)
# Reload the manifests
self._load_manifests()
os.chdir(old_dir) | [
"def",
"save",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"manifests",
"=",
"False",
")",
":",
"# Error checking",
"if",
"not",
"self",
".",
"path",
":",
"raise",
"BagError",
"(",
"\"Bag does not have a path.\"",
")",
"# Change working directory to bag director... | save will persist any changes that have been made to the bag
metadata (self.info).
If you have modified the payload of the bag (added, modified,
removed files in the data directory) and want to regenerate manifests
set the manifests parameter to True. The default is False since you
wouldn't want a save to accidentally create a new manifest for
a corrupted bag.
If you want to control the number of processes that are used when
recalculating checksums use the processes parameter. | [
"save",
"will",
"persist",
"any",
"changes",
"that",
"have",
"been",
"made",
"to",
"the",
"bag",
"metadata",
"(",
"self",
".",
"info",
")",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L263-L319 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag.missing_optional_tagfiles | def missing_optional_tagfiles(self):
"""
From v0.97 we need to validate any tagfiles listed
in the optional tagmanifest(s). As there is no mandatory
directory structure for additional tagfiles we can
only check for entries with missing files (not missing
entries for existing files).
"""
for tagfilepath in list(self.tagfile_entries().keys()):
if not os.path.isfile(os.path.join(self.path, tagfilepath)):
yield tagfilepath | python | def missing_optional_tagfiles(self):
"""
From v0.97 we need to validate any tagfiles listed
in the optional tagmanifest(s). As there is no mandatory
directory structure for additional tagfiles we can
only check for entries with missing files (not missing
entries for existing files).
"""
for tagfilepath in list(self.tagfile_entries().keys()):
if not os.path.isfile(os.path.join(self.path, tagfilepath)):
yield tagfilepath | [
"def",
"missing_optional_tagfiles",
"(",
"self",
")",
":",
"for",
"tagfilepath",
"in",
"list",
"(",
"self",
".",
"tagfile_entries",
"(",
")",
".",
"keys",
"(",
")",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",... | From v0.97 we need to validate any tagfiles listed
in the optional tagmanifest(s). As there is no mandatory
directory structure for additional tagfiles we can
only check for entries with missing files (not missing
entries for existing files). | [
"From",
"v0",
".",
"97",
"we",
"need",
"to",
"validate",
"any",
"tagfiles",
"listed",
"in",
"the",
"optional",
"tagmanifest",
"(",
"s",
")",
".",
"As",
"there",
"is",
"no",
"mandatory",
"directory",
"structure",
"for",
"additional",
"tagfiles",
"we",
"can"... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L325-L335 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag.validate | def validate(self, processes=1, fast=False):
"""Checks the structure and contents are valid. If you supply
the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and
accounted for, instead of re-calculating fixities and
comparing them against the manifest. By default validate()
will re-calculate fixities (fast=False).
"""
self._validate_structure()
self._validate_bagittxt()
self._validate_contents(processes=processes, fast=fast)
return True | python | def validate(self, processes=1, fast=False):
"""Checks the structure and contents are valid. If you supply
the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and
accounted for, instead of re-calculating fixities and
comparing them against the manifest. By default validate()
will re-calculate fixities (fast=False).
"""
self._validate_structure()
self._validate_bagittxt()
self._validate_contents(processes=processes, fast=fast)
return True | [
"def",
"validate",
"(",
"self",
",",
"processes",
"=",
"1",
",",
"fast",
"=",
"False",
")",
":",
"self",
".",
"_validate_structure",
"(",
")",
"self",
".",
"_validate_bagittxt",
"(",
")",
"self",
".",
"_validate_contents",
"(",
"processes",
"=",
"processes... | Checks the structure and contents are valid. If you supply
the parameter fast=True the Payload-Oxum (if present) will
be used to check that the payload files are present and
accounted for, instead of re-calculating fixities and
comparing them against the manifest. By default validate()
will re-calculate fixities (fast=False). | [
"Checks",
"the",
"structure",
"and",
"contents",
"are",
"valid",
".",
"If",
"you",
"supply",
"the",
"parameter",
"fast",
"=",
"True",
"the",
"Payload",
"-",
"Oxum",
"(",
"if",
"present",
")",
"will",
"be",
"used",
"to",
"check",
"that",
"the",
"payload",... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L353-L364 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag.is_valid | def is_valid(self, fast=False):
"""Returns validation success or failure as boolean.
Optional fast parameter passed directly to validate().
"""
try:
self.validate(fast=fast)
except BagError:
return False
return True | python | def is_valid(self, fast=False):
"""Returns validation success or failure as boolean.
Optional fast parameter passed directly to validate().
"""
try:
self.validate(fast=fast)
except BagError:
return False
return True | [
"def",
"is_valid",
"(",
"self",
",",
"fast",
"=",
"False",
")",
":",
"try",
":",
"self",
".",
"validate",
"(",
"fast",
"=",
"fast",
")",
"except",
"BagError",
":",
"return",
"False",
"return",
"True"
] | Returns validation success or failure as boolean.
Optional fast parameter passed directly to validate(). | [
"Returns",
"validation",
"success",
"or",
"failure",
"as",
"boolean",
".",
"Optional",
"fast",
"parameter",
"passed",
"directly",
"to",
"validate",
"()",
"."
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L366-L374 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag._validate_entries | def _validate_entries(self, processes):
"""
Verify that the actual file contents match the recorded hashes stored in the manifest files
"""
errors = list()
# First we'll make sure there's no mismatch between the filesystem
# and the list of files in the manifest(s)
only_in_manifests, only_on_fs = self.compare_manifests_with_fs()
for path in only_in_manifests:
e = FileMissing(path)
logger.warning(str(e))
errors.append(e)
for path in only_on_fs:
e = UnexpectedFile(path)
logger.warning(str(e))
errors.append(e)
# To avoid the overhead of reading the file more than once or loading
# potentially massive files into memory we'll create a dictionary of
# hash objects so we can open a file, read a block and pass it to
# multiple hash objects
available_hashers = set()
for alg in self.algs:
try:
hashlib.new(alg)
available_hashers.add(alg)
except ValueError:
logger.warning("Unable to validate file contents using unknown %s hash algorithm", alg)
if not available_hashers:
raise RuntimeError("%s: Unable to validate bag contents: none of the hash algorithms in %s are supported!" % (self, self.algs))
def _init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
args = ((self.path, rel_path, hashes, available_hashers) for rel_path, hashes in list(self.entries.items()))
try:
if processes == 1:
hash_results = list(map(_calc_hashes, args))
else:
try:
pool = multiprocessing.Pool(processes if processes else None, _init_worker)
hash_results = pool.map(_calc_hashes, args)
finally:
try:
pool.terminate()
except:
# we really don't care about any exception in terminate()
pass
# Any unhandled exceptions are probably fatal
except:
logger.exception("unable to calculate file hashes for %s", self)
raise
for rel_path, f_hashes, hashes in hash_results:
for alg, computed_hash in list(f_hashes.items()):
stored_hash = hashes[alg]
if stored_hash.lower() != computed_hash:
e = ChecksumMismatch(rel_path, alg, stored_hash.lower(), computed_hash)
logger.warning(str(e))
errors.append(e)
if errors:
raise BagValidationError("invalid bag", errors) | python | def _validate_entries(self, processes):
"""
Verify that the actual file contents match the recorded hashes stored in the manifest files
"""
errors = list()
# First we'll make sure there's no mismatch between the filesystem
# and the list of files in the manifest(s)
only_in_manifests, only_on_fs = self.compare_manifests_with_fs()
for path in only_in_manifests:
e = FileMissing(path)
logger.warning(str(e))
errors.append(e)
for path in only_on_fs:
e = UnexpectedFile(path)
logger.warning(str(e))
errors.append(e)
# To avoid the overhead of reading the file more than once or loading
# potentially massive files into memory we'll create a dictionary of
# hash objects so we can open a file, read a block and pass it to
# multiple hash objects
available_hashers = set()
for alg in self.algs:
try:
hashlib.new(alg)
available_hashers.add(alg)
except ValueError:
logger.warning("Unable to validate file contents using unknown %s hash algorithm", alg)
if not available_hashers:
raise RuntimeError("%s: Unable to validate bag contents: none of the hash algorithms in %s are supported!" % (self, self.algs))
def _init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
args = ((self.path, rel_path, hashes, available_hashers) for rel_path, hashes in list(self.entries.items()))
try:
if processes == 1:
hash_results = list(map(_calc_hashes, args))
else:
try:
pool = multiprocessing.Pool(processes if processes else None, _init_worker)
hash_results = pool.map(_calc_hashes, args)
finally:
try:
pool.terminate()
except:
# we really don't care about any exception in terminate()
pass
# Any unhandled exceptions are probably fatal
except:
logger.exception("unable to calculate file hashes for %s", self)
raise
for rel_path, f_hashes, hashes in hash_results:
for alg, computed_hash in list(f_hashes.items()):
stored_hash = hashes[alg]
if stored_hash.lower() != computed_hash:
e = ChecksumMismatch(rel_path, alg, stored_hash.lower(), computed_hash)
logger.warning(str(e))
errors.append(e)
if errors:
raise BagValidationError("invalid bag", errors) | [
"def",
"_validate_entries",
"(",
"self",
",",
"processes",
")",
":",
"errors",
"=",
"list",
"(",
")",
"# First we'll make sure there's no mismatch between the filesystem",
"# and the list of files in the manifest(s)",
"only_in_manifests",
",",
"only_on_fs",
"=",
"self",
".",
... | Verify that the actual file contents match the recorded hashes stored in the manifest files | [
"Verify",
"that",
"the",
"actual",
"file",
"contents",
"match",
"the",
"recorded",
"hashes",
"stored",
"in",
"the",
"manifest",
"files"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L474-L540 |
nickmckay/LiPD-utilities | Matlab/bagit.py | Bag._validate_bagittxt | def _validate_bagittxt(self):
"""
Verify that bagit.txt conforms to specification
"""
bagit_file_path = os.path.join(self.path, "bagit.txt")
with open(bagit_file_path, 'r') as bagit_file:
first_line = bagit_file.readline()
if first_line.startswith(BOM):
raise BagValidationError("bagit.txt must not contain a byte-order mark") | python | def _validate_bagittxt(self):
"""
Verify that bagit.txt conforms to specification
"""
bagit_file_path = os.path.join(self.path, "bagit.txt")
with open(bagit_file_path, 'r') as bagit_file:
first_line = bagit_file.readline()
if first_line.startswith(BOM):
raise BagValidationError("bagit.txt must not contain a byte-order mark") | [
"def",
"_validate_bagittxt",
"(",
"self",
")",
":",
"bagit_file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"path",
",",
"\"bagit.txt\"",
")",
"with",
"open",
"(",
"bagit_file_path",
",",
"'r'",
")",
"as",
"bagit_file",
":",
"first_line",... | Verify that bagit.txt conforms to specification | [
"Verify",
"that",
"bagit",
".",
"txt",
"conforms",
"to",
"specification"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L542-L550 |
nickmckay/LiPD-utilities | Python/lipd/inferred_data.py | _fix_numeric_types | def _fix_numeric_types(c):
"""
Fix any numpy data types that didn't map back to python data types properly
:param dict c: Columns of data
:return dict c: Columns of data
"""
try:
for var, data in c.items():
for k, v in data.items():
if k in ["hasMeanValue", "hasMaxValue", "hasMinValue", "hasMedianValue"]:
if math.isnan(v):
c[var][k] = "nan"
elif not isinstance(v, (int, float)):
try:
c[var][k] = float(v)
except Exception as e:
logger_inferred_data.info("fix_numeric_types: converting float: {}".format(e))
elif k == "hasResolution":
for b, g in v.items():
if b in ["hasMeanValue", "hasMaxValue", "hasMinValue", "hasMedianValue"]:
if math.isnan(g):
c[var][k][b] = "nan"
elif not isinstance(g, (int, float)):
try:
f = float(g)
c[var][k][b] = f
except Exception as e:
logger_inferred_data.info("fix_numeric_types: converting float: {}".format(e))
except Exception as e:
logger_inferred_data.error("fix_numeric_types: {}".format(e))
return c | python | def _fix_numeric_types(c):
"""
Fix any numpy data types that didn't map back to python data types properly
:param dict c: Columns of data
:return dict c: Columns of data
"""
try:
for var, data in c.items():
for k, v in data.items():
if k in ["hasMeanValue", "hasMaxValue", "hasMinValue", "hasMedianValue"]:
if math.isnan(v):
c[var][k] = "nan"
elif not isinstance(v, (int, float)):
try:
c[var][k] = float(v)
except Exception as e:
logger_inferred_data.info("fix_numeric_types: converting float: {}".format(e))
elif k == "hasResolution":
for b, g in v.items():
if b in ["hasMeanValue", "hasMaxValue", "hasMinValue", "hasMedianValue"]:
if math.isnan(g):
c[var][k][b] = "nan"
elif not isinstance(g, (int, float)):
try:
f = float(g)
c[var][k][b] = f
except Exception as e:
logger_inferred_data.info("fix_numeric_types: converting float: {}".format(e))
except Exception as e:
logger_inferred_data.error("fix_numeric_types: {}".format(e))
return c | [
"def",
"_fix_numeric_types",
"(",
"c",
")",
":",
"try",
":",
"for",
"var",
",",
"data",
"in",
"c",
".",
"items",
"(",
")",
":",
"for",
"k",
",",
"v",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"k",
"in",
"[",
"\"hasMeanValue\"",
",",
"\"h... | Fix any numpy data types that didn't map back to python data types properly
:param dict c: Columns of data
:return dict c: Columns of data | [
"Fix",
"any",
"numpy",
"data",
"types",
"that",
"didn",
"t",
"map",
"back",
"to",
"python",
"data",
"types",
"properly",
":",
"param",
"dict",
"c",
":",
"Columns",
"of",
"data",
":",
"return",
"dict",
"c",
":",
"Columns",
"of",
"data"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/inferred_data.py#L11-L41 |
nickmckay/LiPD-utilities | Python/lipd/inferred_data.py | _get_age | def _get_age(columns):
"""
Sift through table column data and find the "age" or "year" column. Return its "values" data.
:param dict columns: Column data
:return list age: Age values
"""
# Need to check multiple places for age, year, or yrbp
# 1. Check the column variable name
# 2. Check for an "inferredVariableType
age = []
try:
# Step 1:
# Check for age first (exact match)
if "age" in columns:
# Save the values
age = columns["age"]["values"]
# Check for year second (exact match)
elif "year" in columns:
# Save the values
age = columns["year"]["values"]
elif "yrbp" in columns:
# Save the values
age = columns["yrbp"]["values"]
# Step 2 No exact matches, check for an "inferredVariableType" : "Age" or "Year"
if not age:
# Loop through column variableNames
for k, v in columns.items():
try:
if v["inferredVariableType"].lower() == "age":
age = v["values"]
elif v["inferredVariableType"].lower() == "year":
age = v["values"]
except Exception:
# Not too concerned if we error here.
pass
# Step 3: No year or age found, start searching for a loose match with "age" or "year" in the variableName.
if not age:
# Loop through column variableNames
for k, v in columns.items():
k_low = k.lower()
# Check for age in the variableName (loose match)
if "age" in k_low:
# Save the values
age = v["values"]
# Check for year in variableName (loose match)
elif "year" in k_low:
# Save the values
age = v["values"]
elif "yrbp" in k_low:
# Save the values
age = v["values"]
# If we expected a dictionary, and didn't get one
except AttributeError as e:
logger_inferred_data.warn("get_age: AttributeError: {}".format(e))
# If we were looking for values, and didn't get one
except KeyError as e:
logger_inferred_data.warn("get_age: KeyError: {}".format(e))
# Fail-safe for other problems
except Exception as e:
logger_inferred_data.warn("get_age: Exception: {}".format(e))
return age | python | def _get_age(columns):
"""
Sift through table column data and find the "age" or "year" column. Return its "values" data.
:param dict columns: Column data
:return list age: Age values
"""
# Need to check multiple places for age, year, or yrbp
# 1. Check the column variable name
# 2. Check for an "inferredVariableType
age = []
try:
# Step 1:
# Check for age first (exact match)
if "age" in columns:
# Save the values
age = columns["age"]["values"]
# Check for year second (exact match)
elif "year" in columns:
# Save the values
age = columns["year"]["values"]
elif "yrbp" in columns:
# Save the values
age = columns["yrbp"]["values"]
# Step 2 No exact matches, check for an "inferredVariableType" : "Age" or "Year"
if not age:
# Loop through column variableNames
for k, v in columns.items():
try:
if v["inferredVariableType"].lower() == "age":
age = v["values"]
elif v["inferredVariableType"].lower() == "year":
age = v["values"]
except Exception:
# Not too concerned if we error here.
pass
# Step 3: No year or age found, start searching for a loose match with "age" or "year" in the variableName.
if not age:
# Loop through column variableNames
for k, v in columns.items():
k_low = k.lower()
# Check for age in the variableName (loose match)
if "age" in k_low:
# Save the values
age = v["values"]
# Check for year in variableName (loose match)
elif "year" in k_low:
# Save the values
age = v["values"]
elif "yrbp" in k_low:
# Save the values
age = v["values"]
# If we expected a dictionary, and didn't get one
except AttributeError as e:
logger_inferred_data.warn("get_age: AttributeError: {}".format(e))
# If we were looking for values, and didn't get one
except KeyError as e:
logger_inferred_data.warn("get_age: KeyError: {}".format(e))
# Fail-safe for other problems
except Exception as e:
logger_inferred_data.warn("get_age: Exception: {}".format(e))
return age | [
"def",
"_get_age",
"(",
"columns",
")",
":",
"# Need to check multiple places for age, year, or yrbp",
"# 1. Check the column variable name",
"# 2. Check for an \"inferredVariableType",
"age",
"=",
"[",
"]",
"try",
":",
"# Step 1:",
"# Check for age first (exact match)",
"if",
"\... | Sift through table column data and find the "age" or "year" column. Return its "values" data.
:param dict columns: Column data
:return list age: Age values | [
"Sift",
"through",
"table",
"column",
"data",
"and",
"find",
"the",
"age",
"or",
"year",
"column",
".",
"Return",
"its",
"values",
"data",
".",
":",
"param",
"dict",
"columns",
":",
"Column",
"data",
":",
"return",
"list",
"age",
":",
"Age",
"values"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/inferred_data.py#L44-L110 |
nickmckay/LiPD-utilities | Python/lipd/inferred_data.py | _get_resolution | def _get_resolution(age, values):
"""
Calculates the resolution (res)
Thanks Deborah!
"""
res = []
try:
# Get the nan index from the values and remove from age
# age2 = age[np.where(~np.isnan(values))[0]]
# res = np.diff(age2)
# Make sure that age and values are numpy arrays
# age = np.array(age, dtype=float)
# values = np.array(values, dtype=float)
# Get the nan index from the values and remove from age
age2 = age[np.where(~np.isnan(values))[0]]
res = np.diff(age2)
except IndexError as e:
print("get_resolution: IndexError: {}".format(e))
except Exception as e:
logger_inferred_data.warn("get_resolution: Exception: {}".format(e))
return res | python | def _get_resolution(age, values):
"""
Calculates the resolution (res)
Thanks Deborah!
"""
res = []
try:
# Get the nan index from the values and remove from age
# age2 = age[np.where(~np.isnan(values))[0]]
# res = np.diff(age2)
# Make sure that age and values are numpy arrays
# age = np.array(age, dtype=float)
# values = np.array(values, dtype=float)
# Get the nan index from the values and remove from age
age2 = age[np.where(~np.isnan(values))[0]]
res = np.diff(age2)
except IndexError as e:
print("get_resolution: IndexError: {}".format(e))
except Exception as e:
logger_inferred_data.warn("get_resolution: Exception: {}".format(e))
return res | [
"def",
"_get_resolution",
"(",
"age",
",",
"values",
")",
":",
"res",
"=",
"[",
"]",
"try",
":",
"# Get the nan index from the values and remove from age",
"# age2 = age[np.where(~np.isnan(values))[0]]",
"# res = np.diff(age2)",
"# Make sure that age and values are numpy arrays",
... | Calculates the resolution (res)
Thanks Deborah! | [
"Calculates",
"the",
"resolution",
"(",
"res",
")",
"Thanks",
"Deborah!"
] | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/inferred_data.py#L113-L136 |
nickmckay/LiPD-utilities | Python/lipd/inferred_data.py | __get_inferred_data_res_2 | def __get_inferred_data_res_2(v=None, calc=True):
"""
Use a list of values to calculate m/m/m/m. Resolution values or otherwise.
:param numpy array v: Values
:param bool calc: If false, we don't need calculations
:return dict: Results of calculation
"""
# Base: If something goes wrong, or if there are no values, then use "NaN" placeholders.
d = {
"hasMinValue": "nan", "hasMaxValue": "nan",
"hasMeanValue": "nan", "hasMedianValue": "nan",
}
try:
if calc:
_min = np.nanmin(v)
_max = np.nanmax(v)
_mean = np.nanmean(v)
_med = np.nanmedian(v)
if np.isnan(_min):
_min = "nan"
else:
_min = abs(_min)
if np.isnan(_max):
_max = "nan"
else:
_min = abs(_min)
if np.isnan(_mean):
_mean = "nan"
else:
_min = abs(_min)
if np.isnan(_med):
_med = "nan"
else:
_min = abs(_min)
d = {
"hasMinValue": _min,
"hasMaxValue": _max,
"hasMeanValue": _mean,
"hasMedianValue": _med
}
except Exception as e:
logger_inferred_data.error("get_inferred_data_res_2: {}".format(e))
return d | python | def __get_inferred_data_res_2(v=None, calc=True):
"""
Use a list of values to calculate m/m/m/m. Resolution values or otherwise.
:param numpy array v: Values
:param bool calc: If false, we don't need calculations
:return dict: Results of calculation
"""
# Base: If something goes wrong, or if there are no values, then use "NaN" placeholders.
d = {
"hasMinValue": "nan", "hasMaxValue": "nan",
"hasMeanValue": "nan", "hasMedianValue": "nan",
}
try:
if calc:
_min = np.nanmin(v)
_max = np.nanmax(v)
_mean = np.nanmean(v)
_med = np.nanmedian(v)
if np.isnan(_min):
_min = "nan"
else:
_min = abs(_min)
if np.isnan(_max):
_max = "nan"
else:
_min = abs(_min)
if np.isnan(_mean):
_mean = "nan"
else:
_min = abs(_min)
if np.isnan(_med):
_med = "nan"
else:
_min = abs(_min)
d = {
"hasMinValue": _min,
"hasMaxValue": _max,
"hasMeanValue": _mean,
"hasMedianValue": _med
}
except Exception as e:
logger_inferred_data.error("get_inferred_data_res_2: {}".format(e))
return d | [
"def",
"__get_inferred_data_res_2",
"(",
"v",
"=",
"None",
",",
"calc",
"=",
"True",
")",
":",
"# Base: If something goes wrong, or if there are no values, then use \"NaN\" placeholders.",
"d",
"=",
"{",
"\"hasMinValue\"",
":",
"\"nan\"",
",",
"\"hasMaxValue\"",
":",
"\"n... | Use a list of values to calculate m/m/m/m. Resolution values or otherwise.
:param numpy array v: Values
:param bool calc: If false, we don't need calculations
:return dict: Results of calculation | [
"Use",
"a",
"list",
"of",
"values",
"to",
"calculate",
"m",
"/",
"m",
"/",
"m",
"/",
"m",
".",
"Resolution",
"values",
"or",
"otherwise",
".",
":",
"param",
"numpy",
"array",
"v",
":",
"Values",
":",
"param",
"bool",
"calc",
":",
"If",
"false",
"we... | train | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/inferred_data.py#L139-L184 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.