repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/needs.py | prepare_env | def prepare_env(app, env, docname):
"""
Prepares the sphinx environment to store sphinx-needs internal data.
"""
if not hasattr(env, 'needs_all_needs'):
# Used to store all needed information about all needs in document
env.needs_all_needs = {}
if not hasattr(env, 'needs_functions'):
# Used to store all registered functions for supporting dynamic need values.
env.needs_functions = {}
# needs_functions = getattr(app.config, 'needs_functions', [])
needs_functions = app.needs_functions
if needs_functions is None:
needs_functions = []
if not isinstance(needs_functions, list):
raise SphinxError('Config parameter needs_functions must be a list!')
# Register built-in functions
for need_common_func in needs_common_functions:
register_func(env, need_common_func)
# Register functions configured by user
for needs_func in needs_functions:
register_func(env, needs_func)
app.config.needs_hide_options += ['hidden']
app.config.needs_extra_options['hidden'] = directives.unchanged
if not hasattr(env, 'needs_workflow'):
# Used to store workflow status information for already executed tasks.
# Some tasks like backlink_creation need be be performed only once.
# But most sphinx-events get called several times (for each single document file), which would also
# execute our code several times...
env.needs_workflow = {
'backlink_creation': False,
'dynamic_values_resolved': False
} | python | def prepare_env(app, env, docname):
"""
Prepares the sphinx environment to store sphinx-needs internal data.
"""
if not hasattr(env, 'needs_all_needs'):
# Used to store all needed information about all needs in document
env.needs_all_needs = {}
if not hasattr(env, 'needs_functions'):
# Used to store all registered functions for supporting dynamic need values.
env.needs_functions = {}
# needs_functions = getattr(app.config, 'needs_functions', [])
needs_functions = app.needs_functions
if needs_functions is None:
needs_functions = []
if not isinstance(needs_functions, list):
raise SphinxError('Config parameter needs_functions must be a list!')
# Register built-in functions
for need_common_func in needs_common_functions:
register_func(env, need_common_func)
# Register functions configured by user
for needs_func in needs_functions:
register_func(env, needs_func)
app.config.needs_hide_options += ['hidden']
app.config.needs_extra_options['hidden'] = directives.unchanged
if not hasattr(env, 'needs_workflow'):
# Used to store workflow status information for already executed tasks.
# Some tasks like backlink_creation need be be performed only once.
# But most sphinx-events get called several times (for each single document file), which would also
# execute our code several times...
env.needs_workflow = {
'backlink_creation': False,
'dynamic_values_resolved': False
} | [
"def",
"prepare_env",
"(",
"app",
",",
"env",
",",
"docname",
")",
":",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'needs_all_needs'",
")",
":",
"# Used to store all needed information about all needs in document",
"env",
".",
"needs_all_needs",
"=",
"{",
"}",
"if"... | Prepares the sphinx environment to store sphinx-needs internal data. | [
"Prepares",
"the",
"sphinx",
"environment",
"to",
"store",
"sphinx",
"-",
"needs",
"internal",
"data",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/needs.py#L311-L349 | train | 46,700 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/needflow.py | make_entity_name | def make_entity_name(name):
"""Creates a valid PlantUML entity name from the given value."""
invalid_chars = "-=!#$%^&*[](){}/~'`<>:;"
for char in invalid_chars:
name = name.replace(char, "_")
return name | python | def make_entity_name(name):
"""Creates a valid PlantUML entity name from the given value."""
invalid_chars = "-=!#$%^&*[](){}/~'`<>:;"
for char in invalid_chars:
name = name.replace(char, "_")
return name | [
"def",
"make_entity_name",
"(",
"name",
")",
":",
"invalid_chars",
"=",
"\"-=!#$%^&*[](){}/~'`<>:;\"",
"for",
"char",
"in",
"invalid_chars",
":",
"name",
"=",
"name",
".",
"replace",
"(",
"char",
",",
"\"_\"",
")",
"return",
"name"
] | Creates a valid PlantUML entity name from the given value. | [
"Creates",
"a",
"valid",
"PlantUML",
"entity",
"name",
"from",
"the",
"given",
"value",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/needflow.py#L63-L68 | train | 46,701 |
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"
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/common.py#L33-L92 | train | 46,702 |
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",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/common.py#L95-L244 | train | 46,703 |
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",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/common.py#L247-L350 | train | 46,704 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L30-L42 | train | 46,705 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L84-L114 | train | 46,706 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/noaa.py#L128-L141 | train | 46,707 |
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"
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/java_magic.py#L20-L33 | train | 46,708 |
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"
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/java_magic.py#L57-L65 | train | 46,709 |
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",
"."
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/metrics.py#L10-L28 | train | 46,710 |
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"
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/metrics.py#L67-L87 | train | 46,711 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/excel.py#L167-L253 | train | 46,712 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L80-L99 | train | 46,713 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L102-L139 | train | 46,714 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L142-L171 | train | 46,715 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L174-L196 | train | 46,716 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L199-L225 | train | 46,717 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L383-L411 | train | 46,718 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L414-L432 | train | 46,719 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/jsons.py#L435-L470 | train | 46,720 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L667-L706 | train | 46,721 |
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",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L236-L245 | train | 46,722 |
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"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Matlab/bagit.py#L542-L550 | train | 46,723 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/functions/functions.py | resolve_dynamic_values | def resolve_dynamic_values(env):
"""
Resolve dynamic values inside need data.
Rough workflow:
#. Parse all needs and their data for a string like [[ my_func(a,b,c) ]]
#. Extract function name and call parameters
#. Execute registered function name with extracted call parameters
#. Replace original string with return value
:param env: Sphinx environment
:return: return value of given function
"""
# Only perform calculation if not already done yet
if env.needs_workflow['dynamic_values_resolved']:
return
needs = env.needs_all_needs
for key, need in needs.items():
for need_option in need:
if need_option in ['docname', 'lineno', 'target_node', 'content']:
# dynamic values in this data are not allowed.
continue
if not isinstance(need[need_option], (list, set)):
func_call = True
while func_call:
try:
func_call, func_return = _detect_and_execute(need[need_option], need, env)
except FunctionParsingException:
raise SphinxError("Function definition of {option} in file {file}:{line} has "
"unsupported parameters. "
"supported are str, int/float, list".format(option=need_option,
file=need['docname'],
line=need['lineno']))
if func_call is None:
continue
# Replace original function string with return value of function call
if func_return is None:
need[need_option] = need[need_option].replace('[[{}]]'.format(func_call), '')
else:
need[need_option] = need[need_option].replace('[[{}]]'.format(func_call), str(func_return))
if need[need_option] == '':
need[need_option] = None
else:
new_values = []
for element in need[need_option]:
try:
func_call, func_return = _detect_and_execute(element, need, env)
except FunctionParsingException:
raise SphinxError("Function definition of {option} in file {file}:{line} has "
"unsupported parameters. "
"supported are str, int/float, list".format(option=need_option,
file=need['docname'],
line=need['lineno']))
if func_call is None:
new_values.append(element)
else:
# Replace original function string with return value of function call
if isinstance(need[need_option], (str, int, float)):
new_values.append(element.replace('[[{}]]'.format(func_call), str(func_return)))
else:
if isinstance(need[need_option], (list, set)):
new_values += func_return
need[need_option] = new_values
# Finally set a flag so that this function gets not executed several times
env.needs_workflow['dynamic_values_resolved'] = True | python | def resolve_dynamic_values(env):
"""
Resolve dynamic values inside need data.
Rough workflow:
#. Parse all needs and their data for a string like [[ my_func(a,b,c) ]]
#. Extract function name and call parameters
#. Execute registered function name with extracted call parameters
#. Replace original string with return value
:param env: Sphinx environment
:return: return value of given function
"""
# Only perform calculation if not already done yet
if env.needs_workflow['dynamic_values_resolved']:
return
needs = env.needs_all_needs
for key, need in needs.items():
for need_option in need:
if need_option in ['docname', 'lineno', 'target_node', 'content']:
# dynamic values in this data are not allowed.
continue
if not isinstance(need[need_option], (list, set)):
func_call = True
while func_call:
try:
func_call, func_return = _detect_and_execute(need[need_option], need, env)
except FunctionParsingException:
raise SphinxError("Function definition of {option} in file {file}:{line} has "
"unsupported parameters. "
"supported are str, int/float, list".format(option=need_option,
file=need['docname'],
line=need['lineno']))
if func_call is None:
continue
# Replace original function string with return value of function call
if func_return is None:
need[need_option] = need[need_option].replace('[[{}]]'.format(func_call), '')
else:
need[need_option] = need[need_option].replace('[[{}]]'.format(func_call), str(func_return))
if need[need_option] == '':
need[need_option] = None
else:
new_values = []
for element in need[need_option]:
try:
func_call, func_return = _detect_and_execute(element, need, env)
except FunctionParsingException:
raise SphinxError("Function definition of {option} in file {file}:{line} has "
"unsupported parameters. "
"supported are str, int/float, list".format(option=need_option,
file=need['docname'],
line=need['lineno']))
if func_call is None:
new_values.append(element)
else:
# Replace original function string with return value of function call
if isinstance(need[need_option], (str, int, float)):
new_values.append(element.replace('[[{}]]'.format(func_call), str(func_return)))
else:
if isinstance(need[need_option], (list, set)):
new_values += func_return
need[need_option] = new_values
# Finally set a flag so that this function gets not executed several times
env.needs_workflow['dynamic_values_resolved'] = True | [
"def",
"resolve_dynamic_values",
"(",
"env",
")",
":",
"# Only perform calculation if not already done yet",
"if",
"env",
".",
"needs_workflow",
"[",
"'dynamic_values_resolved'",
"]",
":",
"return",
"needs",
"=",
"env",
".",
"needs_all_needs",
"for",
"key",
",",
"need... | Resolve dynamic values inside need data.
Rough workflow:
#. Parse all needs and their data for a string like [[ my_func(a,b,c) ]]
#. Extract function name and call parameters
#. Execute registered function name with extracted call parameters
#. Replace original string with return value
:param env: Sphinx environment
:return: return value of given function | [
"Resolve",
"dynamic",
"values",
"inside",
"need",
"data",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/functions/functions.py#L121-L191 | train | 46,724 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | run | def run():
"""
Initialize and start objects. This is called automatically when importing the package.
:return none:
"""
# GLOBALS
global cwd, files, logger_start, logger_benchmark, settings, _timeseries_data
_timeseries_data = {}
# files = {".lpd": [ {"full_path", "filename_ext", "filename_no_ext", "dir"} ], ".xls": [...], ".txt": [...]}
settings = {"note_update": True, "note_validate": True, "verbose": True}
cwd = os.getcwd()
# logger created in whatever directory lipd is called from
logger_start = create_logger("start")
logger_benchmark = create_benchmark("benchmarks", "benchmark.log")
files = {".txt": [], ".lpd": [], ".xls": []}
return | python | def run():
"""
Initialize and start objects. This is called automatically when importing the package.
:return none:
"""
# GLOBALS
global cwd, files, logger_start, logger_benchmark, settings, _timeseries_data
_timeseries_data = {}
# files = {".lpd": [ {"full_path", "filename_ext", "filename_no_ext", "dir"} ], ".xls": [...], ".txt": [...]}
settings = {"note_update": True, "note_validate": True, "verbose": True}
cwd = os.getcwd()
# logger created in whatever directory lipd is called from
logger_start = create_logger("start")
logger_benchmark = create_benchmark("benchmarks", "benchmark.log")
files = {".txt": [], ".lpd": [], ".xls": []}
return | [
"def",
"run",
"(",
")",
":",
"# GLOBALS",
"global",
"cwd",
",",
"files",
",",
"logger_start",
",",
"logger_benchmark",
",",
"settings",
",",
"_timeseries_data",
"_timeseries_data",
"=",
"{",
"}",
"# files = {\".lpd\": [ {\"full_path\", \"filename_ext\", \"filename_no_ext\... | Initialize and start objects. This is called automatically when importing the package.
:return none: | [
"Initialize",
"and",
"start",
"objects",
".",
"This",
"is",
"called",
"automatically",
"when",
"importing",
"the",
"package",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L28-L45 | train | 46,725 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | excel | def excel():
"""
Convert Excel files to LiPD files. LiPD data is returned directly from this function.
| Example
| 1: lipd.readExcel()
| 2: D = lipd.excel()
:return dict _d: Metadata
"""
global files, cwd, settings
_d = {}
# Turn off verbose. We don't want to clutter the console with extra reading/writing output statements
settings["verbose"] = False
# Find excel files
print("Found " + str(len(files[".xls"])) + " Excel files")
logger_start.info("found excel files: {}".format(len(files[".xls"])))
# Start the clock
start = clock()
# Loop for each excel file
for file in files[".xls"]:
# Convert excel file to LiPD
dsn = excel_main(file)
try:
# Read the new LiPD file back in, to get fixes, inferred calculations, updates, etc.
_d[dsn] = readLipd(os.path.join(file["dir"], dsn + ".lpd"))
# Write the modified LiPD file back out again.
writeLipd(_d[dsn], cwd)
except Exception as e:
logger_start.error("excel: Unable to read new LiPD file, {}".format(e))
print("Error: Unable to read new LiPD file: {}, {}".format(dsn, e))
# Time!
end = clock()
logger_benchmark.info(log_benchmark("excel", start, end))
# Start printing stuff again.
settings["verbose"] = True
return _d | python | def excel():
"""
Convert Excel files to LiPD files. LiPD data is returned directly from this function.
| Example
| 1: lipd.readExcel()
| 2: D = lipd.excel()
:return dict _d: Metadata
"""
global files, cwd, settings
_d = {}
# Turn off verbose. We don't want to clutter the console with extra reading/writing output statements
settings["verbose"] = False
# Find excel files
print("Found " + str(len(files[".xls"])) + " Excel files")
logger_start.info("found excel files: {}".format(len(files[".xls"])))
# Start the clock
start = clock()
# Loop for each excel file
for file in files[".xls"]:
# Convert excel file to LiPD
dsn = excel_main(file)
try:
# Read the new LiPD file back in, to get fixes, inferred calculations, updates, etc.
_d[dsn] = readLipd(os.path.join(file["dir"], dsn + ".lpd"))
# Write the modified LiPD file back out again.
writeLipd(_d[dsn], cwd)
except Exception as e:
logger_start.error("excel: Unable to read new LiPD file, {}".format(e))
print("Error: Unable to read new LiPD file: {}, {}".format(dsn, e))
# Time!
end = clock()
logger_benchmark.info(log_benchmark("excel", start, end))
# Start printing stuff again.
settings["verbose"] = True
return _d | [
"def",
"excel",
"(",
")",
":",
"global",
"files",
",",
"cwd",
",",
"settings",
"_d",
"=",
"{",
"}",
"# Turn off verbose. We don't want to clutter the console with extra reading/writing output statements",
"settings",
"[",
"\"verbose\"",
"]",
"=",
"False",
"# Find excel fi... | Convert Excel files to LiPD files. LiPD data is returned directly from this function.
| Example
| 1: lipd.readExcel()
| 2: D = lipd.excel()
:return dict _d: Metadata | [
"Convert",
"Excel",
"files",
"to",
"LiPD",
"files",
".",
"LiPD",
"data",
"is",
"returned",
"directly",
"from",
"this",
"function",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L125-L161 | train | 46,726 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | noaa | def noaa(D="", path="", wds_url="", lpd_url="", version=""):
"""
Convert between NOAA and LiPD files
| Example: LiPD to NOAA converter
| 1: L = lipd.readLipd()
| 2: lipd.noaa(L, "/Users/someuser/Desktop", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/noaa-templates/data-version-1.0.0", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/data-version-1.0.0", "v1-1.0.0")
| Example: NOAA to LiPD converter
| 1: lipd.readNoaa()
| 2: lipd.noaa()
:param dict D: Metadata
:param str path: Path where output files will be written to
:param str wds_url: WDSPaleoUrl, where NOAA template file will be stored on NOAA's FTP server
:param str lpd_url: URL where LiPD file will be stored on NOAA's FTP server
:param str version: Version of the dataset
:return none:
"""
global files, cwd
# When going from NOAA to LPD, use the global "files" variable.
# When going from LPD to NOAA, use the data from the LiPD Library.
# Choose the mode
_mode = noaa_prompt()
start = clock()
# LiPD mode: Convert LiPD files to NOAA files
if _mode == "1":
# _project, _version = noaa_prompt_1()
if not version or not lpd_url:
print("Missing parameters: Please try again and provide all parameters.")
return
if not D:
print("Error: LiPD data must be provided for LiPD -> NOAA conversions")
else:
if "paleoData" in D:
_d = copy.deepcopy(D)
D = lpd_to_noaa(_d, wds_url, lpd_url, version, path)
else:
# For each LiPD file in the LiPD Library
for dsn, dat in D.items():
_d = copy.deepcopy(dat)
# Process this data through the converter
_d = lpd_to_noaa(_d, wds_url, lpd_url, version, path)
# Overwrite the data in the LiPD object with our new data.
D[dsn] = _d
# If no wds url is provided, then remove instances from jsonld metadata
if not wds_url:
D = rm_wds_url(D)
# Write out the new LiPD files, since they now contain the new NOAA URL data
if(path):
writeLipd(D, path)
else:
print("Path not provided. Writing to CWD...")
writeLipd(D, cwd)
# NOAA mode: Convert NOAA files to LiPD files
elif _mode == "2":
# Pass through the global files list. Use NOAA files directly on disk.
noaa_to_lpd(files)
else:
print("Invalid input. Try again.")
end = clock()
logger_benchmark.info(log_benchmark("noaa", start, end))
return | python | def noaa(D="", path="", wds_url="", lpd_url="", version=""):
"""
Convert between NOAA and LiPD files
| Example: LiPD to NOAA converter
| 1: L = lipd.readLipd()
| 2: lipd.noaa(L, "/Users/someuser/Desktop", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/noaa-templates/data-version-1.0.0", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/data-version-1.0.0", "v1-1.0.0")
| Example: NOAA to LiPD converter
| 1: lipd.readNoaa()
| 2: lipd.noaa()
:param dict D: Metadata
:param str path: Path where output files will be written to
:param str wds_url: WDSPaleoUrl, where NOAA template file will be stored on NOAA's FTP server
:param str lpd_url: URL where LiPD file will be stored on NOAA's FTP server
:param str version: Version of the dataset
:return none:
"""
global files, cwd
# When going from NOAA to LPD, use the global "files" variable.
# When going from LPD to NOAA, use the data from the LiPD Library.
# Choose the mode
_mode = noaa_prompt()
start = clock()
# LiPD mode: Convert LiPD files to NOAA files
if _mode == "1":
# _project, _version = noaa_prompt_1()
if not version or not lpd_url:
print("Missing parameters: Please try again and provide all parameters.")
return
if not D:
print("Error: LiPD data must be provided for LiPD -> NOAA conversions")
else:
if "paleoData" in D:
_d = copy.deepcopy(D)
D = lpd_to_noaa(_d, wds_url, lpd_url, version, path)
else:
# For each LiPD file in the LiPD Library
for dsn, dat in D.items():
_d = copy.deepcopy(dat)
# Process this data through the converter
_d = lpd_to_noaa(_d, wds_url, lpd_url, version, path)
# Overwrite the data in the LiPD object with our new data.
D[dsn] = _d
# If no wds url is provided, then remove instances from jsonld metadata
if not wds_url:
D = rm_wds_url(D)
# Write out the new LiPD files, since they now contain the new NOAA URL data
if(path):
writeLipd(D, path)
else:
print("Path not provided. Writing to CWD...")
writeLipd(D, cwd)
# NOAA mode: Convert NOAA files to LiPD files
elif _mode == "2":
# Pass through the global files list. Use NOAA files directly on disk.
noaa_to_lpd(files)
else:
print("Invalid input. Try again.")
end = clock()
logger_benchmark.info(log_benchmark("noaa", start, end))
return | [
"def",
"noaa",
"(",
"D",
"=",
"\"\"",
",",
"path",
"=",
"\"\"",
",",
"wds_url",
"=",
"\"\"",
",",
"lpd_url",
"=",
"\"\"",
",",
"version",
"=",
"\"\"",
")",
":",
"global",
"files",
",",
"cwd",
"# When going from NOAA to LPD, use the global \"files\" variable.",... | Convert between NOAA and LiPD files
| Example: LiPD to NOAA converter
| 1: L = lipd.readLipd()
| 2: lipd.noaa(L, "/Users/someuser/Desktop", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/noaa-templates/data-version-1.0.0", "https://www1.ncdc.noaa.gov/pub/data/paleo/pages2k/NAm2kHydro-2017/data-version-1.0.0", "v1-1.0.0")
| Example: NOAA to LiPD converter
| 1: lipd.readNoaa()
| 2: lipd.noaa()
:param dict D: Metadata
:param str path: Path where output files will be written to
:param str wds_url: WDSPaleoUrl, where NOAA template file will be stored on NOAA's FTP server
:param str lpd_url: URL where LiPD file will be stored on NOAA's FTP server
:param str version: Version of the dataset
:return none: | [
"Convert",
"between",
"NOAA",
"and",
"LiPD",
"files"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L164-L229 | train | 46,727 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | collapseTs | def collapseTs(ts=None):
"""
Collapse a time series back into LiPD record form.
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. New_D = lipd.collapseTs(ts)
_timeseries_data is sorted by time_id, and then by dataSetName
_timeseries_data[10103341]["ODP1098B"] = {data}
:param list ts: Time series
:return dict: Metadata
"""
# Retrieve the associated raw data according to the "time_id" found in each object. Match it in _timeseries_data
global _timeseries_data
_d = {}
if not ts:
print("Error: Time series data not provided. Pass time series into the function.")
else:
# Send time series list through to be collapsed.
try:
_raw = _timeseries_data[ts[0]["time_id"]]
print(mode_ts("collapse", mode="", ts=ts))
_d = collapse(ts, _raw)
_d = rm_empty_fields(_d)
except Exception as e:
print("Error: Unable to collapse the time series: {}".format(e))
logger_start.error("collapseTs: unable to collapse the time series: {}".format(e))
return _d | python | def collapseTs(ts=None):
"""
Collapse a time series back into LiPD record form.
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. New_D = lipd.collapseTs(ts)
_timeseries_data is sorted by time_id, and then by dataSetName
_timeseries_data[10103341]["ODP1098B"] = {data}
:param list ts: Time series
:return dict: Metadata
"""
# Retrieve the associated raw data according to the "time_id" found in each object. Match it in _timeseries_data
global _timeseries_data
_d = {}
if not ts:
print("Error: Time series data not provided. Pass time series into the function.")
else:
# Send time series list through to be collapsed.
try:
_raw = _timeseries_data[ts[0]["time_id"]]
print(mode_ts("collapse", mode="", ts=ts))
_d = collapse(ts, _raw)
_d = rm_empty_fields(_d)
except Exception as e:
print("Error: Unable to collapse the time series: {}".format(e))
logger_start.error("collapseTs: unable to collapse the time series: {}".format(e))
return _d | [
"def",
"collapseTs",
"(",
"ts",
"=",
"None",
")",
":",
"# Retrieve the associated raw data according to the \"time_id\" found in each object. Match it in _timeseries_data",
"global",
"_timeseries_data",
"_d",
"=",
"{",
"}",
"if",
"not",
"ts",
":",
"print",
"(",
"\"Error: Ti... | Collapse a time series back into LiPD record form.
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. New_D = lipd.collapseTs(ts)
_timeseries_data is sorted by time_id, and then by dataSetName
_timeseries_data[10103341]["ODP1098B"] = {data}
:param list ts: Time series
:return dict: Metadata | [
"Collapse",
"a",
"time",
"series",
"back",
"into",
"LiPD",
"record",
"form",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L458-L488 | train | 46,728 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | filterTs | def filterTs(ts, expressions):
"""
Create a new time series that only contains entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| new_ts = filterTs(ts, "archiveType == marine sediment")
| new_ts = filterTs(ts, ["paleoData_variableName == sst", "archiveType == marine sediment"])
| Expressions should use underscores to denote data nesting.
| Ex: paleoData_hasResolution_hasMedian or
:param list OR str expressions: Expressions
:param list ts: Time series
:return list new_ts: Filtered time series that matches the expression
"""
# Make a copy of the ts. We're going to work directly on it.
new_ts = ts[:]
# User provided a single query string
if isinstance(expressions, str):
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expressions)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
# User provided a list of multiple queries
elif isinstance(expressions, list):
# Loop for each query
for expr in expressions:
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expr)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
return new_ts | python | def filterTs(ts, expressions):
"""
Create a new time series that only contains entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| new_ts = filterTs(ts, "archiveType == marine sediment")
| new_ts = filterTs(ts, ["paleoData_variableName == sst", "archiveType == marine sediment"])
| Expressions should use underscores to denote data nesting.
| Ex: paleoData_hasResolution_hasMedian or
:param list OR str expressions: Expressions
:param list ts: Time series
:return list new_ts: Filtered time series that matches the expression
"""
# Make a copy of the ts. We're going to work directly on it.
new_ts = ts[:]
# User provided a single query string
if isinstance(expressions, str):
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expressions)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
# User provided a list of multiple queries
elif isinstance(expressions, list):
# Loop for each query
for expr in expressions:
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expr)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
return new_ts | [
"def",
"filterTs",
"(",
"ts",
",",
"expressions",
")",
":",
"# Make a copy of the ts. We're going to work directly on it.",
"new_ts",
"=",
"ts",
"[",
":",
"]",
"# User provided a single query string",
"if",
"isinstance",
"(",
"expressions",
",",
"str",
")",
":",
"# Us... | Create a new time series that only contains entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| new_ts = filterTs(ts, "archiveType == marine sediment")
| new_ts = filterTs(ts, ["paleoData_variableName == sst", "archiveType == marine sediment"])
| Expressions should use underscores to denote data nesting.
| Ex: paleoData_hasResolution_hasMedian or
:param list OR str expressions: Expressions
:param list ts: Time series
:return list new_ts: Filtered time series that matches the expression | [
"Create",
"a",
"new",
"time",
"series",
"that",
"only",
"contains",
"entries",
"that",
"match",
"the",
"given",
"expression",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L491-L532 | train | 46,729 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | queryTs | def queryTs(ts, expression):
"""
Find the indices of the time series entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| matches = queryTs(ts, "archiveType == marine sediment")
| matches = queryTs(ts, "geo_meanElev <= 2000")
:param str expression: Expression
:param list ts: Time series
:return list _idx: Indices of entries that match the criteria
"""
# Make a copy of the ts. We're going to work directly on it.
_idx = []
# User provided a single query string
if isinstance(expressions, str):
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expressions)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
# User provided a list of multiple queries
elif isinstance(expressions, list):
# Loop for each query
for expr in expressions:
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expr)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
return _idx | python | def queryTs(ts, expression):
"""
Find the indices of the time series entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| matches = queryTs(ts, "archiveType == marine sediment")
| matches = queryTs(ts, "geo_meanElev <= 2000")
:param str expression: Expression
:param list ts: Time series
:return list _idx: Indices of entries that match the criteria
"""
# Make a copy of the ts. We're going to work directly on it.
_idx = []
# User provided a single query string
if isinstance(expressions, str):
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expressions)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
# User provided a list of multiple queries
elif isinstance(expressions, list):
# Loop for each query
for expr in expressions:
# Use some magic to turn the given string expression into a machine-usable comparative expression.
expr_lst = translate_expression(expr)
# Only proceed if the translation resulted in a usable expression.
if expr_lst:
# Return the new filtered time series. This will use the same time series
# that filters down each loop.
new_ts, _idx = get_matches(expr_lst, new_ts)
return _idx | [
"def",
"queryTs",
"(",
"ts",
",",
"expression",
")",
":",
"# Make a copy of the ts. We're going to work directly on it.",
"_idx",
"=",
"[",
"]",
"# User provided a single query string",
"if",
"isinstance",
"(",
"expressions",
",",
"str",
")",
":",
"# Use some magic to tur... | Find the indices of the time series entries that match the given expression.
| Example:
| D = lipd.loadLipd()
| ts = lipd.extractTs(D)
| matches = queryTs(ts, "archiveType == marine sediment")
| matches = queryTs(ts, "geo_meanElev <= 2000")
:param str expression: Expression
:param list ts: Time series
:return list _idx: Indices of entries that match the criteria | [
"Find",
"the",
"indices",
"of",
"the",
"time",
"series",
"entries",
"that",
"match",
"the",
"given",
"expression",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L535-L573 | train | 46,730 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | viewTs | def viewTs(ts):
"""
View the contents of one time series entry in a nicely formatted way
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. viewTs(ts[0])
:param dict ts: One time series entry
:return none:
"""
_ts = ts
if isinstance(ts, list):
_ts = ts[0]
print("It looks like you input a full time series. It's best to view one entry at a time.\n"
"I'll show you the first entry...")
_tmp_sort = OrderedDict()
_tmp_sort["ROOT"] = {}
_tmp_sort["PUBLICATION"] = {}
_tmp_sort["GEO"] = {}
_tmp_sort["OTHERS"] = {}
_tmp_sort["DATA"] = {}
# Organize the data by section
for k,v in _ts.items():
if not any(i == k for i in ["paleoData", "chronData", "mode", "@context"]):
if k in ["archiveType", "dataSetName", "googleSpreadSheetKey", "metadataMD5", "tagMD5", "googleMetadataWorksheet", "lipdVersion"]:
_tmp_sort["ROOT"][k] = v
elif "pub" in k:
_tmp_sort["PUBLICATION"][k] = v
elif "geo" in k:
_tmp_sort["GEO"][k] = v
elif "paleoData_" in k or "chronData_" in k:
if isinstance(v, list) and len(v) > 2:
_tmp_sort["DATA"][k] = "[{}, {}, {}, ...]".format(v[0], v[1], v[2])
else:
_tmp_sort["DATA"][k] = v
else:
if isinstance(v, list) and len(v) > 2:
_tmp_sort["OTHERS"][k] = "[{}, {}, {}, ...]".format(v[0], v[1], v[2])
else:
_tmp_sort["OTHERS"][k] = v
# Start printing the data to console
for k1, v1 in _tmp_sort.items():
print("\n{}\n===============".format(k1))
for k2, v2 in v1.items():
print("{} : {}".format(k2, v2))
return | python | def viewTs(ts):
"""
View the contents of one time series entry in a nicely formatted way
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. viewTs(ts[0])
:param dict ts: One time series entry
:return none:
"""
_ts = ts
if isinstance(ts, list):
_ts = ts[0]
print("It looks like you input a full time series. It's best to view one entry at a time.\n"
"I'll show you the first entry...")
_tmp_sort = OrderedDict()
_tmp_sort["ROOT"] = {}
_tmp_sort["PUBLICATION"] = {}
_tmp_sort["GEO"] = {}
_tmp_sort["OTHERS"] = {}
_tmp_sort["DATA"] = {}
# Organize the data by section
for k,v in _ts.items():
if not any(i == k for i in ["paleoData", "chronData", "mode", "@context"]):
if k in ["archiveType", "dataSetName", "googleSpreadSheetKey", "metadataMD5", "tagMD5", "googleMetadataWorksheet", "lipdVersion"]:
_tmp_sort["ROOT"][k] = v
elif "pub" in k:
_tmp_sort["PUBLICATION"][k] = v
elif "geo" in k:
_tmp_sort["GEO"][k] = v
elif "paleoData_" in k or "chronData_" in k:
if isinstance(v, list) and len(v) > 2:
_tmp_sort["DATA"][k] = "[{}, {}, {}, ...]".format(v[0], v[1], v[2])
else:
_tmp_sort["DATA"][k] = v
else:
if isinstance(v, list) and len(v) > 2:
_tmp_sort["OTHERS"][k] = "[{}, {}, {}, ...]".format(v[0], v[1], v[2])
else:
_tmp_sort["OTHERS"][k] = v
# Start printing the data to console
for k1, v1 in _tmp_sort.items():
print("\n{}\n===============".format(k1))
for k2, v2 in v1.items():
print("{} : {}".format(k2, v2))
return | [
"def",
"viewTs",
"(",
"ts",
")",
":",
"_ts",
"=",
"ts",
"if",
"isinstance",
"(",
"ts",
",",
"list",
")",
":",
"_ts",
"=",
"ts",
"[",
"0",
"]",
"print",
"(",
"\"It looks like you input a full time series. It's best to view one entry at a time.\\n\"",
"\"I'll show y... | View the contents of one time series entry in a nicely formatted way
| Example
| 1. D = lipd.readLipd()
| 2. ts = lipd.extractTs(D)
| 3. viewTs(ts[0])
:param dict ts: One time series entry
:return none: | [
"View",
"the",
"contents",
"of",
"one",
"time",
"series",
"entry",
"in",
"a",
"nicely",
"formatted",
"way"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L576-L626 | train | 46,731 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | showLipds | def showLipds(D=None):
"""
Display the dataset names of a given LiPD data
| Example
| lipd.showLipds(D)
:pararm dict D: LiPD data
:return none:
"""
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
print(json.dumps(D.keys(), indent=2))
return | python | def showLipds(D=None):
"""
Display the dataset names of a given LiPD data
| Example
| lipd.showLipds(D)
:pararm dict D: LiPD data
:return none:
"""
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
print(json.dumps(D.keys(), indent=2))
return | [
"def",
"showLipds",
"(",
"D",
"=",
"None",
")",
":",
"if",
"not",
"D",
":",
"print",
"(",
"\"Error: LiPD data not provided. Pass LiPD data into the function.\"",
")",
"else",
":",
"print",
"(",
"json",
".",
"dumps",
"(",
"D",
".",
"keys",
"(",
")",
",",
"i... | Display the dataset names of a given LiPD data
| Example
| lipd.showLipds(D)
:pararm dict D: LiPD data
:return none: | [
"Display",
"the",
"dataset",
"names",
"of",
"a",
"given",
"LiPD",
"data"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L649-L665 | train | 46,732 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | showMetadata | def showMetadata(dat):
"""
Display the metadata specified LiPD in pretty print
| Example
| showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict dat: Metadata
:return none:
"""
_tmp = rm_values_fields(copy.deepcopy(dat))
print(json.dumps(_tmp, indent=2))
return | python | def showMetadata(dat):
"""
Display the metadata specified LiPD in pretty print
| Example
| showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict dat: Metadata
:return none:
"""
_tmp = rm_values_fields(copy.deepcopy(dat))
print(json.dumps(_tmp, indent=2))
return | [
"def",
"showMetadata",
"(",
"dat",
")",
":",
"_tmp",
"=",
"rm_values_fields",
"(",
"copy",
".",
"deepcopy",
"(",
"dat",
")",
")",
"print",
"(",
"json",
".",
"dumps",
"(",
"_tmp",
",",
"indent",
"=",
"2",
")",
")",
"return"
] | Display the metadata specified LiPD in pretty print
| Example
| showMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict dat: Metadata
:return none: | [
"Display",
"the",
"metadata",
"specified",
"LiPD",
"in",
"pretty",
"print"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L668-L680 | train | 46,733 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | showDfs | def showDfs(d):
"""
Display the available data frame names in a given data frame collection
:param dict d: Dataframe collection
:return none:
"""
if "metadata" in d:
print("metadata")
if "paleoData" in d:
try:
for k, v in d["paleoData"].items():
print(k)
except KeyError:
pass
except AttributeError:
pass
if "chronData" in d:
try:
for k, v in d["chronData"].items():
print(k)
except KeyError:
pass
except AttributeError:
pass
# print("Process Complete")
return | python | def showDfs(d):
"""
Display the available data frame names in a given data frame collection
:param dict d: Dataframe collection
:return none:
"""
if "metadata" in d:
print("metadata")
if "paleoData" in d:
try:
for k, v in d["paleoData"].items():
print(k)
except KeyError:
pass
except AttributeError:
pass
if "chronData" in d:
try:
for k, v in d["chronData"].items():
print(k)
except KeyError:
pass
except AttributeError:
pass
# print("Process Complete")
return | [
"def",
"showDfs",
"(",
"d",
")",
":",
"if",
"\"metadata\"",
"in",
"d",
":",
"print",
"(",
"\"metadata\"",
")",
"if",
"\"paleoData\"",
"in",
"d",
":",
"try",
":",
"for",
"k",
",",
"v",
"in",
"d",
"[",
"\"paleoData\"",
"]",
".",
"items",
"(",
")",
... | Display the available data frame names in a given data frame collection
:param dict d: Dataframe collection
:return none: | [
"Display",
"the",
"available",
"data",
"frame",
"names",
"in",
"a",
"given",
"data",
"frame",
"collection"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L683-L709 | train | 46,734 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | getLipdNames | def getLipdNames(D=None):
"""
Get a list of all LiPD names in the library
| Example
| names = lipd.getLipdNames(D)
:return list f_list: File list
"""
_names = []
try:
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
_names = D.keys()
except Exception:
pass
return _names | python | def getLipdNames(D=None):
"""
Get a list of all LiPD names in the library
| Example
| names = lipd.getLipdNames(D)
:return list f_list: File list
"""
_names = []
try:
if not D:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
_names = D.keys()
except Exception:
pass
return _names | [
"def",
"getLipdNames",
"(",
"D",
"=",
"None",
")",
":",
"_names",
"=",
"[",
"]",
"try",
":",
"if",
"not",
"D",
":",
"print",
"(",
"\"Error: LiPD data not provided. Pass LiPD data into the function.\"",
")",
"else",
":",
"_names",
"=",
"D",
".",
"keys",
"(",
... | Get a list of all LiPD names in the library
| Example
| names = lipd.getLipdNames(D)
:return list f_list: File list | [
"Get",
"a",
"list",
"of",
"all",
"LiPD",
"names",
"in",
"the",
"library"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L714-L731 | train | 46,735 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | getMetadata | def getMetadata(L):
"""
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
"""
_l = {}
try:
# Create a copy. Do not affect the original data.
_l = copy.deepcopy(L)
# Remove values fields
_l = rm_values_fields(_l)
except Exception as e:
# Input likely not formatted correctly, though other problems can occur.
print("Error: Unable to get data. Please check that input is LiPD data: {}".format(e))
return _l | python | def getMetadata(L):
"""
Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only)
"""
_l = {}
try:
# Create a copy. Do not affect the original data.
_l = copy.deepcopy(L)
# Remove values fields
_l = rm_values_fields(_l)
except Exception as e:
# Input likely not formatted correctly, though other problems can occur.
print("Error: Unable to get data. Please check that input is LiPD data: {}".format(e))
return _l | [
"def",
"getMetadata",
"(",
"L",
")",
":",
"_l",
"=",
"{",
"}",
"try",
":",
"# Create a copy. Do not affect the original data.",
"_l",
"=",
"copy",
".",
"deepcopy",
"(",
"L",
")",
"# Remove values fields",
"_l",
"=",
"rm_values_fields",
"(",
"_l",
")",
"except"... | Get metadata from a LiPD data in memory
| Example
| m = lipd.getMetadata(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: LiPD record (metadata only) | [
"Get",
"metadata",
"from",
"a",
"LiPD",
"data",
"in",
"memory"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L734-L753 | train | 46,736 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | getCsv | def getCsv(L=None):
"""
Get CSV from LiPD metadata
| Example
| c = lipd.getCsv(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: CSV data
"""
_c = {}
try:
if not L:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
_j, _c = get_csv_from_metadata(L["dataSetName"], L)
except KeyError as ke:
print("Error: Unable to get data. Please check that input is one LiPD dataset: {}".format(ke))
except Exception as e:
print("Error: Unable to get data. Something went wrong: {}".format(e))
logger_start.warn("getCsv: Exception: Unable to process lipd data: {}".format(e))
return _c | python | def getCsv(L=None):
"""
Get CSV from LiPD metadata
| Example
| c = lipd.getCsv(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: CSV data
"""
_c = {}
try:
if not L:
print("Error: LiPD data not provided. Pass LiPD data into the function.")
else:
_j, _c = get_csv_from_metadata(L["dataSetName"], L)
except KeyError as ke:
print("Error: Unable to get data. Please check that input is one LiPD dataset: {}".format(ke))
except Exception as e:
print("Error: Unable to get data. Something went wrong: {}".format(e))
logger_start.warn("getCsv: Exception: Unable to process lipd data: {}".format(e))
return _c | [
"def",
"getCsv",
"(",
"L",
"=",
"None",
")",
":",
"_c",
"=",
"{",
"}",
"try",
":",
"if",
"not",
"L",
":",
"print",
"(",
"\"Error: LiPD data not provided. Pass LiPD data into the function.\"",
")",
"else",
":",
"_j",
",",
"_c",
"=",
"get_csv_from_metadata",
"... | Get CSV from LiPD metadata
| Example
| c = lipd.getCsv(D["Africa-ColdAirCave.Sundqvist.2013"])
:param dict L: One LiPD record
:return dict d: CSV data | [
"Get",
"CSV",
"from",
"LiPD",
"metadata"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L756-L777 | train | 46,737 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | __universal_read | def __universal_read(file_path, file_type):
"""
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
global files, cwd, settings
# check that we are using the correct function to load this file type. (i.e. readNoaa for a .txt file)
correct_ext = load_fn_matches_ext(file_path, file_type)
# Check that this path references a file
valid_path = path_type(file_path, "file")
# is the path a file?
if valid_path and correct_ext:
# get file metadata for one file
file_meta = collect_metadata_file(file_path)
# append to global files, then load in D
if file_type == ".lpd":
# add meta to global file meta
files[".lpd"].append(file_meta)
# append to global files
elif file_type in [".xls", ".xlsx"]:
print("reading: {}".format(print_filename(file_meta["full_path"])))
files[".xls"].append(file_meta)
# append to global files
elif file_type == ".txt":
print("reading: {}".format(print_filename(file_meta["full_path"])))
files[".txt"].append(file_meta)
# we want to move around with the files we load
# change dir into the dir of the target file
cwd = file_meta["dir"]
if cwd:
os.chdir(cwd)
return | python | def __universal_read(file_path, file_type):
"""
Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
global files, cwd, settings
# check that we are using the correct function to load this file type. (i.e. readNoaa for a .txt file)
correct_ext = load_fn_matches_ext(file_path, file_type)
# Check that this path references a file
valid_path = path_type(file_path, "file")
# is the path a file?
if valid_path and correct_ext:
# get file metadata for one file
file_meta = collect_metadata_file(file_path)
# append to global files, then load in D
if file_type == ".lpd":
# add meta to global file meta
files[".lpd"].append(file_meta)
# append to global files
elif file_type in [".xls", ".xlsx"]:
print("reading: {}".format(print_filename(file_meta["full_path"])))
files[".xls"].append(file_meta)
# append to global files
elif file_type == ".txt":
print("reading: {}".format(print_filename(file_meta["full_path"])))
files[".txt"].append(file_meta)
# we want to move around with the files we load
# change dir into the dir of the target file
cwd = file_meta["dir"]
if cwd:
os.chdir(cwd)
return | [
"def",
"__universal_read",
"(",
"file_path",
",",
"file_type",
")",
":",
"global",
"files",
",",
"cwd",
",",
"settings",
"# check that we are using the correct function to load this file type. (i.e. readNoaa for a .txt file)",
"correct_ext",
"=",
"load_fn_matches_ext",
"(",
"fi... | Use a file path to create file metadata and load a file in the appropriate way, according to the provided file type.
:param str file_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none: | [
"Use",
"a",
"file",
"path",
"to",
"create",
"file",
"metadata",
"and",
"load",
"a",
"file",
"in",
"the",
"appropriate",
"way",
"according",
"to",
"the",
"provided",
"file",
"type",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L801-L843 | train | 46,738 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | __read_lipd_contents | def __read_lipd_contents():
"""
Use the file metadata to read in the LiPD file contents as a dataset library
:return dict: Metadata
"""
global files, settings
_d = {}
try:
if len(files[".lpd"]) == 1:
_d = lipd_read(files[".lpd"][0]["full_path"])
if settings["verbose"]:
print("Finished read: 1 record")
else:
for file in files[".lpd"]:
_d[file["filename_no_ext"]] = lipd_read(file["full_path"])
if settings["verbose"]:
print("Finished read: {} records".format(len(_d)))
except Exception as e:
print("Error: read_lipd_contents: {}".format(e))
return _d | python | def __read_lipd_contents():
"""
Use the file metadata to read in the LiPD file contents as a dataset library
:return dict: Metadata
"""
global files, settings
_d = {}
try:
if len(files[".lpd"]) == 1:
_d = lipd_read(files[".lpd"][0]["full_path"])
if settings["verbose"]:
print("Finished read: 1 record")
else:
for file in files[".lpd"]:
_d[file["filename_no_ext"]] = lipd_read(file["full_path"])
if settings["verbose"]:
print("Finished read: {} records".format(len(_d)))
except Exception as e:
print("Error: read_lipd_contents: {}".format(e))
return _d | [
"def",
"__read_lipd_contents",
"(",
")",
":",
"global",
"files",
",",
"settings",
"_d",
"=",
"{",
"}",
"try",
":",
"if",
"len",
"(",
"files",
"[",
"\".lpd\"",
"]",
")",
"==",
"1",
":",
"_d",
"=",
"lipd_read",
"(",
"files",
"[",
"\".lpd\"",
"]",
"["... | Use the file metadata to read in the LiPD file contents as a dataset library
:return dict: Metadata | [
"Use",
"the",
"file",
"metadata",
"to",
"read",
"in",
"the",
"LiPD",
"file",
"contents",
"as",
"a",
"dataset",
"library"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L900-L920 | train | 46,739 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | __read_file | def __read_file(usr_path, file_type):
"""
Universal read file. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
global files
# no path provided. start gui browse
if not usr_path:
# src files could be a list of one, or a list of many. depending how many files the user selects
src_dir, src_files = get_src_or_dst("read", "file")
# check if src_files is a list of multiple files
if src_files:
for file_path in src_files:
__universal_read(file_path, file_type)
else:
print("No file(s) chosen")
else:
__universal_read(usr_path, file_type)
return | python | def __read_file(usr_path, file_type):
"""
Universal read file. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none:
"""
global files
# no path provided. start gui browse
if not usr_path:
# src files could be a list of one, or a list of many. depending how many files the user selects
src_dir, src_files = get_src_or_dst("read", "file")
# check if src_files is a list of multiple files
if src_files:
for file_path in src_files:
__universal_read(file_path, file_type)
else:
print("No file(s) chosen")
else:
__universal_read(usr_path, file_type)
return | [
"def",
"__read_file",
"(",
"usr_path",
",",
"file_type",
")",
":",
"global",
"files",
"# no path provided. start gui browse",
"if",
"not",
"usr_path",
":",
"# src files could be a list of one, or a list of many. depending how many files the user selects",
"src_dir",
",",
"src_fil... | Universal read file. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to file
:param str file_type: One of approved file types: xls, xlsx, txt, lpd
:return none: | [
"Universal",
"read",
"file",
".",
"Given",
"a",
"path",
"and",
"a",
"type",
"it",
"will",
"do",
"the",
"appropriate",
"read",
"actions"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L923-L946 | train | 46,740 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | __read_directory | def __read_directory(usr_path, file_type):
"""
Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none:
"""
# no path provided. start gui browse
if not usr_path:
# got dir path
usr_path, src_files = get_src_or_dst("read", "directory")
# Check if this is a valid directory path
valid_path = path_type(usr_path, "directory")
# If dir path is valid
if valid_path:
# List all files of target type in dir
files_found = []
# Extra case for xlsx excel files
if file_type == ".xls":
files_found += list_files(".xlsx", usr_path)
files_found += list_files(file_type, usr_path)
# notify how many files were found
print("Found: {} {} file(s)".format(len(files_found), FILE_TYPE_MAP[file_type]["file_type"]))
# Loop for each file found
for file_path in files_found:
# Call read lipd for each file found
__read_file(file_path, file_type)
else:
print("Directory path is not valid: {}".format(usr_path))
return | python | def __read_directory(usr_path, file_type):
"""
Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none:
"""
# no path provided. start gui browse
if not usr_path:
# got dir path
usr_path, src_files = get_src_or_dst("read", "directory")
# Check if this is a valid directory path
valid_path = path_type(usr_path, "directory")
# If dir path is valid
if valid_path:
# List all files of target type in dir
files_found = []
# Extra case for xlsx excel files
if file_type == ".xls":
files_found += list_files(".xlsx", usr_path)
files_found += list_files(file_type, usr_path)
# notify how many files were found
print("Found: {} {} file(s)".format(len(files_found), FILE_TYPE_MAP[file_type]["file_type"]))
# Loop for each file found
for file_path in files_found:
# Call read lipd for each file found
__read_file(file_path, file_type)
else:
print("Directory path is not valid: {}".format(usr_path))
return | [
"def",
"__read_directory",
"(",
"usr_path",
",",
"file_type",
")",
":",
"# no path provided. start gui browse",
"if",
"not",
"usr_path",
":",
"# got dir path",
"usr_path",
",",
"src_files",
"=",
"get_src_or_dst",
"(",
"\"read\"",
",",
"\"directory\"",
")",
"# Check if... | Universal read directory. Given a path and a type, it will do the appropriate read actions
:param str usr_path: Path to directory
:param str file_type: .xls, .xlsx, .txt, .lpd
:return none: | [
"Universal",
"read",
"directory",
".",
"Given",
"a",
"path",
"and",
"a",
"type",
"it",
"will",
"do",
"the",
"appropriate",
"read",
"actions"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L949-L981 | train | 46,741 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | __write_lipd | def __write_lipd(dat, usr_path):
"""
Write LiPD data to file, provided an output directory and dataset name.
:param dict dat: Metadata
:param str usr_path: Destination path
:param str dsn: Dataset name of one specific file to write
:return none:
"""
global settings
# no path provided. start gui browse
if not usr_path:
# got dir path
usr_path, _ignore = get_src_or_dst("write", "directory")
# Check if this is a valid directory path
valid_path = path_type(usr_path, "directory")
# If dir path is valid
if valid_path:
# Filename is given, write out one file
if "paleoData" in dat:
try:
if settings["verbose"]:
print("writing: {}".format(dat["dataSetName"]))
lipd_write(dat, usr_path)
except KeyError as ke:
print("Error: Unable to write file: unknown, {}".format(ke))
except Exception as e:
print("Error: Unable to write file: {}, {}".format(dat["dataSetName"], e))
# Filename is not given, write out whole library
else:
if dat:
for name, lipd_dat in dat.items():
try:
if settings["verbose"]:
print("writing: {}".format(name))
lipd_write(lipd_dat, usr_path)
except Exception as e:
print("Error: Unable to write file: {}, {}".format(name, e))
return | python | def __write_lipd(dat, usr_path):
"""
Write LiPD data to file, provided an output directory and dataset name.
:param dict dat: Metadata
:param str usr_path: Destination path
:param str dsn: Dataset name of one specific file to write
:return none:
"""
global settings
# no path provided. start gui browse
if not usr_path:
# got dir path
usr_path, _ignore = get_src_or_dst("write", "directory")
# Check if this is a valid directory path
valid_path = path_type(usr_path, "directory")
# If dir path is valid
if valid_path:
# Filename is given, write out one file
if "paleoData" in dat:
try:
if settings["verbose"]:
print("writing: {}".format(dat["dataSetName"]))
lipd_write(dat, usr_path)
except KeyError as ke:
print("Error: Unable to write file: unknown, {}".format(ke))
except Exception as e:
print("Error: Unable to write file: {}, {}".format(dat["dataSetName"], e))
# Filename is not given, write out whole library
else:
if dat:
for name, lipd_dat in dat.items():
try:
if settings["verbose"]:
print("writing: {}".format(name))
lipd_write(lipd_dat, usr_path)
except Exception as e:
print("Error: Unable to write file: {}, {}".format(name, e))
return | [
"def",
"__write_lipd",
"(",
"dat",
",",
"usr_path",
")",
":",
"global",
"settings",
"# no path provided. start gui browse",
"if",
"not",
"usr_path",
":",
"# got dir path",
"usr_path",
",",
"_ignore",
"=",
"get_src_or_dst",
"(",
"\"write\"",
",",
"\"directory\"",
")"... | Write LiPD data to file, provided an output directory and dataset name.
:param dict dat: Metadata
:param str usr_path: Destination path
:param str dsn: Dataset name of one specific file to write
:return none: | [
"Write",
"LiPD",
"data",
"to",
"file",
"provided",
"an",
"output",
"directory",
"and",
"dataset",
"name",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L984-L1023 | train | 46,742 |
nickmckay/LiPD-utilities | Python/lipd/__init__.py | __disclaimer | def __disclaimer(opt=""):
"""
Print the disclaimers once. If they've already been shown, skip over.
:return none:
"""
global settings
if opt is "update":
print("Disclaimer: LiPD files may be updated and modified to adhere to standards\n")
settings["note_update"] = False
if opt is "validate":
print("Note: Use lipd.validate() or www.LiPD.net/create "
"to ensure that your new LiPD file(s) are valid")
settings["note_validate"] = False
return | python | def __disclaimer(opt=""):
"""
Print the disclaimers once. If they've already been shown, skip over.
:return none:
"""
global settings
if opt is "update":
print("Disclaimer: LiPD files may be updated and modified to adhere to standards\n")
settings["note_update"] = False
if opt is "validate":
print("Note: Use lipd.validate() or www.LiPD.net/create "
"to ensure that your new LiPD file(s) are valid")
settings["note_validate"] = False
return | [
"def",
"__disclaimer",
"(",
"opt",
"=",
"\"\"",
")",
":",
"global",
"settings",
"if",
"opt",
"is",
"\"update\"",
":",
"print",
"(",
"\"Disclaimer: LiPD files may be updated and modified to adhere to standards\\n\"",
")",
"settings",
"[",
"\"note_update\"",
"]",
"=",
"... | Print the disclaimers once. If they've already been shown, skip over.
:return none: | [
"Print",
"the",
"disclaimers",
"once",
".",
"If",
"they",
"ve",
"already",
"been",
"shown",
"skip",
"over",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/__init__.py#L1026-L1040 | train | 46,743 |
dchaplinsky/unshred | unshred/sheet.py | Sheet.get_shreds | def get_shreds(self, feature_extractors, sheet_name):
"""Detects shreds in the current sheet and constructs Shred instances.
Caches the results for further invocations.
Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature assignment.
sheet_name: string, included in shred attributes.
Returns:
list of Shred instances.
"""
if self._shreds is None:
shreds = []
_, contours, _ = cv2.findContours(self._foreground_mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
shred = self._make_shred(contour, i, feature_extractors,
sheet_name)
if shred is not None:
shreds.append(shred)
self._shreds = shreds
return self._shreds | python | def get_shreds(self, feature_extractors, sheet_name):
"""Detects shreds in the current sheet and constructs Shred instances.
Caches the results for further invocations.
Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature assignment.
sheet_name: string, included in shred attributes.
Returns:
list of Shred instances.
"""
if self._shreds is None:
shreds = []
_, contours, _ = cv2.findContours(self._foreground_mask,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
for i, contour in enumerate(contours):
shred = self._make_shred(contour, i, feature_extractors,
sheet_name)
if shred is not None:
shreds.append(shred)
self._shreds = shreds
return self._shreds | [
"def",
"get_shreds",
"(",
"self",
",",
"feature_extractors",
",",
"sheet_name",
")",
":",
"if",
"self",
".",
"_shreds",
"is",
"None",
":",
"shreds",
"=",
"[",
"]",
"_",
",",
"contours",
",",
"_",
"=",
"cv2",
".",
"findContours",
"(",
"self",
".",
"_f... | Detects shreds in the current sheet and constructs Shred instances.
Caches the results for further invocations.
Args:
feature_extractors: iterable of AbstractShredFeature instances to
use for shreds feature assignment.
sheet_name: string, included in shred attributes.
Returns:
list of Shred instances. | [
"Detects",
"shreds",
"in",
"the",
"current",
"sheet",
"and",
"constructs",
"Shred",
"instances",
"."
] | ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8 | https://github.com/dchaplinsky/unshred/blob/ca9cd6a1c6fb8c77d5424dd660ff5d2f3720c0f8/unshred/sheet.py#L78-L102 | train | 46,744 |
mfussenegger/cr8 | cr8/run_track.py | run_track | def run_track(track,
result_hosts=None,
crate_root=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
failfast=False,
sample_mode='reservoir'):
"""Execute a track file"""
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
executor = Executor(
track_dir=os.path.dirname(track),
log=log,
result_hosts=result_hosts,
crate_root=crate_root,
fail_fast=failfast,
sample_mode=sample_mode
)
error = executor.execute(toml.load(track))
if error:
sys.exit(1) | python | def run_track(track,
result_hosts=None,
crate_root=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
failfast=False,
sample_mode='reservoir'):
"""Execute a track file"""
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
executor = Executor(
track_dir=os.path.dirname(track),
log=log,
result_hosts=result_hosts,
crate_root=crate_root,
fail_fast=failfast,
sample_mode=sample_mode
)
error = executor.execute(toml.load(track))
if error:
sys.exit(1) | [
"def",
"run_track",
"(",
"track",
",",
"result_hosts",
"=",
"None",
",",
"crate_root",
"=",
"None",
",",
"output_fmt",
"=",
"None",
",",
"logfile_info",
"=",
"None",
",",
"logfile_result",
"=",
"None",
",",
"failfast",
"=",
"False",
",",
"sample_mode",
"="... | Execute a track file | [
"Execute",
"a",
"track",
"file"
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_track.py#L104-L126 | train | 46,745 |
nickmckay/LiPD-utilities | Python/lipd/versions.py | update_lipd_version | def update_lipd_version(L):
"""
Metadata is indexed by number at this step.
Use the current version number to determine where to start updating from. Use "chain versioning" to make it
modular. If a file is a few versions behind, convert to EACH version until reaching current. If a file is one
version behind, it will only convert once to the newest.
:param dict L: Metadata
:return dict d: Metadata
"""
# Get the lipd version number.
L, version = get_lipd_version(L)
# Update from (N/A or 1.0) to 1.1
if version in [1.0, "1.0"]:
L = update_lipd_v1_1(L)
version = 1.1
# Update from 1.1 to 1.2
if version in [1.1, "1.1"]:
L = update_lipd_v1_2(L)
version = 1.2
if version in [1.2, "1.2"]:
L = update_lipd_v1_3(L)
version = 1.3
L = fix_doi(L)
L["lipdVersion"] = 1.3
return L | python | def update_lipd_version(L):
"""
Metadata is indexed by number at this step.
Use the current version number to determine where to start updating from. Use "chain versioning" to make it
modular. If a file is a few versions behind, convert to EACH version until reaching current. If a file is one
version behind, it will only convert once to the newest.
:param dict L: Metadata
:return dict d: Metadata
"""
# Get the lipd version number.
L, version = get_lipd_version(L)
# Update from (N/A or 1.0) to 1.1
if version in [1.0, "1.0"]:
L = update_lipd_v1_1(L)
version = 1.1
# Update from 1.1 to 1.2
if version in [1.1, "1.1"]:
L = update_lipd_v1_2(L)
version = 1.2
if version in [1.2, "1.2"]:
L = update_lipd_v1_3(L)
version = 1.3
L = fix_doi(L)
L["lipdVersion"] = 1.3
return L | [
"def",
"update_lipd_version",
"(",
"L",
")",
":",
"# Get the lipd version number.",
"L",
",",
"version",
"=",
"get_lipd_version",
"(",
"L",
")",
"# Update from (N/A or 1.0) to 1.1",
"if",
"version",
"in",
"[",
"1.0",
",",
"\"1.0\"",
"]",
":",
"L",
"=",
"update_l... | Metadata is indexed by number at this step.
Use the current version number to determine where to start updating from. Use "chain versioning" to make it
modular. If a file is a few versions behind, convert to EACH version until reaching current. If a file is one
version behind, it will only convert once to the newest.
:param dict L: Metadata
:return dict d: Metadata | [
"Metadata",
"is",
"indexed",
"by",
"number",
"at",
"this",
"step",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/versions.py#L101-L129 | train | 46,746 |
nickmckay/LiPD-utilities | Python/lipd/versions.py | update_lipd_v1_1 | def update_lipd_v1_1(d):
"""
Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:param dict d: Metadata v1.0
:return dict d: Metadata v1.1
"""
logger_versions.info("enter update_lipd_v1_1")
tmp_all = []
try:
# ChronData is the only structure update
if "chronData" in d:
# As of v1.1, ChronData should have an extra level of abstraction.
# No longer shares the same structure of paleoData
# If no measurement table, then make a measurement table list with the table as the entry
for table in d["chronData"]:
if "chronMeasurementTable" not in table:
tmp_all.append({"chronMeasurementTable": [table]})
# If the table exists, but it is a dictionary, then turn it into a list with one entry
elif "chronMeasurementTable" in table:
if isinstance(table["chronMeasurementTable"], dict):
tmp_all.append({"chronMeasurementTable": [table["chronMeasurementTable"]]})
if tmp_all:
d["chronData"] = tmp_all
# Log that this is now a v1.1 structured file
d["lipdVersion"] = 1.1
except Exception as e:
logger_versions.error("update_lipd_v1_1: Exception: {}".format(e))
logger_versions.info("exit update_lipd_v1_1")
return d | python | def update_lipd_v1_1(d):
"""
Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:param dict d: Metadata v1.0
:return dict d: Metadata v1.1
"""
logger_versions.info("enter update_lipd_v1_1")
tmp_all = []
try:
# ChronData is the only structure update
if "chronData" in d:
# As of v1.1, ChronData should have an extra level of abstraction.
# No longer shares the same structure of paleoData
# If no measurement table, then make a measurement table list with the table as the entry
for table in d["chronData"]:
if "chronMeasurementTable" not in table:
tmp_all.append({"chronMeasurementTable": [table]})
# If the table exists, but it is a dictionary, then turn it into a list with one entry
elif "chronMeasurementTable" in table:
if isinstance(table["chronMeasurementTable"], dict):
tmp_all.append({"chronMeasurementTable": [table["chronMeasurementTable"]]})
if tmp_all:
d["chronData"] = tmp_all
# Log that this is now a v1.1 structured file
d["lipdVersion"] = 1.1
except Exception as e:
logger_versions.error("update_lipd_v1_1: Exception: {}".format(e))
logger_versions.info("exit update_lipd_v1_1")
return d | [
"def",
"update_lipd_v1_1",
"(",
"d",
")",
":",
"logger_versions",
".",
"info",
"(",
"\"enter update_lipd_v1_1\"",
")",
"tmp_all",
"=",
"[",
"]",
"try",
":",
"# ChronData is the only structure update",
"if",
"\"chronData\"",
"in",
"d",
":",
"# As of v1.1, ChronData sho... | Update LiPD v1.0 to v1.1
- chronData entry is a list that allows multiple tables
- paleoData entry is a list that allows multiple tables
- chronData now allows measurement, model, summary, modelTable, ensemble, calibratedAges tables
- Added 'lipdVersion' key
:param dict d: Metadata v1.0
:return dict d: Metadata v1.1 | [
"Update",
"LiPD",
"v1",
".",
"0",
"to",
"v1",
".",
"1",
"-",
"chronData",
"entry",
"is",
"a",
"list",
"that",
"allows",
"multiple",
"tables",
"-",
"paleoData",
"entry",
"is",
"a",
"list",
"that",
"allows",
"multiple",
"tables",
"-",
"chronData",
"now",
... | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/versions.py#L132-L169 | train | 46,747 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | merge_csv_metadata | def merge_csv_metadata(d, csvs):
"""
Using the given metadata dictionary, retrieve CSV data from CSV files, and insert the CSV
values into their respective metadata columns. Checks for both paleoData and chronData tables.
:param dict d: Metadata
:return dict: Modified metadata dictionary
"""
logger_csvs.info("enter merge_csv_metadata")
# Add CSV to paleoData
if "paleoData" in d:
d["paleoData"] = _merge_csv_section(d["paleoData"], "paleo", csvs)
# Add CSV to chronData
if "chronData" in d:
d["chronData"] = _merge_csv_section(d["chronData"], "chron", csvs)
logger_csvs.info("exit merge_csv_metadata")
return d | python | def merge_csv_metadata(d, csvs):
"""
Using the given metadata dictionary, retrieve CSV data from CSV files, and insert the CSV
values into their respective metadata columns. Checks for both paleoData and chronData tables.
:param dict d: Metadata
:return dict: Modified metadata dictionary
"""
logger_csvs.info("enter merge_csv_metadata")
# Add CSV to paleoData
if "paleoData" in d:
d["paleoData"] = _merge_csv_section(d["paleoData"], "paleo", csvs)
# Add CSV to chronData
if "chronData" in d:
d["chronData"] = _merge_csv_section(d["chronData"], "chron", csvs)
logger_csvs.info("exit merge_csv_metadata")
return d | [
"def",
"merge_csv_metadata",
"(",
"d",
",",
"csvs",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter merge_csv_metadata\"",
")",
"# Add CSV to paleoData",
"if",
"\"paleoData\"",
"in",
"d",
":",
"d",
"[",
"\"paleoData\"",
"]",
"=",
"_merge_csv_section",
"(",
"... | Using the given metadata dictionary, retrieve CSV data from CSV files, and insert the CSV
values into their respective metadata columns. Checks for both paleoData and chronData tables.
:param dict d: Metadata
:return dict: Modified metadata dictionary | [
"Using",
"the",
"given",
"metadata",
"dictionary",
"retrieve",
"CSV",
"data",
"from",
"CSV",
"files",
"and",
"insert",
"the",
"CSV",
"values",
"into",
"their",
"respective",
"metadata",
"columns",
".",
"Checks",
"for",
"both",
"paleoData",
"and",
"chronData",
... | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L18-L37 | train | 46,748 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | _merge_csv_section | def _merge_csv_section(sections, pc, csvs):
"""
Add csv data to all paleo data tables
:param dict sections: Metadata
:return dict sections: Metadata
"""
logger_csvs.info("enter merge_csv_section")
try:
# Loop through each table_data in paleoData
for _name, _section in sections.items():
if "measurementTable" in _section:
sections[_name]["measurementTable"] = _merge_csv_table(_section["measurementTable"], pc, csvs)
if "model" in _section:
sections[_name]["model"] = _merge_csv_model(_section["model"], pc, csvs)
except Exception as e:
print("Error: There was an error merging CSV data into the metadata ")
logger_csvs.error("merge_csv_section: {}".format(e))
logger_csvs.info("exit merge_csv_section")
return sections | python | def _merge_csv_section(sections, pc, csvs):
"""
Add csv data to all paleo data tables
:param dict sections: Metadata
:return dict sections: Metadata
"""
logger_csvs.info("enter merge_csv_section")
try:
# Loop through each table_data in paleoData
for _name, _section in sections.items():
if "measurementTable" in _section:
sections[_name]["measurementTable"] = _merge_csv_table(_section["measurementTable"], pc, csvs)
if "model" in _section:
sections[_name]["model"] = _merge_csv_model(_section["model"], pc, csvs)
except Exception as e:
print("Error: There was an error merging CSV data into the metadata ")
logger_csvs.error("merge_csv_section: {}".format(e))
logger_csvs.info("exit merge_csv_section")
return sections | [
"def",
"_merge_csv_section",
"(",
"sections",
",",
"pc",
",",
"csvs",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter merge_csv_section\"",
")",
"try",
":",
"# Loop through each table_data in paleoData",
"for",
"_name",
",",
"_section",
"in",
"sections",
".",
... | Add csv data to all paleo data tables
:param dict sections: Metadata
:return dict sections: Metadata | [
"Add",
"csv",
"data",
"to",
"all",
"paleo",
"data",
"tables"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L40-L64 | train | 46,749 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | _merge_csv_model | def _merge_csv_model(models, pc, csvs):
"""
Add csv data to each column in chron model
:param dict models: Metadata
:return dict models: Metadata
"""
logger_csvs.info("enter merge_csv_model")
try:
for _name, _model in models.items():
if "summaryTable" in _model:
models[_name]["summaryTable"] = _merge_csv_table(_model["summaryTable"], pc, csvs)
if "ensembleTable" in _model:
models[_name]["ensembleTable"] = _merge_csv_table(_model["ensembleTable"], pc, csvs)
if "distributionTable" in _model:
models[_name]["distributionTable"] = _merge_csv_table(_model["distributionTable"], pc, csvs)
except Exception as e:
logger_csvs.error("merge_csv_model: {}",format(e))
logger_csvs.info("exit merge_csv_model")
return models | python | def _merge_csv_model(models, pc, csvs):
"""
Add csv data to each column in chron model
:param dict models: Metadata
:return dict models: Metadata
"""
logger_csvs.info("enter merge_csv_model")
try:
for _name, _model in models.items():
if "summaryTable" in _model:
models[_name]["summaryTable"] = _merge_csv_table(_model["summaryTable"], pc, csvs)
if "ensembleTable" in _model:
models[_name]["ensembleTable"] = _merge_csv_table(_model["ensembleTable"], pc, csvs)
if "distributionTable" in _model:
models[_name]["distributionTable"] = _merge_csv_table(_model["distributionTable"], pc, csvs)
except Exception as e:
logger_csvs.error("merge_csv_model: {}",format(e))
logger_csvs.info("exit merge_csv_model")
return models | [
"def",
"_merge_csv_model",
"(",
"models",
",",
"pc",
",",
"csvs",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter merge_csv_model\"",
")",
"try",
":",
"for",
"_name",
",",
"_model",
"in",
"models",
".",
"items",
"(",
")",
":",
"if",
"\"summaryTable\"",... | Add csv data to each column in chron model
:param dict models: Metadata
:return dict models: Metadata | [
"Add",
"csv",
"data",
"to",
"each",
"column",
"in",
"chron",
"model"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L67-L92 | train | 46,750 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | _merge_csv_column | def _merge_csv_column(table, csvs):
"""
Add csv data to each column in a list of columns
:param dict table: Table metadata
:param str crumbs: Hierarchy crumbs
:param str pc: Paleo or Chron table type
:return dict: Table metadata with csv "values" entry
:return bool ensemble: Ensemble data or not ensemble data
"""
# Start putting CSV data into corresponding column "values" key
try:
ensemble = is_ensemble(table["columns"])
if ensemble:
# realization columns
if len(table["columns"]) == 1:
for _name, _column in table["columns"].items():
_column["values"] = csvs
# depth column + realization columns
elif len(table["columns"]) == 2:
_multi_column = False
for _name, _column in table["columns"].items():
if isinstance(_column["number"], (int, float)):
col_num = cast_int(_column["number"])
_column['values'] = csvs[col_num - 1]
elif isinstance(_column["number"], list):
if _multi_column:
raise Exception("Error: merge_csv_column: This jsonld metadata looks wrong!\n"
"\tAn ensemble table depth should not reference multiple columns of CSV data.\n"
"\tPlease manually fix the ensemble columns in 'metadata.jsonld' inside of your LiPD file.")
else:
_multi_column = True
_column["values"] = csvs[2:]
else:
for _name, _column in table['columns'].items():
col_num = cast_int(_column["number"])
_column['values'] = csvs[col_num - 1]
except IndexError:
logger_csvs.warning("merge_csv_column: IndexError: index out of range of csv_data list")
except KeyError:
logger_csvs.error("merge_csv_column: KeyError: missing columns key")
except Exception as e:
logger_csvs.error("merge_csv_column: Unknown Error: {}".format(e))
print("Quitting...")
exit(1)
# We want to keep one missing value ONLY at the table level. Remove MVs if they're still in column-level
return table, ensemble | python | def _merge_csv_column(table, csvs):
"""
Add csv data to each column in a list of columns
:param dict table: Table metadata
:param str crumbs: Hierarchy crumbs
:param str pc: Paleo or Chron table type
:return dict: Table metadata with csv "values" entry
:return bool ensemble: Ensemble data or not ensemble data
"""
# Start putting CSV data into corresponding column "values" key
try:
ensemble = is_ensemble(table["columns"])
if ensemble:
# realization columns
if len(table["columns"]) == 1:
for _name, _column in table["columns"].items():
_column["values"] = csvs
# depth column + realization columns
elif len(table["columns"]) == 2:
_multi_column = False
for _name, _column in table["columns"].items():
if isinstance(_column["number"], (int, float)):
col_num = cast_int(_column["number"])
_column['values'] = csvs[col_num - 1]
elif isinstance(_column["number"], list):
if _multi_column:
raise Exception("Error: merge_csv_column: This jsonld metadata looks wrong!\n"
"\tAn ensemble table depth should not reference multiple columns of CSV data.\n"
"\tPlease manually fix the ensemble columns in 'metadata.jsonld' inside of your LiPD file.")
else:
_multi_column = True
_column["values"] = csvs[2:]
else:
for _name, _column in table['columns'].items():
col_num = cast_int(_column["number"])
_column['values'] = csvs[col_num - 1]
except IndexError:
logger_csvs.warning("merge_csv_column: IndexError: index out of range of csv_data list")
except KeyError:
logger_csvs.error("merge_csv_column: KeyError: missing columns key")
except Exception as e:
logger_csvs.error("merge_csv_column: Unknown Error: {}".format(e))
print("Quitting...")
exit(1)
# We want to keep one missing value ONLY at the table level. Remove MVs if they're still in column-level
return table, ensemble | [
"def",
"_merge_csv_column",
"(",
"table",
",",
"csvs",
")",
":",
"# Start putting CSV data into corresponding column \"values\" key",
"try",
":",
"ensemble",
"=",
"is_ensemble",
"(",
"table",
"[",
"\"columns\"",
"]",
")",
"if",
"ensemble",
":",
"# realization columns",
... | Add csv data to each column in a list of columns
:param dict table: Table metadata
:param str crumbs: Hierarchy crumbs
:param str pc: Paleo or Chron table type
:return dict: Table metadata with csv "values" entry
:return bool ensemble: Ensemble data or not ensemble data | [
"Add",
"csv",
"data",
"to",
"each",
"column",
"in",
"a",
"list",
"of",
"columns"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L140-L188 | train | 46,751 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | read_csv_from_file | def read_csv_from_file(filename):
"""
Opens the target CSV file and creates a dictionary with one list for each CSV column.
:param str filename:
:return list of lists: column values
"""
logger_csvs.info("enter read_csv_from_file")
d = {}
l = []
try:
logger_csvs.info("open file: {}".format(filename))
with open(filename, 'r') as f:
r = csv.reader(f, delimiter=',')
# Create a dict with X lists corresponding to X columns
for idx, col in enumerate(next(r)):
d[idx] = []
d = cast_values_csvs(d, idx, col)
# Start iter through CSV data
for row in r:
for idx, col in enumerate(row):
# Append the cell to the correct column list
d = cast_values_csvs(d, idx, col)
# Make a list of lists out of the dictionary instead
for idx, col in d.items():
l.append(col)
except FileNotFoundError as e:
print('CSV FileNotFound: ' + filename)
logger_csvs.warn("read_csv_to_columns: FileNotFound: {}, {}".format(filename, e))
logger_csvs.info("exit read_csv_from_file")
return l | python | def read_csv_from_file(filename):
"""
Opens the target CSV file and creates a dictionary with one list for each CSV column.
:param str filename:
:return list of lists: column values
"""
logger_csvs.info("enter read_csv_from_file")
d = {}
l = []
try:
logger_csvs.info("open file: {}".format(filename))
with open(filename, 'r') as f:
r = csv.reader(f, delimiter=',')
# Create a dict with X lists corresponding to X columns
for idx, col in enumerate(next(r)):
d[idx] = []
d = cast_values_csvs(d, idx, col)
# Start iter through CSV data
for row in r:
for idx, col in enumerate(row):
# Append the cell to the correct column list
d = cast_values_csvs(d, idx, col)
# Make a list of lists out of the dictionary instead
for idx, col in d.items():
l.append(col)
except FileNotFoundError as e:
print('CSV FileNotFound: ' + filename)
logger_csvs.warn("read_csv_to_columns: FileNotFound: {}, {}".format(filename, e))
logger_csvs.info("exit read_csv_from_file")
return l | [
"def",
"read_csv_from_file",
"(",
"filename",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter read_csv_from_file\"",
")",
"d",
"=",
"{",
"}",
"l",
"=",
"[",
"]",
"try",
":",
"logger_csvs",
".",
"info",
"(",
"\"open file: {}\"",
".",
"format",
"(",
"fil... | Opens the target CSV file and creates a dictionary with one list for each CSV column.
:param str filename:
:return list of lists: column values | [
"Opens",
"the",
"target",
"CSV",
"file",
"and",
"creates",
"a",
"dictionary",
"with",
"one",
"list",
"for",
"each",
"CSV",
"column",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L208-L241 | train | 46,752 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | write_csv_to_file | def write_csv_to_file(d):
"""
Writes columns of data to a target CSV file.
:param dict d: A dictionary containing one list for every data column. Keys: int, Values: list
:return None:
"""
logger_csvs.info("enter write_csv_to_file")
try:
for filename, data in d.items():
try:
l_columns = _reorder_csv(data, filename)
rows = zip(*l_columns)
with open(filename, 'w+') as f:
w = csv.writer(f)
for row in rows:
row2 = decimal_precision(row)
w.writerow(row2)
except TypeError as e:
print("Error: Unable to write values to CSV file, {}:\n"
"(1) The data table may have 2 or more identical variables. Please correct the LiPD file manually\n"
"(2) There may have been an error trying to prep the values for file write. The 'number' field in the data columns may be a 'string' instead of an 'integer' data type".format(filename))
print(e)
except Exception as e:
print("Error: CSV file not written, {}, {}:\n"
"The data table may have 2 or more identical variables. Please correct the LiPD file manually".format(filename, e))
except AttributeError as e:
logger_csvs.error("write_csv_to_file: Unable to write CSV File: {}".format(e, exc_info=True))
logger_csvs.info("exit write_csv_to_file")
return | python | def write_csv_to_file(d):
"""
Writes columns of data to a target CSV file.
:param dict d: A dictionary containing one list for every data column. Keys: int, Values: list
:return None:
"""
logger_csvs.info("enter write_csv_to_file")
try:
for filename, data in d.items():
try:
l_columns = _reorder_csv(data, filename)
rows = zip(*l_columns)
with open(filename, 'w+') as f:
w = csv.writer(f)
for row in rows:
row2 = decimal_precision(row)
w.writerow(row2)
except TypeError as e:
print("Error: Unable to write values to CSV file, {}:\n"
"(1) The data table may have 2 or more identical variables. Please correct the LiPD file manually\n"
"(2) There may have been an error trying to prep the values for file write. The 'number' field in the data columns may be a 'string' instead of an 'integer' data type".format(filename))
print(e)
except Exception as e:
print("Error: CSV file not written, {}, {}:\n"
"The data table may have 2 or more identical variables. Please correct the LiPD file manually".format(filename, e))
except AttributeError as e:
logger_csvs.error("write_csv_to_file: Unable to write CSV File: {}".format(e, exc_info=True))
logger_csvs.info("exit write_csv_to_file")
return | [
"def",
"write_csv_to_file",
"(",
"d",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter write_csv_to_file\"",
")",
"try",
":",
"for",
"filename",
",",
"data",
"in",
"d",
".",
"items",
"(",
")",
":",
"try",
":",
"l_columns",
"=",
"_reorder_csv",
"(",
"d... | Writes columns of data to a target CSV file.
:param dict d: A dictionary containing one list for every data column. Keys: int, Values: list
:return None: | [
"Writes",
"columns",
"of",
"data",
"to",
"a",
"target",
"CSV",
"file",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L247-L277 | train | 46,753 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | get_csv_from_metadata | def get_csv_from_metadata(dsn, d):
"""
Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files.
:param str dsn: Dataset name
:param dict d: Metadata
:return dict _csvs: Csv
"""
logger_csvs.info("enter get_csv_from_metadata")
_csvs = OrderedDict()
_d = copy.deepcopy(d)
try:
if "paleoData" in _d:
# Process paleoData section
_d["paleoData"], _csvs = _get_csv_from_section(_d["paleoData"], "{}.paleo".format(dsn), _csvs)
if "chronData" in _d:
_d["chronData"], _csvs = _get_csv_from_section(_d["chronData"], "{}.chron".format(dsn), _csvs)
except Exception as e:
print("Error: get_csv_from_metadata: {}, {}".format(dsn, e))
logger_csvs.error("get_csv_from_metadata: {}, {}".format(dsn, e))
logger_csvs.info("exit get_csv_from_metadata")
return _d, _csvs | python | def get_csv_from_metadata(dsn, d):
"""
Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files.
:param str dsn: Dataset name
:param dict d: Metadata
:return dict _csvs: Csv
"""
logger_csvs.info("enter get_csv_from_metadata")
_csvs = OrderedDict()
_d = copy.deepcopy(d)
try:
if "paleoData" in _d:
# Process paleoData section
_d["paleoData"], _csvs = _get_csv_from_section(_d["paleoData"], "{}.paleo".format(dsn), _csvs)
if "chronData" in _d:
_d["chronData"], _csvs = _get_csv_from_section(_d["chronData"], "{}.chron".format(dsn), _csvs)
except Exception as e:
print("Error: get_csv_from_metadata: {}, {}".format(dsn, e))
logger_csvs.error("get_csv_from_metadata: {}, {}".format(dsn, e))
logger_csvs.info("exit get_csv_from_metadata")
return _d, _csvs | [
"def",
"get_csv_from_metadata",
"(",
"dsn",
",",
"d",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter get_csv_from_metadata\"",
")",
"_csvs",
"=",
"OrderedDict",
"(",
")",
"_d",
"=",
"copy",
".",
"deepcopy",
"(",
"d",
")",
"try",
":",
"if",
"\"paleoDat... | Two goals. Get all csv from metadata, and return new metadata with generated filenames to match files.
:param str dsn: Dataset name
:param dict d: Metadata
:return dict _csvs: Csv | [
"Two",
"goals",
".",
"Get",
"all",
"csv",
"from",
"metadata",
"and",
"return",
"new",
"metadata",
"with",
"generated",
"filenames",
"to",
"match",
"files",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L283-L308 | train | 46,754 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | _get_csv_from_section | def _get_csv_from_section(sections, crumbs, csvs):
"""
Get table name, variable name, and column values from paleo metadata
:param dict sections: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict sections: Metadata
:return dict csvs: Csv
"""
logger_csvs.info("enter get_csv_from_section: {}".format(crumbs))
_idx = 0
try:
# Process the tables in section
for _name, _section in sections.items():
# Process each entry sub-table below if they exist
if "measurementTable" in _section:
sections[_name]["measurementTable"], csvs = _get_csv_from_table(_section["measurementTable"],"{}{}{}".format(crumbs, _idx, "measurement") , csvs)
if "model" in _section:
sections[_name]["model"], csvs = _get_csv_from_model(_section["model"], "{}{}{}".format(crumbs, _idx, "model") , csvs)
_idx += 1
except Exception as e:
logger_csvs.error("get_csv_from_section: {}, {}".format(crumbs, e))
print("Error: get_csv_from_section: {}, {}".format(crumbs, e))
logger_csvs.info("exit get_csv_from_section: {}".format(crumbs))
return sections, csvs | python | def _get_csv_from_section(sections, crumbs, csvs):
"""
Get table name, variable name, and column values from paleo metadata
:param dict sections: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict sections: Metadata
:return dict csvs: Csv
"""
logger_csvs.info("enter get_csv_from_section: {}".format(crumbs))
_idx = 0
try:
# Process the tables in section
for _name, _section in sections.items():
# Process each entry sub-table below if they exist
if "measurementTable" in _section:
sections[_name]["measurementTable"], csvs = _get_csv_from_table(_section["measurementTable"],"{}{}{}".format(crumbs, _idx, "measurement") , csvs)
if "model" in _section:
sections[_name]["model"], csvs = _get_csv_from_model(_section["model"], "{}{}{}".format(crumbs, _idx, "model") , csvs)
_idx += 1
except Exception as e:
logger_csvs.error("get_csv_from_section: {}, {}".format(crumbs, e))
print("Error: get_csv_from_section: {}, {}".format(crumbs, e))
logger_csvs.info("exit get_csv_from_section: {}".format(crumbs))
return sections, csvs | [
"def",
"_get_csv_from_section",
"(",
"sections",
",",
"crumbs",
",",
"csvs",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter get_csv_from_section: {}\"",
".",
"format",
"(",
"crumbs",
")",
")",
"_idx",
"=",
"0",
"try",
":",
"# Process the tables in section",
... | Get table name, variable name, and column values from paleo metadata
:param dict sections: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict sections: Metadata
:return dict csvs: Csv | [
"Get",
"table",
"name",
"variable",
"name",
"and",
"column",
"values",
"from",
"paleo",
"metadata"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L311-L339 | train | 46,755 |
nickmckay/LiPD-utilities | Python/lipd/csvs.py | _get_csv_from_model | def _get_csv_from_model(models, crumbs, csvs):
"""
Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv
"""
logger_csvs.info("enter get_csv_from_model: {}".format(crumbs))
_idx = 0
try:
for _name, _model in models.items():
if "distributionTable" in _model:
models[_name]["distributionTable"], csvs = _get_csv_from_table(_model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"), csvs)
if "summaryTable" in _model:
models[_name]["summaryTable"], csvs = _get_csv_from_table(_model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"), csvs)
if "ensembleTable" in _model:
models[_name]["ensembleTable"], csvs = _get_csv_from_table(_model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"), csvs)
_idx += 1
except Exception as e:
print("Error: get_csv_from_model: {}, {}".format(crumbs, e))
logger_csvs.error("Error: get_csv_from_model: {}, {}".format(crumbs, e))
return models, csvs | python | def _get_csv_from_model(models, crumbs, csvs):
"""
Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv
"""
logger_csvs.info("enter get_csv_from_model: {}".format(crumbs))
_idx = 0
try:
for _name, _model in models.items():
if "distributionTable" in _model:
models[_name]["distributionTable"], csvs = _get_csv_from_table(_model["distributionTable"], "{}{}{}".format(crumbs, _idx, "distribution"), csvs)
if "summaryTable" in _model:
models[_name]["summaryTable"], csvs = _get_csv_from_table(_model["summaryTable"], "{}{}{}".format(crumbs, _idx, "summary"), csvs)
if "ensembleTable" in _model:
models[_name]["ensembleTable"], csvs = _get_csv_from_table(_model["ensembleTable"], "{}{}{}".format(crumbs, _idx, "ensemble"), csvs)
_idx += 1
except Exception as e:
print("Error: get_csv_from_model: {}, {}".format(crumbs, e))
logger_csvs.error("Error: get_csv_from_model: {}, {}".format(crumbs, e))
return models, csvs | [
"def",
"_get_csv_from_model",
"(",
"models",
",",
"crumbs",
",",
"csvs",
")",
":",
"logger_csvs",
".",
"info",
"(",
"\"enter get_csv_from_model: {}\"",
".",
"format",
"(",
"crumbs",
")",
")",
"_idx",
"=",
"0",
"try",
":",
"for",
"_name",
",",
"_model",
"in... | Get csv from model data
:param dict models: Metadata
:param str crumbs: Crumbs
:param dict csvs: Csv
:return dict models: Metadata
:return dict csvs: Csv | [
"Get",
"csv",
"from",
"model",
"data"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/csvs.py#L342-L368 | train | 46,756 |
nickmckay/LiPD-utilities | Python/lipd/validator_api.py | get_validator_format | def get_validator_format(L):
"""
Format the LIPD data in the layout that the Lipd.net validator accepts.
'_format' example:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
:param dict L: Metadata
:return list _api_data: Data formatted for validator API
"""
_api_data = []
_j, _csvs = get_csv_from_metadata(L["dataSetName"], L)
_j = rm_values_fields(copy.deepcopy(L))
_j = idx_name_to_num(_j)
# All the filenames being processed
_filenames = ["metadata.jsonld", "bagit.txt", "bag-info.txt", "manifest-md5.txt", "tagmanifest-md5.txt"]\
+ [k for k,v in _csvs.items()]
# Loop for each filename
for filename in _filenames:
# Create a blank template
_file = {"type": "", "filenameFull": "", "filenameShort": "", "data": "", "pretty": ""}
# filename, no path prefix
# _short = os.path.basename(filename)
_short = filename
# Bagit files
if filename.endswith(".txt"):
_file = {"type": "bagit", "filenameFull": filename, "filenameShort": _short}
# JSONLD files
elif filename.endswith(".jsonld"):
_file = {"type": "json", "filenameFull": filename, "filenameShort": _short, "data": _j}
# CSV files
elif filename.endswith(".csv"):
_cols_rows = {"cols": 0, "rows": 0}
ensemble = is_ensemble(_csvs[_short])
# special case for calculating ensemble rows and columns
if ensemble:
_cols_rows = get_ensemble_counts(_csvs[_short])
# all other non-ensemble csv files.
else:
_cols_rows["cols"] = len(_csvs[_short])
for k, v in _csvs[_short].items():
_cols_rows["rows"] = len(v["values"])
break
# take what we've gathered for this file, and add it to the list.
_file = {"type": "csv", "filenameFull": filename, "filenameShort": _short,
"data": _cols_rows}
_api_data.append(_file)
return _api_data | python | def get_validator_format(L):
"""
Format the LIPD data in the layout that the Lipd.net validator accepts.
'_format' example:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
:param dict L: Metadata
:return list _api_data: Data formatted for validator API
"""
_api_data = []
_j, _csvs = get_csv_from_metadata(L["dataSetName"], L)
_j = rm_values_fields(copy.deepcopy(L))
_j = idx_name_to_num(_j)
# All the filenames being processed
_filenames = ["metadata.jsonld", "bagit.txt", "bag-info.txt", "manifest-md5.txt", "tagmanifest-md5.txt"]\
+ [k for k,v in _csvs.items()]
# Loop for each filename
for filename in _filenames:
# Create a blank template
_file = {"type": "", "filenameFull": "", "filenameShort": "", "data": "", "pretty": ""}
# filename, no path prefix
# _short = os.path.basename(filename)
_short = filename
# Bagit files
if filename.endswith(".txt"):
_file = {"type": "bagit", "filenameFull": filename, "filenameShort": _short}
# JSONLD files
elif filename.endswith(".jsonld"):
_file = {"type": "json", "filenameFull": filename, "filenameShort": _short, "data": _j}
# CSV files
elif filename.endswith(".csv"):
_cols_rows = {"cols": 0, "rows": 0}
ensemble = is_ensemble(_csvs[_short])
# special case for calculating ensemble rows and columns
if ensemble:
_cols_rows = get_ensemble_counts(_csvs[_short])
# all other non-ensemble csv files.
else:
_cols_rows["cols"] = len(_csvs[_short])
for k, v in _csvs[_short].items():
_cols_rows["rows"] = len(v["values"])
break
# take what we've gathered for this file, and add it to the list.
_file = {"type": "csv", "filenameFull": filename, "filenameShort": _short,
"data": _cols_rows}
_api_data.append(_file)
return _api_data | [
"def",
"get_validator_format",
"(",
"L",
")",
":",
"_api_data",
"=",
"[",
"]",
"_j",
",",
"_csvs",
"=",
"get_csv_from_metadata",
"(",
"L",
"[",
"\"dataSetName\"",
"]",
",",
"L",
")",
"_j",
"=",
"rm_values_fields",
"(",
"copy",
".",
"deepcopy",
"(",
"L",
... | Format the LIPD data in the layout that the Lipd.net validator accepts.
'_format' example:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
:param dict L: Metadata
:return list _api_data: Data formatted for validator API | [
"Format",
"the",
"LIPD",
"data",
"in",
"the",
"layout",
"that",
"the",
"Lipd",
".",
"net",
"validator",
"accepts",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/validator_api.py#L14-L73 | train | 46,757 |
nickmckay/LiPD-utilities | Python/lipd/validator_api.py | create_detailed_results | def create_detailed_results(result):
"""
Use the result from the API call to create an organized single string output for printing to the console.
:param dict result: Results from API call for one file
:return str string: Organized results for printing
"""
string = ""
# Validation Response output
# string += "VALIDATION RESPONSE\n"
string += "STATUS: {}\n".format(result["status"])
if result["feedback"]:
string += "WARNINGS: {}\n".format(len(result["feedback"]["wrnMsgs"]))
# Loop through and output the Warnings
for msg in result["feedback"]["wrnMsgs"]:
string += "- {}\n".format(msg)
string += "ERRORS: {}\n".format(len(result["feedback"]["errMsgs"]))
# Loop through and output the Errors
for msg in result["feedback"]["errMsgs"]:
string += "- {}\n".format(msg)
return string | python | def create_detailed_results(result):
"""
Use the result from the API call to create an organized single string output for printing to the console.
:param dict result: Results from API call for one file
:return str string: Organized results for printing
"""
string = ""
# Validation Response output
# string += "VALIDATION RESPONSE\n"
string += "STATUS: {}\n".format(result["status"])
if result["feedback"]:
string += "WARNINGS: {}\n".format(len(result["feedback"]["wrnMsgs"]))
# Loop through and output the Warnings
for msg in result["feedback"]["wrnMsgs"]:
string += "- {}\n".format(msg)
string += "ERRORS: {}\n".format(len(result["feedback"]["errMsgs"]))
# Loop through and output the Errors
for msg in result["feedback"]["errMsgs"]:
string += "- {}\n".format(msg)
return string | [
"def",
"create_detailed_results",
"(",
"result",
")",
":",
"string",
"=",
"\"\"",
"# Validation Response output",
"# string += \"VALIDATION RESPONSE\\n\"",
"string",
"+=",
"\"STATUS: {}\\n\"",
".",
"format",
"(",
"result",
"[",
"\"status\"",
"]",
")",
"if",
"result",
... | Use the result from the API call to create an organized single string output for printing to the console.
:param dict result: Results from API call for one file
:return str string: Organized results for printing | [
"Use",
"the",
"result",
"from",
"the",
"API",
"call",
"to",
"create",
"an",
"organized",
"single",
"string",
"output",
"for",
"printing",
"to",
"the",
"console",
"."
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/validator_api.py#L76-L96 | train | 46,758 |
nickmckay/LiPD-utilities | Python/lipd/validator_api.py | display_results | def display_results(results, detailed=False):
"""
Display the results from the validator in a brief or detailed output
:param list results: API results, sorted by dataset name (multiple)
:param bool detailed: Detailed results on or off
:return none:
"""
# print("\nVALIDATOR RESULTS")
# print("======================\n")
if not detailed:
print('FILENAME......................................... STATUS..........')
for entry in results:
try:
if detailed:
print("\n{}".format(entry["filename"]))
print(create_detailed_results(entry))
else:
print("{:<50}{}".format(entry["filename"], entry["status"]))
except Exception as e:
logger_validator_api.debug("display_results: Exception: {}".format(e))
print("Error: display_results: {}".format(e))
return | python | def display_results(results, detailed=False):
"""
Display the results from the validator in a brief or detailed output
:param list results: API results, sorted by dataset name (multiple)
:param bool detailed: Detailed results on or off
:return none:
"""
# print("\nVALIDATOR RESULTS")
# print("======================\n")
if not detailed:
print('FILENAME......................................... STATUS..........')
for entry in results:
try:
if detailed:
print("\n{}".format(entry["filename"]))
print(create_detailed_results(entry))
else:
print("{:<50}{}".format(entry["filename"], entry["status"]))
except Exception as e:
logger_validator_api.debug("display_results: Exception: {}".format(e))
print("Error: display_results: {}".format(e))
return | [
"def",
"display_results",
"(",
"results",
",",
"detailed",
"=",
"False",
")",
":",
"# print(\"\\nVALIDATOR RESULTS\")",
"# print(\"======================\\n\")",
"if",
"not",
"detailed",
":",
"print",
"(",
"'FILENAME......................................... STATUS..........'",
... | Display the results from the validator in a brief or detailed output
:param list results: API results, sorted by dataset name (multiple)
:param bool detailed: Detailed results on or off
:return none: | [
"Display",
"the",
"results",
"from",
"the",
"validator",
"in",
"a",
"brief",
"or",
"detailed",
"output"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/validator_api.py#L99-L124 | train | 46,759 |
nickmckay/LiPD-utilities | Python/lipd/validator_api.py | call_validator_api | def call_validator_api(dsn, api_data):
"""
Single call to the lipd.net validator API
'api_data' format:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
Result format:
{"dat": <dict>, "feedback": <dict>, "filename": "", "status": ""}
:param str dsn: Dataset name
:param list api_data: Prepared payload for one LiPD dataset. All the sorted files (txt, jsonld, csv), API formatted
:return list result: Validator result for one file
"""
_filename = dsn + ".lpd"
try:
# Contact server and send LiPD metadata as the payload
# print("Sending request to LiPD.net validator...\n")
api_data = json.dumps(api_data)
# The payload that is going to be sent with the JSON request
payload = {'json_payload': api_data, 'apikey': 'lipd_linked'}
# Development Link
# response = requests.post('http://localhost:3000/api/validator', data=payload)
# Production Link
response = requests.post('http://www.lipd.net/api/validator', data=payload)
if response.status_code == 413:
result = {"dat": {}, "feedback": {}, "filename": _filename,
"status": "HTTP 413: Request Entity Too Large"}
elif response.status_code == 404:
result = {"dat": {}, "feedback": {}, "filename": _filename,
"status": "HTTP 404: Not Found"}
elif response.status_code == 400:
result = {"dat": {}, "feedback": {}, "filename": _filename,
"status": response.text}
# For an example of the JSON Response, reference the "sample_data_response" below
# Convert JSON string into a Python dictionary
# print("Converting response to json...\n")
else:
result = json.loads(response.text)
except TypeError as e:
logger_validator_api.warning("get_validator_results: TypeError: {}".format(e))
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "JSON DECODE ERROR"}
except requests.exceptions.ConnectionError as e:
logger_validator_api.warning("get_validator_results: ConnectionError: {}".format(e))
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "UNABLE TO REACH SERVER"}
except Exception as e:
logger_validator_api.debug("get_validator_results: Exception: {}".format(e))
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "ERROR BEFORE VALIDATION, {}".format(e)}
if not result:
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "EMPTY RESPONSE"}
result["filename"] = _filename
return result | python | def call_validator_api(dsn, api_data):
"""
Single call to the lipd.net validator API
'api_data' format:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
Result format:
{"dat": <dict>, "feedback": <dict>, "filename": "", "status": ""}
:param str dsn: Dataset name
:param list api_data: Prepared payload for one LiPD dataset. All the sorted files (txt, jsonld, csv), API formatted
:return list result: Validator result for one file
"""
_filename = dsn + ".lpd"
try:
# Contact server and send LiPD metadata as the payload
# print("Sending request to LiPD.net validator...\n")
api_data = json.dumps(api_data)
# The payload that is going to be sent with the JSON request
payload = {'json_payload': api_data, 'apikey': 'lipd_linked'}
# Development Link
# response = requests.post('http://localhost:3000/api/validator', data=payload)
# Production Link
response = requests.post('http://www.lipd.net/api/validator', data=payload)
if response.status_code == 413:
result = {"dat": {}, "feedback": {}, "filename": _filename,
"status": "HTTP 413: Request Entity Too Large"}
elif response.status_code == 404:
result = {"dat": {}, "feedback": {}, "filename": _filename,
"status": "HTTP 404: Not Found"}
elif response.status_code == 400:
result = {"dat": {}, "feedback": {}, "filename": _filename,
"status": response.text}
# For an example of the JSON Response, reference the "sample_data_response" below
# Convert JSON string into a Python dictionary
# print("Converting response to json...\n")
else:
result = json.loads(response.text)
except TypeError as e:
logger_validator_api.warning("get_validator_results: TypeError: {}".format(e))
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "JSON DECODE ERROR"}
except requests.exceptions.ConnectionError as e:
logger_validator_api.warning("get_validator_results: ConnectionError: {}".format(e))
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "UNABLE TO REACH SERVER"}
except Exception as e:
logger_validator_api.debug("get_validator_results: Exception: {}".format(e))
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "ERROR BEFORE VALIDATION, {}".format(e)}
if not result:
result = {"dat": {}, "feedback": {}, "filename": _filename, "status": "EMPTY RESPONSE"}
result["filename"] = _filename
return result | [
"def",
"call_validator_api",
"(",
"dsn",
",",
"api_data",
")",
":",
"_filename",
"=",
"dsn",
"+",
"\".lpd\"",
"try",
":",
"# Contact server and send LiPD metadata as the payload",
"# print(\"Sending request to LiPD.net validator...\\n\")",
"api_data",
"=",
"json",
".",
"dum... | Single call to the lipd.net validator API
'api_data' format:
[
{"type": "csv", "filenameFull": /path/to/filename.csv, "data": "", ...},
{"type": "json", "filenameFull": /path/to/metadata.jsonld, "data": "", ...},
...
]
Result format:
{"dat": <dict>, "feedback": <dict>, "filename": "", "status": ""}
:param str dsn: Dataset name
:param list api_data: Prepared payload for one LiPD dataset. All the sorted files (txt, jsonld, csv), API formatted
:return list result: Validator result for one file | [
"Single",
"call",
"to",
"the",
"lipd",
".",
"net",
"validator",
"API"
] | 5dab6bbeffc5effd68e3a6beaca6b76aa928e860 | https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/validator_api.py#L127-L190 | train | 46,760 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/filter_common.py | procces_filters | def procces_filters(all_needs, current_needlist):
"""
Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters
"""
if current_needlist["sort_by"] is not None:
if current_needlist["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needlist["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs_by_options = []
# Add all need_parts of given needs to the search list
all_needs_incl_parts = prepare_need_list(all_needs)
for need_info in all_needs_incl_parts:
status_filter_passed = False
if current_needlist["status"] is None or len(current_needlist["status"]) == 0:
# Filtering for status was not requested
status_filter_passed = True
elif need_info["status"] is not None and need_info["status"] in current_needlist["status"]:
# Match was found
status_filter_passed = True
tags_filter_passed = False
if len(set(need_info["tags"]) & set(current_needlist["tags"])) > 0 or len(current_needlist["tags"]) == 0:
tags_filter_passed = True
type_filter_passed = False
if need_info["type"] in current_needlist["types"] \
or need_info["type_name"] in current_needlist["types"] \
or len(current_needlist["types"]) == 0:
type_filter_passed = True
if status_filter_passed and tags_filter_passed and type_filter_passed:
found_needs_by_options.append(need_info)
found_needs_by_string = filter_needs(all_needs_incl_parts, current_needlist["filter"])
# found_needs = [x for x in found_needs_by_string if x in found_needs_by_options]
found_needs = check_need_list(found_needs_by_options, found_needs_by_string)
return found_needs | python | def procces_filters(all_needs, current_needlist):
"""
Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters
"""
if current_needlist["sort_by"] is not None:
if current_needlist["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needlist["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs_by_options = []
# Add all need_parts of given needs to the search list
all_needs_incl_parts = prepare_need_list(all_needs)
for need_info in all_needs_incl_parts:
status_filter_passed = False
if current_needlist["status"] is None or len(current_needlist["status"]) == 0:
# Filtering for status was not requested
status_filter_passed = True
elif need_info["status"] is not None and need_info["status"] in current_needlist["status"]:
# Match was found
status_filter_passed = True
tags_filter_passed = False
if len(set(need_info["tags"]) & set(current_needlist["tags"])) > 0 or len(current_needlist["tags"]) == 0:
tags_filter_passed = True
type_filter_passed = False
if need_info["type"] in current_needlist["types"] \
or need_info["type_name"] in current_needlist["types"] \
or len(current_needlist["types"]) == 0:
type_filter_passed = True
if status_filter_passed and tags_filter_passed and type_filter_passed:
found_needs_by_options.append(need_info)
found_needs_by_string = filter_needs(all_needs_incl_parts, current_needlist["filter"])
# found_needs = [x for x in found_needs_by_string if x in found_needs_by_options]
found_needs = check_need_list(found_needs_by_options, found_needs_by_string)
return found_needs | [
"def",
"procces_filters",
"(",
"all_needs",
",",
"current_needlist",
")",
":",
"if",
"current_needlist",
"[",
"\"sort_by\"",
"]",
"is",
"not",
"None",
":",
"if",
"current_needlist",
"[",
"\"sort_by\"",
"]",
"==",
"\"id\"",
":",
"all_needs",
"=",
"sorted",
"(",... | Filters all needs with given configuration
:param current_needlist: needlist object, which stores all filters
:param all_needs: List of all needs inside document
:return: list of needs, which passed the filters | [
"Filters",
"all",
"needs",
"with",
"given",
"configuration"
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/filter_common.py#L68-L117 | train | 46,761 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/filter_common.py | filter_needs | def filter_needs(needs, filter_string="", filter_parts=True, merge_part_with_parent=True):
"""
Filters given needs based on a given filter string.
Returns all needs, which pass the given filter.
:param merge_part_with_parent: If True, need_parts inherit options from their parent need
:param filter_parts: If True, need_parts get also filtered
:param filter_string: strings, which gets evaluated against each need
:param needs: list of needs, which shall be filtered
:return:
"""
if filter_string is None or filter_string == "":
return needs
found_needs = []
for filter_need in needs:
try:
if filter_single_need(filter_need, filter_string):
found_needs.append(filter_need)
except Exception as e:
logger.warning("Filter {0} not valid: Error: {1}".format(filter_string, e))
return found_needs | python | def filter_needs(needs, filter_string="", filter_parts=True, merge_part_with_parent=True):
"""
Filters given needs based on a given filter string.
Returns all needs, which pass the given filter.
:param merge_part_with_parent: If True, need_parts inherit options from their parent need
:param filter_parts: If True, need_parts get also filtered
:param filter_string: strings, which gets evaluated against each need
:param needs: list of needs, which shall be filtered
:return:
"""
if filter_string is None or filter_string == "":
return needs
found_needs = []
for filter_need in needs:
try:
if filter_single_need(filter_need, filter_string):
found_needs.append(filter_need)
except Exception as e:
logger.warning("Filter {0} not valid: Error: {1}".format(filter_string, e))
return found_needs | [
"def",
"filter_needs",
"(",
"needs",
",",
"filter_string",
"=",
"\"\"",
",",
"filter_parts",
"=",
"True",
",",
"merge_part_with_parent",
"=",
"True",
")",
":",
"if",
"filter_string",
"is",
"None",
"or",
"filter_string",
"==",
"\"\"",
":",
"return",
"needs",
... | Filters given needs based on a given filter string.
Returns all needs, which pass the given filter.
:param merge_part_with_parent: If True, need_parts inherit options from their parent need
:param filter_parts: If True, need_parts get also filtered
:param filter_string: strings, which gets evaluated against each need
:param needs: list of needs, which shall be filtered
:return: | [
"Filters",
"given",
"needs",
"based",
"on",
"a",
"given",
"filter",
"string",
".",
"Returns",
"all",
"needs",
"which",
"pass",
"the",
"given",
"filter",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/filter_common.py#L160-L184 | train | 46,762 |
sijis/sumologic-python | src/sumologic/utils.py | get_logging_level | def get_logging_level(debug):
"""Returns logging level based on boolean"""
level = logging.INFO
if debug:
level = logging.DEBUG
return level | python | def get_logging_level(debug):
"""Returns logging level based on boolean"""
level = logging.INFO
if debug:
level = logging.DEBUG
return level | [
"def",
"get_logging_level",
"(",
"debug",
")",
":",
"level",
"=",
"logging",
".",
"INFO",
"if",
"debug",
":",
"level",
"=",
"logging",
".",
"DEBUG",
"return",
"level"
] | Returns logging level based on boolean | [
"Returns",
"logging",
"level",
"based",
"on",
"boolean"
] | b50200907837f0d452d14ead5e647b8e24e2e9e5 | https://github.com/sijis/sumologic-python/blob/b50200907837f0d452d14ead5e647b8e24e2e9e5/src/sumologic/utils.py#L4-L9 | train | 46,763 |
mfussenegger/cr8 | cr8/run_spec.py | run_spec | def run_spec(spec,
benchmark_hosts,
result_hosts=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
action=None,
fail_if=None,
sample_mode='reservoir'):
"""Run a spec file, executing the statements on the benchmark_hosts.
Short example of a spec file:
[setup]
statement_files = ["sql/create_table.sql"]
[[setup.data_files]]
target = "t"
source = "data/t.json"
[[queries]]
statement = "select count(*) from t"
iterations = 2000
concurrency = 10
[teardown]
statements = ["drop table t"]
See https://github.com/mfussenegger/cr8/tree/master/specs
for more examples.
Args:
spec: path to a spec file
benchmark_hosts: hostname[:port] pairs of Crate nodes
result_hosts: optional hostname[:port] Crate node pairs into which the
runtime statistics should be inserted.
output_fmt: output format
action: Optional action to execute.
Default is to execute all actions - setup, queries and teardown.
If present only the specified action will be executed.
The argument can be provided multiple times to execute more than
one action.
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
- meta
- concurrency
- bulk_size
For example:
--fail-if "{runtime_stats.mean} > 1.34"
"""
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
do_run_spec(
spec=spec,
benchmark_hosts=benchmark_hosts,
log=log,
result_hosts=result_hosts,
action=action,
fail_if=fail_if,
sample_mode=sample_mode
) | python | def run_spec(spec,
benchmark_hosts,
result_hosts=None,
output_fmt=None,
logfile_info=None,
logfile_result=None,
action=None,
fail_if=None,
sample_mode='reservoir'):
"""Run a spec file, executing the statements on the benchmark_hosts.
Short example of a spec file:
[setup]
statement_files = ["sql/create_table.sql"]
[[setup.data_files]]
target = "t"
source = "data/t.json"
[[queries]]
statement = "select count(*) from t"
iterations = 2000
concurrency = 10
[teardown]
statements = ["drop table t"]
See https://github.com/mfussenegger/cr8/tree/master/specs
for more examples.
Args:
spec: path to a spec file
benchmark_hosts: hostname[:port] pairs of Crate nodes
result_hosts: optional hostname[:port] Crate node pairs into which the
runtime statistics should be inserted.
output_fmt: output format
action: Optional action to execute.
Default is to execute all actions - setup, queries and teardown.
If present only the specified action will be executed.
The argument can be provided multiple times to execute more than
one action.
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
- meta
- concurrency
- bulk_size
For example:
--fail-if "{runtime_stats.mean} > 1.34"
"""
with Logger(output_fmt=output_fmt,
logfile_info=logfile_info,
logfile_result=logfile_result) as log:
do_run_spec(
spec=spec,
benchmark_hosts=benchmark_hosts,
log=log,
result_hosts=result_hosts,
action=action,
fail_if=fail_if,
sample_mode=sample_mode
) | [
"def",
"run_spec",
"(",
"spec",
",",
"benchmark_hosts",
",",
"result_hosts",
"=",
"None",
",",
"output_fmt",
"=",
"None",
",",
"logfile_info",
"=",
"None",
",",
"logfile_result",
"=",
"None",
",",
"action",
"=",
"None",
",",
"fail_if",
"=",
"None",
",",
... | Run a spec file, executing the statements on the benchmark_hosts.
Short example of a spec file:
[setup]
statement_files = ["sql/create_table.sql"]
[[setup.data_files]]
target = "t"
source = "data/t.json"
[[queries]]
statement = "select count(*) from t"
iterations = 2000
concurrency = 10
[teardown]
statements = ["drop table t"]
See https://github.com/mfussenegger/cr8/tree/master/specs
for more examples.
Args:
spec: path to a spec file
benchmark_hosts: hostname[:port] pairs of Crate nodes
result_hosts: optional hostname[:port] Crate node pairs into which the
runtime statistics should be inserted.
output_fmt: output format
action: Optional action to execute.
Default is to execute all actions - setup, queries and teardown.
If present only the specified action will be executed.
The argument can be provided multiple times to execute more than
one action.
fail-if: An expression that causes cr8 to exit with a failure if it
evaluates to true.
The expression can contain formatting expressions for:
- runtime_stats
- statement
- meta
- concurrency
- bulk_size
For example:
--fail-if "{runtime_stats.mean} > 1.34" | [
"Run",
"a",
"spec",
"file",
"executing",
"the",
"statements",
"on",
"the",
"benchmark_hosts",
"."
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/run_spec.py#L240-L304 | train | 46,764 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | get_sections | def get_sections(need_info):
"""Gets the hierarchy of the section nodes as a list starting at the
section of the current need and then its parent sections"""
sections = []
current_node = need_info['target_node']
while current_node:
if isinstance(current_node, nodes.section):
title = current_node.children[0].astext()
# If using auto-section numbering, then Sphinx inserts
# multiple non-breaking space unicode characters into the title
# we'll replace those with a simple space to make them easier to
# use in filters
title = NON_BREAKING_SPACE.sub(' ', title)
sections.append(title)
current_node = getattr(current_node, 'parent', None)
return sections | python | def get_sections(need_info):
"""Gets the hierarchy of the section nodes as a list starting at the
section of the current need and then its parent sections"""
sections = []
current_node = need_info['target_node']
while current_node:
if isinstance(current_node, nodes.section):
title = current_node.children[0].astext()
# If using auto-section numbering, then Sphinx inserts
# multiple non-breaking space unicode characters into the title
# we'll replace those with a simple space to make them easier to
# use in filters
title = NON_BREAKING_SPACE.sub(' ', title)
sections.append(title)
current_node = getattr(current_node, 'parent', None)
return sections | [
"def",
"get_sections",
"(",
"need_info",
")",
":",
"sections",
"=",
"[",
"]",
"current_node",
"=",
"need_info",
"[",
"'target_node'",
"]",
"while",
"current_node",
":",
"if",
"isinstance",
"(",
"current_node",
",",
"nodes",
".",
"section",
")",
":",
"title",... | Gets the hierarchy of the section nodes as a list starting at the
section of the current need and then its parent sections | [
"Gets",
"the",
"hierarchy",
"of",
"the",
"section",
"nodes",
"as",
"a",
"list",
"starting",
"at",
"the",
"section",
"of",
"the",
"current",
"need",
"and",
"then",
"its",
"parent",
"sections"
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L350-L365 | train | 46,765 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | add_sections | def add_sections(app, doctree, fromdocname):
"""Add section titles to the needs as additional attributes that can
be used in tables and filters"""
needs = getattr(app.builder.env, 'needs_all_needs', {})
for key, need_info in needs.items():
sections = get_sections(need_info)
need_info['sections'] = sections
need_info['section_name'] = sections[0] if sections else "" | python | def add_sections(app, doctree, fromdocname):
"""Add section titles to the needs as additional attributes that can
be used in tables and filters"""
needs = getattr(app.builder.env, 'needs_all_needs', {})
for key, need_info in needs.items():
sections = get_sections(need_info)
need_info['sections'] = sections
need_info['section_name'] = sections[0] if sections else "" | [
"def",
"add_sections",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"needs",
"=",
"getattr",
"(",
"app",
".",
"builder",
".",
"env",
",",
"'needs_all_needs'",
",",
"{",
"}",
")",
"for",
"key",
",",
"need_info",
"in",
"needs",
".",
"items",... | Add section titles to the needs as additional attributes that can
be used in tables and filters | [
"Add",
"section",
"titles",
"to",
"the",
"needs",
"as",
"additional",
"attributes",
"that",
"can",
"be",
"used",
"in",
"tables",
"and",
"filters"
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L378-L385 | train | 46,766 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | create_back_links | def create_back_links(env):
"""
Create back-links in all found needs.
But do this only once, as all needs are already collected and this sorting is for all
needs and not only for the ones of the current document.
:param env: sphinx enviroment
:return: None
"""
if env.needs_workflow['backlink_creation']:
return
needs = env.needs_all_needs
for key, need in needs.items():
for link in need["links"]:
link_main = link.split('.')[0]
try:
link_part = link.split('.')[1]
except IndexError:
link_part = None
if link_main in needs:
if key not in needs[link_main]["links_back"]:
needs[link_main]["links_back"].append(key)
# Handling of links to need_parts inside a need
if link_part is not None:
if link_part in needs[link_main]['parts']:
if 'links_back' not in needs[link_main]['parts'][link_part].keys():
needs[link_main]['parts'][link_part]['links_back'] = []
needs[link_main]['parts'][link_part]['links_back'].append(key)
env.needs_workflow['backlink_creation'] = True | python | def create_back_links(env):
"""
Create back-links in all found needs.
But do this only once, as all needs are already collected and this sorting is for all
needs and not only for the ones of the current document.
:param env: sphinx enviroment
:return: None
"""
if env.needs_workflow['backlink_creation']:
return
needs = env.needs_all_needs
for key, need in needs.items():
for link in need["links"]:
link_main = link.split('.')[0]
try:
link_part = link.split('.')[1]
except IndexError:
link_part = None
if link_main in needs:
if key not in needs[link_main]["links_back"]:
needs[link_main]["links_back"].append(key)
# Handling of links to need_parts inside a need
if link_part is not None:
if link_part in needs[link_main]['parts']:
if 'links_back' not in needs[link_main]['parts'][link_part].keys():
needs[link_main]['parts'][link_part]['links_back'] = []
needs[link_main]['parts'][link_part]['links_back'].append(key)
env.needs_workflow['backlink_creation'] = True | [
"def",
"create_back_links",
"(",
"env",
")",
":",
"if",
"env",
".",
"needs_workflow",
"[",
"'backlink_creation'",
"]",
":",
"return",
"needs",
"=",
"env",
".",
"needs_all_needs",
"for",
"key",
",",
"need",
"in",
"needs",
".",
"items",
"(",
")",
":",
"for... | Create back-links in all found needs.
But do this only once, as all needs are already collected and this sorting is for all
needs and not only for the ones of the current document.
:param env: sphinx enviroment
:return: None | [
"Create",
"back",
"-",
"links",
"in",
"all",
"found",
"needs",
".",
"But",
"do",
"this",
"only",
"once",
"as",
"all",
"needs",
"are",
"already",
"collected",
"and",
"this",
"sorting",
"is",
"for",
"all",
"needs",
"and",
"not",
"only",
"for",
"the",
"on... | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L444-L476 | train | 46,767 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | _fix_list_dyn_func | def _fix_list_dyn_func(list):
"""
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function fixes the above list to the following:
#. link_a
#. [[copy('links', need_id)]]
:param list: list which may contain splitted function calls
:return: list of fixed elements
"""
open_func_string = False
new_list = []
for element in list:
if '[[' in element:
open_func_string = True
new_link = [element]
elif ']]' in element:
new_link.append(element)
open_func_string = False
element = ",".join(new_link)
new_list.append(element)
elif open_func_string:
new_link.append(element)
else:
new_list.append(element)
return new_list | python | def _fix_list_dyn_func(list):
"""
This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function fixes the above list to the following:
#. link_a
#. [[copy('links', need_id)]]
:param list: list which may contain splitted function calls
:return: list of fixed elements
"""
open_func_string = False
new_list = []
for element in list:
if '[[' in element:
open_func_string = True
new_link = [element]
elif ']]' in element:
new_link.append(element)
open_func_string = False
element = ",".join(new_link)
new_list.append(element)
elif open_func_string:
new_link.append(element)
else:
new_list.append(element)
return new_list | [
"def",
"_fix_list_dyn_func",
"(",
"list",
")",
":",
"open_func_string",
"=",
"False",
"new_list",
"=",
"[",
"]",
"for",
"element",
"in",
"list",
":",
"if",
"'[['",
"in",
"element",
":",
"open_func_string",
"=",
"True",
"new_link",
"=",
"[",
"element",
"]",... | This searches a list for dynamic function fragments, which may have been cut by generic searches for ",|;".
Example:
`link_a, [[copy('links', need_id)]]` this will be splitted in list of 3 parts:
#. link_a
#. [[copy('links'
#. need_id)]]
This function fixes the above list to the following:
#. link_a
#. [[copy('links', need_id)]]
:param list: list which may contain splitted function calls
:return: list of fixed elements | [
"This",
"searches",
"a",
"list",
"for",
"dynamic",
"function",
"fragments",
"which",
"may",
"have",
"been",
"cut",
"by",
"generic",
"searches",
"for",
"|",
";",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L617-L651 | train | 46,768 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective.merge_extra_options | def merge_extra_options(self, needs_info):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extra options with empty value to need_info.
# Needed for filters, which need to access these empty/not used options.
for key in self.option_spec:
if key not in needs_info.keys():
needs_info[key] = ""
return extra_keys | python | def merge_extra_options(self, needs_info):
"""Add any extra options introduced via options_ext to needs_info"""
extra_keys = set(self.options.keys()).difference(set(needs_info.keys()))
for key in extra_keys:
needs_info[key] = self.options[key]
# Finally add all not used extra options with empty value to need_info.
# Needed for filters, which need to access these empty/not used options.
for key in self.option_spec:
if key not in needs_info.keys():
needs_info[key] = ""
return extra_keys | [
"def",
"merge_extra_options",
"(",
"self",
",",
"needs_info",
")",
":",
"extra_keys",
"=",
"set",
"(",
"self",
".",
"options",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"set",
"(",
"needs_info",
".",
"keys",
"(",
")",
")",
")",
"for",
"key"... | Add any extra options introduced via options_ext to needs_info | [
"Add",
"any",
"extra",
"options",
"introduced",
"via",
"options_ext",
"to",
"needs_info"
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L299-L311 | train | 46,769 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/need.py | NeedDirective.merge_global_options | def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already exists in needs_info, this global_option got overwritten manually in current need
if key in needs_info.keys():
continue
needs_info[key] = value | python | def merge_global_options(self, needs_info):
"""Add all global defined options to needs_info"""
global_options = getattr(self.env.app.config, 'needs_global_options', None)
if global_options is None:
return
for key, value in global_options.items():
# If key already exists in needs_info, this global_option got overwritten manually in current need
if key in needs_info.keys():
continue
needs_info[key] = value | [
"def",
"merge_global_options",
"(",
"self",
",",
"needs_info",
")",
":",
"global_options",
"=",
"getattr",
"(",
"self",
".",
"env",
".",
"app",
".",
"config",
",",
"'needs_global_options'",
",",
"None",
")",
"if",
"global_options",
"is",
"None",
":",
"return... | Add all global defined options to needs_info | [
"Add",
"all",
"global",
"defined",
"options",
"to",
"needs_info"
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/need.py#L313-L324 | train | 46,770 |
useblocks/sphinxcontrib-needs | sphinxcontrib/needs/directives/needlist.py | process_needlist | def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
# Ok, this is really dirty.
# If we replace a node, docutils checks, if it will not lose any attributes.
# But this is here the case, because we are using the attribute "ids" of a node.
# However, I do not understand, why losing an attribute is such a big deal, so we delete everything
# before docutils claims about it.
for att in ('ids', 'names', 'classes', 'dupnames'):
node[att] = []
node.replace_self([])
continue
id = node.attributes["ids"][0]
current_needfilter = env.need_all_needlists[id]
all_needs = env.needs_all_needs
content = []
all_needs = list(all_needs.values())
if current_needfilter["sort_by"] is not None:
if current_needfilter["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needfilter["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs = procces_filters(all_needs, current_needfilter)
line_block = nodes.line_block()
for need_info in found_needs:
para = nodes.line()
description = "%s: %s" % (need_info["id"], need_info["title"])
if current_needfilter["show_status"] and need_info["status"] is not None:
description += " (%s)" % need_info["status"]
if current_needfilter["show_tags"] and need_info["tags"] is not None:
description += " [%s]" % "; ".join(need_info["tags"])
title = nodes.Text(description, description)
# Create a reference
if not need_info["hide"]:
ref = nodes.reference('', '')
ref['refdocname'] = need_info['docname']
ref['refuri'] = app.builder.get_relative_uri(
fromdocname, need_info['docname'])
ref['refuri'] += '#' + need_info['target_node']['refid']
ref.append(title)
para += ref
else:
para += title
line_block.append(para)
content.append(line_block)
if len(content) == 0:
content.append(no_needs_found_paragraph())
if current_needfilter["show_filters"]:
content.append(used_filter_paragraph(current_needfilter))
node.replace_self(content) | python | def process_needlist(app, doctree, fromdocname):
"""
Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location.
"""
env = app.builder.env
for node in doctree.traverse(Needlist):
if not app.config.needs_include_needs:
# Ok, this is really dirty.
# If we replace a node, docutils checks, if it will not lose any attributes.
# But this is here the case, because we are using the attribute "ids" of a node.
# However, I do not understand, why losing an attribute is such a big deal, so we delete everything
# before docutils claims about it.
for att in ('ids', 'names', 'classes', 'dupnames'):
node[att] = []
node.replace_self([])
continue
id = node.attributes["ids"][0]
current_needfilter = env.need_all_needlists[id]
all_needs = env.needs_all_needs
content = []
all_needs = list(all_needs.values())
if current_needfilter["sort_by"] is not None:
if current_needfilter["sort_by"] == "id":
all_needs = sorted(all_needs, key=lambda node: node["id"])
elif current_needfilter["sort_by"] == "status":
all_needs = sorted(all_needs, key=status_sorter)
found_needs = procces_filters(all_needs, current_needfilter)
line_block = nodes.line_block()
for need_info in found_needs:
para = nodes.line()
description = "%s: %s" % (need_info["id"], need_info["title"])
if current_needfilter["show_status"] and need_info["status"] is not None:
description += " (%s)" % need_info["status"]
if current_needfilter["show_tags"] and need_info["tags"] is not None:
description += " [%s]" % "; ".join(need_info["tags"])
title = nodes.Text(description, description)
# Create a reference
if not need_info["hide"]:
ref = nodes.reference('', '')
ref['refdocname'] = need_info['docname']
ref['refuri'] = app.builder.get_relative_uri(
fromdocname, need_info['docname'])
ref['refuri'] += '#' + need_info['target_node']['refid']
ref.append(title)
para += ref
else:
para += title
line_block.append(para)
content.append(line_block)
if len(content) == 0:
content.append(no_needs_found_paragraph())
if current_needfilter["show_filters"]:
content.append(used_filter_paragraph(current_needfilter))
node.replace_self(content) | [
"def",
"process_needlist",
"(",
"app",
",",
"doctree",
",",
"fromdocname",
")",
":",
"env",
"=",
"app",
".",
"builder",
".",
"env",
"for",
"node",
"in",
"doctree",
".",
"traverse",
"(",
"Needlist",
")",
":",
"if",
"not",
"app",
".",
"config",
".",
"n... | Replace all needlist nodes with a list of the collected needs.
Augment each need with a backlink to the original location. | [
"Replace",
"all",
"needlist",
"nodes",
"with",
"a",
"list",
"of",
"the",
"collected",
"needs",
".",
"Augment",
"each",
"need",
"with",
"a",
"backlink",
"to",
"the",
"original",
"location",
"."
] | f49af4859a74e9fe76de5b9133c01335ac6ae191 | https://github.com/useblocks/sphinxcontrib-needs/blob/f49af4859a74e9fe76de5b9133c01335ac6ae191/sphinxcontrib/needs/directives/needlist.py#L69-L135 | train | 46,771 |
mfussenegger/cr8 | cr8/misc.py | get_lines | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line | python | def get_lines(filename: str) -> Iterator[str]:
"""Create an iterator that returns the lines of a utf-8 encoded file."""
if filename.endswith('.gz'):
with gzip.open(filename, 'r') as f:
for line in f:
yield line.decode('utf-8')
else:
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
yield line | [
"def",
"get_lines",
"(",
"filename",
":",
"str",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"if",
"filename",
".",
"endswith",
"(",
"'.gz'",
")",
":",
"with",
"gzip",
".",
"open",
"(",
"filename",
",",
"'r'",
")",
"as",
"f",
":",
"for",
"line",
... | Create an iterator that returns the lines of a utf-8 encoded file. | [
"Create",
"an",
"iterator",
"that",
"returns",
"the",
"lines",
"of",
"a",
"utf",
"-",
"8",
"encoded",
"file",
"."
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L87-L96 | train | 46,772 |
mfussenegger/cr8 | cr8/misc.py | as_statements | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))
['a', 'b c', 'd']
"""
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield ' '.join(parts)
parts.clear()
if parts:
yield ' '.join(parts) | python | def as_statements(lines: Iterator[str]) -> Iterator[str]:
"""Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))
['a', 'b c', 'd']
"""
lines = (l.strip() for l in lines if l)
lines = (l for l in lines if l and not l.startswith('--'))
parts = []
for line in lines:
parts.append(line.rstrip(';'))
if line.endswith(';'):
yield ' '.join(parts)
parts.clear()
if parts:
yield ' '.join(parts) | [
"def",
"as_statements",
"(",
"lines",
":",
"Iterator",
"[",
"str",
"]",
")",
"->",
"Iterator",
"[",
"str",
"]",
":",
"lines",
"=",
"(",
"l",
".",
"strip",
"(",
")",
"for",
"l",
"in",
"lines",
"if",
"l",
")",
"lines",
"=",
"(",
"l",
"for",
"l",
... | Create an iterator that transforms lines into sql statements.
Statements within the lines must end with ";"
The last statement will be included even if it does not end in ';'
>>> list(as_statements(['select * from', '-- comments are filtered', 't;']))
['select * from t']
>>> list(as_statements(['a;', 'b', 'c;', 'd', ' ']))
['a', 'b c', 'd'] | [
"Create",
"an",
"iterator",
"that",
"transforms",
"lines",
"into",
"sql",
"statements",
"."
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L99-L120 | train | 46,773 |
mfussenegger/cr8 | cr8/misc.py | break_iterable | def break_iterable(iterable, pred):
"""Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]]
"""
sublist = []
for i in iterable:
if pred(i):
yield sublist
sublist = []
else:
sublist.append(i)
yield sublist | python | def break_iterable(iterable, pred):
"""Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]]
"""
sublist = []
for i in iterable:
if pred(i):
yield sublist
sublist = []
else:
sublist.append(i)
yield sublist | [
"def",
"break_iterable",
"(",
"iterable",
",",
"pred",
")",
":",
"sublist",
"=",
"[",
"]",
"for",
"i",
"in",
"iterable",
":",
"if",
"pred",
"(",
"i",
")",
":",
"yield",
"sublist",
"sublist",
"=",
"[",
"]",
"else",
":",
"sublist",
".",
"append",
"("... | Break a iterable on the item that matches the predicate into lists.
The item that matched the predicate is not included in the result.
>>> list(break_iterable([1, 2, 3, 4], lambda x: x == 3))
[[1, 2], [4]] | [
"Break",
"a",
"iterable",
"on",
"the",
"item",
"that",
"matches",
"the",
"predicate",
"into",
"lists",
"."
] | a37d6049f1f9fee2d0556efae2b7b7f8761bffe8 | https://github.com/mfussenegger/cr8/blob/a37d6049f1f9fee2d0556efae2b7b7f8761bffe8/cr8/misc.py#L123-L138 | train | 46,774 |
audiolion/django-language-field | languages/regenerate.py | regenerate | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-type' in data.headers and
'charset=' in data.headers['content-type']):
encoding = data.headers['content-type'].split('charset=')[-1]
else:
encoding = default_encoding
content = data.read().decode(encoding)
languages = []
info = {}
p = None
for line in content.splitlines():
if line == '%%':
if 'Type' in info and info['Type'] == 'language':
languages.append(info)
info = {}
elif ':' not in line and p:
info[p[0]] = paren.sub('', p[2]+line).strip()
else:
p = line.partition(':')
if not p[0] in info: # Keep the first description as it should be the most common
info[p[0]] = paren.sub('', p[2]).strip()
languages_lines = map(lambda x:'("%s", _(u"%s")),'%(x['Subtag'],x['Description']), languages)
# Generate and save the file.
if not filename:
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'languages.py')
# TODO: first make a backup of the file if it exists already.
f = codecs.open(filename, 'w', 'utf-8')
f.write(TEMPLATE % {
'languages': '\n '.join(languages_lines),
})
f.close() | python | def regenerate(location='http://www.iana.org/assignments/language-subtag-registry',
filename=None, default_encoding='utf-8'):
"""
Generate the languages Python module.
"""
paren = re.compile('\([^)]*\)')
# Get the language list.
data = urllib2.urlopen(location)
if ('content-type' in data.headers and
'charset=' in data.headers['content-type']):
encoding = data.headers['content-type'].split('charset=')[-1]
else:
encoding = default_encoding
content = data.read().decode(encoding)
languages = []
info = {}
p = None
for line in content.splitlines():
if line == '%%':
if 'Type' in info and info['Type'] == 'language':
languages.append(info)
info = {}
elif ':' not in line and p:
info[p[0]] = paren.sub('', p[2]+line).strip()
else:
p = line.partition(':')
if not p[0] in info: # Keep the first description as it should be the most common
info[p[0]] = paren.sub('', p[2]).strip()
languages_lines = map(lambda x:'("%s", _(u"%s")),'%(x['Subtag'],x['Description']), languages)
# Generate and save the file.
if not filename:
filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'languages.py')
# TODO: first make a backup of the file if it exists already.
f = codecs.open(filename, 'w', 'utf-8')
f.write(TEMPLATE % {
'languages': '\n '.join(languages_lines),
})
f.close() | [
"def",
"regenerate",
"(",
"location",
"=",
"'http://www.iana.org/assignments/language-subtag-registry'",
",",
"filename",
"=",
"None",
",",
"default_encoding",
"=",
"'utf-8'",
")",
":",
"paren",
"=",
"re",
".",
"compile",
"(",
"'\\([^)]*\\)'",
")",
"# Get the language... | Generate the languages Python module. | [
"Generate",
"the",
"languages",
"Python",
"module",
"."
] | 7847dab863794fd06d8b445c9dda6b45ce830f8d | https://github.com/audiolion/django-language-field/blob/7847dab863794fd06d8b445c9dda6b45ce830f8d/languages/regenerate.py#L22-L62 | train | 46,775 |
mobiusklein/brainpy | brainpy/brainpy.py | newton | def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates are done **in place**
Parameters
----------
power_sum: list of float
elementary_symmetric_polynomial: list of float
order: int
The number of terms to expand to when updating `elementary_symmetric_polynomial`
See Also
--------
https://en.wikipedia.org/wiki/Newton%27s_identities[https://en.wikipedia.org/wiki/Newton%27s_identities]
'''
if len(power_sum) > len(elementary_symmetric_polynomial):
_update_elementary_symmetric_polynomial(power_sum, elementary_symmetric_polynomial, order)
elif len(power_sum) < len(elementary_symmetric_polynomial):
_update_power_sum(power_sum, elementary_symmetric_polynomial, order) | python | def newton(power_sum, elementary_symmetric_polynomial, order):
r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates are done **in place**
Parameters
----------
power_sum: list of float
elementary_symmetric_polynomial: list of float
order: int
The number of terms to expand to when updating `elementary_symmetric_polynomial`
See Also
--------
https://en.wikipedia.org/wiki/Newton%27s_identities[https://en.wikipedia.org/wiki/Newton%27s_identities]
'''
if len(power_sum) > len(elementary_symmetric_polynomial):
_update_elementary_symmetric_polynomial(power_sum, elementary_symmetric_polynomial, order)
elif len(power_sum) < len(elementary_symmetric_polynomial):
_update_power_sum(power_sum, elementary_symmetric_polynomial, order) | [
"def",
"newton",
"(",
"power_sum",
",",
"elementary_symmetric_polynomial",
",",
"order",
")",
":",
"if",
"len",
"(",
"power_sum",
")",
">",
"len",
"(",
"elementary_symmetric_polynomial",
")",
":",
"_update_elementary_symmetric_polynomial",
"(",
"power_sum",
",",
"el... | r'''
Given two lists of values, the first list being the `power sum`s of a
polynomial, and the second being expressions of the roots of the
polynomial as found by Viete's Formula, use information from the longer list to
fill out the shorter list using Newton's Identities.
.. note::
Updates are done **in place**
Parameters
----------
power_sum: list of float
elementary_symmetric_polynomial: list of float
order: int
The number of terms to expand to when updating `elementary_symmetric_polynomial`
See Also
--------
https://en.wikipedia.org/wiki/Newton%27s_identities[https://en.wikipedia.org/wiki/Newton%27s_identities] | [
"r",
"Given",
"two",
"lists",
"of",
"values",
"the",
"first",
"list",
"being",
"the",
"power",
"sum",
"s",
"of",
"a",
"polynomial",
"and",
"the",
"second",
"being",
"expressions",
"of",
"the",
"roots",
"of",
"the",
"polynomial",
"as",
"found",
"by",
"Vie... | 4ccba40af33651a338c0c54bf1a251345c2db8da | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L75-L99 | train | 46,776 |
mobiusklein/brainpy | brainpy/brainpy.py | max_variants | def max_variants(composition):
"""Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int
"""
max_n_variants = 0
for element, count in composition.items():
if element == "H+":
continue
try:
max_n_variants += count * periodic_table[element].max_neutron_shift()
except KeyError:
pass
return max_n_variants | python | def max_variants(composition):
"""Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int
"""
max_n_variants = 0
for element, count in composition.items():
if element == "H+":
continue
try:
max_n_variants += count * periodic_table[element].max_neutron_shift()
except KeyError:
pass
return max_n_variants | [
"def",
"max_variants",
"(",
"composition",
")",
":",
"max_n_variants",
"=",
"0",
"for",
"element",
",",
"count",
"in",
"composition",
".",
"items",
"(",
")",
":",
"if",
"element",
"==",
"\"H+\"",
":",
"continue",
"try",
":",
"max_n_variants",
"+=",
"count"... | Calculates the maximum number of isotopic variants that could be produced by a
composition.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
Returns
-------
max_n_variants : int | [
"Calculates",
"the",
"maximum",
"number",
"of",
"isotopic",
"variants",
"that",
"could",
"be",
"produced",
"by",
"a",
"composition",
"."
] | 4ccba40af33651a338c0c54bf1a251345c2db8da | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L339-L362 | train | 46,777 |
mobiusklein/brainpy | brainpy/brainpy.py | isotopic_variants | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON):
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the monoisotopic peak.
If given a number below 1 or above the maximum number of isotopic variants, the maximum will
be used. If `None`, a "reasonable" value is chosen by `int(sqrt(max_variants(composition)))`.
charge: int
The charge state of the isotopic cluster to produce. Defaults to 0, theoretical neutral mass.
Returns
-------
list of Peaks
See Also
--------
:class:`IsotopicDistribution`
'''
if npeaks is None:
max_n_variants = max_variants(composition)
npeaks = int(sqrt(max_n_variants) - 2)
npeaks = max(npeaks, 3)
else:
# Monoisotopic Peak is not included
npeaks -= 1
return IsotopicDistribution(composition, npeaks).aggregated_isotopic_variants(
charge, charge_carrier=charge_carrier) | python | def isotopic_variants(composition, npeaks=None, charge=0, charge_carrier=PROTON):
'''
Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the monoisotopic peak.
If given a number below 1 or above the maximum number of isotopic variants, the maximum will
be used. If `None`, a "reasonable" value is chosen by `int(sqrt(max_variants(composition)))`.
charge: int
The charge state of the isotopic cluster to produce. Defaults to 0, theoretical neutral mass.
Returns
-------
list of Peaks
See Also
--------
:class:`IsotopicDistribution`
'''
if npeaks is None:
max_n_variants = max_variants(composition)
npeaks = int(sqrt(max_n_variants) - 2)
npeaks = max(npeaks, 3)
else:
# Monoisotopic Peak is not included
npeaks -= 1
return IsotopicDistribution(composition, npeaks).aggregated_isotopic_variants(
charge, charge_carrier=charge_carrier) | [
"def",
"isotopic_variants",
"(",
"composition",
",",
"npeaks",
"=",
"None",
",",
"charge",
"=",
"0",
",",
"charge_carrier",
"=",
"PROTON",
")",
":",
"if",
"npeaks",
"is",
"None",
":",
"max_n_variants",
"=",
"max_variants",
"(",
"composition",
")",
"npeaks",
... | Compute a peak list representing the theoretical isotopic cluster for `composition`.
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
npeaks: int
The number of peaks to include in the isotopic cluster, starting from the monoisotopic peak.
If given a number below 1 or above the maximum number of isotopic variants, the maximum will
be used. If `None`, a "reasonable" value is chosen by `int(sqrt(max_variants(composition)))`.
charge: int
The charge state of the isotopic cluster to produce. Defaults to 0, theoretical neutral mass.
Returns
-------
list of Peaks
See Also
--------
:class:`IsotopicDistribution` | [
"Compute",
"a",
"peak",
"list",
"representing",
"the",
"theoretical",
"isotopic",
"cluster",
"for",
"composition",
"."
] | 4ccba40af33651a338c0c54bf1a251345c2db8da | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/brainpy.py#L579-L611 | train | 46,778 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | getnii_descr | def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
for ci in range(len(rcnlst)):
tmp = rcnlst[ci].split('=')
rcndic[tmp[0]] = tmp[1]
return rcndic | python | def getnii_descr(fim):
'''
Extracts the custom description header field to dictionary
'''
nim = nib.load(fim)
hdr = nim.header
rcnlst = hdr['descrip'].item().split(';')
rcndic = {}
if rcnlst[0]=='':
# print 'w> no description in the NIfTI header'
return rcndic
for ci in range(len(rcnlst)):
tmp = rcnlst[ci].split('=')
rcndic[tmp[0]] = tmp[1]
return rcndic | [
"def",
"getnii_descr",
"(",
"fim",
")",
":",
"nim",
"=",
"nib",
".",
"load",
"(",
"fim",
")",
"hdr",
"=",
"nim",
".",
"header",
"rcnlst",
"=",
"hdr",
"[",
"'descrip'",
"]",
".",
"item",
"(",
")",
".",
"split",
"(",
"';'",
")",
"rcndic",
"=",
"{... | Extracts the custom description header field to dictionary | [
"Extracts",
"the",
"custom",
"description",
"header",
"field",
"to",
"dictionary"
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L111-L127 | train | 46,779 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | orientnii | def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
for i in range(3):
niixyz[i] = np.argmax(abs(A[i,:-1]))
niiorient.append( strorient[ niixyz[i] ] )
print niiorient | python | def orientnii(imfile):
'''Get the orientation from NIfTI sform. Not fully functional yet.'''
strorient = ['L-R', 'S-I', 'A-P']
niiorient = []
niixyz = np.zeros(3,dtype=np.int8)
if os.path.isfile(imfile):
nim = nib.load(imfile)
pct = nim.get_data()
A = nim.get_sform()
for i in range(3):
niixyz[i] = np.argmax(abs(A[i,:-1]))
niiorient.append( strorient[ niixyz[i] ] )
print niiorient | [
"def",
"orientnii",
"(",
"imfile",
")",
":",
"strorient",
"=",
"[",
"'L-R'",
",",
"'S-I'",
",",
"'A-P'",
"]",
"niiorient",
"=",
"[",
"]",
"niixyz",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"dtype",
"=",
"np",
".",
"int8",
")",
"if",
"os",
".",
"... | Get the orientation from NIfTI sform. Not fully functional yet. | [
"Get",
"the",
"orientation",
"from",
"NIfTI",
"sform",
".",
"Not",
"fully",
"functional",
"yet",
"."
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L191-L203 | train | 46,780 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | pick_t1w | def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri and os.path.isfile(mri['T1bc']):
ft1w = mri['T1bc']
elif 'T1nii' in mri and os.path.isfile(mri['T1nii']):
ft1w = mri['T1nii']
elif 'T1DCM' in mri and os.path.exists(mri['MRT1W']):
# create file name for the converted NIfTI image
fnii = 'converted'
call( [rs.DCM2NIIX, '-f', fnii, mri['T1nii'] ] )
ft1nii = glob.glob( os.path.join(mri['T1nii'], '*converted*.nii*') )
ft1w = ft1nii[0]
else:
print 'e> disaster: could not find a T1w image!'
return None
else:
('e> no correct input found for the T1w image')
return None
return ft1w | python | def pick_t1w(mri):
''' Pick the MR T1w from the dictionary for MR->PET registration.
'''
if isinstance(mri, dict):
# check if NIfTI file is given
if 'T1N4' in mri and os.path.isfile(mri['T1N4']):
ft1w = mri['T1N4']
# or another bias corrected
elif 'T1bc' in mri and os.path.isfile(mri['T1bc']):
ft1w = mri['T1bc']
elif 'T1nii' in mri and os.path.isfile(mri['T1nii']):
ft1w = mri['T1nii']
elif 'T1DCM' in mri and os.path.exists(mri['MRT1W']):
# create file name for the converted NIfTI image
fnii = 'converted'
call( [rs.DCM2NIIX, '-f', fnii, mri['T1nii'] ] )
ft1nii = glob.glob( os.path.join(mri['T1nii'], '*converted*.nii*') )
ft1w = ft1nii[0]
else:
print 'e> disaster: could not find a T1w image!'
return None
else:
('e> no correct input found for the T1w image')
return None
return ft1w | [
"def",
"pick_t1w",
"(",
"mri",
")",
":",
"if",
"isinstance",
"(",
"mri",
",",
"dict",
")",
":",
"# check if NIfTI file is given",
"if",
"'T1N4'",
"in",
"mri",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"mri",
"[",
"'T1N4'",
"]",
")",
":",
"ft1w",
... | Pick the MR T1w from the dictionary for MR->PET registration. | [
"Pick",
"the",
"MR",
"T1w",
"from",
"the",
"dictionary",
"for",
"MR",
"-",
">",
"PET",
"registration",
"."
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L237-L264 | train | 46,781 |
pjmark/NIMPA | niftypet/nimpa/prc/imio.py | list_dcm_datain | def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datain['mumapDCM'])
# accept only *.dcm extensions
dcmump = [os.path.join(datain['mumapDCM'],d) for d in dcmump if d.endswith(dcmext)]
dcmlst += dcmump
if 'T1DCM' in datain:
dcmt1 = os.listdir(datain['T1DCM'])
# accept only *.dcm extensions
dcmt1 = [os.path.join(datain['T1DCM'],d) for d in dcmt1 if d.endswith(dcmext)]
dcmlst += dcmt1
if 'T2DCM' in datain:
dcmt2 = os.listdir(datain['T2DCM'])
# accept only *.dcm extensions
dcmt2 = [os.path.join(datain['T2DCM'],d) for d in dcmt2 if d.endswith(dcmext)]
dcmlst += dcmt2
if 'UTE1' in datain:
dcmute1 = os.listdir(datain['UTE1'])
# accept only *.dcm extensions
dcmute1 = [os.path.join(datain['UTE1'],d) for d in dcmute1 if d.endswith(dcmext)]
dcmlst += dcmute1
if 'UTE2' in datain:
dcmute2 = os.listdir(datain['UTE2'])
# accept only *.dcm extensions
dcmute2 = [os.path.join(datain['UTE2'],d) for d in dcmute2 if d.endswith(dcmext)]
dcmlst += dcmute2
#-list-mode data dcm
if 'lm_dcm' in datain:
dcmlst += [datain['lm_dcm']]
if 'lm_ima' in datain:
dcmlst += [datain['lm_ima']]
#-norm
if 'nrm_dcm' in datain:
dcmlst += [datain['nrm_dcm']]
if 'nrm_ima' in datain:
dcmlst += [datain['nrm_ima']]
return dcmlst | python | def list_dcm_datain(datain):
''' List all DICOM file paths in the datain dictionary of input data.
'''
if not isinstance(datain, dict):
raise ValueError('The input is not a dictionary!')
dcmlst = []
# list of mu-map DICOM files
if 'mumapDCM' in datain:
dcmump = os.listdir(datain['mumapDCM'])
# accept only *.dcm extensions
dcmump = [os.path.join(datain['mumapDCM'],d) for d in dcmump if d.endswith(dcmext)]
dcmlst += dcmump
if 'T1DCM' in datain:
dcmt1 = os.listdir(datain['T1DCM'])
# accept only *.dcm extensions
dcmt1 = [os.path.join(datain['T1DCM'],d) for d in dcmt1 if d.endswith(dcmext)]
dcmlst += dcmt1
if 'T2DCM' in datain:
dcmt2 = os.listdir(datain['T2DCM'])
# accept only *.dcm extensions
dcmt2 = [os.path.join(datain['T2DCM'],d) for d in dcmt2 if d.endswith(dcmext)]
dcmlst += dcmt2
if 'UTE1' in datain:
dcmute1 = os.listdir(datain['UTE1'])
# accept only *.dcm extensions
dcmute1 = [os.path.join(datain['UTE1'],d) for d in dcmute1 if d.endswith(dcmext)]
dcmlst += dcmute1
if 'UTE2' in datain:
dcmute2 = os.listdir(datain['UTE2'])
# accept only *.dcm extensions
dcmute2 = [os.path.join(datain['UTE2'],d) for d in dcmute2 if d.endswith(dcmext)]
dcmlst += dcmute2
#-list-mode data dcm
if 'lm_dcm' in datain:
dcmlst += [datain['lm_dcm']]
if 'lm_ima' in datain:
dcmlst += [datain['lm_ima']]
#-norm
if 'nrm_dcm' in datain:
dcmlst += [datain['nrm_dcm']]
if 'nrm_ima' in datain:
dcmlst += [datain['nrm_ima']]
return dcmlst | [
"def",
"list_dcm_datain",
"(",
"datain",
")",
":",
"if",
"not",
"isinstance",
"(",
"datain",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"'The input is not a dictionary!'",
")",
"dcmlst",
"=",
"[",
"]",
"# list of mu-map DICOM files",
"if",
"'mumapDCM'",
... | List all DICOM file paths in the datain dictionary of input data. | [
"List",
"all",
"DICOM",
"file",
"paths",
"in",
"the",
"datain",
"dictionary",
"of",
"input",
"data",
"."
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/niftypet/nimpa/prc/imio.py#L358-L411 | train | 46,782 |
pjmark/NIMPA | cudasetup.py | find_cuda | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
cuda_path = None
if cuda_path is None:
print 'w> nvcc compiler could not be found from the PATH!'
return None
# serach for the CUDA library path
lcuda_path = os.path.join(cuda_path, 'lib64')
if 'LD_LIBRARY_PATH' in os.environ.keys():
if lcuda_path in os.environ['LD_LIBRARY_PATH'].split(os.pathsep):
print 'i> found CUDA lib64 in LD_LIBRARY_PATH: ', lcuda_path
elif os.path.isdir(lcuda_path):
print 'i> found CUDA lib64 in : ', lcuda_path
else:
print 'w> folder for CUDA library (64-bit) could not be found!'
return cuda_path, lcuda_path | python | def find_cuda():
'''Locate the CUDA environment on the system.'''
# search the PATH for NVCC
for fldr in os.environ['PATH'].split(os.pathsep):
cuda_path = join(fldr, 'nvcc')
if os.path.exists(cuda_path):
cuda_path = os.path.dirname(os.path.dirname(cuda_path))
break
cuda_path = None
if cuda_path is None:
print 'w> nvcc compiler could not be found from the PATH!'
return None
# serach for the CUDA library path
lcuda_path = os.path.join(cuda_path, 'lib64')
if 'LD_LIBRARY_PATH' in os.environ.keys():
if lcuda_path in os.environ['LD_LIBRARY_PATH'].split(os.pathsep):
print 'i> found CUDA lib64 in LD_LIBRARY_PATH: ', lcuda_path
elif os.path.isdir(lcuda_path):
print 'i> found CUDA lib64 in : ', lcuda_path
else:
print 'w> folder for CUDA library (64-bit) could not be found!'
return cuda_path, lcuda_path | [
"def",
"find_cuda",
"(",
")",
":",
"# search the PATH for NVCC",
"for",
"fldr",
"in",
"os",
".",
"environ",
"[",
"'PATH'",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
":",
"cuda_path",
"=",
"join",
"(",
"fldr",
",",
"'nvcc'",
")",
"if",
"os",
... | Locate the CUDA environment on the system. | [
"Locate",
"the",
"CUDA",
"environment",
"on",
"the",
"system",
"."
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L53-L78 | train | 46,783 |
pjmark/NIMPA | cudasetup.py | resources_setup | def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.
path_install = os.path.join(path_current, 'resources')
# get the path to the local resources.py (on Linux machines it is in ~/.niftypet)
path_resources = path_niftypet_local()
print path_current
# flag for the resources file if already installed (initially assumed not)
flg_resources = False
# does the local folder for niftypet exists? if not create one.
if not os.path.exists(path_resources):
os.makedirs(path_resources)
# is resources.py in the folder?
if not os.path.isfile(os.path.join(path_resources,'resources.py')):
if os.path.isfile(os.path.join(path_install,'resources.py')):
shutil.copyfile( os.path.join(path_install,'resources.py'), os.path.join(path_resources,'resources.py') )
else:
print 'e> could not fine file <resources.py> to be installed!'
raise IOError('could not find <resources.py')
else:
print 'i> <resources.py> should be already in the local NiftyPET folder.', path_resources
# set the flag that the resources file is already there
flg_resources = True
sys.path.append(path_resources)
try:
import resources
except ImportError as ie:
print '----------------------------'
print 'e> Import Error: NiftyPET''s resources file <resources.py> could not be imported. It should be in ''~/.niftypet/resources.py'' but likely it does not exists.'
print '----------------------------'
# find available GPU devices, select one or more and output the compilation flags
gpuarch = dev_setup()
# return gpuarch for cmake compilation
return gpuarch | python | def resources_setup():
'''
This function checks CUDA devices, selects some and installs resources.py
'''
print 'i> installing file <resources.py> into home directory if it does not exist.'
path_current = os.path.dirname( os.path.realpath(__file__) )
# path to the install version of resources.py.
path_install = os.path.join(path_current, 'resources')
# get the path to the local resources.py (on Linux machines it is in ~/.niftypet)
path_resources = path_niftypet_local()
print path_current
# flag for the resources file if already installed (initially assumed not)
flg_resources = False
# does the local folder for niftypet exists? if not create one.
if not os.path.exists(path_resources):
os.makedirs(path_resources)
# is resources.py in the folder?
if not os.path.isfile(os.path.join(path_resources,'resources.py')):
if os.path.isfile(os.path.join(path_install,'resources.py')):
shutil.copyfile( os.path.join(path_install,'resources.py'), os.path.join(path_resources,'resources.py') )
else:
print 'e> could not fine file <resources.py> to be installed!'
raise IOError('could not find <resources.py')
else:
print 'i> <resources.py> should be already in the local NiftyPET folder.', path_resources
# set the flag that the resources file is already there
flg_resources = True
sys.path.append(path_resources)
try:
import resources
except ImportError as ie:
print '----------------------------'
print 'e> Import Error: NiftyPET''s resources file <resources.py> could not be imported. It should be in ''~/.niftypet/resources.py'' but likely it does not exists.'
print '----------------------------'
# find available GPU devices, select one or more and output the compilation flags
gpuarch = dev_setup()
# return gpuarch for cmake compilation
return gpuarch | [
"def",
"resources_setup",
"(",
")",
":",
"print",
"'i> installing file <resources.py> into home directory if it does not exist.'",
"path_current",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"__file__",
")",
")",
"# path to th... | This function checks CUDA devices, selects some and installs resources.py | [
"This",
"function",
"checks",
"CUDA",
"devices",
"selects",
"some",
"and",
"installs",
"resources",
".",
"py"
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/cudasetup.py#L205-L245 | train | 46,784 |
Syndace/python-omemo | omemo/promise.py | coroutine | def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
back into the generator function.
This simulates sequential execution which in reality can be asynchonous.
"""
@functools.wraps(f)
def _coroutine(*args, **kwargs):
def _resolver(resolve, reject):
try:
generator = f(*args, **kwargs)
except BaseException as e:
# Special case for a function that throws immediately
reject(e)
else:
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
resolve(generator)
else:
def _step(previous, previous_type):
element = None
try:
if previous_type == None:
element = next(generator)
elif previous_type:
element = generator.send(previous)
else:
if not isinstance(previous, BaseException):
previous = RejectedException(previous)
element = generator.throw(previous)
except StopIteration as e:
resolve(getattr(e, "value", None))
except ReturnValueException as e:
resolve(e.value)
except BaseException as e:
reject(e)
else:
try:
element.then(
lambda value : _step(value, True),
lambda reason : _step(reason, False)
)
except AttributeError:
reject(InvalidCoroutineException(element))
_step(None, None)
return Promise(_resolver)
return _coroutine | python | def coroutine(f):
"""
Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
back into the generator function.
This simulates sequential execution which in reality can be asynchonous.
"""
@functools.wraps(f)
def _coroutine(*args, **kwargs):
def _resolver(resolve, reject):
try:
generator = f(*args, **kwargs)
except BaseException as e:
# Special case for a function that throws immediately
reject(e)
else:
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
resolve(generator)
else:
def _step(previous, previous_type):
element = None
try:
if previous_type == None:
element = next(generator)
elif previous_type:
element = generator.send(previous)
else:
if not isinstance(previous, BaseException):
previous = RejectedException(previous)
element = generator.throw(previous)
except StopIteration as e:
resolve(getattr(e, "value", None))
except ReturnValueException as e:
resolve(e.value)
except BaseException as e:
reject(e)
else:
try:
element.then(
lambda value : _step(value, True),
lambda reason : _step(reason, False)
)
except AttributeError:
reject(InvalidCoroutineException(element))
_step(None, None)
return Promise(_resolver)
return _coroutine | [
"def",
"coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"try",
":",
"generator",
... | Implementation of a coroutine.
Use as a decorator:
@coroutine
def foo():
result = yield somePromise
The function passed should be a generator yielding instances of the Promise class
(or compatible).
The coroutine waits for the Promise to resolve and sends the result (or the error)
back into the generator function.
This simulates sequential execution which in reality can be asynchonous. | [
"Implementation",
"of",
"a",
"coroutine",
"."
] | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L164-L225 | train | 46,785 |
Syndace/python-omemo | omemo/promise.py | no_coroutine | def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if you didn't use yield at all.
The example above is equivalent to:
def foo():
five = 5
print("hello")
Why?
This is the counterpart to coroutine used by maybe_coroutine below.
"""
@functools.wraps(f)
def _no_coroutine(*args, **kwargs):
generator = f(*args, **kwargs)
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
return generator
previous = None
first = True
while True:
element = None
try:
if first:
element = next(generator)
else:
element = generator.send(previous)
except StopIteration as e:
return getattr(e, "value", None)
except ReturnValueException as e:
return e.value
else:
previous = element
first = False
return _no_coroutine | python | def no_coroutine(f):
"""
This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if you didn't use yield at all.
The example above is equivalent to:
def foo():
five = 5
print("hello")
Why?
This is the counterpart to coroutine used by maybe_coroutine below.
"""
@functools.wraps(f)
def _no_coroutine(*args, **kwargs):
generator = f(*args, **kwargs)
# Special case for a function that returns immediately
if not isinstance(generator, types.GeneratorType):
return generator
previous = None
first = True
while True:
element = None
try:
if first:
element = next(generator)
else:
element = generator.send(previous)
except StopIteration as e:
return getattr(e, "value", None)
except ReturnValueException as e:
return e.value
else:
previous = element
first = False
return _no_coroutine | [
"def",
"no_coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"_no_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"generator",
"=",
"f",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Speci... | This is not a coroutine ;)
Use as a decorator:
@no_coroutine
def foo():
five = yield 5
print(yield "hello")
The function passed should be a generator yielding whatever you feel like.
The yielded values instantly get passed back into the generator.
It's basically the same as if you didn't use yield at all.
The example above is equivalent to:
def foo():
five = 5
print("hello")
Why?
This is the counterpart to coroutine used by maybe_coroutine below. | [
"This",
"is",
"not",
"a",
"coroutine",
";",
")"
] | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L227-L276 | train | 46,786 |
Syndace/python-omemo | omemo/promise.py | maybe_coroutine | def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only Promises or whatever
you feel like.
The decide parameter must be a function which gets called with the same parameters as
the function to decide whether this is a coroutine or not.
Using this it is possible to either make the function a coroutine or not based on a
parameter to the function call.
Let's explain the example above:
# If the maybeAPromise is an instance of Promise,
# we want the foo function to act as a coroutine.
# If the maybeAPromise is not an instance of Promise,
# we want the foo function to act like any other normal synchronous function.
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
# If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,
# thus maybeAPromise will get resolved asynchronously and the result will be
# pushed back here.
# Otherwise, foo behaves like no_coroutine,
# just pushing the exact value of maybeAPromise back into the generator.
result = yield maybeAPromise
print("hello")
return result
"""
def _maybe_coroutine(f):
@functools.wraps(f)
def __maybe_coroutine(*args, **kwargs):
if decide(*args, **kwargs):
return coroutine(f)(*args, **kwargs)
else:
return no_coroutine(f)(*args, **kwargs)
return __maybe_coroutine
return _maybe_coroutine | python | def maybe_coroutine(decide):
"""
Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only Promises or whatever
you feel like.
The decide parameter must be a function which gets called with the same parameters as
the function to decide whether this is a coroutine or not.
Using this it is possible to either make the function a coroutine or not based on a
parameter to the function call.
Let's explain the example above:
# If the maybeAPromise is an instance of Promise,
# we want the foo function to act as a coroutine.
# If the maybeAPromise is not an instance of Promise,
# we want the foo function to act like any other normal synchronous function.
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
# If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,
# thus maybeAPromise will get resolved asynchronously and the result will be
# pushed back here.
# Otherwise, foo behaves like no_coroutine,
# just pushing the exact value of maybeAPromise back into the generator.
result = yield maybeAPromise
print("hello")
return result
"""
def _maybe_coroutine(f):
@functools.wraps(f)
def __maybe_coroutine(*args, **kwargs):
if decide(*args, **kwargs):
return coroutine(f)(*args, **kwargs)
else:
return no_coroutine(f)(*args, **kwargs)
return __maybe_coroutine
return _maybe_coroutine | [
"def",
"maybe_coroutine",
"(",
"decide",
")",
":",
"def",
"_maybe_coroutine",
"(",
"f",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"f",
")",
"def",
"__maybe_coroutine",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"decide",
"(",
"*"... | Either be a coroutine or not.
Use as a decorator:
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
result = yield maybeAPromise
print("hello")
return result
The function passed should be a generator yielding either only Promises or whatever
you feel like.
The decide parameter must be a function which gets called with the same parameters as
the function to decide whether this is a coroutine or not.
Using this it is possible to either make the function a coroutine or not based on a
parameter to the function call.
Let's explain the example above:
# If the maybeAPromise is an instance of Promise,
# we want the foo function to act as a coroutine.
# If the maybeAPromise is not an instance of Promise,
# we want the foo function to act like any other normal synchronous function.
@maybe_coroutine(lambda maybeAPromise: return isinstance(maybeAPromise, Promise))
def foo(maybeAPromise):
# If isinstance(maybeAPromise, Promise), foo behaves like a coroutine,
# thus maybeAPromise will get resolved asynchronously and the result will be
# pushed back here.
# Otherwise, foo behaves like no_coroutine,
# just pushing the exact value of maybeAPromise back into the generator.
result = yield maybeAPromise
print("hello")
return result | [
"Either",
"be",
"a",
"coroutine",
"or",
"not",
"."
] | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/promise.py#L278-L321 | train | 46,787 |
Syndace/python-omemo | omemo/storagewrapper.py | makeCallbackPromise | def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or the error otherwise.
"""
def _resolver(resolve, reject):
function(
lambda success, result: resolve(result) if success else reject(result),
*args,
**kwargs
)
return Promise(_resolver) | python | def makeCallbackPromise(function, *args, **kwargs):
"""
Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or the error otherwise.
"""
def _resolver(resolve, reject):
function(
lambda success, result: resolve(result) if success else reject(result),
*args,
**kwargs
)
return Promise(_resolver) | [
"def",
"makeCallbackPromise",
"(",
"function",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"_resolver",
"(",
"resolve",
",",
"reject",
")",
":",
"function",
"(",
"lambda",
"success",
",",
"result",
":",
"resolve",
"(",
"result",
")",
"i... | Take a function that reports its result using a callback and return a Promise that
listenes for this callback.
The function must accept a callback as its first parameter.
The callback must take two arguments:
- success : True or False
- result : The result of the operation if success is True or the error otherwise. | [
"Take",
"a",
"function",
"that",
"reports",
"its",
"result",
"using",
"a",
"callback",
"and",
"return",
"a",
"Promise",
"that",
"listenes",
"for",
"this",
"callback",
"."
] | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/storagewrapper.py#L6-L24 | train | 46,788 |
mobiusklein/brainpy | brainpy/composition.py | calculate_mass | def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_mass`).
Returns
-------
mass : float
"""
mass = 0.0
if mass_data is None:
mass_data = nist_mass
for element in composition:
try:
mass += (composition[element] * mass_data[element][0][0])
except KeyError:
match = re.search(r"(\S+)\[(\d+)\]", element)
if match:
element_ = match.group(1)
isotope = int(match.group(2))
mass += composition[element] * mass_data[element_][isotope][0]
else:
raise
return mass | python | def calculate_mass(composition, mass_data=None):
"""Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_mass`).
Returns
-------
mass : float
"""
mass = 0.0
if mass_data is None:
mass_data = nist_mass
for element in composition:
try:
mass += (composition[element] * mass_data[element][0][0])
except KeyError:
match = re.search(r"(\S+)\[(\d+)\]", element)
if match:
element_ = match.group(1)
isotope = int(match.group(2))
mass += composition[element] * mass_data[element_][isotope][0]
else:
raise
return mass | [
"def",
"calculate_mass",
"(",
"composition",
",",
"mass_data",
"=",
"None",
")",
":",
"mass",
"=",
"0.0",
"if",
"mass_data",
"is",
"None",
":",
"mass_data",
"=",
"nist_mass",
"for",
"element",
"in",
"composition",
":",
"try",
":",
"mass",
"+=",
"(",
"com... | Calculates the monoisotopic mass of a composition
Parameters
----------
composition : Mapping
Any Mapping type where keys are element symbols and values are integers
mass_data : dict, optional
A dict with the masses of the chemical elements (the default
value is :py:data:`nist_mass`).
Returns
-------
mass : float | [
"Calculates",
"the",
"monoisotopic",
"mass",
"of",
"a",
"composition"
] | 4ccba40af33651a338c0c54bf1a251345c2db8da | https://github.com/mobiusklein/brainpy/blob/4ccba40af33651a338c0c54bf1a251345c2db8da/brainpy/composition.py#L14-L43 | train | 46,789 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.login | def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise SkybellAuthenticationException(ERROR.USERNAME)
if self._password is None or not isinstance(self._password, str):
raise SkybellAuthenticationException(ERROR.PASSWORD)
self.update_cache(
{
CONST.ACCESS_TOKEN: None
})
login_data = {
'username': self._username,
'password': self._password,
'appId': self.cache(CONST.APP_ID),
CONST.TOKEN: self.cache(CONST.TOKEN)
}
try:
response = self.send_request('post', CONST.LOGIN_URL,
json_data=login_data, retry=False)
except Exception as exc:
raise SkybellAuthenticationException(ERROR.LOGIN_FAILED, exc)
_LOGGER.debug("Login Response: %s", response.text)
response_object = json.loads(response.text)
self.update_cache({
CONST.ACCESS_TOKEN: response_object[CONST.ACCESS_TOKEN]})
_LOGGER.info("Login successful")
return True | python | def login(self, username=None, password=None):
"""Execute Skybell login."""
if username is not None:
self._username = username
if password is not None:
self._password = password
if self._username is None or not isinstance(self._username, str):
raise SkybellAuthenticationException(ERROR.USERNAME)
if self._password is None or not isinstance(self._password, str):
raise SkybellAuthenticationException(ERROR.PASSWORD)
self.update_cache(
{
CONST.ACCESS_TOKEN: None
})
login_data = {
'username': self._username,
'password': self._password,
'appId': self.cache(CONST.APP_ID),
CONST.TOKEN: self.cache(CONST.TOKEN)
}
try:
response = self.send_request('post', CONST.LOGIN_URL,
json_data=login_data, retry=False)
except Exception as exc:
raise SkybellAuthenticationException(ERROR.LOGIN_FAILED, exc)
_LOGGER.debug("Login Response: %s", response.text)
response_object = json.loads(response.text)
self.update_cache({
CONST.ACCESS_TOKEN: response_object[CONST.ACCESS_TOKEN]})
_LOGGER.info("Login successful")
return True | [
"def",
"login",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"if",
"username",
"is",
"not",
"None",
":",
"self",
".",
"_username",
"=",
"username",
"if",
"password",
"is",
"not",
"None",
":",
"self",
".",
"_passw... | Execute Skybell login. | [
"Execute",
"Skybell",
"login",
"."
] | ac966d9f590cda7654f6de7eecc94e2103459eef | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L68-L108 | train | 46,790 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.logout | def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session()
self._devices = None
self.update_cache({CONST.ACCESS_TOKEN: None})
return True | python | def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session()
self._devices = None
self.update_cache({CONST.ACCESS_TOKEN: None})
return True | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
":",
"# No explicit logout call as it doesn't seem to matter",
"# if a logout happens without registering the app which",
"# we aren't currently doing.",
"self",
".",
... | Explicit Skybell logout. | [
"Explicit",
"Skybell",
"logout",
"."
] | ac966d9f590cda7654f6de7eecc94e2103459eef | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L110-L121 | train | 46,791 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.send_request | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.ACCESS_TOKEN):
headers['Authorization'] = 'Bearer ' + \
self.cache(CONST.ACCESS_TOKEN)
headers['user-agent'] = (
'SkyBell/3.4.1 (iPhone9,2; iOS 11.0; loc=en_US; lang=en-US) '
'com.skybell.doorbell/1')
headers['content-type'] = 'application/json'
headers['accepts'] = '*/*'
headers['x-skybell-app-id'] = self.cache(CONST.APP_ID)
headers['x-skybell-client-id'] = self.cache(CONST.CLIENT_ID)
_LOGGER.debug("HTTP %s %s Request with headers: %s",
method, url, headers)
try:
response = getattr(self._session, method)(
url, headers=headers, json=json_data)
_LOGGER.debug("%s %s", response, response.text)
if response and response.status_code < 400:
return response
except RequestException as exc:
_LOGGER.warning("Skybell request exception: %s", exc)
if retry:
self.login()
return self.send_request(method, url, headers, json_data, False)
raise SkybellException(ERROR.REQUEST, "Retry failed") | python | def send_request(self, method, url, headers=None,
json_data=None, retry=True):
"""Send requests to Skybell."""
if not self.cache(CONST.ACCESS_TOKEN) and url != CONST.LOGIN_URL:
self.login()
if not headers:
headers = {}
if self.cache(CONST.ACCESS_TOKEN):
headers['Authorization'] = 'Bearer ' + \
self.cache(CONST.ACCESS_TOKEN)
headers['user-agent'] = (
'SkyBell/3.4.1 (iPhone9,2; iOS 11.0; loc=en_US; lang=en-US) '
'com.skybell.doorbell/1')
headers['content-type'] = 'application/json'
headers['accepts'] = '*/*'
headers['x-skybell-app-id'] = self.cache(CONST.APP_ID)
headers['x-skybell-client-id'] = self.cache(CONST.CLIENT_ID)
_LOGGER.debug("HTTP %s %s Request with headers: %s",
method, url, headers)
try:
response = getattr(self._session, method)(
url, headers=headers, json=json_data)
_LOGGER.debug("%s %s", response, response.text)
if response and response.status_code < 400:
return response
except RequestException as exc:
_LOGGER.warning("Skybell request exception: %s", exc)
if retry:
self.login()
return self.send_request(method, url, headers, json_data, False)
raise SkybellException(ERROR.REQUEST, "Retry failed") | [
"def",
"send_request",
"(",
"self",
",",
"method",
",",
"url",
",",
"headers",
"=",
"None",
",",
"json_data",
"=",
"None",
",",
"retry",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
"and",
"url",
... | Send requests to Skybell. | [
"Send",
"requests",
"to",
"Skybell",
"."
] | ac966d9f590cda7654f6de7eecc94e2103459eef | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L161-L200 | train | 46,792 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.update_cache | def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | python | def update_cache(self, data):
"""Update a cached value."""
UTILS.update(self._cache, data)
self._save_cache() | [
"def",
"update_cache",
"(",
"self",
",",
"data",
")",
":",
"UTILS",
".",
"update",
"(",
"self",
".",
"_cache",
",",
"data",
")",
"self",
".",
"_save_cache",
"(",
")"
] | Update a cached value. | [
"Update",
"a",
"cached",
"value",
"."
] | ac966d9f590cda7654f6de7eecc94e2103459eef | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L206-L209 | train | 46,793 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.dev_cache | def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache | python | def dev_cache(self, device, key=None):
"""Get a cached value for a device."""
device_cache = self._cache.get(CONST.DEVICES, {}).get(device.device_id)
if device_cache and key:
return device_cache.get(key)
return device_cache | [
"def",
"dev_cache",
"(",
"self",
",",
"device",
",",
"key",
"=",
"None",
")",
":",
"device_cache",
"=",
"self",
".",
"_cache",
".",
"get",
"(",
"CONST",
".",
"DEVICES",
",",
"{",
"}",
")",
".",
"get",
"(",
"device",
".",
"device_id",
")",
"if",
"... | Get a cached value for a device. | [
"Get",
"a",
"cached",
"value",
"for",
"a",
"device",
"."
] | ac966d9f590cda7654f6de7eecc94e2103459eef | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L211-L218 | train | 46,794 |
MisterWil/skybellpy | skybellpy/__init__.py | Skybell.update_dev_cache | def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | python | def update_dev_cache(self, device, data):
"""Update cached values for a device."""
self.update_cache(
{
CONST.DEVICES: {
device.device_id: data
}
}) | [
"def",
"update_dev_cache",
"(",
"self",
",",
"device",
",",
"data",
")",
":",
"self",
".",
"update_cache",
"(",
"{",
"CONST",
".",
"DEVICES",
":",
"{",
"device",
".",
"device_id",
":",
"data",
"}",
"}",
")"
] | Update cached values for a device. | [
"Update",
"cached",
"values",
"for",
"a",
"device",
"."
] | ac966d9f590cda7654f6de7eecc94e2103459eef | https://github.com/MisterWil/skybellpy/blob/ac966d9f590cda7654f6de7eecc94e2103459eef/skybellpy/__init__.py#L220-L227 | train | 46,795 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteInactiveDevicesByQuota | def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also deletes the corresponding
sessions, so if a device comes active again and tries to send you an encrypted
message you will not be able to decrypt it.
The value "0" means no limitations/keep all inactive devices.
It is recommended to always restrict the amount of per-jid inactive devices. If
storage space limitations don't play a role, it is recommended to not restrict the
global amount of inactive devices. Otherwise, the global_max can be used to
control the amount of storage that can be used up by inactive sessions. The
default of 15 per-jid devices is very permissive, but it is not recommended to
decrease that number without a good reason.
This is the recommended way to handle inactive device deletion. For a time-based
alternative, look at the deleteInactiveDevicesByAge method.
"""
if per_jid_max < 1 and global_max < 1:
return
if per_jid_max < 1:
per_jid_max = None
if global_max < 1:
global_max = None
bare_jids = yield self._storage.listJIDs()
if not per_jid_max == None:
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
if len(devices) > per_jid_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(devices.items(), key = lambda device: device[1])
# This gets the first (=oldest) n entries, so that only the
# per_jid_max youngest entries are left.
devices = devices[:-per_jid_max]
# Get the device ids and discard the timestamps.
devices = list(map(lambda device: device[0], devices))
yield self.__deleteInactiveDevices(bare_jid, devices)
if not global_max == None:
all_inactive_devices = []
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
all_inactive_devices.extend(map(
lambda device: (bare_jid, device[0], device[1]),
devices.items()
))
if len(all_inactive_devices) > global_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(all_inactive_devices, key = lambda device: device[2])
# This gets the first (=oldest) n entries, so that only the global_max
# youngest entries are left.
devices = devices[:-global_max]
# Get the list of devices to delete for each jid
delete_devices = {}
for device in devices:
bare_jid = device[0]
device_id = device[1]
delete_devices[bare_jid] = delete_devices.get(bare_jid, [])
delete_devices[bare_jid].append(device_id)
# Now, delete the devices
for bare_jid, devices in delete_devices.items():
yield self.__deleteInactiveDevices(bare_jid, devices) | python | def deleteInactiveDevicesByQuota(self, per_jid_max = 15, global_max = 0):
"""
Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also deletes the corresponding
sessions, so if a device comes active again and tries to send you an encrypted
message you will not be able to decrypt it.
The value "0" means no limitations/keep all inactive devices.
It is recommended to always restrict the amount of per-jid inactive devices. If
storage space limitations don't play a role, it is recommended to not restrict the
global amount of inactive devices. Otherwise, the global_max can be used to
control the amount of storage that can be used up by inactive sessions. The
default of 15 per-jid devices is very permissive, but it is not recommended to
decrease that number without a good reason.
This is the recommended way to handle inactive device deletion. For a time-based
alternative, look at the deleteInactiveDevicesByAge method.
"""
if per_jid_max < 1 and global_max < 1:
return
if per_jid_max < 1:
per_jid_max = None
if global_max < 1:
global_max = None
bare_jids = yield self._storage.listJIDs()
if not per_jid_max == None:
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
if len(devices) > per_jid_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(devices.items(), key = lambda device: device[1])
# This gets the first (=oldest) n entries, so that only the
# per_jid_max youngest entries are left.
devices = devices[:-per_jid_max]
# Get the device ids and discard the timestamps.
devices = list(map(lambda device: device[0], devices))
yield self.__deleteInactiveDevices(bare_jid, devices)
if not global_max == None:
all_inactive_devices = []
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
all_inactive_devices.extend(map(
lambda device: (bare_jid, device[0], device[1]),
devices.items()
))
if len(all_inactive_devices) > global_max:
# This sorts the devices from smaller to bigger timestamp, which means
# from old to young.
devices = sorted(all_inactive_devices, key = lambda device: device[2])
# This gets the first (=oldest) n entries, so that only the global_max
# youngest entries are left.
devices = devices[:-global_max]
# Get the list of devices to delete for each jid
delete_devices = {}
for device in devices:
bare_jid = device[0]
device_id = device[1]
delete_devices[bare_jid] = delete_devices.get(bare_jid, [])
delete_devices[bare_jid].append(device_id)
# Now, delete the devices
for bare_jid, devices in delete_devices.items():
yield self.__deleteInactiveDevices(bare_jid, devices) | [
"def",
"deleteInactiveDevicesByQuota",
"(",
"self",
",",
"per_jid_max",
"=",
"15",
",",
"global_max",
"=",
"0",
")",
":",
"if",
"per_jid_max",
"<",
"1",
"and",
"global_max",
"<",
"1",
":",
"return",
"if",
"per_jid_max",
"<",
"1",
":",
"per_jid_max",
"=",
... | Delete inactive devices by setting a quota. With per_jid_max you can define the
amount of inactive devices that are kept for each jid, with global_max you can
define a global maximum for inactive devices. If any of the quotas is reached,
inactive devices are deleted on an LRU basis. This also deletes the corresponding
sessions, so if a device comes active again and tries to send you an encrypted
message you will not be able to decrypt it.
The value "0" means no limitations/keep all inactive devices.
It is recommended to always restrict the amount of per-jid inactive devices. If
storage space limitations don't play a role, it is recommended to not restrict the
global amount of inactive devices. Otherwise, the global_max can be used to
control the amount of storage that can be used up by inactive sessions. The
default of 15 per-jid devices is very permissive, but it is not recommended to
decrease that number without a good reason.
This is the recommended way to handle inactive device deletion. For a time-based
alternative, look at the deleteInactiveDevicesByAge method. | [
"Delete",
"inactive",
"devices",
"by",
"setting",
"a",
"quota",
".",
"With",
"per_jid_max",
"you",
"can",
"define",
"the",
"amount",
"of",
"inactive",
"devices",
"that",
"are",
"kept",
"for",
"each",
"jid",
"with",
"global_max",
"you",
"can",
"define",
"a",
... | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L766-L849 | train | 46,796 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.deleteInactiveDevicesByAge | def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to delete inactive devices that
were inactive for less than a day. Thus, the minimum value for age_days is 1.
It is recommended to keep inactive devices for a longer period of time (e.g.
multiple months), as it reduces the chance for message loss and doesn't require a
lot of storage.
The recommended alternative to deleting inactive devices by age is to delete them
by count/quota. Look at the deleteInactiveDevicesByQuota method for that variant.
"""
if age_days < 1:
return
now = time.time()
bare_jids = yield self._storage.listJIDs()
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
delete_devices = []
for device, timestamp in list(devices.items()):
elapsed_s = now - timestamp
elapsed_m = elapsed_s / 60
elapsed_h = elapsed_m / 60
elapsed_d = elapsed_h / 24
if elapsed_d >= age_days:
delete_devices.append(device)
if len(delete_devices) > 0:
yield self.__deleteInactiveDevices(bare_jid, delete_devices) | python | def deleteInactiveDevicesByAge(self, age_days):
"""
Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to delete inactive devices that
were inactive for less than a day. Thus, the minimum value for age_days is 1.
It is recommended to keep inactive devices for a longer period of time (e.g.
multiple months), as it reduces the chance for message loss and doesn't require a
lot of storage.
The recommended alternative to deleting inactive devices by age is to delete them
by count/quota. Look at the deleteInactiveDevicesByQuota method for that variant.
"""
if age_days < 1:
return
now = time.time()
bare_jids = yield self._storage.listJIDs()
for bare_jid in bare_jids:
devices = yield self.__loadInactiveDevices(bare_jid)
delete_devices = []
for device, timestamp in list(devices.items()):
elapsed_s = now - timestamp
elapsed_m = elapsed_s / 60
elapsed_h = elapsed_m / 60
elapsed_d = elapsed_h / 24
if elapsed_d >= age_days:
delete_devices.append(device)
if len(delete_devices) > 0:
yield self.__deleteInactiveDevices(bare_jid, delete_devices) | [
"def",
"deleteInactiveDevicesByAge",
"(",
"self",
",",
"age_days",
")",
":",
"if",
"age_days",
"<",
"1",
":",
"return",
"now",
"=",
"time",
".",
"time",
"(",
")",
"bare_jids",
"=",
"yield",
"self",
".",
"_storage",
".",
"listJIDs",
"(",
")",
"for",
"ba... | Delete all inactive devices from the device list storage and cache that are older
then a given number of days. This also deletes the corresponding sessions, so if
a device comes active again and tries to send you an encrypted message you will
not be able to decrypt it. You are not allowed to delete inactive devices that
were inactive for less than a day. Thus, the minimum value for age_days is 1.
It is recommended to keep inactive devices for a longer period of time (e.g.
multiple months), as it reduces the chance for message loss and doesn't require a
lot of storage.
The recommended alternative to deleting inactive devices by age is to delete them
by count/quota. Look at the deleteInactiveDevicesByQuota method for that variant. | [
"Delete",
"all",
"inactive",
"devices",
"from",
"the",
"device",
"list",
"storage",
"and",
"cache",
"that",
"are",
"older",
"then",
"a",
"given",
"number",
"of",
"days",
".",
"This",
"also",
"deletes",
"the",
"corresponding",
"sessions",
"so",
"if",
"a",
"... | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L852-L889 | train | 46,797 |
Syndace/python-omemo | omemo/sessionmanager.py | SessionManager.runInactiveDeviceCleanup | def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
self.__inactive_global_max
)
yield self.deleteInactiveDevicesByAge(self.__inactive_max_age) | python | def runInactiveDeviceCleanup(self):
"""
Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create.
"""
yield self.deleteInactiveDevicesByQuota(
self.__inactive_per_jid_max,
self.__inactive_global_max
)
yield self.deleteInactiveDevicesByAge(self.__inactive_max_age) | [
"def",
"runInactiveDeviceCleanup",
"(",
"self",
")",
":",
"yield",
"self",
".",
"deleteInactiveDevicesByQuota",
"(",
"self",
".",
"__inactive_per_jid_max",
",",
"self",
".",
"__inactive_global_max",
")",
"yield",
"self",
".",
"deleteInactiveDevicesByAge",
"(",
"self",... | Runs both the deleteInactiveDevicesByAge and the deleteInactiveDevicesByQuota
methods with the configuration that was set when calling create. | [
"Runs",
"both",
"the",
"deleteInactiveDevicesByAge",
"and",
"the",
"deleteInactiveDevicesByQuota",
"methods",
"with",
"the",
"configuration",
"that",
"was",
"set",
"when",
"calling",
"create",
"."
] | f99be4715a3fad4d3082f5093aceb2c42385b8bd | https://github.com/Syndace/python-omemo/blob/f99be4715a3fad4d3082f5093aceb2c42385b8bd/omemo/sessionmanager.py#L892-L903 | train | 46,798 |
pjmark/NIMPA | resources/resources.py | get_setup | def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt['HMULIST'] = hrdwr_mu
# Microsoft Visual Studio Compiler version
Cnt['MSVC_VRSN'] = MSVC_VRSN
# GPU related setup
Cnt = get_gpu_constants(Cnt)
if 'PATHTOOLS' in globals() and PATHTOOLS!='': Cnt['PATHTOOLS'] = PATHTOOLS
# image processing setup
if 'RESPATH' in globals() and RESPATH!='': Cnt['RESPATH'] = RESPATH
if 'REGPATH' in globals() and REGPATH!='': Cnt['REGPATH'] = REGPATH
if 'DCM2NIIX' in globals() and DCM2NIIX!='': Cnt['DCM2NIIX'] = DCM2NIIX
# hardware mu-maps
if 'HMUDIR' in globals() and HMUDIR!='': Cnt['HMUDIR'] = HMUDIR
if 'VINCIPATH' in globals() and VINCIPATH!='': Cnt['VINCIPATH'] = VINCIPATH
Cnt['ENBLXNAT'] = ENBLXNAT
Cnt['ENBLAGG'] = ENBLAGG
Cnt['CMPL_DCM2NIIX'] = CMPL_DCM2NIIX
return Cnt | python | def get_setup(Cnt = {}):
'''Return a dictionary of GPU, mu-map hardware and third party set-up.'''
# the name of the folder for NiftyPET tools
Cnt['DIRTOOLS'] = DIRTOOLS
# additional paramteres for compiling tools with cmake
Cnt['CMAKE_TLS_PAR'] = CMAKE_TLS_PAR
# hardware mu-maps
Cnt['HMULIST'] = hrdwr_mu
# Microsoft Visual Studio Compiler version
Cnt['MSVC_VRSN'] = MSVC_VRSN
# GPU related setup
Cnt = get_gpu_constants(Cnt)
if 'PATHTOOLS' in globals() and PATHTOOLS!='': Cnt['PATHTOOLS'] = PATHTOOLS
# image processing setup
if 'RESPATH' in globals() and RESPATH!='': Cnt['RESPATH'] = RESPATH
if 'REGPATH' in globals() and REGPATH!='': Cnt['REGPATH'] = REGPATH
if 'DCM2NIIX' in globals() and DCM2NIIX!='': Cnt['DCM2NIIX'] = DCM2NIIX
# hardware mu-maps
if 'HMUDIR' in globals() and HMUDIR!='': Cnt['HMUDIR'] = HMUDIR
if 'VINCIPATH' in globals() and VINCIPATH!='': Cnt['VINCIPATH'] = VINCIPATH
Cnt['ENBLXNAT'] = ENBLXNAT
Cnt['ENBLAGG'] = ENBLAGG
Cnt['CMPL_DCM2NIIX'] = CMPL_DCM2NIIX
return Cnt | [
"def",
"get_setup",
"(",
"Cnt",
"=",
"{",
"}",
")",
":",
"# the name of the folder for NiftyPET tools",
"Cnt",
"[",
"'DIRTOOLS'",
"]",
"=",
"DIRTOOLS",
"# additional paramteres for compiling tools with cmake",
"Cnt",
"[",
"'CMAKE_TLS_PAR'",
"]",
"=",
"CMAKE_TLS_PAR",
"#... | Return a dictionary of GPU, mu-map hardware and third party set-up. | [
"Return",
"a",
"dictionary",
"of",
"GPU",
"mu",
"-",
"map",
"hardware",
"and",
"third",
"party",
"set",
"-",
"up",
"."
] | 3f4231fed2934a1d92e4cd8e9e153b0118e29d86 | https://github.com/pjmark/NIMPA/blob/3f4231fed2934a1d92e4cd8e9e153b0118e29d86/resources/resources.py#L247-L278 | train | 46,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.