hexsha string | size int64 | ext string | lang string | max_stars_repo_path string | max_stars_repo_name string | max_stars_repo_head_hexsha string | max_stars_repo_licenses list | max_stars_count int64 | max_stars_repo_stars_event_min_datetime string | max_stars_repo_stars_event_max_datetime string | max_issues_repo_path string | max_issues_repo_name string | max_issues_repo_head_hexsha string | max_issues_repo_licenses list | max_issues_count int64 | max_issues_repo_issues_event_min_datetime string | max_issues_repo_issues_event_max_datetime string | max_forks_repo_path string | max_forks_repo_name string | max_forks_repo_head_hexsha string | max_forks_repo_licenses list | max_forks_count int64 | max_forks_repo_forks_event_min_datetime string | max_forks_repo_forks_event_max_datetime string | content string | avg_line_length float64 | max_line_length int64 | alphanum_fraction float64 | qsc_code_num_words_quality_signal int64 | qsc_code_num_chars_quality_signal float64 | qsc_code_mean_word_length_quality_signal float64 | qsc_code_frac_words_unique_quality_signal float64 | qsc_code_frac_chars_top_2grams_quality_signal float64 | qsc_code_frac_chars_top_3grams_quality_signal float64 | qsc_code_frac_chars_top_4grams_quality_signal float64 | qsc_code_frac_chars_dupe_5grams_quality_signal float64 | qsc_code_frac_chars_dupe_6grams_quality_signal float64 | qsc_code_frac_chars_dupe_7grams_quality_signal float64 | qsc_code_frac_chars_dupe_8grams_quality_signal float64 | qsc_code_frac_chars_dupe_9grams_quality_signal float64 | qsc_code_frac_chars_dupe_10grams_quality_signal float64 | qsc_code_frac_chars_replacement_symbols_quality_signal float64 | qsc_code_frac_chars_digital_quality_signal float64 | qsc_code_frac_chars_whitespace_quality_signal float64 | qsc_code_size_file_byte_quality_signal float64 | qsc_code_num_lines_quality_signal float64 | qsc_code_num_chars_line_max_quality_signal float64 | qsc_code_num_chars_line_mean_quality_signal float64 | qsc_code_frac_chars_alphabet_quality_signal float64 | qsc_code_frac_chars_comments_quality_signal float64 | qsc_code_cate_xml_start_quality_signal float64 | qsc_code_frac_lines_dupe_lines_quality_signal float64 | qsc_code_cate_autogen_quality_signal float64 | qsc_code_frac_lines_long_string_quality_signal float64 | qsc_code_frac_chars_string_length_quality_signal float64 | qsc_code_frac_chars_long_word_length_quality_signal float64 | qsc_code_frac_lines_string_concat_quality_signal float64 | qsc_code_cate_encoded_data_quality_signal float64 | qsc_code_frac_chars_hex_words_quality_signal float64 | qsc_code_frac_lines_prompt_comments_quality_signal float64 | qsc_code_frac_lines_assert_quality_signal float64 | qsc_codepython_cate_ast_quality_signal float64 | qsc_codepython_frac_lines_func_ratio_quality_signal float64 | qsc_codepython_cate_var_zero_quality_signal bool | qsc_codepython_frac_lines_pass_quality_signal float64 | qsc_codepython_frac_lines_import_quality_signal float64 | qsc_codepython_frac_lines_simplefunc_quality_signal float64 | qsc_codepython_score_lines_no_logic_quality_signal float64 | qsc_codepython_frac_lines_print_quality_signal float64 | qsc_code_num_words int64 | qsc_code_num_chars int64 | qsc_code_mean_word_length int64 | qsc_code_frac_words_unique null | qsc_code_frac_chars_top_2grams int64 | qsc_code_frac_chars_top_3grams int64 | qsc_code_frac_chars_top_4grams int64 | qsc_code_frac_chars_dupe_5grams int64 | qsc_code_frac_chars_dupe_6grams int64 | qsc_code_frac_chars_dupe_7grams int64 | qsc_code_frac_chars_dupe_8grams int64 | qsc_code_frac_chars_dupe_9grams int64 | qsc_code_frac_chars_dupe_10grams int64 | qsc_code_frac_chars_replacement_symbols int64 | qsc_code_frac_chars_digital int64 | qsc_code_frac_chars_whitespace int64 | qsc_code_size_file_byte int64 | qsc_code_num_lines int64 | qsc_code_num_chars_line_max int64 | qsc_code_num_chars_line_mean int64 | qsc_code_frac_chars_alphabet int64 | qsc_code_frac_chars_comments int64 | qsc_code_cate_xml_start int64 | qsc_code_frac_lines_dupe_lines int64 | qsc_code_cate_autogen int64 | qsc_code_frac_lines_long_string int64 | qsc_code_frac_chars_string_length int64 | qsc_code_frac_chars_long_word_length int64 | qsc_code_frac_lines_string_concat null | qsc_code_cate_encoded_data int64 | qsc_code_frac_chars_hex_words int64 | qsc_code_frac_lines_prompt_comments int64 | qsc_code_frac_lines_assert int64 | qsc_codepython_cate_ast int64 | qsc_codepython_frac_lines_func_ratio int64 | qsc_codepython_cate_var_zero int64 | qsc_codepython_frac_lines_pass int64 | qsc_codepython_frac_lines_import int64 | qsc_codepython_frac_lines_simplefunc int64 | qsc_codepython_score_lines_no_logic int64 | qsc_codepython_frac_lines_print int64 | effective string | hits int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
4af4467fd35af514b97c578be7c2435c2bc0f5b0 | 8,316 | py | Python | stix2patterns/grammars/STIXPatternListener.py | delliott90/cti-pattern-validator | cc33861acafa4888e50726b74a611fe20a6f0971 | [
"BSD-3-Clause"
] | null | null | null | stix2patterns/grammars/STIXPatternListener.py | delliott90/cti-pattern-validator | cc33861acafa4888e50726b74a611fe20a6f0971 | [
"BSD-3-Clause"
] | null | null | null | stix2patterns/grammars/STIXPatternListener.py | delliott90/cti-pattern-validator | cc33861acafa4888e50726b74a611fe20a6f0971 | [
"BSD-3-Clause"
] | null | null | null | # Generated from STIXPattern.g4 by ANTLR 4.7.1
from antlr4 import *
# This class defines a complete listener for a parse tree produced by STIXPatternParser.
class STIXPatternListener(ParseTreeListener):
# Enter a parse tree produced by STIXPatternParser#pattern.
def enterPattern(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#pattern.
def exitPattern(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressions.
def enterObservationExpressions(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressions.
def exitObservationExpressions(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionOr.
def enterObservationExpressionOr(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionOr.
def exitObservationExpressionOr(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionAnd.
def enterObservationExpressionAnd(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionAnd.
def exitObservationExpressionAnd(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionRepeated.
def enterObservationExpressionRepeated(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionRepeated.
def exitObservationExpressionRepeated(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionSimple.
def enterObservationExpressionSimple(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionSimple.
def exitObservationExpressionSimple(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionCompound.
def enterObservationExpressionCompound(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionCompound.
def exitObservationExpressionCompound(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionWithin.
def enterObservationExpressionWithin(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionWithin.
def exitObservationExpressionWithin(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#observationExpressionStartStop.
def enterObservationExpressionStartStop(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#observationExpressionStartStop.
def exitObservationExpressionStartStop(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#comparisonExpression.
def enterComparisonExpression(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#comparisonExpression.
def exitComparisonExpression(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#comparisonExpressionAnd.
def enterComparisonExpressionAnd(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#comparisonExpressionAnd.
def exitComparisonExpressionAnd(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestEqual.
def enterPropTestEqual(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestEqual.
def exitPropTestEqual(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestOrder.
def enterPropTestOrder(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestOrder.
def exitPropTestOrder(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestSet.
def enterPropTestSet(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestSet.
def exitPropTestSet(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestLike.
def enterPropTestLike(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestLike.
def exitPropTestLike(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestRegex.
def enterPropTestRegex(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestRegex.
def exitPropTestRegex(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestIsSubset.
def enterPropTestIsSubset(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestIsSubset.
def exitPropTestIsSubset(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestIsSuperset.
def enterPropTestIsSuperset(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestIsSuperset.
def exitPropTestIsSuperset(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#propTestParen.
def enterPropTestParen(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#propTestParen.
def exitPropTestParen(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#startStopQualifier.
def enterStartStopQualifier(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#startStopQualifier.
def exitStartStopQualifier(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#withinQualifier.
def enterWithinQualifier(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#withinQualifier.
def exitWithinQualifier(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#repeatedQualifier.
def enterRepeatedQualifier(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#repeatedQualifier.
def exitRepeatedQualifier(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#objectPath.
def enterObjectPath(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#objectPath.
def exitObjectPath(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#objectType.
def enterObjectType(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#objectType.
def exitObjectType(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#firstPathComponent.
def enterFirstPathComponent(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#firstPathComponent.
def exitFirstPathComponent(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#indexPathStep.
def enterIndexPathStep(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#indexPathStep.
def exitIndexPathStep(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#pathStep.
def enterPathStep(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#pathStep.
def exitPathStep(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#keyPathStep.
def enterKeyPathStep(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#keyPathStep.
def exitKeyPathStep(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#setLiteral.
def enterSetLiteral(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#setLiteral.
def exitSetLiteral(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#primitiveLiteral.
def enterPrimitiveLiteral(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#primitiveLiteral.
def exitPrimitiveLiteral(self, ctx):
pass
# Enter a parse tree produced by STIXPatternParser#orderableLiteral.
def enterOrderableLiteral(self, ctx):
pass
# Exit a parse tree produced by STIXPatternParser#orderableLiteral.
def exitOrderableLiteral(self, ctx):
pass
| 29.076923 | 88 | 0.723184 | 834 | 8,316 | 7.211031 | 0.147482 | 0.062853 | 0.104756 | 0.18856 | 0.753409 | 0.753409 | 0.747256 | 0.746425 | 0.532424 | 0.532424 | 0 | 0.000774 | 0.223425 | 8,316 | 285 | 89 | 29.178947 | 0.930474 | 0.512747 | 0 | 0.492063 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.492063 | false | 0.492063 | 0.007937 | 0 | 0.507937 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 8 |
ab041351dcfae156693c62c6cfa24418a0182cd1 | 11,236 | py | Python | tests/test_hyperband_stopping.py | dannygoldstein/sweeps | 9afd1eb87af59a2b8e1020587876fe944b8e41ad | [
"MIT"
] | null | null | null | tests/test_hyperband_stopping.py | dannygoldstein/sweeps | 9afd1eb87af59a2b8e1020587876fe944b8e41ad | [
"MIT"
] | null | null | null | tests/test_hyperband_stopping.py | dannygoldstein/sweeps | 9afd1eb87af59a2b8e1020587876fe944b8e41ad | [
"MIT"
] | null | null | null | from sweeps import hyperband_stopping as search
def test_hyperband_min_iter_bands():
hbet = search.HyperbandEarlyTerminate.init_from_min_iter(3, 3)
assert hbet.bands[:3] == [3, 9, 27]
def test_hyperband_max_iter_bands():
hbet = search.HyperbandEarlyTerminate.init_from_max_iter(81, 3, 3)
assert hbet.bands[:3] == [3, 9, 27]
class Run(object):
def __init__(self, name, state, history):
self.name = name
self.state = state
self.history = history
def test_init_from_max_iter():
et = search.HyperbandEarlyTerminate.init_from_max_iter(18, 3, 2)
assert et.bands == [2, 6]
def test_single_run():
et = search.HyperbandEarlyTerminate.init_from_max_iter(18, 3, 2)
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"running",
[
{"loss": 10},
{"loss": 9},
{"loss": 8},
{"loss": 7},
{"loss": 6},
{"loss": 5},
{"loss": 4},
{"loss": 3},
{"loss": 2},
{"loss": 1},
],
)
],
)
assert stopped == []
def test_2runs_band1_stop():
et = search.HyperbandEarlyTerminate.init_from_max_iter(18, 3, 2)
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"running",
[
{"loss": 10},
{"loss": 9},
{"loss": 8},
{"loss": 7},
{"loss": 6},
{"loss": 5},
{"loss": 4},
{"loss": 3},
{"loss": 2},
{"loss": 1},
],
),
Run(
"b",
"running",
[
{"loss": 10},
{"loss": 10},
{"loss": 10},
],
),
],
)
assert stopped == ["b"]
def test_2runs_band1_pass():
et = search.HyperbandEarlyTerminate.init_from_max_iter(18, 3, 2)
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"running",
[
{"loss": 10},
{"loss": 9},
{"loss": 8},
{"loss": 7},
{"loss": 6},
{"loss": 5},
{"loss": 4},
{"loss": 3},
{"loss": 2},
{"loss": 1},
],
),
Run(
"b",
"running",
[
{"loss": 10},
{"loss": 10},
{"loss": 6},
],
),
],
)
assert stopped == []
def test_skipped_steps():
et = search.HyperbandEarlyTerminate.init_from_max_iter(18, 3, 2)
et._load_metric_name_and_goal({"metric": {"name": "loss", "goal": "minimize"}})
line = et._load_run_metric_history(
Run(
"a",
"running",
[
{"loss": 10},
{"a": 9},
{"a": 8},
{"a": 7},
{"loss": 6},
{"a": 5},
{"a": 4},
{"a": 3},
{"a": 2},
{"loss": 1},
],
)
)
assert line == [10, 6, 1]
def test_2runs_band1_stop_2():
et = search.HyperbandEarlyTerminate.init_from_max_iter(5, 3, 2)
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"stopped",
[
{"loss": 10},
{"loss": 9},
{"loss": 8},
{"loss": 7},
{"loss": 6},
{"loss": 5},
{"loss": 4},
{"loss": 3},
{"loss": 2},
{"loss": 1},
],
),
Run(
"b",
"running",
[
{"loss": 10},
{"loss": 10},
{"loss": 10},
],
),
],
)
assert stopped == ["b"]
def test_5runs_band1_stop_2():
et = search.HyperbandEarlyTerminate.init_from_max_iter(5, 2, 2)
# bands are at 1 and 2
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"stopped", # This wont be stopped because already stopped
[
{"loss": 10},
{"loss": 9},
],
),
Run(
"b",
"running", # This should be stopped
[
{"loss": 10},
{"loss": 10},
],
),
Run(
"c",
"running", # This passes band 1 but not band 2
[
{"loss": 10},
{"loss": 8},
{"loss": 8},
],
),
Run(
"d",
"running",
[
{"loss": 10},
{"loss": 7},
{"loss": 7},
],
),
Run(
"e",
"finished",
[
{"loss": 10},
{"loss": 6},
{"loss": 6},
],
),
],
)
assert stopped == ["b", "c"]
def test_5runs_band1_stop_2_1stnoband():
et = search.HyperbandEarlyTerminate.init_from_max_iter(5, 2, 2)
# bands are at 1 and 2
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"running", # This wont be stopped because not at band 1
[
{"loss": 10},
],
),
Run(
"b",
"running", # This should be stopped
[
{"loss": 10},
{"loss": 10},
],
),
Run(
"c",
"running", # This passes band 1 but not band 2
[
{"loss": 10},
{"loss": 8},
{"loss": 8},
],
),
Run(
"d",
"running",
[
{"loss": 10},
{"loss": 7},
{"loss": 7},
],
),
Run(
"e",
"finished",
[
{"loss": 10},
{"loss": 6},
{"loss": 6},
],
),
],
)
assert stopped == ["b", "c"]
def test_eta_3():
et = search.HyperbandEarlyTerminate.init_from_max_iter(9, 3, 2)
# bands are at 1 and 3, thresholds are 7 and 4
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "minimize",
}
},
[
Run(
"a",
"stopped", # This wont be stopped because already stopped
[
{"loss": 10},
{"loss": 9},
],
),
Run(
"b",
"running", # This should be stopped
[
{"loss": 10},
{"loss": 10},
],
),
Run(
"c",
"running", # This fails the first threeshold but snuck in so we wont kill
[
{"loss": 10},
{"loss": 8},
{"loss": 8},
{"loss": 3},
],
),
Run(
"d",
"running",
[
{"loss": 10},
{"loss": 7},
{"loss": 7},
{"loss": 4},
],
),
Run(
"e",
"running", # this passes band 1 but doesn't pass band 2
[
{"loss": 10},
{"loss": 6},
{"loss": 6},
{"loss": 6},
],
),
],
)
assert stopped == ["b", "e"]
def test_eta_3_max():
et = search.HyperbandEarlyTerminate.init_from_max_iter(9, 3, 2)
# bands are at 1 and 3, thresholds are 7 and 4
stopped, lines = et.stop_runs(
{
"metric": {
"name": "loss",
"goal": "maximize",
}
},
[
Run(
"a",
"stopped", # This wont be stopped because already stopped
[
{"loss": -10},
{"loss": -9},
],
),
Run(
"b",
"running", # This should be stopped
[
{"loss": -10},
{"loss": -10},
],
),
Run(
"c",
"running", # This fails the first threeshold but snuck in so we wont kill
[
{"loss": -10},
{"loss": -8},
{"loss": -8},
{"loss": -3},
],
),
Run(
"d",
"running",
[
{"loss": -10},
{"loss": -7},
{"loss": -7},
{"loss": -4},
],
),
Run(
"e",
"running", # this passes band 1 but doesn't pass band 2
[
{"loss": -10},
{"loss": -6},
{"loss": -6},
{"loss": -6},
],
),
],
)
assert stopped == ["b", "e"]
| 25.536364 | 90 | 0.281239 | 811 | 11,236 | 3.775586 | 0.110974 | 0.072502 | 0.094709 | 0.145003 | 0.861528 | 0.82887 | 0.820052 | 0.787394 | 0.787394 | 0.773024 | 0 | 0.052564 | 0.581791 | 11,236 | 439 | 91 | 25.594533 | 0.599064 | 0.060253 | 0 | 0.738386 | 0 | 0 | 0.086622 | 0 | 0 | 0 | 0 | 0 | 0.02934 | 1 | 0.031785 | false | 0.002445 | 0.002445 | 0 | 0.036675 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
ab3f4504226284f22de934f2f3a0bbde6a06ac59 | 5,399 | py | Python | bilevel_imaging_toolbox/cuda_solvers.py | dvillacis/BilevelImagingToolbox | 99b259499b68141283601ccddb5732bb38f44d24 | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2020-11-13T07:44:26.000Z | 2021-06-01T21:09:00.000Z | bilevel_imaging_toolbox/cuda_solvers.py | dvillacis/BilevelImagingToolbox | 99b259499b68141283601ccddb5732bb38f44d24 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | bilevel_imaging_toolbox/cuda_solvers.py | dvillacis/BilevelImagingToolbox | 99b259499b68141283601ccddb5732bb38f44d24 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2020-09-09T15:34:18.000Z | 2020-09-09T15:34:18.000Z | import numpy as np
import timeit
import os
# PyCUDA imports
import pycuda.autoinit
import pycuda.driver as drv
from pycuda.compiler import SourceModule
def chambolle_pock_ROF_CUDA(image, clambda, tau, sigma, iters=100):
r""" 2D ROF CUDA solver using Chambolle-Pock Method
Parameters
----------
image : numpy array
The noisy image we are processing
clambda : float
The non-negative weight in the optimization problem
tau : float
Parameter of the proximal operator
iters : int
Number of iterations allowed
"""
print("2D Primal-Dual ROF CUDA solver using Chambolle-Pock method")
start_time = timeit.default_timer()
(h,w) = image.shape
dim = w*h
nc = 1
# Load Modules
init_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/rof/rof_init.cu','r').read())
primal_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/rof/rof_primal.cu','r').read())
dual_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/rof/rof_dual.cu','r').read())
extrapolate_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/rof/rof_extrapolate.cu','r').read())
solution_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/rof/rof_solution.cu','r').read())
# Memory Allocation
nbyted = image.astype(np.float32).nbytes
d_imgInOut = drv.mem_alloc(nbyted)
d_x = drv.mem_alloc(nbyted)
d_xbar = drv.mem_alloc(nbyted)
d_xcur = drv.mem_alloc(nbyted)
d_y1 = drv.mem_alloc(nbyted)
d_y2 = drv.mem_alloc(nbyted)
# Variables
w = np.int32(w)
h = np.int32(h)
nc = np.int32(nc)
sigma = np.float32(sigma)
tau = np.float32(tau)
clambda = np.float32(clambda)
# Copy host memory
h_img = image.astype(np.float32)
drv.memcpy_htod(d_imgInOut,h_img)
# Launch kernel
block = (16,16,1)
grid = (np.ceil((w+block[0]-1)/block[0]),np.ceil((h+block[1]-1)/block[1]))
grid = (int(grid[0]),int(grid[1]))
# Function definition
init_func = init_module.get_function('init')
primal_func = primal_module.get_function('primal')
dual_func = dual_module.get_function('dual')
extrapolate_func = extrapolate_module.get_function('extrapolate')
solution_func = solution_module.get_function('solution')
# Initialization
init_func(d_xbar, d_xcur, d_x, d_y1, d_y2, d_imgInOut, np.int32(w), np.int32(h), np.int32(nc), block=block, grid=grid)
for i in range(iters):
primal_func(d_y1,d_y2,d_xbar,sigma,w,h,nc,block=block,grid=grid)
dual_func(d_x,d_xcur,d_y1,d_y2,d_imgInOut,tau,clambda,w,h,nc,block=block,grid=grid)
extrapolate_func(d_xbar,d_xcur,d_x,np.float32(0.5),w,h,nc,block=block,grid=grid)
solution_func(d_imgInOut,d_x,w,h,nc,block=block,grid=grid)
drv.memcpy_dtoh(h_img,d_imgInOut)
print("Finished Chambolle-Pock ROF CUDA denoising in %d iterations and %f sec"%(iters,timeit.default_timer()-start_time))
return(h_img,0)
def chambolle_pock_TVl1_CUDA(image, clambda, tau, sigma, iters=100):
r""" 2D ROF CUDA solver using Chambolle-Pock Method
Parameters
----------
image : numpy array
The noisy image we are processing
clambda : float
The non-negative weight in the optimization problem
tau : float
Parameter of the proximal operator
iters : int
Number of iterations allowed
"""
print("2D Primal-Dual TV-l1 CUDA solver using Chambolle-Pock method")
start_time = timeit.default_timer()
(h,w) = image.shape
dim = w*h
nc = 1
# Load Modules
init_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/tvl1/tvl1_init.cu','r').read())
primal_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/tvl1/tvl1_primal.cu','r').read())
dual_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/tvl1/tvl1_dual.cu','r').read())
extrapolate_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/tvl1/tvl1_extrapolate.cu','r').read())
solution_module = SourceModule(open('../bilevel_imaging_toolbox/cuda/tvl1/tvl1_solution.cu','r').read())
# Memory Allocation
nbyted = image.astype(np.float32).nbytes
d_imgInOut = drv.mem_alloc(nbyted)
d_x = drv.mem_alloc(nbyted)
d_xbar = drv.mem_alloc(nbyted)
d_xcur = drv.mem_alloc(nbyted)
d_y1 = drv.mem_alloc(nbyted)
d_y2 = drv.mem_alloc(nbyted)
# Copy host memory
h_img = image.astype(np.float32)
drv.memcpy_htod(d_imgInOut,h_img)
# Launch kernel
block = (16,16,1)
grid = (np.ceil((w+block[0]-1)/block[0]),np.ceil((h+block[1]-1)/block[1]))
grid = (int(grid[0]),int(grid[1]))
# Function definition
init_func = init_module.get_function('init')
primal_func = primal_module.get_function('primal')
dual_func = dual_module.get_function('dual')
extrapolate_func = extrapolate_module.get_function('extrapolate')
solution_func = solution_module.get_function('solution')
# Initialization
init_func(d_xbar, d_xcur, d_x, d_y1, d_y2, d_imgInOut, np.int32(w), np.int32(h), np.int32(nc), block=block, grid=grid)
w = np.int32(w)
h = np.int32(h)
nc = np.int32(nc)
sigma = np.float32(sigma)
tau = np.float32(tau)
clambda = np.float32(clambda)
for i in range(iters):
primal_func(d_y1,d_y2,d_xbar,sigma,w,h,nc,block=block,grid=grid)
dual_func(d_x,d_xcur,d_y1,d_y2,d_imgInOut,tau,clambda,w,h,nc,block=block,grid=grid)
extrapolate_func(d_xbar,d_xcur,d_x,np.float32(0.5),w,h,nc,block=block,grid=grid)
solution_func(d_imgInOut,d_x,w,h,nc,block=block,grid=grid)
drv.memcpy_dtoh(h_img,d_imgInOut)
print("Finished Chambolle-Pock TV-l1 CUDA denoising in %d iterations and %f sec"%(iters,timeit.default_timer()-start_time))
return(h_img,0)
| 31.758824 | 124 | 0.740322 | 892 | 5,399 | 4.288117 | 0.140135 | 0.006275 | 0.03451 | 0.053333 | 0.951373 | 0.951373 | 0.951373 | 0.950588 | 0.950588 | 0.932288 | 0 | 0.025261 | 0.112799 | 5,399 | 169 | 125 | 31.946746 | 0.773278 | 0.15614 | 0 | 0.744681 | 0 | 0 | 0.184933 | 0.111136 | 0 | 0 | 0 | 0 | 0 | 1 | 0.021277 | false | 0 | 0.06383 | 0 | 0.085106 | 0.042553 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
db77249468fabbebc5953d444234d96f1cb678a3 | 82,345 | py | Python | fishES.py | invernie/GA-for-evolutionary-landscapes | 8ac865a3cd8db911bc5ad305c14eaaff39a92258 | [
"CC0-1.0"
] | null | null | null | fishES.py | invernie/GA-for-evolutionary-landscapes | 8ac865a3cd8db911bc5ad305c14eaaff39a92258 | [
"CC0-1.0"
] | null | null | null | fishES.py | invernie/GA-for-evolutionary-landscapes | 8ac865a3cd8db911bc5ad305c14eaaff39a92258 | [
"CC0-1.0"
] | null | null | null | from __future__ import division
# extracts strategy frequency for the three result categories (ESS, ES and other). funtype = type of ranking (0 = linear, 1 = exponential, 2 = unspecified); fmin = min solution frequency in population before it is considered predominant in any given cycle
def go(Sel, funtype = 2, fmin = 0.80):
import shelve, os.path
import numpy as np
# uncomment this and change file to .pyx to work in Cython
#cdef int My, Ny, ay, muy, hy, rply, muty, seed, yrec, yL, ESS, ES, endy, totSeeds
# parameter space explored in the simulations
a_range = [0,5,10,15,20]
Mrange = [50,100,200]
mutrange = ['pc','pl']
rplrange = ['det', 'fifo']
murange = [1,3,4,7,9]
# totSeeds corresponds to:
# totSeeds = len(Mrange)*len(Nrange)*len(mutrange)*len(murange)*len(rplrange)*len(hrange)*yL
totSeeds = 7200 # tot simulations per combination of parameters, for each value used to seed the random number generators
yrec = 50 # n of generations at the end of the simulation in which data have been collected
iESS = 32 # ESS index in list generated through itertool
iES1 = 16 # index of the first strategy in the ES set
iES2 = 48
filepath = "D:/" # path from where results are uploaded
pathToSave = "D:/" # path where results of extraction are saved
logfile = "logwritestrat.txt" # log of missing files (if code has run smoothly, it will be empty)
if Sel == "tr" :
hrange = [10,20,30,50]
yL = 6 # yL is the n of rows in the EsSMat matrix, matching the length of the longest parameter range
elif Sel == "kt":
krange = [2,3,5,7]
yL = 6
elif Sel == "rank":
if funtype == 0:
funtype = "lin"
wrange = [55, 60, 64, 69]
elif funtype == 1:
funtype = "exp"
wrange = [55, 60, 80, 89]
else:
raise NameError("Function type needs to be specified correctly")
yL = 6
elif Sel == "rwheel":
wrange = [69,80,89,100]
yL = 6
else:
raise NameError("No selection method with this name")
#proportion of sims where ESS or ES reaches fmin, calculated along one parameter dimension and averaged across seeds
EsSMat = np.zeros([yL,30], dtype = 'float64')
#proportion of sims where ESS or ES reaches fmin in each Sel method, averaged across seed
seedTotMat = np.zeros([2,10], dtype = 'float64')
#store data values individually to look at distribution ([0] ESS [1] ES [2] other)
dtVc = np.zeros(3,dtype = 'int32')
asEsSMat = np.zeros([2,10], dtype = 'float64')
stot1 = 0
sess1 = 0
ses1 = 0
r = 0
for ay in range(5):
print(r) # check if it's running
r += 1
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for rply in range(2):
if Sel == "tr":
for hy in range(4):
if M == 50:
Nrange = [2,5,10,12,50,1]
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r') # opened in read-only mode
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
if ESS == 1:
dtVc [0] += 1
elif ES == 1:
dtVc [1] += 1
else:
dtVc [2] += 1
asEsSMat[0,seed] += ESS
asEsSMat[1,seed] += ES
seedTotMat[0,seed] += ESS
seedTotMat[1,seed] += ES
resdt.close()
sess1+=ESS
ses1+=ES
stot1+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "kt":
for ky in range(4):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 0
ES = 0
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
if ESS == 1:
dtVc [0] += 1
elif ES== 1:
dtVc [1] += 1
else:
dtVc [2] += 1
asEsSMat[0,seed] += ESS
asEsSMat[1,seed] += ES
seedTotMat[0,seed] += ESS
seedTotMat[1,seed] += ES
resdt.close()
sess1+=ESS
ses1+=ES
stot1+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rank":
for wy in range(4):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
if ESS == 1:
dtVc [0] += 1
elif ES== 1:
dtVc [1] += 1
else:
dtVc [2] += 1
asEsSMat[0,seed] += ESS
asEsSMat[1,seed] += ES
seedTotMat[0,seed] += ESS
seedTotMat[1,seed] += ES
resdt.close()
sess1+=ESS
ses1+=ES
stot1+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rwheel":
for wy in range(4):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
if ESS == 1:
dtVc [0] += 1
elif ES== 1:
dtVc [1] += 1
else:
dtVc [2] += 1
asEsSMat[0,seed] += ESS
asEsSMat[1,seed] += ES
seedTotMat[0,seed] += ESS
seedTotMat[1,seed] += ES
resdt.close()
sess1+=ESS
ses1+=ES
stot1+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
#scaled by tot n of sims per seed per value of the parameter under evaluation
divisor_a = totSeeds/len(a_range)
asEsSMat = asEsSMat/divisor_a
EsSMat [ay,0] = sum(asEsSMat [0,:])/10
EsSMat [ay,1] = np.std(asEsSMat [0,:])
EsSMat [ay,2] = sum(asEsSMat [1,:])/10
EsSMat [ay,3] = np.std(asEsSMat [1,:])
#check same n of simulations is opened for each par value,
#same n of ESS and ES cases are reached (i.e. in our analysis we are looking at
#differences in the distribution) and that we are dividing for the correct n of
#parameter values to calculate frequencies
print(stot1,sess1,ses1, "`divisor for a is : " + str(divisor_a))
# statistics on tot convergences to each solution type for this selection method
## ave n of convergences to ESS across seeds
seedTotMat = seedTotMat/(totSeeds)
EsSMat [0,28] = sum(seedTotMat [0,:])/10
## sd
EsSMat [0,29] = np.std(seedTotMat [0,:])
## ave n of convergences to ES across seeds
EsSMat [1,28] = sum(seedTotMat [1,:])/10
## sd
EsSMat [1,29] = np.std(seedTotMat [1,:])
# tot number of convergences to each solution type for this selection method
if funtype == "lin":
dname = pathToSave + 'datadistr-' + Sel + 'l'
elif funtype == "exp":
dname = pathToSave + 'datadistr-' + Sel + 'e'
else:
dname = pathToSave + 'datadistr-' + Sel
distDt = shelve.open(dname)
distDt ['dt'] = dtVc
distDt.close()
MsEsSMat = np.zeros([2,10], dtype = 'float64')
stot2 = 0
sess2 = 0
ses2 = 0
for My in range(3):
for seed in range(10):
for ay in range(5):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for rply in range(2):
if Sel == "tr":
#tr sims run without "from __future__ import division - rounding of N to smallest integer
if M == 50:
Nrange = [2,5,10,12,50,1]
for hy in range(4):
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
MsEsSMat[0,seed] += ESS
MsEsSMat[1,seed] += ES
resdt.close()
sess2+=ESS
ses2+=ES
stot2+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "kt":
for ky in range(4):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
MsEsSMat[0,seed] += ESS
MsEsSMat[1,seed] += ES
resdt.close()
sess2+=ESS
ses2+=ES
stot2+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rank":
for wy in range(4):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
MsEsSMat[0,seed] += ESS
MsEsSMat[1,seed] += ES
resdt.close()
sess2+=ESS
ses2+=ES
stot2+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rwheel":
for wy in range(4):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
MsEsSMat[0,seed] += ESS
MsEsSMat[1,seed] += ES
resdt.close()
sess2+=ESS
ses2+=ES
stot2+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor_M = totSeeds/len(Mrange)
MsEsSMat = MsEsSMat/divisor_M
EsSMat [My,4] = sum(MsEsSMat [0,:])/10
EsSMat [My,5] = np.std(MsEsSMat [0,:])
EsSMat [My,6] = sum(MsEsSMat [1,:])/10
EsSMat [My,7] = np.std(MsEsSMat [1,:])
print(stot2,sess2,ses2, "divisor for M is : " + str(divisor_M))
NsEsSMat = np.zeros([2,10], dtype = 'float64')
stot3 = 0
sess3 = 0
ses3 = 0
for Ny in range(6):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for ay in range(5):
for muty in range(2):
for muy in range(5):
for rply in range(2):
if Sel == "tr":
if M == 50:
Nrange = [2,5,10,12,50,1]
for hy in range(4):
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
for seed in range(10):
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
NsEsSMat[0,seed] += ESS
NsEsSMat[1,seed] += ES
resdt.close()
sess3+=ESS
ses3+=ES
stot3+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "kt":
for ky in range(4):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
for seed in range(10):
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
NsEsSMat[0,seed] += ESS
NsEsSMat[1,seed] += ES
resdt.close()
sess3+=ESS
ses3+=ES
stot3+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rank":
for wy in range(4):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
for seed in range(10):
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
NsEsSMat[0,seed] += ESS
NsEsSMat[1,seed] += ES
resdt.close()
sess3+=ESS
ses3+=ES
stot3+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rwheel":
for wy in range(4):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
for seed in range(10):
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
NsEsSMat[0,seed] += ESS
NsEsSMat[1,seed] += ES
resdt.close()
sess3+=ESS
ses3+=ES
stot3+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor_N = totSeeds/len(Nrange)
NsEsSMat = NsEsSMat/divisor_N
EsSMat [Ny,8] = sum(NsEsSMat [0,:])/10
EsSMat [Ny,9] = np.std(NsEsSMat [0,:])
EsSMat [Ny,10] = sum(NsEsSMat [1,:])/10
EsSMat [Ny,11] = np.std(NsEsSMat [1,:])
print(stot3,sess3,ses3, "divisor for N is : " + str(divisor_N))
mutsEsSMat = np.zeros([2,10], dtype = 'float64')
stot4 = 0
sess4 = 0
ses4 = 0
for muty in range(2):
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for ay in range(5):
for muy in range(5):
for rply in range(2):
if Sel == "tr":
if M == 50:
Nrange = [2,5,10,12,50,1]
for hy in range(4):
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
mutsEsSMat[0,seed] += ESS
mutsEsSMat[1,seed] += ES
resdt.close()
sess4+=ESS
ses4+=ES
stot4+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "kt":
for ky in range(4):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
mutsEsSMat[0,seed] += ESS
mutsEsSMat[1,seed] += ES
resdt.close()
sess4+=ESS
ses4+=ES
stot4+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rank":
for wy in range(4):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
mutsEsSMat[0,seed] += ESS
mutsEsSMat[1,seed] += ES
resdt.close()
sess4+=ESS
ses4+=ES
stot4+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rwheel":
for wy in range(4):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
mutsEsSMat[0,seed] += ESS
mutsEsSMat[1,seed] += ES
resdt.close()
sess4+=ESS
ses4+=ES
stot4+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor_mut = totSeeds/len(mutrange)
mutsEsSMat = mutsEsSMat/divisor_mut
EsSMat [muty,12] = sum(mutsEsSMat [0,:])/10
EsSMat [muty,13] = np.std(mutsEsSMat [0,:])
EsSMat [muty,14] = sum(mutsEsSMat [1,:])/10
EsSMat [muty,15] = np.std(mutsEsSMat [1,:])
print(stot4,sess4,ses4, "divisor for mut is " + str(divisor_mut))
musEsSMat = np.zeros([2,10], dtype = 'float64')
stot5 = 0
sess5 = 0
ses5 = 0
for muy in range(5):
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for ay in range(5):
for rply in range(2):
if Sel == "tr":
if M == 50:
Nrange = [2,5,10,12,50,1]
for hy in range(4):
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
musEsSMat[0,seed] += ESS
musEsSMat[1,seed] += ES
resdt.close()
sess5+=ESS
ses5+=ES
stot5+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "kt":
for ky in range(4):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
musEsSMat[0,seed] += ESS
musEsSMat[1,seed] += ES
resdt.close()
sess5+=ESS
ses5+=ES
stot5+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rank":
for wy in range(4):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
musEsSMat[0,seed] += ESS
musEsSMat[1,seed] += ES
resdt.close()
sess5+=ESS
ses5+=ES
stot5+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rwheel":
for wy in range(4):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
musEsSMat[0,seed] += ESS
musEsSMat[1,seed] += ES
resdt.close()
sess5+=ESS
ses5+=ES
stot5+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor_mu = totSeeds/len(murange)
musEsSMat = musEsSMat/divisor_mu
EsSMat [muy,16] = sum(musEsSMat [0,:])/10
EsSMat [muy,17] = np.std(musEsSMat [0,:])
EsSMat [muy,18] = sum(musEsSMat [1,:])/10
EsSMat [muy,19] = np.std(musEsSMat [1,:])
print(stot5,sess5,ses5, "divisor for mu is " + str(divisor_mu))
rplsEsSMat = np.zeros([2,10], dtype = 'float64')
stot6 = 0
sess6 = 0
ses6 = 0
for rply in range(2):
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for ay in range(5):
if Sel == "tr":
if M == 50:
Nrange = [2,5,10,12,50,1]
for hy in range(4):
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
rplsEsSMat[0,seed] += ESS
rplsEsSMat[1,seed] += ES
resdt.close()
sess6+=ESS
ses6+=ES
stot6+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "kt":
for ky in range(4):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
rplsEsSMat[0,seed] += ESS
rplsEsSMat[1,seed] += ES
resdt.close()
sess6+=ESS
ses6+=ES
stot6+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rank":
for wy in range(4):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
rplsEsSMat[0,seed] += ESS
rplsEsSMat[1,seed] += ES
resdt.close()
sess6+=ESS
ses6+=ES
stot6+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
elif Sel == "rwheel":
for wy in range(4):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
rplsEsSMat[0,seed] += ESS
rplsEsSMat[1,seed] += ES
resdt.close()
sess6+=ESS
ses6+=ES
stot6+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor_rpl = totSeeds/len(rplrange)
rplsEsSMat = rplsEsSMat/divisor_rpl
EsSMat [rply,20] = sum(rplsEsSMat [0,:])/10
EsSMat [rply,21] = np.std(rplsEsSMat [0,:])
EsSMat [rply,22] = sum(rplsEsSMat [1,:])/10
EsSMat [rply,23] = np.std(rplsEsSMat [1,:])
print(stot6,sess6,ses6, "divisor for rpl is " + str(divisor_rpl))
selsEsSMat = np.zeros([2,10], dtype = 'float64')
stot7 = 0
sess7 = 0
ses7 = 0
if Sel == "tr":
for hy in range(4):
for seed in range(10):
for My in range(3):
M = Mrange[My]
if M == 50:
Nrange = [2,5,10,12,50,1]
else:
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for rply in range(2):
for ay in range(5):
suffix = "tr/tr-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-tr" + str(hrange[hy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
selsEsSMat[0,seed] += ESS
selsEsSMat[1,seed] += ES
resdt.close()
sess7+=ESS
ses7+=ES
stot7+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor = totSeeds/len(hrange)
selsEsSMat = selsEsSMat/divisor
EsSMat [hy,24] = sum(selsEsSMat [0,:])/10
EsSMat [hy,25] = np.std(selsEsSMat [0,:])
EsSMat [hy,26] = sum(selsEsSMat [1,:])/10
EsSMat [hy,27] = np.std(selsEsSMat [1,:])
elif Sel == "kt":
for ky in range(4):
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for rply in range(2):
for ay in range(5):
suffix = "kt/kt-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-k" + str(krange[ky]) + "-alp100-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
selsEsSMat[0,seed] += ESS
selsEsSMat[1,seed] += ES
resdt.close()
sess7+=ESS
ses7+=ES
stot7+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor = totSeeds/len(krange)
selsEsSMat = selsEsSMat/divisor
EsSMat [ky,24] = sum(selsEsSMat [0,:])/10
EsSMat [ky,25] = np.std(selsEsSMat [0,:])
EsSMat [ky,26] = sum(selsEsSMat [1,:])/10
EsSMat [ky,27] = np.std(selsEsSMat [1,:])
elif Sel == "rank":
for wy in range(4):
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for rply in range(2):
for ay in range(5):
suffix = "rank/rank-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-" + funtype + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
selsEsSMat[0,seed] += ESS
selsEsSMat[1,seed] += ES
resdt.close()
sess7+=ESS
ses7+=ES
stot7+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor = totSeeds/len(wrange)
selsEsSMat = selsEsSMat/divisor
EsSMat [wy,24] = sum(selsEsSMat [0,:])/10
EsSMat [wy,25] = np.std(selsEsSMat [0,:])
EsSMat [wy,26] = sum(selsEsSMat [1,:])/10
EsSMat [wy,27] = np.std(selsEsSMat [1,:])
elif Sel == "rwheel":
for wy in range(4):
for seed in range(10):
for My in range(3):
M = Mrange[My]
Nrange = [int(round(M/20)),int(M/10),int(M/5),int(round(M/4)),M,1]
for Ny in range(6):
for muty in range(2):
for muy in range(5):
for rply in range(2):
for ay in range(5):
suffix = "rw/rw-a" + str(a_range[ay]) + "M" + str(M) + "-N" + str(Nrange[Ny]) + "-w" + str(wrange[wy]) + "-" + str(mutrange[muty]) + str(murange[muy]) + "-" + str(rplrange[rply])
filename = filepath + suffix + "-" + str(seed)
if os.path.isfile(filename):
resdt = shelve.open(filename, flag = 'r')
freqList = resdt['freqList']
#are the ESS or the ES the predominant (>fmin) strategy in the population at each one of the final recorded time points?
ESS = 1
ES = 1
for endy in range(yrec):
if ESS>0 or ES>0:
if freqList [endy] [iESS] >= fmin:
ESS = 1
else:
ESS = 0
if freqList [endy] [iES1] + freqList [endy] [iES2] >= fmin:
ES = 1
else:
ES = 0
else:
break
selsEsSMat[0,seed] += ESS
selsEsSMat[1,seed] += ES
resdt.close()
sess7+=ESS
ses7+=ES
stot7+=1
else:
with open(logfile, 'a+') as l:
l.write(filename + " non-existent" + '\n')
divisor = totSeeds/len(wrange)
selsEsSMat = selsEsSMat/divisor
EsSMat [wy,24] = sum(selsEsSMat [0,:])/10
EsSMat [wy,25] = np.std(selsEsSMat [0,:])
EsSMat [wy,26] = sum(selsEsSMat [1,:])/10
EsSMat [wy,27] = np.std(selsEsSMat [1,:])
print(stot7,sess7,ses7, ", divisor for sel par is " + str(divisor))
# save extracted statistics to csv file
if Sel == "rank":
if funtype == "lin":
np.savetxt(pathToSave + "summaries/SPS" + Sel + "l-ESS-ES.csv", EsSMat, delimiter = ",", header = "a-ESS, a-ESS-sd, a-ES, a-ES-sd, M-ESS, M-ESS-sd, M-ES, M-ES-sd, N-ESS, N-ESS-sd, N-ES, N-ES-sd, mut-ESS, mut-ESS-sd,mut-ES,mut-ES-sd,mu-ESS,mu-ESS-sd,mu-ES,mu-ES-sd,rpl-ESS,rpl-ESS-sd,rpl-ES,rpl-ES-sd,o-ESS,o-ESS-sd,o-ES,o-ES-sd,ave,ave-sd")
elif funtype == "exp":
np.savetxt(pathToSave + "summaries/SPS" + Sel + "e-ESS-ES.csv", EsSMat, delimiter = ",", header = "a-ESS, a-ESS-sd, a-ES, a-ES-sd, M-ESS, M-ESS-sd, M-ES, M-ES-sd, N-ESS, N-ESS-sd, N-ES, N-ES-sd, mut-ESS, mut-ESS-sd, mut-ES, mut-ES-sd, mu-ESS, mu-ESS-sd,mu-ES, mu-ES-sd, rpl-ESS, rpl-ESS-sd, rpl-ES, rpl-ES-sd,c-ESS, c-ESS-sd,c-ES, c-ES-sd,ave,ave-sd")
elif Sel == "kt":
np.savetxt(pathToSave + "summaries/SPS" + Sel + "-ESS-ES.csv", EsSMat, delimiter = ",", header = "a-ESS, a-ESS-sd, a-ES, a-ES-sd, M-ESS, M-ESS-sd, M-ES, M-ES-sd, N-ESS, N-ESS-sd, N-ES, N-ES-sd, mut-ESS, mut-ESS-sd, mut-ES, mut-ES-sd, mu-ESS, mu-ESS-sd,mu-ES, mu-ES-sd, rpl-ESS, rpl-ESS-sd, rpl-ES, rpl-ES-sd,k-ESS, k-ESS-sd,k-ES, k-ES-sd,ave,ave-sd")
elif Sel == "tr":
np.savetxt(pathToSave + "summaries/SPS" + Sel + "-ESS-ES.csv", EsSMat, delimiter = ",", header = "a-ESS, a-ESS-sd, a-ES, a-ES-sd, M-ESS, M-ESS-sd, M-ES, M-ES-sd, N-ESS, N-ESS-sd, N-ES, N-ES-sd, mut-ESS, mut-ESS-sd, mut-ES, mut-ES-sd, mu-ESS, mu-ESS-sd,mu-ES, mu-ES-sd, rpl-ESS, rpl-ESS-sd, rpl-ES, rpl-ES-sd,h-ESS, h-ESS-sd,h-ES, h-ES-sd,ave,ave-sd")
elif Sel == "rwheel":
np.savetxt(pathToSave + "summaries/SPS" + Sel + "-ESS-ES.csv", EsSMat, delimiter = ",", header = "a-ESS, a-ESS-sd, a-ES, a-ES-sd, M-ESS, M-ESS-sd, M-ES, M-ES-sd, N-ESS, N-ESS-sd, N-ES, N-ES-sd, mut-ESS, mut-ESS-sd, mut-ES, mut-ES-sd, mu-ESS, mu-ESS-sd,mu-ES, mu-ES-sd, rpl-ESS, rpl-ESS-sd, rpl-ES, rpl-ES-sd,w-ESS, w-ESS-sd,w-ES, w-ES-sd,ave,ave-sd")
| 54.787092 | 363 | 0.284474 | 6,389 | 82,345 | 3.657693 | 0.053686 | 0.038641 | 0.02636 | 0.035945 | 0.833112 | 0.828919 | 0.808207 | 0.804228 | 0.801446 | 0.793658 | 0 | 0.037545 | 0.630615 | 82,345 | 1,502 | 364 | 54.823569 | 0.730743 | 0.065966 | 0 | 0.883944 | 0 | 0.004363 | 0.040196 | 0.001744 | 0 | 0 | 0 | 0 | 0 | 1 | 0.000873 | false | 0 | 0.002618 | 0 | 0.00349 | 0.006981 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
db86d5236f725c4dec4e20def0cca10121168f3e | 306,535 | py | Python | Lib/site-packages/tensorflow/python/framework/test_ops.py | foodwaze0/webapp | 897043cbbfdbad8d6c54f0556f31e4127d518fc1 | [
"bzip2-1.0.6"
] | null | null | null | Lib/site-packages/tensorflow/python/framework/test_ops.py | foodwaze0/webapp | 897043cbbfdbad8d6c54f0556f31e4127d518fc1 | [
"bzip2-1.0.6"
] | null | null | null | Lib/site-packages/tensorflow/python/framework/test_ops.py | foodwaze0/webapp | 897043cbbfdbad8d6c54f0556f31e4127d518fc1 | [
"bzip2-1.0.6"
] | null | null | null | """Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
from tensorflow.python.eager import core as _core
from tensorflow.python.eager import execute as _execute
from tensorflow.python.framework import dtypes as _dtypes
from tensorflow.python.framework import errors as _errors
from tensorflow.python.framework import tensor_shape as _tensor_shape
from tensorflow.core.framework import op_def_pb2 as _op_def_pb2
# Needed to trigger the call to _set_call_cpp_shape_fn.
from tensorflow.python.framework import common_shapes as _common_shapes
from tensorflow.python.framework import op_def_registry as _op_def_registry
from tensorflow.python.framework import ops as _ops
from tensorflow.python.framework import op_def_library as _op_def_library
from tensorflow.python.util.deprecation import deprecated_endpoints
from tensorflow.python.util import dispatch as _dispatch
from tensorflow.python.util.tf_export import tf_export
from tensorflow.python.util.tf_export import kwarg_only as _kwarg_only
from tensorflow.tools.docs import doc_controls as _doc_controls
@_dispatch.add_dispatch_list
@tf_export('a')
def a(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "A", name,
_ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return a_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"A", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"A", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def A(name=None):
return a(name=name)
A.__doc__ = a.__doc__
A = _doc_controls.do_not_generate_docs(_kwarg_only(A))
tf_export("raw_ops.A")(A)
def a_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function a
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"A", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"A", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("A")(None)
@_dispatch.add_dispatch_list
@tf_export('attr')
def attr(a, name=None):
r"""TODO: add doc.
Args:
a: An `int`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Attr",
name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_int(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Attr", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def Attr(a, name=None):
return attr(a=a, name=name)
Attr.__doc__ = attr.__doc__
Attr = _doc_controls.do_not_generate_docs(_kwarg_only(Attr))
tf_export("raw_ops.Attr")(Attr)
def attr_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_int(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"Attr", 0, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("Attr")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_bool')
def attr_bool(a, name=None):
r"""TODO: add doc.
Args:
a: A `bool`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "AttrBool",
name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_bool_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_bool, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_bool(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrBool", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_bool, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrBool(a, name=None):
return attr_bool(a=a, name=name)
AttrBool.__doc__ = attr_bool.__doc__
AttrBool = _doc_controls.do_not_generate_docs(_kwarg_only(AttrBool))
tf_export("raw_ops.AttrBool")(AttrBool)
def attr_bool_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_bool
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_bool(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrBool", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrBool")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_bool_list')
def attr_bool_list(a, name=None):
r"""TODO: add doc.
Args:
a: A list of `bools`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrBoolList", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_bool_list_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_bool_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_bool_list' Op, not %r." % a)
a = [_execute.make_bool(_b, "a") for _b in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrBoolList", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_bool_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrBoolList(a, name=None):
return attr_bool_list(a=a, name=name)
AttrBoolList.__doc__ = attr_bool_list.__doc__
AttrBoolList = _doc_controls.do_not_generate_docs(_kwarg_only(AttrBoolList))
tf_export("raw_ops.AttrBoolList")(AttrBoolList)
def attr_bool_list_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_bool_list
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_bool_list' Op, not %r." % a)
a = [_execute.make_bool(_b, "a") for _b in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrBoolList", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrBoolList")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_default')
def attr_default(a="banana", name=None):
r"""TODO: add doc.
Args:
a: An optional `string`. Defaults to `"banana"`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrDefault", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_default_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if a is None:
a = "banana"
a = _execute.make_str(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrDefault", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrDefault(a="banana", name=None):
return attr_default(a=a, name=name)
AttrDefault.__doc__ = attr_default.__doc__
AttrDefault = _doc_controls.do_not_generate_docs(_kwarg_only(AttrDefault))
tf_export("raw_ops.AttrDefault")(AttrDefault)
def attr_default_eager_fallback(a="banana", name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_default
"""
_ctx = ctx if ctx else _context.context()
if a is None:
a = "banana"
a = _execute.make_str(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrDefault", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_empty_list_default')
def attr_empty_list_default(a=[], name=None):
r"""TODO: add doc.
Args:
a: An optional list of `floats`. Defaults to `[]`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrEmptyListDefault", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_empty_list_default_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_empty_list_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if a is None:
a = []
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_empty_list_default' Op, not %r." % a)
a = [_execute.make_float(_f, "a") for _f in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrEmptyListDefault", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_empty_list_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrEmptyListDefault(a=[], name=None):
return attr_empty_list_default(a=a, name=name)
AttrEmptyListDefault.__doc__ = attr_empty_list_default.__doc__
AttrEmptyListDefault = _doc_controls.do_not_generate_docs(_kwarg_only(AttrEmptyListDefault))
tf_export("raw_ops.AttrEmptyListDefault")(AttrEmptyListDefault)
def attr_empty_list_default_eager_fallback(a=[], name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_empty_list_default
"""
_ctx = ctx if ctx else _context.context()
if a is None:
a = []
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_empty_list_default' Op, not %r." % a)
a = [_execute.make_float(_f, "a") for _f in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrEmptyListDefault", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrEmptyListDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_enum')
def attr_enum(a, name=None):
r"""TODO: add doc.
Args:
a: A `string` from: `"apples", "oranges"`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "AttrEnum",
name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_enum_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_enum, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_str(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrEnum", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_enum, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrEnum(a, name=None):
return attr_enum(a=a, name=name)
AttrEnum.__doc__ = attr_enum.__doc__
AttrEnum = _doc_controls.do_not_generate_docs(_kwarg_only(AttrEnum))
tf_export("raw_ops.AttrEnum")(AttrEnum)
def attr_enum_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_enum
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_str(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrEnum", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrEnum")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_enum_list')
def attr_enum_list(a, name=None):
r"""TODO: add doc.
Args:
a: A list of `strings` from: `"apples", "oranges"`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrEnumList", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_enum_list_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_enum_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_enum_list' Op, not %r." % a)
a = [_execute.make_str(_s, "a") for _s in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrEnumList", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_enum_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrEnumList(a, name=None):
return attr_enum_list(a=a, name=name)
AttrEnumList.__doc__ = attr_enum_list.__doc__
AttrEnumList = _doc_controls.do_not_generate_docs(_kwarg_only(AttrEnumList))
tf_export("raw_ops.AttrEnumList")(AttrEnumList)
def attr_enum_list_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_enum_list
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_enum_list' Op, not %r." % a)
a = [_execute.make_str(_s, "a") for _s in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrEnumList", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrEnumList")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_float')
def attr_float(a, name=None):
r"""TODO: add doc.
Args:
a: A `float`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrFloat", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_float_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_float, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_float(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrFloat", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_float, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrFloat(a, name=None):
return attr_float(a=a, name=name)
AttrFloat.__doc__ = attr_float.__doc__
AttrFloat = _doc_controls.do_not_generate_docs(_kwarg_only(AttrFloat))
tf_export("raw_ops.AttrFloat")(AttrFloat)
def attr_float_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_float
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_float(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrFloat", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrFloat")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_list_default')
def attr_list_default(a=[5, 15], name=None):
r"""TODO: add doc.
Args:
a: An optional list of `ints`. Defaults to `[5, 15]`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrListDefault", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_list_default_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_list_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if a is None:
a = [5, 15]
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_list_default' Op, not %r." % a)
a = [_execute.make_int(_i, "a") for _i in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrListDefault", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_list_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrListDefault(a=[5, 15], name=None):
return attr_list_default(a=a, name=name)
AttrListDefault.__doc__ = attr_list_default.__doc__
AttrListDefault = _doc_controls.do_not_generate_docs(_kwarg_only(AttrListDefault))
tf_export("raw_ops.AttrListDefault")(AttrListDefault)
def attr_list_default_eager_fallback(a=[5, 15], name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_list_default
"""
_ctx = ctx if ctx else _context.context()
if a is None:
a = [5, 15]
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_list_default' Op, not %r." % a)
a = [_execute.make_int(_i, "a") for _i in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrListDefault", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrListDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_list_min')
def attr_list_min(a, name=None):
r"""TODO: add doc.
Args:
a: A list of `ints` that has length `>= 2`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrListMin", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_list_min_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_list_min, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_list_min' Op, not %r." % a)
a = [_execute.make_int(_i, "a") for _i in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrListMin", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_list_min, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrListMin(a, name=None):
return attr_list_min(a=a, name=name)
AttrListMin.__doc__ = attr_list_min.__doc__
AttrListMin = _doc_controls.do_not_generate_docs(_kwarg_only(AttrListMin))
tf_export("raw_ops.AttrListMin")(AttrListMin)
def attr_list_min_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_list_min
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_list_min' Op, not %r." % a)
a = [_execute.make_int(_i, "a") for _i in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrListMin", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrListMin")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_list_type_default')
def attr_list_type_default(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of at least 1 `Tensor` objects with the same type.
b: A list with the same length as `a` of `Tensor` objects with the same type as `a`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrListTypeDefault", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return attr_list_type_default_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_list_type_default, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_list_type_default' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'attr_list_type_default' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'attr_list_type_default' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrListTypeDefault", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_list_type_default, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrListTypeDefault(a, b, name=None):
return attr_list_type_default(a=a, b=b, name=name)
AttrListTypeDefault.__doc__ = attr_list_type_default.__doc__
AttrListTypeDefault = _doc_controls.do_not_generate_docs(_kwarg_only(AttrListTypeDefault))
tf_export("raw_ops.AttrListTypeDefault")(AttrListTypeDefault)
def attr_list_type_default_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_list_type_default
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_list_type_default' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'attr_list_type_default' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'attr_list_type_default' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
_attr_T, _inputs_T = _execute.args_to_matching_eager(list(a) + list(b), _ctx, _dtypes.int32)
_inputs_T = [_inputs_T[:_attr_N]] + _inputs_T[_attr_N:]
_inputs_T = _inputs_T[:1] + [_inputs_T[1:]]
(a, b) = _inputs_T
_inputs_flat = list(a) + list(b)
_attrs = ("T", _attr_T, "N", _attr_N)
_result = _execute.execute(b"AttrListTypeDefault", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrListTypeDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_min')
def attr_min(a, name=None):
r"""TODO: add doc.
Args:
a: An `int` that is `>= 5`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "AttrMin",
name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_min_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_min, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_int(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrMin", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_min, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrMin(a, name=None):
return attr_min(a=a, name=name)
AttrMin.__doc__ = attr_min.__doc__
AttrMin = _doc_controls.do_not_generate_docs(_kwarg_only(AttrMin))
tf_export("raw_ops.AttrMin")(AttrMin)
def attr_min_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_min
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_int(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrMin", 0, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrMin")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_partial_shape')
def attr_partial_shape(a, name=None):
r"""TODO: add doc.
Args:
a: A `tf.TensorShape` or list of `ints`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrPartialShape", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_partial_shape_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_partial_shape, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_shape(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrPartialShape", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_partial_shape, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrPartialShape(a, name=None):
return attr_partial_shape(a=a, name=name)
AttrPartialShape.__doc__ = attr_partial_shape.__doc__
AttrPartialShape = _doc_controls.do_not_generate_docs(_kwarg_only(AttrPartialShape))
tf_export("raw_ops.AttrPartialShape")(AttrPartialShape)
def attr_partial_shape_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_partial_shape
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_shape(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrPartialShape", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrPartialShape")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_partial_shape_list')
def attr_partial_shape_list(a, name=None):
r"""TODO: add doc.
Args:
a: A list of shapes (each a `tf.TensorShape` or list of `ints`).
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrPartialShapeList", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_partial_shape_list_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_partial_shape_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_partial_shape_list' Op, not %r." % a)
a = [_execute.make_shape(_s, "a") for _s in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrPartialShapeList", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_partial_shape_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrPartialShapeList(a, name=None):
return attr_partial_shape_list(a=a, name=name)
AttrPartialShapeList.__doc__ = attr_partial_shape_list.__doc__
AttrPartialShapeList = _doc_controls.do_not_generate_docs(_kwarg_only(AttrPartialShapeList))
tf_export("raw_ops.AttrPartialShapeList")(AttrPartialShapeList)
def attr_partial_shape_list_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_partial_shape_list
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_partial_shape_list' Op, not %r." % a)
a = [_execute.make_shape(_s, "a") for _s in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrPartialShapeList", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrPartialShapeList")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_shape')
def attr_shape(a, name=None):
r"""TODO: add doc.
Args:
a: A `tf.TensorShape` or list of `ints`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrShape", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_shape_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_shape, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
a = _execute.make_shape(a, "a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrShape", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_shape, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrShape(a, name=None):
return attr_shape(a=a, name=name)
AttrShape.__doc__ = attr_shape.__doc__
AttrShape = _doc_controls.do_not_generate_docs(_kwarg_only(AttrShape))
tf_export("raw_ops.AttrShape")(AttrShape)
def attr_shape_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_shape
"""
_ctx = ctx if ctx else _context.context()
a = _execute.make_shape(a, "a")
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrShape", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrShape")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_shape_list')
def attr_shape_list(a, name=None):
r"""TODO: add doc.
Args:
a: A list of shapes (each a `tf.TensorShape` or list of `ints`).
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrShapeList", name, _ctx._post_execution_callbacks, "a", a)
return _result
except _core._FallbackException:
try:
return attr_shape_list_eager_fallback(
a=a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_shape_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_shape_list' Op, not %r." % a)
a = [_execute.make_shape(_s, "a") for _s in a]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrShapeList", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_shape_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrShapeList(a, name=None):
return attr_shape_list(a=a, name=name)
AttrShapeList.__doc__ = attr_shape_list.__doc__
AttrShapeList = _doc_controls.do_not_generate_docs(_kwarg_only(AttrShapeList))
tf_export("raw_ops.AttrShapeList")(AttrShapeList)
def attr_shape_list_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_shape_list
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'attr_shape_list' Op, not %r." % a)
a = [_execute.make_shape(_s, "a") for _s in a]
_inputs_flat = []
_attrs = ("a", a)
_result = _execute.execute(b"AttrShapeList", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrShapeList")(None)
@_dispatch.add_dispatch_list
@tf_export('attr_type_default')
def attr_type_default(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"AttrTypeDefault", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return attr_type_default_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_type_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"AttrTypeDefault", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
attr_type_default, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def AttrTypeDefault(a, name=None):
return attr_type_default(a=a, name=name)
AttrTypeDefault.__doc__ = attr_type_default.__doc__
AttrTypeDefault = _doc_controls.do_not_generate_docs(_kwarg_only(AttrTypeDefault))
tf_export("raw_ops.AttrTypeDefault")(AttrTypeDefault)
def attr_type_default_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function attr_type_default
"""
_ctx = ctx if ctx else _context.context()
_attr_T, (a,) = _execute.args_to_matching_eager([a], _ctx, _dtypes.int32)
_inputs_flat = [a]
_attrs = ("T", _attr_T)
_result = _execute.execute(b"AttrTypeDefault", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("AttrTypeDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('b')
def b(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "B", name,
_ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return b_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"B", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"B", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def B(name=None):
return b(name=name)
B.__doc__ = b.__doc__
B = _doc_controls.do_not_generate_docs(_kwarg_only(B))
tf_export("raw_ops.B")(B)
def b_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function b
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"B", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"B", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("B")(None)
@_dispatch.add_dispatch_list
@tf_export('binary')
def binary(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor`.
b: A `Tensor`. Must have the same type as `a`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `a`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Binary",
name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return binary_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
binary, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Binary", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
binary, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"Binary", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def Binary(a, b, name=None):
return binary(a=a, b=b, name=name)
Binary.__doc__ = binary.__doc__
Binary = _doc_controls.do_not_generate_docs(_kwarg_only(Binary))
tf_export("raw_ops.Binary")(Binary)
def binary_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function binary
"""
_ctx = ctx if ctx else _context.context()
_attr_T, _inputs_T = _execute.args_to_matching_eager([a, b], _ctx)
(a, b) = _inputs_T
_inputs_flat = [a, b]
_attrs = ("T", _attr_T)
_result = _execute.execute(b"Binary", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"Binary", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("Binary")(None)
_complex_struct_outputs = ["a", "b", "c"]
_ComplexStructOutput = _collections.namedtuple(
"ComplexStruct", _complex_struct_outputs)
@_dispatch.add_dispatch_list
@tf_export('complex_struct')
def complex_struct(n_a, n_b, t_c, name=None):
r"""TODO: add doc.
Args:
n_a: An `int` that is `>= 0`.
n_b: An `int` that is `>= 0`.
t_c: A list of `tf.DTypes`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b, c).
a: A list of `n_a` `Tensor` objects with type `int32`.
b: A list of `n_b` `Tensor` objects with type `int64`.
c: A list of `Tensor` objects of type `t_c`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ComplexStruct", name, _ctx._post_execution_callbacks, "n_a", n_a,
"n_b", n_b, "t_c", t_c)
_result = _ComplexStructOutput._make(_result)
return _result
except _core._FallbackException:
try:
return complex_struct_eager_fallback(
n_a=n_a, n_b=n_b, t_c=t_c, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
complex_struct, n_a=n_a, n_b=n_b, t_c=t_c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
n_a = _execute.make_int(n_a, "n_a")
n_b = _execute.make_int(n_b, "n_b")
if not isinstance(t_c, (list, tuple)):
raise TypeError(
"Expected list for 't_c' argument to "
"'complex_struct' Op, not %r." % t_c)
t_c = [_execute.make_type(_t, "t_c") for _t in t_c]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ComplexStruct", n_a=n_a, n_b=n_b, t_c=t_c, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
complex_struct, n_a=n_a, n_b=n_b, t_c=t_c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("n_a", _op.get_attr("n_a"), "n_b", _op.get_attr("n_b"), "t_c",
_op.get_attr("t_c"))
_execute.record_gradient(
"ComplexStruct", _inputs_flat, _attrs, _result, name)
_result = [_result[:n_a]] + _result[n_a:]
_result = _result[:1] + [_result[1:1 + n_b]] + _result[1 + n_b:]
_result = _result[:2] + [_result[2:]]
_result = _ComplexStructOutput._make(_result)
return _result
def ComplexStruct(n_a, n_b, t_c, name=None):
return complex_struct(n_a=n_a, n_b=n_b, t_c=t_c, name=name)
ComplexStruct.__doc__ = complex_struct.__doc__
ComplexStruct = _doc_controls.do_not_generate_docs(_kwarg_only(ComplexStruct))
tf_export("raw_ops.ComplexStruct")(ComplexStruct)
def complex_struct_eager_fallback(n_a, n_b, t_c, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function complex_struct
"""
_ctx = ctx if ctx else _context.context()
n_a = _execute.make_int(n_a, "n_a")
n_b = _execute.make_int(n_b, "n_b")
if not isinstance(t_c, (list, tuple)):
raise TypeError(
"Expected list for 't_c' argument to "
"'complex_struct' Op, not %r." % t_c)
t_c = [_execute.make_type(_t, "t_c") for _t in t_c]
_inputs_flat = []
_attrs = ("n_a", n_a, "n_b", n_b, "t_c", t_c)
_result = _execute.execute(b"ComplexStruct", n_a + n_b + len(t_c),
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"ComplexStruct", _inputs_flat, _attrs, _result, name)
_result = [_result[:n_a]] + _result[n_a:]
_result = _result[:1] + [_result[1:1 + n_b]] + _result[1 + n_b:]
_result = _result[:2] + [_result[2:]]
_result = _ComplexStructOutput._make(_result)
return _result
_ops.RegisterShape("ComplexStruct")(None)
@_dispatch.add_dispatch_list
@tf_export('copy_op')
def copy_op(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `a`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "CopyOp",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return copy_op_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
copy_op, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"CopyOp", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
copy_op, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"CopyOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def CopyOp(a, name=None):
return copy_op(a=a, name=name)
CopyOp.__doc__ = copy_op.__doc__
CopyOp = _doc_controls.do_not_generate_docs(_kwarg_only(CopyOp))
tf_export("raw_ops.CopyOp")(CopyOp)
def copy_op_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function copy_op
"""
_ctx = ctx if ctx else _context.context()
_attr_T, (a,) = _execute.args_to_matching_eager([a], _ctx)
_inputs_flat = [a]
_attrs = ("T", _attr_T)
_result = _execute.execute(b"CopyOp", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"CopyOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("CopyOp")(None)
@_dispatch.add_dispatch_list
@tf_export('default_attrs')
def default_attrs(string_val="abc", string_list_val=["abc", ""], int_val=123, int_list_val=[1, 2, 3], float_val=10, float_list_val=[10], bool_val=True, bool_list_val=[True, False], type_val=_dtypes.int32, type_list_val=[_dtypes.int32, _dtypes.float32], shape_val=[2, 1], shape_list_val=[[], [1]], tensor_val=_execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1""", "tensor_val"), tensor_list_val=[_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1""",)], name=None):
r"""TODO: add doc.
Args:
string_val: An optional `string`. Defaults to `"abc"`.
string_list_val: An optional list of `strings`. Defaults to `["abc", ""]`.
int_val: An optional `int`. Defaults to `123`.
int_list_val: An optional list of `ints`. Defaults to `[1, 2, 3]`.
float_val: An optional `float`. Defaults to `10`.
float_list_val: An optional list of `floats`. Defaults to `[10]`.
bool_val: An optional `bool`. Defaults to `True`.
bool_list_val: An optional list of `bools`. Defaults to `[True, False]`.
type_val: An optional `tf.DType`. Defaults to `tf.int32`.
type_list_val: An optional list of `tf.DTypes`. Defaults to `[tf.int32, tf.float32]`.
shape_val: An optional `tf.TensorShape` or list of `ints`. Defaults to `[2, 1]`.
shape_list_val: An optional list of shapes (each a `tf.TensorShape` or list of `ints`). Defaults to `[[], [1]]`.
tensor_val: An optional `tf.TensorProto`. Defaults to `dtype: DT_INT32 tensor_shape { } int_val: 1`.
tensor_list_val: An optional list of `tf.TensorProto` objects. Defaults to `[dtype: DT_INT32 tensor_shape { } int_val: 1]`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"DefaultAttrs", name, _ctx._post_execution_callbacks, "string_val",
string_val, "string_list_val", string_list_val, "int_val", int_val,
"int_list_val", int_list_val, "float_val", float_val,
"float_list_val", float_list_val, "bool_val", bool_val,
"bool_list_val", bool_list_val, "type_val", type_val, "type_list_val",
type_list_val, "shape_val", shape_val, "shape_list_val",
shape_list_val, "tensor_val", tensor_val, "tensor_list_val",
tensor_list_val)
return _result
except _core._FallbackException:
try:
return default_attrs_eager_fallback(
string_val=string_val, string_list_val=string_list_val,
int_val=int_val, int_list_val=int_list_val, float_val=float_val,
float_list_val=float_list_val, bool_val=bool_val,
bool_list_val=bool_list_val, type_val=type_val,
type_list_val=type_list_val, shape_val=shape_val,
shape_list_val=shape_list_val, tensor_val=tensor_val,
tensor_list_val=tensor_list_val, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
default_attrs, string_val=string_val,
string_list_val=string_list_val, int_val=int_val,
int_list_val=int_list_val, float_val=float_val,
float_list_val=float_list_val, bool_val=bool_val,
bool_list_val=bool_list_val, type_val=type_val,
type_list_val=type_list_val, shape_val=shape_val,
shape_list_val=shape_list_val,
tensor_val=tensor_val,
tensor_list_val=tensor_list_val, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if string_val is None:
string_val = "abc"
string_val = _execute.make_str(string_val, "string_val")
if string_list_val is None:
string_list_val = ["abc", ""]
if not isinstance(string_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'string_list_val' argument to "
"'default_attrs' Op, not %r." % string_list_val)
string_list_val = [_execute.make_str(_s, "string_list_val") for _s in string_list_val]
if int_val is None:
int_val = 123
int_val = _execute.make_int(int_val, "int_val")
if int_list_val is None:
int_list_val = [1, 2, 3]
if not isinstance(int_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'int_list_val' argument to "
"'default_attrs' Op, not %r." % int_list_val)
int_list_val = [_execute.make_int(_i, "int_list_val") for _i in int_list_val]
if float_val is None:
float_val = 10
float_val = _execute.make_float(float_val, "float_val")
if float_list_val is None:
float_list_val = [10]
if not isinstance(float_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'float_list_val' argument to "
"'default_attrs' Op, not %r." % float_list_val)
float_list_val = [_execute.make_float(_f, "float_list_val") for _f in float_list_val]
if bool_val is None:
bool_val = True
bool_val = _execute.make_bool(bool_val, "bool_val")
if bool_list_val is None:
bool_list_val = [True, False]
if not isinstance(bool_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'bool_list_val' argument to "
"'default_attrs' Op, not %r." % bool_list_val)
bool_list_val = [_execute.make_bool(_b, "bool_list_val") for _b in bool_list_val]
if type_val is None:
type_val = _dtypes.int32
type_val = _execute.make_type(type_val, "type_val")
if type_list_val is None:
type_list_val = [_dtypes.int32, _dtypes.float32]
if not isinstance(type_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'type_list_val' argument to "
"'default_attrs' Op, not %r." % type_list_val)
type_list_val = [_execute.make_type(_t, "type_list_val") for _t in type_list_val]
if shape_val is None:
shape_val = [2, 1]
shape_val = _execute.make_shape(shape_val, "shape_val")
if shape_list_val is None:
shape_list_val = [[], [1]]
if not isinstance(shape_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'shape_list_val' argument to "
"'default_attrs' Op, not %r." % shape_list_val)
shape_list_val = [_execute.make_shape(_s, "shape_list_val") for _s in shape_list_val]
if tensor_val is None:
tensor_val = _execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1""", "tensor_val")
tensor_val = _execute.make_tensor(tensor_val, "tensor_val")
if tensor_list_val is None:
tensor_list_val = [_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1""",)]
if not isinstance(tensor_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'tensor_list_val' argument to "
"'default_attrs' Op, not %r." % tensor_list_val)
tensor_list_val = [_execute.make_tensor(_t, "tensor_list_val") for _t in tensor_list_val]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"DefaultAttrs", string_val=string_val,
string_list_val=string_list_val, int_val=int_val,
int_list_val=int_list_val, float_val=float_val,
float_list_val=float_list_val, bool_val=bool_val,
bool_list_val=bool_list_val, type_val=type_val,
type_list_val=type_list_val, shape_val=shape_val,
shape_list_val=shape_list_val, tensor_val=tensor_val,
tensor_list_val=tensor_list_val, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
default_attrs, string_val=string_val,
string_list_val=string_list_val, int_val=int_val,
int_list_val=int_list_val, float_val=float_val,
float_list_val=float_list_val, bool_val=bool_val,
bool_list_val=bool_list_val, type_val=type_val,
type_list_val=type_list_val, shape_val=shape_val,
shape_list_val=shape_list_val, tensor_val=tensor_val,
tensor_list_val=tensor_list_val, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def DefaultAttrs(string_val="abc", string_list_val=["abc", ""], int_val=123, int_list_val=[1, 2, 3], float_val=10, float_list_val=[10], bool_val=True, bool_list_val=[True, False], type_val=_dtypes.int32, type_list_val=[_dtypes.int32, _dtypes.float32], shape_val=[2, 1], shape_list_val=[[], [1]], tensor_val=_execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1""", "tensor_val"), tensor_list_val=[_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1""",)], name=None):
return default_attrs(string_val=string_val, string_list_val=string_list_val, int_val=int_val, int_list_val=int_list_val, float_val=float_val, float_list_val=float_list_val, bool_val=bool_val, bool_list_val=bool_list_val, type_val=type_val, type_list_val=type_list_val, shape_val=shape_val, shape_list_val=shape_list_val, tensor_val=tensor_val, tensor_list_val=tensor_list_val, name=name)
DefaultAttrs.__doc__ = default_attrs.__doc__
DefaultAttrs = _doc_controls.do_not_generate_docs(_kwarg_only(DefaultAttrs))
tf_export("raw_ops.DefaultAttrs")(DefaultAttrs)
def default_attrs_eager_fallback(string_val="abc", string_list_val=["abc", ""], int_val=123, int_list_val=[1, 2, 3], float_val=10, float_list_val=[10], bool_val=True, bool_list_val=[True, False], type_val=_dtypes.int32, type_list_val=[_dtypes.int32, _dtypes.float32], shape_val=[2, 1], shape_list_val=[[], [1]], tensor_val=_execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1""", "tensor_val"), tensor_list_val=[_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1""",)], name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function default_attrs
"""
_ctx = ctx if ctx else _context.context()
if string_val is None:
string_val = "abc"
string_val = _execute.make_str(string_val, "string_val")
if string_list_val is None:
string_list_val = ["abc", ""]
if not isinstance(string_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'string_list_val' argument to "
"'default_attrs' Op, not %r." % string_list_val)
string_list_val = [_execute.make_str(_s, "string_list_val") for _s in string_list_val]
if int_val is None:
int_val = 123
int_val = _execute.make_int(int_val, "int_val")
if int_list_val is None:
int_list_val = [1, 2, 3]
if not isinstance(int_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'int_list_val' argument to "
"'default_attrs' Op, not %r." % int_list_val)
int_list_val = [_execute.make_int(_i, "int_list_val") for _i in int_list_val]
if float_val is None:
float_val = 10
float_val = _execute.make_float(float_val, "float_val")
if float_list_val is None:
float_list_val = [10]
if not isinstance(float_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'float_list_val' argument to "
"'default_attrs' Op, not %r." % float_list_val)
float_list_val = [_execute.make_float(_f, "float_list_val") for _f in float_list_val]
if bool_val is None:
bool_val = True
bool_val = _execute.make_bool(bool_val, "bool_val")
if bool_list_val is None:
bool_list_val = [True, False]
if not isinstance(bool_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'bool_list_val' argument to "
"'default_attrs' Op, not %r." % bool_list_val)
bool_list_val = [_execute.make_bool(_b, "bool_list_val") for _b in bool_list_val]
if type_val is None:
type_val = _dtypes.int32
type_val = _execute.make_type(type_val, "type_val")
if type_list_val is None:
type_list_val = [_dtypes.int32, _dtypes.float32]
if not isinstance(type_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'type_list_val' argument to "
"'default_attrs' Op, not %r." % type_list_val)
type_list_val = [_execute.make_type(_t, "type_list_val") for _t in type_list_val]
if shape_val is None:
shape_val = [2, 1]
shape_val = _execute.make_shape(shape_val, "shape_val")
if shape_list_val is None:
shape_list_val = [[], [1]]
if not isinstance(shape_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'shape_list_val' argument to "
"'default_attrs' Op, not %r." % shape_list_val)
shape_list_val = [_execute.make_shape(_s, "shape_list_val") for _s in shape_list_val]
if tensor_val is None:
tensor_val = _execute.make_tensor("""dtype: DT_INT32 tensor_shape { } int_val: 1""", "tensor_val")
tensor_val = _execute.make_tensor(tensor_val, "tensor_val")
if tensor_list_val is None:
tensor_list_val = [_execute.make_tensor(_pb, "tensor_list_val") for _pb in ("""dtype: DT_INT32 tensor_shape { } int_val: 1""",)]
if not isinstance(tensor_list_val, (list, tuple)):
raise TypeError(
"Expected list for 'tensor_list_val' argument to "
"'default_attrs' Op, not %r." % tensor_list_val)
tensor_list_val = [_execute.make_tensor(_t, "tensor_list_val") for _t in tensor_list_val]
_inputs_flat = []
_attrs = ("string_val", string_val, "string_list_val", string_list_val,
"int_val", int_val, "int_list_val", int_list_val, "float_val", float_val,
"float_list_val", float_list_val, "bool_val", bool_val, "bool_list_val",
bool_list_val, "type_val", type_val, "type_list_val", type_list_val,
"shape_val", shape_val, "shape_list_val", shape_list_val, "tensor_val",
tensor_val, "tensor_list_val", tensor_list_val)
_result = _execute.execute(b"DefaultAttrs", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("DefaultAttrs")(None)
@_dispatch.add_dispatch_list
@tf_export('device_placement_op')
def device_placement_op(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `string`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"DevicePlacementOp", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return device_placement_op_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
device_placement_op, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"DevicePlacementOp", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
device_placement_op, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"DevicePlacementOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def DevicePlacementOp(name=None):
return device_placement_op(name=name)
DevicePlacementOp.__doc__ = device_placement_op.__doc__
DevicePlacementOp = _doc_controls.do_not_generate_docs(_kwarg_only(DevicePlacementOp))
tf_export("raw_ops.DevicePlacementOp")(DevicePlacementOp)
def device_placement_op_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function device_placement_op
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"DevicePlacementOp", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"DevicePlacementOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("DevicePlacementOp")(None)
_five_float_outputs_outputs = ["a", "b", "c", "d", "e"]
_FiveFloatOutputsOutput = _collections.namedtuple(
"FiveFloatOutputs", _five_float_outputs_outputs)
@_dispatch.add_dispatch_list
@tf_export('five_float_outputs')
def five_float_outputs(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b, c, d, e).
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `float32`.
c: A `Tensor` of type `float32`.
d: A `Tensor` of type `float32`.
e: A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"FiveFloatOutputs", name, _ctx._post_execution_callbacks)
_result = _FiveFloatOutputsOutput._make(_result)
return _result
except _core._FallbackException:
try:
return five_float_outputs_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
five_float_outputs, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"FiveFloatOutputs", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
five_float_outputs, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"FiveFloatOutputs", _inputs_flat, _attrs, _result, name)
_result = _FiveFloatOutputsOutput._make(_result)
return _result
def FiveFloatOutputs(name=None):
return five_float_outputs(name=name)
FiveFloatOutputs.__doc__ = five_float_outputs.__doc__
FiveFloatOutputs = _doc_controls.do_not_generate_docs(_kwarg_only(FiveFloatOutputs))
tf_export("raw_ops.FiveFloatOutputs")(FiveFloatOutputs)
def five_float_outputs_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function five_float_outputs
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"FiveFloatOutputs", 5, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"FiveFloatOutputs", _inputs_flat, _attrs, _result, name)
_result = _FiveFloatOutputsOutput._make(_result)
return _result
_ops.RegisterShape("FiveFloatOutputs")(None)
@_dispatch.add_dispatch_list
@tf_export('float_input')
def float_input(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"FloatInput", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return float_input_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
float_input, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"FloatInput", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
float_input, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def FloatInput(a, name=None):
return float_input(a=a, name=name)
FloatInput.__doc__ = float_input.__doc__
FloatInput = _doc_controls.do_not_generate_docs(_kwarg_only(FloatInput))
tf_export("raw_ops.FloatInput")(FloatInput)
def float_input_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function float_input
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
_inputs_flat = [a]
_attrs = None
_result = _execute.execute(b"FloatInput", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("FloatInput")(None)
@_dispatch.add_dispatch_list
@tf_export('float_output')
def float_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"FloatOutput", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return float_output_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
float_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"FloatOutput", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
float_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"FloatOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def FloatOutput(name=None):
return float_output(name=name)
FloatOutput.__doc__ = float_output.__doc__
FloatOutput = _doc_controls.do_not_generate_docs(_kwarg_only(FloatOutput))
tf_export("raw_ops.FloatOutput")(FloatOutput)
def float_output_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function float_output
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"FloatOutput", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"FloatOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("FloatOutput")(None)
_float_output_string_output_outputs = ["a", "b"]
_FloatOutputStringOutputOutput = _collections.namedtuple(
"FloatOutputStringOutput", _float_output_string_output_outputs)
@_dispatch.add_dispatch_list
@tf_export('float_output_string_output')
def float_output_string_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b).
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `string`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"FloatOutputStringOutput", name, _ctx._post_execution_callbacks)
_result = _FloatOutputStringOutputOutput._make(_result)
return _result
except _core._FallbackException:
try:
return float_output_string_output_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
float_output_string_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"FloatOutputStringOutput", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
float_output_string_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"FloatOutputStringOutput", _inputs_flat, _attrs, _result, name)
_result = _FloatOutputStringOutputOutput._make(_result)
return _result
def FloatOutputStringOutput(name=None):
return float_output_string_output(name=name)
FloatOutputStringOutput.__doc__ = float_output_string_output.__doc__
FloatOutputStringOutput = _doc_controls.do_not_generate_docs(_kwarg_only(FloatOutputStringOutput))
tf_export("raw_ops.FloatOutputStringOutput")(FloatOutputStringOutput)
def float_output_string_output_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function float_output_string_output
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"FloatOutputStringOutput", 2,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"FloatOutputStringOutput", _inputs_flat, _attrs, _result, name)
_result = _FloatOutputStringOutputOutput._make(_result)
return _result
_ops.RegisterShape("FloatOutputStringOutput")(None)
_foo1_outputs = ["d", "e"]
_Foo1Output = _collections.namedtuple(
"Foo1", _foo1_outputs)
@_dispatch.add_dispatch_list
@tf_export('foo1')
def foo1(a, b, c, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `int32`.
c: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (d, e).
d: A `Tensor` of type `float32`.
e: A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Foo1",
name, _ctx._post_execution_callbacks, a, b, c)
_result = _Foo1Output._make(_result)
return _result
except _core._FallbackException:
try:
return foo1_eager_fallback(
a, b, c, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
foo1, a=a, b=b, c=c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Foo1", a=a, b=b, c=c, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
foo1, a=a, b=b, c=c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"Foo1", _inputs_flat, _attrs, _result, name)
_result = _Foo1Output._make(_result)
return _result
def Foo1(a, b, c, name=None):
return foo1(a=a, b=b, c=c, name=name)
Foo1.__doc__ = foo1.__doc__
Foo1 = _doc_controls.do_not_generate_docs(_kwarg_only(Foo1))
tf_export("raw_ops.Foo1")(Foo1)
def foo1_eager_fallback(a, b, c, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function foo1
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
b = _ops.convert_to_tensor(b, _dtypes.int32)
c = _ops.convert_to_tensor(c, _dtypes.int32)
_inputs_flat = [a, b, c]
_attrs = None
_result = _execute.execute(b"Foo1", 2, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"Foo1", _inputs_flat, _attrs, _result, name)
_result = _Foo1Output._make(_result)
return _result
_ops.RegisterShape("Foo1")(None)
_foo2_outputs = ["d", "e"]
_Foo2Output = _collections.namedtuple(
"Foo2", _foo2_outputs)
@_dispatch.add_dispatch_list
@tf_export('foo2')
def foo2(a, b, c, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `string`.
c: A `Tensor` of type `string`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (d, e).
d: A `Tensor` of type `float32`.
e: A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Foo2",
name, _ctx._post_execution_callbacks, a, b, c)
_result = _Foo2Output._make(_result)
return _result
except _core._FallbackException:
try:
return foo2_eager_fallback(
a, b, c, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
foo2, a=a, b=b, c=c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Foo2", a=a, b=b, c=c, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
foo2, a=a, b=b, c=c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"Foo2", _inputs_flat, _attrs, _result, name)
_result = _Foo2Output._make(_result)
return _result
def Foo2(a, b, c, name=None):
return foo2(a=a, b=b, c=c, name=name)
Foo2.__doc__ = foo2.__doc__
Foo2 = _doc_controls.do_not_generate_docs(_kwarg_only(Foo2))
tf_export("raw_ops.Foo2")(Foo2)
def foo2_eager_fallback(a, b, c, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function foo2
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
b = _ops.convert_to_tensor(b, _dtypes.string)
c = _ops.convert_to_tensor(c, _dtypes.string)
_inputs_flat = [a, b, c]
_attrs = None
_result = _execute.execute(b"Foo2", 2, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"Foo2", _inputs_flat, _attrs, _result, name)
_result = _Foo2Output._make(_result)
return _result
_ops.RegisterShape("Foo2")(None)
_foo3_outputs = ["d", "e"]
_Foo3Output = _collections.namedtuple(
"Foo3", _foo3_outputs)
@_dispatch.add_dispatch_list
@tf_export('foo3')
def foo3(a, b, c, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `string`.
c: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (d, e).
d: A `Tensor` of type `float32`.
e: A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Foo3",
name, _ctx._post_execution_callbacks, a, b, c)
_result = _Foo3Output._make(_result)
return _result
except _core._FallbackException:
try:
return foo3_eager_fallback(
a, b, c, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
foo3, a=a, b=b, c=c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Foo3", a=a, b=b, c=c, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
foo3, a=a, b=b, c=c, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"Foo3", _inputs_flat, _attrs, _result, name)
_result = _Foo3Output._make(_result)
return _result
def Foo3(a, b, c, name=None):
return foo3(a=a, b=b, c=c, name=name)
Foo3.__doc__ = foo3.__doc__
Foo3 = _doc_controls.do_not_generate_docs(_kwarg_only(Foo3))
tf_export("raw_ops.Foo3")(Foo3)
def foo3_eager_fallback(a, b, c, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function foo3
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
b = _ops.convert_to_tensor(b, _dtypes.string)
c = _ops.convert_to_tensor(c, _dtypes.float32)
_inputs_flat = [a, b, c]
_attrs = None
_result = _execute.execute(b"Foo3", 2, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"Foo3", _inputs_flat, _attrs, _result, name)
_result = _Foo3Output._make(_result)
return _result
_ops.RegisterShape("Foo3")(None)
@_dispatch.add_dispatch_list
@tf_export('func_attr')
def func_attr(f, name=None):
r"""TODO: add doc.
Args:
f: A function decorated with @Defun.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "FuncAttr",
name, _ctx._post_execution_callbacks, "f", f)
return _result
except _core._FallbackException:
try:
return func_attr_eager_fallback(
f=f, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
func_attr, f=f, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"FuncAttr", f=f, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
func_attr, f=f, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def FuncAttr(f, name=None):
return func_attr(f=f, name=name)
FuncAttr.__doc__ = func_attr.__doc__
FuncAttr = _doc_controls.do_not_generate_docs(_kwarg_only(FuncAttr))
tf_export("raw_ops.FuncAttr")(FuncAttr)
def func_attr_eager_fallback(f, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function func_attr
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = ("f", f)
_result = _execute.execute(b"FuncAttr", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("FuncAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('func_list_attr')
def func_list_attr(f, name=None):
r"""TODO: add doc.
Args:
f: A list of functions decorated with @Defun.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"FuncListAttr", name, _ctx._post_execution_callbacks, "f", f)
return _result
except _core._FallbackException:
try:
return func_list_attr_eager_fallback(
f=f, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
func_list_attr, f=f, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(f, (list, tuple)):
raise TypeError(
"Expected list for 'f' argument to "
"'func_list_attr' Op, not %r." % f)
try:
_, _, _op = _op_def_lib._apply_op_helper(
"FuncListAttr", f=f, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
func_list_attr, f=f, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def FuncListAttr(f, name=None):
return func_list_attr(f=f, name=name)
FuncListAttr.__doc__ = func_list_attr.__doc__
FuncListAttr = _doc_controls.do_not_generate_docs(_kwarg_only(FuncListAttr))
tf_export("raw_ops.FuncListAttr")(FuncListAttr)
def func_list_attr_eager_fallback(f, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function func_list_attr
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(f, (list, tuple)):
raise TypeError(
"Expected list for 'f' argument to "
"'func_list_attr' Op, not %r." % f)
_inputs_flat = []
_attrs = ("f", f)
_result = _execute.execute(b"FuncListAttr", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("FuncListAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('graph_def_version')
def graph_def_version(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"GraphDefVersion", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return graph_def_version_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
graph_def_version, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"GraphDefVersion", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
graph_def_version, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"GraphDefVersion", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def GraphDefVersion(name=None):
return graph_def_version(name=name)
GraphDefVersion.__doc__ = graph_def_version.__doc__
GraphDefVersion = _doc_controls.do_not_generate_docs(_kwarg_only(GraphDefVersion))
tf_export("raw_ops.GraphDefVersion")(GraphDefVersion)
def graph_def_version_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function graph_def_version
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"GraphDefVersion", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"GraphDefVersion", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("GraphDefVersion")(None)
@_dispatch.add_dispatch_list
@tf_export('in_polymorphic_twice')
def in_polymorphic_twice(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects with the same type.
b: A list of `Tensor` objects with the same type as `a`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"InPolymorphicTwice", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return in_polymorphic_twice_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
in_polymorphic_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'in_polymorphic_twice' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'in_polymorphic_twice' Op, not %r." % b)
_attr_M = len(b)
try:
_, _, _op = _op_def_lib._apply_op_helper(
"InPolymorphicTwice", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
in_polymorphic_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def InPolymorphicTwice(a, b, name=None):
return in_polymorphic_twice(a=a, b=b, name=name)
InPolymorphicTwice.__doc__ = in_polymorphic_twice.__doc__
InPolymorphicTwice = _doc_controls.do_not_generate_docs(_kwarg_only(InPolymorphicTwice))
tf_export("raw_ops.InPolymorphicTwice")(InPolymorphicTwice)
def in_polymorphic_twice_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function in_polymorphic_twice
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'in_polymorphic_twice' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'in_polymorphic_twice' Op, not %r." % b)
_attr_M = len(b)
_attr_T, _inputs_T = _execute.args_to_matching_eager(list(a) + list(b), _ctx)
_inputs_T = [_inputs_T[:_attr_N]] + _inputs_T[_attr_N:]
_inputs_T = _inputs_T[:1] + [_inputs_T[1:]]
(a, b) = _inputs_T
_inputs_flat = list(a) + list(b)
_attrs = ("T", _attr_T, "N", _attr_N, "M", _attr_M)
_result = _execute.execute(b"InPolymorphicTwice", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("InPolymorphicTwice")(None)
@_dispatch.add_dispatch_list
@tf_export('int64_output')
def int64_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int64`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"Int64Output", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return int64_output_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int64_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Int64Output", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int64_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"Int64Output", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def Int64Output(name=None):
return int64_output(name=name)
Int64Output.__doc__ = int64_output.__doc__
Int64Output = _doc_controls.do_not_generate_docs(_kwarg_only(Int64Output))
tf_export("raw_ops.Int64Output")(Int64Output)
def int64_output_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int64_output
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"Int64Output", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"Int64Output", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("Int64Output")(None)
@_dispatch.add_dispatch_list
@tf_export('int_attr')
def int_attr(foo=1, name=None):
r"""TODO: add doc.
Args:
foo: An optional `int`. Defaults to `1`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int64`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "IntAttr",
name, _ctx._post_execution_callbacks, "foo", foo)
return _result
except _core._FallbackException:
try:
return int_attr_eager_fallback(
foo=foo, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_attr, foo=foo, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if foo is None:
foo = 1
foo = _execute.make_int(foo, "foo")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"IntAttr", foo=foo, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_attr, foo=foo, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("foo", _op.get_attr("foo"))
_execute.record_gradient(
"IntAttr", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def IntAttr(foo=1, name=None):
return int_attr(foo=foo, name=name)
IntAttr.__doc__ = int_attr.__doc__
IntAttr = _doc_controls.do_not_generate_docs(_kwarg_only(IntAttr))
tf_export("raw_ops.IntAttr")(IntAttr)
def int_attr_eager_fallback(foo=1, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int_attr
"""
_ctx = ctx if ctx else _context.context()
if foo is None:
foo = 1
foo = _execute.make_int(foo, "foo")
_inputs_flat = []
_attrs = ("foo", foo)
_result = _execute.execute(b"IntAttr", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"IntAttr", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("IntAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('int_input')
def int_input(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "IntInput",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return int_input_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_input, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"IntInput", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_input, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def IntInput(a, name=None):
return int_input(a=a, name=name)
IntInput.__doc__ = int_input.__doc__
IntInput = _doc_controls.do_not_generate_docs(_kwarg_only(IntInput))
tf_export("raw_ops.IntInput")(IntInput)
def int_input_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int_input
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.int32)
_inputs_flat = [a]
_attrs = None
_result = _execute.execute(b"IntInput", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("IntInput")(None)
@_dispatch.add_dispatch_list
@tf_export('int_input_float_input')
def int_input_float_input(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `int32`.
b: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"IntInputFloatInput", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return int_input_float_input_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_input_float_input, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"IntInputFloatInput", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_input_float_input, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def IntInputFloatInput(a, b, name=None):
return int_input_float_input(a=a, b=b, name=name)
IntInputFloatInput.__doc__ = int_input_float_input.__doc__
IntInputFloatInput = _doc_controls.do_not_generate_docs(_kwarg_only(IntInputFloatInput))
tf_export("raw_ops.IntInputFloatInput")(IntInputFloatInput)
def int_input_float_input_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int_input_float_input
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.int32)
b = _ops.convert_to_tensor(b, _dtypes.float32)
_inputs_flat = [a, b]
_attrs = None
_result = _execute.execute(b"IntInputFloatInput", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("IntInputFloatInput")(None)
@_dispatch.add_dispatch_list
@tf_export('int_input_int_output')
def int_input_int_output(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"IntInputIntOutput", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return int_input_int_output_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_input_int_output, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"IntInputIntOutput", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_input_int_output, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"IntInputIntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def IntInputIntOutput(a, name=None):
return int_input_int_output(a=a, name=name)
IntInputIntOutput.__doc__ = int_input_int_output.__doc__
IntInputIntOutput = _doc_controls.do_not_generate_docs(_kwarg_only(IntInputIntOutput))
tf_export("raw_ops.IntInputIntOutput")(IntInputIntOutput)
def int_input_int_output_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int_input_int_output
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.int32)
_inputs_flat = [a]
_attrs = None
_result = _execute.execute(b"IntInputIntOutput", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"IntInputIntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("IntInputIntOutput")(None)
@_dispatch.add_dispatch_list
@tf_export('int_output')
def int_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"IntOutput", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return int_output_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"IntOutput", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"IntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def IntOutput(name=None):
return int_output(name=name)
IntOutput.__doc__ = int_output.__doc__
IntOutput = _doc_controls.do_not_generate_docs(_kwarg_only(IntOutput))
tf_export("raw_ops.IntOutput")(IntOutput)
def int_output_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int_output
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"IntOutput", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"IntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("IntOutput")(None)
_int_output_float_output_outputs = ["a", "b"]
_IntOutputFloatOutputOutput = _collections.namedtuple(
"IntOutputFloatOutput", _int_output_float_output_outputs)
@_dispatch.add_dispatch_list
@tf_export('int_output_float_output')
def int_output_float_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b).
a: A `Tensor` of type `int32`.
b: A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"IntOutputFloatOutput", name, _ctx._post_execution_callbacks)
_result = _IntOutputFloatOutputOutput._make(_result)
return _result
except _core._FallbackException:
try:
return int_output_float_output_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_output_float_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"IntOutputFloatOutput", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
int_output_float_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"IntOutputFloatOutput", _inputs_flat, _attrs, _result, name)
_result = _IntOutputFloatOutputOutput._make(_result)
return _result
def IntOutputFloatOutput(name=None):
return int_output_float_output(name=name)
IntOutputFloatOutput.__doc__ = int_output_float_output.__doc__
IntOutputFloatOutput = _doc_controls.do_not_generate_docs(_kwarg_only(IntOutputFloatOutput))
tf_export("raw_ops.IntOutputFloatOutput")(IntOutputFloatOutput)
def int_output_float_output_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function int_output_float_output
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"IntOutputFloatOutput", 2, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"IntOutputFloatOutput", _inputs_flat, _attrs, _result, name)
_result = _IntOutputFloatOutputOutput._make(_result)
return _result
_ops.RegisterShape("IntOutputFloatOutput")(None)
@_dispatch.add_dispatch_list
@tf_export('kernel_label')
def kernel_label(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `string`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"KernelLabel", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return kernel_label_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
kernel_label, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"KernelLabel", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
kernel_label, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"KernelLabel", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def KernelLabel(name=None):
return kernel_label(name=name)
KernelLabel.__doc__ = kernel_label.__doc__
KernelLabel = _doc_controls.do_not_generate_docs(_kwarg_only(KernelLabel))
tf_export("raw_ops.KernelLabel")(KernelLabel)
def kernel_label_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function kernel_label
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"KernelLabel", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"KernelLabel", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("KernelLabel")(None)
@_dispatch.add_dispatch_list
@tf_export('kernel_label_required')
def kernel_label_required(input, name=None):
r"""TODO: add doc.
Args:
input: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `string`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"KernelLabelRequired", name, _ctx._post_execution_callbacks, input)
return _result
except _core._FallbackException:
try:
return kernel_label_required_eager_fallback(
input, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
kernel_label_required, input=input, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"KernelLabelRequired", input=input, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
kernel_label_required, input=input, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"KernelLabelRequired", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def KernelLabelRequired(input, name=None):
return kernel_label_required(input=input, name=name)
KernelLabelRequired.__doc__ = kernel_label_required.__doc__
KernelLabelRequired = _doc_controls.do_not_generate_docs(_kwarg_only(KernelLabelRequired))
tf_export("raw_ops.KernelLabelRequired")(KernelLabelRequired)
def kernel_label_required_eager_fallback(input, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function kernel_label_required
"""
_ctx = ctx if ctx else _context.context()
input = _ops.convert_to_tensor(input, _dtypes.int32)
_inputs_flat = [input]
_attrs = None
_result = _execute.execute(b"KernelLabelRequired", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"KernelLabelRequired", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("KernelLabelRequired")(None)
@_dispatch.add_dispatch_list
@tf_export('list_input')
def list_input(a, name=None):
r"""TODO: add doc.
Args:
a: A list of at least 1 `Tensor` objects with the same type.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ListInput", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return list_input_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
list_input, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'list_input' Op, not %r." % a)
_attr_N = len(a)
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ListInput", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
list_input, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def ListInput(a, name=None):
return list_input(a=a, name=name)
ListInput.__doc__ = list_input.__doc__
ListInput = _doc_controls.do_not_generate_docs(_kwarg_only(ListInput))
tf_export("raw_ops.ListInput")(ListInput)
def list_input_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function list_input
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'list_input' Op, not %r." % a)
_attr_N = len(a)
_attr_T, a = _execute.args_to_matching_eager(list(a), _ctx)
_inputs_flat = list(a)
_attrs = ("N", _attr_N, "T", _attr_T)
_result = _execute.execute(b"ListInput", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("ListInput")(None)
@_dispatch.add_dispatch_list
@tf_export('list_output')
def list_output(T, name=None):
r"""TODO: add doc.
Args:
T: A list of `tf.DTypes` that has length `>= 1`.
name: A name for the operation (optional).
Returns:
A list of `Tensor` objects of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ListOutput", name, _ctx._post_execution_callbacks, "T", T)
return _result
except _core._FallbackException:
try:
return list_output_eager_fallback(
T=T, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
list_output, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(T, (list, tuple)):
raise TypeError(
"Expected list for 'T' argument to "
"'list_output' Op, not %r." % T)
T = [_execute.make_type(_t, "T") for _t in T]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ListOutput", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
list_output, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"ListOutput", _inputs_flat, _attrs, _result, name)
return _result
def ListOutput(T, name=None):
return list_output(T=T, name=name)
ListOutput.__doc__ = list_output.__doc__
ListOutput = _doc_controls.do_not_generate_docs(_kwarg_only(ListOutput))
tf_export("raw_ops.ListOutput")(ListOutput)
def list_output_eager_fallback(T, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function list_output
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(T, (list, tuple)):
raise TypeError(
"Expected list for 'T' argument to "
"'list_output' Op, not %r." % T)
T = [_execute.make_type(_t, "T") for _t in T]
_inputs_flat = []
_attrs = ("T", T)
_result = _execute.execute(b"ListOutput", len(T), inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"ListOutput", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("ListOutput")(None)
_mixed_struct_outputs = ["a", "b"]
_MixedStructOutput = _collections.namedtuple(
"MixedStruct", _mixed_struct_outputs)
@_dispatch.add_dispatch_list
@tf_export('mixed_struct')
def mixed_struct(n_a, name=None):
r"""TODO: add doc.
Args:
n_a: An `int` that is `>= 0`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b).
a: A list of `n_a` `Tensor` objects with type `int32`.
b: A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"MixedStruct", name, _ctx._post_execution_callbacks, "n_a", n_a)
_result = _MixedStructOutput._make(_result)
return _result
except _core._FallbackException:
try:
return mixed_struct_eager_fallback(
n_a=n_a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
mixed_struct, n_a=n_a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
n_a = _execute.make_int(n_a, "n_a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"MixedStruct", n_a=n_a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
mixed_struct, n_a=n_a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("n_a", _op.get_attr("n_a"))
_execute.record_gradient(
"MixedStruct", _inputs_flat, _attrs, _result, name)
_result = [_result[:n_a]] + _result[n_a:]
_result = _MixedStructOutput._make(_result)
return _result
def MixedStruct(n_a, name=None):
return mixed_struct(n_a=n_a, name=name)
MixedStruct.__doc__ = mixed_struct.__doc__
MixedStruct = _doc_controls.do_not_generate_docs(_kwarg_only(MixedStruct))
tf_export("raw_ops.MixedStruct")(MixedStruct)
def mixed_struct_eager_fallback(n_a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function mixed_struct
"""
_ctx = ctx if ctx else _context.context()
n_a = _execute.make_int(n_a, "n_a")
_inputs_flat = []
_attrs = ("n_a", n_a)
_result = _execute.execute(b"MixedStruct", n_a + 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"MixedStruct", _inputs_flat, _attrs, _result, name)
_result = [_result[:n_a]] + _result[n_a:]
_result = _MixedStructOutput._make(_result)
return _result
_ops.RegisterShape("MixedStruct")(None)
@_dispatch.add_dispatch_list
@tf_export('n_in_polymorphic_twice')
def n_in_polymorphic_twice(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects with the same type.
b: A list with the same length as `a` of `Tensor` objects with the same type as `a`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NInPolymorphicTwice", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return n_in_polymorphic_twice_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_in_polymorphic_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_in_polymorphic_twice' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'n_in_polymorphic_twice' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'n_in_polymorphic_twice' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NInPolymorphicTwice", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_in_polymorphic_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def NInPolymorphicTwice(a, b, name=None):
return n_in_polymorphic_twice(a=a, b=b, name=name)
NInPolymorphicTwice.__doc__ = n_in_polymorphic_twice.__doc__
NInPolymorphicTwice = _doc_controls.do_not_generate_docs(_kwarg_only(NInPolymorphicTwice))
tf_export("raw_ops.NInPolymorphicTwice")(NInPolymorphicTwice)
def n_in_polymorphic_twice_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_in_polymorphic_twice
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_in_polymorphic_twice' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'n_in_polymorphic_twice' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'n_in_polymorphic_twice' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
_attr_T, _inputs_T = _execute.args_to_matching_eager(list(a) + list(b), _ctx)
_inputs_T = [_inputs_T[:_attr_N]] + _inputs_T[_attr_N:]
_inputs_T = _inputs_T[:1] + [_inputs_T[1:]]
(a, b) = _inputs_T
_inputs_flat = list(a) + list(b)
_attrs = ("T", _attr_T, "N", _attr_N)
_result = _execute.execute(b"NInPolymorphicTwice", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("NInPolymorphicTwice")(None)
@_dispatch.add_dispatch_list
@tf_export('n_in_twice')
def n_in_twice(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects with type `int32`.
b: A list with the same length as `a` of `Tensor` objects with type `string`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "NInTwice",
name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return n_in_twice_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_in_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_in_twice' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'n_in_twice' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'n_in_twice' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NInTwice", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_in_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def NInTwice(a, b, name=None):
return n_in_twice(a=a, b=b, name=name)
NInTwice.__doc__ = n_in_twice.__doc__
NInTwice = _doc_controls.do_not_generate_docs(_kwarg_only(NInTwice))
tf_export("raw_ops.NInTwice")(NInTwice)
def n_in_twice_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_in_twice
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_in_twice' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'n_in_twice' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'n_in_twice' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
a = _ops.convert_n_to_tensor(a, _dtypes.int32)
b = _ops.convert_n_to_tensor(b, _dtypes.string)
_inputs_flat = list(a) + list(b)
_attrs = ("N", _attr_N)
_result = _execute.execute(b"NInTwice", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("NInTwice")(None)
@_dispatch.add_dispatch_list
@tf_export('n_in_two_type_variables')
def n_in_two_type_variables(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects with the same type.
b: A list with the same length as `a` of `Tensor` objects with the same type.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NInTwoTypeVariables", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return n_in_two_type_variables_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_in_two_type_variables, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_in_two_type_variables' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'n_in_two_type_variables' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'n_in_two_type_variables' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NInTwoTypeVariables", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_in_two_type_variables, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def NInTwoTypeVariables(a, b, name=None):
return n_in_two_type_variables(a=a, b=b, name=name)
NInTwoTypeVariables.__doc__ = n_in_two_type_variables.__doc__
NInTwoTypeVariables = _doc_controls.do_not_generate_docs(_kwarg_only(NInTwoTypeVariables))
tf_export("raw_ops.NInTwoTypeVariables")(NInTwoTypeVariables)
def n_in_two_type_variables_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_in_two_type_variables
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_in_two_type_variables' Op, not %r." % a)
_attr_N = len(a)
if not isinstance(b, (list, tuple)):
raise TypeError(
"Expected list for 'b' argument to "
"'n_in_two_type_variables' Op, not %r." % b)
if len(b) != _attr_N:
raise ValueError(
"List argument 'b' to 'n_in_two_type_variables' Op with length %d "
"must match length %d of argument 'a'." %
(len(b), _attr_N))
_attr_S, a = _execute.args_to_matching_eager(list(a), _ctx)
_attr_T, b = _execute.args_to_matching_eager(list(b), _ctx)
_inputs_flat = list(a) + list(b)
_attrs = ("S", _attr_S, "T", _attr_T, "N", _attr_N)
_result = _execute.execute(b"NInTwoTypeVariables", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("NInTwoTypeVariables")(None)
@_dispatch.add_dispatch_list
@tf_export('n_ints_in')
def n_ints_in(a, name=None):
r"""TODO: add doc.
Args:
a: A list of at least 2 `Tensor` objects with type `int32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "NIntsIn",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return n_ints_in_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_ints_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_ints_in' Op, not %r." % a)
_attr_N = len(a)
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NIntsIn", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_ints_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def NIntsIn(a, name=None):
return n_ints_in(a=a, name=name)
NIntsIn.__doc__ = n_ints_in.__doc__
NIntsIn = _doc_controls.do_not_generate_docs(_kwarg_only(NIntsIn))
tf_export("raw_ops.NIntsIn")(NIntsIn)
def n_ints_in_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_ints_in
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_ints_in' Op, not %r." % a)
_attr_N = len(a)
a = _ops.convert_n_to_tensor(a, _dtypes.int32)
_inputs_flat = list(a)
_attrs = ("N", _attr_N)
_result = _execute.execute(b"NIntsIn", 0, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("NIntsIn")(None)
@_dispatch.add_dispatch_list
@tf_export('n_ints_out')
def n_ints_out(N, name=None):
r"""TODO: add doc.
Args:
N: An `int` that is `>= 2`.
name: A name for the operation (optional).
Returns:
A list of `N` `Tensor` objects with type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "NIntsOut",
name, _ctx._post_execution_callbacks, "N", N)
return _result
except _core._FallbackException:
try:
return n_ints_out_eager_fallback(
N=N, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_ints_out, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
N = _execute.make_int(N, "N")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NIntsOut", N=N, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_ints_out, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("N", _op.get_attr("N"))
_execute.record_gradient(
"NIntsOut", _inputs_flat, _attrs, _result, name)
return _result
def NIntsOut(N, name=None):
return n_ints_out(N=N, name=name)
NIntsOut.__doc__ = n_ints_out.__doc__
NIntsOut = _doc_controls.do_not_generate_docs(_kwarg_only(NIntsOut))
tf_export("raw_ops.NIntsOut")(NIntsOut)
def n_ints_out_eager_fallback(N, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_ints_out
"""
_ctx = ctx if ctx else _context.context()
N = _execute.make_int(N, "N")
_inputs_flat = []
_attrs = ("N", N)
_result = _execute.execute(b"NIntsOut", N, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"NIntsOut", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("NIntsOut")(None)
@_dispatch.add_dispatch_list
@tf_export('n_ints_out_default')
def n_ints_out_default(N=3, name=None):
r"""TODO: add doc.
Args:
N: An optional `int` that is `>= 2`. Defaults to `3`.
name: A name for the operation (optional).
Returns:
A list of `N` `Tensor` objects with type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NIntsOutDefault", name, _ctx._post_execution_callbacks, "N", N)
return _result
except _core._FallbackException:
try:
return n_ints_out_default_eager_fallback(
N=N, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_ints_out_default, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if N is None:
N = 3
N = _execute.make_int(N, "N")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NIntsOutDefault", N=N, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_ints_out_default, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("N", _op.get_attr("N"))
_execute.record_gradient(
"NIntsOutDefault", _inputs_flat, _attrs, _result, name)
return _result
def NIntsOutDefault(N=3, name=None):
return n_ints_out_default(N=N, name=name)
NIntsOutDefault.__doc__ = n_ints_out_default.__doc__
NIntsOutDefault = _doc_controls.do_not_generate_docs(_kwarg_only(NIntsOutDefault))
tf_export("raw_ops.NIntsOutDefault")(NIntsOutDefault)
def n_ints_out_default_eager_fallback(N=3, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_ints_out_default
"""
_ctx = ctx if ctx else _context.context()
if N is None:
N = 3
N = _execute.make_int(N, "N")
_inputs_flat = []
_attrs = ("N", N)
_result = _execute.execute(b"NIntsOutDefault", N, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"NIntsOutDefault", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("NIntsOutDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('n_polymorphic_in')
def n_polymorphic_in(a, name=None):
r"""TODO: add doc.
Args:
a: A list of at least 2 `Tensor` objects with the same type.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NPolymorphicIn", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return n_polymorphic_in_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_polymorphic_in' Op, not %r." % a)
_attr_N = len(a)
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NPolymorphicIn", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def NPolymorphicIn(a, name=None):
return n_polymorphic_in(a=a, name=name)
NPolymorphicIn.__doc__ = n_polymorphic_in.__doc__
NPolymorphicIn = _doc_controls.do_not_generate_docs(_kwarg_only(NPolymorphicIn))
tf_export("raw_ops.NPolymorphicIn")(NPolymorphicIn)
def n_polymorphic_in_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_polymorphic_in
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_polymorphic_in' Op, not %r." % a)
_attr_N = len(a)
_attr_T, a = _execute.args_to_matching_eager(list(a), _ctx)
_inputs_flat = list(a)
_attrs = ("T", _attr_T, "N", _attr_N)
_result = _execute.execute(b"NPolymorphicIn", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("NPolymorphicIn")(None)
@_dispatch.add_dispatch_list
@tf_export('n_polymorphic_out')
def n_polymorphic_out(T, N, name=None):
r"""TODO: add doc.
Args:
T: A `tf.DType`.
N: An `int` that is `>= 2`.
name: A name for the operation (optional).
Returns:
A list of `N` `Tensor` objects with type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NPolymorphicOut", name, _ctx._post_execution_callbacks, "T", T, "N",
N)
return _result
except _core._FallbackException:
try:
return n_polymorphic_out_eager_fallback(
T=T, N=N, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_out, T=T, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
T = _execute.make_type(T, "T")
N = _execute.make_int(N, "N")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NPolymorphicOut", T=T, N=N, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_out, T=T, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"), "N", _op.get_attr("N"))
_execute.record_gradient(
"NPolymorphicOut", _inputs_flat, _attrs, _result, name)
return _result
def NPolymorphicOut(T, N, name=None):
return n_polymorphic_out(T=T, N=N, name=name)
NPolymorphicOut.__doc__ = n_polymorphic_out.__doc__
NPolymorphicOut = _doc_controls.do_not_generate_docs(_kwarg_only(NPolymorphicOut))
tf_export("raw_ops.NPolymorphicOut")(NPolymorphicOut)
def n_polymorphic_out_eager_fallback(T, N, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_polymorphic_out
"""
_ctx = ctx if ctx else _context.context()
T = _execute.make_type(T, "T")
N = _execute.make_int(N, "N")
_inputs_flat = []
_attrs = ("T", T, "N", N)
_result = _execute.execute(b"NPolymorphicOut", N, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"NPolymorphicOut", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("NPolymorphicOut")(None)
@_dispatch.add_dispatch_list
@tf_export('n_polymorphic_out_default')
def n_polymorphic_out_default(T=_dtypes.bool, N=2, name=None):
r"""TODO: add doc.
Args:
T: An optional `tf.DType`. Defaults to `tf.bool`.
N: An optional `int` that is `>= 2`. Defaults to `2`.
name: A name for the operation (optional).
Returns:
A list of `N` `Tensor` objects with type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NPolymorphicOutDefault", name, _ctx._post_execution_callbacks, "T",
T, "N", N)
return _result
except _core._FallbackException:
try:
return n_polymorphic_out_default_eager_fallback(
T=T, N=N, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_out_default, T=T, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if T is None:
T = _dtypes.bool
T = _execute.make_type(T, "T")
if N is None:
N = 2
N = _execute.make_int(N, "N")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NPolymorphicOutDefault", T=T, N=N, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_out_default, T=T, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"), "N", _op.get_attr("N"))
_execute.record_gradient(
"NPolymorphicOutDefault", _inputs_flat, _attrs, _result, name)
return _result
def NPolymorphicOutDefault(T=_dtypes.bool, N=2, name=None):
return n_polymorphic_out_default(T=T, N=N, name=name)
NPolymorphicOutDefault.__doc__ = n_polymorphic_out_default.__doc__
NPolymorphicOutDefault = _doc_controls.do_not_generate_docs(_kwarg_only(NPolymorphicOutDefault))
tf_export("raw_ops.NPolymorphicOutDefault")(NPolymorphicOutDefault)
def n_polymorphic_out_default_eager_fallback(T=_dtypes.bool, N=2, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_polymorphic_out_default
"""
_ctx = ctx if ctx else _context.context()
if T is None:
T = _dtypes.bool
T = _execute.make_type(T, "T")
if N is None:
N = 2
N = _execute.make_int(N, "N")
_inputs_flat = []
_attrs = ("T", T, "N", N)
_result = _execute.execute(b"NPolymorphicOutDefault", N,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"NPolymorphicOutDefault", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("NPolymorphicOutDefault")(None)
@_dispatch.add_dispatch_list
@tf_export('n_polymorphic_restrict_in')
def n_polymorphic_restrict_in(a, name=None):
r"""TODO: add doc.
Args:
a: A list of at least 2 `Tensor` objects with the same type in: `string`, `bool`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NPolymorphicRestrictIn", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return n_polymorphic_restrict_in_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_restrict_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_polymorphic_restrict_in' Op, not %r." % a)
_attr_N = len(a)
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NPolymorphicRestrictIn", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_restrict_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def NPolymorphicRestrictIn(a, name=None):
return n_polymorphic_restrict_in(a=a, name=name)
NPolymorphicRestrictIn.__doc__ = n_polymorphic_restrict_in.__doc__
NPolymorphicRestrictIn = _doc_controls.do_not_generate_docs(_kwarg_only(NPolymorphicRestrictIn))
tf_export("raw_ops.NPolymorphicRestrictIn")(NPolymorphicRestrictIn)
def n_polymorphic_restrict_in_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_polymorphic_restrict_in
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'n_polymorphic_restrict_in' Op, not %r." % a)
_attr_N = len(a)
_attr_T, a = _execute.args_to_matching_eager(list(a), _ctx)
_inputs_flat = list(a)
_attrs = ("T", _attr_T, "N", _attr_N)
_result = _execute.execute(b"NPolymorphicRestrictIn", 0,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_result = None
return _result
_ops.RegisterShape("NPolymorphicRestrictIn")(None)
@_dispatch.add_dispatch_list
@tf_export('n_polymorphic_restrict_out')
def n_polymorphic_restrict_out(T, N, name=None):
r"""TODO: add doc.
Args:
T: A `tf.DType` from: `tf.string, tf.bool`.
N: An `int` that is `>= 2`.
name: A name for the operation (optional).
Returns:
A list of `N` `Tensor` objects with type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"NPolymorphicRestrictOut", name, _ctx._post_execution_callbacks, "T",
T, "N", N)
return _result
except _core._FallbackException:
try:
return n_polymorphic_restrict_out_eager_fallback(
T=T, N=N, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_restrict_out, T=T, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
T = _execute.make_type(T, "T")
N = _execute.make_int(N, "N")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"NPolymorphicRestrictOut", T=T, N=N, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
n_polymorphic_restrict_out, T=T, N=N, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"), "N", _op.get_attr("N"))
_execute.record_gradient(
"NPolymorphicRestrictOut", _inputs_flat, _attrs, _result, name)
return _result
def NPolymorphicRestrictOut(T, N, name=None):
return n_polymorphic_restrict_out(T=T, N=N, name=name)
NPolymorphicRestrictOut.__doc__ = n_polymorphic_restrict_out.__doc__
NPolymorphicRestrictOut = _doc_controls.do_not_generate_docs(_kwarg_only(NPolymorphicRestrictOut))
tf_export("raw_ops.NPolymorphicRestrictOut")(NPolymorphicRestrictOut)
def n_polymorphic_restrict_out_eager_fallback(T, N, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function n_polymorphic_restrict_out
"""
_ctx = ctx if ctx else _context.context()
T = _execute.make_type(T, "T")
N = _execute.make_int(N, "N")
_inputs_flat = []
_attrs = ("T", T, "N", N)
_result = _execute.execute(b"NPolymorphicRestrictOut", N,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"NPolymorphicRestrictOut", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("NPolymorphicRestrictOut")(None)
@_dispatch.add_dispatch_list
@tf_export('none')
def none(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "None",
name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return none_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
none, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"None", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
none, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def None_(name=None):
return none(name=name)
None_.__doc__ = none.__doc__
None_ = _doc_controls.do_not_generate_docs(_kwarg_only(None_))
tf_export("raw_ops.None_")(None_)
def none_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function none
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"None", 0, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("None")(None)
@_dispatch.add_dispatch_list
@tf_export('old')
def old(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Old",
name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return old_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
old, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Old", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
old, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def Old(name=None):
return old(name=name)
Old.__doc__ = old.__doc__
Old = _doc_controls.do_not_generate_docs(_kwarg_only(Old))
tf_export("raw_ops.Old")(Old)
def old_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function old
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"Old", 0, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("Old")(None)
@_dispatch.add_dispatch_list
@tf_export('op_with_default_attr')
def op_with_default_attr(default_float=123, name=None):
r"""TODO: add doc.
Args:
default_float: An optional `float`. Defaults to `123`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"OpWithDefaultAttr", name, _ctx._post_execution_callbacks,
"default_float", default_float)
return _result
except _core._FallbackException:
try:
return op_with_default_attr_eager_fallback(
default_float=default_float, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
op_with_default_attr, default_float=default_float, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if default_float is None:
default_float = 123
default_float = _execute.make_float(default_float, "default_float")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"OpWithDefaultAttr", default_float=default_float, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
op_with_default_attr, default_float=default_float, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("default_float", _op.get_attr("default_float"))
_execute.record_gradient(
"OpWithDefaultAttr", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def OpWithDefaultAttr(default_float=123, name=None):
return op_with_default_attr(default_float=default_float, name=name)
OpWithDefaultAttr.__doc__ = op_with_default_attr.__doc__
OpWithDefaultAttr = _doc_controls.do_not_generate_docs(_kwarg_only(OpWithDefaultAttr))
tf_export("raw_ops.OpWithDefaultAttr")(OpWithDefaultAttr)
def op_with_default_attr_eager_fallback(default_float=123, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function op_with_default_attr
"""
_ctx = ctx if ctx else _context.context()
if default_float is None:
default_float = 123
default_float = _execute.make_float(default_float, "default_float")
_inputs_flat = []
_attrs = ("default_float", default_float)
_result = _execute.execute(b"OpWithDefaultAttr", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"OpWithDefaultAttr", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("OpWithDefaultAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('op_with_future_default_attr')
def op_with_future_default_attr(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"OpWithFutureDefaultAttr", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return op_with_future_default_attr_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
op_with_future_default_attr, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"OpWithFutureDefaultAttr", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
op_with_future_default_attr, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def OpWithFutureDefaultAttr(name=None):
return op_with_future_default_attr(name=name)
OpWithFutureDefaultAttr.__doc__ = op_with_future_default_attr.__doc__
OpWithFutureDefaultAttr = _doc_controls.do_not_generate_docs(_kwarg_only(OpWithFutureDefaultAttr))
tf_export("raw_ops.OpWithFutureDefaultAttr")(OpWithFutureDefaultAttr)
def op_with_future_default_attr_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function op_with_future_default_attr
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"OpWithFutureDefaultAttr", 0,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_result = None
return _result
_ops.RegisterShape("OpWithFutureDefaultAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('out_t')
def out_t(T, name=None):
r"""TODO: add doc.
Args:
T: A `tf.DType`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "OutT",
name, _ctx._post_execution_callbacks, "T", T)
return _result
except _core._FallbackException:
try:
return out_t_eager_fallback(
T=T, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
out_t, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
T = _execute.make_type(T, "T")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"OutT", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
out_t, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"OutT", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def OutT(T, name=None):
return out_t(T=T, name=name)
OutT.__doc__ = out_t.__doc__
OutT = _doc_controls.do_not_generate_docs(_kwarg_only(OutT))
tf_export("raw_ops.OutT")(OutT)
def out_t_eager_fallback(T, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function out_t
"""
_ctx = ctx if ctx else _context.context()
T = _execute.make_type(T, "T")
_inputs_flat = []
_attrs = ("T", T)
_result = _execute.execute(b"OutT", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"OutT", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("OutT")(None)
@_dispatch.add_dispatch_list
@tf_export('out_type_list')
def out_type_list(T, name=None):
r"""TODO: add doc.
Args:
T: A list of `tf.DTypes`.
name: A name for the operation (optional).
Returns:
A list of `Tensor` objects of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"OutTypeList", name, _ctx._post_execution_callbacks, "T", T)
return _result
except _core._FallbackException:
try:
return out_type_list_eager_fallback(
T=T, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
out_type_list, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(T, (list, tuple)):
raise TypeError(
"Expected list for 'T' argument to "
"'out_type_list' Op, not %r." % T)
T = [_execute.make_type(_t, "T") for _t in T]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"OutTypeList", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
out_type_list, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"OutTypeList", _inputs_flat, _attrs, _result, name)
return _result
def OutTypeList(T, name=None):
return out_type_list(T=T, name=name)
OutTypeList.__doc__ = out_type_list.__doc__
OutTypeList = _doc_controls.do_not_generate_docs(_kwarg_only(OutTypeList))
tf_export("raw_ops.OutTypeList")(OutTypeList)
def out_type_list_eager_fallback(T, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function out_type_list
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(T, (list, tuple)):
raise TypeError(
"Expected list for 'T' argument to "
"'out_type_list' Op, not %r." % T)
T = [_execute.make_type(_t, "T") for _t in T]
_inputs_flat = []
_attrs = ("T", T)
_result = _execute.execute(b"OutTypeList", len(T), inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"OutTypeList", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("OutTypeList")(None)
@_dispatch.add_dispatch_list
@tf_export('out_type_list_restrict')
def out_type_list_restrict(t, name=None):
r"""TODO: add doc.
Args:
t: A list of `tf.DTypes` from: `tf.string, tf.bool` that has length `>= 1`.
name: A name for the operation (optional).
Returns:
A list of `Tensor` objects of type `t`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"OutTypeListRestrict", name, _ctx._post_execution_callbacks, "t", t)
return _result
except _core._FallbackException:
try:
return out_type_list_restrict_eager_fallback(
t=t, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
out_type_list_restrict, t=t, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(t, (list, tuple)):
raise TypeError(
"Expected list for 't' argument to "
"'out_type_list_restrict' Op, not %r." % t)
t = [_execute.make_type(_t, "t") for _t in t]
try:
_, _, _op = _op_def_lib._apply_op_helper(
"OutTypeListRestrict", t=t, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
out_type_list_restrict, t=t, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("t", _op.get_attr("t"))
_execute.record_gradient(
"OutTypeListRestrict", _inputs_flat, _attrs, _result, name)
return _result
def OutTypeListRestrict(t, name=None):
return out_type_list_restrict(t=t, name=name)
OutTypeListRestrict.__doc__ = out_type_list_restrict.__doc__
OutTypeListRestrict = _doc_controls.do_not_generate_docs(_kwarg_only(OutTypeListRestrict))
tf_export("raw_ops.OutTypeListRestrict")(OutTypeListRestrict)
def out_type_list_restrict_eager_fallback(t, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function out_type_list_restrict
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(t, (list, tuple)):
raise TypeError(
"Expected list for 't' argument to "
"'out_type_list_restrict' Op, not %r." % t)
t = [_execute.make_type(_t, "t") for _t in t]
_inputs_flat = []
_attrs = ("t", t)
_result = _execute.execute(b"OutTypeListRestrict", len(t),
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"OutTypeListRestrict", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("OutTypeListRestrict")(None)
@_dispatch.add_dispatch_list
@tf_export('polymorphic')
def polymorphic(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `a`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"Polymorphic", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return polymorphic_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
polymorphic, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Polymorphic", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
polymorphic, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"Polymorphic", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def Polymorphic(a, name=None):
return polymorphic(a=a, name=name)
Polymorphic.__doc__ = polymorphic.__doc__
Polymorphic = _doc_controls.do_not_generate_docs(_kwarg_only(Polymorphic))
tf_export("raw_ops.Polymorphic")(Polymorphic)
def polymorphic_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function polymorphic
"""
_ctx = ctx if ctx else _context.context()
_attr_T, (a,) = _execute.args_to_matching_eager([a], _ctx)
_inputs_flat = [a]
_attrs = ("T", _attr_T)
_result = _execute.execute(b"Polymorphic", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"Polymorphic", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("Polymorphic")(None)
@_dispatch.add_dispatch_list
@tf_export('polymorphic_default_out')
def polymorphic_default_out(T=_dtypes.string, name=None):
r"""TODO: add doc.
Args:
T: An optional `tf.DType`. Defaults to `tf.string`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"PolymorphicDefaultOut", name, _ctx._post_execution_callbacks, "T", T)
return _result
except _core._FallbackException:
try:
return polymorphic_default_out_eager_fallback(
T=T, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
polymorphic_default_out, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if T is None:
T = _dtypes.string
T = _execute.make_type(T, "T")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"PolymorphicDefaultOut", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
polymorphic_default_out, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"PolymorphicDefaultOut", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def PolymorphicDefaultOut(T=_dtypes.string, name=None):
return polymorphic_default_out(T=T, name=name)
PolymorphicDefaultOut.__doc__ = polymorphic_default_out.__doc__
PolymorphicDefaultOut = _doc_controls.do_not_generate_docs(_kwarg_only(PolymorphicDefaultOut))
tf_export("raw_ops.PolymorphicDefaultOut")(PolymorphicDefaultOut)
def polymorphic_default_out_eager_fallback(T=_dtypes.string, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function polymorphic_default_out
"""
_ctx = ctx if ctx else _context.context()
if T is None:
T = _dtypes.string
T = _execute.make_type(T, "T")
_inputs_flat = []
_attrs = ("T", T)
_result = _execute.execute(b"PolymorphicDefaultOut", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"PolymorphicDefaultOut", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("PolymorphicDefaultOut")(None)
@_dispatch.add_dispatch_list
@tf_export('polymorphic_out')
def polymorphic_out(T, name=None):
r"""TODO: add doc.
Args:
T: A `tf.DType`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"PolymorphicOut", name, _ctx._post_execution_callbacks, "T", T)
return _result
except _core._FallbackException:
try:
return polymorphic_out_eager_fallback(
T=T, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
polymorphic_out, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
T = _execute.make_type(T, "T")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"PolymorphicOut", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
polymorphic_out, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"PolymorphicOut", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def PolymorphicOut(T, name=None):
return polymorphic_out(T=T, name=name)
PolymorphicOut.__doc__ = polymorphic_out.__doc__
PolymorphicOut = _doc_controls.do_not_generate_docs(_kwarg_only(PolymorphicOut))
tf_export("raw_ops.PolymorphicOut")(PolymorphicOut)
def polymorphic_out_eager_fallback(T, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function polymorphic_out
"""
_ctx = ctx if ctx else _context.context()
T = _execute.make_type(T, "T")
_inputs_flat = []
_attrs = ("T", T)
_result = _execute.execute(b"PolymorphicOut", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"PolymorphicOut", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("PolymorphicOut")(None)
@_dispatch.add_dispatch_list
@tf_export('ref_in')
def ref_in(a, name=None):
r"""TODO: add doc.
Args:
a: A mutable `Tensor`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_in op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefIn", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_in, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def RefIn(a, name=None):
return ref_in(a=a, name=name)
RefIn.__doc__ = ref_in.__doc__
RefIn = _doc_controls.do_not_generate_docs(_kwarg_only(RefIn))
tf_export("raw_ops.RefIn")(RefIn)
def ref_in_eager_fallback(a, name=None, ctx=None):
raise RuntimeError("ref_in op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefIn")(None)
@_dispatch.add_dispatch_list
@tf_export('ref_input_float_input')
def ref_input_float_input(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type mutable `float32`.
b: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_input_float_input op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefInputFloatInput", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_input_float_input, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def RefInputFloatInput(a, b, name=None):
return ref_input_float_input(a=a, b=b, name=name)
RefInputFloatInput.__doc__ = ref_input_float_input.__doc__
RefInputFloatInput = _doc_controls.do_not_generate_docs(_kwarg_only(RefInputFloatInput))
tf_export("raw_ops.RefInputFloatInput")(RefInputFloatInput)
def ref_input_float_input_eager_fallback(a, b, name=None, ctx=None):
raise RuntimeError("ref_input_float_input op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefInputFloatInput")(None)
@_dispatch.add_dispatch_list
@tf_export('ref_input_float_input_int_output')
def ref_input_float_input_int_output(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type mutable `float32`.
b: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_input_float_input_int_output op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefInputFloatInputIntOutput", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_input_float_input_int_output, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"RefInputFloatInputIntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def RefInputFloatInputIntOutput(a, b, name=None):
return ref_input_float_input_int_output(a=a, b=b, name=name)
RefInputFloatInputIntOutput.__doc__ = ref_input_float_input_int_output.__doc__
RefInputFloatInputIntOutput = _doc_controls.do_not_generate_docs(_kwarg_only(RefInputFloatInputIntOutput))
tf_export("raw_ops.RefInputFloatInputIntOutput")(RefInputFloatInputIntOutput)
def ref_input_float_input_int_output_eager_fallback(a, b, name=None, ctx=None):
raise RuntimeError("ref_input_float_input_int_output op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefInputFloatInputIntOutput")(None)
@_dispatch.add_dispatch_list
@tf_export('ref_input_int_input')
def ref_input_int_input(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type mutable `int32`.
b: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_input_int_input op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefInputIntInput", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_input_int_input, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def RefInputIntInput(a, b, name=None):
return ref_input_int_input(a=a, b=b, name=name)
RefInputIntInput.__doc__ = ref_input_int_input.__doc__
RefInputIntInput = _doc_controls.do_not_generate_docs(_kwarg_only(RefInputIntInput))
tf_export("raw_ops.RefInputIntInput")(RefInputIntInput)
def ref_input_int_input_eager_fallback(a, b, name=None, ctx=None):
raise RuntimeError("ref_input_int_input op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefInputIntInput")(None)
@_dispatch.add_dispatch_list
@tf_export('ref_out')
def ref_out(T, name=None):
r"""TODO: add doc.
Args:
T: A `tf.DType`.
name: A name for the operation (optional).
Returns:
A mutable `Tensor` of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_out op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
T = _execute.make_type(T, "T")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefOut", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_out, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"RefOut", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def RefOut(T, name=None):
return ref_out(T=T, name=name)
RefOut.__doc__ = ref_out.__doc__
RefOut = _doc_controls.do_not_generate_docs(_kwarg_only(RefOut))
tf_export("raw_ops.RefOut")(RefOut)
def ref_out_eager_fallback(T, name=None, ctx=None):
raise RuntimeError("ref_out op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefOut")(None)
@_dispatch.add_dispatch_list
@tf_export('ref_output')
def ref_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type mutable `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_output op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefOutput", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"RefOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def RefOutput(name=None):
return ref_output(name=name)
RefOutput.__doc__ = ref_output.__doc__
RefOutput = _doc_controls.do_not_generate_docs(_kwarg_only(RefOutput))
tf_export("raw_ops.RefOutput")(RefOutput)
def ref_output_eager_fallback(name=None, ctx=None):
raise RuntimeError("ref_output op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefOutput")(None)
_ref_output_float_output_outputs = ["a", "b"]
_RefOutputFloatOutputOutput = _collections.namedtuple(
"RefOutputFloatOutput", _ref_output_float_output_outputs)
@_dispatch.add_dispatch_list
@tf_export('ref_output_float_output')
def ref_output_float_output(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b).
a: A `Tensor` of type mutable `float32`.
b: A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("ref_output_float_output op does not support eager execution. Arg 'a' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RefOutputFloatOutput", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
ref_output_float_output, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"RefOutputFloatOutput", _inputs_flat, _attrs, _result, name)
_result = _RefOutputFloatOutputOutput._make(_result)
return _result
def RefOutputFloatOutput(name=None):
return ref_output_float_output(name=name)
RefOutputFloatOutput.__doc__ = ref_output_float_output.__doc__
RefOutputFloatOutput = _doc_controls.do_not_generate_docs(_kwarg_only(RefOutputFloatOutput))
tf_export("raw_ops.RefOutputFloatOutput")(RefOutputFloatOutput)
def ref_output_float_output_eager_fallback(name=None, ctx=None):
raise RuntimeError("ref_output_float_output op does not support eager execution. Arg 'a' is a ref.")
_ops.RegisterShape("RefOutputFloatOutput")(None)
@_dispatch.add_dispatch_list
@tf_export('requires_older_graph_version')
def requires_older_graph_version(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"RequiresOlderGraphVersion", name, _ctx._post_execution_callbacks)
return _result
except _core._FallbackException:
try:
return requires_older_graph_version_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
requires_older_graph_version, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"RequiresOlderGraphVersion", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
requires_older_graph_version, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"RequiresOlderGraphVersion", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def RequiresOlderGraphVersion(name=None):
return requires_older_graph_version(name=name)
RequiresOlderGraphVersion.__doc__ = requires_older_graph_version.__doc__
RequiresOlderGraphVersion = _doc_controls.do_not_generate_docs(_kwarg_only(RequiresOlderGraphVersion))
tf_export("raw_ops.RequiresOlderGraphVersion")(RequiresOlderGraphVersion)
def requires_older_graph_version_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function requires_older_graph_version
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"RequiresOlderGraphVersion", 1,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"RequiresOlderGraphVersion", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("RequiresOlderGraphVersion")(None)
@_dispatch.add_dispatch_list
@tf_export('reserved_attr')
def reserved_attr(range, name=None):
r"""TODO: add doc.
Args:
range: An `int`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ReservedAttr", name, _ctx._post_execution_callbacks, "range", range)
return _result
except _core._FallbackException:
try:
return reserved_attr_eager_fallback(
range=range, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
reserved_attr, range=range, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
range = _execute.make_int(range, "range")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ReservedAttr", range=range, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
reserved_attr, range=range, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def ReservedAttr(range, name=None):
return reserved_attr(range=range, name=name)
ReservedAttr.__doc__ = reserved_attr.__doc__
ReservedAttr = _doc_controls.do_not_generate_docs(_kwarg_only(ReservedAttr))
tf_export("raw_ops.ReservedAttr")(ReservedAttr)
def reserved_attr_eager_fallback(range, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function reserved_attr
"""
_ctx = ctx if ctx else _context.context()
range = _execute.make_int(range, "range")
_inputs_flat = []
_attrs = ("range", range)
_result = _execute.execute(b"ReservedAttr", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("ReservedAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('reserved_input')
def reserved_input(input, name=None):
r"""TODO: add doc.
Args:
input: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ReservedInput", name, _ctx._post_execution_callbacks, input)
return _result
except _core._FallbackException:
try:
return reserved_input_eager_fallback(
input, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
reserved_input, input=input, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ReservedInput", input=input, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
reserved_input, input=input, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def ReservedInput(input, name=None):
return reserved_input(input=input, name=name)
ReservedInput.__doc__ = reserved_input.__doc__
ReservedInput = _doc_controls.do_not_generate_docs(_kwarg_only(ReservedInput))
tf_export("raw_ops.ReservedInput")(ReservedInput)
def reserved_input_eager_fallback(input, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function reserved_input
"""
_ctx = ctx if ctx else _context.context()
input = _ops.convert_to_tensor(input, _dtypes.int32)
_inputs_flat = [input]
_attrs = None
_result = _execute.execute(b"ReservedInput", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("ReservedInput")(None)
@_dispatch.add_dispatch_list
@tf_export('resource_create_op')
def resource_create_op(resource, name=None):
r"""TODO: add doc.
Args:
resource: A `Tensor` of type `resource`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ResourceCreateOp", name, _ctx._post_execution_callbacks, resource)
return _result
except _core._FallbackException:
try:
return resource_create_op_eager_fallback(
resource, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
resource_create_op, resource=resource, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ResourceCreateOp", resource=resource, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
resource_create_op, resource=resource, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def ResourceCreateOp(resource, name=None):
return resource_create_op(resource=resource, name=name)
ResourceCreateOp.__doc__ = resource_create_op.__doc__
ResourceCreateOp = _doc_controls.do_not_generate_docs(_kwarg_only(ResourceCreateOp))
tf_export("raw_ops.ResourceCreateOp")(ResourceCreateOp)
def resource_create_op_eager_fallback(resource, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function resource_create_op
"""
_ctx = ctx if ctx else _context.context()
resource = _ops.convert_to_tensor(resource, _dtypes.resource)
_inputs_flat = [resource]
_attrs = None
_result = _execute.execute(b"ResourceCreateOp", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("ResourceCreateOp")(None)
@_dispatch.add_dispatch_list
@tf_export('resource_initialized_op')
def resource_initialized_op(resource, name=None):
r"""TODO: add doc.
Args:
resource: A `Tensor` of type `resource`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `bool`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ResourceInitializedOp", name, _ctx._post_execution_callbacks,
resource)
return _result
except _core._FallbackException:
try:
return resource_initialized_op_eager_fallback(
resource, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
resource_initialized_op, resource=resource, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ResourceInitializedOp", resource=resource, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
resource_initialized_op, resource=resource, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"ResourceInitializedOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def ResourceInitializedOp(resource, name=None):
return resource_initialized_op(resource=resource, name=name)
ResourceInitializedOp.__doc__ = resource_initialized_op.__doc__
ResourceInitializedOp = _doc_controls.do_not_generate_docs(_kwarg_only(ResourceInitializedOp))
tf_export("raw_ops.ResourceInitializedOp")(ResourceInitializedOp)
def resource_initialized_op_eager_fallback(resource, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function resource_initialized_op
"""
_ctx = ctx if ctx else _context.context()
resource = _ops.convert_to_tensor(resource, _dtypes.resource)
_inputs_flat = [resource]
_attrs = None
_result = _execute.execute(b"ResourceInitializedOp", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"ResourceInitializedOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("ResourceInitializedOp")(None)
@_dispatch.add_dispatch_list
@tf_export('resource_using_op')
def resource_using_op(resource, name=None):
r"""TODO: add doc.
Args:
resource: A `Tensor` of type `resource`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"ResourceUsingOp", name, _ctx._post_execution_callbacks, resource)
return _result
except _core._FallbackException:
try:
return resource_using_op_eager_fallback(
resource, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
resource_using_op, resource=resource, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"ResourceUsingOp", resource=resource, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
resource_using_op, resource=resource, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def ResourceUsingOp(resource, name=None):
return resource_using_op(resource=resource, name=name)
ResourceUsingOp.__doc__ = resource_using_op.__doc__
ResourceUsingOp = _doc_controls.do_not_generate_docs(_kwarg_only(ResourceUsingOp))
tf_export("raw_ops.ResourceUsingOp")(ResourceUsingOp)
def resource_using_op_eager_fallback(resource, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function resource_using_op
"""
_ctx = ctx if ctx else _context.context()
resource = _ops.convert_to_tensor(resource, _dtypes.resource)
_inputs_flat = [resource]
_attrs = None
_result = _execute.execute(b"ResourceUsingOp", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("ResourceUsingOp")(None)
@_dispatch.add_dispatch_list
@tf_export('restrict')
def restrict(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor`. Must be one of the following types: `string`, `bool`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `a`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Restrict",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return restrict_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
restrict, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Restrict", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
restrict, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"Restrict", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def Restrict(a, name=None):
return restrict(a=a, name=name)
Restrict.__doc__ = restrict.__doc__
Restrict = _doc_controls.do_not_generate_docs(_kwarg_only(Restrict))
tf_export("raw_ops.Restrict")(Restrict)
def restrict_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function restrict
"""
_ctx = ctx if ctx else _context.context()
_attr_T, (a,) = _execute.args_to_matching_eager([a], _ctx)
_inputs_flat = [a]
_attrs = ("T", _attr_T)
_result = _execute.execute(b"Restrict", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"Restrict", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("Restrict")(None)
@_dispatch.add_dispatch_list
@tf_export('simple')
def simple(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Simple",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return simple_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
simple, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Simple", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
simple, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"Simple", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def Simple(a, name=None):
return simple(a=a, name=name)
Simple.__doc__ = simple.__doc__
Simple = _doc_controls.do_not_generate_docs(_kwarg_only(Simple))
tf_export("raw_ops.Simple")(Simple)
def simple_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function simple
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.int32)
_inputs_flat = [a]
_attrs = None
_result = _execute.execute(b"Simple", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"Simple", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("Simple")(None)
@_dispatch.add_dispatch_list
@tf_export('simple_struct')
def simple_struct(n_a, name=None):
r"""TODO: add doc.
Args:
n_a: An `int` that is `>= 0`.
name: A name for the operation (optional).
Returns:
A list of `n_a` `Tensor` objects with type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"SimpleStruct", name, _ctx._post_execution_callbacks, "n_a", n_a)
return _result
except _core._FallbackException:
try:
return simple_struct_eager_fallback(
n_a=n_a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
simple_struct, n_a=n_a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
n_a = _execute.make_int(n_a, "n_a")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"SimpleStruct", n_a=n_a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
simple_struct, n_a=n_a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("n_a", _op.get_attr("n_a"))
_execute.record_gradient(
"SimpleStruct", _inputs_flat, _attrs, _result, name)
return _result
def SimpleStruct(n_a, name=None):
return simple_struct(n_a=n_a, name=name)
SimpleStruct.__doc__ = simple_struct.__doc__
SimpleStruct = _doc_controls.do_not_generate_docs(_kwarg_only(SimpleStruct))
tf_export("raw_ops.SimpleStruct")(SimpleStruct)
def simple_struct_eager_fallback(n_a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function simple_struct
"""
_ctx = ctx if ctx else _context.context()
n_a = _execute.make_int(n_a, "n_a")
_inputs_flat = []
_attrs = ("n_a", n_a)
_result = _execute.execute(b"SimpleStruct", n_a, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"SimpleStruct", _inputs_flat, _attrs, _result, name)
return _result
_ops.RegisterShape("SimpleStruct")(None)
@_dispatch.add_dispatch_list
@tf_export('string_list_attr')
def string_list_attr(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of `strings`.
b: A `string`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"StringListAttr", name, _ctx._post_execution_callbacks, "a", a, "b",
b)
return _result
except _core._FallbackException:
try:
return string_list_attr_eager_fallback(
a=a, b=b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
string_list_attr, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'string_list_attr' Op, not %r." % a)
a = [_execute.make_str(_s, "a") for _s in a]
b = _execute.make_str(b, "b")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"StringListAttr", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
string_list_attr, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def StringListAttr(a, b, name=None):
return string_list_attr(a=a, b=b, name=name)
StringListAttr.__doc__ = string_list_attr.__doc__
StringListAttr = _doc_controls.do_not_generate_docs(_kwarg_only(StringListAttr))
tf_export("raw_ops.StringListAttr")(StringListAttr)
def string_list_attr_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function string_list_attr
"""
_ctx = ctx if ctx else _context.context()
if not isinstance(a, (list, tuple)):
raise TypeError(
"Expected list for 'a' argument to "
"'string_list_attr' Op, not %r." % a)
a = [_execute.make_str(_s, "a") for _s in a]
b = _execute.make_str(b, "b")
_inputs_flat = []
_attrs = ("a", a, "b", b)
_result = _execute.execute(b"StringListAttr", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("StringListAttr")(None)
@_dispatch.add_dispatch_list
@tf_export('stub_resource_handle_op')
def stub_resource_handle_op(container="", shared_name="", name=None):
r"""TODO: add doc.
Args:
container: An optional `string`. Defaults to `""`.
shared_name: An optional `string`. Defaults to `""`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `resource`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"StubResourceHandleOp", name, _ctx._post_execution_callbacks,
"container", container, "shared_name", shared_name)
return _result
except _core._FallbackException:
try:
return stub_resource_handle_op_eager_fallback(
container=container, shared_name=shared_name, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
stub_resource_handle_op, container=container,
shared_name=shared_name, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
if container is None:
container = ""
container = _execute.make_str(container, "container")
if shared_name is None:
shared_name = ""
shared_name = _execute.make_str(shared_name, "shared_name")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"StubResourceHandleOp", container=container, shared_name=shared_name,
name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
stub_resource_handle_op, container=container,
shared_name=shared_name, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("container", _op.get_attr("container"), "shared_name",
_op.get_attr("shared_name"))
_execute.record_gradient(
"StubResourceHandleOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def StubResourceHandleOp(container="", shared_name="", name=None):
return stub_resource_handle_op(container=container, shared_name=shared_name, name=name)
StubResourceHandleOp.__doc__ = stub_resource_handle_op.__doc__
StubResourceHandleOp = _doc_controls.do_not_generate_docs(_kwarg_only(StubResourceHandleOp))
tf_export("raw_ops.StubResourceHandleOp")(StubResourceHandleOp)
def stub_resource_handle_op_eager_fallback(container="", shared_name="", name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function stub_resource_handle_op
"""
_ctx = ctx if ctx else _context.context()
if container is None:
container = ""
container = _execute.make_str(container, "container")
if shared_name is None:
shared_name = ""
shared_name = _execute.make_str(shared_name, "shared_name")
_inputs_flat = []
_attrs = ("container", container, "shared_name", shared_name)
_result = _execute.execute(b"StubResourceHandleOp", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"StubResourceHandleOp", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("StubResourceHandleOp")(None)
@_dispatch.add_dispatch_list
@tf_export('test_attr')
def test_attr(T, name=None):
r"""TODO: add doc.
Args:
T: A `tf.DType` from: `tf.float32, tf.float64`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `T`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "TestAttr",
name, _ctx._post_execution_callbacks, "T", T)
return _result
except _core._FallbackException:
try:
return test_attr_eager_fallback(
T=T, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
test_attr, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
T = _execute.make_type(T, "T")
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TestAttr", T=T, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
test_attr, T=T, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"TestAttr", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def TestAttr(T, name=None):
return test_attr(T=T, name=name)
TestAttr.__doc__ = test_attr.__doc__
TestAttr = _doc_controls.do_not_generate_docs(_kwarg_only(TestAttr))
tf_export("raw_ops.TestAttr")(TestAttr)
def test_attr_eager_fallback(T, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function test_attr
"""
_ctx = ctx if ctx else _context.context()
T = _execute.make_type(T, "T")
_inputs_flat = []
_attrs = ("T", T)
_result = _execute.execute(b"TestAttr", 1, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"TestAttr", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("TestAttr")(None)
_test_string_output_outputs = ["output1", "output2"]
_TestStringOutputOutput = _collections.namedtuple(
"TestStringOutput", _test_string_output_outputs)
@_dispatch.add_dispatch_list
@tf_export('test_string_output')
def test_string_output(input, name=None):
r"""TODO: add doc.
Args:
input: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (output1, output2).
output1: A `Tensor` of type `float32`.
output2: A `Tensor` of type `string`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TestStringOutput", name, _ctx._post_execution_callbacks, input)
_result = _TestStringOutputOutput._make(_result)
return _result
except _core._FallbackException:
try:
return test_string_output_eager_fallback(
input, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
test_string_output, input=input, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TestStringOutput", input=input, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
test_string_output, input=input, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"TestStringOutput", _inputs_flat, _attrs, _result, name)
_result = _TestStringOutputOutput._make(_result)
return _result
def TestStringOutput(input, name=None):
return test_string_output(input=input, name=name)
TestStringOutput.__doc__ = test_string_output.__doc__
TestStringOutput = _doc_controls.do_not_generate_docs(_kwarg_only(TestStringOutput))
tf_export("raw_ops.TestStringOutput")(TestStringOutput)
def test_string_output_eager_fallback(input, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function test_string_output
"""
_ctx = ctx if ctx else _context.context()
input = _ops.convert_to_tensor(input, _dtypes.float32)
_inputs_flat = [input]
_attrs = None
_result = _execute.execute(b"TestStringOutput", 2, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"TestStringOutput", _inputs_flat, _attrs, _result, name)
_result = _TestStringOutputOutput._make(_result)
return _result
_ops.RegisterShape("TestStringOutput")(None)
@_dispatch.add_dispatch_list
@tf_export('two_float_inputs')
def two_float_inputs(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TwoFloatInputs", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return two_float_inputs_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_inputs, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoFloatInputs", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_inputs, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def TwoFloatInputs(a, b, name=None):
return two_float_inputs(a=a, b=b, name=name)
TwoFloatInputs.__doc__ = two_float_inputs.__doc__
TwoFloatInputs = _doc_controls.do_not_generate_docs(_kwarg_only(TwoFloatInputs))
tf_export("raw_ops.TwoFloatInputs")(TwoFloatInputs)
def two_float_inputs_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function two_float_inputs
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
b = _ops.convert_to_tensor(b, _dtypes.float32)
_inputs_flat = [a, b]
_attrs = None
_result = _execute.execute(b"TwoFloatInputs", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("TwoFloatInputs")(None)
@_dispatch.add_dispatch_list
@tf_export('two_float_inputs_float_output')
def two_float_inputs_float_output(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TwoFloatInputsFloatOutput", name, _ctx._post_execution_callbacks, a,
b)
return _result
except _core._FallbackException:
try:
return two_float_inputs_float_output_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_inputs_float_output, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoFloatInputsFloatOutput", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_inputs_float_output, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"TwoFloatInputsFloatOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def TwoFloatInputsFloatOutput(a, b, name=None):
return two_float_inputs_float_output(a=a, b=b, name=name)
TwoFloatInputsFloatOutput.__doc__ = two_float_inputs_float_output.__doc__
TwoFloatInputsFloatOutput = _doc_controls.do_not_generate_docs(_kwarg_only(TwoFloatInputsFloatOutput))
tf_export("raw_ops.TwoFloatInputsFloatOutput")(TwoFloatInputsFloatOutput)
def two_float_inputs_float_output_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function two_float_inputs_float_output
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
b = _ops.convert_to_tensor(b, _dtypes.float32)
_inputs_flat = [a, b]
_attrs = None
_result = _execute.execute(b"TwoFloatInputsFloatOutput", 1,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"TwoFloatInputsFloatOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("TwoFloatInputsFloatOutput")(None)
@_dispatch.add_dispatch_list
@tf_export('two_float_inputs_int_output')
def two_float_inputs_int_output(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `float32`.
name: A name for the operation (optional).
Returns:
A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TwoFloatInputsIntOutput", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return two_float_inputs_int_output_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_inputs_int_output, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoFloatInputsIntOutput", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_inputs_int_output, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"TwoFloatInputsIntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def TwoFloatInputsIntOutput(a, b, name=None):
return two_float_inputs_int_output(a=a, b=b, name=name)
TwoFloatInputsIntOutput.__doc__ = two_float_inputs_int_output.__doc__
TwoFloatInputsIntOutput = _doc_controls.do_not_generate_docs(_kwarg_only(TwoFloatInputsIntOutput))
tf_export("raw_ops.TwoFloatInputsIntOutput")(TwoFloatInputsIntOutput)
def two_float_inputs_int_output_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function two_float_inputs_int_output
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.float32)
b = _ops.convert_to_tensor(b, _dtypes.float32)
_inputs_flat = [a, b]
_attrs = None
_result = _execute.execute(b"TwoFloatInputsIntOutput", 1,
inputs=_inputs_flat, attrs=_attrs, ctx=_ctx,
name=name)
_execute.record_gradient(
"TwoFloatInputsIntOutput", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("TwoFloatInputsIntOutput")(None)
_two_float_outputs_outputs = ["a", "b"]
_TwoFloatOutputsOutput = _collections.namedtuple(
"TwoFloatOutputs", _two_float_outputs_outputs)
@_dispatch.add_dispatch_list
@tf_export('two_float_outputs')
def two_float_outputs(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b).
a: A `Tensor` of type `float32`.
b: A `Tensor` of type `float32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TwoFloatOutputs", name, _ctx._post_execution_callbacks)
_result = _TwoFloatOutputsOutput._make(_result)
return _result
except _core._FallbackException:
try:
return two_float_outputs_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_outputs, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoFloatOutputs", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_float_outputs, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"TwoFloatOutputs", _inputs_flat, _attrs, _result, name)
_result = _TwoFloatOutputsOutput._make(_result)
return _result
def TwoFloatOutputs(name=None):
return two_float_outputs(name=name)
TwoFloatOutputs.__doc__ = two_float_outputs.__doc__
TwoFloatOutputs = _doc_controls.do_not_generate_docs(_kwarg_only(TwoFloatOutputs))
tf_export("raw_ops.TwoFloatOutputs")(TwoFloatOutputs)
def two_float_outputs_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function two_float_outputs
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"TwoFloatOutputs", 2, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"TwoFloatOutputs", _inputs_flat, _attrs, _result, name)
_result = _TwoFloatOutputsOutput._make(_result)
return _result
_ops.RegisterShape("TwoFloatOutputs")(None)
@_dispatch.add_dispatch_list
@tf_export('two_int_inputs')
def two_int_inputs(a, b, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor` of type `int32`.
b: A `Tensor` of type `int32`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TwoIntInputs", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return two_int_inputs_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_int_inputs, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoIntInputs", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_int_inputs, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def TwoIntInputs(a, b, name=None):
return two_int_inputs(a=a, b=b, name=name)
TwoIntInputs.__doc__ = two_int_inputs.__doc__
TwoIntInputs = _doc_controls.do_not_generate_docs(_kwarg_only(TwoIntInputs))
tf_export("raw_ops.TwoIntInputs")(TwoIntInputs)
def two_int_inputs_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function two_int_inputs
"""
_ctx = ctx if ctx else _context.context()
a = _ops.convert_to_tensor(a, _dtypes.int32)
b = _ops.convert_to_tensor(b, _dtypes.int32)
_inputs_flat = [a, b]
_attrs = None
_result = _execute.execute(b"TwoIntInputs", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("TwoIntInputs")(None)
_two_int_outputs_outputs = ["a", "b"]
_TwoIntOutputsOutput = _collections.namedtuple(
"TwoIntOutputs", _two_int_outputs_outputs)
@_dispatch.add_dispatch_list
@tf_export('two_int_outputs')
def two_int_outputs(name=None):
r"""TODO: add doc.
Args:
name: A name for the operation (optional).
Returns:
A tuple of `Tensor` objects (a, b).
a: A `Tensor` of type `int32`.
b: A `Tensor` of type `int32`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TwoIntOutputs", name, _ctx._post_execution_callbacks)
_result = _TwoIntOutputsOutput._make(_result)
return _result
except _core._FallbackException:
try:
return two_int_outputs_eager_fallback(
name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_int_outputs, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoIntOutputs", name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_int_outputs, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = None
_execute.record_gradient(
"TwoIntOutputs", _inputs_flat, _attrs, _result, name)
_result = _TwoIntOutputsOutput._make(_result)
return _result
def TwoIntOutputs(name=None):
return two_int_outputs(name=name)
TwoIntOutputs.__doc__ = two_int_outputs.__doc__
TwoIntOutputs = _doc_controls.do_not_generate_docs(_kwarg_only(TwoIntOutputs))
tf_export("raw_ops.TwoIntOutputs")(TwoIntOutputs)
def two_int_outputs_eager_fallback(name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function two_int_outputs
"""
_ctx = ctx if ctx else _context.context()
_inputs_flat = []
_attrs = None
_result = _execute.execute(b"TwoIntOutputs", 2, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_execute.record_gradient(
"TwoIntOutputs", _inputs_flat, _attrs, _result, name)
_result = _TwoIntOutputsOutput._make(_result)
return _result
_ops.RegisterShape("TwoIntOutputs")(None)
@_dispatch.add_dispatch_list
@tf_export('two_refs_in')
def two_refs_in(a, b, name=None):
r"""TODO: add doc.
Args:
a: A mutable `Tensor`.
b: A mutable `Tensor`. Must have the same type as `a`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
raise RuntimeError("two_refs_in op does not support eager execution. Arg 'b' is a ref.")
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TwoRefsIn", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
two_refs_in, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def TwoRefsIn(a, b, name=None):
return two_refs_in(a=a, b=b, name=name)
TwoRefsIn.__doc__ = two_refs_in.__doc__
TwoRefsIn = _doc_controls.do_not_generate_docs(_kwarg_only(TwoRefsIn))
tf_export("raw_ops.TwoRefsIn")(TwoRefsIn)
def two_refs_in_eager_fallback(a, b, name=None, ctx=None):
raise RuntimeError("two_refs_in op does not support eager execution. Arg 'b' is a ref.")
_ops.RegisterShape("TwoRefsIn")(None)
@_dispatch.add_dispatch_list
@tf_export('type_list')
def type_list(a, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "TypeList",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return type_list_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
type_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TypeList", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
type_list, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def TypeList(a, name=None):
return type_list(a=a, name=name)
TypeList.__doc__ = type_list.__doc__
TypeList = _doc_controls.do_not_generate_docs(_kwarg_only(TypeList))
tf_export("raw_ops.TypeList")(TypeList)
def type_list_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function type_list
"""
_ctx = ctx if ctx else _context.context()
_attr_T, a = _execute.convert_to_mixed_eager_tensors(a, _ctx)
_inputs_flat = list(a)
_attrs = ("T", _attr_T)
_result = _execute.execute(b"TypeList", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("TypeList")(None)
@_dispatch.add_dispatch_list
@tf_export('type_list_restrict')
def type_list_restrict(a, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects with types from: `string`, `bool`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TypeListRestrict", name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return type_list_restrict_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
type_list_restrict, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TypeListRestrict", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
type_list_restrict, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def TypeListRestrict(a, name=None):
return type_list_restrict(a=a, name=name)
TypeListRestrict.__doc__ = type_list_restrict.__doc__
TypeListRestrict = _doc_controls.do_not_generate_docs(_kwarg_only(TypeListRestrict))
tf_export("raw_ops.TypeListRestrict")(TypeListRestrict)
def type_list_restrict_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function type_list_restrict
"""
_ctx = ctx if ctx else _context.context()
_attr_T, a = _execute.convert_to_mixed_eager_tensors(a, _ctx)
_inputs_flat = list(a)
_attrs = ("T", _attr_T)
_result = _execute.execute(b"TypeListRestrict", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("TypeListRestrict")(None)
@_dispatch.add_dispatch_list
@tf_export('type_list_twice')
def type_list_twice(a, b, name=None):
r"""TODO: add doc.
Args:
a: A list of `Tensor` objects.
b: A list of `Tensor` objects. Must have the same type as `a`.
name: A name for the operation (optional).
Returns:
The created Operation.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name,
"TypeListTwice", name, _ctx._post_execution_callbacks, a, b)
return _result
except _core._FallbackException:
try:
return type_list_twice_eager_fallback(
a, b, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
type_list_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"TypeListTwice", a=a, b=b, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
type_list_twice, a=a, b=b, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
return _op
_result = None
return _result
def TypeListTwice(a, b, name=None):
return type_list_twice(a=a, b=b, name=name)
TypeListTwice.__doc__ = type_list_twice.__doc__
TypeListTwice = _doc_controls.do_not_generate_docs(_kwarg_only(TypeListTwice))
tf_export("raw_ops.TypeListTwice")(TypeListTwice)
def type_list_twice_eager_fallback(a, b, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function type_list_twice
"""
_ctx = ctx if ctx else _context.context()
_attr_T, (a, b) = _execute.args_to_mixed_eager_tensors((a, b), _ctx)
_inputs_flat = list(a) + list(b)
_attrs = ("T", _attr_T)
_result = _execute.execute(b"TypeListTwice", 0, inputs=_inputs_flat,
attrs=_attrs, ctx=_ctx, name=name)
_result = None
return _result
_ops.RegisterShape("TypeListTwice")(None)
@_dispatch.add_dispatch_list
@tf_export('unary')
def unary(a, name=None):
r"""TODO: add doc.
Args:
a: A `Tensor`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `a`.
"""
_ctx = _context._context or _context.context()
if _ctx is not None and _ctx._thread_local_data.is_eager:
try:
_result = _pywrap_tensorflow.TFE_Py_FastPathExecute(
_ctx._context_handle, _ctx._thread_local_data.device_name, "Unary",
name, _ctx._post_execution_callbacks, a)
return _result
except _core._FallbackException:
try:
return unary_eager_fallback(
a, name=name, ctx=_ctx)
except _core._SymbolicException:
pass # Add nodes to the TensorFlow graph.
except (TypeError, ValueError):
result = _dispatch.dispatch(
unary, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
except _core._NotOkStatusException as e:
if name is not None:
message = e.message + " name: " + name
else:
message = e.message
_six.raise_from(_core._status_to_exception(e.code, message), None)
# Add nodes to the TensorFlow graph.
try:
_, _, _op = _op_def_lib._apply_op_helper(
"Unary", a=a, name=name)
except (TypeError, ValueError):
result = _dispatch.dispatch(
unary, a=a, name=name)
if result is not _dispatch.OpDispatcher.NOT_SUPPORTED:
return result
raise
_result = _op.outputs[:]
_inputs_flat = _op.inputs
_attrs = ("T", _op.get_attr("T"))
_execute.record_gradient(
"Unary", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
def Unary(a, name=None):
return unary(a=a, name=name)
Unary.__doc__ = unary.__doc__
Unary = _doc_controls.do_not_generate_docs(_kwarg_only(Unary))
tf_export("raw_ops.Unary")(Unary)
def unary_eager_fallback(a, name=None, ctx=None):
r"""This is the slowpath function for Eager mode.
This is for function unary
"""
_ctx = ctx if ctx else _context.context()
_attr_T, (a,) = _execute.args_to_matching_eager([a], _ctx)
_inputs_flat = [a]
_attrs = ("T", _attr_T)
_result = _execute.execute(b"Unary", 1, inputs=_inputs_flat, attrs=_attrs,
ctx=_ctx, name=name)
_execute.record_gradient(
"Unary", _inputs_flat, _attrs, _result, name)
_result, = _result
return _result
_ops.RegisterShape("Unary")(None)
def _InitOpDefLibrary(op_list_proto_bytes):
op_list = _op_def_pb2.OpList()
op_list.ParseFromString(op_list_proto_bytes)
_op_def_registry.register_op_list(op_list)
op_def_lib = _op_def_library.OpDefLibrary()
op_def_lib.add_op_list(op_list)
return op_def_lib
# op {
# name: "A"
# output_arg {
# name: "out"
# type: DT_FLOAT
# }
# }
# op {
# name: "Attr"
# attr {
# name: "a"
# type: "int"
# }
# }
# op {
# name: "AttrBool"
# attr {
# name: "a"
# type: "bool"
# }
# }
# op {
# name: "AttrBoolList"
# attr {
# name: "a"
# type: "list(bool)"
# }
# }
# op {
# name: "AttrDefault"
# attr {
# name: "a"
# type: "string"
# default_value {
# s: "banana"
# }
# }
# }
# op {
# name: "AttrEmptyListDefault"
# attr {
# name: "a"
# type: "list(float)"
# default_value {
# list {
# }
# }
# }
# }
# op {
# name: "AttrEnum"
# attr {
# name: "a"
# type: "string"
# allowed_values {
# list {
# s: "apples"
# s: "oranges"
# }
# }
# }
# }
# op {
# name: "AttrEnumList"
# attr {
# name: "a"
# type: "list(string)"
# allowed_values {
# list {
# s: "apples"
# s: "oranges"
# }
# }
# }
# }
# op {
# name: "AttrFloat"
# attr {
# name: "a"
# type: "float"
# }
# }
# op {
# name: "AttrListDefault"
# attr {
# name: "a"
# type: "list(int)"
# default_value {
# list {
# i: 5
# i: 15
# }
# }
# }
# }
# op {
# name: "AttrListMin"
# attr {
# name: "a"
# type: "list(int)"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "AttrListTypeDefault"
# input_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# input_arg {
# name: "b"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# default_value {
# type: DT_INT32
# }
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 1
# }
# }
# op {
# name: "AttrMin"
# attr {
# name: "a"
# type: "int"
# has_minimum: true
# minimum: 5
# }
# }
# op {
# name: "AttrPartialShape"
# attr {
# name: "a"
# type: "shape"
# }
# }
# op {
# name: "AttrPartialShapeList"
# attr {
# name: "a"
# type: "list(shape)"
# }
# }
# op {
# name: "AttrShape"
# attr {
# name: "a"
# type: "shape"
# }
# }
# op {
# name: "AttrShapeList"
# attr {
# name: "a"
# type: "list(shape)"
# }
# }
# op {
# name: "AttrTypeDefault"
# input_arg {
# name: "a"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# default_value {
# type: DT_INT32
# }
# }
# }
# op {
# name: "B"
# output_arg {
# name: "out"
# type: DT_FLOAT
# }
# }
# op {
# name: "Binary"
# input_arg {
# name: "a"
# type_attr: "T"
# }
# input_arg {
# name: "b"
# type_attr: "T"
# }
# output_arg {
# name: "out"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "ComplexStruct"
# output_arg {
# name: "a"
# type: DT_INT32
# number_attr: "n_a"
# }
# output_arg {
# name: "b"
# type: DT_INT64
# number_attr: "n_b"
# }
# output_arg {
# name: "c"
# type_list_attr: "t_c"
# }
# attr {
# name: "n_a"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "n_b"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "t_c"
# type: "list(type)"
# has_minimum: true
# }
# }
# op {
# name: "CopyOp"
# input_arg {
# name: "a"
# type_attr: "T"
# }
# output_arg {
# name: "b"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "DefaultAttrs"
# attr {
# name: "string_val"
# type: "string"
# default_value {
# s: "abc"
# }
# }
# attr {
# name: "string_list_val"
# type: "list(string)"
# default_value {
# list {
# s: "abc"
# s: ""
# }
# }
# }
# attr {
# name: "int_val"
# type: "int"
# default_value {
# i: 123
# }
# }
# attr {
# name: "int_list_val"
# type: "list(int)"
# default_value {
# list {
# i: 1
# i: 2
# i: 3
# }
# }
# }
# attr {
# name: "float_val"
# type: "float"
# default_value {
# f: 10
# }
# }
# attr {
# name: "float_list_val"
# type: "list(float)"
# default_value {
# list {
# f: 10
# }
# }
# }
# attr {
# name: "bool_val"
# type: "bool"
# default_value {
# b: true
# }
# }
# attr {
# name: "bool_list_val"
# type: "list(bool)"
# default_value {
# list {
# b: true
# b: false
# }
# }
# }
# attr {
# name: "type_val"
# type: "type"
# default_value {
# type: DT_INT32
# }
# }
# attr {
# name: "type_list_val"
# type: "list(type)"
# default_value {
# list {
# type: DT_INT32
# type: DT_FLOAT
# }
# }
# }
# attr {
# name: "shape_val"
# type: "shape"
# default_value {
# shape {
# dim {
# size: 2
# }
# dim {
# size: 1
# }
# }
# }
# }
# attr {
# name: "shape_list_val"
# type: "list(shape)"
# default_value {
# list {
# shape {
# }
# shape {
# dim {
# size: 1
# }
# }
# }
# }
# }
# attr {
# name: "tensor_val"
# type: "tensor"
# default_value {
# tensor {
# dtype: DT_INT32
# tensor_shape {
# }
# int_val: 1
# }
# }
# }
# attr {
# name: "tensor_list_val"
# type: "list(tensor)"
# default_value {
# list {
# tensor {
# dtype: DT_INT32
# tensor_shape {
# }
# int_val: 1
# }
# }
# }
# }
# }
# op {
# name: "DevicePlacementOp"
# output_arg {
# name: "device"
# type: DT_STRING
# }
# is_stateful: true
# }
# op {
# name: "FiveFloatOutputs"
# output_arg {
# name: "a"
# type: DT_FLOAT
# }
# output_arg {
# name: "b"
# type: DT_FLOAT
# }
# output_arg {
# name: "c"
# type: DT_FLOAT
# }
# output_arg {
# name: "d"
# type: DT_FLOAT
# }
# output_arg {
# name: "e"
# type: DT_FLOAT
# }
# }
# op {
# name: "FloatInput"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# }
# op {
# name: "FloatOutput"
# output_arg {
# name: "a"
# type: DT_FLOAT
# }
# }
# op {
# name: "FloatOutputStringOutput"
# output_arg {
# name: "a"
# type: DT_FLOAT
# }
# output_arg {
# name: "b"
# type: DT_STRING
# }
# }
# op {
# name: "Foo1"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# input_arg {
# name: "b"
# type: DT_INT32
# }
# input_arg {
# name: "c"
# type: DT_INT32
# }
# output_arg {
# name: "d"
# type: DT_FLOAT
# }
# output_arg {
# name: "e"
# type: DT_INT32
# }
# }
# op {
# name: "Foo2"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# input_arg {
# name: "b"
# type: DT_STRING
# }
# input_arg {
# name: "c"
# type: DT_STRING
# }
# output_arg {
# name: "d"
# type: DT_FLOAT
# }
# output_arg {
# name: "e"
# type: DT_INT32
# }
# }
# op {
# name: "Foo3"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# input_arg {
# name: "b"
# type: DT_STRING
# }
# input_arg {
# name: "c"
# type: DT_FLOAT
# }
# output_arg {
# name: "d"
# type: DT_FLOAT
# }
# output_arg {
# name: "e"
# type: DT_INT32
# }
# }
# op {
# name: "FuncAttr"
# attr {
# name: "f"
# type: "func"
# }
# }
# op {
# name: "FuncListAttr"
# attr {
# name: "f"
# type: "list(func)"
# }
# }
# op {
# name: "GraphDefVersion"
# output_arg {
# name: "version"
# type: DT_INT32
# }
# is_stateful: true
# }
# op {
# name: "InPolymorphicTwice"
# input_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# input_arg {
# name: "b"
# type_attr: "T"
# number_attr: "M"
# }
# attr {
# name: "T"
# type: "type"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# }
# attr {
# name: "M"
# type: "int"
# has_minimum: true
# }
# }
# op {
# name: "Int64Output"
# output_arg {
# name: "out"
# type: DT_INT64
# }
# }
# op {
# name: "IntAttr"
# output_arg {
# name: "out"
# type: DT_INT64
# }
# attr {
# name: "foo"
# type: "int"
# default_value {
# i: 1
# }
# }
# }
# op {
# name: "IntInput"
# input_arg {
# name: "a"
# type: DT_INT32
# }
# }
# op {
# name: "IntInputFloatInput"
# input_arg {
# name: "a"
# type: DT_INT32
# }
# input_arg {
# name: "b"
# type: DT_FLOAT
# }
# }
# op {
# name: "IntInputIntOutput"
# input_arg {
# name: "a"
# type: DT_INT32
# }
# output_arg {
# name: "b"
# type: DT_INT32
# }
# }
# op {
# name: "IntOutput"
# output_arg {
# name: "a"
# type: DT_INT32
# }
# }
# op {
# name: "IntOutputFloatOutput"
# output_arg {
# name: "a"
# type: DT_INT32
# }
# output_arg {
# name: "b"
# type: DT_FLOAT
# }
# }
# op {
# name: "KernelLabel"
# output_arg {
# name: "result"
# type: DT_STRING
# }
# }
# op {
# name: "KernelLabelRequired"
# input_arg {
# name: "input"
# type: DT_INT32
# }
# output_arg {
# name: "result"
# type: DT_STRING
# }
# }
# op {
# name: "ListInput"
# input_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 1
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "ListOutput"
# output_arg {
# name: "a"
# type_list_attr: "T"
# }
# attr {
# name: "T"
# type: "list(type)"
# has_minimum: true
# minimum: 1
# }
# }
# op {
# name: "MixedStruct"
# output_arg {
# name: "a"
# type: DT_INT32
# number_attr: "n_a"
# }
# output_arg {
# name: "b"
# type: DT_FLOAT
# }
# attr {
# name: "n_a"
# type: "int"
# has_minimum: true
# }
# }
# op {
# name: "NInPolymorphicTwice"
# input_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# input_arg {
# name: "b"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# }
# }
# op {
# name: "NInTwice"
# input_arg {
# name: "a"
# type: DT_INT32
# number_attr: "N"
# }
# input_arg {
# name: "b"
# type: DT_STRING
# number_attr: "N"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# }
# }
# op {
# name: "NInTwoTypeVariables"
# input_arg {
# name: "a"
# type_attr: "S"
# number_attr: "N"
# }
# input_arg {
# name: "b"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "S"
# type: "type"
# }
# attr {
# name: "T"
# type: "type"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# }
# }
# op {
# name: "NIntsIn"
# input_arg {
# name: "a"
# type: DT_INT32
# number_attr: "N"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NIntsOut"
# output_arg {
# name: "a"
# type: DT_INT32
# number_attr: "N"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NIntsOutDefault"
# output_arg {
# name: "a"
# type: DT_INT32
# number_attr: "N"
# }
# attr {
# name: "N"
# type: "int"
# default_value {
# i: 3
# }
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NPolymorphicIn"
# input_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NPolymorphicOut"
# output_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NPolymorphicOutDefault"
# output_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# default_value {
# type: DT_BOOL
# }
# }
# attr {
# name: "N"
# type: "int"
# default_value {
# i: 2
# }
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NPolymorphicRestrictIn"
# input_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# allowed_values {
# list {
# type: DT_STRING
# type: DT_BOOL
# }
# }
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "NPolymorphicRestrictOut"
# output_arg {
# name: "a"
# type_attr: "T"
# number_attr: "N"
# }
# attr {
# name: "T"
# type: "type"
# allowed_values {
# list {
# type: DT_STRING
# type: DT_BOOL
# }
# }
# }
# attr {
# name: "N"
# type: "int"
# has_minimum: true
# minimum: 2
# }
# }
# op {
# name: "None"
# }
# op {
# name: "Old"
# deprecation {
# version: 8
# explanation: "For reasons"
# }
# }
# op {
# name: "OpWithDefaultAttr"
# output_arg {
# name: "a"
# type: DT_INT32
# }
# attr {
# name: "default_float"
# type: "float"
# default_value {
# f: 123
# }
# }
# }
# op {
# name: "OpWithFutureDefaultAttr"
# }
# op {
# name: "OutT"
# output_arg {
# name: "a"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "OutTypeList"
# output_arg {
# name: "out"
# type_list_attr: "T"
# }
# attr {
# name: "T"
# type: "list(type)"
# has_minimum: true
# }
# }
# op {
# name: "OutTypeListRestrict"
# output_arg {
# name: "out"
# type_list_attr: "t"
# }
# attr {
# name: "t"
# type: "list(type)"
# has_minimum: true
# minimum: 1
# allowed_values {
# list {
# type: DT_STRING
# type: DT_BOOL
# }
# }
# }
# }
# op {
# name: "Polymorphic"
# input_arg {
# name: "a"
# type_attr: "T"
# }
# output_arg {
# name: "out"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "PolymorphicDefaultOut"
# output_arg {
# name: "out"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# default_value {
# type: DT_STRING
# }
# }
# }
# op {
# name: "PolymorphicOut"
# output_arg {
# name: "out"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "RefIn"
# input_arg {
# name: "a"
# type_attr: "T"
# is_ref: true
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "RefInputFloatInput"
# input_arg {
# name: "a"
# type: DT_FLOAT
# is_ref: true
# }
# input_arg {
# name: "b"
# type: DT_FLOAT
# }
# }
# op {
# name: "RefInputFloatInputIntOutput"
# input_arg {
# name: "a"
# type: DT_FLOAT
# is_ref: true
# }
# input_arg {
# name: "b"
# type: DT_FLOAT
# }
# output_arg {
# name: "c"
# type: DT_INT32
# }
# }
# op {
# name: "RefInputIntInput"
# input_arg {
# name: "a"
# type: DT_INT32
# is_ref: true
# }
# input_arg {
# name: "b"
# type: DT_INT32
# }
# }
# op {
# name: "RefOut"
# output_arg {
# name: "a"
# type_attr: "T"
# is_ref: true
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "RefOutput"
# output_arg {
# name: "a"
# type: DT_INT32
# is_ref: true
# }
# }
# op {
# name: "RefOutputFloatOutput"
# output_arg {
# name: "a"
# type: DT_FLOAT
# is_ref: true
# }
# output_arg {
# name: "b"
# type: DT_FLOAT
# }
# }
# op {
# name: "RequiresOlderGraphVersion"
# output_arg {
# name: "version"
# type: DT_INT32
# }
# is_stateful: true
# }
# op {
# name: "ReservedAttr"
# attr {
# name: "range"
# type: "int"
# }
# }
# op {
# name: "ReservedInput"
# input_arg {
# name: "input"
# type: DT_INT32
# }
# }
# op {
# name: "ResourceCreateOp"
# input_arg {
# name: "resource"
# type: DT_RESOURCE
# }
# is_stateful: true
# }
# op {
# name: "ResourceInitializedOp"
# input_arg {
# name: "resource"
# type: DT_RESOURCE
# }
# output_arg {
# name: "initialized"
# type: DT_BOOL
# }
# is_stateful: true
# }
# op {
# name: "ResourceUsingOp"
# input_arg {
# name: "resource"
# type: DT_RESOURCE
# }
# is_stateful: true
# }
# op {
# name: "Restrict"
# input_arg {
# name: "a"
# type_attr: "T"
# }
# output_arg {
# name: "out"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# allowed_values {
# list {
# type: DT_STRING
# type: DT_BOOL
# }
# }
# }
# }
# op {
# name: "Simple"
# input_arg {
# name: "a"
# type: DT_INT32
# }
# output_arg {
# name: "out"
# type: DT_FLOAT
# }
# }
# op {
# name: "SimpleStruct"
# output_arg {
# name: "a"
# type: DT_INT32
# number_attr: "n_a"
# }
# attr {
# name: "n_a"
# type: "int"
# has_minimum: true
# }
# }
# op {
# name: "StringListAttr"
# attr {
# name: "a"
# type: "list(string)"
# }
# attr {
# name: "b"
# type: "string"
# }
# }
# op {
# name: "StubResourceHandleOp"
# output_arg {
# name: "resource"
# type: DT_RESOURCE
# }
# attr {
# name: "container"
# type: "string"
# default_value {
# s: ""
# }
# }
# attr {
# name: "shared_name"
# type: "string"
# default_value {
# s: ""
# }
# }
# is_stateful: true
# }
# op {
# name: "TestAttr"
# output_arg {
# name: "out"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# allowed_values {
# list {
# type: DT_FLOAT
# type: DT_DOUBLE
# }
# }
# }
# }
# op {
# name: "TestStringOutput"
# input_arg {
# name: "input"
# type: DT_FLOAT
# }
# output_arg {
# name: "output1"
# type: DT_FLOAT
# }
# output_arg {
# name: "output2"
# type: DT_STRING
# }
# }
# op {
# name: "TwoFloatInputs"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# input_arg {
# name: "b"
# type: DT_FLOAT
# }
# }
# op {
# name: "TwoFloatInputsFloatOutput"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# input_arg {
# name: "b"
# type: DT_FLOAT
# }
# output_arg {
# name: "c"
# type: DT_FLOAT
# }
# }
# op {
# name: "TwoFloatInputsIntOutput"
# input_arg {
# name: "a"
# type: DT_FLOAT
# }
# input_arg {
# name: "b"
# type: DT_FLOAT
# }
# output_arg {
# name: "c"
# type: DT_INT32
# }
# }
# op {
# name: "TwoFloatOutputs"
# output_arg {
# name: "a"
# type: DT_FLOAT
# }
# output_arg {
# name: "b"
# type: DT_FLOAT
# }
# }
# op {
# name: "TwoIntInputs"
# input_arg {
# name: "a"
# type: DT_INT32
# }
# input_arg {
# name: "b"
# type: DT_INT32
# }
# }
# op {
# name: "TwoIntOutputs"
# output_arg {
# name: "a"
# type: DT_INT32
# }
# output_arg {
# name: "b"
# type: DT_INT32
# }
# }
# op {
# name: "TwoRefsIn"
# input_arg {
# name: "a"
# type_attr: "T"
# is_ref: true
# }
# input_arg {
# name: "b"
# type_attr: "T"
# is_ref: true
# }
# attr {
# name: "T"
# type: "type"
# }
# }
# op {
# name: "TypeList"
# input_arg {
# name: "a"
# type_list_attr: "T"
# }
# attr {
# name: "T"
# type: "list(type)"
# has_minimum: true
# }
# }
# op {
# name: "TypeListRestrict"
# input_arg {
# name: "a"
# type_list_attr: "T"
# }
# attr {
# name: "T"
# type: "list(type)"
# has_minimum: true
# minimum: 1
# allowed_values {
# list {
# type: DT_STRING
# type: DT_BOOL
# }
# }
# }
# }
# op {
# name: "TypeListTwice"
# input_arg {
# name: "a"
# type_list_attr: "T"
# }
# input_arg {
# name: "b"
# type_list_attr: "T"
# }
# attr {
# name: "T"
# type: "list(type)"
# has_minimum: true
# }
# }
# op {
# name: "Unary"
# input_arg {
# name: "a"
# type_attr: "T"
# }
# output_arg {
# name: "b"
# type_attr: "T"
# }
# attr {
# name: "T"
# type: "type"
# }
# }
_op_def_lib = _InitOpDefLibrary(b"\n\014\n\001A\032\007\n\003out\030\001\n\020\n\004Attr\"\010\n\001a\022\003int\n\025\n\010AttrBool\"\t\n\001a\022\004bool\n\037\n\014AttrBoolList\"\017\n\001a\022\nlist(bool)\n$\n\013AttrDefault\"\025\n\001a\022\006string\032\010\022\006banana\n,\n\024AttrEmptyListDefault\"\024\n\001a\022\013list(float)\032\002\n\000\n,\n\010AttrEnum\" \n\001a\022\006string:\023\n\021\022\006apples\022\007oranges\n6\n\014AttrEnumList\"&\n\001a\022\014list(string):\023\n\021\022\006apples\022\007oranges\n\027\n\tAttrFloat\"\n\n\001a\022\005float\n)\n\017AttrListDefault\"\026\n\001a\022\tlist(int)\032\006\n\004\032\002\005\017\n!\n\013AttrListMin\"\022\n\001a\022\tlist(int)(\0010\002\nH\n\023AttrListTypeDefault\022\t\n\001a\"\001T*\001N\022\t\n\001b\"\001T*\001N\"\r\n\001T\022\004type\032\0020\003\"\014\n\001N\022\003int(\0010\001\n\027\n\007AttrMin\"\014\n\001a\022\003int(\0010\005\n\036\n\020AttrPartialShape\"\n\n\001a\022\005shape\n(\n\024AttrPartialShapeList\"\020\n\001a\022\013list(shape)\n\027\n\tAttrShape\"\n\n\001a\022\005shape\n!\n\rAttrShapeList\"\020\n\001a\022\013list(shape)\n(\n\017AttrTypeDefault\022\006\n\001a\"\001T\"\r\n\001T\022\004type\032\0020\003\n\014\n\001B\032\007\n\003out\030\001\n-\n\006Binary\022\006\n\001a\"\001T\022\006\n\001b\"\001T\032\010\n\003out\"\001T\"\t\n\001T\022\004type\nb\n\rComplexStruct\032\n\n\001a\030\003*\003n_a\032\n\n\001b\030\t*\003n_b\032\010\n\001c2\003t_c\"\014\n\003n_a\022\003int(\001\"\014\n\003n_b\022\003int(\001\"\023\n\003t_c\022\nlist(type)(\001\n#\n\006CopyOp\022\006\n\001a\"\001T\032\006\n\001b\"\001T\"\t\n\001T\022\004type\n\343\003\n\014DefaultAttrs\"\033\n\nstring_val\022\006string\032\005\022\003abc\"*\n\017string_list_val\022\014list(string)\032\t\n\007\022\003abc\022\000\"\022\n\007int_val\022\003int\032\002\030{\"\"\n\014int_list_val\022\tlist(int)\032\007\n\005\032\003\001\002\003\"\031\n\tfloat_val\022\005float\032\005%\000\000 A\"\'\n\016float_list_val\022\013list(float)\032\010\n\006\"\004\000\000 A\"\024\n\010bool_val\022\004bool\032\002(\001\"#\n\rbool_list_val\022\nlist(bool)\032\006\n\004*\002\001\000\"\024\n\010type_val\022\004type\032\0020\003\"#\n\rtype_list_val\022\nlist(type)\032\006\n\0042\002\003\001\"\036\n\tshape_val\022\005shape\032\n:\010\022\002\010\002\022\002\010\001\")\n\016shape_list_val\022\013list(shape)\032\n\n\010:\000:\004\022\002\010\001\"\037\n\ntensor_val\022\006tensor\032\tB\007\010\003\022\000:\001\001\",\n\017tensor_list_val\022\014list(tensor)\032\013\n\tB\007\010\003\022\000:\001\001\n\"\n\021DevicePlacementOp\032\n\n\006device\030\007\210\001\001\n5\n\020FiveFloatOutputs\032\005\n\001a\030\001\032\005\n\001b\030\001\032\005\n\001c\030\001\032\005\n\001d\030\001\032\005\n\001e\030\001\n\023\n\nFloatInput\022\005\n\001a\030\001\n\024\n\013FloatOutput\032\005\n\001a\030\001\n\'\n\027FloatOutputStringOutput\032\005\n\001a\030\001\032\005\n\001b\030\007\n)\n\004Foo1\022\005\n\001a\030\001\022\005\n\001b\030\003\022\005\n\001c\030\003\032\005\n\001d\030\001\032\005\n\001e\030\003\n)\n\004Foo2\022\005\n\001a\030\001\022\005\n\001b\030\007\022\005\n\001c\030\007\032\005\n\001d\030\001\032\005\n\001e\030\003\n)\n\004Foo3\022\005\n\001a\030\001\022\005\n\001b\030\007\022\005\n\001c\030\001\032\005\n\001d\030\001\032\005\n\001e\030\003\n\025\n\010FuncAttr\"\t\n\001f\022\004func\n\037\n\014FuncListAttr\"\017\n\001f\022\nlist(func)\n!\n\017GraphDefVersion\032\013\n\007version\030\003\210\001\001\nM\n\022InPolymorphicTwice\022\t\n\001a\"\001T*\001N\022\t\n\001b\"\001T*\001M\"\t\n\001T\022\004type\"\n\n\001N\022\003int(\001\"\n\n\001M\022\003int(\001\n\026\n\013Int64Output\032\007\n\003out\030\t\n\"\n\007IntAttr\032\007\n\003out\030\t\"\016\n\003foo\022\003int\032\002\030\001\n\021\n\010IntInput\022\005\n\001a\030\003\n\"\n\022IntInputFloatInput\022\005\n\001a\030\003\022\005\n\001b\030\001\n!\n\021IntInputIntOutput\022\005\n\001a\030\003\032\005\n\001b\030\003\n\022\n\tIntOutput\032\005\n\001a\030\003\n$\n\024IntOutputFloatOutput\032\005\n\001a\030\003\032\005\n\001b\030\001\n\031\n\013KernelLabel\032\n\n\006result\030\007\n,\n\023KernelLabelRequired\022\t\n\005input\030\003\032\n\n\006result\030\007\n/\n\tListInput\022\t\n\001a\"\001T*\001N\"\014\n\001N\022\003int(\0010\001\"\t\n\001T\022\004type\n)\n\nListOutput\032\006\n\001a2\001T\"\023\n\001T\022\nlist(type)(\0010\001\n.\n\013MixedStruct\032\n\n\001a\030\003*\003n_a\032\005\n\001b\030\001\"\014\n\003n_a\022\003int(\001\nB\n\023NInPolymorphicTwice\022\t\n\001a\"\001T*\001N\022\t\n\001b\"\001T*\001N\"\t\n\001T\022\004type\"\n\n\001N\022\003int(\001\n*\n\010NInTwice\022\010\n\001a\030\003*\001N\022\010\n\001b\030\007*\001N\"\n\n\001N\022\003int(\001\nM\n\023NInTwoTypeVariables\022\t\n\001a\"\001S*\001N\022\t\n\001b\"\001T*\001N\"\t\n\001S\022\004type\"\t\n\001T\022\004type\"\n\n\001N\022\003int(\001\n!\n\007NIntsIn\022\010\n\001a\030\003*\001N\"\014\n\001N\022\003int(\0010\002\n\"\n\010NIntsOut\032\010\n\001a\030\003*\001N\"\014\n\001N\022\003int(\0010\002\n-\n\017NIntsOutDefault\032\010\n\001a\030\003*\001N\"\020\n\001N\022\003int\032\002\030\003(\0010\002\n4\n\016NPolymorphicIn\022\t\n\001a\"\001T*\001N\"\t\n\001T\022\004type\"\014\n\001N\022\003int(\0010\002\n5\n\017NPolymorphicOut\032\t\n\001a\"\001T*\001N\"\t\n\001T\022\004type\"\014\n\001N\022\003int(\0010\002\nD\n\026NPolymorphicOutDefault\032\t\n\001a\"\001T*\001N\"\r\n\001T\022\004type\032\0020\n\"\020\n\001N\022\003int\032\002\030\002(\0010\002\nD\n\026NPolymorphicRestrictIn\022\t\n\001a\"\001T*\001N\"\021\n\001T\022\004type:\006\n\0042\002\007\n\"\014\n\001N\022\003int(\0010\002\nE\n\027NPolymorphicRestrictOut\032\t\n\001a\"\001T*\001N\"\021\n\001T\022\004type:\006\n\0042\002\007\n\"\014\n\001N\022\003int(\0010\002\n\006\n\004None\n\026\n\003OldB\017\010\010\022\013For reasons\n9\n\021OpWithDefaultAttr\032\005\n\001a\030\003\"\035\n\rdefault_float\022\005float\032\005%\000\000\366B\n\031\n\027OpWithFutureDefaultAttr\n\031\n\004OutT\032\006\n\001a\"\001T\"\t\n\001T\022\004type\n*\n\013OutTypeList\032\010\n\003out2\001T\"\021\n\001T\022\nlist(type)(\001\n<\n\023OutTypeListRestrict\032\010\n\003out2\001t\"\033\n\001t\022\nlist(type)(\0010\001:\006\n\0042\002\007\n\n*\n\013Polymorphic\022\006\n\001a\"\001T\032\010\n\003out\"\001T\"\t\n\001T\022\004type\n0\n\025PolymorphicDefaultOut\032\010\n\003out\"\001T\"\r\n\001T\022\004type\032\0020\007\n%\n\016PolymorphicOut\032\010\n\003out\"\001T\"\t\n\001T\022\004type\n\035\n\005RefIn\022\t\n\001a\"\001T\200\001\001\"\t\n\001T\022\004type\n%\n\022RefInputFloatInput\022\010\n\001a\030\001\200\001\001\022\005\n\001b\030\001\n5\n\033RefInputFloatInputIntOutput\022\010\n\001a\030\001\200\001\001\022\005\n\001b\030\001\032\005\n\001c\030\003\n#\n\020RefInputIntInput\022\010\n\001a\030\003\200\001\001\022\005\n\001b\030\003\n\036\n\006RefOut\032\t\n\001a\"\001T\200\001\001\"\t\n\001T\022\004type\n\025\n\tRefOutput\032\010\n\001a\030\003\200\001\001\n\'\n\024RefOutputFloatOutput\032\010\n\001a\030\001\200\001\001\032\005\n\001b\030\001\n+\n\031RequiresOlderGraphVersion\032\013\n\007version\030\003\210\001\001\n\034\n\014ReservedAttr\"\014\n\005range\022\003int\n\032\n\rReservedInput\022\t\n\005input\030\003\n#\n\020ResourceCreateOp\022\014\n\010resource\030\024\210\001\001\n9\n\025ResourceInitializedOp\022\014\n\010resource\030\024\032\017\n\013initialized\030\n\210\001\001\n\"\n\017ResourceUsingOp\022\014\n\010resource\030\024\210\001\001\n/\n\010Restrict\022\006\n\001a\"\001T\032\010\n\003out\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\007\n\n\030\n\006Simple\022\005\n\001a\030\003\032\007\n\003out\030\001\n(\n\014SimpleStruct\032\n\n\001a\030\003*\003n_a\"\014\n\003n_a\022\003int(\001\n0\n\016StringListAttr\"\021\n\001a\022\014list(string)\"\013\n\001b\022\006string\n[\n\024StubResourceHandleOp\032\014\n\010resource\030\024\"\027\n\tcontainer\022\006string\032\002\022\000\"\031\n\013shared_name\022\006string\032\002\022\000\210\001\001\n\'\n\010TestAttr\032\010\n\003out\"\001T\"\021\n\001T\022\004type:\006\n\0042\002\001\002\n7\n\020TestStringOutput\022\t\n\005input\030\001\032\013\n\007output1\030\001\032\013\n\007output2\030\007\n\036\n\016TwoFloatInputs\022\005\n\001a\030\001\022\005\n\001b\030\001\n0\n\031TwoFloatInputsFloatOutput\022\005\n\001a\030\001\022\005\n\001b\030\001\032\005\n\001c\030\001\n.\n\027TwoFloatInputsIntOutput\022\005\n\001a\030\001\022\005\n\001b\030\001\032\005\n\001c\030\003\n\037\n\017TwoFloatOutputs\032\005\n\001a\030\001\032\005\n\001b\030\001\n\034\n\014TwoIntInputs\022\005\n\001a\030\003\022\005\n\001b\030\003\n\035\n\rTwoIntOutputs\032\005\n\001a\030\003\032\005\n\001b\030\003\n,\n\tTwoRefsIn\022\t\n\001a\"\001T\200\001\001\022\t\n\001b\"\001T\200\001\001\"\t\n\001T\022\004type\n%\n\010TypeList\022\006\n\001a2\001T\"\021\n\001T\022\nlist(type)(\001\n7\n\020TypeListRestrict\022\006\n\001a2\001T\"\033\n\001T\022\nlist(type)(\0010\001:\006\n\0042\002\007\n\n2\n\rTypeListTwice\022\006\n\001a2\001T\022\006\n\001b2\001T\"\021\n\001T\022\nlist(type)(\001\n\"\n\005Unary\022\006\n\001a\"\001T\032\006\n\001b\"\001T\"\t\n\001T\022\004type")
| 32.172019 | 9,088 | 0.673447 | 40,843 | 306,535 | 4.699679 | 0.014127 | 0.027882 | 0.019068 | 0.017817 | 0.86524 | 0.8461 | 0.829767 | 0.810382 | 0.772653 | 0.750309 | 0 | 0.019491 | 0.217345 | 306,535 | 9,527 | 9,089 | 32.175396 | 0.780594 | 0.162915 | 0 | 0.74929 | 1 | 0.00473 | 0.096124 | 0.037335 | 0 | 0 | 0 | 0.010392 | 0 | 1 | 0.046988 | false | 0.014349 | 0.002996 | 0.01561 | 0.161936 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 |
dba7774d6c29eaf3ca38c056af840fe925070f3e | 25,281 | py | Python | tests/vi/test_word_end.py | uri/Vintageous | d5662872bcf1e7439875fe1c5133010db2ace8fd | [
"MIT"
] | null | null | null | tests/vi/test_word_end.py | uri/Vintageous | d5662872bcf1e7439875fe1c5133010db2ace8fd | [
"MIT"
] | null | null | null | tests/vi/test_word_end.py | uri/Vintageous | d5662872bcf1e7439875fe1c5133010db2ace8fd | [
"MIT"
] | null | null | null | import unittest
# from Vintageous.vi.constants import _MODE_INTERNAL_NORMAL
from Vintageous.vi.constants import MODE_NORMAL
# from Vintageous.vi.constants import MODE_VISUAL
# from Vintageous.vi.constants import MODE_VISUAL_LINE
from Vintageous.tests.commands import BufferTest
from Vintageous.tests.commands import set_text
from Vintageous.tests.commands import add_selection
from Vintageous.vi.units import next_word_end
from Vintageous.vi.units import word_ends
from Vintageous.vi.units import CLASS_VI_INTERNAL_WORD_START
class Test_next_word_end_InNormalMode_FromWhitespace(BufferTest):
def testToWordStart(self):
set_text(self.view, ' foo bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 5)
def testToPunctuationStart(self):
set_text(self.view, ' (foo)\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEmptyLine(self):
set_text(self.view, ' \n\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 5)
def testToWhitespaceLine(self):
set_text(self.view, ' \n \n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 7)
def testToEofWithNewline(self):
set_text(self.view, ' \n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEof(self):
set_text(self.view, ' ')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneWordLine(self):
set_text(self.view, ' \nfoo\nbar')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 7)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, ' \n foo\nbar')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 8)
def testToOneCharWord(self):
set_text(self.view, ' a foo bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharLine(self):
set_text(self.view, ' \na\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 4)
def testToOneCharLineWithLeadingWhitespace(self):
set_text(self.view, ' \n a\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 5)
class Test_next_word_end_InNormalMode_FromWordStart(BufferTest):
def testToWordStart(self):
set_text(self.view, 'foo bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToPunctuationStart(self):
set_text(self.view, 'foo (bar)\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEmptyLine(self):
set_text(self.view, 'foo\n\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToWhitespaceLine(self):
set_text(self.view, 'foo\n \n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEofWithNewline(self):
set_text(self.view, 'foo\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEof(self):
set_text(self.view, 'foo')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneWordLine(self):
set_text(self.view, 'foo\nbar\nbaz')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, 'foo\n bar\nbaz')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharWord(self):
set_text(self.view, 'foo a bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharLine(self):
set_text(self.view, 'foo\na\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharLineWithLeadingWhitespace(self):
set_text(self.view, 'foo\n a\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
class Test_next_word_end_InNormalMode_FromWord(BufferTest):
def testToWordStart(self):
set_text(self.view, 'foo bar\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToPunctuationStart(self):
set_text(self.view, 'foo (bar)\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEmptyLine(self):
set_text(self.view, 'foo\n\n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToWhitespaceLine(self):
set_text(self.view, 'foo\n \n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEofWithNewline(self):
set_text(self.view, 'foo\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEof(self):
set_text(self.view, 'foo')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneWordLine(self):
set_text(self.view, 'foo\nbar\nbaz')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, 'foo\n bar\nbaz')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharWord(self):
set_text(self.view, 'foo a bar\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharLine(self):
set_text(self.view, 'foo\na\n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToOneCharLineWithLeadingWhitespace(self):
set_text(self.view, 'foo\n a\n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
class Test_next_word_end_InNormalMode_FromPunctuationStart(BufferTest):
def testToWordStart(self):
set_text(self.view, ':foo\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToPunctuationStart(self):
set_text(self.view, ': (foo)\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToEmptyLine(self):
set_text(self.view, ':\n\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToWhitespaceLine(self):
set_text(self.view, ':\n \n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToEofWithNewline(self):
set_text(self.view, ':\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToEof(self):
set_text(self.view, ':')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToOneWordLine(self):
set_text(self.view, ':\nbar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, ':\n bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToOneCharWord(self):
set_text(self.view, ':a bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToOneCharLine(self):
set_text(self.view, ':\na\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToOneCharLineWithLeadingWhitespace(self):
set_text(self.view, ':\n a\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
class Test_next_word_end_InNormalMode_FromEmptyLine(BufferTest):
def testToWordStart(self):
set_text(self.view, '\nfoo\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 4)
def testToPunctuationStart(self):
set_text(self.view, '\n (foo)\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToEmptyLine(self):
set_text(self.view, '\n\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
def testToWhitespaceLine(self):
set_text(self.view, '\n \n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 5)
def testToEofWithNewline(self):
set_text(self.view, '\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 1)
def testToEof(self):
set_text(self.view, '')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 0)
def testToOneWordLine(self):
set_text(self.view, '\nbar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 4)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, '\n bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 5)
def testToOneCharWord(self):
set_text(self.view, '\na bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneCharLine(self):
set_text(self.view, '\na\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneCharLineWithLeadingWhitespace(self):
set_text(self.view, '\n a\n\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 3)
class Test_next_word_end_InNormalMode_FromPunctuation(BufferTest):
def testToWordStart(self):
set_text(self.view, '::foo\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToPunctuationStart(self):
set_text(self.view, ':: (foo)\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToEmptyLine(self):
set_text(self.view, '::\n\n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToWhitespaceLine(self):
set_text(self.view, '::\n \n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToEofWithNewline(self):
set_text(self.view, '::\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToEof(self):
set_text(self.view, '::')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneWordLine(self):
set_text(self.view, '::\nbar\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, '::\n bar\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneCharWord(self):
set_text(self.view, '::a bar\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneCharLine(self):
set_text(self.view, '::\na\n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
def testToOneCharLineWithLeadingWhitespace(self):
set_text(self.view, '::\n a\n\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b)
self.assertEqual(pt, 2)
class Test_next_word_end_InInternalNormalMode_FromWhitespace(BufferTest):
def testToWhitespaceLine(self):
set_text(self.view, ' \n ')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 5)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, ' \n foo')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 7)
class Test_next_word_end_InInternalNormalMode_FromWordStart(BufferTest):
def testToWhitespaceLine(self):
set_text(self.view, 'foo\n ')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 3)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, 'foo\n bar')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 3)
class Test_next_word_end_InInternalNormalMode_FromWord(BufferTest):
def testToWhitespaceLine(self):
set_text(self.view, 'foo\n ')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 3)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, 'foo\n bar')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 3)
class Test_next_word_end_InInternalNormalMode_FromPunctuationStart(BufferTest):
def testToWhitespaceLine(self):
set_text(self.view, '.\n ')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 1)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, '.\n bar')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 1)
class Test_next_word_end_InInternalNormalMode_FromPunctuation(BufferTest):
def testToWhitespaceLine(self):
set_text(self.view, '::\n ')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 2)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, '::\n bar')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 2)
class Test_next_word_end_InInternalNormalMode_FromEmptyLine(BufferTest):
def testToWhitespaceLine(self):
set_text(self.view, '\n ')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 3)
def testToOneWordLineWithLeadingWhitespace(self):
set_text(self.view, '\n bar')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = next_word_end(self.view, r.b, internal=True)
self.assertEqual(pt, 5)
class Test_words_InNormalMode(BufferTest):
def testMove1(self):
set_text(self.view, 'foo bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b)
self.assertEqual(pt, 2)
def testMove2(self):
set_text(self.view, 'foo bar fizz\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, count=2)
self.assertEqual(pt, 6)
def testMove10(self):
set_text(self.view, ''.join(('foo bar\n',) * 5))
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, count=9)
self.assertEqual(pt, 34)
class Test_words_InInternalNormalMode_FromEmptyLine(BufferTest):
# We can assume the stuff tested for normal mode applies to internal normal mode, so we
# don't bother with that. Instead, we only test the differing behavior when advancing by
# word starts in internal normal.
def testMove1ToLineWithLeadingWhiteSpace(self):
set_text(self.view, '\n bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True)
self.assertEqual(pt, 4)
def testMove2ToLineWithLeadingWhiteSpace(self):
set_text(self.view, '\n bar')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, count=2, internal=True)
self.assertEqual(pt, 6)
def testMove1ToWhitespaceLine(self):
set_text(self.view, '\n \n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, count=1, internal=True)
self.assertEqual(pt, 3)
def testMove2ToOneWordLine(self):
set_text(self.view, '\nfoo\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 4)
def testMove3AndSwallowLastNewlineChar(self):
set_text(self.view, '\nfoo\n bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=3)
self.assertEqual(pt, 9)
def testMove2ToLineWithLeadingWhiteSpace(self):
set_text(self.view, '\nfoo\n \n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 7)
class Test_words_InInternalNormalMode_FromOneWordLine(BufferTest):
# We can assume the stuff tested for normal mode applies to internal normal mode, so we
# don't bother with that. Instead, we only test the differing behavior when advancing by
# word starts in internal normal.
def testMove1ToEol(self):
set_text(self.view, 'foo\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=1)
self.assertEqual(pt, 2)
def testMove2ToLineWithLeadingWhiteSpaceFromWordStart(self):
set_text(self.view, 'foo\n\nbar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 7)
def testMove2ToEmptyLineFromWord(self):
set_text(self.view, 'foo\n\nbar\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 7)
def testMove2ToOneWordLineFromWordStart(self):
set_text(self.view, 'foo\nbar\nccc\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 6)
def testMove2ToOneWordLineFromWord(self):
set_text(self.view, 'foo\nbar\nccc\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 6)
def testMove2ToWhitespaceline(self):
set_text(self.view, 'foo\n \nccc\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 9)
def testMove2ToWhitespacelineFollowedByLeadingWhitespaceFromWord(self):
set_text(self.view, 'foo\n \n ccc\n')
r = self.R((0, 1), (0, 1))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 10)
def testMove2ToWhitespacelineFollowedByLeadingWhitespaceFromWordStart(self):
set_text(self.view, 'foo\n \n ccc\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 10)
class Test_words_InInternalNormalMode_FromLine(BufferTest):
def testMove2ToEol(self):
set_text(self.view, 'foo bar\n')
r = self.R((0, 0), (0, 0))
add_selection(self.view, r)
pt = word_ends(self.view, r.b, internal=True, count=2)
self.assertEqual(pt, 6)
| 30.792935 | 93 | 0.565524 | 3,578 | 25,281 | 3.869201 | 0.034097 | 0.166426 | 0.12742 | 0.104016 | 0.931739 | 0.911514 | 0.897356 | 0.864707 | 0.859795 | 0.845348 | 0 | 0.028885 | 0.289269 | 25,281 | 820 | 94 | 30.830488 | 0.741596 | 0.022467 | 0 | 0.878333 | 0 | 0 | 0.034836 | 0 | 0 | 0 | 0 | 0 | 0.16 | 1 | 0.16 | false | 0 | 0.013333 | 0 | 0.2 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
91d0678a2105f5f0a021b1003742cf22bcb393de | 5,416 | py | Python | tests/slippinj/databases/drivers/test_oracle.py | scm-spain/slippin-jimmy | d0e52277daff523eda63f5d3137b5a990413923d | [
"Apache-2.0"
] | 7 | 2016-03-31T06:17:23.000Z | 2018-01-25T15:25:05.000Z | tests/slippinj/databases/drivers/test_oracle.py | scm-spain/slippin-jimmy | d0e52277daff523eda63f5d3137b5a990413923d | [
"Apache-2.0"
] | 8 | 2016-03-30T18:45:09.000Z | 2017-06-19T09:21:35.000Z | tests/slippinj/databases/drivers/test_oracle.py | scm-spain/slippin-jimmy | d0e52277daff523eda63f5d3137b5a990413923d | [
"Apache-2.0"
] | 13 | 2017-04-21T08:17:14.000Z | 2019-07-12T04:59:24.000Z | import logging
from mock import Mock, patch
from slippinj.databases.drivers.oracle import Oracle
class TestOracle:
def setup_method(self, method):
self.logger = logging.getLogger('test')
self.logger.addHandler(logging.NullHandler())
def teardown_method(self,method):
self.logger = None
@patch.object(Oracle, '_Oracle__makedict')
def test_get_tables_info_when_no_table_list_is_provided(self,__makedict):
__makedict.return_value = None
mocked_table_list_query_cursor = Mock()
mocked_table_list_query_cursor.execute = Mock(return_value=True)
mocked_table_list_query_cursor.fetchall = Mock(return_value=[{'TABLE_NAME': 'unit'}, {'TABLE_NAME': 'test'}])
mocked_table_count_query_cursor = Mock()
mocked_table_count_query_cursor.execute = Mock(return_value=True)
mocked_table_count_query_cursor.fetchone = Mock(return_value=[10])
columns = {
'TABLE_NAME': '',
'COLUMN_NAME': 'column',
'DATA_TYPE': 'string',
'DATA_LENGTH': '1',
'NULLABLE': 'N',
'DATA_DEFAULT': ''
}
tables_columns = []
columns.update(TABLE_NAME='unit')
tables_columns.append(columns.copy())
columns.update(TABLE_NAME='test')
tables_columns.append(columns.copy())
mocked_table_columns_query_cursor = Mock()
mocked_table_columns_query_cursor.execute = Mock(return_value=True)
mocked_table_columns_query_cursor.fetchall = Mock(return_value=tables_columns)
mocked_table_top_query_cursor = Mock()
mocked_table_top_query_cursor.execute = Mock(return_value=True)
mocked_table_top_query_cursor.fetchall = Mock(return_value=[])
mocked_oracle = Mock()
mocked_oracle.cursor = Mock(side_effect=[mocked_table_list_query_cursor, mocked_table_count_query_cursor,
mocked_table_columns_query_cursor, mocked_table_top_query_cursor])
mocked_builder = Mock()
mocked_builder.build = Mock(return_value=mocked_oracle)
expected = {'tables': {'test': {'columns': [{'character_maximum_length': '1',
'column_default': '',
'column_name': 'column',
'data_type': 'string',
'is_nullable': 'N'}],
'count': 10,
'rows': []},
'unit': {'columns': [{'character_maximum_length': '1',
'column_default': '',
'column_name': 'column',
'data_type': 'string',
'is_nullable': 'N'}],
'count': 10,
'rows': []}},
'db_connection_string': 'jdbc:oracle:thin:@//test'
}
assert expected == Oracle(mocked_builder, self.logger, db_host = 'test').get_all_tables_info(None, None, None)
@patch.object(Oracle, '_Oracle__makedict')
def test_get_tables_info_when_table_list_has_been_provided(self, __makedict):
__makedict.return_value = None
mocked_table_count_query_cursor = Mock()
mocked_table_count_query_cursor.execute = Mock(return_value=True)
mocked_table_count_query_cursor.fetchone = Mock(return_value=[10])
columns = {
'TABLE_NAME': '',
'COLUMN_NAME': 'column',
'DATA_TYPE': 'string',
'DATA_LENGTH': '1',
'NULLABLE': 'N',
'DATA_DEFAULT': ''
}
tables_columns = []
columns.update(TABLE_NAME='unit')
tables_columns.append(columns.copy())
columns.update(TABLE_NAME='test')
tables_columns.append(columns.copy())
mocked_table_columns_query_cursor = Mock()
mocked_table_columns_query_cursor.execute = Mock(return_value=True)
mocked_table_columns_query_cursor.fetchall = Mock(return_value=tables_columns)
mocked_table_top_query_cursor = Mock()
mocked_table_top_query_cursor.execute = Mock(return_value=True)
mocked_table_top_query_cursor.fetchall = Mock(return_value=[])
mocked_oracle = Mock()
mocked_oracle.cursor = Mock(side_effect=[mocked_table_count_query_cursor, mocked_table_columns_query_cursor, mocked_table_top_query_cursor])
mocked_builder = Mock()
mocked_builder.build = Mock(return_value=mocked_oracle)
expected = {'tables': {
'unit': {'columns': [{'character_maximum_length': '1',
'column_default': '',
'column_name': 'column',
'data_type': 'string',
'is_nullable': 'N'}],
'count': 10,
'rows': []}},
'db_connection_string': 'jdbc:oracle:thin:@//test'
}
assert expected == Oracle(mocked_builder, self.logger, db_host = 'test').get_all_tables_info('unit', None, None)
| 45.133333 | 148 | 0.562962 | 533 | 5,416 | 5.285178 | 0.144465 | 0.109336 | 0.085197 | 0.059638 | 0.910188 | 0.872914 | 0.860845 | 0.860845 | 0.860845 | 0.809372 | 0 | 0.004147 | 0.332164 | 5,416 | 119 | 149 | 45.512605 | 0.774675 | 0 | 0 | 0.737374 | 0 | 0 | 0.120569 | 0.022157 | 0 | 0 | 0 | 0 | 0.020202 | 1 | 0.040404 | false | 0 | 0.030303 | 0 | 0.080808 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
91ddd50bcd3ab25c3d8c9358803c91dc21082bf2 | 108,859 | py | Python | store/tests/tests_viewset_Order.py | SupportFJNR/Blitz-API | 3e363f1e06d21628338dcbe5c18911400ca81435 | [
"MIT"
] | 3 | 2019-10-22T00:16:49.000Z | 2021-07-15T07:44:43.000Z | store/tests/tests_viewset_Order.py | SupportFJNR/Blitz-API | 3e363f1e06d21628338dcbe5c18911400ca81435 | [
"MIT"
] | 1,183 | 2018-04-19T18:40:30.000Z | 2022-03-31T21:05:05.000Z | store/tests/tests_viewset_Order.py | SupportFJNR/Blitz-API | 3e363f1e06d21628338dcbe5c18911400ca81435 | [
"MIT"
] | 12 | 2018-04-17T19:16:42.000Z | 2022-01-27T00:19:59.000Z | import json
from datetime import (
datetime,
timedelta,
date,
)
from rest_framework import status
from rest_framework.test import (
APIClient,
APITestCase,
)
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.core import mail
from django.test import override_settings
from django.utils import timezone
from django.urls import reverse
import pytz
import responses
from unittest import mock
from blitz_api.factories import (
UserFactory,
AdminFactory,
)
from workplace.models import (
TimeSlot,
Period,
Workplace,
)
from retirement.models import (
Retreat,
RetreatInvitation,
RetreatType,
RetreatDate, Reservation,
)
from store.tests.paysafe_sample_responses import (
SAMPLE_PROFILE_RESPONSE,
SAMPLE_PAYMENT_RESPONSE,
SAMPLE_CARD_RESPONSE,
SAMPLE_INVALID_PAYMENT_TOKEN,
SAMPLE_INVALID_SINGLE_USE_TOKEN,
SAMPLE_CARD_ALREADY_EXISTS,
SAMPLE_CARD_REFUSED,
)
from store.models import (
Package,
Order,
OrderLine,
Membership,
PaymentProfile,
Coupon,
CouponUser,
MembershipCoupon,
OptionProduct,
)
User = get_user_model()
LOCAL_TIMEZONE = pytz.timezone(settings.TIME_ZONE)
@override_settings(
PAYSAFE={
'ACCOUNT_NUMBER': "0123456789",
'USER': "user",
'PASSWORD': "password",
'BASE_URL': "http://example.com/",
'VAULT_URL': "customervault/v1/",
'CARD_URL': "cardpayments/v1/"
},
LOCAL_SETTINGS={
"EMAIL_SERVICE": True,
"FRONTEND_INTEGRATION": {
"POLICY_URL": "fake_url",
"LINK_TO_BE_PREPARED_FOR_VIRTUAL_RETREAT": "fake_url",
"PROFILE_URL": "fake_url"
}
}
)
class OrderTests(APITestCase):
def setUp(self):
self.retreat_content_type = ContentType.objects.get_for_model(Retreat)
self.client = APIClient()
self.user: User = UserFactory()
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.save()
self.admin = AdminFactory()
self.admin.city = "Current city"
self.admin.phone = "123-456-7890"
self.admin.save()
self.user_for_no_place_retreat: User = UserFactory()
self.membership = Membership.objects.create(
name="basic_membership",
details="1-Year student membership",
available=True,
price=50,
duration=timedelta(days=365),
)
self.package_type = ContentType.objects.get_for_model(Package)
self.package = Package.objects.create(
name="extreme_package",
details="100 reservations package",
available=True,
price=40,
reservations=100,
)
self.package2 = Package.objects.create(
name="extreme_package2",
details="1000 reservations package",
available=True,
price=4000,
reservations=1000,
)
self.order = Order.objects.create(
user=self.user,
transaction_date=timezone.now(),
authorization_id=1,
settlement_id=1,
reference_number=751,
)
self.order_admin = Order.objects.create(
user=self.admin,
transaction_date=timezone.now(),
authorization_id=2,
settlement_id=2,
reference_number=751,
)
self.order_line = OrderLine.objects.create(
order=self.order,
quantity=1,
content_type=self.package_type,
object_id=self.package.id,
cost=self.package.price,
)
self.payment_profile = PaymentProfile.objects.create(
name="payment_api_name",
owner=self.admin,
external_api_id="123",
external_api_url="https://example.com/customervault/v1/profiles"
)
self.workplace = Workplace.objects.create(
name="random_workplace",
details="This is a description of the workplace.",
seats=40,
address_line1="123 random street",
postal_code="123 456",
state_province="Random state",
country="Random country",
)
self.workplace_no_seats = Workplace.objects.create(
name="random_workplace",
details="This is a description of the workplace.",
seats=0,
address_line1="123 random street",
postal_code="123 456",
state_province="Random state",
country="Random country",
)
self.period = Period.objects.create(
name="random_period_active",
workplace=self.workplace,
start_date=timezone.now(),
end_date=timezone.now() + timedelta(weeks=4),
price=3,
is_active=True,
)
self.period_no_seats = Period.objects.create(
name="random_period_active",
workplace=self.workplace_no_seats,
start_date=timezone.now(),
end_date=timezone.now() + timedelta(weeks=4),
price=3,
is_active=True,
)
self.time_slot = TimeSlot.objects.create(
name="morning_time_slot",
period=self.period,
price=1,
start_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 8)),
end_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 12)),
)
self.time_slot_no_seats = TimeSlot.objects.create(
name="no_place_left_timeslot",
period=self.period_no_seats,
price=3,
start_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 8)),
end_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 12)),
)
self.retreatType = RetreatType.objects.create(
name="Type 1",
minutes_before_display_link=10,
number_of_tomatoes=4,
template_id_for_welcome_message=1,
)
self.retreat = Retreat.objects.create(
name="mega_retreat",
details="This is a description of the mega retreat.",
seats=400,
address_line1="123 random street",
postal_code="123 456",
state_province="Random state",
country="Random country",
price=199,
min_day_refund=7,
min_day_exchange=7,
refund_rate=50,
accessibility=True,
form_url="example.com",
carpool_url='example2.com',
review_url='example3.com',
has_shared_rooms=True,
toilet_gendered=False,
room_type=Retreat.SINGLE_OCCUPATION,
type=self.retreatType,
)
RetreatDate.objects.create(
start_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 8)),
end_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 17, 12)),
retreat=self.retreat,
)
self.retreat.activate()
self.retreat.add_wait_queue_place(self.user, generate_cron=False)
self.retreat_no_seats = Retreat.objects.create(
name="mega_retreat",
details="This is a description of the mega retreat.",
seats=1,
address_line1="123 random street",
postal_code="123 456",
state_province="Random state",
country="Random country",
price=199,
min_day_refund=7,
min_day_exchange=7,
refund_rate=50,
accessibility=True,
form_url="example.com",
carpool_url='example2.com',
review_url='example3.com',
has_shared_rooms=True,
toilet_gendered=False,
room_type=Retreat.SINGLE_OCCUPATION,
type=self.retreatType,
)
RetreatDate.objects.create(
start_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 8)),
end_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 17, 12)),
retreat=self.retreat_no_seats,
)
Reservation.objects.create(
user=self.user_for_no_place_retreat,
retreat=self.retreat_no_seats,
is_active=True,
)
self.retreat_no_seats.activate()
self.coupon = Coupon.objects.create(
code="ABCD1234",
start_time=LOCAL_TIMEZONE.localize(datetime(2000, 1, 15, 8)),
end_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 8)),
value=10,
max_use_per_user=0,
max_use=0,
owner=self.admin,
)
self.coupon.applicable_product_types.set([self.package_type])
self.coupon_user = CouponUser.objects.create(
user=self.admin,
uses=5,
coupon=self.coupon,
)
self.invitation = RetreatInvitation.objects.create(
retreat=self.retreat,
nb_places=5,
reserve_seat=True
)
self.maxDiff = None
self.options: OptionProduct = OptionProduct.objects.create(
name="Vegan",
details="Vegan details",
available=True,
price=50,
max_quantity=10
)
@responses.activate
def test_create_with_payment_token(self):
"""
Ensure we can create an order when provided with a payment_token.
(Token representing an existing payment card.)
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}, {
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
'metadata':
json.dumps({'invitation_id': self.invitation.id}),
'options': [{
'id': self.options.id,
'quantity': 1
}]
}],
'coupon': "ABCD1234",
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
new_order_id = response_data['id']
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][1]['order']
del response_data['order_lines'][1]['url']
del response_data['order_lines'][1]['id']
del response_data['order_lines'][2]['order']
del response_data['order_lines'][2]['url']
del response_data['order_lines'][2]['id']
del response_data['order_lines'][3]['order']
del response_data['order_lines'][3]['url']
del response_data['order_lines'][3]['id']
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
content = {
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 50.0,
'metadata': None,
'options': []
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
'coupon': "ABCD1234",
'coupon_real_value': 10.0,
'cost': 2 * self.package.price - 10,
'metadata': None,
'options': []
}, {
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 0.0,
'metadata': None,
'options': []
}, {
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'metadata':
json.dumps({'invitation_id': self.invitation.id}),
'cost': 199.0 + self.options.price,
'options': [{
'id': self.options.id,
'quantity': 1
}]
}],
'user': f'http://testserver/users/{self.admin.id}',
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertCountEqual(response_data['order_lines'],
content['order_lines'])
del response_data['order_lines']
del content['order_lines']
self.assertEqual(response_data, content)
old_uses = self.coupon_user.uses
self.coupon_user.refresh_from_db()
self.assertEqual(self.coupon_user.uses, old_uses + 1)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, self.package.reservations * 2)
self.assertEqual(admin.membership, self.membership)
self.assertEqual(
admin.membership_end,
FIXED_TIME.date() + self.membership.duration
)
admin.tickets = 1
admin.membership = None
admin.save()
# 1 email for the order details
# 1 email for the retreat informations
self.assertEqual(len(mail.outbox), 2)
# validate that the invitation are linked to the
# reservation of the retreat
self.assertEqual(
self.invitation.retreat_reservations.all()[0].user,
self.admin)
new_order: Order = Order.objects.get(id=new_order_id)
total_price = \
self.membership.price * 1 + \
self.package.price * 2 + \
self.retreat.price * 1 + \
self.options.price - \
self.coupon.value
self.assertEqual(new_order.total_cost, total_price)
@responses.activate
def test_order_retreat_invitation_reserved_seats(self):
"""
Ensure we can create an order when provided with a payment_token.
(Token representing an existing payment card.)
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
self.retreat.seats = self.invitation.nb_places_free()
self.retreat.save()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
'options': [{
'id': self.options.id,
'quantity': 1
}]
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_400_BAD_REQUEST,
response.content,
)
response_data = json.loads(response.content)
data = {
"non_field_errors": [
"There are no places left in the requested retreat."]
}
self.assertEqual(
response_data,
data,
response_data,
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
'metadata':
json.dumps({'invitation_id': self.invitation.id}),
'options': [{
'id': self.options.id,
'quantity': 1
}]
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
@responses.activate
def test_buy_renew_membership(self):
"""
Ensure we can renew a membership
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
end_time_membership = date(2018, 1, 15)
end_time_membership_updated = \
end_time_membership + self.membership.duration
self.user.membership = self.membership
self.user.membership_end = end_time_membership
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
self.user.refresh_from_db()
self.assertEqual(self.user.membership_end,
end_time_membership_updated)
@responses.activate
def test_buy_renew_membership_with_old_membership(self):
"""
Ensure we can renew a membership
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
end_time_membership = date(2017, 1, 15)
end_time_membership_updated = \
FIXED_TIME.date() + self.membership.duration
self.user.membership = self.membership
self.user.membership_end = end_time_membership
self.user.save()
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
self.user.refresh_from_db()
self.assertEqual(self.user.membership_end,
end_time_membership_updated)
@responses.activate
def test_create_reservation_only(self):
"""
Ensure we can create an order for a reservation only.
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'order_lines': [{
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
content = {
'order_lines': [{
'content_type': 'timeslot',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 0.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.admin.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '0',
'settlement_id': '0',
'reference_number': '0',
}
self.assertEqual(response_data, content)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 0)
admin.tickets = 1
admin.membership = None
admin.save()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
@responses.activate
def test_create_reservation_only_from_admin(self):
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'order_lines': [{
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}],
'target_user': 'http://testserver/users/' + str(self.user.id),
'bypass_payment': False,
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['transaction_date']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
content = {
'order_lines': [{
'content_type': 'timeslot',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 0.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.user.id),
'authorization_id': '0',
'settlement_id': '0',
'reference_number': '0',
}
self.assertEqual(response_data, content)
user = self.user
user.refresh_from_db()
self.assertEqual(user.tickets, 0)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
@responses.activate
def test_create_reservation_only_from_admin_without_payment(self):
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'order_lines': [{
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}],
'target_user': 'http://testserver/users/' + str(self.user.id),
'bypass_payment': True,
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED,
response.content)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['transaction_date']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
content = {
'order_lines': [{
'content_type': 'timeslot',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 0.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.user.id),
'authorization_id': '0',
'settlement_id': '0',
'reference_number': '0',
}
self.assertEqual(response_data, content)
user = self.user
user.refresh_from_db()
self.assertEqual(user.tickets, 1)
@responses.activate
def test_create_reservation_only_from_not_admin(self):
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'order_lines': [{
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}],
'target_user': 'http://testserver/users/' + str(self.user.id),
'bypass_payment': False,
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors':
[
'You don\'t have the permission to create '
'an order for another user.'
]
}
self.assertEqual(response_data, content)
@responses.activate
def test_create_reservation_twice(self):
"""
Ensure we can't create an order for the same reservation twice.
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'order_lines': [{
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
content = {
'order_lines': [{
'content_type': 'timeslot',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 0.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.admin.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '0',
'settlement_id': '0',
'reference_number': '0',
}
self.assertEqual(response_data, content)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 0)
admin.tickets = 1
admin.membership = None
admin.save()
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"You already are registered to this timeslot: "
"2130-01-15 13:00:00+00:00 - 2130-01-15 17:00:00+00:00."
]
}
self.assertEqual(response_data, content)
@responses.activate
def test_create_user_has_membership(self):
"""
Ensure we can't create an order containing a membership if the user
already has a membership.
"""
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"You already have an active membership."
]
}
self.assertEqual(response_data, content)
admin = self.admin
admin.refresh_from_db()
admin.tickets = 1
admin.membership = None
admin.save()
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@responses.activate
def test_create_no_place_left(self):
"""
Ensure we can't create an order with reservations if the requested
timeslot has no place left.
"""
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'timeslot',
'object_id': self.time_slot_no_seats.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"There are no places left in the requested timeslot."
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
def test_create_coupon_invalid(self):
"""
Ensure we can't create an order with invalid coupon.
"""
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "INVALID",
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'coupon': ['Object with code=INVALID does not exist.']
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
def test_create_coupon_max_use_exceeded(self):
"""
Ensure we can't create an order with a coupon already used maximum
times.
"""
self.client.force_authenticate(user=self.admin)
self.coupon.max_use = 1
self.coupon.save()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'Maximum number of uses exceeded for this coupon.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.coupon.max_use = 0
self.coupon.save()
old_uses = self.coupon_user.uses
self.coupon_user.refresh_from_db()
self.assertEqual(self.coupon_user.uses, old_uses)
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
def test_create_coupon_max_user_use_exceeded(self):
"""
Ensure we can't create an order with a coupon already used maximum
times by a specific user.
"""
self.client.force_authenticate(user=self.admin)
self.coupon.max_use_per_user = 1
self.coupon.save()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'Maximum number of uses exceeded for this coupon.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.coupon.max_use_per_user = 0
self.coupon.save()
old_uses = self.coupon_user.uses
self.coupon_user.refresh_from_db()
self.assertEqual(self.coupon_user.uses, old_uses)
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
def test_create_coupon_not_active(self):
"""
Ensure we can't create an order with a coupon that is not active.
"""
FIXED_TIME = datetime(1999, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'This coupon is only valid between 2000-01-15 and 2130-01-15.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.coupon.max_use = 0
self.coupon.save()
old_uses = self.coupon_user.uses
self.coupon_user.refresh_from_db()
self.assertEqual(self.coupon_user.uses, old_uses)
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
def test_create_coupon_not_applicable(self):
"""
Ensure we can't create an order with a coupon that is not applicable.
"""
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'This coupon does not apply to any product.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.coupon.max_use = 0
self.coupon.save()
old_uses = self.coupon_user.uses
self.coupon_user.refresh_from_db()
self.assertEqual(self.coupon_user.uses, old_uses)
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
@responses.activate
def test_create_no_place_left_retreat(self):
"""
Ensure we can't create an order with reservations if the requested
retreat has no place left.
"""
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'retreat',
'object_id': self.retreat_no_seats.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"There are no places left in the requested retreat."
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
@responses.activate
def test_create_reserved_retreat_not_authorized(self):
"""
Ensure we can't create an order with reservations if the requested
retreat has only reserved seats and the user has not been notified
(not on the mailing list).
"""
self.client.force_authenticate(user=self.user)
self.retreat_no_seats.wait_queue_places.all().delete()
self.retreat_no_seats.add_wait_queue_place(self.user,
generate_cron=False)
self.retreat_no_seats.save()
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'retreat',
'object_id': self.retreat_no_seats.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"There are no places left in the requested retreat."
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@responses.activate
def test_create_reserved_retreat(self):
"""
Ensure we can create an order with reservations if the requested
retreat has reserved seats and the user has been notified
(on the mailing list).
"""
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
self.retreat_no_seats.wait_queue_places.all().delete()
new_wait_queue_place = \
self.retreat_no_seats.add_wait_queue_place(self.user)
self.retreat_no_seats.add_user_to_wait_queue(self.user)
new_wait_queue_place.notify()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'retreat',
'object_id': self.retreat_no_seats.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
content = {
'order_lines': [{
'content_type': 'retreat',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 199.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.user.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
# 1 email for the order details
# 1 email for the notification
# 1 email for the retreat informations
self.assertEqual(len(mail.outbox), 3)
@responses.activate
def test_fail_order_retreat_no_membership(self):
"""
Ensure we can't create an order with a physical retreat that need a
membership of we do not have a membership in profile or in cart
"""
self.client.force_authenticate(user=self.user)
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.save()
self.assertEqual(
self.user.get_active_membership(),
None
)
self.retreat.exclusive_memberships.add(self.membership)
self.retreat.save()
self.assertTrue(
self.retreat.exclusive_memberships.all().exists()
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [
{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
},
],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_400_BAD_REQUEST,
response.content
)
response_data = json.loads(response.content)
content = {
"non_field_errors": [
"User does not have the required membership to "
"order this retreat."
]
}
self.assertEqual(
response_data,
content
)
@responses.activate
def test_fail_order_retreat_membership_expired(self):
"""
Ensure we can't create an order with a physical retreat that need a
membership of we do not have a membership in profile or in cart
"""
self.client.force_authenticate(user=self.user)
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.membership = self.membership
self.user.membership_end = date.today()
self.user.save()
self.assertEqual(
self.user.get_active_membership(),
None
)
self.retreat.exclusive_memberships.add(self.membership)
self.retreat.save()
self.assertTrue(
self.retreat.exclusive_memberships.all().exists()
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [
{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
},
],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_400_BAD_REQUEST,
response.content
)
response_data = json.loads(response.content)
content = {
"non_field_errors": [
"User does not have the required membership to "
"order this retreat."
]
}
self.assertEqual(
response_data,
content
)
@responses.activate
def test_buy_retreat_with_membership_expired(self):
"""
Ensure we can create an order with a physical retreat that need a
membership of we do not have a membership in profile but have one in
cart
"""
self.client.force_authenticate(user=self.user)
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.membership = self.membership
self.user.membership_end = date.today()
self.user.save()
self.assertEqual(
self.user.get_active_membership(),
None
)
self.retreat.exclusive_memberships.add(self.membership)
self.retreat.save()
self.assertTrue(
self.retreat.exclusive_memberships.all().exists()
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [
{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
},
{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
},
],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content
)
@responses.activate
def test_buy_retreat_without_membership(self):
"""
Ensure we can create an order with a physical retreat that need a
membership of we do not have a membership in profile but have one in
cart
"""
self.client.force_authenticate(user=self.user)
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.save()
self.assertEqual(
self.user.get_active_membership(),
None
)
self.retreat.exclusive_memberships.add(self.membership)
self.retreat.save()
self.assertTrue(
self.retreat.exclusive_memberships.all().exists()
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [
{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
},
{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
},
],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content
)
@responses.activate
def test_create_retreat(self):
"""
Ensure we can create an order with a physical retreat and a
membership and that we pay for all
"""
self.client.force_authenticate(user=self.user)
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.save()
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [
{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
},
{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}
],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][1]['order']
del response_data['order_lines'][1]['object_id']
del response_data['order_lines'][1]['url']
del response_data['order_lines'][1]['id']
content = {
'order_lines': [
{
'content_type': 'retreat',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 199.0,
'metadata': None,
'options': []
},
{
'content_type': 'membership',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 50.0,
'metadata': None,
'options': []
}
],
'user': 'http://testserver/users/' + str(self.user.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
# 1 email for the order details
# 1 email for the retreat informations
self.assertEqual(len(mail.outbox), 2)
@responses.activate
def test_create_retreat_twice(self):
"""
Ensure we can't create an order with a reservation for a retreat
to which the user is already registered.
"""
self.client.force_authenticate(user=self.user)
self.user.city = "Current city"
self.user.phone = "123-456-7890"
self.user.save()
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
content = {
'order_lines': [{
'content_type': 'retreat',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 199.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.user.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
# 1 email for the order details
# 1 email for the retreat informations
self.assertEqual(len(mail.outbox), 2)
# Duplicate order
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_400_BAD_REQUEST,
response.content
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"You already are registered to this retreat: {0}.".format(
str(self.retreat)
)
]
}
self.assertEqual(response_data, content)
@responses.activate
def test_create_retreat_missing_user_info(self):
"""
Ensure we can't create an order with reservations if the requesting
user has an incomplete profile.
"""
self.client.force_authenticate(user=self.user)
self.user.city = None
self.user.save()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'retreat',
'object_id': self.retreat_no_seats.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"Incomplete user profile. 'phone' and 'city' field must "
"be filled in the user profile to book a retreat."
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@responses.activate
def test_create_not_enough_tickets(self):
"""
Ensure we can't create an order with reservations if the requesting
user doesn't have enough tickets.
"""
self.client.force_authenticate(user=self.admin)
self.admin.tickets = 0
self.admin.save()
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'timeslot',
'object_id': self.time_slot_no_seats.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
"You don't have enough tickets to make this reservation."
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 0)
self.assertEqual(admin.membership, None)
self.admin.tickets = 1
self.admin.save()
@responses.activate
def test_create_with_invalid_payment_token(self):
"""
Ensure we can't create an order when provided with a bad payment_token.
(Token representing an non-existing payment card.)
"""
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_INVALID_PAYMENT_TOKEN,
status=400
)
data = {
'payment_token': "invalid",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = {
'non_field_errors': [
"An error occured while processing the payment: "
"invalid payment token or payment profile/card "
"inactive."
]
}
self.assertEqual(
json.loads(response.content).get('non_field_errors'),
content.get('non_field_errors'))
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
@responses.activate
def test_create_with_single_use_token_no_profile(self):
"""
Ensure we can create an order when provided with a single_use_token.
(Token representing a new payment card.)
The PaymentProfile will be created if none exists.
"""
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/",
json=SAMPLE_PROFILE_RESPONSE,
status=201
)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/123/cards/",
json=SAMPLE_CARD_RESPONSE,
status=201
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'single_use_token': "SChsxyprFn176yhD",
'order_lines': [{
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][1]['order']
del response_data['order_lines'][1]['object_id']
del response_data['order_lines'][1]['url']
del response_data['order_lines'][1]['id']
content = {
'order_lines': [{
'content_type': 'package',
'quantity': 2,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 2 * self.package.price,
'metadata': None,
'options': []
}, {
'content_type': 'timeslot',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 0.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.user.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
user = self.user
user.refresh_from_db()
self.assertEqual(user.tickets, self.package.reservations * 2)
user.tickets = 1
user.save()
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
@responses.activate
def test_create_with_single_use_token_existing_profile(self):
"""
Ensure we can create an order when provided with a single_use_token.
The existing PaymentProfile will be used. A new card will be added.
"""
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/123/cards/",
json=SAMPLE_CARD_RESPONSE,
status=201
)
data = {
'single_use_token': "SChsxyprFn176yhD",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][1]['order']
del response_data['order_lines'][1]['object_id']
del response_data['order_lines'][1]['url']
del response_data['order_lines'][1]['id']
content = {
'order_lines': [{
'content_type': 'membership',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 50.0,
'metadata': None,
'options': []
}, {
'content_type': 'package',
'quantity': 2,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 2 * self.package.price,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.admin.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, self.package.reservations * 2 + 1)
self.assertEqual(admin.membership, self.membership)
admin.tickets = 1
admin.membership = None
admin.save()
@responses.activate
def test_create_with_invalid_single_use_token(self):
"""
Ensure we can't create an order when provided with a bad
single_use_token.
(Token representing a new payment card.)
"""
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/123/cards/",
json=SAMPLE_INVALID_SINGLE_USE_TOKEN,
status=400
)
data = {
'single_use_token': "invalid",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = content = {
'non_field_errors': [
"An error occured while processing the payment: "
"invalid payment or single-use token."
]
}
self.assertEqual(
json.loads(response.content).get('non_field_errors'),
content.get('non_field_errors'))
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
@responses.activate
def test_create_with_invalid_single_use_token_no_profile(self):
"""
Ensure we can't create an order when provided with a bad
single_use_token.
(Token representing a new payment card.)
"""
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/",
json=SAMPLE_INVALID_SINGLE_USE_TOKEN,
status=400
)
data = {
'single_use_token': "invalid",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = {
'non_field_errors': [
"An error occured while processing the payment: "
"invalid payment or single-use token."
]
}
self.assertEqual(
json.loads(response.content).get('non_field_errors'),
content.get('non_field_errors'))
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
user = self.user
user.refresh_from_db()
self.assertEqual(user.tickets, 1)
self.assertEqual(user.membership, None)
@responses.activate
def test_create_payment_issue(self):
"""
Ensure we can't create an order when the payment proccessing fails.
"""
self.client.force_authenticate(user=self.user)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/",
json=SAMPLE_PROFILE_RESPONSE,
status=201
)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/123/cards/",
json=SAMPLE_CARD_RESPONSE,
status=201
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_CARD_REFUSED,
status=400
)
data = {
'single_use_token': "invalid",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = content = {
'non_field_errors': [
"An error occured while processing the payment: "
"the request has been declined by the issuing bank."
]
}
self.assertEqual(
json.loads(response.content).get('non_field_errors'),
content.get('non_field_errors'))
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
user = self.user
user.refresh_from_db()
self.assertEqual(user.tickets, 1)
self.assertEqual(user.membership, None)
@responses.activate
def test_create_with_single_use_token_existing_card(self):
"""
Ensure we can create an order when provided with a single_use_token
representing a card that is already stored in the user's profile.
"""
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/123/cards/",
json=SAMPLE_CARD_ALREADY_EXISTS,
status=400
)
responses.add(
responses.POST,
"http://example.com/customervault/v1/profiles/123/cards/",
json=SAMPLE_CARD_RESPONSE,
status=201
)
responses.add(
responses.GET,
"http://example.com/customervault/v1/cards/456",
json=SAMPLE_CARD_RESPONSE,
status=200
)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
responses.add(
responses.DELETE,
"http://example.com/customervault/v1/profiles/123/cards/"
"424d2472-4afd-44a3-a678-8f4611e864a5",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'user': reverse('user-detail', args=[self.admin.id]),
'single_use_token': "invalid",
'transaction_date': timezone.now(),
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['order']
del response_data['order_lines'][0]['object_id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][1]['order']
del response_data['order_lines'][1]['object_id']
del response_data['order_lines'][1]['url']
del response_data['order_lines'][1]['id']
content = {
'authorization_id': '1',
'order_lines': [{
'content_type': 'membership',
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 50.0,
'metadata': None,
'options': []
}, {
'content_type': 'package',
'quantity': 2,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 2 * self.package.price,
'metadata': None,
'options': []
}],
'settlement_id': '1',
'reference_number': '751',
'transaction_date': response_data['transaction_date'],
'user': 'http://testserver/users/' + str(self.admin.id),
}
self.assertEqual(response_data, content)
self.admin.refresh_from_db()
self.assertEqual(self.admin.tickets, self.package.reservations * 2 + 1)
self.assertEqual(self.admin.membership, self.membership)
def test_create_missing_payment_details(self):
"""
Ensure we can't create an order if no payment details are provided.
"""
self.client.force_authenticate(user=self.admin)
data = {
'user': reverse('user-detail', args=[self.user.id]),
'transaction_date': timezone.now(),
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'order': 'http://testserver/orders/' + str(self.order.id),
'quantity': 1,
'url': 'http://testserver/order_lines/' +
str(self.order_line.id)
}, {
'content_type': 'package',
'object_id': self.package.id,
'order': 'http://testserver/orders/' + str(self.order.id),
'quantity': 2,
'url': 'http://testserver/order_lines/' +
str(self.order_line.id)
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = {
'non_field_errors': [
'A payment_token or single_use_token is required to '
'create an order.'
]
}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
admin = self.admin
admin.refresh_from_db()
self.assertEqual(admin.tickets, 1)
self.assertEqual(admin.membership, None)
def test_create_missing_field(self):
"""
Ensure we can't create an order when required field are missing.
"""
self.client.force_authenticate(user=self.admin)
data = {}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = {
'order_lines': ['This field is required.']
}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_null_field(self):
"""
Ensure we can't create an order when required field are null.
"""
self.client.force_authenticate(user=self.admin)
data = {
'order_lines': None,
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = {
'order_lines': ['This field may not be null.']
}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_create_invalid_field(self):
"""
Ensure we can't create an order when required field are invalid.
"""
self.client.force_authenticate(user=self.admin)
data = {
'order_lines': (1,),
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
content = {
'order_lines': [{
'non_field_errors': [
'Invalid data. Expected a dictionary, but got int.'
]
}]
}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
@responses.activate
def test_create_with_membership_coupon(self):
"""
Ensure we can order a membership that includes a membership coupon
"""
self.client.force_authenticate(user=self.admin)
nb_coupon_start = self.admin.coupons.all().count()
membership_coupon = MembershipCoupon.objects.create(
value=100,
percent_off=0,
max_use=4,
max_use_per_user=4,
details="",
membership=self.membership,
)
membership_coupon.applicable_product_types.set(
[ContentType.objects.get_for_model(Membership)]
)
membership_coupon.save()
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['order']
content = {
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 50.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.admin.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
self.assertEqual(self.admin.coupons.all().count(), 1 + nb_coupon_start)
# Get the last coupon generate, it should be the new one associate
# with the membership
new_coupon = self.admin.coupons.all().order_by('-id')[0]
self.assertEqual(new_coupon.value, membership_coupon.value)
self.assertEqual(new_coupon.percent_off, 0)
self.assertEqual(new_coupon.max_use, 4)
self.assertEqual(new_coupon.max_use_per_user, 4)
self.assertEqual(new_coupon.details, "")
self.assertTrue(
timezone.now() - timedelta(minutes=1) <
new_coupon.start_time <
timezone.now()
)
self.assertTrue(
timezone.now() + self.membership.duration - timedelta(minutes=1) <
new_coupon.end_time <
timezone.now() + self.membership.duration
)
@responses.activate
def test_create_with_membership_coupon_after_limit(self):
"""
Ensure we can order a membership that includes a membership coupon
"""
self.client.force_authenticate(user=self.admin)
nb_coupon_start = self.admin.coupons.all().count()
membership_coupon = MembershipCoupon.objects.create(
value=100,
percent_off=0,
max_use=4,
max_use_per_user=4,
details="",
membership=self.membership,
limit_date=timezone.now()
)
membership_coupon.applicable_product_types.set(
[ContentType.objects.get_for_model(Membership)]
)
membership_coupon.save()
FIXED_TIME = datetime(2018, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
responses.add(
responses.POST,
"http://example.com/cardpayments/v1/accounts/0123456789/auths/",
json=SAMPLE_PAYMENT_RESPONSE,
status=200
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-list'),
data,
format='json',
)
self.assertEqual(
response.status_code,
status.HTTP_201_CREATED,
response.content,
)
response_data = json.loads(response.content)
del response_data['url']
del response_data['id']
del response_data['order_lines'][0]['id']
del response_data['order_lines'][0]['url']
del response_data['order_lines'][0]['order']
content = {
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
'coupon': None,
'coupon_real_value': 0.0,
'cost': 50.0,
'metadata': None,
'options': []
}],
'user': 'http://testserver/users/' + str(self.admin.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
}
self.assertEqual(response_data, content)
# The number of coupon does not change since the limit_date is expired
self.assertEqual(self.admin.coupons.all().count(), nb_coupon_start)
def test_update(self):
"""
Ensure we can update an order.
An empty 'order_lines' list will be ignored.
"""
self.client.force_authenticate(user=self.admin)
data = {
'order_lines': [{
'content_type': 'package',
'object_id': self.package.id,
'quantity': 99,
}],
}
response = self.client.put(
reverse(
'order-detail',
kwargs={'pk': self.order.id},
),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'id': self.order.id,
'url': 'http://testserver/orders/' + str(self.order.id),
'user': 'http://testserver/users/' + str(self.user.id),
'transaction_date': response_data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
'order_lines': [{
'url': f'http://testserver/order_lines/{self.order_line.id}',
'id': self.order_line.id,
'content_type': 'package',
'coupon_real_value': 0.0,
'cost': 99.0 * self.package.price,
'coupon': None,
'object_id': self.package.id,
'quantity': 99,
'order': 'http://testserver/orders/' + str(self.order.id),
'metadata': None,
'options': [],
}],
}
self.assertCountEqual(response_data['order_lines'],
content['order_lines'])
del response_data['order_lines']
del content['order_lines']
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_delete(self):
"""
Ensure we can delete an order.
"""
self.client.force_authenticate(user=self.admin)
response = self.client.delete(
reverse(
'order-detail',
kwargs={'pk': self.order.id},
),
)
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
def test_list(self):
"""
Ensure we can't list orders as an unauthenticated user.
"""
response = self.client.get(
reverse('order-list'),
format='json',
)
data = json.loads(response.content)
content = {'detail': 'Authentication credentials were not provided.'}
self.assertEqual(data, content)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_list_owner(self):
"""
Ensure we can list owned orders as an authenticated user.
"""
self.client.force_authenticate(user=self.user)
response = self.client.get(
reverse('order-list'),
format='json',
)
data = json.loads(response.content)
content = {
'count': 1,
'next': None,
'previous': None,
'results': [{
'id': self.order.id,
'transaction_date': data['results'][0]['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
'order_lines': [{
'content_type': 'package',
'id': self.order_line.id,
'object_id': self.package.id,
'order': 'http://testserver/orders/' + str(self.order.id),
'quantity': 1,
'url': 'http://testserver/order_lines/' +
str(self.order_line.id),
'coupon': None,
'coupon_real_value': 0.0,
'cost': self.package.price,
'metadata': None,
'options': []
}],
'url': 'http://testserver/orders/' + str(self.order.id),
'user': 'http://testserver/users/' + str(self.user.id),
}]
}
self.assertEqual(data, content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_list_admin(self):
"""
Ensure we can list all orders as an admin.
"""
self.client.force_authenticate(user=self.admin)
response = self.client.get(
reverse('order-list'),
format='json',
)
data = json.loads(response.content)
content = {
'count': 2,
'next': None,
'previous': None,
'results': [{
'id': self.order.id,
'transaction_date': data['results'][0]['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
'order_lines': [{
'content_type': 'package',
'id': self.order_line.id,
'object_id': self.package.id,
'order': 'http://testserver/orders/' + str(self.order.id),
'quantity': 1,
'url': 'http://testserver/order_lines/' +
str(self.order_line.id),
'coupon': None,
'coupon_real_value': 0.0,
'cost': self.package.price,
'metadata': None,
'options': []
}],
'url': 'http://testserver/orders/' + str(self.order.id),
'user': 'http://testserver/users/' + str(self.user.id),
}, {
'id': self.order_admin.id,
'transaction_date': data['results'][1]['transaction_date'],
'authorization_id': '2',
'settlement_id': '2',
'reference_number': '751',
'order_lines': [],
'url': 'http://testserver/orders/' + str(self.order_admin.id),
'user': 'http://testserver/users/' + str(self.admin.id),
}]
}
self.assertEqual(data, content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_read(self):
"""
Ensure we can't read an order as an unauthenticated user.
"""
response = self.client.get(
reverse(
'order-detail',
kwargs={'pk': self.order.id},
),
)
content = {'detail': 'Authentication credentials were not provided.'}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_read_owner(self):
"""
Ensure we can read an order owned by an authenticated user.
"""
self.client.force_authenticate(user=self.user)
response = self.client.get(
reverse(
'order-detail',
kwargs={'pk': self.order.id},
),
)
data = json.loads(response.content)
content = {
'id': self.order.id,
'transaction_date': data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
'order_lines': [{
'content_type': 'package',
'id': self.order_line.id,
'object_id': self.package.id,
'order': 'http://testserver/orders/' + str(self.order.id),
'quantity': 1,
'url': 'http://testserver/order_lines/' +
str(self.order_line.id),
'coupon': None,
'coupon_real_value': 0.0,
'cost': self.package.price,
'metadata': None,
'options': []
}],
'url': 'http://testserver/orders/' + str(self.order.id),
'user': 'http://testserver/users/' + str(self.user.id),
}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_read_owner_not_owned(self):
"""
Ensure we can't read an order not owned by an authenticated user.
"""
self.client.force_authenticate(user=self.user)
response = self.client.get(
reverse(
'order-detail',
kwargs={'pk': 2},
),
)
content = {'detail': 'Not found.'}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_read_admin(self):
"""
Ensure we can read any order as an admin.
"""
self.client.force_authenticate(user=self.admin)
response = self.client.get(
reverse(
'order-detail',
kwargs={'pk': self.order.id},
),
)
data = json.loads(response.content)
content = {
'id': self.order.id,
'transaction_date': data['transaction_date'],
'authorization_id': '1',
'settlement_id': '1',
'reference_number': '751',
'order_lines': [{
'content_type': 'package',
'id': self.order_line.id,
'object_id': self.package.id,
'order': 'http://testserver/orders/' + str(self.order.id),
'quantity': 1,
'url': 'http://testserver/order_lines/' +
str(self.order_line.id),
'coupon': None,
'coupon_real_value': 0.0,
'cost': self.package.price,
'metadata': None,
'options': []
}],
'url': 'http://testserver/orders/' + str(self.order.id),
'user': 'http://testserver/users/' + str(self.user.id),
}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_read_non_existent(self):
"""
Ensure we get not found when asking for an order that doesn't
exist.
"""
self.client.force_authenticate(user=self.user)
response = self.client.get(
reverse(
'order-detail',
kwargs={'pk': 999},
),
)
content = {'detail': 'Not found.'}
self.assertEqual(json.loads(response.content), content)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_validate_coupon(self):
"""
Ensure that we can validate a coupon before creating an order.
"""
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}, {
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
self.assertEqual(
response.status_code,
status.HTTP_200_OK,
response.content,
)
content = {
'value': 10.0
}
self.assertEqual(response_data, content)
def test_validate_coupon_multi_line(self):
"""
Ensure that we can validate a coupon before creating an order.
"""
self.client.force_authenticate(user=self.admin)
coupon = Coupon.objects.create(
code="TEST_MULTI",
start_time=LOCAL_TIMEZONE.localize(datetime(2000, 1, 15, 8)),
end_time=LOCAL_TIMEZONE.localize(datetime(2130, 1, 15, 8)),
value=1000,
max_use_per_user=0,
max_use=0,
owner=self.admin,
)
coupon.applicable_product_types.set(
[
self.package_type,
self.retreat_content_type
]
)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}, {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
}, {
'content_type': 'timeslot',
'object_id': self.time_slot.id,
'quantity': 1,
}, {
'content_type': 'retreat',
'object_id': self.retreat.id,
'quantity': 1,
}],
'coupon': coupon.code,
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
self.assertEqual(
response.status_code,
status.HTTP_200_OK,
response.content,
)
content = {
'orderline': {
'content_type': 'package',
'object_id': self.package.id,
'quantity': 2,
'metadata': None,
'options': []
},
'value': 239.0
}
price_retreat_package = self.retreat.price + self.package.price
self.assertEqual(response_data.get('value'), price_retreat_package)
def test_validate_coupon_invalid(self):
"""
Ensure we can't validate a coupon with an invalid coupon.
"""
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "INVALID",
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'coupon': ['Object with code=INVALID does not exist.']
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_validate_coupon_missing(self):
"""
Ensure we can't validate a coupon with a missing coupon.
"""
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'coupon': ['This field is required.']
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_validate_coupon_max_use_exceeded(self):
"""
Ensure we can't validate a coupon with a coupon already used maximum
times.
"""
self.client.force_authenticate(user=self.admin)
self.coupon.max_use = 1
self.coupon.save()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'Maximum number of uses exceeded for this coupon.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.coupon.max_use = 0
self.coupon.save()
def test_validate_coupon_max_user_use_exceeded(self):
"""
Ensure we can't validate a coupon with a coupon already used maximum
times by a specific user.
"""
self.client.force_authenticate(user=self.admin)
self.coupon.max_use_per_user = 1
self.coupon.save()
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'Maximum number of uses exceeded for this coupon.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.coupon.max_use_per_user = 0
self.coupon.save()
def test_validate_coupon_not_active(self):
"""
Ensure we can't validate a coupon with a coupon that is not active.
"""
FIXED_TIME = datetime(1999, 1, 1, tzinfo=LOCAL_TIMEZONE)
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
with mock.patch(
'store.serializers.timezone.now', return_value=FIXED_TIME):
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'This coupon is only valid between 2000-01-15 and 2130-01-15.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
def test_validate_coupon_not_applicable(self):
"""
Ensure we can't validate a coupon with a coupon that is not applicable.
"""
self.client.force_authenticate(user=self.admin)
data = {
'payment_token': "CZgD1NlBzPuSefg",
'order_lines': [{
'content_type': 'membership',
'object_id': self.membership.id,
'quantity': 1,
}],
'coupon': "ABCD1234",
}
response = self.client.post(
reverse('order-validate-coupon'),
data,
format='json',
)
response_data = json.loads(response.content)
content = {
'non_field_errors': [
'This coupon does not apply to any product.'
]
}
self.assertEqual(response_data, content)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
| 30.146497 | 79 | 0.523172 | 10,567 | 108,859 | 5.200814 | 0.042964 | 0.043234 | 0.028386 | 0.031224 | 0.899631 | 0.881544 | 0.86211 | 0.852594 | 0.839001 | 0.823189 | 0 | 0.024738 | 0.36426 | 108,859 | 3,610 | 80 | 30.154848 | 0.76937 | 0.047805 | 0 | 0.764727 | 0 | 0.000355 | 0.181062 | 0.006415 | 0 | 0 | 0 | 0 | 0.065649 | 1 | 0.020937 | false | 0.001419 | 0.006742 | 0 | 0.028034 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
37dd05a13749312ba2069d88874a8d3958916900 | 123 | py | Python | list_all_data/__init__.py | wahlflo/lad | 294a42b4f0e015db76b5019b99bb0047da4a2ce2 | [
"MIT"
] | 1 | 2020-10-15T05:04:33.000Z | 2020-10-15T05:04:33.000Z | list_all_data/__init__.py | wahlflo/lad | 294a42b4f0e015db76b5019b99bb0047da4a2ce2 | [
"MIT"
] | null | null | null | list_all_data/__init__.py | wahlflo/lad | 294a42b4f0e015db76b5019b99bb0047da4a2ce2 | [
"MIT"
] | null | null | null | from .libary import get_alternate_data_streams_recursively, get_alternate_data_streams_of_file, path_is_an_ntfs_filesystem
| 61.5 | 122 | 0.926829 | 19 | 123 | 5.315789 | 0.789474 | 0.237624 | 0.316832 | 0.455446 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.04878 | 123 | 1 | 123 | 123 | 0.863248 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 9 |
37f82547c33fc923d413d275fba7639c89890750 | 6,269 | py | Python | beluga/liepack/domain/liealgebras/tests/test_liealgebras.py | grantmjg/beluga | 2b06a1ae3de30f5fb98d78188f40e33cd8b155f1 | [
"MIT"
] | null | null | null | beluga/liepack/domain/liealgebras/tests/test_liealgebras.py | grantmjg/beluga | 2b06a1ae3de30f5fb98d78188f40e33cd8b155f1 | [
"MIT"
] | null | null | null | beluga/liepack/domain/liealgebras/tests/test_liealgebras.py | grantmjg/beluga | 2b06a1ae3de30f5fb98d78188f40e33cd8b155f1 | [
"MIT"
] | null | null | null | from beluga.liepack import commutator
from beluga.liepack.domain.liealgebras import *
from random import uniform
tol = 1e-15
def test_rn():
x = rn(4)
y = rn(4)
z = rn(4)
zero = rn(4)
# Vector basis tests
x.set_vector([1,0,0])
y.set_vector([0,1,0])
z.set_vector([0,0,1])
zero.zero()
a = 2
b = 3
# Algebra definitions
assert ((x + y) * z == x * z + y * z).all() # Right distributive
assert (x * (y + z) == x * y + x * z).all() # Left Distributive
assert ((a * x) * (b * y) == (a * b) * (x * y)).all() # Scalar multiplication
# Lie algebra definitions
assert (commutator(a * x + b * y, z) == a * commutator(x, z) + b * commutator(y, z)).all() # Bilinearity
assert (commutator(x, x) == zero).all() # Alternativity
assert (commutator(y, y) == zero).all()
assert (commutator(z, z) == zero).all()
assert (commutator(x, commutator(y, z)) + commutator(z, commutator(x, y)) + commutator(y, commutator(z, x)) == zero).all() # Jacobi Identity
assert (commutator(x, y) == -commutator(y, x)).all() # Anticommutivity
# rn specific (not simple)
assert (commutator(x,y) == zero).all()
assert (commutator(x,z) == zero).all()
assert (commutator(y,z) == zero).all()
# Random vector tests
x.random()
y.random()
z.random()
zero.zero()
a = uniform(-1,1)
b = uniform(-1,1)
# Algebra definitions
assert (((x + y) * z) - (x * z + y * z) < tol).all() # Right distributive
assert ((x * (y + z)) - (x * y + x * z) < tol).all() # Left Distributive
assert (((a * x) * (b * y)) - ((a * b) * (x * y)) < tol).all() # Scalar multiplication
# Lie algebra definitions
assert ((commutator(a * x + b * y, z)) - (a * commutator(x, z) + b * commutator(y, z)) < tol).all() # Bilinearity
assert (commutator(x, x) == zero).all() # Alternativity
assert (commutator(y, y) == zero).all()
assert (commutator(z, z) == zero).all()
assert (commutator(x, commutator(y, z)) + commutator(z, commutator(x, y)) + commutator(y, commutator(z, x)) < tol).all() # Jacobi Identity
assert (commutator(x, y) == -commutator(y, x)).all() # Anticommutivity
def test_so():
x = so(3)
y = so(3)
z = so(3)
zero = so(3)
# Vector basis tests
x.set_vector([1,0,0])
y.set_vector([0,1,0])
z.set_vector([0,0,1])
zero.zero()
a = 2
b = 3
# Algebra definitions
assert ((x + y) * z == x * z + y * z).all() # Right distributive
assert (x * (y + z) == x * y + x * z).all() # Left Distributive
assert ((a * x) * (b * y) == (a * b) * (x * y)).all() # Scalar multiplication
# Lie algebra definitions
assert (commutator(a * x + b * y, z) == a * commutator(x, z) + b * commutator(y, z)).all() # Bilinearity
assert (commutator(x, x) == zero).all() # Alternativity
assert (commutator(y, y) == zero).all()
assert (commutator(z, z) == zero).all()
assert (commutator(x, commutator(y, z)) + commutator(z, commutator(x, y)) + commutator(y, commutator(z, x)) == zero).all() # Jacobi Identity
assert (commutator(x, y) == -commutator(y, x)).all() # Anticommutivity
# so specific (simple)
assert (commutator(x, y) == z).all()
assert (commutator(x, z) == -y).all()
assert (commutator(y, z) == x).all()
# Random vector tests
x.random()
y.random()
z.random()
zero.zero()
a = uniform(-1,1)
b = uniform(-1,1)
# Algebra definitions
assert (((x + y) * z) - (x * z + y * z) < tol).all() # Right distributive
assert ((x * (y + z)) - (x * y + x * z) < tol).all() # Left Distributive
assert (((a * x) * (b * y)) - ((a * b) * (x * y)) < tol).all() # Scalar multiplication
# Lie algebra definitions
assert ((commutator(a * x + b * y, z)) - (a * commutator(x, z) + b * commutator(y, z)) < tol).all() # Bilinearity
assert (commutator(x, x) == zero).all() # Alternativity
assert (commutator(y, y) == zero).all()
assert (commutator(z, z) == zero).all()
assert (commutator(x, commutator(y, z)) + commutator(z, commutator(x, y)) + commutator(y, commutator(z, x)) < tol).all() # Jacobi Identity
assert (commutator(x, y) == -commutator(y, x)).all() # Anticommutivity
def test_sp():
x = sp(2)
y = sp(2)
z = sp(2)
zero = sp(2)
# Vector basis tests
x.set_vector([1,0,0])
y.set_vector([0,1,0])
z.set_vector([0,0,1])
zero.zero()
a = 2
b = 3
# Algebra definitions
assert ((x + y)*z == x*z + y*z).all() # Right distributive
assert (x*(y + z) == x*y + x*z).all() # Left Distributive
assert ((a*x) * (b*y) == (a*b) * (x*y)).all() #Scalar multiplication
# Lie algebra definitions
assert (commutator(a*x + b*y, z) == a*commutator(x,z) + b*commutator(y,z)).all() # Bilinearity
assert (commutator(x, x) == zero).all() # Alternativity
assert (commutator(y, y) == zero).all()
assert (commutator(z, z) == zero).all()
assert (commutator(x, commutator(y,z)) + commutator(z, commutator(x,y)) + commutator(y, commutator(z,x)) == zero).all() # Jacobi Identity
assert (commutator(x,y) == -commutator(y,x)).all() # Anticommutivity
# sp specific (simple)
assert (commutator(x,y) == 2*y).all()
assert (commutator(x,z) == -2*z).all()
assert (commutator(y,z) == x).all()
# Random vector tests
x.random()
y.random()
z.random()
zero.zero()
a = uniform(-1,1)
b = uniform(-1,1)
# Algebra definitions
assert (((x + y) * z) - (x * z + y * z) < tol).all() # Right distributive
assert ((x * (y + z)) - (x * y + x * z) < tol).all() # Left Distributive
assert (((a * x) * (b * y)) - ((a * b) * (x * y)) < tol).all() # Scalar multiplication
# Lie algebra definitions
assert ((commutator(a * x + b * y, z)) - (a * commutator(x, z) + b * commutator(y, z)) < tol).all() # Bilinearity
assert (commutator(x, x) == zero).all() # Alternativity
assert (commutator(y, y) == zero).all()
assert (commutator(z, z) == zero).all()
assert (commutator(x, commutator(y, z)) + commutator(z, commutator(x, y)) + commutator(y, commutator(z, x)) < tol).all() # Jacobi Identity
assert (commutator(x, y) == -commutator(y, x)).all() # Anticommutivity
| 37.76506 | 145 | 0.557505 | 903 | 6,269 | 3.857143 | 0.055371 | 0.206718 | 0.11714 | 0.092449 | 0.942578 | 0.909274 | 0.890899 | 0.890899 | 0.890899 | 0.890899 | 0 | 0.01305 | 0.242144 | 6,269 | 165 | 146 | 37.993939 | 0.720059 | 0.183123 | 0 | 0.779661 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.533898 | 1 | 0.025424 | false | 0 | 0.025424 | 0 | 0.050847 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
5302507e9ca75b8c3a82cc2b9bb9aa1713477ebd | 33,895 | py | Python | desktop/libs/notebook/src/notebook/connectors/altus_adb.py | FrommyMind/hue | 60a2df13da71bed656adbf61269ab841e2370ed4 | [
"Apache-2.0"
] | 2 | 2020-02-02T15:22:13.000Z | 2020-07-29T15:25:44.000Z | desktop/libs/notebook/src/notebook/connectors/altus_adb.py | FrommyMind/hue | 60a2df13da71bed656adbf61269ab841e2370ed4 | [
"Apache-2.0"
] | 7 | 2019-11-28T21:48:38.000Z | 2020-08-02T18:06:40.000Z | desktop/libs/notebook/src/notebook/connectors/altus_adb.py | FrommyMind/hue | 60a2df13da71bed656adbf61269ab841e2370ed4 | [
"Apache-2.0"
] | 6 | 2020-05-29T21:46:30.000Z | 2020-12-15T20:32:19.000Z | #!/usr/bin/env python
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from future import standard_library
standard_library.install_aliases()
from builtins import object
import logging
import json
import sys
from django.urls import reverse
from django.utils.translation import ugettext as _
from notebook.connectors.altus import AnalyticDbApi
from notebook.connectors.base import Api, QueryError
if sys.version_info[0] > 2:
import urllib.request, urllib.error
from urllib.parse import quote as urllib_quote, quote_plus as urllib_quote_plus
else:
from urllib import quote as urllib_quote, quote_plus as urllib_quote_plus
LOG = logging.getLogger(__name__)
RUNNING_STATES = ('QUEUED', 'RUNNING', 'SUBMITTING')
class AltusAdbApi(Api):
def __init__(self, user, cluster_name, interpreter=None, request=None):
Api.__init__(self, user, interpreter=interpreter, request=request)
self.cluster_name = cluster_name
def execute(self, notebook, snippet):
statement = snippet['statement']
return HueQuery(self.user, cluster_crn=self.cluster_name).do_execute(statement)
def check_status(self, notebook, snippet):
handle = snippet['result']['handle']
return HueQuery(self.user, cluster_crn=self.cluster_name).do_check_status(handle)
def fetch_result(self, notebook, snippet, rows, start_over):
handle = snippet['result']['handle']
return HueQuery(self.user, cluster_crn=self.cluster_name).do_fetch_result(handle)
def close_statement(self, notebook, snippet):
return {'status': -1}
def cancel(self, notebook, snippet):
return {'status': -1, 'message': _('Could not cancel.')}
def get_log(self, notebook, snippet, startFrom=0, size=None):
return '...'
def get_jobs(self, notebook, snippet, logs):
return []
def autocomplete(self, snippet, database=None, table=None, column=None, nested=None, operation=None):
url_path = '/notebook/api/autocomplete'
if database is not None:
url_path = '%s/%s' % (url_path, database)
if table is not None:
url_path = '%s/%s' % (url_path, table)
if column is not None:
url_path = '%s/%s' % (url_path, column)
if nested is not None:
url_path = '%s/%s' % (url_path, nested)
return HueQuery(self.user, cluster_crn=self.cluster_name).do_post(url_path=url_path)
class HueQuery(object):
def __init__(self, user, cluster_crn):
self.user = user
self.cluster_crn = cluster_crn
self.api = AnalyticDbApi(self.user)
def do_post(self, url_path):
payload = '''{"method":"POST","url":"https://localhost:8888''' + url_path +'''","httpVersion":"HTTP/1.1","headers":[{"name":"Accept-Encoding","value":"gzip, deflate, br"},{"name":"Content-Type","value":"application/x-www-form-urlencoded; charset=UTF-8"},{"name":"Accept","value":"*/*"},{"name":"X-Requested-With","value":"XMLHttpRequest"},{"name":"Connection","value":"keep-alive"}],"queryString":[],"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=UTF-8",
"text": "snippet=%7B%22type%22%3A%22impala%22%2C%22source%22%3A%22data%22%7D",
"params": [
{
"name": "snippet",
"value": "%7B%22type%22%3A%22impala%22%2C%22source%22%3A%22data%22%7D"
}
]
}}'''
resp = self.api.submit_hue_query(self.cluster_crn, payload)
return json.loads(resp['payload'])
def do_execute(self, query):
payload = '''
{
"method": "POST",
"url": "http://127.0.0.1:8000/notebook/api/execute/impala",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Accept-Encoding",
"value": "gzip, deflate, br"
},
{
"name": "Content-Type",
"value": "application/x-www-form-urlencoded; charset=UTF-8"
},
{
"name": "Accept",
"value": "*/*"
},
{
"name": "X-Requested-With",
"value": "XMLHttpRequest"
},
{
"name": "Connection",
"value": "keep-alive"
}
],
"queryString": [],
"cookies": [
],
"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=UTF-8",
"text": "notebook=%7B%22uuid%22%3A%22f2b8a233-c34c-44b8-a8a1-0e6123996216%22%2C%22name%22%3A%22%22%2C%22description%22%3A%22%22%2C%22type%22%3A%22query-impala%22%2C%22initialType%22%3A%22impala%22%2C%22coordinatorUuid%22%3Anull%2C%22isHistory%22%3Atrue%2C%22isManaged%22%3Afalse%2C%22parentSavedQueryUuid%22%3Anull%2C%22isSaved%22%3Afalse%2C%22onSuccessUrl%22%3Anull%2C%22pubSubUrl%22%3Anull%2C%22isPresentationModeDefault%22%3Afalse%2C%22isPresentationMode%22%3Afalse%2C%22isPresentationModeInitialized%22%3Atrue%2C%22presentationSnippets%22%3A%7B%7D%2C%22isHidingCode%22%3Afalse%2C%22snippets%22%3A%5B%7B%22id%22%3A%22dd5755a3-e8db-82d9-4f98-9f4fb5a99a06%22%2C%22name%22%3A%22%22%2C%22type%22%3A%22impala%22%2C%22isBatchable%22%3Atrue%2C%22aceCursorPosition%22%3A%7B%22column%22%3A33%2C%22row%22%3A0%7D%2C%22errors%22%3A%5B%5D%2C%22aceErrorsHolder%22%3A%5B%5D%2C%22aceWarningsHolder%22%3A%5B%5D%2C%22aceErrors%22%3A%5B%5D%2C%22aceWarnings%22%3A%5B%5D%2C%22editorMode%22%3Atrue%2C%22dbSelectionVisible%22%3Afalse%2C%22isSqlDialect%22%3Atrue%2C%22namespaceRefreshEnabled%22%3Afalse%2C%22availableNamespaces%22%3A%5B%5D%2C%22availableComputes%22%3A%5B%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22default-romain%22%2C%22id%22%3A%22default-romain%22%2C%22name%22%3A%22default-romain%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22compute1%22%2C%22id%22%3A%22compute1%22%2C%22name%22%3A%22compute1%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22compute2%22%2C%22id%22%3A%22compute2%22%2C%22name%22%3A%22compute2%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22altus%22%2C%22namespace%22%3A%22Altus%22%2C%22id%22%3A%22Altus%22%2C%22name%22%3A%22Altus%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22storage1%22%2C%22id%22%3A%22storage1%22%2C%22name%22%3A%22storage1%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22storage2%22%2C%22id%22%3A%22storage2%22%2C%22name%22%3A%22storage2%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22Default%22%2C%22id%22%3A%22Default%22%2C%22name%22%3A%22default%22%7D%5D%2C%22compute%22%3A%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22default-romain%22%2C%22id%22%3A%22default-romain%22%2C%22name%22%3A%22default-romain%22%7D%2C%22database%22%3A%22default%22%2C%22currentQueryTab%22%3A%22queryHistory%22%2C%22pinnedContextTabs%22%3A%5B%5D%2C%22loadingQueries%22%3Afalse%2C%22queriesHasErrors%22%3Afalse%2C%22queriesCurrentPage%22%3A1%2C%22queriesTotalPages%22%3A1%2C%22queriesFilter%22%3A%22%22%2C%22queriesFilterVisible%22%3Afalse%2C%22statementType%22%3A%22text%22%2C%22statementTypes%22%3A%5B%22text%22%2C%22file%22%5D%2C%22statementPath%22%3A%22%22%2C%22externalStatementLoaded%22%3Afalse%2C%22associatedDocumentLoading%22%3Atrue%2C%22associatedDocumentUuid%22%3Anull%2C%22statement_raw%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22statementsList%22%3A%5B%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%5D%2C%22aceSize%22%3A100%2C%22status%22%3A%22running%22%2C%22statusForButtons%22%3A%22executing%22%2C%22properties%22%3A%7B%22files%22%3A%5B%5D%2C%22functions%22%3A%5B%5D%2C%22arguments%22%3A%5B%5D%2C%22settings%22%3A%5B%5D%7D%2C%22viewSettings%22%3A%7B%22placeHolder%22%3A%22Example%3A+SELECT+*+FROM+tablename%2C+or+press+CTRL+%2B+space%22%2C%22sqlDialect%22%3Atrue%7D%2C%22variables%22%3A%5B%5D%2C%22hasCurlyBracketParameters%22%3Atrue%2C%22variableNames%22%3A%5B%5D%2C%22variableValues%22%3A%7B%7D%2C%22statement%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22result%22%3A%7B%22id%22%3A%2206840534-9434-33b5-5eca-2cd08432ceb3%22%2C%22type%22%3A%22table%22%2C%22hasResultset%22%3Atrue%2C%22handle%22%3A%7B%22has_more_statements%22%3Afalse%2C%22statement_id%22%3A0%2C%22statements_count%22%3A1%2C%22previous_statement_hash%22%3A%22acb6478fcf28c31b5e76d49de7d77bbe46fe5e4f9436c16c0ca8ed5f%22%7D%2C%22meta%22%3A%5B%5D%2C%22rows%22%3Anull%2C%22hasMore%22%3Afalse%2C%22statement_id%22%3A0%2C%22statement_range%22%3A%7B%22start%22%3A%7B%22row%22%3A0%2C%22column%22%3A0%7D%2C%22end%22%3A%7B%22row%22%3A0%2C%22column%22%3A0%7D%7D%2C%22statements_count%22%3A1%2C%22previous_statement_hash%22%3Anull%2C%22metaFilter%22%3A%7B%22query%22%3A%22%22%2C%22facets%22%3A%7B%7D%2C%22text%22%3A%5B%5D%7D%2C%22isMetaFilterVisible%22%3Afalse%2C%22filteredMetaChecked%22%3Atrue%2C%22filteredMeta%22%3A%5B%5D%2C%22fetchedOnce%22%3Afalse%2C%22startTime%22%3A%222018-06-12T16%3A15%3A01.951Z%22%2C%22endTime%22%3A%222018-06-12T16%3A15%3A01.951Z%22%2C%22executionTime%22%3A0%2C%22data%22%3A%5B%5D%2C%22explanation%22%3A%22%22%2C%22logs%22%3A%22%22%2C%22logLines%22%3A0%2C%22hasSomeResults%22%3Afalse%7D%2C%22showGrid%22%3Atrue%2C%22showChart%22%3Afalse%2C%22showLogs%22%3Atrue%2C%22progress%22%3A0%2C%22jobs%22%3A%5B%5D%2C%22isLoading%22%3Afalse%2C%22resultsKlass%22%3A%22results+impala%22%2C%22errorsKlass%22%3A%22results+impala+alert+alert-error%22%2C%22is_redacted%22%3Afalse%2C%22chartType%22%3A%22bars%22%2C%22chartSorting%22%3A%22none%22%2C%22chartScatterGroup%22%3Anull%2C%22chartScatterSize%22%3Anull%2C%22chartScope%22%3A%22world%22%2C%22chartTimelineType%22%3A%22bar%22%2C%22chartLimits%22%3A%5B5%2C10%2C25%2C50%2C100%5D%2C%22chartLimit%22%3Anull%2C%22chartX%22%3Anull%2C%22chartXPivot%22%3Anull%2C%22chartYSingle%22%3Anull%2C%22chartYMulti%22%3A%5B%5D%2C%22chartData%22%3A%5B%5D%2C%22chartMapType%22%3A%22marker%22%2C%22chartMapLabel%22%3Anull%2C%22chartMapHeat%22%3Anull%2C%22hideStacked%22%3Atrue%2C%22hasDataForChart%22%3Afalse%2C%22previousChartOptions%22%3A%7B%22chartLimit%22%3Anull%2C%22chartX%22%3Anull%2C%22chartXPivot%22%3Anull%2C%22chartYSingle%22%3Anull%2C%22chartMapType%22%3A%22marker%22%2C%22chartMapLabel%22%3Anull%2C%22chartMapHeat%22%3Anull%2C%22chartYMulti%22%3A%5B%5D%2C%22chartScope%22%3A%22world%22%2C%22chartTimelineType%22%3A%22bar%22%2C%22chartSorting%22%3A%22none%22%2C%22chartScatterGroup%22%3Anull%2C%22chartScatterSize%22%3Anull%7D%2C%22isResultSettingsVisible%22%3Afalse%2C%22settingsVisible%22%3Afalse%2C%22checkStatusTimeout%22%3Anull%2C%22topRisk%22%3Anull%2C%22suggestion%22%3A%22%22%2C%22hasSuggestion%22%3Anull%2C%22compatibilityCheckRunning%22%3Afalse%2C%22compatibilitySourcePlatform%22%3A%22impala%22%2C%22compatibilitySourcePlatforms%22%3A%5B%7B%22name%22%3A%22Teradata%22%2C%22value%22%3A%22teradata%22%7D%2C%7B%22name%22%3A%22Oracle%22%2C%22value%22%3A%22oracle%22%7D%2C%7B%22name%22%3A%22Netezza%22%2C%22value%22%3A%22netezza%22%7D%2C%7B%22name%22%3A%22Impala%22%2C%22value%22%3A%22impala%22%7D%2C%7B%22name%22%3A%22impala%22%2C%22value%22%3A%22impala%22%7D%2C%7B%22name%22%3A%22DB2%22%2C%22value%22%3A%22db2%22%7D%2C%7B%22name%22%3A%22Greenplum%22%2C%22value%22%3A%22greenplum%22%7D%2C%7B%22name%22%3A%22MySQL%22%2C%22value%22%3A%22mysql%22%7D%2C%7B%22name%22%3A%22PostgreSQL%22%2C%22value%22%3A%22postgresql%22%7D%2C%7B%22name%22%3A%22Informix%22%2C%22value%22%3A%22informix%22%7D%2C%7B%22name%22%3A%22SQL+Server%22%2C%22value%22%3A%22sqlserver%22%7D%2C%7B%22name%22%3A%22Sybase%22%2C%22value%22%3A%22sybase%22%7D%2C%7B%22name%22%3A%22Access%22%2C%22value%22%3A%22access%22%7D%2C%7B%22name%22%3A%22Firebird%22%2C%22value%22%3A%22firebird%22%7D%2C%7B%22name%22%3A%22ANSISQL%22%2C%22value%22%3A%22ansisql%22%7D%2C%7B%22name%22%3A%22Generic%22%2C%22value%22%3A%22generic%22%7D%5D%2C%22compatibilityTargetPlatform%22%3A%22impala%22%2C%22compatibilityTargetPlatforms%22%3A%5B%7B%22name%22%3A%22Impala%22%2C%22value%22%3A%22impala%22%7D%2C%7B%22name%22%3A%22impala%22%2C%22value%22%3A%22impala%22%7D%5D%2C%22showOptimizer%22%3Atrue%2C%22delayedStatement%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22wasBatchExecuted%22%3Afalse%2C%22isReady%22%3Atrue%2C%22lastExecuted%22%3A1528820101947%2C%22lastAceSelectionRowOffset%22%3A0%2C%22executingBlockingOperation%22%3Anull%2C%22showLongOperationWarning%22%3Afalse%2C%22formatEnabled%22%3Atrue%2C%22isFetchingData%22%3Afalse%2C%22isCanceling%22%3Afalse%2C%22aceAutoExpand%22%3Afalse%7D%5D%2C%22selectedSnippet%22%3A%22impala%22%2C%22creatingSessionLocks%22%3A%5B%5D%2C%22sessions%22%3A%5B%7B%22type%22%3A%22impala%22%2C%22properties%22%3A%5B%7B%22multiple%22%3Atrue%2C%22defaultValue%22%3A%5B%5D%2C%22value%22%3A%5B%5D%2C%22nice_name%22%3A%22Files%22%2C%22key%22%3A%22files%22%2C%22help_text%22%3A%22Add+one+or+more+files%2C+jars%2C+or+arcimpalas+to+the+list+of+resources.%22%2C%22type%22%3A%22hdfs-files%22%7D%2C%7B%22multiple%22%3Atrue%2C%22defaultValue%22%3A%5B%5D%2C%22value%22%3A%5B%5D%2C%22nice_name%22%3A%22Functions%22%2C%22key%22%3A%22functions%22%2C%22help_text%22%3A%22Add+one+or+more+registered+UDFs+(requires+function+name+and+fully-qualified+class+name).%22%2C%22type%22%3A%22functions%22%7D%2C%7B%22nice_name%22%3A%22Settings%22%2C%22multiple%22%3Atrue%2C%22key%22%3A%22settings%22%2C%22help_text%22%3A%22impala+and+Hadoop+configuration+properties.%22%2C%22defaultValue%22%3A%5B%5D%2C%22type%22%3A%22settings%22%2C%22options%22%3A%5B%22impala.map.aggr%22%2C%22impala.exec.compress.output%22%2C%22impala.exec.parallel%22%2C%22impala.execution.engine%22%2C%22mapreduce.job.queuename%22%5D%2C%22value%22%3A%5B%5D%7D%5D%2C%22reuse_session%22%3Atrue%2C%22id%22%3A6865%2C%22session_id%22%3A%22714fb09b96ba3368%3A4d02ec93d7ffbfb6%22%7D%5D%2C%22directoryUuid%22%3A%22%22%2C%22dependentsCoordinator%22%3A%5B%5D%2C%22historyFilter%22%3A%22%22%2C%22historyFilterVisible%22%3Afalse%2C%22loadingHistory%22%3Afalse%2C%22historyInitialHeight%22%3A1679%2C%22forceHistoryInitialHeight%22%3Atrue%2C%22historyCurrentPage%22%3A1%2C%22historyTotalPages%22%3A3%2C%22schedulerViewModel%22%3Anull%2C%22schedulerViewModelIsLoaded%22%3Afalse%2C%22isBatchable%22%3Atrue%2C%22isExecutingAll%22%3Afalse%2C%22executingAllIndex%22%3A0%2C%22retryModalConfirm%22%3Anull%2C%22retryModalCancel%22%3Anull%2C%22unloaded%22%3Afalse%2C%22updateHistoryFailed%22%3Afalse%2C%22viewSchedulerId%22%3A%22%22%2C%22loadingScheduler%22%3Afalse%7D&snippet=%7B%22id%22%3A%22dd5755a3-e8db-82d9-4f98-9f4fb5a99a06%22%2C%22type%22%3A%22impala%22%2C%22status%22%3A%22running%22%2C%22statementType%22%3A%22text%22%2C%22statement%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22aceCursorPosition%22%3A%7B%22column%22%3A33%2C%22row%22%3A0%7D%2C%22statementPath%22%3A%22%22%2C%22associatedDocumentUuid%22%3Anull%2C%22properties%22%3A%7B%22files%22%3A%5B%5D%2C%22functions%22%3A%5B%5D%2C%22arguments%22%3A%5B%5D%2C%22settings%22%3A%5B%5D%7D%2C%22result%22%3A%7B%22id%22%3A%2206840534-9434-33b5-5eca-2cd08432ceb3%22%2C%22type%22%3A%22table%22%2C%22handle%22%3A%7B%22has_more_statements%22%3Afalse%2C%22statement_id%22%3A0%2C%22statements_count%22%3A1%2C%22previous_statement_hash%22%3A%22acb6478fcf28c31b5e76d49de7d77bbe46fe5e4f9436c16c0ca8ed5f%22%7D%7D%2C%22database%22%3A%22default%22%2C%22compute%22%3A%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22default-romain%22%2C%22id%22%3A%22default-romain%22%2C%22name%22%3A%22default-romain%22%7D%2C%22wasBatchExecuted%22%3Afalse%7D",
"params": [
{
"name": "notebook",
"value": "%7B%22uuid%22%3A%22f2b8a233-c34c-44b8-a8a1-0e6123996216%22%2C%22name%22%3A%22%22%2C%22description%22%3A%22%22%2C%22type%22%3A%22query-impala%22%2C%22initialType%22%3A%22impala%22%2C%22coordinatorUuid%22%3Anull%2C%22isHistory%22%3Atrue%2C%22isManaged%22%3Afalse%2C%22parentSavedQueryUuid%22%3Anull%2C%22isSaved%22%3Afalse%2C%22onSuccessUrl%22%3Anull%2C%22pubSubUrl%22%3Anull%2C%22isPresentationModeDefault%22%3Afalse%2C%22isPresentationMode%22%3Afalse%2C%22isPresentationModeInitialized%22%3Atrue%2C%22presentationSnippets%22%3A%7B%7D%2C%22isHidingCode%22%3Afalse%2C%22snippets%22%3A%5B%7B%22id%22%3A%22dd5755a3-e8db-82d9-4f98-9f4fb5a99a06%22%2C%22name%22%3A%22%22%2C%22type%22%3A%22impala%22%2C%22isBatchable%22%3Atrue%2C%22aceCursorPosition%22%3A%7B%22column%22%3A33%2C%22row%22%3A0%7D%2C%22errors%22%3A%5B%5D%2C%22aceErrorsHolder%22%3A%5B%5D%2C%22aceWarningsHolder%22%3A%5B%5D%2C%22aceErrors%22%3A%5B%5D%2C%22aceWarnings%22%3A%5B%5D%2C%22editorMode%22%3Atrue%2C%22dbSelectionVisible%22%3Afalse%2C%22isSqlDialect%22%3Atrue%2C%22namespaceRefreshEnabled%22%3Afalse%2C%22availableNamespaces%22%3A%5B%5D%2C%22availableComputes%22%3A%5B%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22default-romain%22%2C%22id%22%3A%22default-romain%22%2C%22name%22%3A%22default-romain%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22compute1%22%2C%22id%22%3A%22compute1%22%2C%22name%22%3A%22compute1%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22compute2%22%2C%22id%22%3A%22compute2%22%2C%22name%22%3A%22compute2%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22altus%22%2C%22namespace%22%3A%22Altus%22%2C%22id%22%3A%22Altus%22%2C%22name%22%3A%22Altus%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22storage1%22%2C%22id%22%3A%22storage1%22%2C%22name%22%3A%22storage1%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22storage2%22%2C%22id%22%3A%22storage2%22%2C%22name%22%3A%22storage2%22%7D%2C%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22Default%22%2C%22id%22%3A%22Default%22%2C%22name%22%3A%22default%22%7D%5D%2C%22compute%22%3A%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22default-romain%22%2C%22id%22%3A%22default-romain%22%2C%22name%22%3A%22default-romain%22%7D%2C%22database%22%3A%22default%22%2C%22currentQueryTab%22%3A%22queryHistory%22%2C%22pinnedContextTabs%22%3A%5B%5D%2C%22loadingQueries%22%3Afalse%2C%22queriesHasErrors%22%3Afalse%2C%22queriesCurrentPage%22%3A1%2C%22queriesTotalPages%22%3A1%2C%22queriesFilter%22%3A%22%22%2C%22queriesFilterVisible%22%3Afalse%2C%22statementType%22%3A%22text%22%2C%22statementTypes%22%3A%5B%22text%22%2C%22file%22%5D%2C%22statementPath%22%3A%22%22%2C%22externalStatementLoaded%22%3Afalse%2C%22associatedDocumentLoading%22%3Atrue%2C%22associatedDocumentUuid%22%3Anull%2C%22statement_raw%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22statementsList%22%3A%5B%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%5D%2C%22aceSize%22%3A100%2C%22status%22%3A%22running%22%2C%22statusForButtons%22%3A%22executing%22%2C%22properties%22%3A%7B%22files%22%3A%5B%5D%2C%22functions%22%3A%5B%5D%2C%22arguments%22%3A%5B%5D%2C%22settings%22%3A%5B%5D%7D%2C%22viewSettings%22%3A%7B%22placeHolder%22%3A%22Example%3A+SELECT+*+FROM+tablename%2C+or+press+CTRL+%2B+space%22%2C%22sqlDialect%22%3Atrue%7D%2C%22variables%22%3A%5B%5D%2C%22hasCurlyBracketParameters%22%3Atrue%2C%22variableNames%22%3A%5B%5D%2C%22variableValues%22%3A%7B%7D%2C%22statement%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22result%22%3A%7B%22id%22%3A%2206840534-9434-33b5-5eca-2cd08432ceb3%22%2C%22type%22%3A%22table%22%2C%22hasResultset%22%3Atrue%2C%22handle%22%3A%7B%22has_more_statements%22%3Afalse%2C%22statement_id%22%3A0%2C%22statements_count%22%3A1%2C%22previous_statement_hash%22%3A%22acb6478fcf28c31b5e76d49de7d77bbe46fe5e4f9436c16c0ca8ed5f%22%7D%2C%22meta%22%3A%5B%5D%2C%22rows%22%3Anull%2C%22hasMore%22%3Afalse%2C%22statement_id%22%3A0%2C%22statement_range%22%3A%7B%22start%22%3A%7B%22row%22%3A0%2C%22column%22%3A0%7D%2C%22end%22%3A%7B%22row%22%3A0%2C%22column%22%3A0%7D%7D%2C%22statements_count%22%3A1%2C%22previous_statement_hash%22%3Anull%2C%22metaFilter%22%3A%7B%22query%22%3A%22%22%2C%22facets%22%3A%7B%7D%2C%22text%22%3A%5B%5D%7D%2C%22isMetaFilterVisible%22%3Afalse%2C%22filteredMetaChecked%22%3Atrue%2C%22filteredMeta%22%3A%5B%5D%2C%22fetchedOnce%22%3Afalse%2C%22startTime%22%3A%222018-06-12T16%3A15%3A01.951Z%22%2C%22endTime%22%3A%222018-06-12T16%3A15%3A01.951Z%22%2C%22executionTime%22%3A0%2C%22data%22%3A%5B%5D%2C%22explanation%22%3A%22%22%2C%22logs%22%3A%22%22%2C%22logLines%22%3A0%2C%22hasSomeResults%22%3Afalse%7D%2C%22showGrid%22%3Atrue%2C%22showChart%22%3Afalse%2C%22showLogs%22%3Atrue%2C%22progress%22%3A0%2C%22jobs%22%3A%5B%5D%2C%22isLoading%22%3Afalse%2C%22resultsKlass%22%3A%22results+impala%22%2C%22errorsKlass%22%3A%22results+impala+alert+alert-error%22%2C%22is_redacted%22%3Afalse%2C%22chartType%22%3A%22bars%22%2C%22chartSorting%22%3A%22none%22%2C%22chartScatterGroup%22%3Anull%2C%22chartScatterSize%22%3Anull%2C%22chartScope%22%3A%22world%22%2C%22chartTimelineType%22%3A%22bar%22%2C%22chartLimits%22%3A%5B5%2C10%2C25%2C50%2C100%5D%2C%22chartLimit%22%3Anull%2C%22chartX%22%3Anull%2C%22chartXPivot%22%3Anull%2C%22chartYSingle%22%3Anull%2C%22chartYMulti%22%3A%5B%5D%2C%22chartData%22%3A%5B%5D%2C%22chartMapType%22%3A%22marker%22%2C%22chartMapLabel%22%3Anull%2C%22chartMapHeat%22%3Anull%2C%22hideStacked%22%3Atrue%2C%22hasDataForChart%22%3Afalse%2C%22previousChartOptions%22%3A%7B%22chartLimit%22%3Anull%2C%22chartX%22%3Anull%2C%22chartXPivot%22%3Anull%2C%22chartYSingle%22%3Anull%2C%22chartMapType%22%3A%22marker%22%2C%22chartMapLabel%22%3Anull%2C%22chartMapHeat%22%3Anull%2C%22chartYMulti%22%3A%5B%5D%2C%22chartScope%22%3A%22world%22%2C%22chartTimelineType%22%3A%22bar%22%2C%22chartSorting%22%3A%22none%22%2C%22chartScatterGroup%22%3Anull%2C%22chartScatterSize%22%3Anull%7D%2C%22isResultSettingsVisible%22%3Afalse%2C%22settingsVisible%22%3Afalse%2C%22checkStatusTimeout%22%3Anull%2C%22topRisk%22%3Anull%2C%22suggestion%22%3A%22%22%2C%22hasSuggestion%22%3Anull%2C%22compatibilityCheckRunning%22%3Afalse%2C%22compatibilitySourcePlatform%22%3A%22impala%22%2C%22compatibilitySourcePlatforms%22%3A%5B%7B%22name%22%3A%22Teradata%22%2C%22value%22%3A%22teradata%22%7D%2C%7B%22name%22%3A%22Oracle%22%2C%22value%22%3A%22oracle%22%7D%2C%7B%22name%22%3A%22Netezza%22%2C%22value%22%3A%22netezza%22%7D%2C%7B%22name%22%3A%22Impala%22%2C%22value%22%3A%22impala%22%7D%2C%7B%22name%22%3A%22impala%22%2C%22value%22%3A%22impala%22%7D%2C%7B%22name%22%3A%22DB2%22%2C%22value%22%3A%22db2%22%7D%2C%7B%22name%22%3A%22Greenplum%22%2C%22value%22%3A%22greenplum%22%7D%2C%7B%22name%22%3A%22MySQL%22%2C%22value%22%3A%22mysql%22%7D%2C%7B%22name%22%3A%22PostgreSQL%22%2C%22value%22%3A%22postgresql%22%7D%2C%7B%22name%22%3A%22Informix%22%2C%22value%22%3A%22informix%22%7D%2C%7B%22name%22%3A%22SQL+Server%22%2C%22value%22%3A%22sqlserver%22%7D%2C%7B%22name%22%3A%22Sybase%22%2C%22value%22%3A%22sybase%22%7D%2C%7B%22name%22%3A%22Access%22%2C%22value%22%3A%22access%22%7D%2C%7B%22name%22%3A%22Firebird%22%2C%22value%22%3A%22firebird%22%7D%2C%7B%22name%22%3A%22ANSISQL%22%2C%22value%22%3A%22ansisql%22%7D%2C%7B%22name%22%3A%22Generic%22%2C%22value%22%3A%22generic%22%7D%5D%2C%22compatibilityTargetPlatform%22%3A%22impala%22%2C%22compatibilityTargetPlatforms%22%3A%5B%7B%22name%22%3A%22Impala%22%2C%22value%22%3A%22impala%22%7D%2C%7B%22name%22%3A%22impala%22%2C%22value%22%3A%22impala%22%7D%5D%2C%22showOptimizer%22%3Atrue%2C%22delayedStatement%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22wasBatchExecuted%22%3Afalse%2C%22isReady%22%3Atrue%2C%22lastExecuted%22%3A1528820101947%2C%22lastAceSelectionRowOffset%22%3A0%2C%22executingBlockingOperation%22%3Anull%2C%22showLongOperationWarning%22%3Afalse%2C%22formatEnabled%22%3Atrue%2C%22isFetchingData%22%3Afalse%2C%22isCanceling%22%3Afalse%2C%22aceAutoExpand%22%3Afalse%7D%5D%2C%22selectedSnippet%22%3A%22impala%22%2C%22creatingSessionLocks%22%3A%5B%5D%2C%22sessions%22%3A%5B%7B%22type%22%3A%22impala%22%2C%22properties%22%3A%5B%7B%22multiple%22%3Atrue%2C%22defaultValue%22%3A%5B%5D%2C%22value%22%3A%5B%5D%2C%22nice_name%22%3A%22Files%22%2C%22key%22%3A%22files%22%2C%22help_text%22%3A%22Add+one+or+more+files%2C+jars%2C+or+arcimpalas+to+the+list+of+resources.%22%2C%22type%22%3A%22hdfs-files%22%7D%2C%7B%22multiple%22%3Atrue%2C%22defaultValue%22%3A%5B%5D%2C%22value%22%3A%5B%5D%2C%22nice_name%22%3A%22Functions%22%2C%22key%22%3A%22functions%22%2C%22help_text%22%3A%22Add+one+or+more+registered+UDFs+(requires+function+name+and+fully-qualified+class+name).%22%2C%22type%22%3A%22functions%22%7D%2C%7B%22nice_name%22%3A%22Settings%22%2C%22multiple%22%3Atrue%2C%22key%22%3A%22settings%22%2C%22help_text%22%3A%22impala+and+Hadoop+configuration+properties.%22%2C%22defaultValue%22%3A%5B%5D%2C%22type%22%3A%22settings%22%2C%22options%22%3A%5B%22impala.map.aggr%22%2C%22impala.exec.compress.output%22%2C%22impala.exec.parallel%22%2C%22impala.execution.engine%22%2C%22mapreduce.job.queuename%22%5D%2C%22value%22%3A%5B%5D%7D%5D%2C%22reuse_session%22%3Atrue%2C%22id%22%3A6865%2C%22session_id%22%3A%22714fb09b96ba3368%3A4d02ec93d7ffbfb6%22%7D%5D%2C%22directoryUuid%22%3A%22%22%2C%22dependentsCoordinator%22%3A%5B%5D%2C%22historyFilter%22%3A%22%22%2C%22historyFilterVisible%22%3Afalse%2C%22loadingHistory%22%3Afalse%2C%22historyInitialHeight%22%3A1679%2C%22forceHistoryInitialHeight%22%3Atrue%2C%22historyCurrentPage%22%3A1%2C%22historyTotalPages%22%3A3%2C%22schedulerViewModel%22%3Anull%2C%22schedulerViewModelIsLoaded%22%3Afalse%2C%22isBatchable%22%3Atrue%2C%22isExecutingAll%22%3Afalse%2C%22executingAllIndex%22%3A0%2C%22retryModalConfirm%22%3Anull%2C%22retryModalCancel%22%3Anull%2C%22unloaded%22%3Afalse%2C%22updateHistoryFailed%22%3Afalse%2C%22viewSchedulerId%22%3A%22%22%2C%22loadingScheduler%22%3Afalse%7D"
},
{
"name": "snippet",
"value": "%7B%22id%22%3A%22dd5755a3-e8db-82d9-4f98-9f4fb5a99a06%22%2C%22type%22%3A%22impala%22%2C%22status%22%3A%22running%22%2C%22statementType%22%3A%22text%22%2C%22statement%22%3A%22SELECT+*+FROM+web_logs+LIMIT+100%3B%22%2C%22aceCursorPosition%22%3A%7B%22column%22%3A33%2C%22row%22%3A0%7D%2C%22statementPath%22%3A%22%22%2C%22associatedDocumentUuid%22%3Anull%2C%22properties%22%3A%7B%22files%22%3A%5B%5D%2C%22functions%22%3A%5B%5D%2C%22arguments%22%3A%5B%5D%2C%22settings%22%3A%5B%5D%7D%2C%22result%22%3A%7B%22id%22%3A%2206840534-9434-33b5-5eca-2cd08432ceb3%22%2C%22type%22%3A%22table%22%2C%22handle%22%3A%7B%22has_more_statements%22%3Afalse%2C%22statement_id%22%3A0%2C%22statements_count%22%3A1%2C%22previous_statement_hash%22%3A%22acb6478fcf28c31b5e76d49de7d77bbe46fe5e4f9436c16c0ca8ed5f%22%7D%7D%2C%22database%22%3A%22default%22%2C%22compute%22%3A%7B%22interface%22%3A%22impala%22%2C%22type%22%3A%22direct%22%2C%22namespace%22%3A%22default-romain%22%2C%22id%22%3A%22default-romain%22%2C%22name%22%3A%22default-romain%22%7D%2C%22wasBatchExecuted%22%3Afalse%7D"
}
]
}
}'''
payload = payload.replace('SELECT+*+FROM+web_logs+LIMIT+100', urllib_quote_plus(query.replace('\n', ' ')))
resp = self.api.submit_hue_query(self.cluster_crn, payload)
if 'payload' in resp:
resp_payload = json.loads(resp['payload'])
if 'handle' in resp_payload:
return resp_payload['handle']
else:
raise QueryError(resp_payload.get('message'))
else:
raise QueryError(resp.get('message'))
def do_check_status(self, handle):
notebook = {"type":"impala", "name": "query", "isSaved": False, "sessions": [], "snippets": [{"id": "1234", "type":"impala","statement_raw": "SHOW DATABASES", "result": {"handle": {} }}]}
snippet = {"id": "1234", "type": "impala", "statement":"SHOW DATABASES", "status": "running", "result": {'handle': {"log_context":None,"statements_count":1,"end":{"column":13,"row":0},"statement_id":0,"has_more_statements":False,"start":{"column":0,"row":0},"secret":"3h9WBnLbTUYAAAAAPQjxlQ==\n","has_result_set":True,"session_guid":"qcrpEBmCTGacxfhM+CxbkQ==\n","statement":"SHOW DATABASES","operation_type":0,"modified_row_count":None,"guid":"3h9WBnLbTUYAAAAAPQjxlQ==\n","previous_statement_hash":"5b1f14102d749be7b41da376bcdbb64f993ce00bc46e3aab0b8008c4"}}, "properties": {}}
snippet['result']['handle'] = handle
notebook_payload = urllib_quote(json.dumps(notebook))
snippet_payload = urllib_quote(json.dumps(snippet))
payload = '''
{
"method": "POST",
"url": "http://127.0.0.1:8000/notebook/api/check_status",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Accept-Encoding",
"value": "gzip, deflate, br"
},
{
"name": "Content-Type",
"value": "application/x-www-form-urlencoded; charset=UTF-8"
},
{
"name": "Accept",
"value": "*/*"
},
{
"name": "X-Requested-With",
"value": "XMLHttpRequest"
},
{
"name": "Connection",
"value": "keep-alive"
}
],
"queryString": [],
"cookies": [
],
"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=UTF-8",
"text": "notebook=%(notebook)s&snippet=%(snippet)s",
"params": [
{
"name": "notebook",
"value": "%(notebook)s"
},
{
"name": "snippet",
"value": "%(snippet)s"
}
]
}
}''' % {'notebook': notebook_payload, 'snippet': snippet_payload}
resp = self.api.submit_hue_query(self.cluster_crn, payload)
resp_payload = json.loads(resp['payload'])
if 'query_status' in resp_payload:
return resp_payload['query_status']
else:
return resp_payload
def do_fetch_result(self, handle):
notebook = {"type":"impala", "name": "query", "isSaved": False, "sessions": [], "snippets": [{"id": "1234", "type":"impala","statement_raw": "SHOW DATABASES", "result": {"handle": {} }}]}
snippet = {"id": "1234", "type": "impala", "statement":"SHOW DATABASES", "status": "running", "result": {'handle': {"log_context":None,"statements_count":1,"end":{"column":13,"row":0},"statement_id":0,"has_more_statements":False,"start":{"column":0,"row":0},"secret":"3h9WBnLbTUYAAAAAPQjxlQ==\n","has_result_set":True,"session_guid":"qcrpEBmCTGacxfhM+CxbkQ==\n","statement":"SHOW DATABASES","operation_type":0,"modified_row_count":None,"guid":"3h9WBnLbTUYAAAAAPQjxlQ==\n","previous_statement_hash":"5b1f14102d749be7b41da376bcdbb64f993ce00bc46e3aab0b8008c4"}}, "properties": {}}
rows = 100
start_over = True
snippet['result']['handle'] = handle
notebook_payload = urllib_quote(json.dumps(notebook))
snippet_payload = urllib_quote(json.dumps(snippet))
rows_payload = urllib_quote(json.dumps(rows))
start_over_payload = urllib_quote(json.dumps(start_over))
payload = '''
{
"method": "POST",
"url": "http://127.0.0.1:8000/notebook/api/fetch_result_data",
"httpVersion": "HTTP/1.1",
"headers": [
{
"name": "Accept-Encoding",
"value": "gzip, deflate, br"
},
{
"name": "Content-Type",
"value": "application/x-www-form-urlencoded; charset=UTF-8"
},
{
"name": "Accept",
"value": "*/*"
},
{
"name": "X-Requested-With",
"value": "XMLHttpRequest"
},
{
"name": "Connection",
"value": "keep-alive"
}
],
"queryString": [],
"cookies": [
],
"postData": {
"mimeType": "application/x-www-form-urlencoded; charset=UTF-8",
"text": "notebook=%(notebook)s&snippet=%(snippet)s&rows=%(rows)s&startOver=%(start_over)s",
"params": [
{
"name": "notebook",
"value": "%(notebook)s"
},
{
"name": "snippet",
"value": "%(snippet)s"
},
{
"name": "rows",
"value": %(rows)s
},
{
"name": "startOver",
"value": "%(start_over)s"
}
]
}
}''' % {'notebook': notebook_payload, 'snippet': snippet_payload, 'rows': rows_payload, 'start_over': start_over_payload}
resp = self.api.submit_hue_query(self.cluster_crn, payload)
return json.loads(resp['payload'])['result']
| 107.603175 | 11,123 | 0.726508 | 5,110 | 33,895 | 4.775734 | 0.105675 | 0.070152 | 0.020652 | 0.021636 | 0.904975 | 0.899893 | 0.894812 | 0.888748 | 0.888748 | 0.88465 | 0 | 0.211274 | 0.10503 | 33,895 | 314 | 11,124 | 107.94586 | 0.593209 | 0.022393 | 0 | 0.4 | 0 | 0.040816 | 0.866606 | 0.705857 | 0 | 0 | 0 | 0 | 0 | 1 | 0.057143 | false | 0 | 0.04898 | 0.016327 | 0.167347 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 11 |
530df538c0c1c4743e6db37a84224c891d7c3080 | 12,909 | py | Python | exabel_data_sdk/stubs/exabel/api/data/v1/time_series_service_pb2_grpc.py | aksestok/python-sdk | 520a3d9822ffa9a023262b379ea3b3d19cb10853 | [
"MIT"
] | 1 | 2021-12-22T11:23:57.000Z | 2021-12-22T11:23:57.000Z | exabel_data_sdk/stubs/exabel/api/data/v1/time_series_service_pb2_grpc.py | aksestok/python-sdk | 520a3d9822ffa9a023262b379ea3b3d19cb10853 | [
"MIT"
] | 18 | 2021-01-13T16:24:38.000Z | 2022-03-15T13:32:29.000Z | exabel_data_sdk/stubs/exabel/api/data/v1/time_series_service_pb2_grpc.py | aksestok/python-sdk | 520a3d9822ffa9a023262b379ea3b3d19cb10853 | [
"MIT"
] | 10 | 2021-01-11T13:24:51.000Z | 2021-12-17T20:53:06.000Z | # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from exabel_data_sdk.stubs.exabel.api.data.v1 import time_series_messages_pb2 as exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2
from exabel_data_sdk.stubs.exabel.api.data.v1 import time_series_service_pb2 as exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
class TimeSeriesServiceStub(object):
"""Manages time series in the Data API.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.ListTimeSeries = channel.unary_unary(
'/exabel.api.data.v1.TimeSeriesService/ListTimeSeries',
request_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.ListTimeSeriesRequest.SerializeToString,
response_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.ListTimeSeriesResponse.FromString,
)
self.GetTimeSeries = channel.unary_unary(
'/exabel.api.data.v1.TimeSeriesService/GetTimeSeries',
request_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.GetTimeSeriesRequest.SerializeToString,
response_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.FromString,
)
self.CreateTimeSeries = channel.unary_unary(
'/exabel.api.data.v1.TimeSeriesService/CreateTimeSeries',
request_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.CreateTimeSeriesRequest.SerializeToString,
response_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.FromString,
)
self.UpdateTimeSeries = channel.unary_unary(
'/exabel.api.data.v1.TimeSeriesService/UpdateTimeSeries',
request_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.UpdateTimeSeriesRequest.SerializeToString,
response_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.FromString,
)
self.DeleteTimeSeries = channel.unary_unary(
'/exabel.api.data.v1.TimeSeriesService/DeleteTimeSeries',
request_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.DeleteTimeSeriesRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.BatchDeleteTimeSeriesPoints = channel.unary_unary(
'/exabel.api.data.v1.TimeSeriesService/BatchDeleteTimeSeriesPoints',
request_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.BatchDeleteTimeSeriesPointsRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
class TimeSeriesServiceServicer(object):
"""Manages time series in the Data API.
"""
def ListTimeSeries(self, request, context):
"""Lists all time series for one entity or for one signal. Only the names are returned.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def GetTimeSeries(self, request, context):
"""Gets one time series. The known_time (of present) must be formatted
according to RFC3339, as specified by
https://developers.google.com/protocol-buffers/docs/proto3#json.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def CreateTimeSeries(self, request, context):
"""Creates one time series and returns it.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def UpdateTimeSeries(self, request, context):
"""Updates one time series and returns it. The data in this request and the
existing data will be merged together.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def DeleteTimeSeries(self, request, context):
"""Deletes one time series. The time series and all its points will be deleted.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def BatchDeleteTimeSeriesPoints(self, request, context):
"""Deletes part(s) of one time series. The requested points will be deleted, but the time series
will not. With this request, it is possible to delete all points from a time series, but not
the time series itself.
"""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_TimeSeriesServiceServicer_to_server(servicer, server):
rpc_method_handlers = {
'ListTimeSeries': grpc.unary_unary_rpc_method_handler(
servicer.ListTimeSeries,
request_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.ListTimeSeriesRequest.FromString,
response_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.ListTimeSeriesResponse.SerializeToString,
),
'GetTimeSeries': grpc.unary_unary_rpc_method_handler(
servicer.GetTimeSeries,
request_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.GetTimeSeriesRequest.FromString,
response_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.SerializeToString,
),
'CreateTimeSeries': grpc.unary_unary_rpc_method_handler(
servicer.CreateTimeSeries,
request_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.CreateTimeSeriesRequest.FromString,
response_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.SerializeToString,
),
'UpdateTimeSeries': grpc.unary_unary_rpc_method_handler(
servicer.UpdateTimeSeries,
request_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.UpdateTimeSeriesRequest.FromString,
response_serializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.SerializeToString,
),
'DeleteTimeSeries': grpc.unary_unary_rpc_method_handler(
servicer.DeleteTimeSeries,
request_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.DeleteTimeSeriesRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'BatchDeleteTimeSeriesPoints': grpc.unary_unary_rpc_method_handler(
servicer.BatchDeleteTimeSeriesPoints,
request_deserializer=exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.BatchDeleteTimeSeriesPointsRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'exabel.api.data.v1.TimeSeriesService', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class TimeSeriesService(object):
"""Manages time series in the Data API.
"""
@staticmethod
def ListTimeSeries(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/exabel.api.data.v1.TimeSeriesService/ListTimeSeries',
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.ListTimeSeriesRequest.SerializeToString,
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.ListTimeSeriesResponse.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def GetTimeSeries(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/exabel.api.data.v1.TimeSeriesService/GetTimeSeries',
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.GetTimeSeriesRequest.SerializeToString,
exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def CreateTimeSeries(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/exabel.api.data.v1.TimeSeriesService/CreateTimeSeries',
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.CreateTimeSeriesRequest.SerializeToString,
exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def UpdateTimeSeries(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/exabel.api.data.v1.TimeSeriesService/UpdateTimeSeries',
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.UpdateTimeSeriesRequest.SerializeToString,
exabel_dot_api_dot_data_dot_v1_dot_time__series__messages__pb2.TimeSeries.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def DeleteTimeSeries(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/exabel.api.data.v1.TimeSeriesService/DeleteTimeSeries',
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.DeleteTimeSeriesRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def BatchDeleteTimeSeriesPoints(request,
target,
options=(),
channel_credentials=None,
call_credentials=None,
insecure=False,
compression=None,
wait_for_ready=None,
timeout=None,
metadata=None):
return grpc.experimental.unary_unary(request, target, '/exabel.api.data.v1.TimeSeriesService/BatchDeleteTimeSeriesPoints',
exabel_dot_api_dot_data_dot_v1_dot_time__series__service__pb2.BatchDeleteTimeSeriesPointsRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| 52.052419 | 150 | 0.710357 | 1,354 | 12,909 | 6.299114 | 0.113737 | 0.055106 | 0.045023 | 0.056279 | 0.804197 | 0.800446 | 0.767382 | 0.74065 | 0.702075 | 0.693165 | 0 | 0.009405 | 0.225734 | 12,909 | 247 | 151 | 52.263158 | 0.843922 | 0.083585 | 0 | 0.572165 | 1 | 0 | 0.091944 | 0.061895 | 0 | 0 | 0 | 0 | 0 | 1 | 0.072165 | false | 0 | 0.020619 | 0.030928 | 0.139175 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
5342b982471e22a071b8d2031c852a27ec290780 | 33,173 | py | Python | vimms/BOMAS.py | hechth/vimms | ce5922578cf225d46cb285da8e7af97b5321f5aa | [
"MIT"
] | 11 | 2019-07-11T09:19:18.000Z | 2021-03-07T08:44:36.000Z | vimms/BOMAS.py | hechth/vimms | ce5922578cf225d46cb285da8e7af97b5321f5aa | [
"MIT"
] | 159 | 2019-12-11T14:41:40.000Z | 2021-03-31T19:47:08.000Z | vimms/BOMAS.py | hechth/vimms | ce5922578cf225d46cb285da8e7af97b5321f5aa | [
"MIT"
] | 4 | 2019-10-09T18:42:49.000Z | 2020-07-10T14:21:59.000Z | import time
from mass_spec_utils.data_import.mzmine import load_picked_boxes, map_boxes_to_scans
from mass_spec_utils.data_import.mzml import MZMLFile
from vimms.Agent import TopNDEWAgent
from vimms.Box import *
from vimms.Common import *
from vimms.Controller import TopN_SmartRoiController, WeightedDEWController, TopN_RoiController, \
NonOverlapController, IntensityNonOverlapController, TopNBoxRoiController, FlexibleNonOverlapController, \
FixedScansController, RoiBuilder, AgentBasedController, TopNController
from vimms.DsDA import get_schedule, dsda_get_scan_params, create_dsda_schedule
from vimms.Environment import *
from vimms.Evaluation import evaluate_multi_peak_roi_aligner
from vimms.Evaluation import evaluate_multiple_simulated_env
from vimms.GridEstimator import *
from vimms.Roi import FrequentistRoiAligner
def run_coverage_evaluation(box_file, mzml_file, half_isolation_window):
boxes = load_picked_boxes(box_file)
mz_file = MZMLFile(mzml_file)
scans2boxes, boxes2scans = map_boxes_to_scans(mz_file, boxes, half_isolation_window=half_isolation_window)
coverage = len(boxes2scans) / len(boxes)
return coverage
def run_env(mass_spec, controller, min_rt, max_rt, mzml_file):
env = Environment(mass_spec, controller, min_rt, max_rt)
env.run()
env.write_mzML(None, mzml_file)
chems = [event.chem.__repr__() for event in env.mass_spec.fragmentation_events if event.ms_level > 1]
chemical_coverage = len(np.unique(np.array(chems))) / len(env.mass_spec.chemicals)
return chemical_coverage
########################################################################################################################
# Evaluation methods
########################################################################################################################
def top_n_evaluation(param_dict):
mass_spec = load_obj(param_dict['mass_spec_file'])
params = load_obj(param_dict['params_file'])
topn = TopNController(param_dict['ionisation_mode'], param_dict['N'], param_dict['isolation_width'],
param_dict['mz_tol'], param_dict['rt_tol'], param_dict['min_ms1_intensity'], params=params)
chemical_coverage = run_env(mass_spec, topn, param_dict['min_rt'], param_dict['max_rt'],
param_dict['save_file_name'])
coverage = run_coverage_evaluation(param_dict['box_file'], param_dict['save_file_name'],
param_dict['half_isolation_window'])
print('coverage', coverage)
print('chemical_coverage', chemical_coverage)
if param_dict['coverage_type'] == 'coverage':
return coverage
else:
return chemical_coverage
def smart_roi_evaluation(param_dict):
mass_spec = load_obj(param_dict['mass_spec_file'])
params = load_obj(param_dict['params_file'])
smartroi = TopN_SmartRoiController(param_dict['ionisation_mode'], param_dict['isolation_window'],
param_dict['mz_tol'], param_dict['min_ms1_intensity'],
param_dict['min_roi_intensity'], param_dict['min_roi_length'],
param_dict['N'], param_dict['rt_tol'],
param_dict['min_roi_length_for_fragmentation'],
param_dict['reset_length_seconds'],
param_dict['iif'], length_units="scans", drop_perc=param_dict['dp'] / 100,
ms1_shift=0, params=params)
chemical_coverage = run_env(mass_spec, smartroi, param_dict['min_rt'], param_dict['max_rt'],
param_dict['save_file_name'])
coverage = run_coverage_evaluation(param_dict['box_file'], param_dict['save_file_name'],
param_dict['half_isolation_window'])
print('coverage', coverage)
print('chemical_coverage', chemical_coverage)
if param_dict['coverage_type'] == 'coverage':
return coverage
else:
return chemical_coverage
def smart_roi_evaluation(param_dict):
mass_spec = load_obj(param_dict['mass_spec_file'])
params = load_obj(param_dict['params_file'])
smart_roi = TopN_SmartRoiController(param_dict['ionisation_mode'], param_dict['isolation_width'],
param_dict['mz_tol'], param_dict['min_ms1_intensity'],
param_dict['min_roi_intensity'], param_dict['min_roi_length'],
N=param_dict['N'], rt_tol=param_dict['rt_tol'],
min_roi_length_for_fragmentation=param_dict['min_roi_length_for_fragmentation'],
reset_length_seconds=param_dict['reset_length_seconds'],
intensity_increase_factor=param_dict['intensity_increase_factor'],
drop_perc=param_dict['drop_perc'], ms1_shift=param_dict['ms1_shift'],
params=params)
run_env(mass_spec, smart_roi, param_dict['min_rt'], param_dict['max_rt'], param_dict['save_file_name'])
coverage = run_coverage_evaluation(param_dict['box_file'], param_dict['save_file_name'],
param_dict['half_isolation_window'])
return coverage
def weighted_dew_evaluation(param_dict):
mass_spec = load_obj(param_dict['mass_spec_file'])
params = load_obj(param_dict['params_file'])
weighted_dew = WeightedDEWController(param_dict['ionisation_mode'], param_dict['N'], param_dict['isolation_width'],
param_dict['mz_tol'], param_dict['rt_tol'], param_dict['min_ms1_intensity'],
exclusion_t_0=param_dict['exclusion_t_0'],
log_intensity=param_dict['log_intensity'], params=params)
run_env(mass_spec, weighted_dew, param_dict['min_rt'], param_dict['max_rt'], param_dict['save_file_name'])
coverage = run_coverage_evaluation(param_dict['box_file'], param_dict['save_file_name'],
param_dict['half_isolation_window'])
return coverage
########################################################################################################################
# Experiment evaluation methods
########################################################################################################################
def top_n_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol, rt_tol, min_ms1_intensity,
base_chemicals=None, mzmine_files=None, rt_tolerance=100, experiment_dir=None,
progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = TopNController(POSITIVE, N, isolation_window, mz_tol, rt_tol, min_ms1_intensity, ms1_shift=0,
initial_exclusion_list=None, force_N=False)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
def top_n_exclusion_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol, rt_tol,
min_ms1_intensity,
base_chemicals=None, mzmine_files=None, rt_tolerance=100,
experiment_dir=None, progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
agent = TopNDEWAgent(POSITIVE, N, isolation_window, mz_tol, rt_tol, min_ms1_intensity, remove_exclusion=False)
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = AgentBasedController(agent)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
def top_n_roi_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol, rt_tol,
min_ms1_intensity, min_roi_intensity, min_roi_length, base_chemicals=None,
mzmine_files=None, rt_tolerance=100, experiment_dir=None, progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = TopN_RoiController(POSITIVE, isolation_window, mz_tol, min_ms1_intensity, min_roi_intensity,
min_roi_length, N=N, rt_tol=rt_tol)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
def smart_roi_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol, rt_tol,
min_ms1_intensity, min_roi_intensity, min_roi_length,
min_roi_length_for_fragmentation, reset_length_seconds, intensity_increase_factor,
drop_perc, ms1_shift, base_chemicals=None, mzmine_files=None,
rt_tolerance=100, experiment_dir=None, progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = TopN_SmartRoiController(POSITIVE, isolation_window, mz_tol, min_ms1_intensity,
min_roi_intensity,
min_roi_length, N=N, rt_tol=rt_tol,
min_roi_length_for_fragmentation=min_roi_length_for_fragmentation,
reset_length_seconds=reset_length_seconds,
intensity_increase_factor=intensity_increase_factor,
drop_perc=drop_perc, ms1_shift=ms1_shift)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
def weighted_dew_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol, r, t0,
min_ms1_intensity, base_chemicals=None, mzmine_files=None, rt_tolerance=100,
experiment_dir=None, progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = WeightedDEWController(POSITIVE, N, isolation_window, mz_tol, r, min_ms1_intensity,
exclusion_t_0=t0, log_intensity=True)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
def box_controller_experiment_evaluation(datasets, group_list, min_rt, max_rt, N, isolation_window,
mz_tol, rt_tol, min_ms1_intensity, min_roi_intensity, min_roi_length,
boxes_params, base_chemicals=None, mzmine_files=None, rt_tolerance=100,
experiment_dir=None, progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
boxes = []
boxes_intensity = []
aligner = RoiAligner()
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = TopNBoxRoiController(POSITIVE, isolation_window, mz_tol, min_ms1_intensity, min_roi_intensity,
min_roi_length, boxes_params=boxes_params, boxes=boxes,
boxes_intensity=boxes_intensity, N=N, rt_tol=rt_tol)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
rois = env.controller.live_roi + env.controller.dead_roi
aligner.add_sample(rois, 'sample_' + str(i), group_list[i])
boxes = aligner.get_boxes()
boxes_intensity = aligner.get_max_frag_intensities()
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
# change roi_type to ROI_TYPE_SMART to toggle smartroi
# change exclusion_method to ROI_EXCLUSION_WEIGHTED_DEW and specify exclusion_t_0 to toggle weighteddew
def non_overlap_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol, rt_tol, min_ms1_intensity,
min_roi_intensity, min_roi_length, rt_box_size, mz_box_size,
min_roi_length_for_fragmentation, base_chemicals=None, mzmine_files=None,
rt_tolerance=100, experiment_dir=None,
roi_type=RoiBuilder.ROI_TYPE_NORMAL, reset_length_seconds=1e6,
intensity_increase_factor=10, drop_perc=0.1 / 100,
exclusion_method=ROI_EXCLUSION_DEW, exclusion_t_0=None, progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
grid = GridEstimator(LocatorGrid(min_rt, max_rt, rt_box_size, 0, 3000, mz_box_size), IdentityDrift())
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = NonOverlapController(
POSITIVE, isolation_window, mz_tol, min_ms1_intensity, min_roi_intensity,
min_roi_length, N, grid, rt_tol=rt_tol,
min_roi_length_for_fragmentation=min_roi_length_for_fragmentation,
roi_type=roi_type, reset_length_seconds=reset_length_seconds,
intensity_increase_factor=intensity_increase_factor, drop_perc=drop_perc,
exclusion_method=exclusion_method, exclusion_t_0=exclusion_t_0)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
# change roi_type to ROI_TYPE_SMART to toggle smartroi
# change exclusion_method to ROI_EXCLUSION_WEIGHTED_DEW and specify exclusion_t_0 to toggle weighteddew
def intensity_non_overlap_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol,
rt_tol, min_ms1_intensity, min_roi_intensity, min_roi_length,
rt_box_size, mz_box_size, min_roi_length_for_fragmentation,
scoring_params={'theta1': 1}, base_chemicals=None, mzmine_files=None,
rt_tolerance=100, experiment_dir=None,
roi_type=RoiBuilder.ROI_TYPE_NORMAL, reset_length_seconds=1e6,
intensity_increase_factor=10, drop_perc=0.1 / 100,
exclusion_method=ROI_EXCLUSION_DEW, exclusion_t_0=None,
progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
grid = GridEstimator(AllOverlapGrid(min_rt, max_rt, rt_box_size, 0, 3000, mz_box_size), IdentityDrift())
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = IntensityNonOverlapController(
POSITIVE, isolation_window, mz_tol, min_ms1_intensity, min_roi_intensity,
min_roi_length, N, grid, rt_tol=rt_tol,
min_roi_length_for_fragmentation=min_roi_length_for_fragmentation, scoring_params=scoring_params,
roi_type=roi_type, reset_length_seconds=reset_length_seconds,
intensity_increase_factor=intensity_increase_factor, drop_perc=drop_perc,
exclusion_method=exclusion_method, exclusion_t_0=exclusion_t_0)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
# change roi_type to ROI_TYPE_SMART to toggle smartroi
# change exclusion_method to ROI_EXCLUSION_WEIGHTED_DEW and specify exclusion_t_0 to toggle weighteddew
def flexible_non_overlap_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol,
rt_tol, min_ms1_intensity, min_roi_intensity, min_roi_length,
rt_box_size, mz_box_size, min_roi_length_for_fragmentation,
scoring_params=None, base_chemicals=None, mzmine_files=None,
rt_tolerance=100, experiment_dir=None,
roi_type=RoiBuilder.ROI_TYPE_NORMAL, reset_length_seconds=1e6,
intensity_increase_factor=10, drop_perc=0.1 / 100,
exclusion_method=ROI_EXCLUSION_DEW, exclusion_t_0=None,
progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
grid = GridEstimator(AllOverlapGrid(min_rt, max_rt, rt_box_size, 0, 3000, mz_box_size), IdentityDrift())
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
if scoring_params['theta3'] != 0:
register_all_roi = True
else:
register_all_roi = False
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = FlexibleNonOverlapController(
POSITIVE, isolation_window, mz_tol, min_ms1_intensity, min_roi_intensity,
min_roi_length, N, grid, rt_tol=rt_tol, register_all_roi=register_all_roi,
min_roi_length_for_fragmentation=min_roi_length_for_fragmentation, scoring_params=scoring_params,
roi_type=roi_type, reset_length_seconds=reset_length_seconds,
intensity_increase_factor=intensity_increase_factor, drop_perc=drop_perc,
exclusion_method=exclusion_method, exclusion_t_0=exclusion_t_0)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
def case_control_non_overlap_experiment_evaluation(datasets, min_rt, max_rt, N, isolation_window, mz_tol,
rt_tol, min_ms1_intensity, min_roi_intensity, min_roi_length,
rt_box_size, mz_box_size, min_roi_length_for_fragmentation,
scoring_params=None, base_chemicals=None, mzmine_files=None,
rt_tolerance=100, experiment_dir=None, box_method='mean',
roi_type=RoiBuilder.ROI_TYPE_NORMAL, reset_length_seconds=1e6,
intensity_increase_factor=10, drop_perc=0.1 / 100,
exclusion_method=ROI_EXCLUSION_DEW, exclusion_t_0=None,
progress_bar=False):
if base_chemicals is not None or mzmine_files is not None:
env_list = []
grid = CaseControlGridEstimator(AllOverlapGrid(min_rt, max_rt, rt_box_size, 0, 3000, mz_box_size),
IdentityDrift(), rt_tolerance=rt_tolerance, box_method=box_method)
mzml_files = []
source_files = ['sample_' + str(i) for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
controller = FlexibleNonOverlapController(
POSITIVE, isolation_window, mz_tol, min_ms1_intensity, min_roi_intensity,
min_roi_length, N, grid, rt_tol=rt_tol,
min_roi_length_for_fragmentation=min_roi_length_for_fragmentation, scoring_params=scoring_params,
roi_type=roi_type, reset_length_seconds=reset_length_seconds,
intensity_increase_factor=intensity_increase_factor, drop_perc=drop_perc,
exclusion_method=exclusion_method, exclusion_t_0=exclusion_t_0)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
if base_chemicals is None:
file_link = os.path.join(experiment_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
env.write_mzML(experiment_dir, source_files[i] + '.mzml')
if base_chemicals is not None:
evaluation = evaluate_multiple_simulated_env(env_list, base_chemicals=base_chemicals)
else:
roi_aligner = FrequentistRoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files, True)
return env_list, evaluation
else:
return None, None
def dsda_experiment_evaluation(datasets, base_dir, min_rt, max_rt, N, isolation_window, mz_tol, rt_tol,
min_ms1_intensity, mzmine_files=None, rt_tolerance=100, progress_bar=False):
data_dir = os.path.join(base_dir, 'Data')
schedule_dir = os.path.join(base_dir, 'settings')
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[0]) # necessary to get timings for schedule
create_dsda_schedule(mass_spec, N, min_rt, max_rt, base_dir)
print('Please open and run R script now')
time.sleep(1)
template_file = os.path.join(base_dir, 'DsDA_Timing_schedule.csv')
env_list = []
mzml_files = []
source_files = ['sample_' + "%03d" % i for i in range(len(datasets))]
for i in range(len(datasets)):
mass_spec = IndependentMassSpectrometer(POSITIVE, datasets[i])
if i == 0:
controller = TopNController(POSITIVE, N, isolation_window, mz_tol, rt_tol, min_ms1_intensity,
ms1_shift=0, initial_exclusion_list=None, force_N=False)
else:
print('Looking for next schedule')
new_schedule = get_schedule(i, schedule_dir)
print('Found next schedule')
time.sleep(1)
schedule_param_list = dsda_get_scan_params(new_schedule, template_file, isolation_window, mz_tol,
rt_tol)
controller = FixedScansController(schedule=schedule_param_list)
env = Environment(mass_spec, controller, min_rt, max_rt, progress_bar=progress_bar)
env.run()
if progress_bar is False:
print('Processed dataset ' + str(i))
env_list.append(env)
file_link = os.path.join(data_dir, source_files[i] + '.mzml')
mzml_files.append(file_link)
print("Processed ", i + 1, " files")
env.write_mzML(data_dir, source_files[i] + '.mzml')
print("Waiting for R to process .mzML files")
if mzmine_files is None:
evaluation = evaluate_multiple_simulated_env(env_list)
else:
roi_aligner = RoiAligner(rt_tolerance=rt_tolerance)
for i in range(len(mzml_files)):
roi_aligner.add_picked_peaks(mzml_files[i], mzmine_files[i], source_files[i], 'mzmine')
evaluation = evaluate_multi_peak_roi_aligner(roi_aligner, source_files)
return env_list, evaluation
else:
return None, None
| 59.556553 | 120 | 0.61951 | 3,878 | 33,173 | 4.922898 | 0.054152 | 0.0363 | 0.021371 | 0.019014 | 0.864334 | 0.847782 | 0.828977 | 0.820439 | 0.808653 | 0.798491 | 0 | 0.006944 | 0.288096 | 33,173 | 556 | 121 | 59.663669 | 0.801448 | 0.01661 | 0 | 0.730159 | 0 | 0 | 0.04967 | 0.006131 | 0 | 0 | 0 | 0 | 0 | 1 | 0.03373 | false | 0 | 0.025794 | 0 | 0.119048 | 0.039683 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
535c2a124eef205791fc4d0c07b53178ac91fe44 | 162 | py | Python | main.py | ldurazo/Invoicer | 60328c1e096d4d285ed3291af2678bd7ac184e49 | [
"Unlicense"
] | null | null | null | main.py | ldurazo/Invoicer | 60328c1e096d4d285ed3291af2678bd7ac184e49 | [
"Unlicense"
] | null | null | null | main.py | ldurazo/Invoicer | 60328c1e096d4d285ed3291af2678bd7ac184e49 | [
"Unlicense"
] | null | null | null | import invoicer.invoicer
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
invoicer.invoicer.generate_invoice()
| 20.25 | 76 | 0.808642 | 24 | 162 | 5.25 | 0.458333 | 0.142857 | 0.206349 | 0.238095 | 0.253968 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.061728 | 162 | 7 | 77 | 23.142857 | 0.828947 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.6 | 0 | 0.6 | 0 | 1 | 0 | 0 | null | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
727d1981855761d8d88259106c9d8bb3fd87ea39 | 111 | py | Python | test/test_del_contact.py | vanyushkina/python_training | 77c856e26a7affc25315eded7e3771174cdb8a20 | [
"Apache-2.0"
] | null | null | null | test/test_del_contact.py | vanyushkina/python_training | 77c856e26a7affc25315eded7e3771174cdb8a20 | [
"Apache-2.0"
] | null | null | null | test/test_del_contact.py | vanyushkina/python_training | 77c856e26a7affc25315eded7e3771174cdb8a20 | [
"Apache-2.0"
] | null | null | null | from model.contact import Contact
def test_delete_first_contact(app):
app.contact.delete_first_contact()
| 18.5 | 38 | 0.810811 | 16 | 111 | 5.3125 | 0.5625 | 0.258824 | 0.423529 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.117117 | 111 | 5 | 39 | 22.2 | 0.867347 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | false | 0 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
72a784bc221451da438703dcc98890bf07f7de61 | 7,353 | py | Python | data/transcoder_evaluation_gfg/python/LEXICOGRAPHICALLY_LARGEST_SUBSEQUENCE_EVERY_CHARACTER_OCCURS_LEAST_K_TIMES.py | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/python/LEXICOGRAPHICALLY_LARGEST_SUBSEQUENCE_EVERY_CHARACTER_OCCURS_LEAST_K_TIMES.py | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/python/LEXICOGRAPHICALLY_LARGEST_SUBSEQUENCE_EVERY_CHARACTER_OCCURS_LEAST_K_TIMES.py | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | # Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( s , t , n , k ) :
last = 0
cnt = 0
new_last = 0
size = 0
string = 'zyxwvutsrqponmlkjihgfedcba'
for ch in string :
cnt = 0
for i in range ( last , n ) :
if s [ i ] == ch :
cnt += 1
if cnt >= k :
for i in range ( last , n ) :
if s [ i ] == ch :
t [ size ] = ch
new_last = i
size += 1
last = new_last
#TOFILL
if __name__ == '__main__':
param = [
([' ', 'A', 'A', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'H', 'L', 'L', 'O', 'P', 'T', 'U', 'V', 'W', 'Z', 'a', 'b', 'f', 'f', 'h', 'h', 'i', 'j', 'q', 'y', 'y', 'z'],[' ', ' ', 'B', 'D', 'F', 'G', 'H', 'I', 'K', 'K', 'L', 'P', 'P', 'R', 'R', 'U', 'V', 'Y', 'Z', 'Z', 'e', 'g', 'h', 'j', 'l', 'o', 'p', 'q', 'r', 't', 'v', 'y', 'z'],25,21,),
(['8', '7', '8', '1', '3', '8', '8', '1', '7', '0', '6', '8', '8', '7', '3', '1', '0', '9', '6', '1', '9', '2', '6', '6', '3', '1', '9', '7', '5', '5', '0', '0', '0', '7', '6', '4', '9', '7', '3', '0', '7', '0', '8'],['0', '2', '1', '1', '8', '9', '6', '0', '1', '7', '0', '2', '1', '8', '7', '9', '9', '8', '0', '2', '7', '9', '1', '6', '8', '1', '3', '4', '7', '8', '0', '2', '4', '2', '6', '9', '1', '1', '4', '2', '4', '7', '4'],22,22,),
(['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],30,34,),
(['x', 'H', 'h', 'z', 'X', 'S', 'f', 'h'],['H', 'f', 'Q', 'b', 'H', 'X', 'l', 'u'],4,7,),
(['0', '1', '1', '2', '3', '3', '4', '4', '4', '5', '5', '6', '7', '7', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9'],['0', '0', '0', '1', '2', '2', '2', '2', '3', '3', '4', '6', '6', '6', '6', '7', '7', '8', '8', '8', '9', '9', '9', '9', '9'],20,13,),
(['1', '1', '0', '0', '0', '1', '0', '0', '0', '1', '1', '0', '1'],['0', '1', '0', '1', '1', '0', '1', '1', '0', '0', '1', '1', '1'],10,12,),
(['A', 'B', 'B', 'C', 'E', 'E', 'E', 'F', 'L', 'M', 'M', 'M', 'M', 'O', 'O', 'P', 'P', 'Q', 'S', 'T', 'W', 'Y', 'Z', 'a', 'a', 'b', 'd', 'e', 'f', 'i', 'k', 'l', 'l', 'n', 'n', 'n', 'p', 'p', 'q', 'r', 'r', 't', 'u', 'u', 'u', 'u', 'u', 'x', 'x'],[' ', 'B', 'B', 'C', 'C', 'D', 'E', 'I', 'K', 'K', 'O', 'Q', 'Q', 'T', 'T', 'X', 'X', 'X', 'a', 'b', 'c', 'd', 'h', 'h', 'i', 'k', 'k', 'l', 'n', 'o', 'o', 'p', 'p', 'q', 'q', 'r', 'r', 's', 'u', 'u', 'u', 'v', 'w', 'x', 'x', 'x', 'x', 'y', 'z'],39,46,),
(['7', '2', '9', '3', '7', '3', '4', '5', '7', '6', '6', '3', '3', '7', '1', '3', '2', '1', '9', '5', '9', '9', '3', '8', '8', '6', '6', '2', '7', '1', '9', '9', '4', '1', '4', '1', '3', '5'],['6', '3', '7', '2', '9', '2', '6', '4', '4', '7', '6', '4', '5', '5', '9', '0', '0', '4', '2', '3', '6', '7', '6', '2', '6', '7', '8', '6', '6', '5', '2', '6', '4', '4', '1', '8', '3', '0'],26,27,),
(['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],16,19,),
(['n', 'T', 't', 'o', 'i', 'p', 'f', 'R', 'x', 'I', 'p', 'E', 'C', 'm', 'r', 'c', 'U', 'e', ' ', 'o', 'e', 'J', 'C', 'd', 'G', 'l'],['b', 'u', 'F', 'm', 's', 'x', 'T', 'm', 'x', 'o', 'i', 'U', 'd', 'N', 'h', 'z', 'I', 'u', 'g', 'J', 'u', 'f', 'e', 'Q', 'H', 'y'],16,21,)
]
filled_function_param = [
([' ', 'A', 'A', 'C', 'C', 'D', 'D', 'E', 'E', 'F', 'F', 'H', 'L', 'L', 'O', 'P', 'T', 'U', 'V', 'W', 'Z', 'a', 'b', 'f', 'f', 'h', 'h', 'i', 'j', 'q', 'y', 'y', 'z'],[' ', ' ', 'B', 'D', 'F', 'G', 'H', 'I', 'K', 'K', 'L', 'P', 'P', 'R', 'R', 'U', 'V', 'Y', 'Z', 'Z', 'e', 'g', 'h', 'j', 'l', 'o', 'p', 'q', 'r', 't', 'v', 'y', 'z'],25,21,),
(['8', '7', '8', '1', '3', '8', '8', '1', '7', '0', '6', '8', '8', '7', '3', '1', '0', '9', '6', '1', '9', '2', '6', '6', '3', '1', '9', '7', '5', '5', '0', '0', '0', '7', '6', '4', '9', '7', '3', '0', '7', '0', '8'],['0', '2', '1', '1', '8', '9', '6', '0', '1', '7', '0', '2', '1', '8', '7', '9', '9', '8', '0', '2', '7', '9', '1', '6', '8', '1', '3', '4', '7', '8', '0', '2', '4', '2', '6', '9', '1', '1', '4', '2', '4', '7', '4'],22,22,),
(['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],30,34,),
(['x', 'H', 'h', 'z', 'X', 'S', 'f', 'h'],['H', 'f', 'Q', 'b', 'H', 'X', 'l', 'u'],4,7,),
(['0', '1', '1', '2', '3', '3', '4', '4', '4', '5', '5', '6', '7', '7', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9'],['0', '0', '0', '1', '2', '2', '2', '2', '3', '3', '4', '6', '6', '6', '6', '7', '7', '8', '8', '8', '9', '9', '9', '9', '9'],20,13,),
(['1', '1', '0', '0', '0', '1', '0', '0', '0', '1', '1', '0', '1'],['0', '1', '0', '1', '1', '0', '1', '1', '0', '0', '1', '1', '1'],10,12,),
(['A', 'B', 'B', 'C', 'E', 'E', 'E', 'F', 'L', 'M', 'M', 'M', 'M', 'O', 'O', 'P', 'P', 'Q', 'S', 'T', 'W', 'Y', 'Z', 'a', 'a', 'b', 'd', 'e', 'f', 'i', 'k', 'l', 'l', 'n', 'n', 'n', 'p', 'p', 'q', 'r', 'r', 't', 'u', 'u', 'u', 'u', 'u', 'x', 'x'],[' ', 'B', 'B', 'C', 'C', 'D', 'E', 'I', 'K', 'K', 'O', 'Q', 'Q', 'T', 'T', 'X', 'X', 'X', 'a', 'b', 'c', 'd', 'h', 'h', 'i', 'k', 'k', 'l', 'n', 'o', 'o', 'p', 'p', 'q', 'q', 'r', 'r', 's', 'u', 'u', 'u', 'v', 'w', 'x', 'x', 'x', 'x', 'y', 'z'],39,46,),
(['7', '2', '9', '3', '7', '3', '4', '5', '7', '6', '6', '3', '3', '7', '1', '3', '2', '1', '9', '5', '9', '9', '3', '8', '8', '6', '6', '2', '7', '1', '9', '9', '4', '1', '4', '1', '3', '5'],['6', '3', '7', '2', '9', '2', '6', '4', '4', '7', '6', '4', '5', '5', '9', '0', '0', '4', '2', '3', '6', '7', '6', '2', '6', '7', '8', '6', '6', '5', '2', '6', '4', '4', '1', '8', '3', '0'],26,27,),
(['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],['0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1'],16,19,),
(['n', 'T', 't', 'o', 'i', 'p', 'f', 'R', 'x', 'I', 'p', 'E', 'C', 'm', 'r', 'c', 'U', 'e', ' ', 'o', 'e', 'J', 'C', 'd', 'G', 'l'],['b', 'u', 'F', 'm', 's', 'x', 'T', 'm', 'x', 'o', 'i', 'U', 'd', 'N', 'h', 'z', 'I', 'u', 'g', 'J', 'u', 'f', 'e', 'Q', 'H', 'y'],16,21,)
]
n_success = 0
for i, parameters_set in enumerate(param):
f_filled(*(filled_function_param[i]))
f_gold(*parameters_set)
if parameters_set == filled_function_param[i]:
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) | 122.55 | 505 | 0.244798 | 1,362 | 7,353 | 1.302496 | 0.072687 | 0.162345 | 0.202931 | 0.248027 | 0.741826 | 0.741826 | 0.741826 | 0.741826 | 0.741826 | 0.741826 | 0 | 0.144695 | 0.228342 | 7,353 | 60 | 506 | 122.55 | 0.167959 | 0.02516 | 0 | 0.52 | 0 | 0 | 0.173998 | 0.003631 | 0 | 0 | 0 | 0 | 0 | 1 | 0.02 | false | 0 | 0 | 0 | 0.02 | 0.02 | 0 | 0 | 1 | null | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 |
72b1c3fbdfbf0519ae0cc562f32db02d3319c04e | 3,244 | py | Python | MyKit-Learn/linear_regression/lr.py | theFong/MyKit-Learn | 46f70ebebca252a65ea476931cd568a3a03077b8 | [
"MIT"
] | 1 | 2018-07-12T05:20:30.000Z | 2018-07-12T05:20:30.000Z | MyKit-Learn/linear_regression/lr.py | theFong/MyKit-Learn | 46f70ebebca252a65ea476931cd568a3a03077b8 | [
"MIT"
] | null | null | null | MyKit-Learn/linear_regression/lr.py | theFong/MyKit-Learn | 46f70ebebca252a65ea476931cd568a3a03077b8 | [
"MIT"
] | null | null | null | from __future__ import division, print_function
from typing import List
import numpy
import scipy
class LinearRegression:
def __init__(self, nb_features: int):
self.nb_features = nb_features
def train(self, features: List[List[float]], values: List[float]):
# creating f(x) = W0 + sum((Wd)(Xd))
# finding W's
# use LMS(least mean squared(minimizing residuals sum(mean squared error)))
# LMS = ((X^tX)^-1) (X^tY)
# make sure N > D+1
# features = X values = y
y = numpy.array([values]).transpose()
x = numpy.array(features)
# add w0
x = numpy.append([[1]]*len(features),x, axis=1)
xtx = x.transpose().dot(x)
xty = x.transpose().dot(y)
xtxInv = numpy.linalg.inv(xtx)
self.weights = xtxInv.dot(xty)
def phi(self, x: List[float]) -> List[float]:
aug = []
for i in range(1,len(x)):
for k in range(2,self.nb_features+1):
aug.append(numpy.power(x[i],k))
return aug
def predict(self, features: List[List[float]]) -> List[float]:
# f(x) = wtx
# x -> p(x) [1,x,x^2...x^d]
x = numpy.array(features)
x = numpy.append([[1]]*len(features),x, axis=1)
return numpy.inner(self.weights.transpose(),x)[0]
def get_weights(self) -> List[float]:
"""
for a model y = 1 + 3 * x_0 - 2 * x_1,
the return value should be [1, 3, -2].
"""
return self.weights
class LinearRegressionWithL2Loss:
'''Use L2 loss for weight regularization'''
def __init__(self, nb_features: int, alpha: float):
self.alpha = alpha
self.nb_features = nb_features
def train(self, features: List[List[float]], values: List[float]):
# creating f(x) = W0 + sum((Wd)(Xd))
# finding W's
# use LMS(least mean squared(minimizing residuals sum(mean squared error)))
# LMS = ((X^tX)^-1) (X^tY) Now (X^tX -> X^tX + lI)
# make sure N > D+1
# features = X values = y
y = numpy.array([values]).transpose()
x = numpy.array(features)
# add w0
x = numpy.append([[1]]*len(features),x, axis=1)
# xtx -> xtx + lI
xtx = numpy.add(x.transpose().dot(x), self.alpha * numpy.identity(x.shape[1]))
xty = x.transpose().dot(y)
xtxInv = numpy.linalg.inv(xtx)
self.weights = xtxInv.dot(xty)
def phi(self, x: List[float]) -> List[float]:
aug = []
for i in range(1,len(x)):
for k in range(2,self.nb_features+1):
aug.append(numpy.power(x[i],k))
return aug
def predict(self, features: List[List[float]]) -> List[float]:
# f(x) = wtx + l|w|^2
# x -> p(x) [1,x,x^2...x^d]
x = numpy.array(features)
x = numpy.append([[1]]*len(features),x, axis=1)
return numpy.inner(self.weights.transpose(),x)[0]
def get_weights(self) -> List[float]:
"""
for a model y = 1 + 3 * x_0 - 2 * x_1,
the return value should be [1, 3, -2].
"""
return self.weights
if __name__ == '__main__':
print(numpy.__version__)
print(scipy.__version__)
| 31.192308 | 86 | 0.544698 | 461 | 3,244 | 3.739696 | 0.212581 | 0.073086 | 0.048724 | 0.046404 | 0.815545 | 0.815545 | 0.787703 | 0.787703 | 0.787703 | 0.787703 | 0 | 0.021071 | 0.297781 | 3,244 | 103 | 87 | 31.495146 | 0.735733 | 0.218249 | 0 | 0.740741 | 0 | 0 | 0.003265 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.185185 | false | 0 | 0.074074 | 0 | 0.407407 | 0.055556 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
f42a9bb04f11a3fad6182d63b431357fb1c1f3cb | 455 | py | Python | apiaudio/api_resources/__init__.py | aflorithmic/aflr_python | 505317bec82f9c4bacc1604b6e90e6468d87607b | [
"MIT"
] | 20 | 2021-03-18T20:50:24.000Z | 2021-07-14T08:02:06.000Z | apiaudio/api_resources/__init__.py | aflorithmic/apiaudio-python | 8354bc159d8f6b7d688af1a34037811e84b8729c | [
"MIT"
] | 7 | 2021-07-21T10:00:55.000Z | 2022-03-23T16:42:43.000Z | apiaudio/api_resources/__init__.py | aflorithmic/apiaudio-python | 8354bc159d8f6b7d688af1a34037811e84b8729c | [
"MIT"
] | 5 | 2021-02-26T09:06:04.000Z | 2021-04-01T16:51:58.000Z | from apiaudio.api_resources.script import Script
from apiaudio.api_resources.speech import Speech
from apiaudio.api_resources.voice import Voice
from apiaudio.api_resources.mastering import Mastering
from apiaudio.api_resources.sound import Sound
from apiaudio.api_resources.syncTTS import SyncTTS
from apiaudio.api_resources.media import Media
from apiaudio.api_resources.birdcache import Birdcache
from apiaudio.api_resources.connector import Connector
| 45.5 | 54 | 0.881319 | 63 | 455 | 6.222222 | 0.222222 | 0.27551 | 0.344388 | 0.55102 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.079121 | 455 | 9 | 55 | 50.555556 | 0.935561 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
f43eeb5f7b9d03b067d5e4316e5c22f53f5845f7 | 15,398 | py | Python | tests/native/test_importfile.py | aaronater10/sfconfig | f1ebd0a4dc5e6ec235d30b0ef1540fb65422729a | [
"MIT"
] | null | null | null | tests/native/test_importfile.py | aaronater10/sfconfig | f1ebd0a4dc5e6ec235d30b0ef1540fb65422729a | [
"MIT"
] | null | null | null | tests/native/test_importfile.py | aaronater10/sfconfig | f1ebd0a4dc5e6ec235d30b0ef1540fb65422729a | [
"MIT"
] | null | null | null | # importfile - Tests
from src import sfcparse
from os import path
import unittest
test_file_path = './tests/test_files/native/importfile_files/'
################################################################
# TESTS
# New testing methods since v1.2.0
class TestImportFile(unittest.TestCase):
# 1. Basic File Import - Importing an Empty File
def test1_basic_file_import(self):
filename = '1_empty.data'
filepath = test_file_path + filename
assert path.getsize(filepath) == 0, f"File Not Empty: {filename}"
assert (sfcparse.importfile(filepath)) == None, f"Not None {filename}"
# 2. Single Line Import - Importing Singles Lines of All Accepted Data Types
def test2_single_line_import(self):
filename = '2_single_line.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (file_import.data_str == "data") and (isinstance(file_import.data_str, str))
assert (file_import.data_int == 1) and (isinstance(file_import.data_int, int))
assert (file_import.data_float == 1.0) and (isinstance(file_import.data_float, float))
assert (file_import.data_bool == True) and (isinstance(file_import.data_bool, bool))
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_dict == {'k1':1, 'k2':2, 'k3':3}) and (isinstance(file_import.data_dict, dict))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
assert (file_import.data_none == None) and (isinstance(file_import.data_none, type(None)))
assert (file_import.data_bytes == b'data') and (isinstance(file_import.data_bytes, bytes))
# 3. Multi Line Import - Importing Multi Line of All Accepted Data Types
def test3_multi_line_import(self):
filename = '3_multi_line.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_dict == {'k1':1, 'k2':2, 'k3':3}) and (isinstance(file_import.data_dict, dict))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
# 4. Multi-Single Line Import - Importing Multi and Single Lines Together
def test4_multi_single_line_import(self):
filename = '4_multi-single_line.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (file_import.data_bool == True) and (isinstance(file_import.data_bool, bool))
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_str == "data") and (isinstance(file_import.data_str, str))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_none == None) and (isinstance(file_import.data_none, type(None)))
assert (file_import.data_bytes == b'data') and (isinstance(file_import.data_bytes, bytes))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
# 5. Multi-Single Comments Import - Importing Multi and Single Lines with Comments
def test5_multi_single_comments_import(self):
filename = '5_multi-single_comments.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (file_import.data_bool == True) and (isinstance(file_import.data_bool, bool))
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_str == "data") and (isinstance(file_import.data_str, str))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_none == None) and (isinstance(file_import.data_none, type(None)))
assert (file_import.data_bytes == b'data') and (isinstance(file_import.data_bytes, bytes))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
# 6. Nested Data Import - Importing Nested Data
def test6_nested_data_import(self):
filename = '6_nested.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert isinstance(file_import.data_list, list)
assert (file_import.data_list[0] == [1,2,3]) and (isinstance(file_import.data_list[0], list))
assert (file_import.data_list[1] == [1, 2, 3, 4, 5]) and (isinstance(file_import.data_list[1], list))
assert (file_import.data_list[2] == {'k1': 1, 'k2': 2, 'k3': 3}) and (isinstance(file_import.data_list[2], dict))
assert (file_import.data_list[3] == (1, 2, 3)) and (isinstance(file_import.data_list[3], tuple))
assert (file_import.data_list[4] == {1, 2, 3}) and (isinstance(file_import.data_list[4], set))
assert (file_import.data_list[5] == [1, 2, 3]) and (isinstance(file_import.data_list[5], list))
# 7. White Space Import - Importing Data with White Space in Between
def test7_white_space_import(self):
filename = '7_white_space.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_str == "data") and (isinstance(file_import.data_str, str))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_none == None) and (isinstance(file_import.data_none, type(None)))
assert (file_import.data_bytes == b'data') and (isinstance(file_import.data_bytes, bytes))
assert (file_import.data_float == 1.0) and (isinstance(file_import.data_float, float))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
assert (file_import.data_bool == True) and (isinstance(file_import.data_bool, bool))
# 8. All Multi-Single Line Types Import - Importing All Multi-Single Line Types Together
def test8_all_multi_single_types_import(self):
filename = '8_all_multi-single_types.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
# Multi
assert (file_import.data_list_m == [1,2,3]) and (isinstance(file_import.data_list_m, list))
assert (file_import.data_dict_m == {'k1':1, 'k2':2, 'k3':3}) and (isinstance(file_import.data_dict_m, dict))
assert (file_import.data_tuple_m == (1,2,3)) and (isinstance(file_import.data_tuple_m, tuple))
assert (file_import.data_set_m == {1,2,3}) and (isinstance(file_import.data_set_m, set))
# Single
assert (file_import.data_str == "data") and (isinstance(file_import.data_str, str))
assert (file_import.data_int == 1) and (isinstance(file_import.data_int, int))
assert (file_import.data_float == 1.0) and (isinstance(file_import.data_float, float))
assert (file_import.data_bool == True) and (isinstance(file_import.data_bool, bool))
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_dict == {'k1':1, 'k2':2, 'k3':3}) and (isinstance(file_import.data_dict, dict))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
assert (file_import.data_none == None) and (isinstance(file_import.data_none, type(None)))
assert (file_import.data_bytes == b'data') and (isinstance(file_import.data_bytes, bytes))
# 9. Big Data Import - Importing 100K+ Values of Data with Single Lines
def test9_big_data_import(self):
filename = '9_big_data_with_singles.data'
filepath = test_file_path + filename
big_data_len = 100_000
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (len(file_import.data_single) == big_data_len) and (isinstance(file_import.data_single, list))
assert (file_import.data_float == 1.0) and (isinstance(file_import.data_float, float))
assert (file_import.data_bool == True) and (isinstance(file_import.data_bool, bool))
assert (len(file_import.data_multi) == big_data_len) and (isinstance(file_import.data_multi, dict))
assert (file_import.data_none == None) and (isinstance(file_import.data_none, type(None)))
assert (file_import.data_bytes == b'data') and (isinstance(file_import.data_bytes, bytes))
# 10. Misc Behavior Import - Importing Misc, Odd, or Unique Data Inputs
def test10_misc_data_import(self):
filename = '10_misc.data'
filepath = test_file_path + filename
# Test File Import
assert sfcparse.importfile(filepath)
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types
assert (file_import.data_single_tuple_1 == (1,)) and (isinstance(file_import.data_single_tuple_1, tuple))
assert (file_import.data_single_tuple_2 == (1,)) and (isinstance(file_import.data_single_tuple_2, tuple))
assert (file_import.data_tuple_int_1 == 1) and (isinstance(file_import.data_tuple_int_1, int))
assert (file_import.data_tuple_int_2 == 1) and (isinstance(file_import.data_tuple_int_2, int))
assert (file_import.data_str_1 == "data with internal spaces") and (isinstance(file_import.data_str_1, str))
assert (file_import.data_str_2 == " data with internal and end spaces ") and (isinstance(file_import.data_str_2, str))
assert (file_import.data_list == [1,2,3]) and (isinstance(file_import.data_list, list))
assert (file_import.data_dict == {'k1':1, 'k2':2, 'k3':3}) and (isinstance(file_import.data_dict, dict))
assert (file_import.data_tuple == (1,2,3)) and (isinstance(file_import.data_tuple, tuple))
assert (file_import.data_set == {1,2,3}) and (isinstance(file_import.data_set, set))
assert (file_import.data_token1 == ['normal value', "var = 'value'", 'normal value']) and (isinstance(file_import.data_token1, list))
assert (file_import.data_end_token1 == ['normal value', "var = 'value'", 'normal value']) and (isinstance(file_import.data_end_token1, list))
# 11. Single-Line Attr Dedup OFF - Turning OFF Attribute Dedup Feature Test
def test11_single_attr_dedup_off(self):
filename = '11_attr_dedup_off_single.data'
filepath = test_file_path + filename
# Test Turn OFF Attr Dedup Protection
file_import = sfcparse.importfile(filepath, False)
# Test Attributes and Types - Confirm data and it's type was in fact changed inside file
assert (file_import.data_dict == "changed data") and (isinstance(file_import.data_dict, str))
# 12. Multi-Line Attr Dedup OFF - Turning OFF Attribute Dedup Feature Test
def test12_multi_attr_dedup_off(self):
filename = '12_attr_dedup_off_multi.data'
filepath = test_file_path + filename
# Test Turn OFF Attr Dedup Protection
file_import = sfcparse.importfile(filepath, False)
# Test Attributes and Types - Confirm data and it's type was in fact changed inside file
assert (file_import.data_list == "changed data") and (isinstance(file_import.data_list, str))
# 13. Single-Line Attr Lock - Attribute Locked and Cannot Re-Assign
def test13_single_attr_lock(self):
filename = '13_attr_lock_single.data'
filepath = test_file_path + filename
# Test File Import
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types - Confirm attr values not changed and match expected
change_value = 'changed_value'
with self.assertRaises(Exception): file_import.data_str = change_value
self.assertEqual(file_import.data_str, "data")
with self.assertRaises(Exception): file_import.data_int = change_value
self.assertEqual(file_import.data_int, 1)
with self.assertRaises(Exception): file_import.data_float = change_value
self.assertEqual(file_import.data_float, 1.0)
with self.assertRaises(Exception): file_import.data_bool = change_value
self.assertEqual(file_import.data_bool, True)
with self.assertRaises(Exception): file_import.data_list = change_value
self.assertEqual(file_import.data_list, [1,2,3])
with self.assertRaises(Exception): file_import.data_dict = change_value
self.assertEqual(file_import.data_dict, {'k1':1, 'k2':2, 'k3':3})
with self.assertRaises(Exception): file_import.data_tuple = change_value
self.assertEqual(file_import.data_tuple, (1,2,3))
with self.assertRaises(Exception): file_import.data_set = change_value
self.assertEqual(file_import.data_set, {1,2,3})
with self.assertRaises(Exception): file_import.data_none = change_value
self.assertEqual(file_import.data_none, None)
with self.assertRaises(Exception): file_import.data_bytes = change_value
self.assertEqual(file_import.data_bytes, b'data')
# 14. Single-Line Attr Lock - Attribute Locked and Cannot Re-Assign
def test14_multi_attr_lock(self):
filename = '14_attr_lock_multi.data'
filepath = test_file_path + filename
# Test File Import
file_import = sfcparse.importfile(filepath)
# Test Attributes and Types - Confirm attr values not changed and match expected
change_value = 'changed_value'
with self.assertRaises(Exception): file_import.data_list = change_value
self.assertEqual(file_import.data_list, [1,2,3])
with self.assertRaises(Exception): file_import.data_dict = change_value
self.assertEqual(file_import.data_dict, {'k1':1, 'k2':2, 'k3':3})
with self.assertRaises(Exception): file_import.data_tuple = change_value
self.assertEqual(file_import.data_tuple, (1,2,3))
with self.assertRaises(Exception): file_import.data_set = change_value
self.assertEqual(file_import.data_set, {1,2,3})
| 51.498328 | 149 | 0.692168 | 2,133 | 15,398 | 4.741678 | 0.068448 | 0.204667 | 0.250544 | 0.182717 | 0.86494 | 0.819557 | 0.770912 | 0.714752 | 0.690429 | 0.666601 | 0 | 0.021737 | 0.193337 | 15,398 | 299 | 150 | 51.498328 | 0.792529 | 0.120795 | 0 | 0.603352 | 0 | 0 | 0.050264 | 0.019063 | 0 | 0 | 0 | 0 | 0.648045 | 1 | 0.078212 | false | 0 | 0.798883 | 0 | 0.882682 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 10 |
f47ef7827fc3b1d1fa1986830db9de26a0f33ac0 | 1,072 | py | Python | sporepedia/__init__.py | LEv145/sporepedia.py | defbf4758b333978fac60b7df5270c4890b92328 | [
"MIT"
] | 6 | 2021-12-13T22:36:53.000Z | 2022-01-14T12:58:30.000Z | sporepedia/__init__.py | LEv145/sporepedia.py | defbf4758b333978fac60b7df5270c4890b92328 | [
"MIT"
] | null | null | null | sporepedia/__init__.py | LEv145/sporepedia.py | defbf4758b333978fac60b7df5270c4890b92328 | [
"MIT"
] | null | null | null | from .api import (
ABCSearchParam,
APIClient,
APIClientProtocol,
AdventureStat,
Author,
Creation,
Difficulty,
DwrParserError,
FieldsSearchParam,
FunctionsSearchParam,
ModelsSearchParam,
PurposesSearchParam,
SearchFilter,
SearchMixin,
SearchParams,
SearchRequestComposer,
SearchResponceBuilder,
SearchServiceResult,
SporeDwrEngineParser,
Status,
StatusName,
parse_dwr,
to_python__mockup,
)
from .client import (
SporepediaClient,
)
__all__ = [
"ABCSearchParam",
"APIClient",
"APIClientProtocol",
"AdventureStat",
"Author",
"Creation",
"Difficulty",
"DwrParserError",
"FieldsSearchParam",
"FunctionsSearchParam",
"ModelsSearchParam",
"PurposesSearchParam",
"SearchFilter",
"SearchMixin",
"SearchParams",
"SearchRequestComposer",
"SearchResponceBuilder",
"SearchServiceResult",
"SporeDwrEngineParser",
"SporepediaClient",
"Status",
"StatusName",
"parse_dwr",
"to_python__mockup",
]
| 19.142857 | 28 | 0.664179 | 61 | 1,072 | 11.47541 | 0.52459 | 0.065714 | 0.114286 | 0.151429 | 0.908571 | 0.908571 | 0.908571 | 0.8 | 0.8 | 0.8 | 0 | 0 | 0.237873 | 1,072 | 55 | 29 | 19.490909 | 0.856793 | 0 | 0 | 0 | 0 | 0 | 0.315299 | 0.039179 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.037037 | 0 | 0.037037 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
22b671bf9d9c50a01946610805ee48c3a5304fc6 | 35 | py | Python | extern/pycftrackers/lib/eco/config/__init__.py | tsingqguo/AttackTracker | 054268d5afa0044675c7acf1ac13e621f1c9549e | [
"Apache-2.0"
] | 11 | 2020-11-25T16:19:23.000Z | 2022-01-12T08:08:47.000Z | extern/pycftrackers/lib/eco/config/__init__.py | tsingqguo/AttackTracker | 054268d5afa0044675c7acf1ac13e621f1c9549e | [
"Apache-2.0"
] | 4 | 2021-03-19T02:17:49.000Z | 2022-03-11T23:53:54.000Z | extern/pycftrackers/lib/eco/config/__init__.py | tsingqguo/AttackTracker | 054268d5afa0044675c7acf1ac13e621f1c9549e | [
"Apache-2.0"
] | 1 | 2020-01-05T03:39:38.000Z | 2020-01-05T03:39:38.000Z | from .gpu_config import gpu_config
| 17.5 | 34 | 0.857143 | 6 | 35 | 4.666667 | 0.666667 | 0.642857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.114286 | 35 | 1 | 35 | 35 | 0.903226 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
22bcbe79750267cd2a26ed4361e2ee35a7fc3e63 | 2,368 | py | Python | 2018/day_12/python/day12.py | josephroquedev/advent-of-code | bb217deb7a5f5ed5c8c04cb726ddadb5b042ee4d | [
"MIT"
] | null | null | null | 2018/day_12/python/day12.py | josephroquedev/advent-of-code | bb217deb7a5f5ed5c8c04cb726ddadb5b042ee4d | [
"MIT"
] | 2 | 2021-06-02T00:41:38.000Z | 2021-11-30T10:05:29.000Z | 2018/day_12/python/day12.py | autoreleasefool/advent-of-code | bb217deb7a5f5ed5c8c04cb726ddadb5b042ee4d | [
"MIT"
] | null | null | null | from aoc import AOC
aoc = AOC(year=2018, day=12)
data = aoc.load()
## Part 1
start_state = None
transformations = {}
for index, line in enumerate(data.lines()):
line = line.strip()
if index == 0:
start_state = [1 if x == "#" else 0 for x in line]
elif not line:
continue
else:
state = tuple([1 if x == "#" else 0 for x in line[:5]])
transformations[state] = 1 if line[9] == "#" else 0
start_index = 4
state = [0, 0, 0, 0] + start_state
for i in range(20):
if sum(state[:5]) > 0:
state = [0, 0, 0, 0] + state
start_index += 4
if sum(state[-6:]) > 0:
state.append(0)
state.append(0)
state.append(0)
state.append(0)
next_state = state[:]
for index, pot in enumerate(state):
pot_state = tuple(state[index - 2 : index + 3])
if pot_state in transformations:
next_state[index] = transformations[pot_state]
else:
next_state[index] = 0
state = next_state
total = 0
for index, pot in enumerate(state):
total += (index - start_index) if pot == 1 else 0
aoc.p1(total)
## Part 2
start_state = None
transformations = {}
for index, line in enumerate(data.lines()):
line = line.strip()
if index == 0:
start_state = [1 if x == "#" else 0 for x in line]
elif not line:
continue
else:
state = tuple([1 if x == "#" else 0 for x in line[:5]])
transformations[state] = 1 if line[9] == "#" else 0
start_index = 4
state = [0, 0, 0, 0] + start_state
last_total = 0
for i in range(501):
if sum(state[:5]) > 0:
state = [0, 0, 0, 0] + state
start_index += 4
if sum(state[-6:]) > 0:
state.append(0)
state.append(0)
state.append(0)
state.append(0)
total = 0
for index, pot in enumerate(state):
total += (index - start_index) if pot == 1 else 0
if i == 500:
diff = total - last_total
final_sum = total + (50000000000 - 500) * diff
aoc.p2(final_sum)
last_total = total
next_state = state[:]
for index, pot in enumerate(state):
pot_state = tuple(state[index - 2 : index + 3])
if pot_state in transformations:
next_state[index] = transformations[pot_state]
else:
next_state[index] = 0
state = next_state
| 24.412371 | 63 | 0.560811 | 347 | 2,368 | 3.737752 | 0.149856 | 0.064765 | 0.018504 | 0.080185 | 0.857363 | 0.857363 | 0.857363 | 0.857363 | 0.857363 | 0.857363 | 0 | 0.06055 | 0.309544 | 2,368 | 96 | 64 | 24.666667 | 0.732722 | 0.00549 | 0 | 0.842105 | 0 | 0 | 0.002553 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.013158 | 0 | 0.013158 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
22fd40b0d9f2742184bd1b608bb443e531ce503a | 254 | py | Python | distex/__init__.py | stnatter/distex | 8024b825abd6add61cddc93580550ee77a6ef9fb | [
"BSD-2-Clause"
] | null | null | null | distex/__init__.py | stnatter/distex | 8024b825abd6add61cddc93580550ee77a6ef9fb | [
"BSD-2-Clause"
] | null | null | null | distex/__init__.py | stnatter/distex | 8024b825abd6add61cddc93580550ee77a6ef9fb | [
"BSD-2-Clause"
] | null | null | null | from .pool import Pool, RemoteException, HostSpec, PickleType, LoopType
from .poolmap import PoolMap
from .version import __version__, __version_info__ # noqa
__all__ = [
'Pool', 'RemoteException', 'HostSpec', 'PickleType', 'LoopType', 'PoolMap']
| 31.75 | 79 | 0.748031 | 26 | 254 | 6.807692 | 0.461538 | 0.214689 | 0.305085 | 0.418079 | 0.508475 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.137795 | 254 | 7 | 80 | 36.285714 | 0.808219 | 0.015748 | 0 | 0 | 0 | 0 | 0.209677 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.6 | 0 | 0.6 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
fe1da4e00ded459651343e3eae878f6075b58bce | 245 | py | Python | app/main/encryption.py | alphagov/notify-api | 16dbafbad69e5bb179ba4b2202a7afa299c88d61 | [
"MIT"
] | 12 | 2015-10-06T08:58:28.000Z | 2016-08-08T17:51:29.000Z | app/main/encryption.py | gds-attic/notify-api | 16dbafbad69e5bb179ba4b2202a7afa299c88d61 | [
"MIT"
] | 3 | 2015-10-15T15:12:04.000Z | 2016-06-13T15:13:41.000Z | app/main/encryption.py | gds-attic/notify-api | 16dbafbad69e5bb179ba4b2202a7afa299c88d61 | [
"MIT"
] | 3 | 2016-05-31T17:40:15.000Z | 2021-04-10T20:03:33.000Z | from flask.ext.bcrypt import generate_password_hash, check_password_hash
def hashpw(password):
return generate_password_hash(password, 10)
def checkpw(password, hashed_password):
return check_password_hash(hashed_password, password)
| 24.5 | 72 | 0.820408 | 32 | 245 | 5.96875 | 0.46875 | 0.251309 | 0.209424 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009217 | 0.114286 | 245 | 9 | 73 | 27.222222 | 0.870968 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.4 | false | 1 | 0.2 | 0.4 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | 0 | 8 |
a3abdaaf869addd6d7706c5ee814da2a09203269 | 61 | py | Python | tests/parser/good/comp.py | Nakrez/RePy | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | [
"MIT"
] | 1 | 2020-11-24T05:24:26.000Z | 2020-11-24T05:24:26.000Z | tests/parser/good/comp.py | Nakrez/RePy | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | [
"MIT"
] | null | null | null | tests/parser/good/comp.py | Nakrez/RePy | 057db55a99eac2c5cb3d622fa1f2e29f6083d8d6 | [
"MIT"
] | null | null | null | 1 < 2 > 3 == 3 >= 5 <= 4 != 20 in 20 not in 1 is 1 is not 42
| 30.5 | 60 | 0.459016 | 17 | 61 | 1.647059 | 0.588235 | 0.214286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.368421 | 0.377049 | 61 | 1 | 61 | 61 | 0.368421 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
a3c7890ce8379379ac3943580a76221fae6493d5 | 70,206 | py | Python | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_tcp_cfg.py | tkamata-test/ydk-py | b637e7853a8edbbd31fbc05afa3aa4110b31c5f9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_tcp_cfg.py | tkamata-test/ydk-py | b637e7853a8edbbd31fbc05afa3aa4110b31c5f9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ip_tcp_cfg.py | tkamata-test/ydk-py | b637e7853a8edbbd31fbc05afa3aa4110b31c5f9 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | """ Cisco_IOS_XR_ip_tcp_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR ip\-tcp package configuration.
This module contains definitions
for the following management objects\:
ip\-tcp\: Global IP TCP configuration
ip\: ip
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights reserved.
"""
import re
import collections
from enum import Enum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk.errors import YPYError, YPYModelError
class IpTcp(object):
"""
Global IP TCP configuration
.. attribute:: accept_rate
TCP connection accept rate
**type**\: int
**range:** 1..1000
**default value**\: 500
.. attribute:: directory
TCP directory details
**type**\: :py:class:`Directory <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.IpTcp.Directory>`
**presence node**\: True
.. attribute:: maximum_segment_size
TCP initial maximum segment size
**type**\: int
**range:** 68..10000
.. attribute:: num_thread
TCP InQueue and OutQueue threads
**type**\: :py:class:`NumThread <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.IpTcp.NumThread>`
**presence node**\: True
.. attribute:: path_mtu_discovery
Aging time; 0 for infinite, and range be (10,30)
**type**\: int
**range:** \-2147483648..2147483647
**units**\: minute
**default value**\: 10
.. attribute:: receive_q
TCP receive Queue Size
**type**\: int
**range:** 40..800
.. attribute:: selective_ack
Enable TCP selective\-ACK
**type**\: :py:class:`Empty<ydk.types.Empty>`
.. attribute:: syn_wait_time
Time to wait on new TCP connections in seconds
**type**\: int
**range:** 5..30
**units**\: second
.. attribute:: throttle
Throttle TCP receive buffer (in percentage)
**type**\: :py:class:`Throttle <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.IpTcp.Throttle>`
**presence node**\: True
.. attribute:: timestamp
Enable TCP timestamp option
**type**\: :py:class:`Empty<ydk.types.Empty>`
.. attribute:: window_size
TCP receive window size (bytes)
**type**\: int
**range:** 2048..65535
**units**\: byte
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.accept_rate = None
self.directory = None
self.maximum_segment_size = None
self.num_thread = None
self.path_mtu_discovery = None
self.receive_q = None
self.selective_ack = None
self.syn_wait_time = None
self.throttle = None
self.timestamp = None
self.window_size = None
class Directory(object):
"""
TCP directory details
.. attribute:: directoryname
Directory name
**type**\: str
**mandatory**\: True
.. attribute:: max_debug_files
Set number of Debug files
**type**\: int
**range:** 1..10000
**mandatory**\: True
.. attribute:: max_file_size_files
Set size of debug files in bytes
**type**\: int
**range:** 1024..4294967295
**mandatory**\: True
**units**\: byte
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.directoryname = None
self.max_debug_files = None
self.max_file_size_files = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip-tcp/Cisco-IOS-XR-ip-tcp-cfg:directory'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.directoryname is not None:
return True
if self.max_debug_files is not None:
return True
if self.max_file_size_files is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['IpTcp.Directory']['meta_info']
class Throttle(object):
"""
Throttle TCP receive buffer (in percentage)
.. attribute:: tcpmaxthrottle
Max throttle
**type**\: int
**range:** 0..100
**mandatory**\: True
.. attribute:: tcpmin_throttle
Min throttle
**type**\: int
**range:** 0..100
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.tcpmaxthrottle = None
self.tcpmin_throttle = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip-tcp/Cisco-IOS-XR-ip-tcp-cfg:throttle'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.tcpmaxthrottle is not None:
return True
if self.tcpmin_throttle is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['IpTcp.Throttle']['meta_info']
class NumThread(object):
"""
TCP InQueue and OutQueue threads
.. attribute:: tcp_in_q_threads
InQ Threads
**type**\: int
**range:** 1..16
**mandatory**\: True
.. attribute:: tcp_out_q_threads
OutQ Threads
**type**\: int
**range:** 1..16
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.tcp_in_q_threads = None
self.tcp_out_q_threads = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip-tcp/Cisco-IOS-XR-ip-tcp-cfg:num-thread'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.tcp_in_q_threads is not None:
return True
if self.tcp_out_q_threads is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['IpTcp.NumThread']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip-tcp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.accept_rate is not None:
return True
if self.directory is not None and self.directory._has_data():
return True
if self.maximum_segment_size is not None:
return True
if self.num_thread is not None and self.num_thread._has_data():
return True
if self.path_mtu_discovery is not None:
return True
if self.receive_q is not None:
return True
if self.selective_ack is not None:
return True
if self.syn_wait_time is not None:
return True
if self.throttle is not None and self.throttle._has_data():
return True
if self.timestamp is not None:
return True
if self.window_size is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['IpTcp']['meta_info']
class Ip(object):
"""
ip
.. attribute:: cinetd
Cinetd configuration data
**type**\: :py:class:`Cinetd <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd>`
.. attribute:: forward_protocol
Controls forwarding of physical and directed IP broadcasts
**type**\: :py:class:`ForwardProtocol <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.cinetd = Ip.Cinetd()
self.cinetd.parent = self
self.forward_protocol = Ip.ForwardProtocol()
self.forward_protocol.parent = self
class Cinetd(object):
"""
Cinetd configuration data
.. attribute:: services
Describing services of cinetd
**type**\: :py:class:`Services <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.services = Ip.Cinetd.Services()
self.services.parent = self
class Services(object):
"""
Describing services of cinetd
.. attribute:: ipv4
IPV4 related services
**type**\: :py:class:`Ipv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4>`
.. attribute:: ipv6
IPV6 related services
**type**\: :py:class:`Ipv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6>`
.. attribute:: vrfs
VRF table
**type**\: :py:class:`Vrfs <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.ipv4 = Ip.Cinetd.Services.Ipv4()
self.ipv4.parent = self
self.ipv6 = Ip.Cinetd.Services.Ipv6()
self.ipv6.parent = self
self.vrfs = Ip.Cinetd.Services.Vrfs()
self.vrfs.parent = self
class Ipv4(object):
"""
IPV4 related services
.. attribute:: small_servers
Describing IPV4 and IPV6 small servers
**type**\: :py:class:`SmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.small_servers = Ip.Cinetd.Services.Ipv4.SmallServers()
self.small_servers.parent = self
class SmallServers(object):
"""
Describing IPV4 and IPV6 small servers
.. attribute:: tcp_small_servers
Describing TCP related IPV4 and IPV6 small servers
**type**\: :py:class:`TcpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers.TcpSmallServers>`
**presence node**\: True
.. attribute:: udp_small_servers
UDP small servers configuration
**type**\: :py:class:`UdpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.tcp_small_servers = None
self.udp_small_servers = None
class TcpSmallServers(object):
"""
Describing TCP related IPV4 and IPV6 small
servers
.. attribute:: access_control_list_name
Access list
**type**\: str
.. attribute:: small_server
Set number of allowable TCP small servers, specify 0 for no\-limit
**type**\: int
**range:** \-2147483648..2147483647
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_control_list_name = None
self.small_server = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv4/Cisco-IOS-XR-ip-tcp-cfg:small-servers/Cisco-IOS-XR-ip-tcp-cfg:tcp-small-servers'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_control_list_name is not None:
return True
if self.small_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv4.SmallServers.TcpSmallServers']['meta_info']
class UdpSmallServers(object):
"""
UDP small servers configuration
.. attribute:: access_control_list_name
Specify the access list
**type**\: str
**mandatory**\: True
.. attribute:: small_server
Set number of allowable small servers, specify 0 for no\-limit
**type**\: int
**range:** 0..2147483647
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_control_list_name = None
self.small_server = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv4/Cisco-IOS-XR-ip-tcp-cfg:small-servers/Cisco-IOS-XR-ip-udp-cfg:udp-small-servers'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_control_list_name is not None:
return True
if self.small_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv4.SmallServers.UdpSmallServers']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv4/Cisco-IOS-XR-ip-tcp-cfg:small-servers'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.tcp_small_servers is not None and self.tcp_small_servers._has_data():
return True
if self.udp_small_servers is not None and self.udp_small_servers._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv4.SmallServers']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv4'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.small_servers is not None and self.small_servers._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv4']['meta_info']
class Vrfs(object):
"""
VRF table
.. attribute:: vrf
VRF specific data
**type**\: list of :py:class:`Vrf <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.vrf = YList()
self.vrf.parent = self
self.vrf.name = 'vrf'
class Vrf(object):
"""
VRF specific data
.. attribute:: vrf_name <key>
Name of the VRF instance
**type**\: str
**pattern:** [\\w\\\-\\.\:,\_@#%$\\+=\\\|;]+
.. attribute:: ipv4
IPV4 related services
**type**\: :py:class:`Ipv4 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4>`
.. attribute:: ipv6
IPV6 related services
**type**\: :py:class:`Ipv6 <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.vrf_name = None
self.ipv4 = Ip.Cinetd.Services.Vrfs.Vrf.Ipv4()
self.ipv4.parent = self
self.ipv6 = Ip.Cinetd.Services.Vrfs.Vrf.Ipv6()
self.ipv6.parent = self
class Ipv6(object):
"""
IPV6 related services
.. attribute:: telnet
TELNET server configuration commands
**type**\: :py:class:`Telnet <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet>`
.. attribute:: tftp
TFTP server configuration commands
**type**\: :py:class:`Tftp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.telnet = Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet()
self.telnet.parent = self
self.tftp = Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp()
self.tftp.parent = self
class Telnet(object):
"""
TELNET server configuration commands
.. attribute:: tcp
TCP details
**type**\: :py:class:`Tcp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet.Tcp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.tcp = None
class Tcp(object):
"""
TCP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: maximum_server
Set number of allowable servers
**type**\: int
**range:** 1..100
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_list_name = None
self.maximum_server = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:tcp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_list_name is not None:
return True
if self.maximum_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet.Tcp']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:telnet'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.tcp is not None and self.tcp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Telnet']['meta_info']
class Tftp(object):
"""
TFTP server configuration commands
.. attribute:: udp
UDP details
**type**\: :py:class:`Udp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp.Udp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.udp = None
class Udp(object):
"""
UDP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: dscp_value
Set IP DSCP (DiffServ CodePoint) for TFTP Server Packets
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: home_directory
Specify device name where file is read from (e .g. flash\:)
**type**\: str
**mandatory**\: True
.. attribute:: maximum_server
Set number of allowable servers, 0 for no\-limit
**type**\: int
**range:** 0..2147483647
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_list_name = None
self.dscp_value = None
self.home_directory = None
self.maximum_server = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:udp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_list_name is not None:
return True
if self.dscp_value is not None:
return True
if self.home_directory is not None:
return True
if self.maximum_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp.Udp']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:tftp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.udp is not None and self.udp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv6.Tftp']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:ipv6'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.telnet is not None and self.telnet._has_data():
return True
if self.tftp is not None and self.tftp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv6']['meta_info']
class Ipv4(object):
"""
IPV4 related services
.. attribute:: telnet
TELNET server configuration commands
**type**\: :py:class:`Telnet <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet>`
.. attribute:: tftp
TFTP server configuration commands
**type**\: :py:class:`Tftp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.telnet = Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet()
self.telnet.parent = self
self.tftp = Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp()
self.tftp.parent = self
class Telnet(object):
"""
TELNET server configuration commands
.. attribute:: tcp
TCP details
**type**\: :py:class:`Tcp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet.Tcp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.tcp = None
class Tcp(object):
"""
TCP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: maximum_server
Set number of allowable servers
**type**\: int
**range:** 1..100
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_list_name = None
self.maximum_server = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:tcp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_list_name is not None:
return True
if self.maximum_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet.Tcp']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:telnet'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.tcp is not None and self.tcp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Telnet']['meta_info']
class Tftp(object):
"""
TFTP server configuration commands
.. attribute:: udp
UDP details
**type**\: :py:class:`Udp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp.Udp>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.udp = None
class Udp(object):
"""
UDP details
.. attribute:: access_list_name
Access list
**type**\: str
.. attribute:: dscp_value
Set IP DSCP (DiffServ CodePoint) for TFTP Server Packets
**type**\: int
**range:** \-2147483648..2147483647
.. attribute:: home_directory
Specify device name where file is read from (e .g. flash\:)
**type**\: str
**mandatory**\: True
.. attribute:: maximum_server
Set number of allowable servers, 0 for no\-limit
**type**\: int
**range:** 0..2147483647
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_list_name = None
self.dscp_value = None
self.home_directory = None
self.maximum_server = None
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:udp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_list_name is not None:
return True
if self.dscp_value is not None:
return True
if self.home_directory is not None:
return True
if self.maximum_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp.Udp']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:tftp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.udp is not None and self.udp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv4.Tftp']['meta_info']
@property
def _common_path(self):
if self.parent is None:
raise YPYModelError('parent is not set . Cannot derive path.')
return self.parent._common_path +'/Cisco-IOS-XR-ip-tcp-cfg:ipv4'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.telnet is not None and self.telnet._has_data():
return True
if self.tftp is not None and self.tftp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf.Ipv4']['meta_info']
@property
def _common_path(self):
if self.vrf_name is None:
raise YPYModelError('Key property vrf_name is None')
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:vrfs/Cisco-IOS-XR-ip-tcp-cfg:vrf[Cisco-IOS-XR-ip-tcp-cfg:vrf-name = ' + str(self.vrf_name) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.vrf_name is not None:
return True
if self.ipv4 is not None and self.ipv4._has_data():
return True
if self.ipv6 is not None and self.ipv6._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs.Vrf']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:vrfs'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.vrf is not None:
for child_ref in self.vrf:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Vrfs']['meta_info']
class Ipv6(object):
"""
IPV6 related services
.. attribute:: small_servers
Describing IPV4 and IPV6 small servers
**type**\: :py:class:`SmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.small_servers = Ip.Cinetd.Services.Ipv6.SmallServers()
self.small_servers.parent = self
class SmallServers(object):
"""
Describing IPV4 and IPV6 small servers
.. attribute:: tcp_small_servers
Describing TCP related IPV4 and IPV6 small servers
**type**\: :py:class:`TcpSmallServers <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers>`
**presence node**\: True
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.tcp_small_servers = None
class TcpSmallServers(object):
"""
Describing TCP related IPV4 and IPV6 small
servers
.. attribute:: access_control_list_name
Access list
**type**\: str
.. attribute:: small_server
Set number of allowable TCP small servers, specify 0 for no\-limit
**type**\: int
**range:** \-2147483648..2147483647
**mandatory**\: True
.. attribute:: _is_presence
Is present if this instance represents presence container else not
**type**\: bool
This class is a :ref:`presence class<presence-class>`
"""
_prefix = 'ip-tcp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self._is_presence = True
self.access_control_list_name = None
self.small_server = None
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv6/Cisco-IOS-XR-ip-tcp-cfg:small-servers/Cisco-IOS-XR-ip-tcp-cfg:tcp-small-servers'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self._is_presence:
return True
if self.access_control_list_name is not None:
return True
if self.small_server is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv6.SmallServers.TcpSmallServers']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv6/Cisco-IOS-XR-ip-tcp-cfg:small-servers'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.tcp_small_servers is not None and self.tcp_small_servers._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv6.SmallServers']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services/Cisco-IOS-XR-ip-tcp-cfg:ipv6'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.small_servers is not None and self.small_servers._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services.Ipv6']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd/Cisco-IOS-XR-ip-tcp-cfg:services'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.ipv4 is not None and self.ipv4._has_data():
return True
if self.ipv6 is not None and self.ipv6._has_data():
return True
if self.vrfs is not None and self.vrfs._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd.Services']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-tcp-cfg:cinetd'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.services is not None and self.services._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.Cinetd']['meta_info']
class ForwardProtocol(object):
"""
Controls forwarding of physical and directed IP
broadcasts
.. attribute:: udp
Packets to a specific UDP port
**type**\: :py:class:`Udp <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol.Udp>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.udp = Ip.ForwardProtocol.Udp()
self.udp.parent = self
class Udp(object):
"""
Packets to a specific UDP port
.. attribute:: disable
Disable IP Forward Protocol UDP
**type**\: :py:class:`Empty<ydk.types.Empty>`
.. attribute:: ports
Port configuration
**type**\: :py:class:`Ports <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol.Udp.Ports>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.disable = None
self.ports = Ip.ForwardProtocol.Udp.Ports()
self.ports.parent = self
class Ports(object):
"""
Port configuration
.. attribute:: port
Well\-known ports are enabled by default and non well\-known ports are disabled by default. It is not allowed to configure the default
**type**\: list of :py:class:`Port <ydk.models.cisco_ios_xr.Cisco_IOS_XR_ip_tcp_cfg.Ip.ForwardProtocol.Udp.Ports.Port>`
"""
_prefix = 'ip-udp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.port = YList()
self.port.parent = self
self.port.name = 'port'
class Port(object):
"""
Well\-known ports are enabled by default and
non well\-known ports are disabled by default.
It is not allowed to configure the default.
.. attribute:: port_id <key>
Port number
**type**\: int
**range:** 1..65535
.. attribute:: enable
Specify 'false' to disable well\-known ports Domain (53), TFTP (69), NameServer (42), TACACS (49), NetBiosNameService (137), or NetBiosDatagramService (138). Specify 'true' to enable non well\-known ports
**type**\: bool
**mandatory**\: True
"""
_prefix = 'ip-udp-cfg'
_revision = '2016-02-26'
def __init__(self):
self.parent = None
self.port_id = None
self.enable = None
@property
def _common_path(self):
if self.port_id is None:
raise YPYModelError('Key property port_id is None')
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol/Cisco-IOS-XR-ip-udp-cfg:udp/Cisco-IOS-XR-ip-udp-cfg:ports/Cisco-IOS-XR-ip-udp-cfg:port[Cisco-IOS-XR-ip-udp-cfg:port-id = ' + str(self.port_id) + ']'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.port_id is not None:
return True
if self.enable is not None:
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.ForwardProtocol.Udp.Ports.Port']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol/Cisco-IOS-XR-ip-udp-cfg:udp/Cisco-IOS-XR-ip-udp-cfg:ports'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.port is not None:
for child_ref in self.port:
if child_ref._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.ForwardProtocol.Udp.Ports']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol/Cisco-IOS-XR-ip-udp-cfg:udp'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.disable is not None:
return True
if self.ports is not None and self.ports._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.ForwardProtocol.Udp']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip/Cisco-IOS-XR-ip-udp-cfg:forward-protocol'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.udp is not None and self.udp._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip.ForwardProtocol']['meta_info']
@property
def _common_path(self):
return '/Cisco-IOS-XR-ip-tcp-cfg:ip'
def is_config(self):
''' Returns True if this instance represents config data else returns False '''
return True
def _has_data(self):
if not self.is_config():
return False
if self.cinetd is not None and self.cinetd._has_data():
return True
if self.forward_protocol is not None and self.forward_protocol._has_data():
return True
return False
@staticmethod
def _meta_info():
from ydk.models.cisco_ios_xr._meta import _Cisco_IOS_XR_ip_tcp_cfg as meta
return meta._meta_table['Ip']['meta_info']
| 37.048021 | 249 | 0.424123 | 6,384 | 70,206 | 4.456297 | 0.039787 | 0.056803 | 0.071004 | 0.06074 | 0.872509 | 0.854652 | 0.837393 | 0.818201 | 0.804773 | 0.798692 | 0 | 0.017044 | 0.503604 | 70,206 | 1,894 | 250 | 37.067582 | 0.799283 | 0.226491 | 0 | 0.807598 | 0 | 0.022059 | 0.1109 | 0.078214 | 0 | 0 | 0 | 0 | 0 | 1 | 0.183824 | false | 0 | 0.042892 | 0.022059 | 0.544118 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 9 |
a3cd9f89ea3b4451de7b81e145fa4a9a1e084e29 | 8,773 | py | Python | _site/tomat/apps/users/migrations/0001_initial.py | Lisaveta-K/lisaveta-k.github.io | 96306c4d2634d62e6d0ac504aee8ca91f8b3de11 | [
"MIT"
] | null | null | null | _site/tomat/apps/users/migrations/0001_initial.py | Lisaveta-K/lisaveta-k.github.io | 96306c4d2634d62e6d0ac504aee8ca91f8b3de11 | [
"MIT"
] | null | null | null | _site/tomat/apps/users/migrations/0001_initial.py | Lisaveta-K/lisaveta-k.github.io | 96306c4d2634d62e6d0ac504aee8ca91f8b3de11 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'User'
db.create_table(u'users_user', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('password', self.gf('django.db.models.fields.CharField')(max_length=128)),
('last_login', self.gf('django.db.models.fields.DateTimeField')(default=datetime.datetime.now)),
('email', self.gf('django.db.models.fields.EmailField')(unique=True, max_length=75, db_index=True)),
('is_active', self.gf('django.db.models.fields.BooleanField')(default=False, db_index=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('phone', self.gf('django.db.models.fields.CharField')(max_length=50, blank=True)),
('birthday', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
('status', self.gf('django.db.models.fields.PositiveSmallIntegerField')(default=1, db_index=True)),
))
db.send_create_signal(u'users', ['User'])
# Adding model 'Country'
db.create_table(u'users_country', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('title', self.gf('django.db.models.fields.CharField')(max_length=50)),
))
db.send_create_signal(u'users', ['Country'])
# Adding model 'Region'
db.create_table(u'users_region', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('country', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.Country'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal(u'users', ['Region'])
# Adding model 'City'
db.create_table(u'users_city', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('region', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.Region'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal(u'users', ['City'])
# Adding model 'Address'
db.create_table(u'users_address', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(related_name='addresses', to=orm['users.User'])),
('city', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('postal_code', self.gf('django.db.models.fields.CharField')(max_length=6, blank=True)),
('street', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('house', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('flat', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('original_string', self.gf('django.db.models.fields.TextField')(blank=True)),
('receiver_title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('email', self.gf('django.db.models.fields.EmailField')(max_length=75, blank=True)),
('phone', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
))
db.send_create_signal(u'users', ['Address'])
# Adding model 'Company'
db.create_table(u'users_company', (
(u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.OneToOneField')(related_name='company', unique=True, to=orm['users.User'])),
('title', self.gf('django.db.models.fields.CharField')(max_length=255)),
('city', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)),
('industry', self.gf('django.db.models.fields.CharField')(max_length=255)),
('phone', self.gf('django.db.models.fields.CharField')(max_length=255)),
))
db.send_create_signal(u'users', ['Company'])
def backwards(self, orm):
# Deleting model 'User'
db.delete_table(u'users_user')
# Deleting model 'Country'
db.delete_table(u'users_country')
# Deleting model 'Region'
db.delete_table(u'users_region')
# Deleting model 'City'
db.delete_table(u'users_city')
# Deleting model 'Address'
db.delete_table(u'users_address')
# Deleting model 'Company'
db.delete_table(u'users_company')
models = {
u'users.address': {
'Meta': {'object_name': 'Address'},
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'flat': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'house': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'original_string': ('django.db.models.fields.TextField', [], {'blank': 'True'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'postal_code': ('django.db.models.fields.CharField', [], {'max_length': '6', 'blank': 'True'}),
'receiver_title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'street': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'addresses'", 'to': u"orm['users.User']"})
},
u'users.city': {
'Meta': {'object_name': 'City'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'region': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.Region']"}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'users.company': {
'Meta': {'object_name': 'Company'},
'city': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'industry': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'company'", 'unique': 'True', 'to': u"orm['users.User']"})
},
u'users.country': {
'Meta': {'object_name': 'Country'},
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
u'users.region': {
'Meta': {'object_name': 'Region'},
'country': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['users.Country']"}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
u'users.user': {
'Meta': {'object_name': 'User'},
'birthday': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'email': ('django.db.models.fields.EmailField', [], {'unique': 'True', 'max_length': '75', 'db_index': 'True'}),
u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'phone': ('django.db.models.fields.CharField', [], {'max_length': '50', 'blank': 'True'}),
'status': ('django.db.models.fields.PositiveSmallIntegerField', [], {'default': '1', 'db_index': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'})
}
}
complete_apps = ['users'] | 58.099338 | 150 | 0.582925 | 1,025 | 8,773 | 4.879024 | 0.090732 | 0.110378 | 0.190362 | 0.271946 | 0.823835 | 0.778244 | 0.765847 | 0.733453 | 0.716857 | 0.625675 | 0 | 0.015104 | 0.200046 | 8,773 | 151 | 151 | 58.099338 | 0.697492 | 0.033626 | 0 | 0.225 | 0 | 0 | 0.461548 | 0.282693 | 0 | 0 | 0 | 0 | 0 | 1 | 0.016667 | false | 0.016667 | 0.033333 | 0 | 0.075 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
a3fbb3813d7a72e684fbdce0a77269730123ad65 | 107 | py | Python | tests/end2end/test_synthetic.py | Delaunay/Ranked | 287940019c3baf233fcc7b5d341f4ed8a0fdac6d | [
"BSD-3-Clause"
] | null | null | null | tests/end2end/test_synthetic.py | Delaunay/Ranked | 287940019c3baf233fcc7b5d341f4ed8a0fdac6d | [
"BSD-3-Clause"
] | 3 | 2022-03-13T02:53:06.000Z | 2022-03-19T19:15:16.000Z | tests/end2end/test_synthetic.py | Delaunay/Ranked | 287940019c3baf233fcc7b5d341f4ed8a0fdac6d | [
"BSD-3-Clause"
] | null | null | null | from ranked.simulation import synthetic_main
def test_synthetic_matches():
synthetic_main(20, 5, 10)
| 17.833333 | 44 | 0.785047 | 15 | 107 | 5.333333 | 0.8 | 0.325 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.054348 | 0.140187 | 107 | 5 | 45 | 21.4 | 0.815217 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
430c3b638887812821b52289b42030e00c81ba1f | 126 | py | Python | clx/xms/__init__.py | linhuiwzqu/clxcommunications | 5f5fe593402fdb014c17fa5ef200ee9b39d42caf | [
"Apache-2.0"
] | 3 | 2018-01-23T14:18:25.000Z | 2019-02-12T07:35:37.000Z | clx/xms/__init__.py | linhuiwzqu/clxcommunications | 5f5fe593402fdb014c17fa5ef200ee9b39d42caf | [
"Apache-2.0"
] | 3 | 2017-01-20T08:23:05.000Z | 2017-01-20T10:38:10.000Z | clx/xms/__init__.py | linhuiwzqu/clxcommunications | 5f5fe593402fdb014c17fa5ef200ee9b39d42caf | [
"Apache-2.0"
] | 2 | 2019-03-07T18:33:52.000Z | 2021-06-24T01:23:03.000Z | # -*- coding: utf-8 -*-
"""The ``clx.xms`` package.
"""
from clx.xms.exceptions import *
from clx.xms.client import Client
| 14 | 33 | 0.634921 | 18 | 126 | 4.444444 | 0.611111 | 0.225 | 0.25 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.009434 | 0.15873 | 126 | 8 | 34 | 15.75 | 0.745283 | 0.373016 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
432307055d4dca0a91aa9140a658810232fbd644 | 110 | py | Python | kageku/__init__.py | lucaspellegrinelli/kugoku-ai | 7ccd4225d1348c3c894c48251ad85798d03776c1 | [
"MIT"
] | null | null | null | kageku/__init__.py | lucaspellegrinelli/kugoku-ai | 7ccd4225d1348c3c894c48251ad85798d03776c1 | [
"MIT"
] | null | null | null | kageku/__init__.py | lucaspellegrinelli/kugoku-ai | 7ccd4225d1348c3c894c48251ad85798d03776c1 | [
"MIT"
] | null | null | null | from kageku.flags import *
from kageku.board import *
from kageku.action import *
from kageku.consts import *
| 22 | 27 | 0.781818 | 16 | 110 | 5.375 | 0.4375 | 0.465116 | 0.55814 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.145455 | 110 | 4 | 28 | 27.5 | 0.914894 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
4a5bfdbacf299d63d133aef8f639042733184d8a | 2,101 | py | Python | Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/linalg/__init__.py | Con-Mi/lambda-packs | b23a8464abdd88050b83310e1d0e99c54dac28ab | [
"MIT"
] | 3 | 2019-04-01T11:03:04.000Z | 2019-12-31T02:17:15.000Z | Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/linalg/__init__.py | Con-Mi/lambda-packs | b23a8464abdd88050b83310e1d0e99c54dac28ab | [
"MIT"
] | 1 | 2021-04-15T18:46:45.000Z | 2021-04-15T18:46:45.000Z | Keras_tensorflow_nightly/source2.7/tensorflow/tools/api/generator/api/linalg/__init__.py | Con-Mi/lambda-packs | b23a8464abdd88050b83310e1d0e99c54dac28ab | [
"MIT"
] | 1 | 2021-09-23T13:43:07.000Z | 2021-09-23T13:43:07.000Z | """Imports for Python API.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.python import cholesky
from tensorflow.python import cholesky_solve
from tensorflow.python import einsum
from tensorflow.python import eye
from tensorflow.python import matrix_band_part as band_part
from tensorflow.python import matrix_determinant as det
from tensorflow.python import matrix_diag as diag
from tensorflow.python import matrix_diag_part as diag_part
from tensorflow.python import matrix_inverse as inv
from tensorflow.python import matrix_set_diag as set_diag
from tensorflow.python import matrix_solve as solve
from tensorflow.python import matrix_solve_ls as lstsq
from tensorflow.python import matrix_transpose as transpose
from tensorflow.python import matrix_triangular_solve as triangular_solve
from tensorflow.python import norm
from tensorflow.python import qr
from tensorflow.python import self_adjoint_eig as eigh
from tensorflow.python import self_adjoint_eigvals as eigvalsh
from tensorflow.python import svd
from tensorflow.python import tensordot
from tensorflow.python import trace
from tensorflow.python.ops.gen_linalg_ops import log_matrix_determinant as slogdet
from tensorflow.python.ops.gen_linalg_ops import matrix_exponential as expm
from tensorflow.python.ops.gen_linalg_ops import matrix_logarithm as logm
from tensorflow.python.ops.linalg.linalg import LinearOperator
from tensorflow.python.ops.linalg.linalg import LinearOperatorComposition
from tensorflow.python.ops.linalg.linalg import LinearOperatorDiag
from tensorflow.python.ops.linalg.linalg import LinearOperatorFullMatrix
from tensorflow.python.ops.linalg.linalg import LinearOperatorIdentity
from tensorflow.python.ops.linalg.linalg import LinearOperatorLowRankUpdate
from tensorflow.python.ops.linalg.linalg import LinearOperatorLowerTriangular
from tensorflow.python.ops.linalg.linalg import LinearOperatorScaledIdentity
from tensorflow.python.ops.linalg.linalg import adjoint
from tensorflow.python.ops.linalg.linalg import logdet | 53.871795 | 82 | 0.871966 | 293 | 2,101 | 6.129693 | 0.232082 | 0.265033 | 0.378619 | 0.304009 | 0.616927 | 0.47049 | 0.303452 | 0.075167 | 0.052339 | 0 | 0 | 0 | 0.087101 | 2,101 | 39 | 83 | 53.871795 | 0.936392 | 0.068063 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
4a9f0159904322564849efb7179c5f0824aa5e6a | 46,957 | py | Python | nova/tests/unit/objects/test_service.py | bopopescu/nova-token | ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2 | [
"Apache-2.0"
] | null | null | null | nova/tests/unit/objects/test_service.py | bopopescu/nova-token | ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2 | [
"Apache-2.0"
] | null | null | null | nova/tests/unit/objects/test_service.py | bopopescu/nova-token | ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2 | [
"Apache-2.0"
] | 2 | 2017-07-20T17:31:34.000Z | 2020-07-24T02:42:19.000Z | begin_unit
comment|'# Copyright 2013 IBM Corp.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'# a copy of the License at'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# http://www.apache.org/licenses/LICENSE-2.0'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Unless required by applicable law or agreed to in writing, software'
nl|'\n'
comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT'
nl|'\n'
comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the'
nl|'\n'
comment|'# License for the specific language governing permissions and limitations'
nl|'\n'
comment|'# under the License.'
nl|'\n'
nl|'\n'
name|'import'
name|'mock'
newline|'\n'
name|'from'
name|'oslo_utils'
name|'import'
name|'timeutils'
newline|'\n'
name|'from'
name|'oslo_versionedobjects'
name|'import'
name|'base'
name|'as'
name|'ovo_base'
newline|'\n'
name|'from'
name|'oslo_versionedobjects'
name|'import'
name|'exception'
name|'as'
name|'ovo_exc'
newline|'\n'
nl|'\n'
name|'from'
name|'nova'
op|'.'
name|'compute'
name|'import'
name|'manager'
name|'as'
name|'compute_manager'
newline|'\n'
name|'from'
name|'nova'
name|'import'
name|'context'
newline|'\n'
name|'from'
name|'nova'
name|'import'
name|'db'
newline|'\n'
name|'from'
name|'nova'
name|'import'
name|'exception'
newline|'\n'
name|'from'
name|'nova'
name|'import'
name|'objects'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'objects'
name|'import'
name|'aggregate'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'objects'
name|'import'
name|'fields'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'objects'
name|'import'
name|'service'
newline|'\n'
name|'from'
name|'nova'
name|'import'
name|'test'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'tests'
op|'.'
name|'unit'
op|'.'
name|'objects'
name|'import'
name|'test_compute_node'
newline|'\n'
name|'from'
name|'nova'
op|'.'
name|'tests'
op|'.'
name|'unit'
op|'.'
name|'objects'
name|'import'
name|'test_objects'
newline|'\n'
nl|'\n'
DECL|variable|NOW
name|'NOW'
op|'='
name|'timeutils'
op|'.'
name|'utcnow'
op|'('
op|')'
op|'.'
name|'replace'
op|'('
name|'microsecond'
op|'='
number|'0'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|function|_fake_service
name|'def'
name|'_fake_service'
op|'('
op|'**'
name|'kwargs'
op|')'
op|':'
newline|'\n'
indent|' '
name|'fake_service'
op|'='
op|'{'
nl|'\n'
string|"'created_at'"
op|':'
name|'NOW'
op|','
nl|'\n'
string|"'updated_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted_at'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'deleted'"
op|':'
name|'False'
op|','
nl|'\n'
string|"'id'"
op|':'
number|'123'
op|','
nl|'\n'
string|"'host'"
op|':'
string|"'fake-host'"
op|','
nl|'\n'
string|"'binary'"
op|':'
string|"'nova-fake'"
op|','
nl|'\n'
string|"'topic'"
op|':'
string|"'fake-service-topic'"
op|','
nl|'\n'
string|"'report_count'"
op|':'
number|'1'
op|','
nl|'\n'
string|"'forced_down'"
op|':'
name|'False'
op|','
nl|'\n'
string|"'disabled'"
op|':'
name|'False'
op|','
nl|'\n'
string|"'disabled_reason'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'last_seen_up'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'version'"
op|':'
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|','
nl|'\n'
op|'}'
newline|'\n'
name|'fake_service'
op|'.'
name|'update'
op|'('
name|'kwargs'
op|')'
newline|'\n'
name|'return'
name|'fake_service'
newline|'\n'
nl|'\n'
DECL|variable|fake_service
dedent|''
name|'fake_service'
op|'='
name|'_fake_service'
op|'('
op|')'
newline|'\n'
nl|'\n'
DECL|variable|OPTIONAL
name|'OPTIONAL'
op|'='
op|'['
string|"'availability_zone'"
op|','
string|"'compute_node'"
op|']'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|class|_TestServiceObject
name|'class'
name|'_TestServiceObject'
op|'('
name|'object'
op|')'
op|':'
newline|'\n'
DECL|member|supported_hv_specs_comparator
indent|' '
name|'def'
name|'supported_hv_specs_comparator'
op|'('
name|'self'
op|','
name|'expected'
op|','
name|'obj_val'
op|')'
op|':'
newline|'\n'
indent|' '
name|'obj_val'
op|'='
op|'['
name|'inst'
op|'.'
name|'to_list'
op|'('
op|')'
name|'for'
name|'inst'
name|'in'
name|'obj_val'
op|']'
newline|'\n'
name|'self'
op|'.'
name|'assertJsonEqual'
op|'('
name|'expected'
op|','
name|'obj_val'
op|')'
newline|'\n'
nl|'\n'
DECL|member|pci_device_pools_comparator
dedent|''
name|'def'
name|'pci_device_pools_comparator'
op|'('
name|'self'
op|','
name|'expected'
op|','
name|'obj_val'
op|')'
op|':'
newline|'\n'
indent|' '
name|'obj_val'
op|'='
name|'obj_val'
op|'.'
name|'obj_to_primitive'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertJsonEqual'
op|'('
name|'expected'
op|','
name|'obj_val'
op|')'
newline|'\n'
nl|'\n'
DECL|member|comparators
dedent|''
name|'def'
name|'comparators'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
op|'{'
string|"'stats'"
op|':'
name|'self'
op|'.'
name|'assertJsonEqual'
op|','
nl|'\n'
string|"'host_ip'"
op|':'
name|'self'
op|'.'
name|'assertJsonEqual'
op|','
nl|'\n'
string|"'supported_hv_specs'"
op|':'
name|'self'
op|'.'
name|'supported_hv_specs_comparator'
op|','
nl|'\n'
string|"'pci_device_pools'"
op|':'
name|'self'
op|'.'
name|'pci_device_pools_comparator'
op|'}'
newline|'\n'
nl|'\n'
DECL|member|subs
dedent|''
name|'def'
name|'subs'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'return'
op|'{'
string|"'supported_hv_specs'"
op|':'
string|"'supported_instances'"
op|','
nl|'\n'
string|"'pci_device_pools'"
op|':'
string|"'pci_stats'"
op|'}'
newline|'\n'
nl|'\n'
DECL|member|_test_query
dedent|''
name|'def'
name|'_test_query'
op|'('
name|'self'
op|','
name|'db_method'
op|','
name|'obj_method'
op|','
op|'*'
name|'args'
op|','
op|'**'
name|'kwargs'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
name|'db_method'
op|')'
newline|'\n'
name|'db_exception'
op|'='
name|'kwargs'
op|'.'
name|'pop'
op|'('
string|"'db_exception'"
op|','
name|'None'
op|')'
newline|'\n'
name|'if'
name|'db_exception'
op|':'
newline|'\n'
indent|' '
name|'getattr'
op|'('
name|'db'
op|','
name|'db_method'
op|')'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'*'
name|'args'
op|','
op|'**'
name|'kwargs'
op|')'
op|'.'
name|'AndRaise'
op|'('
nl|'\n'
name|'db_exception'
op|')'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'getattr'
op|'('
name|'db'
op|','
name|'db_method'
op|')'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'*'
name|'args'
op|','
op|'**'
name|'kwargs'
op|')'
op|'.'
name|'AndReturn'
op|'('
nl|'\n'
name|'fake_service'
op|')'
newline|'\n'
dedent|''
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'obj'
op|'='
name|'getattr'
op|'('
name|'service'
op|'.'
name|'Service'
op|','
name|'obj_method'
op|')'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'*'
name|'args'
op|','
nl|'\n'
op|'**'
name|'kwargs'
op|')'
newline|'\n'
name|'if'
name|'db_exception'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'assertIsNone'
op|'('
name|'obj'
op|')'
newline|'\n'
dedent|''
name|'else'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'compare_obj'
op|'('
name|'obj'
op|','
name|'fake_service'
op|','
name|'allow_missing'
op|'='
name|'OPTIONAL'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_id
dedent|''
dedent|''
name|'def'
name|'test_get_by_id'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_query'
op|'('
string|"'service_get'"
op|','
string|"'get_by_id'"
op|','
number|'123'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_host_and_topic
dedent|''
name|'def'
name|'test_get_by_host_and_topic'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_query'
op|'('
string|"'service_get_by_host_and_topic'"
op|','
nl|'\n'
string|"'get_by_host_and_topic'"
op|','
string|"'fake-host'"
op|','
string|"'fake-topic'"
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_host_and_binary
dedent|''
name|'def'
name|'test_get_by_host_and_binary'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_query'
op|'('
string|"'service_get_by_host_and_binary'"
op|','
nl|'\n'
string|"'get_by_host_and_binary'"
op|','
string|"'fake-host'"
op|','
string|"'fake-binary'"
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_host_and_binary_raises
dedent|''
name|'def'
name|'test_get_by_host_and_binary_raises'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_query'
op|'('
string|"'service_get_by_host_and_binary'"
op|','
nl|'\n'
string|"'get_by_host_and_binary'"
op|','
string|"'fake-host'"
op|','
string|"'fake-binary'"
op|','
nl|'\n'
name|'db_exception'
op|'='
name|'exception'
op|'.'
name|'HostBinaryNotFound'
op|'('
nl|'\n'
name|'host'
op|'='
string|"'fake-host'"
op|','
name|'binary'
op|'='
string|"'fake-binary'"
op|')'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_compute_host
dedent|''
name|'def'
name|'test_get_by_compute_host'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_query'
op|'('
string|"'service_get_by_compute_host'"
op|','
string|"'get_by_compute_host'"
op|','
nl|'\n'
string|"'fake-host'"
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_args
dedent|''
name|'def'
name|'test_get_by_args'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_query'
op|'('
string|"'service_get_by_host_and_binary'"
op|','
string|"'get_by_args'"
op|','
nl|'\n'
string|"'fake-host'"
op|','
string|"'fake-binary'"
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_create
dedent|''
name|'def'
name|'test_create'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_create'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_create'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'{'
string|"'host'"
op|':'
string|"'fake-host'"
op|','
nl|'\n'
string|"'version'"
op|':'
name|'fake_service'
op|'['
string|"'version'"
op|']'
op|'}'
nl|'\n'
op|')'
op|'.'
name|'AndReturn'
op|'('
name|'fake_service'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'host'
op|'='
string|"'fake-host'"
newline|'\n'
name|'service_obj'
op|'.'
name|'create'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'fake_service'
op|'['
string|"'id'"
op|']'
op|','
name|'service_obj'
op|'.'
name|'id'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|','
name|'service_obj'
op|'.'
name|'version'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_recreate_fails
dedent|''
name|'def'
name|'test_recreate_fails'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_create'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_create'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'{'
string|"'host'"
op|':'
string|"'fake-host'"
op|','
nl|'\n'
string|"'version'"
op|':'
name|'fake_service'
op|'['
string|"'version'"
op|']'
op|'}'
nl|'\n'
op|')'
op|'.'
name|'AndReturn'
op|'('
name|'fake_service'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'host'
op|'='
string|"'fake-host'"
newline|'\n'
name|'service_obj'
op|'.'
name|'create'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertRaises'
op|'('
name|'exception'
op|'.'
name|'ObjectActionError'
op|','
name|'service_obj'
op|'.'
name|'create'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_save
dedent|''
name|'def'
name|'test_save'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_update'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_update'
op|'('
name|'self'
op|'.'
name|'context'
op|','
number|'123'
op|','
nl|'\n'
op|'{'
string|"'host'"
op|':'
string|"'fake-host'"
op|','
nl|'\n'
string|"'version'"
op|':'
name|'fake_service'
op|'['
string|"'version'"
op|']'
op|'}'
nl|'\n'
op|')'
op|'.'
name|'AndReturn'
op|'('
name|'fake_service'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'id'
op|'='
number|'123'
newline|'\n'
name|'service_obj'
op|'.'
name|'host'
op|'='
string|"'fake-host'"
newline|'\n'
name|'service_obj'
op|'.'
name|'save'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|','
name|'service_obj'
op|'.'
name|'version'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'.'
name|'object'
op|'('
name|'db'
op|','
string|"'service_create'"
op|','
nl|'\n'
name|'return_value'
op|'='
name|'fake_service'
op|')'
newline|'\n'
DECL|member|test_set_id_failure
name|'def'
name|'test_set_id_failure'
op|'('
name|'self'
op|','
name|'db_mock'
op|')'
op|':'
newline|'\n'
indent|' '
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
name|'binary'
op|'='
string|"'nova-compute'"
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'create'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertRaises'
op|'('
name|'ovo_exc'
op|'.'
name|'ReadOnlyFieldError'
op|','
name|'setattr'
op|','
nl|'\n'
name|'service_obj'
op|','
string|"'id'"
op|','
number|'124'
op|')'
newline|'\n'
nl|'\n'
DECL|member|_test_destroy
dedent|''
name|'def'
name|'_test_destroy'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_destroy'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_destroy'
op|'('
name|'self'
op|'.'
name|'context'
op|','
number|'123'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'id'
op|'='
number|'123'
newline|'\n'
name|'service_obj'
op|'.'
name|'destroy'
op|'('
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_destroy
dedent|''
name|'def'
name|'test_destroy'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
comment|'# The test harness needs db.service_destroy to work,'
nl|'\n'
comment|"# so avoid leaving it broken here after we're done"
nl|'\n'
indent|' '
name|'orig_service_destroy'
op|'='
name|'db'
op|'.'
name|'service_destroy'
newline|'\n'
name|'try'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'_test_destroy'
op|'('
op|')'
newline|'\n'
dedent|''
name|'finally'
op|':'
newline|'\n'
indent|' '
name|'db'
op|'.'
name|'service_destroy'
op|'='
name|'orig_service_destroy'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_topic
dedent|''
dedent|''
name|'def'
name|'test_get_by_topic'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_get_all_by_topic'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_get_all_by_topic'
op|'('
name|'self'
op|'.'
name|'context'
op|','
string|"'fake-topic'"
op|')'
op|'.'
name|'AndReturn'
op|'('
nl|'\n'
op|'['
name|'fake_service'
op|']'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_by_topic'
op|'('
name|'self'
op|'.'
name|'context'
op|','
string|"'fake-topic'"
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'compare_obj'
op|'('
name|'services'
op|'['
number|'0'
op|']'
op|','
name|'fake_service'
op|','
name|'allow_missing'
op|'='
name|'OPTIONAL'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_all_by_binary'"
op|')'
newline|'\n'
DECL|member|test_get_by_binary
name|'def'
name|'test_get_by_binary'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_get'
op|'.'
name|'return_value'
op|'='
op|'['
name|'fake_service'
op|']'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_by_binary'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'fake-binary'"
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'fake-binary'"
op|','
nl|'\n'
name|'include_disabled'
op|'='
name|'False'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_all_by_binary'"
op|')'
newline|'\n'
DECL|member|test_get_by_binary_disabled
name|'def'
name|'test_get_by_binary_disabled'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_get'
op|'.'
name|'return_value'
op|'='
op|'['
name|'_fake_service'
op|'('
name|'disabled'
op|'='
name|'True'
op|')'
op|']'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_by_binary'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'fake-binary'"
op|','
nl|'\n'
name|'include_disabled'
op|'='
name|'True'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'fake-binary'"
op|','
nl|'\n'
name|'include_disabled'
op|'='
name|'True'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_all_by_binary'"
op|')'
newline|'\n'
DECL|member|test_get_by_binary_both
name|'def'
name|'test_get_by_binary_both'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_get'
op|'.'
name|'return_value'
op|'='
op|'['
name|'_fake_service'
op|'('
op|')'
op|','
nl|'\n'
name|'_fake_service'
op|'('
name|'disabled'
op|'='
name|'True'
op|')'
op|']'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_by_binary'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'fake-binary'"
op|','
nl|'\n'
name|'include_disabled'
op|'='
name|'True'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'2'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'fake-binary'"
op|','
nl|'\n'
name|'include_disabled'
op|'='
name|'True'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_by_host
dedent|''
name|'def'
name|'test_get_by_host'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_get_all_by_host'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_get_all_by_host'
op|'('
name|'self'
op|'.'
name|'context'
op|','
string|"'fake-host'"
op|')'
op|'.'
name|'AndReturn'
op|'('
nl|'\n'
op|'['
name|'fake_service'
op|']'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_by_host'
op|'('
name|'self'
op|'.'
name|'context'
op|','
string|"'fake-host'"
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'compare_obj'
op|'('
name|'services'
op|'['
number|'0'
op|']'
op|','
name|'fake_service'
op|','
name|'allow_missing'
op|'='
name|'OPTIONAL'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_all
dedent|''
name|'def'
name|'test_get_all'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_get_all'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_get_all'
op|'('
name|'self'
op|'.'
name|'context'
op|','
name|'disabled'
op|'='
name|'False'
op|')'
op|'.'
name|'AndReturn'
op|'('
nl|'\n'
op|'['
name|'fake_service'
op|']'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_all'
op|'('
name|'self'
op|'.'
name|'context'
op|','
name|'disabled'
op|'='
name|'False'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'compare_obj'
op|'('
name|'services'
op|'['
number|'0'
op|']'
op|','
name|'fake_service'
op|','
name|'allow_missing'
op|'='
name|'OPTIONAL'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_get_all_with_az
dedent|''
name|'def'
name|'test_get_all_with_az'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'db'
op|','
string|"'service_get_all'"
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'aggregate'
op|'.'
name|'AggregateList'
op|','
nl|'\n'
string|"'get_by_metadata_key'"
op|')'
newline|'\n'
name|'db'
op|'.'
name|'service_get_all'
op|'('
name|'self'
op|'.'
name|'context'
op|','
name|'disabled'
op|'='
name|'None'
op|')'
op|'.'
name|'AndReturn'
op|'('
nl|'\n'
op|'['
name|'dict'
op|'('
name|'fake_service'
op|','
name|'topic'
op|'='
string|"'compute'"
op|')'
op|']'
op|')'
newline|'\n'
name|'agg'
op|'='
name|'aggregate'
op|'.'
name|'Aggregate'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|')'
newline|'\n'
name|'agg'
op|'.'
name|'name'
op|'='
string|"'foo'"
newline|'\n'
name|'agg'
op|'.'
name|'metadata'
op|'='
op|'{'
string|"'availability_zone'"
op|':'
string|"'test-az'"
op|'}'
newline|'\n'
name|'agg'
op|'.'
name|'create'
op|'('
op|')'
newline|'\n'
name|'agg'
op|'.'
name|'hosts'
op|'='
op|'['
name|'fake_service'
op|'['
string|"'host'"
op|']'
op|']'
newline|'\n'
name|'aggregate'
op|'.'
name|'AggregateList'
op|'.'
name|'get_by_metadata_key'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'availability_zone'"
op|','
name|'hosts'
op|'='
name|'set'
op|'('
name|'agg'
op|'.'
name|'hosts'
op|')'
op|')'
op|'.'
name|'AndReturn'
op|'('
op|'['
name|'agg'
op|']'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'services'
op|'='
name|'service'
op|'.'
name|'ServiceList'
op|'.'
name|'get_all'
op|'('
name|'self'
op|'.'
name|'context'
op|','
name|'set_zones'
op|'='
name|'True'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'len'
op|'('
name|'services'
op|')'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
string|"'test-az'"
op|','
name|'services'
op|'['
number|'0'
op|']'
op|'.'
name|'availability_zone'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_compute_node
dedent|''
name|'def'
name|'test_compute_node'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'fake_compute_node'
op|'='
name|'objects'
op|'.'
name|'ComputeNode'
op|'.'
name|'_from_db_object'
op|'('
nl|'\n'
name|'self'
op|'.'
name|'context'
op|','
name|'objects'
op|'.'
name|'ComputeNode'
op|'('
op|')'
op|','
nl|'\n'
name|'test_compute_node'
op|'.'
name|'fake_compute_node'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'StubOutWithMock'
op|'('
name|'objects'
op|'.'
name|'ComputeNodeList'
op|','
string|"'get_all_by_host'"
op|')'
newline|'\n'
name|'objects'
op|'.'
name|'ComputeNodeList'
op|'.'
name|'get_all_by_host'
op|'('
nl|'\n'
name|'self'
op|'.'
name|'context'
op|','
string|"'fake-host'"
op|')'
op|'.'
name|'AndReturn'
op|'('
nl|'\n'
op|'['
name|'fake_compute_node'
op|']'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'mox'
op|'.'
name|'ReplayAll'
op|'('
op|')'
newline|'\n'
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
name|'id'
op|'='
number|'123'
op|','
name|'host'
op|'='
string|'"fake-host"'
op|','
nl|'\n'
name|'binary'
op|'='
string|'"nova-compute"'
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'_context'
op|'='
name|'self'
op|'.'
name|'context'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'service_obj'
op|'.'
name|'compute_node'
op|','
nl|'\n'
name|'fake_compute_node'
op|')'
newline|'\n'
comment|"# Make sure it doesn't re-fetch this"
nl|'\n'
name|'service_obj'
op|'.'
name|'compute_node'
newline|'\n'
nl|'\n'
DECL|member|test_load_when_orphaned
dedent|''
name|'def'
name|'test_load_when_orphaned'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'service_obj'
op|'='
name|'service'
op|'.'
name|'Service'
op|'('
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'id'
op|'='
number|'123'
newline|'\n'
name|'self'
op|'.'
name|'assertRaises'
op|'('
name|'exception'
op|'.'
name|'OrphanedObjectError'
op|','
nl|'\n'
name|'getattr'
op|','
name|'service_obj'
op|','
string|"'compute_node'"
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'.'
name|'object'
op|'('
name|'objects'
op|'.'
name|'ComputeNodeList'
op|','
string|"'get_all_by_host'"
op|')'
newline|'\n'
DECL|member|test_obj_make_compatible_for_compute_node
name|'def'
name|'test_obj_make_compatible_for_compute_node'
op|'('
name|'self'
op|','
name|'get_all_by_host'
op|')'
op|':'
newline|'\n'
indent|' '
name|'service_obj'
op|'='
name|'objects'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|')'
newline|'\n'
name|'fake_service_dict'
op|'='
name|'fake_service'
op|'.'
name|'copy'
op|'('
op|')'
newline|'\n'
name|'fake_compute_obj'
op|'='
name|'objects'
op|'.'
name|'ComputeNode'
op|'('
name|'host'
op|'='
name|'fake_service'
op|'['
string|"'host'"
op|']'
op|','
nl|'\n'
name|'service_id'
op|'='
name|'fake_service'
op|'['
string|"'id'"
op|']'
op|')'
newline|'\n'
name|'get_all_by_host'
op|'.'
name|'return_value'
op|'='
op|'['
name|'fake_compute_obj'
op|']'
newline|'\n'
nl|'\n'
name|'versions'
op|'='
name|'ovo_base'
op|'.'
name|'obj_tree_get_versions'
op|'('
string|"'Service'"
op|')'
newline|'\n'
name|'versions'
op|'['
string|"'ComputeNode'"
op|']'
op|'='
string|"'1.10'"
newline|'\n'
name|'service_obj'
op|'.'
name|'obj_make_compatible_from_manifest'
op|'('
name|'fake_service_dict'
op|','
string|"'1.9'"
op|','
nl|'\n'
name|'versions'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
nl|'\n'
name|'fake_compute_obj'
op|'.'
name|'obj_to_primitive'
op|'('
name|'target_version'
op|'='
string|"'1.10'"
op|','
nl|'\n'
name|'version_manifest'
op|'='
name|'versions'
op|')'
op|','
nl|'\n'
name|'fake_service_dict'
op|'['
string|"'compute_node'"
op|']'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|')'
newline|'\n'
DECL|member|test_get_minimum_version_none
name|'def'
name|'test_get_minimum_version_none'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_get'
op|'.'
name|'return_value'
op|'='
name|'None'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'0'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'nova-compute'"
op|')'
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'['
string|"'nova-compute'"
op|']'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|')'
newline|'\n'
DECL|member|test_get_minimum_version
name|'def'
name|'test_get_minimum_version'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_get'
op|'.'
name|'return_value'
op|'='
op|'{'
string|"'nova-compute'"
op|':'
number|'123'
op|'}'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'123'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'nova-compute'"
op|')'
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'['
string|"'nova-compute'"
op|']'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|')'
newline|'\n'
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.objects.service.LOG'"
op|')'
newline|'\n'
DECL|member|test_get_minimum_version_checks_binary
name|'def'
name|'test_get_minimum_version_checks_binary'
op|'('
name|'self'
op|','
name|'mock_log'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_get'
op|'.'
name|'return_value'
op|'='
name|'None'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'0'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'nova-compute'"
op|')'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertFalse'
op|'('
name|'mock_log'
op|'.'
name|'warning'
op|'.'
name|'called'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertRaises'
op|'('
name|'exception'
op|'.'
name|'ObjectActionError'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version'
op|','
nl|'\n'
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'compute'"
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertTrue'
op|'('
name|'mock_log'
op|'.'
name|'warning'
op|'.'
name|'called'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|')'
newline|'\n'
DECL|member|test_get_minimum_version_with_caching
name|'def'
name|'test_get_minimum_version_with_caching'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'enable_min_version_cache'
op|'('
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'return_value'
op|'='
op|'{'
string|"'nova-compute'"
op|':'
number|'123'
op|'}'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'123'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'nova-compute'"
op|')'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
op|'{'
string|'"nova-compute"'
op|':'
number|'123'
op|'}'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'_MIN_VERSION_CACHE'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'123'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
string|"'nova-compute'"
op|')'
op|')'
newline|'\n'
name|'mock_get'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'context'
op|','
op|'['
string|"'nova-compute'"
op|']'
op|')'
newline|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'_SERVICE_VERSION_CACHING'
op|'='
name|'False'
newline|'\n'
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'clear_min_version_cache'
op|'('
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|')'
newline|'\n'
DECL|member|test_get_min_version_multiple_with_old
name|'def'
name|'test_get_min_version_multiple_with_old'
op|'('
name|'self'
op|','
name|'mock_gmv'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_gmv'
op|'.'
name|'return_value'
op|'='
op|'{'
string|"'nova-api'"
op|':'
name|'None'
op|','
nl|'\n'
string|"'nova-scheduler'"
op|':'
number|'2'
op|','
nl|'\n'
string|"'nova-conductor'"
op|':'
number|'3'
op|'}'
newline|'\n'
nl|'\n'
name|'binaries'
op|'='
op|'['
string|"'nova-api'"
op|','
string|"'nova-api'"
op|','
string|"'nova-conductor'"
op|','
nl|'\n'
string|"'nova-conductor'"
op|','
string|"'nova-api'"
op|']'
newline|'\n'
name|'minimum'
op|'='
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version_multi'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
name|'binaries'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'0'
op|','
name|'minimum'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|')'
newline|'\n'
DECL|member|test_get_min_version_multiple
name|'def'
name|'test_get_min_version_multiple'
op|'('
name|'self'
op|','
name|'mock_gmv'
op|')'
op|':'
newline|'\n'
indent|' '
name|'mock_gmv'
op|'.'
name|'return_value'
op|'='
op|'{'
string|"'nova-api'"
op|':'
number|'1'
op|','
nl|'\n'
string|"'nova-scheduler'"
op|':'
number|'2'
op|','
nl|'\n'
string|"'nova-conductor'"
op|':'
number|'3'
op|'}'
newline|'\n'
nl|'\n'
name|'binaries'
op|'='
op|'['
string|"'nova-api'"
op|','
string|"'nova-api'"
op|','
string|"'nova-conductor'"
op|','
nl|'\n'
string|"'nova-conductor'"
op|','
string|"'nova-api'"
op|']'
newline|'\n'
name|'minimum'
op|'='
name|'objects'
op|'.'
name|'Service'
op|'.'
name|'get_minimum_version_multi'
op|'('
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
name|'binaries'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
number|'1'
op|','
name|'minimum'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|','
nl|'\n'
name|'return_value'
op|'='
op|'{'
string|"'nova-compute'"
op|':'
number|'2'
op|'}'
op|')'
newline|'\n'
DECL|member|test_create_above_minimum
name|'def'
name|'test_create_above_minimum'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.objects.service.SERVICE_VERSION'"
op|','
nl|'\n'
name|'new'
op|'='
number|'3'
op|')'
op|':'
newline|'\n'
indent|' '
name|'objects'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
name|'binary'
op|'='
string|"'nova-compute'"
op|')'
op|'.'
name|'create'
op|'('
op|')'
newline|'\n'
nl|'\n'
dedent|''
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|','
nl|'\n'
name|'return_value'
op|'='
op|'{'
string|"'nova-compute'"
op|':'
number|'2'
op|'}'
op|')'
newline|'\n'
DECL|member|test_create_equal_to_minimum
name|'def'
name|'test_create_equal_to_minimum'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.objects.service.SERVICE_VERSION'"
op|','
nl|'\n'
name|'new'
op|'='
number|'2'
op|')'
op|':'
newline|'\n'
indent|' '
name|'objects'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
name|'binary'
op|'='
string|"'nova-compute'"
op|')'
op|'.'
name|'create'
op|'('
op|')'
newline|'\n'
nl|'\n'
dedent|''
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_get_minimum_version'"
op|','
nl|'\n'
name|'return_value'
op|'='
op|'{'
string|"'nova-compute'"
op|':'
number|'2'
op|'}'
op|')'
newline|'\n'
DECL|member|test_create_below_minimum
name|'def'
name|'test_create_below_minimum'
op|'('
name|'self'
op|','
name|'mock_get'
op|')'
op|':'
newline|'\n'
indent|' '
name|'with'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.objects.service.SERVICE_VERSION'"
op|','
nl|'\n'
name|'new'
op|'='
number|'1'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'assertRaises'
op|'('
name|'exception'
op|'.'
name|'ServiceTooOld'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'context'
op|','
nl|'\n'
name|'binary'
op|'='
string|"'nova-compute'"
op|','
nl|'\n'
op|')'
op|'.'
name|'create'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
dedent|''
dedent|''
dedent|''
name|'class'
name|'TestServiceObject'
op|'('
name|'test_objects'
op|'.'
name|'_LocalTest'
op|','
nl|'\n'
DECL|class|TestServiceObject
name|'_TestServiceObject'
op|')'
op|':'
newline|'\n'
indent|' '
name|'pass'
newline|'\n'
nl|'\n'
nl|'\n'
dedent|''
name|'class'
name|'TestRemoteServiceObject'
op|'('
name|'test_objects'
op|'.'
name|'_RemoteTest'
op|','
nl|'\n'
DECL|class|TestRemoteServiceObject
name|'_TestServiceObject'
op|')'
op|':'
newline|'\n'
indent|' '
name|'pass'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|class|TestServiceVersion
dedent|''
name|'class'
name|'TestServiceVersion'
op|'('
name|'test'
op|'.'
name|'TestCase'
op|')'
op|':'
newline|'\n'
DECL|member|setUp
indent|' '
name|'def'
name|'setUp'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'ctxt'
op|'='
name|'context'
op|'.'
name|'get_admin_context'
op|'('
op|')'
newline|'\n'
name|'super'
op|'('
name|'TestServiceVersion'
op|','
name|'self'
op|')'
op|'.'
name|'setUp'
op|'('
op|')'
newline|'\n'
nl|'\n'
DECL|member|_collect_things
dedent|''
name|'def'
name|'_collect_things'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'data'
op|'='
op|'{'
nl|'\n'
string|"'compute_rpc'"
op|':'
name|'compute_manager'
op|'.'
name|'ComputeManager'
op|'.'
name|'target'
op|'.'
name|'version'
op|','
nl|'\n'
op|'}'
newline|'\n'
name|'return'
name|'data'
newline|'\n'
nl|'\n'
DECL|member|test_version
dedent|''
name|'def'
name|'test_version'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'calculated'
op|'='
name|'self'
op|'.'
name|'_collect_things'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
nl|'\n'
name|'len'
op|'('
name|'service'
op|'.'
name|'SERVICE_VERSION_HISTORY'
op|')'
op|','
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|'+'
number|'1'
op|','
nl|'\n'
string|"'Service version %i has no history. Please update '"
nl|'\n'
string|"'nova.objects.service.SERVICE_VERSION_HISTORY '"
nl|'\n'
string|"'and add %s to it'"
op|'%'
op|'('
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|','
name|'repr'
op|'('
name|'calculated'
op|')'
op|')'
op|')'
newline|'\n'
name|'current'
op|'='
name|'service'
op|'.'
name|'SERVICE_VERSION_HISTORY'
op|'['
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|']'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
nl|'\n'
name|'current'
op|','
name|'calculated'
op|','
nl|'\n'
string|"'Changes detected that require a SERVICE_VERSION change. Please '"
nl|'\n'
string|"'increment nova.objects.service.SERVICE_VERSION, and make sure it'"
nl|'\n'
string|"'is equal to nova.compute.manager.ComputeManager.target.version.'"
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_version_in_init
dedent|''
name|'def'
name|'test_version_in_init'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'assertRaises'
op|'('
name|'exception'
op|'.'
name|'ObjectActionError'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|','
nl|'\n'
name|'version'
op|'='
number|'123'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_version_set_on_init
dedent|''
name|'def'
name|'test_version_set_on_init'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'service'
op|'.'
name|'SERVICE_VERSION'
op|','
nl|'\n'
name|'objects'
op|'.'
name|'Service'
op|'('
op|')'
op|'.'
name|'version'
op|')'
newline|'\n'
nl|'\n'
DECL|member|test_version_loaded_from_db
dedent|''
name|'def'
name|'test_version_loaded_from_db'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'fake_version'
op|'='
name|'fake_service'
op|'['
string|"'version'"
op|']'
op|'+'
number|'1'
newline|'\n'
name|'fake_different_service'
op|'='
name|'dict'
op|'('
name|'fake_service'
op|')'
newline|'\n'
name|'fake_different_service'
op|'['
string|"'version'"
op|']'
op|'='
name|'fake_version'
newline|'\n'
name|'obj'
op|'='
name|'objects'
op|'.'
name|'Service'
op|'('
op|')'
newline|'\n'
name|'obj'
op|'.'
name|'_from_db_object'
op|'('
name|'self'
op|'.'
name|'ctxt'
op|','
name|'obj'
op|','
name|'fake_different_service'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'fake_version'
op|','
name|'obj'
op|'.'
name|'version'
op|')'
newline|'\n'
nl|'\n'
nl|'\n'
DECL|class|TestServiceStatusNotification
dedent|''
dedent|''
name|'class'
name|'TestServiceStatusNotification'
op|'('
name|'test'
op|'.'
name|'TestCase'
op|')'
op|':'
newline|'\n'
DECL|member|setUp
indent|' '
name|'def'
name|'setUp'
op|'('
name|'self'
op|')'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'ctxt'
op|'='
name|'context'
op|'.'
name|'get_admin_context'
op|'('
op|')'
newline|'\n'
name|'super'
op|'('
name|'TestServiceStatusNotification'
op|','
name|'self'
op|')'
op|'.'
name|'setUp'
op|'('
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.objects.service.ServiceStatusNotification'"
op|')'
newline|'\n'
DECL|member|_verify_notification
name|'def'
name|'_verify_notification'
op|'('
name|'self'
op|','
name|'service_obj'
op|','
name|'mock_notification'
op|')'
op|':'
newline|'\n'
indent|' '
name|'service_obj'
op|'.'
name|'save'
op|'('
op|')'
newline|'\n'
nl|'\n'
name|'self'
op|'.'
name|'assertTrue'
op|'('
name|'mock_notification'
op|'.'
name|'called'
op|')'
newline|'\n'
nl|'\n'
name|'event_type'
op|'='
name|'mock_notification'
op|'.'
name|'call_args'
op|'['
number|'1'
op|']'
op|'['
string|"'event_type'"
op|']'
newline|'\n'
name|'priority'
op|'='
name|'mock_notification'
op|'.'
name|'call_args'
op|'['
number|'1'
op|']'
op|'['
string|"'priority'"
op|']'
newline|'\n'
name|'publisher'
op|'='
name|'mock_notification'
op|'.'
name|'call_args'
op|'['
number|'1'
op|']'
op|'['
string|"'publisher'"
op|']'
newline|'\n'
name|'payload'
op|'='
name|'mock_notification'
op|'.'
name|'call_args'
op|'['
number|'1'
op|']'
op|'['
string|"'payload'"
op|']'
newline|'\n'
nl|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'service_obj'
op|'.'
name|'host'
op|','
name|'publisher'
op|'.'
name|'host'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'service_obj'
op|'.'
name|'binary'
op|','
name|'publisher'
op|'.'
name|'binary'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'fields'
op|'.'
name|'NotificationPriority'
op|'.'
name|'INFO'
op|','
name|'priority'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
string|"'service'"
op|','
name|'event_type'
op|'.'
name|'object'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'fields'
op|'.'
name|'NotificationAction'
op|'.'
name|'UPDATE'
op|','
nl|'\n'
name|'event_type'
op|'.'
name|'action'
op|')'
newline|'\n'
name|'for'
name|'field'
name|'in'
name|'service'
op|'.'
name|'ServiceStatusPayload'
op|'.'
name|'SCHEMA'
op|':'
newline|'\n'
indent|' '
name|'if'
name|'field'
name|'in'
name|'fake_service'
op|':'
newline|'\n'
indent|' '
name|'self'
op|'.'
name|'assertEqual'
op|'('
name|'fake_service'
op|'['
name|'field'
op|']'
op|','
name|'getattr'
op|'('
name|'payload'
op|','
name|'field'
op|')'
op|')'
newline|'\n'
nl|'\n'
dedent|''
dedent|''
name|'mock_notification'
op|'.'
name|'return_value'
op|'.'
name|'emit'
op|'.'
name|'assert_called_once_with'
op|'('
name|'self'
op|'.'
name|'ctxt'
op|')'
newline|'\n'
nl|'\n'
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_update'"
op|')'
newline|'\n'
DECL|member|test_service_update_with_notification
name|'def'
name|'test_service_update_with_notification'
op|'('
name|'self'
op|','
name|'mock_db_service_update'
op|')'
op|':'
newline|'\n'
indent|' '
name|'service_obj'
op|'='
name|'objects'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'ctxt'
op|','
name|'id'
op|'='
name|'fake_service'
op|'['
string|"'id'"
op|']'
op|')'
newline|'\n'
name|'mock_db_service_update'
op|'.'
name|'return_value'
op|'='
name|'fake_service'
newline|'\n'
name|'for'
name|'key'
op|','
name|'value'
name|'in'
op|'{'
string|"'disabled'"
op|':'
name|'True'
op|','
nl|'\n'
string|"'disabled_reason'"
op|':'
string|"'my reason'"
op|','
nl|'\n'
string|"'forced_down'"
op|':'
name|'True'
op|'}'
op|'.'
name|'items'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'setattr'
op|'('
name|'service_obj'
op|','
name|'key'
op|','
name|'value'
op|')'
newline|'\n'
name|'self'
op|'.'
name|'_verify_notification'
op|'('
name|'service_obj'
op|')'
newline|'\n'
nl|'\n'
dedent|''
dedent|''
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.objects.service.ServiceStatusNotification'"
op|')'
newline|'\n'
op|'@'
name|'mock'
op|'.'
name|'patch'
op|'('
string|"'nova.db.service_update'"
op|')'
newline|'\n'
DECL|member|test_service_update_without_notification
name|'def'
name|'test_service_update_without_notification'
op|'('
name|'self'
op|','
nl|'\n'
name|'mock_db_service_update'
op|','
nl|'\n'
name|'mock_notification'
op|')'
op|':'
newline|'\n'
indent|' '
name|'service_obj'
op|'='
name|'objects'
op|'.'
name|'Service'
op|'('
name|'context'
op|'='
name|'self'
op|'.'
name|'ctxt'
op|','
name|'id'
op|'='
name|'fake_service'
op|'['
string|"'id'"
op|']'
op|')'
newline|'\n'
name|'mock_db_service_update'
op|'.'
name|'return_value'
op|'='
name|'fake_service'
newline|'\n'
nl|'\n'
name|'for'
name|'key'
op|','
name|'value'
name|'in'
op|'{'
string|"'report_count'"
op|':'
number|'13'
op|','
nl|'\n'
string|"'last_seen_up'"
op|':'
name|'timeutils'
op|'.'
name|'utcnow'
op|'('
op|')'
op|'}'
op|'.'
name|'items'
op|'('
op|')'
op|':'
newline|'\n'
indent|' '
name|'setattr'
op|'('
name|'service_obj'
op|','
name|'key'
op|','
name|'value'
op|')'
newline|'\n'
name|'service_obj'
op|'.'
name|'save'
op|'('
op|')'
newline|'\n'
name|'self'
op|'.'
name|'assertFalse'
op|'('
name|'mock_notification'
op|'.'
name|'called'
op|')'
newline|'\n'
dedent|''
dedent|''
dedent|''
endmarker|''
end_unit
| 12.485243 | 88 | 0.609643 | 6,934 | 46,957 | 4.007499 | 0.047015 | 0.172305 | 0.092126 | 0.077084 | 0.889053 | 0.84119 | 0.790341 | 0.729596 | 0.683496 | 0.637218 | 0 | 0.002354 | 0.095428 | 46,957 | 3,760 | 89 | 12.488564 | 0.65185 | 0 | 0 | 0.943883 | 0 | 0 | 0.369295 | 0.056243 | 0 | 0 | 0 | 0 | 0.014096 | 0 | null | null | 0.000532 | 0.003989 | null | null | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
4a9f9bf6b6891e8003f2cc5c0270b9ef835b1a61 | 44,046 | py | Python | pycwr/draw/RadarPlot.py | YvZheng/pycwr | 5602741f52366ba9d29e441953f1f2ece0a470db | [
"MIT"
] | 144 | 2019-11-27T14:36:41.000Z | 2022-02-23T08:21:17.000Z | pycwr/draw/RadarPlot.py | YvZheng/pycwr | 5602741f52366ba9d29e441953f1f2ece0a470db | [
"MIT"
] | 32 | 2019-11-29T10:11:53.000Z | 2022-03-14T07:46:44.000Z | pycwr/draw/RadarPlot.py | YvZheng/pycwr | 5602741f52366ba9d29e441953f1f2ece0a470db | [
"MIT"
] | 57 | 2019-11-27T12:51:44.000Z | 2022-01-29T14:50:05.000Z | import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from ..configure.default_config import CINRAD_COLORMAP, CINRAD_field_bins, \
CINRAD_field_normvar, CINRAD_field_mapping
import numpy as np
from ..configure.location_config import CN_shp_info
import cartopy.feature as cfeature
from ..core.transforms import geographic_to_cartesian_aeqd, cartesian_to_geographic_aeqd, antenna_vectors_to_cartesian
from .VerticalSectionPlot import VerticalSection
from cartopy.mpl.ticker import LongitudeFormatter, LatitudeFormatter
import cartopy, matplotlib
class Graph(object):
"""Improved mapping function, cartesian coords, recommended"""
def __init__(self, NRadar):
self.Radar = NRadar
def plot_ppi(self, ax, sweep_num, field_name, cmap=None, min_max=None, cmap_bins=None, cbar=True,
orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param sweep_num: The sweep_num volume scan to draw, from 0 start!
:param field_name: field dict to select data, eg: "dBZ" "V"
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins: bins of colormaps
:param cbar: if True, plot with colorbar, else not!
:param orientation: vertical or horizontal, if cbar is True , this is vaild!, colorbar oriention!
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs: other arguments for pcolormesh!
:return:
"""
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
if field_name == "V":
vmax = self.Radar.scan_info.nyquist_velocity[sweep_num].values
vmin = -1 * vmax
elif min_max is not None:
vmin, vmax = min_max
elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1:
vmax = np.nanmax(self.Radar.fields[sweep_num][field_name])
vmin = np.nanmin(self.Radar.fields[sweep_num][field_name])
else:
vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]]
if cmap is None:
cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]]
if cmap_bins is None:
cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]]
ax.set_aspect("equal")
radar_data = self.Radar.fields[sweep_num][field_name]
x, y = radar_data.x, radar_data.y
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
gci = ax.pcolormesh(x / 1000., y / 1000., radar_data, cmap=cmaps, \
zorder=0, norm=norm, shading='auto', **kwargs)
if cbar:
cb=plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
if clabel is not None:
cb.set_label(clabel)
return gci
def plot_rhi(self, ax, sweep_num, field_name, cmap=None, min_max=None,cmap_bins=None, cbar=True,
orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
if field_name == "V":
vmax = self.Radar.scan_info.nyquist_velocity[0].values
vmin = -1 * vmax
elif min_max is not None:
vmin, vmax = min_max
elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1:
vmax = np.nanmax(self.Radar.fields[0][field_name])
vmin = np.nanmin(self.Radar.fields[0][field_name])
else:
vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]]
if cmap is None:
cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]]
if cmap_bins is None:
cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]]
mesh_xy = (self.Radar.fields[sweep_num].x ** 2 + self.Radar.fields[sweep_num].y ** 2) ** 0.5
mesh_z = self.Radar.fields[sweep_num].z
field_data = self.Radar.fields[sweep_num][field_name]
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
gci = ax.pcolormesh(mesh_xy/1000., mesh_z/1000., field_data, cmap=cmaps,
norm=norm, shading='auto', **kwargs)
if cbar:
cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
if clabel is not None:
cb.set_label(clabel)
return gci
def plot_vcs(self, ax, start_xy, end_xy, field_name, cmap=None, min_max=None,cmap_bins=None, cbar=True,
orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param start_xy: (start_x, start_y) units:km, VCS start position!
:param end_xy: (end_x, end_y) units:km, VCS end position!
:param field_name: field dict to select data, eg: "dBZ" "V"
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins: bins of colormap
:param cbar: bool, if True, plot with colorbar,
:param orientation: vertical or horizontal, it is vaild when cbar is True
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:return:
"""
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
if field_name == "V":
vmax = self.Radar.scan_info.nyquist_velocity[0].values
vmin = -1 * vmax
elif min_max is not None:
vmin, vmax = min_max
elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1:
vmax = np.nanmax(self.Radar.fields[0][field_name])
vmin = np.nanmin(self.Radar.fields[0][field_name])
else:
vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]]
if cmap is None:
cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]]
if cmap_bins is None:
cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]]
start_point = (start_xy[0] * 1000., start_xy[1] * 1000) ##km to meters
end_point = (end_xy[0] * 1000., end_xy[1] * 1000) ##km to meters
mesh_xy, mesh_z, field_data = self.Radar.get_vcs_data(start_point, end_point, field_name)
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
for isweep, _ in enumerate(mesh_xy):
gci = ax.pcolormesh(mesh_xy[isweep] / 1000., mesh_z[isweep] / 1000., field_data[isweep], cmap=cmaps,
norm=norm, shading='auto', **kwargs)
if cbar:
cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return gci
def plot_crf(self, ax, cmap=CINRAD_COLORMAP[CINRAD_field_mapping["dBZ"]],
min_max=CINRAD_field_normvar[CINRAD_field_mapping["dBZ"]], cmap_bins=CINRAD_field_bins[CINRAD_field_mapping["dBZ"]],
cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
显示组合反射率因子
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param XRange: np.ndarray, 1d, units:meters
:param YRange: np.ndarray, 1d, units:meters
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins: bins of colormaps
:param cbar: if True, plot with colorbar, else not!
:param orientation: vertical or horizontal, if cbar is True , this is vaild!, colorbar oriention!
:param kwargs: other arguments for pcolormesh!
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:return:
"""
max_range = int(self.Radar.fields[0].range.max().values)
XRange = np.arange(-1 * max_range, max_range+1, 1000.)
YRange = XRange
self.Radar.add_product_CR_xy(XRange, YRange)
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
vmin, vmax = min_max
ax.set_aspect("equal")
radar_data = self.Radar.product['CR'].values
x, y = np.meshgrid(self.Radar.product['CR'].x_cr.values,
self.Radar.product['CR'].y_cr.values, indexing="ij")
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
gci = ax.pcolormesh(x / 1000., y / 1000., radar_data, cmap=cmaps, \
zorder=0, norm=norm, shading='auto', **kwargs)
if cbar:
cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return gci
def plot_cappi(self, ax, level_height=3000, cmap=CINRAD_COLORMAP[CINRAD_field_mapping["dBZ"]],
min_max=CINRAD_field_normvar[CINRAD_field_mapping["dBZ"]], cmap_bins=CINRAD_field_bins[CINRAD_field_mapping["dBZ"]],
cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
显示CAPPI图像
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param level_height: height of cappi, units:meters, default, 3000m
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins: bins of colormaps
:param cbar: if True, plot with colorbar, else not!
:param orientation: vertical or horizontal, if cbar is True , this is vaild!, colorbar oriention!
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs: other arguments for pcolormesh!
:return:
"""
max_range = int(self.Radar.fields[0].range.max().values)
XRange = np.arange(-1 * max_range, max_range + 1, 1000.)
YRange = XRange
self.Radar.add_product_CAPPI_xy(XRange, YRange, level_height)
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
vmin, vmax = min_max
ax.set_aspect("equal")
radar_data = self.Radar.product["CAPPI_%d"%level_height].values
x, y = np.meshgrid(self.Radar.product["CAPPI_%d"%level_height]['x_cappi_%d'%level_height].values,
self.Radar.product["CAPPI_%d"%level_height]['y_cappi_%d'%level_height].values, indexing="ij")
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
gci = ax.pcolormesh(x / 1000., y / 1000., radar_data, cmap=cmaps, \
zorder=0, norm=norm,shading='auto', **kwargs)
if cbar:
cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return gci
def add_rings(self, ax, rings, color="#5B5B5B", linestyle='-', linewidth=0.6, **kwargs):
"""
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param rings: distance from radar (units:km)
:param color: line color for rings
:param linestyle: linestyle for rings, {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
:param linewidth: linewidth for rings , float
:param kwargs: other arguments for ax.plot
:return:
"""
theta = np.linspace(0, 2 * np.pi, 200)
for i in rings:
x0 = i * np.cos(theta)
y0 = i * np.sin(theta)
gci = ax.plot(x0, y0, linestyle=linestyle, linewidth=linewidth, color=color, **kwargs)
for rad in np.arange(0, np.pi, np.pi / 6):
gci = ax.plot([-1 * rings[-1] * np.sin(rad), rings[-1] * np.sin(rad)], \
[-1 * rings[-1] * np.cos(rad), rings[-1] * np.cos(rad)], \
linestyle=linestyle, linewidth=linewidth, color=color, **kwargs)
return gci
def add_lines(self, ax, start_xy, end_xy, color='red', marker='x', markersize=12, **kwargs):
"""
:param ax: ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param start_xy: (start_x, start_y) units:km, line start position, units:km
:param end_xy: (end_x, end_y) units:km, line end position, units:km
:param color: color for line
:param marker: marker style for line marker
:param markersize: float, for markersize
:param kwargs: kwargs are used to specify other properties like a line label in plot!
:return:
"""
line_x = [start_xy[0], end_xy[0]]
line_y = [start_xy[1], end_xy[1]]
gci = ax.plot(line_x, line_y, color=color, marker=marker,markersize=markersize, **kwargs)
return gci
class GraphMap(object):
def __init__(self, NRadar, transform):
"""
:param NRadar: NRadar object, read from basedata
:param transform: The transform argument to plotting functions tells Cartopy what coordinate system your data are defined in.
"""
self.Radar = NRadar
self.transform = transform
def plot_ppi_map(self, ax, sweep_num, field_name, extend=None, cmap=None, min_max=None,\
cmap_bins=None, cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, \
clabel=None, **kwargs):
"""
:param ax: cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree())
:param sweep_num: The sweep_num volume scan to draw, from 0 start!
:param field_name: field dict to select data, eg: "dBZ" "V"
:param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins:bins of cmaps, int
:param cbar: bool, if True, plot with colorbar,
:param orientation: vertical or horizontal, it is vaild when cbar is True
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs: kwargs: other arguments for pcolormesh!
:return:
"""
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!"
if field_name == "V":
vmax = self.Radar.scan_info.nyquist_velocity[sweep_num].values
vmin = -1 * vmax
elif min_max is not None:
vmin, vmax = min_max
elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1:
vmax = np.nanmax(self.Radar.fields[sweep_num][field_name])
vmin = np.nanmin(self.Radar.fields[sweep_num][field_name])
else:
vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]]
if cmap is None:
cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]]
if cmap_bins is None:
cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]]
if extend is None:
min_lon = np.min(self.Radar.fields[sweep_num].lon)
max_lon = np.max(self.Radar.fields[sweep_num].lon)
min_lat = np.min(self.Radar.fields[sweep_num].lat)
max_lat = np.max(self.Radar.fields[sweep_num].lat)
else:
min_lon, max_lon, min_lat, max_lat = extend
#ax.set_aspect("equal")
radar_data = self.Radar.fields[sweep_num][field_name]
lat, lon = radar_data.lat, radar_data.lon
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
pm = ax.pcolormesh(lon, lat, radar_data, transform=self.transform, cmap=cmap, norm=norm, zorder=4, **kwargs)
ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0)
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \
edgecolor='none', facecolor="white"), zorder=1)
ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2)
ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3)
ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), self.transform, \
edgecolor='k', facecolor='none'), linewidth=0.5, \
linestyle='-', zorder=5, alpha=0.8)
parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1)
meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1)
ax.set_xticks(meridians, crs=self.transform)
ax.set_yticks(parallels, crs=self.transform)
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
if cbar:
cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return ax
def plot_cappi_map(self, ax, level_height, extend=None, cmap=CINRAD_COLORMAP[CINRAD_field_mapping['dBZ']],
min_max=CINRAD_field_normvar[CINRAD_field_mapping['dBZ']], cmap_bins=CINRAD_field_bins[CINRAD_field_mapping['dBZ']],
cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
显示CAPPI图像
:param ax: cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree())
:param level_height: height of cappi, units:meters, default, 3000m
:param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins:bins of cmaps, int
:param cbar: bool, if True, plot with colorbar,
:param orientation: vertical or horizontal, it is vaild when cbar is True
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs: kwargs: other arguments for pcolormesh!
:return:
"""
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!"
vmin, vmax = min_max
if extend is None:
min_lon = np.min(self.Radar.fields[0].lon)
max_lon = np.max(self.Radar.fields[0].lon)
min_lat = np.min(self.Radar.fields[0].lat)
max_lat = np.max(self.Radar.fields[0].lat)
else:
min_lon, max_lon, min_lat, max_lat = extend
XLON = np.arange(min_lon, max_lon, 0.01)
YLAT = np.arange(min_lat, max_lat, 0.01)
# ax.set_aspect("equal")
self.Radar.add_product_CAPPI_lonlat(XLON, YLAT, level_height)
radar_data = self.Radar.product["CAPPI_geo_%d" % level_height].values
lon, lat = np.meshgrid(XLON, YLAT, indexing="ij")
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
pm = ax.pcolormesh(lon, lat, radar_data, transform=self.transform, cmap=cmap, norm=norm, zorder=4, **kwargs)
# ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=self.transform)
ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0)
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \
edgecolor='none', facecolor="white"), zorder=1)
ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2)
ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3)
ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), self.transform, \
edgecolor='k', facecolor='none'), linewidth=0.5, \
linestyle='-', zorder=5, alpha=0.8)
parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1)
meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1)
ax.set_xticks(meridians, crs=self.transform)
ax.set_yticks(parallels, crs=self.transform)
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
if cbar:
cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return ax
def plot_crf_map(self, ax, extend=None, cmap=CINRAD_COLORMAP[CINRAD_field_mapping['dBZ']],
min_max=CINRAD_field_normvar[CINRAD_field_mapping['dBZ']], cmap_bins=CINRAD_field_bins[CINRAD_field_mapping['dBZ']],
cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
显示组合反射率因子
:param ax: cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree())
:param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins:bins of cmaps, int
:param cbar: bool, if True, plot with colorbar,
:param orientation: vertical or horizontal, it is vaild when cbar is True
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs: kwargs: other arguments for pcolormesh!
:return:
"""
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!"
vmin, vmax = min_max
if extend is None:
min_lon = np.min(self.Radar.fields[0].lon)
max_lon = np.max(self.Radar.fields[0].lon)
min_lat = np.min(self.Radar.fields[0].lat)
max_lat = np.max(self.Radar.fields[0].lat)
else:
min_lon, max_lon, min_lat, max_lat = extend
XLON = np.arange(min_lon, max_lon, 0.01)
YLAT = np.arange(min_lat, max_lat, 0.01)
#ax.set_aspect("equal")
self.Radar.add_product_CR_lonlat(XLON, YLAT)
radar_data = self.Radar.product["CR_geo"].values
lon, lat = np.meshgrid(XLON, YLAT, indexing="ij")
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
pm = ax.pcolormesh(lon, lat, radar_data, transform=self.transform, cmap=cmap, norm=norm, zorder=4, **kwargs)
#ax.set_extent([min_lon, max_lon, min_lat, max_lat], crs=self.transform)
ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0)
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \
edgecolor='none', facecolor="white"), zorder=1)
ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2)
ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3)
ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), self.transform, \
edgecolor='k', facecolor='none'), linewidth=0.5, \
linestyle='-', zorder=5, alpha=0.8)
parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1)
meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1)
ax.set_xticks(meridians, crs=self.transform)
ax.set_yticks(parallels, crs=self.transform)
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
if cbar:
cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return ax
def plot_vcs_map(self, ax, start_lonlat, end_lonlat, field_name, cmap=None, min_max=None,\
cmap_bins=None, cbar=True, orientation="vertical", cbar_ticks=None, cbar_ticklabels=None,\
clabel=None, **kwargs):
"""
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param start_lonlat:(startlon, startlat), VCS start position!
:param end_lonlat:(endlon, endlat), VCS end position!
:param field_name: field dict to select data, eg: "dBZ" "V"
:param cmap:str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max:The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins:bins of cmaps, int
:param cbar:bool, if True, plot with colorbar,
:param orientation:vertical or horizontal, it is vaild when cbar is True
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs: other arguments for pcolormesh!
:return:
"""
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
if field_name == "V":
vmax = self.Radar.scan_info.nyquist_velocity[0].values
vmin = -1 * vmax
elif min_max is not None:
vmin, vmax = min_max
elif CINRAD_field_normvar[CINRAD_field_mapping[field_name]] == -1:
vmax = np.nanmax(self.Radar.fields[0][field_name])
vmin = np.nanmin(self.Radar.fields[0][field_name])
else:
vmin, vmax = CINRAD_field_normvar[CINRAD_field_mapping[field_name]]
if cmap is None:
cmap = CINRAD_COLORMAP[CINRAD_field_mapping[field_name]]
if cmap_bins is None:
cmap_bins = CINRAD_field_bins[CINRAD_field_mapping[field_name]]
cmaps = plt.get_cmap(cmap)
levels = MaxNLocator(nbins=cmap_bins).tick_values(vmin, vmax)
norm = BoundaryNorm(levels, ncolors=cmaps.N, clip=True)
start_x, start_y = geographic_to_cartesian_aeqd(lat=start_lonlat[1], lon=start_lonlat[0],
lat_0=self.Radar.scan_info.latitude.values,
lon_0=self.Radar.scan_info.longitude.values)
end_x, end_y = geographic_to_cartesian_aeqd(lat=end_lonlat[1], lon=end_lonlat[0],
lat_0=self.Radar.scan_info.latitude.values,
lon_0=self.Radar.scan_info.longitude.values)
mesh_xy, mesh_z, field_data = self.Radar.get_vcs_data((start_x[0], start_y[0]), (end_x[0], end_y[0]), field_name)
for isweep, _ in enumerate(mesh_xy):
gci = ax.pcolormesh(mesh_xy[isweep] / 1000., mesh_z[isweep] / 1000., field_data[isweep], cmap=cmaps,
norm=norm, **kwargs)
xticks_data = ax.get_xticks()
x_points_tk, y_points_tk = VerticalSection.get_points_from_ranges((start_x[0] / 1000., start_y[0] / 1000),
(end_x[0] / 1000, end_y[0] / 1000),
xticks_data)
lon_point, lat_point = cartesian_to_geographic_aeqd(x_points_tk * 1000., y_points_tk * 1000.,
lat_0=self.Radar.scan_info.latitude.values,
lon_0=self.Radar.scan_info.longitude.values) # to meters
ax.set_xticklabels(["(%.2f, %.2f)" % (lon_point[i], lat_point[i]) \
for i, _ in enumerate(xticks_data)], rotation=15, fontsize=10)
if cbar:
cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = levels
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return gci
def add_lines_map(self, ax, start_lonlat, end_lonlat, color='red', marker='x', **kwargs):
"""
:param ax: cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree())
:param start_lonlat: (startlon, startlat), line start position!
:param end_lonlat: (endlon, endlat), line end position!
:param color: str, color for line
:param marker: str, style of marker
:param markersize:float, size of marker
:param kwargs:
:return:
"""
line_lon = [start_lonlat[0], end_lonlat[0]]
line_lat = [start_lonlat[1], end_lonlat[1]]
gci = ax.plot(line_lon, line_lat, color=color, marker=marker, transform=self.transform,zorder=20, **kwargs)
return gci
def plot_xy(ax, x, y, data, cmap="CN_ref", bounds=np.arange(-5, 76, 5), cbar=True, orientation="vertical",
cbar_ticks=None, cbar_ticklabels=None, clabel=None, **kwargs):
"""
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param x: mesh grid x for data units: m
:param y: y: mesh grid y for data units: m
:param data: radar data ,dims like x,y
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param orientation: vertical or horizontal, if cbar is True , this is vaild!, colorbar oriention!
:param cbar: if True, plot with colorbar, else not!
:param bounds: Monotonically increasing sequence of boundaries
:param cbar_ticks: Set the locations of the tick marks from sequence ticks
:param cbar_ticklabels: Set the text values of the tick labels.
:param kwargs:
:return:
"""
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
ax.set_aspect("equal")
cmaps = plt.get_cmap(cmap)
norm = BoundaryNorm(bounds, ncolors=cmaps.N, clip=True)
gci = ax.pcolormesh(x / 1000., y / 1000., data, cmap=cmaps, \
zorder=0, norm=norm, **kwargs)
if cbar:
cb = plt.colorbar(mappable=gci, ax=ax, orientation=orientation)
if cbar_ticks is not None and cbar_ticklabels is not None:
cb.set_ticks(cbar_ticks)
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
else:
cb.set_ticks(bounds)
if clabel is not None:
cb.set_label(clabel)
return gci
def add_rings(ax, rings, color="#5B5B5B", linestyle='-', linewidth=0.6, **kwargs):
"""
:param ax: axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param rings: distance from radar (units:km)
:param color: line color for rings
:param linestyle: linestyle for rings, {'-', '--', '-.', ':', '', (offset, on-off-seq), ...}
:param linewidth: linewidth for rings , float
:param kwargs: other arguments for ax.plot
:return:
"""
theta = np.linspace(0, 2 * np.pi, 200)
for i in rings:
x0 = i * np.cos(theta)
y0 = i * np.sin(theta)
gci = ax.plot(x0, y0, linestyle=linestyle, linewidth=linewidth, color=color, **kwargs)
for rad in np.arange(0, np.pi, np.pi / 6):
gci = ax.plot([-1 * rings[-1] * np.sin(rad), rings[-1] * np.sin(rad)], \
[-1 * rings[-1] * np.cos(rad), rings[-1] * np.cos(rad)], \
linestyle=linestyle, linewidth=linewidth, color=color, **kwargs)
return gci
def plot_az_ranges(ax, _range, azimuth, elevation, data, cmap="CN_ref", bounds=np.arange(-5,76,5), cbar=True,
orientation="vertical", cbar_ticks=None, cbar_ticklabels=None, **kwargs):
"""
:param ax:axes.Axes object or array of Axes objects., eg: fig, ax = plt.subplots
:param _range: data second dim's range, 1d, units:meters, numpy.ndarray
:param azimuth: data first dim's azimuth, 1d, units:degeree, numpy.ndarray
:param elevation: data first dim's elevation, 1d, units:degeree, numpy.ndarray
:param data: radar data ,dims like x,y
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins: bins of colormaps
:param cbar: if True, plot with colorbar, else not!
:param orientation: vertical or horizontal, if cbar is True , this is vaild!, colorbar oriention!
:param kwargs: other arguments for pcolormesh!
:return:
"""
assert isinstance(ax, matplotlib.axes._axes.Axes), "axes should be matplotlib axes not cartopy axes!"
x, y, z = antenna_vectors_to_cartesian(_range, azimuth, elevation, edges=True)
return plot_xy(ax, x, y, data, cmap=cmap, bounds=bounds, cbar=cbar, orientation=orientation, cbar_ticks=cbar_ticks,
cbar_ticklabels=cbar_ticklabels, **kwargs)
def plot_lonlat_map(ax, lon, lat, data, transform, extend=None, cmap="CN_ref", bounds=np.arange(-5,76,5),
cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None, clabel=None,\
**kwargs):
"""
:param ax:cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree())
:param lon: lon mesh grid for data units: degree
:param lat: lat mesh grid for data units: degree
:param data: radar data ,dims like lat, lon
:param transform: The transform argument to plotting functions tells Cartopy what coordinate system your data are defined in.
:param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins:bins of cmaps, int
:param cbar: bool, if True, plot with colorbar,
:param orientation: vertical or horizontal, it is vaild when cbar is True
:param kwargs: kwargs: other arguments for pcolormesh!
:return: pcolor result
"""
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!"
if extend is None:
min_lon = np.min(lon)
max_lon = np.max(lon)
min_lat = np.min(lat)
max_lat = np.max(lat)
else:
min_lon, max_lon, min_lat, max_lat = extend
ax.set_aspect("equal")
cmaps = plt.get_cmap(cmap)
norm = BoundaryNorm(bounds, ncolors=cmaps.N, clip=True)
pm = ax.pcolormesh(lon, lat, data, transform=transform, cmap=cmap, norm=norm, zorder=4, **kwargs)
ax.add_feature(cfeature.OCEAN.with_scale('50m'), zorder=0)
ax.add_feature(cfeature.NaturalEarthFeature('physical', 'land', '50m', \
edgecolor='none', facecolor="white"), zorder=1)
ax.add_feature(cfeature.LAKES.with_scale('50m'), zorder=2)
ax.add_feature(cfeature.RIVERS.with_scale('50m'), zorder=3)
ax.add_feature(cfeature.ShapelyFeature(CN_shp_info.geometries(), transform, \
edgecolor='k', facecolor='none'), linewidth=0.5, \
linestyle='-', zorder=5, alpha=0.8)
parallels = np.arange(int(min_lat), np.ceil(max_lat) + 1, 1)
meridians = np.arange(int(min_lon), np.ceil(max_lon) + 1, 1)
ax.set_xticks(meridians, crs=transform)
ax.set_yticks(parallels, crs=transform)
lon_formatter = LongitudeFormatter()
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
if cbar:
cb = plt.colorbar(mappable=pm, ax=ax, orientation=orientation)
if cbar_ticks is None:
ticks = bounds
else:
ticks = cbar_ticks
cb.set_ticks(ticks)
if clabel is not None:
cb.set_label(clabel)
if cbar_ticklabels is not None:
if orientation == "vertical":
cb.ax.set_yticklabels(cbar_ticklabels)
else:
cb.ax.set_xticklabels(cbar_ticklabels)
return pm
def plot_az_ranges_map(ax, _range, azimuth, elevation, data, main_point, transform, extend=None, cmap="CN_ref",
bounds=np.arange(-5,76,5), cbar=True, orientation="vertical",cbar_ticks=None, cbar_ticklabels=None,
**kwargs):
"""
plot radar data with map, using range, azimuth, elevation
:param ax:cartopy.mpl.geoaxes.GeoAxesSubplot, it should get from cartopy, eg:plt.axes(projection=ccrs.PlateCarree())
:param _range:data second dim's range, 1d, units:meters, numpy.ndarray
:param azimuth:data first dim's azimuth, 1d, units:degeree, numpy.ndarray
:param elevation:data first dim's elevation, 1d, units:degeree, numpy.ndarray
:param data:radar data ,dims like lat, lon
:param main_point: list, (lon_0, lat_0) of radar station, units:degree
:param transform: The transform argument to plotting functions tells Cartopy what coordinate system your data are defined in.
:param extend: (min_lon, max_lon, min_lat, max_lat), Latitude and longitude range, units:degrees
:param cmap: str or Colormap, optional, A Colormap instance or registered colormap name. to see cm.py!
:param min_max: The colorbar range(vmin, vmax). If None, suitable min/max values are automatically chosen by min max of data!
:param cmap_bins:bins of cmaps, int
:param cbar: bool, if True, plot with colorbar,
:param orientation: vertical or horizontal, it is vaild when cbar is True
:param kwargs: kwargs: other arguments for pcolormesh!
:return: pcolor result
"""
assert isinstance(ax, cartopy.mpl.geoaxes.GeoAxesSubplot), "axes is not cartopy axes!"
main_lon, main_lat = main_point
x, y, z = antenna_vectors_to_cartesian(_range, azimuth, elevation, edges=True)
lon, lat = cartesian_to_geographic_aeqd(x, y, main_lon, main_lat)
return plot_lonlat_map(ax, lon, lat, data,transform, extend, cmap, bounds, cbar, orientation,cbar_ticks, cbar_ticklabels **kwargs) | 53.518834 | 136 | 0.632997 | 5,895 | 44,046 | 4.57676 | 0.057167 | 0.023647 | 0.022016 | 0.01705 | 0.907858 | 0.887732 | 0.875612 | 0.862713 | 0.855115 | 0.849259 | 0 | 0.01137 | 0.263179 | 44,046 | 823 | 137 | 53.518834 | 0.819961 | 0.279072 | 0 | 0.814815 | 0 | 0 | 0.035652 | 0 | 0 | 0 | 0 | 0 | 0.024074 | 1 | 0.035185 | false | 0 | 0.02037 | 0 | 0.090741 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
434c36a921b4129763b1ecc59fd8026fa5903a66 | 1,962 | py | Python | API/server/python-flask-server-generated/swagger_server/controllers/model_flow_chart_extension_controller.py | zhuofusong/machine-fault-diagnosis | 4c35885e3fbb3c552f526019313a8eae9df28905 | [
"MIT"
] | 2 | 2020-04-30T01:06:55.000Z | 2020-06-08T04:11:28.000Z | API/server/python-flask-server-generated/swagger_server/controllers/model_flow_chart_extension_controller.py | zhuofusong/machine-fault-diagnosis | 4c35885e3fbb3c552f526019313a8eae9df28905 | [
"MIT"
] | 5 | 2020-04-13T14:13:53.000Z | 2021-08-24T17:16:30.000Z | API/server/python-flask-server-generated/swagger_server/controllers/model_flow_chart_extension_controller.py | zhuofusong/machine-fault-diagnosis | 4c35885e3fbb3c552f526019313a8eae9df28905 | [
"MIT"
] | null | null | null | import connexion
import six
from swagger_server.models.model_flow_chart_extension_meta import ModelFlowChartExtensionMeta # noqa: E501
from swagger_server import util
def model_flow_model_flow_id_extension_delete(model_flow_id): # noqa: E501
"""delete a model flow chart extension
delete a model flow chart extension # noqa: E501
:param model_flow_id: model flow chart id
:type model_flow_id: str
:rtype: object
"""
return 'do some magic!'
def model_flow_model_flow_id_extension_get(model_flow_id): # noqa: E501
"""retrieve a model flow chart extension
retrieve a model flow chart extension # noqa: E501
:param model_flow_id: model flow chart id
:type model_flow_id: str
:rtype: List[ModelFlowChartExtensionMeta]
"""
return 'do some magic!'
def model_flow_model_flow_id_extension_post(model_flow_id, model_flow_chart_extension): # noqa: E501
"""create a model flow chart extension
create a model flow chart extension # noqa: E501
:param model_flow_id: model flow chart id
:type model_flow_id: str
:param model_flow_chart_extension: model flow chart extension
:type model_flow_chart_extension: dict | bytes
:rtype: object
"""
if connexion.request.is_json:
model_flow_chart_extension = .from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!'
def model_flow_model_flow_id_extension_put(model_flow_id, model_flow_chart_extension): # noqa: E501
"""update a model flow chart extension
update a model flow chart extension # noqa: E501
:param model_flow_id: model flow chart id
:type model_flow_id: str
:param model_flow_chart_extension: model flow chart extension
:type model_flow_chart_extension: dict | bytes
:rtype: object
"""
if connexion.request.is_json:
model_flow_chart_extension = .from_dict(connexion.request.get_json()) # noqa: E501
return 'do some magic!'
| 29.727273 | 107 | 0.739551 | 281 | 1,962 | 4.864769 | 0.149466 | 0.283102 | 0.235552 | 0.319678 | 0.857352 | 0.829554 | 0.721287 | 0.697879 | 0.697879 | 0.63643 | 0 | 0.020846 | 0.19317 | 1,962 | 65 | 108 | 30.184615 | 0.842704 | 0.038736 | 0 | 0.5 | 0 | 0 | 0.067551 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0.25 | null | null | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
60968c74375e97c17b677ffa44cfe14033c38f96 | 16,815 | py | Python | tests/test_documentmanifest.py | gustavofonseca/document-store | 32da9a5cf8744fb6f2427e30cd3a1bacab11761b | [
"BSD-2-Clause"
] | 6 | 2018-12-05T15:52:13.000Z | 2019-04-18T14:14:32.000Z | tests/test_documentmanifest.py | gustavofonseca/document-store | 32da9a5cf8744fb6f2427e30cd3a1bacab11761b | [
"BSD-2-Clause"
] | 117 | 2018-09-03T21:13:30.000Z | 2019-09-26T19:16:24.000Z | tests/test_documentmanifest.py | gustavofonseca/document-store | 32da9a5cf8744fb6f2427e30cd3a1bacab11761b | [
"BSD-2-Clause"
] | 9 | 2018-12-05T14:01:30.000Z | 2019-07-04T17:34:08.000Z | import functools
import unittest
from documentstore.domain import DocumentManifest
def fake_utcnow():
return "2018-08-05T22:33:49.795151Z"
new = DocumentManifest.new
add_version = functools.partial(DocumentManifest.add_version, now=fake_utcnow)
add_asset_version = functools.partial(
DocumentManifest.add_asset_version, now=fake_utcnow
)
add_rendition_version = functools.partial(
DocumentManifest.add_rendition_version, now=fake_utcnow
)
class TestNewManifest(unittest.TestCase):
def test_minimal_structure(self):
expected = {"id": "0034-8910-rsp-48-2-0275", "versions": []}
self.assertEqual(new("0034-8910-rsp-48-2-0275"), expected)
def test_ids_are_converted_to_str(self):
expected = {"id": "275", "versions": []}
self.assertEqual(new(275), expected)
class TestAddVersion(unittest.TestCase):
def test_first_version(self):
doc = {"id": "0034-8910-rsp-48-2-0275", "versions": []}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {"0034-8910-rsp-48-2-0275-gf01.gif": []},
"timestamp": fake_utcnow(),
"renditions": [],
}
],
}
self.assertEqual(
add_version(
doc,
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
["0034-8910-rsp-48-2-0275-gf01.gif"],
),
expected,
)
def test_manifest_versions_are_immutable(self):
doc = {"id": "0034-8910-rsp-48-2-0275", "versions": []}
new_version = add_version(
doc,
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
["0034-8910-rsp-48-2-0275-gf01.gif"],
)
self.assertEqual(len(doc["versions"]), 0)
self.assertEqual(len(new_version["versions"]), 1)
def test_add_version_with_assets_mapping(self):
doc = {"id": "0034-8910-rsp-48-2-0275", "versions": []}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {"0034-8910-rsp-48-2-0275-gf01.gif": []},
"timestamp": fake_utcnow(),
"renditions": [],
}
],
}
self.assertEqual(
add_version(
doc,
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
{"0034-8910-rsp-48-2-0275-gf01.gif": ""},
),
expected,
)
def test_add_version_with_assets_mapping_nonempty(self):
doc = {"id": "0034-8910-rsp-48-2-0275", "versions": []}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {
"0034-8910-rsp-48-2-0275-gf01.gif": [
"/rawfiles/8e644999a8fa4/0034-8910-rsp-48-2-0275-gf01.gif"
]
},
}
],
}
self.assertEqual(
add_version(
doc,
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
{
"0034-8910-rsp-48-2-0275-gf01.gif": "/rawfiles/8e644999a8fa4/0034-8910-rsp-48-2-0275-gf01.gif"
},
),
expected,
)
def test_add_version_with_assets_mapping_nonempty(self):
doc = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {
"0034-8910-rsp-48-2-0275-gf01.gif": [
(
"2018-08-05 21:15:07.795137",
"/rawfiles/8e644999a8fa4/0034-8910-rsp-48-2-0275-gf01.gif",
)
]
},
}
],
}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {
"0034-8910-rsp-48-2-0275-gf01.gif": [
(
"2018-08-05 21:15:07.795137",
"/rawfiles/8e644999a8fa4/0034-8910-rsp-48-2-0275-gf01.gif",
),
(
fake_utcnow(),
"/rawfiles/7a664999a8fb3/0034-8910-rsp-48-2-0275-gf01.gif",
),
]
},
}
],
}
self.assertEqual(
add_asset_version(
doc,
"0034-8910-rsp-48-2-0275-gf01.gif",
"/rawfiles/7a664999a8fb3/0034-8910-rsp-48-2-0275-gf01.gif",
),
expected,
)
def test_additional_data_are_preserved_while_adding_versions_for_assets(self):
doc = {
"_revision": "a1eda318424",
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {"0034-8910-rsp-48-2-0275-gf01.gif": []},
}
],
}
expected = {
"_revision": "a1eda318424",
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {
"0034-8910-rsp-48-2-0275-gf01.gif": [
(
fake_utcnow(),
"/rawfiles/7a664999a8fb3/0034-8910-rsp-48-2-0275-gf01.gif",
)
]
},
}
],
}
self.assertEqual(
add_asset_version(
doc,
"0034-8910-rsp-48-2-0275-gf01.gif",
"/rawfiles/7a664999a8fb3/0034-8910-rsp-48-2-0275-gf01.gif",
),
expected,
)
def test_add_asset_version_for_unknown_asset(self):
doc = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"data": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
"assets": {
"0034-8910-rsp-48-2-0275-gf01.gif": [
"/rawfiles/8e644999a8fa4/0034-8910-rsp-48-2-0275-gf01.gif"
]
},
}
],
}
self.assertRaises(
KeyError,
add_asset_version,
doc,
"0034-8910-rsp-48-2-0275-UNKNOWN.gif",
"/rawfiles/7a664999a8fb3/0034-8910-rsp-48-2-0275-gf01.gif",
)
def test_additional_data_are_preserved_while_adding_versions(self):
doc = {
"_revision": "a1eda318424",
"id": "0034-8910-rsp-48-2-0275",
"versions": [],
}
new_version = add_version(
doc,
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.xml",
["0034-8910-rsp-48-2-0275-gf01.gif"],
)
self.assertEqual(new_version["_revision"], "a1eda318424")
class AddRenditionVersionTests(unittest.TestCase):
def test_first_version(self):
doc = {"id": "0034-8910-rsp-48-2-0275", "versions": [{"renditions": []}]}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
}
],
"mimetype": "application/pdf",
"lang": "pt-br",
}
]
}
],
}
self.assertEqual(
add_rendition_version(
doc,
"0034-8910-rsp-48-2-0275.pdf",
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"application/pdf",
"pt-br",
243000,
),
expected,
)
def test_second_version(self):
doc = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
}
],
"mimetype": "application/pdf",
"lang": "pt-br",
}
]
}
],
}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
},
{
"timestamp": "2018-08-05T22:33:49.795151Z", # vai repetir nos testes
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275-v2.pdf",
"size_bytes": 223461,
},
],
"mimetype": "application/pdf",
"lang": "pt-br",
}
]
}
],
}
self.assertEqual(
add_rendition_version(
doc,
"0034-8910-rsp-48-2-0275.pdf",
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275-v2.pdf",
"application/pdf",
"pt-br",
223461,
),
expected,
)
def test_filename_and_lang_must_match(self):
doc = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
}
],
"mimetype": "application/pdf",
"lang": "pt-br",
}
]
}
],
}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
}
],
"mimetype": "application/pdf",
"lang": "pt-br",
},
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z", # vai repetir nos testes
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275-v2.pdf",
"size_bytes": 223461,
}
],
"mimetype": "application/pdf",
"lang": "pt",
},
]
}
],
}
self.assertEqual(
add_rendition_version(
doc,
"0034-8910-rsp-48-2-0275.pdf",
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275-v2.pdf",
"application/pdf",
"pt",
223461,
),
expected,
)
def test_filename_and_mimetype_must_match(self):
doc = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
}
],
"mimetype": "application/pdf",
"lang": "pt-br",
}
]
}
],
}
expected = {
"id": "0034-8910-rsp-48-2-0275",
"versions": [
{
"renditions": [
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z",
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275.pdf",
"size_bytes": 243000,
}
],
"mimetype": "application/pdf",
"lang": "pt-br",
},
{
"filename": "0034-8910-rsp-48-2-0275.pdf",
"data": [
{
"timestamp": "2018-08-05T22:33:49.795151Z", # vai repetir nos testes
"url": "/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275-v2.pdf",
"size_bytes": 223461,
}
],
"mimetype": "application/octet-stream",
"lang": "pt-br",
},
]
}
],
}
self.assertEqual(
add_rendition_version(
doc,
"0034-8910-rsp-48-2-0275.pdf",
"/rawfiles/7ca9f9b2687cb/0034-8910-rsp-48-2-0275-v2.pdf",
"application/octet-stream",
"pt-br",
223461,
),
expected,
)
| 35.625 | 114 | 0.367232 | 1,327 | 16,815 | 4.56217 | 0.081387 | 0.117608 | 0.161711 | 0.191113 | 0.895111 | 0.863396 | 0.846217 | 0.840601 | 0.840601 | 0.816815 | 0 | 0.247047 | 0.506512 | 16,815 | 471 | 115 | 35.700637 | 0.482526 | 0.004044 | 0 | 0.615561 | 0 | 0 | 0.29469 | 0.220689 | 0 | 0 | 0 | 0 | 0.034325 | 1 | 0.034325 | false | 0 | 0.006865 | 0.002288 | 0.050343 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 |
8801dce31214b108afe26babe74f442a5b45a221 | 180 | py | Python | LuoguCodes/AT699.py | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/AT699.py | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | LuoguCodes/AT699.py | Anguei/OI-Codes | 0ef271e9af0619d4c236e314cd6d8708d356536a | [
"MIT"
] | null | null | null | n, s = int(raw_input()), raw_input()
print max(s.count(';1';), s.count(';2';), s.count(';3';), s.count(';4';)), min(s.count(';1';), s.count(';2';), s.count(';3';), s.count(';4';))
| 60 | 142 | 0.5 | 34 | 180 | 2.588235 | 0.382353 | 0.545455 | 0.159091 | 0.181818 | 0.636364 | 0.636364 | 0.636364 | 0.636364 | 0.636364 | 0.636364 | 0 | 0.048193 | 0.077778 | 180 | 2 | 143 | 90 | 0.481928 | 0 | 0 | 0 | 0 | 0 | 0.088889 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | null | 0 | 0 | null | null | 0.5 | 0 | 0 | 0 | null | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 7 |
714d1df8ff702098a529a7a9e111b8a494f3094f | 14,085 | py | Python | test/lazy/test_cached_cg_lazy_tensor.py | cdgreenidge/gpytorch | d4cc610963bd812052e43e3aed84fb8b2ec94aa6 | [
"MIT"
] | null | null | null | test/lazy/test_cached_cg_lazy_tensor.py | cdgreenidge/gpytorch | d4cc610963bd812052e43e3aed84fb8b2ec94aa6 | [
"MIT"
] | null | null | null | test/lazy/test_cached_cg_lazy_tensor.py | cdgreenidge/gpytorch | d4cc610963bd812052e43e3aed84fb8b2ec94aa6 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import math
import torch
import gpytorch
import unittest
import warnings
from gpytorch.lazy import CachedCGLazyTensor, NonLazyTensor
from test.lazy._lazy_tensor_test_case import LazyTensorTestCase
class TestCachedCGLazyTensorNoLogdet(LazyTensorTestCase, unittest.TestCase):
seed = 0
def create_lazy_tensor(self):
mat = torch.randn(5, 6)
mat = mat.matmul(mat.transpose(-1, -2))
mat.requires_grad_(True)
lazy_tensor = NonLazyTensor(mat)
eager_rhs = torch.randn(5, 10).detach()
with gpytorch.settings.num_trace_samples(1000): # For inv_quad_logdet tests
solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms(
lazy_tensor, eager_rhs.detach(), logdet_terms=False
)
eager_rhss = [eager_rhs.detach(), eager_rhs[..., -2:-1].detach()]
solves = [solve.detach(), solve[..., -2:-1].detach()]
return CachedCGLazyTensor(
lazy_tensor, eager_rhss, solves, probe_vecs, probe_vec_norms, probe_vec_solves, tmats
)
def evaluate_lazy_tensor(self, lazy_tensor):
return lazy_tensor.base_lazy_tensor.tensor
def test_inv_matmul_vec(self):
lazy_tensor = self.create_lazy_tensor().requires_grad_(True)
lazy_tensor_copy = lazy_tensor.clone().detach_().requires_grad_(True)
evaluated = self.evaluate_lazy_tensor(lazy_tensor_copy)
test_vector = lazy_tensor.eager_rhss[1].squeeze(-1).clone().detach().requires_grad_(True)
test_vector_copy = lazy_tensor_copy.eager_rhss[1].squeeze(-1).clone().detach().requires_grad_(True)
# Make sure that we get no warning about CG
with gpytorch.settings.max_cg_iterations(200), warnings.catch_warnings(record=True) as w:
res = lazy_tensor.inv_matmul(test_vector)
actual = evaluated.inverse().matmul(test_vector_copy)
self.assertEqual(len(w), 0)
self.assertLess(((res - actual).abs() / actual.abs().clamp(1, 1e5)).max().item(), 3e-1)
grad = torch.randn_like(res)
# Make sure that we get a warning that CG was run
with warnings.catch_warnings(record=True) as w:
res.backward(gradient=grad)
actual.backward(gradient=grad)
self.assertEqual(len(w), 1)
for arg, arg_copy in zip(lazy_tensor.representation(), lazy_tensor_copy.representation()):
if arg_copy.grad is not None:
self.assertLess(
((arg.grad - arg_copy.grad).abs() / arg_copy.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
self.assertLess(
((test_vector.grad - test_vector_copy.grad).abs() / test_vector.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
def test_inv_matmul_vector_with_left(self):
lazy_tensor = self.create_lazy_tensor().requires_grad_(True)
lazy_tensor_copy = lazy_tensor.clone().detach_().requires_grad_(True)
evaluated = self.evaluate_lazy_tensor(lazy_tensor_copy)
test_vector = lazy_tensor.eager_rhss[0][..., -1].squeeze(-1).clone().detach().requires_grad_(True)
test_vector_copy = lazy_tensor_copy.eager_rhss[0][..., -1].squeeze(-1).clone().detach().requires_grad_(True)
test_left = lazy_tensor.eager_rhss[0][..., :-1].t().clone().detach().requires_grad_(True)
test_left_copy = lazy_tensor_copy.eager_rhss[0][..., :-1].t().clone().detach().requires_grad_(True)
# Make sure that we get no warning about CG
with gpytorch.settings.max_cg_iterations(200), warnings.catch_warnings(record=True) as w:
res = lazy_tensor.inv_matmul(test_vector, test_left)
actual = test_left_copy @ evaluated.inverse() @ test_vector_copy
self.assertEqual(len(w), 0)
self.assertLess(((res - actual).abs() / actual.abs().clamp(1, 1e5)).max().item(), 3e-1)
grad = torch.randn_like(res)
# Make sure that we get no warning about CG
with warnings.catch_warnings(record=True) as w:
res.backward(gradient=grad)
actual.backward(gradient=grad)
self.assertEqual(len(w), 0)
for arg, arg_copy in zip(lazy_tensor.representation(), lazy_tensor_copy.representation()):
if arg_copy.grad is not None:
self.assertLess(
((arg.grad - arg_copy.grad).abs() / arg_copy.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
self.assertLess(
((test_left.grad - test_left_copy.grad).abs() / test_left.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
self.assertLess(
((test_vector.grad - test_vector_copy.grad).abs() / test_vector.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
def test_inv_matmul_matrix(self):
lazy_tensor = self.create_lazy_tensor().requires_grad_(True)
lazy_tensor_copy = lazy_tensor.clone().detach_().requires_grad_(True)
evaluated = self.evaluate_lazy_tensor(lazy_tensor_copy)
test_vector = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True)
test_vector_copy = lazy_tensor_copy.eager_rhss[0].clone().detach().requires_grad_(True)
# Make sure that we get no warning about CG
with gpytorch.settings.max_cg_iterations(100), warnings.catch_warnings(record=True) as w:
res = lazy_tensor.inv_matmul(test_vector)
actual = evaluated.inverse().matmul(test_vector_copy)
self.assertEqual(len(w), 0)
self.assertLess(((res - actual).abs() / actual.abs().clamp(1, 1e5)).max().item(), 3e-1)
grad = torch.randn_like(res)
# Make sure that we get a warning that CG was run
with warnings.catch_warnings(record=True) as w:
res.backward(gradient=grad)
actual.backward(gradient=grad)
self.assertEqual(len(w), 1)
for arg, arg_copy in zip(lazy_tensor.representation(), lazy_tensor_copy.representation()):
if arg_copy.grad is not None:
self.assertLess(
((arg.grad - arg_copy.grad).abs() / arg_copy.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
self.assertLess(
((test_vector.grad - test_vector_copy.grad).abs() / test_vector.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
def test_inv_matmul_matrix_with_left(self):
lazy_tensor = self.create_lazy_tensor().requires_grad_(True)
lazy_tensor_copy = lazy_tensor.clone().detach_().requires_grad_(True)
evaluated = self.evaluate_lazy_tensor(lazy_tensor_copy)
test_vector = lazy_tensor.eager_rhss[0][..., 2:].clone().detach().requires_grad_(True)
test_vector_copy = lazy_tensor_copy.eager_rhss[0][..., 2:].clone().detach().requires_grad_(True)
test_left = lazy_tensor.eager_rhss[0][..., :2].transpose(-1, -2).clone().detach().requires_grad_(True)
test_left_copy = lazy_tensor_copy.eager_rhss[0][..., :2].transpose(-1, -2).clone().detach().requires_grad_(True)
# Make sure that we get no warning about CG
with gpytorch.settings.max_cg_iterations(100), warnings.catch_warnings(record=True) as w:
res = lazy_tensor.inv_matmul(test_vector, test_left)
actual = test_left_copy @ evaluated.inverse() @ test_vector_copy
self.assertEqual(len(w), 0)
self.assertLess(((res - actual).abs() / actual.abs().clamp(1, 1e5)).max().item(), 3e-1)
grad = torch.randn_like(res)
# Make sure that we get no warning about CG
with warnings.catch_warnings(record=True) as w:
res.backward(gradient=grad)
actual.backward(gradient=grad)
self.assertEqual(len(w), 0)
for arg, arg_copy in zip(lazy_tensor.representation(), lazy_tensor_copy.representation()):
if arg_copy.grad is not None:
self.assertLess(
((arg.grad - arg_copy.grad).abs() / arg_copy.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
self.assertLess(
((test_left.grad - test_left_copy.grad).abs() / test_left.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
self.assertLess(
((test_vector.grad - test_vector_copy.grad).abs() / test_vector.grad.abs().clamp(1, 1e5)).max().item(), 3e-1
)
def test_inv_quad_logdet(self):
pass
def test_inv_quad_logdet_no_reduce(self):
pass
def test_root_inv_decomposition(self):
lazy_tensor = self.create_lazy_tensor()
root_approx = lazy_tensor.root_inv_decomposition()
test_mat = lazy_tensor.eager_rhss[0].clone().detach()
res = root_approx.matmul(test_mat)
actual = lazy_tensor.inv_matmul(test_mat)
self.assertLess(torch.norm(res - actual) / actual.norm(), 0.1)
class TestCachedCGLazyTensor(TestCachedCGLazyTensorNoLogdet):
seed = 0
def create_lazy_tensor(self):
mat = torch.randn(5, 6)
mat = mat.matmul(mat.transpose(-1, -2))
mat.requires_grad_(True)
lazy_tensor = NonLazyTensor(mat)
eager_rhs = torch.randn(5, 10).detach()
with gpytorch.settings.num_trace_samples(1000): # For inv_quad_logdet tests
solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms(
lazy_tensor, eager_rhs.detach()
)
eager_rhss = [eager_rhs.detach(), eager_rhs[..., -2:-1].detach()]
solves = [solve.detach(), solve[..., -2:-1].detach()]
return CachedCGLazyTensor(
lazy_tensor, eager_rhss, solves, probe_vecs, probe_vec_norms, probe_vec_solves, tmats
)
def evaluate_lazy_tensor(self, lazy_tensor):
return lazy_tensor.base_lazy_tensor.tensor
def test_inv_quad_logdet(self):
# Forward
lazy_tensor = self.create_lazy_tensor()
evaluated = self.evaluate_lazy_tensor(lazy_tensor)
flattened_evaluated = evaluated.view(-1, *lazy_tensor.matrix_shape)
vecs = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True)
vecs_copy = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True)
with gpytorch.settings.num_trace_samples(128), warnings.catch_warnings(record=True) as w:
res_inv_quad, res_logdet = lazy_tensor.inv_quad_logdet(inv_quad_rhs=vecs, logdet=True)
self.assertEqual(len(w), 0)
res = res_inv_quad + res_logdet
actual_inv_quad = evaluated.inverse().matmul(vecs_copy).mul(vecs_copy).sum(-2).sum(-1)
actual_logdet = torch.cat(
[torch.logdet(flattened_evaluated[i]).unsqueeze(0) for i in range(lazy_tensor.batch_shape.numel())]
).view(lazy_tensor.batch_shape)
actual = actual_inv_quad + actual_logdet
diff = (res - actual).abs() / actual.abs().clamp(1, math.inf)
self.assertLess(diff.max().item(), 15e-2)
def test_inv_quad_logdet_no_reduce(self):
# Forward
lazy_tensor = self.create_lazy_tensor()
evaluated = self.evaluate_lazy_tensor(lazy_tensor)
flattened_evaluated = evaluated.view(-1, *lazy_tensor.matrix_shape)
vecs = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True)
vecs_copy = lazy_tensor.eager_rhss[0].clone().detach().requires_grad_(True)
with gpytorch.settings.num_trace_samples(128), warnings.catch_warnings(record=True) as w:
res_inv_quad, res_logdet = lazy_tensor.inv_quad_logdet(
inv_quad_rhs=vecs, logdet=True, reduce_inv_quad=False
)
self.assertEqual(len(w), 0)
res = res_inv_quad.sum(-1) + res_logdet
actual_inv_quad = evaluated.inverse().matmul(vecs_copy).mul(vecs_copy).sum(-2).sum(-1)
actual_logdet = torch.cat(
[torch.logdet(flattened_evaluated[i]).unsqueeze(0) for i in range(lazy_tensor.batch_shape.numel())]
).view(lazy_tensor.batch_shape)
actual = actual_inv_quad + actual_logdet
diff = (res - actual).abs() / actual.abs().clamp(1, math.inf)
self.assertLess(diff.max().item(), 15e-2)
class TestCachedCGLazyTensorNoLogdetBatch(TestCachedCGLazyTensorNoLogdet):
seed = 0
def create_lazy_tensor(self):
mat = torch.randn(3, 5, 6)
mat = mat.matmul(mat.transpose(-1, -2))
mat.requires_grad_(True)
with gpytorch.settings.num_trace_samples(1000): # For inv_quad_logdet tests
lazy_tensor = NonLazyTensor(mat)
eager_rhs = torch.randn(3, 5, 10).detach()
solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms(
lazy_tensor, eager_rhs.detach(), logdet_terms=False
)
return CachedCGLazyTensor(
lazy_tensor, [eager_rhs], [solve], probe_vecs, probe_vec_norms, probe_vec_solves, tmats
)
def evaluate_lazy_tensor(self, lazy_tensor):
return lazy_tensor.base_lazy_tensor.tensor
def test_inv_matmul_vec(self):
pass
def test_inv_matmul_vector_with_left(self):
pass
class TestCachedCGLazyTensorBatch(TestCachedCGLazyTensor):
seed = 0
def create_lazy_tensor(self):
mat = torch.randn(3, 5, 6)
mat = mat.matmul(mat.transpose(-1, -2))
mat.requires_grad_(True)
with gpytorch.settings.num_trace_samples(1000): # For inv_quad_logdet tests
lazy_tensor = NonLazyTensor(mat)
eager_rhs = torch.randn(3, 5, 10).detach()
solve, probe_vecs, probe_vec_norms, probe_vec_solves, tmats = CachedCGLazyTensor.precompute_terms(
lazy_tensor, eager_rhs.detach()
)
return CachedCGLazyTensor(
lazy_tensor, [eager_rhs], [solve], probe_vecs, probe_vec_norms, probe_vec_solves, tmats
)
def evaluate_lazy_tensor(self, lazy_tensor):
return lazy_tensor.base_lazy_tensor.tensor
def test_inv_matmul_vec(self):
pass
def test_inv_matmul_vector_with_left(self):
pass
| 45.730519 | 120 | 0.653177 | 1,856 | 14,085 | 4.674569 | 0.076509 | 0.122176 | 0.051637 | 0.05302 | 0.93603 | 0.932918 | 0.930152 | 0.92266 | 0.915053 | 0.907446 | 0 | 0.019289 | 0.223358 | 14,085 | 307 | 121 | 45.879479 | 0.773837 | 0.034718 | 0 | 0.770833 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1125 | 1 | 0.0875 | false | 0.025 | 0.029167 | 0.016667 | 0.183333 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
715aad0ad5432c527bf0604bc6dfb1fb94ad411e | 139 | py | Python | MillerArrays/millerArraySymmetry.py | MooersLab/jupyterlabcctbxsnips | c5f0947b4e8c4e5839b9b6b15c81c62915103155 | [
"MIT"
] | null | null | null | MillerArrays/millerArraySymmetry.py | MooersLab/jupyterlabcctbxsnips | c5f0947b4e8c4e5839b9b6b15c81c62915103155 | [
"MIT"
] | null | null | null | MillerArrays/millerArraySymmetry.py | MooersLab/jupyterlabcctbxsnips | c5f0947b4e8c4e5839b9b6b15c81c62915103155 | [
"MIT"
] | null | null | null | [print("Miller Array %s: %s" % (i, miller_array.info().crystal_symmetry_from_file)) for i, miller_array in list(enumerate(miller_arrays))]
| 69.5 | 138 | 0.755396 | 22 | 139 | 4.5 | 0.681818 | 0.333333 | 0.242424 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.086331 | 139 | 1 | 139 | 139 | 0.779528 | 0 | 0 | 0 | 0 | 0 | 0.136691 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 7 |
718a1428e2841fb25bc2cae5cd0dcf159fce0add | 4,928 | py | Python | free.py | ferdiansyah420/fer.di | 13246233998f19b99af2e906037ea2180a9a80a3 | [
"Apache-2.0"
] | null | null | null | free.py | ferdiansyah420/fer.di | 13246233998f19b99af2e906037ea2180a9a80a3 | [
"Apache-2.0"
] | null | null | null | free.py | ferdiansyah420/fer.di | 13246233998f19b99af2e906037ea2180a9a80a3 | [
"Apache-2.0"
] | null | null | null | # Author : ./R15K1 | V4N654T
import zlib, base64
exec(zlib.decompress(base64.b64decode("eJztmk/LZkcRxdfOp3hIFpkBjQQSESUL14ILETchq5nEjMi8MCTgwg+vy0ziTG53159fnXvO7oHuOqee21VdXd3PPn68fHr1+s0/vvzh+29/8/tnHz/+9MP33z29ffzh8elv//rZF3/+7PGfx98//8vvvvj8b8/+h1dffvXJ0y/jk18/fnHYlTEBKKLpoCx1rf5/LGQ8o2pYYr3EdbwnTO/O/dCvZJR/po51IZxnCayoPbWZcocW+u810raSC30+7yU9RNwlUcKqW4/fYRPTWextxNWs0nw1ZHssmHNcA18tJdS7Y1lxJHmjsv/7HfubmmqnJZs/UHXo0NZ0fCUzE1gvscLeh3GCt0D1EqELISIdVC8RuhAi0kH1EqELISIdVC8RuhAi0kH1EqELISIdVC8RuhAi0kH1EqELISIdWC+xwt6L3luAHlC9hOiKavK7Ea/UiHcPXgZgL4HSCKmOAayXRGFETfHAekkURsgkLpr8eiEDxHiLB9VLiC43EziA6PJ+BtzPOnakzi10AGELuF6SlJG05IHrJUkZSUseuF6SlJG05IHrJUkZSUseuF6SlJG05IHrJUkZSUseuF6SlLkVAmyF7E87nLo93b2QFFC9hOiqfBSmOuYETu5O7hmApJdkUL0k6CJoyAfWS6ywn2CKzjNgvcQK+xnmKA3DZJcna38KkL9iwEW+UJHv8l4GYC/B0n4MZzahzHY8dXu6Yn5zaAiFhoNCBmAvwdJ+BCc2ocR2PHV7Oju9lfYHRDDZ5cnan8bLvwisl1hhP8McpSfAeokV9hNM0XkGqpcEXe9qICjKB9VLiC4f/IAHv46jW+dZcwBhC7hekpSRtOSB6yVJGUlLHrhekpSRtOSB6yVJGUlLHrhekpSRtOSB6yVJGUlLHrhekpS5FQJshexPO5y6Pd29kBRQvYTocmufA4gu72fA/cytfRxhC7hekpSRtOSB6yVJGUlLHrhekpSRtOSB6yVJGUlLHrhekpSRtOSB6yVJGUlLHrhekpS5FQJshexPO5y6Pd29kBRQvYTouiIjaswJnASLVTkFzjDQat5hWazKUbkwJpKvxkj4n921daetmWjDSULLlhRp7bbaS/iQ6MDIWbjI5ZRot+9fdGWmVZm5NGMQBBtwmIqFqQNVCFQvIbqcvIDJy490cYQt4HpJUkbSkgeulyRlJC154HpJUkbSkgeulyRlJC154HpJUkbSkgeulyRlJC154HpJUuZWCLAVsj/tcOr2dPdCUkD1EqLLj3SbpyWb951zIOGyPk/wBE/wBE9on+ACxQXK8fTmAsVrWGwN33IVq4LqJUSXkxcwefnFGI6wBVwvScpIWvLA9ZKkjKQlD1wvScpIWvLA9ZKkjKQlD1wvScpIWvLA9ZKkjKQlD1wvScrcCgG2QvanHU7dnu5eSAqoXkJ0+TVY4rRk875sPSXsDkJHllhkObaWxoQQpaCLuJK3wceev9VpVijNOsEujMmanWPfMXGiyoGxMCaHeSZZN3urs+ULKspYlHCPqRlzAm+m7pDFg9X9cgyJxZCjSAhULyG6XGw4UfY44yTJAdhLmDTnwuZpyeZdNJ4TwkI2CVQvIboIC8VJ0N2neBBWdje/I8vlRQaKY+sWV6OVvG15r4bYaVUorTqhLozJmp1j3zGxO81BsTAmCK5CBnM1EK+zFP0hDf87MnecT0m2HK9o32J5synrcxB2FRdL7njGg9XNdAyJxZCjSAhYL7HCPoCJmtdB9RKhCyEiHVQvEboQItJB9RKhCyEiHVQvEboQItJB9RKhCyEiHVQvEboQItJB9RKhCyEiHVgvscLeD99MJE5LNu+biVPCRVHLPniCJ3iCJ3hC+wRfFIdMSzbfUVrolDP7w23ABmzABmzABmzABmzABpgGrg3PG1V7jqzmKTzXEG4eELzFTq7QLUk782M9rmhjjlG/2pXXuexHa+BtcJIZDCXVzgJJ1+o74M+/GVgEyL43wWqmTsqLrLhMjxNUz8hdLTNIuhiR5+iyC8j0OXc/AtLGZEA7+yMTxO6MEFTTgr8AnWiTs2Yryd/lvH9Ej0lAa8dijM9jhM7ivU1foZF4zGLvo9Yuoat5k0odUFt4EGtVW6J8WrL5vWmHvpQ1no7A/GCBBroJHLPlqhy4C2OSqEcR+eqngipLjmatV0fSzFhMK5e81lld8giVPC521ocu6ifEVB1JHyN5WcFJunlv0fsH7Rq4j3tZECaZdvCx16xoOsTFyjxC72EqlAdvfiIH78DPlVrHJMDPlXJmhEA9598i3TcTkxe77CEDQlxJm3bK+VAZsV5iREDwrMqtULT3iKKoWcX80j0DtwmAKPL5y4g2Jhhj6pIxQueTy2dXdH84+Jo9ALKHNOG2fdYq8oYePSYa+PU2jKyJ8TqvbHpuoWz3jpafJo6JhnOqBON1XlARvmN/U1PttGTz26oO3dmajj6RQg20mndYVqpySC6MiWcNBnnjLyOKvFeJh7NbuSrnuIUxsYwzSLoYb/wPhqtCbUFjGTWpuokV41zRp4uMWarEu5INvMCYCJEk/fHQG0OwuDv0CCQWzdydyGNqxpzATSE3hTKQRshMh0q8srVrqsF2olLCprXpkJhGssw48KYAQVxNKLdEu6rx2yxR5T2DeExjM/rg6SeQ8eh/wchcNan2HZZ+AnlGGCaqrZi6yM1oCzuJCCWR46nb07VSSdWiBc55dygtj00cE42efU35xUwL43Xea9q8kQtt5N7Cj4fbgA3YgA3YgA3YgA3YgA0wDeyc72hNjoljYtHQQaCf2IZSXmQtSRNc92eQtFG7XyrB2Uq8wrt9xRMPd4orVblVjDcPAd1LqL50Wc7HzPA+UOWkvDAmnHQGCYa2nFj0G/ac5+/Qk7mDj5dZI5VRj/HBujQTjux24YK1WJXL1YUxuQYcXFLB5chaGLM+1Nfi8WPiIFugtBNW8mH2Te6RbAZJG7XvwiU4W4l9F86almze1XYXIfQWNhh0L6H6fBdOnZZs3nfh54S+C+fT+i68jjFW1V0WjGizSa6jVWQTSay8ZxA6la5ifUEeD0yjP9tCvH0Hl1t2h4S+IJ8yJgPKV2RJVzde2vFjUiB8b38XvhqyqgrCkSDF10NZx8ns3m6MpfX4zDuP85h2Y3bNlAgIFgXljHVuiX8tbQeha7Gqe1nYJY2AWLEmXkndYfes5pXP/9ucRSrvEEeulDmEu7QzgnYG1wHnmPUyjXCXdsi6GcEVyCnahWimvIOPMazB/e9FPcyL3zusnjv4eJm1d9VeHzp0j4OQNNCNbcl4W+hk6yRWfm7h53mtYwKgmrlL/mLQd2ymlF1Hi4y410932WfHFoa5ZLf4WyDcibGPSyun1C4cW8cEQHXDn5Nj26jhe94w3kHl5V2KyTmX0EkkIULYJzU8T+NeLx/nmA9YyRWsR+4/rCfsLOeFS0fdjaeNFlkN17KmKbvNctWvKxbowiXphihuTx7LB4yDUrIYQU5jQrztLXWXxBVUEw+/bcTkwJ/4IV0xudqFETqBdfG6BgXT9fBWZlBRx6TTShU17caKbL+eEe2RH/S1jgmAakXtB30sVvmKbsyDvoYvIXqa7qa8yBqprMNLP12cwZP/nYIZFsXoLo9Oyjv4uM7qs1L0mAAga8kWOp+VZMg6eMeclWrt1zDe5Q6py1GRWrvabCNRD6NkOOD+QR84mWydxJKRt8PlU2b0mACo7q8+ZbJYfcrcG+tTJs1+HSNy7Q5l1Sz7GgoJjF/TaWl1+vQGThexXEC0LBbdvU5ufVTR4bLx+DrvVpTgGmLyVtvYJgF5mCoE4+VYRgfhYEbRf/A678QTeylRDys66HwT1zomAKrr2DdxLFbyzldO5Ju4wfYTGAUMnJuf1ueKsjvuhV8wc5wUwgkGVNpVMvn0nKZt13K8on2L5SHdmfTTl2n/bl9pwD2G1jEB0NqFTujU/vAmvh7KUtqkdoIzZPyYYIxZ2WOEzicnn3xmEe0Qgtq1/YRLzMvqWK2RGjVtnxBfLg/kHbONtu6jZJ83tLkqEKSsYi10jVzOkbUNI+wiVguXHt4qoqIYdad/yphoCO/ZLWRNjNd5r2nL9kDvmySn3b5pyeZrXx/1ca5jkXDUewEbsAEbsAEbsAEbsAEbsIGz4W41RY+JhltNEozXeUFPctydqVTl9gzePAR0L6H60mU5HzPD+0CVk/LCmAzeFEg+H2mirVs8cu9U+lgxK2M6LTGTRGnC/ZFZgoTj/Ta9lTpab0P/fyitEztxTDTwS2gYWRPjdV53j/OnJZt397iLENq3DAbdS6g+d4+p05LNu3t8TjisAdhMTC4wS8lGXzpIH0xwS2U4KzJrzyApZXQRVajK5dPCmKzZOfYdEyeqHBgLY86nROAWNX0bZRWrYoVNjiFk0pEgVguXHt4qoqIYxaaCu4SlfMDskd3ib4FwE0+LbEa0R/PfaIXgBpEs/V/OzIaDgu8+HxVe68xjvM57Tdut9+sy++7A+1YqjPBYnw3YgA3YgA3YgA3YgA3YAMHAzokV3ecZMiYabjVJMF7n3b4iiYe7M+7OxIL5vWgAu5EuzTmNGSMHqpzZFsYkUc8iArCWMnP/2ARl0qco7pecQcLg5X5FbyEgHunGRd1qlFt8zayia7+Otto3OaeIh/h8RtqYC5CtreRCqoyPlifS9DCTiBJvNbEPULNpdUg2eaO1qf2hUs8S9PYftEd+6hQ9JgGtN99jfFYvNuq5yUXBztgPZrubtEGxlcnJh/z6j9/8+5uXzz/66NN/Pr1+8/yrl9+9ff6vb948f/3ixePbp7eP14/Xbx6vvn7x4tmvnv0Xz0sdgg=="))) | 1,642.666667 | 4,879 | 0.964286 | 152 | 4,928 | 31.263158 | 0.973684 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.15064 | 0.001826 | 4,928 | 3 | 4,879 | 1,642.666667 | 0.81541 | 0.005276 | 0 | 0 | 0 | 0.5 | 0.986737 | 0.986737 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | null | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 10 |
71b5b82b5c433e8354c9e7aa8964f39df8b1cd81 | 82 | py | Python | 001133SelfeduPy/Selfedu001133PyBegin_v07_Str_02_ord_20200415.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | 001133SelfeduPy/Selfedu001133PyBegin_v07_Str_02_ord_20200415.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | 001133SelfeduPy/Selfedu001133PyBegin_v07_Str_02_ord_20200415.py | SafonovMikhail/python_000577 | 739f764e80f1ca354386f00b8e9db1df8c96531d | [
"Apache-2.0"
] | null | null | null | # выведение кода символа в строке
print(ord("a"))
print(ord('A'))
print(ord('0'))
| 16.4 | 33 | 0.658537 | 14 | 82 | 3.857143 | 0.642857 | 0.444444 | 0.333333 | 0.518519 | 0.481481 | 0 | 0 | 0 | 0 | 0 | 0 | 0.013699 | 0.109756 | 82 | 4 | 34 | 20.5 | 0.726027 | 0.378049 | 0 | 0 | 0 | 0 | 0.061224 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 7 |
e0910c4cbfdc5c25fa064784616a5c37e18bf407 | 16,293 | py | Python | lib/jnpr/healthbot/swagger/api/system_api.py | minefuto/healthbot-py-client | bb81452c974456af44299aebf32a73abeda8a943 | [
"Apache-2.0"
] | null | null | null | lib/jnpr/healthbot/swagger/api/system_api.py | minefuto/healthbot-py-client | bb81452c974456af44299aebf32a73abeda8a943 | [
"Apache-2.0"
] | null | null | null | lib/jnpr/healthbot/swagger/api/system_api.py | minefuto/healthbot-py-client | bb81452c974456af44299aebf32a73abeda8a943 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
"""
Healthbot APIs
API interface for Healthbot application # noqa: E501
OpenAPI spec version: 1.0.0
Contact: healthbot-hackers@juniper.net
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from jnpr.healthbot.swagger.api_client import ApiClient
class SystemApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def retrieve_available_nodes(self, **kwargs): # noqa: E501
"""List of available nodes # noqa: E501
Get the list of available nodes in the installation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_available_nodes(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str authorization: authentication header object
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.retrieve_available_nodes_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.retrieve_available_nodes_with_http_info(**kwargs) # noqa: E501
return data
def retrieve_available_nodes_with_http_info(self, **kwargs): # noqa: E501
"""List of available nodes # noqa: E501
Get the list of available nodes in the installation. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_available_nodes_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str authorization: authentication header object
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['authorization'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method retrieve_available_nodes" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'multipart/form-data']) # noqa: E501
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/nodes/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def retrieve_sensor_device_group(self, device_group_name, **kwargs): # noqa: E501
"""Get all All API's. # noqa: E501
GET sensors subscribed for a device-group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_sensor_device_group(device_group_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str device_group_name: Device Group (required)
:param str authorization: authentication header object
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.retrieve_sensor_device_group_with_http_info(device_group_name, **kwargs) # noqa: E501
else:
(data) = self.retrieve_sensor_device_group_with_http_info(device_group_name, **kwargs) # noqa: E501
return data
def retrieve_sensor_device_group_with_http_info(self, device_group_name, **kwargs): # noqa: E501
"""Get all All API's. # noqa: E501
GET sensors subscribed for a device-group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_sensor_device_group_with_http_info(device_group_name, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str device_group_name: Device Group (required)
:param str authorization: authentication header object
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['device_group_name', 'authorization'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method retrieve_sensor_device_group" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'device_group_name' is set
if ('device_group_name' not in params or
params['device_group_name'] is None):
raise ValueError("Missing the required parameter `device_group_name` when calling `retrieve_sensor_device_group`") # noqa: E501
collection_formats = {}
path_params = {}
if 'device_group_name' in params:
path_params['device_group_name'] = params['device_group_name'] # noqa: E501
query_params = []
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'multipart/form-data']) # noqa: E501
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/sensor/device-group/{device_group_name}/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def retrieve_system_details(self, **kwargs): # noqa: E501
"""Retrieve system details. # noqa: E501
Retrieve system details for HealthBot system. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_system_details(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str authorization: authentication header object
:param str service_name: service name takes in the name of the service for which details are required.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.retrieve_system_details_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.retrieve_system_details_with_http_info(**kwargs) # noqa: E501
return data
def retrieve_system_details_with_http_info(self, **kwargs): # noqa: E501
"""Retrieve system details. # noqa: E501
Retrieve system details for HealthBot system. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_system_details_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str authorization: authentication header object
:param str service_name: service name takes in the name of the service for which details are required.
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['authorization', 'service_name'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method retrieve_system_details" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if 'service_name' in params:
query_params.append(('service_name', params['service_name'])) # noqa: E501
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'multipart/form-data']) # noqa: E501
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/system-details/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def retrieve_tsdb_counters(self, **kwargs): # noqa: E501
"""TSDB counters # noqa: E501
Get TSDB counters # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_tsdb_counters(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str authorization: authentication header object
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.retrieve_tsdb_counters_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.retrieve_tsdb_counters_with_http_info(**kwargs) # noqa: E501
return data
def retrieve_tsdb_counters_with_http_info(self, **kwargs): # noqa: E501
"""TSDB counters # noqa: E501
Get TSDB counters # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.retrieve_tsdb_counters_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str authorization: authentication header object
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['authorization'] # noqa: E501
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method retrieve_tsdb_counters" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
if 'authorization' in params:
header_params['Authorization'] = params['authorization'] # noqa: E501
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'multipart/form-data']) # noqa: E501
# Authentication setting
auth_settings = [] # noqa: E501
return self.api_client.call_api(
'/tsdb-counters/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None, # noqa: E501
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| 38.156909 | 140 | 0.618977 | 1,846 | 16,293 | 5.201517 | 0.091008 | 0.053322 | 0.026557 | 0.029994 | 0.902208 | 0.900437 | 0.885753 | 0.864924 | 0.864924 | 0.864924 | 0 | 0.017465 | 0.293623 | 16,293 | 426 | 141 | 38.246479 | 0.816839 | 0.336893 | 0 | 0.790909 | 1 | 0 | 0.180791 | 0.043584 | 0 | 0 | 0 | 0 | 0 | 1 | 0.040909 | false | 0 | 0.018182 | 0 | 0.118182 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
1cae01e7c43e78fa82b39e3341e645d311876aea | 11,087 | py | Python | env/lib/python3.7/site-packages/docusign_esign/apis/organizations_api.py | davidgacc/docusign | e63167101656d0066d481844576ce687ea80eb91 | [
"MIT"
] | null | null | null | env/lib/python3.7/site-packages/docusign_esign/apis/organizations_api.py | davidgacc/docusign | e63167101656d0066d481844576ce687ea80eb91 | [
"MIT"
] | null | null | null | env/lib/python3.7/site-packages/docusign_esign/apis/organizations_api.py | davidgacc/docusign | e63167101656d0066d481844576ce687ea80eb91 | [
"MIT"
] | 1 | 2021-12-20T11:44:00.000Z | 2021-12-20T11:44:00.000Z | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..client.configuration import Configuration
from ..client.api_client import ApiClient
class OrganizationsApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def delete_report(self, organization_id, report_correlation_id, **kwargs):
"""
Retrieves org level report by correlation id and site.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_report(organization_id, report_correlation_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str organization_id: (required)
:param str report_correlation_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.delete_report_with_http_info(organization_id, report_correlation_id, **kwargs)
else:
(data) = self.delete_report_with_http_info(organization_id, report_correlation_id, **kwargs)
return data
def delete_report_with_http_info(self, organization_id, report_correlation_id, **kwargs):
"""
Retrieves org level report by correlation id and site.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.delete_report_with_http_info(organization_id, report_correlation_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str organization_id: (required)
:param str report_correlation_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['organization_id', 'report_correlation_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method delete_report" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'organization_id' is set
if ('organization_id' not in params) or (params['organization_id'] is None):
raise ValueError("Missing the required parameter `organization_id` when calling `delete_report`")
# verify the required parameter 'report_correlation_id' is set
if ('report_correlation_id' not in params) or (params['report_correlation_id'] is None):
raise ValueError("Missing the required parameter `report_correlation_id` when calling `delete_report`")
collection_formats = {}
resource_path = '/v2.1/organization_reporting/{organizationId}/reports/{reportCorrelationId}'.replace('{format}', 'json')
path_params = {}
if 'organization_id' in params:
path_params['organizationId'] = params['organization_id']
if 'report_correlation_id' in params:
path_params['reportCorrelationId'] = params['report_correlation_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_report(self, organization_id, report_correlation_id, **kwargs):
"""
Retrieves org level report by correlation id and site.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_report(organization_id, report_correlation_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str organization_id: (required)
:param str report_correlation_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_report_with_http_info(organization_id, report_correlation_id, **kwargs)
else:
(data) = self.get_report_with_http_info(organization_id, report_correlation_id, **kwargs)
return data
def get_report_with_http_info(self, organization_id, report_correlation_id, **kwargs):
"""
Retrieves org level report by correlation id and site.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.get_report_with_http_info(organization_id, report_correlation_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str organization_id: (required)
:param str report_correlation_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['organization_id', 'report_correlation_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_report" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'organization_id' is set
if ('organization_id' not in params) or (params['organization_id'] is None):
raise ValueError("Missing the required parameter `organization_id` when calling `get_report`")
# verify the required parameter 'report_correlation_id' is set
if ('report_correlation_id' not in params) or (params['report_correlation_id'] is None):
raise ValueError("Missing the required parameter `report_correlation_id` when calling `get_report`")
collection_formats = {}
resource_path = '/v2.1/organization_reporting/{organizationId}/reports/{reportCorrelationId}'.replace('{format}', 'json')
path_params = {}
if 'organization_id' in params:
path_params['organizationId'] = params['organization_id']
if 'report_correlation_id' in params:
path_params['reportCorrelationId'] = params['report_correlation_id']
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
# Authentication setting
auth_settings = []
return self.api_client.call_api(resource_path, 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| 42.972868 | 140 | 0.602778 | 1,146 | 11,087 | 5.576789 | 0.150087 | 0.06916 | 0.089188 | 0.067908 | 0.900172 | 0.888437 | 0.888437 | 0.876545 | 0.876545 | 0.876545 | 0 | 0.001591 | 0.319654 | 11,087 | 257 | 141 | 43.140078 | 0.845685 | 0.316858 | 0 | 0.738095 | 0 | 0 | 0.2039 | 0.077144 | 0 | 0 | 0 | 0 | 0 | 1 | 0.039683 | false | 0 | 0.055556 | 0 | 0.150794 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
e8000490d7de12f6f54f07c5ab8a774c7ea4d259 | 24,658 | py | Python | src/myjob/core/migrations/0001_initial.py | noutc123/Myjob | a609559b0793d9fe624e51d540bfbcfa84a8fc72 | [
"MIT"
] | 1 | 2022-01-21T10:32:08.000Z | 2022-01-21T10:32:08.000Z | src/myjob/core/migrations/0001_initial.py | noutc123/Myjob | a609559b0793d9fe624e51d540bfbcfa84a8fc72 | [
"MIT"
] | null | null | null | src/myjob/core/migrations/0001_initial.py | noutc123/Myjob | a609559b0793d9fe624e51d540bfbcfa84a8fc72 | [
"MIT"
] | null | null | null | # Generated by Django 4.0 on 2022-01-10 01:12
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='Job',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('titre', models.CharField(max_length=200)),
('type_contrat', models.CharField(choices=[('TEMP PLEIN ', 'TEMP PLEIN '), ('PERMANENT', 'PERMANENT'), ('OCCASIONNEL', 'OCCASIONNEL'), ('STAGE', 'STAGE'), ('FREELANCER', 'FREELANCER'), ('TEMP PARTIEL', 'TEMP PARTIEL'), ('CONTRACTUEL', 'CONTRACTUEL')], max_length=50)),
('salaire_min', models.PositiveIntegerField(default=0)),
('date_debut', models.DateTimeField(auto_now_add=True)),
('date_fin', models.DateTimeField()),
('description', models.TextField()),
('salaire_max', models.PositiveIntegerField(default=0)),
('Job_statue', models.CharField(choices=[('draft', 'en attente'), ('bad', 'refuser'), ('poster', 'ok')], max_length=150)),
('work_location', models.CharField(choices=[('AF', 'Afghanistan'), ('ZA', 'Afrique du Sud'), ('AL', 'Albanie'), ('DZ', 'Algérie'), ('DE', 'Allemagne'), ('AD', 'Andorre'), ('AO', 'Angola'), ('AI', 'Anguilla'), ('AQ', 'Antarctique'), ('AG', 'Antigua-et-Barbuda'), ('AN', 'Antilles néerlandaises'), ('SA', 'Arabie saoudite'), ('AR', 'Argentine'), ('AM', 'Arménie'), ('AW', 'Aruba'), ('AU', 'Australie'), ('AT', 'Autriche'), ('AZ', 'Azerbaïdjan'), ('BS', 'Bahamas'), ('BH', 'Bahreïn'), ('BD', 'Bangladesh'), ('BB', 'Barbade'), ('BY', 'Bélarus'), ('BE', 'Belgique'), ('BZ', 'Belize'), ('BJ', 'Bénin'), ('BM', 'Bermudes'), ('BT', 'Bhoutan'), ('BO', 'Bolivie'), ('BA', 'Bosnie-Herzégovine'), ('BW', 'Botswana'), ('BR', 'Brésil'), ('BN', 'Brunéi Darussalam'), ('BG', 'Bulgarie'), ('BF', 'Burkina Faso'), ('BI', 'Burundi'), ('KH', 'Cambodge'), ('CM', 'Cameroun'), ('CA', 'Canada'), ('CV', 'Cap-Vert'), ('EA', 'Ceuta et Melilla'), ('CL', 'Chili'), ('CN', 'Chine'), ('CY', 'Chypre'), ('CO', 'Colombie'), ('KM', 'Comores'), ('CG', 'Congo-Brazzaville'), ('KP', 'Corée du Nord'), ('KR', 'Corée du Sud'), ('CR', 'Costa Rica'), ('CI', 'Côte d’Ivoire'), ('HR', 'Croatie'), ('CU', 'Cuba'), ('DK', 'Danemark'), ('DG', 'Diego Garcia'), ('DJ', 'Djibouti'), ('DM', 'Dominique'), ('EG', 'Égypte'), ('SV', 'El Salvador'), ('AE', 'Émirats arabes unis'), ('EC', 'Équateur'), ('ER', 'Érythrée'), ('ES', 'Espagne'), ('EE', 'Estonie'), ('VA', 'État de la Cité du Vatican'), ('FM', 'États fédérés de Micronésie'), ('US', 'États-Unis'), ('ET', 'Éthiopie'), ('FJ', 'Fidji'), ('FI', 'Finlande'), ('FR', 'France'), ('GA', 'Gabon'), ('GM', 'Gambie'), ('GE', 'Géorgie'), ('GS', 'Géorgie du Sud et les îles Sandwich du Sud'), ('GH', 'Ghana'), ('GI', 'Gibraltar'), ('GR', 'Grèce'), ('GD', 'Grenade'), ('GL', 'Groenland'), ('GP', 'Guadeloupe'), ('GU', 'Guam'), ('GT', 'Guatemala'), ('GG', 'Guernesey'), ('GN', 'Guinée'), ('GQ', 'Guinée équatoriale'), ('GW', 'Guinée-Bissau'), ('GY', 'Guyana'), ('GF', 'Guyane française'), ('HT', 'Haïti'), ('HN', 'Honduras'), ('HU', 'Hongrie'), ('BV', 'Île Bouvet'), ('CX', 'Île Christmas'), ('CP', 'Île Clipperton'), ('AC', "Île de l'Ascension"), ('IM', 'Île de Man'), ('NF', 'Île Norfolk'), ('AX', 'Îles Åland'), ('KY', 'Îles Caïmans'), ('IC', 'Îles Canaries'), ('CC', 'Îles Cocos - Keeling'), ('CK', 'Îles Cook'), ('FO', 'Îles Féroé'), ('HM', 'Îles Heard et MacDonald'), ('FK', 'Îles Malouines'), ('MP', 'Îles Mariannes du Nord'), ('MH', 'Îles Marshall'), ('UM', 'Îles Mineures Éloignées des États-Unis'), ('SB', 'Îles Salomon'), ('TC', 'Îles Turks et Caïques'), ('VG', 'Îles Vierges britanniques'), ('VI', 'Îles Vierges des États-Unis'), ('IN', 'Inde'), ('ID', 'Indonésie'), ('IQ', 'Irak'), ('IR', 'Iran'), ('IE', 'Irlande'), ('IS', 'Islande'), ('IL', 'Israël'), ('IT', 'Italie'), ('JM', 'Jamaïque'), ('JP', 'Japon'), ('JE', 'Jersey'), ('JO', 'Jordanie'), ('KZ', 'Kazakhstan'), ('KE', 'Kenya'), ('KG', 'Kirghizistan'), ('KI', 'Kiribati'), ('KW', 'Koweït'), ('LA', 'Laos'), ('LS', 'Lesotho'), ('LV', 'Lettonie'), ('LB', 'Liban'), ('LR', 'Libéria'), ('LY', 'Libye'), ('LI', 'Liechtenstein'), ('LT', 'Lituanie'), ('LU', 'Luxembourg'), ('MK', 'Macédoine'), ('MG', 'Madagascar'), ('MY', 'Malaisie'), ('MW', 'Malawi'), ('MV', 'Maldives'), ('ML', 'Mali'), ('MT', 'Malte'), ('MA', 'Maroc'), ('MQ', 'Martinique'), ('MU', 'Maurice'), ('MR', 'Mauritanie'), ('YT', 'Mayotte'), ('MX', 'Mexique'), ('MD', 'Moldavie'), ('MC', 'Monaco'), ('MN', 'Mongolie'), ('ME', 'Monténégro'), ('MS', 'Montserrat'), ('MZ', 'Mozambique'), ('MM', 'Myanmar'), ('NA', 'Namibie'), ('NR', 'Nauru'), ('NP', 'Népal'), ('NI', 'Nicaragua'), ('NE', 'Niger'), ('NG', 'Nigéria'), ('NU', 'Niue'), ('NO', 'Norvège'), ('NC', 'Nouvelle-Calédonie'), ('NZ', 'Nouvelle-Zélande'), ('OM', 'Oman'), ('UG', 'Ouganda'), ('UZ', 'Ouzbékistan'), ('PK', 'Pakistan'), ('PW', 'Palaos'), ('PA', 'Panama'), ('PG', 'Papouasie-Nouvelle-Guinée'), ('PY', 'Paraguay'), ('NL', 'Pays-Bas'), ('PE', 'Pérou'), ('PH', 'Philippines'), ('PN', 'Pitcairn'), ('PL', 'Pologne'), ('PF', 'Polynésie française'), ('PR', 'Porto Rico'), ('PT', 'Portugal'), ('QA', 'Qatar'), ('HK', 'R.A.S. chinoise de Hong Kong'), ('MO', 'R.A.S. chinoise de Macao'), ('QO', 'régions éloignées de l’Océanie'), ('CF', 'République centrafricaine'), ('CD', 'République démocratique du Congo'), ('DO', 'République dominicaine'), ('CZ', 'République tchèque'), ('RE', 'Réunion'), ('RO', 'Roumanie'), ('GB', 'Royaume-Uni'), ('RU', 'Russie'), ('RW', 'Rwanda'), ('EH', 'Sahara occidental'), ('BL', 'Saint-Barthélémy'), ('KN', 'Saint-Kitts-et-Nevis'), ('SM', 'Saint-Marin'), ('MF', 'Saint-Martin'), ('PM', 'Saint-Pierre-et-Miquelon'), ('VC', 'Saint-Vincent-et-les Grenadines'), ('SH', 'Sainte-Hélène'), ('LC', 'Sainte-Lucie'), ('WS', 'Samoa'), ('AS', 'Samoa américaines'), ('ST', 'Sao Tomé-et-Principe'), ('SN', 'Sénégal'), ('RS', 'Serbie'), ('CS', 'Serbie-et-Monténégro'), ('SC', 'Seychelles'), ('SL', 'Sierra Leone'), ('SG', 'Singapour'), ('SK', 'Slovaquie'), ('SI', 'Slovénie'), ('SO', 'Somalie'), ('SD', 'Soudan'), ('LK', 'Sri Lanka'), ('SE', 'Suède'), ('CH', 'Suisse'), ('SR', 'Suriname'), ('SJ', 'Svalbard et Île Jan Mayen'), ('SZ', 'Swaziland'), ('SY', 'Syrie'), ('TJ', 'Tadjikistan'), ('TW', 'Taïwan'), ('TZ', 'Tanzanie'), ('TD', 'Tchad'), ('TF', 'Terres australes françaises'), ('IO', "Territoire britannique de l'océan Indien"), ('PS', 'Territoire palestinien'), ('TH', 'Thaïlande'), ('TL', 'Timor oriental'), ('TG', 'Togo'), ('TK', 'Tokelau'), ('TO', 'Tonga'), ('TT', 'Trinité-et-Tobago'), ('TA', 'Tristan da Cunha'), ('TN', 'Tunisie'), ('TM', 'Turkménistan'), ('TR', 'Turquie'), ('TV', 'Tuvalu'), ('UA', 'Ukraine'), ('EU', 'Union européenne'), ('UY', 'Uruguay'), ('VU', 'Vanuatu'), ('VE', 'Venezuela'), ('VN', 'Viêt Nam'), ('WF', 'Wallis-et-Futuna'), ('YE', 'Yémen'), ('ZM', 'Zambie'), ('ZW', 'Zimbabwe')], max_length=200)),
('nombres_experiences', models.PositiveIntegerField(default=0)),
],
options={
'ordering': ('date_debut', 'date_fin', 'Job_statue'),
'abstract': False,
},
),
migrations.CreateModel(
name='Metier',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nom', models.CharField(max_length=200)),
('domaine', models.CharField(max_length=200)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ProfilUser',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('location', models.CharField(max_length=200)),
('Description', models.TextField()),
('adresse', models.CharField(max_length=50)),
('nationalite', models.CharField(choices=[('AF', 'Afghanistan'), ('ZA', 'Afrique du Sud'), ('AL', 'Albanie'), ('DZ', 'Algérie'), ('DE', 'Allemagne'), ('AD', 'Andorre'), ('AO', 'Angola'), ('AI', 'Anguilla'), ('AQ', 'Antarctique'), ('AG', 'Antigua-et-Barbuda'), ('AN', 'Antilles néerlandaises'), ('SA', 'Arabie saoudite'), ('AR', 'Argentine'), ('AM', 'Arménie'), ('AW', 'Aruba'), ('AU', 'Australie'), ('AT', 'Autriche'), ('AZ', 'Azerbaïdjan'), ('BS', 'Bahamas'), ('BH', 'Bahreïn'), ('BD', 'Bangladesh'), ('BB', 'Barbade'), ('BY', 'Bélarus'), ('BE', 'Belgique'), ('BZ', 'Belize'), ('BJ', 'Bénin'), ('BM', 'Bermudes'), ('BT', 'Bhoutan'), ('BO', 'Bolivie'), ('BA', 'Bosnie-Herzégovine'), ('BW', 'Botswana'), ('BR', 'Brésil'), ('BN', 'Brunéi Darussalam'), ('BG', 'Bulgarie'), ('BF', 'Burkina Faso'), ('BI', 'Burundi'), ('KH', 'Cambodge'), ('CM', 'Cameroun'), ('CA', 'Canada'), ('CV', 'Cap-Vert'), ('EA', 'Ceuta et Melilla'), ('CL', 'Chili'), ('CN', 'Chine'), ('CY', 'Chypre'), ('CO', 'Colombie'), ('KM', 'Comores'), ('CG', 'Congo-Brazzaville'), ('KP', 'Corée du Nord'), ('KR', 'Corée du Sud'), ('CR', 'Costa Rica'), ('CI', 'Côte d’Ivoire'), ('HR', 'Croatie'), ('CU', 'Cuba'), ('DK', 'Danemark'), ('DG', 'Diego Garcia'), ('DJ', 'Djibouti'), ('DM', 'Dominique'), ('EG', 'Égypte'), ('SV', 'El Salvador'), ('AE', 'Émirats arabes unis'), ('EC', 'Équateur'), ('ER', 'Érythrée'), ('ES', 'Espagne'), ('EE', 'Estonie'), ('VA', 'État de la Cité du Vatican'), ('FM', 'États fédérés de Micronésie'), ('US', 'États-Unis'), ('ET', 'Éthiopie'), ('FJ', 'Fidji'), ('FI', 'Finlande'), ('FR', 'France'), ('GA', 'Gabon'), ('GM', 'Gambie'), ('GE', 'Géorgie'), ('GS', 'Géorgie du Sud et les îles Sandwich du Sud'), ('GH', 'Ghana'), ('GI', 'Gibraltar'), ('GR', 'Grèce'), ('GD', 'Grenade'), ('GL', 'Groenland'), ('GP', 'Guadeloupe'), ('GU', 'Guam'), ('GT', 'Guatemala'), ('GG', 'Guernesey'), ('GN', 'Guinée'), ('GQ', 'Guinée équatoriale'), ('GW', 'Guinée-Bissau'), ('GY', 'Guyana'), ('GF', 'Guyane française'), ('HT', 'Haïti'), ('HN', 'Honduras'), ('HU', 'Hongrie'), ('BV', 'Île Bouvet'), ('CX', 'Île Christmas'), ('CP', 'Île Clipperton'), ('AC', "Île de l'Ascension"), ('IM', 'Île de Man'), ('NF', 'Île Norfolk'), ('AX', 'Îles Åland'), ('KY', 'Îles Caïmans'), ('IC', 'Îles Canaries'), ('CC', 'Îles Cocos - Keeling'), ('CK', 'Îles Cook'), ('FO', 'Îles Féroé'), ('HM', 'Îles Heard et MacDonald'), ('FK', 'Îles Malouines'), ('MP', 'Îles Mariannes du Nord'), ('MH', 'Îles Marshall'), ('UM', 'Îles Mineures Éloignées des États-Unis'), ('SB', 'Îles Salomon'), ('TC', 'Îles Turks et Caïques'), ('VG', 'Îles Vierges britanniques'), ('VI', 'Îles Vierges des États-Unis'), ('IN', 'Inde'), ('ID', 'Indonésie'), ('IQ', 'Irak'), ('IR', 'Iran'), ('IE', 'Irlande'), ('IS', 'Islande'), ('IL', 'Israël'), ('IT', 'Italie'), ('JM', 'Jamaïque'), ('JP', 'Japon'), ('JE', 'Jersey'), ('JO', 'Jordanie'), ('KZ', 'Kazakhstan'), ('KE', 'Kenya'), ('KG', 'Kirghizistan'), ('KI', 'Kiribati'), ('KW', 'Koweït'), ('LA', 'Laos'), ('LS', 'Lesotho'), ('LV', 'Lettonie'), ('LB', 'Liban'), ('LR', 'Libéria'), ('LY', 'Libye'), ('LI', 'Liechtenstein'), ('LT', 'Lituanie'), ('LU', 'Luxembourg'), ('MK', 'Macédoine'), ('MG', 'Madagascar'), ('MY', 'Malaisie'), ('MW', 'Malawi'), ('MV', 'Maldives'), ('ML', 'Mali'), ('MT', 'Malte'), ('MA', 'Maroc'), ('MQ', 'Martinique'), ('MU', 'Maurice'), ('MR', 'Mauritanie'), ('YT', 'Mayotte'), ('MX', 'Mexique'), ('MD', 'Moldavie'), ('MC', 'Monaco'), ('MN', 'Mongolie'), ('ME', 'Monténégro'), ('MS', 'Montserrat'), ('MZ', 'Mozambique'), ('MM', 'Myanmar'), ('NA', 'Namibie'), ('NR', 'Nauru'), ('NP', 'Népal'), ('NI', 'Nicaragua'), ('NE', 'Niger'), ('NG', 'Nigéria'), ('NU', 'Niue'), ('NO', 'Norvège'), ('NC', 'Nouvelle-Calédonie'), ('NZ', 'Nouvelle-Zélande'), ('OM', 'Oman'), ('UG', 'Ouganda'), ('UZ', 'Ouzbékistan'), ('PK', 'Pakistan'), ('PW', 'Palaos'), ('PA', 'Panama'), ('PG', 'Papouasie-Nouvelle-Guinée'), ('PY', 'Paraguay'), ('NL', 'Pays-Bas'), ('PE', 'Pérou'), ('PH', 'Philippines'), ('PN', 'Pitcairn'), ('PL', 'Pologne'), ('PF', 'Polynésie française'), ('PR', 'Porto Rico'), ('PT', 'Portugal'), ('QA', 'Qatar'), ('HK', 'R.A.S. chinoise de Hong Kong'), ('MO', 'R.A.S. chinoise de Macao'), ('QO', 'régions éloignées de l’Océanie'), ('CF', 'République centrafricaine'), ('CD', 'République démocratique du Congo'), ('DO', 'République dominicaine'), ('CZ', 'République tchèque'), ('RE', 'Réunion'), ('RO', 'Roumanie'), ('GB', 'Royaume-Uni'), ('RU', 'Russie'), ('RW', 'Rwanda'), ('EH', 'Sahara occidental'), ('BL', 'Saint-Barthélémy'), ('KN', 'Saint-Kitts-et-Nevis'), ('SM', 'Saint-Marin'), ('MF', 'Saint-Martin'), ('PM', 'Saint-Pierre-et-Miquelon'), ('VC', 'Saint-Vincent-et-les Grenadines'), ('SH', 'Sainte-Hélène'), ('LC', 'Sainte-Lucie'), ('WS', 'Samoa'), ('AS', 'Samoa américaines'), ('ST', 'Sao Tomé-et-Principe'), ('SN', 'Sénégal'), ('RS', 'Serbie'), ('CS', 'Serbie-et-Monténégro'), ('SC', 'Seychelles'), ('SL', 'Sierra Leone'), ('SG', 'Singapour'), ('SK', 'Slovaquie'), ('SI', 'Slovénie'), ('SO', 'Somalie'), ('SD', 'Soudan'), ('LK', 'Sri Lanka'), ('SE', 'Suède'), ('CH', 'Suisse'), ('SR', 'Suriname'), ('SJ', 'Svalbard et Île Jan Mayen'), ('SZ', 'Swaziland'), ('SY', 'Syrie'), ('TJ', 'Tadjikistan'), ('TW', 'Taïwan'), ('TZ', 'Tanzanie'), ('TD', 'Tchad'), ('TF', 'Terres australes françaises'), ('IO', "Territoire britannique de l'océan Indien"), ('PS', 'Territoire palestinien'), ('TH', 'Thaïlande'), ('TL', 'Timor oriental'), ('TG', 'Togo'), ('TK', 'Tokelau'), ('TO', 'Tonga'), ('TT', 'Trinité-et-Tobago'), ('TA', 'Tristan da Cunha'), ('TN', 'Tunisie'), ('TM', 'Turkménistan'), ('TR', 'Turquie'), ('TV', 'Tuvalu'), ('UA', 'Ukraine'), ('EU', 'Union européenne'), ('UY', 'Uruguay'), ('VU', 'Vanuatu'), ('VE', 'Venezuela'), ('VN', 'Viêt Nam'), ('WF', 'Wallis-et-Futuna'), ('YE', 'Yémen'), ('ZM', 'Zambie'), ('ZW', 'Zimbabwe')], max_length=200)),
('birthday', models.DateField()),
('metier', models.CharField(choices=[('developpeur', 'dev Android'), ('developpeur', 'DEV WEb'), ('DATA SCIENTIST', 'DATA SCIENTIST')], max_length=200)),
('cv', models.FileField(null=True, upload_to='Cv_doc', verbose_name='User_Cv')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ProfilRetruteur',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('location', models.CharField(max_length=200)),
('Description', models.TextField()),
('adresse', models.CharField(max_length=50)),
('nationalite', models.CharField(choices=[('AF', 'Afghanistan'), ('ZA', 'Afrique du Sud'), ('AL', 'Albanie'), ('DZ', 'Algérie'), ('DE', 'Allemagne'), ('AD', 'Andorre'), ('AO', 'Angola'), ('AI', 'Anguilla'), ('AQ', 'Antarctique'), ('AG', 'Antigua-et-Barbuda'), ('AN', 'Antilles néerlandaises'), ('SA', 'Arabie saoudite'), ('AR', 'Argentine'), ('AM', 'Arménie'), ('AW', 'Aruba'), ('AU', 'Australie'), ('AT', 'Autriche'), ('AZ', 'Azerbaïdjan'), ('BS', 'Bahamas'), ('BH', 'Bahreïn'), ('BD', 'Bangladesh'), ('BB', 'Barbade'), ('BY', 'Bélarus'), ('BE', 'Belgique'), ('BZ', 'Belize'), ('BJ', 'Bénin'), ('BM', 'Bermudes'), ('BT', 'Bhoutan'), ('BO', 'Bolivie'), ('BA', 'Bosnie-Herzégovine'), ('BW', 'Botswana'), ('BR', 'Brésil'), ('BN', 'Brunéi Darussalam'), ('BG', 'Bulgarie'), ('BF', 'Burkina Faso'), ('BI', 'Burundi'), ('KH', 'Cambodge'), ('CM', 'Cameroun'), ('CA', 'Canada'), ('CV', 'Cap-Vert'), ('EA', 'Ceuta et Melilla'), ('CL', 'Chili'), ('CN', 'Chine'), ('CY', 'Chypre'), ('CO', 'Colombie'), ('KM', 'Comores'), ('CG', 'Congo-Brazzaville'), ('KP', 'Corée du Nord'), ('KR', 'Corée du Sud'), ('CR', 'Costa Rica'), ('CI', 'Côte d’Ivoire'), ('HR', 'Croatie'), ('CU', 'Cuba'), ('DK', 'Danemark'), ('DG', 'Diego Garcia'), ('DJ', 'Djibouti'), ('DM', 'Dominique'), ('EG', 'Égypte'), ('SV', 'El Salvador'), ('AE', 'Émirats arabes unis'), ('EC', 'Équateur'), ('ER', 'Érythrée'), ('ES', 'Espagne'), ('EE', 'Estonie'), ('VA', 'État de la Cité du Vatican'), ('FM', 'États fédérés de Micronésie'), ('US', 'États-Unis'), ('ET', 'Éthiopie'), ('FJ', 'Fidji'), ('FI', 'Finlande'), ('FR', 'France'), ('GA', 'Gabon'), ('GM', 'Gambie'), ('GE', 'Géorgie'), ('GS', 'Géorgie du Sud et les îles Sandwich du Sud'), ('GH', 'Ghana'), ('GI', 'Gibraltar'), ('GR', 'Grèce'), ('GD', 'Grenade'), ('GL', 'Groenland'), ('GP', 'Guadeloupe'), ('GU', 'Guam'), ('GT', 'Guatemala'), ('GG', 'Guernesey'), ('GN', 'Guinée'), ('GQ', 'Guinée équatoriale'), ('GW', 'Guinée-Bissau'), ('GY', 'Guyana'), ('GF', 'Guyane française'), ('HT', 'Haïti'), ('HN', 'Honduras'), ('HU', 'Hongrie'), ('BV', 'Île Bouvet'), ('CX', 'Île Christmas'), ('CP', 'Île Clipperton'), ('AC', "Île de l'Ascension"), ('IM', 'Île de Man'), ('NF', 'Île Norfolk'), ('AX', 'Îles Åland'), ('KY', 'Îles Caïmans'), ('IC', 'Îles Canaries'), ('CC', 'Îles Cocos - Keeling'), ('CK', 'Îles Cook'), ('FO', 'Îles Féroé'), ('HM', 'Îles Heard et MacDonald'), ('FK', 'Îles Malouines'), ('MP', 'Îles Mariannes du Nord'), ('MH', 'Îles Marshall'), ('UM', 'Îles Mineures Éloignées des États-Unis'), ('SB', 'Îles Salomon'), ('TC', 'Îles Turks et Caïques'), ('VG', 'Îles Vierges britanniques'), ('VI', 'Îles Vierges des États-Unis'), ('IN', 'Inde'), ('ID', 'Indonésie'), ('IQ', 'Irak'), ('IR', 'Iran'), ('IE', 'Irlande'), ('IS', 'Islande'), ('IL', 'Israël'), ('IT', 'Italie'), ('JM', 'Jamaïque'), ('JP', 'Japon'), ('JE', 'Jersey'), ('JO', 'Jordanie'), ('KZ', 'Kazakhstan'), ('KE', 'Kenya'), ('KG', 'Kirghizistan'), ('KI', 'Kiribati'), ('KW', 'Koweït'), ('LA', 'Laos'), ('LS', 'Lesotho'), ('LV', 'Lettonie'), ('LB', 'Liban'), ('LR', 'Libéria'), ('LY', 'Libye'), ('LI', 'Liechtenstein'), ('LT', 'Lituanie'), ('LU', 'Luxembourg'), ('MK', 'Macédoine'), ('MG', 'Madagascar'), ('MY', 'Malaisie'), ('MW', 'Malawi'), ('MV', 'Maldives'), ('ML', 'Mali'), ('MT', 'Malte'), ('MA', 'Maroc'), ('MQ', 'Martinique'), ('MU', 'Maurice'), ('MR', 'Mauritanie'), ('YT', 'Mayotte'), ('MX', 'Mexique'), ('MD', 'Moldavie'), ('MC', 'Monaco'), ('MN', 'Mongolie'), ('ME', 'Monténégro'), ('MS', 'Montserrat'), ('MZ', 'Mozambique'), ('MM', 'Myanmar'), ('NA', 'Namibie'), ('NR', 'Nauru'), ('NP', 'Népal'), ('NI', 'Nicaragua'), ('NE', 'Niger'), ('NG', 'Nigéria'), ('NU', 'Niue'), ('NO', 'Norvège'), ('NC', 'Nouvelle-Calédonie'), ('NZ', 'Nouvelle-Zélande'), ('OM', 'Oman'), ('UG', 'Ouganda'), ('UZ', 'Ouzbékistan'), ('PK', 'Pakistan'), ('PW', 'Palaos'), ('PA', 'Panama'), ('PG', 'Papouasie-Nouvelle-Guinée'), ('PY', 'Paraguay'), ('NL', 'Pays-Bas'), ('PE', 'Pérou'), ('PH', 'Philippines'), ('PN', 'Pitcairn'), ('PL', 'Pologne'), ('PF', 'Polynésie française'), ('PR', 'Porto Rico'), ('PT', 'Portugal'), ('QA', 'Qatar'), ('HK', 'R.A.S. chinoise de Hong Kong'), ('MO', 'R.A.S. chinoise de Macao'), ('QO', 'régions éloignées de l’Océanie'), ('CF', 'République centrafricaine'), ('CD', 'République démocratique du Congo'), ('DO', 'République dominicaine'), ('CZ', 'République tchèque'), ('RE', 'Réunion'), ('RO', 'Roumanie'), ('GB', 'Royaume-Uni'), ('RU', 'Russie'), ('RW', 'Rwanda'), ('EH', 'Sahara occidental'), ('BL', 'Saint-Barthélémy'), ('KN', 'Saint-Kitts-et-Nevis'), ('SM', 'Saint-Marin'), ('MF', 'Saint-Martin'), ('PM', 'Saint-Pierre-et-Miquelon'), ('VC', 'Saint-Vincent-et-les Grenadines'), ('SH', 'Sainte-Hélène'), ('LC', 'Sainte-Lucie'), ('WS', 'Samoa'), ('AS', 'Samoa américaines'), ('ST', 'Sao Tomé-et-Principe'), ('SN', 'Sénégal'), ('RS', 'Serbie'), ('CS', 'Serbie-et-Monténégro'), ('SC', 'Seychelles'), ('SL', 'Sierra Leone'), ('SG', 'Singapour'), ('SK', 'Slovaquie'), ('SI', 'Slovénie'), ('SO', 'Somalie'), ('SD', 'Soudan'), ('LK', 'Sri Lanka'), ('SE', 'Suède'), ('CH', 'Suisse'), ('SR', 'Suriname'), ('SJ', 'Svalbard et Île Jan Mayen'), ('SZ', 'Swaziland'), ('SY', 'Syrie'), ('TJ', 'Tadjikistan'), ('TW', 'Taïwan'), ('TZ', 'Tanzanie'), ('TD', 'Tchad'), ('TF', 'Terres australes françaises'), ('IO', "Territoire britannique de l'océan Indien"), ('PS', 'Territoire palestinien'), ('TH', 'Thaïlande'), ('TL', 'Timor oriental'), ('TG', 'Togo'), ('TK', 'Tokelau'), ('TO', 'Tonga'), ('TT', 'Trinité-et-Tobago'), ('TA', 'Tristan da Cunha'), ('TN', 'Tunisie'), ('TM', 'Turkménistan'), ('TR', 'Turquie'), ('TV', 'Tuvalu'), ('UA', 'Ukraine'), ('EU', 'Union européenne'), ('UY', 'Uruguay'), ('VU', 'Vanuatu'), ('VE', 'Venezuela'), ('VN', 'Viêt Nam'), ('WF', 'Wallis-et-Futuna'), ('YE', 'Yémen'), ('ZM', 'Zambie'), ('ZW', 'Zimbabwe')], max_length=200)),
('web_site', models.CharField(blank=True, max_length=200, null=True)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='auth.user')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Postuler',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('motivation_letter', models.TextField()),
('date_post', models.DateField(auto_now_add=True)),
('response_status', models.CharField(choices=[('Retruter', 'Retruter'), ('REFUSER', 'REFUSER'), ('WAITING', 'WAITING')], max_length=200)),
('job_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.job')),
('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='auth.user')),
],
options={
'ordering': ('date_post', 'id'),
'abstract': False,
},
),
migrations.AddField(
model_name='job',
name='metier',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.metier'),
),
migrations.AddField(
model_name='job',
name='profilretruteur',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.profilretruteur'),
),
migrations.CreateModel(
name='Formation',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_debut', models.DateField()),
('date_fin', models.DateField()),
('nom', models.CharField(max_length=200)),
('lieux', models.CharField(max_length=200)),
('description', models.TextField()),
('profiluser', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.profiluser')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Experience',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_de_debut', models.DateField()),
('date_de_fin', models.DateField()),
('title', models.CharField(max_length=200)),
('Description', models.TextField()),
('lieux', models.CharField(max_length=200)),
('type_contrat', models.CharField(choices=[('TEMP PLEIN ', 'TEMP PLEIN '), ('PERMANENT', 'PERMANENT'), ('OCCASIONNEL', 'OCCASIONNEL'), ('STAGE', 'STAGE'), ('FREELANCER', 'FREELANCER'), ('TEMP PARTIEL', 'TEMP PARTIEL'), ('CONTRACTUEL', 'CONTRACTUEL')], max_length=50)),
('experiences_users', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='experiences_user', to='core.profiluser')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Competence',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('niveau', models.CharField(max_length=2000)),
('description', models.TextField()),
('nom', models.CharField(max_length=200)),
('profiluser', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='core.profiluser')),
],
options={
'abstract': False,
},
),
]
| 165.489933 | 5,838 | 0.536094 | 2,672 | 24,658 | 4.909805 | 0.263847 | 0.015779 | 0.014635 | 0.023782 | 0.893208 | 0.888254 | 0.869731 | 0.869731 | 0.861651 | 0.855096 | 0 | 0.004067 | 0.162422 | 24,658 | 148 | 5,839 | 166.608108 | 0.631143 | 0.001744 | 0 | 0.602837 | 1 | 0 | 0.443343 | 0.007476 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.014184 | 0 | 0.042553 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
e8236ad12c0548ac69245cf327165bf409fd89a8 | 50,445 | py | Python | userbot/plugins/lagggg.py | justteen/BUZZ-USERBOT | 55651cce150e1d04d2c61efb2565ef9f46b42933 | [
"BSL-1.0"
] | null | null | null | userbot/plugins/lagggg.py | justteen/BUZZ-USERBOT | 55651cce150e1d04d2c61efb2565ef9f46b42933 | [
"BSL-1.0"
] | null | null | null | userbot/plugins/lagggg.py | justteen/BUZZ-USERBOT | 55651cce150e1d04d2c61efb2565ef9f46b42933 | [
"BSL-1.0"
] | null | null | null | # Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Copyright BL 2021
from telethon.tl.types import ChannelParticipantsAdmins
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
from uniborg.util import lightning_cmd
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
@borg.on(lightning_cmd(pattern=r"monster"))
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
async def _(event):
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
if event.fwd_from:
return
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
mentions = " ⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰😈꙰꙰꙰꙰꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰😈꙰꙰꙰꙰꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰😈꙰꙰꙰꙰꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰😈꙰꙰꙰꙰꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰⃟꙰⃟꙰⃟꙰꙰"
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
chat = await event.get_input_chat()
async for x in borg.iter_participants(chat, filter=ChannelParticipantsAdmins):
mentions += f""
reply_message = None
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
if event.reply_to_msg_id:
reply_message = await event.get_reply_message()
await reply_message.reply(mentions)
else:
await event.reply(mentions)
await event.delete()
# Creator------> @hacker11000
#Userbot-------> Black Lightning Userbot
# Don't kang without permission otherwise put credits....
# if u kang without credit so u r world's biggest noob!.
| 41.246934 | 4,102 | 0.626643 | 6,267 | 50,445 | 5.693155 | 0.010212 | 0.146753 | 0.166765 | 0.200118 | 0.87424 | 0.87424 | 0.87424 | 0.87424 | 0.87424 | 0.87424 | 0 | 0.028154 | 0.159282 | 50,445 | 1,222 | 4,103 | 41.280687 | 0.716859 | 0.840143 | 0 | 0 | 0 | 0 | 0.694921 | 0.693562 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.117647 | 0 | 0.176471 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 11 |
1c2671fbae543fa25260b383fcaaaff961492171 | 3,800 | py | Python | tests/system/test_connection_ncs1001.py | kstaniek/condoor | 77c054b29d4e286c1d7aca2c74dff86b805e1fae | [
"Apache-2.0"
] | 7 | 2016-01-20T09:04:09.000Z | 2020-02-25T07:14:38.000Z | tests/system/test_connection_ncs1001.py | kstaniek/condoor | 77c054b29d4e286c1d7aca2c74dff86b805e1fae | [
"Apache-2.0"
] | 55 | 2015-12-16T14:50:59.000Z | 2018-04-23T15:27:15.000Z | tests/system/test_connection_ncs1001.py | kstaniek/condoor | 77c054b29d4e286c1d7aca2c74dff86b805e1fae | [
"Apache-2.0"
] | 19 | 2016-04-22T06:09:32.000Z | 2022-02-25T20:21:51.000Z | from tests.system.common import CondoorTestCase, StopTelnetSrv, StartTelnetSrv
from tests.dmock.dmock import NCS1001Handler
from tests.utils import remove_cache_file
import condoor
class TestNCS1001Connection(CondoorTestCase):
@StartTelnetSrv(NCS1001Handler, 10023)
def setUp(self):
CondoorTestCase.setUp(self)
@StopTelnetSrv()
def tearDown(self):
pass
def test_NCS1001_1_discovery(self):
"""NCS1001: Test the connection and discovery"""
remove_cache_file()
urls = ["telnet://admin:admin@127.0.0.1:10023"]
conn = condoor.Connection("host", urls, log_session=self.log_session, log_level=self.log_level)
self.conn = conn
conn.connect(self.logfile_condoor)
self.assertEqual(conn.is_discovered, True, "Not discovered properly")
self.assertEqual(conn.hostname, "ncs1001-fb-1", "Wrong Hostname: {}".format(conn.hostname))
self.assertEqual(conn.family, "NCS1001", "Wrong Family: {}".format(conn.family))
self.assertEqual(conn.platform, "NCS1001", "Wrong Platform: {}".format(conn.platform))
self.assertEqual(conn.os_type, "eXR", "Wrong OS Type: {}".format(conn.os_type))
self.assertEqual(conn.os_version, "6.2.1", "Wrong Version: {}".format(conn.os_version))
self.assertEqual(conn.udi['name'], "Rack 0", "Wrong Name: {}".format(conn.udi['name']))
self.assertEqual(conn.udi['description'], "Network Convergence System 1001 line system 3 slots",
"Wrong Description: {}".format(conn.udi['description']))
self.assertEqual(conn.udi['pid'], "NCS1001-K9", "Wrong PID: {}".format(conn.udi['pid']))
self.assertEqual(conn.udi['vid'], "V01", "Wrong VID: {}".format(conn.udi['vid']))
self.assertEqual(conn.udi['sn'], "CAT2051B0XT", "Wrong S/N: {}".format(conn.udi['sn']))
self.assertEqual(conn.prompt, "RP/0/RP0/CPU0:ncs1001-fb-1#", "Wrong Prompt: {}".format(conn.prompt))
with self.assertRaises(condoor.CommandSyntaxError):
conn.send("wrongcommand")
conn.disconnect()
def test_NCS1001_2_rediscovery(self):
"""NCS1001: Test the connection and discovery"""
remove_cache_file()
urls = ["telnet://admin:admin@127.0.0.1:10023"]
conn = condoor.Connection("host", urls, log_session=self.log_session, log_level=self.log_level)
self.conn = conn
conn.connect(self.logfile_condoor)
self.assertEqual(conn.is_discovered, True, "Not discovered properly")
self.assertEqual(conn.hostname, "ncs1001-fb-1", "Wrong Hostname: {}".format(conn.hostname))
self.assertEqual(conn.family, "NCS1001", "Wrong Family: {}".format(conn.family))
self.assertEqual(conn.platform, "NCS1001", "Wrong Platform: {}".format(conn.platform))
self.assertEqual(conn.os_type, "eXR", "Wrong OS Type: {}".format(conn.os_type))
self.assertEqual(conn.os_version, "6.2.1", "Wrong Version: {}".format(conn.os_version))
self.assertEqual(conn.udi['name'], "Rack 0", "Wrong Name: {}".format(conn.udi['name']))
self.assertEqual(conn.udi['description'], "Network Convergence System 1001 line system 3 slots",
"Wrong Description: {}".format(conn.udi['description']))
self.assertEqual(conn.udi['pid'], "NCS1001-K9", "Wrong PID: {}".format(conn.udi['pid']))
self.assertEqual(conn.udi['vid'], "V01", "Wrong VID: {}".format(conn.udi['vid']))
self.assertEqual(conn.udi['sn'], "CAT2051B0XT", "Wrong S/N: {}".format(conn.udi['sn']))
self.assertEqual(conn.prompt, "RP/0/RP0/CPU0:ncs1001-fb-1#", "Wrong Prompt: {}".format(conn.prompt))
with self.assertRaises(condoor.CommandSyntaxError):
conn.send("wrongcommand")
conn.disconnect()
| 50.666667 | 108 | 0.656316 | 462 | 3,800 | 5.329004 | 0.192641 | 0.146223 | 0.185215 | 0.089358 | 0.858652 | 0.858652 | 0.858652 | 0.858652 | 0.858652 | 0.858652 | 0 | 0.045019 | 0.175789 | 3,800 | 74 | 109 | 51.351351 | 0.74106 | 0.022368 | 0 | 0.763636 | 0 | 0 | 0.237105 | 0.034026 | 0 | 0 | 0 | 0 | 0.472727 | 1 | 0.072727 | false | 0.018182 | 0.072727 | 0 | 0.163636 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
1c630a3b880013e972b4641ad1a9c076cb5338f8 | 2,863 | py | Python | tests/playwhe/cli/store/test_select_last_result.py | playwhesmarter/playwhe | 44a4420c4c1f8684ff24b71e1af1b902adb54b95 | [
"MIT"
] | 1 | 2016-06-29T15:26:53.000Z | 2016-06-29T15:26:53.000Z | tests/playwhe/cli/store/test_select_last_result.py | dwayne/playwhe | 44a4420c4c1f8684ff24b71e1af1b902adb54b95 | [
"MIT"
] | 17 | 2015-03-29T13:49:50.000Z | 2016-07-29T08:14:57.000Z | tests/playwhe/cli/store/test_select_last_result.py | playwhesmarter/playwhe | 44a4420c4c1f8684ff24b71e1af1b902adb54b95 | [
"MIT"
] | 1 | 2016-03-23T16:30:17.000Z | 2016-03-23T16:30:17.000Z | import datetime
import unittest
from sqlalchemy import create_engine
from playwhe.cli.store import Store, schema, select_last_result
class SelectLastResultTestCase(unittest.TestCase):
def setUp(self):
self.store = Store()
self.store.initialize()
def tearDown(self):
self.store = None
def test_it_returns_last_result(self):
with self.store.bind.begin() as conn:
conn.execute(schema.results.insert(), [
{ 'draw': 100, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'EM', 'mark_number': 1 },
{ 'draw': 101, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'AM', 'mark_number': 2 },
{ 'draw': 102, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'AN', 'mark_number': 3 },
{ 'draw': 103, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'PM', 'mark_number': 4 },
{ 'draw': 104, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'EM', 'mark_number': 5 },
{ 'draw': 105, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'AM', 'mark_number': 6 },
{ 'draw': 106, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'AN', 'mark_number': 7 },
{ 'draw': 107, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'PM', 'mark_number': 8 }
])
last_result = conn.execute(select_last_result()).fetchone()
self.assertEqual(last_result, (107, datetime.date(2000, 1, 2), 'PM', 8))
def test_when_no_results(self):
with self.store.bind.begin() as conn:
last_result = conn.execute(select_last_result()).fetchone()
self.assertIsNone(last_result)
def test_when_draw_is_incorrect(self):
with self.store.bind.begin() as conn:
conn.execute(schema.results.insert(), [
{ 'draw': 100, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'EM', 'mark_number': 1 },
{ 'draw': 102, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'AN', 'mark_number': 3 },
{ 'draw': 103, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'PM', 'mark_number': 4 },
{ 'draw': 104, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'EM', 'mark_number': 5 },
{ 'draw': 105, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'AM', 'mark_number': 6 },
{ 'draw': 106, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'AN', 'mark_number': 7 },
{ 'draw': 107, 'date': datetime.date(2000, 1, 2), 'period_abbr': 'PM', 'mark_number': 8 },
{ 'draw': 201, 'date': datetime.date(2000, 1, 1), 'period_abbr': 'AM', 'mark_number': 2 },
])
last_result = conn.execute(select_last_result()).fetchone()
self.assertEqual(last_result, (107, datetime.date(2000, 1, 2), 'PM', 8))
| 51.125 | 106 | 0.561299 | 365 | 2,863 | 4.243836 | 0.189041 | 0.139445 | 0.185926 | 0.197547 | 0.784377 | 0.784377 | 0.784377 | 0.784377 | 0.763719 | 0.732085 | 0 | 0.084151 | 0.252882 | 2,863 | 55 | 107 | 52.054545 | 0.640019 | 0 | 0 | 0.571429 | 0 | 0 | 0.180231 | 0 | 0 | 0 | 0 | 0 | 0.071429 | 1 | 0.119048 | false | 0 | 0.095238 | 0 | 0.238095 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
1c8290f3f1832526f322452899f8ba4f142febdd | 11,225 | py | Python | scripts/py/bsg_synthetic_modules.py | developandplay/bsg_sv2v | 1da0ecc03f64f4082347a412b064f43a2227d400 | [
"BSD-3-Clause"
] | null | null | null | scripts/py/bsg_synthetic_modules.py | developandplay/bsg_sv2v | 1da0ecc03f64f4082347a412b064f43a2227d400 | [
"BSD-3-Clause"
] | null | null | null | scripts/py/bsg_synthetic_modules.py | developandplay/bsg_sv2v | 1da0ecc03f64f4082347a412b064f43a2227d400 | [
"BSD-3-Clause"
] | null | null | null | '''
bsg_synthetic_modules.py
This file contains a list of ~all the synthetic modules that DesignCompiler
will use for elaboration. During the conversion phase, if a synthetic module is
found, the instance will be replaced with the AST returned from the function of
the same name found in this file. There are a number of synthetic modules that
are not yet implemented. In the event that one of these modules is found, an
ERROR will be thrown.
'''
import sys
import logging
from pyverilog.vparser.ast import *
from bsg_utility_funcs import __get_instance_ports
# Unsigned addition operation
def ADD_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Plus(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed addition operation
def ADD_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = Plus(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned subtraction operation
def SUB_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Minus(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed subtraction operation
def SUB_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = Minus(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned multiplication operation
def MULT_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Times(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed multiplication operation
def MULT_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = Times(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned less-than operation
def LT_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = LessThan(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed less-than operation
def LT_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = LessThan(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned greater-than operation
def GT_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = GreaterThan(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed greater-than operation
def GT_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = GreaterThan(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned less-than-or-equal operation
def LEQ_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = LessEq(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed less-than-or-equal operation
def LEQ_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = LessEq(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned greater-than-or-equal operation
def GEQ_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = GreaterEq(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed greater-than-or-equal operation
def GEQ_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = GreaterEq(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned division operation
def DIV_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Divide(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed division operation
def DIV_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = Divide(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned remainder operation
def REM_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Mod(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed remainder operation
def REM_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = Mod(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned equals operation
def EQ_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Eq(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed equals operation
def EQ_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = Eq(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned not-equals operation
def NE_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = NotEq(p['A'], p['B'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed not-equals operation
def NE_TC_OP( instance ):
p = __get_instance_ports(instance)
rval = NotEq(SystemCall('signed', [p['A']]), SystemCall('signed',[p['B']]))
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned shift (left) operation
def ASH_UNS_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Sll(p['A'], p['SH'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Unsigned shift (right) operation
def ASHR_UNS_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Srl(p['A'], p['SH'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Signed shift (right) operation
def ASHR_TC_UNS_OP( instance ):
p = __get_instance_ports(instance)
rval = Sra(SystemCall('signed', [p['A']]), p['SH'])
return Assign(Lvalue(p['Z']), Rvalue(rval))
# Select operation. Each select_op synthetic module has a Z output port, and
# pairs of DATAn and CONTROLn ports where n is a number starting with 1. When
# CONTROLn is hot, Z=DATAn. At any given point, one-and-only-one of the
# CONTROLn ports is hot.
def SELECT_OP( instance ):
p = __get_instance_ports(instance)
control_count = int((len(p)-1) / 2)
cond_stmt = IntConst('1\'b0')
for i in range(control_count, 0, -1):
cond_stmt = Cond(p['CONTROL%d' % i], p['DATA%d' % i], cond_stmt)
return Assign(Lvalue(p['Z']), Rvalue(cond_stmt))
# multiplexing operation
def MUX_OP( instance ):
p = __get_instance_ports(instance)
for c in range(32):
if len(p) == 1 + c + 2**c:
break
cond_stmt = IntConst('1\'b0')
for i in range(control_count, 0, -1):
cond_stmt = Cond(p['CONTROL%d' % i], p['DATA%d' % i], cond_stmt)
return Assign(Lvalue(p['Z']), Rvalue(cond_stmt))
################################################################################
# The following SYNTHETIC modules have not been implemented yet. An ERROR will
# be thrown if any of these modules are found in the verilog file being
# converted. In the event that one of these is found, you should implement said
# cell and move it above.
################################################################################
def ADD_UNS_CI_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def ADD_TC_CI_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def SUB_UNS_CI_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def SUB_TC_CI_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def MOD_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def DIVREM_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def DIVMOD_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def MOD_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def DIVREM_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def DIVMOD_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def ASH_UNS_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def ASH_TC_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def ASH_TC_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def ASHR_UNS_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def ASHR_TC_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def BSH_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def BSH_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def BSHL_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def BSHR_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def BSHR_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def SLA_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def SLA_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def SRA_UNS_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
def SRA_TC_OP( instance ):
logging.error('No implementation defined for %s replacement!' % sys._getframe().f_code.co_name)
return InstanceList(instance.module, [], [instance])
| 38.050847 | 97 | 0.705122 | 1,599 | 11,225 | 4.754847 | 0.115072 | 0.067079 | 0.058924 | 0.049717 | 0.842957 | 0.818361 | 0.818361 | 0.791267 | 0.790477 | 0.645666 | 0 | 0.001536 | 0.129889 | 11,225 | 294 | 98 | 38.180272 | 0.776902 | 0.153408 | 0 | 0.5625 | 0 | 0 | 0.14321 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.265625 | false | 0 | 0.020833 | 0 | 0.552083 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 8 |
c72dc2d1a64a2a23a09c27eb96fa157d9a9ce826 | 255 | py | Python | urllib3/connectionpool.py | oliland/urllib3 | 43f0c6b83e6cdbe153b0283fbe97401bf99a8b95 | [
"MIT"
] | null | null | null | urllib3/connectionpool.py | oliland/urllib3 | 43f0c6b83e6cdbe153b0283fbe97401bf99a8b95 | [
"MIT"
] | null | null | null | urllib3/connectionpool.py | oliland/urllib3 | 43f0c6b83e6cdbe153b0283fbe97401bf99a8b95 | [
"MIT"
] | null | null | null | from ._sync.connectionpool import (ConnectionPool, HTTPConnectionPool,
HTTPSConnectionPool, connection_from_url)
__all__ = [
'ConnectionPool', 'HTTPConnectionPool', 'HTTPSConnectionPool',
'connection_from_url'
]
| 36.428571 | 76 | 0.690196 | 17 | 255 | 9.823529 | 0.529412 | 0.383234 | 0.610778 | 0.730539 | 0.814371 | 0.814371 | 0 | 0 | 0 | 0 | 0 | 0 | 0.227451 | 255 | 6 | 77 | 42.5 | 0.847716 | 0 | 0 | 0 | 0 | 0 | 0.27451 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.166667 | 0 | 0.166667 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
c7346f14e9acc36fcebaab9f133ce386a97e7451 | 795 | py | Python | myapp/config.py | dvaruas/slowly-stamps | 1eee6ce12a62dfb9104372ed8d4b6aa299aa5d02 | [
"MIT"
] | null | null | null | myapp/config.py | dvaruas/slowly-stamps | 1eee6ce12a62dfb9104372ed8d4b6aa299aa5d02 | [
"MIT"
] | null | null | null | myapp/config.py | dvaruas/slowly-stamps | 1eee6ce12a62dfb9104372ed8d4b6aa299aa5d02 | [
"MIT"
] | null | null | null | import os
class ProdConfig:
DEBUG = False
RESOURCES_DIR = "/app/resources"
USER_IMAGES_DIR = os.path.join(RESOURCES_DIR, "users")
STAMP_IMAGES_DIR = os.path.join(RESOURCES_DIR, "stamps")
SQLALCHEMY_DATABASE_URI = "sqlite:///{}".format(os.path.join(RESOURCES_DIR, "data.db"))
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(16)
class DevConfig:
DEBUG = True
RESOURCES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, "resources"))
USER_IMAGES_DIR = os.path.join(RESOURCES_DIR, "users")
STAMP_IMAGES_DIR = os.path.join(RESOURCES_DIR, "stamps")
SQLALCHEMY_DATABASE_URI = "sqlite:///{}".format(os.path.join(RESOURCES_DIR, "data.db"))
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.urandom(16)
| 37.857143 | 100 | 0.718239 | 107 | 795 | 5.056075 | 0.327103 | 0.099815 | 0.12939 | 0.210721 | 0.757856 | 0.757856 | 0.757856 | 0.757856 | 0.757856 | 0.757856 | 0 | 0.005882 | 0.144654 | 795 | 20 | 101 | 39.75 | 0.789706 | 0 | 0 | 0.588235 | 0 | 0 | 0.104403 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.058824 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 7 |
c74ae0305a8a133b574e4c3e3c3778c4379ce627 | 256,249 | py | Python | pyidf/setpoint_managers.py | marcelosalles/pyidf | c2f744211572b5e14e29522aac1421ba88addb0e | [
"Apache-2.0"
] | 19 | 2015-12-08T23:33:51.000Z | 2022-01-31T04:41:10.000Z | pyidf/setpoint_managers.py | marcelosalles/pyidf | c2f744211572b5e14e29522aac1421ba88addb0e | [
"Apache-2.0"
] | 2 | 2019-10-04T10:57:00.000Z | 2021-10-01T06:46:17.000Z | pyidf/setpoint_managers.py | marcelosalles/pyidf | c2f744211572b5e14e29522aac1421ba88addb0e | [
"Apache-2.0"
] | 7 | 2015-11-04T02:25:01.000Z | 2021-12-08T03:14:28.000Z | """ Data objects in group "Setpoint Managers"
"""
from collections import OrderedDict
import logging
from pyidf.helper import DataObject
logger = logging.getLogger("pyidf")
logger.addHandler(logging.NullHandler())
class SetpointManagerScheduled(DataObject):
""" Corresponds to IDD object `SetpointManager:Scheduled`
The simplest Setpoint Manager simply uses a schedule to determine one
or more setpoints. Values of the nodes are not used as input.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'required-field': True,
'autosizable': False,
'accepted-values': [u'Temperature',
u'MaximumTemperature',
u'MinimumTemperature',
u'HumidityRatio',
u'MaximumHumidityRatio',
u'MinimumHumidityRatio',
u'MassFlowRate',
u'MaximumMassFlowRate',
u'MinimumMassFlowRate'],
'autocalculatable': False,
'type': 'alpha'}),
(u'schedule name',
{'name': u'Schedule Name',
'pyname': u'schedule_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:Scheduled',
'pyname': u'SetpointManagerScheduled',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value=None):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def schedule_name(self):
"""field `Schedule Name`
Args:
value (str): value for IDD Field `Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `schedule_name` or None if not set
"""
return self["Schedule Name"]
@schedule_name.setter
def schedule_name(self, value=None):
"""Corresponds to IDD field `Schedule Name`"""
self["Schedule Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which control variable will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerScheduledDualSetpoint(DataObject):
""" Corresponds to IDD object `SetpointManager:Scheduled:DualSetpoint`
This setpoint manager places a high and low schedule value
on one or more nodes.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'high setpoint schedule name',
{'name': u'High Setpoint Schedule Name',
'pyname': u'high_setpoint_schedule_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'low setpoint schedule name',
{'name': u'Low Setpoint Schedule Name',
'pyname': u'low_setpoint_schedule_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:Scheduled:DualSetpoint',
'pyname': u'SetpointManagerScheduledDualSetpoint',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def high_setpoint_schedule_name(self):
"""field `High Setpoint Schedule Name`
Args:
value (str): value for IDD Field `High Setpoint Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `high_setpoint_schedule_name` or None if not set
"""
return self["High Setpoint Schedule Name"]
@high_setpoint_schedule_name.setter
def high_setpoint_schedule_name(self, value=None):
"""Corresponds to IDD field `High Setpoint Schedule Name`"""
self["High Setpoint Schedule Name"] = value
@property
def low_setpoint_schedule_name(self):
"""field `Low Setpoint Schedule Name`
Args:
value (str): value for IDD Field `Low Setpoint Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `low_setpoint_schedule_name` or None if not set
"""
return self["Low Setpoint Schedule Name"]
@low_setpoint_schedule_name.setter
def low_setpoint_schedule_name(self, value=None):
"""Corresponds to IDD field `Low Setpoint Schedule Name`"""
self["Low Setpoint Schedule Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerOutdoorAirReset(DataObject):
""" Corresponds to IDD object `SetpointManager:OutdoorAirReset`
The Outdoor Air Reset Setpoint Manager sets the supply air
temperature according to the outdoor air temperature using a reset rule.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'setpoint at outdoor low temperature',
{'name': u'Setpoint at Outdoor Low Temperature',
'pyname': u'setpoint_at_outdoor_low_temperature',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'outdoor low temperature',
{'name': u'Outdoor Low Temperature',
'pyname': u'outdoor_low_temperature',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'setpoint at outdoor high temperature',
{'name': u'Setpoint at Outdoor High Temperature',
'pyname': u'setpoint_at_outdoor_high_temperature',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'outdoor high temperature',
{'name': u'Outdoor High Temperature',
'pyname': u'outdoor_high_temperature',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'schedule name',
{'name': u'Schedule Name',
'pyname': u'schedule_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'setpoint at outdoor low temperature 2',
{'name': u'Setpoint at Outdoor Low Temperature 2',
'pyname': u'setpoint_at_outdoor_low_temperature_2',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'outdoor low temperature 2',
{'name': u'Outdoor Low Temperature 2',
'pyname': u'outdoor_low_temperature_2',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'setpoint at outdoor high temperature 2',
{'name': u'Setpoint at Outdoor High Temperature 2',
'pyname': u'setpoint_at_outdoor_high_temperature_2',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'outdoor high temperature 2',
{'name': u'Outdoor High Temperature 2',
'pyname': u'outdoor_high_temperature_2',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:OutdoorAirReset',
'pyname': u'SetpointManagerOutdoorAirReset',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def setpoint_at_outdoor_low_temperature(self):
"""field `Setpoint at Outdoor Low Temperature`
| Units: C
Args:
value (float): value for IDD Field `Setpoint at Outdoor Low Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `setpoint_at_outdoor_low_temperature` or None if not set
"""
return self["Setpoint at Outdoor Low Temperature"]
@setpoint_at_outdoor_low_temperature.setter
def setpoint_at_outdoor_low_temperature(self, value=None):
"""Corresponds to IDD field `Setpoint at Outdoor Low Temperature`"""
self["Setpoint at Outdoor Low Temperature"] = value
@property
def outdoor_low_temperature(self):
"""field `Outdoor Low Temperature`
| Units: C
Args:
value (float): value for IDD Field `Outdoor Low Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `outdoor_low_temperature` or None if not set
"""
return self["Outdoor Low Temperature"]
@outdoor_low_temperature.setter
def outdoor_low_temperature(self, value=None):
"""Corresponds to IDD field `Outdoor Low Temperature`"""
self["Outdoor Low Temperature"] = value
@property
def setpoint_at_outdoor_high_temperature(self):
"""field `Setpoint at Outdoor High Temperature`
| Units: C
Args:
value (float): value for IDD Field `Setpoint at Outdoor High Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `setpoint_at_outdoor_high_temperature` or None if not set
"""
return self["Setpoint at Outdoor High Temperature"]
@setpoint_at_outdoor_high_temperature.setter
def setpoint_at_outdoor_high_temperature(self, value=None):
"""Corresponds to IDD field `Setpoint at Outdoor High Temperature`"""
self["Setpoint at Outdoor High Temperature"] = value
@property
def outdoor_high_temperature(self):
"""field `Outdoor High Temperature`
| Units: C
Args:
value (float): value for IDD Field `Outdoor High Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `outdoor_high_temperature` or None if not set
"""
return self["Outdoor High Temperature"]
@outdoor_high_temperature.setter
def outdoor_high_temperature(self, value=None):
"""Corresponds to IDD field `Outdoor High Temperature`"""
self["Outdoor High Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
@property
def schedule_name(self):
"""field `Schedule Name`
| Optional input.
| Schedule allows scheduling of the outdoor air reset rule - a schedule value
| of 1 means use the first rule; a value of 2 means use the second rule.
Args:
value (str): value for IDD Field `Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `schedule_name` or None if not set
"""
return self["Schedule Name"]
@schedule_name.setter
def schedule_name(self, value=None):
"""Corresponds to IDD field `Schedule Name`"""
self["Schedule Name"] = value
@property
def setpoint_at_outdoor_low_temperature_2(self):
"""field `Setpoint at Outdoor Low Temperature 2`
| 2nd outdoor air temperature reset rule
| Units: C
Args:
value (float): value for IDD Field `Setpoint at Outdoor Low Temperature 2`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `setpoint_at_outdoor_low_temperature_2` or None if not set
"""
return self["Setpoint at Outdoor Low Temperature 2"]
@setpoint_at_outdoor_low_temperature_2.setter
def setpoint_at_outdoor_low_temperature_2(self, value=None):
"""Corresponds to IDD field `Setpoint at Outdoor Low Temperature 2`"""
self["Setpoint at Outdoor Low Temperature 2"] = value
@property
def outdoor_low_temperature_2(self):
"""field `Outdoor Low Temperature 2`
| 2nd outdoor air temperature reset rule
| Units: C
Args:
value (float): value for IDD Field `Outdoor Low Temperature 2`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `outdoor_low_temperature_2` or None if not set
"""
return self["Outdoor Low Temperature 2"]
@outdoor_low_temperature_2.setter
def outdoor_low_temperature_2(self, value=None):
"""Corresponds to IDD field `Outdoor Low Temperature 2`"""
self["Outdoor Low Temperature 2"] = value
@property
def setpoint_at_outdoor_high_temperature_2(self):
"""field `Setpoint at Outdoor High Temperature 2`
| 2nd outdoor air temperature reset rule
| Units: C
Args:
value (float): value for IDD Field `Setpoint at Outdoor High Temperature 2`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `setpoint_at_outdoor_high_temperature_2` or None if not set
"""
return self["Setpoint at Outdoor High Temperature 2"]
@setpoint_at_outdoor_high_temperature_2.setter
def setpoint_at_outdoor_high_temperature_2(self, value=None):
"""Corresponds to IDD field `Setpoint at Outdoor High Temperature 2`"""
self["Setpoint at Outdoor High Temperature 2"] = value
@property
def outdoor_high_temperature_2(self):
"""field `Outdoor High Temperature 2`
| 2nd outdoor air temperature reset rule
| Units: C
Args:
value (float): value for IDD Field `Outdoor High Temperature 2`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `outdoor_high_temperature_2` or None if not set
"""
return self["Outdoor High Temperature 2"]
@outdoor_high_temperature_2.setter
def outdoor_high_temperature_2(self, value=None):
"""Corresponds to IDD field `Outdoor High Temperature 2`"""
self["Outdoor High Temperature 2"] = value
class SetpointManagerSingleZoneReheat(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:Reheat`
This setpoint manager detects the control zone load, zone inlet node flow rate, and
zone node temperature and calculates a setpoint temperature for the supply air that
will satisfy the zone load (heating or cooling) for the control zone. This setpoint
manager is not limited to reheat applications.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'minimum supply air temperature',
{'name': u'Minimum Supply Air Temperature',
'pyname': u'minimum_supply_air_temperature',
'default': -99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'maximum supply air temperature',
{'name': u'Maximum Supply Air Temperature',
'pyname': u'maximum_supply_air_temperature',
'default': 99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'control zone name',
{'name': u'Control Zone Name',
'pyname': u'control_zone_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'zone node name',
{'name': u'Zone Node Name',
'pyname': u'zone_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'zone inlet node name',
{'name': u'Zone Inlet Node Name',
'pyname': u'zone_inlet_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:SingleZone:Reheat',
'pyname': u'SetpointManagerSingleZoneReheat',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def minimum_supply_air_temperature(self):
"""field `Minimum Supply Air Temperature`
| Units: C
| Default value: -99.0
Args:
value (float): value for IDD Field `Minimum Supply Air Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_supply_air_temperature` or None if not set
"""
return self["Minimum Supply Air Temperature"]
@minimum_supply_air_temperature.setter
def minimum_supply_air_temperature(self, value=-99.0):
"""Corresponds to IDD field `Minimum Supply Air Temperature`"""
self["Minimum Supply Air Temperature"] = value
@property
def maximum_supply_air_temperature(self):
"""field `Maximum Supply Air Temperature`
| Units: C
| Default value: 99.0
Args:
value (float): value for IDD Field `Maximum Supply Air Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_supply_air_temperature` or None if not set
"""
return self["Maximum Supply Air Temperature"]
@maximum_supply_air_temperature.setter
def maximum_supply_air_temperature(self, value=99.0):
"""Corresponds to IDD field `Maximum Supply Air Temperature`"""
self["Maximum Supply Air Temperature"] = value
@property
def control_zone_name(self):
"""field `Control Zone Name`
Args:
value (str): value for IDD Field `Control Zone Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_name` or None if not set
"""
return self["Control Zone Name"]
@control_zone_name.setter
def control_zone_name(self, value=None):
"""Corresponds to IDD field `Control Zone Name`"""
self["Control Zone Name"] = value
@property
def zone_node_name(self):
"""field `Zone Node Name`
Args:
value (str): value for IDD Field `Zone Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `zone_node_name` or None if not set
"""
return self["Zone Node Name"]
@zone_node_name.setter
def zone_node_name(self, value=None):
"""Corresponds to IDD field `Zone Node Name`"""
self["Zone Node Name"] = value
@property
def zone_inlet_node_name(self):
"""field `Zone Inlet Node Name`
Args:
value (str): value for IDD Field `Zone Inlet Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `zone_inlet_node_name` or None if not set
"""
return self["Zone Inlet Node Name"]
@zone_inlet_node_name.setter
def zone_inlet_node_name(self, value=None):
"""Corresponds to IDD field `Zone Inlet Node Name`"""
self["Zone Inlet Node Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerSingleZoneHeating(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:Heating`
This setpoint manager detects the control zone load to meet the current heating
setpoint, zone inlet node flow rate, and zone node temperature, and calculates a
setpoint temperature for the supply air that will satisfy the zone heating load for
the control zone.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'minimum supply air temperature',
{'name': u'Minimum Supply Air Temperature',
'pyname': u'minimum_supply_air_temperature',
'default': -99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'maximum supply air temperature',
{'name': u'Maximum Supply Air Temperature',
'pyname': u'maximum_supply_air_temperature',
'default': 99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'control zone name',
{'name': u'Control Zone Name',
'pyname': u'control_zone_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'zone node name',
{'name': u'Zone Node Name',
'pyname': u'zone_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'zone inlet node name',
{'name': u'Zone Inlet Node Name',
'pyname': u'zone_inlet_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 8,
'name': u'SetpointManager:SingleZone:Heating',
'pyname': u'SetpointManagerSingleZoneHeating',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def minimum_supply_air_temperature(self):
"""field `Minimum Supply Air Temperature`
| Units: C
| Default value: -99.0
Args:
value (float): value for IDD Field `Minimum Supply Air Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_supply_air_temperature` or None if not set
"""
return self["Minimum Supply Air Temperature"]
@minimum_supply_air_temperature.setter
def minimum_supply_air_temperature(self, value=-99.0):
"""Corresponds to IDD field `Minimum Supply Air Temperature`"""
self["Minimum Supply Air Temperature"] = value
@property
def maximum_supply_air_temperature(self):
"""field `Maximum Supply Air Temperature`
| Units: C
| Default value: 99.0
Args:
value (float): value for IDD Field `Maximum Supply Air Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_supply_air_temperature` or None if not set
"""
return self["Maximum Supply Air Temperature"]
@maximum_supply_air_temperature.setter
def maximum_supply_air_temperature(self, value=99.0):
"""Corresponds to IDD field `Maximum Supply Air Temperature`"""
self["Maximum Supply Air Temperature"] = value
@property
def control_zone_name(self):
"""field `Control Zone Name`
Args:
value (str): value for IDD Field `Control Zone Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_name` or None if not set
"""
return self["Control Zone Name"]
@control_zone_name.setter
def control_zone_name(self, value=None):
"""Corresponds to IDD field `Control Zone Name`"""
self["Control Zone Name"] = value
@property
def zone_node_name(self):
"""field `Zone Node Name`
Args:
value (str): value for IDD Field `Zone Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `zone_node_name` or None if not set
"""
return self["Zone Node Name"]
@zone_node_name.setter
def zone_node_name(self, value=None):
"""Corresponds to IDD field `Zone Node Name`"""
self["Zone Node Name"] = value
@property
def zone_inlet_node_name(self):
"""field `Zone Inlet Node Name`
Args:
value (str): value for IDD Field `Zone Inlet Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `zone_inlet_node_name` or None if not set
"""
return self["Zone Inlet Node Name"]
@zone_inlet_node_name.setter
def zone_inlet_node_name(self, value=None):
"""Corresponds to IDD field `Zone Inlet Node Name`"""
self["Zone Inlet Node Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerSingleZoneCooling(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:Cooling`
This setpoint manager detects the control zone load to meet the current cooling
setpoint, zone inlet node flow rate, and zone node temperature, and calculates a
setpoint temperature for the supply air that will satisfy the zone cooling load for
the control zone.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'minimum supply air temperature',
{'name': u'Minimum Supply Air Temperature',
'pyname': u'minimum_supply_air_temperature',
'default': -99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'maximum supply air temperature',
{'name': u'Maximum Supply Air Temperature',
'pyname': u'maximum_supply_air_temperature',
'default': 99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'control zone name',
{'name': u'Control Zone Name',
'pyname': u'control_zone_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'zone node name',
{'name': u'Zone Node Name',
'pyname': u'zone_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'zone inlet node name',
{'name': u'Zone Inlet Node Name',
'pyname': u'zone_inlet_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 8,
'name': u'SetpointManager:SingleZone:Cooling',
'pyname': u'SetpointManagerSingleZoneCooling',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def minimum_supply_air_temperature(self):
"""field `Minimum Supply Air Temperature`
| Units: C
| Default value: -99.0
Args:
value (float): value for IDD Field `Minimum Supply Air Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_supply_air_temperature` or None if not set
"""
return self["Minimum Supply Air Temperature"]
@minimum_supply_air_temperature.setter
def minimum_supply_air_temperature(self, value=-99.0):
"""Corresponds to IDD field `Minimum Supply Air Temperature`"""
self["Minimum Supply Air Temperature"] = value
@property
def maximum_supply_air_temperature(self):
"""field `Maximum Supply Air Temperature`
| Units: C
| Default value: 99.0
Args:
value (float): value for IDD Field `Maximum Supply Air Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_supply_air_temperature` or None if not set
"""
return self["Maximum Supply Air Temperature"]
@maximum_supply_air_temperature.setter
def maximum_supply_air_temperature(self, value=99.0):
"""Corresponds to IDD field `Maximum Supply Air Temperature`"""
self["Maximum Supply Air Temperature"] = value
@property
def control_zone_name(self):
"""field `Control Zone Name`
Args:
value (str): value for IDD Field `Control Zone Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_name` or None if not set
"""
return self["Control Zone Name"]
@control_zone_name.setter
def control_zone_name(self, value=None):
"""Corresponds to IDD field `Control Zone Name`"""
self["Control Zone Name"] = value
@property
def zone_node_name(self):
"""field `Zone Node Name`
Args:
value (str): value for IDD Field `Zone Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `zone_node_name` or None if not set
"""
return self["Zone Node Name"]
@zone_node_name.setter
def zone_node_name(self, value=None):
"""Corresponds to IDD field `Zone Node Name`"""
self["Zone Node Name"] = value
@property
def zone_inlet_node_name(self):
"""field `Zone Inlet Node Name`
Args:
value (str): value for IDD Field `Zone Inlet Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `zone_inlet_node_name` or None if not set
"""
return self["Zone Inlet Node Name"]
@zone_inlet_node_name.setter
def zone_inlet_node_name(self, value=None):
"""Corresponds to IDD field `Zone Inlet Node Name`"""
self["Zone Inlet Node Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerSingleZoneHumidityMinimum(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:Humidity:Minimum`
The Single Zone Minimum Humidity Setpoint Manager allows the
control of a single zone minimum humidity level.
This setpoint manager can be used in conjunction with
object ZoneControl:Humidistat to detect humidity levels.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'schedule name',
{'name': u'Schedule Name',
'pyname': u'schedule_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'control zone air node name',
{'name': u'Control Zone Air Node Name',
'pyname': u'control_zone_air_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:SingleZone:Humidity:Minimum',
'pyname': u'SetpointManagerSingleZoneHumidityMinimum',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| This field is not really used and will be deleted from the object.
| The required information is gotten internally or
| not needed by the program.
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value=None):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def schedule_name(self):
"""field `Schedule Name`
| This field is not really used and will be deleted from the object.
| The required information is gotten internally or
| not needed by the program.
Args:
value (str): value for IDD Field `Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `schedule_name` or None if not set
"""
return self["Schedule Name"]
@schedule_name.setter
def schedule_name(self, value=None):
"""Corresponds to IDD field `Schedule Name`"""
self["Schedule Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which humidity ratio setpoint will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
@property
def control_zone_air_node_name(self):
"""field `Control Zone Air Node Name`
| Name of the zone air node for the humidity control zone
Args:
value (str): value for IDD Field `Control Zone Air Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_air_node_name` or None if not set
"""
return self["Control Zone Air Node Name"]
@control_zone_air_node_name.setter
def control_zone_air_node_name(self, value=None):
"""Corresponds to IDD field `Control Zone Air Node Name`"""
self["Control Zone Air Node Name"] = value
class SetpointManagerSingleZoneHumidityMaximum(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:Humidity:Maximum`
The Single Zone Maximum Humidity Setpoint Manager allows the
control of a single zone maximum humidity level.
This setpoint manager can be used in conjunction with
object ZoneControl:Humidistat to detect humidity levels.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'schedule name',
{'name': u'Schedule Name',
'pyname': u'schedule_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'control zone air node name',
{'name': u'Control Zone Air Node Name',
'pyname': u'control_zone_air_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:SingleZone:Humidity:Maximum',
'pyname': u'SetpointManagerSingleZoneHumidityMaximum',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| This field is not really used and will be deleted from the object.
| The required information is gotten internally or
| not needed by the program.
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value=None):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def schedule_name(self):
"""field `Schedule Name`
| This field is not really used and will be deleted from the object.
| The required information is gotten internally or
| not needed by the program.
Args:
value (str): value for IDD Field `Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `schedule_name` or None if not set
"""
return self["Schedule Name"]
@schedule_name.setter
def schedule_name(self, value=None):
"""Corresponds to IDD field `Schedule Name`"""
self["Schedule Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which humidity ratio setpoint will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
@property
def control_zone_air_node_name(self):
"""field `Control Zone Air Node Name`
| Name of the zone air node for the humidity control zone
Args:
value (str): value for IDD Field `Control Zone Air Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_air_node_name` or None if not set
"""
return self["Control Zone Air Node Name"]
@control_zone_air_node_name.setter
def control_zone_air_node_name(self, value=None):
"""Corresponds to IDD field `Control Zone Air Node Name`"""
self["Control Zone Air Node Name"] = value
class SetpointManagerMixedAir(DataObject):
""" Corresponds to IDD object `SetpointManager:MixedAir`
The Mixed Air Setpoint Manager is meant to be used in conjunction
with a Controller:OutdoorAir object. This setpoint manager is used
to establish a temperature setpoint at the mixed air node.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'reference setpoint node name',
{'name': u'Reference Setpoint Node Name',
'pyname': u'reference_setpoint_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'fan inlet node name',
{'name': u'Fan Inlet Node Name',
'pyname': u'fan_inlet_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'fan outlet node name',
{'name': u'Fan Outlet Node Name',
'pyname': u'fan_outlet_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:MixedAir',
'pyname': u'SetpointManagerMixedAir',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def reference_setpoint_node_name(self):
"""field `Reference Setpoint Node Name`
Args:
value (str): value for IDD Field `Reference Setpoint Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `reference_setpoint_node_name` or None if not set
"""
return self["Reference Setpoint Node Name"]
@reference_setpoint_node_name.setter
def reference_setpoint_node_name(self, value=None):
"""Corresponds to IDD field `Reference Setpoint Node Name`"""
self["Reference Setpoint Node Name"] = value
@property
def fan_inlet_node_name(self):
"""field `Fan Inlet Node Name`
Args:
value (str): value for IDD Field `Fan Inlet Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `fan_inlet_node_name` or None if not set
"""
return self["Fan Inlet Node Name"]
@fan_inlet_node_name.setter
def fan_inlet_node_name(self, value=None):
"""Corresponds to IDD field `Fan Inlet Node Name`"""
self["Fan Inlet Node Name"] = value
@property
def fan_outlet_node_name(self):
"""field `Fan Outlet Node Name`
Args:
value (str): value for IDD Field `Fan Outlet Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `fan_outlet_node_name` or None if not set
"""
return self["Fan Outlet Node Name"]
@fan_outlet_node_name.setter
def fan_outlet_node_name(self, value=None):
"""Corresponds to IDD field `Fan Outlet Node Name`"""
self["Fan Outlet Node Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerOutdoorAirPretreat(DataObject):
""" Corresponds to IDD object `SetpointManager:OutdoorAirPretreat`
This setpoint manager determines the required
conditions at the outdoor air stream node which will
produce the reference setpoint condition at the
mixed air node when mixed with the return air stream
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature',
u'HumidityRatio',
u'MaximumHumidityRatio',
u'MinimumHumidityRatio'],
'autocalculatable': False,
'type': 'alpha'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'default': -99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'default': 99.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'minimum setpoint humidity ratio',
{'name': u'Minimum Setpoint Humidity Ratio',
'pyname': u'minimum_setpoint_humidity_ratio',
'default': 1e-05,
'maximum': 1.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'kgWater/kgDryAir'}),
(u'maximum setpoint humidity ratio',
{'name': u'Maximum Setpoint Humidity Ratio',
'pyname': u'maximum_setpoint_humidity_ratio',
'default': 1.0,
'maximum': 1.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'kgWater/kgDryAir'}),
(u'reference setpoint node name',
{'name': u'Reference Setpoint Node Name',
'pyname': u'reference_setpoint_node_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'mixed air stream node name',
{'name': u'Mixed Air Stream Node Name',
'pyname': u'mixed_air_stream_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'outdoor air stream node name',
{'name': u'Outdoor Air Stream Node Name',
'pyname': u'outdoor_air_stream_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'return air stream node name',
{'name': u'Return Air Stream Node Name',
'pyname': u'return_air_stream_node_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 11,
'name': u'SetpointManager:OutdoorAirPretreat',
'pyname': u'SetpointManagerOutdoorAirPretreat',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value=None):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Applicable only if Control variable is Temperature
| Units: C
| Default value: -99.0
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=-99.0):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Applicable only if Control variable is Temperature
| Units: C
| Default value: 99.0
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=99.0):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def minimum_setpoint_humidity_ratio(self):
"""field `Minimum Setpoint Humidity Ratio`
| Applicable only if Control variable is
| MaximumHumidityRatio, MinimumHumidityRatio, or HumidityRatio - then minimum is 0.00001
| Units: kgWater/kgDryAir
| Default value: 1e-05
| value <= 1.0
Args:
value (float): value for IDD Field `Minimum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_humidity_ratio` or None if not set
"""
return self["Minimum Setpoint Humidity Ratio"]
@minimum_setpoint_humidity_ratio.setter
def minimum_setpoint_humidity_ratio(self, value=1e-05):
"""Corresponds to IDD field `Minimum Setpoint Humidity Ratio`"""
self["Minimum Setpoint Humidity Ratio"] = value
@property
def maximum_setpoint_humidity_ratio(self):
"""field `Maximum Setpoint Humidity Ratio`
| Applicable only if Control variable is
| MaximumHumidityRatio, MinimumHumidityRatio, or HumidityRatio - then minimum is 0.00001
| Units: kgWater/kgDryAir
| Default value: 1.0
| value <= 1.0
Args:
value (float): value for IDD Field `Maximum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_humidity_ratio` or None if not set
"""
return self["Maximum Setpoint Humidity Ratio"]
@maximum_setpoint_humidity_ratio.setter
def maximum_setpoint_humidity_ratio(self, value=1.0):
"""Corresponds to IDD field `Maximum Setpoint Humidity Ratio`"""
self["Maximum Setpoint Humidity Ratio"] = value
@property
def reference_setpoint_node_name(self):
"""field `Reference Setpoint Node Name`
| The current setpoint at this node is the
| desired condition for the Mixed Air Node
| This node must have a valid setpoint
| which has been set by another setpoint manager
Args:
value (str): value for IDD Field `Reference Setpoint Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `reference_setpoint_node_name` or None if not set
"""
return self["Reference Setpoint Node Name"]
@reference_setpoint_node_name.setter
def reference_setpoint_node_name(self, value=None):
"""Corresponds to IDD field `Reference Setpoint Node Name`"""
self["Reference Setpoint Node Name"] = value
@property
def mixed_air_stream_node_name(self):
"""field `Mixed Air Stream Node Name`
| Name of Mixed Air Node
Args:
value (str): value for IDD Field `Mixed Air Stream Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `mixed_air_stream_node_name` or None if not set
"""
return self["Mixed Air Stream Node Name"]
@mixed_air_stream_node_name.setter
def mixed_air_stream_node_name(self, value=None):
"""Corresponds to IDD field `Mixed Air Stream Node Name`"""
self["Mixed Air Stream Node Name"] = value
@property
def outdoor_air_stream_node_name(self):
"""field `Outdoor Air Stream Node Name`
| Name of Outdoor Air Stream Node
Args:
value (str): value for IDD Field `Outdoor Air Stream Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `outdoor_air_stream_node_name` or None if not set
"""
return self["Outdoor Air Stream Node Name"]
@outdoor_air_stream_node_name.setter
def outdoor_air_stream_node_name(self, value=None):
"""Corresponds to IDD field `Outdoor Air Stream Node Name`"""
self["Outdoor Air Stream Node Name"] = value
@property
def return_air_stream_node_name(self):
"""field `Return Air Stream Node Name`
| Name of Return Air Stream Node
Args:
value (str): value for IDD Field `Return Air Stream Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `return_air_stream_node_name` or None if not set
"""
return self["Return Air Stream Node Name"]
@return_air_stream_node_name.setter
def return_air_stream_node_name(self, value=None):
"""Corresponds to IDD field `Return Air Stream Node Name`"""
self["Return Air Stream Node Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature or humidity
| ratio will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerWarmest(DataObject):
""" Corresponds to IDD object `SetpointManager:Warmest`
This SetpointManager resets the cooling supply air temperature
of a central forced air HVAC system according to the
cooling demand of the warmest zone.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'default': 12.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'default': 18.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'strategy',
{'name': u'Strategy',
'pyname': u'strategy',
'default': u'MaximumTemperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'MaximumTemperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:Warmest',
'pyname': u'SetpointManagerWarmest',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
| Default value: 12.0
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=12.0):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
| Default value: 18.0
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=18.0):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def strategy(self):
"""field `Strategy`
| Default value: MaximumTemperature
Args:
value (str): value for IDD Field `Strategy`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `strategy` or None if not set
"""
return self["Strategy"]
@strategy.setter
def strategy(self, value="MaximumTemperature"):
"""Corresponds to IDD field `Strategy`"""
self["Strategy"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerColdest(DataObject):
""" Corresponds to IDD object `SetpointManager:Coldest`
This SetpointManager is used in dual duct systems to reset
the setpoint temperature of the air in the heating supply duct.
Usually it is used in conjunction with a SetpointManager:Warmest
resetting the temperature of the air in the cooling supply duct.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'default': 20.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'default': 50.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'strategy',
{'name': u'Strategy',
'pyname': u'strategy',
'default': u'MinimumTemperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'MinimumTemperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:Coldest',
'pyname': u'SetpointManagerColdest',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object.
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
| Default value: 20.0
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=20.0):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
| Default value: 50.0
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=50.0):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def strategy(self):
"""field `Strategy`
| Default value: MinimumTemperature
Args:
value (str): value for IDD Field `Strategy`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `strategy` or None if not set
"""
return self["Strategy"]
@strategy.setter
def strategy(self, value="MinimumTemperature"):
"""Corresponds to IDD field `Strategy`"""
self["Strategy"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerReturnAirBypassFlow(DataObject):
""" Corresponds to IDD object `SetpointManager:ReturnAirBypassFlow`
This setpoint manager determines the required
mass flow rate through a return air bypass duct
to meet the specified temperature setpoint
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Flow',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Flow'],
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'temperature setpoint schedule name',
{'name': u'Temperature Setpoint Schedule Name',
'pyname': u'temperature_setpoint_schedule_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 4,
'name': u'SetpointManager:ReturnAirBypassFlow',
'pyname': u'SetpointManagerReturnAirBypassFlow',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Flow
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Flow"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object.
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def temperature_setpoint_schedule_name(self):
"""field `Temperature Setpoint Schedule Name`
Args:
value (str): value for IDD Field `Temperature Setpoint Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `temperature_setpoint_schedule_name` or None if not set
"""
return self["Temperature Setpoint Schedule Name"]
@temperature_setpoint_schedule_name.setter
def temperature_setpoint_schedule_name(self, value=None):
"""Corresponds to IDD field `Temperature Setpoint Schedule Name`"""
self["Temperature Setpoint Schedule Name"] = value
class SetpointManagerWarmestTemperatureFlow(DataObject):
""" Corresponds to IDD object `SetpointManager:WarmestTemperatureFlow`
This setpoint manager sets both the supply air temperature
and the supply air flow rate.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'default': 12.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'default': 18.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'strategy',
{'name': u'Strategy',
'pyname': u'strategy',
'default': u'TemperatureFirst',
'required-field': False,
'autosizable': False,
'accepted-values': [u'TemperatureFirst',
u'FlowFirst'],
'autocalculatable': False,
'type': 'alpha'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'minimum turndown ratio',
{'name': u'Minimum Turndown Ratio',
'pyname': u'minimum_turndown_ratio',
'default': 0.2,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'dimensionless'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 8,
'name': u'SetpointManager:WarmestTemperatureFlow',
'pyname': u'SetpointManagerWarmestTemperatureFlow',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value=None):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object.
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
| Default value: 12.0
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=12.0):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
| Default value: 18.0
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=18.0):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def strategy(self):
"""field `Strategy`
| For TemperatureFirst the manager tries to find the highest setpoint temperature
| that will satisfy all the zone cooling loads at minimum supply air flow rate.
| If this setpoint temperature is less than the minimum, the setpoint temperature is set
| to the minimum, and the supply air flow rate is increased to meet the loads.
| For FlowFirst the manager tries to find the lowest supply air flow rate
| that will satisfy all the zone cooling loads at the maximum setpoint temperature.
| If this flow is greater than the maximum, the flow is set to the maximum and the
| setpoint temperature is reduced to satisfy the cooling loads.
| Default value: TemperatureFirst
Args:
value (str): value for IDD Field `Strategy`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `strategy` or None if not set
"""
return self["Strategy"]
@strategy.setter
def strategy(self, value="TemperatureFirst"):
"""Corresponds to IDD field `Strategy`"""
self["Strategy"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
@property
def minimum_turndown_ratio(self):
"""field `Minimum Turndown Ratio`
| Fraction of the maximum supply air flow rate.
| Used to define the minimum supply flow for the TemperatureFirst strategy.
| Units: dimensionless
| Default value: 0.2
Args:
value (float): value for IDD Field `Minimum Turndown Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_turndown_ratio` or None if not set
"""
return self["Minimum Turndown Ratio"]
@minimum_turndown_ratio.setter
def minimum_turndown_ratio(self, value=0.2):
"""Corresponds to IDD field `Minimum Turndown Ratio`"""
self["Minimum Turndown Ratio"] = value
class SetpointManagerMultiZoneHeatingAverage(DataObject):
""" Corresponds to IDD object `SetpointManager:MultiZone:Heating:Average`
This setpoint manager sets the average supply air temperature based on the heating load
requirements of all controlled zones in an air loop served by a central air-conditioner.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'default': 20.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'default': 50.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:MultiZone:Heating:Average',
'pyname': u'SetpointManagerMultiZoneHeatingAverage',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
| Default value: 20.0
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=20.0):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
| Default value: 50.0
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=50.0):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerMultiZoneCoolingAverage(DataObject):
""" Corresponds to IDD object `SetpointManager:MultiZone:Cooling:Average`
This setpoint manager sets the average supply air temperature based on the cooling load
requirements of all controlled zones in an air loop served by a central air-conditioner.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'default': 12.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'default': 18.0,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:MultiZone:Cooling:Average',
'pyname': u'SetpointManagerMultiZoneCoolingAverage',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
| Default value: 12.0
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=12.0):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
| Default value: 18.0
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=18.0):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerMultiZoneMinimumHumidityAverage(DataObject):
""" Corresponds to IDD object `SetpointManager:MultiZone:MinimumHumidity:Average`
This setpoint manager sets the average supply air minimum humidity ratio based on moisture
load requirements of all controlled zones in an air loop served by a central air-conditioner.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint humidity ratio',
{'name': u'Minimum Setpoint Humidity Ratio',
'pyname': u'minimum_setpoint_humidity_ratio',
'default': 0.005,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'maximum setpoint humidity ratio',
{'name': u'Maximum Setpoint Humidity Ratio',
'pyname': u'maximum_setpoint_humidity_ratio',
'default': 0.012,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:MultiZone:MinimumHumidity:Average',
'pyname': u'SetpointManagerMultiZoneMinimumHumidityAverage',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_humidity_ratio(self):
"""field `Minimum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.005
Args:
value (float): value for IDD Field `Minimum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_humidity_ratio` or None if not set
"""
return self["Minimum Setpoint Humidity Ratio"]
@minimum_setpoint_humidity_ratio.setter
def minimum_setpoint_humidity_ratio(self, value=0.005):
"""Corresponds to IDD field `Minimum Setpoint Humidity Ratio`"""
self["Minimum Setpoint Humidity Ratio"] = value
@property
def maximum_setpoint_humidity_ratio(self):
"""field `Maximum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.012
Args:
value (float): value for IDD Field `Maximum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_humidity_ratio` or None if not set
"""
return self["Maximum Setpoint Humidity Ratio"]
@maximum_setpoint_humidity_ratio.setter
def maximum_setpoint_humidity_ratio(self, value=0.012):
"""Corresponds to IDD field `Maximum Setpoint Humidity Ratio`"""
self["Maximum Setpoint Humidity Ratio"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the humidity ratio will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerMultiZoneMaximumHumidityAverage(DataObject):
""" Corresponds to IDD object `SetpointManager:MultiZone:MaximumHumidity:Average`
This setpoint manager sets the average supply air maximum humidity ratio based on moisture
load requirements of all controlled zones in an air loop served by a central air-conditioner.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint humidity ratio',
{'name': u'Minimum Setpoint Humidity Ratio',
'pyname': u'minimum_setpoint_humidity_ratio',
'default': 0.008,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'maximum setpoint humidity ratio',
{'name': u'Maximum Setpoint Humidity Ratio',
'pyname': u'maximum_setpoint_humidity_ratio',
'default': 0.015,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:MultiZone:MaximumHumidity:Average',
'pyname': u'SetpointManagerMultiZoneMaximumHumidityAverage',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_humidity_ratio(self):
"""field `Minimum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.008
Args:
value (float): value for IDD Field `Minimum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_humidity_ratio` or None if not set
"""
return self["Minimum Setpoint Humidity Ratio"]
@minimum_setpoint_humidity_ratio.setter
def minimum_setpoint_humidity_ratio(self, value=0.008):
"""Corresponds to IDD field `Minimum Setpoint Humidity Ratio`"""
self["Minimum Setpoint Humidity Ratio"] = value
@property
def maximum_setpoint_humidity_ratio(self):
"""field `Maximum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.015
Args:
value (float): value for IDD Field `Maximum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_humidity_ratio` or None if not set
"""
return self["Maximum Setpoint Humidity Ratio"]
@maximum_setpoint_humidity_ratio.setter
def maximum_setpoint_humidity_ratio(self, value=0.015):
"""Corresponds to IDD field `Maximum Setpoint Humidity Ratio`"""
self["Maximum Setpoint Humidity Ratio"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the humidity ratio will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerMultiZoneHumidityMinimum(DataObject):
""" Corresponds to IDD object `SetpointManager:MultiZone:Humidity:Minimum`
This setpoint manager sets the minimum supply air humidity ratio based on humidification
requirements of a controlled zone with critical humidity ratio setpoint (i.e., a zone with
the highest humidity ratio setpoint) in an air loop served by a central air-conditioner.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint humidity ratio',
{'name': u'Minimum Setpoint Humidity Ratio',
'pyname': u'minimum_setpoint_humidity_ratio',
'default': 0.005,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'maximum setpoint humidity ratio',
{'name': u'Maximum Setpoint Humidity Ratio',
'pyname': u'maximum_setpoint_humidity_ratio',
'default': 0.012,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:MultiZone:Humidity:Minimum',
'pyname': u'SetpointManagerMultiZoneHumidityMinimum',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_humidity_ratio(self):
"""field `Minimum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.005
Args:
value (float): value for IDD Field `Minimum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_humidity_ratio` or None if not set
"""
return self["Minimum Setpoint Humidity Ratio"]
@minimum_setpoint_humidity_ratio.setter
def minimum_setpoint_humidity_ratio(self, value=0.005):
"""Corresponds to IDD field `Minimum Setpoint Humidity Ratio`"""
self["Minimum Setpoint Humidity Ratio"] = value
@property
def maximum_setpoint_humidity_ratio(self):
"""field `Maximum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.012
Args:
value (float): value for IDD Field `Maximum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_humidity_ratio` or None if not set
"""
return self["Maximum Setpoint Humidity Ratio"]
@maximum_setpoint_humidity_ratio.setter
def maximum_setpoint_humidity_ratio(self, value=0.012):
"""Corresponds to IDD field `Maximum Setpoint Humidity Ratio`"""
self["Maximum Setpoint Humidity Ratio"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the humidity ratio will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerMultiZoneHumidityMaximum(DataObject):
""" Corresponds to IDD object `SetpointManager:MultiZone:Humidity:Maximum`
This setpoint manager sets the maximum supply air humidity ratio based on dehumidification
requirements of a controlled zone with critical humidity ratio setpoint (i.e., a zone with
the lowest humidity ratio setpoint) in an air loop served by a central air-conditioner.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'hvac air loop name',
{'name': u'HVAC Air Loop Name',
'pyname': u'hvac_air_loop_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum setpoint humidity ratio',
{'name': u'Minimum Setpoint Humidity Ratio',
'pyname': u'minimum_setpoint_humidity_ratio',
'default': 0.008,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'maximum setpoint humidity ratio',
{'name': u'Maximum Setpoint Humidity Ratio',
'pyname': u'maximum_setpoint_humidity_ratio',
'default': 0.015,
'minimum>': 0.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'kgWater/kgDryAir'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:MultiZone:Humidity:Maximum',
'pyname': u'SetpointManagerMultiZoneHumidityMaximum',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def hvac_air_loop_name(self):
"""field `HVAC Air Loop Name`
| Enter the name of an AirLoopHVAC object
Args:
value (str): value for IDD Field `HVAC Air Loop Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `hvac_air_loop_name` or None if not set
"""
return self["HVAC Air Loop Name"]
@hvac_air_loop_name.setter
def hvac_air_loop_name(self, value=None):
"""Corresponds to IDD field `HVAC Air Loop Name`"""
self["HVAC Air Loop Name"] = value
@property
def minimum_setpoint_humidity_ratio(self):
"""field `Minimum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.008
Args:
value (float): value for IDD Field `Minimum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_humidity_ratio` or None if not set
"""
return self["Minimum Setpoint Humidity Ratio"]
@minimum_setpoint_humidity_ratio.setter
def minimum_setpoint_humidity_ratio(self, value=0.008):
"""Corresponds to IDD field `Minimum Setpoint Humidity Ratio`"""
self["Minimum Setpoint Humidity Ratio"] = value
@property
def maximum_setpoint_humidity_ratio(self):
"""field `Maximum Setpoint Humidity Ratio`
| Units: kgWater/kgDryAir
| Default value: 0.015
Args:
value (float): value for IDD Field `Maximum Setpoint Humidity Ratio`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_humidity_ratio` or None if not set
"""
return self["Maximum Setpoint Humidity Ratio"]
@maximum_setpoint_humidity_ratio.setter
def maximum_setpoint_humidity_ratio(self, value=0.015):
"""Corresponds to IDD field `Maximum Setpoint Humidity Ratio`"""
self["Maximum Setpoint Humidity Ratio"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the humidity ratio will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerFollowOutdoorAirTemperature(DataObject):
""" Corresponds to IDD object `SetpointManager:FollowOutdoorAirTemperature`
This setpoint manager is used to place a temperature setpoint on a system node
that is derived from the current outdoor air environmental conditions.
The outdoor air conditions are obtained from the weather information during the simulation.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature',
u'MinimumTemperature',
u'MaximumTemperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'reference temperature type',
{'name': u'Reference Temperature Type',
'pyname': u'reference_temperature_type',
'default': u'OutdoorAirWetBulb',
'required-field': False,
'autosizable': False,
'accepted-values': [u'OutdoorAirWetBulb',
u'OutdoorAirDryBulb'],
'autocalculatable': False,
'type': 'alpha'}),
(u'offset temperature difference',
{'name': u'Offset Temperature Difference',
'pyname': u'offset_temperature_difference',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'deltaC'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:FollowOutdoorAirTemperature',
'pyname': u'SetpointManagerFollowOutdoorAirTemperature',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def reference_temperature_type(self):
"""field `Reference Temperature Type`
| Default value: OutdoorAirWetBulb
Args:
value (str): value for IDD Field `Reference Temperature Type`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `reference_temperature_type` or None if not set
"""
return self["Reference Temperature Type"]
@reference_temperature_type.setter
def reference_temperature_type(self, value="OutdoorAirWetBulb"):
"""Corresponds to IDD field `Reference Temperature Type`"""
self["Reference Temperature Type"] = value
@property
def offset_temperature_difference(self):
"""field `Offset Temperature Difference`
| Units: deltaC
Args:
value (float): value for IDD Field `Offset Temperature Difference`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `offset_temperature_difference` or None if not set
"""
return self["Offset Temperature Difference"]
@offset_temperature_difference.setter
def offset_temperature_difference(self, value=None):
"""Corresponds to IDD field `Offset Temperature Difference`"""
self["Offset Temperature Difference"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=None):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=None):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which control variable will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerFollowSystemNodeTemperature(DataObject):
""" Corresponds to IDD object `SetpointManager:FollowSystemNodeTemperature`
This setpoint manager is used to place a temperature setpoint on a
system node that is derived from the current temperatures at a separate
system node. The current value of the temperature at a reference node
is obtained and used to generate setpoint on a second system node.
If the reference node is also designated to be an outdoor air (intake) node,
then this setpoint manager can be used to follow outdoor air conditions
that are adjusted for altitude.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature',
u'MinimumTemperature',
u'MaximumTemperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'reference node name',
{'name': u'Reference Node Name',
'pyname': u'reference_node_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'reference temperature type',
{'name': u'Reference Temperature Type',
'pyname': u'reference_temperature_type',
'default': u'NodeDryBulb',
'required-field': False,
'autosizable': False,
'accepted-values': [u'NodeWetBulb',
u'NodeDryBulb'],
'autocalculatable': False,
'type': 'alpha'}),
(u'offset temperature difference',
{'name': u'Offset Temperature Difference',
'pyname': u'offset_temperature_difference',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'deltaC'}),
(u'maximum limit setpoint temperature',
{'name': u'Maximum Limit Setpoint Temperature',
'pyname': u'maximum_limit_setpoint_temperature',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'minimum limit setpoint temperature',
{'name': u'Minimum Limit Setpoint Temperature',
'pyname': u'minimum_limit_setpoint_temperature',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:FollowSystemNodeTemperature',
'pyname': u'SetpointManagerFollowSystemNodeTemperature',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def reference_node_name(self):
"""field `Reference Node Name`
Args:
value (str): value for IDD Field `Reference Node Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `reference_node_name` or None if not set
"""
return self["Reference Node Name"]
@reference_node_name.setter
def reference_node_name(self, value=None):
"""Corresponds to IDD field `Reference Node Name`"""
self["Reference Node Name"] = value
@property
def reference_temperature_type(self):
"""field `Reference Temperature Type`
| Default value: NodeDryBulb
Args:
value (str): value for IDD Field `Reference Temperature Type`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `reference_temperature_type` or None if not set
"""
return self["Reference Temperature Type"]
@reference_temperature_type.setter
def reference_temperature_type(self, value="NodeDryBulb"):
"""Corresponds to IDD field `Reference Temperature Type`"""
self["Reference Temperature Type"] = value
@property
def offset_temperature_difference(self):
"""field `Offset Temperature Difference`
| Units: deltaC
Args:
value (float): value for IDD Field `Offset Temperature Difference`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `offset_temperature_difference` or None if not set
"""
return self["Offset Temperature Difference"]
@offset_temperature_difference.setter
def offset_temperature_difference(self, value=None):
"""Corresponds to IDD field `Offset Temperature Difference`"""
self["Offset Temperature Difference"] = value
@property
def maximum_limit_setpoint_temperature(self):
"""field `Maximum Limit Setpoint Temperature`
| Units: C
Args:
value (float): value for IDD Field `Maximum Limit Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_limit_setpoint_temperature` or None if not set
"""
return self["Maximum Limit Setpoint Temperature"]
@maximum_limit_setpoint_temperature.setter
def maximum_limit_setpoint_temperature(self, value=None):
"""Corresponds to IDD field `Maximum Limit Setpoint Temperature`"""
self["Maximum Limit Setpoint Temperature"] = value
@property
def minimum_limit_setpoint_temperature(self):
"""field `Minimum Limit Setpoint Temperature`
| Units: C
Args:
value (float): value for IDD Field `Minimum Limit Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_limit_setpoint_temperature` or None if not set
"""
return self["Minimum Limit Setpoint Temperature"]
@minimum_limit_setpoint_temperature.setter
def minimum_limit_setpoint_temperature(self, value=None):
"""Corresponds to IDD field `Minimum Limit Setpoint Temperature`"""
self["Minimum Limit Setpoint Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which control variable will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerFollowGroundTemperature(DataObject):
""" Corresponds to IDD object `SetpointManager:FollowGroundTemperature`
This setpoint manager is used to place a temperature setpoint on a
system node that is derived from a current ground temperature.
The ground temperatures are specified in different
Site:GroundTemperature:* objects and used during the simulation.
This setpoint manager is primarily intended for condenser or plant loops
using some type of ground heat exchanger.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Temperature',
u'MinimumTemperature',
u'MaximumTemperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'reference ground temperature object type',
{'name': u'Reference Ground Temperature Object Type',
'pyname': u'reference_ground_temperature_object_type',
'required-field': False,
'autosizable': False,
'accepted-values': [u'Site:GroundTemperature:BuildingSurface',
u'Site:GroundTemperature:Shallow',
u'Site:GroundTemperature:Deep',
u'Site:GroundTemperature:FCfactorMethod'],
'autocalculatable': False,
'type': 'alpha'}),
(u'offset temperature difference',
{'name': u'Offset Temperature Difference',
'pyname': u'offset_temperature_difference',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'deltaC'}),
(u'maximum setpoint temperature',
{'name': u'Maximum Setpoint Temperature',
'pyname': u'maximum_setpoint_temperature',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'minimum setpoint temperature',
{'name': u'Minimum Setpoint Temperature',
'pyname': u'minimum_setpoint_temperature',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:FollowGroundTemperature',
'pyname': u'SetpointManagerFollowGroundTemperature',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def reference_ground_temperature_object_type(self):
"""field `Reference Ground Temperature Object Type`
Args:
value (str): value for IDD Field `Reference Ground Temperature Object Type`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `reference_ground_temperature_object_type` or None if not set
"""
return self["Reference Ground Temperature Object Type"]
@reference_ground_temperature_object_type.setter
def reference_ground_temperature_object_type(self, value=None):
"""Corresponds to IDD field `Reference Ground Temperature Object
Type`"""
self["Reference Ground Temperature Object Type"] = value
@property
def offset_temperature_difference(self):
"""field `Offset Temperature Difference`
| Units: deltaC
Args:
value (float): value for IDD Field `Offset Temperature Difference`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `offset_temperature_difference` or None if not set
"""
return self["Offset Temperature Difference"]
@offset_temperature_difference.setter
def offset_temperature_difference(self, value=None):
"""Corresponds to IDD field `Offset Temperature Difference`"""
self["Offset Temperature Difference"] = value
@property
def maximum_setpoint_temperature(self):
"""field `Maximum Setpoint Temperature`
| Units: C
Args:
value (float): value for IDD Field `Maximum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_setpoint_temperature` or None if not set
"""
return self["Maximum Setpoint Temperature"]
@maximum_setpoint_temperature.setter
def maximum_setpoint_temperature(self, value=None):
"""Corresponds to IDD field `Maximum Setpoint Temperature`"""
self["Maximum Setpoint Temperature"] = value
@property
def minimum_setpoint_temperature(self):
"""field `Minimum Setpoint Temperature`
| Units: C
Args:
value (float): value for IDD Field `Minimum Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_setpoint_temperature` or None if not set
"""
return self["Minimum Setpoint Temperature"]
@minimum_setpoint_temperature.setter
def minimum_setpoint_temperature(self, value=None):
"""Corresponds to IDD field `Minimum Setpoint Temperature`"""
self["Minimum Setpoint Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which control variable will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerCondenserEnteringReset(DataObject):
""" Corresponds to IDD object `SetpointManager:CondenserEnteringReset`
This setpoint manager uses one curve to determine the optimum condenser entering water temperature
for a given timestep and two other curves to place boundary conditions on the setpoint value.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': True,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'default condenser entering water temperature schedule name',
{'name': u'Default Condenser Entering Water Temperature Schedule Name',
'pyname': u'default_condenser_entering_water_temperature_schedule_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum design wetbulb temperature curve name',
{'name': u'Minimum Design Wetbulb Temperature Curve Name',
'pyname': u'minimum_design_wetbulb_temperature_curve_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum outside air wetbulb temperature curve name',
{'name': u'Minimum Outside Air Wetbulb Temperature Curve Name',
'pyname': u'minimum_outside_air_wetbulb_temperature_curve_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'optimized cond entering water temperature curve name',
{'name': u'Optimized Cond Entering Water Temperature Curve Name',
'pyname': u'optimized_cond_entering_water_temperature_curve_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'minimum lift',
{'name': u'Minimum Lift',
'pyname': u'minimum_lift',
'default': 11.1,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'deltaC'}),
(u'maximum condenser entering water temperature',
{'name': u'Maximum Condenser Entering Water Temperature',
'pyname': u'maximum_condenser_entering_water_temperature',
'default': 32.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'cooling tower design inlet air wet-bulb temperature',
{'name': u'Cooling Tower Design Inlet Air Wet-Bulb Temperature',
'pyname': u'cooling_tower_design_inlet_air_wetbulb_temperature',
'default': 25.56,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 10,
'name': u'SetpointManager:CondenserEnteringReset',
'pyname': u'SetpointManagerCondenserEnteringReset',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def default_condenser_entering_water_temperature_schedule_name(self):
"""field `Default Condenser Entering Water Temperature Schedule Name`
| This scheduled setpoint value is only used in a given timestep if the
| "Optimized" Condenser Entering Temperature does not fall within the prescribed
| boundary conditions.
Args:
value (str): value for IDD Field `Default Condenser Entering Water Temperature Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `default_condenser_entering_water_temperature_schedule_name` or None if not set
"""
return self[
"Default Condenser Entering Water Temperature Schedule Name"]
@default_condenser_entering_water_temperature_schedule_name.setter
def default_condenser_entering_water_temperature_schedule_name(
self,
value=None):
"""Corresponds to IDD field `Default Condenser Entering Water
Temperature Schedule Name`"""
self[
"Default Condenser Entering Water Temperature Schedule Name"] = value
@property
def minimum_design_wetbulb_temperature_curve_name(self):
"""field `Minimum Design Wetbulb Temperature Curve Name`
Args:
value (str): value for IDD Field `Minimum Design Wetbulb Temperature Curve Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `minimum_design_wetbulb_temperature_curve_name` or None if not set
"""
return self["Minimum Design Wetbulb Temperature Curve Name"]
@minimum_design_wetbulb_temperature_curve_name.setter
def minimum_design_wetbulb_temperature_curve_name(self, value=None):
"""Corresponds to IDD field `Minimum Design Wetbulb Temperature Curve
Name`"""
self["Minimum Design Wetbulb Temperature Curve Name"] = value
@property
def minimum_outside_air_wetbulb_temperature_curve_name(self):
"""field `Minimum Outside Air Wetbulb Temperature Curve Name`
Args:
value (str): value for IDD Field `Minimum Outside Air Wetbulb Temperature Curve Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `minimum_outside_air_wetbulb_temperature_curve_name` or None if not set
"""
return self["Minimum Outside Air Wetbulb Temperature Curve Name"]
@minimum_outside_air_wetbulb_temperature_curve_name.setter
def minimum_outside_air_wetbulb_temperature_curve_name(self, value=None):
"""Corresponds to IDD field `Minimum Outside Air Wetbulb Temperature
Curve Name`"""
self["Minimum Outside Air Wetbulb Temperature Curve Name"] = value
@property
def optimized_cond_entering_water_temperature_curve_name(self):
"""field `Optimized Cond Entering Water Temperature Curve Name`
Args:
value (str): value for IDD Field `Optimized Cond Entering Water Temperature Curve Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `optimized_cond_entering_water_temperature_curve_name` or None if not set
"""
return self["Optimized Cond Entering Water Temperature Curve Name"]
@optimized_cond_entering_water_temperature_curve_name.setter
def optimized_cond_entering_water_temperature_curve_name(self, value=None):
"""Corresponds to IDD field `Optimized Cond Entering Water Temperature
Curve Name`"""
self["Optimized Cond Entering Water Temperature Curve Name"] = value
@property
def minimum_lift(self):
"""field `Minimum Lift`
| Units: deltaC
| Default value: 11.1
Args:
value (float): value for IDD Field `Minimum Lift`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_lift` or None if not set
"""
return self["Minimum Lift"]
@minimum_lift.setter
def minimum_lift(self, value=11.1):
"""Corresponds to IDD field `Minimum Lift`"""
self["Minimum Lift"] = value
@property
def maximum_condenser_entering_water_temperature(self):
"""field `Maximum Condenser Entering Water Temperature`
| Units: C
| Default value: 32.0
Args:
value (float): value for IDD Field `Maximum Condenser Entering Water Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_condenser_entering_water_temperature` or None if not set
"""
return self["Maximum Condenser Entering Water Temperature"]
@maximum_condenser_entering_water_temperature.setter
def maximum_condenser_entering_water_temperature(self, value=32.0):
"""Corresponds to IDD field `Maximum Condenser Entering Water
Temperature`"""
self["Maximum Condenser Entering Water Temperature"] = value
@property
def cooling_tower_design_inlet_air_wetbulb_temperature(self):
"""field `Cooling Tower Design Inlet Air Wet-Bulb Temperature`
| Units: C
| Default value: 25.56
Args:
value (float): value for IDD Field `Cooling Tower Design Inlet Air Wet-Bulb Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `cooling_tower_design_inlet_air_wetbulb_temperature` or None if not set
"""
return self["Cooling Tower Design Inlet Air Wet-Bulb Temperature"]
@cooling_tower_design_inlet_air_wetbulb_temperature.setter
def cooling_tower_design_inlet_air_wetbulb_temperature(self, value=25.56):
""" Corresponds to IDD field `Cooling Tower Design Inlet Air Wet-Bulb Temperature`
"""
self["Cooling Tower Design Inlet Air Wet-Bulb Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which control variable will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerCondenserEnteringResetIdeal(DataObject):
""" Corresponds to IDD object `SetpointManager:CondenserEnteringReset:Ideal`
This setpoint manager determine the ideal optimum condenser entering water temperature
setpoint for a given timestep.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'alpha'}),
(u'control variable',
{'name': u'Control Variable',
'pyname': u'control_variable',
'default': u'Temperature',
'required-field': True,
'autosizable': False,
'accepted-values': [u'Temperature'],
'autocalculatable': False,
'type': 'alpha'}),
(u'minimum lift',
{'name': u'Minimum Lift',
'pyname': u'minimum_lift',
'default': 11.1,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'deltaC'}),
(u'maximum condenser entering water temperature',
{'name': u'Maximum Condenser Entering Water Temperature',
'pyname': u'maximum_condenser_entering_water_temperature',
'default': 32.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 5,
'name': u'SetpointManager:CondenserEnteringReset:Ideal',
'pyname': u'SetpointManagerCondenserEnteringResetIdeal',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def control_variable(self):
"""field `Control Variable`
| Default value: Temperature
Args:
value (str): value for IDD Field `Control Variable`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_variable` or None if not set
"""
return self["Control Variable"]
@control_variable.setter
def control_variable(self, value="Temperature"):
"""Corresponds to IDD field `Control Variable`"""
self["Control Variable"] = value
@property
def minimum_lift(self):
"""field `Minimum Lift`
| Units: deltaC
| Default value: 11.1
Args:
value (float): value for IDD Field `Minimum Lift`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_lift` or None if not set
"""
return self["Minimum Lift"]
@minimum_lift.setter
def minimum_lift(self, value=11.1):
"""Corresponds to IDD field `Minimum Lift`"""
self["Minimum Lift"] = value
@property
def maximum_condenser_entering_water_temperature(self):
"""field `Maximum Condenser Entering Water Temperature`
| Units: C
| Default value: 32.0
Args:
value (float): value for IDD Field `Maximum Condenser Entering Water Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_condenser_entering_water_temperature` or None if not set
"""
return self["Maximum Condenser Entering Water Temperature"]
@maximum_condenser_entering_water_temperature.setter
def maximum_condenser_entering_water_temperature(self, value=32.0):
"""Corresponds to IDD field `Maximum Condenser Entering Water
Temperature`"""
self["Maximum Condenser Entering Water Temperature"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which control variable will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerSingleZoneOneStageCooling(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:OneStageCooling`
This object can be used with CoilSystem:Cooling:DX to model on/off cycling control
of single stage air systems. Setpoints are modulated to run coil full on or full off
depending on zone conditions. Intended for use with ZoneControl:Thermostat:StagedDualSetpoint
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'cooling stage on supply air setpoint temperature',
{'name': u'Cooling Stage On Supply Air Setpoint Temperature',
'pyname': u'cooling_stage_on_supply_air_setpoint_temperature',
'default': -99.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'cooling stage off supply air setpoint temperature',
{'name': u'Cooling Stage Off Supply Air Setpoint Temperature',
'pyname': u'cooling_stage_off_supply_air_setpoint_temperature',
'default': 99.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'control zone name',
{'name': u'Control Zone Name',
'pyname': u'control_zone_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:SingleZone:OneStageCooling',
'pyname': u'SetpointManagerSingleZoneOneStageCooling',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def cooling_stage_on_supply_air_setpoint_temperature(self):
"""field `Cooling Stage On Supply Air Setpoint Temperature`
| This is the setpoint value applied when cooling device is to cycle ON
| Units: C
| Default value: -99.0
Args:
value (float): value for IDD Field `Cooling Stage On Supply Air Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `cooling_stage_on_supply_air_setpoint_temperature` or None if not set
"""
return self["Cooling Stage On Supply Air Setpoint Temperature"]
@cooling_stage_on_supply_air_setpoint_temperature.setter
def cooling_stage_on_supply_air_setpoint_temperature(self, value=-99.0):
"""Corresponds to IDD field `Cooling Stage On Supply Air Setpoint
Temperature`"""
self["Cooling Stage On Supply Air Setpoint Temperature"] = value
@property
def cooling_stage_off_supply_air_setpoint_temperature(self):
"""field `Cooling Stage Off Supply Air Setpoint Temperature`
| This is the setpoint value applied when cooling device is to cycle OFF
| Units: C
| Default value: 99.0
Args:
value (float): value for IDD Field `Cooling Stage Off Supply Air Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `cooling_stage_off_supply_air_setpoint_temperature` or None if not set
"""
return self["Cooling Stage Off Supply Air Setpoint Temperature"]
@cooling_stage_off_supply_air_setpoint_temperature.setter
def cooling_stage_off_supply_air_setpoint_temperature(self, value=99.0):
"""Corresponds to IDD field `Cooling Stage Off Supply Air Setpoint
Temperature`"""
self["Cooling Stage Off Supply Air Setpoint Temperature"] = value
@property
def control_zone_name(self):
"""field `Control Zone Name`
Args:
value (str): value for IDD Field `Control Zone Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_name` or None if not set
"""
return self["Control Zone Name"]
@control_zone_name.setter
def control_zone_name(self, value=None):
"""Corresponds to IDD field `Control Zone Name`"""
self["Control Zone Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerSingleZoneOneStageHeating(DataObject):
""" Corresponds to IDD object `SetpointManager:SingleZone:OneStageHeating`
This object can be used with CoilSystem:Heating:DX, Coil:Heating:Gas,
Coil:Heating:Electric to model on/off cycling control of single stage air systems.
Setpoints are modulated to run coil full on or full off depending on zone conditions.
Intended for use with ZoneControl:Thermostat:StagedDualSetpoint.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'heating stage on supply air setpoint temperature',
{'name': u'Heating Stage On Supply Air Setpoint Temperature',
'pyname': u'heating_stage_on_supply_air_setpoint_temperature',
'default': 99.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'heating stage off supply air setpoint temperature',
{'name': u'Heating Stage Off Supply Air Setpoint Temperature',
'pyname': u'heating_stage_off_supply_air_setpoint_temperature',
'default': -99.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'real',
'unit': u'C'}),
(u'control zone name',
{'name': u'Control Zone Name',
'pyname': u'control_zone_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'}),
(u'setpoint node or nodelist name',
{'name': u'Setpoint Node or NodeList Name',
'pyname': u'setpoint_node_or_nodelist_name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 0,
'name': u'SetpointManager:SingleZone:OneStageHeating',
'pyname': u'SetpointManagerSingleZoneOneStageHeating',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def heating_stage_on_supply_air_setpoint_temperature(self):
"""field `Heating Stage On Supply Air Setpoint Temperature`
| This is the setpoint value applied when heating device is to cycle ON
| Units: C
| Default value: 99.0
Args:
value (float): value for IDD Field `Heating Stage On Supply Air Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `heating_stage_on_supply_air_setpoint_temperature` or None if not set
"""
return self["Heating Stage On Supply Air Setpoint Temperature"]
@heating_stage_on_supply_air_setpoint_temperature.setter
def heating_stage_on_supply_air_setpoint_temperature(self, value=99.0):
"""Corresponds to IDD field `Heating Stage On Supply Air Setpoint
Temperature`"""
self["Heating Stage On Supply Air Setpoint Temperature"] = value
@property
def heating_stage_off_supply_air_setpoint_temperature(self):
"""field `Heating Stage Off Supply Air Setpoint Temperature`
| This is the setpoint value applied when heating device is to cycle OFF
| Units: C
| Default value: -99.0
Args:
value (float): value for IDD Field `Heating Stage Off Supply Air Setpoint Temperature`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `heating_stage_off_supply_air_setpoint_temperature` or None if not set
"""
return self["Heating Stage Off Supply Air Setpoint Temperature"]
@heating_stage_off_supply_air_setpoint_temperature.setter
def heating_stage_off_supply_air_setpoint_temperature(self, value=-99.0):
"""Corresponds to IDD field `Heating Stage Off Supply Air Setpoint
Temperature`"""
self["Heating Stage Off Supply Air Setpoint Temperature"] = value
@property
def control_zone_name(self):
"""field `Control Zone Name`
Args:
value (str): value for IDD Field `Control Zone Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `control_zone_name` or None if not set
"""
return self["Control Zone Name"]
@control_zone_name.setter
def control_zone_name(self, value=None):
"""Corresponds to IDD field `Control Zone Name`"""
self["Control Zone Name"] = value
@property
def setpoint_node_or_nodelist_name(self):
"""field `Setpoint Node or NodeList Name`
| Node(s) at which the temperature will be set
Args:
value (str): value for IDD Field `Setpoint Node or NodeList Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `setpoint_node_or_nodelist_name` or None if not set
"""
return self["Setpoint Node or NodeList Name"]
@setpoint_node_or_nodelist_name.setter
def setpoint_node_or_nodelist_name(self, value=None):
"""Corresponds to IDD field `Setpoint Node or NodeList Name`"""
self["Setpoint Node or NodeList Name"] = value
class SetpointManagerReturnTemperatureChilledWater(DataObject):
""" Corresponds to IDD object `SetpointManager:ReturnTemperature:ChilledWater`
This setpoint manager is used to place a temperature setpoint on a plant supply
outlet node based on a target return water setpoint. The setpoint manager attempts
to achieve the desired return water temperature by adjusting the supply temperature
setpoint based on the plant conditions at each system time step.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'plant loop supply outlet node',
{'name': u'Plant Loop Supply Outlet Node',
'pyname': u'plant_loop_supply_outlet_node',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'plant loop supply inlet node',
{'name': u'Plant Loop Supply Inlet Node',
'pyname': u'plant_loop_supply_inlet_node',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'minimum supply temperature setpoint',
{'name': u'Minimum Supply Temperature Setpoint',
'pyname': u'minimum_supply_temperature_setpoint',
'default': 5.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum supply temperature setpoint',
{'name': u'Maximum Supply Temperature Setpoint',
'pyname': u'maximum_supply_temperature_setpoint',
'default': 10.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'return temperature setpoint input type',
{'name': u'Return Temperature Setpoint Input Type',
'pyname': u'return_temperature_setpoint_input_type',
'required-field': True,
'autosizable': False,
'accepted-values': [u'Constant',
u'Scheduled',
u'ReturnTemperatureSetpoint'],
'autocalculatable': False,
'type': 'alpha'}),
(u'return temperature setpoint constant value',
{'name': u'Return Temperature Setpoint Constant Value',
'pyname': u'return_temperature_setpoint_constant_value',
'default': 13.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'return temperature setpoint schedule name',
{'name': u'Return Temperature Setpoint Schedule Name',
'pyname': u'return_temperature_setpoint_schedule_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 7,
'name': u'SetpointManager:ReturnTemperature:ChilledWater',
'pyname': u'SetpointManagerReturnTemperatureChilledWater',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def plant_loop_supply_outlet_node(self):
"""field `Plant Loop Supply Outlet Node`
| This is the name of the supply outlet node for the plant being controlled by this
| setpoint manager. Typically this is where the setpoint will be actuated for
| supply equipment to control to, but not necessarily. This setpoint manager will
| mine that information from the internal plant data structures.
Args:
value (str): value for IDD Field `Plant Loop Supply Outlet Node`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `plant_loop_supply_outlet_node` or None if not set
"""
return self["Plant Loop Supply Outlet Node"]
@plant_loop_supply_outlet_node.setter
def plant_loop_supply_outlet_node(self, value=None):
"""Corresponds to IDD field `Plant Loop Supply Outlet Node`"""
self["Plant Loop Supply Outlet Node"] = value
@property
def plant_loop_supply_inlet_node(self):
"""field `Plant Loop Supply Inlet Node`
| This is the name of the supply inlet node for the plant being controlled with this
| setpoint manager. The temperature on this node is controlled by actuating the
| supply setpoint.
Args:
value (str): value for IDD Field `Plant Loop Supply Inlet Node`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `plant_loop_supply_inlet_node` or None if not set
"""
return self["Plant Loop Supply Inlet Node"]
@plant_loop_supply_inlet_node.setter
def plant_loop_supply_inlet_node(self, value=None):
"""Corresponds to IDD field `Plant Loop Supply Inlet Node`"""
self["Plant Loop Supply Inlet Node"] = value
@property
def minimum_supply_temperature_setpoint(self):
"""field `Minimum Supply Temperature Setpoint`
| This is the minimum chilled water supply temperature setpoint. This is also used as the default
| setpoint during no-load or negative-load conditions and during initialization.
| Units: C
| Default value: 5.0
Args:
value (float): value for IDD Field `Minimum Supply Temperature Setpoint`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_supply_temperature_setpoint` or None if not set
"""
return self["Minimum Supply Temperature Setpoint"]
@minimum_supply_temperature_setpoint.setter
def minimum_supply_temperature_setpoint(self, value=5.0):
"""Corresponds to IDD field `Minimum Supply Temperature Setpoint`"""
self["Minimum Supply Temperature Setpoint"] = value
@property
def maximum_supply_temperature_setpoint(self):
"""field `Maximum Supply Temperature Setpoint`
| This is the maximum reset temperature for the chilled water supply.
| Units: C
| Default value: 10.0
Args:
value (float): value for IDD Field `Maximum Supply Temperature Setpoint`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_supply_temperature_setpoint` or None if not set
"""
return self["Maximum Supply Temperature Setpoint"]
@maximum_supply_temperature_setpoint.setter
def maximum_supply_temperature_setpoint(self, value=10.0):
"""Corresponds to IDD field `Maximum Supply Temperature Setpoint`"""
self["Maximum Supply Temperature Setpoint"] = value
@property
def return_temperature_setpoint_input_type(self):
"""field `Return Temperature Setpoint Input Type`
| This defines whether the chilled water return temperature target is constant,
| scheduled, or specified on the supply inlet node by a separate setpoint manager.
Args:
value (str): value for IDD Field `Return Temperature Setpoint Input Type`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `return_temperature_setpoint_input_type` or None if not set
"""
return self["Return Temperature Setpoint Input Type"]
@return_temperature_setpoint_input_type.setter
def return_temperature_setpoint_input_type(self, value=None):
"""Corresponds to IDD field `Return Temperature Setpoint Input Type`"""
self["Return Temperature Setpoint Input Type"] = value
@property
def return_temperature_setpoint_constant_value(self):
"""field `Return Temperature Setpoint Constant Value`
| This is the desired return temperature target, which is met by adjusting the
| supply temperature setpoint. This constant value is only used if
| the Design Chilled Water Return Temperature Input Type is Constant
| Units: C
| Default value: 13.0
Args:
value (float): value for IDD Field `Return Temperature Setpoint Constant Value`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `return_temperature_setpoint_constant_value` or None if not set
"""
return self["Return Temperature Setpoint Constant Value"]
@return_temperature_setpoint_constant_value.setter
def return_temperature_setpoint_constant_value(self, value=13.0):
"""Corresponds to IDD field `Return Temperature Setpoint Constant
Value`"""
self["Return Temperature Setpoint Constant Value"] = value
@property
def return_temperature_setpoint_schedule_name(self):
"""field `Return Temperature Setpoint Schedule Name`
| This is the desired return temperature target, which is met by adjusting the
| supply temperature setpoint. This is a schedule name to allow the return temperature
| target value to be scheduled. This field is only used if
| the Design Chilled Water Return Temperature Input Type is Scheduled
Args:
value (str): value for IDD Field `Return Temperature Setpoint Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `return_temperature_setpoint_schedule_name` or None if not set
"""
return self["Return Temperature Setpoint Schedule Name"]
@return_temperature_setpoint_schedule_name.setter
def return_temperature_setpoint_schedule_name(self, value=None):
"""Corresponds to IDD field `Return Temperature Setpoint Schedule
Name`"""
self["Return Temperature Setpoint Schedule Name"] = value
class SetpointManagerReturnTemperatureHotWater(DataObject):
""" Corresponds to IDD object `SetpointManager:ReturnTemperature:HotWater`
This setpoint manager is used to place a temperature setpoint on a plant supply
outlet node based on a target return water setpoint. The setpoint manager attempts
to achieve the desired return water temperature by adjusting the supply temperature
setpoint based on the plant conditions at each system time step.
"""
_schema = {'extensible-fields': OrderedDict(),
'fields': OrderedDict([(u'name',
{'name': u'Name',
'pyname': u'name',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': 'alpha'}),
(u'plant loop supply outlet node',
{'name': u'Plant Loop Supply Outlet Node',
'pyname': u'plant_loop_supply_outlet_node',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'plant loop supply inlet node',
{'name': u'Plant Loop Supply Inlet Node',
'pyname': u'plant_loop_supply_inlet_node',
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'node'}),
(u'minimum supply temperature setpoint',
{'name': u'Minimum Supply Temperature Setpoint',
'pyname': u'minimum_supply_temperature_setpoint',
'default': 77.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'maximum supply temperature setpoint',
{'name': u'Maximum Supply Temperature Setpoint',
'pyname': u'maximum_supply_temperature_setpoint',
'default': 82.0,
'required-field': True,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'return temperature setpoint input type',
{'name': u'Return Temperature Setpoint Input Type',
'pyname': u'return_temperature_setpoint_input_type',
'required-field': True,
'autosizable': False,
'accepted-values': [u'Constant',
u'Scheduled',
u'ReturnTemperatureSetpoint'],
'autocalculatable': False,
'type': 'alpha'}),
(u'return temperature setpoint constant value',
{'name': u'Return Temperature Setpoint Constant Value',
'pyname': u'return_temperature_setpoint_constant_value',
'default': 71.0,
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'real',
'unit': u'C'}),
(u'return temperature setpoint schedule name',
{'name': u'Return Temperature Setpoint Schedule Name',
'pyname': u'return_temperature_setpoint_schedule_name',
'required-field': False,
'autosizable': False,
'autocalculatable': False,
'type': u'object-list'})]),
'format': None,
'group': u'Setpoint Managers',
'min-fields': 7,
'name': u'SetpointManager:ReturnTemperature:HotWater',
'pyname': u'SetpointManagerReturnTemperatureHotWater',
'required-object': False,
'unique-object': False}
@property
def name(self):
"""field `Name`
Args:
value (str): value for IDD Field `Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `name` or None if not set
"""
return self["Name"]
@name.setter
def name(self, value=None):
"""Corresponds to IDD field `Name`"""
self["Name"] = value
@property
def plant_loop_supply_outlet_node(self):
"""field `Plant Loop Supply Outlet Node`
| This is the name of the supply outlet node for the plant being controlled by this
| setpoint manager. Typically this is where the setpoint will be actuated for
| supply equipment to control to, but not necessarily. This setpoint manager will
| mine that information from the internal plant data structures.
Args:
value (str): value for IDD Field `Plant Loop Supply Outlet Node`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `plant_loop_supply_outlet_node` or None if not set
"""
return self["Plant Loop Supply Outlet Node"]
@plant_loop_supply_outlet_node.setter
def plant_loop_supply_outlet_node(self, value=None):
"""Corresponds to IDD field `Plant Loop Supply Outlet Node`"""
self["Plant Loop Supply Outlet Node"] = value
@property
def plant_loop_supply_inlet_node(self):
"""field `Plant Loop Supply Inlet Node`
| This is the name of the supply inlet node for the plant being controlled with this
| setpoint manager. The temperature on this node is controlled by actuating the
| supply setpoint.
Args:
value (str): value for IDD Field `Plant Loop Supply Inlet Node`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `plant_loop_supply_inlet_node` or None if not set
"""
return self["Plant Loop Supply Inlet Node"]
@plant_loop_supply_inlet_node.setter
def plant_loop_supply_inlet_node(self, value=None):
"""Corresponds to IDD field `Plant Loop Supply Inlet Node`"""
self["Plant Loop Supply Inlet Node"] = value
@property
def minimum_supply_temperature_setpoint(self):
"""field `Minimum Supply Temperature Setpoint`
| This is the minimum reset temperature for the hot water supply.
| Units: C
| Default value: 77.0
Args:
value (float): value for IDD Field `Minimum Supply Temperature Setpoint`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `minimum_supply_temperature_setpoint` or None if not set
"""
return self["Minimum Supply Temperature Setpoint"]
@minimum_supply_temperature_setpoint.setter
def minimum_supply_temperature_setpoint(self, value=77.0):
"""Corresponds to IDD field `Minimum Supply Temperature Setpoint`"""
self["Minimum Supply Temperature Setpoint"] = value
@property
def maximum_supply_temperature_setpoint(self):
"""field `Maximum Supply Temperature Setpoint`
| This is the maximum hot water supply temperature setpoint. This is also used as the default
| setpoint during no-load or negative-load conditions and during initialization.
| Units: C
| Default value: 82.0
Args:
value (float): value for IDD Field `Maximum Supply Temperature Setpoint`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `maximum_supply_temperature_setpoint` or None if not set
"""
return self["Maximum Supply Temperature Setpoint"]
@maximum_supply_temperature_setpoint.setter
def maximum_supply_temperature_setpoint(self, value=82.0):
"""Corresponds to IDD field `Maximum Supply Temperature Setpoint`"""
self["Maximum Supply Temperature Setpoint"] = value
@property
def return_temperature_setpoint_input_type(self):
"""field `Return Temperature Setpoint Input Type`
| This defines whether the hot water return temperature target is constant,
| scheduled, or specified on the supply inlet node by a separate setpoint manager.
Args:
value (str): value for IDD Field `Return Temperature Setpoint Input Type`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `return_temperature_setpoint_input_type` or None if not set
"""
return self["Return Temperature Setpoint Input Type"]
@return_temperature_setpoint_input_type.setter
def return_temperature_setpoint_input_type(self, value=None):
"""Corresponds to IDD field `Return Temperature Setpoint Input Type`"""
self["Return Temperature Setpoint Input Type"] = value
@property
def return_temperature_setpoint_constant_value(self):
"""field `Return Temperature Setpoint Constant Value`
| This is the desired return temperature target, which is met by adjusting the
| supply temperature setpoint. This constant value is only used if
| the Design Hot Water Return Temperature Input Type is Constant
| Units: C
| Default value: 71.0
Args:
value (float): value for IDD Field `Return Temperature Setpoint Constant Value`
Raises:
ValueError: if `value` is not a valid value
Returns:
float: the value of `return_temperature_setpoint_constant_value` or None if not set
"""
return self["Return Temperature Setpoint Constant Value"]
@return_temperature_setpoint_constant_value.setter
def return_temperature_setpoint_constant_value(self, value=71.0):
"""Corresponds to IDD field `Return Temperature Setpoint Constant
Value`"""
self["Return Temperature Setpoint Constant Value"] = value
@property
def return_temperature_setpoint_schedule_name(self):
"""field `Return Temperature Setpoint Schedule Name`
| This is the desired return temperature target, which is met by adjusting the
| supply temperature setpoint. This is a schedule name to allow the return temperature
| target value to be scheduled. This field is only used if
| the Design Hot Water Return Temperature Input Type is Scheduled
Args:
value (str): value for IDD Field `Return Temperature Setpoint Schedule Name`
Raises:
ValueError: if `value` is not a valid value
Returns:
str: the value of `return_temperature_setpoint_schedule_name` or None if not set
"""
return self["Return Temperature Setpoint Schedule Name"]
@return_temperature_setpoint_schedule_name.setter
def return_temperature_setpoint_schedule_name(self, value=None):
"""Corresponds to IDD field `Return Temperature Setpoint Schedule
Name`"""
self["Return Temperature Setpoint Schedule Name"] = value
| 39.289942 | 112 | 0.490644 | 23,393 | 256,249 | 5.272859 | 0.018382 | 0.024775 | 0.035412 | 0.055647 | 0.941815 | 0.928511 | 0.905333 | 0.885195 | 0.863378 | 0.849507 | 0 | 0.003803 | 0.428458 | 256,249 | 6,521 | 113 | 39.295967 | 0.83841 | 0.289258 | 0 | 0.867119 | 0 | 0 | 0.251343 | 0.035378 | 0 | 0 | 0 | 0 | 0 | 1 | 0.129492 | false | 0.001017 | 0.001017 | 0 | 0.214915 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
c74fdf3cdce6429abeb941d6a0668a8535791cb4 | 40 | py | Python | astroML/dimensionality/__init__.py | autocorr/astroML | 9bdeff87b9ae1993849bfc04d7f2865c05c8e52e | [
"BSD-2-Clause"
] | 3 | 2017-02-23T07:59:15.000Z | 2021-01-16T18:49:32.000Z | astroML/dimensionality/__init__.py | cfroning/astroML | 9bdeff87b9ae1993849bfc04d7f2865c05c8e52e | [
"BSD-2-Clause"
] | null | null | null | astroML/dimensionality/__init__.py | cfroning/astroML | 9bdeff87b9ae1993849bfc04d7f2865c05c8e52e | [
"BSD-2-Clause"
] | 1 | 2021-01-16T18:49:36.000Z | 2021-01-16T18:49:36.000Z | from iterative_pca import iterative_pca
| 20 | 39 | 0.9 | 6 | 40 | 5.666667 | 0.666667 | 0.705882 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.1 | 40 | 1 | 40 | 40 | 0.944444 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 1 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
1bf1c5f499e56b5dba7581fc45d2b4df6c25117a | 12,447 | py | Python | programs/program_chair_3.py | aluo-x/shape2prog | 1177e5205b99bb293e353688b564c94a14211c75 | [
"BSD-2-Clause"
] | 109 | 2019-01-10T03:16:21.000Z | 2022-02-10T07:39:22.000Z | programs/program_chair_3.py | aluo-x/shape2prog | 1177e5205b99bb293e353688b564c94a14211c75 | [
"BSD-2-Clause"
] | 6 | 2019-06-11T13:30:08.000Z | 2020-11-19T17:42:12.000Z | programs/program_chair_3.py | aluo-x/shape2prog | 1177e5205b99bb293e353688b564c94a14211c75 | [
"BSD-2-Clause"
] | 16 | 2019-01-16T08:08:18.000Z | 2021-11-11T02:52:40.000Z | from .utils import *
import math
import os
from .label_config import max_step, max_param
from misc import get_distance_to_center
###################################
# generate straight chair 4 legs
# seat-top can be: square, circle, rectangle
# horizontal bars connect legs
# back can be tilted
# max steps: 10
###################################
def generate_single(d):
data = np.zeros((32, 32, 32), dtype=np.uint8)
steps = []
p = np.random.rand()
if p < 0.8:
top_t = 1
else:
top_t = 2
leg_h = np.random.randint(8, 14) - top_t
total_height = leg_h + top_t
entire_height = np.random.choice([22, 23, 24, 25, 26], 1)[0]
back_height = entire_height - total_height
leg_start = -int(entire_height/2)
seattop_start = leg_start + leg_h
# leg_start = -total_height
# seattop_start = leg_start + leg_h
tilt_amount = np.random.choice([0,1,2,3,4], 1)[0]
seattop_offset = -int(np.rint(tilt_amount/2))
if tilt_amount!=0:
back_thickness = np.random.choice([1,2,3], 1)[0]
else:
back_thickness = np.random.choice([1,2], 1)[0]
# back_height = total_height
# sample the seattop
p = np.random.rand()
top_type = -1
if p < 0.5:
# rectangle seattop
top_r2 = np.random.randint(6, 12)
top_r1 = top_r2- np.random.choice([1, 2],1)[0]
# data, step = draw_rectangle_top(data, seattop_start, top_r1, top_r2, top_t)
data, step = draw_rectangle_top(data, seattop_start, seattop_offset, 0, top_t, top_r1, top_r2)
steps.append(step)
top_type = 0
elif p < 0.75:
# square seattop
q = np.random.rand()
if q < 0.75:
top_r = np.random.randint(5, 9)
elif q < 0.95:
top_r = np.random.randint(10, 11)
else:
top_r = 11
# data, step = draw_square_top(data, seattop_start, top_r, top_t)
data, step = draw_square_top(data, seattop_start, seattop_offset, 0, top_t, top_r)
steps.append(step)
top_type = 1
else:
# circle seattop
q = np.random.rand()
if q < 0.75:
top_r = np.random.randint(5, 9)
elif q < 0.95:
top_r = np.random.randint(10, 11)
else:
top_r = 11
# data, step = draw_circle_top(data, seattop_start, top_r, top_t, d)
data, step = draw_circle_top(data, seattop_start, seattop_offset, 0, top_t, top_r)
steps.append(step)
top_type = 2
if top_type == 0:
p = np.random.rand()
if p < 0.45:
leg_w = 1
leg_l = 1
elif p < 0.725:
leg_w = 1
leg_l = 2
else:
leg_w = 2
leg_l = 1
p = np.random.rand()
if p < 0.5:
shrink_w = 0
shrink_l = 0
else:
shrink_w = np.random.randint(0, min(1, top_r1-leg_w))
shrink_l = np.random.randint(0, min(2, top_r2-leg_l))
s1 = top_r1 - shrink_w - leg_w
s2 = top_r2 - shrink_l - leg_l
# data, step = draw_vertical_leg(data, leg_start, -s1, -s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, -s1 - leg_w + seattop_offset, -s2 - leg_l, leg_h+top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, +s1, -s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, +s1 + seattop_offset, -s2 - leg_l, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, +s1, +s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, +s1 + seattop_offset, +s2, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, -s1, +s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, -s1 - leg_w + seattop_offset, +s2, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# p = np.random.rand()
# if p<0.99:
# print("triggered")
# # data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, +s2, back_w, back_l, back_h)
# data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, +s2, back_h, back_w, back_l)
# steps.append(step)
# # data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, -s2, back_w, back_l, back_h)
# data, step = draw_vertical_leg(data, leg_start + leg_h + top_t, +s1, -s2 - back_l, back_h, back_w, back_l)
# steps.append(step)
# data, step = draw_vertboard(data, leg_start + leg_h + top_t, +s1+np.random.choice([-1, 0],1)[0], -s2, 1, 2*s2, back_h)
# data, step = draw_vertboard(data, leg_start + leg_h + top_t, +s1+np.random.choice([-1, 0],1)[0], -s2, back_h, 1, 2*s2)
data, step = draw_tilt_back(data, leg_start + leg_h + top_t, +s1 + np.random.choice([-1, 0], 1)[0] + seattop_offset, -s2, back_height, back_thickness, 2 * s2, tilt_amount)
steps.append(step)
if top_type == 1:
p = np.random.rand()
if p < 0.6:
leg_w = 1
leg_l = 1
elif p < 0.8:
leg_w = 1
leg_l = 2
else:
leg_w = 2
leg_l = 1
p = np.random.rand()
if p < 0.7:
shrink_w = 0
shrink_l = 0
else:
shrink_w = np.random.randint(0, 2)
shrink_l = shrink_w
s1 = top_r - shrink_w - leg_w
s2 = top_r - shrink_l - leg_l
# data, step = draw_vertical_leg(data, leg_start, -s1, -s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, -s1 - leg_w + seattop_offset, -s2 - leg_l, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, +s1, -s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, +s1 + seattop_offset, -s2 - leg_l, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, +s1, +s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, +s1 + seattop_offset, +s2, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, -s1, +s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, -s1 - leg_w + seattop_offset, +s2, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# p = np.random.rand()
# if p < 0.99:
# print("triggered")
# # data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, +s2, back_w, back_l, back_h)
# data, step = draw_vertical_leg(data, leg_start + leg_h + top_t, +s1, +s2, back_h, back_w, back_l)
# steps.append(step)
# # data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, -s2, back_w, back_l, back_h)
# data, step = draw_vertical_leg(data, leg_start + leg_h + top_t, +s1, -s2 - back_l, back_h, back_w, back_l)
# steps.append(step)
# data, step = draw_vertboard(data, leg_start + leg_h + top_t, +s1+np.random.choice([-1, 1],1)[0], -s2, 1, 2*s2, back_h)
# data, step = draw_vertboard(data, leg_start + leg_h + top_t, +s1+np.random.choice([-1, 1],1)[0], -s2, back_h, 1, 2*s2)
data, step = draw_tilt_back(data, leg_start + leg_h + top_t, +s1 + np.random.choice([-1, 0], 1)[0] + seattop_offset, -s2, back_height, back_thickness, 2 * s2, tilt_amount)
steps.append(step)
if top_type == 2:
p = np.random.rand()
if p < 0.6:
leg_w = 1
leg_l = 1
elif p < 0.8:
leg_w = 1
leg_l = 2
else:
leg_w = 2
leg_l = 1
p = np.random.rand()
if p < 1.1:
shrink_w = 0
shrink_l = 0
else:
shrink_w = np.random.randint(0, 2)
shrink_l = shrink_w
s1 = int(round(top_r / math.sqrt(2))) - shrink_w - leg_w
s2 = int(round(top_r / math.sqrt(2))) - shrink_l - leg_l
# data, step = draw_vertical_leg(data, leg_start, -s1, -s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, -s1 - leg_w + seattop_offset, -s2 - leg_l, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, +s1, -s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, +s1 + seattop_offset, -s2 - leg_l, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, +s1, +s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, +s1 + seattop_offset, +s2, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# data, step = draw_vertical_leg(data, leg_start, -s1, +s2, leg_w, leg_l, leg_h+top_t)
data, step = draw_vertical_leg(data, leg_start, -s1 - leg_w + seattop_offset, +s2, leg_h + top_t, leg_w, leg_l)
steps.append(step)
# p = np.random.rand()
# if p < 0.99:
# print("triggered")
# # data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, +s2, back_w, back_l, back_h)
# data, step = draw_vertical_leg(data, leg_start + leg_h + top_t, +s1, +s2, back_h, back_w, back_l)
# steps.append(step)
# # data, step = draw_vertical_leg(data, leg_start+leg_h+top_t, +s1, -s2, back_w, back_l, back_h)
# data, step = draw_vertical_leg(data, leg_start + leg_h + top_t, +s1, -s2 - back_l, back_h, back_w, back_l)
# steps.append(step)
# data, step = draw_vertboard(data, leg_start + leg_h + top_t, +s1+np.random.choice([-1, 1],1)[0], -s2, 1, 2*s2, back_h)
# data, step = draw_vertboard(data, leg_start + leg_h + top_t, +s1 + np.random.choice([-1, 1], 1)[0], -s2, back_h, 1, 2 * s2)
data, step = draw_tilt_back(data, leg_start + leg_h + top_t, +s1 + np.random.choice([-1, 0], 1)[0] + seattop_offset, -s2, back_height, back_thickness, 2 * s2, tilt_amount)
steps.append(step)
h_bar_t = np.random.randint(1, 3)
h_bar_start = leg_start + np.random.randint(2, min(5, leg_h-h_bar_t))
p = np.random.rand()
if p < 0.5:
data, step = draw_horizontal_bar(data, h_bar_start, -s1 - leg_w + seattop_offset, -s2 - leg_l, h_bar_t, 2 * (s1 + leg_w), leg_l)
steps.append(step)
data, step = draw_horizontal_bar(data, h_bar_start, -s1 - leg_w + seattop_offset, s2, h_bar_t, 2 * (s1 + leg_w), leg_l)
steps.append(step)
# third single bar
start = np.random.randint(-s1-leg_w, s1 + 1)
q = np.random.rand()
if q < 0.5:
width = leg_w
else:
width = np.random.randint(1, min(4, 2*s1))
data, step = draw_horizontal_bar(data, h_bar_start, start + seattop_offset, -s2 - leg_l, h_bar_t, width, 2 * (s2 + leg_l))
steps.append(step)
else:
data, step = draw_horizontal_bar(data, h_bar_start, -s1 - leg_w + seattop_offset, -s2 - leg_l, h_bar_t, 2 * (s1 + leg_w), leg_l)
steps.append(step)
data, step = draw_horizontal_bar(data, h_bar_start, -s1 - leg_w + seattop_offset, s2, h_bar_t, 2 * (s1 + leg_w), leg_l)
steps.append(step)
data, step = draw_horizontal_bar(data, h_bar_start, -s1 - leg_w + seattop_offset, -s2 - leg_l, h_bar_t, leg_w, 2 * (s2 + leg_l))
steps.append(step)
data, step = draw_horizontal_bar(data, h_bar_start, s1 + seattop_offset, -s2 - leg_l, h_bar_t, leg_w, 2 * (s2 + leg_l))
steps.append(step)
return data, steps
def generate_batch(num):
data = np.zeros((num, 32, 32, 32), dtype=np.uint8)
label = np.zeros((num, max_step, max_param), dtype=np.int32)
d = get_distance_to_center()
for i in range(num):
x, y = generate_single(d)
data[i, ...] = x
for k1 in range(len(y)):
label[i, k1, 0:len(y[k1])] = y[k1]
return data, label
def check_max_steps():
d = get_distance_to_center()
step = 0
for i in range(200):
x, y = generate_single(d)
if len(y) > step:
step = len(y)
print("Maximum Steps: " + str(step) + " " + os.path.basename(__file__))
return step
| 42.773196 | 179 | 0.580863 | 2,057 | 12,447 | 3.228974 | 0.063199 | 0.069858 | 0.104788 | 0.055405 | 0.82716 | 0.807287 | 0.789822 | 0.767088 | 0.728696 | 0.720566 | 0 | 0.043444 | 0.28063 | 12,447 | 290 | 180 | 42.92069 | 0.698347 | 0.30433 | 0 | 0.621053 | 1 | 0 | 0.001878 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.015789 | false | 0 | 0.026316 | 0 | 0.057895 | 0.005263 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
40128675202fcf78728a189bbf9d52c917a48e5b | 48,828 | py | Python | msgraph/cli/command_modules/devicescorpmgt/azext_devicescorpmgt/vendored_sdks/devicescorpmgt/aio/operations/_users_operations.py | microsoftgraph/msgraph-cli-archived | 489f70bf4ede1ce67b84bfb31e66da3e4db76062 | [
"MIT"
] | null | null | null | msgraph/cli/command_modules/devicescorpmgt/azext_devicescorpmgt/vendored_sdks/devicescorpmgt/aio/operations/_users_operations.py | microsoftgraph/msgraph-cli-archived | 489f70bf4ede1ce67b84bfb31e66da3e4db76062 | [
"MIT"
] | 22 | 2022-03-29T22:54:37.000Z | 2022-03-29T22:55:27.000Z | msgraph/cli/command_modules/devicescorpmgt/azext_devicescorpmgt/vendored_sdks/devicescorpmgt/aio/operations/_users_operations.py | microsoftgraph/msgraph-cli-archived | 489f70bf4ede1ce67b84bfb31e66da3e4db76062 | [
"MIT"
] | null | null | null | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from typing import Any, AsyncIterable, Callable, Dict, Generic, List, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from ... import models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class usersOperations:
"""usersOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~devices_corporate_management.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list_device_management_troubleshooting_events(
self,
user_id: str,
orderby: Optional[List[Union[str, "models.Enum140"]]] = None,
select: Optional[List[Union[str, "models.Enum141"]]] = None,
expand: Optional[List[str]] = None,
**kwargs
) -> AsyncIterable["models.collectionofdevicemanagementtroubleshootingevent"]:
"""Get deviceManagementTroubleshootingEvents from users.
Get deviceManagementTroubleshootingEvents from users.
:param user_id: key: id of user.
:type user_id: str
:param orderby: Order items by property values.
:type orderby: list[str or ~devices_corporate_management.models.Enum140]
:param select: Select properties to be returned.
:type select: list[str or ~devices_corporate_management.models.Enum141]
:param expand: Expand related entities.
:type expand: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either collectionofdevicemanagementtroubleshootingevent or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~devices_corporate_management.models.collectionofdevicemanagementtroubleshootingevent]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.collectionofdevicemanagementtroubleshootingevent"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_device_management_troubleshooting_events.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if self._config.top is not None:
query_parameters['$top'] = self._serialize.query("self._config.top", self._config.top, 'int', minimum=0)
if self._config.skip is not None:
query_parameters['$skip'] = self._serialize.query("self._config.skip", self._config.skip, 'int', minimum=0)
if self._config.search is not None:
query_parameters['$search'] = self._serialize.query("self._config.search", self._config.search, 'str')
if self._config.filter is not None:
query_parameters['$filter'] = self._serialize.query("self._config.filter", self._config.filter, 'str')
if self._config.count is not None:
query_parameters['$count'] = self._serialize.query("self._config.count", self._config.count, 'bool')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query("orderby", orderby, '[str]', div=',')
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('collectionofdevicemanagementtroubleshootingevent', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.odata_next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize(models.odataerror, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_device_management_troubleshooting_events.metadata = {'url': '/users/{user-id}/deviceManagementTroubleshootingEvents'} # type: ignore
async def create_device_management_troubleshooting_events(
self,
user_id: str,
body: "models.microsoftgraphdevicemanagementtroubleshootingevent",
**kwargs
) -> "models.microsoftgraphdevicemanagementtroubleshootingevent":
"""Create new navigation property to deviceManagementTroubleshootingEvents for users.
Create new navigation property to deviceManagementTroubleshootingEvents for users.
:param user_id: key: id of user.
:type user_id: str
:param body: New navigation property.
:type body: ~devices_corporate_management.models.microsoftgraphdevicemanagementtroubleshootingevent
:keyword callable cls: A custom type or function that will be passed the direct response
:return: microsoftgraphdevicemanagementtroubleshootingevent, or the result of cls(response)
:rtype: ~devices_corporate_management.models.microsoftgraphdevicemanagementtroubleshootingevent
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.microsoftgraphdevicemanagementtroubleshootingevent"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create_device_management_troubleshooting_events.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'microsoftgraphdevicemanagementtroubleshootingevent')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('microsoftgraphdevicemanagementtroubleshootingevent', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_device_management_troubleshooting_events.metadata = {'url': '/users/{user-id}/deviceManagementTroubleshootingEvents'} # type: ignore
async def get_device_management_troubleshooting_events(
self,
user_id: str,
device_management_troubleshooting_event_id: str,
select: Optional[List[Union[str, "models.Enum142"]]] = None,
expand: Optional[List[str]] = None,
**kwargs
) -> "models.microsoftgraphdevicemanagementtroubleshootingevent":
"""Get deviceManagementTroubleshootingEvents from users.
Get deviceManagementTroubleshootingEvents from users.
:param user_id: key: id of user.
:type user_id: str
:param device_management_troubleshooting_event_id: key: id of
deviceManagementTroubleshootingEvent.
:type device_management_troubleshooting_event_id: str
:param select: Select properties to be returned.
:type select: list[str or ~devices_corporate_management.models.Enum142]
:param expand: Expand related entities.
:type expand: list[str]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: microsoftgraphdevicemanagementtroubleshootingevent, or the result of cls(response)
:rtype: ~devices_corporate_management.models.microsoftgraphdevicemanagementtroubleshootingevent
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.microsoftgraphdevicemanagementtroubleshootingevent"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.get_device_management_troubleshooting_events.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'deviceManagementTroubleshootingEvent-id': self._serialize.url("device_management_troubleshooting_event_id", device_management_troubleshooting_event_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('microsoftgraphdevicemanagementtroubleshootingevent', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_device_management_troubleshooting_events.metadata = {'url': '/users/{user-id}/deviceManagementTroubleshootingEvents/{deviceManagementTroubleshootingEvent-id}'} # type: ignore
async def update_device_management_troubleshooting_events(
self,
user_id: str,
device_management_troubleshooting_event_id: str,
body: "models.microsoftgraphdevicemanagementtroubleshootingevent",
**kwargs
) -> None:
"""Update the navigation property deviceManagementTroubleshootingEvents in users.
Update the navigation property deviceManagementTroubleshootingEvents in users.
:param user_id: key: id of user.
:type user_id: str
:param device_management_troubleshooting_event_id: key: id of
deviceManagementTroubleshootingEvent.
:type device_management_troubleshooting_event_id: str
:param body: New navigation property values.
:type body: ~devices_corporate_management.models.microsoftgraphdevicemanagementtroubleshootingevent
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update_device_management_troubleshooting_events.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'deviceManagementTroubleshootingEvent-id': self._serialize.url("device_management_troubleshooting_event_id", device_management_troubleshooting_event_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'microsoftgraphdevicemanagementtroubleshootingevent')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
if cls:
return cls(pipeline_response, None, {})
update_device_management_troubleshooting_events.metadata = {'url': '/users/{user-id}/deviceManagementTroubleshootingEvents/{deviceManagementTroubleshootingEvent-id}'} # type: ignore
async def delete_device_management_troubleshooting_events(
self,
user_id: str,
device_management_troubleshooting_event_id: str,
if_match: Optional[str] = None,
**kwargs
) -> None:
"""Delete navigation property deviceManagementTroubleshootingEvents for users.
Delete navigation property deviceManagementTroubleshootingEvents for users.
:param user_id: key: id of user.
:type user_id: str
:param device_management_troubleshooting_event_id: key: id of
deviceManagementTroubleshootingEvent.
:type device_management_troubleshooting_event_id: str
:param if_match: ETag.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.delete_device_management_troubleshooting_events.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'deviceManagementTroubleshootingEvent-id': self._serialize.url("device_management_troubleshooting_event_id", device_management_troubleshooting_event_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if if_match is not None:
header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
if cls:
return cls(pipeline_response, None, {})
delete_device_management_troubleshooting_events.metadata = {'url': '/users/{user-id}/deviceManagementTroubleshootingEvents/{deviceManagementTroubleshootingEvent-id}'} # type: ignore
def list_managed_app_registrations(
self,
user_id: str,
orderby: Optional[List[Union[str, "models.Enum143"]]] = None,
select: Optional[List[Union[str, "models.Enum144"]]] = None,
expand: Optional[List[Union[str, "models.Enum145"]]] = None,
**kwargs
) -> AsyncIterable["models.collectionofmanagedappregistration0"]:
"""Get managedAppRegistrations from users.
Get managedAppRegistrations from users.
:param user_id: key: id of user.
:type user_id: str
:param orderby: Order items by property values.
:type orderby: list[str or ~devices_corporate_management.models.Enum143]
:param select: Select properties to be returned.
:type select: list[str or ~devices_corporate_management.models.Enum144]
:param expand: Expand related entities.
:type expand: list[str or ~devices_corporate_management.models.Enum145]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either collectionofmanagedappregistration0 or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~devices_corporate_management.models.collectionofmanagedappregistration0]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.collectionofmanagedappregistration0"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_managed_app_registrations.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if self._config.top is not None:
query_parameters['$top'] = self._serialize.query("self._config.top", self._config.top, 'int', minimum=0)
if self._config.skip is not None:
query_parameters['$skip'] = self._serialize.query("self._config.skip", self._config.skip, 'int', minimum=0)
if self._config.search is not None:
query_parameters['$search'] = self._serialize.query("self._config.search", self._config.search, 'str')
if self._config.filter is not None:
query_parameters['$filter'] = self._serialize.query("self._config.filter", self._config.filter, 'str')
if self._config.count is not None:
query_parameters['$count'] = self._serialize.query("self._config.count", self._config.count, 'bool')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query("orderby", orderby, '[str]', div=',')
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('collectionofmanagedappregistration0', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.odata_next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize(models.odataerror, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_managed_app_registrations.metadata = {'url': '/users/{user-id}/managedAppRegistrations'} # type: ignore
def list_ref_managed_app_registrations(
self,
user_id: str,
orderby: Optional[List[Union[str, "models.Enum146"]]] = None,
**kwargs
) -> AsyncIterable["models.collectionoflinksofmanagedappregistration"]:
"""Get ref of managedAppRegistrations from users.
Get ref of managedAppRegistrations from users.
:param user_id: key: id of user.
:type user_id: str
:param orderby: Order items by property values.
:type orderby: list[str or ~devices_corporate_management.models.Enum146]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either collectionoflinksofmanagedappregistration or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~devices_corporate_management.models.collectionoflinksofmanagedappregistration]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.collectionoflinksofmanagedappregistration"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_ref_managed_app_registrations.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if self._config.top is not None:
query_parameters['$top'] = self._serialize.query("self._config.top", self._config.top, 'int', minimum=0)
if self._config.skip is not None:
query_parameters['$skip'] = self._serialize.query("self._config.skip", self._config.skip, 'int', minimum=0)
if self._config.search is not None:
query_parameters['$search'] = self._serialize.query("self._config.search", self._config.search, 'str')
if self._config.filter is not None:
query_parameters['$filter'] = self._serialize.query("self._config.filter", self._config.filter, 'str')
if self._config.count is not None:
query_parameters['$count'] = self._serialize.query("self._config.count", self._config.count, 'bool')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query("orderby", orderby, '[str]', div=',')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('collectionoflinksofmanagedappregistration', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.odata_next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize(models.odataerror, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_ref_managed_app_registrations.metadata = {'url': '/users/{user-id}/managedAppRegistrations/$ref'} # type: ignore
async def create_ref_managed_app_registrations(
self,
user_id: str,
body: Dict[str, object],
**kwargs
) -> Dict[str, object]:
"""Create new navigation property ref to managedAppRegistrations for users.
Create new navigation property ref to managedAppRegistrations for users.
:param user_id: key: id of user.
:type user_id: str
:param body: New navigation property ref value.
:type body: dict[str, object]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: dict mapping str to object, or the result of cls(response)
:rtype: dict[str, object]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[Dict[str, object]]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create_ref_managed_app_registrations.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, '{object}')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('{object}', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_ref_managed_app_registrations.metadata = {'url': '/users/{user-id}/managedAppRegistrations/$ref'} # type: ignore
def list_managed_devices(
self,
user_id: str,
orderby: Optional[List[Union[str, "models.Enum147"]]] = None,
select: Optional[List[Union[str, "models.Enum148"]]] = None,
expand: Optional[List[Union[str, "models.Enum149"]]] = None,
**kwargs
) -> AsyncIterable["models.collectionofmanageddevice"]:
"""Get managedDevices from users.
Get managedDevices from users.
:param user_id: key: id of user.
:type user_id: str
:param orderby: Order items by property values.
:type orderby: list[str or ~devices_corporate_management.models.Enum147]
:param select: Select properties to be returned.
:type select: list[str or ~devices_corporate_management.models.Enum148]
:param expand: Expand related entities.
:type expand: list[str or ~devices_corporate_management.models.Enum149]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either collectionofmanageddevice or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~devices_corporate_management.models.collectionofmanageddevice]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.collectionofmanageddevice"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_managed_devices.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if self._config.top is not None:
query_parameters['$top'] = self._serialize.query("self._config.top", self._config.top, 'int', minimum=0)
if self._config.skip is not None:
query_parameters['$skip'] = self._serialize.query("self._config.skip", self._config.skip, 'int', minimum=0)
if self._config.search is not None:
query_parameters['$search'] = self._serialize.query("self._config.search", self._config.search, 'str')
if self._config.filter is not None:
query_parameters['$filter'] = self._serialize.query("self._config.filter", self._config.filter, 'str')
if self._config.count is not None:
query_parameters['$count'] = self._serialize.query("self._config.count", self._config.count, 'bool')
if orderby is not None:
query_parameters['$orderby'] = self._serialize.query("orderby", orderby, '[str]', div=',')
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('collectionofmanageddevice', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.odata_next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize(models.odataerror, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list_managed_devices.metadata = {'url': '/users/{user-id}/managedDevices'} # type: ignore
async def create_managed_devices(
self,
user_id: str,
body: "models.microsoftgraphmanageddevice",
**kwargs
) -> "models.microsoftgraphmanageddevice":
"""Create new navigation property to managedDevices for users.
Create new navigation property to managedDevices for users.
:param user_id: key: id of user.
:type user_id: str
:param body: New navigation property.
:type body: ~devices_corporate_management.models.microsoftgraphmanageddevice
:keyword callable cls: A custom type or function that will be passed the direct response
:return: microsoftgraphmanageddevice, or the result of cls(response)
:rtype: ~devices_corporate_management.models.microsoftgraphmanageddevice
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.microsoftgraphmanageddevice"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.create_managed_devices.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'microsoftgraphmanageddevice')
body_content_kwargs['content'] = body_content
request = self._client.post(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('microsoftgraphmanageddevice', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_managed_devices.metadata = {'url': '/users/{user-id}/managedDevices'} # type: ignore
async def get_managed_devices(
self,
user_id: str,
managed_device_id: str,
select: Optional[List[Union[str, "models.Enum160"]]] = None,
expand: Optional[List[Union[str, "models.Enum161"]]] = None,
**kwargs
) -> "models.microsoftgraphmanageddevice":
"""Get managedDevices from users.
Get managedDevices from users.
:param user_id: key: id of user.
:type user_id: str
:param managed_device_id: key: id of managedDevice.
:type managed_device_id: str
:param select: Select properties to be returned.
:type select: list[str or ~devices_corporate_management.models.Enum160]
:param expand: Expand related entities.
:type expand: list[str or ~devices_corporate_management.models.Enum161]
:keyword callable cls: A custom type or function that will be passed the direct response
:return: microsoftgraphmanageddevice, or the result of cls(response)
:rtype: ~devices_corporate_management.models.microsoftgraphmanageddevice
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["models.microsoftgraphmanageddevice"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.get_managed_devices.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'managedDevice-id': self._serialize.url("managed_device_id", managed_device_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if select is not None:
query_parameters['$select'] = self._serialize.query("select", select, '[str]', div=',')
if expand is not None:
query_parameters['$expand'] = self._serialize.query("expand", expand, '[str]', div=',')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('microsoftgraphmanageddevice', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_managed_devices.metadata = {'url': '/users/{user-id}/managedDevices/{managedDevice-id}'} # type: ignore
async def update_managed_devices(
self,
user_id: str,
managed_device_id: str,
body: "models.microsoftgraphmanageddevice",
**kwargs
) -> None:
"""Update the navigation property managedDevices in users.
Update the navigation property managedDevices in users.
:param user_id: key: id of user.
:type user_id: str
:param managed_device_id: key: id of managedDevice.
:type managed_device_id: str
:param body: New navigation property values.
:type body: ~devices_corporate_management.models.microsoftgraphmanageddevice
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self.update_managed_devices.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'managedDevice-id': self._serialize.url("managed_device_id", managed_device_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(body, 'microsoftgraphmanageddevice')
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
if cls:
return cls(pipeline_response, None, {})
update_managed_devices.metadata = {'url': '/users/{user-id}/managedDevices/{managedDevice-id}'} # type: ignore
async def delete_managed_devices(
self,
user_id: str,
managed_device_id: str,
if_match: Optional[str] = None,
**kwargs
) -> None:
"""Delete navigation property managedDevices for users.
Delete navigation property managedDevices for users.
:param user_id: key: id of user.
:type user_id: str
:param managed_device_id: key: id of managedDevice.
:type managed_device_id: str
:param if_match: ETag.
:type if_match: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
accept = "application/json"
# Construct URL
url = self.delete_managed_devices.metadata['url'] # type: ignore
path_format_arguments = {
'user-id': self._serialize.url("user_id", user_id, 'str'),
'managedDevice-id': self._serialize.url("managed_device_id", managed_device_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
# Construct headers
header_parameters = {} # type: Dict[str, Any]
if if_match is not None:
header_parameters['If-Match'] = self._serialize.header("if_match", if_match, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize(models.odataerror, response)
raise HttpResponseError(response=response, model=error)
if cls:
return cls(pipeline_response, None, {})
delete_managed_devices.metadata = {'url': '/users/{user-id}/managedDevices/{managedDevice-id}'} # type: ignore
| 49.672431 | 186 | 0.658311 | 5,137 | 48,828 | 6.047304 | 0.048083 | 0.017576 | 0.011299 | 0.015773 | 0.914019 | 0.912152 | 0.897537 | 0.880187 | 0.868083 | 0.862321 | 0 | 0.006522 | 0.240129 | 48,828 | 982 | 187 | 49.723014 | 0.830741 | 0.133837 | 0 | 0.818636 | 0 | 0 | 0.122429 | 0.056385 | 0 | 0 | 0 | 0 | 0 | 1 | 0.014975 | false | 0 | 0.011647 | 0 | 0.079867 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
404bd9d946792cc155f9093166213e4ad082c596 | 14,346 | py | Python | tests/Algorithms.py | jacobdenobel/ModEA | 7bfb0870612b5267a5997b6753acc1c95fd36ca0 | [
"MIT"
] | 1 | 2020-11-03T15:34:16.000Z | 2020-11-03T15:34:16.000Z | tests/Algorithms.py | jacobdenobel/ModEA | 7bfb0870612b5267a5997b6753acc1c95fd36ca0 | [
"MIT"
] | null | null | null | tests/Algorithms.py | jacobdenobel/ModEA | 7bfb0870612b5267a5997b6753acc1c95fd36ca0 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import unittest
import numpy as np
import random
from modea.Algorithms import _onePlusOneES, _customizedES
def sphere(X):
return sum([x**2 for x in X])
class OnePlusOneTest(unittest.TestCase):
def setUp(self):
np.random.seed(42)
random.seed(42)
def test_onePlusOne(self):
gensize, sigmas, fitness, best_ind = _onePlusOneES(5, sphere, 250)
self.assertListEqual([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], gensize)
self.assertListEqual([13.023659385451472, 10.541224881082313, 10.541224881082313, 10.541224881082313, 10.541224881082313,
10.541224881082313, 10.541224881082313, 10.541224881082313, 10.541224881082313, 6.1473499408489527,
6.1473499408489527, 6.1473499408489527, 6.1473499408489527, 6.1473499408489527, 6.1473499408489527,
6.1473499408489527, 6.1473499408489527, 6.1473499408489527, 6.1473499408489527, 6.1473499408489527,
6.1473499408489527, 6.1473499408489527, 6.1473499408489527, 6.1473499408489527, 6.1473499408489527,
3.4729859904048412, 2.2432205043004552, 2.2432205043004552, 2.2432205043004552, 2.2432205043004552,
2.2432205043004552, 2.2432205043004552, 2.2432205043004552, 0.93375022487417703, 0.93375022487417703,
0.93375022487417703, 0.93375022487417703, 0.93375022487417703, 0.93375022487417703, 0.93375022487417703,
0.93375022487417703, 0.93375022487417703, 0.62834917759940589, 0.62834917759940589, 0.62834917759940589,
0.24313819465891517, 0.24313819465891517, 0.24313819465891517, 0.24313819465891517, 0.24313819465891517,
0.24313819465891517, 0.24313819465891517, 0.24313819465891517, 0.24313819465891517, 0.24313819465891517,
0.24313819465891517, 0.23330705105211108, 0.23330705105211108, 0.23330705105211108, 0.23330705105211108,
0.23330705105211108, 0.23330705105211108, 0.23330705105211108, 0.23330705105211108, 0.23330705105211108,
0.23030670316819365, 0.21383778088213332, 0.21383778088213332, 0.21383778088213332, 0.21383778088213332,
0.21383778088213332, 0.21383778088213332, 0.21383778088213332, 0.21383778088213332, 0.21383778088213332,
0.21383778088213332, 0.21383778088213332, 0.21383778088213332, 0.21383778088213332, 0.21383778088213332,
0.21383778088213332, 0.21383778088213332, 0.21383778088213332, 0.2075245187938613, 0.18038773000143055,
0.18038773000143055, 0.11057574467337064, 0.11057574467337064, 0.095653628535671761, 0.095653628535671761,
0.092837063588373903, 0.092837063588373903, 0.080948318966528862, 0.080948318966528862, 0.080948318966528862,
0.080948318966528862, 0.080948318966528862, 0.080948318966528862, 0.0643070276972557, 0.0643070276972557,
0.0643070276972557, 0.0643070276972557, 0.0643070276972557, 0.0643070276972557, 0.0643070276972557,
0.053421169099607285, 0.053421169099607285, 0.053421169099607285, 0.053421169099607285, 0.033590424935720696,
0.033590424935720696, 0.033590424935720696, 0.033590424935720696, 0.031541722985728105, 0.031541722985728105,
0.031541722985728105, 0.031541722985728105, 0.016945406521219331, 0.016945406521219331, 0.016945406521219331,
0.016945406521219331, 0.016945406521219331, 0.016945406521219331, 0.016945406521219331, 0.016945406521219331,
0.016945406521219331, 0.016945406521219331, 0.016945406521219331, 0.016945406521219331, 0.016945406521219331,
0.016945406521219331, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463,
0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463,
0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463,
0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013457378561860463,
0.013457378561860463, 0.013457378561860463, 0.013457378561860463, 0.013384383130791263, 0.013384383130791263,
0.013384383130791263, 0.013384383130791263, 0.013384383130791263, 0.013384383130791263, 0.013384383130791263,
0.013384383130791263, 0.013384383130791263, 0.013384383130791263, 0.013384383130791263, 0.013384383130791263,
0.013384383130791263, 0.013384383130791263, 0.012146018152651972, 0.012146018152651972, 0.012146018152651972,
0.0084251220857654192, 0.0084251220857654192, 0.0084251220857654192, 0.0084251220857654192,
0.0084251220857654192, 0.0084251220857654192, 0.0084251220857654192, 0.0084251220857654192,
0.0084251220857654192, 0.0084251220857654192, 0.0084251220857654192, 0.0084251220857654192,
0.0053729335198040044, 0.0053729335198040044, 0.0053729335198040044, 0.00082941537051649109,
0.00082941537051649109, 0.00082941537051649109, 0.00082941537051649109, 0.00082941537051649109,
0.00082941537051649109, 0.00082941537051649109, 0.00082941537051649109, 0.00033656382447449021,
0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021,
0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021,
0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021,
0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021,
0.00033656382447449021, 0.00033656382447449021, 0.00033656382447449021, 0.00019149973142124787,
0.00019149973142124787, 0.00019149973142124787, 0.00019149973142124787, 9.9433877410602447e-05,
9.9433877410602447e-05, 9.9433877410602447e-05, 9.9433877410602447e-05, 4.5130684523027633e-05,
4.5130684523027633e-05, 4.5130684523027633e-05, 4.5130684523027633e-05, 4.5130684523027633e-05,
4.2321307388608291e-05, 4.2321307388608291e-05, 4.2321307388608291e-05, 4.2321307388608291e-05,
3.4297211302987206e-05, 3.4297211302987206e-05, 3.4297211302987206e-05, 3.4297211302987206e-05,
3.4297211302987206e-05, 3.4297211302987206e-05, 3.4297211302987206e-05, 3.4297211302987206e-05,
3.4297211302987206e-05, 3.4297211302987206e-05, 3.4297211302987206e-05, 2.028527974303762e-05,
2.028527974303762e-05, 2.028527974303762e-05, 2.028527974303762e-05, 2.028527974303762e-05,
2.028527974303762e-05, 9.2901682984619832e-06, 9.2901682984619832e-06, 9.2901682984619832e-06], fitness)
self.assertListEqual([[0.0009614810266920609],
[-0.0026396213864220705],
[0.00019035212334714215],
[0.0011574936475235022],
[-0.00014864721725064457]],
best_ind.genotype.tolist())
class CMATest(unittest.TestCase):
def test_CMA(self):
np.random.seed(42)
random.seed(42)
gensize, sigmas, fitness, best_ind = _customizedES(5, sphere, 250)
self.assertListEqual([8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
8, 8], gensize)
np.testing.assert_array_almost_equal([12.358143128302745, 12.358143128302745, 12.358143128302745, 12.358143128302745,
12.358143128302745, 12.358143128302745, 12.358143128302745, 12.358143128302745,
23.843489104882579, 23.843489104882579, 23.843489104882579, 23.843489104882579],
fitness[:12])
np.testing.assert_array_almost_equal([[-0.037539876507280745], [0.5006237700034122], [0.007162824278235114],
[0.8674124073459843], [-0.7366419353773903]], best_ind.genotype.tolist())
class restartCMATest(unittest.TestCase):
def setUp(self):
np.random.seed(42)
random.seed(42)
def test_CMA(self):
gensize, sigmas, fitness, best_ind = _customizedES(2, sphere, 5000, opts={'ipop': 'BIPOP'})
exp_gensize = [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
6, 6, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 11, 11, 11, 11, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11]
exp_sigmas = [13.699569604866394,
13.699569604866394,
13.699569604866394,
13.699569604866394,
13.699569604866394,
13.699569604866394,
52.945369311602761,
52.945369311602761,
52.945369311602761,
52.945369311602761]
exp_fitness_first = [0.17173676998861423,
0.17173676998861423,
0.17173676998861423,
0.17173676998861423,
0.17173676998861423,
0.17173676998861423,
4.5559464826267613,
4.5559464826267613,
4.5559464826267613,
4.5559464826267613]
exp_fitness_last = [0.00074290, 0.00074290, 0.00074290, 0.00074290,
0.00074290, 0.00074290, 0.00074290, 0.00074290,
0.00074290, 0.00074290, 0.00074290, 0.00074290,
0.00074290, 0.00074290, 0.00074290]
self.assertListEqual(exp_gensize, gensize)
np.testing.assert_array_almost_equal(exp_sigmas[:10], sigmas[:10])
np.testing.assert_array_almost_equal(exp_fitness_first, fitness[:10])
np.testing.assert_array_almost_equal(exp_fitness_last, fitness[-15:])
np.testing.assert_array_almost_equal([[8.881784197001252e-16], [1.7763568394002505e-15]], best_ind.genotype.tolist())
if __name__ == '__main__':
unittest.main()
| 82.924855 | 140 | 0.549491 | 1,761 | 14,346 | 4.44293 | 0.080636 | 0.115286 | 0.172163 | 0.228528 | 0.873594 | 0.838062 | 0.771345 | 0.732234 | 0.7284 | 0.707439 | 0 | 0.691297 | 0.326432 | 14,346 | 172 | 141 | 83.406977 | 0.11839 | 0.002928 | 0 | 0.470199 | 0 | 0 | 0.001189 | 0 | 0 | 0 | 0 | 0 | 0.072848 | 1 | 0.039735 | false | 0 | 0.033113 | 0.006623 | 0.099338 | 0.006623 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
404fc846950dc9b62ad4824d8675c996da48545f | 139 | py | Python | src/Pythia/python/adapter_import_test/module_two/file_two.py | 5sigmapoint2/Pythia | c4ef8b4fc87e711921015c537a061663e153deb2 | [
"MIT"
] | 52 | 2016-11-05T14:26:22.000Z | 2022-03-30T11:27:40.000Z | src/Pythia/python/adapter_import_test/module_two/file_two.py | 5sigmapoint2/Pythia | c4ef8b4fc87e711921015c537a061663e153deb2 | [
"MIT"
] | 57 | 2016-11-02T13:56:48.000Z | 2022-01-18T03:50:38.000Z | src/Pythia/python/adapter_import_test/module_two/file_two.py | 5sigmapoint2/Pythia | c4ef8b4fc87e711921015c537a061663e153deb2 | [
"MIT"
] | 5 | 2017-10-19T13:35:50.000Z | 2022-02-09T06:51:11.000Z | print('Interpreting module_two.file_two.py')
def fun():
print('module_two::file_two::fun()')
return 'module_two::file_two::fun()'
| 23.166667 | 44 | 0.690647 | 21 | 139 | 4.285714 | 0.428571 | 0.3 | 0.433333 | 0.533333 | 0.422222 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.115108 | 139 | 5 | 45 | 27.8 | 0.731707 | 0 | 0 | 0 | 0 | 0 | 0.640288 | 0.546763 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | true | 0 | 0 | 0 | 0.5 | 0.5 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 10 |
4069cd9c0f22db22b943c94fe83b5e2e75170879 | 422 | py | Python | server/script3.py | neuefische/flatten_the_queue | 71ea610818389df10bde7d49f2b5d98153ee089b | [
"MIT"
] | 3 | 2020-03-22T23:55:53.000Z | 2020-03-26T20:05:33.000Z | server/script3.py | neuefische/flatten_the_queue | 71ea610818389df10bde7d49f2b5d98153ee089b | [
"MIT"
] | 18 | 2020-03-21T10:08:41.000Z | 2022-02-27T01:34:18.000Z | server/script3.py | neuefische/flatten_the_queue | 71ea610818389df10bde7d49f2b5d98153ee089b | [
"MIT"
] | null | null | null | print('[{"name":"Lidl","id":"ChIJiyY_mbyFsUcRUnTY2vvE3gw","street":"Behringstra\u00dfe 154","city":"Hamburg","current_popularity":1000},{"name":"ALDI Hamburg-Bahrenfeld","id":"ChIJgZqGDZWFsUcRMoj-OHgDLgE","street":"Bahrenfelder Kirchenweg 80","city":"Hamburg","current_popularity":1000},{"name":"REWE","id":"ChIJJ9JyqsCFsUcR9XjndPhq30g","street":"Von-Sauer-Stra\u00dfe 11-13","city":"Hamburg","current_popularity":1000}]') | 422 | 422 | 0.746445 | 47 | 422 | 6.617021 | 0.617021 | 0.106109 | 0.173633 | 0.270096 | 0.334405 | 0.231511 | 0 | 0 | 0 | 0 | 0 | 0.074341 | 0.011848 | 422 | 1 | 422 | 422 | 0.671463 | 0 | 0 | 0 | 0 | 1 | 0.976359 | 0.940898 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 8 |
4079298dbbb6da9078e6b3764e76612b6c20924e | 89,820 | py | Python | instagram/agents.py | ssyuzev/pyInstagram | 075dbe5aef307817f4ac88579d1d681589f49013 | [
"MIT"
] | null | null | null | instagram/agents.py | ssyuzev/pyInstagram | 075dbe5aef307817f4ac88579d1d681589f49013 | [
"MIT"
] | null | null | null | instagram/agents.py | ssyuzev/pyInstagram | 075dbe5aef307817f4ac88579d1d681589f49013 | [
"MIT"
] | null | null | null | import aiohttp
import asyncio
import hashlib
from .entities import (Account, Comment, Element, HasMediaElement,Media, Location, Story, Tag,
UpdatableElement)
from .exceptions import (AuthException, CheckpointException, ExceptionManager,
IncorrectVerificationTypeException, InstagramException,
InternetException, UnexpectedResponse, NotUpdatedElement)
import json
import re
import requests
from requests.exceptions import HTTPError
from time import sleep, time
exception_manager = ExceptionManager()
class WebAgent:
def __init__(self, cookies=None, logger=None):
self.rhx_gis = None
self.csrf_token = None
self.session = requests.Session()
if cookies:
self.session.cookies = requests.cookies.cookiejar_from_dict(cookies)
self.logger = logger
@exception_manager.decorator
def update(self, obj=None, settings=None):
if not self.logger is None:
self.logger.info("Update '%s' started", "self" if obj is None else obj)
if not isinstance(obj, UpdatableElement) and not obj is None:
raise TypeError("obj must be UpdatableElement type or None")
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
query = "https://www.instagram.com/"
if not obj is None:
query += obj.base_url + getattr(obj, obj.primary_key)
response = self.get_request(query, **settings)
try:
match = re.search(
r"<script[^>]*>\s*window._sharedData\s*=\s*((?!<script>).*)\s*;\s*</script>",
response.text,
)
data = json.loads(match.group(1))
self.rhx_gis = data.get("rhx_gis", "")
self.csrf_token = data["config"]["csrf_token"]
if obj is None:
return None
data = data["entry_data"]
for key in obj.entry_data_path:
data=data[key]
obj.set_data(data)
if not self.logger is None:
self.logger.info("Update '%s' was successfull", "self" if obj is None else obj)
return data
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Update '%s' was unsuccessfull: %s",
"self" if obj is None else obj,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def get_media(self, obj, pointer=None, count=12, limit=50, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get media '%s' started", obj)
if not isinstance(obj, HasMediaElement):
raise TypeError("'obj' must be HasMediaElement type")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
variables_string = '{{"{name}":"{name_value}","first":{first},"after":"{after}"}}'
medias = []
if pointer is None:
try:
data = self.update(obj, settings=settings)
data = data[obj.media_path[-1]]
page_info = data["page_info"]
edges = data["edges"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
m = Media(node["shortcode"])
m.set_data(node)
if isinstance(obj, Account):
m.likes_count = node["edge_media_preview_like"]["count"]
m.owner = obj
else:
m.likes_count = node["edge_liked_by"]
obj.media.add(m)
medias.append(m)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
else:
if not self.logger is None:
self.logger.info("Get media '%s' was successfull", obj)
return medias, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get media '%s' was unsuccessfull: %s", obj, str(exception))
raise UnexpectedResponse(
exception,
"https://www.instagram.com/" + obj.base_url + getattr(obj, obj.primary_key),
)
while True:
data = {"after": pointer, "first": min(limit, count)}
if isinstance(obj, Tag):
data["name"] = "tag_name"
data["name_value"] = obj.name
else:
data["name"] = "id"
data["name_value"] = obj.id
response = self.graphql_request(
query_hash=obj.media_query_hash,
variables=variables_string.format(**data),
referer="https://instagram.com/" + obj.base_url + getattr(obj, obj.primary_key),
settings=settings,
)
try:
data = response.json()["data"]
for key in obj.media_path:
data = data[key]
page_info = data["page_info"]
edges = data["edges"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
m = Media(node["shortcode"])
m.set_data(node)
if isinstance(obj, Account):
m.likes_count = node["edge_media_preview_like"]["count"]
m.owner = obj
else:
m.likes_count = node["edge_liked_by"]
obj.media.add(m)
medias.append(m)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get media '%s' was successfull", obj)
return medias, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get media '%s' was unsuccessfull: %s", obj, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def get_likes(self, media, pointer=None, count=20, limit=50, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get likes '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
if media.id is None:
self.update(media, settings=settings)
if pointer:
variables_string = '{{"shortcode":"{shortcode}","first":{first},"after":"{after}"}}'
else:
variables_string = '{{"shortcode":"{shortcode}","first":{first}}}'
likes = []
while True:
data = {"shortcode": media.code, "first": min(limit, count)}
if pointer:
data["after"] = pointer
response = self.graphql_request(
query_hash="1cb6ec562846122743b61e492c85999f",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
media.base_url,
getattr(media, media.primary_key),
),
settings=settings,
)
try:
data = response.json()["data"]["shortcode_media"]["edge_liked_by"]
edges = data["edges"]
page_info = data["page_info"]
media.likes_count = data["count"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
account = Account(node["username"])
account.id = node["id"]
account.profile_pic_url = node["profile_pic_url"]
account.is_verified = node["is_verified"]
account.full_name = node["full_name"]
media.likes.add(account)
likes.append(account)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count-len(edges)
variables_string = \
'{{"shortcode":"{shortcode}","first":{first},"after":"{after}"}}'
sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get likes '%s' was successfull", media)
return likes, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get likes '%s' was unsuccessfull: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def get_comments(self, media, pointer=None, count=35, limit=32, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get comments '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
comments = []
if pointer is None:
try:
data = self.update(media, settings=settings)
if "edge_media_to_comment" in data:
data = data["edge_media_to_comment"]
else:
data = data["edge_media_to_parent_comment"]
edges = data["edges"]
page_info = data["page_info"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
c = Comment(node["id"], media=media,
owner=Account(node["owner"]["username"]),
text=node["text"],
created_at=node["created_at"])
media.comments.add(c)
comments.append(c)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and not pointer is None:
count = count-len(edges)
else:
if not self.logger is None:
self.logger.info("Get comments '%s' was successfull", media)
return comments, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get comments '%s' was unsuccessfull: %s",
media,
str(exception),
)
raise UnexpectedResponse(exception, media)
variables_string = '{{"shortcode":"{code}","first":{first},"after":"{after}"}}'
while True:
data = {"after": pointer, "code": media.code, "first": min(limit, count)}
response = self.graphql_request(
query_hash="f0986789a5c5d17c2400faebf16efd0d",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
media.base_url,
getattr(media, media.primary_key),
),
settings=settings,
)
try:
data = response.json()["data"]["shortcode_media"]["edge_media_to_comment"]
media.comments_count = data["count"]
edges = data["edges"]
page_info = data["page_info"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
c = Comment(node["id"],
media=media,
owner=Account(node["owner"]["username"]),
text=node["text"],
created_at=node["created_at"])
media.comments.add(c)
comments.append(c)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get comments '%s' was successfull", media)
return comments, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get comments '%s' was unsuccessfull: %s",
media,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
def graphql_request(self, query_hash, variables, referer, settings=None):
if not isinstance(query_hash, str):
raise TypeError("'query_hash' must be str type")
if not isinstance(variables, str):
raise TypeError("'variables' must be str type")
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
if not "params" in settings:
settings["params"] = dict()
settings["params"].update({"query_hash": query_hash})
settings["params"]["variables"] = variables
gis = "%s:%s" % (self.rhx_gis, variables)
if not "headers" in settings:
settings["headers"] = dict()
settings["headers"].update({
# "X-IG-App-ID": "936619743392459",
"X-Instagram-GIS": hashlib.md5(gis.encode("utf-8")).hexdigest(),
"X-Requested-With": "XMLHttpRequest",
"Referer": referer,
})
return self.get_request("https://www.instagram.com/graphql/query/", **settings)
def action_request(self, referer, url, data=None, settings=None):
if not isinstance(referer, str):
raise TypeError("'referer' must be str type")
if not isinstance(url, str):
raise TypeError("'url' must be str type")
if not isinstance(data, dict) and not data is None:
raise TypeError("'data' must be dict type or None")
data = dict() if data is None else data.copy()
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
headers = {
"Referer": referer,
"X-CSRFToken": self.csrf_token,
"X-Instagram-Ajax": "543e5253a719",
"X-Requested-With": "XMLHttpRequest",
"X-IG-App-ID": "936619743392459",
}
if "headers" in settings:
settings["headers"].update(headers)
else:
settings["headers"] = headers
if "data" in settings:
settings["data"].update(data)
else:
settings["data"] = data
return self.post_request(url, **settings)
def get_request(self, *args, **kwargs):
try:
response = self.session.get(*args, **kwargs)
response.raise_for_status()
return response
except (requests.exceptions.RequestException, ConnectionResetError) as exception:
raise InternetException(exception)
def post_request(self, *args, **kwargs):
try:
response = self.session.post(*args, **kwargs)
response.raise_for_status()
return response
except (requests.exceptions.RequestException, ConnectionResetError) as exception:
raise InternetException(exception)
class AsyncWebAgent:
def __init__(self, cookies=None, logger=None):
self.rhx_gis = None
self.csrf_token = None
self.session = aiohttp.ClientSession(cookies=cookies)
self.logger = logger
async def delete(self):
await self.session.close()
@exception_manager.decorator
async def update(self, obj=None, settings=None):
if not self.logger is None:
self.logger.info("Update '%s' started", "self" if obj is None else obj)
if not isinstance(obj, UpdatableElement) and not obj is None:
raise TypeError("obj must be UpdatableElement type or None")
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
query = "https://www.instagram.com/"
if not obj is None:
query += obj.base_url + getattr(obj, obj.primary_key)
response = await self.get_request(query, **settings)
try:
match = re.search(
r"<script[^>]*>\s*window._sharedData\s*=\s*((?!<script>).*)\s*;\s*</script>",
await response.text(),
)
data = json.loads(match.group(1))
self.rhx_gis = data.get("rhx_gis", "")
self.csrf_token = data["config"]["csrf_token"]
if obj is None:
return None
data = data["entry_data"]
for key in obj.entry_data_path:
data = data[key]
obj.set_data(data)
if not self.logger is None:
self.logger.info("Update '%s' was successfull", "self" if obj is None else obj)
return data
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.exception(
"Update '%s' was unsuccessfull: %s",
"self" if obj is None else obj,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def get_media(self, obj, pointer=None, count=12, limit=50, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get media '%s' started", obj)
if not isinstance(obj, HasMediaElement):
raise TypeError("'obj' must be HasMediaElement type")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
variables_string = '{{"{name}":"{name_value}","first":{first},"after":"{after}"}}'
medias = []
if pointer is None:
try:
data = await self.update(obj, settings=settings)
data = data[obj.media_path[-1]]
page_info = data["page_info"]
edges = data["edges"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
m = Media(node["shortcode"])
m.set_data(node)
if isinstance(obj, Account):
m.likes_count = node["edge_media_preview_like"]["count"]
m.owner = obj
else:
m.likes_count = node["edge_liked_by"]
obj.media.add(m)
medias.append(m)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
else:
if not self.logger is None:
self.logger.info("Get media '%s' was successfull", obj)
return medias, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get media '%s' was unsuccessfull: %s", obj, str(exception))
raise UnexpectedResponse(
exception,
"https://www.instagram.com/" + obj.base_url + getattr(obj, obj.primary_key),
)
while True:
data = {"after": pointer, "first": min(limit, count)}
if isinstance(obj, Tag):
data["name"] = "tag_name"
data["name_value"] = obj.name
else:
data["name"] = "id"
data["name_value"] = obj.id
response = await self.graphql_request(
query_hash=obj.media_query_hash,
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
obj.base_url,
getattr(obj, obj.primary_key),
),
settings=settings,
)
try:
data = (await response.json())["data"]
for key in obj.media_path:
data = data[key]
page_info = data["page_info"]
edges = data["edges"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
m = Media(node["shortcode"])
m.set_data(node)
if isinstance(obj, Account):
m.likes_count = node["edge_media_preview_like"]["count"]
m.owner = obj
else:
m.likes_count = node["edge_liked_by"]
obj.media.add(m)
medias.append(m)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
await asyncio.sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get media '%s' was successfull", obj)
return medias, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get media '%s' was unsuccessfull: %s", obj, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def get_likes(self, media, pointer=None, count=20, limit=50, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get likes '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
if media.id is None:
await self.update(media, settings=settings)
if pointer:
variables_string = '{{"shortcode":"{shortcode}","first":{first},"after":"{after}"}}'
else:
variables_string = '{{"shortcode":"{shortcode}","first":{first}}}'
likes = []
while True:
data = {"shortcode": media.code, "first": min(limit, count)}
if pointer:
data["after"] = pointer
response = await self.graphql_request(
query_hash="1cb6ec562846122743b61e492c85999f",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
media.base_url,
getattr(media, media.primary_key),
),
settings=settings,
)
try:
data = (await response.json())["data"]["shortcode_media"]["edge_liked_by"]
edges = data["edges"]
page_info = data["page_info"]
media.likes_count = data["count"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
account = Account(node["username"])
account.id = node["id"]
account.profile_pic_url = node["profile_pic_url"]
account.is_verified = node["is_verified"]
account.full_name = node["full_name"]
media.likes.add(account)
likes.append(account)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count-len(edges)
variables_string = \
'{{"shortcode":"{shortcode}","first":{first},"after":"{after}"}}'
await asyncio.sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get likes '%s' was successfull", media)
return likes, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get likes '%s' was unsuccessfull: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def get_comments(self, media, pointer=None, count=35, limit=32, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get comments '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
comments = []
if pointer is None:
try:
data = await self.update(media, settings=settings)
if "edge_media_to_comment" in data:
data = data["edge_media_to_comment"]
else:
data = data["edge_media_to_parent_comment"]
edges = data["edges"]
page_info = data["page_info"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
c = Comment(node["id"], media=media,
owner=Account(node["owner"]["username"]),
text=node["text"],
created_at=node["created_at"])
media.comments.add(c)
comments.append(c)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and not pointer is None:
count = count - len(edges)
else:
if not self.logger is None:
self.logger.info("Get comments '%s' was successfull", media)
return comments, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get comments '%s' was unsuccessfull: %s",
media,
str(exception),
)
raise UnexpectedResponse(exception, media)
variables_string = '{{"shortcode":"{code}","first":{first},"after":"{after}"}}'
while True:
data = {"after": pointer, "code": media.code, "first": min(limit, count)}
response = await self.graphql_request(
query_hash="f0986789a5c5d17c2400faebf16efd0d",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
media.base_url,
getattr(media, media.primary_key),
),
settings=settings,
)
try:
data = (await response.json())["data"]["shortcode_media"]["edge_media_to_comment"]
media.comments_count = data["count"]
edges = data["edges"]
page_info = data["page_info"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
c = Comment(node["id"],
media=media,
owner=Account(node["owner"]["username"]),
text=node["text"],
created_at=node["created_at"])
media.comments.add(c)
comments.append(c)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
await asyncio.sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get comments '%s' was successfull", media)
return comments, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get comments '%s' was unsuccessfull: %s",
media,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
async def graphql_request(self, query_hash, referer, variables, settings=None):
if not isinstance(query_hash, str):
raise TypeError("'query_hash' must be str type")
if not isinstance(variables, str):
raise TypeError("'variables' must be str type")
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
if not "params" in settings:
settings["params"] = dict()
settings["params"].update({"query_hash": query_hash})
settings["params"]["variables"] = variables
gis = "%s:%s" % (self.rhx_gis, variables)
if not "headers" in settings:
settings["headers"] = dict()
settings["headers"].update({
# "X-IG-App-ID": "936619743392459",
"X-Instagram-GIS": hashlib.md5(gis.encode("utf-8")).hexdigest(),
"X-Requested-With": "XMLHttpRequest",
"Referer": referer,
})
return await self.get_request("https://www.instagram.com/graphql/query/", **settings)
async def action_request(self, url, referer, data=None, settings=None):
if not isinstance(referer, str):
raise TypeError("'referer' must be str type")
if not isinstance(url, str):
raise TypeError("'url' must be str type")
if not isinstance(data, dict) and not data is None:
raise TypeError("'data' must be dict type or None")
data = dict() if data is None else data.copy()
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
headers = {
"Referer": referer,
"X-CSRFToken": self.csrf_token,
"X-Instagram-AJAX": "1",
"X-Requested-With": "XMLHttpRequest",
}
if "headers" in settings:
settings["headers"].update(headers)
else:
settings["headers"] = headers
if "data" in settings:
settings["data"].update(data)
else:
settings["data"] = data
return await self.post_request(url, **settings)
async def get_request(self, *args, **kwargs):
try:
return await self.session.get(*args, **kwargs)
except aiohttp.ClientResponseError as exception:
raise InternetException(exception)
async def post_request(self, *args, **kwargs):
try:
return await self.session.post(*args, **kwargs)
except aiohttp.ClientResponseError as exception:
raise InternetException(exception)
class WebAgentAccount(Account, WebAgent):
@exception_manager.decorator
def __init__(self, username, cookies=None, logger=None):
if not isinstance(username, str):
raise TypeError("'username' must be str type")
Account.__init__(self, username)
WebAgent.__init__(self, cookies=cookies, logger=logger)
@exception_manager.decorator
def auth(self, password, settings=None):
if not self.logger is None:
self.logger.info("Auth started")
if not isinstance(password, str):
raise TypeError("'password' must be str type")
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
self.update(settings=settings)
if "headers" not in settings:
settings["headers"] = {}
settings["headers"].update({
"X-IG-App-ID": "936619743392459",
# "X_Instagram-AJAX": "ee72defd9231",
"X-CSRFToken": self.csrf_token,
"Referer": "https://www.instagram.com/",
"Content-Type": "application/x-www-form-urlencoded",
})
str_time = str(int(time()))
password = '#PWD_INSTAGRAM_BROWSER:0:' + str_time + ':' + password
if "data" not in settings:
settings["data"] = {}
settings["data"].update({"username": self.username, "enc_password": password})
try:
response = self.post_request(
"https://www.instagram.com/accounts/login/ajax/",
**settings,
)
except InternetException as exception:
response = exception.response
try:
data = response.json()
if data.get("authenticated") is False:
raise AuthException(self.username)
elif data.get("message") == "checkpoint_required":
checkpoint_url = "https://instagram.com" + data.get("checkpoint_url")
data = self.checkpoint_handle(
url=checkpoint_url,
settings=settings,
)
raise CheckpointException(
username=self.username,
checkpoint_url=checkpoint_url,
navigation=data["navigation"],
types=data["types"],
)
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Auth was unsuccessfully: %s", str(exception))
raise UnexpectedResponse(exception, response.url)
if not self.logger is None:
self.logger.info("Auth was successfully")
@exception_manager.decorator
def checkpoint_handle(self, url, settings=None):
if not self.logger is None:
self.logger.info("Handle checkpoint page for '%s' started", self.username)
response = self.get_request(url, **settings)
try:
match = re.search(
r"<script[^>]*>\s*window._sharedData\s*=\s*((?!<script>).*)\s*;\s*</script>",
response.text,
)
data = json.loads(match.group(1))
data = data["entry_data"]["Challenge"][0]
navigation = {
key: "https://instagram.com" + value for key, value in data["navigation"].items()
}
data = data["extraData"]["content"]
data = list(filter(lambda item: item["__typename"] == "GraphChallengePageForm", data))
data = data[0]["fields"][0]["values"]
types = []
for d in data:
types.append({"label": d["label"].lower().split(":")[0], "value": d["value"]})
if not self.logger is None:
self.logger.info("Handle checkpoint page for '%s' was successfull", self.username)
return {"navigation": navigation, "types": types}
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Handle checkpoint page for '%s' was unsuccessfull: %s",
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def checkpoint_send(self, checkpoint_url, forward_url, choice, settings=None):
if not self.logger is None:
self.logger.info("Send verify code for '%s' started", self.username)
response = self.action_request(
referer=checkpoint_url,
url=forward_url,
data={"choice": choice},
settings=settings,
)
try:
navigation = response.json()["navigation"]
if not self.logger is None:
self.logger.info("Send verify code for '%s' was successfully", self.username)
return {
key: "https://instagram.com" + value for key, value in navigation.items()
}
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Send verify code by %s to '%s' was unsuccessfully: %s",
type,
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def checkpoint_replay(self, forward_url, replay_url, settings=None):
if not self.logger is None:
self.logger.info("Resend verify code for '%s' started")
response = self.action_request(
url=replay_url,
referer=forward_url,
settings=settings,
)
try:
navigation = response.json()["navigation"]
if not self.logger is None:
self.logger.info("Resend verify code for '%s' was successfull")
return {
key: "https://instagram.com" + value for key, value in navigation.items()
}
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Resend verify code for '%s' was unsuccessfull: %s",
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def checkpoint(self, url, code, settings=None):
if not self.logger is None:
self.logger.info("Verify account '%s' started")
response = self.action_request(
referer=url,
url=url,
data={"security_code": code},
settings=settings,
)
try:
result = response.json()["status"] == "ok"
if not self.logger is None:
self.logger.info("Verify account '%s' was successfull")
return result
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Verify account '%s' was unsuccessfull: %s",
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def update(self, obj=None, settings=None):
if obj is None:
obj = self
return WebAgent.update(self, obj, settings=settings)
@exception_manager.decorator
def get_media(self, obj=None, pointer=None, count=12, limit=12, delay=0, settings=None):
if obj is None:
obj = self
return WebAgent.get_media(self, obj, pointer=pointer, count=count, limit=limit, delay=delay,
settings=settings)
@exception_manager.decorator
def get_follows(self, account=None, pointer=None, count=20, limit=50, delay=0, settings=None):
if account is None:
account = self
if not self.logger is None:
self.logger.info("Get '%s' follows started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type or None")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(count, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
if account.id is None:
self.update(account, settings=settings)
if pointer is None:
variables_string = '{{"id":"{id}","first":{first}}}'
else:
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
follows = []
while True:
data = {"first": min(limit, count), "id": account.id}
if not pointer is None:
data["after"] = pointer
response = self.graphql_request(
query_hash="58712303d941c6855d4e888c5f0cd22f",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
account.base_url,
getattr(account, account.primary_key),
),
settings=settings,
)
try:
data = response.json()["data"]["user"]["edge_follow"]
edges = data["edges"]
page_info = data["page_info"]
account.follows_count = data["count"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
a = Account(node["username"])
a.id = node["id"]
a.profile_pic_url = node["profile_pic_url"]
a.is_verified = node["is_verified"]
a.full_name = node["full_name"]
account.follows.add(a)
follows.append(a)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get '%s' follows was successfully", account)
return follows, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get '%s' follows was unsuccessfully: %s",
account,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def get_followers(self, account=None, pointer=None, count=20, limit=50, delay=0, settings=None):
if account is None:
account = self
if not self.logger is None:
self.logger.info("Get '%s' followers started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type or None")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
if account.id is None:
self.update(account, settings=settings)
if pointer is None:
variables_string = '{{"id":"{id}","first":{first}}}'
else:
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
followers = []
while True:
data = {"first": min(limit, count), "id": account.id}
if not pointer is None:
data["after"] = pointer
response = self.graphql_request(
query_hash="37479f2b8209594dde7facb0d904896a",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
account.base_url,
getattr(account, account.primary_key),
),
settings=settings,
)
try:
data = response.json()["data"]["user"]["edge_followed_by"]
edges = data["edges"]
page_info = data["page_info"]
account.followers_count = data["count"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
a = Account(node["username"])
a.id = node["id"]
a.profile_pic_url = node["profile_pic_url"]
a.is_verified = node["is_verified"]
a.full_name = node["full_name"]
account.followers.add(a)
followers.append(a)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get '%s' followers was successfully", account)
return followers, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get '%s' followers was unsuccessfully: %s",
account,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def stories(self, settings=None):
if not self.logger is None:
self.logger.info("Get stories started")
response = self.graphql_request(
query_hash="60b755363b5c230111347a7a4e242001",
variables='{"only_stories":true}',
referer="https://instagram.com/%s%s" % (self.base_url, getattr(self, self.primary_key)),
settings=settings,
)
try:
data = response.json()["data"]["user"]["feed_reels_tray"]["edge_reels_tray_to_reel"]
if not self.logger is None:
self.logger.info("Get stories was successfully")
return [Story(edge["node"]["id"]) for edge in data["edges"]]
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get stories was unsuccessfully: %s", str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def feed(self, pointer=None, count=12, limit=50, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get feed started")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
variables_string = '{{"fetch_media_item_count":{first},"fetch_media_item_cursor":"{after}",\
"fetch_comment_count":4,"fetch_like":10,"has_stories":false}}'
feed = []
while True:
response = self.graphql_request(
query_hash="485c25657308f08317c1e4b967356828",
variables=variables_string.format(
after=pointer,
first=min(limit, count),
) if pointer else "{}",
referer="https://instagram.com/%s%s" % (
self.base_url,
getattr(self, self.primary_key),
),
settings=settings,
)
try:
data = response.json()["data"]["user"]["edge_web_feed_timeline"]
edges = data["edges"]
page_info = data["page_info"]
length = len(edges)
for index in range(min(length, count)):
node = edges[index]["node"]
if not "shortcode" in node:
length -= 1
continue
m = Media(node["shortcode"])
m.set_data(node)
feed.append(m)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if length < count and page_info["has_next_page"]:
count -= length
sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get feed was successfully")
return feed, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get feed was unsuccessfully: %s", str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def like(self, media, settings=None):
if not self.logger is None:
self.logger.info("Like '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
self.update(media, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/likes/%s/like/" % media.id,
settings=settings,
)
try:
if not self.logger is None:
self.logger.info("Like '%s' was successfully", media)
return response.json()["status"] == "ok"
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Like '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def unlike(self, media, settings=None):
if not self.logger is None:
self.logger.info("Unlike '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
self.update(media, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/likes/%s/unlike/" % media.id,
settings=settings,
)
try:
result = response.json()["status"] == "ok"
if not self.logger is None:
self.logger.info("Like '%s' was successfully", media)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Like '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def save(self, media, settings=None):
if not self.logger is None:
self.logger.info("Save '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
self.update(media, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/save/%s/save/" % media.id,
settings=settings,
)
try:
if not self.logger is None:
self.logger.info("Save '%s' was successfully", media)
return response.json()["status"] == "ok"
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Save '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def unsave(self, media, settings=None):
if not self.logger is None:
self.logger.info("Unsave '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
self.update(media, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/save/%s/unsave/" % media.id,
settings=settings,
)
try:
result = response.json()["status"] == "ok"
if not self.logger is None:
self.logger.info("Unsave '%s' was successfully", media)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Unsave '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def add_comment(self, media, text, settings=None):
if not self.logger is None:
self.logger.info("Comment '%s' started")
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if not isinstance(text, str):
raise TypeError("'text' must be str type")
if media.id is None:
self.update(media, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/comments/%s/add/" % media.id,
data={"comment_text": text},
settings=settings,
)
try:
data = response.json()
if data["status"] == "ok":
comment = Comment(
data["id"],
media=media,
owner=self,
text=data["text"],
created_at=data["created_time"],
)
else:
comment = None
if not self.logger is None:
self.logger.info("Comment '%s' was successfully", media)
return comment
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Comment '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def delete_comment(self, comment, settings=None):
if not self.logger is None:
self.logger.info("Delete comment '%s' started", comment)
if not isinstance(comment, Comment):
raise TypeError("'comment' must be Comment type")
if comment.media.id is None:
self.update(comment.media, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/p/%s/" % comment.media.code,
url="https://www.instagram.com/web/comments/%s/delete/%s/" % (
comment.media.id,
comment.id,
),
settings=settings,
)
try:
result = response.json()["status"] == "ok"
if result:
del comment
if not self.logger is None:
self.logger.info("Delete comment '%s' was successfully", comment)
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Delete comment '%s' was unsuccessfully: %s",
comment,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def follow(self, account, settings=None):
if not self.logger is None:
self.logger.info("Follow to '%s' started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type")
if account.id is None:
self.update(account, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/%s" % account.username,
url="https://www.instagram.com/web/friendships/%s/follow/" % account.id,
settings=settings,
)
try:
result = response.json()["status"] == "ok"
if not self.logger is None:
self.logger.info("Follow to '%s' was successfully", account)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Follow to '%s' was unsuccessfully: %s", account, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
def unfollow(self, account, settings=None):
if not self.logger is None:
self.logger.info("Unfollow to '%s' started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type")
if account.id is None:
self.update(account, settings=settings)
response = self.action_request(
referer="https://www.instagram.com/%s/" % account.username,
url="https://www.instagram.com/web/friendships/%s/unfollow/" % account.id,
settings=settings,
)
try:
result = response.json()["status"] == "ok"
if not self.logger is None:
self.logger.info("Unfollow to '%s' was successfully", account)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Unfollow to '%s' was unsuccessfully: %s",
account,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
class AsyncWebAgentAccount(Account, AsyncWebAgent):
def __init__(self, username, cookies=None, logger=None):
if not isinstance(username, str):
raise TypeError("'username' must be str type")
Account.__init__(self, username)
AsyncWebAgent.__init__(self, cookies=cookies, logger=logger)
def __del__(self):
Account.__del__(self)
async def delete(self):
await self.session.close()
async def auth(self, password, settings=None):
if not self.logger is None:
self.logger.info("Auth started")
if not isinstance(password, str):
raise TypeError("'password' must be str type")
if not isinstance(settings, dict) and not settings is None:
raise TypeError("'settings' must be dict type or None")
settings = dict() if settings is None else settings.copy()
await self.update(settings=settings)
if not "headers" in settings:
settings["headers"] = {}
settings["headers"].update({
"X-IG-App-ID": "936619743392459",
# "X_Instagram-AJAX": "ee72defd9231",
"X-CSRFToken": self.csrf_token,
"Referer": "https://www.instagram.com/",
})
if not "data" in settings:
settings["data"] = {}
settings["data"].update({"username": self.username, "password": password})
response = await self.post_request(
"https://www.instagram.com/accounts/login/ajax/",
**settings,
)
try:
data = await response.json()
if data.get("authenticated") is False:
raise AuthException(self.username)
elif data.get("message") == "checkpoint_required":
checkpoint_url = "https://instagram.com" + data.get("checkpoint_url")
data = await self.checkpoint_handle(
url=checkpoint_url,
settings=settings,
)
raise CheckpointException(
username=self.username,
checkpoint_url=checkpoint_url,
navigation=data["navigation"],
types=data["types"],
)
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Auth was unsuccessfully: %s", str(exception))
raise UnexpectedResponse(exception, response.url)
if not self.logger is None:
self.logger.info("Auth was successfully")
@exception_manager.decorator
async def checkpoint_handle(self, url, settings=None):
if not self.logger is None:
self.logger.info("Handle checkpoint page for '%s' started", self.username)
response = await self.get_request(url, **settings)
try:
match = re.search(
r"<script[^>]*>\s*window._sharedData\s*=\s*((?!<script>).*)\s*;\s*</script>",
await response.text(),
)
data = json.loads(match.group(1))
data = data["entry_data"]["Challenge"][0]
navigation = {
key: "https://instagram.com" + value for key, value in data["navigation"].items()
}
data = data["extraData"]["content"]
data = list(filter(lambda item: item["__typename"] == "GraphChallengePageForm", data))
data = data[0]["fields"][0]["values"]
types = []
for d in data:
types.append({"label": d["label"].lower().split(":")[0], "value": d["value"]})
if not self.logger is None:
self.logger.info("Handle checkpoint page for '%s' was successfull", self.username)
return {"navigation": navigation, "types": types}
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Handle checkpoint page for '%s' was unsuccessfull: %s",
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def checkpoint_send(self, checkpoint_url, forward_url, choice, settings=None):
if not self.logger is None:
self.logger.info("Send verify code for '%s' started", self.username)
response = await self.action_request(
referer=checkpoint_url,
url=forward_url,
data={"choice": choice},
settings=settings,
)
try:
navigation = (await response.json())["navigation"]
if not self.logger is None:
self.logger.info("Send verify code for '%s' was successfully", self.username)
return {
key: "https://instagram.com" + value for key, value in navigation.items()
}
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Send verify code by %s to '%s' was unsuccessfully: %s",
type,
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def checkpoint_replay(self, forward_url, replay_url, settings=None):
if not self.logger is None:
self.logger.info("Resend verify code for '%s' started")
response = await self.action_request(
url=replay_url,
referer=forward_url,
settings=settings,
)
try:
navigation = (await response.json())["navigation"]
if not self.logger is None:
self.logger.info("Resend verify code for '%s' was successfull")
return {
key: "https://instagram.com" + value for key, value in navigation.items()
}
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Resend verify code for '%s' was unsuccessfull: %s",
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def checkpoint(self, url, code, settings=None):
if not self.logger is None:
self.logger.info("Verify account '%s' started")
response = await self.action_request(
referer=url,
url=url,
data={"security_code": code},
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Verify account '%s' was successfull", self.username)
return result
except (AttributeError, KeyError, ValueError) as exception:
if not self.logger is None:
self.logger.error(
"Verify account '%s' was unsuccessfull: %s",
self.username,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def update(self, obj=None, settings=None):
if obj is None:
obj = self
return await AsyncWebAgent.update(self, obj, settings=settings)
@exception_manager.decorator
async def get_media(self, obj=None, pointer=None, count=12, limit=12, delay=0, settings=None):
if obj is None:
obj = self
return await AsyncWebAgent.get_media(self, obj, pointer=pointer, count=count, limit=limit,
delay=delay, settings=settings)
@exception_manager.decorator
async def get_follows(self, account=None, pointer=None, count=20, limit=50, delay=0,
settings=None):
if account is None:
account = self
if not self.logger is None:
self.logger.info("Get '%s' follows started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type or None")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(count, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
if account.id is None:
await self.update(account, settings=settings)
if pointer is None:
variables_string = '{{"id":"{id}","first":{first}}}'
else:
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
follows = []
while True:
data = {"first": min(limit, count), "id": account.id}
if not pointer is None:
data["after"] = pointer
response = await self.graphql_request(
query_hash="58712303d941c6855d4e888c5f0cd22f",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
account.base_url,
getattr(account, account.primary_key),
),
settings=settings,
)
try:
data = (await response.json())["data"]["user"]["edge_follow"]
edges = data["edges"]
page_info = data["page_info"]
account.follows_count = data["count"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
a = Account(node["username"])
a.id = node["id"]
a.profile_pic_url = node["profile_pic_url"]
a.is_verified = node["is_verified"]
a.full_name = node["full_name"]
account.follows.add(a)
follows.append(a)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
await asyncio.sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get '%s' follows was successfully", account)
return follows, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get '%s' follows was unsuccessfully: %s",
account,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def get_followers(self, account=None, pointer=None, count=20, limit=50, delay=0,
settings=None):
if account is None:
account = self
if not self.logger is None:
self.logger.info("Get '%s' followers started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type or None")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
if account.id is None:
await self.update(account, settings=settings)
if pointer is None:
variables_string = '{{"id":"{id}","first":{first}}}'
else:
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
followers = []
while True:
data = {"first": min(limit, count), "id": account.id}
if not pointer is None:
data["after"] = pointer
response = await self.graphql_request(
query_hash="37479f2b8209594dde7facb0d904896a",
variables=variables_string.format(**data),
referer="https://instagram.com/%s%s" % (
account.base_url,
getattr(account, account.primary_key),
),
settings=settings,
)
try:
data = (await response.json())["data"]["user"]["edge_followed_by"]
edges = data["edges"]
page_info = data["page_info"]
account.followers_count = data["count"]
for index in range(min(len(edges), count)):
node = edges[index]["node"]
a = Account(node["username"])
a.id = node["id"]
a.profile_pic_url = node["profile_pic_url"]
a.is_verified = node["is_verified"]
a.full_name = node["full_name"]
account.followers.add(a)
followers.append(a)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if len(edges) < count and page_info["has_next_page"]:
count = count - len(edges)
variables_string = '{{"id":"{id}","first":{first},"after":"{after}"}}'
await asyncio.sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get '%s' followers was successfully", account)
return followers, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Get '%s' followers was unsuccessfully: %s",
account,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def stories(self, settings=None):
if not self.logger is None:
self.logger.info("Get stories started")
response = await self.graphql_request(
query_hash="60b755363b5c230111347a7a4e242001",
variables='{"only_stories":true}',
referer="https://instagram.com/%s%s" % (self.base_url, getattr(self, self.primary_key)),
settings=settings,
)
try:
data = (await response.json())["data"]["user"]["feed_reels_tray"]
data = data["edge_reels_tray_to_reel"]
result = [Story(edge["node"]["id"]) for edge in data["edges"]]
if not self.logger is None:
self.logger.info("Get stories was successfully")
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get stories was unsuccessfully: %s", str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def feed(self, pointer=None, count=12, limit=50, delay=0, settings=None):
if not self.logger is None:
self.logger.info("Get feed started")
if not isinstance(pointer, str) and not pointer is None:
raise TypeError("'pointer' must be str type or None")
if not isinstance(count, int):
raise TypeError("'count' must be int type")
if not isinstance(limit, int):
raise TypeError("'limit' must be int type")
if not isinstance(delay, (int, float)):
raise TypeError("'delay' must be int or float type")
variables_string = '{{"fetch_media_item_count":{first},"fetch_media_item_cursor":"{after}",\
"fetch_comment_count":4,"fetch_like":10,"has_stories":false}}'
feed = []
while True:
response = await self.graphql_request(
query_hash="485c25657308f08317c1e4b967356828",
variables=variables_string.format(
after=pointer,
first=min(limit, count),
) if pointer else "{}",
referer="https://instagram.com/%s%s" % (
self.base_url,
getattr(self, self.post_request),
),
settings=settings,
)
try:
data = (await response.json())["data"]["user"]["edge_web_feed_timeline"]
edges = data["edges"]
page_info = data["page_info"]
length = len(edges)
for index in range(min(length, count)):
node = edges[index]["node"]
if not "shortcode" in node:
length -= 1
continue
m = Media(node["shortcode"])
m.set_data(node)
feed.append(m)
pointer = page_info["end_cursor"] if page_info["has_next_page"] else None
if length < count and page_info["has_next_page"]:
count -= length
await asyncio.sleep(delay)
else:
if not self.logger is None:
self.logger.info("Get feed was successfully")
return feed, pointer
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Get feed was unsuccessfully: %s", str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def like(self, media, settings=None):
if not self.logger is None:
self.logger.info("Like '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
await self.update(media, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/likes/%s/like/" % media.id,
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Like '%s' was successfully", media)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Like '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def unlike(self, media, settings=None):
if not self.logger is None:
self.logger.info("Unlike '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
await self.update(media, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/likes/%s/unlike/" % media.id,
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Like '%s' was successfully", media)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Like '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def save(self, media, settings=None):
if not self.logger is None:
self.logger.info("Save '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
await self.update(media, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/save/%s/save/" % media.id,
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Save '%s' was successfully", media)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Save '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def unsave(self, media, settings=None):
if not self.logger is None:
self.logger.info("Unsave '%s' started", media)
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if media.id is None:
await self.update(media, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/save/%s/unsave/" % media.id,
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Unsave '%s' was successfully", media)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Unsave '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def add_comment(self, media, text, settings=None):
if not self.logger is None:
self.logger.info("Comment '%s' started")
if not isinstance(media, Media):
raise TypeError("'media' must be Media type")
if not isinstance(text, str):
raise TypeError("'text' must be str type")
if media.id is None:
await self.update(media, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/p/%s/" % media.code,
url="https://www.instagram.com/web/comments/%s/add/" % media.id,
data={"comment_text": text},
settings=settings,
)
try:
data = await response.json()
if data["status"] == "ok":
comment = Comment(
data["id"],
media=media,
owner=self,
text=data["text"],
created_at=data["created_time"],
)
else:
comment = None
if not self.logger is None:
self.logger.info("Comment '%s' was successfully", media)
return comment
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Comment '%s' was unsuccessfully: %s", media, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def delete_comment(self, comment, settings=None):
if not self.logger is None:
self.logger.info("Delete comment '%s' started", comment)
if not isinstance(comment, Comment):
raise TypeError("'comment' must be Comment type")
if comment.media.id is None:
await self.update(comment.media, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/p/%s/" % comment.media.code,
url="https://www.instagram.com/web/comments/%s/delete/%s/" % (
comment.media.id,
comment.id,
),
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if result:
del comment
if not self.logger is None:
self.logger.info("Delete comment '%s' was successfully", comment)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Delete comment '%s' was unsuccessfully: %s",
comment,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def follow(self, account, settings=None):
if not self.logger is None:
self.logger.info("Follow to '%s' started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type")
if account.id is None:
await self.update(account, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/%s" % account.username,
url="https://www.instagram.com/web/friendships/%s/follow/" % account.id,
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Follow to '%s' was successfully", account)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error("Follow to '%s' was unsuccessfully: %s", account, str(exception))
raise UnexpectedResponse(exception, response.url)
@exception_manager.decorator
async def unfollow(self, account, settings=None):
if not self.logger is None:
self.logger.info("Unfollow to '%s' started", account)
if not isinstance(account, Account):
raise TypeError("'account' must be Account type")
if account.id is None:
await self.update(account, settings=settings)
response = await self.action_request(
referer="https://www.instagram.com/%s" % account.username,
url="https://www.instagram.com/web/friendships/%s/unfollow/" % account.id,
settings=settings,
)
try:
result = (await response.json())["status"] == "ok"
if not self.logger is None:
self.logger.info("Unfollow to '%s' was successfully", account)
return result
except (ValueError, KeyError) as exception:
if not self.logger is None:
self.logger.error(
"Unfollow to '%s' was unsuccessfully: %s",
account,
str(exception),
)
raise UnexpectedResponse(exception, response.url)
| 41.893657 | 100 | 0.536885 | 9,533 | 89,820 | 4.985524 | 0.029477 | 0.05681 | 0.030509 | 0.042292 | 0.974562 | 0.970564 | 0.966272 | 0.963473 | 0.957603 | 0.953437 | 0 | 0.008126 | 0.351959 | 89,820 | 2,143 | 101 | 41.913206 | 0.808391 | 0.001548 | 0 | 0.880406 | 0 | 0.002136 | 0.167012 | 0.026428 | 0 | 0 | 0 | 0 | 0 | 1 | 0.017085 | false | 0.004805 | 0.005339 | 0 | 0.054992 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
9085577b0abb3be366013b3c6bf71340f39b79ef | 11,509 | py | Python | src/encoded/tests/test_types_experiment.py | caseylitton/encoded | ecfb135ba84ef5cad2a71638720d782cbfc4d14a | [
"MIT"
] | null | null | null | src/encoded/tests/test_types_experiment.py | caseylitton/encoded | ecfb135ba84ef5cad2a71638720d782cbfc4d14a | [
"MIT"
] | 1 | 2018-12-14T18:00:30.000Z | 2018-12-14T18:00:30.000Z | src/encoded/tests/test_types_experiment.py | caseylitton/encoded | ecfb135ba84ef5cad2a71638720d782cbfc4d14a | [
"MIT"
] | null | null | null | import pytest
@pytest.fixture
def base_experiment(testapp, lab, award, cell_free):
item = {
'award': award['uuid'],
'lab': lab['uuid'],
'assay_term_name': 'RNA-seq',
'biosample_ontology': cell_free['uuid'],
'status': 'in progress'
}
return testapp.post_json('/experiment', item, status=201).json['@graph'][0]
def test_isogenic_replicate_type(testapp, base_experiment, donor_1, donor_2,biosample_1, biosample_2, library_1, library_2, replicate_1_1, replicate_2_1 ):
testapp.patch_json(donor_1['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult' })
testapp.patch_json(donor_1['@id'], {'sex': 'female' })
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id']})
testapp.patch_json(biosample_2['@id'], {'donor': donor_1['@id']})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'], replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['replication_type']=='isogenic'
def test_anisogenic_replicate_type_sex_age_matched(testapp, base_experiment, donor_1, donor_2,biosample_1, biosample_2, library_1, library_2, replicate_1_1, replicate_2_1 ):
testapp.patch_json(donor_1['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult'})
testapp.patch_json(donor_2['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult' })
testapp.patch_json(donor_1['@id'], {'sex': 'female' })
testapp.patch_json(donor_2['@id'], {'sex': 'female' })
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id']})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id']})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'], replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['replication_type']=='anisogenic'
def test_anisogenic_replicate_type_sex_matched(testapp, base_experiment, donor_1, donor_2,biosample_1, biosample_2, library_1, library_2, replicate_1_1, replicate_2_1 ):
testapp.patch_json(donor_1['@id'], {'age_units': 'year', 'age': '15', 'life_stage': 'adult' })
testapp.patch_json(donor_2['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult' })
testapp.patch_json(donor_1['@id'], {'sex': 'female' })
testapp.patch_json(donor_2['@id'], {'sex': 'female' })
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id']})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id']})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'], replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['replication_type']=='anisogenic'
def test_anisogenic_replicate_type_age_matched(testapp, base_experiment, donor_1, donor_2,biosample_1, biosample_2, library_1, library_2, replicate_1_1, replicate_2_1 ):
testapp.patch_json(donor_1['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult' })
testapp.patch_json(donor_2['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult' })
testapp.patch_json(donor_1['@id'], {'sex': 'female' })
testapp.patch_json(donor_2['@id'], {'sex': 'mixed' })
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id']})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id']})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'], replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['replication_type']=='anisogenic'
def test_anisogenic_replicate_type(testapp, base_experiment, donor_1, donor_2,biosample_1, biosample_2, library_1, library_2, replicate_1_1, replicate_2_1 ):
testapp.patch_json(donor_1['@id'], {'age': 'unknown' })
testapp.patch_json(donor_2['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult' })
testapp.patch_json(donor_1['@id'], {'sex': 'female' })
testapp.patch_json(donor_2['@id'], {'sex': 'unknown' })
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id']})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id']})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'], replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['replication_type']=='anisogenic'
def test_experiment_biosample_summary(testapp,
base_experiment,
donor_1,
donor_2,
biosample_1,
biosample_2,
library_1,
library_2,
treatment,
replicate_1_1,
replicate_2_1,
s2r_plus,
liver):
testapp.patch_json(donor_1['@id'], {'age_units': 'year', 'age': '55', 'life_stage': 'adult'})
testapp.patch_json(donor_2['@id'], {'age_units': 'day', 'age': '1', 'life_stage': 'child'})
testapp.patch_json(donor_1['@id'], {'sex': 'female',
"life_stage": "embryonic"})
testapp.patch_json(donor_2['@id'], {'sex': 'male'})
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id'],
'treatments': [treatment['@id']],
'biosample_ontology': s2r_plus['uuid'],
"subcellular_fraction_term_name": "nucleus",
})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id'],
'biosample_ontology': liver['uuid'],
'treatments': [treatment['@id']]})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'],
replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['biosample_summary'] == \
'S2R+ nuclear fraction and ' + \
'liver male child (1 day), treated with ethanol'
def test_experiment_biosample_summary_2(testapp,
base_experiment,
donor_1,
donor_2,
biosample_1,
biosample_2,
library_1,
library_2,
treatment,
replicate_1_1,
replicate_2_1,
liver):
testapp.patch_json(donor_1['@id'], {'age_units': 'day', 'age': '10', 'life_stage': 'child'})
testapp.patch_json(donor_2['@id'], {'age_units': 'day', 'age': '10', 'life_stage': 'child'})
testapp.patch_json(donor_1['@id'], {'sex': 'male'})
testapp.patch_json(donor_2['@id'], {'sex': 'male'})
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id'],
'biosample_ontology': liver['uuid'],
'treatments': [treatment['@id']]})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id'],
'biosample_ontology': liver['uuid']})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
testapp.patch_json(base_experiment['@id'], {'replicates': [replicate_1_1['@id'],
replicate_2_1['@id']]})
res = testapp.get(base_experiment['@id']+'@@index-data')
assert res.json['object']['biosample_summary'] == \
'liver male child (10 days) not treated and treated with ethanol'
def test_experiment_protein_tags(testapp, base_experiment, donor_1, donor_2, biosample_1, biosample_2, construct_genetic_modification, construct_genetic_modification_N, library_1, library_2, replicate_1_1, replicate_2_1):
testapp.patch_json(biosample_1['@id'], {'donor': donor_1['@id'], 'genetic_modifications': [construct_genetic_modification['@id']]})
testapp.patch_json(biosample_2['@id'], {'donor': donor_2['@id'], 'genetic_modifications': [construct_genetic_modification_N['@id']]})
testapp.patch_json(library_1['@id'], {'biosample': biosample_1['@id']})
testapp.patch_json(library_2['@id'], {'biosample': biosample_2['@id']})
testapp.patch_json(replicate_1_1['@id'], {'library': library_1['@id']})
testapp.patch_json(replicate_2_1['@id'], {'library': library_2['@id']})
protein_tags = testapp.get(
base_experiment['@id'] + '@@index-data'
).json['object']['protein_tags']
assert len(protein_tags) == 2
assert {
'name': 'eGFP',
'location': 'C-terminal',
'target': '/targets/ATF4-human/'
} in protein_tags
assert {
'name': 'eGFP',
'location': 'N-terminal',
'target': '/targets/ATF4-human/'
} in protein_tags
| 62.210811 | 221 | 0.581371 | 1,370 | 11,509 | 4.557664 | 0.071533 | 0.040839 | 0.207559 | 0.129725 | 0.903107 | 0.896381 | 0.863389 | 0.857783 | 0.842889 | 0.837764 | 0 | 0.031787 | 0.226431 | 11,509 | 184 | 222 | 62.548913 | 0.66955 | 0 | 0 | 0.710843 | 0 | 0 | 0.195847 | 0.006256 | 0 | 0 | 0 | 0 | 0.060241 | 1 | 0.054217 | false | 0 | 0.006024 | 0 | 0.066265 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
90bedbd1773ab006e5fbabfce604ba68c596e59c | 92 | py | Python | parameters_8001.py | atahaneryol/Tidenow | 2cc095d9f891b52206343822923e91aaf315cf80 | [
"BSD-3-Clause"
] | null | null | null | parameters_8001.py | atahaneryol/Tidenow | 2cc095d9f891b52206343822923e91aaf315cf80 | [
"BSD-3-Clause"
] | null | null | null | parameters_8001.py | atahaneryol/Tidenow | 2cc095d9f891b52206343822923e91aaf315cf80 | [
"BSD-3-Clause"
] | null | null | null | password="pbkdf2(1000,20,sha512)$bf141d5aebf91cc1$c0633dcbf0e84e0e8fa71f903d78208fafb7154a"
| 46 | 91 | 0.891304 | 7 | 92 | 11.714286 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.43956 | 0.01087 | 92 | 1 | 92 | 92 | 0.461538 | 0 | 0 | 0 | 0 | 0 | 0.869565 | 0.869565 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 8 |
90d496ff6027c1a2a84fa5a77ca52f4284d1145c | 283 | py | Python | jsonrpcake/compat.py | joehillen/jsonrpcake | 4a2463996dad828c6b89a8c8931f5883615bfd36 | [
"BSD-3-Clause"
] | 18 | 2015-09-03T02:50:45.000Z | 2021-01-27T03:13:24.000Z | jsonrpcake/compat.py | joehillen/jsonrpcake | 4a2463996dad828c6b89a8c8931f5883615bfd36 | [
"BSD-3-Clause"
] | 1 | 2016-08-25T12:41:22.000Z | 2017-10-03T01:08:09.000Z | jsonrpcake/compat.py | joehillen/jsonrpcake | 4a2463996dad828c6b89a8c8931f5883615bfd36 | [
"BSD-3-Clause"
] | 3 | 2017-01-12T06:33:15.000Z | 2019-01-28T20:51:31.000Z | """
Python 2/3 compatibility.
"""
#noinspection PyUnresolvedReferences
try:
#noinspection PyUnresolvedReferences,PyCompatibility
from urllib.parse import urlsplit
except ImportError:
#noinspection PyUnresolvedReferences,PyCompatibility
from urlparse import urlsplit
| 23.583333 | 56 | 0.805654 | 24 | 283 | 9.5 | 0.666667 | 0.447368 | 0.429825 | 0.464912 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.008197 | 0.137809 | 283 | 11 | 57 | 25.727273 | 0.92623 | 0.575972 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.75 | 0 | 0.75 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
29291909cec2629a4b6e60793bb700ccd5764bdd | 43,633 | py | Python | chi/plots/_time_series.py | DavAug/chi | d0bde8b18305b4ebd3e0a2c92f78dcf27f8f365f | [
"BSD-3-Clause"
] | 2 | 2021-12-09T17:35:36.000Z | 2022-03-17T13:45:06.000Z | chi/plots/_time_series.py | DavAug/chi | d0bde8b18305b4ebd3e0a2c92f78dcf27f8f365f | [
"BSD-3-Clause"
] | 30 | 2021-07-30T08:55:17.000Z | 2022-03-21T21:55:54.000Z | chi/plots/_time_series.py | DavAug/chi | d0bde8b18305b4ebd3e0a2c92f78dcf27f8f365f | [
"BSD-3-Clause"
] | 2 | 2021-08-04T15:07:21.000Z | 2021-12-15T11:42:31.000Z | #
# This file is part of the chi repository
# (https://github.com/DavAug/chi/) which is released under the
# BSD 3-clause license. See accompanying LICENSE.md for copyright notice and
# full license details.
#
import numpy as np
import pandas as pd
import plotly.colors
import plotly.graph_objects as go
from chi import plots
class PDPredictivePlot(plots.SingleFigure):
"""
A figure class that visualises the predictions of a predictive
pharmacodynamic model.
Extends :class:`SingleFigure`.
Parameters
----------
updatemenu
Boolean flag that enables or disables interactive buttons, such as a
logarithmic scale switch for the y-axis.
"""
def __init__(self, updatemenu=True):
super(PDPredictivePlot, self).__init__(updatemenu)
def _add_data_trace(self, _id, times, measurements, color):
"""
Adds scatter plot of an indiviudals pharamcodynamics to figure.
"""
self._fig.add_trace(
go.Scatter(
x=times,
y=measurements,
name="ID: %d" % _id,
showlegend=True,
mode="markers",
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))))
def _add_prediction_scatter_trace(self, times, samples):
"""
Adds scatter plot of samples from the predictive model.
"""
# Get colour (light blueish)
color = plotly.colors.qualitative.Pastel2[1]
# Add trace
self._fig.add_trace(
go.Scatter(
x=times,
y=samples,
name="Predicted samples",
showlegend=True,
mode="markers",
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))))
def _add_prediction_bulk_prob_trace(self, data):
"""
Adds the bulk probabilities as two line plots (one for upper and lower
limit) and shaded area to the figure.
"""
# Construct times that go from min to max and back to min
# (Important for shading with 'toself')
times = data['Time'].unique()
times = np.hstack([times, times[::-1]])
# Get unique bulk probabilities and sort in descending order
bulk_probs = data['Bulk probability'].unique()
bulk_probs[::-1].sort()
# Get colors (shift start a little bit, because 0th level is too light)
n_traces = len(bulk_probs)
shift = 2
colors = plotly.colors.sequential.Blues[shift:shift+n_traces]
# Add traces
for trace_id, bulk_prob in enumerate(bulk_probs):
# Get relevant upper and lower percentiles
mask = data['Bulk probability'] == bulk_prob
reduced_data = data[mask]
upper = reduced_data['Upper'].to_numpy()
lower = reduced_data['Lower'].to_numpy()
values = np.hstack([upper, lower[::-1]])
# Add trace
self._fig.add_trace(go.Scatter(
x=times,
y=values,
line=dict(width=1, color=colors[trace_id]),
fill='toself',
legendgroup='Model prediction',
name='Predictive model',
text="%s Bulk" % bulk_prob,
hoverinfo='text',
showlegend=True if trace_id == n_traces-1 else False))
def _compute_bulk_probs(self, data, bulk_probs, time_key, sample_key):
"""
Computes the upper and lower percentiles from the predictive model
samples, corresponding to the provided bulk probabilities.
"""
# Create container for perecentiles
container = pd.DataFrame(columns=[
'Time', 'Upper', 'Lower', 'Bulk probability'])
# Translate bulk probabilities into percentiles
percentiles = []
for bulk_prob in bulk_probs:
lower = 0.5 - bulk_prob / 2
upper = 0.5 + bulk_prob / 2
percentiles.append([bulk_prob, lower, upper])
# Get unique times
unique_times = data[time_key].unique()
# Fill container with percentiles for each time
for time in unique_times:
# Mask relevant data
mask = data[time_key] == time
reduced_data = data[mask]
# Get percentiles
percentile_df = reduced_data[sample_key].rank(
pct=True)
for item in percentiles:
bulk_prob, lower, upper = item
# Get biomarker value corresponding to percentiles
mask = percentile_df <= lower
biom_lower = reduced_data[mask][sample_key].max()
mask = percentile_df >= upper
biom_upper = reduced_data[mask][sample_key].min()
# Append percentiles to container
container = container.append(pd.DataFrame({
'Time': [time],
'Lower': [biom_lower],
'Upper': [biom_upper],
'Bulk probability': [str(bulk_prob)]}))
return container
def add_data(
self, data, observable=None, id_key='ID', time_key='Time',
obs_key='Observable', value_key='Value'):
"""
Adds pharmacodynamic time series data of (multiple) individuals to
the figure.
Expects a :class:`pandas.DataFrame` with an ID, a time, an
observable and a value column, and adds a scatter plot of the
measured time series to the figure. Each individual receives a
unique colour.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD data in form of
an ID, time, and observable column.
observable
The predicted observable. This argument is used to determine the
relevant rows in the dataframe. If ``None``, the first observable
in the observable column is selected.
id_key
Key label of the :class:`DataFrame` which specifies the ID column.
The ID refers to the identity of an individual. Defaults to
``'ID'``.
time_key
Key label of the :class:`DataFrame` which specifies the time
column. Defaults to ``'Time'``.
obs_key
Key label of the :class:`DataFrame` which specifies the
observable column. Defaults to ``'Observable'``.
value_key
Key label of the :class:`DataFrame` which specifies the column of
the measured values. Defaults to ``'Value'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
for key in [id_key, time_key, obs_key, value_key]:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
# Default to first bimoarker, if observable is not specified
biom_types = data[obs_key].unique()
if observable is None:
observable = biom_types[0]
if observable not in biom_types:
raise ValueError(
'The observable could not be found in the observable column.')
# Mask data for observable
mask = data[obs_key] == observable
data = data[mask]
# Get a colour scheme
colors = plotly.colors.qualitative.Plotly
n_colors = len(colors)
# Fill figure with scatter plots of individual data
ids = data[id_key].unique()
for index, _id in enumerate(ids):
# Get individual data
mask = data[id_key] == _id
times = data[time_key][mask]
measurements = data[value_key][mask]
color = colors[index % n_colors]
# Create Scatter plot
self._add_data_trace(_id, times, measurements, color)
def add_prediction(
self, data, observable=None, bulk_probs=[0.9], time_key='Time',
obs_key='Observable', value_key='Value'):
r"""
Adds the prediction to the figure.
Expects a :class:`pandas.DataFrame` with a time, an observable and a
value column. The time column determines the times of the
measurements and the value column the measured value.
The observable column determines the observable.
A list of bulk probabilities ``bulk_probs`` can be specified, which are
then added as area to the figure. The corresponding upper and lower
percentiles are estimated from the ranks of the provided
samples.
.. warning::
For low sample sizes the illustrated bulk probabilities may deviate
significantly from the theoretical bulk probabilities. The upper
and lower limit are determined from the rank of the samples for
each time point.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD simulation in
form of a time and observable column.
observable
The predicted observable. This argument is used to determine the
relevant rows in the dataframe. If ``None``, the first observable
in the observable column is selected.
bulk_probs
A list of bulk probabilities that are illustrated in the
figure. If ``None`` the samples are illustrated as a scatter plot.
time_key
Key label of the :class:`pandas.DataFrame` which specifies the time
column. Defaults to ``'Time'``.
obs_key
Key label of the :class:`pandas.DataFrame` which specifies the
observable column. Defaults to ``'Observable'``.
value_key
Key label of the :class:`pandas.DataFrame` which specifies the
value column. Defaults to ``'Value'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
for key in [time_key, obs_key, value_key]:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
# Default to first bimoarker, if observable is not specified
biom_types = data[obs_key].dropna().unique()
if observable is None:
observable = biom_types[0]
if observable not in biom_types:
raise ValueError(
'The observable could not be found in the observable column.')
# Mask data for observable
mask = data[obs_key] == observable
data = data[mask]
# Add samples as scatter plot if no bulk probabilites are provided, and
# terminate method
if bulk_probs is None:
times = data[time_key]
samples = data[value_key]
self._add_prediction_scatter_trace(times, samples)
return None
# Not more than 7 bulk probabilities are allowed (Purely aesthetic
# criterion)
if len(bulk_probs) > 7:
raise ValueError(
'At most 7 different bulk probabilities can be illustrated at '
'the same time.')
# Make sure that bulk probabilities are between 0 and 1
bulk_probs = [float(probability) for probability in bulk_probs]
for probability in bulk_probs:
if (probability < 0) or (probability > 1):
raise ValueError(
'The provided bulk probabilities have to between 0 and 1.')
# Add bulk probabilities to figure
percentile_df = self._compute_bulk_probs(
data, bulk_probs, time_key, value_key)
self._add_prediction_bulk_prob_trace(percentile_df)
class PKPredictivePlot(plots.SingleSubplotFigure):
"""
A figure class that visualises the predictions of a predictive
pharmacokinetic model.
Extends :class:`SingleSubplotFigure`.
Parameters
----------
updatemenu
Boolean flag that enables or disables interactive buttons, such as a
logarithmic scale switch for the y-axis.
"""
def __init__(self, updatemenu=True):
super(PKPredictivePlot, self).__init__()
self._create_template_figure(
rows=2, cols=1, shared_x=True, row_heights=[0.2, 0.8])
# Define legend name of prediction
self._prediction_name = 'Predictive model'
if updatemenu:
self._add_updatemenu()
def _add_dose_trace(
self, _id, times, doses, durations, color,
is_prediction=False):
"""
Adds scatter plot of dose events to figure.
"""
# Convert durations to strings
durations = [
'Dose duration: ' + str(duration) for duration in durations]
name = "ID: %s" % str(_id)
if is_prediction is True:
name = 'Predictive model'
# Add scatter plot of dose events
self._fig.add_trace(
go.Scatter(
x=times,
y=doses,
name=name,
legendgroup=name,
showlegend=False,
mode="markers",
text=durations,
hoverinfo='text',
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))),
row=1,
col=1)
def _add_biom_trace(self, _id, times, measurements, color):
"""
Adds scatter plot of an indiviudals pharamcokinetics to figure.
"""
self._fig.add_trace(
go.Scatter(
x=times,
y=measurements,
name="ID: %s" % str(_id),
legendgroup="ID: %s" % str(_id),
showlegend=True,
mode="markers",
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))),
row=2,
col=1)
def _add_updatemenu(self):
"""
Adds a button to the figure that switches the biomarker scale from
linear to logarithmic.
"""
self._fig.update_layout(
updatemenus=[
dict(
type="buttons",
direction="left",
buttons=list([
dict(
args=[{"yaxis2.type": "linear"}],
label="Linear y-scale",
method="relayout"
),
dict(
args=[{"yaxis2.type": "log"}],
label="Log y-scale",
method="relayout"
)
]),
pad={"r": 0, "t": -10},
showactive=True,
x=0.0,
xanchor="left",
y=1.15,
yanchor="top"
)
]
)
def _add_prediction_scatter_trace(self, times, samples):
"""
Adds scatter plot of samples from the predictive model.
"""
# Get colour (light blueish)
color = plotly.colors.qualitative.Pastel2[1]
# Add trace
self._fig.add_trace(
go.Scatter(
x=times,
y=samples,
name="Predicted samples",
showlegend=True,
mode="markers",
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))))
def _add_prediction_bulk_prob_trace(self, data, colors):
"""
Adds the bulk probabilities as two line plots (one for upper and lower
limit) and shaded area to the figure.
"""
# Construct times that go from min to max and back to min
# (Important for shading with 'toself')
times = data['Time'].unique()
times = np.hstack([times, times[::-1]])
# Get unique bulk probabilities and sort in descending order
bulk_probs = data['Bulk probability'].unique()
bulk_probs[::-1].sort()
# Add traces
n_traces = len(bulk_probs)
for trace_id, bulk_prob in enumerate(bulk_probs):
# Get relevant upper and lower percentiles
mask = data['Bulk probability'] == bulk_prob
reduced_data = data[mask]
upper = reduced_data['Upper'].to_numpy()
lower = reduced_data['Lower'].to_numpy()
values = np.hstack([upper, lower[::-1]])
# Add trace
self._fig.add_trace(go.Scatter(
x=times,
y=values,
line=dict(width=1, color=colors[trace_id]),
fill='toself',
legendgroup=self._prediction_name,
name=self._prediction_name,
text="%s Bulk" % bulk_prob,
hoverinfo='text',
showlegend=True if trace_id == n_traces-1 else False),
row=2,
col=1)
def _compute_bulk_probs(self, data, bulk_probs, time_key, sample_key):
"""
Computes the upper and lower percentiles from the predictive model
samples, corresponding to the provided bulk probabilities.
"""
# Create container for perecentiles
container = pd.DataFrame(columns=[
'Time', 'Upper', 'Lower', 'Bulk probability'])
# Translate bulk probabilities into percentiles
percentiles = []
for bulk_prob in bulk_probs:
lower = 0.5 - bulk_prob / 2
upper = 0.5 + bulk_prob / 2
percentiles.append([bulk_prob, lower, upper])
# Get unique times
unique_times = data[time_key].unique()
# Fill container with percentiles for each time
for time in unique_times:
# Mask relevant data
mask = data[time_key] == time
reduced_data = data[mask]
# Get percentiles
percentile_df = reduced_data[sample_key].rank(
pct=True)
for item in percentiles:
bulk_prob, lower, upper = item
# Get biomarker value corresponding to percentiles
mask = percentile_df <= lower
biom_lower = reduced_data[mask][sample_key].max()
mask = percentile_df >= upper
biom_upper = reduced_data[mask][sample_key].min()
# Append percentiles to container
container = container.append(pd.DataFrame({
'Time': [time],
'Lower': [biom_lower],
'Upper': [biom_upper],
'Bulk probability': [str(bulk_prob)]}))
return container
def add_data(
self, data, observable=None, id_key='ID', time_key='Time',
obs_key='Observable', value_key='Value', dose_key='Dose',
dose_duration_key='Duration'):
"""
Adds pharmacokinetic time series data of (multiple) individuals to
the figure.
Expects a :class:`pandas.DataFrame` with an ID, a time, an
observable and a value column, and adds a scatter plot of the
measuremed time series to the figure. The dataframe is also expected
to have information about the administered dose via a dose and a
dose duration column. Each individual receives a unique colour.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD data in form of
an ID, time, and observable column.
observable
The measured observable. This argument is used to determine the
relevant rows in the dataframe. If ``None``, the first observable
in the observable column is selected.
id_key
Key label of the :class:`DataFrame` which specifies the ID column.
The ID refers to the identity of an individual. Defaults to
``'ID'``.
time_key
Key label of the :class:`DataFrame` which specifies the time
column. Defaults to ``'Time'``.
obs_key
Key label of the :class:`DataFrame` which specifies the
observable column. Defaults to ``'Observable'``.
value_key
Key label of the :class:`DataFrame` which specifies the column of
the measured values. Defaults to ``'Value'``.
dose_key
Key label of the :class:`DataFrame` which specifies the dose
column. Defaults to ``'Dose'``.
dose_duration_key
Key label of the :class:`DataFrame` which specifies the dose
duration column. Defaults to ``'Duration'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
keys = [
id_key, time_key, obs_key, value_key, dose_key, dose_duration_key]
for key in keys:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
# Default to first bimoarker, if observable is not specified
biom_types = data[obs_key].dropna().unique()
if observable is None:
observable = biom_types[0]
if observable not in biom_types:
raise ValueError(
'The observable could not be found in the observable column.')
# Get dose information
mask = data[dose_key].notnull()
dose_data = data[mask][[id_key, time_key, dose_key, dose_duration_key]]
# Mask data for observable
mask = data[obs_key] == observable
data = data[mask][[id_key, time_key, value_key]]
# Set axis labels to dataframe keys
self.set_axis_labels(time_key, obs_key, dose_key)
# Get a colour scheme
colors = plotly.colors.qualitative.Plotly
n_colors = len(colors)
# Fill figure with scatter plots of individual data
ids = data[id_key].unique()
for index, _id in enumerate(ids):
# Get doses applied to individual
mask = dose_data[id_key] == _id
dose_times = dose_data[time_key][mask]
doses = dose_data[dose_key][mask]
durations = dose_data[dose_duration_key][mask]
# Get observable measurements
mask = data[id_key] == _id
times = data[time_key][mask]
measurements = data[value_key][mask]
# Get a color for the individual
color = colors[index % n_colors]
# Create scatter plot of dose events
self._add_dose_trace(_id, dose_times, doses, durations, color)
# Create Scatter plot
self._add_biom_trace(_id, times, measurements, color)
def add_prediction(
self, data, observable=None, bulk_probs=[0.9], time_key='Time',
obs_key='Observable', value_key='Value', dose_key='Dose',
dose_duration_key='Duration'):
r"""
Adds the prediction for the observable pharmacokinetic observable
values to the figure.
Expects a :class:`pandas.DataFrame` with a time, an observable and a
value column. The time column determines the time of the observable
measurement and the sample column the corresponding observable
measurement. The observable column determines the observable type. The
dataframe is also expected to have information about the administered
dose via a dose and a dose duration column.
A list of bulk probabilities ``bulk_probs`` can be specified, which are
then added as area to the figure. The corresponding upper and lower
percentiles are estimated from the ranks of the provided
samples.
.. warning::
For low sample sizes the illustrated bulk probabilities may deviate
significantly from the theoretical bulk probabilities. The upper
and lower limit are determined from the rank of the samples for
each time point.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD simulation in
form of a time and observable column.
observable
The predicted observable. This argument is used to determine the
relevant rows in the dataframe. If ``None``, the first observable
in the observable column is selected.
bulk_probs
A list of bulk probabilities that are illustrated in the
figure. If ``None`` the samples are illustrated as a scatter plot.
time_key
Key label of the :class:`pandas.DataFrame` which specifies the time
column. Defaults to ``'Time'``.
obs_key
Key label of the :class:`pandas.DataFrame` which specifies the
observable column. Defaults to ``'Observable'``.
value_key
Key label of the :class:`pandas.DataFrame` which specifies the
value column. Defaults to ``'Value'``.
dose_key
Key label of the :class:`DataFrame` which specifies the dose
column. Defaults to ``'Dose'``.
dose_duration_key
Key label of the :class:`DataFrame` which specifies the dose
duration column. Defaults to ``'Duration'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
keys = [
time_key, obs_key, value_key, dose_key, dose_duration_key]
for key in keys:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
# Default to first bimoarker, if observable is not specified
biom_types = data[obs_key].dropna().unique()
if observable is None:
observable = biom_types[0]
if observable not in biom_types:
raise ValueError(
'The observable could not be found in the observable column.')
# Get dose information
mask = data[dose_key].notnull()
dose_data = data[mask][[time_key, dose_key, dose_duration_key]]
# Mask data for observable
mask = data[obs_key] == observable
data = data[mask][[time_key, value_key]]
# Set axis labels to dataframe keys
self.set_axis_labels(time_key, obs_key, dose_key)
# Add samples as scatter plot if no bulk probabilites are provided, and
# terminate method
if bulk_probs is None:
times = data[time_key]
samples = data[value_key]
self._add_prediction_scatter_trace(times, samples)
return None
# Not more than 7 bulk probabilities are allowed (Purely aesthetic
# criterion)
if len(bulk_probs) > 7:
raise ValueError(
'At most 7 different bulk probabilities can be illustrated at '
'the same time.')
# Make sure that bulk probabilities are between 0 and 1
bulk_probs = [float(probability) for probability in bulk_probs]
for probability in bulk_probs:
if (probability < 0) or (probability > 1):
raise ValueError(
'The provided bulk probabilities have to between 0 and 1.')
# Define colour scheme
shift = 2
colors = plotly.colors.sequential.Blues[shift:]
# Create scatter plot of dose events
self._add_dose_trace(
_id=None,
times=dose_data[time_key],
doses=dose_data[dose_key],
durations=dose_data[dose_duration_key],
color=colors[0],
is_prediction=True)
# Add bulk probabilities to figure
percentile_df = self._compute_bulk_probs(
data, bulk_probs, time_key, value_key)
self._add_prediction_bulk_prob_trace(percentile_df, colors)
def set_axis_labels(self, time_label, biom_label, dose_label):
"""
Sets the label of the time axis, the biomarker axis, and the dose axis.
"""
self._fig.update_xaxes(title=time_label, row=2)
self._fig.update_yaxes(title=dose_label, row=1)
self._fig.update_yaxes(title=biom_label, row=2)
class PDTimeSeriesPlot(plots.SingleFigure):
"""
A figure class that visualises measurements of a pharmacodynamic
observables across multiple individuals.
Measurements of a pharmacodynamic observables over time are visualised as a
scatter plot.
Extends :class:`SingleFigure`.
Parameters
----------
updatemenu
Boolean flag that enables or disables interactive buttons, such as a
logarithmic scale switch for the y-axis.
"""
def __init__(self, updatemenu=True):
super(PDTimeSeriesPlot, self).__init__(updatemenu)
def _add_data_trace(self, _id, times, measurements, color):
"""
Adds scatter plot of an indiviudals pharamcodynamics to figure.
"""
self._fig.add_trace(
go.Scatter(
x=times,
y=measurements,
name="ID: %d" % _id,
showlegend=True,
mode="markers",
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))))
def _add_simulation_trace(self, times, biomarker):
"""
Adds scatter plot of an indiviudals pharamcodynamics to figure.
"""
self._fig.add_trace(
go.Scatter(
x=times,
y=biomarker,
name="Model",
showlegend=True,
mode="lines",
line=dict(color='black')))
def add_data(
self, data, observable=None, id_key='ID', time_key='Time',
obs_key='Observable', value_key='Value'):
"""
Adds pharmacodynamic time series data of (multiple) individuals to
the figure.
Expects a :class:`pandas.DataFrame` with an ID, a time, an
observable and a value column, and adds a scatter plot of the
measuremed time series to the figure. Each individual receives a
unique colour.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD data in form of
an ID, time, and observable column.
observable
The measured bimoarker. This argument is used to determine the
relevant rows in the dataframe. If ``None``, the first observable
in the observable column is selected.
id_key
Key label of the :class:`DataFrame` which specifies the ID column.
The ID refers to the identity of an individual. Defaults to
``'ID'``.
time_key
Key label of the :class:`DataFrame` which specifies the time
column. Defaults to ``'Time'``.
obs_key
Key label of the :class:`DataFrame` which specifies the
observable column. Defaults to ``'Observable'``.
value_key
Key label of the :class:`DataFrame` which specifies the column of
the measured values. Defaults to ``'Value'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
for key in [id_key, time_key, obs_key, value_key]:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
# Default to first bimoarker, if observable is not specified
biom_types = data[obs_key].dropna().unique()
if observable is None:
observable = biom_types[0]
if observable not in biom_types:
raise ValueError(
'The observable could not be found in the observable column.')
# Mask data for observable
mask = data[obs_key] == observable
data = data[mask]
# Get a colour scheme
colors = plotly.colors.qualitative.Plotly
n_colors = len(colors)
# Fill figure with scatter plots of individual data
ids = data[id_key].unique()
for index, _id in enumerate(ids):
# Get individual data
mask = data[id_key] == _id
times = data[time_key][mask]
measurements = data[value_key][mask]
color = colors[index % n_colors]
# Create Scatter plot
self._add_data_trace(_id, times, measurements, color)
def add_simulation(self, data, time_key='Time', value_key='Value'):
"""
Adds a pharmacodynamic time series simulation to the figure.
Expects a :class:`pandas.DataFrame` with a time and a value
column, and adds a line plot of the simulated time series to the
figure.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD simulation in
form of a time and value column.
time_key
Key label of the :class:`DataFrame` which specifies the time
column. Defaults to ``'Time'``.
value_key
Key label of the :class:`DataFrame` which specifies the
value column. Defaults to ``'Value'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
for key in [time_key, value_key]:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
times = data[time_key]
values = data[value_key]
self._add_simulation_trace(times, values)
class PKTimeSeriesPlot(plots.SingleSubplotFigure):
"""
A figure class that visualises measurements of a pharmacokinetic observable
across multiple individuals.
Measurements of a pharmacokinetic observable over time are visualised as a
scatter plot.
Extends :class:`SingleSubplotFigure`.
Parameters
----------
updatemenu
Boolean flag that enables or disables interactive buttons, such as a
logarithmic scale switch for the y-axis.
"""
def __init__(self, updatemenu=True):
super(PKTimeSeriesPlot, self).__init__()
self._create_template_figure(
rows=2, cols=1, shared_x=True, row_heights=[0.2, 0.8])
if updatemenu:
self._add_updatemenu()
def _add_dose_trace(self, _id, times, doses, durations, color):
"""
Adds scatter plot of an indiviudals pharamcodynamics to figure.
"""
# Convert durations to strings
durations = [
'Dose duration: ' + str(duration) for duration in durations]
# Add scatter plot of dose events
self._fig.add_trace(
go.Scatter(
x=times,
y=doses,
name="ID: %s" % str(_id),
legendgroup="ID: %s" % str(_id),
showlegend=False,
mode="markers",
text=durations,
hoverinfo='text',
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))),
row=1,
col=1)
def _add_biom_trace(self, _id, times, measurements, color):
"""
Adds scatter plot of an indiviudals pharamcodynamics to figure.
"""
self._fig.add_trace(
go.Scatter(
x=times,
y=measurements,
name="ID: %s" % str(_id),
legendgroup="ID: %s" % str(_id),
showlegend=True,
mode="markers",
marker=dict(
symbol='circle',
color=color,
opacity=0.7,
line=dict(color='black', width=1))),
row=2,
col=1)
def _add_updatemenu(self):
"""
Adds a button to the figure that switches the biomarker scale from
linear to logarithmic.
"""
self._fig.update_layout(
updatemenus=[
dict(
type="buttons",
direction="left",
buttons=list([
dict(
args=[{"yaxis2.type": "linear"}],
label="Linear y-scale",
method="relayout"
),
dict(
args=[{"yaxis2.type": "log"}],
label="Log y-scale",
method="relayout"
)
]),
pad={"r": 0, "t": -10},
showactive=True,
x=0.0,
xanchor="left",
y=1.15,
yanchor="top"
)
]
)
def add_data(
self, data, observable=None, id_key='ID', time_key='Time',
obs_key='Observable', value_key='Value', dose_key='Dose',
dose_duration_key='Duration'):
"""
Adds pharmacokinetic time series data of (multiple) individuals to
the figure.
Expects a :class:`pandas.DataFrame` with an ID, a time, an
observable and a value column, and adds a scatter plot of the
measuremed time series to the figure. The dataframe is also expected
to have information about the administered dose via a dose and a
dose duration column. Each individual receives a unique colour.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD data in form of
an ID, time, observable and value column.
observable
The measured bimoarker. This argument is used to determine the
relevant rows in the dataframe. If ``None``, the first observable
in the observable column is selected.
id_key
Key label of the :class:`DataFrame` which specifies the ID column.
The ID refers to the identity of an individual. Defaults to
``'ID'``.
time_key
Key label of the :class:`DataFrame` which specifies the time
column. Defaults to ``'Time'``.
obs_key
Key label of the :class:`DataFrame` which specifies the
observable column. Defaults to ``'Observable'``.
value_key
Key label of the :class:`DataFrame` which specifies the column of
the measured values. Defaults to ``'Value'``.
dose_key
Key label of the :class:`DataFrame` which specifies the dose
column. Defaults to ``'Dose'``.
dose_duration_key
Key label of the :class:`DataFrame` which specifies the dose
duration column. Defaults to ``'Duration'``.
"""
# Check input format
if not isinstance(data, pd.DataFrame):
raise TypeError(
'Data has to be pandas.DataFrame.')
keys = [
id_key, time_key, obs_key, value_key, dose_key, dose_duration_key]
for key in keys:
if key not in data.keys():
raise ValueError(
'Data does not have the key <' + str(key) + '>.')
# Default to first bimoarker, if observable is not specified
biom_types = data[obs_key].dropna().unique()
if observable is None:
observable = biom_types[0]
if observable not in biom_types:
raise ValueError(
'The observable could not be found in the observable column.')
# Get dose information
mask = data[dose_key].notnull()
dose_data = data[mask][[id_key, time_key, dose_key, dose_duration_key]]
# Mask data for observable
mask = data[obs_key] == observable
data = data[mask][[id_key, time_key, value_key]]
# Set axis labels to dataframe keys
self.set_axis_labels(time_key, obs_key, dose_key)
# Get a colour scheme
colors = plotly.colors.qualitative.Plotly
n_colors = len(colors)
# Fill figure with scatter plots of individual data
ids = data[id_key].unique()
for index, _id in enumerate(ids):
# Get doses applied to individual
mask = dose_data[id_key] == _id
dose_times = dose_data[time_key][mask]
doses = dose_data[dose_key][mask]
durations = dose_data[dose_duration_key][mask]
# Get observable measurements
mask = data[id_key] == _id
times = data[time_key][mask]
measurements = data[value_key][mask]
# Get a color for the individual
color = colors[index % n_colors]
# Create scatter plot of dose events
self._add_dose_trace(_id, dose_times, doses, durations, color)
# Create Scatter plot
self._add_biom_trace(_id, times, measurements, color)
def add_simulation(
self, data, time_key='Time', value_key='Value',
dose_key='Dose'):
"""
Adds a pharmacokinetic time series simulation to the figure.
Expects a :class:`pandas.DataFrame` with a time, a value,
and a dose column. A line plot of the biomarker time series, as well
as the dosing regimen is added to the figure.
Parameters
----------
data
A :class:`pandas.DataFrame` with the time series PD simulation in
form of a time and a value column.
time_key
Key label of the :class:`DataFrame` which specifies the time
column. Defaults to ``'Time'``.
value_key
Key label of the :class:`DataFrame` which specifies the simulated
values column. Defaults to ``'Value'``.
"""
raise NotImplementedError
def set_axis_labels(self, time_label, biom_label, dose_label):
"""
Sets the label of the time axis, the biomarker axis, and the dose axis.
"""
self._fig.update_xaxes(title=time_label, row=2)
self._fig.update_yaxes(title=dose_label, row=1)
self._fig.update_yaxes(title=biom_label, row=2)
| 36.821097 | 79 | 0.563954 | 4,993 | 43,633 | 4.808131 | 0.069898 | 0.010622 | 0.014163 | 0.017328 | 0.942142 | 0.93052 | 0.921856 | 0.917482 | 0.910401 | 0.910401 | 0 | 0.004648 | 0.354044 | 43,633 | 1,184 | 80 | 36.852196 | 0.847117 | 0.368185 | 0 | 0.875 | 0 | 0 | 0.080891 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.051786 | false | 0 | 0.008929 | 0 | 0.075 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
293aa9a32e63b2f8979d4bd960323a978bba5129 | 36 | py | Python | lib/IPCE/Lib/fepy/encoding.py | AustralianDisabilityLimited/MultiversePlatform | 7e1aad33d48b9e47f3db2ca638cb57592336ddb7 | [
"MIT"
] | 33 | 2015-02-16T02:52:08.000Z | 2022-02-18T08:46:32.000Z | lib/IPCE/Lib/fepy/encoding.py | bensku/MultiversePlatform | 7e1aad33d48b9e47f3db2ca638cb57592336ddb7 | [
"MIT"
] | 1 | 2017-09-09T18:50:23.000Z | 2020-12-29T18:13:56.000Z | lib/IPCE/Lib/fepy/encoding.py | bensku/MultiversePlatform | 7e1aad33d48b9e47f3db2ca638cb57592336ddb7 | [
"MIT"
] | 31 | 2015-02-07T16:20:24.000Z | 2022-02-23T15:02:43.000Z | def install():
import encodings
| 12 | 20 | 0.694444 | 4 | 36 | 6.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.222222 | 36 | 2 | 21 | 18 | 0.892857 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | true | 0 | 0.5 | 0 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
469f3ba6a1f04a840d5f043044918e7ab5d6a30f | 862 | py | Python | youtube_api.py | yaishenka/PedsClicker | e5b8553a86da59346c173da1bda2ea0ec96c131e | [
"MIT"
] | 1 | 2019-11-26T17:30:21.000Z | 2019-11-26T17:30:21.000Z | youtube_api.py | yaishenka/PedsClicker | e5b8553a86da59346c173da1bda2ea0ec96c131e | [
"MIT"
] | 2 | 2019-04-05T13:05:36.000Z | 2021-06-01T23:44:21.000Z | youtube_api.py | yaishenka/PewdsClicker | e5b8553a86da59346c173da1bda2ea0ec96c131e | [
"MIT"
] | null | null | null | import requests
def get_pewds_subs_count(api_key):
try:
response = requests.get(
'https://www.googleapis.com/youtube/v3/channels',
params={'part': 'statistics', 'id': 'UC-lHJZR3Gqxm24_Vd_AJ5Yw',
'key': api_key})
subs = int(response.json().get('items')[0].get('statistics').get(
'subscriberCount'))
except:
subs = 0
finally:
return subs
def get_tseries_subs_count(api_key):
try:
response = requests.get(
'https://www.googleapis.com/youtube/v3/channels',
params={'part': 'statistics', 'id': 'UCq-Fj5jknLsUf-MWSy4_brA',
'key': api_key})
subs = int(response.json().get('items')[0].get('statistics').get(
'subscriberCount'))
except:
subs = 0
finally:
return subs
| 28.733333 | 75 | 0.555684 | 94 | 862 | 4.957447 | 0.414894 | 0.051502 | 0.051502 | 0.064378 | 0.828326 | 0.828326 | 0.828326 | 0.828326 | 0.828326 | 0.828326 | 0 | 0.019737 | 0.294664 | 862 | 29 | 76 | 29.724138 | 0.746711 | 0 | 0 | 0.8 | 0 | 0 | 0.276102 | 0.055684 | 0 | 0 | 0 | 0 | 0 | 1 | 0.08 | false | 0 | 0.04 | 0 | 0.2 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d3bdf73617812a98d50f02b9a2478c4fb001f9d6 | 1,133 | py | Python | python/graphscope/nx/algorithms/tests/forward/test_traversal.py | lnfjpt/GraphScope | 917146f86d8387302a2e1de6963115e7568bf3ee | [
"Apache-2.0"
] | 1 | 2021-12-30T02:55:16.000Z | 2021-12-30T02:55:16.000Z | python/graphscope/nx/algorithms/tests/forward/test_traversal.py | lnfjpt/GraphScope | 917146f86d8387302a2e1de6963115e7568bf3ee | [
"Apache-2.0"
] | null | null | null | python/graphscope/nx/algorithms/tests/forward/test_traversal.py | lnfjpt/GraphScope | 917146f86d8387302a2e1de6963115e7568bf3ee | [
"Apache-2.0"
] | null | null | null | import networkx.algorithms.traversal.tests.test_beamsearch
import networkx.algorithms.traversal.tests.test_bfs
import networkx.algorithms.traversal.tests.test_dfs
import networkx.algorithms.traversal.tests.test_edgebfs
import networkx.algorithms.traversal.tests.test_edgedfs
import pytest
from graphscope.nx.utils.compat import import_as_graphscope_nx
import_as_graphscope_nx(networkx.algorithms.traversal.tests.test_beamsearch,
decorators=pytest.mark.usefixtures("graphscope_session"))
import_as_graphscope_nx(networkx.algorithms.traversal.tests.test_bfs,
decorators=pytest.mark.usefixtures("graphscope_session"))
import_as_graphscope_nx(networkx.algorithms.traversal.tests.test_dfs,
decorators=pytest.mark.usefixtures("graphscope_session"))
import_as_graphscope_nx(networkx.algorithms.traversal.tests.test_edgebfs,
decorators=pytest.mark.usefixtures("graphscope_session"))
import_as_graphscope_nx(networkx.algorithms.traversal.tests.test_edgedfs,
decorators=pytest.mark.usefixtures("graphscope_session"))
| 47.208333 | 81 | 0.78376 | 127 | 1,133 | 6.732283 | 0.173228 | 0.210526 | 0.315789 | 0.374269 | 0.923977 | 0.923977 | 0.552047 | 0.552047 | 0.552047 | 0.48655 | 0 | 0 | 0.134157 | 1,133 | 23 | 82 | 49.26087 | 0.87156 | 0 | 0 | 0.294118 | 0 | 0 | 0.079435 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.705882 | 0 | 0.705882 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
311a7cec7deadbd6fbdd8799f219cbaec4b43738 | 2,441 | py | Python | model/metric_functions/dense_metrics.py | fish258/MonoRec | c0612d2710802004cdd83205e63d0582de543c41 | [
"MIT"
] | 388 | 2021-05-13T08:31:36.000Z | 2022-03-31T15:50:33.000Z | model/metric_functions/dense_metrics.py | fish258/MonoRec | c0612d2710802004cdd83205e63d0582de543c41 | [
"MIT"
] | 28 | 2021-06-15T13:22:09.000Z | 2022-03-26T03:36:20.000Z | model/metric_functions/dense_metrics.py | fish258/MonoRec | c0612d2710802004cdd83205e63d0582de543c41 | [
"MIT"
] | 59 | 2021-06-16T13:47:39.000Z | 2022-03-28T01:11:21.000Z | import torch
from utils import preprocess_roi, get_positive_depth, get_absolute_depth
def sc_inv_metric(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, roi=None, max_distance=None):
"""
Computes scale inveriant metric described in (14)
:param depth_prediction: Depth prediction computed by the network
:param depth_gt: GT Depth
:param roi: Specify a region of interest on which the metric should be computed
:return: metric (mean over batch_size)
"""
depth_prediction, depth_gt = preprocess_roi(depth_prediction, depth_gt, roi)
depth_prediction, depth_gt = get_positive_depth(depth_prediction, depth_gt)
depth_prediction, depth_gt = get_absolute_depth(depth_prediction, depth_gt, max_distance)
n = depth_gt.shape[2] * depth_gt.shape[3]
E = torch.log(depth_prediction) - torch.log(depth_gt)
E[torch.isnan(E)] = 0
batch_metric = torch.sqrt(1 / n * torch.sum(E**2, dim=[2, 3]) - 1 / (n**2) * (torch.sum(E, dim=[2, 3])**2))
batch_metric[torch.isnan(batch_metric)] = 0
result = torch.mean(batch_metric)
return result
def l1_rel_metric(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, roi=None, max_distance=None):
"""
Computes the L1-rel metric described in (15)
:param depth_prediction: Depth prediction computed by the network
:param depth_gt: GT Depth
:param roi: Specify a region of interest on which the metric should be computed
:return: metric (mean over batch_size)
"""
depth_prediction, depth_gt = preprocess_roi(depth_prediction, depth_gt, roi)
depth_prediction, depth_gt = get_positive_depth(depth_prediction, depth_gt)
depth_prediction, depth_gt = get_absolute_depth(depth_prediction, depth_gt, max_distance)
return torch.mean(torch.abs(depth_prediction - depth_gt) / depth_gt)
def l1_inv_metric(depth_prediction: torch.Tensor, depth_gt: torch.Tensor, roi=None, max_distance=None):
"""
Computes the L1-inv metric described in (16)
:param depth_prediction: Depth prediction computed by the network
:param depth_gt: GT Depth
:param roi: Specify a region of interest on which the metric should be computed
:return: metric (mean over batch_size)
"""
depth_prediction, depth_gt = preprocess_roi(depth_prediction, depth_gt, roi)
depth_prediction, depth_gt = get_positive_depth(depth_prediction, depth_gt)
return torch.mean(torch.abs(depth_prediction - depth_gt)) | 45.203704 | 111 | 0.743957 | 361 | 2,441 | 4.783934 | 0.174515 | 0.243196 | 0.243196 | 0.229299 | 0.784019 | 0.781123 | 0.781123 | 0.781123 | 0.781123 | 0.72901 | 0 | 0.011291 | 0.165506 | 2,441 | 54 | 112 | 45.203704 | 0.836524 | 0.316264 | 0 | 0.363636 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.136364 | false | 0 | 0.090909 | 0 | 0.363636 | 0 | 0 | 0 | 0 | null | 1 | 1 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
315d5b1236e8faa7fbbfebb8702bd1560d8b5c4e | 2,012 | py | Python | tests/test_config.py | ONSdigital/spp-cognito-auth | 0630b4e6516db4d5715c86fef72dd2886f0b0057 | [
"MIT"
] | null | null | null | tests/test_config.py | ONSdigital/spp-cognito-auth | 0630b4e6516db4d5715c86fef72dd2886f0b0057 | [
"MIT"
] | null | null | null | tests/test_config.py | ONSdigital/spp-cognito-auth | 0630b4e6516db4d5715c86fef72dd2886f0b0057 | [
"MIT"
] | 1 | 2021-04-11T07:57:14.000Z | 2021-04-11T07:57:14.000Z | import os
from unittest import mock
from spp_cognito_auth import AuthConfig
from spp_cognito_auth.config import DEFAULT_SCOPES
@mock.patch.dict(
os.environ,
{
"CLIENT_ID": "client-id",
"CLIENT_SECRET": "client-secret",
"CALLBACK_URL": "callback-url",
"COGNITO_DOMAIN": "cognito-domain",
"COGNITO_ENDPOINT": "cognito-endpoint",
},
)
def test_from_env():
auth_config = AuthConfig.from_env()
assert auth_config.client_id == "client-id"
assert auth_config.client_secret == "client-secret"
assert auth_config.callback_url == "callback-url"
assert auth_config.cognito_domain == "cognito-domain"
assert auth_config.cognito_endpoint == "cognito-endpoint"
assert auth_config.cognito_scopes == DEFAULT_SCOPES
def test_init():
auth_config = AuthConfig(
client_id="client-id",
client_secret="client-secret",
callback_url="callback-url",
cognito_domain="cognito-domain",
cognito_endpoint="cognito-endpoint",
cognito_scopes=["cognito-scopes"],
)
assert auth_config.client_id == "client-id"
assert auth_config.client_secret == "client-secret"
assert auth_config.callback_url == "callback-url"
assert auth_config.cognito_domain == "cognito-domain"
assert auth_config.cognito_endpoint == "cognito-endpoint"
assert auth_config.cognito_scopes == ["cognito-scopes"]
def test_init_has_default_scopes():
auth_config = AuthConfig(
client_id="client-id",
client_secret="client-secret",
callback_url="callback-url",
cognito_domain="cognito-domain",
cognito_endpoint="cognito-endpoint",
)
assert auth_config.client_id == "client-id"
assert auth_config.client_secret == "client-secret"
assert auth_config.callback_url == "callback-url"
assert auth_config.cognito_domain == "cognito-domain"
assert auth_config.cognito_endpoint == "cognito-endpoint"
assert auth_config.cognito_scopes == DEFAULT_SCOPES
| 34.101695 | 61 | 0.704771 | 239 | 2,012 | 5.640167 | 0.117155 | 0.163205 | 0.21365 | 0.153561 | 0.816766 | 0.816766 | 0.816766 | 0.816766 | 0.816766 | 0.816766 | 0 | 0 | 0.182903 | 2,012 | 58 | 62 | 34.689655 | 0.819951 | 0 | 0 | 0.568627 | 0 | 0 | 0.236581 | 0 | 0 | 0 | 0 | 0 | 0.352941 | 1 | 0.058824 | false | 0 | 0.078431 | 0 | 0.137255 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
9ed21479580d8e477b56b270174a809221044f55 | 45,948 | py | Python | baseline/baseline_functions.py | slacgismo/pge-baseline-study | a521b091a23d25742a4e29c43fbfc8d2492e2b43 | [
"BSD-2-Clause"
] | null | null | null | baseline/baseline_functions.py | slacgismo/pge-baseline-study | a521b091a23d25742a4e29c43fbfc8d2492e2b43 | [
"BSD-2-Clause"
] | null | null | null | baseline/baseline_functions.py | slacgismo/pge-baseline-study | a521b091a23d25742a4e29c43fbfc8d2492e2b43 | [
"BSD-2-Clause"
] | null | null | null | from helper_functions import *
from error_functions import *
from data_get import *
from calendar_date import *
import global_vars
from datetime import datetime
# runBaseline(interval_df, DRDays, temp_df, interval, date, storage_list)
# runs baseline functions for an SAID for given day using passed in data
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# interval, int, 15 or 60, data collection interval used to find correct sql table
# date, pandas.datetime, date to run baselines on
# storage_list, list, starter list for new row
# output
# row_data, list, all data including baseline for specific SAID
def runBaseline(interval_df, DRDays, temp_df, interval, date, storage_list):
try:
maxTemp = getMaxTemp(temp_df, date)
if(global_vars.PRINTFLAG >= 2):
print("Max Temp is",maxTemp,"F")
except:
# print("Failed MaxTemp")
return 'NA'
maxTemp = str(maxTemp)
# used for time inputs
twoPM = pd.to_datetime(('14:00').strip(),format='%H:%M').time()
eightPM = pd.to_datetime(('20:00').strip(),format='%H:%M').time()
try:
errorsTTN = getTenTenNonAdjustment(interval_df, DRDays, date)
except:
return 'NA'
if errorsTTN == 'NA':
return 'NA'
try:
errorsTTA, cappedAdjustmentsErrorsTTA = getTenTenWithAdjustment(interval_df, DRDays, date, twoPM, interval)
except:
return 'NA'
if errorsTTA == 'NA':
return 'NA'
errorsThTN = getThreeTenNonAdjustment(interval_df, DRDays, date, twoPM, eightPM)
if errorsThTN == 'NA':
return 'NA'
try:
errorsThTA, cappedAdjustmentsErrorsThTA = getThreeTenWithAdjustment(interval_df, DRDays, date, twoPM, eightPM, interval)
except:
return 'NA'
if errorsThTA == 'NA':
return 'NA'
try:
errorsFN, cappedAdjustmentsErrorsFN = getFourNintyWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsFN == 'NA':
return 'NA'
if isHoliday(date):
try:
errorsF, cappedAdjustmentsErrorsF = getThreeFiveWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsF == 'NA':
return 'NA'
if(global_vars.PRINTFLAG >= 2):
print("errors", errorsF)
print("cappedAdjustmentsErrors", cappedAdjustmentsErrorsF)
try:
errorsT, cappedAdjustmentsErrorsT = getFourFourWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsT == 'NA':
return 'NA'
#bussinessday
else:
try:
errorsF, cappedAdjustmentsErrorsF = getFiveTenWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsF == 'NA':
return 'NA'
try:
errorsT, cappedAdjustmentsErrorsT = getTenTenWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsT == 'NA':
return 'NA'
today = str(datetime.now().date())
row_data = [errorsTTN[0], errorsTTN[1], errorsTTN[2], errorsTTA[0], errorsTTA[1], errorsTTA[2], cappedAdjustmentsErrorsTTA[0][0], cappedAdjustmentsErrorsTTA[0][1], cappedAdjustmentsErrorsTTA[0][2], cappedAdjustmentsErrorsTTA[1][0], cappedAdjustmentsErrorsTTA[1][1], cappedAdjustmentsErrorsTTA[1][2], cappedAdjustmentsErrorsTTA[2][0], cappedAdjustmentsErrorsTTA[2][1], cappedAdjustmentsErrorsTTA[2][2], cappedAdjustmentsErrorsTTA[3][0], cappedAdjustmentsErrorsTTA[3][1], cappedAdjustmentsErrorsTTA[3][2], cappedAdjustmentsErrorsTTA[4][0], cappedAdjustmentsErrorsTTA[4][1], cappedAdjustmentsErrorsTTA[4][2], cappedAdjustmentsErrorsTTA[5][0], cappedAdjustmentsErrorsTTA[5][1], cappedAdjustmentsErrorsTTA[5][2], cappedAdjustmentsErrorsTTA[6][0], cappedAdjustmentsErrorsTTA[6][1], cappedAdjustmentsErrorsTTA[6][2], cappedAdjustmentsErrorsTTA[7][0], cappedAdjustmentsErrorsTTA[7][1], cappedAdjustmentsErrorsTTA[7][2], cappedAdjustmentsErrorsTTA[8][0], cappedAdjustmentsErrorsTTA[8][1], cappedAdjustmentsErrorsTTA[8][2], cappedAdjustmentsErrorsTTA[9][0], cappedAdjustmentsErrorsTTA[9][1], cappedAdjustmentsErrorsTTA[9][2], cappedAdjustmentsErrorsTTA[10][0], cappedAdjustmentsErrorsTTA[10][1], cappedAdjustmentsErrorsTTA[10][2], errorsThTN[0], errorsThTN[1], errorsThTN[2], errorsThTA[0], errorsThTA[1], errorsThTA[2], cappedAdjustmentsErrorsThTA[0][0], cappedAdjustmentsErrorsThTA[0][1], cappedAdjustmentsErrorsThTA[0][2], cappedAdjustmentsErrorsThTA[1][0], cappedAdjustmentsErrorsThTA[1][1], cappedAdjustmentsErrorsThTA[1][2], cappedAdjustmentsErrorsThTA[2][0], cappedAdjustmentsErrorsThTA[2][1], cappedAdjustmentsErrorsThTA[2][2], cappedAdjustmentsErrorsThTA[3][0], cappedAdjustmentsErrorsThTA[3][1], cappedAdjustmentsErrorsThTA[3][2], cappedAdjustmentsErrorsThTA[4][0], cappedAdjustmentsErrorsThTA[4][1], cappedAdjustmentsErrorsThTA[4][2], cappedAdjustmentsErrorsThTA[5][0], cappedAdjustmentsErrorsThTA[5][1], cappedAdjustmentsErrorsThTA[5][2], cappedAdjustmentsErrorsThTA[6][0], cappedAdjustmentsErrorsThTA[6][1], cappedAdjustmentsErrorsThTA[6][2], cappedAdjustmentsErrorsThTA[7][0], cappedAdjustmentsErrorsThTA[7][1], cappedAdjustmentsErrorsThTA[7][2], cappedAdjustmentsErrorsThTA[8][0], cappedAdjustmentsErrorsThTA[8][1], cappedAdjustmentsErrorsThTA[8][2], cappedAdjustmentsErrorsThTA[9][0], cappedAdjustmentsErrorsThTA[9][1], cappedAdjustmentsErrorsThTA[9][2], cappedAdjustmentsErrorsThTA[10][0], cappedAdjustmentsErrorsThTA[10][1], cappedAdjustmentsErrorsThTA[10][2], errorsFN[0], errorsFN[1], errorsFN[2], cappedAdjustmentsErrorsFN[0][0], cappedAdjustmentsErrorsFN[0][1], cappedAdjustmentsErrorsFN[0][2], cappedAdjustmentsErrorsFN[1][0], cappedAdjustmentsErrorsFN[1][1], cappedAdjustmentsErrorsFN[1][2], cappedAdjustmentsErrorsFN[2][0], cappedAdjustmentsErrorsFN[2][1], cappedAdjustmentsErrorsFN[2][2], cappedAdjustmentsErrorsFN[3][0], cappedAdjustmentsErrorsFN[3][1], cappedAdjustmentsErrorsFN[3][2], cappedAdjustmentsErrorsFN[4][0], cappedAdjustmentsErrorsFN[4][1], cappedAdjustmentsErrorsFN[4][2], cappedAdjustmentsErrorsFN[5][0], cappedAdjustmentsErrorsFN[5][1], cappedAdjustmentsErrorsFN[5][2], cappedAdjustmentsErrorsFN[6][0], cappedAdjustmentsErrorsFN[6][1], cappedAdjustmentsErrorsFN[6][2], cappedAdjustmentsErrorsFN[7][0], cappedAdjustmentsErrorsFN[7][1], cappedAdjustmentsErrorsFN[7][2], cappedAdjustmentsErrorsFN[8][0], cappedAdjustmentsErrorsFN[8][1], cappedAdjustmentsErrorsFN[8][2], cappedAdjustmentsErrorsFN[9][0], cappedAdjustmentsErrorsFN[9][1], cappedAdjustmentsErrorsFN[9][2], cappedAdjustmentsErrorsFN[10][0], cappedAdjustmentsErrorsFN[10][1], cappedAdjustmentsErrorsFN[10][2], errorsF[0], errorsF[1], errorsF[2], cappedAdjustmentsErrorsF[0][0], cappedAdjustmentsErrorsF[0][1], cappedAdjustmentsErrorsF[0][2], cappedAdjustmentsErrorsF[1][0], cappedAdjustmentsErrorsF[1][1], cappedAdjustmentsErrorsF[1][2], cappedAdjustmentsErrorsF[2][0], cappedAdjustmentsErrorsF[2][1], cappedAdjustmentsErrorsF[2][2], cappedAdjustmentsErrorsF[3][0], cappedAdjustmentsErrorsF[3][1], cappedAdjustmentsErrorsF[3][2], cappedAdjustmentsErrorsF[4][0], cappedAdjustmentsErrorsF[4][1], cappedAdjustmentsErrorsF[4][2], cappedAdjustmentsErrorsF[5][0], cappedAdjustmentsErrorsF[5][1], cappedAdjustmentsErrorsF[5][2], cappedAdjustmentsErrorsF[6][0], cappedAdjustmentsErrorsF[6][1], cappedAdjustmentsErrorsF[6][2], cappedAdjustmentsErrorsF[7][0], cappedAdjustmentsErrorsF[7][1], cappedAdjustmentsErrorsF[7][2], cappedAdjustmentsErrorsF[8][0], cappedAdjustmentsErrorsF[8][1], cappedAdjustmentsErrorsF[8][2], cappedAdjustmentsErrorsF[9][0], cappedAdjustmentsErrorsF[9][1], cappedAdjustmentsErrorsF[9][2], cappedAdjustmentsErrorsF[10][0], cappedAdjustmentsErrorsF[10][1], cappedAdjustmentsErrorsF[10][2], errorsT[0], errorsT[1], errorsT[2], cappedAdjustmentsErrorsT[0][0], cappedAdjustmentsErrorsT[0][1], cappedAdjustmentsErrorsT[0][2], cappedAdjustmentsErrorsT[1][0], cappedAdjustmentsErrorsT[1][1], cappedAdjustmentsErrorsT[1][2], cappedAdjustmentsErrorsT[2][0], cappedAdjustmentsErrorsT[2][1], cappedAdjustmentsErrorsT[2][2], cappedAdjustmentsErrorsT[3][0], cappedAdjustmentsErrorsT[3][1], cappedAdjustmentsErrorsT[3][2], cappedAdjustmentsErrorsT[4][0], cappedAdjustmentsErrorsT[4][1], cappedAdjustmentsErrorsT[4][2], cappedAdjustmentsErrorsT[5][0], cappedAdjustmentsErrorsT[5][1], cappedAdjustmentsErrorsT[5][2], cappedAdjustmentsErrorsT[6][0], cappedAdjustmentsErrorsT[6][1], cappedAdjustmentsErrorsT[6][2], cappedAdjustmentsErrorsT[7][0], cappedAdjustmentsErrorsT[7][1], cappedAdjustmentsErrorsT[7][2], cappedAdjustmentsErrorsT[8][0], cappedAdjustmentsErrorsT[8][1], cappedAdjustmentsErrorsT[8][2], cappedAdjustmentsErrorsT[9][0], cappedAdjustmentsErrorsT[9][1], cappedAdjustmentsErrorsT[9][2], cappedAdjustmentsErrorsT[10][0], cappedAdjustmentsErrorsT[10][1], cappedAdjustmentsErrorsT[10][2]]
row_data.append(today)
row_data.insert(0, maxTemp)
# Holiday is H, Bussiness is B
if isHoliday(date):
row_data.insert(0, 'H')
else:
row_data.insert(0, 'B')
row_data.insert(0, date)
row_data.insert(0, storage_list[2])
row_data.insert(0, storage_list[1])
row_data.insert(0, storage_list[0])
if(global_vars.PRINTFLAG >= 2):
print("returning row")
return row_data
def runBaseline2(interval_df, DRDays, temp_df, interval, date, storage_list):
try:
maxTemp = getMaxTemp(temp_df, date)
if(global_vars.PRINTFLAG >= 2):
print("Max Temp is",maxTemp,"F")
except:
# print("Failed MaxTemp")
return 'NA'
maxTemp = str(maxTemp)
# used for time inputs
twoPM = pd.to_datetime(('14:00').strip(),format='%H:%M').time()
eightPM = pd.to_datetime(('20:00').strip(),format='%H:%M').time()
try:
errorsTTN = getTenTenNonAdjustment(interval_df, DRDays, date)
except:
return 'NA'
if errorsTTN == 'NA':
return 'NA'
try:
errorsTTA, cappedAdjustmentsErrorsTTA = getTenTenWithAdjustment(interval_df, DRDays, date, twoPM, interval)
except:
return 'NA'
if errorsTTA == 'NA':
return 'NA'
errorsThTN = getThreeTenNonAdjustment(interval_df, DRDays, date, twoPM, eightPM)
if errorsThTN == 'NA':
return 'NA'
try:
errorsThTA, cappedAdjustmentsErrorsThTA = getThreeTenWithAdjustment(interval_df, DRDays, date, twoPM, eightPM, interval)
except:
return 'NA'
if errorsThTA == 'NA':
return 'NA'
errorsFiveTN = getFiveTenNonAdjustment(interval_df, DRDays, date, twoPM, eightPM)
if errorsThTN == 'NA':
return 'NA'
try:
errorsFiveTA, cappedAdjustmentsErrorsFiveTA = getFiveTenWithAdjustment(interval_df, DRDays, date, twoPM, eightPM, interval)
except:
return 'NA'
if errorsThTA == 'NA':
return 'NA'
try:
errorsFN, cappedAdjustmentsErrorsFN = getFourNintyWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsFN == 'NA':
return 'NA'
if isHoliday(date):
try:
errorsF, cappedAdjustmentsErrorsF = getThreeFiveWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsF == 'NA':
return 'NA'
if(global_vars.PRINTFLAG >= 2):
print("errors", errorsF)
print("cappedAdjustmentsErrors", cappedAdjustmentsErrorsF)
try:
errorsT, cappedAdjustmentsErrorsT = getFourFourWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsT == 'NA':
return 'NA'
#bussinessday
else:
try:
errorsF, cappedAdjustmentsErrorsF = getFiveTenWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsF == 'NA':
return 'NA'
try:
errorsT, cappedAdjustmentsErrorsT = getTenTenWeather(interval_df, DRDays, temp_df, date)
except:
return 'NA'
if errorsT == 'NA':
return 'NA'
today = str(datetime.now().date())
row_data = [errorsTTN[0], errorsTTN[1], errorsTTN[2], errorsTTA[0], errorsTTA[1], errorsTTA[2], cappedAdjustmentsErrorsTTA[0][0], cappedAdjustmentsErrorsTTA[0][1], cappedAdjustmentsErrorsTTA[0][2], cappedAdjustmentsErrorsTTA[1][0], cappedAdjustmentsErrorsTTA[1][1], cappedAdjustmentsErrorsTTA[1][2], cappedAdjustmentsErrorsTTA[2][0], cappedAdjustmentsErrorsTTA[2][1], cappedAdjustmentsErrorsTTA[2][2], cappedAdjustmentsErrorsTTA[3][0], cappedAdjustmentsErrorsTTA[3][1], cappedAdjustmentsErrorsTTA[3][2], cappedAdjustmentsErrorsTTA[4][0], cappedAdjustmentsErrorsTTA[4][1], cappedAdjustmentsErrorsTTA[4][2], cappedAdjustmentsErrorsTTA[5][0], cappedAdjustmentsErrorsTTA[5][1], cappedAdjustmentsErrorsTTA[5][2], cappedAdjustmentsErrorsTTA[6][0], cappedAdjustmentsErrorsTTA[6][1], cappedAdjustmentsErrorsTTA[6][2], cappedAdjustmentsErrorsTTA[7][0], cappedAdjustmentsErrorsTTA[7][1], cappedAdjustmentsErrorsTTA[7][2], cappedAdjustmentsErrorsTTA[8][0], cappedAdjustmentsErrorsTTA[8][1], cappedAdjustmentsErrorsTTA[8][2], cappedAdjustmentsErrorsTTA[9][0], cappedAdjustmentsErrorsTTA[9][1], cappedAdjustmentsErrorsTTA[9][2], cappedAdjustmentsErrorsTTA[10][0], cappedAdjustmentsErrorsTTA[10][1], cappedAdjustmentsErrorsTTA[10][2], errorsThTN[0], errorsThTN[1], errorsThTN[2], errorsThTA[0], errorsThTA[1], errorsThTA[2], cappedAdjustmentsErrorsThTA[0][0], cappedAdjustmentsErrorsThTA[0][1], cappedAdjustmentsErrorsThTA[0][2], cappedAdjustmentsErrorsThTA[1][0], cappedAdjustmentsErrorsThTA[1][1], cappedAdjustmentsErrorsThTA[1][2], cappedAdjustmentsErrorsThTA[2][0], cappedAdjustmentsErrorsThTA[2][1], cappedAdjustmentsErrorsThTA[2][2], cappedAdjustmentsErrorsThTA[3][0], cappedAdjustmentsErrorsThTA[3][1], cappedAdjustmentsErrorsThTA[3][2], cappedAdjustmentsErrorsThTA[4][0], cappedAdjustmentsErrorsThTA[4][1], cappedAdjustmentsErrorsThTA[4][2], cappedAdjustmentsErrorsThTA[5][0], cappedAdjustmentsErrorsThTA[5][1], cappedAdjustmentsErrorsThTA[5][2], cappedAdjustmentsErrorsThTA[6][0], cappedAdjustmentsErrorsThTA[6][1], cappedAdjustmentsErrorsThTA[6][2], cappedAdjustmentsErrorsThTA[7][0], cappedAdjustmentsErrorsThTA[7][1], cappedAdjustmentsErrorsThTA[7][2], cappedAdjustmentsErrorsThTA[8][0], cappedAdjustmentsErrorsThTA[8][1], cappedAdjustmentsErrorsThTA[8][2], cappedAdjustmentsErrorsThTA[9][0], cappedAdjustmentsErrorsThTA[9][1], cappedAdjustmentsErrorsThTA[9][2], cappedAdjustmentsErrorsThTA[10][0], cappedAdjustmentsErrorsThTA[10][1], cappedAdjustmentsErrorsThTA[10][2], errorsFiveTN[0], errorsFiveTN[1], errorsFiveTN[2], errorsFiveTA[0], errorsFiveTA[1], errorsFiveTA[2], cappedAdjustmentsErrorsFiveTA[0][0], cappedAdjustmentsErrorsFiveTA[0][1], cappedAdjustmentsErrorsFiveTA[0][2], cappedAdjustmentsErrorsFiveTA[1][0], cappedAdjustmentsErrorsFiveTA[1][1], cappedAdjustmentsErrorsFiveTA[1][2], cappedAdjustmentsErrorsFiveTA[2][0], cappedAdjustmentsErrorsFiveTA[2][1], cappedAdjustmentsErrorsFiveTA[2][2], cappedAdjustmentsErrorsFiveTA[3][0], cappedAdjustmentsErrorsFiveTA[3][1], cappedAdjustmentsErrorsFiveTA[3][2], cappedAdjustmentsErrorsFiveTA[4][0], cappedAdjustmentsErrorsFiveTA[4][1], cappedAdjustmentsErrorsFiveTA[4][2], cappedAdjustmentsErrorsFiveTA[5][0], cappedAdjustmentsErrorsFiveTA[5][1], cappedAdjustmentsErrorsFiveTA[5][2], cappedAdjustmentsErrorsFiveTA[6][0], cappedAdjustmentsErrorsFiveTA[6][1], cappedAdjustmentsErrorsFiveTA[6][2], cappedAdjustmentsErrorsFiveTA[7][0], cappedAdjustmentsErrorsFiveTA[7][1], cappedAdjustmentsErrorsFiveTA[7][2], cappedAdjustmentsErrorsFiveTA[8][0], cappedAdjustmentsErrorsFiveTA[8][1], cappedAdjustmentsErrorsFiveTA[8][2], cappedAdjustmentsErrorsFiveTA[9][0], cappedAdjustmentsErrorsFiveTA[9][1], cappedAdjustmentsErrorsFiveTA[9][2], cappedAdjustmentsErrorsFiveTA[10][0], cappedAdjustmentsErrorsFiveTA[10][1], cappedAdjustmentsErrorsFiveTA[10][2], errorsFN[0], errorsFN[1], errorsFN[2], cappedAdjustmentsErrorsFN[0][0], cappedAdjustmentsErrorsFN[0][1], cappedAdjustmentsErrorsFN[0][2], cappedAdjustmentsErrorsFN[1][0], cappedAdjustmentsErrorsFN[1][1], cappedAdjustmentsErrorsFN[1][2], cappedAdjustmentsErrorsFN[2][0], cappedAdjustmentsErrorsFN[2][1], cappedAdjustmentsErrorsFN[2][2], cappedAdjustmentsErrorsFN[3][0], cappedAdjustmentsErrorsFN[3][1], cappedAdjustmentsErrorsFN[3][2], cappedAdjustmentsErrorsFN[4][0], cappedAdjustmentsErrorsFN[4][1], cappedAdjustmentsErrorsFN[4][2], cappedAdjustmentsErrorsFN[5][0], cappedAdjustmentsErrorsFN[5][1], cappedAdjustmentsErrorsFN[5][2], cappedAdjustmentsErrorsFN[6][0], cappedAdjustmentsErrorsFN[6][1], cappedAdjustmentsErrorsFN[6][2], cappedAdjustmentsErrorsFN[7][0], cappedAdjustmentsErrorsFN[7][1], cappedAdjustmentsErrorsFN[7][2], cappedAdjustmentsErrorsFN[8][0], cappedAdjustmentsErrorsFN[8][1], cappedAdjustmentsErrorsFN[8][2], cappedAdjustmentsErrorsFN[9][0], cappedAdjustmentsErrorsFN[9][1], cappedAdjustmentsErrorsFN[9][2], cappedAdjustmentsErrorsFN[10][0], cappedAdjustmentsErrorsFN[10][1], cappedAdjustmentsErrorsFN[10][2], errorsF[0], errorsF[1], errorsF[2], cappedAdjustmentsErrorsF[0][0], cappedAdjustmentsErrorsF[0][1], cappedAdjustmentsErrorsF[0][2], cappedAdjustmentsErrorsF[1][0], cappedAdjustmentsErrorsF[1][1], cappedAdjustmentsErrorsF[1][2], cappedAdjustmentsErrorsF[2][0], cappedAdjustmentsErrorsF[2][1], cappedAdjustmentsErrorsF[2][2], cappedAdjustmentsErrorsF[3][0], cappedAdjustmentsErrorsF[3][1], cappedAdjustmentsErrorsF[3][2], cappedAdjustmentsErrorsF[4][0], cappedAdjustmentsErrorsF[4][1], cappedAdjustmentsErrorsF[4][2], cappedAdjustmentsErrorsF[5][0], cappedAdjustmentsErrorsF[5][1], cappedAdjustmentsErrorsF[5][2], cappedAdjustmentsErrorsF[6][0], cappedAdjustmentsErrorsF[6][1], cappedAdjustmentsErrorsF[6][2], cappedAdjustmentsErrorsF[7][0], cappedAdjustmentsErrorsF[7][1], cappedAdjustmentsErrorsF[7][2], cappedAdjustmentsErrorsF[8][0], cappedAdjustmentsErrorsF[8][1], cappedAdjustmentsErrorsF[8][2], cappedAdjustmentsErrorsF[9][0], cappedAdjustmentsErrorsF[9][1], cappedAdjustmentsErrorsF[9][2], cappedAdjustmentsErrorsF[10][0], cappedAdjustmentsErrorsF[10][1], cappedAdjustmentsErrorsF[10][2], errorsT[0], errorsT[1], errorsT[2], cappedAdjustmentsErrorsT[0][0], cappedAdjustmentsErrorsT[0][1], cappedAdjustmentsErrorsT[0][2], cappedAdjustmentsErrorsT[1][0], cappedAdjustmentsErrorsT[1][1], cappedAdjustmentsErrorsT[1][2], cappedAdjustmentsErrorsT[2][0], cappedAdjustmentsErrorsT[2][1], cappedAdjustmentsErrorsT[2][2], cappedAdjustmentsErrorsT[3][0], cappedAdjustmentsErrorsT[3][1], cappedAdjustmentsErrorsT[3][2], cappedAdjustmentsErrorsT[4][0], cappedAdjustmentsErrorsT[4][1], cappedAdjustmentsErrorsT[4][2], cappedAdjustmentsErrorsT[5][0], cappedAdjustmentsErrorsT[5][1], cappedAdjustmentsErrorsT[5][2], cappedAdjustmentsErrorsT[6][0], cappedAdjustmentsErrorsT[6][1], cappedAdjustmentsErrorsT[6][2], cappedAdjustmentsErrorsT[7][0], cappedAdjustmentsErrorsT[7][1], cappedAdjustmentsErrorsT[7][2], cappedAdjustmentsErrorsT[8][0], cappedAdjustmentsErrorsT[8][1], cappedAdjustmentsErrorsT[8][2], cappedAdjustmentsErrorsT[9][0], cappedAdjustmentsErrorsT[9][1], cappedAdjustmentsErrorsT[9][2], cappedAdjustmentsErrorsT[10][0], cappedAdjustmentsErrorsT[10][1], cappedAdjustmentsErrorsT[10][2]]
# errorsFiveTN[0], errorsFiveTN[1], errorsFiveTN[2], errorsFiveTA[0], errorsFiveTA[1], errorsFiveTA[2], cappedAdjustmentsErrorsFiveTA[0][0], cappedAdjustmentsErrorsFiveTA[0][1], cappedAdjustmentsErrorsFiveTA[0][2], cappedAdjustmentsErrorsFiveTA[1][0], cappedAdjustmentsErrorsFiveTA[1][1], cappedAdjustmentsErrorsFiveTA[1][2], cappedAdjustmentsErrorsFiveTA[2][0], cappedAdjustmentsErrorsFiveTA[2][1], cappedAdjustmentsErrorsFiveTA[2][2], cappedAdjustmentsErrorsFiveTA[3][0], cappedAdjustmentsErrorsFiveTA[3][1], cappedAdjustmentsErrorsFiveTA[3][2], cappedAdjustmentsErrorsFiveTA[4][0], cappedAdjustmentsErrorsFiveTA[4][1], cappedAdjustmentsErrorsFiveTA[4][2], cappedAdjustmentsErrorsFiveTA[5][0], cappedAdjustmentsErrorsFiveTA[5][1], cappedAdjustmentsErrorsFiveTA[5][2], cappedAdjustmentsErrorsFiveTA[6][0], cappedAdjustmentsErrorsFiveTA[6][1], cappedAdjustmentsErrorsFiveTA[6][2], cappedAdjustmentsErrorsFiveTA[7][0], cappedAdjustmentsErrorsFiveTA[7][1], cappedAdjustmentsErrorsFiveTA[7][2], cappedAdjustmentsErrorsFiveTA[8][0], cappedAdjustmentsErrorsFiveTA[8][1], cappedAdjustmentsErrorsFiveTA[8][2], cappedAdjustmentsErrorsFiveTA[9][0], cappedAdjustmentsErrorsFiveTA[9][1], cappedAdjustmentsErrorsFiveTA[9][2], cappedAdjustmentsErrorsFiveTA[10][0], cappedAdjustmentsErrorsFiveTA[10][1], cappedAdjustmentsErrorsFiveTA[10][2],
row_data.append(today)
row_data.insert(0, maxTemp)
# Holiday is H, Bussiness is B
if isHoliday(date):
row_data.insert(0, 'H')
else:
row_data.insert(0, 'B')
row_data.insert(0, date)
row_data.insert(0, storage_list[2])
row_data.insert(0, storage_list[1])
row_data.insert(0, storage_list[0])
if(global_vars.PRINTFLAG >= 2):
print("returning row")
return row_data
# runFrequentBaseline(interval_df, DRDays, temp_df, interval, date, storage_list)
# runs baseline functions for an SAID for given day using passed in data
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# interval, int, 15 or 60, data collection interval used to find correct sql table
# date, pandas.datetime, date to run baselines on
# storage_list, list, starter list for new row
# output
# row_data, list, all data including baseline for specific SAID
def runFrequentBaseline(interval_df, DRDays, temp_df, interval, date, storage_list):
try:
maxTemp = getMaxTemp(temp_df, date)
if(global_vars.PRINTFLAG >= 2):
print("Max Temp is",maxTemp,"F")
except:
print("Might be error with python version if this prints many times, try Python 3.5.5")
return 'NA'
maxTemp = str(maxTemp)
# used for time inputs
twoAM = pd.to_datetime(('02:00').strip(),format='%H:%M').time()
fourAM = pd.to_datetime(('04:00').strip(),format='%H:%M').time()
eightAM = pd.to_datetime(('08:00').strip(),format='%H:%M').time()
tenAM = pd.to_datetime(('10:00').strip(),format='%H:%M').time()
twoPM = pd.to_datetime(('14:00').strip(),format='%H:%M').time()
fourPM = pd.to_datetime(('16:00').strip(),format='%H:%M').time()
eightPM = pd.to_datetime(('20:00').strip(),format='%H:%M').time()
tenPM = pd.to_datetime(('22:00').strip(),format='%H:%M').time()
event_times = [fourAM, eightAM, tenAM, twoPM, fourPM, eightPM, tenPM]
event_tuples = [(eightAM, tenAM), (twoPM, fourPM), (eightPM, tenPM),
(fourAM, eightAM), (tenAM, twoPM), (fourPM, eightPM),
(fourAM, tenAM), (tenAM, fourPM), (fourPM, tenPM),
(eightAM, fourPM), (twoPM, tenPM)]
# all data that will be returned for that date
row_data = []
try:
for start_time in event_times:
errorsTTA, cappedAdjustmentsErrorsTTA = getTenTenWithAdjustment(interval_df, DRDays, date, start_time, interval)
if errorsTTA == 'NA':
return 'NA'
row_data.append(errorsTTA[0])
row_data.append(errorsTTA[1])
row_data.append(errorsTTA[2])
except:
return 'NA'
try:
for (start_time, end_time) in event_tuples:
errorsThTN = getThreeTenNonAdjustment(interval_df, DRDays, date, start_time, end_time)
if errorsThTN == 'NA':
return 'NA'
row_data.append(errorsThTN[0])
row_data.append(errorsThTN[1])
row_data.append(errorsThTN[2])
except:
return 'NA'
try:
for (start_time, end_time) in event_tuples:
errorsThTA, cappedAdjustmentsErrorsThTA = getThreeTenWithAdjustment(interval_df, DRDays, date, start_time, end_time, interval)
if errorsTTA == 'NA':
return 'NA'
row_data.append(errorsThTA[0])
row_data.append(errorsThTA[1])
row_data.append(errorsThTA[2])
except:
return 'NA'
today = str(datetime.now().date())
row_data.append(today)
row_data.insert(0, maxTemp)
# Holiday is H, Bussiness is B
if isHoliday(date):
row_data.insert(0, 'H')
else:
row_data.insert(0, 'B')
row_data.insert(0, date)
row_data.insert(0, storage_list[2])
row_data.insert(0, storage_list[1])
row_data.insert(0, storage_list[0])
if(global_vars.PRINTFLAG >= 2):
print("returning row")
return row_data
def runXSPBaseline(interval_df, DRDays, temp_df, interval, date, storage_list):
# used for time inputs
twoPM = pd.to_datetime(('14:00').strip(),format='%H:%M').time()
eightPM = pd.to_datetime(('20:00').strip(),format='%H:%M').time()
try:
errorsTTN = getTenTenNonAdjustment(interval_df, DRDays, date)
except:
errorsTTN = ['NA','NA','NA']
try:
errorsTTA, cappedAdjustmentsErrorsTTA = getTenTenWithAdjustment(interval_df, DRDays, date, twoPM, interval)
except:
errorsTTA = ['NA','NA','NA']
try:
errorsThTN = getThreeTenNonAdjustment(interval_df, DRDays, date, twoPM, eightPM)
except:
errorsThTN = ['NA','NA','NA']
try:
errorsThTA, cappedAdjustmentsErrorsThTA = getThreeTenWithAdjustment(interval_df, DRDays, date, twoPM, eightPM, interval)
except:
errorsThTA = ['NA','NA','NA']
row_data = [errorsTTN[0], errorsTTN[1], errorsTTN[2], errorsTTA[0], errorsTTA[1], errorsTTA[2], errorsThTN[0], errorsThTN[1], errorsThTN[2], errorsThTA[0], errorsThTA[1], errorsThTA[2]]
return row_data
# getTenTenNonAdjustment(interval_df, DRdays, date)
# gets error rates for 10-in-10 Baseline with no adjustment
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# date, pandas.datetime, date to run baselines on
# output
# error, triple, (cv, rmse, mape)
def getTenTenNonAdjustment(interval_df, DRDays, date):
# get numpy array interval data for past 10 days and current date (11 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <= 10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA'
prediction = np.mean(numberData[0:numberData.shape[0]-1], axis=0)
actual = numberData[numberData.shape[0]-1,:]
if(global_vars.PRINTFLAG >= 2):
print("10-in-10 With No Adjustment:")
errors = getErrors(prediction, actual)
return errors
# getTenTenWithAdjustment(interval_df, DRdays, date, timeInitial, timeFinal)
# gets error rates for 10-in-10 Baseline with adjustment based on the start and end time
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# date, pandas.datetime, date to run baselines on
# eventTime, datetime.time, time of start of event
# interval, int, period between each interval measurement
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getTenTenWithAdjustment(interval_df, DRDays, date, eventTime, interval):
# get numpy array interval data for past 10 days and current date (11 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <= 10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
prediction = np.mean(numberData[0:numberData.shape[0]-1], axis=0)
actual = numberData[numberData.shape[0]-1,:]
adjustment = getAdjustment(numberData, time_indexes, eventTime, interval)
if(global_vars.PRINTFLAG >= 2):
print("10-10 With Adjustment Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, adjustment)
prediction = [data * adjustment for data in prediction]
# print("10pred", prediction)
if(global_vars.PRINTFLAG >= 2):
print("10-in-10 With Adjustment:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getThreeTenNonAdjustment(interval_df, DRdays, date)
# gets error rates for 3-in-10 Baseline (top three days of the last 10) with no adjustment
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# date, pandas.datetime, date to run baselines on
# eventStart, datetime.time, event start time
# eventEnd, datetime.time, event end time
# output
# error, triple, (cv, rmse, mape)
def getThreeTenNonAdjustment(interval_df, DRDays, date, eventStart, eventEnd):
# get numpy array interval data for past 10 days and current date (11 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <=10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
numberData = np.asarray(numberData)
eventStartTimeIndex = time_indexes.index(eventStart)
eventEndTimeIndex = time_indexes.index(eventEnd)
numberData_row_part_totals = np.sum(numberData[0:numberData.shape[0]-1, eventStartTimeIndex:eventEndTimeIndex], axis=1)
max_rows = numberData_row_part_totals.argsort()[-3:][::-1]
prediction = np.mean(numberData[max_rows], axis=0)
actual = numberData[numberData.shape[0]-1,:]
if(global_vars.PRINTFLAG >= 2):
print("3-in-10 With No Adjustment:")
errors = getErrors(prediction, actual)
return errors
# getThreeTenWithAdjustment(interval_df, DRdays, date, eventTime, interval)
# gets error rates for 3-in-10 Baseline (top three days of the last 10) with adjustment
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# date, pandas.datetime, date to run baselines on
# eventTime, datetime.time, time of start of event
# eventEnd, datetime.time, event end time
# interval, int, period between each interval measurement
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getThreeTenWithAdjustment(interval_df, DRDays, date, eventTime, eventEnd, interval):
# get numpy array interval data for past 10 days and current date (11 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <=10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
numberData = np.asarray(numberData)
eventStartTimeIndex = time_indexes.index(eventTime)
eventEndTimeIndex = time_indexes.index(eventEnd)
numberData_row_part_totals = np.sum(numberData[0:numberData.shape[0]-1, eventStartTimeIndex:eventEndTimeIndex], axis=1)
max_rows = numberData_row_part_totals.argsort()[-3:][::-1]
prediction = np.mean(numberData[max_rows], axis=0)
actual = numberData[numberData.shape[0]-1,:]
max_rows = max_rows.tolist()
max_rows.append(numberData.shape[0]-1)
# max_rows = np.vstack([max_rows, newrow])
adjustment = getAdjustment(numberData[max_rows], time_indexes, eventTime, interval)
# print("ey\n",numberData[max_rows])
# print("adjustment",adjustment)
if(global_vars.PRINTFLAG >= 2):
print("3-10 With Adjustment Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, adjustment)
if(global_vars.PRINTFLAG >= 2):
print("adjustment", adjustment)
prediction = [data * adjustment for data in prediction]
# print("3pred", prediction)
if(global_vars.PRINTFLAG >= 2):
print("3-in-10 With Adjustment:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getThreeTenNonAdjustment(interval_df, DRdays, date)
# gets error rates for 3-in-10 Baseline (top three days of the last 10) with no adjustment
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# date, pandas.datetime, date to run baselines on
# eventStart, datetime.time, event start time
# eventEnd, datetime.time, event end time
# output
# error, triple, (cv, rmse, mape)
def getFiveTenNonAdjustment(interval_df, DRDays, date, eventStart, eventEnd):
# get numpy array interval data for past 10 days and current date (11 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <=10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
numberData = np.asarray(numberData)
eventStartTimeIndex = time_indexes.index(eventStart)
eventEndTimeIndex = time_indexes.index(eventEnd)
numberData_row_part_totals = np.sum(numberData[0:numberData.shape[0]-1, eventStartTimeIndex:eventEndTimeIndex], axis=1)
max_rows = numberData_row_part_totals.argsort()[-5:][::-1]
prediction = np.mean(numberData[max_rows], axis=0)
actual = numberData[numberData.shape[0]-1,:]
if(global_vars.PRINTFLAG >= 2):
print("3-in-10 With No Adjustment:")
errors = getErrors(prediction, actual)
return errors
# getThreeTenWithAdjustment(interval_df, DRdays, date, eventTime, interval)
# gets error rates for 3-in-10 Baseline (top three days of the last 10) with adjustment
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# date, pandas.datetime, date to run baselines on
# eventTime, datetime.time, time of start of event
# eventEnd, datetime.time, event end time
# interval, int, period between each interval measurement
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getFiveTenWithAdjustment(interval_df, DRDays, date, eventTime, eventEnd, interval):
# get numpy array interval data for past 10 days and current date (11 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <=10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
numberData = np.asarray(numberData)
eventStartTimeIndex = time_indexes.index(eventTime)
eventEndTimeIndex = time_indexes.index(eventEnd)
numberData_row_part_totals = np.sum(numberData[0:numberData.shape[0]-1, eventStartTimeIndex:eventEndTimeIndex], axis=1)
max_rows = numberData_row_part_totals.argsort()[-5:][::-1]
prediction = np.mean(numberData[max_rows], axis=0)
actual = numberData[numberData.shape[0]-1,:]
max_rows = max_rows.tolist()
max_rows.append(numberData.shape[0]-1)
# max_rows = np.vstack([max_rows, newrow])
adjustment = getAdjustment(numberData[max_rows], time_indexes, eventTime, interval)
# print("ey\n",numberData[max_rows])
# print("adjustment",adjustment)
if(global_vars.PRINTFLAG >= 2):
print("3-10 With Adjustment Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, adjustment)
if(global_vars.PRINTFLAG >= 2):
print("adjustment", adjustment)
prediction = [data * adjustment for data in prediction]
# print("3pred", prediction)
if(global_vars.PRINTFLAG >= 2):
print("3-in-10 With Adjustment:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getFourNintyWeather(interval_df, DRDays, temp_df, date)
# runs 4-90 baseline function and return error. Top 4 weather days of any error
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# date, pandas.datetime, date to run baselines on
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getFourNintyWeather(interval_df, DRDays, temp_df, date):
tempHours, tempData = getPastDaysTemp(temp_df, DRDays, date, 90, False)
# print("td",len(tempData))
# print(tempData)
# Make all tempDatas in the same hour the same
tempData = adjustTimeTemp(tempHours, tempData)
# print("td",len(tempData))
# print(tempData)
# Temp measurements per day
chunksize = 48
# to split days into seperate rows
max_days_temp = []
try:
for i in range(90):
newRow = max(tempData[(i*chunksize):(i+1)*chunksize])
max_days_temp.append(newRow)
except:
return 'NA','NA'
# get index of max temps from high to low
max_days_temp = np.asarray(max_days_temp)
indexList = list(max_days_temp.argsort())
indexList.reverse()
# get numpy array interval data for past 90 days and current date (91 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 90, False)
if numberData.shape[0] <= 90:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
prediction = np.mean(numberData[indexList[:4]], axis=0)
actual = numberData[numberData.shape[0]-1,:]
if(global_vars.PRINTFLAG >= 2):
print("4-90 Weather Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, 1.51)
if(global_vars.PRINTFLAG >= 2):
print("4-90 Weather:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getFiveTenWeather(interval_df, DRDays, temp_df, date)
# runs 5-10 baseline function and return error. Top 5 weather days of any error
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# date, pandas.datetime, date to run baselines on
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getFiveTenWeather(interval_df, DRDays, temp_df, date):
tempHours, tempData = getPastDaysTemp(temp_df, DRDays, date, 10, True)
# Make all tempDatas in the same hour the same
tempData = adjustTimeTemp(tempHours, tempData)
# print("td 5-10",len(tempData),date)
# print(tempData)
# Temp measurements per day
chunksize = 48
# to split days into seperate rows
max_days_temp = []
try:
for i in range(10):
newRow = max(tempData[(i*chunksize):(i+1)*chunksize])
max_days_temp.append(newRow)
except:
return 'NA','NA'
# get index of max temps from high to low
max_days_temp = np.asarray(max_days_temp)
indexList = list(max_days_temp.argsort())
indexList.reverse()
# get numpy array interval data for past 90 days and current date (91 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
# print("5-10", numberData)
if numberData.shape[0] <= 10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
prediction = np.mean(numberData[indexList[:5]], axis=0)
actual = numberData[numberData.shape[0]-1,:]
# print("5-10", prediction)
if(global_vars.PRINTFLAG >= 2):
print("5-10 Weather Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, 1.51)
if(global_vars.PRINTFLAG >= 2):
print("5-10 Weather:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getTenTenWeather(interval_df, DRDays, temp_df, date)
# runs 10-10 baseline function and return error. Top 5 weather days of any error
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# date, pandas.datetime, date to run baselines on
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getTenTenWeather(interval_df, DRDays, temp_df, date):
tempHours, tempData = getPastDaysTemp(temp_df, DRDays, date, 10, True)
# Make all tempDatas in the same hour the same
tempData = adjustTimeTemp(tempHours, tempData)
# Temp measurements per day
chunksize = 48
# to split days into seperate rows
max_days_temp = []
try:
for i in range(10):
newRow = max(tempData[(i*chunksize):(i+1)*chunksize])
max_days_temp.append(newRow)
except:
return 'NA','NA'
# get index of max temps from high to low
max_days_temp = np.asarray(max_days_temp)
indexList = list(max_days_temp.argsort())
indexList.reverse()
# get numpy array interval data for past 90 days and current date (91 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 10, True)
if numberData.shape[0] <= 10:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
prediction = np.mean(numberData[indexList[:10]], axis=0)
actual = numberData[numberData.shape[0]-1,:]
if(global_vars.PRINTFLAG >= 2):
print("10-10 Weather Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, 1.51)
if(global_vars.PRINTFLAG >= 2):
print("10-10 Weather:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getThreeFiveWeather(interval_df, DRDays, temp_df, date)
# runs 3-5 baseline function and return error. Top 5 weather days of any error
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# date, pandas.datetime, date to run baselines on
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getThreeFiveWeather(interval_df, DRDays, temp_df, date):
tempHours, tempData = getPastDaysTemp(temp_df, DRDays, date, 5, True)
# print("td",len(tempData))
# print(tempData)
# Make all tempDatas in the same hour the same
tempData = adjustTimeTemp(tempHours, tempData)
# print("td 3-5",len(tempData), date)
# print(tempData)
# Temp measurements per day
chunksize = 48
# to split days into seperate rows
max_days_temp = []
# try:
# for i in range(5):
# newRow = max(tempData[(i*chunksize):(i+1)*chunksize])
# max_days_temp.append(newRow)
# print(max_days_temp)
# except:
# print("Oh No")
# return 'NA','NA'
for i in range(5):
newRow = max(tempData[(i*chunksize):(i+1)*chunksize])
max_days_temp.append(newRow)
# print(max_days_temp)
# get index of max temps from high to low
max_days_temp = np.asarray(max_days_temp)
indexList = list(max_days_temp.argsort())
indexList.reverse()
# get numpy array interval data for past 90 days and current date (91 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 5, True)
# print("3-5", numberData)
if numberData.shape[0] <= 5:
if(global_vars.PRINTFLAG >= 2):
print("Dataframe has only",numberData.shape[0], "days")
return 'NA','NA'
prediction = (numberData[indexList[0]]*0.5)+(numberData[indexList[1]]*0.3)+(numberData[indexList[2]]*0.2)
actual = numberData[numberData.shape[0]-1,:]
# print("3-5", prediction)
# print("3-5 a", actual)
if(global_vars.PRINTFLAG >= 2):
print("3-5 Weather Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, 1.51)
if(global_vars.PRINTFLAG >= 2):
print("3-5 Weather:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
# getFourFourWeather(interval_df, DRDays, temp_df, date)
# runs 4-4 baseline function and return error. Top 5 weather days of any error
# input
# interval_df, pandas.Dataframe, contains all interval data relevant to SAID
# DRdays, list, contains list of DR event dates in datetime form
# temp_df, pandas.Dataframe, contains all temperature data
# date, pandas.datetime, date to run baselines on
# output
# error, triple, (cv, rmse, mape)
# cappedAdjustmentsErrors,list of triples, error rates for each capped adjustment in list form
def getFourFourWeather(interval_df, DRDays, temp_df, date):
tempHours, tempData = getPastDaysTemp(temp_df, DRDays, date, 4, True)
# Make all tempDatas in the same hour the same
tempData = adjustTimeTemp(tempHours, tempData)
# Temp measurements per day
chunksize = 48
# to split days into seperate rows
max_days_temp = []
try:
for i in range(4):
newRow = max(tempData[(i*chunksize):(i+1)*chunksize])
max_days_temp.append(newRow)
except:
return 'NA','NA'
# get index of max temps from high to low
max_days_temp = np.asarray(max_days_temp)
indexList = list(max_days_temp.argsort())
indexList.reverse()
# get numpy array interval data for past 90 days and current date (91 rows)
numberData, time_indexes = getNeededDates(interval_df, DRDays, date, 4, True)
if numberData.shape[0] <= 4:
return 'NA','NA'
prediction = np.mean(numberData[indexList[:4]], axis=0)
actual = numberData[numberData.shape[0]-1,:]
if(global_vars.PRINTFLAG >= 2):
print("4-4 Weather Capped:")
# -50,-40,-30,-20,-10,0 ,10,20,30,40,50 adjustment list (no)
cappedAdjustmentsErrors = getCappedAdjustments(prediction, actual, 1.51)
if(global_vars.PRINTFLAG >= 2):
print("4-4 Weather:")
errors = getErrors(prediction, actual)
return errors, cappedAdjustmentsErrors
| 47.417957 | 7,123 | 0.737312 | 5,497 | 45,948 | 6.094415 | 0.048208 | 0.023581 | 0.031521 | 0.02388 | 0.967523 | 0.957494 | 0.946091 | 0.931942 | 0.917585 | 0.903525 | 0 | 0.039426 | 0.135 | 45,948 | 968 | 7,124 | 47.466942 | 0.803472 | 0.258618 | 0 | 0.834951 | 0 | 0 | 0.036048 | 0.001359 | 0 | 0 | 0 | 0 | 0 | 1 | 0.029126 | false | 0 | 0.01165 | 0 | 0.18835 | 0.081553 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 |
733494306ad86e62e2c458b76ef287a1de364773 | 44,089 | py | Python | sdk/agrifood/azure-agrifood-farming/azure/agrifood/farming/operations/_seasonal_fields_operations.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 2,728 | 2015-01-09T10:19:32.000Z | 2022-03-31T14:50:33.000Z | sdk/agrifood/azure-agrifood-farming/azure/agrifood/farming/operations/_seasonal_fields_operations.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 17,773 | 2015-01-05T15:57:17.000Z | 2022-03-31T23:50:25.000Z | sdk/agrifood/azure-agrifood-farming/azure/agrifood/farming/operations/_seasonal_fields_operations.py | rsdoherty/azure-sdk-for-python | 6bba5326677468e6660845a703686327178bb7b1 | [
"MIT"
] | 1,916 | 2015-01-19T05:05:41.000Z | 2022-03-31T19:36:44.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
import datetime
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRequest, HttpResponse
from azure.core.polling import LROPoller, NoPolling, PollingMethod
from azure.core.polling.base_polling import LROBasePolling
from .. import models as _models
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any, Callable, Dict, Generic, Iterable, List, Optional, TypeVar, Union
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]]
class SeasonalFieldsOperations(object):
"""SeasonalFieldsOperations operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.agrifood.farming.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
def list_by_farmer_id(
self,
farmer_id, # type: str
farm_ids=None, # type: Optional[List[str]]
field_ids=None, # type: Optional[List[str]]
season_ids=None, # type: Optional[List[str]]
crop_variety_ids=None, # type: Optional[List[str]]
crop_ids=None, # type: Optional[List[str]]
min_avg_yield_value=None, # type: Optional[float]
max_avg_yield_value=None, # type: Optional[float]
avg_yield_unit=None, # type: Optional[str]
min_avg_seed_population_value=None, # type: Optional[float]
max_avg_seed_population_value=None, # type: Optional[float]
avg_seed_population_unit=None, # type: Optional[str]
min_planting_date_time=None, # type: Optional[datetime.datetime]
max_planting_date_time=None, # type: Optional[datetime.datetime]
ids=None, # type: Optional[List[str]]
names=None, # type: Optional[List[str]]
property_filters=None, # type: Optional[List[str]]
statuses=None, # type: Optional[List[str]]
min_created_date_time=None, # type: Optional[datetime.datetime]
max_created_date_time=None, # type: Optional[datetime.datetime]
min_last_modified_date_time=None, # type: Optional[datetime.datetime]
max_last_modified_date_time=None, # type: Optional[datetime.datetime]
max_page_size=50, # type: Optional[int]
skip_token=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.SeasonalFieldListResponse"]
"""Returns a paginated list of seasonal field resources under a particular farmer.
:param farmer_id: ID of the associated farmer.
:type farmer_id: str
:param farm_ids: Farm Ids of the resource.
:type farm_ids: list[str]
:param field_ids: Field Ids of the resource.
:type field_ids: list[str]
:param season_ids: Season Ids of the resource.
:type season_ids: list[str]
:param crop_variety_ids: CropVarietyIds of the resource.
:type crop_variety_ids: list[str]
:param crop_ids: Ids of the crop it belongs to.
:type crop_ids: list[str]
:param min_avg_yield_value: Minimum average yield value of the seasonal field(inclusive).
:type min_avg_yield_value: float
:param max_avg_yield_value: Maximum average yield value of the seasonal field(inclusive).
:type max_avg_yield_value: float
:param avg_yield_unit: Unit of the average yield value attribute.
:type avg_yield_unit: str
:param min_avg_seed_population_value: Minimum average seed population value of the seasonal
field(inclusive).
:type min_avg_seed_population_value: float
:param max_avg_seed_population_value: Maximum average seed population value of the seasonal
field(inclusive).
:type max_avg_seed_population_value: float
:param avg_seed_population_unit: Unit of average seed population value attribute.
:type avg_seed_population_unit: str
:param min_planting_date_time: Minimum planting datetime, sample format: yyyy-MM-ddTHH:mm:ssZ.
:type min_planting_date_time: ~datetime.datetime
:param max_planting_date_time: Maximum planting datetime, sample format: yyyy-MM-ddTHH:mm:ssZ.
:type max_planting_date_time: ~datetime.datetime
:param ids: Ids of the resource.
:type ids: list[str]
:param names: Names of the resource.
:type names: list[str]
:param property_filters: Filters on key-value pairs within the Properties object.
eg. "{testKey} eq {testValue}".
:type property_filters: list[str]
:param statuses: Statuses of the resource.
:type statuses: list[str]
:param min_created_date_time: Minimum creation date of resource (inclusive).
:type min_created_date_time: ~datetime.datetime
:param max_created_date_time: Maximum creation date of resource (inclusive).
:type max_created_date_time: ~datetime.datetime
:param min_last_modified_date_time: Minimum last modified date of resource (inclusive).
:type min_last_modified_date_time: ~datetime.datetime
:param max_last_modified_date_time: Maximum last modified date of resource (inclusive).
:type max_last_modified_date_time: ~datetime.datetime
:param max_page_size: Maximum number of items needed (inclusive).
Minimum = 10, Maximum = 1000, Default value = 50.
:type max_page_size: int
:param skip_token: Skip token for getting next set of results.
:type skip_token: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SeasonalFieldListResponse or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.agrifood.farming.models.SeasonalFieldListResponse]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SeasonalFieldListResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list_by_farmer_id.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'farmerId': self._serialize.url("farmer_id", farmer_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if farm_ids is not None:
query_parameters['farmIds'] = [self._serialize.query("farm_ids", q, 'str') if q is not None else '' for q in farm_ids]
if field_ids is not None:
query_parameters['fieldIds'] = [self._serialize.query("field_ids", q, 'str') if q is not None else '' for q in field_ids]
if season_ids is not None:
query_parameters['seasonIds'] = [self._serialize.query("season_ids", q, 'str') if q is not None else '' for q in season_ids]
if crop_variety_ids is not None:
query_parameters['cropVarietyIds'] = [self._serialize.query("crop_variety_ids", q, 'str') if q is not None else '' for q in crop_variety_ids]
if crop_ids is not None:
query_parameters['cropIds'] = [self._serialize.query("crop_ids", q, 'str') if q is not None else '' for q in crop_ids]
if min_avg_yield_value is not None:
query_parameters['minAvgYieldValue'] = self._serialize.query("min_avg_yield_value", min_avg_yield_value, 'float')
if max_avg_yield_value is not None:
query_parameters['maxAvgYieldValue'] = self._serialize.query("max_avg_yield_value", max_avg_yield_value, 'float')
if avg_yield_unit is not None:
query_parameters['avgYieldUnit'] = self._serialize.query("avg_yield_unit", avg_yield_unit, 'str')
if min_avg_seed_population_value is not None:
query_parameters['minAvgSeedPopulationValue'] = self._serialize.query("min_avg_seed_population_value", min_avg_seed_population_value, 'float')
if max_avg_seed_population_value is not None:
query_parameters['maxAvgSeedPopulationValue'] = self._serialize.query("max_avg_seed_population_value", max_avg_seed_population_value, 'float')
if avg_seed_population_unit is not None:
query_parameters['avgSeedPopulationUnit'] = self._serialize.query("avg_seed_population_unit", avg_seed_population_unit, 'str')
if min_planting_date_time is not None:
query_parameters['minPlantingDateTime'] = self._serialize.query("min_planting_date_time", min_planting_date_time, 'iso-8601')
if max_planting_date_time is not None:
query_parameters['maxPlantingDateTime'] = self._serialize.query("max_planting_date_time", max_planting_date_time, 'iso-8601')
if ids is not None:
query_parameters['ids'] = [self._serialize.query("ids", q, 'str') if q is not None else '' for q in ids]
if names is not None:
query_parameters['names'] = [self._serialize.query("names", q, 'str') if q is not None else '' for q in names]
if property_filters is not None:
query_parameters['propertyFilters'] = [self._serialize.query("property_filters", q, 'str') if q is not None else '' for q in property_filters]
if statuses is not None:
query_parameters['statuses'] = [self._serialize.query("statuses", q, 'str') if q is not None else '' for q in statuses]
if min_created_date_time is not None:
query_parameters['minCreatedDateTime'] = self._serialize.query("min_created_date_time", min_created_date_time, 'iso-8601')
if max_created_date_time is not None:
query_parameters['maxCreatedDateTime'] = self._serialize.query("max_created_date_time", max_created_date_time, 'iso-8601')
if min_last_modified_date_time is not None:
query_parameters['minLastModifiedDateTime'] = self._serialize.query("min_last_modified_date_time", min_last_modified_date_time, 'iso-8601')
if max_last_modified_date_time is not None:
query_parameters['maxLastModifiedDateTime'] = self._serialize.query("max_last_modified_date_time", max_last_modified_date_time, 'iso-8601')
if max_page_size is not None:
query_parameters['$maxPageSize'] = self._serialize.query("max_page_size", max_page_size, 'int', maximum=1000, minimum=10)
if skip_token is not None:
query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'farmerId': self._serialize.url("farmer_id", farmer_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('SeasonalFieldListResponse', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list_by_farmer_id.metadata = {'url': '/farmers/{farmerId}/seasonal-fields'} # type: ignore
def list(
self,
farm_ids=None, # type: Optional[List[str]]
field_ids=None, # type: Optional[List[str]]
season_ids=None, # type: Optional[List[str]]
crop_variety_ids=None, # type: Optional[List[str]]
crop_ids=None, # type: Optional[List[str]]
min_avg_yield_value=None, # type: Optional[float]
max_avg_yield_value=None, # type: Optional[float]
avg_yield_unit=None, # type: Optional[str]
min_avg_seed_population_value=None, # type: Optional[float]
max_avg_seed_population_value=None, # type: Optional[float]
avg_seed_population_unit=None, # type: Optional[str]
min_planting_date_time=None, # type: Optional[datetime.datetime]
max_planting_date_time=None, # type: Optional[datetime.datetime]
ids=None, # type: Optional[List[str]]
names=None, # type: Optional[List[str]]
property_filters=None, # type: Optional[List[str]]
statuses=None, # type: Optional[List[str]]
min_created_date_time=None, # type: Optional[datetime.datetime]
max_created_date_time=None, # type: Optional[datetime.datetime]
min_last_modified_date_time=None, # type: Optional[datetime.datetime]
max_last_modified_date_time=None, # type: Optional[datetime.datetime]
max_page_size=50, # type: Optional[int]
skip_token=None, # type: Optional[str]
**kwargs # type: Any
):
# type: (...) -> Iterable["_models.SeasonalFieldListResponse"]
"""Returns a paginated list of seasonal field resources across all farmers.
:param farm_ids: Farm Ids of the resource.
:type farm_ids: list[str]
:param field_ids: Field Ids of the resource.
:type field_ids: list[str]
:param season_ids: Season Ids of the resource.
:type season_ids: list[str]
:param crop_variety_ids: CropVarietyIds of the resource.
:type crop_variety_ids: list[str]
:param crop_ids: Ids of the crop it belongs to.
:type crop_ids: list[str]
:param min_avg_yield_value: Minimum average yield value of the seasonal field(inclusive).
:type min_avg_yield_value: float
:param max_avg_yield_value: Maximum average yield value of the seasonal field(inclusive).
:type max_avg_yield_value: float
:param avg_yield_unit: Unit of the average yield value attribute.
:type avg_yield_unit: str
:param min_avg_seed_population_value: Minimum average seed population value of the seasonal
field(inclusive).
:type min_avg_seed_population_value: float
:param max_avg_seed_population_value: Maximum average seed population value of the seasonal
field(inclusive).
:type max_avg_seed_population_value: float
:param avg_seed_population_unit: Unit of average seed population value attribute.
:type avg_seed_population_unit: str
:param min_planting_date_time: Minimum planting datetime, sample format: yyyy-MM-ddTHH:mm:ssZ.
:type min_planting_date_time: ~datetime.datetime
:param max_planting_date_time: Maximum planting datetime, sample format: yyyy-MM-ddTHH:mm:ssZ.
:type max_planting_date_time: ~datetime.datetime
:param ids: Ids of the resource.
:type ids: list[str]
:param names: Names of the resource.
:type names: list[str]
:param property_filters: Filters on key-value pairs within the Properties object.
eg. "{testKey} eq {testValue}".
:type property_filters: list[str]
:param statuses: Statuses of the resource.
:type statuses: list[str]
:param min_created_date_time: Minimum creation date of resource (inclusive).
:type min_created_date_time: ~datetime.datetime
:param max_created_date_time: Maximum creation date of resource (inclusive).
:type max_created_date_time: ~datetime.datetime
:param min_last_modified_date_time: Minimum last modified date of resource (inclusive).
:type min_last_modified_date_time: ~datetime.datetime
:param max_last_modified_date_time: Maximum last modified date of resource (inclusive).
:type max_last_modified_date_time: ~datetime.datetime
:param max_page_size: Maximum number of items needed (inclusive).
Minimum = 10, Maximum = 1000, Default value = 50.
:type max_page_size: int
:param skip_token: Skip token for getting next set of results.
:type skip_token: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either SeasonalFieldListResponse or the result of cls(response)
:rtype: ~azure.core.paging.ItemPaged[~azure.agrifood.farming.models.SeasonalFieldListResponse]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SeasonalFieldListResponse"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
if farm_ids is not None:
query_parameters['farmIds'] = [self._serialize.query("farm_ids", q, 'str') if q is not None else '' for q in farm_ids]
if field_ids is not None:
query_parameters['fieldIds'] = [self._serialize.query("field_ids", q, 'str') if q is not None else '' for q in field_ids]
if season_ids is not None:
query_parameters['seasonIds'] = [self._serialize.query("season_ids", q, 'str') if q is not None else '' for q in season_ids]
if crop_variety_ids is not None:
query_parameters['cropVarietyIds'] = [self._serialize.query("crop_variety_ids", q, 'str') if q is not None else '' for q in crop_variety_ids]
if crop_ids is not None:
query_parameters['cropIds'] = [self._serialize.query("crop_ids", q, 'str') if q is not None else '' for q in crop_ids]
if min_avg_yield_value is not None:
query_parameters['minAvgYieldValue'] = self._serialize.query("min_avg_yield_value", min_avg_yield_value, 'float')
if max_avg_yield_value is not None:
query_parameters['maxAvgYieldValue'] = self._serialize.query("max_avg_yield_value", max_avg_yield_value, 'float')
if avg_yield_unit is not None:
query_parameters['avgYieldUnit'] = self._serialize.query("avg_yield_unit", avg_yield_unit, 'str')
if min_avg_seed_population_value is not None:
query_parameters['minAvgSeedPopulationValue'] = self._serialize.query("min_avg_seed_population_value", min_avg_seed_population_value, 'float')
if max_avg_seed_population_value is not None:
query_parameters['maxAvgSeedPopulationValue'] = self._serialize.query("max_avg_seed_population_value", max_avg_seed_population_value, 'float')
if avg_seed_population_unit is not None:
query_parameters['avgSeedPopulationUnit'] = self._serialize.query("avg_seed_population_unit", avg_seed_population_unit, 'str')
if min_planting_date_time is not None:
query_parameters['minPlantingDateTime'] = self._serialize.query("min_planting_date_time", min_planting_date_time, 'iso-8601')
if max_planting_date_time is not None:
query_parameters['maxPlantingDateTime'] = self._serialize.query("max_planting_date_time", max_planting_date_time, 'iso-8601')
if ids is not None:
query_parameters['ids'] = [self._serialize.query("ids", q, 'str') if q is not None else '' for q in ids]
if names is not None:
query_parameters['names'] = [self._serialize.query("names", q, 'str') if q is not None else '' for q in names]
if property_filters is not None:
query_parameters['propertyFilters'] = [self._serialize.query("property_filters", q, 'str') if q is not None else '' for q in property_filters]
if statuses is not None:
query_parameters['statuses'] = [self._serialize.query("statuses", q, 'str') if q is not None else '' for q in statuses]
if min_created_date_time is not None:
query_parameters['minCreatedDateTime'] = self._serialize.query("min_created_date_time", min_created_date_time, 'iso-8601')
if max_created_date_time is not None:
query_parameters['maxCreatedDateTime'] = self._serialize.query("max_created_date_time", max_created_date_time, 'iso-8601')
if min_last_modified_date_time is not None:
query_parameters['minLastModifiedDateTime'] = self._serialize.query("min_last_modified_date_time", min_last_modified_date_time, 'iso-8601')
if max_last_modified_date_time is not None:
query_parameters['maxLastModifiedDateTime'] = self._serialize.query("max_last_modified_date_time", max_last_modified_date_time, 'iso-8601')
if max_page_size is not None:
query_parameters['$maxPageSize'] = self._serialize.query("max_page_size", max_page_size, 'int', maximum=1000, minimum=10)
if skip_token is not None:
query_parameters['$skipToken'] = self._serialize.query("skip_token", skip_token, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
}
url = self._client.format_url(url, **path_format_arguments)
request = self._client.get(url, query_parameters, header_parameters)
return request
def extract_data(pipeline_response):
deserialized = self._deserialize('SeasonalFieldListResponse', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, iter(list_of_elem)
def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, model=error)
return pipeline_response
return ItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/seasonal-fields'} # type: ignore
def get(
self,
farmer_id, # type: str
seasonal_field_id, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.SeasonalField"
"""Gets a specified seasonal field resource under a particular farmer.
:param farmer_id: ID of the associated farmer.
:type farmer_id: str
:param seasonal_field_id: ID of the seasonal field.
:type seasonal_field_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SeasonalField, or the result of cls(response)
:rtype: ~azure.agrifood.farming.models.SeasonalField
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SeasonalField"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'farmerId': self._serialize.url("farmer_id", farmer_id, 'str'),
'seasonalFieldId': self._serialize.url("seasonal_field_id", seasonal_field_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('SeasonalField', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/farmers/{farmerId}/seasonal-fields/{seasonalFieldId}'} # type: ignore
def create_or_update(
self,
farmer_id, # type: str
seasonal_field_id, # type: str
seasonal_field=None, # type: Optional["_models.SeasonalField"]
**kwargs # type: Any
):
# type: (...) -> "_models.SeasonalField"
"""Creates or Updates a seasonal field resource under a particular farmer.
:param farmer_id: ID of the associated farmer resource.
:type farmer_id: str
:param seasonal_field_id: ID of the seasonal field resource.
:type seasonal_field_id: str
:param seasonal_field: Seasonal field resource payload to create or update.
:type seasonal_field: ~azure.agrifood.farming.models.SeasonalField
:keyword callable cls: A custom type or function that will be passed the direct response
:return: SeasonalField, or the result of cls(response)
:rtype: ~azure.agrifood.farming.models.SeasonalField
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.SeasonalField"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
content_type = kwargs.pop("content_type", "application/merge-patch+json")
accept = "application/json"
# Construct URL
url = self.create_or_update.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'farmerId': self._serialize.url("farmer_id", farmer_id, 'str'),
'seasonalFieldId': self._serialize.url("seasonal_field_id", seasonal_field_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
if seasonal_field is not None:
body_content = self._serialize.body(seasonal_field, 'SeasonalField')
else:
body_content = None
body_content_kwargs['content'] = body_content
request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
if response.status_code == 200:
deserialized = self._deserialize('SeasonalField', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('SeasonalField', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
create_or_update.metadata = {'url': '/farmers/{farmerId}/seasonal-fields/{seasonalFieldId}'} # type: ignore
def delete(
self,
farmer_id, # type: str
seasonal_field_id, # type: str
**kwargs # type: Any
):
# type: (...) -> None
"""Deletes a specified seasonal-field resource under a particular farmer.
:param farmer_id: ID of the farmer.
:type farmer_id: str
:param seasonal_field_id: ID of the seasonal field.
:type seasonal_field_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: None, or the result of cls(response)
:rtype: None
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
accept = "application/json"
# Construct URL
url = self.delete.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'farmerId': self._serialize.url("farmer_id", farmer_id, 'str'),
'seasonalFieldId': self._serialize.url("seasonal_field_id", seasonal_field_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
if cls:
return cls(pipeline_response, None, {})
delete.metadata = {'url': '/farmers/{farmerId}/seasonal-fields/{seasonalFieldId}'} # type: ignore
def get_cascade_delete_job_details(
self,
job_id, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.CascadeDeleteJob"
"""Get cascade delete job for specified seasonal field.
:param job_id: ID of the job.
:type job_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: CascadeDeleteJob, or the result of cls(response)
:rtype: ~azure.agrifood.farming.models.CascadeDeleteJob
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.CascadeDeleteJob"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
accept = "application/json"
# Construct URL
url = self.get_cascade_delete_job_details.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'jobId': self._serialize.url("job_id", job_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('CascadeDeleteJob', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get_cascade_delete_job_details.metadata = {'url': '/seasonal-fields/cascade-delete/{jobId}'} # type: ignore
def _create_cascade_delete_job_initial(
self,
job_id, # type: str
farmer_id, # type: str
seasonal_field_id, # type: str
**kwargs # type: Any
):
# type: (...) -> "_models.CascadeDeleteJob"
cls = kwargs.pop('cls', None) # type: ClsType["_models.CascadeDeleteJob"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2021-03-31-preview"
accept = "application/json"
# Construct URL
url = self._create_cascade_delete_job_initial.metadata['url'] # type: ignore
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'jobId': self._serialize.url("job_id", job_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['farmerId'] = self._serialize.query("farmer_id", farmer_id, 'str')
query_parameters['seasonalFieldId'] = self._serialize.query("seasonal_field_id", seasonal_field_id, 'str')
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.put(url, query_parameters, header_parameters)
pipeline_response = self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
error = self._deserialize.failsafe_deserialize(_models.ErrorResponse, response)
raise HttpResponseError(response=response, model=error)
deserialized = self._deserialize('CascadeDeleteJob', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_cascade_delete_job_initial.metadata = {'url': '/seasonal-fields/cascade-delete/{jobId}'} # type: ignore
def begin_create_cascade_delete_job(
self,
job_id, # type: str
farmer_id, # type: str
seasonal_field_id, # type: str
**kwargs # type: Any
):
# type: (...) -> LROPoller["_models.CascadeDeleteJob"]
"""Create a cascade delete job for specified seasonal field.
:param job_id: Job ID supplied by end user.
:type job_id: str
:param farmer_id: ID of the associated farmer.
:type farmer_id: str
:param seasonal_field_id: ID of the seasonalField to be deleted.
:type seasonal_field_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be LROBasePolling.
Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy.
:paramtype polling: bool or ~azure.core.polling.PollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of LROPoller that returns either CascadeDeleteJob or the result of cls(response)
:rtype: ~azure.core.polling.LROPoller[~azure.agrifood.farming.models.CascadeDeleteJob]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, PollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.CascadeDeleteJob"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = self._create_cascade_delete_job_initial(
job_id=job_id,
farmer_id=farmer_id,
seasonal_field_id=seasonal_field_id,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('CascadeDeleteJob', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'Endpoint': self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True),
'jobId': self._serialize.url("job_id", job_id, 'str'),
}
if polling is True: polling_method = LROBasePolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = NoPolling()
else: polling_method = polling
if cont_token:
return LROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_cascade_delete_job.metadata = {'url': '/seasonal-fields/cascade-delete/{jobId}'} # type: ignore
| 54.700993 | 171 | 0.656649 | 5,190 | 44,089 | 5.326012 | 0.070135 | 0.040446 | 0.021163 | 0.023298 | 0.876926 | 0.862094 | 0.854859 | 0.847298 | 0.845416 | 0.834744 | 0 | 0.00691 | 0.245004 | 44,089 | 805 | 172 | 54.768944 | 0.823505 | 0.295471 | 0 | 0.782 | 0 | 0 | 0.120232 | 0.043262 | 0 | 0 | 0 | 0 | 0 | 1 | 0.032 | false | 0 | 0.022 | 0 | 0.1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
b48e331d170d937a54475a9be2ca2a640d85651d | 34 | py | Python | tests/fixtures/package_with_helpers_submodule/lib/helpers.py | sergiobrr/tg2 | 401d77d82bd9daacb9444150c63bb039bf003436 | [
"MIT"
] | 812 | 2015-01-16T22:57:52.000Z | 2022-03-27T04:49:40.000Z | tests/fixtures/package_with_helpers_submodule/lib/helpers.py | sergiobrr/tg2 | 401d77d82bd9daacb9444150c63bb039bf003436 | [
"MIT"
] | 74 | 2015-02-18T17:55:31.000Z | 2021-12-13T10:41:08.000Z | tests/fixtures/package_with_helpers_submodule/lib/helpers.py | sergiobrr/tg2 | 401d77d82bd9daacb9444150c63bb039bf003436 | [
"MIT"
] | 72 | 2015-06-10T06:02:45.000Z | 2022-03-27T08:37:24.000Z |
def get_text():
return 'HI!!' | 11.333333 | 17 | 0.558824 | 5 | 34 | 3.6 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.235294 | 34 | 3 | 17 | 11.333333 | 0.692308 | 0 | 0 | 0 | 0 | 0 | 0.117647 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.5 | true | 0 | 0 | 0.5 | 1 | 0 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 1 | 1 | 0 | 0 | 7 |
81ea454e9a5ae00b1bec440bb112dc062b265cc9 | 31,001 | py | Python | sdk/cognitiveservices/azure-cognitiveservices-vision-face/azure/cognitiveservices/vision/face/operations/_face_list_operations.py | vincenttran-msft/azure-sdk-for-python | 348b56f9f03eeb3f7b502eed51daf494ffff874d | [
"MIT"
] | 2,728 | 2015-01-09T10:19:32.000Z | 2022-03-31T14:50:33.000Z | sdk/cognitiveservices/azure-cognitiveservices-vision-face/azure/cognitiveservices/vision/face/operations/_face_list_operations.py | v-xuto/azure-sdk-for-python | 9c6296d22094c5ede410bc83749e8df8694ccacc | [
"MIT"
] | 17,773 | 2015-01-05T15:57:17.000Z | 2022-03-31T23:50:25.000Z | sdk/cognitiveservices/azure-cognitiveservices-vision-face/azure/cognitiveservices/vision/face/operations/_face_list_operations.py | v-xuto/azure-sdk-for-python | 9c6296d22094c5ede410bc83749e8df8694ccacc | [
"MIT"
] | 1,916 | 2015-01-19T05:05:41.000Z | 2022-03-31T19:36:44.000Z | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.pipeline import ClientRawResponse
from .. import models
class FaceListOperations(object):
"""FaceListOperations operations.
You should not instantiate directly this class, but create a Client instance that will create it for you and attach it as attribute.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = models
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
def create(
self, face_list_id, name, user_data=None, recognition_model="recognition_01", custom_headers=None, raw=False, **operation_config):
"""Create an empty face list with user-specified faceListId, name, an
optional userData and recognitionModel. Up to 64 face lists are allowed
in one subscription.
<br /> Face list is a list of faces, up to 1,000 faces, and used by
[Face - Find
Similar](https://docs.microsoft.com/rest/api/faceapi/face/findsimilar).
<br /> After creation, user should use [FaceList - Add
Face](https://docs.microsoft.com/rest/api/faceapi/facelist/addfacefromurl)
to import the faces. No image will be stored. Only the extracted face
features are stored on server until [FaceList -
Delete](https://docs.microsoft.com/rest/api/faceapi/facelist/delete) is
called.
<br /> Find Similar is used for scenario like finding celebrity-like
faces, similar face filtering, or as a light way face identification.
But if the actual use is to identify person, please use
[PersonGroup](https://docs.microsoft.com/rest/api/faceapi/persongroup)
/
[LargePersonGroup](https://docs.microsoft.com/rest/api/faceapi/largepersongroup)
and [Face -
Identify](https://docs.microsoft.com/rest/api/faceapi/face/identify).
<br /> Please consider
[LargeFaceList](https://docs.microsoft.com/rest/api/faceapi/largefacelist)
when the face number is large. It can support up to 1,000,000 faces.
<br />'recognitionModel' should be specified to associate with this
face list. The default value for 'recognitionModel' is
'recognition_01', if the latest model needed, please explicitly specify
the model you need in this parameter. New faces that are added to an
existing face list will use the recognition model that's already
associated with the collection. Existing face features in a face list
can't be updated to features extracted by another version of
recognition model.
Please Refer to [Specify a face recognition
model](https://docs.microsoft.com/azure/cognitive-services/face/face-api-how-to-topics/specify-recognition-model).
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param name: User defined name, maximum length is 128.
:type name: str
:param user_data: User specified data. Length should not exceed 16KB.
:type user_data: str
:param recognition_model: Possible values include: 'recognition_01',
'recognition_02', 'recognition_03', 'recognition_04'
:type recognition_model: str or
~azure.cognitiveservices.vision.face.models.RecognitionModel
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
body = models.MetaDataContract(name=name, user_data=user_data, recognition_model=recognition_model)
# Construct URL
url = self.create.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(body, 'MetaDataContract')
# Construct and send request
request = self._client.put(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
create.metadata = {'url': '/facelists/{faceListId}'}
def get(
self, face_list_id, return_recognition_model=False, custom_headers=None, raw=False, **operation_config):
"""Retrieve a face list’s faceListId, name, userData, recognitionModel and
faces in the face list.
.
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param return_recognition_model: A value indicating whether the
operation should return 'recognitionModel' in response.
:type return_recognition_model: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: FaceList or ClientRawResponse if raw=true
:rtype: ~azure.cognitiveservices.vision.face.models.FaceList or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
# Construct URL
url = self.get.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if return_recognition_model is not None:
query_parameters['returnRecognitionModel'] = self._serialize.query("return_recognition_model", return_recognition_model, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('FaceList', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
get.metadata = {'url': '/facelists/{faceListId}'}
def update(
self, face_list_id, name=None, user_data=None, custom_headers=None, raw=False, **operation_config):
"""Update information of a face list.
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param name: User defined name, maximum length is 128.
:type name: str
:param user_data: User specified data. Length should not exceed 16KB.
:type user_data: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
body = models.NameAndUserDataContract(name=name, user_data=user_data)
# Construct URL
url = self.update.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(body, 'NameAndUserDataContract')
# Construct and send request
request = self._client.patch(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
update.metadata = {'url': '/facelists/{faceListId}'}
def delete(
self, face_list_id, custom_headers=None, raw=False, **operation_config):
"""Delete a specified face list.
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
# Construct URL
url = self.delete.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete.metadata = {'url': '/facelists/{faceListId}'}
def list(
self, return_recognition_model=False, custom_headers=None, raw=False, **operation_config):
"""List face lists’ faceListId, name, userData and recognitionModel. <br
/>
To get face information inside faceList use [FaceList -
Get](https://docs.microsoft.com/rest/api/faceapi/facelist/get)
.
:param return_recognition_model: A value indicating whether the
operation should return 'recognitionModel' in response.
:type return_recognition_model: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: list or ClientRawResponse if raw=true
:rtype: list[~azure.cognitiveservices.vision.face.models.FaceList] or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
# Construct URL
url = self.list.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True)
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if return_recognition_model is not None:
query_parameters['returnRecognitionModel'] = self._serialize.query("return_recognition_model", return_recognition_model, 'bool')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('[FaceList]', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
list.metadata = {'url': '/facelists'}
def delete_face(
self, face_list_id, persisted_face_id, custom_headers=None, raw=False, **operation_config):
"""Delete a face from a face list by specified faceListId and
persistedFaceId.
<br /> Adding/deleting faces to/from a same face list are processed
sequentially and to/from different face lists are in parallel.
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param persisted_face_id: Id referencing a particular persistedFaceId
of an existing face.
:type persisted_face_id: str
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: None or ClientRawResponse if raw=true
:rtype: None or ~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
# Construct URL
url = self.delete_face.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$'),
'persistedFaceId': self._serialize.url("persisted_face_id", persisted_face_id, 'str')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.delete(url, query_parameters, header_parameters)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
delete_face.metadata = {'url': '/facelists/{faceListId}/persistedfaces/{persistedFaceId}'}
def add_face_from_url(
self, face_list_id, url, user_data=None, target_face=None, detection_model="detection_01", custom_headers=None, raw=False, **operation_config):
"""Add a face to a specified face list, up to 1,000 faces.
<br /> To deal with an image contains multiple faces, input face can be
specified as an image with a targetFace rectangle. It returns a
persistedFaceId representing the added face. No image will be stored.
Only the extracted face feature will be stored on server until
[FaceList - Delete
Face](https://docs.microsoft.com/rest/api/faceapi/facelist/deleteface)
or [FaceList -
Delete](https://docs.microsoft.com/rest/api/faceapi/facelist/delete) is
called.
<br /> Note persistedFaceId is different from faceId generated by [Face
-
Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl).
* Higher face image quality means better detection and recognition
precision. Please consider high-quality faces: frontal, clear, and face
size is 200x200 pixels (100 pixels between eyes) or bigger.
* JPEG, PNG, GIF (the first frame), and BMP format are supported. The
allowed image file size is from 1KB to 6MB.
* "targetFace" rectangle should contain one face. Zero or multiple
faces will be regarded as an error. If the provided "targetFace"
rectangle is not returned from [Face -
Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl),
there’s no guarantee to detect and add the face successfully.
* Out of detectable face size (36x36 - 4096x4096 pixels), large
head-pose, or large occlusions will cause failures.
* Adding/deleting faces to/from a same face list are processed
sequentially and to/from different face lists are in parallel.
* The minimum detectable face size is 36x36 pixels in an image no
larger than 1920x1080 pixels. Images with dimensions higher than
1920x1080 pixels will need a proportionally larger minimum face size.
* Different 'detectionModel' values can be provided. To use and compare
different detection models, please refer to [How to specify a detection
model](https://docs.microsoft.com/azure/cognitive-services/face/face-api-how-to-topics/specify-detection-model).
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param url: Publicly reachable URL of an image
:type url: str
:param user_data: User-specified data about the face for any purpose.
The maximum length is 1KB.
:type user_data: str
:param target_face: A face rectangle to specify the target face to be
added to a person in the format of "targetFace=left,top,width,height".
E.g. "targetFace=10,10,100,100". If there is more than one face in the
image, targetFace is required to specify which face to add. No
targetFace means there is only one face detected in the entire image.
:type target_face: list[int]
:param detection_model: Name of detection model. Detection model is
used to detect faces in the submitted image. A detection model name
can be provided when performing Face - Detect or (Large)FaceList - Add
Face or (Large)PersonGroup - Add Face. The default value is
'detection_01', if another model is needed, please explicitly specify
it. Possible values include: 'detection_01', 'detection_02',
'detection_03'
:type detection_model: str or
~azure.cognitiveservices.vision.face.models.DetectionModel
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PersistedFace or ClientRawResponse if raw=true
:rtype: ~azure.cognitiveservices.vision.face.models.PersistedFace or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
image_url = models.ImageUrl(url=url)
# Construct URL
url = self.add_face_from_url.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if user_data is not None:
query_parameters['userData'] = self._serialize.query("user_data", user_data, 'str', max_length=1024)
if target_face is not None:
query_parameters['targetFace'] = self._serialize.query("target_face", target_face, '[int]', div=',')
if detection_model is not None:
query_parameters['detectionModel'] = self._serialize.query("detection_model", detection_model, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(image_url, 'ImageUrl')
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PersistedFace', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
add_face_from_url.metadata = {'url': '/facelists/{faceListId}/persistedfaces'}
def add_face_from_stream(
self, face_list_id, image, user_data=None, target_face=None, detection_model="detection_01", custom_headers=None, raw=False, callback=None, **operation_config):
"""Add a face to a specified face list, up to 1,000 faces.
<br /> To deal with an image contains multiple faces, input face can be
specified as an image with a targetFace rectangle. It returns a
persistedFaceId representing the added face. No image will be stored.
Only the extracted face feature will be stored on server until
[FaceList - Delete
Face](https://docs.microsoft.com/rest/api/faceapi/facelist/deleteface)
or [FaceList -
Delete](https://docs.microsoft.com/rest/api/faceapi/facelist/delete) is
called.
<br /> Note persistedFaceId is different from faceId generated by [Face
-
Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl).
* Higher face image quality means better detection and recognition
precision. Please consider high-quality faces: frontal, clear, and face
size is 200x200 pixels (100 pixels between eyes) or bigger.
* JPEG, PNG, GIF (the first frame), and BMP format are supported. The
allowed image file size is from 1KB to 6MB.
* "targetFace" rectangle should contain one face. Zero or multiple
faces will be regarded as an error. If the provided "targetFace"
rectangle is not returned from [Face -
Detect](https://docs.microsoft.com/rest/api/faceapi/face/detectwithurl),
there’s no guarantee to detect and add the face successfully.
* Out of detectable face size (36x36 - 4096x4096 pixels), large
head-pose, or large occlusions will cause failures.
* Adding/deleting faces to/from a same face list are processed
sequentially and to/from different face lists are in parallel.
* The minimum detectable face size is 36x36 pixels in an image no
larger than 1920x1080 pixels. Images with dimensions higher than
1920x1080 pixels will need a proportionally larger minimum face size.
* Different 'detectionModel' values can be provided. To use and compare
different detection models, please refer to [How to specify a detection
model](https://docs.microsoft.com/azure/cognitive-services/face/face-api-how-to-topics/specify-detection-model).
:param face_list_id: Id referencing a particular face list.
:type face_list_id: str
:param image: An image stream.
:type image: Generator
:param user_data: User-specified data about the face for any purpose.
The maximum length is 1KB.
:type user_data: str
:param target_face: A face rectangle to specify the target face to be
added to a person in the format of "targetFace=left,top,width,height".
E.g. "targetFace=10,10,100,100". If there is more than one face in the
image, targetFace is required to specify which face to add. No
targetFace means there is only one face detected in the entire image.
:type target_face: list[int]
:param detection_model: Name of detection model. Detection model is
used to detect faces in the submitted image. A detection model name
can be provided when performing Face - Detect or (Large)FaceList - Add
Face or (Large)PersonGroup - Add Face. The default value is
'detection_01', if another model is needed, please explicitly specify
it. Possible values include: 'detection_01', 'detection_02',
'detection_03'
:type detection_model: str or
~azure.cognitiveservices.vision.face.models.DetectionModel
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param callback: When specified, will be called with each chunk of
data that is streamed. The callback should take two arguments, the
bytes of the current chunk of data and the response object. If the
data is uploading, response will be None.
:type callback: Callable[Bytes, response=None]
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:return: PersistedFace or ClientRawResponse if raw=true
:rtype: ~azure.cognitiveservices.vision.face.models.PersistedFace or
~msrest.pipeline.ClientRawResponse
:raises:
:class:`APIErrorException<azure.cognitiveservices.vision.face.models.APIErrorException>`
"""
# Construct URL
url = self.add_face_from_stream.metadata['url']
path_format_arguments = {
'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True),
'faceListId': self._serialize.url("face_list_id", face_list_id, 'str', max_length=64, pattern=r'^[a-z0-9-_]+$')
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {}
if user_data is not None:
query_parameters['userData'] = self._serialize.query("user_data", user_data, 'str', max_length=1024)
if target_face is not None:
query_parameters['targetFace'] = self._serialize.query("target_face", target_face, '[int]', div=',')
if detection_model is not None:
query_parameters['detectionModel'] = self._serialize.query("detection_model", detection_model, 'str')
# Construct headers
header_parameters = {}
header_parameters['Accept'] = 'application/json'
header_parameters['Content-Type'] = 'application/octet-stream'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._client.stream_upload(image, callback)
# Construct and send request
request = self._client.post(url, query_parameters, header_parameters, body_content)
response = self._client.send(request, stream=False, **operation_config)
if response.status_code not in [200]:
raise models.APIErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('PersistedFace', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
add_face_from_stream.metadata = {'url': '/facelists/{faceListId}/persistedfaces'}
| 49.36465 | 172 | 0.676752 | 3,675 | 31,001 | 5.574422 | 0.102041 | 0.02304 | 0.017085 | 0.019477 | 0.845065 | 0.829591 | 0.822757 | 0.809626 | 0.799326 | 0.795128 | 0 | 0.010407 | 0.23438 | 31,001 | 627 | 173 | 49.443381 | 0.852707 | 0.506403 | 0 | 0.703704 | 0 | 0 | 0.112928 | 0.027867 | 0 | 0 | 0 | 0 | 0 | 1 | 0.041667 | false | 0 | 0.009259 | 0 | 0.115741 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
c304a31d35328bee7e6dcf1b8311168d06eba548 | 21,129 | py | Python | tests/test_04_usdnvolgauge.py | taariq/volumegauge | f92ea90f4eefab9079fd624bddbe0e3cf5684f80 | [
"Apache-2.0"
] | 3 | 2020-12-17T01:11:08.000Z | 2020-12-24T08:06:07.000Z | tests/test_04_usdnvolgauge.py | taariq/volumegauge | f92ea90f4eefab9079fd624bddbe0e3cf5684f80 | [
"Apache-2.0"
] | 13 | 2020-11-22T20:24:23.000Z | 2021-01-07T20:19:57.000Z | tests/test_04_usdnvolgauge.py | taariq/volumegauge | f92ea90f4eefab9079fd624bddbe0e3cf5684f80 | [
"Apache-2.0"
] | 3 | 2020-12-17T18:32:46.000Z | 2020-12-23T21:57:47.000Z | #!/usr/bin/python3
import pytest
PERIOD = 30
DENOMINATOR = 10 ** 18
SMOOTHING = 2
ALPHA = DENOMINATOR - SMOOTHING * DENOMINATOR / (PERIOD + 1)
def test_exchange_usdn_to_crv3(_usdnvolgauge, usdnpool, USDN, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange(0, 1, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange(0, 1, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDN)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDN)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_crv3_to_usdn(_usdnvolgauge, usdnpool, CRV3, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange(1, 0, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange(1, 0, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(CRV3)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(CRV3)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdn_to_dai(_usdnvolgauge, usdnpool, USDN, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(0, 1, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(0, 1, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDN)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDN)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_dai_to_usdn(_usdnvolgauge, usdnpool, DAI, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(1, 0, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(1, 0, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(DAI)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(DAI)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdn_to_usdc(_usdnvolgauge, usdnpool, USDN, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(0, 2, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(0, 2, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDN)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDN)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdc_to_usdn(_usdnvolgauge, usdnpool, USDC, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(2, 0, 50 * 10 ** 6, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(2, 0, 50 * 10 ** 6, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDC)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDC)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdn_to_usdt(_usdnvolgauge, usdnpool, USDN, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(0, 3, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(0, 3, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDN)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDN)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdt_to_usdn(_usdnvolgauge, usdnpool, USDT, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(3, 0, 50 * 10 ** 6, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(3, 0, 50 * 10 ** 6, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDT)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDT)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_dai_to_usdc(_usdnvolgauge, usdnpool, DAI, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(1, 2, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(1, 2, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(DAI)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(DAI)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdc_to_dai(_usdnvolgauge, usdnpool, USDC, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(2, 1, 50 * 10 ** 6, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(2, 1, 50 * 10 ** 6, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDC)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDC)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_dai_to_usdt(_usdnvolgauge, usdnpool, DAI, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(1, 3, 50 * 10 ** 18, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(1, 3, 50 * 10 ** 18, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(DAI)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(DAI)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdt_to_dai(_usdnvolgauge, usdnpool, USDT, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(3, 1, 50 * 10 ** 6, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(3, 1, 50 * 10 ** 6, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDT)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDT)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdc_to_usdt(_usdnvolgauge, usdnpool, USDC, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(2, 3, 50 * 10 ** 6, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(2, 3, 50 * 10 ** 6, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDC)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDC)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV")
def test_exchange_underlying_usdt_to_usdc(_usdnvolgauge, usdnpool, USDT, tracker, accounts):
for i in range(5):
print("Attemp #" + str(i + 1) + " .....")
last_reward_amount = tracker.rewardAmount()
tx = _usdnvolgauge.exchange_underlying(3, 2, 50 * 10 ** 6, 0, {'from': accounts[0]})
vgas = tx.gas_used
print("VGaugeGas : " + str(vgas) + " Unit")
tx = usdnpool.exchange_underlying(3, 2, 50 * 10 ** 6, 0, {'from': accounts[0]})
print("OriginGas : " + str(tx.gas_used) + " Unit")
print("ConsumedGasByVolumeGauge : " + str(vgas - tx.gas_used) + " Unit")
current_reward_amount = tracker.rewardAmount()
lastvolumedata = tracker.lastVolumeData(USDT)
last_volume = lastvolumedata[0]
last_amount = lastvolumedata[1]
currentvolumedata = tracker.currentVolumeData(USDT)
current_volume = currentvolumedata[0]
current_amount = currentvolumedata[1]
newvolume = ALPHA * last_volume + (DENOMINATOR - ALPHA) * current_volume
newamount = ALPHA * last_amount + (DENOMINATOR - ALPHA) * current_amount
price_v_ema = newvolume / newamount
print("price_by_volume_EMA* : " + str(price_v_ema / DENOMINATOR) + " CRV")
print("reward_amount : " + str(current_reward_amount) + " (" + str(current_reward_amount / DENOMINATOR) + " CRV)")
print("increased_reward_amount_in_CRV : " + str(float(current_reward_amount - last_reward_amount) / DENOMINATOR) + " CRV") | 61.421512 | 130 | 0.649061 | 2,350 | 21,129 | 5.57617 | 0.028085 | 0.102564 | 0.081197 | 0.066239 | 0.983745 | 0.983745 | 0.983745 | 0.983745 | 0.983745 | 0.983745 | 0 | 0.022272 | 0.222254 | 21,129 | 344 | 131 | 61.421512 | 0.775148 | 0.000805 | 0 | 0.850153 | 0 | 0 | 0.116048 | 0.035809 | 0 | 0 | 0 | 0 | 0 | 1 | 0.042813 | false | 0 | 0.003058 | 0 | 0.045872 | 0.299694 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
c304a4b5907189e916e064b59bda84edcb9d59f0 | 915 | py | Python | tests/parser/stratcomp.test.py | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | tests/parser/stratcomp.test.py | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | tests/parser/stratcomp.test.py | veltri/DLV2 | 944aaef803aa75e7ec51d7e0c2b0d964687fdd0e | [
"Apache-2.0"
] | null | null | null | input = """
% Strategic Companies
%
% As we want to produce X, Y or Z must be strategic.
strategic(Y) | strategic(Z) :- produced_by(X,Y,Z).
% W is strategic, if it is controlled by strategic
% companies X, Y, and Z
strategic(W) :- controlled_by(W,X,Y,Z),
Strategic(X), Strategic(Y), Strategic(Z).
% Handle special 0 symbol
:- strategic(0).
Strategic(X) :- strategic(X).
Strategic(0) :- true.
true.
"""
output = """
% Strategic Companies
%
% As we want to produce X, Y or Z must be strategic.
strategic(Y) | strategic(Z) :- produced_by(X,Y,Z).
% W is strategic, if it is controlled by strategic
% companies X, Y, and Z
strategic(W) :- controlled_by(W,X,Y,Z),
Strategic(X), Strategic(Y), Strategic(Z).
% Handle special 0 symbol
:- strategic(0).
Strategic(X) :- strategic(X).
Strategic(0) :- true.
true.
"""
| 22.317073 | 60 | 0.597814 | 132 | 915 | 4.113636 | 0.212121 | 0.029466 | 0.209945 | 0.14733 | 0.979742 | 0.979742 | 0.979742 | 0.979742 | 0.979742 | 0.979742 | 0 | 0.008811 | 0.255738 | 915 | 40 | 61 | 22.875 | 0.788546 | 0 | 0 | 0.866667 | 0 | 0 | 0.964733 | 0.052332 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
5ed99c878ccae5e870d8e7396a797ae6a9c8e68c | 48 | py | Python | error.py | networktocode/python-checker | 616e0b9332a5dd7089fbfadd1ed446a6d61138e0 | [
"Apache-2.0"
] | 1 | 2020-09-03T23:01:21.000Z | 2020-09-03T23:01:21.000Z | error.py | networktocode/python-checker | 616e0b9332a5dd7089fbfadd1ed446a6d61138e0 | [
"Apache-2.0"
] | null | null | null | error.py | networktocode/python-checker | 616e0b9332a5dd7089fbfadd1ed446a6d61138e0 | [
"Apache-2.0"
] | 1 | 2021-04-05T09:51:27.000Z | 2021-04-05T09:51:27.000Z | import foobar
def black():
print("Hahaha")
| 9.6 | 19 | 0.645833 | 6 | 48 | 5.166667 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.208333 | 48 | 4 | 20 | 12 | 0.815789 | 0 | 0 | 0 | 0 | 0 | 0.125 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.333333 | true | 0 | 0.333333 | 0 | 0.666667 | 0.333333 | 1 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
5ee65579cc599c1929387dc0fbc637603ac48244 | 3,770 | py | Python | alpyro_msgs/visualization_msgs/interactivemarker.py | rho2/alpyro_msgs | b5a680976c40c83df70d61bb2db1de32a1cde8d3 | [
"MIT"
] | 1 | 2020-12-13T13:07:10.000Z | 2020-12-13T13:07:10.000Z | alpyro_msgs/visualization_msgs/interactivemarker.py | rho2/alpyro_msgs | b5a680976c40c83df70d61bb2db1de32a1cde8d3 | [
"MIT"
] | null | null | null | alpyro_msgs/visualization_msgs/interactivemarker.py | rho2/alpyro_msgs | b5a680976c40c83df70d61bb2db1de32a1cde8d3 | [
"MIT"
] | null | null | null | from typing import List
from typing_extensions import Annotated
from typing import Final
from alpyro_msgs import RosMessage, float32, string
from alpyro_msgs.geometry_msgs.pose import Pose
from alpyro_msgs.std_msgs.header import Header
from alpyro_msgs.visualization_msgs.interactivemarkercontrol import InteractiveMarkerControl
from alpyro_msgs.visualization_msgs.menuentry import MenuEntry
class InteractiveMarker(RosMessage):
__msg_typ__ = "visualization_msgs/InteractiveMarker"
__msg_def__ = "c3RkX21zZ3MvSGVhZGVyIGhlYWRlcgogIHVpbnQzMiBzZXEKICB0aW1lIHN0YW1wCiAgc3RyaW5nIGZyYW1lX2lkCmdlb21ldHJ5X21zZ3MvUG9zZSBwb3NlCiAgZ2VvbWV0cnlfbXNncy9Qb2ludCBwb3NpdGlvbgogICAgZmxvYXQ2NCB4CiAgICBmbG9hdDY0IHkKICAgIGZsb2F0NjQgegogIGdlb21ldHJ5X21zZ3MvUXVhdGVybmlvbiBvcmllbnRhdGlvbgogICAgZmxvYXQ2NCB4CiAgICBmbG9hdDY0IHkKICAgIGZsb2F0NjQgegogICAgZmxvYXQ2NCB3CnN0cmluZyBuYW1lCnN0cmluZyBkZXNjcmlwdGlvbgpmbG9hdDMyIHNjYWxlCnZpc3VhbGl6YXRpb25fbXNncy9NZW51RW50cnlbXSBtZW51X2VudHJpZXMKICB1aW50OCBGRUVEQkFDSz0wCiAgdWludDggUk9TUlVOPTEKICB1aW50OCBST1NMQVVOQ0g9MgogIHVpbnQzMiBpZAogIHVpbnQzMiBwYXJlbnRfaWQKICBzdHJpbmcgdGl0bGUKICBzdHJpbmcgY29tbWFuZAogIHVpbnQ4IGNvbW1hbmRfdHlwZQp2aXN1YWxpemF0aW9uX21zZ3MvSW50ZXJhY3RpdmVNYXJrZXJDb250cm9sW10gY29udHJvbHMKICB1aW50OCBJTkhFUklUPTAKICB1aW50OCBGSVhFRD0xCiAgdWludDggVklFV19GQUNJTkc9MgogIHVpbnQ4IE5PTkU9MAogIHVpbnQ4IE1FTlU9MQogIHVpbnQ4IEJVVFRPTj0yCiAgdWludDggTU9WRV9BWElTPTMKICB1aW50OCBNT1ZFX1BMQU5FPTQKICB1aW50OCBST1RBVEVfQVhJUz01CiAgdWludDggTU9WRV9ST1RBVEU9NgogIHVpbnQ4IE1PVkVfM0Q9NwogIHVpbnQ4IFJPVEFURV8zRD04CiAgdWludDggTU9WRV9ST1RBVEVfM0Q9OQogIHN0cmluZyBuYW1lCiAgZ2VvbWV0cnlfbXNncy9RdWF0ZXJuaW9uIG9yaWVudGF0aW9uCiAgICBmbG9hdDY0IHgKICAgIGZsb2F0NjQgeQogICAgZmxvYXQ2NCB6CiAgICBmbG9hdDY0IHcKICB1aW50OCBvcmllbnRhdGlvbl9tb2RlCiAgdWludDggaW50ZXJhY3Rpb25fbW9kZQogIGJvb2wgYWx3YXlzX3Zpc2libGUKICB2aXN1YWxpemF0aW9uX21zZ3MvTWFya2VyW10gbWFya2VycwogICAgdWludDggQVJST1c9MAogICAgdWludDggQ1VCRT0xCiAgICB1aW50OCBTUEhFUkU9MgogICAgdWludDggQ1lMSU5ERVI9MwogICAgdWludDggTElORV9TVFJJUD00CiAgICB1aW50OCBMSU5FX0xJU1Q9NQogICAgdWludDggQ1VCRV9MSVNUPTYKICAgIHVpbnQ4IFNQSEVSRV9MSVNUPTcKICAgIHVpbnQ4IFBPSU5UUz04CiAgICB1aW50OCBURVhUX1ZJRVdfRkFDSU5HPTkKICAgIHVpbnQ4IE1FU0hfUkVTT1VSQ0U9MTAKICAgIHVpbnQ4IFRSSUFOR0xFX0xJU1Q9MTEKICAgIHVpbnQ4IEFERD0wCiAgICB1aW50OCBNT0RJRlk9MAogICAgdWludDggREVMRVRFPTIKICAgIHVpbnQ4IERFTEVURUFMTD0zCiAgICBzdGRfbXNncy9IZWFkZXIgaGVhZGVyCiAgICAgIHVpbnQzMiBzZXEKICAgICAgdGltZSBzdGFtcAogICAgICBzdHJpbmcgZnJhbWVfaWQKICAgIHN0cmluZyBucwogICAgaW50MzIgaWQKICAgIGludDMyIHR5cGUKICAgIGludDMyIGFjdGlvbgogICAgZ2VvbWV0cnlfbXNncy9Qb3NlIHBvc2UKICAgICAgZ2VvbWV0cnlfbXNncy9Qb2ludCBwb3NpdGlvbgogICAgICAgIGZsb2F0NjQgeAogICAgICAgIGZsb2F0NjQgeQogICAgICAgIGZsb2F0NjQgegogICAgICBnZW9tZXRyeV9tc2dzL1F1YXRlcm5pb24gb3JpZW50YXRpb24KICAgICAgICBmbG9hdDY0IHgKICAgICAgICBmbG9hdDY0IHkKICAgICAgICBmbG9hdDY0IHoKICAgICAgICBmbG9hdDY0IHcKICAgIGdlb21ldHJ5X21zZ3MvVmVjdG9yMyBzY2FsZQogICAgICBmbG9hdDY0IHgKICAgICAgZmxvYXQ2NCB5CiAgICAgIGZsb2F0NjQgegogICAgc3RkX21zZ3MvQ29sb3JSR0JBIGNvbG9yCiAgICAgIGZsb2F0MzIgcgogICAgICBmbG9hdDMyIGcKICAgICAgZmxvYXQzMiBiCiAgICAgIGZsb2F0MzIgYQogICAgZHVyYXRpb24gbGlmZXRpbWUKICAgIGJvb2wgZnJhbWVfbG9ja2VkCiAgICBnZW9tZXRyeV9tc2dzL1BvaW50W10gcG9pbnRzCiAgICAgIGZsb2F0NjQgeAogICAgICBmbG9hdDY0IHkKICAgICAgZmxvYXQ2NCB6CiAgICBzdGRfbXNncy9Db2xvclJHQkFbXSBjb2xvcnMKICAgICAgZmxvYXQzMiByCiAgICAgIGZsb2F0MzIgZwogICAgICBmbG9hdDMyIGIKICAgICAgZmxvYXQzMiBhCiAgICBzdHJpbmcgdGV4dAogICAgc3RyaW5nIG1lc2hfcmVzb3VyY2UKICAgIGJvb2wgbWVzaF91c2VfZW1iZWRkZWRfbWF0ZXJpYWxzCiAgYm9vbCBpbmRlcGVuZGVudF9tYXJrZXJfb3JpZW50YXRpb24KICBzdHJpbmcgZGVzY3JpcHRpb24KCg=="
__md5_sum__ = "dd86d22909d5a3364b384492e35c10af"
header: Header
pose: Pose
name: string
description: string
scale: float32
menu_entries: Annotated[List[MenuEntry], 0, 0]
controls: Annotated[List[InteractiveMarkerControl], 0, 0]
| 163.913043 | 3,038 | 0.965517 | 89 | 3,770 | 40.595506 | 0.393258 | 0.013839 | 0.019374 | 0.014946 | 0.01716 | 0 | 0 | 0 | 0 | 0 | 0 | 0.106406 | 0.022812 | 3,770 | 22 | 3,039 | 171.363636 | 0.874321 | 0 | 0 | 0 | 0 | 0 | 0.819098 | 0.819098 | 0 | 1 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.421053 | 0 | 1 | 0 | 0 | 0 | 1 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
6f051ae81c0300bbb0d26dadc923d96d8ca85f85 | 22,927 | py | Python | tests/test_dbt_parsers.py | mmmatthew/dbt-metabase | e7c7832c473b8d17ad2dd02f402c881e93897332 | [
"MIT"
] | 154 | 2019-12-13T16:03:02.000Z | 2022-03-30T11:44:47.000Z | tests/test_dbt_parsers.py | mmmatthew/dbt-metabase | e7c7832c473b8d17ad2dd02f402c881e93897332 | [
"MIT"
] | 60 | 2020-01-28T21:31:08.000Z | 2022-03-31T11:35:49.000Z | tests/test_dbt_parsers.py | mmmatthew/dbt-metabase | e7c7832c473b8d17ad2dd02f402c881e93897332 | [
"MIT"
] | 19 | 2020-03-25T08:29:45.000Z | 2022-03-01T16:39:59.000Z | import logging
import unittest
from dbtmetabase.models.interface import DbtInterface
from dbtmetabase.models.metabase import ModelType
from dbtmetabase.parsers.dbt_folder import (
MetabaseModel,
MetabaseColumn,
)
class TestDbtFolderReader(unittest.TestCase):
def setUp(self):
"""Must specify dbt root dir"""
self.interface = DbtInterface(
database="test",
schema="public",
path="tests/fixtures/sample_project/",
)
logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
def test_read_models(self):
models = self.interface.parser.read_models(self.interface.get_config())[0]
expectation = [
MetabaseModel(
name="customers",
schema="PUBLIC",
description="This table has basic information about a customer, as well as some derived facts based on a customer's orders",
model_type=ModelType.nodes,
dbt_name=None,
source=None,
unique_id=None,
columns=[
MetabaseColumn(
name="CUSTOMER_ID",
description="This is a unique identifier for a customer",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="FIRST_NAME",
description="Customer's first name. PII.",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="LAST_NAME",
description="Customer's last name. PII.",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="FIRST_ORDER",
description="Date (UTC) of a customer's first order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="MOST_RECENT_ORDER",
description="Date (UTC) of a customer's most recent order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="NUMBER_OF_ORDERS",
description="Count of the number of orders a customer has placed",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="TOTAL_ORDER_AMOUNT",
description="Total value (AUD) of a customer's orders",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="orders",
schema="PUBLIC",
description="This table has basic information about orders, as well as some derived facts based on payments",
model_type=ModelType.nodes,
dbt_name=None,
source=None,
unique_id=None,
columns=[
MetabaseColumn(
name="ORDER_ID",
description="This is a unique identifier for an order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="CUSTOMER_ID",
description="Foreign key to the customers table",
meta_fields={},
semantic_type="type/FK",
visibility_type=None,
fk_target_table="PUBLIC.CUSTOMERS",
fk_target_field="CUSTOMER_ID",
),
MetabaseColumn(
name="ORDER_DATE",
description="Date (UTC) that the order was placed",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="STATUS",
description='{{ doc("orders_status") }}',
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="AMOUNT",
description="Total amount (AUD) of the order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="CREDIT_CARD_AMOUNT",
description="Amount of the order (AUD) paid for by credit card",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="COUPON_AMOUNT",
description="Amount of the order (AUD) paid for by coupon",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="BANK_TRANSFER_AMOUNT",
description="Amount of the order (AUD) paid for by bank transfer",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="GIFT_CARD_AMOUNT",
description="Amount of the order (AUD) paid for by gift card",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="stg_customers",
schema="PUBLIC",
description="",
model_type=ModelType.nodes,
dbt_name=None,
source=None,
unique_id=None,
columns=[
MetabaseColumn(
name="CUSTOMER_ID",
description=None,
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
)
],
),
MetabaseModel(
name="stg_orders",
schema="PUBLIC",
description="",
model_type=ModelType.nodes,
dbt_name=None,
source=None,
unique_id=None,
columns=[
MetabaseColumn(
name="ORDER_ID",
description=None,
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="STATUS",
description=None,
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="stg_payments",
schema="PUBLIC",
description="",
model_type=ModelType.nodes,
dbt_name=None,
source=None,
unique_id=None,
columns=[
MetabaseColumn(
name="PAYMENT_ID",
description=None,
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="PAYMENT_METHOD",
description=None,
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
]
self.assertEqual(models, expectation)
logging.info("Done")
class TestDbtManifestReader(unittest.TestCase):
def setUp(self):
"""Must specify dbt root dir"""
self.interface = DbtInterface(
database="test",
schema="public",
manifest_path="tests/fixtures/sample_project/target/manifest.json",
)
logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
def test_read_models(self):
models = self.interface.parser.read_models(self.interface.get_config())[0]
expectation = [
MetabaseModel(
name="orders",
schema="PUBLIC",
description="This table has basic information about orders, as well as some derived facts based on payments",
model_type=ModelType.nodes,
dbt_name="orders",
source=None,
unique_id="model.jaffle_shop.orders",
columns=[
MetabaseColumn(
name="ORDER_ID",
description="This is a unique identifier for an order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="CUSTOMER_ID",
description="Foreign key to the customers table",
meta_fields={},
semantic_type="type/FK",
visibility_type=None,
fk_target_table="PUBLIC.CUSTOMERS",
fk_target_field="CUSTOMER_ID",
),
MetabaseColumn(
name="ORDER_DATE",
description="Date (UTC) that the order was placed",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="STATUS",
description="Orders can be one of the following statuses:\n\n| status | description |\n|----------------|------------------------------------------------------------------------------------------------------------------------|\n| placed | The order has been placed but has not yet left the warehouse |\n| shipped | The order has ben shipped to the customer and is currently in transit |\n| completed | The order has been received by the customer |\n| return_pending | The customer has indicated that they would like to return the order, but it has not yet been received at the warehouse |\n| returned | The order has been returned by the customer and received at the warehouse |",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="AMOUNT",
description="Total amount (AUD) of the order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="CREDIT_CARD_AMOUNT",
description="Amount of the order (AUD) paid for by credit card",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="COUPON_AMOUNT",
description="Amount of the order (AUD) paid for by coupon",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="BANK_TRANSFER_AMOUNT",
description="Amount of the order (AUD) paid for by bank transfer",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="GIFT_CARD_AMOUNT",
description="Amount of the order (AUD) paid for by gift card",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="customers",
schema="PUBLIC",
description="This table has basic information about a customer, as well as some derived facts based on a customer's orders",
model_type=ModelType.nodes,
dbt_name="customers",
source=None,
unique_id="model.jaffle_shop.customers",
columns=[
MetabaseColumn(
name="CUSTOMER_ID",
description="This is a unique identifier for a customer",
meta_fields={},
semantic_type="type/FK",
visibility_type=None,
fk_target_table="PUBLIC.ORDERS",
fk_target_field="CUSTOMER_ID",
),
MetabaseColumn(
name="FIRST_NAME",
description="Customer's first name. PII.",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="LAST_NAME",
description="Customer's last name. PII.",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="FIRST_ORDER",
description="Date (UTC) of a customer's first order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="MOST_RECENT_ORDER",
description="Date (UTC) of a customer's most recent order",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="NUMBER_OF_ORDERS",
description="Count of the number of orders a customer has placed",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="TOTAL_ORDER_AMOUNT",
description="Total value (AUD) of a customer's orders",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="stg_orders",
schema="PUBLIC",
description="",
model_type=ModelType.nodes,
dbt_name="stg_orders",
source=None,
unique_id="model.jaffle_shop.stg_orders",
columns=[
MetabaseColumn(
name="ORDER_ID",
description="",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="STATUS",
description="",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="stg_payments",
schema="PUBLIC",
description="",
model_type=ModelType.nodes,
dbt_name="stg_payments",
source=None,
unique_id="model.jaffle_shop.stg_payments",
columns=[
MetabaseColumn(
name="PAYMENT_ID",
description="",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
MetabaseColumn(
name="PAYMENT_METHOD",
description="",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
),
],
),
MetabaseModel(
name="stg_customers",
schema="PUBLIC",
description="",
model_type=ModelType.nodes,
dbt_name="stg_customers",
source=None,
unique_id="model.jaffle_shop.stg_customers",
columns=[
MetabaseColumn(
name="CUSTOMER_ID",
description="",
meta_fields={},
semantic_type=None,
visibility_type=None,
fk_target_table=None,
fk_target_field=None,
)
],
),
]
self.assertEqual(models, expectation)
logging.info("Done")
| 42.774254 | 1,072 | 0.404937 | 1,664 | 22,927 | 5.330529 | 0.09375 | 0.075761 | 0.109583 | 0.104171 | 0.921195 | 0.914431 | 0.910034 | 0.896956 | 0.873957 | 0.873957 | 0 | 0.000183 | 0.522266 | 22,927 | 535 | 1,073 | 42.854206 | 0.809641 | 0.002224 | 0 | 0.941065 | 0 | 0.005703 | 0.162694 | 0.015963 | 0 | 0 | 0 | 0 | 0.003802 | 1 | 0.007605 | false | 0 | 0.009506 | 0 | 0.020913 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 |
6f27f8a54822f6176753763f9ed7adbf9e49bfe7 | 100 | py | Python | generate_token.py | adithyabsk/roambot | 6616d5848bc6a485cf1a86caccfe47b6e38fe063 | [
"MIT"
] | 4 | 2022-01-06T21:59:53.000Z | 2022-03-11T20:04:11.000Z | generate_token.py | adithyabsk/tftbot | 842e14baf7818b9d0026e6b452f536bec2a326d2 | [
"MIT"
] | null | null | null | generate_token.py | adithyabsk/tftbot | 842e14baf7818b9d0026e6b452f536bec2a326d2 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
from tftbot.obsidian import generate_initial_token
generate_initial_token()
| 16.666667 | 50 | 0.83 | 14 | 100 | 5.642857 | 0.785714 | 0.379747 | 0.506329 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.09 | 100 | 5 | 51 | 20 | 0.868132 | 0.2 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 7 |
6f397000830810df24848a00d8369918b6bb760e | 1,507 | py | Python | lib/solutions/FIZ/fizz_buzz_solution.py | DPNT-Sourcecode/FIZ-txik01 | 3890a84047a7b5fa562123231e3324815bdb8024 | [
"Apache-2.0"
] | null | null | null | lib/solutions/FIZ/fizz_buzz_solution.py | DPNT-Sourcecode/FIZ-txik01 | 3890a84047a7b5fa562123231e3324815bdb8024 | [
"Apache-2.0"
] | null | null | null | lib/solutions/FIZ/fizz_buzz_solution.py | DPNT-Sourcecode/FIZ-txik01 | 3890a84047a7b5fa562123231e3324815bdb8024 | [
"Apache-2.0"
] | null | null | null | def fizz_buzz(number):
if (number%3==0 or '3' in str(number)) and (number%5 == 0 or '5' in str(number)) and ((number%3==0 and '3' in str(number)) or (number%5 == 0 and '5' in str(number))) and number % 2 == 0:
return "fizz buzz deluxe"
elif (number%3==0 or '3' in str(number)) and (number%5 == 0 or '5' in str(number)) and ((number%3==0 and '3' in str(number)) or (number%5 == 0 and '5' in str(number))) and number % 2 != 0:
return "fizz buzz fake deluxe"
elif (number%3 == 0 or '3' in str(number)) and ((number%3==0 and '3' in str(number)) or (number%5 == 0 and '5' in str(number))) and number % 2 == 0:
return "fizz deluxe"
elif (number%3 == 0 or '3' in str(number)) and ((number%3==0 and '3' in str(number)) or (number%5 == 0 and '5' in str(number))) and number % 2 != 0:
return "fizz fake deluxe"
elif (number%5 == 0 or '5' in str(number)) and ((number%3==0 and '3' in str(number)) or (number%5 == 0 and '5' in str(number)) and number % 2 == 0):
return "buzz deluxe"
elif (number%5 == 0 or '5' in str(number)) and ((number%3==0 and '3' in str(number)) or (number%5 == 0 and '5' in str(number)) and number % 2 != 0):
return "buzz fake deluxe"
elif (number%3 == 0 or '3' in str(number)) and (number%5 == 0 or '5' in str(number)):
return "fizz buzz"
elif (number%5 == 0 or '5' in str(number)):
return "buzz"
elif (number%3 == 0 or '3' in str(number)):
return "fizz"
else:
return number
| 68.5 | 192 | 0.572661 | 277 | 1,507 | 3.111913 | 0.064982 | 0.139211 | 0.306265 | 0.243619 | 0.945476 | 0.929234 | 0.929234 | 0.929234 | 0.929234 | 0.854988 | 0 | 0.073684 | 0.24353 | 1,507 | 21 | 193 | 71.761905 | 0.682456 | 0 | 0 | 0 | 0 | 0 | 0.087591 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.047619 | false | 0 | 0 | 0 | 0.52381 | 0 | 0 | 0 | 0 | null | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 9 |
6f662ac413dc190be28c54c5139336854c72cd0a | 215 | py | Python | mindefuse/problem/secret/generators/__init__.py | sinistro14/mindefuse | c7371a81731d0b9a03d3ef18f91c336e4135c17d | [
"MIT"
] | null | null | null | mindefuse/problem/secret/generators/__init__.py | sinistro14/mindefuse | c7371a81731d0b9a03d3ef18f91c336e4135c17d | [
"MIT"
] | 1 | 2019-08-22T19:51:12.000Z | 2019-08-22T19:51:12.000Z | mindefuse/problem/secret/generators/__init__.py | sinistro14/mindefuse | c7371a81731d0b9a03d3ef18f91c336e4135c17d | [
"MIT"
] | null | null | null | #!/usr/bin/env python3.7
from .secret_generator import SecretGenerator
from .numeric_generator import NumericGenerator
from .l_string_generator import LStringGenerator
from .string_generator import StringGenerator
| 30.714286 | 48 | 0.865116 | 26 | 215 | 6.961538 | 0.615385 | 0.331492 | 0.232044 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.010204 | 0.088372 | 215 | 6 | 49 | 35.833333 | 0.913265 | 0.106977 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | null | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 7 |
48cecdce9c20b7311840ffc5ad331afd6f303e7b | 7,295 | py | Python | tests/test_parser.py | snsnlou/python-dotenv | 303423864ae00f8d5f21cb39d6421a7d775a3daf | [
"BSD-3-Clause"
] | 1 | 2020-10-21T02:27:23.000Z | 2020-10-21T02:27:23.000Z | tests/test_parser.py | snsnlou/python-dotenv | 303423864ae00f8d5f21cb39d6421a7d775a3daf | [
"BSD-3-Clause"
] | null | null | null | tests/test_parser.py | snsnlou/python-dotenv | 303423864ae00f8d5f21cb39d6421a7d775a3daf | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
import pytest
from dotenv.compat import StringIO
from dotenv.parser import Binding, Original, parse_stream
@pytest.mark.parametrize("test_input,expected", [
(u"", []),
(u"a=b", [Binding(key=u"a", value=u"b", original=Original(string=u"a=b", line=1), error=False)]),
(u"'a'=b", [Binding(key=u"a", value=u"b", original=Original(string=u"'a'=b", line=1), error=False)]),
(u"[=b", [Binding(key=u"[", value=u"b", original=Original(string=u"[=b", line=1), error=False)]),
(u" a = b ", [Binding(key=u"a", value=u"b", original=Original(string=u" a = b ", line=1), error=False)]),
(u"export a=b", [Binding(key=u"a", value=u"b", original=Original(string=u"export a=b", line=1), error=False)]),
(
u" export 'a'=b",
[Binding(key=u"a", value=u"b", original=Original(string=u" export 'a'=b", line=1), error=False)],
),
(u"# a=b", [Binding(key=None, value=None, original=Original(string=u"# a=b", line=1), error=False)]),
(u"a=b#c", [Binding(key=u"a", value=u"b#c", original=Original(string=u"a=b#c", line=1), error=False)]),
(
u'a=b #c',
[Binding(key=u"a", value=u"b", original=Original(string=u"a=b #c", line=1), error=False)],
),
(
u'a=b\t#c',
[Binding(key=u"a", value=u"b", original=Original(string=u"a=b\t#c", line=1), error=False)],
),
(
u"a=b c",
[Binding(key=u"a", value=u"b c", original=Original(string=u"a=b c", line=1), error=False)],
),
(
u"a=b\tc",
[Binding(key=u"a", value=u"b\tc", original=Original(string=u"a=b\tc", line=1), error=False)],
),
(
u"a=b c",
[Binding(key=u"a", value=u"b c", original=Original(string=u"a=b c", line=1), error=False)],
),
(
u"a=b\u00a0 c",
[Binding(key=u"a", value=u"b\u00a0 c", original=Original(string=u"a=b\u00a0 c", line=1), error=False)],
),
(
u"a=b c ",
[Binding(key=u"a", value=u"b c", original=Original(string=u"a=b c ", line=1), error=False)],
),
(
u"a='b c '",
[Binding(key=u"a", value=u"b c ", original=Original(string=u"a='b c '", line=1), error=False)],
),
(
u'a="b c "',
[Binding(key=u"a", value=u"b c ", original=Original(string=u'a="b c "', line=1), error=False)],
),
(
u"export export_a=1",
[
Binding(key=u"export_a", value=u"1", original=Original(string=u"export export_a=1", line=1), error=False)
],
),
(
u"export port=8000",
[Binding(key=u"port", value=u"8000", original=Original(string=u"export port=8000", line=1), error=False)],
),
(u'a="b\nc"', [Binding(key=u"a", value=u"b\nc", original=Original(string=u'a="b\nc"', line=1), error=False)]),
(u"a='b\nc'", [Binding(key=u"a", value=u"b\nc", original=Original(string=u"a='b\nc'", line=1), error=False)]),
(u'a="b\nc"', [Binding(key=u"a", value=u"b\nc", original=Original(string=u'a="b\nc"', line=1), error=False)]),
(u'a="b\\nc"', [Binding(key=u"a", value=u'b\nc', original=Original(string=u'a="b\\nc"', line=1), error=False)]),
(u"a='b\\nc'", [Binding(key=u"a", value=u'b\\nc', original=Original(string=u"a='b\\nc'", line=1), error=False)]),
(u'a="b\\"c"', [Binding(key=u"a", value=u'b"c', original=Original(string=u'a="b\\"c"', line=1), error=False)]),
(u"a='b\\'c'", [Binding(key=u"a", value=u"b'c", original=Original(string=u"a='b\\'c'", line=1), error=False)]),
(u"a=à", [Binding(key=u"a", value=u"à", original=Original(string=u"a=à", line=1), error=False)]),
(u'a="à"', [Binding(key=u"a", value=u"à", original=Original(string=u'a="à"', line=1), error=False)]),
(
u'no_value_var',
[Binding(key=u'no_value_var', value=None, original=Original(string=u"no_value_var", line=1), error=False)],
),
(u'a: b', [Binding(key=None, value=None, original=Original(string=u"a: b", line=1), error=True)]),
(
u"a=b\nc=d",
[
Binding(key=u"a", value=u"b", original=Original(string=u"a=b\n", line=1), error=False),
Binding(key=u"c", value=u"d", original=Original(string=u"c=d", line=2), error=False),
],
),
(
u"a=b\rc=d",
[
Binding(key=u"a", value=u"b", original=Original(string=u"a=b\r", line=1), error=False),
Binding(key=u"c", value=u"d", original=Original(string=u"c=d", line=2), error=False),
],
),
(
u"a=b\r\nc=d",
[
Binding(key=u"a", value=u"b", original=Original(string=u"a=b\r\n", line=1), error=False),
Binding(key=u"c", value=u"d", original=Original(string=u"c=d", line=2), error=False),
],
),
(
u'a=\nb=c',
[
Binding(key=u"a", value=u'', original=Original(string=u'a=\n', line=1), error=False),
Binding(key=u"b", value=u'c', original=Original(string=u"b=c", line=2), error=False),
]
),
(
u"\n\n",
[
Binding(key=None, value=None, original=Original(string=u"\n\n", line=1), error=False),
]
),
(
u"a=b\n\n",
[
Binding(key=u"a", value=u"b", original=Original(string=u"a=b\n", line=1), error=False),
Binding(key=None, value=None, original=Original(string=u"\n", line=2), error=False),
]
),
(
u'a=b\n\nc=d',
[
Binding(key=u"a", value=u"b", original=Original(string=u"a=b\n", line=1), error=False),
Binding(key=u"c", value=u"d", original=Original(string=u"\nc=d", line=2), error=False),
]
),
(
u'a="\nb=c',
[
Binding(key=None, value=None, original=Original(string=u'a="\n', line=1), error=True),
Binding(key=u"b", value=u"c", original=Original(string=u"b=c", line=2), error=False),
]
),
(
u'# comment\na="b\nc"\nd=e\n',
[
Binding(key=None, value=None, original=Original(string=u"# comment\n", line=1), error=False),
Binding(key=u"a", value=u"b\nc", original=Original(string=u'a="b\nc"\n', line=2), error=False),
Binding(key=u"d", value=u"e", original=Original(string=u"d=e\n", line=4), error=False),
],
),
(
u'a=b\n# comment 1',
[
Binding(key="a", value="b", original=Original(string=u"a=b\n", line=1), error=False),
Binding(key=None, value=None, original=Original(string=u"# comment 1", line=2), error=False),
],
),
(
u'# comment 1\n# comment 2',
[
Binding(key=None, value=None, original=Original(string=u"# comment 1\n", line=1), error=False),
Binding(key=None, value=None, original=Original(string=u"# comment 2", line=2), error=False),
],
),
(
u'uglyKey[%$=\"S3cr3t_P4ssw#rD\" #\na=b',
[
Binding(key=u'uglyKey[%$',
value=u'S3cr3t_P4ssw#rD',
original=Original(string=u"uglyKey[%$=\"S3cr3t_P4ssw#rD\" #\n", line=1), error=False),
Binding(key=u"a", value=u"b", original=Original(string=u'a=b', line=2), error=False),
],
),
])
def test_parse_stream(test_input, expected):
result = parse_stream(StringIO(test_input))
assert list(result) == expected
| 42.412791 | 117 | 0.540096 | 1,175 | 7,295 | 3.337021 | 0.051915 | 0.049987 | 0.044376 | 0.316756 | 0.863555 | 0.819944 | 0.786534 | 0.756185 | 0.749809 | 0.738077 | 0 | 0.016555 | 0.221659 | 7,295 | 171 | 118 | 42.660819 | 0.674005 | 0.002879 | 0 | 0.295181 | 0 | 0 | 0.134351 | 0.007426 | 0 | 0 | 0 | 0 | 0.006024 | 1 | 0.006024 | false | 0 | 0.018072 | 0 | 0.024096 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
5b026bc535038d3f5040b2412b8bd0384c381dfb | 544 | py | Python | rdmo/core/constants.py | Raspeanut/rdmo | 9f785010a499c372a2f8368ccf76d2ea4150adcb | [
"Apache-2.0"
] | null | null | null | rdmo/core/constants.py | Raspeanut/rdmo | 9f785010a499c372a2f8368ccf76d2ea4150adcb | [
"Apache-2.0"
] | null | null | null | rdmo/core/constants.py | Raspeanut/rdmo | 9f785010a499c372a2f8368ccf76d2ea4150adcb | [
"Apache-2.0"
] | null | null | null | from django.utils.translation import ugettext_lazy as _
VALUE_TYPE_TEXT = 'text'
VALUE_TYPE_URL = 'url'
VALUE_TYPE_INTEGER = 'integer'
VALUE_TYPE_FLOAT = 'float'
VALUE_TYPE_BOOLEAN = 'boolean'
VALUE_TYPE_DATETIME = 'datetime'
VALUE_TYPE_OPTIONS = 'option'
VALUE_TYPE_CHOICES = (
(VALUE_TYPE_TEXT, _('Text')),
(VALUE_TYPE_URL, _('URL')),
(VALUE_TYPE_INTEGER, _('Integer')),
(VALUE_TYPE_FLOAT, _('Float')),
(VALUE_TYPE_BOOLEAN, _('Boolean')),
(VALUE_TYPE_DATETIME, _('Datetime')),
(VALUE_TYPE_OPTIONS, _('Option'))
)
| 28.631579 | 55 | 0.715074 | 67 | 544 | 5.223881 | 0.283582 | 0.385714 | 0.074286 | 0.097143 | 0.822857 | 0.822857 | 0.822857 | 0.822857 | 0.822857 | 0.822857 | 0 | 0 | 0.136029 | 544 | 18 | 56 | 30.222222 | 0.744681 | 0 | 0 | 0 | 0 | 0 | 0.147059 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | false | 0 | 0.058824 | 0 | 0.058824 | 0 | 0 | 0 | 0 | null | 1 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d2ae6ee0e6c74fbee7a6314a2d9bc42722183dad | 17,265 | py | Python | mayan/apps/events/tests/test_models.py | bonitobonita24/Mayan-EDMS | 7845fe0e1e83c81f5d227a16116397a3d3883b85 | [
"Apache-2.0"
] | 343 | 2015-01-05T14:19:35.000Z | 2018-12-10T19:07:48.000Z | mayan/apps/events/tests/test_models.py | bonitobonita24/Mayan-EDMS | 7845fe0e1e83c81f5d227a16116397a3d3883b85 | [
"Apache-2.0"
] | 191 | 2015-01-03T00:48:19.000Z | 2018-11-30T09:10:25.000Z | mayan/apps/events/tests/test_models.py | bonitobonita24/Mayan-EDMS | 7845fe0e1e83c81f5d227a16116397a3d3883b85 | [
"Apache-2.0"
] | 114 | 2015-01-08T20:21:05.000Z | 2018-12-10T19:07:53.000Z | from mayan.apps.acls.models import AccessControlList
from mayan.apps.testing.tests.base import BaseTestCase
from ..models import EventSubscription, Notification, ObjectEventSubscription
from ..permissions import permission_events_view
from .mixins import NotificationTestMixin
class EventNotificationModelTestCase(NotificationTestMixin, BaseTestCase):
def setUp(self):
super().setUp()
self._create_test_event_type()
self._create_local_test_user()
self._create_local_test_object()
def test_event_notification_single_user_no_permission(self):
notification_count = Notification.objects.count()
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count)
def test_event_notification_single_user_with_access(self):
notification_count = Notification.objects.count()
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
AccessControlList.objects.grant(
obj=self.test_object, permission=permission_events_view,
role=self.test_role
)
result = self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_user)
self.assertEqual(notification.action, result)
def test_event_notification_multiple_users_with_user_0_access(self):
self._create_local_test_user()
notification_count = Notification.objects.count()
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_object, permission=permission_events_view,
role=self.test_roles[0]
)
result = self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_users[0])
self.assertEqual(notification.action, result)
def test_event_notification_multiple_users_with_user_1_access(self):
self._create_local_test_user()
notification_count = Notification.objects.count()
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_object, permission=permission_events_view,
role=self.test_roles[1]
)
result = self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_users[1])
self.assertEqual(notification.action, result)
def test_event_notification_multiple_users_with_all_user_access(self):
self._create_local_test_user()
notification_count = Notification.objects.count()
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
EventSubscription.objects.create(
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_object, permission=permission_events_view,
role=self.test_roles[0]
)
AccessControlList.objects.grant(
obj=self.test_object, permission=permission_events_view,
role=self.test_roles[1]
)
result = self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count + 2)
notifications = Notification.objects.all()
user_pk_list = notifications.values_list('user__id', flat=True)
self.assertTrue(self.test_users[0].pk in user_pk_list)
self.assertEqual(notifications[0].action, result)
self.assertTrue(self.test_users[1].pk in user_pk_list)
self.assertEqual(notifications[1].action, result)
class ObjectEventNotificationModelTestCase(NotificationTestMixin, BaseTestCase):
def setUp(self):
super().setUp()
self._create_test_event_type()
self._create_local_test_user()
self._create_local_test_object()
def test_object_notification_single_user_no_permission(self):
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_object,
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count)
def test_object_notification_single_user_with_access(self):
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_object,
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
AccessControlList.objects.grant(
obj=self.test_object, permission=permission_events_view,
role=self.test_role
)
result = self._test_event_type.commit(target=self.test_object)
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_user)
self.assertEqual(notification.action, result)
def test_object_notification_single_user_and_multiple_objects_with_object_0_access(self):
self._create_local_test_object()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_role
)
result_0 = self._test_event_type.commit(target=self.test_objects[0])
self._test_event_type.commit(target=self.test_objects[1])
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_user)
self.assertEqual(notification.action, result_0)
def test_object_notification_single_user_and_multiple_objects_with_object_0_target_access(self):
self._create_local_test_object()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_role
)
result_0 = self._test_event_type.commit(
target=self.test_objects[0], action_object=self.test_objects[1]
)
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_user)
self.assertEqual(notification.action, result_0)
def test_object_notification_single_user_and_multiple_objects_with_object_1_action_object_access(self):
self._create_local_test_object()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_user
)
AccessControlList.objects.grant(
obj=self.test_objects[1], permission=permission_events_view,
role=self.test_role
)
result_0 = self._test_event_type.commit(
target=self.test_objects[0], action_object=self.test_objects[1]
)
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_user)
self.assertEqual(notification.action, result_0)
def test_object_notification_multiple_users_and_single_object_with_user_0_access(self):
self._create_local_test_user()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_roles[0]
)
result_0 = self._test_event_type.commit(target=self.test_objects[0])
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_users[0])
self.assertEqual(notification.action, result_0)
def test_object_notification_multiple_users_and_single_object_with_user_1_access(self):
self._create_local_test_user()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_roles[1]
)
result_0 = self._test_event_type.commit(target=self.test_objects[0])
self.assertEqual(Notification.objects.count(), notification_count + 1)
notification = Notification.objects.first()
self.assertEqual(notification.user, self.test_users[1])
self.assertEqual(notification.action, result_0)
def test_object_notification_multiple_users_and_single_object_with_both_user_access(self):
self._create_local_test_user()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_roles[0]
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_roles[1]
)
result_0 = self._test_event_type.commit(target=self.test_objects[0])
self.assertEqual(Notification.objects.count(), notification_count + 2)
notifications = Notification.objects.all()
user_pk_list = notifications.values_list('user__id', flat=True)
self.assertTrue(self.test_users[0].pk in user_pk_list)
self.assertEqual(notifications[0].action, result_0)
self.assertTrue(self.test_users[1].pk in user_pk_list)
self.assertEqual(notifications[1].action, result_0)
def test_object_notification_multiple_users_and_multiple_object_with_user_0_and_object_0_access(self):
self._create_local_test_user()
self._create_local_test_object()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_roles[0]
)
result_0 = self._test_event_type.commit(target=self.test_objects[0])
self._test_event_type.commit(target=self.test_objects[1])
self.assertEqual(Notification.objects.count(), notification_count + 1)
notifications = Notification.objects.all()
self.assertEqual(notifications[0].user, self.test_users[0])
self.assertEqual(notifications[0].action, result_0)
def test_object_notification_multiple_users_and_multiple_object_with_user_0_and_object_0_action_object_access(self):
self._create_local_test_user()
self._create_local_test_object()
notification_count = Notification.objects.count()
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[0]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[0],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
ObjectEventSubscription.objects.create(
content_object=self.test_objects[1],
stored_event_type=self._test_event_type.stored_event_type,
user=self.test_users[1]
)
AccessControlList.objects.grant(
obj=self.test_objects[0], permission=permission_events_view,
role=self.test_roles[0]
)
result_0 = self._test_event_type.commit(
action_object=self.test_objects[1], target=self.test_objects[0]
)
result_1 = self._test_event_type.commit(
action_object=self.test_objects[0], target=self.test_objects[1]
)
self.assertEqual(Notification.objects.count(), notification_count + 2)
notifications = Notification.objects.all()
self.assertEqual(notifications[0].user, self.test_users[0])
self.assertEqual(notifications[0].action, result_1)
self.assertEqual(notifications[1].user, self.test_users[0])
self.assertEqual(notifications[1].action, result_0)
| 39.417808 | 120 | 0.695511 | 1,960 | 17,265 | 5.753061 | 0.035204 | 0.119191 | 0.079816 | 0.072366 | 0.967453 | 0.965413 | 0.963374 | 0.962043 | 0.955835 | 0.955835 | 0 | 0.01025 | 0.220156 | 17,265 | 437 | 121 | 39.508009 | 0.827243 | 0 | 0 | 0.774286 | 0 | 0 | 0.000927 | 0 | 0 | 0 | 0 | 0 | 0.134286 | 1 | 0.048571 | false | 0 | 0.014286 | 0 | 0.068571 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
82bd13d553e16de1809e897ed9b08b5f9d8c1061 | 5,691 | py | Python | output_projection.py | https-cloud-google-com-products-ai/SentenceFunction | f5bfc7c7b7fc1611a7acad9202ce9a44dd1c5d24 | [
"Apache-2.0"
] | 34 | 2018-05-21T05:35:27.000Z | 2021-11-16T08:44:48.000Z | output_projection.py | aifin-hkust/SentenceFunction | f5bfc7c7b7fc1611a7acad9202ce9a44dd1c5d24 | [
"Apache-2.0"
] | 9 | 2018-12-13T03:03:25.000Z | 2021-07-28T02:55:26.000Z | output_projection.py | kepei1106/SentenceFunction | f5bfc7c7b7fc1611a7acad9202ce9a44dd1c5d24 | [
"Apache-2.0"
] | 11 | 2019-01-02T06:38:52.000Z | 2021-11-16T08:44:51.000Z | import tensorflow as tf
from tensorflow.contrib.layers.python.layers import layers
from tensorflow.python.ops import variable_scope
def output_projection_layer(num_units, num_symbols, latent_size, num_embed_units, topic_mask, ordinary_mask, func_mask, name="output_projection"):
def output_fn(outputs, latent_z, label_embedding):
with variable_scope.variable_scope(name):
local_d = tf.reshape(outputs, [-1, num_units])
local_l = tf.reshape(tf.concat([outputs, latent_z], 1), [-1, num_units + latent_size])
local_d2 = tf.reshape(tf.concat([outputs, latent_z, label_embedding], 1), [-1, num_units + latent_size + num_embed_units])
# type controller
l_fc1 = tf.contrib.layers.fully_connected(local_l, num_units + latent_size, activation_fn=tf.tanh, scope = 'l_fc1')
l_fc2 = tf.contrib.layers.fully_connected(l_fc1, 3, activation_fn=None, scope = 'l_fc2')
p_dis = tf.nn.softmax(l_fc2)
p_dis_1, p_dis_2, p_dis_3 = tf.split(p_dis, 3, axis = 1)
p_dis_1 = tf.reshape(tf.tile(p_dis_1, [1, num_symbols]), [-1, num_symbols])
p_dis_2 = tf.reshape(tf.tile(p_dis_2, [1, num_symbols]), [-1, num_symbols])
p_dis_3 = tf.reshape(tf.tile(p_dis_3, [1, num_symbols]), [-1, num_symbols])
type_index = p_dis
# topic words
w_fc2 = tf.contrib.layers.fully_connected(local_d, num_symbols, activation_fn=None, scope = 'w_fc2')
p_w = tf.exp(w_fc2)
p_w = p_w * tf.tile(tf.reshape(topic_mask, [1, num_symbols]), [tf.shape(local_d)[0], 1])
temp_normal = tf.tile(tf.reduce_sum(p_w, 1, keep_dims=True), [1, num_symbols])
y_prob_d = tf.div(p_w, temp_normal)
# ordinary words
d1_fc2 = tf.contrib.layers.fully_connected(local_d, num_symbols, activation_fn=None, scope = 'd1_fc2')
temp_d1 = tf.exp(d1_fc2)
temp_d1 = temp_d1 * tf.tile(tf.reshape(ordinary_mask, [1, num_symbols]), [tf.shape(local_d)[0], 1])
temp_normal = tf.tile(tf.reduce_sum(temp_d1, 1, keep_dims=True), [1, num_symbols])
y_prob_d1 = tf.div(temp_d1, temp_normal)
# function-related words
d2_fc2 = tf.contrib.layers.fully_connected(local_d2, num_symbols, activation_fn=None, scope = 'd2_fc2')
temp_d2 = tf.exp(d2_fc2)
temp_d2 = temp_d2 * tf.tile(tf.reshape(func_mask, [1, num_symbols]), [tf.shape(local_d)[0], 1])
temp_normal = tf.tile(tf.reduce_sum(temp_d2, 1, keep_dims=True), [1, num_symbols])
y_prob_d2 = tf.div(temp_d2, temp_normal)
y_prob = p_dis_1 * y_prob_d + p_dis_2 * y_prob_d1 + p_dis_3 * y_prob_d2
return y_prob, type_index
def my_sequence_loss(outputs, targets, latent_z, label_embedding, max_time):
with variable_scope.variable_scope("decoder/%s" % name):
local_labels = tf.reshape(targets, [-1])
local_d = tf.reshape(outputs, [-1, num_units])
local_l = tf.reshape(tf.concat([outputs, latent_z], 1), [-1, num_units + latent_size])
local_d2 = tf.reshape(tf.concat([outputs, latent_z, label_embedding], 1), [-1, num_units + latent_size + num_embed_units])
# type controller
l_fc1 = tf.contrib.layers.fully_connected(local_l, num_units + latent_size, activation_fn=tf.tanh, scope = 'l_fc1')
l_fc2 = tf.contrib.layers.fully_connected(l_fc1, 3, activation_fn=None, scope = 'l_fc2')
p_dis = tf.nn.softmax(l_fc2)
p_dis_1, p_dis_2, p_dis_3 = tf.split(p_dis, 3, axis = 1)
p_dis_1 = tf.reshape(tf.tile(p_dis_1, [1, num_symbols]), [-1, num_symbols])
p_dis_2 = tf.reshape(tf.tile(p_dis_2, [1, num_symbols]), [-1, num_symbols])
p_dis_3 = tf.reshape(tf.tile(p_dis_3, [1, num_symbols]), [-1, num_symbols])
# topic words
w_fc2 = tf.contrib.layers.fully_connected(local_d, num_symbols, activation_fn=None, scope = 'w_fc2')
p_w = tf.exp(w_fc2)
p_w = p_w * tf.tile(tf.reshape(topic_mask, [1, num_symbols]), [tf.shape(local_d)[0], 1])
temp_normal = tf.tile(tf.reduce_sum(p_w, 1, keep_dims=True), [1, num_symbols])
y_prob_d = tf.div(p_w, temp_normal)
# ordinary words
d1_fc2 = tf.contrib.layers.fully_connected(local_d, num_symbols, activation_fn=None, scope = 'd1_fc2')
temp_d1 = tf.exp(d1_fc2)
temp_d1 = temp_d1 * tf.tile(tf.reshape(ordinary_mask, [1, num_symbols]), [tf.shape(local_d)[0], 1])
temp_normal = tf.tile(tf.reduce_sum(temp_d1, 1, keep_dims=True), [1, num_symbols])
y_prob_d1 = tf.div(temp_d1, temp_normal)
# function-related words
d2_fc2 = tf.contrib.layers.fully_connected(local_d2, num_symbols, activation_fn=None, scope = 'd2_fc2')
temp_d2 = tf.exp(d2_fc2)
temp_d2 = temp_d2 * tf.tile(tf.reshape(func_mask, [1, num_symbols]), [tf.shape(local_d)[0], 1])
temp_normal = tf.tile(tf.reduce_sum(temp_d2, 1, keep_dims=True), [1, num_symbols])
y_prob_d2 = tf.div(temp_d2, temp_normal)
y_prob = p_dis_1 * y_prob_d + p_dis_2 * y_prob_d1 + p_dis_3 * y_prob_d2
# cross entropy
labels_onehot = tf.one_hot(local_labels, num_symbols)
labels_onehot = tf.clip_by_value(labels_onehot, 0.0, 1.0)
y_prob = tf.clip_by_value(y_prob, 1e-18, 1.0)
cross_entropy = tf.reshape(tf.reduce_sum(-labels_onehot * tf.log(y_prob), 1), [-1, 1])
return cross_entropy
return output_fn, my_sequence_loss
| 60.542553 | 146 | 0.634159 | 910 | 5,691 | 3.624176 | 0.106593 | 0.097029 | 0.080049 | 0.060643 | 0.825045 | 0.791389 | 0.791389 | 0.791389 | 0.791389 | 0.791389 | 0 | 0.038958 | 0.237744 | 5,691 | 93 | 147 | 61.193548 | 0.7213 | 0.025479 | 0 | 0.753623 | 0 | 0 | 0.014632 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.043478 | false | 0 | 0.043478 | 0 | 0.130435 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
814aeecb616864037a8e231c3ddb50ef6fccafaa | 116 | py | Python | discord/abc.py | kuzaku-developers/disnake | 61cc1ad4c2bafd39726a1447c85f7e469e41af10 | [
"MIT"
] | null | null | null | discord/abc.py | kuzaku-developers/disnake | 61cc1ad4c2bafd39726a1447c85f7e469e41af10 | [
"MIT"
] | null | null | null | discord/abc.py | kuzaku-developers/disnake | 61cc1ad4c2bafd39726a1447c85f7e469e41af10 | [
"MIT"
] | null | null | null | from disnake.abc import *
from disnake.abc import __dict__ as __original_dict__
locals().update(__original_dict__)
| 23.2 | 53 | 0.827586 | 16 | 116 | 5.125 | 0.5625 | 0.268293 | 0.341463 | 0.487805 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.103448 | 116 | 4 | 54 | 29 | 0.788462 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.666667 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 0 | 8 |
817bef3fd663068e694dbe02e20461c3b181bb41 | 86,315 | py | Python | data/transcoder_evaluation_gfg/python/PRINT_GIVEN_MATRIX_COUNTER_CLOCK_WISE_SPIRAL_FORM.py | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 241 | 2021-07-20T08:35:20.000Z | 2022-03-31T02:39:08.000Z | data/transcoder_evaluation_gfg/python/PRINT_GIVEN_MATRIX_COUNTER_CLOCK_WISE_SPIRAL_FORM.py | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 49 | 2021-07-22T23:18:42.000Z | 2022-03-24T09:15:26.000Z | data/transcoder_evaluation_gfg/python/PRINT_GIVEN_MATRIX_COUNTER_CLOCK_WISE_SPIRAL_FORM.py | mxl1n/CodeGen | e5101dd5c5e9c3720c70c80f78b18f13e118335a | [
"MIT"
] | 71 | 2021-07-21T05:17:52.000Z | 2022-03-29T23:49:28.000Z | # Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( m , n , arr ) :
k = 0 ; l = 0
cnt = 0
total = m * n
while ( k < m and l < n ) :
if ( cnt == total ) :
break
for i in range ( k , m ) :
print ( arr [ i ] [ l ] , end = " " )
cnt += 1
l += 1
if ( cnt == total ) :
break
for i in range ( l , n ) :
print ( arr [ m - 1 ] [ i ] , end = " " )
cnt += 1
m -= 1
if ( cnt == total ) :
break
if ( k < m ) :
for i in range ( m - 1 , k - 1 , - 1 ) :
print ( arr [ i ] [ n - 1 ] , end = " " )
cnt += 1
n -= 1
if ( cnt == total ) :
break
if ( l < n ) :
for i in range ( n - 1 , l - 1 , - 1 ) :
print ( arr [ k ] [ i ] , end = " " )
cnt += 1
k += 1
#TOFILL
if __name__ == '__main__':
param = [
(30,37,[[3, 6, 8, 9, 9, 9, 10, 10, 14, 15, 15, 18, 21, 21, 23, 52, 53, 57, 59, 60, 67, 68, 68, 69, 79, 80, 80, 81, 84, 85, 87, 89, 89, 90, 93, 93, 95, 99], [5, 7, 8, 12, 15, 16, 17, 19, 20, 20, 21, 29, 29, 31, 33, 34, 50, 54, 55, 57, 57, 59, 65, 70, 72, 76, 80, 81, 83, 84, 84, 85, 85, 87, 91, 94, 94, 96], [4, 7, 11, 12, 13, 14, 15, 20, 22, 23, 30, 33, 35, 35, 36, 37, 39, 40, 41, 48, 49, 59, 60, 60, 64, 65, 69, 71, 72, 81, 82, 83, 84, 87, 92, 92, 96, 97], [1, 2, 5, 7, 7, 13, 13, 14, 19, 26, 27, 28, 35, 38, 38, 41, 43, 44, 47, 49, 51, 54, 55, 56, 57, 59, 61, 61, 72, 73, 74, 78, 78, 81, 83, 85, 91, 91], [2, 6, 7, 10, 14, 16, 20, 22, 25, 28, 29, 36, 37, 38, 41, 42, 43, 46, 49, 50, 53, 54, 55, 60, 60, 62, 62, 64, 64, 69, 73, 73, 79, 85, 87, 95, 96, 97], [3, 4, 4, 9, 9, 10, 11, 13, 25, 28, 33, 37, 37, 39, 41, 43, 45, 47, 49, 49, 50, 56, 56, 56, 65, 68, 68, 72, 76, 81, 82, 84, 87, 88, 88, 95, 96, 98], [4, 6, 11, 12, 14, 15, 19, 22, 27, 29, 30, 35, 36, 37, 37, 38, 39, 45, 48, 51, 53, 53, 55, 59, 59, 62, 65, 67, 67, 74, 74, 85, 87, 90, 96, 97, 97, 99], [6, 10, 15, 16, 19, 19, 22, 22, 22, 24, 29, 30, 32, 33, 35, 35, 35, 36, 38, 43, 49, 49, 49, 53, 53, 58, 60, 62, 68, 73, 77, 80, 86, 88, 89, 92, 92, 94], [1, 2, 2, 4, 4, 5, 5, 8, 10, 11, 14, 16, 18, 23, 23, 28, 31, 36, 38, 41, 44, 45, 46, 47, 51, 53, 54, 59, 64, 66, 68, 69, 76, 85, 88, 89, 92, 99], [6, 7, 10, 14, 15, 17, 24, 26, 27, 30, 33, 37, 38, 40, 41, 44, 49, 51, 52, 52, 55, 55, 59, 64, 66, 68, 79, 80, 81, 82, 82, 85, 90, 93, 94, 95, 97, 98], [3, 8, 10, 12, 12, 21, 21, 23, 34, 35, 36, 38, 39, 39, 40, 42, 47, 51, 53, 56, 56, 58, 60, 61, 68, 74, 78, 84, 85, 86, 90, 92, 93, 94, 94, 98, 99, 99], [1, 14, 14, 17, 20, 22, 22, 22, 25, 25, 25, 26, 28, 29, 32, 34, 38, 39, 40, 42, 42, 47, 51, 56, 56, 57, 65, 67, 68, 70, 70, 70, 72, 73, 78, 90, 94, 98], [1, 9, 13, 16, 18, 21, 22, 23, 26, 26, 28, 28, 30, 33, 40, 45, 48, 49, 50, 53, 55, 57, 74, 76, 77, 81, 84, 85, 88, 89, 90, 91, 91, 93, 94, 95, 99, 99], [2, 4, 6, 10, 12, 14, 15, 15, 20, 23, 25, 26, 27, 33, 35, 38, 39, 46, 51, 54, 68, 70, 70, 73, 73, 74, 74, 76, 77, 80, 86, 89, 89, 91, 92, 93, 98, 99], [2, 3, 5, 6, 8, 9, 11, 14, 16, 24, 26, 26, 33, 33, 33, 34, 35, 36, 44, 44, 45, 47, 49, 51, 51, 56, 59, 64, 66, 67, 73, 74, 80, 86, 90, 97, 99, 99], [1, 7, 7, 16, 17, 17, 18, 18, 19, 21, 26, 29, 30, 32, 36, 39, 44, 45, 45, 47, 49, 57, 59, 62, 64, 65, 68, 71, 79, 80, 84, 85, 90, 92, 93, 94, 97, 99], [9, 9, 12, 15, 15, 17, 21, 22, 22, 28, 30, 31, 31, 33, 34, 38, 38, 38, 40, 44, 46, 46, 47, 52, 53, 59, 64, 65, 69, 73, 74, 79, 80, 83, 89, 92, 95, 99], [2, 2, 4, 5, 9, 10, 17, 23, 30, 33, 33, 33, 35, 39, 42, 43, 44, 44, 46, 54, 58, 60, 60, 61, 61, 61, 67, 68, 74, 78, 86, 87, 88, 89, 93, 97, 99, 99], [16, 16, 17, 17, 17, 17, 19, 20, 20, 22, 34, 35, 38, 38, 39, 39, 40, 42, 44, 46, 46, 48, 49, 58, 63, 66, 67, 71, 74, 75, 77, 77, 84, 84, 86, 89, 96, 98], [7, 8, 8, 11, 14, 17, 20, 27, 28, 29, 29, 34, 35, 36, 37, 39, 39, 42, 50, 50, 51, 52, 53, 55, 55, 57, 59, 61, 68, 68, 71, 74, 79, 83, 86, 87, 94, 99], [6, 8, 9, 11, 13, 15, 16, 16, 18, 20, 21, 25, 25, 32, 36, 45, 47, 51, 51, 53, 58, 58, 60, 62, 63, 66, 66, 67, 69, 70, 80, 81, 83, 85, 85, 91, 93, 99], [2, 4, 9, 9, 12, 13, 28, 29, 30, 31, 35, 35, 44, 46, 47, 48, 48, 56, 58, 61, 61, 62, 64, 65, 67, 68, 68, 78, 80, 84, 86, 87, 89, 91, 92, 94, 94, 94], [6, 7, 8, 14, 20, 34, 36, 38, 40, 41, 43, 44, 45, 52, 55, 55, 58, 60, 62, 67, 68, 73, 78, 79, 79, 80, 80, 84, 86, 86, 87, 88, 92, 92, 93, 93, 96, 98], [3, 4, 5, 7, 9, 9, 12, 15, 16, 17, 20, 23, 25, 26, 34, 36, 37, 38, 41, 42, 48, 48, 53, 59, 61, 63, 65, 66, 66, 68, 69, 70, 74, 75, 83, 86, 87, 97], [9, 9, 10, 13, 16, 21, 21, 23, 24, 26, 27, 31, 35, 35, 40, 51, 56, 56, 60, 61, 64, 66, 66, 67, 70, 70, 72, 74, 76, 77, 79, 85, 86, 89, 92, 93, 99, 99], [5, 5, 5, 7, 7, 13, 18, 19, 20, 20, 25, 26, 28, 29, 31, 37, 37, 42, 45, 46, 48, 50, 52, 53, 53, 54, 58, 64, 67, 67, 69, 75, 82, 82, 86, 93, 98, 99], [3, 7, 10, 11, 16, 19, 21, 21, 26, 31, 32, 34, 35, 37, 38, 39, 49, 51, 54, 55, 56, 57, 58, 59, 63, 65, 66, 73, 77, 78, 79, 82, 85, 85, 88, 91, 91, 96], [6, 7, 8, 10, 11, 13, 17, 17, 18, 22, 22, 23, 28, 29, 30, 35, 35, 36, 46, 48, 51, 63, 64, 66, 67, 69, 71, 73, 75, 78, 86, 86, 87, 89, 93, 94, 98, 99], [2, 3, 5, 5, 6, 14, 16, 17, 18, 20, 21, 22, 31, 36, 40, 41, 42, 43, 43, 48, 49, 59, 62, 62, 67, 70, 71, 75, 76, 79, 83, 83, 88, 92, 95, 96, 97, 98], [1, 2, 6, 10, 12, 14, 22, 24, 27, 28, 31, 33, 34, 36, 40, 45, 46, 46, 47, 49, 49, 50, 50, 58, 60, 62, 64, 65, 72, 75, 76, 81, 84, 84, 84, 87, 93, 97], [1, 2, 3, 3, 10, 14, 14, 14, 18, 18, 20, 24, 25, 26, 27, 29, 31, 36, 41, 44, 44, 46, 48, 49, 51, 51, 51, 53, 56, 64, 71, 72, 79, 80, 84, 86, 95, 97], [3, 4, 5, 5, 6, 7, 10, 11, 13, 18, 18, 19, 20, 23, 31, 32, 37, 41, 41, 42, 47, 48, 50, 56, 57, 59, 60, 65, 77, 79, 83, 83, 85, 87, 88, 89, 95, 98], [4, 10, 16, 16, 18, 21, 26, 34, 35, 36, 36, 40, 41, 45, 46, 53, 53, 55, 61, 64, 65, 66, 67, 70, 71, 78, 81, 81, 81, 84, 85, 85, 90, 93, 94, 95, 97, 98], [1, 6, 7, 11, 12, 14, 19, 25, 26, 28, 29, 32, 33, 34, 34, 36, 38, 49, 56, 59, 60, 66, 72, 72, 72, 77, 78, 79, 80, 82, 90, 91, 92, 93, 94, 95, 96, 97], [2, 5, 10, 14, 16, 19, 25, 31, 32, 32, 33, 34, 34, 38, 40, 42, 42, 43, 43, 48, 48, 49, 50, 51, 51, 57, 57, 61, 61, 76, 78, 83, 87, 89, 91, 91, 98, 99], [4, 7, 12, 13, 13, 21, 28, 29, 30, 34, 35, 36, 44, 44, 45, 46, 46, 46, 49, 68, 71, 71, 72, 77, 79, 80, 80, 83, 84, 87, 88, 89, 92, 93, 95, 97, 98, 99], [3, 7, 10, 11, 12, 16, 17, 19, 23, 25, 27, 30, 31, 33, 35, 35, 37, 41, 42, 42, 42, 64, 64, 64, 68, 70, 73, 74, 75, 83, 83, 83, 88, 89, 91, 95, 97, 98], [9, 10, 15, 16, 16, 17, 20, 20, 25, 26, 28, 29, 32, 32, 32, 39, 42, 43, 43, 45, 45, 47, 52, 55, 57, 58, 61, 66, 67, 75, 76, 84, 85, 92, 92, 94, 98, 99]],),
(16,23,[[70, 24, -36, -76, -56, -14, -44, 92, 76, 88, -22, -82, 40, 28, 52, -62, 86, 66, 4, -70, 26, 70, 32, -70, 52, 6, 10, 62, -60], [56, 32, 88, -78, -50, 64, 70, -76, 0, 86, 44, -58, -24, 0, 72, 12, 48, -76, 76, 56, 94, 48, -36, 56, 62, 60, -44, -58, 96], [82, -64, -46, 64, 84, 82, 4, 36, 52, 32, -80, 56, -48, 20, 92, 58, 74, 8, -20, -22, 30, -30, 56, 92, 98, -34, -70, 38, 66], [72, -46, 58, -86, -30, -26, -66, -58, 44, 84, 4, -34, 96, 18, 64, -22, -42, -14, 76, 30, 94, -96, -6, 80, -6, 80, 2, -82, -10], [-2, 82, 60, -70, -68, 80, 80, -46, 30, 82, 78, 36, -64, 0, -70, 64, -64, 0, -8, -44, 90, -46, -60, 76, -88, -18, 8, -76, -94], [-98, 98, -94, 36, 94, 46, 88, -52, 70, 42, -86, 40, 80, 0, 96, 8, 18, 54, -98, -28, 52, 22, -82, -72, 54, 60, 16, 4, -88], [74, -22, -56, -20, 62, 66, 92, -84, -26, -46, -56, -86, -62, 86, -86, -78, -40, -80, 96, 12, -62, -28, 64, -58, -6, -28, -62, -22, -50], [-32, -92, -88, 20, 64, -80, -78, -60, -66, 40, 46, 68, -48, 10, 84, -96, 28, -18, 62, -44, 14, -38, 0, -50, -44, 54, -52, -72, -70], [12, -92, -42, -72, 22, 24, 4, -92, -36, -6, 66, 18, 0, 70, 94, 40, -18, -4, 86, -28, 34, -24, -70, 98, 36, -74, -92, -72, -88], [90, -80, 12, -8, 16, 92, 86, 4, 38, 68, -66, -76, 16, -68, -54, -34, 38, -38, -94, 44, -82, -72, -90, 18, -80, -84, 32, -72, -64], [-98, 90, -80, 8, -90, 86, -78, -66, -42, 38, -58, 44, 24, -22, -54, 12, -86, 88, -42, -50, 34, -12, -68, -26, 16, 70, 24, -6, -88], [96, -4, -66, -56, -64, -98, 68, 12, -8, 70, 0, -32, 56, -98, -56, 94, 6, -34, 10, 46, 62, 30, -88, -50, 78, -44, 78, 24, -4], [-58, -50, 52, -30, 48, -66, 94, 36, -26, -62, -74, -82, -88, 2, 60, -44, 6, 30, 94, 74, -42, 92, 22, 46, -50, -88, -94, -4, -34], [68, 8, -86, -26, -42, -82, 10, -2, 38, 88, 4, -76, -36, -2, 56, 64, 60, 38, 70, -26, 90, -54, 86, -96, 40, 18, 12, 92, -30], [82, 28, -40, -94, 46, -40, -80, -96, 60, -14, 26, -48, 88, -68, 2, 58, 48, -50, -52, 36, 66, 6, -38, 70, 82, -38, -2, -20, 54], [-32, -36, -92, 22, -2, 64, -46, -70, 38, 38, -92, -98, 82, -50, -28, -92, 10, 94, -10, 38, -50, -80, -64, -28, 66, -36, -14, 78, 92], [4, -22, -64, -96, -8, -72, 34, 60, 92, -30, -70, -78, 38, 22, 26, -48, 92, 80, -60, -30, 30, -60, 18, 98, 72, -62, -60, -66, 42], [60, 26, -68, -30, -92, -80, -56, 60, -4, -94, 62, -88, -4, 16, 96, -74, -38, -6, -22, 26, 36, -30, 12, -42, -36, -52, 24, 34, 22], [28, -14, -96, 76, 82, -82, 98, 42, 56, 14, -80, 34, 24, 68, -86, 44, -32, -64, 54, 70, -88, 20, 48, 80, 20, 90, 6, 76, -34], [54, -96, -34, 68, 70, -96, 72, 78, -58, 4, -54, -62, 74, -66, -6, -14, 44, 32, 70, -10, 98, 86, 54, -66, 38, -36, 44, 4, -74], [94, 76, 26, -66, 54, -44, 2, 16, -54, 46, -22, -20, 38, 30, -64, 44, 90, -38, 28, -44, -82, -86, -84, -42, 22, 16, -48, 20, -66], [-88, 44, -14, 20, -90, -40, 24, 48, 64, 22, 76, -8, -30, 38, -52, -16, -94, 52, 98, 88, 48, -64, -84, -82, -2, 14, -40, -84, 62], [70, 16, 58, 30, -20, 50, -88, -8, -68, -76, 94, 36, 34, 40, -82, 58, -26, -96, 94, -52, 98, 96, 70, -90, 10, 86, -26, -18, 6], [0, 24, 82, 68, 8, -66, -24, 50, 50, -44, 28, 36, -76, 6, 90, 46, -74, 96, 28, 4, 12, 84, 60, 28, 20, 78, 60, 80, 40], [-68, 86, 60, 96, -48, 32, 8, 38, 16, -64, -14, -90, 76, 44, -48, 8, 58, 68, -28, 46, -66, 76, 98, 14, -62, -22, 18, 58, 28], [-82, 60, 32, -62, -60, -80, 90, -74, -68, 32, 72, -70, -78, 8, 82, -28, 20, 98, -56, -68, 30, 48, -54, 34, 2, 32, -38, -8, -98], [-78, 20, 56, -46, -96, 18, -94, -30, 52, -20, -8, -92, 62, 2, 80, 14, 14, 54, -48, 50, 78, 58, -82, 76, 18, -76, -94, -68, 92], [44, 40, -48, -4, 44, 84, 26, -24, 80, -90, 36, 60, -68, -74, 70, -92, 0, -98, -8, 42, -24, 46, 18, -26, -28, -28, -60, -12, -62], [-40, -98, -20, 72, 62, -32, 80, -52, 88, 10, 10, 92, -68, -6, 64, 44, 72, 52, 66, -84, -48, 8, 86, -42, -82, -50, -24, -72, -78]],),
(8,7,[[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]],),
(25,38,[[31, 11, 19, 16, 1, 30, 52, 56, 46, 97, 11, 40, 81, 29, 56, 11, 87, 59, 39, 22, 66, 33, 97, 79, 15, 8, 97, 8, 74, 91, 35, 9, 54, 55, 51, 68, 53, 22, 83, 26, 77, 35, 58, 22, 93, 31, 95], [43, 69, 23, 43, 5, 10, 71, 76, 41, 83, 44, 10, 6, 16, 18, 55, 20, 66, 24, 26, 67, 51, 70, 27, 8, 22, 35, 85, 20, 96, 60, 40, 57, 47, 32, 73, 28, 44, 28, 28, 79, 48, 44, 33, 15, 28, 97], [50, 98, 46, 72, 39, 10, 70, 14, 42, 11, 44, 50, 70, 42, 26, 64, 46, 42, 20, 49, 82, 79, 52, 78, 80, 56, 31, 38, 11, 31, 43, 26, 59, 86, 89, 75, 5, 6, 84, 7, 6, 61, 21, 92, 30, 10, 16], [91, 42, 50, 28, 22, 10, 16, 5, 88, 92, 22, 89, 85, 64, 60, 60, 35, 47, 55, 6, 74, 31, 25, 17, 60, 6, 95, 19, 56, 19, 83, 46, 42, 24, 21, 32, 89, 95, 42, 12, 60, 91, 26, 88, 9, 39, 86], [8, 32, 38, 86, 5, 66, 23, 63, 11, 45, 80, 2, 13, 8, 43, 33, 62, 91, 54, 8, 75, 37, 99, 3, 36, 44, 50, 11, 93, 20, 12, 50, 87, 42, 84, 40, 30, 4, 21, 10, 63, 13, 87, 41, 64, 54, 22], [4, 55, 21, 31, 34, 74, 51, 93, 59, 13, 51, 10, 42, 99, 16, 54, 93, 18, 43, 35, 27, 81, 89, 78, 84, 15, 90, 83, 32, 59, 99, 67, 66, 40, 44, 2, 15, 78, 54, 28, 39, 82, 86, 51, 17, 14, 70], [34, 88, 70, 24, 25, 78, 4, 28, 29, 67, 55, 4, 91, 93, 94, 30, 13, 54, 97, 34, 11, 91, 46, 4, 23, 18, 73, 13, 71, 18, 23, 11, 94, 99, 46, 19, 48, 11, 31, 47, 73, 17, 57, 12, 77, 33, 74], [88, 15, 77, 25, 79, 45, 71, 28, 59, 82, 13, 74, 24, 46, 45, 86, 66, 13, 25, 84, 60, 27, 41, 49, 9, 15, 29, 85, 47, 30, 65, 1, 17, 49, 80, 88, 46, 43, 94, 59, 2, 86, 7, 24, 42, 2, 54], [58, 22, 69, 31, 83, 1, 21, 53, 17, 38, 52, 20, 89, 33, 80, 10, 8, 22, 63, 97, 63, 26, 59, 61, 31, 57, 24, 49, 53, 44, 11, 48, 44, 69, 52, 63, 77, 54, 27, 39, 41, 34, 82, 19, 96, 72, 30], [40, 31, 5, 14, 67, 58, 47, 19, 37, 59, 95, 76, 97, 27, 76, 46, 34, 37, 36, 54, 7, 93, 18, 32, 44, 73, 62, 70, 36, 25, 8, 49, 28, 72, 50, 92, 36, 99, 61, 79, 25, 50, 80, 17, 29, 8, 34], [59, 78, 42, 86, 60, 47, 53, 9, 15, 41, 99, 93, 60, 90, 40, 52, 17, 94, 60, 95, 5, 46, 92, 56, 56, 64, 61, 94, 24, 61, 49, 25, 63, 76, 43, 94, 67, 18, 37, 69, 87, 84, 70, 19, 56, 1, 77], [96, 22, 66, 12, 15, 58, 26, 23, 83, 34, 46, 90, 66, 23, 86, 38, 47, 14, 38, 52, 98, 8, 20, 46, 78, 49, 67, 19, 5, 87, 74, 40, 46, 55, 38, 20, 76, 79, 44, 51, 78, 51, 85, 69, 79, 54, 35], [60, 66, 47, 44, 6, 3, 50, 15, 92, 34, 3, 11, 26, 18, 88, 6, 75, 33, 78, 58, 35, 87, 80, 91, 59, 4, 30, 18, 81, 58, 80, 5, 3, 1, 29, 33, 27, 57, 97, 97, 13, 52, 28, 59, 20, 13, 62], [16, 56, 5, 26, 42, 76, 43, 75, 13, 50, 40, 57, 66, 11, 79, 92, 11, 47, 37, 25, 11, 4, 12, 29, 33, 57, 77, 47, 68, 94, 88, 66, 72, 37, 44, 62, 51, 90, 45, 74, 68, 32, 45, 31, 38, 48, 78], [59, 14, 26, 4, 32, 68, 8, 57, 79, 85, 4, 57, 95, 39, 92, 4, 37, 58, 26, 91, 56, 75, 20, 70, 42, 47, 13, 61, 71, 77, 97, 47, 13, 27, 48, 65, 58, 37, 91, 63, 21, 11, 27, 1, 92, 56, 97], [78, 42, 67, 47, 47, 4, 22, 4, 45, 28, 45, 44, 34, 27, 94, 57, 22, 11, 10, 54, 12, 24, 25, 28, 20, 90, 46, 6, 51, 97, 95, 63, 85, 52, 55, 8, 55, 11, 77, 64, 12, 45, 47, 72, 59, 33, 89], [20, 3, 87, 39, 86, 57, 10, 47, 56, 8, 29, 3, 83, 32, 88, 71, 87, 95, 40, 93, 58, 21, 23, 94, 83, 32, 74, 26, 68, 49, 98, 89, 42, 33, 49, 90, 8, 28, 70, 2, 89, 6, 82, 45, 9, 9, 31], [91, 81, 34, 26, 93, 64, 9, 72, 88, 44, 94, 91, 99, 21, 9, 44, 89, 71, 3, 92, 87, 7, 86, 2, 23, 84, 74, 48, 36, 21, 23, 57, 48, 75, 2, 47, 18, 87, 44, 86, 80, 78, 19, 97, 98, 94, 45], [57, 52, 31, 53, 11, 95, 9, 99, 69, 72, 51, 8, 47, 89, 37, 7, 55, 53, 83, 15, 91, 63, 9, 5, 29, 92, 64, 85, 44, 98, 78, 79, 15, 36, 13, 58, 87, 69, 70, 11, 96, 80, 32, 17, 40, 4, 35], [13, 39, 68, 30, 2, 79, 10, 28, 20, 13, 98, 5, 52, 42, 22, 95, 97, 79, 37, 72, 25, 46, 42, 62, 96, 41, 83, 92, 7, 56, 22, 85, 75, 76, 73, 51, 73, 33, 98, 9, 62, 26, 85, 32, 48, 91, 36], [26, 34, 21, 57, 49, 47, 79, 27, 19, 71, 62, 99, 92, 35, 26, 90, 7, 15, 31, 13, 36, 38, 36, 8, 74, 92, 72, 10, 82, 18, 53, 12, 66, 67, 68, 48, 38, 19, 20, 89, 87, 33, 87, 74, 29, 55, 20], [97, 70, 79, 56, 85, 79, 48, 51, 38, 28, 64, 63, 70, 10, 7, 79, 97, 49, 93, 52, 44, 10, 63, 62, 7, 20, 29, 41, 27, 59, 74, 7, 12, 47, 57, 8, 94, 28, 16, 21, 1, 26, 84, 81, 38, 15, 2], [58, 14, 70, 96, 80, 69, 96, 99, 95, 57, 14, 65, 85, 44, 6, 86, 1, 73, 39, 10, 67, 50, 86, 62, 64, 1, 86, 43, 34, 78, 92, 28, 36, 7, 65, 23, 36, 1, 83, 32, 86, 66, 81, 73, 11, 11, 4], [34, 65, 6, 51, 52, 27, 94, 36, 37, 48, 98, 98, 56, 44, 6, 67, 47, 95, 15, 54, 77, 20, 55, 69, 56, 57, 95, 21, 50, 14, 89, 19, 16, 31, 13, 75, 2, 40, 26, 82, 51, 72, 5, 42, 20, 83, 51], [86, 32, 78, 51, 74, 30, 76, 43, 30, 45, 48, 43, 7, 91, 8, 85, 55, 50, 46, 77, 26, 90, 13, 94, 6, 38, 10, 4, 55, 14, 46, 81, 59, 18, 92, 34, 45, 36, 20, 77, 24, 64, 85, 2, 34, 47, 17], [98, 4, 97, 79, 79, 30, 81, 52, 9, 15, 97, 42, 81, 61, 91, 50, 5, 62, 2, 61, 56, 12, 74, 47, 27, 1, 71, 37, 10, 15, 76, 34, 37, 33, 94, 16, 84, 99, 20, 10, 96, 80, 74, 67, 9, 62, 29], [4, 66, 86, 39, 1, 9, 85, 49, 11, 76, 13, 40, 70, 68, 17, 31, 91, 88, 34, 92, 25, 99, 10, 56, 62, 63, 92, 35, 75, 17, 33, 65, 35, 81, 84, 73, 25, 64, 99, 81, 34, 39, 97, 79, 34, 67, 54], [56, 47, 54, 22, 12, 36, 19, 71, 71, 27, 95, 97, 72, 55, 37, 69, 88, 75, 7, 30, 76, 1, 57, 23, 28, 18, 27, 6, 72, 98, 42, 60, 55, 31, 62, 4, 36, 80, 49, 30, 28, 34, 71, 7, 53, 55, 98], [92, 2, 72, 3, 66, 11, 74, 68, 21, 60, 78, 7, 35, 83, 14, 93, 62, 75, 21, 17, 81, 5, 38, 94, 64, 95, 90, 73, 1, 20, 31, 95, 51, 76, 95, 72, 1, 92, 65, 77, 85, 10, 51, 60, 95, 86, 94], [32, 83, 13, 97, 70, 17, 76, 31, 84, 8, 79, 98, 18, 95, 48, 10, 36, 37, 2, 83, 20, 43, 47, 60, 81, 35, 76, 49, 45, 89, 26, 10, 92, 62, 89, 56, 58, 81, 24, 76, 45, 98, 67, 89, 5, 4, 19], [51, 99, 18, 42, 6, 60, 76, 55, 41, 7, 18, 27, 73, 35, 63, 78, 43, 5, 76, 77, 25, 35, 73, 90, 81, 17, 65, 92, 30, 52, 80, 99, 48, 27, 96, 39, 21, 83, 56, 44, 46, 88, 90, 37, 49, 93, 9], [48, 87, 6, 42, 99, 31, 56, 38, 40, 16, 77, 75, 40, 97, 71, 47, 88, 94, 79, 83, 75, 5, 1, 24, 88, 37, 55, 90, 47, 15, 39, 17, 35, 45, 39, 91, 71, 54, 89, 98, 34, 13, 56, 36, 67, 99, 32], [35, 2, 27, 59, 17, 6, 17, 71, 88, 39, 36, 6, 44, 2, 61, 97, 52, 96, 67, 59, 14, 42, 17, 71, 59, 67, 17, 96, 70, 28, 8, 99, 7, 11, 77, 18, 3, 43, 58, 53, 51, 33, 83, 11, 35, 98, 64], [87, 77, 12, 98, 78, 53, 90, 33, 64, 90, 91, 1, 45, 90, 50, 8, 58, 12, 74, 80, 85, 33, 70, 42, 57, 58, 47, 82, 38, 31, 89, 79, 86, 9, 56, 60, 23, 19, 35, 3, 50, 93, 16, 69, 69, 23, 72], [55, 90, 11, 41, 28, 40, 82, 89, 87, 5, 20, 57, 77, 37, 71, 77, 50, 71, 37, 71, 98, 26, 62, 42, 37, 50, 64, 19, 6, 39, 50, 53, 18, 56, 39, 57, 96, 57, 49, 50, 10, 11, 59, 31, 66, 88, 35], [3, 78, 32, 3, 22, 42, 45, 57, 5, 21, 16, 48, 46, 33, 84, 95, 40, 32, 33, 45, 48, 32, 68, 60, 10, 15, 38, 18, 9, 43, 36, 50, 21, 19, 33, 71, 60, 18, 57, 80, 78, 24, 32, 11, 53, 52, 9], [1, 17, 36, 26, 14, 50, 53, 69, 69, 94, 21, 21, 18, 16, 67, 60, 70, 3, 30, 50, 45, 63, 45, 31, 69, 8, 64, 8, 44, 38, 37, 22, 31, 85, 42, 45, 47, 68, 64, 34, 71, 64, 24, 96, 49, 38, 21], [5, 26, 29, 5, 76, 10, 44, 84, 51, 31, 49, 53, 21, 10, 59, 42, 70, 90, 1, 4, 58, 45, 27, 4, 42, 54, 55, 97, 67, 70, 12, 14, 66, 62, 61, 37, 83, 55, 97, 57, 16, 77, 66, 50, 47, 87, 2], [46, 1, 84, 31, 57, 82, 83, 43, 59, 2, 37, 29, 99, 68, 48, 84, 70, 48, 44, 87, 66, 88, 66, 65, 45, 37, 54, 2, 44, 10, 21, 23, 28, 83, 79, 62, 83, 45, 52, 11, 97, 88, 37, 45, 94, 68, 71], [87, 89, 96, 21, 49, 74, 7, 46, 65, 92, 83, 20, 3, 14, 7, 83, 54, 87, 49, 92, 67, 50, 80, 87, 56, 20, 22, 19, 50, 80, 98, 31, 40, 5, 39, 9, 4, 76, 52, 2, 86, 45, 88, 79, 62, 59, 67], [99, 70, 74, 19, 75, 38, 5, 54, 1, 99, 85, 57, 27, 34, 71, 57, 94, 34, 28, 69, 5, 12, 11, 59, 4, 67, 63, 67, 66, 4, 71, 96, 32, 46, 1, 47, 71, 34, 52, 51, 49, 84, 7, 68, 43, 80, 17], [8, 65, 11, 13, 26, 6, 36, 83, 32, 63, 11, 39, 88, 55, 40, 79, 85, 72, 99, 86, 36, 9, 3, 70, 32, 36, 8, 65, 51, 99, 82, 48, 83, 69, 4, 8, 95, 95, 2, 41, 48, 36, 51, 36, 29, 65, 39], [88, 90, 78, 25, 22, 42, 28, 69, 82, 92, 5, 62, 92, 48, 9, 94, 1, 32, 9, 50, 18, 86, 48, 59, 14, 73, 87, 59, 91, 31, 61, 19, 21, 99, 91, 65, 72, 54, 76, 57, 68, 3, 83, 21, 93, 1, 41], [31, 87, 42, 13, 14, 4, 49, 16, 58, 97, 71, 91, 38, 99, 3, 34, 13, 15, 51, 11, 83, 25, 97, 64, 14, 74, 52, 17, 63, 80, 37, 35, 69, 95, 10, 60, 55, 61, 15, 55, 4, 75, 66, 11, 91, 29, 44], [69, 8, 28, 93, 78, 65, 82, 14, 99, 86, 4, 14, 41, 55, 8, 86, 56, 58, 1, 81, 2, 92, 84, 75, 18, 11, 11, 82, 66, 83, 42, 8, 64, 3, 43, 97, 4, 37, 13, 99, 99, 82, 26, 20, 71, 76, 95], [30, 63, 45, 6, 22, 40, 69, 52, 5, 84, 31, 52, 67, 64, 52, 33, 29, 83, 87, 68, 60, 69, 16, 19, 23, 92, 98, 93, 79, 40, 52, 56, 48, 26, 71, 21, 7, 79, 26, 66, 55, 46, 52, 20, 14, 2, 16], [45, 37, 1, 72, 82, 14, 21, 94, 66, 1, 49, 51, 75, 95, 7, 22, 29, 5, 24, 99, 65, 23, 33, 19, 50, 45, 97, 28, 97, 3, 43, 37, 51, 68, 81, 7, 55, 51, 50, 83, 89, 17, 76, 27, 53, 10, 53]],),
(20,19,[[-92, -90, -82, -80, -70, -62, -58, -48, -30, -26, -26, -14, -6, 4, 4, 4, 10, 12, 20, 24, 32, 36, 36, 40, 42, 54, 64, 64, 88, 90, 92, 96], [-98, -92, -76, -56, -54, -38, -36, -34, -32, -24, -22, -22, -20, -16, -4, -2, -2, -2, 0, 4, 6, 20, 26, 34, 42, 44, 44, 60, 72, 80, 86, 98], [-86, -84, -82, -78, -72, -66, -60, -54, -24, -18, -12, -10, -10, -4, 6, 18, 20, 22, 32, 38, 40, 48, 64, 68, 68, 68, 70, 78, 84, 84, 94, 98], [-96, -78, -76, -58, -54, -50, -46, -46, -42, -36, -34, -26, -22, -18, -14, -10, -6, -4, -2, 10, 26, 36, 46, 46, 52, 56, 76, 80, 80, 88, 94, 98], [-82, -64, -56, -52, -34, -28, -22, -20, -18, -16, -6, -2, 0, 0, 10, 10, 12, 12, 14, 20, 22, 32, 34, 46, 46, 50, 54, 62, 64, 72, 82, 90], [-98, -82, -78, -78, -72, -64, -60, -50, -50, -48, -42, 20, 26, 32, 40, 40, 44, 44, 48, 58, 62, 68, 76, 78, 84, 86, 90, 94, 94, 96, 98, 98], [-96, -96, -92, -76, -74, -72, -66, -56, -48, -38, -38, -30, -8, -8, -4, 6, 12, 12, 14, 46, 54, 56, 58, 60, 60, 68, 72, 78, 80, 82, 82, 84], [-96, -96, -96, -94, -70, -66, -64, -64, -44, -20, -18, -14, -10, -8, -6, -2, -2, 2, 4, 10, 24, 30, 30, 40, 40, 58, 64, 68, 76, 76, 96, 98], [-88, -84, -84, -64, -64, -58, -40, -38, -32, -30, -28, -24, -14, -6, -6, 0, 14, 26, 28, 28, 34, 36, 36, 44, 48, 50, 54, 62, 68, 74, 74, 94], [-98, -96, -96, -88, -86, -76, -74, -74, -70, -70, -52, -42, -34, -16, -2, 0, 8, 8, 14, 18, 34, 34, 42, 46, 54, 56, 70, 78, 80, 92, 94, 96], [-96, -94, -90, -90, -76, -74, -62, -62, -54, -46, -38, -32, -32, -22, -22, -10, 2, 4, 6, 34, 48, 48, 50, 54, 56, 60, 74, 76, 80, 90, 96, 96], [-72, -70, -64, -62, -62, -60, -52, -50, -44, -40, -34, -32, -28, -4, 2, 14, 16, 34, 34, 44, 52, 54, 66, 68, 68, 68, 72, 82, 84, 88, 88, 94], [-98, -96, -88, -84, -78, -56, -48, -42, -36, -34, -26, -18, -10, 0, 6, 8, 14, 20, 26, 32, 40, 46, 48, 54, 54, 60, 60, 78, 92, 96, 98, 98], [-94, -78, -72, -54, -54, -54, -52, -48, -44, -44, -34, -28, -26, -18, -16, -16, -12, -10, -4, 2, 2, 2, 8, 24, 26, 44, 52, 52, 62, 72, 76, 84], [-94, -92, -86, -78, -72, -72, -70, -64, -58, -56, -56, -54, -40, -30, -30, -26, -10, -4, 4, 8, 32, 32, 44, 48, 50, 58, 64, 82, 84, 88, 92, 96], [-86, -84, -68, -34, -24, -22, -6, -6, -4, -4, -2, 0, 0, 0, 2, 2, 12, 18, 24, 26, 36, 40, 46, 56, 58, 64, 68, 80, 82, 84, 88, 90], [-92, -80, -78, -74, -70, -62, -50, -48, -48, -46, -44, -42, -30, -16, -2, 0, 22, 24, 26, 26, 44, 54, 62, 64, 64, 68, 70, 78, 86, 92, 98, 98], [-92, -92, -92, -80, -76, -74, -64, -58, -54, -52, -50, -48, -42, -38, -30, -24, -20, -20, -6, -4, -2, 8, 12, 18, 30, 40, 44, 50, 52, 66, 70, 74], [-98, -90, -86, -74, -58, -44, -36, -26, -18, -16, -8, -6, -2, 2, 4, 8, 18, 22, 24, 34, 42, 48, 48, 48, 54, 60, 64, 70, 80, 84, 94, 98], [-94, -88, -82, -78, -78, -76, -74, -70, -70, -68, -64, -56, -36, -34, -28, -26, -24, -20, -16, -2, 6, 12, 24, 46, 60, 62, 68, 74, 74, 84, 88, 98], [-90, -80, -78, -72, -68, -62, -58, -48, -46, -44, -32, -16, -6, 0, 18, 24, 26, 28, 36, 44, 50, 52, 52, 64, 76, 76, 82, 82, 84, 86, 94, 96], [-98, -96, -92, -92, -86, -78, -64, -34, -32, -20, 4, 8, 12, 12, 16, 18, 26, 28, 32, 36, 36, 40, 48, 52, 52, 56, 60, 64, 76, 76, 78, 82], [-94, -88, -64, -54, -50, -42, -34, -24, -16, -12, -4, 4, 4, 8, 16, 22, 22, 32, 38, 38, 40, 42, 44, 50, 54, 64, 70, 72, 76, 80, 92, 94], [-98, -96, -84, -72, -64, -60, -56, -54, -48, -46, -40, -34, -32, -30, -28, -24, -20, -16, -10, -2, 0, 2, 16, 34, 40, 44, 48, 52, 66, 66, 82, 90], [-98, -96, -96, -94, -68, -66, -60, -50, -38, -34, -12, -12, -4, 2, 12, 14, 16, 22, 24, 28, 30, 38, 50, 56, 62, 78, 80, 80, 82, 90, 94, 96], [-90, -80, -76, -70, -68, -68, -64, -50, -42, -40, -38, -34, -26, -24, -20, -14, -14, -10, -4, -2, 0, 0, 22, 28, 44, 58, 58, 66, 66, 70, 72, 96], [-98, -94, -90, -90, -88, -84, -76, -72, -70, -70, -34, -28, -26, -12, 6, 6, 6, 8, 14, 20, 24, 32, 58, 62, 68, 68, 68, 78, 80, 84, 92, 92], [-90, -84, -80, -72, -72, -70, -64, -60, -58, -48, -46, -44, -20, -18, -12, -10, -8, -6, -2, 2, 6, 12, 14, 14, 22, 32, 40, 56, 66, 86, 90, 92], [-96, -88, -84, -76, -58, -52, -50, -46, -42, -38, -30, -28, -20, -10, -2, 0, 2, 16, 22, 26, 34, 36, 46, 54, 58, 60, 60, 76, 76, 78, 82, 88], [-94, -88, -84, -84, -82, -72, -68, -60, -58, -50, -40, -30, -22, -12, -12, -8, -4, -2, 8, 10, 16, 24, 30, 32, 36, 38, 70, 72, 84, 86, 90, 90], [-98, -80, -80, -76, -70, -60, -46, -40, -34, -32, -26, -26, -26, -24, -22, -20, -16, 0, 12, 34, 44, 46, 48, 60, 66, 80, 82, 84, 86, 94, 94, 98], [-96, -88, -86, -84, -76, -64, -38, -30, -22, -6, -6, -4, -2, 12, 20, 22, 24, 24, 26, 28, 32, 32, 44, 46, 68, 78, 80, 80, 84, 92, 94, 94]],),
(34,24,[[1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0], [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1], [0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0], [1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]],),
(29,32,[[1, 1, 9, 19, 20, 23, 25, 27, 28, 28, 29, 31, 33, 33, 36, 38, 41, 42, 44, 47, 47, 51, 57, 58, 61, 63, 65, 66, 68, 70, 70, 71, 74, 76, 80, 83, 85, 90, 90, 93, 93, 94, 97], [1, 3, 3, 4, 5, 7, 7, 10, 12, 17, 18, 24, 24, 25, 25, 27, 31, 31, 34, 39, 40, 41, 41, 42, 49, 49, 51, 55, 62, 64, 66, 72, 74, 74, 80, 82, 83, 84, 84, 91, 94, 96, 98], [1, 5, 6, 6, 7, 9, 18, 20, 20, 21, 22, 22, 27, 29, 30, 36, 36, 37, 37, 37, 39, 45, 48, 48, 48, 53, 55, 56, 58, 59, 59, 66, 69, 75, 76, 77, 82, 82, 84, 86, 88, 93, 93], [1, 5, 7, 13, 18, 19, 23, 23, 25, 28, 28, 29, 33, 34, 34, 35, 41, 45, 45, 45, 45, 49, 50, 52, 54, 55, 55, 60, 63, 65, 66, 67, 67, 68, 70, 72, 74, 79, 79, 83, 83, 89, 97], [3, 3, 5, 6, 11, 15, 17, 20, 24, 25, 26, 29, 31, 34, 34, 35, 40, 43, 43, 44, 44, 52, 52, 54, 54, 64, 65, 65, 67, 69, 69, 72, 77, 78, 78, 78, 81, 83, 88, 88, 90, 93, 95], [1, 4, 10, 11, 14, 15, 17, 21, 21, 22, 23, 24, 27, 28, 31, 32, 33, 33, 39, 41, 50, 53, 55, 57, 61, 62, 65, 65, 65, 71, 73, 74, 78, 81, 81, 82, 83, 86, 86, 92, 98, 98, 99], [5, 6, 6, 7, 9, 18, 19, 20, 20, 22, 23, 27, 29, 31, 38, 38, 39, 40, 42, 44, 53, 56, 58, 64, 65, 67, 68, 69, 71, 73, 73, 74, 76, 77, 77, 79, 82, 88, 90, 94, 94, 96, 97], [1, 2, 3, 4, 5, 7, 9, 10, 10, 13, 20, 21, 23, 26, 27, 29, 29, 29, 31, 33, 34, 34, 37, 39, 41, 43, 46, 46, 48, 53, 55, 58, 58, 61, 67, 67, 70, 78, 79, 90, 93, 95, 96], [1, 1, 3, 4, 5, 8, 10, 11, 11, 13, 15, 18, 21, 21, 24, 30, 30, 31, 32, 44, 46, 54, 59, 61, 62, 65, 66, 67, 68, 70, 72, 76, 77, 78, 78, 80, 81, 83, 85, 87, 89, 92, 96], [1, 4, 5, 5, 7, 10, 11, 13, 22, 25, 26, 28, 29, 29, 33, 34, 34, 36, 37, 37, 38, 40, 45, 46, 47, 53, 56, 62, 62, 68, 68, 75, 78, 80, 82, 87, 89, 89, 91, 91, 92, 96, 97], [1, 4, 6, 6, 6, 9, 9, 10, 15, 17, 22, 23, 31, 31, 33, 33, 37, 38, 44, 46, 50, 56, 57, 58, 62, 63, 65, 70, 71, 76, 79, 79, 80, 81, 83, 87, 88, 88, 89, 91, 92, 94, 99], [1, 1, 2, 7, 10, 10, 14, 15, 18, 22, 25, 27, 28, 30, 32, 35, 37, 41, 42, 43, 53, 53, 55, 57, 57, 61, 61, 63, 64, 66, 67, 67, 68, 71, 74, 75, 76, 76, 78, 78, 78, 85, 89], [2, 9, 10, 10, 11, 11, 18, 26, 34, 35, 35, 36, 36, 40, 43, 43, 45, 49, 49, 50, 54, 64, 65, 65, 66, 68, 69, 70, 72, 78, 79, 81, 81, 82, 91, 92, 92, 93, 94, 95, 95, 96, 98], [4, 5, 5, 10, 10, 11, 13, 16, 21, 22, 24, 33, 33, 33, 34, 35, 37, 38, 39, 41, 43, 46, 51, 56, 56, 58, 58, 66, 73, 74, 74, 76, 76, 77, 78, 78, 81, 83, 87, 88, 94, 95, 97], [5, 7, 8, 10, 11, 14, 14, 15, 15, 19, 19, 21, 23, 23, 31, 39, 44, 46, 46, 47, 53, 53, 54, 57, 57, 58, 59, 60, 62, 68, 68, 69, 72, 79, 80, 80, 80, 81, 84, 89, 91, 98, 99], [1, 1, 2, 7, 8, 9, 14, 15, 18, 20, 21, 33, 34, 36, 37, 42, 46, 48, 53, 55, 55, 66, 67, 71, 73, 77, 80, 82, 84, 84, 85, 87, 87, 88, 90, 92, 92, 93, 93, 94, 95, 98, 99], [1, 1, 1, 9, 9, 11, 13, 18, 19, 20, 32, 32, 34, 44, 45, 46, 47, 50, 50, 52, 54, 56, 57, 59, 60, 61, 61, 63, 67, 67, 68, 76, 76, 77, 78, 80, 83, 85, 88, 92, 93, 94, 95], [3, 5, 6, 7, 7, 11, 14, 17, 18, 19, 26, 26, 27, 28, 29, 33, 35, 36, 36, 37, 41, 47, 49, 55, 58, 69, 71, 72, 74, 79, 80, 81, 85, 87, 90, 92, 93, 94, 94, 94, 96, 97, 98], [8, 9, 11, 13, 13, 13, 16, 21, 21, 23, 23, 28, 42, 46, 47, 48, 55, 58, 60, 64, 67, 68, 71, 71, 72, 73, 73, 73, 77, 77, 80, 81, 86, 88, 88, 90, 90, 91, 93, 93, 95, 96, 97], [1, 5, 9, 10, 12, 13, 14, 15, 19, 20, 25, 27, 30, 30, 33, 37, 38, 39, 40, 41, 42, 42, 51, 54, 55, 58, 59, 60, 64, 64, 73, 74, 78, 79, 80, 80, 85, 87, 88, 91, 93, 97, 99], [2, 3, 4, 5, 8, 9, 9, 12, 12, 14, 17, 17, 18, 21, 23, 23, 26, 32, 34, 34, 34, 45, 45, 48, 49, 56, 60, 62, 63, 64, 67, 71, 71, 75, 76, 77, 77, 79, 81, 83, 87, 88, 98], [3, 3, 3, 7, 9, 12, 15, 18, 26, 27, 30, 34, 37, 38, 41, 42, 44, 44, 45, 57, 58, 64, 67, 67, 70, 71, 73, 75, 76, 80, 83, 86, 87, 88, 88, 89, 90, 90, 92, 95, 97, 98, 98], [1, 1, 3, 3, 4, 5, 6, 9, 10, 11, 12, 12, 20, 21, 21, 22, 23, 28, 32, 35, 43, 48, 52, 53, 53, 56, 59, 60, 65, 66, 70, 71, 73, 74, 74, 79, 81, 83, 85, 87, 91, 97, 98], [3, 3, 3, 4, 15, 21, 24, 25, 28, 31, 31, 33, 38, 40, 41, 42, 43, 43, 46, 46, 46, 46, 47, 50, 50, 58, 58, 61, 67, 67, 70, 71, 73, 79, 85, 88, 90, 90, 91, 91, 93, 96, 97], [2, 5, 5, 6, 9, 12, 16, 17, 17, 18, 20, 22, 26, 27, 31, 36, 38, 40, 43, 45, 47, 48, 55, 62, 62, 64, 65, 67, 68, 69, 71, 72, 73, 76, 79, 80, 82, 84, 87, 88, 91, 94, 99], [1, 8, 8, 11, 21, 22, 23, 23, 33, 34, 36, 40, 40, 41, 42, 42, 45, 46, 47, 56, 57, 60, 60, 62, 66, 67, 73, 73, 76, 80, 80, 80, 82, 83, 83, 83, 84, 88, 92, 92, 94, 98, 99], [6, 9, 11, 14, 14, 17, 18, 20, 20, 21, 21, 21, 23, 29, 33, 34, 40, 43, 44, 45, 49, 54, 55, 58, 59, 65, 65, 68, 70, 73, 74, 77, 79, 82, 83, 84, 85, 86, 88, 93, 93, 97, 97], [2, 8, 10, 10, 11, 13, 15, 15, 16, 20, 22, 23, 24, 27, 29, 29, 31, 37, 37, 40, 40, 43, 45, 47, 47, 49, 49, 50, 51, 61, 63, 65, 72, 72, 75, 76, 76, 80, 82, 82, 84, 93, 97], [1, 6, 11, 12, 15, 19, 21, 26, 26, 27, 29, 31, 31, 32, 37, 37, 38, 41, 46, 55, 56, 56, 59, 59, 60, 63, 64, 66, 74, 76, 81, 82, 82, 83, 88, 93, 93, 95, 95, 96, 98, 99, 99], [1, 2, 8, 8, 8, 12, 12, 20, 22, 22, 23, 34, 34, 37, 38, 38, 40, 42, 49, 52, 54, 55, 56, 57, 63, 64, 65, 66, 68, 70, 71, 71, 71, 71, 73, 75, 77, 78, 78, 79, 80, 91, 99], [2, 2, 4, 8, 10, 11, 12, 15, 25, 35, 37, 40, 41, 44, 44, 46, 46, 48, 48, 48, 49, 50, 50, 53, 55, 59, 62, 68, 69, 70, 76, 76, 80, 81, 82, 84, 84, 86, 89, 91, 92, 96, 99], [1, 2, 4, 7, 9, 15, 17, 18, 20, 20, 20, 26, 27, 29, 30, 35, 36, 44, 48, 49, 49, 57, 58, 60, 62, 67, 72, 75, 77, 78, 80, 83, 83, 83, 84, 85, 85, 90, 91, 94, 94, 96, 98], [2, 5, 19, 19, 21, 21, 23, 28, 32, 33, 39, 41, 46, 49, 51, 51, 53, 54, 54, 57, 57, 58, 63, 63, 64, 64, 64, 65, 65, 67, 69, 70, 70, 71, 72, 75, 75, 79, 88, 88, 89, 91, 95], [2, 2, 6, 6, 11, 14, 16, 16, 21, 26, 29, 31, 34, 35, 36, 36, 39, 40, 43, 48, 62, 62, 65, 66, 66, 67, 68, 72, 75, 76, 77, 81, 84, 85, 86, 87, 88, 92, 93, 94, 96, 96, 99], [1, 3, 3, 4, 7, 8, 8, 8, 10, 12, 13, 17, 20, 20, 21, 24, 28, 30, 30, 35, 38, 41, 42, 44, 48, 50, 53, 56, 57, 57, 58, 59, 62, 67, 73, 74, 74, 75, 75, 76, 90, 96, 99], [1, 1, 6, 8, 8, 9, 11, 11, 12, 14, 14, 14, 16, 18, 18, 22, 23, 23, 24, 25, 25, 26, 27, 30, 40, 40, 41, 43, 47, 48, 49, 52, 55, 57, 61, 71, 73, 86, 91, 94, 94, 97, 98], [4, 8, 10, 11, 19, 21, 27, 27, 28, 29, 29, 31, 34, 36, 38, 39, 40, 42, 42, 45, 48, 54, 56, 57, 57, 58, 60, 62, 62, 65, 67, 71, 73, 73, 80, 83, 85, 86, 89, 91, 92, 93, 93], [2, 3, 5, 6, 6, 9, 10, 11, 12, 14, 15, 19, 19, 20, 21, 22, 24, 27, 27, 34, 38, 39, 39, 41, 46, 47, 50, 51, 51, 53, 56, 59, 60, 71, 79, 83, 84, 84, 86, 87, 87, 89, 93], [2, 6, 6, 7, 7, 8, 9, 10, 11, 17, 18, 22, 28, 30, 32, 32, 33, 37, 38, 39, 42, 54, 61, 63, 68, 71, 71, 71, 73, 76, 78, 80, 80, 88, 89, 92, 92, 92, 93, 93, 94, 98, 99], [8, 11, 11, 12, 14, 14, 15, 16, 16, 19, 19, 21, 26, 31, 32, 33, 37, 38, 40, 41, 41, 44, 45, 50, 58, 64, 65, 67, 69, 70, 72, 72, 72, 79, 81, 87, 90, 91, 91, 95, 98, 99, 99], [2, 4, 5, 7, 10, 13, 17, 18, 19, 29, 29, 30, 31, 35, 35, 42, 43, 44, 45, 46, 47, 48, 49, 49, 51, 51, 58, 58, 60, 63, 64, 66, 73, 77, 80, 81, 82, 87, 88, 94, 98, 98, 99], [3, 4, 8, 14, 15, 15, 19, 26, 27, 29, 31, 31, 31, 33, 33, 36, 39, 40, 42, 42, 44, 46, 48, 48, 49, 52, 54, 54, 55, 57, 65, 65, 71, 71, 78, 83, 86, 89, 89, 90, 90, 95, 99], [1, 1, 7, 7, 7, 11, 13, 13, 14, 16, 17, 17, 20, 22, 23, 24, 27, 28, 28, 29, 29, 31, 38, 46, 48, 48, 48, 50, 57, 69, 73, 75, 80, 81, 84, 84, 87, 87, 87, 90, 96, 98, 99]],),
(26,33,[[-86, 20, -54, -26, 56, -86, 34, 90, -62, 18, -58, 92, 32, -76, -64, 44, -48, 10, 88, -8, -56, -90, -42, 94, -18, 48, -64, -46, -32, -72, 44, 22, -66, -10, 84, -46], [88, 32, -90, 14, -50, 42, 14, -26, 48, 68, 72, 44, 70, 94, 38, -46, -50, -2, 4, 82, -54, -84, -42, 78, 48, 22, -78, 4, 8, 22, -78, -92, -66, -38, -90, 88], [78, 40, -94, 12, -44, -74, -34, -30, -70, 90, -26, -62, 46, 46, 22, 98, 94, 38, 66, -34, -66, -82, -98, 46, -56, -44, -36, 86, 68, -2, 98, 28, -2, 20, -46, 66], [12, 72, -98, 56, 42, 48, 2, -22, 0, 40, 8, 84, 12, -36, -46, -6, 0, -4, 72, 42, -88, -38, -10, 54, -96, 36, -22, 34, 98, 88, 78, 10, 28, -2, 46, 34], [32, 20, -28, 68, -6, 86, -80, -66, 86, 22, -40, -74, 50, 38, -62, 10, -86, 86, -56, -6, -54, 66, -20, 68, 64, 90, -84, -36, 58, -70, 24, 80, -72, 44, 62, 40], [-36, -28, 96, -72, -10, -30, 82, 62, -94, 84, -76, -40, 30, -70, -6, -58, 28, -84, -50, -58, 16, -52, -32, -26, 96, 64, -6, -34, 30, 50, 44, 94, -52, 54, 8, 18], [-68, -78, -70, 54, -34, 24, 62, -92, 76, -42, 26, -92, -70, -54, -68, 64, -62, -14, 76, -98, -26, -8, 42, -10, -24, 26, 22, 78, -84, 56, 72, 96, 6, 78, 48, -48], [-48, 72, -42, 34, -48, 30, -58, 80, -34, -84, -56, 92, -22, 60, 76, -50, 66, 66, 68, 98, -18, 80, -82, 20, -32, -54, -24, -58, -26, -48, 72, -2, -46, -12, 6, 22], [30, -50, -42, 6, -98, -2, 46, 16, 14, 26, 28, -64, -42, -76, 66, 56, -74, 60, 6, 38, -36, 4, -98, 62, -36, -12, 34, 98, 64, -72, 20, -92, 28, -64, -62, 26], [24, 62, -90, 20, -84, 82, -22, -24, 30, -40, 48, -84, -98, -22, 32, -22, -40, 12, -20, -66, -40, 22, -2, 36, 64, -98, 66, 30, -36, 64, 22, 56, 90, -10, 76, -64], [74, 14, 94, 80, 96, -38, 98, 54, -90, 32, -8, 22, 18, -48, 32, -38, -72, -26, 46, 44, 92, 64, -36, -50, 78, 24, -58, -14, 52, -44, -56, -42, 0, -28, -74, 52], [54, -66, 14, -54, 38, 82, -22, -12, -22, -96, 12, 98, -72, -32, -8, -28, -50, 22, 8, -60, 88, -62, 72, -26, 22, -46, 68, 12, 84, 60, 4, -94, 84, -58, -6, 52], [54, 58, 44, -54, -40, -24, -54, 20, 16, 6, -72, 16, 96, 30, -74, 84, -82, -6, 86, 26, 82, 44, -40, -84, -58, -60, -72, 72, 0, -40, 72, 16, 8, 94, -70, -64], [-24, 26, -80, 72, -54, 60, 72, -26, 62, -82, -68, -52, -64, 64, -22, -32, 4, -80, -46, 50, 8, -74, -46, -62, 42, 86, -24, 16, 28, -88, -74, -6, 30, 84, 96, -46], [86, 28, 72, -66, -78, 84, 4, 72, 72, 14, -96, -56, 80, -74, -56, -84, -58, -74, -12, 42, -12, 6, 96, -14, 34, -28, 6, 80, 94, 88, 76, 86, 76, -16, -78, 88], [-48, -50, -92, -42, -82, 8, 58, -60, -80, 80, 62, -16, -72, 22, -82, -62, 32, 12, -20, 26, 36, 18, 88, 40, -74, -44, 8, -88, -58, 0, -8, -18, -74, -40, -30, 54], [-46, -4, 36, -42, 50, 58, 8, 38, -2, 4, 22, 72, 36, -48, -56, 98, -70, 36, 0, 20, 8, -74, -94, 32, -28, 30, -92, -96, 86, 76, -12, 22, -96, 70, 16, 62], [-40, 70, -28, 42, -80, -30, -46, 58, -30, 76, 50, 60, 22, 8, 58, -94, -52, 4, -80, 92, -92, 44, 36, 94, -52, 42, -30, -98, 68, 92, 46, -24, 36, -52, 62, 88], [-64, -60, -38, 0, 50, 90, -22, -34, 82, 58, -58, -8, 76, 4, -70, -66, -66, -60, 14, 42, 16, -2, 92, -84, -88, -66, 24, -14, 38, -76, 4, 0, 14, 40, -6, 2], [-48, -98, 88, -30, -44, 22, -30, -48, -24, 88, -54, 0, 64, -84, 34, -18, 66, -8, -2, 62, -64, -46, -94, -26, -76, 36, -22, -40, -54, -72, 86, 64, 20, 78, 84, 78], [36, 30, -12, 38, 14, -90, -26, -24, 76, -78, 18, 42, -8, 46, 32, -32, -64, 74, -38, 6, 70, 58, 44, 8, -42, 10, 28, 80, -52, 92, -48, -18, -42, 84, -84, -44], [88, 4, 34, 48, 18, 64, 74, 46, -74, -46, 96, 68, 70, -60, -2, -20, 10, -52, 10, 20, 60, -10, -56, 96, -36, -72, -70, 14, 90, 38, -4, -64, -78, 4, -82, -58], [-20, 72, -88, -2, 68, -26, -94, 44, -44, -34, -82, -70, -58, 28, 56, 0, 18, -46, 42, 60, -80, 38, 14, -74, 20, -54, 90, 0, -86, 32, -90, 92, 44, -96, -38, -18], [38, -86, -92, 28, 18, 72, 42, -64, 92, 36, 60, 80, 50, 42, -56, 40, -92, 42, 12, 72, 2, 54, -22, -60, -92, 72, -58, -40, 98, -36, 70, 98, -70, -72, 78, -76], [-64, 58, -68, 90, -74, 32, -64, -30, 66, -36, 90, -16, 62, 82, 62, 20, -16, 32, 58, -80, 72, 98, 80, 60, -42, 8, 90, -66, -92, -54, -52, -18, -48, 98, 98, 58], [-12, 4, -22, 48, 60, 90, 70, -68, 84, 18, 6, -62, -98, -70, -58, -94, 92, 76, 6, 74, 44, 60, -6, -50, 30, 8, -18, 88, -50, 84, 94, -82, 32, 12, -36, -92], [-34, -46, -38, -38, 54, 84, -80, -92, -26, 94, 12, 88, -70, -74, 28, -42, -68, -62, 14, 42, 20, 6, 16, 26, -62, -22, -94, -28, -76, -96, 54, 30, -28, -28, -2, -22], [-18, -18, -36, 88, -16, -62, -12, -70, -34, 28, -10, 52, 12, 48, -38, -88, 24, -28, 0, -22, -74, 32, -54, 60, -36, 10, -32, 0, -60, -90, -6, 50, -24, -84, 70, 80], [74, -86, -98, -62, -74, -24, 52, 46, -12, 96, 6, 4, -52, 66, 40, 64, -16, 20, -52, 62, 10, -42, -94, -68, 60, 38, 44, 0, -14, 94, -56, 36, 84, 30, -96, -24], [60, -8, -86, -42, 60, -96, -10, 58, 30, 22, -6, 68, -88, 68, -74, -60, 40, 18, 4, -18, -20, -32, 62, -88, -22, -46, -16, 10, 36, 90, -42, -34, 6, 8, -26, -82], [66, 12, -8, -60, 26, 30, 42, -50, -44, 60, 14, 98, -38, -68, 40, -62, -50, -78, 26, -60, -50, -62, -34, -76, 4, 56, 80, 60, -18, -74, 60, 92, 58, 38, 4, 32], [-72, 82, -54, 62, -46, 18, 38, -54, 14, 66, -40, -96, -24, 40, -48, 10, 4, -90, 20, 48, -16, 28, 64, 64, -50, -92, -76, 22, 2, 92, -2, 82, 22, -4, -80, -46], [34, 60, -52, 60, 38, -60, -78, -2, -64, 94, 8, 34, 28, 68, 54, -60, -60, -40, -28, 32, -64, 32, -66, 68, 8, -2, 28, 86, -70, -64, -30, -70, -80, -42, -78, -28], [-52, 54, 88, 14, -18, 26, 76, 72, 90, 44, -64, -84, 22, -2, -26, 24, 8, -4, 94, -8, 6, 38, -44, 74, -84, 20, 26, -94, -68, -80, -52, 62, -98, 82, -4, -58], [-84, -26, 26, 66, 2, -52, -4, -98, 84, 40, -24, 84, 88, -2, -62, -56, -20, 32, -8, -98, -52, -32, -44, -52, 36, -4, 18, 14, 84, 16, -18, 28, 56, 74, -42, -80], [-34, -26, -54, -8, -8, 22, 0, -90, -58, 58, 88, 10, 52, -62, 16, -14, -58, -60, -78, -70, 66, -48, -12, -4, 36, -92, 64, -94, -22, 80, 8, -40, 84, -84, 68, 78]],),
(8,12,[[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]],),
(11,13,[[64, 68, 58, 56, 2, 27, 96, 83, 78, 9, 95, 48, 14, 87, 69, 80, 53, 66, 66], [73, 89, 19, 52, 59, 68, 81, 18, 13, 72, 3, 23, 38, 7, 31, 13, 43, 43, 23], [16, 27, 30, 3, 80, 29, 97, 63, 71, 40, 89, 30, 54, 97, 95, 37, 16, 68, 94], [37, 15, 40, 33, 21, 78, 39, 85, 98, 96, 20, 54, 73, 69, 31, 13, 20, 62, 85], [1, 69, 48, 96, 10, 31, 75, 60, 5, 70, 58, 49, 50, 86, 88, 23, 18, 33, 40], [68, 56, 90, 13, 86, 61, 96, 96, 24, 14, 95, 40, 67, 93, 46, 1, 3, 26, 59], [64, 32, 11, 34, 39, 79, 15, 31, 88, 70, 86, 88, 24, 46, 99, 98, 49, 59, 45], [41, 82, 38, 58, 88, 61, 8, 83, 98, 61, 41, 26, 23, 69, 78, 19, 55, 83, 58], [74, 29, 48, 22, 87, 66, 88, 90, 42, 11, 52, 1, 25, 58, 43, 4, 55, 59, 18], [78, 88, 25, 5, 10, 15, 79, 61, 1, 24, 97, 61, 15, 54, 67, 22, 46, 85, 59], [23, 10, 43, 18, 33, 49, 7, 40, 89, 2, 73, 27, 61, 69, 72, 89, 79, 89, 37], [64, 92, 9, 64, 3, 63, 47, 66, 59, 40, 19, 21, 67, 60, 28, 96, 3, 2, 66], [63, 16, 10, 51, 36, 9, 34, 89, 90, 84, 26, 82, 33, 14, 55, 44, 15, 83, 65], [37, 85, 66, 33, 57, 48, 83, 57, 11, 71, 11, 79, 45, 33, 45, 35, 78, 92, 87], [24, 83, 15, 14, 83, 19, 25, 13, 91, 77, 83, 76, 65, 22, 25, 86, 97, 37, 33], [21, 69, 3, 98, 62, 72, 89, 33, 37, 88, 56, 11, 19, 22, 85, 19, 38, 3, 32], [82, 24, 96, 11, 49, 40, 44, 64, 89, 47, 49, 99, 25, 54, 13, 75, 29, 22, 41], [79, 49, 25, 39, 26, 69, 87, 10, 2, 18, 99, 84, 53, 50, 89, 94, 22, 3, 26], [98, 70, 94, 92, 33, 45, 55, 56, 40, 94, 16, 83, 36, 57, 89, 13, 96, 82, 75]],)
]
filled_function_param = [
(30,37,[[3, 6, 8, 9, 9, 9, 10, 10, 14, 15, 15, 18, 21, 21, 23, 52, 53, 57, 59, 60, 67, 68, 68, 69, 79, 80, 80, 81, 84, 85, 87, 89, 89, 90, 93, 93, 95, 99], [5, 7, 8, 12, 15, 16, 17, 19, 20, 20, 21, 29, 29, 31, 33, 34, 50, 54, 55, 57, 57, 59, 65, 70, 72, 76, 80, 81, 83, 84, 84, 85, 85, 87, 91, 94, 94, 96], [4, 7, 11, 12, 13, 14, 15, 20, 22, 23, 30, 33, 35, 35, 36, 37, 39, 40, 41, 48, 49, 59, 60, 60, 64, 65, 69, 71, 72, 81, 82, 83, 84, 87, 92, 92, 96, 97], [1, 2, 5, 7, 7, 13, 13, 14, 19, 26, 27, 28, 35, 38, 38, 41, 43, 44, 47, 49, 51, 54, 55, 56, 57, 59, 61, 61, 72, 73, 74, 78, 78, 81, 83, 85, 91, 91], [2, 6, 7, 10, 14, 16, 20, 22, 25, 28, 29, 36, 37, 38, 41, 42, 43, 46, 49, 50, 53, 54, 55, 60, 60, 62, 62, 64, 64, 69, 73, 73, 79, 85, 87, 95, 96, 97], [3, 4, 4, 9, 9, 10, 11, 13, 25, 28, 33, 37, 37, 39, 41, 43, 45, 47, 49, 49, 50, 56, 56, 56, 65, 68, 68, 72, 76, 81, 82, 84, 87, 88, 88, 95, 96, 98], [4, 6, 11, 12, 14, 15, 19, 22, 27, 29, 30, 35, 36, 37, 37, 38, 39, 45, 48, 51, 53, 53, 55, 59, 59, 62, 65, 67, 67, 74, 74, 85, 87, 90, 96, 97, 97, 99], [6, 10, 15, 16, 19, 19, 22, 22, 22, 24, 29, 30, 32, 33, 35, 35, 35, 36, 38, 43, 49, 49, 49, 53, 53, 58, 60, 62, 68, 73, 77, 80, 86, 88, 89, 92, 92, 94], [1, 2, 2, 4, 4, 5, 5, 8, 10, 11, 14, 16, 18, 23, 23, 28, 31, 36, 38, 41, 44, 45, 46, 47, 51, 53, 54, 59, 64, 66, 68, 69, 76, 85, 88, 89, 92, 99], [6, 7, 10, 14, 15, 17, 24, 26, 27, 30, 33, 37, 38, 40, 41, 44, 49, 51, 52, 52, 55, 55, 59, 64, 66, 68, 79, 80, 81, 82, 82, 85, 90, 93, 94, 95, 97, 98], [3, 8, 10, 12, 12, 21, 21, 23, 34, 35, 36, 38, 39, 39, 40, 42, 47, 51, 53, 56, 56, 58, 60, 61, 68, 74, 78, 84, 85, 86, 90, 92, 93, 94, 94, 98, 99, 99], [1, 14, 14, 17, 20, 22, 22, 22, 25, 25, 25, 26, 28, 29, 32, 34, 38, 39, 40, 42, 42, 47, 51, 56, 56, 57, 65, 67, 68, 70, 70, 70, 72, 73, 78, 90, 94, 98], [1, 9, 13, 16, 18, 21, 22, 23, 26, 26, 28, 28, 30, 33, 40, 45, 48, 49, 50, 53, 55, 57, 74, 76, 77, 81, 84, 85, 88, 89, 90, 91, 91, 93, 94, 95, 99, 99], [2, 4, 6, 10, 12, 14, 15, 15, 20, 23, 25, 26, 27, 33, 35, 38, 39, 46, 51, 54, 68, 70, 70, 73, 73, 74, 74, 76, 77, 80, 86, 89, 89, 91, 92, 93, 98, 99], [2, 3, 5, 6, 8, 9, 11, 14, 16, 24, 26, 26, 33, 33, 33, 34, 35, 36, 44, 44, 45, 47, 49, 51, 51, 56, 59, 64, 66, 67, 73, 74, 80, 86, 90, 97, 99, 99], [1, 7, 7, 16, 17, 17, 18, 18, 19, 21, 26, 29, 30, 32, 36, 39, 44, 45, 45, 47, 49, 57, 59, 62, 64, 65, 68, 71, 79, 80, 84, 85, 90, 92, 93, 94, 97, 99], [9, 9, 12, 15, 15, 17, 21, 22, 22, 28, 30, 31, 31, 33, 34, 38, 38, 38, 40, 44, 46, 46, 47, 52, 53, 59, 64, 65, 69, 73, 74, 79, 80, 83, 89, 92, 95, 99], [2, 2, 4, 5, 9, 10, 17, 23, 30, 33, 33, 33, 35, 39, 42, 43, 44, 44, 46, 54, 58, 60, 60, 61, 61, 61, 67, 68, 74, 78, 86, 87, 88, 89, 93, 97, 99, 99], [16, 16, 17, 17, 17, 17, 19, 20, 20, 22, 34, 35, 38, 38, 39, 39, 40, 42, 44, 46, 46, 48, 49, 58, 63, 66, 67, 71, 74, 75, 77, 77, 84, 84, 86, 89, 96, 98], [7, 8, 8, 11, 14, 17, 20, 27, 28, 29, 29, 34, 35, 36, 37, 39, 39, 42, 50, 50, 51, 52, 53, 55, 55, 57, 59, 61, 68, 68, 71, 74, 79, 83, 86, 87, 94, 99], [6, 8, 9, 11, 13, 15, 16, 16, 18, 20, 21, 25, 25, 32, 36, 45, 47, 51, 51, 53, 58, 58, 60, 62, 63, 66, 66, 67, 69, 70, 80, 81, 83, 85, 85, 91, 93, 99], [2, 4, 9, 9, 12, 13, 28, 29, 30, 31, 35, 35, 44, 46, 47, 48, 48, 56, 58, 61, 61, 62, 64, 65, 67, 68, 68, 78, 80, 84, 86, 87, 89, 91, 92, 94, 94, 94], [6, 7, 8, 14, 20, 34, 36, 38, 40, 41, 43, 44, 45, 52, 55, 55, 58, 60, 62, 67, 68, 73, 78, 79, 79, 80, 80, 84, 86, 86, 87, 88, 92, 92, 93, 93, 96, 98], [3, 4, 5, 7, 9, 9, 12, 15, 16, 17, 20, 23, 25, 26, 34, 36, 37, 38, 41, 42, 48, 48, 53, 59, 61, 63, 65, 66, 66, 68, 69, 70, 74, 75, 83, 86, 87, 97], [9, 9, 10, 13, 16, 21, 21, 23, 24, 26, 27, 31, 35, 35, 40, 51, 56, 56, 60, 61, 64, 66, 66, 67, 70, 70, 72, 74, 76, 77, 79, 85, 86, 89, 92, 93, 99, 99], [5, 5, 5, 7, 7, 13, 18, 19, 20, 20, 25, 26, 28, 29, 31, 37, 37, 42, 45, 46, 48, 50, 52, 53, 53, 54, 58, 64, 67, 67, 69, 75, 82, 82, 86, 93, 98, 99], [3, 7, 10, 11, 16, 19, 21, 21, 26, 31, 32, 34, 35, 37, 38, 39, 49, 51, 54, 55, 56, 57, 58, 59, 63, 65, 66, 73, 77, 78, 79, 82, 85, 85, 88, 91, 91, 96], [6, 7, 8, 10, 11, 13, 17, 17, 18, 22, 22, 23, 28, 29, 30, 35, 35, 36, 46, 48, 51, 63, 64, 66, 67, 69, 71, 73, 75, 78, 86, 86, 87, 89, 93, 94, 98, 99], [2, 3, 5, 5, 6, 14, 16, 17, 18, 20, 21, 22, 31, 36, 40, 41, 42, 43, 43, 48, 49, 59, 62, 62, 67, 70, 71, 75, 76, 79, 83, 83, 88, 92, 95, 96, 97, 98], [1, 2, 6, 10, 12, 14, 22, 24, 27, 28, 31, 33, 34, 36, 40, 45, 46, 46, 47, 49, 49, 50, 50, 58, 60, 62, 64, 65, 72, 75, 76, 81, 84, 84, 84, 87, 93, 97], [1, 2, 3, 3, 10, 14, 14, 14, 18, 18, 20, 24, 25, 26, 27, 29, 31, 36, 41, 44, 44, 46, 48, 49, 51, 51, 51, 53, 56, 64, 71, 72, 79, 80, 84, 86, 95, 97], [3, 4, 5, 5, 6, 7, 10, 11, 13, 18, 18, 19, 20, 23, 31, 32, 37, 41, 41, 42, 47, 48, 50, 56, 57, 59, 60, 65, 77, 79, 83, 83, 85, 87, 88, 89, 95, 98], [4, 10, 16, 16, 18, 21, 26, 34, 35, 36, 36, 40, 41, 45, 46, 53, 53, 55, 61, 64, 65, 66, 67, 70, 71, 78, 81, 81, 81, 84, 85, 85, 90, 93, 94, 95, 97, 98], [1, 6, 7, 11, 12, 14, 19, 25, 26, 28, 29, 32, 33, 34, 34, 36, 38, 49, 56, 59, 60, 66, 72, 72, 72, 77, 78, 79, 80, 82, 90, 91, 92, 93, 94, 95, 96, 97], [2, 5, 10, 14, 16, 19, 25, 31, 32, 32, 33, 34, 34, 38, 40, 42, 42, 43, 43, 48, 48, 49, 50, 51, 51, 57, 57, 61, 61, 76, 78, 83, 87, 89, 91, 91, 98, 99], [4, 7, 12, 13, 13, 21, 28, 29, 30, 34, 35, 36, 44, 44, 45, 46, 46, 46, 49, 68, 71, 71, 72, 77, 79, 80, 80, 83, 84, 87, 88, 89, 92, 93, 95, 97, 98, 99], [3, 7, 10, 11, 12, 16, 17, 19, 23, 25, 27, 30, 31, 33, 35, 35, 37, 41, 42, 42, 42, 64, 64, 64, 68, 70, 73, 74, 75, 83, 83, 83, 88, 89, 91, 95, 97, 98], [9, 10, 15, 16, 16, 17, 20, 20, 25, 26, 28, 29, 32, 32, 32, 39, 42, 43, 43, 45, 45, 47, 52, 55, 57, 58, 61, 66, 67, 75, 76, 84, 85, 92, 92, 94, 98, 99]],),
(16,23,[[70, 24, -36, -76, -56, -14, -44, 92, 76, 88, -22, -82, 40, 28, 52, -62, 86, 66, 4, -70, 26, 70, 32, -70, 52, 6, 10, 62, -60], [56, 32, 88, -78, -50, 64, 70, -76, 0, 86, 44, -58, -24, 0, 72, 12, 48, -76, 76, 56, 94, 48, -36, 56, 62, 60, -44, -58, 96], [82, -64, -46, 64, 84, 82, 4, 36, 52, 32, -80, 56, -48, 20, 92, 58, 74, 8, -20, -22, 30, -30, 56, 92, 98, -34, -70, 38, 66], [72, -46, 58, -86, -30, -26, -66, -58, 44, 84, 4, -34, 96, 18, 64, -22, -42, -14, 76, 30, 94, -96, -6, 80, -6, 80, 2, -82, -10], [-2, 82, 60, -70, -68, 80, 80, -46, 30, 82, 78, 36, -64, 0, -70, 64, -64, 0, -8, -44, 90, -46, -60, 76, -88, -18, 8, -76, -94], [-98, 98, -94, 36, 94, 46, 88, -52, 70, 42, -86, 40, 80, 0, 96, 8, 18, 54, -98, -28, 52, 22, -82, -72, 54, 60, 16, 4, -88], [74, -22, -56, -20, 62, 66, 92, -84, -26, -46, -56, -86, -62, 86, -86, -78, -40, -80, 96, 12, -62, -28, 64, -58, -6, -28, -62, -22, -50], [-32, -92, -88, 20, 64, -80, -78, -60, -66, 40, 46, 68, -48, 10, 84, -96, 28, -18, 62, -44, 14, -38, 0, -50, -44, 54, -52, -72, -70], [12, -92, -42, -72, 22, 24, 4, -92, -36, -6, 66, 18, 0, 70, 94, 40, -18, -4, 86, -28, 34, -24, -70, 98, 36, -74, -92, -72, -88], [90, -80, 12, -8, 16, 92, 86, 4, 38, 68, -66, -76, 16, -68, -54, -34, 38, -38, -94, 44, -82, -72, -90, 18, -80, -84, 32, -72, -64], [-98, 90, -80, 8, -90, 86, -78, -66, -42, 38, -58, 44, 24, -22, -54, 12, -86, 88, -42, -50, 34, -12, -68, -26, 16, 70, 24, -6, -88], [96, -4, -66, -56, -64, -98, 68, 12, -8, 70, 0, -32, 56, -98, -56, 94, 6, -34, 10, 46, 62, 30, -88, -50, 78, -44, 78, 24, -4], [-58, -50, 52, -30, 48, -66, 94, 36, -26, -62, -74, -82, -88, 2, 60, -44, 6, 30, 94, 74, -42, 92, 22, 46, -50, -88, -94, -4, -34], [68, 8, -86, -26, -42, -82, 10, -2, 38, 88, 4, -76, -36, -2, 56, 64, 60, 38, 70, -26, 90, -54, 86, -96, 40, 18, 12, 92, -30], [82, 28, -40, -94, 46, -40, -80, -96, 60, -14, 26, -48, 88, -68, 2, 58, 48, -50, -52, 36, 66, 6, -38, 70, 82, -38, -2, -20, 54], [-32, -36, -92, 22, -2, 64, -46, -70, 38, 38, -92, -98, 82, -50, -28, -92, 10, 94, -10, 38, -50, -80, -64, -28, 66, -36, -14, 78, 92], [4, -22, -64, -96, -8, -72, 34, 60, 92, -30, -70, -78, 38, 22, 26, -48, 92, 80, -60, -30, 30, -60, 18, 98, 72, -62, -60, -66, 42], [60, 26, -68, -30, -92, -80, -56, 60, -4, -94, 62, -88, -4, 16, 96, -74, -38, -6, -22, 26, 36, -30, 12, -42, -36, -52, 24, 34, 22], [28, -14, -96, 76, 82, -82, 98, 42, 56, 14, -80, 34, 24, 68, -86, 44, -32, -64, 54, 70, -88, 20, 48, 80, 20, 90, 6, 76, -34], [54, -96, -34, 68, 70, -96, 72, 78, -58, 4, -54, -62, 74, -66, -6, -14, 44, 32, 70, -10, 98, 86, 54, -66, 38, -36, 44, 4, -74], [94, 76, 26, -66, 54, -44, 2, 16, -54, 46, -22, -20, 38, 30, -64, 44, 90, -38, 28, -44, -82, -86, -84, -42, 22, 16, -48, 20, -66], [-88, 44, -14, 20, -90, -40, 24, 48, 64, 22, 76, -8, -30, 38, -52, -16, -94, 52, 98, 88, 48, -64, -84, -82, -2, 14, -40, -84, 62], [70, 16, 58, 30, -20, 50, -88, -8, -68, -76, 94, 36, 34, 40, -82, 58, -26, -96, 94, -52, 98, 96, 70, -90, 10, 86, -26, -18, 6], [0, 24, 82, 68, 8, -66, -24, 50, 50, -44, 28, 36, -76, 6, 90, 46, -74, 96, 28, 4, 12, 84, 60, 28, 20, 78, 60, 80, 40], [-68, 86, 60, 96, -48, 32, 8, 38, 16, -64, -14, -90, 76, 44, -48, 8, 58, 68, -28, 46, -66, 76, 98, 14, -62, -22, 18, 58, 28], [-82, 60, 32, -62, -60, -80, 90, -74, -68, 32, 72, -70, -78, 8, 82, -28, 20, 98, -56, -68, 30, 48, -54, 34, 2, 32, -38, -8, -98], [-78, 20, 56, -46, -96, 18, -94, -30, 52, -20, -8, -92, 62, 2, 80, 14, 14, 54, -48, 50, 78, 58, -82, 76, 18, -76, -94, -68, 92], [44, 40, -48, -4, 44, 84, 26, -24, 80, -90, 36, 60, -68, -74, 70, -92, 0, -98, -8, 42, -24, 46, 18, -26, -28, -28, -60, -12, -62], [-40, -98, -20, 72, 62, -32, 80, -52, 88, 10, 10, 92, -68, -6, 64, 44, 72, 52, 66, -84, -48, 8, 86, -42, -82, -50, -24, -72, -78]],),
(8,7,[[0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]],),
(25,38,[[31, 11, 19, 16, 1, 30, 52, 56, 46, 97, 11, 40, 81, 29, 56, 11, 87, 59, 39, 22, 66, 33, 97, 79, 15, 8, 97, 8, 74, 91, 35, 9, 54, 55, 51, 68, 53, 22, 83, 26, 77, 35, 58, 22, 93, 31, 95], [43, 69, 23, 43, 5, 10, 71, 76, 41, 83, 44, 10, 6, 16, 18, 55, 20, 66, 24, 26, 67, 51, 70, 27, 8, 22, 35, 85, 20, 96, 60, 40, 57, 47, 32, 73, 28, 44, 28, 28, 79, 48, 44, 33, 15, 28, 97], [50, 98, 46, 72, 39, 10, 70, 14, 42, 11, 44, 50, 70, 42, 26, 64, 46, 42, 20, 49, 82, 79, 52, 78, 80, 56, 31, 38, 11, 31, 43, 26, 59, 86, 89, 75, 5, 6, 84, 7, 6, 61, 21, 92, 30, 10, 16], [91, 42, 50, 28, 22, 10, 16, 5, 88, 92, 22, 89, 85, 64, 60, 60, 35, 47, 55, 6, 74, 31, 25, 17, 60, 6, 95, 19, 56, 19, 83, 46, 42, 24, 21, 32, 89, 95, 42, 12, 60, 91, 26, 88, 9, 39, 86], [8, 32, 38, 86, 5, 66, 23, 63, 11, 45, 80, 2, 13, 8, 43, 33, 62, 91, 54, 8, 75, 37, 99, 3, 36, 44, 50, 11, 93, 20, 12, 50, 87, 42, 84, 40, 30, 4, 21, 10, 63, 13, 87, 41, 64, 54, 22], [4, 55, 21, 31, 34, 74, 51, 93, 59, 13, 51, 10, 42, 99, 16, 54, 93, 18, 43, 35, 27, 81, 89, 78, 84, 15, 90, 83, 32, 59, 99, 67, 66, 40, 44, 2, 15, 78, 54, 28, 39, 82, 86, 51, 17, 14, 70], [34, 88, 70, 24, 25, 78, 4, 28, 29, 67, 55, 4, 91, 93, 94, 30, 13, 54, 97, 34, 11, 91, 46, 4, 23, 18, 73, 13, 71, 18, 23, 11, 94, 99, 46, 19, 48, 11, 31, 47, 73, 17, 57, 12, 77, 33, 74], [88, 15, 77, 25, 79, 45, 71, 28, 59, 82, 13, 74, 24, 46, 45, 86, 66, 13, 25, 84, 60, 27, 41, 49, 9, 15, 29, 85, 47, 30, 65, 1, 17, 49, 80, 88, 46, 43, 94, 59, 2, 86, 7, 24, 42, 2, 54], [58, 22, 69, 31, 83, 1, 21, 53, 17, 38, 52, 20, 89, 33, 80, 10, 8, 22, 63, 97, 63, 26, 59, 61, 31, 57, 24, 49, 53, 44, 11, 48, 44, 69, 52, 63, 77, 54, 27, 39, 41, 34, 82, 19, 96, 72, 30], [40, 31, 5, 14, 67, 58, 47, 19, 37, 59, 95, 76, 97, 27, 76, 46, 34, 37, 36, 54, 7, 93, 18, 32, 44, 73, 62, 70, 36, 25, 8, 49, 28, 72, 50, 92, 36, 99, 61, 79, 25, 50, 80, 17, 29, 8, 34], [59, 78, 42, 86, 60, 47, 53, 9, 15, 41, 99, 93, 60, 90, 40, 52, 17, 94, 60, 95, 5, 46, 92, 56, 56, 64, 61, 94, 24, 61, 49, 25, 63, 76, 43, 94, 67, 18, 37, 69, 87, 84, 70, 19, 56, 1, 77], [96, 22, 66, 12, 15, 58, 26, 23, 83, 34, 46, 90, 66, 23, 86, 38, 47, 14, 38, 52, 98, 8, 20, 46, 78, 49, 67, 19, 5, 87, 74, 40, 46, 55, 38, 20, 76, 79, 44, 51, 78, 51, 85, 69, 79, 54, 35], [60, 66, 47, 44, 6, 3, 50, 15, 92, 34, 3, 11, 26, 18, 88, 6, 75, 33, 78, 58, 35, 87, 80, 91, 59, 4, 30, 18, 81, 58, 80, 5, 3, 1, 29, 33, 27, 57, 97, 97, 13, 52, 28, 59, 20, 13, 62], [16, 56, 5, 26, 42, 76, 43, 75, 13, 50, 40, 57, 66, 11, 79, 92, 11, 47, 37, 25, 11, 4, 12, 29, 33, 57, 77, 47, 68, 94, 88, 66, 72, 37, 44, 62, 51, 90, 45, 74, 68, 32, 45, 31, 38, 48, 78], [59, 14, 26, 4, 32, 68, 8, 57, 79, 85, 4, 57, 95, 39, 92, 4, 37, 58, 26, 91, 56, 75, 20, 70, 42, 47, 13, 61, 71, 77, 97, 47, 13, 27, 48, 65, 58, 37, 91, 63, 21, 11, 27, 1, 92, 56, 97], [78, 42, 67, 47, 47, 4, 22, 4, 45, 28, 45, 44, 34, 27, 94, 57, 22, 11, 10, 54, 12, 24, 25, 28, 20, 90, 46, 6, 51, 97, 95, 63, 85, 52, 55, 8, 55, 11, 77, 64, 12, 45, 47, 72, 59, 33, 89], [20, 3, 87, 39, 86, 57, 10, 47, 56, 8, 29, 3, 83, 32, 88, 71, 87, 95, 40, 93, 58, 21, 23, 94, 83, 32, 74, 26, 68, 49, 98, 89, 42, 33, 49, 90, 8, 28, 70, 2, 89, 6, 82, 45, 9, 9, 31], [91, 81, 34, 26, 93, 64, 9, 72, 88, 44, 94, 91, 99, 21, 9, 44, 89, 71, 3, 92, 87, 7, 86, 2, 23, 84, 74, 48, 36, 21, 23, 57, 48, 75, 2, 47, 18, 87, 44, 86, 80, 78, 19, 97, 98, 94, 45], [57, 52, 31, 53, 11, 95, 9, 99, 69, 72, 51, 8, 47, 89, 37, 7, 55, 53, 83, 15, 91, 63, 9, 5, 29, 92, 64, 85, 44, 98, 78, 79, 15, 36, 13, 58, 87, 69, 70, 11, 96, 80, 32, 17, 40, 4, 35], [13, 39, 68, 30, 2, 79, 10, 28, 20, 13, 98, 5, 52, 42, 22, 95, 97, 79, 37, 72, 25, 46, 42, 62, 96, 41, 83, 92, 7, 56, 22, 85, 75, 76, 73, 51, 73, 33, 98, 9, 62, 26, 85, 32, 48, 91, 36], [26, 34, 21, 57, 49, 47, 79, 27, 19, 71, 62, 99, 92, 35, 26, 90, 7, 15, 31, 13, 36, 38, 36, 8, 74, 92, 72, 10, 82, 18, 53, 12, 66, 67, 68, 48, 38, 19, 20, 89, 87, 33, 87, 74, 29, 55, 20], [97, 70, 79, 56, 85, 79, 48, 51, 38, 28, 64, 63, 70, 10, 7, 79, 97, 49, 93, 52, 44, 10, 63, 62, 7, 20, 29, 41, 27, 59, 74, 7, 12, 47, 57, 8, 94, 28, 16, 21, 1, 26, 84, 81, 38, 15, 2], [58, 14, 70, 96, 80, 69, 96, 99, 95, 57, 14, 65, 85, 44, 6, 86, 1, 73, 39, 10, 67, 50, 86, 62, 64, 1, 86, 43, 34, 78, 92, 28, 36, 7, 65, 23, 36, 1, 83, 32, 86, 66, 81, 73, 11, 11, 4], [34, 65, 6, 51, 52, 27, 94, 36, 37, 48, 98, 98, 56, 44, 6, 67, 47, 95, 15, 54, 77, 20, 55, 69, 56, 57, 95, 21, 50, 14, 89, 19, 16, 31, 13, 75, 2, 40, 26, 82, 51, 72, 5, 42, 20, 83, 51], [86, 32, 78, 51, 74, 30, 76, 43, 30, 45, 48, 43, 7, 91, 8, 85, 55, 50, 46, 77, 26, 90, 13, 94, 6, 38, 10, 4, 55, 14, 46, 81, 59, 18, 92, 34, 45, 36, 20, 77, 24, 64, 85, 2, 34, 47, 17], [98, 4, 97, 79, 79, 30, 81, 52, 9, 15, 97, 42, 81, 61, 91, 50, 5, 62, 2, 61, 56, 12, 74, 47, 27, 1, 71, 37, 10, 15, 76, 34, 37, 33, 94, 16, 84, 99, 20, 10, 96, 80, 74, 67, 9, 62, 29], [4, 66, 86, 39, 1, 9, 85, 49, 11, 76, 13, 40, 70, 68, 17, 31, 91, 88, 34, 92, 25, 99, 10, 56, 62, 63, 92, 35, 75, 17, 33, 65, 35, 81, 84, 73, 25, 64, 99, 81, 34, 39, 97, 79, 34, 67, 54], [56, 47, 54, 22, 12, 36, 19, 71, 71, 27, 95, 97, 72, 55, 37, 69, 88, 75, 7, 30, 76, 1, 57, 23, 28, 18, 27, 6, 72, 98, 42, 60, 55, 31, 62, 4, 36, 80, 49, 30, 28, 34, 71, 7, 53, 55, 98], [92, 2, 72, 3, 66, 11, 74, 68, 21, 60, 78, 7, 35, 83, 14, 93, 62, 75, 21, 17, 81, 5, 38, 94, 64, 95, 90, 73, 1, 20, 31, 95, 51, 76, 95, 72, 1, 92, 65, 77, 85, 10, 51, 60, 95, 86, 94], [32, 83, 13, 97, 70, 17, 76, 31, 84, 8, 79, 98, 18, 95, 48, 10, 36, 37, 2, 83, 20, 43, 47, 60, 81, 35, 76, 49, 45, 89, 26, 10, 92, 62, 89, 56, 58, 81, 24, 76, 45, 98, 67, 89, 5, 4, 19], [51, 99, 18, 42, 6, 60, 76, 55, 41, 7, 18, 27, 73, 35, 63, 78, 43, 5, 76, 77, 25, 35, 73, 90, 81, 17, 65, 92, 30, 52, 80, 99, 48, 27, 96, 39, 21, 83, 56, 44, 46, 88, 90, 37, 49, 93, 9], [48, 87, 6, 42, 99, 31, 56, 38, 40, 16, 77, 75, 40, 97, 71, 47, 88, 94, 79, 83, 75, 5, 1, 24, 88, 37, 55, 90, 47, 15, 39, 17, 35, 45, 39, 91, 71, 54, 89, 98, 34, 13, 56, 36, 67, 99, 32], [35, 2, 27, 59, 17, 6, 17, 71, 88, 39, 36, 6, 44, 2, 61, 97, 52, 96, 67, 59, 14, 42, 17, 71, 59, 67, 17, 96, 70, 28, 8, 99, 7, 11, 77, 18, 3, 43, 58, 53, 51, 33, 83, 11, 35, 98, 64], [87, 77, 12, 98, 78, 53, 90, 33, 64, 90, 91, 1, 45, 90, 50, 8, 58, 12, 74, 80, 85, 33, 70, 42, 57, 58, 47, 82, 38, 31, 89, 79, 86, 9, 56, 60, 23, 19, 35, 3, 50, 93, 16, 69, 69, 23, 72], [55, 90, 11, 41, 28, 40, 82, 89, 87, 5, 20, 57, 77, 37, 71, 77, 50, 71, 37, 71, 98, 26, 62, 42, 37, 50, 64, 19, 6, 39, 50, 53, 18, 56, 39, 57, 96, 57, 49, 50, 10, 11, 59, 31, 66, 88, 35], [3, 78, 32, 3, 22, 42, 45, 57, 5, 21, 16, 48, 46, 33, 84, 95, 40, 32, 33, 45, 48, 32, 68, 60, 10, 15, 38, 18, 9, 43, 36, 50, 21, 19, 33, 71, 60, 18, 57, 80, 78, 24, 32, 11, 53, 52, 9], [1, 17, 36, 26, 14, 50, 53, 69, 69, 94, 21, 21, 18, 16, 67, 60, 70, 3, 30, 50, 45, 63, 45, 31, 69, 8, 64, 8, 44, 38, 37, 22, 31, 85, 42, 45, 47, 68, 64, 34, 71, 64, 24, 96, 49, 38, 21], [5, 26, 29, 5, 76, 10, 44, 84, 51, 31, 49, 53, 21, 10, 59, 42, 70, 90, 1, 4, 58, 45, 27, 4, 42, 54, 55, 97, 67, 70, 12, 14, 66, 62, 61, 37, 83, 55, 97, 57, 16, 77, 66, 50, 47, 87, 2], [46, 1, 84, 31, 57, 82, 83, 43, 59, 2, 37, 29, 99, 68, 48, 84, 70, 48, 44, 87, 66, 88, 66, 65, 45, 37, 54, 2, 44, 10, 21, 23, 28, 83, 79, 62, 83, 45, 52, 11, 97, 88, 37, 45, 94, 68, 71], [87, 89, 96, 21, 49, 74, 7, 46, 65, 92, 83, 20, 3, 14, 7, 83, 54, 87, 49, 92, 67, 50, 80, 87, 56, 20, 22, 19, 50, 80, 98, 31, 40, 5, 39, 9, 4, 76, 52, 2, 86, 45, 88, 79, 62, 59, 67], [99, 70, 74, 19, 75, 38, 5, 54, 1, 99, 85, 57, 27, 34, 71, 57, 94, 34, 28, 69, 5, 12, 11, 59, 4, 67, 63, 67, 66, 4, 71, 96, 32, 46, 1, 47, 71, 34, 52, 51, 49, 84, 7, 68, 43, 80, 17], [8, 65, 11, 13, 26, 6, 36, 83, 32, 63, 11, 39, 88, 55, 40, 79, 85, 72, 99, 86, 36, 9, 3, 70, 32, 36, 8, 65, 51, 99, 82, 48, 83, 69, 4, 8, 95, 95, 2, 41, 48, 36, 51, 36, 29, 65, 39], [88, 90, 78, 25, 22, 42, 28, 69, 82, 92, 5, 62, 92, 48, 9, 94, 1, 32, 9, 50, 18, 86, 48, 59, 14, 73, 87, 59, 91, 31, 61, 19, 21, 99, 91, 65, 72, 54, 76, 57, 68, 3, 83, 21, 93, 1, 41], [31, 87, 42, 13, 14, 4, 49, 16, 58, 97, 71, 91, 38, 99, 3, 34, 13, 15, 51, 11, 83, 25, 97, 64, 14, 74, 52, 17, 63, 80, 37, 35, 69, 95, 10, 60, 55, 61, 15, 55, 4, 75, 66, 11, 91, 29, 44], [69, 8, 28, 93, 78, 65, 82, 14, 99, 86, 4, 14, 41, 55, 8, 86, 56, 58, 1, 81, 2, 92, 84, 75, 18, 11, 11, 82, 66, 83, 42, 8, 64, 3, 43, 97, 4, 37, 13, 99, 99, 82, 26, 20, 71, 76, 95], [30, 63, 45, 6, 22, 40, 69, 52, 5, 84, 31, 52, 67, 64, 52, 33, 29, 83, 87, 68, 60, 69, 16, 19, 23, 92, 98, 93, 79, 40, 52, 56, 48, 26, 71, 21, 7, 79, 26, 66, 55, 46, 52, 20, 14, 2, 16], [45, 37, 1, 72, 82, 14, 21, 94, 66, 1, 49, 51, 75, 95, 7, 22, 29, 5, 24, 99, 65, 23, 33, 19, 50, 45, 97, 28, 97, 3, 43, 37, 51, 68, 81, 7, 55, 51, 50, 83, 89, 17, 76, 27, 53, 10, 53]],),
(20,19,[[-92, -90, -82, -80, -70, -62, -58, -48, -30, -26, -26, -14, -6, 4, 4, 4, 10, 12, 20, 24, 32, 36, 36, 40, 42, 54, 64, 64, 88, 90, 92, 96], [-98, -92, -76, -56, -54, -38, -36, -34, -32, -24, -22, -22, -20, -16, -4, -2, -2, -2, 0, 4, 6, 20, 26, 34, 42, 44, 44, 60, 72, 80, 86, 98], [-86, -84, -82, -78, -72, -66, -60, -54, -24, -18, -12, -10, -10, -4, 6, 18, 20, 22, 32, 38, 40, 48, 64, 68, 68, 68, 70, 78, 84, 84, 94, 98], [-96, -78, -76, -58, -54, -50, -46, -46, -42, -36, -34, -26, -22, -18, -14, -10, -6, -4, -2, 10, 26, 36, 46, 46, 52, 56, 76, 80, 80, 88, 94, 98], [-82, -64, -56, -52, -34, -28, -22, -20, -18, -16, -6, -2, 0, 0, 10, 10, 12, 12, 14, 20, 22, 32, 34, 46, 46, 50, 54, 62, 64, 72, 82, 90], [-98, -82, -78, -78, -72, -64, -60, -50, -50, -48, -42, 20, 26, 32, 40, 40, 44, 44, 48, 58, 62, 68, 76, 78, 84, 86, 90, 94, 94, 96, 98, 98], [-96, -96, -92, -76, -74, -72, -66, -56, -48, -38, -38, -30, -8, -8, -4, 6, 12, 12, 14, 46, 54, 56, 58, 60, 60, 68, 72, 78, 80, 82, 82, 84], [-96, -96, -96, -94, -70, -66, -64, -64, -44, -20, -18, -14, -10, -8, -6, -2, -2, 2, 4, 10, 24, 30, 30, 40, 40, 58, 64, 68, 76, 76, 96, 98], [-88, -84, -84, -64, -64, -58, -40, -38, -32, -30, -28, -24, -14, -6, -6, 0, 14, 26, 28, 28, 34, 36, 36, 44, 48, 50, 54, 62, 68, 74, 74, 94], [-98, -96, -96, -88, -86, -76, -74, -74, -70, -70, -52, -42, -34, -16, -2, 0, 8, 8, 14, 18, 34, 34, 42, 46, 54, 56, 70, 78, 80, 92, 94, 96], [-96, -94, -90, -90, -76, -74, -62, -62, -54, -46, -38, -32, -32, -22, -22, -10, 2, 4, 6, 34, 48, 48, 50, 54, 56, 60, 74, 76, 80, 90, 96, 96], [-72, -70, -64, -62, -62, -60, -52, -50, -44, -40, -34, -32, -28, -4, 2, 14, 16, 34, 34, 44, 52, 54, 66, 68, 68, 68, 72, 82, 84, 88, 88, 94], [-98, -96, -88, -84, -78, -56, -48, -42, -36, -34, -26, -18, -10, 0, 6, 8, 14, 20, 26, 32, 40, 46, 48, 54, 54, 60, 60, 78, 92, 96, 98, 98], [-94, -78, -72, -54, -54, -54, -52, -48, -44, -44, -34, -28, -26, -18, -16, -16, -12, -10, -4, 2, 2, 2, 8, 24, 26, 44, 52, 52, 62, 72, 76, 84], [-94, -92, -86, -78, -72, -72, -70, -64, -58, -56, -56, -54, -40, -30, -30, -26, -10, -4, 4, 8, 32, 32, 44, 48, 50, 58, 64, 82, 84, 88, 92, 96], [-86, -84, -68, -34, -24, -22, -6, -6, -4, -4, -2, 0, 0, 0, 2, 2, 12, 18, 24, 26, 36, 40, 46, 56, 58, 64, 68, 80, 82, 84, 88, 90], [-92, -80, -78, -74, -70, -62, -50, -48, -48, -46, -44, -42, -30, -16, -2, 0, 22, 24, 26, 26, 44, 54, 62, 64, 64, 68, 70, 78, 86, 92, 98, 98], [-92, -92, -92, -80, -76, -74, -64, -58, -54, -52, -50, -48, -42, -38, -30, -24, -20, -20, -6, -4, -2, 8, 12, 18, 30, 40, 44, 50, 52, 66, 70, 74], [-98, -90, -86, -74, -58, -44, -36, -26, -18, -16, -8, -6, -2, 2, 4, 8, 18, 22, 24, 34, 42, 48, 48, 48, 54, 60, 64, 70, 80, 84, 94, 98], [-94, -88, -82, -78, -78, -76, -74, -70, -70, -68, -64, -56, -36, -34, -28, -26, -24, -20, -16, -2, 6, 12, 24, 46, 60, 62, 68, 74, 74, 84, 88, 98], [-90, -80, -78, -72, -68, -62, -58, -48, -46, -44, -32, -16, -6, 0, 18, 24, 26, 28, 36, 44, 50, 52, 52, 64, 76, 76, 82, 82, 84, 86, 94, 96], [-98, -96, -92, -92, -86, -78, -64, -34, -32, -20, 4, 8, 12, 12, 16, 18, 26, 28, 32, 36, 36, 40, 48, 52, 52, 56, 60, 64, 76, 76, 78, 82], [-94, -88, -64, -54, -50, -42, -34, -24, -16, -12, -4, 4, 4, 8, 16, 22, 22, 32, 38, 38, 40, 42, 44, 50, 54, 64, 70, 72, 76, 80, 92, 94], [-98, -96, -84, -72, -64, -60, -56, -54, -48, -46, -40, -34, -32, -30, -28, -24, -20, -16, -10, -2, 0, 2, 16, 34, 40, 44, 48, 52, 66, 66, 82, 90], [-98, -96, -96, -94, -68, -66, -60, -50, -38, -34, -12, -12, -4, 2, 12, 14, 16, 22, 24, 28, 30, 38, 50, 56, 62, 78, 80, 80, 82, 90, 94, 96], [-90, -80, -76, -70, -68, -68, -64, -50, -42, -40, -38, -34, -26, -24, -20, -14, -14, -10, -4, -2, 0, 0, 22, 28, 44, 58, 58, 66, 66, 70, 72, 96], [-98, -94, -90, -90, -88, -84, -76, -72, -70, -70, -34, -28, -26, -12, 6, 6, 6, 8, 14, 20, 24, 32, 58, 62, 68, 68, 68, 78, 80, 84, 92, 92], [-90, -84, -80, -72, -72, -70, -64, -60, -58, -48, -46, -44, -20, -18, -12, -10, -8, -6, -2, 2, 6, 12, 14, 14, 22, 32, 40, 56, 66, 86, 90, 92], [-96, -88, -84, -76, -58, -52, -50, -46, -42, -38, -30, -28, -20, -10, -2, 0, 2, 16, 22, 26, 34, 36, 46, 54, 58, 60, 60, 76, 76, 78, 82, 88], [-94, -88, -84, -84, -82, -72, -68, -60, -58, -50, -40, -30, -22, -12, -12, -8, -4, -2, 8, 10, 16, 24, 30, 32, 36, 38, 70, 72, 84, 86, 90, 90], [-98, -80, -80, -76, -70, -60, -46, -40, -34, -32, -26, -26, -26, -24, -22, -20, -16, 0, 12, 34, 44, 46, 48, 60, 66, 80, 82, 84, 86, 94, 94, 98], [-96, -88, -86, -84, -76, -64, -38, -30, -22, -6, -6, -4, -2, 12, 20, 22, 24, 24, 26, 28, 32, 32, 44, 46, 68, 78, 80, 80, 84, 92, 94, 94]],),
(34,24,[[1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0], [0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1], [0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0], [0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1], [0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1], [1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0], [1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1], [0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0], [1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0], [0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1], [1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1], [0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0], [1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 1, 1], [0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0], [0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1], [1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1], [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1], [0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1], [0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0], [1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], [1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0], [1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1], [1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1], [1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0], [1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0]],),
(29,32,[[1, 1, 9, 19, 20, 23, 25, 27, 28, 28, 29, 31, 33, 33, 36, 38, 41, 42, 44, 47, 47, 51, 57, 58, 61, 63, 65, 66, 68, 70, 70, 71, 74, 76, 80, 83, 85, 90, 90, 93, 93, 94, 97], [1, 3, 3, 4, 5, 7, 7, 10, 12, 17, 18, 24, 24, 25, 25, 27, 31, 31, 34, 39, 40, 41, 41, 42, 49, 49, 51, 55, 62, 64, 66, 72, 74, 74, 80, 82, 83, 84, 84, 91, 94, 96, 98], [1, 5, 6, 6, 7, 9, 18, 20, 20, 21, 22, 22, 27, 29, 30, 36, 36, 37, 37, 37, 39, 45, 48, 48, 48, 53, 55, 56, 58, 59, 59, 66, 69, 75, 76, 77, 82, 82, 84, 86, 88, 93, 93], [1, 5, 7, 13, 18, 19, 23, 23, 25, 28, 28, 29, 33, 34, 34, 35, 41, 45, 45, 45, 45, 49, 50, 52, 54, 55, 55, 60, 63, 65, 66, 67, 67, 68, 70, 72, 74, 79, 79, 83, 83, 89, 97], [3, 3, 5, 6, 11, 15, 17, 20, 24, 25, 26, 29, 31, 34, 34, 35, 40, 43, 43, 44, 44, 52, 52, 54, 54, 64, 65, 65, 67, 69, 69, 72, 77, 78, 78, 78, 81, 83, 88, 88, 90, 93, 95], [1, 4, 10, 11, 14, 15, 17, 21, 21, 22, 23, 24, 27, 28, 31, 32, 33, 33, 39, 41, 50, 53, 55, 57, 61, 62, 65, 65, 65, 71, 73, 74, 78, 81, 81, 82, 83, 86, 86, 92, 98, 98, 99], [5, 6, 6, 7, 9, 18, 19, 20, 20, 22, 23, 27, 29, 31, 38, 38, 39, 40, 42, 44, 53, 56, 58, 64, 65, 67, 68, 69, 71, 73, 73, 74, 76, 77, 77, 79, 82, 88, 90, 94, 94, 96, 97], [1, 2, 3, 4, 5, 7, 9, 10, 10, 13, 20, 21, 23, 26, 27, 29, 29, 29, 31, 33, 34, 34, 37, 39, 41, 43, 46, 46, 48, 53, 55, 58, 58, 61, 67, 67, 70, 78, 79, 90, 93, 95, 96], [1, 1, 3, 4, 5, 8, 10, 11, 11, 13, 15, 18, 21, 21, 24, 30, 30, 31, 32, 44, 46, 54, 59, 61, 62, 65, 66, 67, 68, 70, 72, 76, 77, 78, 78, 80, 81, 83, 85, 87, 89, 92, 96], [1, 4, 5, 5, 7, 10, 11, 13, 22, 25, 26, 28, 29, 29, 33, 34, 34, 36, 37, 37, 38, 40, 45, 46, 47, 53, 56, 62, 62, 68, 68, 75, 78, 80, 82, 87, 89, 89, 91, 91, 92, 96, 97], [1, 4, 6, 6, 6, 9, 9, 10, 15, 17, 22, 23, 31, 31, 33, 33, 37, 38, 44, 46, 50, 56, 57, 58, 62, 63, 65, 70, 71, 76, 79, 79, 80, 81, 83, 87, 88, 88, 89, 91, 92, 94, 99], [1, 1, 2, 7, 10, 10, 14, 15, 18, 22, 25, 27, 28, 30, 32, 35, 37, 41, 42, 43, 53, 53, 55, 57, 57, 61, 61, 63, 64, 66, 67, 67, 68, 71, 74, 75, 76, 76, 78, 78, 78, 85, 89], [2, 9, 10, 10, 11, 11, 18, 26, 34, 35, 35, 36, 36, 40, 43, 43, 45, 49, 49, 50, 54, 64, 65, 65, 66, 68, 69, 70, 72, 78, 79, 81, 81, 82, 91, 92, 92, 93, 94, 95, 95, 96, 98], [4, 5, 5, 10, 10, 11, 13, 16, 21, 22, 24, 33, 33, 33, 34, 35, 37, 38, 39, 41, 43, 46, 51, 56, 56, 58, 58, 66, 73, 74, 74, 76, 76, 77, 78, 78, 81, 83, 87, 88, 94, 95, 97], [5, 7, 8, 10, 11, 14, 14, 15, 15, 19, 19, 21, 23, 23, 31, 39, 44, 46, 46, 47, 53, 53, 54, 57, 57, 58, 59, 60, 62, 68, 68, 69, 72, 79, 80, 80, 80, 81, 84, 89, 91, 98, 99], [1, 1, 2, 7, 8, 9, 14, 15, 18, 20, 21, 33, 34, 36, 37, 42, 46, 48, 53, 55, 55, 66, 67, 71, 73, 77, 80, 82, 84, 84, 85, 87, 87, 88, 90, 92, 92, 93, 93, 94, 95, 98, 99], [1, 1, 1, 9, 9, 11, 13, 18, 19, 20, 32, 32, 34, 44, 45, 46, 47, 50, 50, 52, 54, 56, 57, 59, 60, 61, 61, 63, 67, 67, 68, 76, 76, 77, 78, 80, 83, 85, 88, 92, 93, 94, 95], [3, 5, 6, 7, 7, 11, 14, 17, 18, 19, 26, 26, 27, 28, 29, 33, 35, 36, 36, 37, 41, 47, 49, 55, 58, 69, 71, 72, 74, 79, 80, 81, 85, 87, 90, 92, 93, 94, 94, 94, 96, 97, 98], [8, 9, 11, 13, 13, 13, 16, 21, 21, 23, 23, 28, 42, 46, 47, 48, 55, 58, 60, 64, 67, 68, 71, 71, 72, 73, 73, 73, 77, 77, 80, 81, 86, 88, 88, 90, 90, 91, 93, 93, 95, 96, 97], [1, 5, 9, 10, 12, 13, 14, 15, 19, 20, 25, 27, 30, 30, 33, 37, 38, 39, 40, 41, 42, 42, 51, 54, 55, 58, 59, 60, 64, 64, 73, 74, 78, 79, 80, 80, 85, 87, 88, 91, 93, 97, 99], [2, 3, 4, 5, 8, 9, 9, 12, 12, 14, 17, 17, 18, 21, 23, 23, 26, 32, 34, 34, 34, 45, 45, 48, 49, 56, 60, 62, 63, 64, 67, 71, 71, 75, 76, 77, 77, 79, 81, 83, 87, 88, 98], [3, 3, 3, 7, 9, 12, 15, 18, 26, 27, 30, 34, 37, 38, 41, 42, 44, 44, 45, 57, 58, 64, 67, 67, 70, 71, 73, 75, 76, 80, 83, 86, 87, 88, 88, 89, 90, 90, 92, 95, 97, 98, 98], [1, 1, 3, 3, 4, 5, 6, 9, 10, 11, 12, 12, 20, 21, 21, 22, 23, 28, 32, 35, 43, 48, 52, 53, 53, 56, 59, 60, 65, 66, 70, 71, 73, 74, 74, 79, 81, 83, 85, 87, 91, 97, 98], [3, 3, 3, 4, 15, 21, 24, 25, 28, 31, 31, 33, 38, 40, 41, 42, 43, 43, 46, 46, 46, 46, 47, 50, 50, 58, 58, 61, 67, 67, 70, 71, 73, 79, 85, 88, 90, 90, 91, 91, 93, 96, 97], [2, 5, 5, 6, 9, 12, 16, 17, 17, 18, 20, 22, 26, 27, 31, 36, 38, 40, 43, 45, 47, 48, 55, 62, 62, 64, 65, 67, 68, 69, 71, 72, 73, 76, 79, 80, 82, 84, 87, 88, 91, 94, 99], [1, 8, 8, 11, 21, 22, 23, 23, 33, 34, 36, 40, 40, 41, 42, 42, 45, 46, 47, 56, 57, 60, 60, 62, 66, 67, 73, 73, 76, 80, 80, 80, 82, 83, 83, 83, 84, 88, 92, 92, 94, 98, 99], [6, 9, 11, 14, 14, 17, 18, 20, 20, 21, 21, 21, 23, 29, 33, 34, 40, 43, 44, 45, 49, 54, 55, 58, 59, 65, 65, 68, 70, 73, 74, 77, 79, 82, 83, 84, 85, 86, 88, 93, 93, 97, 97], [2, 8, 10, 10, 11, 13, 15, 15, 16, 20, 22, 23, 24, 27, 29, 29, 31, 37, 37, 40, 40, 43, 45, 47, 47, 49, 49, 50, 51, 61, 63, 65, 72, 72, 75, 76, 76, 80, 82, 82, 84, 93, 97], [1, 6, 11, 12, 15, 19, 21, 26, 26, 27, 29, 31, 31, 32, 37, 37, 38, 41, 46, 55, 56, 56, 59, 59, 60, 63, 64, 66, 74, 76, 81, 82, 82, 83, 88, 93, 93, 95, 95, 96, 98, 99, 99], [1, 2, 8, 8, 8, 12, 12, 20, 22, 22, 23, 34, 34, 37, 38, 38, 40, 42, 49, 52, 54, 55, 56, 57, 63, 64, 65, 66, 68, 70, 71, 71, 71, 71, 73, 75, 77, 78, 78, 79, 80, 91, 99], [2, 2, 4, 8, 10, 11, 12, 15, 25, 35, 37, 40, 41, 44, 44, 46, 46, 48, 48, 48, 49, 50, 50, 53, 55, 59, 62, 68, 69, 70, 76, 76, 80, 81, 82, 84, 84, 86, 89, 91, 92, 96, 99], [1, 2, 4, 7, 9, 15, 17, 18, 20, 20, 20, 26, 27, 29, 30, 35, 36, 44, 48, 49, 49, 57, 58, 60, 62, 67, 72, 75, 77, 78, 80, 83, 83, 83, 84, 85, 85, 90, 91, 94, 94, 96, 98], [2, 5, 19, 19, 21, 21, 23, 28, 32, 33, 39, 41, 46, 49, 51, 51, 53, 54, 54, 57, 57, 58, 63, 63, 64, 64, 64, 65, 65, 67, 69, 70, 70, 71, 72, 75, 75, 79, 88, 88, 89, 91, 95], [2, 2, 6, 6, 11, 14, 16, 16, 21, 26, 29, 31, 34, 35, 36, 36, 39, 40, 43, 48, 62, 62, 65, 66, 66, 67, 68, 72, 75, 76, 77, 81, 84, 85, 86, 87, 88, 92, 93, 94, 96, 96, 99], [1, 3, 3, 4, 7, 8, 8, 8, 10, 12, 13, 17, 20, 20, 21, 24, 28, 30, 30, 35, 38, 41, 42, 44, 48, 50, 53, 56, 57, 57, 58, 59, 62, 67, 73, 74, 74, 75, 75, 76, 90, 96, 99], [1, 1, 6, 8, 8, 9, 11, 11, 12, 14, 14, 14, 16, 18, 18, 22, 23, 23, 24, 25, 25, 26, 27, 30, 40, 40, 41, 43, 47, 48, 49, 52, 55, 57, 61, 71, 73, 86, 91, 94, 94, 97, 98], [4, 8, 10, 11, 19, 21, 27, 27, 28, 29, 29, 31, 34, 36, 38, 39, 40, 42, 42, 45, 48, 54, 56, 57, 57, 58, 60, 62, 62, 65, 67, 71, 73, 73, 80, 83, 85, 86, 89, 91, 92, 93, 93], [2, 3, 5, 6, 6, 9, 10, 11, 12, 14, 15, 19, 19, 20, 21, 22, 24, 27, 27, 34, 38, 39, 39, 41, 46, 47, 50, 51, 51, 53, 56, 59, 60, 71, 79, 83, 84, 84, 86, 87, 87, 89, 93], [2, 6, 6, 7, 7, 8, 9, 10, 11, 17, 18, 22, 28, 30, 32, 32, 33, 37, 38, 39, 42, 54, 61, 63, 68, 71, 71, 71, 73, 76, 78, 80, 80, 88, 89, 92, 92, 92, 93, 93, 94, 98, 99], [8, 11, 11, 12, 14, 14, 15, 16, 16, 19, 19, 21, 26, 31, 32, 33, 37, 38, 40, 41, 41, 44, 45, 50, 58, 64, 65, 67, 69, 70, 72, 72, 72, 79, 81, 87, 90, 91, 91, 95, 98, 99, 99], [2, 4, 5, 7, 10, 13, 17, 18, 19, 29, 29, 30, 31, 35, 35, 42, 43, 44, 45, 46, 47, 48, 49, 49, 51, 51, 58, 58, 60, 63, 64, 66, 73, 77, 80, 81, 82, 87, 88, 94, 98, 98, 99], [3, 4, 8, 14, 15, 15, 19, 26, 27, 29, 31, 31, 31, 33, 33, 36, 39, 40, 42, 42, 44, 46, 48, 48, 49, 52, 54, 54, 55, 57, 65, 65, 71, 71, 78, 83, 86, 89, 89, 90, 90, 95, 99], [1, 1, 7, 7, 7, 11, 13, 13, 14, 16, 17, 17, 20, 22, 23, 24, 27, 28, 28, 29, 29, 31, 38, 46, 48, 48, 48, 50, 57, 69, 73, 75, 80, 81, 84, 84, 87, 87, 87, 90, 96, 98, 99]],),
(26,33,[[-86, 20, -54, -26, 56, -86, 34, 90, -62, 18, -58, 92, 32, -76, -64, 44, -48, 10, 88, -8, -56, -90, -42, 94, -18, 48, -64, -46, -32, -72, 44, 22, -66, -10, 84, -46], [88, 32, -90, 14, -50, 42, 14, -26, 48, 68, 72, 44, 70, 94, 38, -46, -50, -2, 4, 82, -54, -84, -42, 78, 48, 22, -78, 4, 8, 22, -78, -92, -66, -38, -90, 88], [78, 40, -94, 12, -44, -74, -34, -30, -70, 90, -26, -62, 46, 46, 22, 98, 94, 38, 66, -34, -66, -82, -98, 46, -56, -44, -36, 86, 68, -2, 98, 28, -2, 20, -46, 66], [12, 72, -98, 56, 42, 48, 2, -22, 0, 40, 8, 84, 12, -36, -46, -6, 0, -4, 72, 42, -88, -38, -10, 54, -96, 36, -22, 34, 98, 88, 78, 10, 28, -2, 46, 34], [32, 20, -28, 68, -6, 86, -80, -66, 86, 22, -40, -74, 50, 38, -62, 10, -86, 86, -56, -6, -54, 66, -20, 68, 64, 90, -84, -36, 58, -70, 24, 80, -72, 44, 62, 40], [-36, -28, 96, -72, -10, -30, 82, 62, -94, 84, -76, -40, 30, -70, -6, -58, 28, -84, -50, -58, 16, -52, -32, -26, 96, 64, -6, -34, 30, 50, 44, 94, -52, 54, 8, 18], [-68, -78, -70, 54, -34, 24, 62, -92, 76, -42, 26, -92, -70, -54, -68, 64, -62, -14, 76, -98, -26, -8, 42, -10, -24, 26, 22, 78, -84, 56, 72, 96, 6, 78, 48, -48], [-48, 72, -42, 34, -48, 30, -58, 80, -34, -84, -56, 92, -22, 60, 76, -50, 66, 66, 68, 98, -18, 80, -82, 20, -32, -54, -24, -58, -26, -48, 72, -2, -46, -12, 6, 22], [30, -50, -42, 6, -98, -2, 46, 16, 14, 26, 28, -64, -42, -76, 66, 56, -74, 60, 6, 38, -36, 4, -98, 62, -36, -12, 34, 98, 64, -72, 20, -92, 28, -64, -62, 26], [24, 62, -90, 20, -84, 82, -22, -24, 30, -40, 48, -84, -98, -22, 32, -22, -40, 12, -20, -66, -40, 22, -2, 36, 64, -98, 66, 30, -36, 64, 22, 56, 90, -10, 76, -64], [74, 14, 94, 80, 96, -38, 98, 54, -90, 32, -8, 22, 18, -48, 32, -38, -72, -26, 46, 44, 92, 64, -36, -50, 78, 24, -58, -14, 52, -44, -56, -42, 0, -28, -74, 52], [54, -66, 14, -54, 38, 82, -22, -12, -22, -96, 12, 98, -72, -32, -8, -28, -50, 22, 8, -60, 88, -62, 72, -26, 22, -46, 68, 12, 84, 60, 4, -94, 84, -58, -6, 52], [54, 58, 44, -54, -40, -24, -54, 20, 16, 6, -72, 16, 96, 30, -74, 84, -82, -6, 86, 26, 82, 44, -40, -84, -58, -60, -72, 72, 0, -40, 72, 16, 8, 94, -70, -64], [-24, 26, -80, 72, -54, 60, 72, -26, 62, -82, -68, -52, -64, 64, -22, -32, 4, -80, -46, 50, 8, -74, -46, -62, 42, 86, -24, 16, 28, -88, -74, -6, 30, 84, 96, -46], [86, 28, 72, -66, -78, 84, 4, 72, 72, 14, -96, -56, 80, -74, -56, -84, -58, -74, -12, 42, -12, 6, 96, -14, 34, -28, 6, 80, 94, 88, 76, 86, 76, -16, -78, 88], [-48, -50, -92, -42, -82, 8, 58, -60, -80, 80, 62, -16, -72, 22, -82, -62, 32, 12, -20, 26, 36, 18, 88, 40, -74, -44, 8, -88, -58, 0, -8, -18, -74, -40, -30, 54], [-46, -4, 36, -42, 50, 58, 8, 38, -2, 4, 22, 72, 36, -48, -56, 98, -70, 36, 0, 20, 8, -74, -94, 32, -28, 30, -92, -96, 86, 76, -12, 22, -96, 70, 16, 62], [-40, 70, -28, 42, -80, -30, -46, 58, -30, 76, 50, 60, 22, 8, 58, -94, -52, 4, -80, 92, -92, 44, 36, 94, -52, 42, -30, -98, 68, 92, 46, -24, 36, -52, 62, 88], [-64, -60, -38, 0, 50, 90, -22, -34, 82, 58, -58, -8, 76, 4, -70, -66, -66, -60, 14, 42, 16, -2, 92, -84, -88, -66, 24, -14, 38, -76, 4, 0, 14, 40, -6, 2], [-48, -98, 88, -30, -44, 22, -30, -48, -24, 88, -54, 0, 64, -84, 34, -18, 66, -8, -2, 62, -64, -46, -94, -26, -76, 36, -22, -40, -54, -72, 86, 64, 20, 78, 84, 78], [36, 30, -12, 38, 14, -90, -26, -24, 76, -78, 18, 42, -8, 46, 32, -32, -64, 74, -38, 6, 70, 58, 44, 8, -42, 10, 28, 80, -52, 92, -48, -18, -42, 84, -84, -44], [88, 4, 34, 48, 18, 64, 74, 46, -74, -46, 96, 68, 70, -60, -2, -20, 10, -52, 10, 20, 60, -10, -56, 96, -36, -72, -70, 14, 90, 38, -4, -64, -78, 4, -82, -58], [-20, 72, -88, -2, 68, -26, -94, 44, -44, -34, -82, -70, -58, 28, 56, 0, 18, -46, 42, 60, -80, 38, 14, -74, 20, -54, 90, 0, -86, 32, -90, 92, 44, -96, -38, -18], [38, -86, -92, 28, 18, 72, 42, -64, 92, 36, 60, 80, 50, 42, -56, 40, -92, 42, 12, 72, 2, 54, -22, -60, -92, 72, -58, -40, 98, -36, 70, 98, -70, -72, 78, -76], [-64, 58, -68, 90, -74, 32, -64, -30, 66, -36, 90, -16, 62, 82, 62, 20, -16, 32, 58, -80, 72, 98, 80, 60, -42, 8, 90, -66, -92, -54, -52, -18, -48, 98, 98, 58], [-12, 4, -22, 48, 60, 90, 70, -68, 84, 18, 6, -62, -98, -70, -58, -94, 92, 76, 6, 74, 44, 60, -6, -50, 30, 8, -18, 88, -50, 84, 94, -82, 32, 12, -36, -92], [-34, -46, -38, -38, 54, 84, -80, -92, -26, 94, 12, 88, -70, -74, 28, -42, -68, -62, 14, 42, 20, 6, 16, 26, -62, -22, -94, -28, -76, -96, 54, 30, -28, -28, -2, -22], [-18, -18, -36, 88, -16, -62, -12, -70, -34, 28, -10, 52, 12, 48, -38, -88, 24, -28, 0, -22, -74, 32, -54, 60, -36, 10, -32, 0, -60, -90, -6, 50, -24, -84, 70, 80], [74, -86, -98, -62, -74, -24, 52, 46, -12, 96, 6, 4, -52, 66, 40, 64, -16, 20, -52, 62, 10, -42, -94, -68, 60, 38, 44, 0, -14, 94, -56, 36, 84, 30, -96, -24], [60, -8, -86, -42, 60, -96, -10, 58, 30, 22, -6, 68, -88, 68, -74, -60, 40, 18, 4, -18, -20, -32, 62, -88, -22, -46, -16, 10, 36, 90, -42, -34, 6, 8, -26, -82], [66, 12, -8, -60, 26, 30, 42, -50, -44, 60, 14, 98, -38, -68, 40, -62, -50, -78, 26, -60, -50, -62, -34, -76, 4, 56, 80, 60, -18, -74, 60, 92, 58, 38, 4, 32], [-72, 82, -54, 62, -46, 18, 38, -54, 14, 66, -40, -96, -24, 40, -48, 10, 4, -90, 20, 48, -16, 28, 64, 64, -50, -92, -76, 22, 2, 92, -2, 82, 22, -4, -80, -46], [34, 60, -52, 60, 38, -60, -78, -2, -64, 94, 8, 34, 28, 68, 54, -60, -60, -40, -28, 32, -64, 32, -66, 68, 8, -2, 28, 86, -70, -64, -30, -70, -80, -42, -78, -28], [-52, 54, 88, 14, -18, 26, 76, 72, 90, 44, -64, -84, 22, -2, -26, 24, 8, -4, 94, -8, 6, 38, -44, 74, -84, 20, 26, -94, -68, -80, -52, 62, -98, 82, -4, -58], [-84, -26, 26, 66, 2, -52, -4, -98, 84, 40, -24, 84, 88, -2, -62, -56, -20, 32, -8, -98, -52, -32, -44, -52, 36, -4, 18, 14, 84, 16, -18, 28, 56, 74, -42, -80], [-34, -26, -54, -8, -8, 22, 0, -90, -58, 58, 88, 10, 52, -62, 16, -14, -58, -60, -78, -70, 66, -48, -12, -4, 36, -92, 64, -94, -22, 80, 8, -40, 84, -84, 68, 78]],),
(8,12,[[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]],),
(11,13,[[64, 68, 58, 56, 2, 27, 96, 83, 78, 9, 95, 48, 14, 87, 69, 80, 53, 66, 66], [73, 89, 19, 52, 59, 68, 81, 18, 13, 72, 3, 23, 38, 7, 31, 13, 43, 43, 23], [16, 27, 30, 3, 80, 29, 97, 63, 71, 40, 89, 30, 54, 97, 95, 37, 16, 68, 94], [37, 15, 40, 33, 21, 78, 39, 85, 98, 96, 20, 54, 73, 69, 31, 13, 20, 62, 85], [1, 69, 48, 96, 10, 31, 75, 60, 5, 70, 58, 49, 50, 86, 88, 23, 18, 33, 40], [68, 56, 90, 13, 86, 61, 96, 96, 24, 14, 95, 40, 67, 93, 46, 1, 3, 26, 59], [64, 32, 11, 34, 39, 79, 15, 31, 88, 70, 86, 88, 24, 46, 99, 98, 49, 59, 45], [41, 82, 38, 58, 88, 61, 8, 83, 98, 61, 41, 26, 23, 69, 78, 19, 55, 83, 58], [74, 29, 48, 22, 87, 66, 88, 90, 42, 11, 52, 1, 25, 58, 43, 4, 55, 59, 18], [78, 88, 25, 5, 10, 15, 79, 61, 1, 24, 97, 61, 15, 54, 67, 22, 46, 85, 59], [23, 10, 43, 18, 33, 49, 7, 40, 89, 2, 73, 27, 61, 69, 72, 89, 79, 89, 37], [64, 92, 9, 64, 3, 63, 47, 66, 59, 40, 19, 21, 67, 60, 28, 96, 3, 2, 66], [63, 16, 10, 51, 36, 9, 34, 89, 90, 84, 26, 82, 33, 14, 55, 44, 15, 83, 65], [37, 85, 66, 33, 57, 48, 83, 57, 11, 71, 11, 79, 45, 33, 45, 35, 78, 92, 87], [24, 83, 15, 14, 83, 19, 25, 13, 91, 77, 83, 76, 65, 22, 25, 86, 97, 37, 33], [21, 69, 3, 98, 62, 72, 89, 33, 37, 88, 56, 11, 19, 22, 85, 19, 38, 3, 32], [82, 24, 96, 11, 49, 40, 44, 64, 89, 47, 49, 99, 25, 54, 13, 75, 29, 22, 41], [79, 49, 25, 39, 26, 69, 87, 10, 2, 18, 99, 84, 53, 50, 89, 94, 22, 3, 26], [98, 70, 94, 92, 33, 45, 55, 56, 40, 94, 16, 83, 36, 57, 89, 13, 96, 82, 75]],)
]
n_success = 0
for i, parameters_set in enumerate(param):
f_filled(*(filled_function_param[i]))
f_gold(*parameters_set)
if parameters_set == filled_function_param[i]:
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) | 1,182.39726 | 8,724 | 0.44399 | 21,551 | 86,315 | 1.77718 | 0.007192 | 0.047833 | 0.038851 | 0.029661 | 0.987232 | 0.987206 | 0.986266 | 0.986266 | 0.984909 | 0.984909 | 0 | 0.587438 | 0.255749 | 86,315 | 73 | 8,725 | 1,182.39726 | 0.008764 | 0.002143 | 0 | 0.507937 | 0 | 0 | 0.000325 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.015873 | false | 0 | 0 | 0 | 0.015873 | 0.079365 | 0 | 0 | 1 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 11 |
819a74e50a1d290535e8c800ecfa1473c4a4cdbe | 181 | py | Python | tests/testeasy_pass.py | sahal-mulki/easy_pass | f40778e44e9de918d0583b80114c7d5ee9c0fe60 | [
"MIT"
] | 1 | 2021-02-06T06:11:24.000Z | 2021-02-06T06:11:24.000Z | tests/testeasy_pass.py | sahal-mulki/easy_pass | f40778e44e9de918d0583b80114c7d5ee9c0fe60 | [
"MIT"
] | null | null | null | tests/testeasy_pass.py | sahal-mulki/easy_pass | f40778e44e9de918d0583b80114c7d5ee9c0fe60 | [
"MIT"
] | null | null | null | from easy_pass import easy_pass
def test_haversine():
assert easy_pass.Password(password="password").hash == '5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8'
| 36.2 | 125 | 0.839779 | 17 | 181 | 8.705882 | 0.647059 | 0.162162 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.259036 | 0.082873 | 181 | 4 | 126 | 45.25 | 0.63253 | 0 | 0 | 0 | 0 | 0 | 0.39779 | 0.353591 | 0 | 0 | 0 | 0 | 0.333333 | 1 | 0.333333 | true | 0.666667 | 0.333333 | 0 | 0.666667 | 0 | 1 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 0 | 1 | 0 | 0 | 8 |
81af8d79e617c9c16ed6d0a89517e455cb3205a1 | 15,982 | py | Python | models.py | Blackbox-EVA2021/CMIWAE | 8e2b8fbfb40325e74512b004430f8f00801be13d | [
"MIT"
] | 1 | 2022-01-30T06:12:55.000Z | 2022-01-30T06:12:55.000Z | models.py | Blackbox-EVA2021/CMIWAE | 8e2b8fbfb40325e74512b004430f8f00801be13d | [
"MIT"
] | null | null | null | models.py | Blackbox-EVA2021/CMIWAE | 8e2b8fbfb40325e74512b004430f8f00801be13d | [
"MIT"
] | null | null | null | #! /usr/bin/env python
# Models
import torch
from torch import nn, Tensor
from typing import Type, List
class IllegalArgument(Exception):
pass
# Encoder and decoder parts for variational autoencoder
def conv_BN(in_ch, out_ch, kernel_size, stride, use_BatchNorm):
output = [nn.Conv2d(in_ch, out_ch, kernel_size, stride=stride, padding=(kernel_size - 1) // 2)]
if use_BatchNorm:
output.append(nn.BatchNorm2d(out_ch))
return output
class MinimalBlock(nn.Module):
def __init__(
self,
in_ch: int,
out_ch: int,
kernel_size: int = 3,
stride: int = 1,
nonlin = nn.ReLU(inplace=True),
use_BatchNorm: bool = True
) -> None:
super(MinimalBlock, self).__init__()
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
assert (in_ch >= 1) and (out_ch >= 1) and (kernel_size >= 1) and (stride >= 1)
layers = [nn.Conv2d(in_ch, out_ch, kernel_size, stride=stride, padding=(kernel_size - 1) // 2)]
layers.append(nonlin)
if use_BatchNorm:
layers.append(nn.BatchNorm2d(out_ch))
self.conv_nonlin_bn = torch.nn.Sequential(*layers)
def forward(self, x: Tensor) -> Tensor:
return self.conv_nonlin_bn(x)
def deconv_BN(in_ch, out_ch, kernel_size, stride, use_BatchNorm=True):
if stride == 1:
output_padding = 0
elif stride == 2:
output_padding = kernel_size % 2
else:
raise IllegalArgument(f"Unexpected value {stride} for stride.")
output = [nn.ConvTranspose2d(in_ch, out_ch, kernel_size, stride, padding=(kernel_size - 1) // 2, output_padding=output_padding)]
if use_BatchNorm:
output.append(nn.BatchNorm2d(out_ch))
return output
class MinimalBlockTranspose(nn.Module):
def __init__(
self,
in_ch: int,
out_ch: int,
kernel_size: int = 3,
stride: int = 1,
nonlin = nn.ReLU(inplace=True),
use_BatchNorm: bool = True
) -> None:
super(MinimalBlockTranspose, self).__init__()
# Both self.conv1 and self.downsample layers downsample the input when stride != 1
assert (in_ch >= 1) and (out_ch >= 1) and (kernel_size >= 1) and (stride >= 1)
if stride == 1:
output_padding = 0
elif stride == 2:
output_padding = kernel_size % 2
else:
raise IllegalArgument(f"Unexpected value {stride} for stride.")
layers = [nn.ConvTranspose2d(in_ch, out_ch, kernel_size, stride, padding=(kernel_size - 1) // 2, output_padding=output_padding)]
layers.append(nonlin)
if use_BatchNorm:
layers.append(nn.BatchNorm2d(out_ch))
self.deconv_nonlin_bn = torch.nn.Sequential(*layers)
def forward(self, x: Tensor) -> Tensor:
return self.deconv_nonlin_bn(x)
class Enc(nn.Module): # plain encoder, without additional level inputs or outputs
def __init__(
self,
in_ch: int,
block: Type[MinimalBlock],
height: int = 64,
width: int = 128,
layers_num: List[int] = [1, 1, 1, 1, 1, 1, 1],
channels: List[int] = [32, 48, 64, 96, 128, 192, 256],
latent_ch: int = 2,
latent_size: int = 64,
kernel_size: int = 3,
nonlin = nn.ReLU(inplace=True),
use_BatchNorm: bool = True,
dropout: float = 0.1,
fc_hidden_layer: int = None,
init_params = False
) -> None:
super(Enc, self).__init__()
assert (height >= 1) and (width >=1)
self.length = len(layers_num) # number of outputs, number of reductions (except first), number of block clusters
assert (self.length == len(channels)) and (self.length >= 1)
assert (in_ch >= 1) and (latent_ch >= 1) and (latent_size >= 1) and (kernel_size >= 1)
reduction_factor = 2**(self.length - 1)
assert (height % reduction_factor == 0) and (width % reduction_factor == 0)
self.dropout_lay = torch.nn.Dropout(dropout)
self.layer = []
input_ch = in_ch
for i in range(self.length):
self.layer.append(self._make_layer(block, layers_num[i], input_ch, channels[i], kernel_size, 1 if i == 0 else 2, nonlin, use_BatchNorm))
input_ch = channels[i]
self.layer = nn.ModuleList(self.layer)
self.fc_input_size = channels[-1] * (height // reduction_factor) * (width // reduction_factor)
if fc_hidden_layer is None:
self.fc = nn.Sequential(
torch.nn.Flatten(),
torch.nn.Linear(self.fc_input_size, latent_ch * latent_size),
torch.nn.Unflatten(1, (latent_ch, latent_size)))
else:
assert fc_hidden_layer >= 1
self.fc = nn.Sequential(
torch.nn.Flatten(),
torch.nn.Linear(self.fc_input_size, fc_hidden_layer),
torch.nn.BatchNorm1d(fc_hidden_layer),
nonlin,
torch.nn.Linear(fc_hidden_layer, latent_ch * latent_size),
torch.nn.Unflatten(1, (latent_ch, latent_size)))
if init_params:
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block: Type[MinimalBlock], blocks: int, in_ch: int, out_ch: int, kernel_size: int, stride: int,
nonlin, use_BatchNorm: bool)-> nn.Sequential:
assert blocks >= 1
layers = []
layers.append(block(in_ch, out_ch, kernel_size, stride, nonlin, use_BatchNorm))
for _ in range(1, blocks):
layers.append(block(out_ch, out_ch, kernel_size, 1, nonlin, use_BatchNorm))
return nn.Sequential(*layers)
def forward(self, x: Tensor) -> Tensor:
out = self.dropout_lay(x)
for i in range(self.length):
out = self.layer[i](out)
out = self.fc(out)
return out
def count_num_of_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
def get_fc_input_size(self):
return self.fc_input_size
class Enc_cond(nn.Module): # encoder for conditional data
def __init__(
self,
in_ch: int,
block: Type[MinimalBlock],
height: int = 64,
width: int = 128,
layers_num: List[int] = [1, 1, 1, 1, 1, 1, 1],
channels: List[int] = [32, 48, 64, 96, 128, 192, 256],
latent_ch: int = 2,
latent_size: int = 64,
kernel_size: int = 3,
nonlin = nn.ReLU(inplace=True),
use_BatchNorm: bool = True,
dropout: float = 0.1,
init_params = False
) -> None:
super(Enc_cond, self).__init__()
assert (height >= 1) and (width >=1)
self.length = len(layers_num) # number of outputs, number of reductions (except first), number of block clusters
assert (self.length == len(channels)) and (self.length >= 1)
assert (in_ch >= 1) and (latent_ch >= 1) and (latent_size >= 1) and (kernel_size >= 1)
reduction_factor = 2**(self.length - 1)
assert (height % reduction_factor == 0) and (width % reduction_factor == 0)
self.dropout_lay = torch.nn.Dropout(dropout)
self.layer = []
input_ch = in_ch
for i in range(self.length):
self.layer.append(self._make_layer(block, layers_num[i], input_ch, channels[i], kernel_size, 1 if i == 0 else 2, nonlin, use_BatchNorm))
input_ch = channels[i]
self.layer = nn.ModuleList(self.layer)
self.fc_input_size = channels[-1] * (height // reduction_factor) * (width // reduction_factor)
self.fc_params = nn.Sequential(
torch.nn.Flatten(),
torch.nn.Linear(self.fc_input_size, latent_ch * latent_size),
torch.nn.Unflatten(1, (latent_ch, latent_size))
)
if init_params:
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block: Type[MinimalBlock], blocks: int, in_ch: int, out_ch: int, kernel_size: int, stride: int,
nonlin, use_BatchNorm: bool)-> nn.Sequential:
assert blocks >= 1
layers = []
layers.append(block(in_ch, out_ch, kernel_size, stride, nonlin, use_BatchNorm))
for _ in range(1, blocks):
layers.append(block(out_ch, out_ch, kernel_size, 1, nonlin, use_BatchNorm))
return nn.Sequential(*layers)
def forward(self, x: Tensor) -> List[Tensor]:
output = [x]
out = self.dropout_lay(x)
for i in range(self.length):
out = self.layer[i](out)
output.append(out)
assert len(output) == self.length + 1
params = self.fc_params(out)
return output, params
def count_num_of_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
class Dec(nn.Module): # plain decoder, without additional level inputs
def __init__(
self,
out_ch: int,
block: Type[MinimalBlockTranspose],
height: int = 64,
width: int = 128,
layers_num: List[int] = [1, 1, 1, 1, 1, 1, 1],
channels: List[int] = [32, 48, 64, 96, 128, 192, 256],
latent_size: int = 64,
kernel_size: int = 3,
nonlin = nn.ReLU(inplace=True),
use_BatchNorm: bool = True,
dropout: float = 0.1,
init_params = False
) -> None:
super(Dec, self).__init__()
assert (height >= 1) and (width >=1)
self.length = len(layers_num) # number of outputs, number of reductions (except first), number of block clusters
assert (self.length == len(channels)) and (self.length >= 1)
assert (out_ch >= 1) and (latent_size >= 1) and (kernel_size >= 1)
reduction_factor = 2**(self.length - 1)
assert (height % reduction_factor == 0) and (width % reduction_factor == 0)
self.dropout_lay = torch.nn.Dropout(dropout)
self.fc = nn.Sequential(
torch.nn.Linear(latent_size, channels[-1] * (height // reduction_factor) * (width // reduction_factor)),
nonlin,
torch.nn.Unflatten(1, (channels[-1], (height // reduction_factor), (width // reduction_factor)))
)
self.layer = []
input_ch = channels[-1]
for i in range(self.length - 1, 0, -1):
self.layer.append(self._make_layer(block, layers_num[i], channels[i], channels[i - 1], kernel_size, 2, nonlin, use_BatchNorm))
self.layer.append(self._make_layer(block, layers_num[i], channels[0], out_ch, kernel_size, 1, nonlin, use_BatchNorm))
self.layer = nn.ModuleList(self.layer)
if init_params:
for m in self.modules():
if isinstance(m, nn.ConvTranspose2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block: Type[MinimalBlockTranspose], blocks: int, in_ch: int, out_ch: int, kernel_size: int, stride: int,
nonlin, use_BatchNorm: bool)-> nn.Sequential:
assert blocks >= 1
layers = []
layers.append(block(in_ch, out_ch, kernel_size, stride, nonlin, use_BatchNorm))
for _ in range(1, blocks):
layers.append(block(out_ch, out_ch, kernel_size, 1, nonlin, use_BatchNorm))
return nn.Sequential(*layers)
def forward(self, x: Tensor) -> Tensor:
out = self.dropout_lay(x)
out = self.fc(out)
for i in range(self.length):
out = self.layer[i](out)
return out
def count_num_of_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad)
class Dec_cond(nn.Module): # conditional decoder, with additional level inputs of conditional data from conditional encoder
def __init__(
self,
out_ch: int,
block: Type[MinimalBlockTranspose],
height: int = 64,
width: int = 128,
layers_num: List[int] = [1, 1, 1, 1, 1, 1, 1],
channels: List[int] = [32, 48, 64, 96, 128, 192, 256],
cond_in_ch: List[int] = [32, 48, 64, 96, 128, 192, 256],
latent_size: int = 64,
kernel_size: int = 3,
nonlin = nn.ReLU(inplace=True),
use_BatchNorm: bool = True,
dropout: float = 0.1,
init_params = False
) -> None:
super(Dec_cond, self).__init__()
assert (height >= 1) and (width >=1)
self.length = len(layers_num) # number of outputs, number of reductions (except first), number of block clusters
assert (self.length == len(channels)) and (self.length >= 1)
assert (out_ch >= 1) and (latent_size >= 1) and (kernel_size >= 1)
self.cond_in_ch = cond_in_ch
reduction_factor = 2**(self.length - 1)
assert (height % reduction_factor == 0) and (width % reduction_factor == 0)
self.dropout_lay = torch.nn.Dropout(dropout)
self.fc = nn.Sequential(
torch.nn.Linear(latent_size, channels[-1] * (height // reduction_factor) * (width // reduction_factor)),
nonlin,
torch.nn.Unflatten(1, (channels[-1], (height // reduction_factor), (width // reduction_factor)))
)
self.layer = []
for i in range(self.length - 1, 0, -1):
self.layer.append(self._make_layer(block, layers_num[i], channels[i] + cond_in_ch[i], channels[i - 1], kernel_size, 2, nonlin, use_BatchNorm))
self.layer.append(self._make_layer(block, layers_num[i], channels[0] + cond_in_ch[0], out_ch, kernel_size, 1, nonlin, use_BatchNorm))
self.layer = nn.ModuleList(self.layer)
if init_params:
for m in self.modules():
if isinstance(m, nn.ConvTranspose2d):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
def _make_layer(self, block: Type[MinimalBlockTranspose], blocks: int, in_ch: int, out_ch: int, kernel_size: int, stride: int,
nonlin, use_BatchNorm: bool)-> nn.Sequential:
assert blocks >= 1
layers = []
layers.append(block(in_ch, out_ch, kernel_size, stride, nonlin, use_BatchNorm))
for _ in range(1, blocks):
layers.append(block(out_ch, out_ch, kernel_size, 1, nonlin, use_BatchNorm))
return nn.Sequential(*layers)
def forward(self, x: Tensor, xl: List[Tensor]) -> Tensor:
assert len(xl) == self.length + 1
out = self.dropout_lay(x)
out = self.fc(out)
for i in range(self.length):
out = torch.cat([out, xl[self.length - i][:, :self.cond_in_ch[(self.length - 1) - i]]], 1)
out = self.layer[i](out)
return out
def count_num_of_parameters(self):
return sum(p.numel() for p in self.parameters() if p.requires_grad) | 40.055138 | 154 | 0.586723 | 2,081 | 15,982 | 4.318597 | 0.074003 | 0.046734 | 0.006676 | 0.026705 | 0.888172 | 0.888172 | 0.884834 | 0.884834 | 0.884834 | 0.884389 | 0 | 0.026919 | 0.293393 | 15,982 | 399 | 155 | 40.055138 | 0.768883 | 0.049869 | 0 | 0.824451 | 0 | 0 | 0.007777 | 0 | 0 | 0 | 0 | 0 | 0.07837 | 1 | 0.0721 | false | 0.003135 | 0.009404 | 0.021944 | 0.15674 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
81c7197bd1ebf9b4509a5409fd04c7564ca8639e | 178 | py | Python | tests/test_charinfo.py | vim-scripts/betterga | b735e2787aad6abb051343a8cd1f8441391214e9 | [
"MIT"
] | null | null | null | tests/test_charinfo.py | vim-scripts/betterga | b735e2787aad6abb051343a8cd1f8441391214e9 | [
"MIT"
] | null | null | null | tests/test_charinfo.py | vim-scripts/betterga | b735e2787aad6abb051343a8cd1f8441391214e9 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding:utf-8 -*-
import doctest
import autoload.betterga
def load_tests(loader, tests, ignore):
return doctest.DocTestSuite(autoload.betterga)
| 17.8 | 50 | 0.735955 | 23 | 178 | 5.652174 | 0.782609 | 0.246154 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.006452 | 0.129213 | 178 | 9 | 51 | 19.777778 | 0.832258 | 0.230337 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.25 | false | 0 | 0.5 | 0.25 | 1 | 0 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 7 |
c490493a85ef61d2890b52782c56fd890e2c924e | 14,974 | py | Python | isi_sdk_8_1_0/test/test_protocols_api.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 24 | 2018-06-22T14:13:23.000Z | 2022-03-23T01:21:26.000Z | isi_sdk_8_1_0/test/test_protocols_api.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 46 | 2018-04-30T13:28:22.000Z | 2022-03-21T21:11:07.000Z | isi_sdk_8_1_0/test/test_protocols_api.py | mohitjain97/isilon_sdk_python | a371f438f542568edb8cda35e929e6b300b1177c | [
"Unlicense"
] | 29 | 2018-06-19T00:14:04.000Z | 2022-02-08T17:51:19.000Z | # coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 5
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import isi_sdk_8_1_0
from isi_sdk_8_1_0.api.protocols_api import ProtocolsApi # noqa: E501
from isi_sdk_8_1_0.rest import ApiException
class TestProtocolsApi(unittest.TestCase):
"""ProtocolsApi unit test stubs"""
def setUp(self):
self.api = isi_sdk_8_1_0.api.protocols_api.ProtocolsApi() # noqa: E501
def tearDown(self):
pass
def test_create_hdfs_proxyuser(self):
"""Test case for create_hdfs_proxyuser
"""
pass
def test_create_hdfs_rack(self):
"""Test case for create_hdfs_rack
"""
pass
def test_create_ndmp_settings_preferred_ip(self):
"""Test case for create_ndmp_settings_preferred_ip
"""
pass
def test_create_ndmp_settings_variable(self):
"""Test case for create_ndmp_settings_variable
"""
pass
def test_create_ndmp_user(self):
"""Test case for create_ndmp_user
"""
pass
def test_create_nfs_alias(self):
"""Test case for create_nfs_alias
"""
pass
def test_create_nfs_export(self):
"""Test case for create_nfs_export
"""
pass
def test_create_nfs_netgroup_check_item(self):
"""Test case for create_nfs_netgroup_check_item
"""
pass
def test_create_nfs_netgroup_flush_item(self):
"""Test case for create_nfs_netgroup_flush_item
"""
pass
def test_create_nfs_nlm_sessions_check_item(self):
"""Test case for create_nfs_nlm_sessions_check_item
"""
pass
def test_create_nfs_reload_item(self):
"""Test case for create_nfs_reload_item
"""
pass
def test_create_ntp_server(self):
"""Test case for create_ntp_server
"""
pass
def test_create_smb_log_level_filter(self):
"""Test case for create_smb_log_level_filter
"""
pass
def test_create_smb_share(self):
"""Test case for create_smb_share
"""
pass
def test_create_swift_account(self):
"""Test case for create_swift_account
"""
pass
def test_delete_hdfs_proxyuser(self):
"""Test case for delete_hdfs_proxyuser
"""
pass
def test_delete_hdfs_rack(self):
"""Test case for delete_hdfs_rack
"""
pass
def test_delete_ndmp_contexts_backup_by_id(self):
"""Test case for delete_ndmp_contexts_backup_by_id
"""
pass
def test_delete_ndmp_contexts_bre_by_id(self):
"""Test case for delete_ndmp_contexts_bre_by_id
"""
pass
def test_delete_ndmp_contexts_restore_by_id(self):
"""Test case for delete_ndmp_contexts_restore_by_id
"""
pass
def test_delete_ndmp_dumpdate(self):
"""Test case for delete_ndmp_dumpdate
"""
pass
def test_delete_ndmp_session(self):
"""Test case for delete_ndmp_session
"""
pass
def test_delete_ndmp_settings_preferred_ip(self):
"""Test case for delete_ndmp_settings_preferred_ip
"""
pass
def test_delete_ndmp_settings_variable(self):
"""Test case for delete_ndmp_settings_variable
"""
pass
def test_delete_ndmp_user(self):
"""Test case for delete_ndmp_user
"""
pass
def test_delete_nfs_alias(self):
"""Test case for delete_nfs_alias
"""
pass
def test_delete_nfs_export(self):
"""Test case for delete_nfs_export
"""
pass
def test_delete_nfs_nlm_session(self):
"""Test case for delete_nfs_nlm_session
"""
pass
def test_delete_ntp_server(self):
"""Test case for delete_ntp_server
"""
pass
def test_delete_ntp_servers(self):
"""Test case for delete_ntp_servers
"""
pass
def test_delete_smb_log_level_filter(self):
"""Test case for delete_smb_log_level_filter
"""
pass
def test_delete_smb_log_level_filters(self):
"""Test case for delete_smb_log_level_filters
"""
pass
def test_delete_smb_openfile(self):
"""Test case for delete_smb_openfile
"""
pass
def test_delete_smb_session(self):
"""Test case for delete_smb_session
"""
pass
def test_delete_smb_sessions_computer_user(self):
"""Test case for delete_smb_sessions_computer_user
"""
pass
def test_delete_smb_share(self):
"""Test case for delete_smb_share
"""
pass
def test_delete_smb_shares(self):
"""Test case for delete_smb_shares
"""
pass
def test_delete_swift_account(self):
"""Test case for delete_swift_account
"""
pass
def test_get_ftp_settings(self):
"""Test case for get_ftp_settings
"""
pass
def test_get_hdfs_log_level(self):
"""Test case for get_hdfs_log_level
"""
pass
def test_get_hdfs_proxyuser(self):
"""Test case for get_hdfs_proxyuser
"""
pass
def test_get_hdfs_rack(self):
"""Test case for get_hdfs_rack
"""
pass
def test_get_hdfs_ranger_plugin_settings(self):
"""Test case for get_hdfs_ranger_plugin_settings
"""
pass
def test_get_hdfs_settings(self):
"""Test case for get_hdfs_settings
"""
pass
def test_get_http_settings(self):
"""Test case for get_http_settings
"""
pass
def test_get_ndmp_contexts_backup(self):
"""Test case for get_ndmp_contexts_backup
"""
pass
def test_get_ndmp_contexts_backup_by_id(self):
"""Test case for get_ndmp_contexts_backup_by_id
"""
pass
def test_get_ndmp_contexts_bre(self):
"""Test case for get_ndmp_contexts_bre
"""
pass
def test_get_ndmp_contexts_bre_by_id(self):
"""Test case for get_ndmp_contexts_bre_by_id
"""
pass
def test_get_ndmp_contexts_restore(self):
"""Test case for get_ndmp_contexts_restore
"""
pass
def test_get_ndmp_contexts_restore_by_id(self):
"""Test case for get_ndmp_contexts_restore_by_id
"""
pass
def test_get_ndmp_diagnostics(self):
"""Test case for get_ndmp_diagnostics
"""
pass
def test_get_ndmp_dumpdate(self):
"""Test case for get_ndmp_dumpdate
"""
pass
def test_get_ndmp_logs(self):
"""Test case for get_ndmp_logs
"""
pass
def test_get_ndmp_session(self):
"""Test case for get_ndmp_session
"""
pass
def test_get_ndmp_sessions(self):
"""Test case for get_ndmp_sessions
"""
pass
def test_get_ndmp_settings_dmas(self):
"""Test case for get_ndmp_settings_dmas
"""
pass
def test_get_ndmp_settings_global(self):
"""Test case for get_ndmp_settings_global
"""
pass
def test_get_ndmp_settings_preferred_ip(self):
"""Test case for get_ndmp_settings_preferred_ip
"""
pass
def test_get_ndmp_settings_variable(self):
"""Test case for get_ndmp_settings_variable
"""
pass
def test_get_ndmp_user(self):
"""Test case for get_ndmp_user
"""
pass
def test_get_nfs_alias(self):
"""Test case for get_nfs_alias
"""
pass
def test_get_nfs_check(self):
"""Test case for get_nfs_check
"""
pass
def test_get_nfs_export(self):
"""Test case for get_nfs_export
"""
pass
def test_get_nfs_exports_summary(self):
"""Test case for get_nfs_exports_summary
"""
pass
def test_get_nfs_log_level(self):
"""Test case for get_nfs_log_level
"""
pass
def test_get_nfs_netgroup(self):
"""Test case for get_nfs_netgroup
"""
pass
def test_get_nfs_nlm_locks(self):
"""Test case for get_nfs_nlm_locks
"""
pass
def test_get_nfs_nlm_session(self):
"""Test case for get_nfs_nlm_session
"""
pass
def test_get_nfs_nlm_sessions(self):
"""Test case for get_nfs_nlm_sessions
"""
pass
def test_get_nfs_nlm_waiters(self):
"""Test case for get_nfs_nlm_waiters
"""
pass
def test_get_nfs_settings_export(self):
"""Test case for get_nfs_settings_export
"""
pass
def test_get_nfs_settings_global(self):
"""Test case for get_nfs_settings_global
"""
pass
def test_get_nfs_settings_zone(self):
"""Test case for get_nfs_settings_zone
"""
pass
def test_get_ntp_server(self):
"""Test case for get_ntp_server
"""
pass
def test_get_ntp_settings(self):
"""Test case for get_ntp_settings
"""
pass
def test_get_smb_log_level(self):
"""Test case for get_smb_log_level
"""
pass
def test_get_smb_log_level_filter(self):
"""Test case for get_smb_log_level_filter
"""
pass
def test_get_smb_openfiles(self):
"""Test case for get_smb_openfiles
"""
pass
def test_get_smb_sessions(self):
"""Test case for get_smb_sessions
"""
pass
def test_get_smb_settings_global(self):
"""Test case for get_smb_settings_global
"""
pass
def test_get_smb_settings_share(self):
"""Test case for get_smb_settings_share
"""
pass
def test_get_smb_share(self):
"""Test case for get_smb_share
"""
pass
def test_get_smb_shares_summary(self):
"""Test case for get_smb_shares_summary
"""
pass
def test_get_snmp_settings(self):
"""Test case for get_snmp_settings
"""
pass
def test_get_swift_account(self):
"""Test case for get_swift_account
"""
pass
def test_list_hdfs_proxyusers(self):
"""Test case for list_hdfs_proxyusers
"""
pass
def test_list_hdfs_racks(self):
"""Test case for list_hdfs_racks
"""
pass
def test_list_ndmp_settings_preferred_ips(self):
"""Test case for list_ndmp_settings_preferred_ips
"""
pass
def test_list_ndmp_users(self):
"""Test case for list_ndmp_users
"""
pass
def test_list_nfs_aliases(self):
"""Test case for list_nfs_aliases
"""
pass
def test_list_nfs_exports(self):
"""Test case for list_nfs_exports
"""
pass
def test_list_ntp_servers(self):
"""Test case for list_ntp_servers
"""
pass
def test_list_smb_log_level_filters(self):
"""Test case for list_smb_log_level_filters
"""
pass
def test_list_smb_shares(self):
"""Test case for list_smb_shares
"""
pass
def test_list_swift_accounts(self):
"""Test case for list_swift_accounts
"""
pass
def test_update_ftp_settings(self):
"""Test case for update_ftp_settings
"""
pass
def test_update_hdfs_log_level(self):
"""Test case for update_hdfs_log_level
"""
pass
def test_update_hdfs_proxyuser(self):
"""Test case for update_hdfs_proxyuser
"""
pass
def test_update_hdfs_rack(self):
"""Test case for update_hdfs_rack
"""
pass
def test_update_hdfs_ranger_plugin_settings(self):
"""Test case for update_hdfs_ranger_plugin_settings
"""
pass
def test_update_hdfs_settings(self):
"""Test case for update_hdfs_settings
"""
pass
def test_update_http_settings(self):
"""Test case for update_http_settings
"""
pass
def test_update_ndmp_diagnostics(self):
"""Test case for update_ndmp_diagnostics
"""
pass
def test_update_ndmp_settings_global(self):
"""Test case for update_ndmp_settings_global
"""
pass
def test_update_ndmp_settings_preferred_ip(self):
"""Test case for update_ndmp_settings_preferred_ip
"""
pass
def test_update_ndmp_settings_variable(self):
"""Test case for update_ndmp_settings_variable
"""
pass
def test_update_ndmp_user(self):
"""Test case for update_ndmp_user
"""
pass
def test_update_nfs_alias(self):
"""Test case for update_nfs_alias
"""
pass
def test_update_nfs_export(self):
"""Test case for update_nfs_export
"""
pass
def test_update_nfs_log_level(self):
"""Test case for update_nfs_log_level
"""
pass
def test_update_nfs_netgroup(self):
"""Test case for update_nfs_netgroup
"""
pass
def test_update_nfs_settings_export(self):
"""Test case for update_nfs_settings_export
"""
pass
def test_update_nfs_settings_global(self):
"""Test case for update_nfs_settings_global
"""
pass
def test_update_nfs_settings_zone(self):
"""Test case for update_nfs_settings_zone
"""
pass
def test_update_ntp_server(self):
"""Test case for update_ntp_server
"""
pass
def test_update_ntp_settings(self):
"""Test case for update_ntp_settings
"""
pass
def test_update_smb_log_level(self):
"""Test case for update_smb_log_level
"""
pass
def test_update_smb_settings_global(self):
"""Test case for update_smb_settings_global
"""
pass
def test_update_smb_settings_share(self):
"""Test case for update_smb_settings_share
"""
pass
def test_update_smb_share(self):
"""Test case for update_smb_share
"""
pass
def test_update_snmp_settings(self):
"""Test case for update_snmp_settings
"""
pass
def test_update_swift_account(self):
"""Test case for update_swift_account
"""
pass
if __name__ == '__main__':
unittest.main()
| 19.371281 | 79 | 0.600508 | 1,870 | 14,974 | 4.372193 | 0.063636 | 0.105308 | 0.165484 | 0.22566 | 0.917441 | 0.736179 | 0.377079 | 0.148483 | 0.038772 | 0 | 0 | 0.002263 | 0.32129 | 14,974 | 772 | 80 | 19.396373 | 0.802224 | 0.394951 | 0 | 0.48062 | 1 | 0 | 0.000951 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.484496 | false | 0.48062 | 0.01938 | 0 | 0.507752 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 7 |
c4b736c7124c8f106cb46d0707d43f5cd5161472 | 111 | py | Python | test.py | BAXYCoding/coding-practice | fad58d84c3e26d38136b31aba20047f4729916ac | [
"Unlicense"
] | null | null | null | test.py | BAXYCoding/coding-practice | fad58d84c3e26d38136b31aba20047f4729916ac | [
"Unlicense"
] | null | null | null | test.py | BAXYCoding/coding-practice | fad58d84c3e26d38136b31aba20047f4729916ac | [
"Unlicense"
] | null | null | null | from arithmetic_arranger import *
print(arithmetic_arranger(["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]))
| 27.75 | 75 | 0.648649 | 15 | 111 | 4.666667 | 0.866667 | 0.514286 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0.202128 | 0.153153 | 111 | 3 | 76 | 37 | 0.542553 | 0 | 0 | 0 | 0 | 0 | 0.279279 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | true | 0 | 0.5 | 0 | 0.5 | 0.5 | 1 | 0 | 0 | null | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 1 | 0 | 7 |
c4ce5fdb838bec36b7675ec2002d77f6acbd4c0e | 18,599 | py | Python | datagenerators.py | threehundred/benthic-ensemble-paper | 30dc12ecb1b842ba1a65db50ac9c748abf464ae2 | [
"MIT"
] | null | null | null | datagenerators.py | threehundred/benthic-ensemble-paper | 30dc12ecb1b842ba1a65db50ac9c748abf464ae2 | [
"MIT"
] | null | null | null | datagenerators.py | threehundred/benthic-ensemble-paper | 30dc12ecb1b842ba1a65db50ac9c748abf464ae2 | [
"MIT"
] | null | null | null | import tensorflow as tf
from random import shuffle, sample
import os
import random
import tensorflow.keras
import pandas as pd
import sqlite3
import numpy as np
import pickle
from PIL import Image
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
import utils
#from import utils
from multilabeldirectoryiterator import MultiLabelDirectoryIterator
from fullimagepointcroppingloader import FullImagePointCroppingLoader
class KerasDataset:
SQLITE = "SQLITE"
CSV = "CSV"
def __init__(self,
filepath,
label_key,
image_path_key,
category_limit=10000000,
query=None,
save_path=None,
img_width=256,
img_height=256,
batch_size=16,
patch_sizes=[]):
self.save_path = save_path
self.IMG_WIDTH = img_width
self.IMG_HEIGHT = img_height
self.BATCH_SIZE = batch_size
if ".sqlite" in filepath:
self.X_train, \
self.X_val, \
self.X_test, \
self.y_train, \
self.y_val, \
self.y_test, \
self.classes, \
self.class_weight_dict = self.package_from_sqlite(filepath, query, label_key, image_path_key, category_limit, save_path)
self.mean_image = self.calculate_mean_image(self.X_train)
elif ".csv" in filepath:
self.X_train, \
self.X_val, \
self.X_test, \
self.y_train, \
self.y_val, \
self.y_test, \
self.classes, \
self.class_weight_dict = self.package_from_csv(filepath, label_key, image_path_key, category_limit, save_path)
self.mean_image = self.calculate_mean_image(self.X_train)
else:
self.X_train, \
self.X_val, \
self.X_test, \
self.y_train, \
self.y_val, \
self.y_test, \
self.classes, \
self.class_weight_dict = self.load_saved_data(filepath)
self.mean_image = self.load_mean_image(filepath)
self.training = self.make_train_generator(self.X_train, self.y_train, patch_sizes)
self.validation = self.make_val_generator(self.X_val, self.y_val, patch_sizes)
def train_val_test(self, df, label_key, image_path_key, limit):
LABEL_KEY = label_key
SAMPLE_SIZE = limit
labels = df[LABEL_KEY].unique()
dfs = []
for label in labels:
sub_df = df[df[LABEL_KEY] == label]
if len(sub_df) <= SAMPLE_SIZE:
dfs.append(sub_df)
else:
dfs.append(sub_df.sample(n=SAMPLE_SIZE))
df = pd.concat(dfs)
X = []
y = []
for index, row in df.iterrows():
X.append(row[image_path_key])
y.append(row[LABEL_KEY])
le = preprocessing.LabelEncoder()
y = le.fit_transform(y)
from sklearn.utils import class_weight
class_weight = class_weight.compute_class_weight('balanced', np.unique(y), y)
class_weight_dict = dict(enumerate(class_weight))
onehot_y = np.zeros((len(y), len(le.classes_)), dtype="float16")
for i, label_index in enumerate(y):
onehot_y[i, label_index] = 1.
y = onehot_y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
return X_train, X_val, X_test, y_train, y_val, y_test, le.classes_, class_weight_dict
def package_from_dataframe(self, df, label_key, image_path_key, category_limit, save_path=None):
X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict = self.train_val_test(df,
label_key=label_key,
image_path_key=image_path_key,
limit=category_limit)
if save_path is not None:
if not os.path.isdir(save_path):
os.makedirs(save_path)
self.pickle_objects(save_path,
[X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict],
["X_train", "X_val", "X_test", "y_train", "y_val", "y_test", "classes", "class_weight_dict"])
self.save_labels(save_path, classes)
return X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict
def package_from_csv(self, csv_file, label_key, image_path_key, category_limit, save_path=None):
all_photos = pd.read_csv(csv_file)
return self.package_from_dataframe(all_photos, label_key=label_key, image_path_key=image_path_key,
category_limit=category_limit, save_path=save_path)
def package_from_sqlite(self, sqlite_file, query, label_key, image_path_key, category_limit, save_path=None):
con = sqlite3.connect(sqlite_file)
all_photos = pd.read_sql_query(query, con)
con.close()
return self.package_from_dataframe(all_photos, label_key=label_key, image_path_key=image_path_key,
category_limit=category_limit, save_path=save_path)
def pickle_objects(self, destination_path, objects_to_save, filenames):
for index, item_to_save in enumerate(objects_to_save):
pickle.dump(item_to_save, open(os.path.join(destination_path, str(filenames[index]) + ".p"), "wb"))
def save_labels(self, destination_path, classes):
with open(os.path.join(destination_path, "labels.txt"), 'w') as file_handler:
for item in classes:
file_handler.write("{}\n".format(item))
def load_saved_data(self, path):
X_train = pickle.load(open(os.path.join(path ,"X_train.p"), "rb"))
X_val = pickle.load(open(os.path.join(path, "X_val.p"), "rb"))
X_test = None#pickle.load(open(os.path.join(path, "X_test.p"), "rb"))
y_train = pickle.load(open(os.path.join(path, "y_train.p"), "rb"))
y_val = pickle.load(open(os.path.join(path, "y_val.p"), "rb"))
y_test = None #pickle.load(open(os.path.join(path, "y_test.p"), "rb"))
classes = pickle.load(open(os.path.join(path, "classes.p"), "rb"))
class_weight_dict = pickle.load(open(os.path.join(path, "class_weight_dict.p"), "rb"))
return X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict
def make_train_generator(self, X_train, y_train, patch_sizes):
train_datagen = ImageDataGenerator(
horizontal_flip=True,
vertical_flip=True,
preprocessing_function=self.preprocess_img)
train_generator = MultiLabelDirectoryIterator(
X_train, y_train, train_datagen,
target_size=(self.IMG_WIDTH, self.IMG_HEIGHT),
batch_size=self.BATCH_SIZE,
class_mode='categorical')
# save_to_dir="./augmentedsamples")
return train_generator
def make_val_generator(self, X_val, y_val, patch_sizes):
val_datagen = ImageDataGenerator(preprocessing_function=self.preprocess_img)
val_generator = MultiLabelDirectoryIterator(
X_val, y_val, val_datagen,
target_size=(self.IMG_WIDTH, self.IMG_HEIGHT),
batch_size=self.BATCH_SIZE,
class_mode='categorical')
# save_to_dir="./augmentedsamples")
return val_generator
def calculate_mean_image(self, X_train):
mean_image = utils.calculate_mean_image_from_file_list(X_train)
im = Image.fromarray(mean_image)
im.save(os.path.join(self.save_path, "mean_image.jpg"))
return np.array(im, dtype=np.float)
def load_mean_image(self, filepath):
mean_image = Image.open(os.path.join(filepath, "mean_image.jpg"))
return mean_image
def preprocess_img(self, img):
img -= self.mean_image
return img
class KerasFullImageDataset:
SQLITE = "SQLITE"
CSV = "CSV"
def __init__(self,
filepath,
label_key,
image_path_key,
point_x_key,
point_y_key,
category_limit=10000000,
query=None,
save_path=None,
img_width=256,
img_height=256,
batch_size=16,
patch_sizes=[]):
self.save_path = save_path
self.IMG_WIDTH = img_width
self.IMG_HEIGHT = img_height
self.BATCH_SIZE = batch_size
if ".sqlite" in filepath:
self.X_train, \
self.X_val, \
self.X_test, \
self.y_train, \
self.y_val, \
self.y_test, \
self.classes, \
self.class_weight_dict = self.package_from_sqlite(filepath, query, label_key, image_path_key, point_x_key, point_y_key, category_limit, save_path)
self.mean_image = self.calculate_mean_image(self.X_train)
elif ".csv" in filepath:
self.X_train, \
self.X_val, \
self.X_test, \
self.y_train, \
self.y_val, \
self.y_test, \
self.classes, \
self.class_weight_dict = self.package_from_csv(filepath, label_key, image_path_key, point_x_key, point_y_key, category_limit, save_path)
self.mean_image = self.calculate_mean_image(self.X_train)
else:
self.X_train, \
self.X_val, \
self.X_test, \
self.y_train, \
self.y_val, \
self.y_test, \
self.classes, \
self.class_weight_dict = self.load_saved_data(filepath)
self.mean_image = self.load_mean_image(filepath)
self.training = self.make_train_generator(self.X_train, self.y_train, patch_sizes)
self.validation = self.make_val_generator(self.X_val, self.y_val, patch_sizes)
def train_val_test(self, df, label_key, image_path_key, point_x_key, point_y_key, limit):
LABEL_KEY = label_key
SAMPLE_SIZE = limit
labels = df[LABEL_KEY].unique()
dfs = []
for label in labels:
sub_df = df[df[LABEL_KEY] == label]
if len(sub_df) <= SAMPLE_SIZE:
dfs.append(sub_df)
else:
dfs.append(sub_df.sample(n=SAMPLE_SIZE))
df = pd.concat(dfs)
X = []
y = []
for index, row in df.iterrows():
X.append({"image_path": row[image_path_key], "point_x": row[point_x_key], "point_y": row[point_y_key]})
y.append(row[LABEL_KEY])
le = preprocessing.LabelEncoder()
y = le.fit_transform(y)
from sklearn.utils import class_weight
class_weight = class_weight.compute_class_weight('balanced', np.unique(y), y)
class_weight_dict = dict(enumerate(class_weight))
onehot_y = np.zeros((len(y), len(le.classes_)), dtype="float16")
for i, label_index in enumerate(y):
onehot_y[i, label_index] = 1.
y = onehot_y
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)
return X_train, X_val, X_test, y_train, y_val, y_test, le.classes_, class_weight_dict
def package_from_dataframe(self, df, label_key, image_path_key, point_x_key, point_y_key, category_limit, save_path=None):
X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict = self.train_val_test(df,
label_key=label_key,
point_x_key=point_x_key,
point_y_key=point_y_key,
image_path_key=image_path_key,
limit=category_limit)
if save_path is not None:
if not os.path.isdir(save_path):
os.makedirs(save_path)
self.pickle_objects(save_path,
[X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict],
["X_train", "X_val", "X_test", "y_train", "y_val", "y_test", "classes", "class_weight_dict"])
self.save_labels(save_path, classes)
return X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict
def package_from_csv(self, csv_file, label_key, image_path_key, point_x_key, point_y_key, category_limit, save_path=None):
all_photos = pd.read_csv(csv_file)
return self.package_from_dataframe(all_photos, label_key=label_key, image_path_key=image_path_key, point_x_key=point_x_key, point_y_key=point_y_key,
category_limit=category_limit, save_path=save_path)
def package_from_sqlite(self, sqlite_file, query, label_key, image_path_key, point_x_key, point_y_key, category_limit, save_path=None):
con = sqlite3.connect(sqlite_file)
all_photos = pd.read_sql_query(query, con)
con.close()
return self.package_from_dataframe(all_photos, label_key=label_key, image_path_key=image_path_key, point_x_key=point_x_key, point_y_key=point_y_key,
category_limit=category_limit, save_path=save_path)
def pickle_objects(self, destination_path, objects_to_save, filenames):
for index, item_to_save in enumerate(objects_to_save):
pickle.dump(item_to_save, open(os.path.join(destination_path, str(filenames[index]) + ".p"), "wb"))
def save_labels(self, destination_path, classes):
with open(os.path.join(destination_path, "labels.txt"), 'w') as file_handler:
for item in classes:
file_handler.write("{}\n".format(item))
def load_saved_data(self, path):
X_train = pickle.load(open(os.path.join(path ,"X_train.p"), "rb"))
X_val = pickle.load(open(os.path.join(path, "X_val.p"), "rb"))
X_test = None#pickle.load(open(os.path.join(path, "X_test.p"), "rb"))
y_train = pickle.load(open(os.path.join(path, "y_train.p"), "rb"))
y_val = pickle.load(open(os.path.join(path, "y_val.p"), "rb"))
y_test = None #pickle.load(open(os.path.join(path, "y_test.p"), "rb"))
classes = pickle.load(open(os.path.join(path, "classes.p"), "rb"))
class_weight_dict = pickle.load(open(os.path.join(path, "class_weight_dict.p"), "rb"))
return X_train, X_val, X_test, y_train, y_val, y_test, classes, class_weight_dict
def the_generator(self, X_train, y_train, batch_size, cropping_function):
nb_train_samples = len(X_train)
while True:
for start in range(0, nb_train_samples, batch_size):
x_batch = []
y_batch = []
end = min(start + batch_size, nb_train_samples)
for index in range(start, end):
patch = cropping_function(X_train[index])
y = y_train[index]
x_batch.append(patch)
y_batch.append(y)
yield (np.array(x_batch), np.array(y_batch))
def make_train_generator(self, X_train, y_train, patch_sizes):
train_generator = FullImagePointCroppingLoader(X_train, y_train,
#train_generator = self.the_generator(X_train, y_train,
self.BATCH_SIZE,
self.cropping_function)
return train_generator
def cropping_function(self, image_dict):
patch = utils.load_image_and_crop_o(image_dict["image_path"], image_dict["point_x"], image_dict["point_y"], 256, 256)
patch = tf.keras.preprocessing.image.img_to_array(patch)
patch = self.preprocess_img(patch)
return patch
'''
def cropping_function(self, image_dict):
# randomly select crop ratio
height_ratio = random.choice([7, 7.5, 8, 8.5, 9])
# randomly jitter crop center
jitter = random.choice([-0.01, -0.02, -0.03, -0.04, -0.05, 0.05, 0.04, 0.03, 0.02, 0.01])
point_x = image_dict["point_x"] + jitter
point_y = image_dict["point_y"] + jitter
#patch = utils.load_image_and_crop_o(image_dict["image_path"], image_dict["point_x"], image_dict["point_y"], 256, 256)
patch = utils.load_image_and_crop_ratio(image_dict["image_path"], point_x, point_y, 256, 256, height_ratio)
patch = tf.keras.preprocessing.image.img_to_array(patch)
patch = self.preprocess_img(patch)
return patch
'''
def make_val_generator(self, X_val, y_val, patch_sizes):
val_generator = FullImagePointCroppingLoader(X_val, y_val,
#val_generator = self.the_generator(X_val, y_val,
self.BATCH_SIZE,
self.cropping_function)
return val_generator
def calculate_mean_image(self, X_train):
mean_image = utils.calculate_mean_image_from_crop_file_list(sample(X_train, 100))
im = Image.fromarray(mean_image)
im.save(os.path.join(self.save_path, "mean_image.jpg"))
return np.array(im, dtype=np.float)
def load_mean_image(self, filepath):
mean_image = Image.open(os.path.join(filepath, "mean_image.jpg"))
return mean_image
def preprocess_img(self, img):
img -= self.mean_image
#img = ImFeelingLucky().white_balance_pil_image(keras.preprocessing.image.array_to_img(img))
#img = ImFeelingLucky().white_balance_img_array(img)
# normalise for faster training times
img /= 255.0
return img
| 41.701794 | 158 | 0.598849 | 2,451 | 18,599 | 4.204814 | 0.078743 | 0.026781 | 0.032602 | 0.037842 | 0.853192 | 0.830196 | 0.819814 | 0.812827 | 0.812827 | 0.812827 | 0 | 0.009244 | 0.302005 | 18,599 | 445 | 159 | 41.795506 | 0.784625 | 0.031453 | 0 | 0.792683 | 0 | 0 | 0.028883 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.085366 | false | 0 | 0.054878 | 0 | 0.222561 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
f223cff511caf0ad132777cca2ed31beec3b302f | 27,764 | py | Python | scicast/tkinter_scicast.py | iandriver/scicast | 5c391a20e063fbb4a540e69704208f8309afc484 | [
"MIT"
] | 5 | 2016-11-05T00:01:15.000Z | 2020-11-19T13:54:30.000Z | scicast/tkinter_scicast.py | iandriver/SCICAST | 5c391a20e063fbb4a540e69704208f8309afc484 | [
"MIT"
] | null | null | null | scicast/tkinter_scicast.py | iandriver/SCICAST | 5c391a20e063fbb4a540e69704208f8309afc484 | [
"MIT"
] | 1 | 2017-08-29T02:33:49.000Z | 2017-08-29T02:33:49.000Z |
try:
import tkinter as tk
from tkinter.filedialog import askopenfilename
class Window(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.title("scicast")
self.path = tk.StringVar()
self.cell_path = tk.StringVar()
self.gene_path = tk.StringVar()
self.gene_label_path = tk.StringVar()
self.exclude_gene_path = tk.StringVar()
self.asset = tk.StringVar()
self.gene_number = tk.IntVar(value=200)
self.depth_number = tk.IntVar(value=20)
self.kmeans_cluster_range = tk.StringVar(value='2,4')
self.color_cells = tk.StringVar()
self.color_genes = tk.StringVar()
self.test_clust_stability = tk.IntVar(value=0)
self.genes_corr = tk.StringVar()
self.annotate_gene_subset = tk.StringVar()
#type or choose gene matrix file
dir_label = tk.Label(self, text="Browse or type path to gene cell matrix file:")
path_entry = tk.Entry(self, textvariable=self.path, width=40)
browse_button = tk.Button(self, text="Browse for gene cell matrix file", command=self.browse)
#type or choose cell group file
cell_label = tk.Label(self, text="Browse or type path to cell group file:")
cell_path_entry = tk.Entry(self, textvariable=self.cell_path, width=40)
cell_browse_button = tk.Button(self, text="Browse for cell group file", command=self.browse_cellp)
#type or choose gene group file
gene_label = tk.Label(self, text="Browse or type path to gene group file:")
gene_path_entry = tk.Entry(self, textvariable=self.gene_path, width=40)
gene_browse_button = tk.Button(self, text="Browse for gene group file", command=self.browse_genep)
#type or choose file of genes to exclude from all analysis
exclude_gene_label = tk.Label(self, text="Browse or type path to file with genes to exclude from analysis (i.e cell cycle):")
exclude_gene_path_entry = tk.Entry(self, textvariable=self.exclude_gene_path, width=40)
exclude_gene_browse_button = tk.Button(self, text="Browse for exclude genes file", command=self.browse_excludeg)
#type or choose file of genes which will be labeled in gene PCA plot
annotate_gene_subset_label = tk.Label(self, text="Annotate only these genes in gene PCA:")
annotate_gene_subset_path_entry = tk.Entry(self, textvariable=self.annotate_gene_subset, width=40)
annotate_gene_subset_browse_button = tk.Button(self, text="Browse gene annotation file", command=self.browse_annotateg)
#define file extensions
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt'),('csv files', '.csv'), ('cufflinks counts', '.count_table'), ('cufflinks fpkm', 'fpkm_table'), ('gene matrix', '.matrix')]
#setup metric menu options
self.metric_menu_var = tk.StringVar()
self.metric_menu_var.set("seuclidean")
metric_menu_label = tk.Label(self, text="Choose Metric:")
metric_option_menu = tk.OptionMenu(self, self.metric_menu_var, 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule')
#setup method option menu
self.method_menu_var = tk.StringVar()
self.method_menu_var.set("ward")
method_menu_label = tk.Label(self, text="Choose Method:")
method_option_menu = tk.OptionMenu(self, self.method_menu_var, 'single', 'complete', 'average', 'weighted', 'centroid', 'median')
#setup qgraph option menu
self.qgraph_menu_var = tk.StringVar()
self.qgraph_menu_var.set("none")
qgraph_menu_label = tk.Label(self, text="Choose which qgraph networks to generate:")
qgraph_option_menu = tk.OptionMenu(self, self.qgraph_menu_var, 'gene','cell','both')
#setup image format selection menu
self.image_format_menu_var = tk.StringVar()
self.image_format_menu_var.set("pdf")
image_format_menu_label = tk.Label(self, text="Select image format for output files:")
image_format_option_menu = tk.OptionMenu(self, self.image_format_menu_var, 'tif', 'png', 'jpeg')
#setup z-direction option menu
self.zdir_menu_var = tk.IntVar()
self.zdir_menu_var.set(0)
zdir_menu_label = tk.Label(self, text="Choose z:")
zdir_option_menu = tk.OptionMenu(self, self.zdir_menu_var, 1,'None')
self.flags = ["Don't Run Heatmaps","Don't Run Correlation", "Verbose", "Test Significance by Groups (User Defined)", "Test Significance by Unbiased Clusters", "Exclude Cells Not in User Cell Groups", "Add Ellipse", "Add Cell Names to PCA", "Display Only Unique Signifcant Genes", "Run Significance Test for kmeans clusters", "Input Matrix is already log2", "use t-SNE (for kmeans clustering)"]
self.variables = []
asset_label = tk.Label(self, text="Output File Name:")
asset_entry = tk.Entry(self, textvariable=self.asset, width=40)
gene_number_label = tk.Label(self, text="Number of genes to include")
gene_number_entry = tk.Entry(self, textvariable=self.gene_number, width=10)
kmeans_range_label = tk.Label(self, text="Range of cluster for kmeans (inclusive):")
kmeans_range_entry = tk.Entry(self, textvariable=self.kmeans_cluster_range, width=10)
depth_number_label = tk.Label(self, text="Depth at which subclustering will stop")
depth_number_entry = tk.Entry(self, textvariable=self.depth_number, width=10)
color_cells_label = tk.Label(self, text="Provide specific colors and markers for each cell group.")
color_cells_entry = tk.Entry(self, textvariable=self.color_cells, width=20)
color_genes_label = tk.Label(self, text="Provide specific colors and markers for each gene group.")
color_genes_entry = tk.Entry(self, textvariable=self.color_cells, width=20)
test_clust_stability_label = tk.Label(self, text="Number of iterations to test cluster stability with varying gene numbers.")
test_clust_stability_entry = tk.Entry(self, textvariable=self.test_clust_stability, width=10)
genes_corr_label = tk.Label(self, text="Comma seperated list of genes to add to correlation search.")
genes_corr_entry = tk.Entry(self, textvariable=self.genes_corr, width=20)
create_button = tk.Button(self, text="Run scicast", command=self.genAsset)
dir_label.grid(row=1, column=1, columnspan=2, sticky='w')
path_entry.grid(row=2, column=1, columnspan=2, sticky='w')
browse_button.grid(row=3, column=1, columnspan=2, sticky='w')
cell_label.grid(row=4, column=1, columnspan=2, sticky='w')
cell_path_entry.grid(row=5, column=1, columnspan=2, sticky='w')
cell_browse_button.grid(row=6, column=1, columnspan=2, sticky='w')
gene_label.grid(row=7, column=1, columnspan=2, sticky='w')
gene_path_entry.grid(row=8, column=1, columnspan=2, sticky='w')
gene_browse_button.grid(row=9, column=1, columnspan=2, sticky='w')
exclude_gene_label.grid(row=10, column=1, columnspan=2, sticky='w')
exclude_gene_path_entry.grid(row=11, column=1, columnspan=2, sticky='w')
exclude_gene_browse_button.grid(row=12, column=1, columnspan=2, sticky='w')
annotate_gene_subset_label.grid(row=9, column=4, columnspan=2, sticky='w')
annotate_gene_subset_path_entry.grid(row=10, column=4, columnspan=2, sticky='w')
annotate_gene_subset_browse_button.grid(row=11, column=4, columnspan=2, sticky='w')
gene_number_label.grid(row=13, column=1, columnspan=2, sticky='w')
gene_number_entry.grid(row=14, column=1, columnspan=2, sticky='w')
depth_number_label.grid(row=15, column=1, columnspan=2, sticky='w')
depth_number_entry.grid(row=16, column=1, columnspan=2, sticky='w')
for i, flag in enumerate(self.flags):
var = tk.BooleanVar()
tk.Checkbutton(self, text=flag, variable=var).grid(row=1+i, column=3, columnspan=1, sticky='w')
self.variables.append(var)
metric_menu_label.grid(row=2+len(self.flags), column=3, columnspan=1, sticky='w')
metric_option_menu.grid(row=3+len(self.flags), column=3, columnspan=1, sticky='w')
method_menu_label.grid(row=4+len(self.flags), column=3, columnspan=1, sticky='w')
method_option_menu.grid(row=5+len(self.flags), column=3, columnspan=1, sticky='w')
qgraph_menu_label.grid(row=15, column=4, columnspan=1, sticky='w')
qgraph_option_menu.grid(row=16, column=4, columnspan=1, sticky='w')
image_format_menu_label.grid(row=17, column=4, columnspan=1, sticky='e')
image_format_option_menu.grid(row=18, column=4, columnspan=1, sticky='e')
zdir_menu_label.grid(row=17, column=4, columnspan=1, sticky='w')
zdir_option_menu.grid(row=18, column=4, columnspan=1, sticky='w')
kmeans_range_label.grid(row=12, column=4, columnspan=1, sticky='w')
kmeans_range_entry.grid(row=13, column=4, columnspan=1, sticky='w')
color_cells_label.grid(row=1, column=4, columnspan=1, sticky='w')
color_cells_entry.grid(row=2, column=4, columnspan=1, sticky='w')
color_genes_label.grid(row=3, column=4, columnspan=1, sticky='w')
color_genes_entry.grid(row=4, column=4, columnspan=1, sticky='w')
test_clust_stability_label.grid(row=5, column=4, columnspan=1, sticky='w')
test_clust_stability_entry.grid(row=6, column=4, columnspan=1, sticky='w')
genes_corr_label.grid(row=7, column=4, columnspan=1, sticky='w')
genes_corr_entry.grid(row=8, column=4, columnspan=1, sticky='w')
asset_label.grid(row=17, column=1, columnspan=1, sticky='w')
asset_entry.grid(row=18, column=1, columnspan=1, sticky='w')
create_button.grid(row=24, column=2, columnspan=2)
def browse(self):
file_path= askopenfilename(**self.file_opt)
if file_path:
self.path.set(file_path)
def browse_cellp(self):
file_path= askopenfilename(**self.file_opt)
if file_path:
self.cell_path.set(file_path)
def browse_genep(self):
file_path= askopenfilename(**self.file_opt)
if file_path:
self.gene_path.set(file_path)
def browse_excludeg(self):
file_path= askopenfilename(**self.file_opt)
if file_path:
self.exclude_gene_path.set(file_path)
def browse_annotateg(self):
file_path= askopenfilename(**self.file_opt)
if file_path:
self.annotate_gene_subset.set(file_path)
def genAsset(self):
all_options_dict = {}
asset_path = self.path.get()
asset_name = self.asset.get()
asset_metric_menu_option = self.metric_menu_var.get()
asset_method_menu_option = self.method_menu_var.get()
asset_gene_number = self.gene_number.get()
asset_depth = self.depth_number.get()
asset_cell_path = self.cell_path.get()
asset_gene_path = self.gene_path.get()
asset_zdir = self.zdir_menu_var.get()
asset_qgraph = self.qgraph_menu_var.get()
asset_image_format = self.image_format_menu_var.get()
asset_kmeans_cluster_range = self.kmeans_cluster_range.get()
asset_exclude_gene_path = self.exclude_gene_path.get()
asset_color_cells = self.color_cells.get()
asset_color_genes = self.color_genes.get()
asset_test_clust_stability = self.test_clust_stability.get()
asset_genes_corr = self.genes_corr.get()
asset_annotate_gene_subset = self.annotate_gene_subset.get()
for var, flag in zip(self.variables, self.flags):
all_options_dict[flag] = var.get()
all_options_dict['filepath'] = asset_path
all_options_dict['output_name'] = asset_name
all_options_dict['method'] = asset_method_menu_option
all_options_dict['metric'] =asset_metric_menu_option
all_options_dict['gene_number'] =asset_gene_number
all_options_dict['depth'] = asset_depth
all_options_dict['cell_file'] = asset_cell_path
all_options_dict['gene_file'] = asset_gene_path
all_options_dict['zdir'] = asset_zdir
all_options_dict['qgraph'] = asset_qgraph
all_options_dict['image_format'] = asset_image_format
all_options_dict['kmeans_cluster_range'] = asset_kmeans_cluster_range
all_options_dict['exclude_genes'] = asset_exclude_gene_path
all_options_dict['color_cells'] = asset_color_cells
all_options_dict['color_genes'] = asset_color_genes
all_options_dict['test_clust_stability'] = asset_test_clust_stability
all_options_dict['genes_corr'] = asset_genes_corr
all_options_dict['annotate_gene_subset'] = asset_annotate_gene_subset
self.all_dict = all_options_dict
self.destroy()
except ImportError:
import Tkinter as tk
import tkFileDialog
class Window(tk.Frame):
def __init__(self):
tk.Frame.__init__(self)
#self.title("scicast")
self.path = tk.StringVar()
self.cell_path = tk.StringVar()
self.gene_path = tk.StringVar()
self.gene_label_path = tk.StringVar()
self.exclude_gene_path = tk.StringVar()
self.asset = tk.StringVar()
self.gene_number = tk.IntVar(value=200)
self.depth_number = tk.IntVar(value=20)
self.kmeans_cluster_range = tk.StringVar(value='2,4')
self.color_cells = tk.StringVar()
self.color_genes = tk.StringVar()
self.test_clust_stability = tk.IntVar(value=0)
self.genes_corr = tk.StringVar()
self.annotate_gene_subset = tk.StringVar()
#type or choose gene matrix file
dir_label = tk.Label(self, text="Browse or type path to gene cell matrix file:")
path_entry = tk.Entry(self, textvariable=self.path, width=40)
browse_button = tk.Button(self, text="Browse for gene cell matrix file", command=self.browse)
#type or choose cell group file
cell_label = tk.Label(self, text="Browse or type path to cell group file:")
cell_path_entry = tk.Entry(self, textvariable=self.cell_path, width=40)
cell_browse_button = tk.Button(self, text="Browse for cell group file", command=self.browse_cellp)
#type or choose gene group file
gene_label = tk.Label(self, text="Browse or type path to gene group file:")
gene_path_entry = tk.Entry(self, textvariable=self.gene_path, width=40)
gene_browse_button = tk.Button(self, text="Browse for gene group file", command=self.browse_genep)
#type or choose file of genes to exclude from all analysis
exclude_gene_label = tk.Label(self, text="Browse or type path to file with genes to exclude from analysis (i.e cell cycle):")
exclude_gene_path_entry = tk.Entry(self, textvariable=self.exclude_gene_path, width=40)
exclude_gene_browse_button = tk.Button(self, text="Browse for exclude genes file", command=self.browse_excludeg)
#type or choose file of genes which will be labeled in gene PCA plot
annotate_gene_subset_label = tk.Label(self, text="Annotate only these genes in gene PCA:")
annotate_gene_subset_path_entry = tk.Entry(self, textvariable=self.annotate_gene_subset, width=40)
annotate_gene_subset_browse_button = tk.Button(self, text="Browse gene annotation file", command=self.browse_annotateg)
#define file extensions
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt'),('csv files', '.csv')]
#setup metric menu options
self.metric_menu_var = tk.StringVar()
self.metric_menu_var.set("seuclidean")
metric_menu_label = tk.Label(self, text="Choose Metric:")
metric_option_menu = tk.OptionMenu(self, self.metric_menu_var, 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'yule')
#setup method option menu
self.method_menu_var = tk.StringVar()
self.method_menu_var.set("ward")
method_menu_label = tk.Label(self, text="Choose Method:")
method_option_menu = tk.OptionMenu(self, self.method_menu_var, 'single', 'complete', 'average', 'weighted', 'centroid', 'median')
#setup qgraph option menu
self.qgraph_menu_var = tk.StringVar()
self.qgraph_menu_var.set("none")
qgraph_menu_label = tk.Label(self, text="Choose which qgraph networks to generate:")
qgraph_option_menu = tk.OptionMenu(self, self.qgraph_menu_var, 'gene','cell','both')
#setup image format selection menu
self.image_format_menu_var = tk.StringVar()
self.image_format_menu_var.set("pdf")
image_format_menu_label = tk.Label(self, text="Select image format for output files:")
image_format_option_menu = tk.OptionMenu(self, self.image_format_menu_var, 'tif', 'png', 'jpeg')
#setup z-direction option menu
self.zdir_menu_var = tk.IntVar()
self.zdir_menu_var.set(0)
zdir_menu_label = tk.Label(self, text="Choose z:")
zdir_option_menu = tk.OptionMenu(self, self.zdir_menu_var, 1,'None')
self.flags = ["Don't Run Heatmaps","Don't Run Correlation", "Verbose", "Test Significance by Groups (User Defined)", "Test Significance by Unbiased Clusters", "Exclude Cells Not in User Cell Groups", "Add Ellipse", "Add Cell Names to PCA", "Display Only Unique Signifcant Genes", "Run Significance Test for kmeans clusters", "Input Matrix is already log2", "use t-SNE (for kmeans clustering)"]
self.variables = []
asset_label = tk.Label(self, text="Output File Name:")
asset_entry = tk.Entry(self, textvariable=self.asset, width=40)
gene_number_label = tk.Label(self, text="Number of genes to include")
gene_number_entry = tk.Entry(self, textvariable=self.gene_number, width=10)
kmeans_range_label = tk.Label(self, text="Range of cluster for kmeans (inclusive):")
kmeans_range_entry = tk.Entry(self, textvariable=self.kmeans_cluster_range, width=10)
depth_number_label = tk.Label(self, text="Depth at which subclustering will stop")
depth_number_entry = tk.Entry(self, textvariable=self.depth_number, width=10)
color_cells_label = tk.Label(self, text="Provide specific colors and markers for each cell group.")
color_cells_entry = tk.Entry(self, textvariable=self.color_cells, width=20)
color_genes_label = tk.Label(self, text="Provide specific colors and markers for each gene group.")
color_genes_entry = tk.Entry(self, textvariable=self.color_cells, width=20)
test_clust_stability_label = tk.Label(self, text="Number of iterations to test cluster stability with varying gene numbers.")
test_clust_stability_entry = tk.Entry(self, textvariable=self.test_clust_stability, width=10)
genes_corr_label = tk.Label(self, text="Comma seperated list of genes to add to correlation search.")
genes_corr_entry = tk.Entry(self, textvariable=self.genes_corr, width=20)
create_button = tk.Button(self, text="Run scicast", command=self.genAsset)
dir_label.grid(row=1, column=1, columnspan=2, sticky='w')
path_entry.grid(row=2, column=1, columnspan=2, sticky='w')
browse_button.grid(row=3, column=1, columnspan=2, sticky='w')
cell_label.grid(row=4, column=1, columnspan=2, sticky='w')
cell_path_entry.grid(row=5, column=1, columnspan=2, sticky='w')
cell_browse_button.grid(row=6, column=1, columnspan=2, sticky='w')
gene_label.grid(row=7, column=1, columnspan=2, sticky='w')
gene_path_entry.grid(row=8, column=1, columnspan=2, sticky='w')
gene_browse_button.grid(row=9, column=1, columnspan=2, sticky='w')
exclude_gene_label.grid(row=10, column=1, columnspan=2, sticky='w')
exclude_gene_path_entry.grid(row=11, column=1, columnspan=2, sticky='w')
exclude_gene_browse_button.grid(row=12, column=1, columnspan=2, sticky='w')
annotate_gene_subset_label.grid(row=9, column=4, columnspan=2, sticky='w')
annotate_gene_subset_path_entry.grid(row=10, column=4, columnspan=2, sticky='w')
annotate_gene_subset_browse_button.grid(row=11, column=4, columnspan=2, sticky='w')
gene_number_label.grid(row=13, column=1, columnspan=2, sticky='w')
gene_number_entry.grid(row=14, column=1, columnspan=2, sticky='w')
depth_number_label.grid(row=15, column=1, columnspan=2, sticky='w')
depth_number_entry.grid(row=16, column=1, columnspan=2, sticky='w')
for i, flag in enumerate(self.flags):
var = tk.BooleanVar()
tk.Checkbutton(self, text=flag, variable=var).grid(row=1+i, column=3, columnspan=1, sticky='w')
self.variables.append(var)
metric_menu_label.grid(row=2+len(self.flags), column=3, columnspan=1, sticky='w')
metric_option_menu.grid(row=3+len(self.flags), column=3, columnspan=1, sticky='w')
method_menu_label.grid(row=4+len(self.flags), column=3, columnspan=1, sticky='w')
method_option_menu.grid(row=5+len(self.flags), column=3, columnspan=1, sticky='w')
qgraph_menu_label.grid(row=15, column=4, columnspan=1, sticky='w')
qgraph_option_menu.grid(row=16, column=4, columnspan=1, sticky='w')
image_format_menu_label.grid(row=17, column=5, columnspan=1, sticky='w')
image_format_option_menu.grid(row=18, column=5, columnspan=1, sticky='w')
zdir_menu_label.grid(row=17, column=4, columnspan=1, sticky='w')
zdir_option_menu.grid(row=18, column=4, columnspan=1, sticky='w')
kmeans_range_label.grid(row=12, column=4, columnspan=1, sticky='w')
kmeans_range_entry.grid(row=13, column=4, columnspan=1, sticky='w')
color_cells_label.grid(row=1, column=4, columnspan=1, sticky='w')
color_cells_entry.grid(row=2, column=4, columnspan=1, sticky='w')
color_genes_label.grid(row=3, column=4, columnspan=1, sticky='w')
color_genes_entry.grid(row=4, column=4, columnspan=1, sticky='w')
test_clust_stability_label.grid(row=5, column=4, columnspan=1, sticky='w')
test_clust_stability_entry.grid(row=6, column=4, columnspan=1, sticky='w')
genes_corr_label.grid(row=7, column=4, columnspan=1, sticky='w')
genes_corr_entry.grid(row=8, column=4, columnspan=1, sticky='w')
asset_label.grid(row=17, column=1, columnspan=1, sticky='w')
asset_entry.grid(row=18, column=1, columnspan=1, sticky='w')
create_button.grid(row=24, column=2, columnspan=2)
def browse(self):
file_path= tkFileDialog.askopenfilename(**self.file_opt)
if file_path:
self.path.set(file_path)
def browse_cellp(self):
file_path= tkFileDialog.askopenfilename(**self.file_opt)
if file_path:
self.cell_path.set(file_path)
def browse_genep(self):
file_path= tkFileDialog.askopenfilename(**self.file_opt)
if file_path:
self.gene_path.set(file_path)
def browse_excludeg(self):
file_path= tkFileDialog.askopenfilename(**self.file_opt)
if file_path:
self.exclude_gene_path.set(file_path)
def browse_annotateg(self):
file_path= tkFileDialog.askopenfilename(**self.file_opt)
if file_path:
self.annotate_gene_subset.set(file_path)
def genAsset(self):
all_options_dict = {}
asset_path = self.path.get()
asset_name = self.asset.get()
asset_metric_menu_option = self.metric_menu_var.get()
asset_method_menu_option = self.method_menu_var.get()
asset_gene_number = self.gene_number.get()
asset_depth = self.depth_number.get()
asset_cell_path = self.cell_path.get()
asset_gene_path = self.gene_path.get()
asset_zdir = self.zdir_menu_var.get()
asset_qgraph = self.qgraph_menu_var.get()
asset_image_format = self.image_format_menu_var.get()
asset_kmeans_cluster_range = self.kmeans_cluster_range.get()
asset_exclude_gene_path = self.exclude_gene_path.get()
asset_color_cells = self.color_cells.get()
asset_color_genes = self.color_genes.get()
asset_test_clust_stability = self.test_clust_stability.get()
asset_genes_corr = self.genes_corr.get()
asset_annotate_gene_subset = self.annotate_gene_subset.get()
for var, flag in zip(self.variables, self.flags):
all_options_dict[flag] = var.get()
all_options_dict['filepath'] = asset_path
all_options_dict['output_name'] = asset_name
all_options_dict['method'] = asset_method_menu_option
all_options_dict['metric'] =asset_metric_menu_option
all_options_dict['gene_number'] =asset_gene_number
all_options_dict['depth'] = asset_depth
all_options_dict['cell_file'] = asset_cell_path
all_options_dict['gene_file'] = asset_gene_path
all_options_dict['zdir'] = asset_zdir
all_options_dict['qgraph'] = asset_qgraph
all_options_dict['image_format'] = asset_image_format
all_options_dict['kmeans_cluster_range'] = asset_kmeans_cluster_range
all_options_dict['exclude_genes'] = asset_exclude_gene_path
all_options_dict['color_cells'] = asset_color_cells
all_options_dict['color_genes'] = asset_color_genes
all_options_dict['test_clust_stability'] = asset_test_clust_stability
all_options_dict['genes_corr'] = asset_genes_corr
all_options_dict['annotate_gene_subset'] = asset_annotate_gene_subset
self.all_dict = all_options_dict
self.destroy()
| 55.639279 | 405 | 0.64915 | 3,714 | 27,764 | 4.61524 | 0.063813 | 0.03512 | 0.045622 | 0.046205 | 0.985823 | 0.985823 | 0.98349 | 0.98349 | 0.980748 | 0.980748 | 0 | 0.017572 | 0.237502 | 27,764 | 498 | 406 | 55.751004 | 0.792111 | 0.027554 | 0 | 0.954178 | 0 | 0 | 0.134834 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.037736 | false | 0 | 0.013477 | 0 | 0.056604 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
1efa9930ad57c53afd43a72207806cc4ec17abe3 | 27,302 | py | Python | rlax/_src/distributions_test.py | chris-chris/rlax | 78af9edcc24deb1d518bd64b9df606ba48994b2b | [
"Apache-2.0"
] | null | null | null | rlax/_src/distributions_test.py | chris-chris/rlax | 78af9edcc24deb1d518bd64b9df606ba48994b2b | [
"Apache-2.0"
] | null | null | null | rlax/_src/distributions_test.py | chris-chris/rlax | 78af9edcc24deb1d518bd64b9df606ba48994b2b | [
"Apache-2.0"
] | null | null | null | # Lint as: python3
# Copyright 2019 DeepMind Technologies Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Unit tests for `distributions.py`."""
from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax.tree_util import tree_map
import numpy as np
from rlax._src import distributions
class SoftmaxTest(parameterized.TestCase):
def setUp(self):
super(SoftmaxTest, self).setUp()
self.logits = np.array([[1, 1, 0], [1, 2, 0]], dtype=np.float32)
self.samples = np.array([0, 1], dtype=np.int32)
self.expected_probs = np.array( # softmax with temperature=10
[[0.34425336, 0.34425336, 0.31149334],
[0.332225, 0.3671654, 0.3006096]],
dtype=np.float32)
probs = np.array( # softmax with temperature=1
[[0.42231882, 0.42231882, 0.15536241],
[0.24472848, 0.66524094, 0.09003057]],
dtype=np.float32)
logprobs = np.log(probs)
self.expected_logprobs = np.array(
[logprobs[0][self.samples[0]], logprobs[1][self.samples[1]]])
self.expected_entropy = -np.sum(probs * logprobs, axis=-1)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_softmax_probs(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.softmax(temperature=10.)
# Optionally compile.
softmax = compile_fn(distrib.probs)
# For each element in the batch.
for logits, expected in zip(self.logits, self.expected_probs):
# Optionally convert to device array.
logits = place_fn(logits)
# Test outputs.
actual = softmax(logits)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_softmax_probs_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.softmax(temperature=10.)
# Vmap and optionally compile.
softmax = compile_fn(distrib.probs)
# Optionally convert to device array.
logits = place_fn(self.logits)
# Test softmax output in batch.
actual = softmax(logits)
np.testing.assert_allclose(self.expected_probs, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_softmax_logprob(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.softmax()
# Optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# For each element in the batch.
for logits, samples, expected in zip(
self.logits, self.samples, self.expected_logprobs):
# Optionally convert to device array.
logits, samples = tree_map(place_fn, (logits, samples))
# Test output.
actual = logprob_fn(samples, logits)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_softmax_logprob_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.softmax()
# Vmap and optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# Optionally convert to device array.
logits, samples = tree_map(place_fn, (self.logits, self.samples))
# Test softmax output in batch.
actual = logprob_fn(samples, logits)
np.testing.assert_allclose(self.expected_logprobs, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_softmax_entropy(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.softmax()
# Optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# For each element in the batch.
for logits, expected in zip(self.logits, self.expected_entropy):
# Optionally convert to device array.
logits = place_fn(logits)
# Test outputs.
actual = entropy_fn(logits)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_softmax_entropy_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.softmax()
# Vmap and optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# Optionally convert to device array.
logits = place_fn(self.logits)
# Test softmax output in batch.
actual = entropy_fn(logits)
np.testing.assert_allclose(self.expected_entropy, actual, atol=1e-4)
class GreedyTest(parameterized.TestCase):
def setUp(self):
super(GreedyTest, self).setUp()
self.preferences = np.array([[1, 1, 0], [1, 2, 0]], dtype=np.float32)
self.samples = np.array([0, 1], dtype=np.int32)
self.expected_probs = np.array(
[[0.5, 0.5, 0.], [0., 1., 0.]], dtype=np.float32)
self.expected_logprob = np.array(
[-0.6931472, 0.], dtype=np.float32)
self.expected_entropy = np.array(
[0.6931472, 0.], dtype=np.float32)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_probs(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.greedy()
# Optionally compile.
greedy = compile_fn(distrib.probs)
# For each element in the batch.
for preferences, expected in zip(self.preferences, self.expected_probs):
# Optionally convert to device array.
preferences = place_fn(preferences)
# Test outputs.
actual = greedy(preferences)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_probs_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.greedy()
# Vmap and optionally compile.
greedy = compile_fn(distrib.probs)
# Optionally convert to device array.
preferences = place_fn(self.preferences)
# Test greedy output in batch.
actual = greedy(preferences)
np.testing.assert_allclose(self.expected_probs, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_logprob(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.greedy()
# Optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# For each element in the batch.
for preferences, samples, expected in zip(
self.preferences, self.samples, self.expected_logprob):
# Optionally convert to device array.
preferences, samples = tree_map(place_fn, (preferences, samples))
# Test output.
actual = logprob_fn(samples, preferences)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_logprob_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.greedy()
# Vmap and optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# Optionally convert to device array.
preferences, samples = tree_map(place_fn, (self.preferences, self.samples))
# Test greedy output in batch.
actual = logprob_fn(samples, preferences)
np.testing.assert_allclose(self.expected_logprob, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_entropy(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.greedy()
# Optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# For each element in the batch.
for preferences, expected in zip(self.preferences, self.expected_entropy):
# Optionally convert to device array.
preferences = place_fn(preferences)
# Test outputs.
actual = entropy_fn(preferences)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_entropy_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.greedy()
# Vmap and optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# Optionally convert to device array.
preferences = place_fn(self.preferences)
# Test greedy output in batch.
actual = entropy_fn(preferences)
np.testing.assert_allclose(self.expected_entropy, actual, atol=1e-4)
class EpsilonGreedyTest(parameterized.TestCase):
def setUp(self):
super(EpsilonGreedyTest, self).setUp()
self.epsilon = 0.2
self.preferences = np.array([[1, 1, 0, 0], [1, 2, 0, 0]], dtype=np.float32)
self.samples = np.array([0, 1], dtype=np.int32)
self.expected_probs = np.array(
[[0.45, 0.45, 0.05, 0.05], [0.05, 0.85, 0.05, 0.05]], dtype=np.float32)
self.expected_logprob = np.array(
[-0.7985077, -0.1625189], dtype=np.float32)
self.expected_entropy = np.array(
[1.01823008, 0.58750093], dtype=np.float32)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_probs(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.epsilon_greedy(self.epsilon)
# Optionally compile.
probs_fn = compile_fn(distrib.probs)
# For each element in the batch.
for preferences, expected in zip(self.preferences, self.expected_probs):
# Optionally convert to device array.
preferences = place_fn(preferences)
# Test outputs.
actual = probs_fn(preferences)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_probs_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.epsilon_greedy(self.epsilon)
# Vmap and optionally compile.
probs_fn = compile_fn(distrib.probs)
# Optionally convert to device array.
preferences = place_fn(self.preferences)
# Test greedy output in batch.
actual = probs_fn(preferences)
np.testing.assert_allclose(self.expected_probs, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_logprob(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.epsilon_greedy(self.epsilon)
# Optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# For each element in the batch.
for preferences, samples, expected in zip(
self.preferences, self.samples, self.expected_logprob):
# Optionally convert to device array.
preferences, samples = tree_map(place_fn, (preferences, samples))
# Test output.
actual = logprob_fn(samples, preferences)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_logprob_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.epsilon_greedy(self.epsilon)
# Vmap and optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# Optionally convert to device array.
preferences, samples = tree_map(place_fn, (self.preferences, self.samples))
# Test greedy output in batch.
actual = logprob_fn(samples, preferences)
np.testing.assert_allclose(self.expected_logprob, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_entropy(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.epsilon_greedy(self.epsilon)
# Optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# For each element in the batch.
for preferences, expected in zip(self.preferences, self.expected_entropy):
# Optionally convert to device array.
preferences = place_fn(preferences)
# Test outputs.
actual = entropy_fn(preferences)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_greedy_entropy_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.epsilon_greedy(self.epsilon)
# Vmap and optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# Optionally convert to device array.
preferences = place_fn(self.preferences)
# Test greedy output in batch.
actual = entropy_fn(preferences)
np.testing.assert_allclose(self.expected_entropy, actual, atol=1e-4)
class GaussianDiagonalTest(parameterized.TestCase):
def setUp(self):
super(GaussianDiagonalTest, self).setUp()
self.mu = np.array([[1., -1], [0.1, -0.1]], dtype=np.float32)
self.sigma = np.array([[0.1, 0.1], [0.2, 0.3]], dtype=np.float32)
self.sample = np.array([[1.2, -1.1], [-0.1, 0.]], dtype=np.float32)
# Expected values for the distribution's function were computed using
# tfd.MultivariateNormalDiag (from the tensorflow_probability package).
self.expected_prob_a = np.array(
[1.3064219, 1.5219283], dtype=np.float32)
self.expected_logprob_a = np.array(
[0.26729202, 0.41997814], dtype=np.float32)
self.expected_entropy = np.array(
[-1.7672932, 0.02446628], dtype=np.float32)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_gaussian_prob(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.gaussian_diagonal()
# Optionally compile.
prob_fn = compile_fn(distrib.prob)
# For each element in the batch.
for mu, sigma, sample, expected in zip(
self.mu, self.sigma, self.sample, self.expected_prob_a):
# Optionally convert to device array.
mu, sigma, sample = tree_map(place_fn, (mu, sigma, sample))
# Test outputs.
actual = prob_fn(sample, mu, sigma)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_gaussian_prob_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.gaussian_diagonal()
# Vmap and optionally compile.
prob_fn = compile_fn(distrib.prob)
# Optionally convert to device array.
mu, sigma, sample = tree_map(place_fn, (self.mu, self.sigma, self.sample))
# Test greedy output in batch.
actual = prob_fn(sample, mu, sigma)
np.testing.assert_allclose(self.expected_prob_a, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_gaussian_logprob(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.gaussian_diagonal()
# Optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# For each element in the batch.
for mu, sigma, sample, expected in zip(
self.mu, self.sigma, self.sample, self.expected_logprob_a):
# Optionally convert to device array.
mu, sigma, sample = tree_map(place_fn, (mu, sigma, sample))
# Test output.
actual = logprob_fn(sample, mu, sigma)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_gaussian_logprob_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.gaussian_diagonal()
# Vmap and optionally compile.
logprob_fn = compile_fn(distrib.logprob)
# Optionally convert to device array.
mu, sigma, sample = tree_map(place_fn, (self.mu, self.sigma, self.sample))
# Test greedy output in batch.
actual = logprob_fn(sample, mu, sigma)
np.testing.assert_allclose(self.expected_logprob_a, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_gaussian_entropy(self, compile_fn, place_fn):
"""Tests for a single element."""
distrib = distributions.gaussian_diagonal()
# Optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# For each element in the batch.
for mu, sigma, sample, expected in zip(
self.mu, self.sigma, self.sample, self.expected_entropy):
# Optionally convert to device array.
mu, sigma, sample = tree_map(place_fn, (mu, sigma, sample))
# Test outputs.
actual = entropy_fn(mu, sigma)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_gaussian_entropy_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
distrib = distributions.gaussian_diagonal()
# Vmap and optionally compile.
entropy_fn = compile_fn(distrib.entropy)
# Optionally convert to device array.
mu, sigma = tree_map(place_fn, (self.mu, self.sigma))
# Test greedy output in batch.
actual = entropy_fn(mu, sigma)
np.testing.assert_allclose(self.expected_entropy, actual, atol=1e-4)
class ImportanceSamplingTest(parameterized.TestCase):
def setUp(self):
super(ImportanceSamplingTest, self).setUp()
self.pi_logits = np.array([[0.2, 0.8], [0.6, 0.4]], dtype=np.float32)
self.mu_logits = np.array([[0.8, 0.2], [0.6, 0.4]], dtype=np.float32)
self.actions = np.array([1, 0], dtype=np.int32)
pi = jax.nn.softmax(self.pi_logits)
mu = jax.nn.softmax(self.mu_logits)
self.expected_rhos = np.array(
[pi[0][1] / mu[0][1], pi[1][0] / mu[1][0]], dtype=np.float32)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_importance_sampling_ratios(self, compile_fn, place_fn):
"""Tests for a single element."""
# Optionally compile.
ratios_fn = compile_fn(distributions.categorical_importance_sampling_ratios)
# For each element in the batch.
for pi_logits, mu_logits, actions, expected in zip(
self.pi_logits, self.mu_logits, self.actions, self.expected_rhos):
# Optionally convert to device array.
pi_logits, mu_logits, actions = tree_map(
place_fn, (pi_logits, mu_logits, actions))
# Test outputs.
actual = ratios_fn(pi_logits, mu_logits, actions)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_importance_sampling_ratios_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
# Vmap and optionally compile.
ratios_fn = compile_fn(
jax.vmap(distributions.categorical_importance_sampling_ratios))
# Optionally convert to device array.
pi_logits, mu_logits, actions = tree_map(
place_fn, (self.pi_logits, self.mu_logits, self.actions))
# Test softmax output in batch.
actual = ratios_fn(pi_logits, mu_logits, actions)
np.testing.assert_allclose(self.expected_rhos, actual, atol=1e-4)
class CategoricalKLTest(parameterized.TestCase):
def setUp(self):
super(CategoricalKLTest, self).setUp()
self.p_logits = np.array([[1, 1, 0], [1, 2, 0]], dtype=np.float32)
p_probs = np.array([[0.42231882, 0.42231882, 0.15536241],
[0.24472848, 0.66524094, 0.09003057]],
dtype=np.float32)
p_logprobs = np.log(p_probs)
self.q_logits = np.array([[1, 2, 0], [1, 1, 0]], dtype=np.float32)
q_probs = np.array([[0.24472848, 0.66524094, 0.09003057],
[0.42231882, 0.42231882, 0.15536241]],
dtype=np.float32)
q_logprobs = np.log(q_probs)
self.expected_kl = np.sum(p_probs * (p_logprobs - q_logprobs), axis=-1)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_categorical_kl_divergence(self, compile_fn, place_fn):
"""Tests for a single element."""
# Optionally compile.
kl_fn = compile_fn(distributions.categorical_kl_divergence)
# For each element in the batch.
for p_logits, q_logits, expected in zip(
self.p_logits, self.q_logits, self.expected_kl):
# Optionally convert to device array.
p_logits, q_logits = tree_map(place_fn, (p_logits, q_logits))
# Test outputs.
actual = kl_fn(p_logits, q_logits)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_categorical_kl_divergence_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
# Vmap and optionally compile.
kl_fn = compile_fn(jax.vmap(distributions.categorical_kl_divergence))
# Optionally convert to device array.
p_logits, q_logits = tree_map(place_fn, (self.p_logits, self.q_logits))
# Test softmax output in batch.
actual = kl_fn(p_logits, q_logits)
np.testing.assert_allclose(self.expected_kl, actual, atol=1e-4)
class CategoricalCrossEntropyTest(parameterized.TestCase):
def setUp(self):
super(CategoricalCrossEntropyTest, self).setUp()
self.labels = np.array([[0., 1., 0.], [1., 0., 0.]], dtype=np.float32)
self.logits = np.array([[10., 1., -2.], [1., 4., 0.2]], dtype=np.float32)
self.expected = np.array([9.00013, 3.0696733], dtype=np.float32)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_categorical_cross_entropy(self, compile_fn, place_fn):
"""Tests for a single element."""
# Optionally compile.
cross_entropy = compile_fn(distributions.categorical_cross_entropy)
# Test outputs.
for labels, logits, expected in zip(
self.labels, self.logits, self.expected):
# Optionally convert to device array.
labels, logits = tree_map(place_fn, (labels, logits))
# Test outputs.
actual = cross_entropy(labels=labels, logits=logits)
np.testing.assert_allclose(expected, actual, atol=1e-4)
@parameterized.named_parameters(
('JitOnp', jax.jit, lambda t: t),
('NoJitOnp', lambda fn: fn, lambda t: t),
('JitJnp', jax.jit, jax.device_put),
('NoJitJnp', lambda fn: fn, jax.device_put))
def test_categorical_cross_entropy_batch(self, compile_fn, place_fn):
"""Tests for a full batch."""
# Vmap and optionally compile.
cross_entropy = jax.vmap(distributions.categorical_cross_entropy)
cross_entropy = compile_fn(cross_entropy)
# Optionally convert to device array.
labels, logits = tree_map(place_fn, (self.labels, self.logits))
# Test outputs.
actual = cross_entropy(labels, logits)
np.testing.assert_allclose(self.expected, actual, atol=1e-4)
if __name__ == '__main__':
absltest.main()
| 41.179487 | 80 | 0.671672 | 3,682 | 27,302 | 4.837588 | 0.05975 | 0.020211 | 0.026948 | 0.057265 | 0.872895 | 0.854985 | 0.818605 | 0.790085 | 0.770773 | 0.753874 | 0 | 0.027604 | 0.19592 | 27,302 | 662 | 81 | 41.241692 | 0.783765 | 0.16801 | 0 | 0.723982 | 0 | 0 | 0.037796 | 0 | 0 | 0 | 0 | 0 | 0.067873 | 1 | 0.08371 | false | 0 | 0.027149 | 0 | 0.126697 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
487085a350421868648945f2f36d102e3aeaf9ed | 5,500 | py | Python | tests/_async/test_zip.py | christopher-henderson/PyStream | 8c76a634448d98591aa68087bf78c6cd4da6a6b7 | [
"MIT"
] | null | null | null | tests/_async/test_zip.py | christopher-henderson/PyStream | 8c76a634448d98591aa68087bf78c6cd4da6a6b7 | [
"MIT"
] | 12 | 2020-10-10T14:28:10.000Z | 2020-10-28T05:42:34.000Z | tests/_async/test_zip.py | christopher-henderson/PyStream | 8c76a634448d98591aa68087bf78c6cd4da6a6b7 | [
"MIT"
] | null | null | null | import unittest
from pstream import AsyncStream
from tests._async.utils import Driver, Method
class Zip(Method):
def __init__(self, args):
super(Zip, self).__init__(AsyncStream.zip, args)
class TestZip(unittest.TestCase):
@Driver(initial=range(5), method=Zip(args=[range(5)]), want=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])
def test__a_a(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(5), method=Zip(args=[range(5)]), want=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])
def test__a_s(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(5), method=Zip(args=[range(5)]), want=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])
def test__s_a(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(5), method=Zip(args=[range(5)]), want=[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)])
def test__s_s(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
###############################
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__a_aa(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__a_as(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__a_sa(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__a_ss(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__s_aa(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__s_as(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__s_sa(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(2), method=Zip(args=[range(3, 5), range(6, 8)]), want=[(0, 3, 6), (1, 4, 7)])
def test2__s_ss(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
###############################
@Driver(initial=range(5), method=Zip(args=[]), want=[(0,), (1,), (2,), (3,), (4,)])
def test3__a_a(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(5), method=Zip(args=[]), want=[(0,), (1,), (2,), (3,), (4,)])
def test3__a_s(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(5), method=Zip(args=[]), want=[(0,), (1,), (2,), (3,), (4,)])
def test3__s_a(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=range(5), method=Zip(args=[]), want=[(0,), (1,), (2,), (3,), (4,)])
def test3__s_s(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
###############################
@Driver(initial=[], method=Zip(args=[range(5)]), want=[])
def test4__a_a(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=[], method=Zip(args=[range(5)]), want=[])
def test4__a_s(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=[], method=Zip(args=[range(5)]), want=[])
def test4__s_a(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
@Driver(initial=[], method=Zip(args=[range(5)]), want=[])
def test4__s_s(self, got=None, want=None, exception=None):
if exception is not None:
raise exception
self.assertEqual(got, want)
if __name__ == '__main__':
unittest.main()
| 38.194444 | 105 | 0.581273 | 800 | 5,500 | 3.9 | 0.06375 | 0.047115 | 0.083333 | 0.096154 | 0.938462 | 0.938462 | 0.938462 | 0.938462 | 0.938462 | 0.938462 | 0 | 0.042493 | 0.229818 | 5,500 | 143 | 106 | 38.461538 | 0.694051 | 0 | 0 | 0.733945 | 0 | 0 | 0.00148 | 0 | 0 | 0 | 0 | 0 | 0.183486 | 1 | 0.192661 | false | 0 | 0.027523 | 0 | 0.238532 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
6f825373dc4bf3693a5612ec072906ff7eed2970 | 46,612 | py | Python | vnftest/tests/unit/common/test_utils.py | onap/vnfsdk-dovetail-integration | 2720441e7c03bdb57aefba16a262f1eef1ce2cbd | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | vnftest/tests/unit/common/test_utils.py | onap/vnfsdk-dovetail-integration | 2720441e7c03bdb57aefba16a262f1eef1ce2cbd | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | vnftest/tests/unit/common/test_utils.py | onap/vnfsdk-dovetail-integration | 2720441e7c03bdb57aefba16a262f1eef1ce2cbd | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | ##############################################################################
# Copyright 2018 EuropeanSoftwareMarketingLtd.
# ===================================================================
# Licensed under the ApacheLicense, Version2.0 (the"License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
#
# software distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and limitations under
# the License
##############################################################################
# vnftest comment: this is a modified copy of
# yardstick/tests/unit/common/test_utils.py
from copy import deepcopy
import errno
import importlib
import ipaddress
from itertools import product, chain
import mock
import os
import six
from six.moves import configparser
import unittest
import vnftest
from vnftest import ssh
from vnftest.common import utils
from vnftest.common import import_utils
from vnftest.common import constants
class IterSubclassesTestCase(unittest.TestCase):
# Disclaimer: this class is a modified copy from
# rally/tests/unit/common/plugin/test_discover.py
# Copyright 2015: Mirantis Inc.
def test_itersubclasses(self):
class A(object):
pass
class B(A):
pass
class C(A):
pass
class D(C):
pass
self.assertEqual([B, C, D], list(utils.findsubclasses(A)))
class ImportModulesFromPackageTestCase(unittest.TestCase):
@mock.patch('vnftest.common.utils.os.walk')
def test_import_modules_from_package_no_mod(self, mock_walk):
vnftest_root = os.path.dirname(os.path.dirname(vnftest.__file__))
mock_walk.return_value = ([
(os.path.join(vnftest_root, 'foo'), ['bar'], ['__init__.py']),
(os.path.join(vnftest_root, 'foo', 'bar'), [], ['baz.txt', 'qux.rst'])
])
import_utils.import_modules_from_package('foo.bar')
@mock.patch('vnftest.common.utils.os.walk')
@mock.patch.object(importlib, 'import_module')
def test_import_modules_from_package(self, mock_import_module, mock_walk):
vnftest_root = os.path.dirname(os.path.dirname(vnftest.__file__))
mock_walk.return_value = ([
(os.path.join(vnftest_root, 'foo', os.pardir, 'bar'), [], ['baz.py'])
])
import_utils.import_modules_from_package('foo.bar')
mock_import_module.assert_called_once_with('bar.baz')
class GetParaFromYaml(unittest.TestCase):
@mock.patch('vnftest.common.utils.os.environ.get')
def test_get_param_para_not_found(self, get_env):
file_path = 'config_sample.yaml'
get_env.return_value = self._get_file_abspath(file_path)
args = 'releng.file'
default = 'hello'
self.assertTrue(constants.get_param(args, default), default)
def _get_file_abspath(self, filename):
curr_path = os.path.dirname(os.path.abspath(__file__))
file_path = os.path.join(curr_path, filename)
return file_path
class CommonUtilTestCase(unittest.TestCase):
def setUp(self):
self.data = {
"benchmark": {
"data": {
"mpstat": {
"cpu0": {
"%sys": "0.00",
"%idle": "99.00"
},
"loadavg": [
"1.09",
"0.29"
]
},
"rtt": "1.03"
}
}
}
def test__dict_key_flatten(self):
line = 'mpstat.loadavg1=0.29,rtt=1.03,mpstat.loadavg0=1.09,' \
'mpstat.cpu0.%idle=99.00,mpstat.cpu0.%sys=0.00'
# need to sort for assert to work
line = ",".join(sorted(line.split(',')))
flattened_data = utils.flatten_dict_key(
self.data['benchmark']['data'])
result = ",".join(
("=".join(item) for item in sorted(flattened_data.items())))
self.assertEqual(result, line)
@mock.patch('vnftest.common.utils.open', create=True)
def test_(self, mock_open):
mock_open.side_effect = IOError
with self.assertRaises(IOError):
utils.find_relative_file('my/path', 'task/path')
self.assertEqual(mock_open.call_count, 2)
@mock.patch('vnftest.common.utils.open', create=True)
def test_open_relative_path(self, mock_open):
mock_open_result = mock_open()
mock_open_call_count = 1 # initial call to get result
self.assertEqual(utils.open_relative_file('foo', 'bar'), mock_open_result)
mock_open_call_count += 1 # one more call expected
self.assertEqual(mock_open.call_count, mock_open_call_count)
self.assertIn('foo', mock_open.call_args_list[-1][0][0])
self.assertNotIn('bar', mock_open.call_args_list[-1][0][0])
def open_effect(*args, **kwargs):
if kwargs.get('name', args[0]) == os.path.join('bar', 'foo'):
return mock_open_result
raise IOError(errno.ENOENT, 'not found')
mock_open.side_effect = open_effect
self.assertEqual(utils.open_relative_file('foo', 'bar'), mock_open_result)
mock_open_call_count += 2 # two more calls expected
self.assertEqual(mock_open.call_count, mock_open_call_count)
self.assertIn('foo', mock_open.call_args_list[-1][0][0])
self.assertIn('bar', mock_open.call_args_list[-1][0][0])
# test an IOError of type ENOENT
mock_open.side_effect = IOError(errno.ENOENT, 'not found')
with self.assertRaises(IOError):
# the second call still raises
utils.open_relative_file('foo', 'bar')
mock_open_call_count += 2 # two more calls expected
self.assertEqual(mock_open.call_count, mock_open_call_count)
self.assertIn('foo', mock_open.call_args_list[-1][0][0])
self.assertIn('bar', mock_open.call_args_list[-1][0][0])
# test an IOError other than ENOENT
mock_open.side_effect = IOError(errno.EBUSY, 'busy')
with self.assertRaises(IOError):
utils.open_relative_file('foo', 'bar')
mock_open_call_count += 1 # one more call expected
self.assertEqual(mock_open.call_count, mock_open_call_count)
class TestMacAddressToHex(unittest.TestCase):
def test_mac_address_to_hex_list(self):
self.assertEqual(utils.mac_address_to_hex_list("ea:3e:e1:9a:99:e8"),
['0xea', '0x3e', '0xe1', '0x9a', '0x99', '0xe8'])
class TranslateToStrTestCase(unittest.TestCase):
def test_translate_to_str_unicode(self):
input_str = u'hello'
output_str = utils.translate_to_str(input_str)
result = 'hello'
self.assertEqual(result, output_str)
def test_translate_to_str_dict_list_unicode(self):
input_str = {
u'hello': {u'hello': [u'world']}
}
output_str = utils.translate_to_str(input_str)
result = {
'hello': {'hello': ['world']}
}
self.assertEqual(result, output_str)
def test_translate_to_str_non_string(self):
input_value = object()
result = utils.translate_to_str(input_value)
self.assertIs(input_value, result)
class TestParseCpuInfo(unittest.TestCase):
def test_single_socket_no_hyperthread(self):
cpuinfo = """\
processor : 2
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel Core Processor (Haswell, no TSX)
stepping : 1
microcode : 0x1
cpu MHz : 2294.684
cache size : 4096 KB
physical id : 0
siblings : 5
core id : 2
cpu cores : 5
apicid : 2
initial apicid : 2
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
bugs :
bogomips : 4589.36
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 3
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel Core Processor (Haswell, no TSX)
stepping : 1
microcode : 0x1
cpu MHz : 2294.684
cache size : 4096 KB
physical id : 0
siblings : 5
core id : 3
cpu cores : 5
apicid : 3
initial apicid : 3
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
bugs :
bogomips : 4589.36
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 4
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel Core Processor (Haswell, no TSX)
stepping : 1
microcode : 0x1
cpu MHz : 2294.684
cache size : 4096 KB
physical id : 0
siblings : 5
core id : 4
cpu cores : 5
apicid : 4
initial apicid : 4
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl eagerfpu pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt arat
bugs :
bogomips : 4589.36
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
"""
socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
assert sorted(socket_map.keys()) == [0]
assert sorted(socket_map[0].keys()) == [2, 3, 4]
def test_single_socket_hyperthread(self):
cpuinfo = """\
processor : 5
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
stepping : 3
microcode : 0x1d
cpu MHz : 3501.708
cache size : 8192 KB
physical id : 0
siblings : 8
core id : 1
cpu cores : 4
apicid : 3
initial apicid : 3
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
bugs :
bogomips : 6987.36
clflush size : 64
cache_alignment : 64
address sizes : 39 bits physical, 48 bits virtual
power management:
processor : 6
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
stepping : 3
microcode : 0x1d
cpu MHz : 3531.829
cache size : 8192 KB
physical id : 0
siblings : 8
core id : 2
cpu cores : 4
apicid : 5
initial apicid : 5
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
bugs :
bogomips : 6987.36
clflush size : 64
cache_alignment : 64
address sizes : 39 bits physical, 48 bits virtual
power management:
processor : 7
vendor_id : GenuineIntel
cpu family : 6
model : 60
model name : Intel(R) Xeon(R) CPU E3-1275 v3 @ 3.50GHz
stepping : 3
microcode : 0x1d
cpu MHz : 3500.213
cache size : 8192 KB
physical id : 0
siblings : 8
core id : 3
cpu cores : 4
apicid : 7
initial apicid : 7
fpu : yes
fpu_exception : yes
cpuid level : 13
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts
bugs :
bogomips : 6987.24
clflush size : 64
cache_alignment : 64
address sizes : 39 bits physical, 48 bits virtual
power management:
"""
socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
assert sorted(socket_map.keys()) == [0]
assert sorted(socket_map[0].keys()) == [1, 2, 3]
assert sorted(socket_map[0][1]) == [5]
assert sorted(socket_map[0][2]) == [6]
assert sorted(socket_map[0][3]) == [7]
def test_dual_socket_hyperthread(self):
cpuinfo = """\
processor : 1
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.976
cache size : 56320 KB
physical id : 0
siblings : 44
core id : 1
cpu cores : 22
apicid : 2
initial apicid : 2
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4401.07
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 2
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1226.892
cache size : 56320 KB
physical id : 0
siblings : 44
core id : 2
cpu cores : 22
apicid : 4
initial apicid : 4
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4400.84
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 43
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.305
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 28
cpu cores : 22
apicid : 120
initial apicid : 120
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4411.31
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 44
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.305
cache size : 56320 KB
physical id : 0
siblings : 44
core id : 0
cpu cores : 22
apicid : 1
initial apicid : 1
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4410.61
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 85
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.573
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 26
cpu cores : 22
apicid : 117
initial apicid : 117
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4409.07
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 86
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.305
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 27
cpu cores : 22
apicid : 119
initial apicid : 119
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4406.62
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 87
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.708
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 28
cpu cores : 22
apicid : 121
initial apicid : 121
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4413.48
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
"""
socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
assert sorted(socket_map.keys()) == [0, 1]
assert sorted(socket_map[0].keys()) == [0, 1, 2]
assert sorted(socket_map[1].keys()) == [26, 27, 28]
assert sorted(socket_map[0][0]) == [44]
assert sorted(socket_map[0][1]) == [1]
assert sorted(socket_map[0][2]) == [2]
assert sorted(socket_map[1][26]) == [85]
assert sorted(socket_map[1][27]) == [86]
assert sorted(socket_map[1][28]) == [43, 87]
def test_dual_socket_no_hyperthread(self):
cpuinfo = """\
processor : 1
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.976
cache size : 56320 KB
physical id : 0
siblings : 44
core id : 1
cpu cores : 22
apicid : 2
initial apicid : 2
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4401.07
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 2
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1226.892
cache size : 56320 KB
physical id : 0
siblings : 44
core id : 2
cpu cores : 22
apicid : 4
initial apicid : 4
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4400.84
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 43
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.305
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 28
cpu cores : 22
apicid : 120
initial apicid : 120
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4411.31
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 44
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.305
cache size : 56320 KB
physical id : 0
siblings : 44
core id : 0
cpu cores : 22
apicid : 1
initial apicid : 1
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4410.61
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 85
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.573
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 26
cpu cores : 22
apicid : 117
initial apicid : 117
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4409.07
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 86
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.305
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 27
cpu cores : 22
apicid : 119
initial apicid : 119
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4406.62
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
processor : 87
vendor_id : GenuineIntel
cpu family : 6
model : 79
model name : Intel(R) Xeon(R) CPU E5-2699 v4 @ 2.20GHz
stepping : 1
microcode : 0xb00001f
cpu MHz : 1200.708
cache size : 56320 KB
physical id : 1
siblings : 44
core id : 28
cpu cores : 22
apicid : 121
initial apicid : 121
fpu : yes
fpu_exception : yes
cpuid level : 20
wp : yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts
bugs :
bogomips : 4413.48
clflush size : 64
cache_alignment : 64
address sizes : 46 bits physical, 48 bits virtual
power management:
"""
socket_map = utils.SocketTopology.parse_cpuinfo(cpuinfo)
processors = socket_map.processors()
assert processors == [1, 2, 43, 44, 85, 86, 87]
cores = socket_map.cores()
assert cores == [0, 1, 2, 26, 27, 28]
sockets = socket_map.sockets()
assert sockets == [0, 1]
class SetDictValueTestCase(unittest.TestCase):
def test_set_dict_value(self):
input_dic = {
'hello': 'world'
}
output_dic = utils.set_dict_value(input_dic, 'welcome.to', 'vnftest')
self.assertEqual(output_dic.get('welcome', {}).get('to'), 'vnftest')
class RemoveFileTestCase(unittest.TestCase):
def test_remove_file(self):
try:
utils.remove_file('notexistfile.txt')
except Exception as e: # pylint: disable=broad-except
# NOTE(ralonsoh): to narrow the scope of this exception.
self.assertTrue(isinstance(e, OSError))
class TestUtils(unittest.TestCase):
@mock.patch('vnftest.common.utils.os.makedirs')
def test_makedirs(self, *_):
self.assertIsNone(utils.makedirs('a/b/c/d'))
@mock.patch('vnftest.common.utils.os.makedirs')
def test_makedirs_exists(self, mock_os_makedirs):
mock_os_makedirs.side_effect = OSError(errno.EEXIST, 'exists')
self.assertIsNone(utils.makedirs('a/b/c/d'))
@mock.patch('vnftest.common.utils.os.makedirs')
def test_makedirs_busy(self, mock_os_makedirs):
mock_os_makedirs.side_effect = OSError(errno.EBUSY, 'busy')
with self.assertRaises(OSError):
utils.makedirs('a/b/c/d')
@mock.patch('vnftest.common.utils.jsonify')
def test_result_handler(self, mock_jsonify):
mock_jsonify.return_value = 432
self.assertEqual(utils.result_handler('x', 234), 432)
mock_jsonify.assert_called_once_with({'status': 'x', 'result': 234})
@mock.patch('random.randint')
@mock.patch('socket.socket')
def test_get_free_port(self, mock_socket, mock_randint):
mock_randint.return_value = 7777
s = mock_socket('x', 'y')
s.connect_ex.side_effect = iter([0, 1])
result = utils.get_free_port('10.20.30.40')
self.assertEqual(result, 7777)
self.assertEqual(s.connect_ex.call_count, 2)
@mock.patch('subprocess.check_output')
def test_execute_command(self, mock_check_output):
expected = ['hello world', '1234']
mock_check_output.return_value = os.linesep.join(expected)
result = utils.execute_command('my_command arg1 arg2')
self.assertEqual(result, expected)
@mock.patch('subprocess.Popen')
def test_source_env(self, mock_popen):
base_env = deepcopy(os.environ)
mock_process = mock_popen()
output_list = [
'garbage line before',
'NEW_ENV_VALUE=234',
'garbage line after',
]
mock_process.communicate.return_value = os.linesep.join(output_list), '', 0
expected = {'NEW_ENV_VALUE': '234'}
result = utils.source_env('my_file')
self.assertDictEqual(result, expected)
os.environ.clear()
os.environ.update(base_env)
@mock.patch('vnftest.common.utils.configparser.ConfigParser')
def test_parse_ini_file(self, mock_config_parser_type):
defaults = {
'default1': 'value1',
'default2': 'value2',
}
s1 = {
'key1': 'value11',
'key2': 'value22',
}
s2 = {
'key1': 'value123',
'key2': 'value234',
}
mock_config_parser = mock_config_parser_type()
mock_config_parser.read.return_value = True
mock_config_parser.sections.return_value = ['s1', 's2']
mock_config_parser.items.side_effect = iter([
defaults.items(),
s1.items(),
s2.items(),
])
expected = {
'DEFAULT': defaults,
's1': s1,
's2': s2,
}
result = utils.parse_ini_file('my_path')
self.assertDictEqual(result, expected)
@mock.patch('vnftest.common.utils.configparser.ConfigParser')
def test_parse_ini_file_missing_section_header(self, mock_config_parser_type):
mock_config_parser = mock_config_parser_type()
mock_config_parser.read.side_effect = \
configparser.MissingSectionHeaderError(mock.Mock(), 321, mock.Mock())
with self.assertRaises(configparser.MissingSectionHeaderError):
utils.parse_ini_file('my_path')
@mock.patch('vnftest.common.utils.configparser.ConfigParser')
def test_parse_ini_file_no_file(self, mock_config_parser_type):
mock_config_parser = mock_config_parser_type()
mock_config_parser.read.return_value = False
with self.assertRaises(RuntimeError):
utils.parse_ini_file('my_path')
@mock.patch('vnftest.common.utils.configparser.ConfigParser')
def test_parse_ini_file_no_default_section_header(self, mock_config_parser_type):
s1 = {
'key1': 'value11',
'key2': 'value22',
}
s2 = {
'key1': 'value123',
'key2': 'value234',
}
mock_config_parser = mock_config_parser_type()
mock_config_parser.read.return_value = True
mock_config_parser.sections.return_value = ['s1', 's2']
mock_config_parser.items.side_effect = iter([
configparser.NoSectionError(mock.Mock()),
s1.items(),
s2.items(),
])
expected = {
'DEFAULT': {},
's1': s1,
's2': s2,
}
result = utils.parse_ini_file('my_path')
self.assertDictEqual(result, expected)
def test_join_non_strings(self):
self.assertEqual(utils.join_non_strings(':'), '')
self.assertEqual(utils.join_non_strings(':', 'a'), 'a')
self.assertEqual(utils.join_non_strings(':', 'a', 2, 'c'), 'a:2:c')
self.assertEqual(utils.join_non_strings(':', ['a', 2, 'c']), 'a:2:c')
self.assertEqual(utils.join_non_strings(':', 'abc'), 'abc')
def test_validate_non_string_sequence(self):
self.assertEqual(utils.validate_non_string_sequence([1, 2, 3]), [1, 2, 3])
self.assertIsNone(utils.validate_non_string_sequence('123'))
self.assertIsNone(utils.validate_non_string_sequence(1))
self.assertEqual(utils.validate_non_string_sequence(1, 2), 2)
self.assertEqual(utils.validate_non_string_sequence(1, default=2), 2)
with self.assertRaises(RuntimeError):
utils.validate_non_string_sequence(1, raise_exc=RuntimeError)
class TestUtilsIpAddrMethods(unittest.TestCase):
GOOD_IP_V4_ADDRESS_STR_LIST = [
u'0.0.0.0',
u'10.20.30.40',
u'127.0.0.1',
u'10.20.30.40',
u'172.29.50.75',
u'192.168.230.9',
u'255.255.255.255',
]
GOOD_IP_V4_MASK_STR_LIST = [
u'/1',
u'/8',
u'/13',
u'/19',
u'/24',
u'/32',
]
GOOD_IP_V6_ADDRESS_STR_LIST = [
u'::1',
u'fe80::250:56ff:fe89:91ff',
u'123:4567:89ab:cdef:123:4567:89ab:cdef',
]
GOOD_IP_V6_MASK_STR_LIST = [
u'/1',
u'/16',
u'/29',
u'/64',
u'/99',
u'/128',
]
INVALID_IP_ADDRESS_STR_LIST = [
1,
u'w.x.y.z',
u'10.20.30.40/33',
u'123:4567:89ab:cdef:123:4567:89ab:cdef/129',
]
def test_safe_ip_address(self):
addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
for addr in addr_list:
# test with no mask
expected = ipaddress.ip_address(addr)
self.assertEqual(utils.safe_ip_address(addr), expected, addr)
def test_safe_ip_address_v6_ip(self):
addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
for addr in addr_list:
# test with no mask
expected = ipaddress.ip_address(addr)
self.assertEqual(utils.safe_ip_address(addr), expected, addr)
@mock.patch("vnftest.common.utils.logging")
def test_safe_ip_address_negative(self, *args):
# NOTE(ralonsoh): check the calls to mocked functions.
for value in self.INVALID_IP_ADDRESS_STR_LIST:
self.assertIsNone(utils.safe_ip_address(value), value)
addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
mask_list = self.GOOD_IP_V4_MASK_STR_LIST
for addr_mask_pair in product(addr_list, mask_list):
value = ''.join(addr_mask_pair)
self.assertIsNone(utils.safe_ip_address(value), value)
addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
mask_list = self.GOOD_IP_V6_MASK_STR_LIST
for addr_mask_pair in product(addr_list, mask_list):
value = ''.join(addr_mask_pair)
self.assertIsNone(utils.safe_ip_address(value), value)
def test_get_ip_version(self):
addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
for addr in addr_list:
# test with no mask
self.assertEqual(utils.get_ip_version(addr), 4, addr)
def test_get_ip_version_v6_ip(self):
addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
for addr in addr_list:
# test with no mask
self.assertEqual(utils.get_ip_version(addr), 6, addr)
@mock.patch("vnftest.common.utils.logging")
def test_get_ip_version_negative(self, *args):
# NOTE(ralonsoh): check the calls to mocked functions.
for value in self.INVALID_IP_ADDRESS_STR_LIST:
self.assertIsNone(utils.get_ip_version(value), value)
addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
mask_list = self.GOOD_IP_V4_MASK_STR_LIST
for addr_mask_pair in product(addr_list, mask_list):
value = ''.join(addr_mask_pair)
self.assertIsNone(utils.get_ip_version(value), value)
addr_list = self.GOOD_IP_V6_ADDRESS_STR_LIST
mask_list = self.GOOD_IP_V6_MASK_STR_LIST
for addr_mask_pair in product(addr_list, mask_list):
value = ''.join(addr_mask_pair)
self.assertIsNone(utils.get_ip_version(value), value)
def test_ip_to_hex(self):
self.assertEqual(utils.ip_to_hex('0.0.0.0'), '00000000')
self.assertEqual(utils.ip_to_hex('10.20.30.40'), '0a141e28')
self.assertEqual(utils.ip_to_hex('127.0.0.1'), '7f000001')
self.assertEqual(utils.ip_to_hex('172.31.90.100'), 'ac1f5a64')
self.assertEqual(utils.ip_to_hex('192.168.254.253'), 'c0a8fefd')
self.assertEqual(utils.ip_to_hex('255.255.255.255'), 'ffffffff')
def test_ip_to_hex_v6_ip(self):
for value in self.GOOD_IP_V6_ADDRESS_STR_LIST:
self.assertEqual(utils.ip_to_hex(value), value)
@mock.patch("vnftest.common.utils.logging")
def test_ip_to_hex_negative(self, *args):
# NOTE(ralonsoh): check the calls to mocked functions.
addr_list = self.GOOD_IP_V4_ADDRESS_STR_LIST
mask_list = self.GOOD_IP_V4_MASK_STR_LIST
value_iter = (''.join(pair) for pair in product(addr_list, mask_list))
for value in chain(value_iter, self.INVALID_IP_ADDRESS_STR_LIST):
self.assertEqual(utils.ip_to_hex(value), value)
class ReadMeminfoTestCase(unittest.TestCase):
MEMINFO = (b'MemTotal: 65860500 kB\n'
b'MemFree: 28690900 kB\n'
b'MemAvailable: 52873764 kB\n'
b'Active(anon): 3015676 kB\n'
b'HugePages_Total: 8\n'
b'Hugepagesize: 1048576 kB')
MEMINFO_DICT = {'MemTotal': '65860500',
'MemFree': '28690900',
'MemAvailable': '52873764',
'Active(anon)': '3015676',
'HugePages_Total': '8',
'Hugepagesize': '1048576'}
class TestUtils(unittest.TestCase):
def test_convert_xml_to_dict(self):
input_str = "<a><b>dummy1</b><b>dummy2</b></a>"
result = utils.xml_to_dict(input_str)
self.assertEqual(result, {'a': {'b': ['dummy1', 'dummy2']}})
def test_format(self):
input_str = "{aaa}"
params = {'aaa': 'dummy'}
result = utils.format(input_str, params)
self.assertEqual(result, "dummy")
def test_obj_to_dict(self):
dummy_class = DummyClass()
result = utils.normalize_data_struct(dummy_class)
self.assertEqual(result, {'aaa': 'aaa', 'bbb': ["1", "2"], 'ccc': {"x": "y"}})
def test_load_resource(self):
input_str = "vnftest/tests/unit/common/config_sample.yaml"
resource = utils.load_resource(input_str)
assert resource is not None
class DummyClass(object):
def __init__(self):
self.aaa = "aaa"
self.bbb = ["1", "2"]
self.ccc = {"x": "y"}
| 40.70917 | 690 | 0.654746 | 6,730 | 46,612 | 4.359287 | 0.096137 | 0.01026 | 0.016361 | 0.015679 | 0.815188 | 0.787886 | 0.757345 | 0.74487 | 0.738292 | 0.725748 | 0 | 0.063798 | 0.267592 | 46,612 | 1,144 | 691 | 40.744755 | 0.795571 | 0.028834 | 0 | 0.673802 | 0 | 0.021407 | 0.602724 | 0.018435 | 0 | 0 | 0.003794 | 0 | 0.092762 | 1 | 0.04791 | false | 0.004077 | 0.022426 | 0 | 0.097859 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
6fb619940e521a8aedb23387ba9a6f62e8513d46 | 1,490 | py | Python | docs/source/_sdf_tools/__init__.py | amlucas/sdfTools | 804376e233c1069d8d6fbca8d2678dc387147f62 | [
"MIT"
] | 3 | 2019-07-16T13:01:13.000Z | 2021-03-03T15:38:56.000Z | docs/source/_sdf_tools/__init__.py | amlucas/sdfTools | 804376e233c1069d8d6fbca8d2678dc387147f62 | [
"MIT"
] | 10 | 2019-07-12T08:29:21.000Z | 2019-07-16T12:05:27.000Z | docs/source/_sdf_tools/__init__.py | amlucas/sdfTools | 804376e233c1069d8d6fbca8d2678dc387147f62 | [
"MIT"
] | null | null | null | class int3:
r"""None
"""
def __init__():
r"""__init__(*args, **kwargs)
Overloaded function.
1. __init__(self: sdf_tools.int3, x: int, y: int, z: int) -> None
2. __init__(self: sdf_tools.int3, arg0: tuple) -> None
3. __init__(self: sdf_tools.int3, arg0: list) -> None
"""
pass
@property
def x():
r"""
"""
pass
@property
def y():
r"""
"""
pass
@property
def z():
r"""
"""
pass
class real2:
r"""None
"""
def __init__():
r"""__init__(*args, **kwargs)
Overloaded function.
1. __init__(self: sdf_tools.real2, x: float, y: float) -> None
2. __init__(self: sdf_tools.real2, arg0: tuple) -> None
3. __init__(self: sdf_tools.real2, arg0: list) -> None
"""
pass
@property
def x():
r"""
"""
pass
@property
def y():
r"""
"""
pass
class real3:
r"""None
"""
def __init__():
r"""__init__(*args, **kwargs)
Overloaded function.
1. __init__(self: sdf_tools.real3, x: float, y: float, z: float) -> None
2. __init__(self: sdf_tools.real3, arg0: tuple) -> None
3. __init__(self: sdf_tools.real3, arg0: list) -> None
"""
pass
@property
def x():
r"""
"""
pass
@property
def y():
r"""
"""
pass
@property
def z():
r"""
"""
pass
| 15.204082 | 72 | 0.473154 | 170 | 1,490 | 3.741176 | 0.164706 | 0.113208 | 0.15566 | 0.226415 | 0.904088 | 0.882075 | 0.805031 | 0.72327 | 0.581761 | 0.581761 | 0 | 0.028571 | 0.365772 | 1,490 | 97 | 73 | 15.360825 | 0.644444 | 0.491275 | 0 | 0.638298 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0.234043 | true | 0.234043 | 0 | 0 | 0.297872 | 0 | 0 | 0 | 0 | null | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 8 |
82eb8c57c081f3fbbbc8a7553a8395a0ec6ed0f4 | 27,816 | py | Python | Cogs/Comic.py | Damiian1/techwizardshardware | 97ceafc15036be4136e860076d73d74f1887f041 | [
"MIT"
] | null | null | null | Cogs/Comic.py | Damiian1/techwizardshardware | 97ceafc15036be4136e860076d73d74f1887f041 | [
"MIT"
] | null | null | null | Cogs/Comic.py | Damiian1/techwizardshardware | 97ceafc15036be4136e860076d73d74f1887f041 | [
"MIT"
] | null | null | null | import asyncio
import discord
import random
import time
import datetime as dt
from discord.ext import commands
from Cogs import Settings
from Cogs import GetImage
from Cogs import ComicHelper
from Cogs import DL
from Cogs import Message
def setup(bot):
# Add the bot and deps
settings = bot.get_cog("Settings")
bot.add_cog(Comic(bot, settings))
# This module will probably get comics... *finges crossed*
class Comic:
# Init with the bot reference, and a reference to the settings var
def __init__(self, bot, settings):
self.bot = bot
self.settings = settings
def getRandDateBetween(self, first, last):
# Takes two date strings "MM-DD-YYYY" and
# returns a dict of day, month, and year values
# from a random date between them
fDate = first.split("-")
fJDate = ComicHelper.date_to_jd(int(fDate[2]), int(fDate[0]), int(fDate[1]))
lDate = last.split("-")
lJDate = ComicHelper.date_to_jd(int(lDate[2]), int(lDate[0]), int(lDate[1]))
# Get random Julian Date
randJDate = random.uniform(fJDate, lJDate)
# Convert to gregorian
gDate = ComicHelper.jd_to_date(randJDate)
yea = int(gDate[0])
mon = int(gDate[1])
day = int(gDate[2])
# Make sure all months/days are double digits
if (int(mon) < 10):
mon = "0"+str(mon)
if (int(day) < 10):
day = "0"+str(day)
# Build our dict and return it
newDate = { "Year" : str(yea), "Month" : str(mon), "Day" : str(day)}
return newDate
def dateDict(self, date):
# Takes a MM-DD-YYYY string or array
# and converts it to a dict
if type(date) == str:
# Split by "-"
date = date.split("-")
yea = int(date[2])
mon = int(date[0])
day = int(date[1])
# Make sure all months/days are double digits
if (int(mon) < 10):
mon = "0"+str(mon)
if (int(day) < 10):
day = "0"+str(day)
# Build our dict and return it
newDate = { "Year" : str(yea), "Month" : str(mon), "Day" : str(day)}
return newDate
def isDateBetween(self, check, first, last):
# Takes three date strings "MM-DD-YYY" and
# returns whether the first is between the next two
fDate = first.split("-")
fJDate = ComicHelper.date_to_jd(int(fDate[2]), int(fDate[0]), int(fDate[1]))
lDate = last.split("-")
lJDate = ComicHelper.date_to_jd(int(lDate[2]), int(lDate[0]), int(lDate[1]))
cDate = check.split("-")
cJDate = ComicHelper.date_to_jd(int(cDate[2]), int(cDate[0]), int(cDate[1]))
if cJDate <= lJDate and cJDate >= fJDate:
return True
else:
return False
def dateIsValid(self, date : str = None):
# Checks if a passed date is a valid MM-DD-YYYY string
if not date:
# Auto to today's date
date = dt.datetime.today().strftime("%m-%d-%Y")
try:
startDate = date.split("-")
except ValueError:
# Doesn't split by -? Not valid
return False
if len(startDate) < 3:
# Not enough values
return False
for d in startDate:
try:
int(d)
except ValueError:
return False
return True
def canDisplay(self, server):
# Check if we can display images
lastTime = int(self.settings.getServerStat(server, "LastPicture"))
threshold = int(self.settings.getServerStat(server, "PictureThreshold"))
if not GetImage.canDisplay( lastTime, threshold ):
# await channel.send('Too many images at once - please wait a few seconds.')
return False
# If we made it here - set the LastPicture method
self.settings.setServerStat(server, "LastPicture", int(time.time()))
return True
def buildDilbertURL(self, date):
return "http://dilbert.com/strip/" + str(date['Year']) + "-" + str(date['Month']) + "-" + str(date['Day'])
# ####### #
# Dilbert #
# ####### #
@commands.command(pass_context=True)
async def randilbert(self, ctx):
"""Randomly picks and displays a Dilbert comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Get some preliminary values
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "04-16-1989"
# Start a loop to find a comic
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
# Try to get a valid comic
date = self.getRandDateBetween(firstDate, todayDate)
url = self.buildDilbertURL(date)
imageHTML = await ComicHelper.getImageHTML(url)
if imageHTML:
# Got it!
gotComic = True
# Increment try counter
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
# Got a comic link
imageURL = ComicHelper.getImageURL(imageHTML)
imageDisplayName = ComicHelper.getImageTitle(imageHTML)
if imageDisplayName.lower().startswith("dilbert comic for "):
d = imageDisplayName.split(" ")[-1].split("-")
imageDisplayName = "Dilbert Comic for {}-{}-{}".format(d[1], d[2], d[0])
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
@commands.command(pass_context=True)
async def dilbert(self, ctx, *, date : str = None):
"""Displays the Dilbert comic for the passed date (MM-DD-YYYY)."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to today's date
date = dt.datetime.today().strftime("%m-%d-%Y")
if not self.dateIsValid(date):
msg = 'Usage: `{}dilbert "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Can't be after this date
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "04-16-1989"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
# Build our url and check if it's valid
url = self.buildDilbertURL(self.dateDict(date))
imageHTML = await ComicHelper.getImageHTML(url)
if not imageHTML:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
# Got a comic link
imageURL = ComicHelper.getImageURL(imageHTML)
imageDisplayName = ComicHelper.getImageTitle(imageHTML)
if imageDisplayName.lower().startswith("dilbert comic for "):
d = imageDisplayName.split(" ")[-1].split("-")
imageDisplayName = "Dilbert Comic for {}-{}-{}".format(d[1], d[2], d[0])
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
# #### #
# XKCD #
# #### #
@commands.command(pass_context=True)
async def randxkcd(self, ctx):
"""Displays a random XKCD comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Must be a comic number
archiveURL = "http://xkcd.com/archive/"
archiveHTML = await ComicHelper.getImageHTML(archiveURL)
newest = int(ComicHelper.getNewestXKCD(archiveHTML))
# Start a loop to find a comic
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
# Build our url
date = random.randint(1, newest)
comicURL = "http://xkcd.com/" + str(date) + "/"
# now we get the actual comic info
imageHTML = await ComicHelper.getImageHTML(comicURL)
if imageHTML:
gotComic = True
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
# Got a comic link
imageURL = ComicHelper.getXKCDImageURL(imageHTML)
imageDisplayName = ComicHelper.getXKCDImageTitle(imageHTML)
imageText = ComicHelper.getXKCDImageText(imageHTML)
title = '{} *({})*'.format(imageDisplayName, date)
# Download Image
await Message.Embed(title=title, image=imageURL, url=imageURL, description=imageText, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, title)
@commands.command(pass_context=True)
async def xkcd(self, ctx, *, date : str = None):
"""Displays the XKCD comic for the passed date (MM-DD-YYYY) or comic number if found."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to today's date
date = dt.datetime.today().strftime("%m-%d-%Y")
if not self.dateIsValid(date):
# If it's an int - let's see if it fits
try:
date = int(date)
except:
msg = 'Usage: `{}xkcd "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Must be a comic number
archiveURL = "http://xkcd.com/archive/"
archiveHTML = await ComicHelper.getImageHTML(archiveURL)
newest = int(ComicHelper.getNewestXKCD(archiveHTML))
if int(date) > int(newest) or int(date) < 1:
msg = "Comic out of range. Must be between 1 and {}".format(newest)
await channel.send(msg)
return
comicURL = "/" + str(date) + "/"
else:
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "01-01-2006"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
# Get date in a dict (Month, Day, Year)
dateDict = self.dateDict(date)
# Get URL
archiveURL = "http://xkcd.com/archive/"
archiveHTML = await ComicHelper.getImageHTML(archiveURL)
xkcdDate = "{}-{}-{}".format(int(dateDict['Year']), int(dateDict['Month']), int(dateDict['Day']))
comicURL = ComicHelper.getXKCDURL( archiveHTML, xkcdDate )
if not comicURL:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
comicNumber = comicURL.replace('/', '').strip()
comicURL = "http://xkcd.com" + comicURL
# now we get the actual comic info
imageHTML = await ComicHelper.getImageHTML(comicURL)
imageURL = ComicHelper.getXKCDImageURL(imageHTML)
imageText = ComicHelper.getXKCDImageText(imageHTML)
imageDisplayName = ComicHelper.getXKCDImageTitle(imageHTML)
title = '{} *({})*'.format(imageDisplayName, comicNumber)
# Download Image
await Message.Embed(title=title, image=imageURL, url=imageURL, color=ctx.author, description=imageText).send(ctx)
# await GetImage.get(ctx, imageURL, title)
# ################### #
# Cyanide & Happiness #
# ################### #
@commands.command(pass_context=True)
async def randcyanide(self, ctx):
"""Randomly picks and displays a Cyanide & Happiness comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "01-26-2005"
# Get a random Julian date between the first comic and today
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
date = self.getRandDateBetween(firstDate, todayDate)
# Get Arvhive URL
getURL = "http://explosm.net/comics/archive/" + date['Year'] + "/" + date['Month']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
if imageHTML:
imagePage = ComicHelper.getCHURL(imageHTML, date['Year'] + "." + date['Month'] + "." + date['Day'])
if imagePage:
comicHTML = await ComicHelper.getImageHTML(imagePage)
if comicHTML:
imageURL = ComicHelper.getCHImageURL( comicHTML )
if imageURL:
gotComic = True
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
imageDisplayName = "Cyanide & Happiness Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL.strip(), url=imageURL.strip(), color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL.strip(), imageDisplayName)
@commands.command(pass_context=True)
async def cyanide(self, ctx, *, date : str = None):
"""Displays the Cyanide & Happiness comic for the passed date (MM-DD-YYYY) if found."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to today's date
date = dt.datetime.today().strftime("%m-%d-%Y")
if not self.dateIsValid(date):
msg = 'Usage: `{}cyanide "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "01-26-2005"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
dateDict = self.dateDict(date)
# Get Arvhive URL
getURL = "http://explosm.net/comics/archive/" + dateDict['Year'] + "/" + dateDict['Month']
gotComic = False
imageHTML = await ComicHelper.getImageHTML(getURL)
if imageHTML:
imagePage = ComicHelper.getCHURL(imageHTML, dateDict['Year'] + "." + dateDict['Month'] + "." + dateDict['Day'])
if imagePage:
comicHTML = await ComicHelper.getImageHTML(imagePage)
if comicHTML:
imageURL = ComicHelper.getCHImageURL( comicHTML )
if imageURL:
gotComic = True
if not gotComic:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
imageDisplayName = "Cyanide & Happiness Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL.strip(), url=imageURL.strip(), color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL.strip(), imageDisplayName)
# ############### #
# Calvin & Hobbes #
# ############### #
@commands.command(pass_context=True)
async def randcalvin(self, ctx):
"""Randomly picks and displays a Calvin & Hobbes comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Can't be after this date.
todayDate = "12-31-1995"
# Can't be before this date.
firstDate = "11-18-1985"
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
date = self.getRandDateBetween(firstDate, todayDate)
# Get URL
# getURL = "http://marcel-oehler.marcellosendos.ch/comics/ch/" + date['Year'] + "/" + date['Month'] + "/" + date['Year'] + date['Month'] + date['Day'] + ".gif"
getURL = "http://downloads.esbasura.com/comics/Calvin%20and%20Hobbes/" + date["Year"] + "/" + "ch" + date["Year"][2:] + date["Month"] + date["Day"] + ".gif"
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL.strip(), "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")
if imageHTML:
imageURL = getURL
gotComic = True
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
imageDisplayName = "Calvin & Hobbes Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
@commands.command(pass_context=True)
async def calvin(self, ctx, *, date : str = None):
"""Displays the Calvin & Hobbes comic for the passed date (MM-DD-YYYY) if found."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to the last Calvin & Hobbes comic
date = "12-31-1995"
if not self.dateIsValid(date):
msg = 'Usage: `{}calvin "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Can't be after this date.
todayDate = "12-31-1995"
# Can't be before this date.
firstDate = "11-18-1985"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
dateDict = self.dateDict(date)
# Get URL
# getURL = "http://marcel-oehler.marcellosendos.ch/comics/ch/" + dateDict['Year'] + "/" + dateDict['Month'] + "/" + dateDict['Year'] + dateDict['Month'] + dateDict['Day'] + ".gif"
getURL = "http://downloads.esbasura.com/comics/Calvin%20and%20Hobbes/" + dateDict["Year"] + "/" + "ch" + dateDict["Year"][2:] + dateDict["Month"] + dateDict["Day"] + ".gif"
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36")
if not imageHTML:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
imageDisplayName = "Calvin & Hobbes Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=getURL, url=getURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, getURL, imageDisplayName)
# ####################### #
# Garfield Minus Garfield #
# ####################### #
@commands.command(pass_context=True)
async def randgmg(self, ctx):
"""Randomly picks and displays a Garfield Minus Garfield comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "02-13-2008"
# Get a random Julian date between the first comic and today
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
date = self.getRandDateBetween(firstDate, todayDate)
# Get URL
getURL = "http://garfieldminusgarfield.net/day/" + date['Year'] + "/" + date['Month'] + "/" + date['Day']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
if imageHTML:
imageURL = ComicHelper.getGMGImageURL(imageHTML)
if imageURL:
gotComic = True
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
imageDisplayName = "Garfield Minus Garfield Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
@commands.command(pass_context=True)
async def gmg(self, ctx, *, date : str = None):
"""Displays the Garfield Minus Garfield comic for the passed date (MM-DD-YYYY) if found."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to today
date = dt.datetime.today().strftime("%m-%d-%Y")
if not self.dateIsValid(date):
msg = 'Usage: `{}gmg "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "02-13-2008"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
dateDict = self.dateDict(date)
# Get URL
getURL = "http://garfieldminusgarfield.net/day/" + dateDict['Year'] + "/" + dateDict['Month'] + "/" + dateDict['Day']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
# Comment out to test
'''if imageHTML == None:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return'''
imageURL = ComicHelper.getGMGImageURL(imageHTML)
if not imageURL:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
imageDisplayName = "Garfield Minus Garfield Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
# ######## #
# Garfield #
# ######## #
@commands.command(pass_context=True)
async def randgarfield(self, ctx):
"""Randomly picks and displays a Garfield comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "06-19-1978"
# Get a random Julian date between the first comic and today
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
date = self.getRandDateBetween(firstDate, todayDate)
# Get URL
getURL = "https://garfield.com/comic/" + date['Year'] + "/" + date['Month'] + "/" + date['Day']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
if imageHTML:
imageURL = ComicHelper.getGImageURL(imageHTML)
if imageURL:
gotComic = True
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
imageDisplayName = "Garfield Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
@commands.command(pass_context=True)
async def garfield(self, ctx, *, date : str = None):
"""Displays the Garfield comic for the passed date (MM-DD-YYYY) if found."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to today
date = dt.datetime.today().strftime("%m-%d-%Y")
if not self.dateIsValid(date):
msg = 'Usage: `{}garfield "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "06-19-1978"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
dateDict = self.dateDict(date)
# Get URL
getURL = "https://garfield.com/comic/" + dateDict['Year'] + "/" + dateDict['Month'] + "/" + dateDict['Day']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
# Comment out to test
'''if imageHTML == None:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return'''
imageURL = ComicHelper.getGImageURL(imageHTML)
if not imageURL:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
imageDisplayName = "Garfield Comic for " + dateDict['Month'] + "-" + dateDict['Day'] + "-" + dateDict['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
# ####### #
# Peanuts #
# ####### #
@commands.command(pass_context=True)
async def randpeanuts(self, ctx):
"""Randomly picks and displays a Peanuts comic."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "10-02-1950"
# Get a random Julian date between the first comic and today
gotComic = False
tries = 0
while not gotComic:
if tries >= 10:
break
date = self.getRandDateBetween(firstDate, todayDate)
# Get URL
getURL = "http://www.gocomics.com/peanuts/" + date['Year'] + "/" + date['Month'] + "/" + date['Day']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
if imageHTML:
imageURL = ComicHelper.getPeanutsImageURL(imageHTML)
if imageURL:
gotComic = True
tries += 1
if tries >= 10:
msg = 'Failed to find working link.'
await channel.send(msg)
return
imageDisplayName = "Peanuts Comic for " + date['Month'] + "-" + date['Day'] + "-" + date['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
@commands.command(pass_context=True)
async def peanuts(self, ctx, *, date : str = None):
"""Displays the Peanuts comic for the passed date (MM-DD-YYYY) if found."""
channel = ctx.message.channel
author = ctx.message.author
server = ctx.message.guild
if not self.canDisplay(server):
return
if not date:
# Auto to today
date = dt.datetime.today().strftime("%m-%d-%Y")
if not self.dateIsValid(date):
msg = 'Usage: `{}peanuts "[date MM-DD-YYYY]"`'.format(ctx.prefix)
await channel.send(msg)
return
# Can't be after this date.
todayDate = dt.datetime.today().strftime("%m-%d-%Y")
# Can't be before this date.
firstDate = "10-02-1950"
if not self.isDateBetween(date, firstDate, todayDate):
msg = "Date out of range. Must be between {} and {}".format(firstDate, todayDate)
await channel.send(msg)
return
dateDict = self.dateDict(date)
# Get URL
getURL = "http://www.gocomics.com/peanuts/" + dateDict['Year'] + "/" + dateDict['Month'] + "/" + dateDict['Day']
# Retrieve html and info
imageHTML = await ComicHelper.getImageHTML(getURL)
# Comment out to test
'''if imageHTML == None:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return'''
imageURL = ComicHelper.getPeanutsImageURL(imageHTML)
if not imageURL:
msg = 'No comic found for *{}*'.format(date)
await channel.send(msg)
return
imageDisplayName = "Peanuts Comic for " + dateDict['Month'] + "-" + dateDict['Day'] + "-" + dateDict['Year']
# Download Image
await Message.Embed(title=imageDisplayName, image=imageURL, url=imageURL, color=ctx.author).send(ctx)
# await GetImage.get(ctx, imageURL, imageDisplayName)
| 30.838137 | 182 | 0.635713 | 3,467 | 27,816 | 5.091145 | 0.094606 | 0.012464 | 0.029913 | 0.034446 | 0.832927 | 0.802221 | 0.7931 | 0.751572 | 0.728231 | 0.720299 | 0 | 0.01311 | 0.223936 | 27,816 | 901 | 183 | 30.872364 | 0.804558 | 0.148512 | 0 | 0.790291 | 0 | 0.003884 | 0.132682 | 0 | 0.003884 | 0 | 0 | 0 | 0 | 1 | 0.015534 | false | 0.027184 | 0.021359 | 0.001942 | 0.143689 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d24027166d44136ae46b0090d6409c51539585f9 | 4,799 | py | Python | tests/crossbarhttp_tests.py | ydaniels/crossbarhttprequests | 77f19408eb176fd35b80a5b99fdeec1924a61396 | [
"MIT"
] | 1 | 2021-05-16T16:41:52.000Z | 2021-05-16T16:41:52.000Z | tests/crossbarhttp_tests.py | ydaniels/crossbarhttprequests | 77f19408eb176fd35b80a5b99fdeec1924a61396 | [
"MIT"
] | null | null | null | tests/crossbarhttp_tests.py | ydaniels/crossbarhttprequests | 77f19408eb176fd35b80a5b99fdeec1924a61396 | [
"MIT"
] | null | null | null | import unittest
import crossbarhttp
import os
from unittest.mock import patch
class CrossbarHttpTests(unittest.TestCase):
url = None
@classmethod
def setUpClass(cls):
cls.url = os.getenv('ROUTER_URL', "http://localhost:8080")
def test_call(self):
client = crossbarhttp.Client(self.__class__.url + "/call")
result = client.call("test.add", 2, 3, offset=10)
self.assertEqual(result, 15)
def test_publish(self):
client = crossbarhttp.Client(self.__class__.url + "/publish")
publish_id = client.publish("test.publish", 4, 7, event="new event")
self.assertIsNotNone(publish_id)
def test_call_no_callee(self):
client = crossbarhttp.Client(self.__class__.url + "/call")
with self.assertRaises(crossbarhttp.ClientNoCalleeRegistered) as context:
client.call("test.does_not_exist", 2, 3, offset=10)
def test_call_bad_url(self):
client = crossbarhttp.Client(self.__class__.url + "/call_bad_url")
with self.assertRaises(crossbarhttp.ClientBadUrl) as context:
client.call("test.add", 2, 3, offset=10)
def test_publish_bad_url(self):
client = crossbarhttp.Client(self.__class__.url + "/publish_bad_url")
with self.assertRaises(crossbarhttp.ClientBadUrl) as context:
client.publish("test.publish", 4, 7, event="new event")
def test_call_bad_host(self):
client = crossbarhttp.Client("http://bad:8080/call")
with self.assertRaises(crossbarhttp.ClientBadHost) as context:
client.call("test.add", 2, 3, offset=10)
def test_publish_bad_host(self):
client = crossbarhttp.Client("http://bad:8080/publish")
with self.assertRaises(crossbarhttp.ClientBadHost) as context:
client.publish("test.publish", 4, 7, event="new event")
def test_call_missing_signature_params(self):
client = crossbarhttp.Client(self.__class__.url + "/call-signature")
with self.assertRaises(crossbarhttp.ClientMissingParams) as context:
client.call("test.add", 2, 3, offset=10)
def test_call_bad_signature(self):
client = crossbarhttp.Client(self.__class__.url + "/call-signature",
key="key", secret="bad secret")
with self.assertRaises(crossbarhttp.ClientSignatureError) as context:
client.call("test.add", 2, 3, offset=10)
def test_call_signature(self):
client = crossbarhttp.Client(self.__class__.url + "/call-signature",
key="key", secret="secret")
result = client.call("test.add", 2, 3, offset=10)
self.assertEqual(result, 15)
def test_publish_missing_signature_params(self):
client = crossbarhttp.Client(self.__class__.url + "/publish-signature")
with self.assertRaises(crossbarhttp.ClientMissingParams) as context:
client.publish("test.publish", 4, 7, event="new event")
def test_publish_bad_signature(self):
client = crossbarhttp.Client(self.__class__.url + "/publish-signature",
key="key", secret="bad secret")
with self.assertRaises(crossbarhttp.ClientSignatureError) as context:
client.publish("test.publish", 4, 7, event="new event")
def test_publish_signature(self):
client = crossbarhttp.Client(self.__class__.url + "/publish-signature",
key="key", secret="secret")
publish_id = client.publish("test.publish", 4, 7, event="new event")
self.assertIsNotNone(publish_id)
def test_verbose(self):
client = crossbarhttp.Client(self.__class__.url + "/call-signature",
key="key", secret="secret", verbose=True)
result = client.call("test.add", 2, 3, offset=10)
self.assertEqual(result, 15)
@patch('crossbarhttp.Client._make_api_call')
def test_invalid_call_params(self, _make_api_call):
client = crossbarhttp.Client(self.__class__.url + "/call-signature",
key="key", secret="secret")
_make_api_call.return_value = "{}"
result = client.call("test.add", 2, 3, offset=10)
self.assertIsNone(result)
def test_no_call_params(self):
client = crossbarhttp.Client(self.__class__.url + "/call")
with self.assertRaises(crossbarhttp.ClientMissingParams) as context:
client._make_api_call("POST", client.url)
def test_call_exception(self):
client = crossbarhttp.Client(self.__class__.url + "/call")
with self.assertRaises(crossbarhttp.ClientCallRuntimeError) as context:
client.call("test.exception")
if __name__ == '__main__':
unittest.main()
| 39.336066 | 81 | 0.647427 | 550 | 4,799 | 5.401818 | 0.136364 | 0.109054 | 0.137328 | 0.150791 | 0.836419 | 0.81757 | 0.81757 | 0.81757 | 0.734433 | 0.626388 | 0 | 0.017881 | 0.230881 | 4,799 | 121 | 82 | 39.661157 | 0.78705 | 0 | 0 | 0.494253 | 0 | 0 | 0.123567 | 0.007085 | 0 | 0 | 0 | 0 | 0.195402 | 1 | 0.206897 | false | 0 | 0.045977 | 0 | 0.275862 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
d2797e8a8be1d27abee7325a8524b0ff992a3f4e | 3,790 | py | Python | model/detection/ssd_config.py | saiabinesh/EdgeNets | 2b232d3f7fb60658755dad1ebca0ffc895cc795e | [
"MIT"
] | 392 | 2019-06-08T00:34:58.000Z | 2022-03-26T18:46:44.000Z | model/detection/ssd_config.py | saiabinesh/EdgeNets | 2b232d3f7fb60658755dad1ebca0ffc895cc795e | [
"MIT"
] | 37 | 2019-06-23T07:37:36.000Z | 2022-03-02T17:24:30.000Z | model/detection/ssd_config.py | saiabinesh/EdgeNets | 2b232d3f7fb60658755dad1ebca0ffc895cc795e | [
"MIT"
] | 87 | 2019-06-11T16:32:07.000Z | 2022-01-30T14:44:29.000Z | # ============================================
__author__ = "Sachin Mehta"
__maintainer__ = "Sachin Mehta"
# ============================================
'''
This file contains the standard SSD configuration
'''
import numpy as np
import math
class SSD300Configuration(object):
# match default boxes to any ground truth with jaccard overlap higher than a threshold (0.5)
iou_threshold = 0.45
neg_pos_ratio = 3
center_variance = 0.1
size_variance = 0.2
image_size = 300
# PRIOR related settings
strides = [8, 16, 32, 64, 100, 300]
m = len(strides)
feature_maps = []
for stride in strides:
temp = int(math.ceil(image_size/ stride))
feature_maps.append(temp)
#feature_maps = [38, 19, 10, 5, 3, 1]
s_max_size = int(math.ceil(1.05 * image_size))
s_min_size = int(math.ceil(0.1 * image_size))
sizes = [int(k) for k in np.linspace(s_min_size, s_max_size, m+1)]
min_sizes = sizes[:m]
max_sizes = sizes[1:]
#min_sizes = [30, 60, 111, 162, 213, 264]
#max_sizes = [60, 111, 162, 213, 264, 315]
# aspect ratio contains a list of pair (e.g. [2, 2] or [2,3] or single valued list e.g. [2,]
# This has a relationship with # of boxes per location. For example, [2,] means that 4 (=2*2) boxes per location
# [2, 3] means that 6=(2*2) boxes per location
aspect_ratio = [[2, 3]] * m
box_per_location = [] # number of boxes per feature map location
for pair in aspect_ratio:
if len(pair) == 1:
box_per_location.append(pair[0] * pair[0])
else:
box_per_location.append(np.prod(pair))
assert len(feature_maps) == len(strides) == len(min_sizes) == len(max_sizes) == len(aspect_ratio)
clip = True
# test specific options
nms_threshold = 0.45
conf_threshold = 0.01 # change this value during demo
top_k = 200 # MAX detections per class
max_per_image = -1
class SSD512Configuration(object):
# match default boxes to any ground truth with jaccard overlap higher than a threshold (0.5)
iou_threshold = 0.45
neg_pos_ratio = 3
center_variance = 0.1
size_variance = 0.2
image_size = 512
# PRIOR related settings
strides = [8, 16, 32, 64, 128, 512]
m = len(strides)
feature_maps = []
for stride in strides:
temp = int(math.ceil(image_size / stride))
feature_maps.append(temp)
#min_sizes = [36, 77, 154, 230, 307, 461]
#max_sizes = [77, 154, 230, 307, 384, 538]
s_max_size = int(math.ceil(1.05 * image_size))
s_min_size = int(math.ceil(0.1 * image_size))
sizes = [int(k) for k in np.linspace(s_min_size, s_max_size, m + 1)]
min_sizes = sizes[:m]
max_sizes = sizes[1:]
# aspect ratio contains a list of pair (e.g. [2, 2] or [2,3] or single valued list e.g. [2,]
# This has a relationship with # of boxes per location. For example, [2,] means that 4 (=2*2) boxes per location
# [2, 3] means that 6=(2*2) boxes per location
aspect_ratio = [[2, 3]] * m
box_per_location = [] # number of boxes per feature map location
for pair in aspect_ratio:
if len(pair) == 1:
box_per_location.append(pair[0] * pair[0])
else:
box_per_location.append(np.prod(pair))
clip = True
assert len(feature_maps) == len(strides) == len(min_sizes) == len(max_sizes) == len(aspect_ratio)
# test specific options
nms_threshold = 0.45
conf_threshold = 0.01 # change this value during demo
top_k = 200 # MAX detections per class
max_per_image = -1
def get_config(im_size):
if im_size == 300:
return SSD300Configuration()
elif im_size == 512:
return SSD512Configuration()
else:
print('{} image size not supported'.format(im_size))
| 31.848739 | 116 | 0.62058 | 579 | 3,790 | 3.899827 | 0.252159 | 0.058459 | 0.029229 | 0.026572 | 0.817538 | 0.805137 | 0.805137 | 0.805137 | 0.775022 | 0.775022 | 0 | 0.075768 | 0.244327 | 3,790 | 118 | 117 | 32.118644 | 0.71264 | 0.328232 | 0 | 0.774648 | 0 | 0 | 0.02074 | 0 | 0 | 0 | 0 | 0 | 0.028169 | 1 | 0.014085 | false | 0 | 0.028169 | 0 | 0.661972 | 0.014085 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 8 |
96288fe470d32f588730d8ab07c2f92138bae49e | 202,060 | py | Python | poem/Poem/api/tests/test_probes.py | ARGOeu/poem-react-ui | f21ceddf53471fd947d8a296d629782e61489b91 | [
"Apache-2.0"
] | null | null | null | poem/Poem/api/tests/test_probes.py | ARGOeu/poem-react-ui | f21ceddf53471fd947d8a296d629782e61489b91 | [
"Apache-2.0"
] | 139 | 2020-04-06T09:22:16.000Z | 2021-08-02T06:39:22.000Z | poem/Poem/api/tests/test_probes.py | vrdel/poem-2 | 42672fc066b71b4958168d8031e1da0043ac6d1f | [
"Apache-2.0"
] | 3 | 2019-07-10T09:37:38.000Z | 2020-04-02T10:48:38.000Z | import datetime
import json
from Poem.api import views_internal as views
from Poem.poem import models as poem_models
from Poem.poem_super_admin import models as admin_models
from Poem.tenants.models import Tenant
from Poem.users.models import CustUser
from django.contrib.contenttypes.models import ContentType
from django.core import serializers
from django_tenants.test.cases import TenantTestCase
from django_tenants.test.client import TenantRequestFactory
from django_tenants.utils import schema_context, get_public_schema_name, \
get_tenant_domain_model
from rest_framework import status
from rest_framework.test import force_authenticate
from .utils_test import encode_data
class ListProbesAPIViewTests(TenantTestCase):
def setUp(self):
self.factory = TenantRequestFactory(self.tenant)
self.view = views.ListProbes.as_view()
self.url = '/api/v2/internal/probes/'
self.tenant_user = CustUser.objects.create_user(username='testuser')
self.tenant_superuser = CustUser.objects.create_user(
username='poem', is_superuser=True
)
with schema_context(get_public_schema_name()):
self.super_tenant = Tenant.objects.create(
name='public', schema_name=get_public_schema_name()
)
get_tenant_domain_model().objects.create(
domain='public', tenant=self.super_tenant, is_primary=True
)
self.user = CustUser.objects.create_user(username='testuser')
self.superuser = CustUser.objects.create_user(
username='poem', is_superuser=True
)
tag = admin_models.OSTag.objects.create(name='CentOS 6')
repo = admin_models.YumRepo.objects.create(
name='repo-1', tag=tag
)
self.package1 = admin_models.Package.objects.create(
name='nagios-plugins-argo',
version='0.1.7'
)
self.package1.repos.add(repo)
self.package2 = admin_models.Package.objects.create(
name='nagios-plugins-argo',
version='0.1.11'
)
self.package2.repos.add(repo)
self.probe1 = admin_models.Probe.objects.create(
name='ams-probe',
package=self.package1,
description='Probe is inspecting AMS service by trying to publish '
'and consume randomly generated messages.',
comment='Initial version.',
repository='https://github.com/ARGOeu/nagios-plugins-argo',
docurl='https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
user='poem',
datetime=datetime.datetime.now()
)
self.probe2 = admin_models.Probe.objects.create(
name='argo-web-api',
package=self.package1,
description='This is a probe for checking AR and status reports are'
' properly working.',
comment='Initial version.',
repository='https://github.com/ARGOeu/nagios-plugins-argo',
docurl='https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.probe3 = admin_models.Probe.objects.create(
name='ams-publisher-probe',
package=self.package2,
description='Probe is inspecting AMS publisher running on Nagios '
'monitoring instances.',
comment='Initial version.',
repository='https://github.com/ARGOeu/nagios-plugins-argo',
docurl='https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
user='poem',
datetime=datetime.datetime.now()
)
admin_models.ProbeHistory.objects.create(
object_id=self.probe1,
name=self.probe1.name,
package=self.probe1.package,
description=self.probe1.description,
comment=self.probe1.comment,
repository=self.probe1.repository,
docurl=self.probe1.docurl,
version_comment='Initial version.',
version_user=self.superuser.username
)
pv = admin_models.ProbeHistory.objects.create(
object_id=self.probe2,
name=self.probe2.name,
package=self.probe2.package,
description=self.probe2.description,
comment=self.probe2.comment,
repository=self.probe2.repository,
docurl=self.probe2.docurl,
version_comment='Initial version.',
version_user=self.superuser.username
)
self.probe1.package = self.package2
self.probe1.comment = 'Newer version.'
self.probe1.save()
pv2 = admin_models.ProbeHistory.objects.create(
object_id=self.probe1,
name=self.probe1.name,
package=self.probe1.package,
description=self.probe1.description,
comment=self.probe1.comment,
repository=self.probe1.repository,
docurl=self.probe1.docurl,
version_comment='[{"changed": {"fields": ["package", "comment"]}}]',
version_user=self.superuser.username
)
admin_models.ProbeHistory.objects.create(
object_id=self.probe3,
name=self.probe3.name,
package=self.probe3.package,
description=self.probe3.description,
comment=self.probe3.comment,
repository=self.probe3.repository,
docurl=self.probe3.docurl,
version_comment='Initial version.',
version_user=self.superuser.username
)
mtype = admin_models.MetricTemplateType.objects.create(name='Active')
metrictype = poem_models.MetricType.objects.create(name='Active')
metrictag1 = admin_models.MetricTags.objects.create(name='test_tag1')
metrictag2 = admin_models.MetricTags.objects.create(name='test_tag2')
group = poem_models.GroupOfMetrics.objects.create(name='TEST')
ct = ContentType.objects.get_for_model(poem_models.Metric)
mt1 = admin_models.MetricTemplate.objects.create(
name='argo.API-Check',
mtype=mtype,
probekey=pv,
probeexecutable='["web-api"]',
config='["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]',
attribute='["argo.api_TOKEN --token"]',
flags='["OBSESS 1"]'
)
mt1.tags.add(metrictag1, metrictag2)
mt2 = admin_models.MetricTemplate.objects.create(
name='argo.AMS-Check',
mtype=mtype,
probekey=pv2,
probeexecutable='["ams-probe"]',
config='["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]',
attribute='["argo.ams_TOKEN --token"]',
flags='["OBSESS 1"]',
parameter='["--project EGI"]'
)
mt2.tags.add(metrictag1)
metric1 = poem_models.Metric.objects.create(
name='argo.API-Check',
mtype=metrictype,
group=group,
probekey=pv,
probeexecutable='["web-api"]',
config='["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]',
attribute='["argo.api_TOKEN --token"]',
flags='["OBSESS 1"]'
)
metric2 = poem_models.Metric.objects.create(
name='argo.AMS-Check',
group=group,
mtype=metrictype,
probekey=pv2,
probeexecutable='["ams-probe"]',
config='["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]',
attribute='["argo.ams_TOKEN --token"]',
flags='["OBSESS 1"]',
parameter='["--project EGI"]'
)
poem_models.TenantHistory.objects.create(
object_id=metric1.id,
serialized_data=serializers.serialize(
'json', [metric1],
use_natural_foreign_keys=True,
use_natural_primary_keys=True
),
object_repr=metric1.__str__(),
content_type=ct,
date_created=datetime.datetime.now(),
comment='Initial version.',
user=self.tenant_superuser.username
)
poem_models.TenantHistory.objects.create(
object_id=metric2.id,
serialized_data=serializers.serialize(
'json', [metric2],
use_natural_foreign_keys=True,
use_natural_primary_keys=True
),
object_repr=metric2.__str__(),
content_type=ct,
date_created=datetime.datetime.now(),
comment='Initial version.',
user=self.tenant_superuser.username
)
def test_get_list_of_all_probes_sp_superuser(self):
request = self.factory.get(self.url)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(
response.data,
[
{
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 2
},
{
'name': 'ams-publisher-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS publisher running '
'on Nagios monitoring instances.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 1
},
{
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/'
'blob/master/README.md',
'nv': 1
}
]
)
def test_get_list_of_all_probes_sp_user(self):
request = self.factory.get(self.url)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(
response.data,
[
{
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 2
},
{
'name': 'ams-publisher-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS publisher running '
'on Nagios monitoring instances.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 1
},
{
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/'
'blob/master/README.md',
'nv': 1
}
]
)
def test_get_list_of_all_probes_tenant_superuser(self):
request = self.factory.get(self.url)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(
response.data,
[
{
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 2
},
{
'name': 'ams-publisher-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS publisher running '
'on Nagios monitoring instances.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 1
},
{
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/'
'blob/master/README.md',
'nv': 1
}
]
)
def test_get_list_of_all_probes_tenant_user(self):
request = self.factory.get(self.url)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(
response.data,
[
{
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 2
},
{
'name': 'ams-publisher-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS publisher running '
'on Nagios monitoring instances.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'nv': 1
},
{
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/'
'blob/master/README.md',
'nv': 1
}
]
)
def test_get_probe_by_name_sp_superuser(self):
request = self.factory.get(self.url + 'ams-probe')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request, 'ams-probe')
self.assertEqual(
response.data,
{
'id': self.probe1.id,
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'Probe is inspecting AMS service by trying to '
'publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': 'poem',
'datetime': datetime.datetime.strftime(
self.probe1.datetime,
'%Y-%m-%dT%H:%M:%S.%f'
),
}
)
def test_get_probe_by_name_sp_user(self):
request = self.factory.get(self.url + 'ams-probe')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request, 'ams-probe')
self.assertEqual(
response.data,
{
'id': self.probe1.id,
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'Probe is inspecting AMS service by trying to '
'publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': 'poem',
'datetime': datetime.datetime.strftime(
self.probe1.datetime,
'%Y-%m-%dT%H:%M:%S.%f'
),
}
)
def test_get_probe_by_name_tenant_superuser(self):
request = self.factory.get(self.url + 'ams-probe')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request, 'ams-probe')
self.assertEqual(
response.data,
{
'id': self.probe1.id,
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'Probe is inspecting AMS service by trying to '
'publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': 'poem',
'datetime': datetime.datetime.strftime(
self.probe1.datetime,
'%Y-%m-%dT%H:%M:%S.%f'
),
}
)
def test_get_probe_by_name_tenant_user(self):
request = self.factory.get(self.url + 'ams-probe')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request, 'ams-probe')
self.assertEqual(
response.data,
{
'id': self.probe1.id,
'name': 'ams-probe',
'version': '0.1.11',
'package': 'nagios-plugins-argo (0.1.11)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'Probe is inspecting AMS service by trying to '
'publish and consume randomly generated '
'messages.',
'comment': 'Newer version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': 'poem',
'datetime': datetime.datetime.strftime(
self.probe1.datetime,
'%Y-%m-%dT%H:%M:%S.%f'
),
}
)
def test_get_probe_by_name_if_no_datetime_nor_user_sp_superuser(self):
request = self.factory.get(self.url + 'argo-web-api')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request, 'argo-web-api')
self.assertEqual(
response.data,
{
'id': self.probe2.id,
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': '',
'datetime': ''
}
)
def test_get_probe_by_name_if_no_datetime_nor_user_sp_user(self):
request = self.factory.get(self.url + 'argo-web-api')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request, 'argo-web-api')
self.assertEqual(
response.data,
{
'id': self.probe2.id,
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': '',
'datetime': ''
}
)
def test_get_probe_by_name_if_no_datetime_nor_user_tenant_superuser(self):
request = self.factory.get(self.url + 'argo-web-api')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request, 'argo-web-api')
self.assertEqual(
response.data,
{
'id': self.probe2.id,
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': '',
'datetime': ''
}
)
def test_get_probe_by_name_if_no_datetime_nor_user_tenant_user(self):
request = self.factory.get(self.url + 'argo-web-api')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request, 'argo-web-api')
self.assertEqual(
response.data,
{
'id': self.probe2.id,
'name': 'argo-web-api',
'version': '0.1.7',
'package': 'nagios-plugins-argo (0.1.7)',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
'description': 'This is a probe for checking AR and status '
'reports are properly working.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'user': '',
'datetime': ''
}
)
def test_get_probe_permission_denied_in_case_of_no_authorization(self):
request = self.factory.get(self.url + 'ams-probe')
response = self.view(request, 'ams-probe')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_get_probe_empty_dict_in_case_of_nonexisting_probe_sp_spruser(self):
request = self.factory.get(self.url + 'nonexisting_probe')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request, 'nonexisting_probe')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_probe_empty_dict_in_case_of_nonexisting_probe_sp_user(self):
request = self.factory.get(self.url + 'nonexisting_probe')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request, 'nonexisting_probe')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_probe_empty_dict_in_case_of_nonexisting_probe_ten_sprusr(self):
request = self.factory.get(self.url + 'nonexisting_probe')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request, 'nonexisting_probe')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_get_probe_empty_dict_in_case_of_nonexisting_probe_ten_user(self):
request = self.factory.get(self.url + 'nonexisting_probe')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request, 'nonexisting_probe')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
def test_put_probe_with_already_existing_name_sp_superuser(self):
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nagios-plugins-argo (0.1.7)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Probe with this name already exists.'
)
def test_put_probe_with_already_existing_name_sp_user(self):
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nagios-plugins-argo (0.1.7)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_already_existing_name_tenant_superuser(self):
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nagios-plugins-argo (0.1.7)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_already_existing_name_tenant_user(self):
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nagios-plugins-argo (0.1.7)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_nonexisting_package_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting (1.0.0)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.data['detail'], 'Package does not exist.')
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_nonexisting_package_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting (1.0.0)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_nonexisting_package_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting (1.0.0)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_nonexisting_package_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting (1.0.0)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_no_package_version_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Package version should be specified.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_no_package_version_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_no_package_version_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_with_no_package_version_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'id': self.probe1.id,
'name': 'argo-web-api',
'package': 'nonexisting',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service by trying '
'to publish and consume randomly generated '
'messages.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package=probe.package
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
self.assertEqual(version.version_user, 'poem')
def test_put_probe_without_new_version_sp_superuser(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe-new')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/master/'
'README.md',
)
self.assertEqual(
probe.description, 'Probe is inspecting AMS service.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo2'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["comment", "description", "docurl", '
'"name", "package", "repository"]}}]'
)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe-new', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_without_new_version_sp_user(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package=probe.package
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_without_new_version_tenant_superuser(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package=probe.package
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_without_new_version_tenant_user(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package=probe.package
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["package", "comment"]}}]'
)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_no_new_name_metric_history_without_new_version_sp_spusr(
self
):
data = {
'id': self.probe1.id,
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package__version=probe.package.version
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo2',
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["comment", "description", "docurl", '
'"package", "repository"]}}]'
)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_no_new_name_metric_history_without_new_version_sp_user(
self
):
data = {
'id': self.probe1.id,
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo',
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_no_new_name_metric_history_without_new_version_tn_spusr(
self
):
data = {
'id': self.probe1.id,
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo',
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_no_new_name_metric_history_without_new_version_tn_user(
self
):
data = {
'id': self.probe1.id,
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo',
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_without_metrictemplate_update_sp_spusr(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(probe.name, 'web-api')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'New version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is checking AR and status reports.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo2',
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment,
'[{"changed": {"fields": ["comment", "description", "docurl", '
'"name", "package", "repository"]}}]'
)
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(
mt.probekey,
admin_models.ProbeHistory.objects.filter(
object_id=probe
).order_by('-date_created')[1]
)
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(
metric.probekey,
admin_models.ProbeHistory.objects.filter(
object_id=probe
).order_by('-date_created')[1]
)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_without_metrictemplate_update_sp_user(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(probe.name, 'argo-web-api')
self.assertEqual(probe.package, self.package1)
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'This is a probe for checking AR and status reports are properly '
'working.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.version_comment, 'Initial version.')
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_without_metrictemplate_update_tn_sprusr(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(probe.name, 'argo-web-api')
self.assertEqual(probe.package, self.package1)
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'This is a probe for checking AR and status reports are properly '
'working.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.version_comment, 'Initial version.')
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_without_metrictemplate_update_tn_user(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(probe.name, 'argo-web-api')
self.assertEqual(probe.package, self.package1)
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'This is a probe for checking AR and status reports are properly '
'working.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(version.version_comment, 'Initial version.')
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_with_metrictemplate_update_sp_spruser(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': True
}
content, content_type = encode_data(data)
request = self.factory.put(
self.url, content, content_type=content_type
)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
versions = admin_models.ProbeHistory.objects.filter(
object_id=self.probe2
).order_by('-date_created')
self.assertEqual(versions.count(), 2)
self.assertEqual(probe.name, 'web-api')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'New version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is checking AR and status reports.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo2',
)
self.assertEqual(versions[0].name, probe.name)
self.assertEqual(versions[0].package, probe.package)
self.assertEqual(versions[0].comment, probe.comment)
self.assertEqual(versions[0].docurl, probe.docurl)
self.assertEqual(versions[0].description, probe.description)
self.assertEqual(versions[0].repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, versions[0])
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, versions[1])
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_with_metrictemplate_update_sp_user(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': True
}
content, content_type = encode_data(data)
request = self.factory.put(
self.url, content, content_type=content_type
)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
versions = admin_models.ProbeHistory.objects.filter(
object_id=self.probe2
).order_by('-date_created')
self.assertEqual(versions.count(), 1)
self.assertEqual(probe.name, 'argo-web-api')
self.assertEqual(probe.package, self.package1)
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'This is a probe for checking AR and status reports are properly '
'working.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(versions[0].name, probe.name)
self.assertEqual(versions[0].package, probe.package)
self.assertEqual(versions[0].comment, probe.comment)
self.assertEqual(versions[0].docurl, probe.docurl)
self.assertEqual(versions[0].description, probe.description)
self.assertEqual(versions[0].repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, versions[0])
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, versions[0])
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_with_metrictemplate_update_tennt_sprusr(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': True
}
content, content_type = encode_data(data)
request = self.factory.put(
self.url, content, content_type=content_type
)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
versions = admin_models.ProbeHistory.objects.filter(
object_id=self.probe2
).order_by('-date_created')
self.assertEqual(versions.count(), 1)
self.assertEqual(probe.name, 'argo-web-api')
self.assertEqual(probe.package, self.package1)
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'This is a probe for checking AR and status reports are properly '
'working.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(versions[0].name, probe.name)
self.assertEqual(versions[0].package, probe.package)
self.assertEqual(versions[0].comment, probe.comment)
self.assertEqual(versions[0].docurl, probe.docurl)
self.assertEqual(versions[0].description, probe.description)
self.assertEqual(versions[0].repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, versions[0])
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, versions[0])
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_new_version_with_metrictemplate_update_tenant_user(
self
):
data = {
'id': self.probe2.id,
'name': 'web-api',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'New version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is checking AR and status reports.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': True
}
content, content_type = encode_data(data)
request = self.factory.put(
self.url, content, content_type=content_type
)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
versions = admin_models.ProbeHistory.objects.filter(
object_id=self.probe2
).order_by('-date_created')
self.assertEqual(versions.count(), 1)
self.assertEqual(probe.name, 'argo-web-api')
self.assertEqual(probe.package, self.package1)
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'This is a probe for checking AR and status reports are properly '
'working.'
)
self.assertEqual(
probe.repository,
'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(versions[0].name, probe.name)
self.assertEqual(versions[0].package, probe.package)
self.assertEqual(versions[0].comment, probe.comment)
self.assertEqual(versions[0].docurl, probe.docurl)
self.assertEqual(versions[0].description, probe.description)
self.assertEqual(versions[0].repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.API-Check')
self.assertEqual(mt.probekey, versions[0])
metric = poem_models.Metric.objects.get(name='argo.API-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["web-api"]')
self.assertEqual(metric.probekey, versions[0])
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 120", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.api_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.API-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['argo-web-api', '0.1.7']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_with_nonexisting_probe_sp_superuser(self):
data = {
'id': 999,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.data['detail'], 'Probe does not exist.')
def test_put_probe_with_nonexisting_probe_sp_user(self):
data = {
'id': 999,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
def test_put_probe_with_nonexisting_probe_tenant_superuser(self):
data = {
'id': 999,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
def test_put_probe_with_nonexisting_probe_tenant_user(self):
data = {
'id': 999,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'description': 'Probe is inspecting AMS service.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
def test_put_probe_missing_data_key_sp_superuser(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Missing data key: description'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_missing_data_key_sp_user(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_missing_data_key_tenant_superuser(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_put_probe_missing_data_key_tenant_user(self):
data = {
'id': self.probe1.id,
'name': 'ams-probe-new',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Newer version.',
'docurl':
'https://github.com/ARGOeu/nagios-plugins-argo2/blob/'
'master/README.md',
'repository': 'https://github.com/ARGOeu/nagios-plugins-'
'argo2',
'update_metrics': False
}
content, content_type = encode_data(data)
request = self.factory.put(self.url, content, content_type=content_type)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to change probes.'
)
probe = admin_models.Probe.objects.get(id=self.probe1.id)
version = admin_models.ProbeHistory.objects.get(
object_id=probe, package__version=probe.package.version
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 2
)
self.assertEqual(probe.name, 'ams-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.comment, 'Newer version.')
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/master/'
'README.md',
)
self.assertEqual(
probe.description,
'Probe is inspecting AMS service by trying to publish and consume '
'randomly generated messages.'
)
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
mt = admin_models.MetricTemplate.objects.get(name='argo.AMS-Check')
self.assertEqual(mt.probekey, version)
metric = poem_models.Metric.objects.get(name='argo.AMS-Check')
self.assertEqual(metric.group.name, 'TEST')
self.assertEqual(metric.parent, '')
self.assertEqual(metric.probeexecutable, '["ams-probe"]')
self.assertEqual(metric.probekey, version)
self.assertEqual(
metric.config,
'["maxCheckAttempts 3", "timeout 60", '
'"path /usr/libexec/argo-monitoring/probes/argo", '
'"interval 5", "retryInterval 3"]'
)
self.assertEqual(metric.attribute, '["argo.ams_TOKEN --token"]')
self.assertEqual(metric.dependancy, '')
self.assertEqual(metric.flags, '["OBSESS 1"]')
self.assertEqual(metric.files, '')
self.assertEqual(metric.parameter, '["--project EGI"]')
self.assertEqual(metric.fileparameter, '')
mt_history = poem_models.TenantHistory.objects.filter(
object_repr='argo.AMS-Check'
).order_by('-date_created')
self.assertEqual(mt_history.count(), 1)
self.assertEqual(
mt_history[0].comment, 'Initial version.'
)
serialized_data = json.loads(mt_history[0].serialized_data)[0]['fields']
self.assertEqual(serialized_data['name'], metric.name)
self.assertEqual(serialized_data['mtype'], ['Active'])
self.assertEqual(
serialized_data['probekey'], ['ams-probe', '0.1.11']
)
self.assertEqual(serialized_data['group'], ['TEST'])
self.assertEqual(serialized_data['parent'], metric.parent)
self.assertEqual(
serialized_data['probeexecutable'], metric.probeexecutable
)
self.assertEqual(serialized_data['config'], metric.config)
self.assertEqual(serialized_data['attribute'], metric.attribute)
self.assertEqual(serialized_data['dependancy'], metric.dependancy)
self.assertEqual(serialized_data['flags'], metric.flags)
self.assertEqual(serialized_data['files'], metric.files)
self.assertEqual(serialized_data['parameter'], metric.parameter)
self.assertEqual(serialized_data['fileparameter'], metric.fileparameter)
def test_post_probe_sp_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
probe = admin_models.Probe.objects.get(name='poem-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.description, 'Probe inspects POEM service.')
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package__version=probe.package.version
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
def test_post_probe_sp_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_probe_tenant_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_probe_tenant_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_sp_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': self.probe1.id
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
probe = admin_models.Probe.objects.get(name='poem-probe')
self.assertEqual(probe.package, self.package2)
self.assertEqual(probe.description, 'Probe inspects POEM service.')
self.assertEqual(probe.comment, 'Initial version.')
self.assertEqual(
probe.repository, 'https://github.com/ARGOeu/nagios-plugins-argo'
)
self.assertEqual(
probe.docurl,
'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
version = admin_models.ProbeHistory.objects.get(
name=probe.name, package__version=probe.package.version
)
self.assertEqual(version.name, probe.name)
self.assertEqual(version.package, probe.package)
self.assertEqual(version.comment, probe.comment)
self.assertEqual(version.docurl, probe.docurl)
self.assertEqual(version.description, probe.description)
self.assertEqual(version.repository, probe.repository)
self.assertEqual(
version.version_comment, 'Derived from ams-probe (0.1.11).'
)
def test_post_cloned_probe_sp_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': self.probe1.id
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_tenant_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': self.probe1.id
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_tenant_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': self.probe1.id
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_from_nonexisting_probe_sp_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': 999
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(
response.data['detail'], 'Probe from which to clone does not exist.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_from_nonexisting_probe_sp_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': 999
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_from_nonexisting_probe_tenant_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': 999
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_cloned_probe_from_nonexisting_probe_tenant_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': 999
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_probe_with_name_which_already_exists_sp_superuser(self):
data = {
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Probe with this name already exists.'
)
def test_post_probe_with_name_which_already_exists_sp_user(self):
data = {
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
def test_post_probe_with_name_which_already_exists_tenant_superuser(self):
data = {
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
def test_post_probe_with_name_which_already_exists_tenant_user(self):
data = {
'name': 'ams-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
def test_post_probe_with_nonexisting_package_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'name': 'ams-probe',
'package': 'nonexisting (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Package does not exist.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_post_probe_with_nonexisting_package_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'name': 'ams-probe',
'package': 'nonexisting (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_post_probe_with_nonexisting_package_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'name': 'ams-probe',
'package': 'nonexisting (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_post_probe_with_nonexisting_package_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'name': 'ams-probe',
'package': 'nonexisting (0.1.11)',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_post_probe_with_package_without_version_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'name': 'ams-probe',
'package': 'nonexisting',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Package version should be specified.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_post_probe_with_package_without_version_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
data = {
'name': 'ams-probe',
'package': 'nonexisting',
'description': 'Probe inspects POEM service.',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now()
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_post_probe_missing_data_key_sp_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'], 'Missing data key: description'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_probe_missing_data_key_sp_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_probe_missing_data_key_tenant_superuser(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_post_probe_missing_data_key_tenant_user(self):
data = {
'name': 'poem-probe',
'package': 'nagios-plugins-argo (0.1.11)',
'comment': 'Initial version.',
'repository': 'https://github.com/ARGOeu/nagios-plugins-argo',
'docurl': 'https://github.com/ARGOeu/nagios-plugins-argo/blob/'
'master/README.md',
'user': 'testuser',
'datetime': datetime.datetime.now(),
'cloned_from': ''
}
request = self.factory.post(self.url, data, format='json')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'], 'You do not have permission to add probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='poem-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(name='poem-probe').count(),
0
)
def test_delete_probe_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'ams-publisher-probe')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request, 'ams-publisher-probe')
self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT)
self.assertEqual(admin_models.Probe.objects.all().count(), 2)
self.assertRaises(
admin_models.Probe.DoesNotExist,
admin_models.Probe.objects.get,
name='ams-publisher-probe'
)
self.assertEqual(
admin_models.ProbeHistory.objects.filter(
object_id=self.probe3
).count(), 0
)
def test_delete_probe_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'ams-publisher-probe')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request, 'ams-publisher-probe')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(name='ams-publisher-probe')
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(
object_id=self.probe3
).count(), 1
)
def test_delete_probe_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'ams-publisher-probe')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request, 'ams-publisher-probe')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(name='ams-publisher-probe')
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(
object_id=self.probe3
).count(), 1
)
def test_delete_probe_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'ams-publisher-probe')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request, 'ams-publisher-probe')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(name='ams-publisher-probe')
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(
object_id=self.probe3
).count(), 1
)
def test_delete_probe_associated_to_metric_template_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'argo-web-api')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request, 'argo-web-api')
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(
response.data['detail'],
'You cannot delete probe that is associated to metric templates.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
def test_delete_probe_associated_to_metric_template_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'argo-web-api')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request, 'argo-web-api')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
def test_delete_probe_associated_to_metric_template_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'argo-web-api')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request, 'argo-web-api')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
def test_delete_probe_associated_to_metric_template_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'argo-web-api')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request, 'argo-web-api')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
probe = admin_models.Probe.objects.get(id=self.probe2.id)
assert probe
self.assertEqual(
admin_models.ProbeHistory.objects.filter(object_id=probe).count(), 1
)
def test_delete_probe_without_name_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url)
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(response.data['detail'], 'Probe name not specified.')
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_delete_probe_without_name_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url)
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_delete_probe_without_name_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_delete_probe_without_name_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url)
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_trying_to_delete_nonexisting_probe_sp_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'nonexisting')
request.tenant = self.super_tenant
force_authenticate(request, user=self.superuser)
response = self.view(request, 'nonexisting')
self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
self.assertEqual(response.data['detail'], 'Probe does not exist.')
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_trying_to_delete_nonexisting_probe_sp_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'nonexisting')
request.tenant = self.super_tenant
force_authenticate(request, user=self.user)
response = self.view(request, 'nonexisting')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_trying_to_delete_nonexisting_probe_tenant_superuser(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'nonexisting')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_superuser)
response = self.view(request, 'nonexisting')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
def test_trying_to_delete_nonexisting_probe_tenant_user(self):
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
request = self.factory.delete(self.url + 'nonexisting')
request.tenant = self.tenant
force_authenticate(request, user=self.tenant_user)
response = self.view(request, 'nonexisting')
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(
response.data['detail'],
'You do not have permission to delete probes.'
)
self.assertEqual(admin_models.Probe.objects.all().count(), 3)
| 44.982191 | 80 | 0.599936 | 20,666 | 202,060 | 5.750992 | 0.013839 | 0.157762 | 0.054691 | 0.063441 | 0.982785 | 0.982146 | 0.980185 | 0.976163 | 0.972268 | 0.970753 | 0 | 0.009297 | 0.275522 | 202,060 | 4,491 | 81 | 44.992207 | 0.802586 | 0 | 0 | 0.834974 | 0 | 0 | 0.222637 | 0.005523 | 0 | 0 | 0 | 0 | 0.291142 | 1 | 0.021973 | false | 0 | 0.003433 | 0 | 0.025635 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
96398e371549e50af4129a18f961e2d20909290f | 1,273 | py | Python | tests/datetime/test_timezone.py | shammellee/pendulum | bb179c8fb6ef92b7bfc471a46338abbfac9fafca | [
"MIT"
] | 5,049 | 2016-07-04T07:16:34.000Z | 2022-03-31T07:41:48.000Z | tests/datetime/test_timezone.py | shammellee/pendulum | bb179c8fb6ef92b7bfc471a46338abbfac9fafca | [
"MIT"
] | 536 | 2016-07-05T22:46:29.000Z | 2022-03-22T12:41:54.000Z | tests/datetime/test_timezone.py | shammellee/pendulum | bb179c8fb6ef92b7bfc471a46338abbfac9fafca | [
"MIT"
] | 373 | 2016-07-05T19:51:51.000Z | 2022-03-23T16:57:46.000Z | import pendulum
from ..conftest import assert_datetime
def test_in_timezone():
d = pendulum.datetime(2015, 1, 15, 18, 15, 34)
now = pendulum.datetime(2015, 1, 15, 18, 15, 34)
assert d.timezone_name == "UTC"
assert_datetime(d, now.year, now.month, now.day, now.hour, now.minute)
d = d.in_timezone("Europe/Paris")
assert d.timezone_name == "Europe/Paris"
assert_datetime(d, now.year, now.month, now.day, now.hour + 1, now.minute)
def test_in_tz():
d = pendulum.datetime(2015, 1, 15, 18, 15, 34)
now = pendulum.datetime(2015, 1, 15, 18, 15, 34)
assert d.timezone_name == "UTC"
assert_datetime(d, now.year, now.month, now.day, now.hour, now.minute)
d = d.in_tz("Europe/Paris")
assert d.timezone_name == "Europe/Paris"
assert_datetime(d, now.year, now.month, now.day, now.hour + 1, now.minute)
def test_astimezone():
d = pendulum.datetime(2015, 1, 15, 18, 15, 34)
now = pendulum.datetime(2015, 1, 15, 18, 15, 34)
assert d.timezone_name == "UTC"
assert_datetime(d, now.year, now.month, now.day, now.hour, now.minute)
d = d.astimezone(pendulum.timezone("Europe/Paris"))
assert d.timezone_name == "Europe/Paris"
assert_datetime(d, now.year, now.month, now.day, now.hour + 1, now.minute)
| 34.405405 | 78 | 0.665357 | 205 | 1,273 | 4.034146 | 0.136585 | 0.118501 | 0.145103 | 0.152358 | 0.882709 | 0.882709 | 0.882709 | 0.882709 | 0.882709 | 0.882709 | 0 | 0.077586 | 0.17989 | 1,273 | 36 | 79 | 35.361111 | 0.714559 | 0 | 0 | 0.692308 | 0 | 0 | 0.063629 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0.115385 | false | 0 | 0.076923 | 0 | 0.192308 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | null | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.