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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
5409c39f8214bd5f953202a47a6e5813defe49ef
| 9,455
|
py
|
Python
|
src/core_utils/utils.py
|
MoveBigRocks/core-utils
|
c167f80059e87db45564bf5e78f10d7e4ce18f21
|
[
"MIT"
] | null | null | null |
src/core_utils/utils.py
|
MoveBigRocks/core-utils
|
c167f80059e87db45564bf5e78f10d7e4ce18f21
|
[
"MIT"
] | null | null | null |
src/core_utils/utils.py
|
MoveBigRocks/core-utils
|
c167f80059e87db45564bf5e78f10d7e4ce18f21
|
[
"MIT"
] | null | null | null |
__pyarmor__(__name__, __file__, b'\x50\x59\x41\x52\x4d\x4f\x52\x00\x00\x03\x09\x00\x61\x0d\x0d\x0a\x08\x2d\xa0\x01\x00\x00\x00\x00\x01\x00\x00\x00\x40\x00\x00\x00\xf2\x08\x00\x00\x00\x00\x00\x10\x6e\x40\x6f\xd1\x33\x93\xc6\x7c\x83\x17\xad\xc7\x7e\xcf\xcb\xab\x00\x00\x00\x00\x00\x00\x00\x00\xe0\xb9\xa6\x67\x62\xe0\xc9\xf2\x0a\xee\xa7\xfc\xe9\x92\x2e\xb0\x0f\x0f\xb0\x89\xc4\x7f\xda\x33\x51\x22\xdf\x8d\xcf\xd0\x56\x46\xfa\xaf\x33\x0c\xbb\x7b\x35\x12\x3f\x2b\x69\x7b\x2b\x90\x4b\x0c\x3c\x90\xd6\x84\x65\xc0\xc9\xc2\x90\x17\x5a\xd3\x6e\xf2\x5d\xe2\xb8\xf2\xf6\xef\x50\xf5\x01\x49\x74\x3b\x67\xbd\xd9\x31\x42\x83\x7b\x6b\xb9\x5e\xa6\xf3\xf6\x47\xc9\x08\x65\xe2\xaa\x58\x3e\x96\x01\x20\xfa\x95\xd0\x1b\x8e\x33\x04\xcf\xb9\x1d\xf0\xb1\xb7\x04\x65\x96\xa7\x0e\x28\x8f\xcc\x98\xb4\x93\x91\xb8\x3f\xa4\xe6\x6f\x17\xea\x21\xe8\xb7\x93\x67\xda\x4c\xf1\xa0\x79\xcb\x94\x0b\xe7\x0c\xf0\x6b\xec\x81\xd4\x4e\x64\xbd\xef\x0a\x88\xbf\xc3\x28\xc1\xc3\xa4\x03\x69\x44\xf4\x98\xf2\x9a\x61\x95\x63\xe3\x27\x98\x0a\x33\x44\x31\xe2\xb1\xb7\x4f\x8c\x9b\xb5\x65\x6b\x42\x5b\x15\x22\x64\xdc\x5d\x5d\xd5\x21\xc9\x24\xb0\x44\x0f\x97\x7c\x0e\x62\x8c\x8a\x6b\xbe\xdd\x30\x6a\xae\x21\xc7\xea\x44\xed\x56\xd8\x04\xea\xb8\x8f\x1b\x41\xa8\x27\xf0\xc6\xcd\xed\x6b\xda\x1e\xff\x13\xc7\x82\x16\x67\x02\x56\x8b\x49\xe9\x7d\x80\x0b\x60\x48\xd8\x14\xd3\x39\x63\xe5\x06\xeb\xf9\x52\xa1\xf3\xc7\x8b\x56\xbc\xd8\x98\x81\x7b\x88\x30\x74\x7b\xa3\x08\xf4\x6c\x30\xd8\x45\x45\xcb\x3e\x3b\xd5\xb4\x21\x14\x04\xb8\xe6\xf3\xc3\x9e\xbd\x0b\xdf\x01\xa4\xdf\xa2\xfa\xd3\x9c\x29\x60\xc9\x3b\x66\x4c\x49\xd9\x3c\x89\xe6\xe1\xda\xc3\x90\x0e\x0f\x8f\x3c\xee\xa3\x7e\xa1\x24\x80\x19\xff\xad\x3d\x77\xa0\x37\x1c\xda\x98\xbd\xd9\x33\xb9\x1b\xa7\xa2\xf7\x1c\x09\x0b\xae\xb9\x57\xf1\x34\x75\xba\x13\x60\x75\x52\x84\x98\x9d\x63\x56\x96\x3b\xd8\x63\x03\x63\x3e\x8d\x3f\xf6\xad\xa3\x26\xd4\x3b\x88\x1c\x6f\x83\x90\x48\x8f\x49\xbe\xcf\x2b\x09\x3e\xba\x86\xa7\x1c\x1d\xb2\xb4\x1e\x04\x81\x6c\x02\x00\xf7\xdd\x89\x2e\x10\xf4\x72\x6a\x24\x28\xaf\x51\xb2\x4e\xa9\xd1\xb8\xd1\x72\x61\x21\x0e\xe5\x9b\x64\x1b\x9d\xf4\xd6\x7c\x1f\xde\x88\xbd\x58\x04\x38\xe7\xb5\x57\xf9\x7d\x6f\x03\xc6\x47\xd6\xa3\x84\x27\xb9\xb5\x6a\x3d\x0f\x59\xbe\xca\x21\x28\xf9\x62\x7a\xd4\xcd\x7e\x3b\xd4\xac\x7a\xe8\xe9\x29\xe5\xf6\xff\x94\x03\x1b\xbf\x2a\xa0\x1a\x1e\x50\x2a\xfe\xd1\x40\x95\x9c\x21\x35\x8b\xf7\x1e\x3f\x51\xf3\xf8\xa1\x31\x53\xb3\xcf\x23\x34\xb7\x63\x50\xc2\xcc\xb2\x5f\x5d\x8e\x6b\x64\x25\x2c\x90\xe6\x7a\x70\x07\x77\xb9\x6a\x03\x09\xd9\x0a\x04\xcc\x9e\xae\x70\xa9\x88\xf1\x32\x00\x7d\x2d\x8a\x6a\x72\x11\xd1\x39\xed\x5a\xbe\x60\xb6\x3c\xcd\x75\x0d\xfd\x65\xd1\xb6\x1c\x13\x20\xaa\xef\x56\xff\xe7\x21\x12\xc5\xe7\xb2\x52\x47\x49\xe1\x5d\x2d\x90\x9e\x5f\xfb\x0b\xb5\x6d\x47\xae\xbf\x9b\x5d\x95\x61\x0f\x45\x07\x05\x62\x84\xd7\x45\x51\x23\xc4\xd1\x91\xef\xe0\x8a\x51\xb2\xb2\xf1\x00\x12\xb9\x50\x1a\x92\x66\xdb\x70\x8f\x02\x1e\x65\x69\x23\x9b\x3a\x2d\x31\x84\x79\xb4\x26\xc4\x1c\xff\x0a\x3e\x5d\xbc\x46\x28\x10\x68\xaf\xcb\xf1\xad\xe4\x84\xcd\x4c\xdc\x20\x16\xd4\xf5\x01\xd3\xd2\x6b\x75\xc0\x4c\xad\x8d\xfc\x52\x51\xc2\x55\x95\xf1\x16\xcd\x4b\x0b\x1c\x34\x69\x26\xc9\x20\x6c\x78\xeb\x8a\x4a\x43\x7c\x11\xed\xaa\xa8\xfe\xd9\x76\x2c\x45\xb8\xc9\x8f\x5b\x3b\x2b\x85\xce\xf2\xf7\x49\x31\xe4\x0f\x96\x14\xca\x10\x20\x8b\x87\xef\xc9\xc4\x74\x0f\xe0\x4e\xe6\x90\x93\xab\x51\x00\x68\x0a\x5e\x3c\xf6\xf6\x2d\x31\x84\x2b\x83\xc5\x5f\x75\xb0\x8b\x00\xe6\x62\xdc\xe3\xf6\xe7\x41\x26\xad\x18\x81\xcc\xa9\x86\xfe\x71\x7b\x65\x0c\x0b\xdc\xd2\xd9\x04\x58\xe3\x2b\x57\x55\x15\x8d\x02\xd4\x8a\xeb\x54\x01\x74\xd5\x8f\xce\xd3\x49\x7c\x7e\xab\x61\x5c\x18\xd1\x0d\xb2\xe1\xe3\x2f\xc3\xeb\xff\x51\x68\x63\xe6\x1d\xc4\x5c\xc2\x7b\x65\x7c\xeb\x81\xa5\xd0\xd3\x3e\x5b\xd0\x75\xf8\x5c\x6e\x4a\x84\x39\x0d\x15\xb5\xae\xef\xe1\x63\x1d\x04\x95\x5a\x78\xb1\xfe\x15\x28\xd0\x28\xb4\x20\x44\x5c\x61\x2d\xee\xa0\x91\x1f\x18\xa6\x5b\x9e\x0f\xbb\xae\x19\xb2\x62\x52\x6b\x32\x2f\x67\xbd\x64\xd1\x96\x36\xe2\x06\x3f\x95\x1e\x85\xe8\xa4\x5c\x49\xe9\x52\x79\x57\xbb\xcb\xa1\xf9\x8f\x0b\x9f\x25\x20\x8e\x0f\x5e\x72\xb8\x15\x20\x02\xd4\xf8\x8e\xc7\x03\x0b\x7f\x2f\x10\xa3\x36\xb6\x3e\xad\xcd\x50\x7d\x5e\xcd\xa4\xdc\xbc\x5e\x7d\xab\x2b\x58\x5a\x2b\xa9\x31\xae\x06\x4f\x05\xcd\x81\x7f\x97\x39\x8e\x06\x81\x1f\x0a\x94\x72\xa5\x45\x59\xdf\x02\x24\xdb\xd6\xaa\xf2\xba\x8a\xdc\x0e\x8a\xd0\x91\xf3\xba\xba\x4e\x63\xc7\x02\x52\x1b\x52\x09\xe5\xd4\xec\x11\x15\xfa\x78\xc8\x62\xfc\xcc\x2b\x72\xf1\x53\x2c\xc9\xe9\x88\x9a\x44\x96\xbc\x4f\x8e\x55\x43\x26\x52\x79\x69\xdb\x3c\x79\x1b\xd4\x5f\x36\x3b\xd8\x70\xb7\xcf\x20\x46\x36\x46\xdc\x46\xb8\xb2\x7d\xe8\xf0\x46\xa7\x13\xb3\x79\x42\x1a\x9c\xf8\x94\xc5\x60\x90\x8f\x77\xdf\xc2\x04\xa4\x82\x29\x75\x29\x73\x49\xf0\xf5\xd5\xdb\xbb\x20\xea\x9f\x1d\xb6\x46\x92\xff\x1d\xa5\x54\x5a\xb2\x10\x12\x35\x4c\x9b\x86\xaf\x39\x35\x0a\xaf\xb3\x45\x4d\x1e\xf9\x05\x44\x26\xac\xc3\x4c\x0f\x18\xc9\x91\x8b\xde\x4d\x56\x69\xf3\x1e\x5b\xc2\x3a\xf2\xf7\xd0\x63\x63\xae\xe0\x32\x20\x48\x19\x89\xc7\xfd\x76\xf2\x36\x25\x96\x14\x2f\x60\xbd\x54\xa0\x19\x34\x30\xab\x85\xf1\x99\xd2\xa4\x70\xac\xd7\x64\xdd\x73\x64\x0a\x92\xa2\xf6\xe2\x00\x45\xbf\x59\x4a\x6c\x0e\x0b\x79\x42\x69\xa8\x3c\xd7\x6c\x30\x02\x5c\x4d\x6e\xe4\xf8\x71\xc4\x73\x3c\xfb\x14\xf1\x2f\xaf\xc7\x12\xf3\xd8\x1a\x98\xe1\xd2\xbd\xeb\x0f\xfa\x98\xc4\xa6\x8b\x64\xf5\x1d\xc9\x64\xe2\x5d\x86\x93\xb6\xcc\x89\x86\x74\x5d\x01\x75\x7b\x2f\x79\xab\x53\x0c\x83\x07\x45\x6f\x4f\x88\x36\xc8\x4d\x7e\xad\x17\x0c\xb8\x54\xdf\x58\xe4\x7b\xc9\xa7\xdb\x4c\xc4\x2e\x71\xeb\x15\xef\x4c\x38\x37\xf9\x65\x58\x19\xd3\x46\x0b\x3f\xa4\xeb\x67\xa3\xfa\x08\x98\x05\x6d\xcb\x50\x0d\x52\xd3\xf9\xc6\xf0\x37\xf7\xa4\x93\x74\xd1\x28\x1b\x02\x0b\xe7\x9c\x04\x65\xc5\x89\x70\x45\x04\xbb\x0c\x96\x75\x8f\xf5\x40\x01\xd9\x5d\x73\xeb\x3b\x84\xae\x05\xe1\xd4\xf1\xbd\x70\x13\x17\x16\x27\x25\xf8\x18\xaf\x8d\x10\xd1\x79\xf2\xdd\xe9\x98\x74\x82\xab\x05\x8a\x58\x76\x32\x01\x50\x0e\x03\x42\x2a\xe6\x59\x2c\x6b\x2e\x0f\x60\x37\xba\xb1\x00\x3a\x6a\xa2\xc3\x4c\x7e\x5e\x5e\x1f\xb6\x26\xa8\x6d\xc0\x53\x80\xee\x82\x7a\xdf\xd0\xee\x3e\x91\x4f\xb3\x4a\xe5\xc1\xef\xeb\x13\x9f\x81\x34\x11\xee\x1e\x6e\x29\x5a\x76\x94\xbe\x71\x6c\xd8\xc3\x84\x2a\x49\xaa\x47\x6d\x80\x1d\xd0\x32\x69\xc6\x2a\x51\x1a\x3c\xdf\x3a\xe3\x5b\xa9\xc2\x60\xd9\xe4\x4b\xe5\x13\x08\x99\xfa\x38\xfa\xb5\xab\x0a\xc3\xaa\x1e\x9a\xc4\x48\xfc\xd9\xc6\x13\x5a\xec\xef\x90\x21\xf8\x4f\xe2\xf6\xa4\xcf\xf7\x88\xc4\x51\xf1\x83\x16\x47\x34\xf5\x6d\x0a\x16\x74\x76\xfe\xfc\xb0\x19\xbb\x6a\x4d\xe1\x99\xc1\x3f\x57\x7b\x4f\xc5\x42\x63\xe6\xc0\x7d\x43\xb6\xd5\x14\xbb\x79\x47\x06\xed\x4a\x4b\x17\x38\x22\xb3\xff\xfd\x58\x91\x18\x3f\x72\x67\xfc\xe0\xd3\x3e\xde\xe8\x09\xc6\xb3\x74\x41\x88\x31\x92\x8f\xfe\xc6\x45\xe5\x3b\xe1\xe5\x71\x95\xa6\x16\x6c\x68\x03\xea\xc3\x22\xd5\x0d\xe2\x7d\xdc\xfd\x0f\x18\x7c\x1e\x34\xe3\xaa\x75\x4f\x50\xfe\xb9\x78\x80\x40\xef\x66\xe4\xae\xec\xae\x36\x7b\x7c\x48\x8f\xa5\x10\x30\x4c\xa9\xba\xd0\xe1\x5b\x97\x76\xff\x17\xbd\x46\x5a\x63\xaf\x4d\x2e\x53\xeb\x3a\x74\x41\x76\x66\xcd\x87\x5a\x2a\x4e\xbb\x32\x31\x0e\xfd\xcb\x5a\x89\x10\xd6\x18\xb6\xd3\x61\x5b\x0f\x69\x57\xb5\xf5\x1d\x9f\x64\xb0\xb4\x87\xf3\x83\x71\xb9\x63\x85\x85\xe5\x39\x78\xf8\x7d\x53\xae\xe1\xbc\xa8\x4b\x6b\x60\x4a\x83\x90\x94\x4e\x67\x72\xc4\x3e\xa8\xa9\x8f\xa6\xb7\x11\x4b\x94\x22\x2a\xc9\x01\x86\x0c\xac\xbc\xdc\x55\x92\x8b\x84\x7b\xd8\xea\xbd\xd5\xbb\xe0\x32\x1c\x75\xee\x33\x50\x6b\xfe\x85\x4f\x8f\xf1\xf6\x6f\x67\x93\xea\xfe\xe4\x82\x62\x1f\x41\x50\x43\x0d\x2b\xa3\x25\x72\xfe\x03\x85\xda\x16\xac\xdb\x32\x78\xae\xf8\xc3\x6c\x4f\x4e\x07\x9f\x5c\x13\xc5\x78\x0d\xd5\x0f\x67\xc9\x9b\xa7\x90\xcd\x96\xd1\x3b\x32\x44\x2c\xfa\x12\xaa\x57\x8c\x1b\xd2\x53\x92\x6d\x13\xb3\x06\x58\x72\x64\x18\x88\x5e\x5e\xb1\xda\xda\x73\xc0\xdd\x45\x1a\x92\x3c\x70\xa8\x2b\xbe\x5d\xdc\x63\x4f\x18\x69\xae\x8e\xa1\xc7\xef\x5f\xa8\x31\x6f\x10\x43\xfa\x6f\x95\xfb\xd1\x72\x7d\xd3\x6e\xd0\x30\xa9\x84\x6d\xb4\x12\x18\xef\xef\xa6\x6e\x26\xb2\xea\xf9\xb6\x01\x33\xb2\x94\x48\x45\x51\x46\x23\x1b\x13\xe7\xac\xf4\xea\x74\xf7\x07\x9d\x3c\x75\xa0\xd2\x3b\x45\x90\x91\xa4\xe9\x31\x14\x50\x8d\x78\x89\xc9\x45\x94\x39\x5c\xf2\x16\x08\x95\x8c\xa9\xab\x8d\x94\x51\x9d\xa3\x91\x49\xb8\xd6\x7e\xa0\x7b\x95\x6d\x1d\x76\xc7\x45\x98\xd1\x92\x6b\x52\x3b\x5a\x44\xa6\x9e\xe0\x87\x8a\xfd\x09\x7a\x03\x58\x3c\xf0\xd3\x2c\x31\xd5\x2d\x68\xd7\xa7\x43\xe5\x8a\x26\x3a\xc3\x99\x8e\x87\x09\xe2\xe2\x60\x6a\x12\xf6\x52\xec\xc9\x0f\xcd\xc7\x91\x02\xdd\x44\x32\x1a\x46\x6a\x8e\x7f\x1b\xb7\xc9\x65\x7b\xcf\x32\x9e\x73\xee\x43\xf3\x01\x23\xa8\xaa\x51\x1e\xcb\xec\xf5\xbe\x6e\xe8\xba\xea\x32\x80\x47\xb6\x4f\x73\xce\xb1\x62\x55\x55\x80\xbf\x2e\xaa\xed\x13\x8f\x46\x57\xe2\xde\xe5\x6e\x58\xa5\x35\xd7\x2c\x08\x61\xd3\xe0\xfc\x11\xe8\x64\xd1\xa0\x11\xfb\x4d\xcc\x45\x13\x98\x3c\xd1\x24\x6d\x1c\xe9\xdc\xab\xf8\xc4\x07\xb5\xc2\xd4\xa9\x75\x7c\x06\x82\x07\x5f\x06\x57\xfe\x29\xb2\x3f\x19\x7d\x4e\x1b\x0a\x21\x04\x8c\xb7\x2d\xbf\xee\x98\xbc\xf9\x69\x21\x94\x02\xcb\x8f\xf0\x56\x46\x60\x1a\x4a\x8c\x95\x4e\xa4\x56\x46\x5b\xb7\x3d\x5e\xef\x87\xce\xed\xc0\x96\x2b\xcd\x4e\xc7\xa3\x91\x16\x84\x80\xd7\x54\xa4\xd7\x5e\xb7\xc7\x56\x86\xf9\xc5\x71\xd6\x04\xf1\x41\x01\xf5\x35\x99\x68\xc8\xf6\x47\xef\xa8\xa4\x15\xb4\xfc\x73\xb8\xeb\xb7\x2a\xf5\x29\x9e\xe2\xa2\x36\x12\xe9\xbc\x5d\x03\xe8\xe0\xa0\x9c\x59\x1d\x25\x55\x46\x86\xf2\x84\xde\x29\x77\xdb\xc5\xc2\xd8\xee\xc0\x4a\x73\xb1\xae\xe4\xc1\x91\x7f\xf0\x4c\x06\xa7\x15\xcf\xe4\xca\x0e\xc9\xc4\x95\xb4\x3d\x14\x8e\x1f\x20\x0b\x79\x88\xde\x42\x3f\x30\xde\x11\x75\x2d\x77\xed\x23\x2c\x68\xdd\x9f\xb3\x71\x82\x15\x1f\xab\x9e\x2f\x3a\xfb\xc3\x23\x20\xab\x7c\x2e\xdf\x9a\xe8\xbd\x4e\x28\xdb\x09\xc1\x97', 2)
| 9,455
| 9,455
| 0.749974
| 2,359
| 9,455
| 3.000848
| 0.11064
| 0.016104
| 0.016528
| 0.013561
| 0.005509
| 0.00339
| 0.00339
| 0
| 0
| 0
| 0
| 0.314431
| 0.000317
| 9,455
| 1
| 9,455
| 9,455
| 0.434511
| 0
| 0
| 0
| 0
| 1
| 0.99577
| 0.99577
| 0
| 1
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 1
| 1
| 1
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| null | 1
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 10
|
541172a89a37bcc95c9f680d6efbb7d8e3765702
| 13,977
|
py
|
Python
|
models/glc/cism/glimmer-cism/tests/higher-order/livv/bin/VV_ismip.py
|
fmyuan/clm-microbe
|
9faee9ed7d6c092c4a9e4a207f32cbffab78b85c
|
[
"MIT"
] | 5
|
2019-03-12T01:58:26.000Z
|
2020-12-16T03:08:25.000Z
|
models/glc/cism/glimmer-cism/tests/higher-order/livv/bin/VV_ismip.py
|
fmyuan/clm-microbe
|
9faee9ed7d6c092c4a9e4a207f32cbffab78b85c
|
[
"MIT"
] | 1
|
2022-01-21T01:51:13.000Z
|
2022-01-21T01:51:13.000Z
|
models/glc/cism/glimmer-cism/tests/higher-order/livv/bin/VV_ismip.py
|
email-clm/CLM-Microbe
|
711c87faec2c1bfe2cea1a7ebd07e4373e82a184
|
[
"MIT"
] | 13
|
2016-03-08T21:04:52.000Z
|
2021-05-16T03:29:35.000Z
|
#!/usr/bin/env
import sys
import os
from optparse import OptionParser
import subprocess
import collections
import VV_outprocess
# routine for ISMIP HOM A 80km
def a80details(solver_file,job_path): # using data, fill the web page with info
solver_file.write('<HTML>\n')
solver_file.write('<H3>ISMIP HOM A 80km Iteration Count Details:</H3>')
solver_file.write('<H4>Eventually published in plot form</H4>')
solver_file.write('<BR> \n')
# JFNK gnu 1 proc
solver_file.write('<H4>New Run:</H4>')
procttl_ih1d, nonlist_ih1d,avg2_ih1d,out_flag_ih1d, ndiha1_name, ldiha1_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-a/80km/data/ishom.a.80km.out.1', 'imhoma1')
solver_file.write("Number of Processors = " + str(procttl_ih1d[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih1d:
solver_file.write(str(item) + ", ")
# print this to an array that ncl can use for plotting
# print item
solver_file.write('<BR>\n')
if out_flag_ih1d == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih1d:
solver_file.write(str(item) + ", ")
# print this to an array that ncl can use for plotting
# print item
solver_file.write('<BR> \n')
solver_file.write('<H4>Benchmark Run:</H4>')
procttl_ih1b, nonlist_ih1b,avg2_ih1b,out_flag_ih1b,ndiha1b_name, ldiha1b_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-a/80km/bench/ishom.a.80km.out.1', 'imhoma1b')
solver_file.write("Number of Processors = " + str(procttl_ih1b[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih1b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih1b == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih1b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
# JFNK gnu 2 proc
solver_file.write('<H4>New Run:</H4>')
procttl_ih2d, nonlist_ih2d,avg2_ih2d,out_flag_ih2d,ndiha2_name,ldiha2_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-a/80km/data/ishom.a.80km.out.2','imhoma2')
solver_file.write("Number of Processors = " + str(procttl_ih2d[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih2d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih2d == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) THAT FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih2d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
solver_file.write('<H4>Benchmark Run:</H4>')
procttl_ih2b, nonlist_ih2b,avg2_ih2b,out_flag_ih2b,ndiha2b_name,ldiha2b_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-a/80km/bench/ishom.a.80km.out.2','imhoma2b')
solver_file.write("Number of Processors = " + str(procttl_ih2b[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih2b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih2b == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) THAT FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih2b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
# JFNK gnu 4 proc
solver_file.write('<H4>New Run:</H4>')
procttl_ih4d, nonlist_ih4d,avg2_ih4d,out_flag_ih4d,ndiha4_name,ldiha4_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-a/80km/data/ishom.a.80km.out.4','imhoma4')
solver_file.write("Number of Processors = " + str(procttl_ih4d[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih4d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih4d == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih4d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
solver_file.write('<H4>Benchmark Run:</H4>')
procttl_ih4b, nonlist_ih4b,avg2_ih4b,out_flag_ih4b,ndiha4b_name,ldiha4b_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-a/80km/bench/ishom.a.80km.out.4','imhoma4b')
solver_file.write("Number of Processors = " + str(procttl_ih4b[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih4b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih4b == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih4b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
solver_file.write('</HTML>\n')
solver_file.close()
# routine for ISMIP HOM C 80km
def c80details(solver_file,job_path): # using data, fill the web page with info
solver_file.write('<HTML>\n')
solver_file.write('<H3>ISMIP HOM C Iteration Count Details:</H3>')
solver_file.write('<H4>Eventually published in plot form</H4>')
solver_file.write('<BR> \n')
# JFNK gnu 1 proc
solver_file.write('<H4>New Run:</H4>')
procttl_ih1d, nonlist_ih1d,avg2_ih1d,out_flag_ih1d,ndihc1_name,ldihc1_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-c/80km/data/ishom.c.80km.out.1','imhomc1')
solver_file.write("Number of Processors = " + str(procttl_ih1d[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih1d:
solver_file.write(str(item) + ", ")
# print this to an array that ncl can use for plotting
# print item
solver_file.write('<BR>\n')
if out_flag_ih1d == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih1d:
solver_file.write(str(item) + ", ")
# print this to an array that ncl can use for plotting
# print item
solver_file.write('<BR> \n')
solver_file.write('<H4>Benchmark Run:</H4>')
procttl_ih1b, nonlist_ih1b,avg2_ih1b,out_flag_ih1b,ndihc1b_name,ldihc1b_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-c/80km/bench/ishom.c.80km.out.1','imhomc1b')
solver_file.write("Number of Processors = " + str(procttl_ih1b[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih1b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih1b == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih1b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
# JFNK gnu 2 proc
solver_file.write('<H4>New Run:</H4>')
procttl_ih2d, nonlist_ih2d,avg2_ih2d,out_flag_ih2d,ndihc2_name,ldihc2_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-c/80km/data/ishom.c.80km.out.2','imhom2')
solver_file.write("Number of Processors = " + str(procttl_ih2d[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih2d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih2d == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) THAT FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih2d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
solver_file.write('<H4>Benchmark Run:</H4>')
procttl_ih2b, nonlist_ih2b,avg2_ih2b,out_flag_ih2b,ndihc2b_name,ldihc2b_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-c/80km/bench/ishom.c.80km.out.2','imhom2b')
solver_file.write("Number of Processors = " + str(procttl_ih2b[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih2b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih2b == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) THAT FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih2b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
# JFNK gnu 4 proc
solver_file.write('<H4>New Run:</H4>')
procttl_ih4d, nonlist_ih4d,avg2_ih4d,out_flag_ih4d,ndihc4_name,ldihc4_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-c/80km/data/ishom.c.80km.out.4','imhomc4')
solver_file.write("Number of Processors = " + str(procttl_ih4d[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih4d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih4d == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih4d:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
solver_file.write('<H4>Benchmark Run:</H4>')
procttl_ih4b, nonlist_ih4b,avg2_ih4b,out_flag_ih4b,ndihc4b_name,ldihc4b_name = VV_outprocess.jobprocess(job_path + '/ismip-hom-c/80km/bench/ishom.c.80km.out.4','imhomc4b')
solver_file.write("Number of Processors = " + str(procttl_ih4b[-1]) + "<BR>\n")
solver_file.write("Number of Nonlinear Iterations = ")
for item in nonlist_ih4b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR>\n')
if out_flag_ih4b == 1:
solver_file.write('<FONT COLOR="red">***TIME STEP(S) WHICH FAILED TO CONVERGE</FONT> <BR>\n')
solver_file.write("Average Number of Linear Iterations per Time-Step = ")
for item in avg2_ih4b:
solver_file.write(str(item) + ", ")
solver_file.write('<BR> \n')
solver_file.write('</HTML>\n')
solver_file.close()
def a80plot(plot_file,job_path,ncl_path,html_path): # using data, fill the web page with info
plot_file.write('<HTML>\n')
plot_file.write('<H3>ISMIP HOM A 80km Plot Details:</H3>')
ishoma_plotfile=''+ ncl_path + '/ismipa80.ncl'
stock='STOCK = addfile(\"'+ job_path + '/ismip-hom-a/80km/bench/ishom.a.80km.JFNK.out.nc\", \"r\")'
VAR1 ='VAR1 = addfile(\"' + job_path + '/ismip-hom-a/80km/data/ishom.a.80km.JFNK.out.nc\", \"r\")'
png = 'PNG = "' + ncl_path + '/ismipa80"'
plot_ishoma = "ncl '" + VAR1 + "' '" + stock + "' '" + png + "' " + ishoma_plotfile
#TODO create an iteration plot and have that also in the html file
try:
output = subprocess.call(plot_ishoma, shell=True)
except:
print "error creating ncl ismip hom a plots"
raise
# transferring ismipa pic to www file
if (ncl_path + '/ismipa80.png'):
ishomapic = "mv -f " + ncl_path + "/ismipa80.png" + " " + html_path + "/"
try:
output = subprocess.call(ishomapic, shell=True)
except:
print "error moving ismip hom a 80km png file to www directory"
sys.exit(1)
raise
plot_file.write('<HTML>\n')
plot_file.write('<TITLE>ISMIP HOM A 80km </TITLE>\n')
plot_file.write('<TABLE>\n')
plot_file.write('<TR>\n')
plot_file.write('<H4>Difference from benchmark run</H4>\n')
plot_file.write('<BR>\n')
plot_file.write('<OBJECT data="ismipa80.png" type="image/png" width="1100" height="800" hspace=10 align=left alt="ISMIP HOM A 80km Plots">\n')
plot_file.write('</OBJECT>\n')
plot_file.write('<TR>\n')
plot_file.write('<BR>\n')
plot_file.write('</TABLE>\n')
plot_file.write('</HTML>\n')
plot_file.close()
def c80plot(plot_file,job_path,ncl_path,html_path): # using data, fill the web page with info
plot_file.write('<HTML>\n')
plot_file.write('<H3>ISMIP HOM C 80km Plot Details:</H3>')
ishomc_plotfile=''+ ncl_path + '/ismipc80.ncl'
stock='STOCK = addfile(\"'+ job_path + '/ismip-hom-c/80km/bench/ishom.c.80km.JFNK.out.nc\", \"r\")'
VAR1 ='VAR1 = addfile(\"' + job_path + '/ismip-hom-c/80km/data/ishom.c.80km.JFNK.out.nc\", \"r\")'
png = 'PNG = "' + ncl_path + '/ismipc80"'
plot_ishomc = "ncl '" + VAR1 + "' '" + stock + "' '" + png + "' " + ishomc_plotfile
#TODO create an iteration plot and have that also in the html file
try:
output = subprocess.call(plot_ishomc, shell=True)
except:
print "error creating ncl ismip hom c 80km plots"
raise
# transferring ismipa pic to www file
if (ncl_path + '/ismipc80.png'):
ishomcpic = "mv -f " + ncl_path + "/ismipc80.png" + " " + html_path + "/"
try:
output = subprocess.call(ishomcpic, shell=True)
except:
print "error moving ismip hom c 80km png file to www directory"
sys.exit(1)
raise
plot_file.write('<HTML>\n')
plot_file.write('<TITLE>ISMIP HOM C 80km </TITLE>\n')
plot_file.write('<TABLE>\n')
plot_file.write('<TR>\n')
plot_file.write('<H4>Difference from benchmark run</H4>\n')
plot_file.write('<BR>\n')
plot_file.write('<OBJECT data="ismipc80.png" type="image/png" width="1100" height="800" hspace=10 align=left alt="ISMIP HOM C Plots">\n')
plot_file.write('</OBJECT>\n')
plot_file.write('<TR>\n')
plot_file.write('<BR>\n')
plot_file.write('</TABLE>\n')
plot_file.write('</HTML>\n')
plot_file.close()
| 44.942122
| 174
| 0.669099
| 2,127
| 13,977
| 4.230842
| 0.091678
| 0.146016
| 0.196689
| 0.060451
| 0.911657
| 0.910323
| 0.910101
| 0.901433
| 0.888321
| 0.87343
| 0
| 0.032527
| 0.168563
| 13,977
| 310
| 175
| 45.087097
| 0.741847
| 0.0606
| 0
| 0.786885
| 0
| 0.07377
| 0.362589
| 0.053423
| 0.008197
| 0
| 0
| 0.003226
| 0
| 0
| null | null | 0
| 0.02459
| null | null | 0.016393
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 9
|
541846abbe5ea32e597556cb55fb2ec51220ce37
| 10,621
|
py
|
Python
|
multiagent_traffic_simulator_orig.py
|
oldpaws/AI3601_RL_Final_Project_MAGAIL
|
6e53d5c4ad21c9e3907e6d14b20c04b3287800cf
|
[
"MIT"
] | null | null | null |
multiagent_traffic_simulator_orig.py
|
oldpaws/AI3601_RL_Final_Project_MAGAIL
|
6e53d5c4ad21c9e3907e6d14b20c04b3287800cf
|
[
"MIT"
] | null | null | null |
multiagent_traffic_simulator_orig.py
|
oldpaws/AI3601_RL_Final_Project_MAGAIL
|
6e53d5c4ad21c9e3907e6d14b20c04b3287800cf
|
[
"MIT"
] | null | null | null |
import numpy as np
from dataclasses import replace
from example_adapter import get_observation_adapter
from smarts.core.smarts import SMARTS
from smarts.core.agent import AgentSpec
from smarts.core.agent_interface import AgentInterface
from smarts.core.controllers import ActionSpaceType
from smarts.core.scenario import Scenario
from smarts.core.traffic_history_provider import TrafficHistoryProvider
from smarts.env.wrappers.parallel_env import ParallelEnv
def get_action_adapter():
def action_adapter(model_action):
assert len(model_action) == 2
return (model_action[0], model_action[1])
return action_adapter
class MATrafficSimOrig:
def __init__(self, scenarios, agent_number, obs_stacked_size=1):
self.scenarios_iterator = Scenario.scenario_variations(scenarios, [])
self._init_scenario()
self.obs_stacked_size = obs_stacked_size
self.n_agents = agent_number
self.agentid_to_vehid = {}
self.agent_ids = [f"agent_{i}" for i in range(self.n_agents)]
self.agent_spec = AgentSpec(
interface=AgentInterface(
max_episode_steps=None,
waypoints=True,
neighborhood_vehicles=True,
ogm=False,
rgb=False,
lidar=False,
action=ActionSpaceType.Imitation,
),
action_adapter=get_action_adapter(),
# observation_adapter=get_observation_adapter(obs_stacked_size),
)
self.smarts = SMARTS(
agent_interfaces={},
traffic_sim=None,
envision=None,
)
def seed(self, seed):
np.random.seed(seed)
def step(self, action):
for agent_id in self.agent_ids:
if agent_id not in action.keys():
continue
agent_action = action[agent_id]
action[agent_id] = self.agent_spec.action_adapter(agent_action)
observations, rewards, dones, _ = self.smarts.step(action)
info = {}
for k in observations.keys():
observations[k] = self.agent_spec.observation_adapter(
observations[k]
)
dones["__all__"] = all(dones.values())
return (
observations,
rewards,
dones,
info,
)
def reset(self):
if self.vehicle_itr + self.n_agents >= (len(self.vehicle_ids) - 1):
self.vehicle_itr = 0
self.vehicle_id = self.vehicle_ids[self.vehicle_itr : self.vehicle_itr + self.n_agents]
traffic_history_provider = self.smarts.get_provider_by_type(
TrafficHistoryProvider
)
assert traffic_history_provider
for i in range(self.n_agents):
self.agentid_to_vehid[f"agent_{i}"] = self.vehicle_id[i]
agent_interfaces = {}
history_start_time = self.vehicle_missions[self.vehicle_id[0]].start_time
for agent_id in self.agent_ids:
vehicle = self.agentid_to_vehid[agent_id]
agent_interfaces[agent_id] = self.agent_spec.interface
if history_start_time > self.vehicle_missions[vehicle].start_time:
history_start_time = self.vehicle_missions[vehicle].start_time
traffic_history_provider.start_time = history_start_time
ego_missions = {}
for agent_id in self.agent_ids:
vehicle = self.agentid_to_vehid[agent_id]
ego_missions[agent_id] = replace(
self.vehicle_missions[vehicle],
start_time=self.vehicle_missions[vehicle].start_time
- history_start_time,
)
self.scenario.set_ego_missions(ego_missions)
self.smarts.switch_ego_agents(agent_interfaces)
observations = self.smarts.reset(self.scenario)
for k in observations.keys():
observations[k] = self.agent_spec.observation_adapter(
observations[k]
)
# self.vehicle_itr += self.n_agents
self.vehicle_itr = np.random.randint(0, len(self.vehicle_ids))
return observations
def _init_scenario(self):
self.scenario = next(self.scenarios_iterator)
self.vehicle_missions = self.scenario.discover_missions_of_traffic_histories()
self.veh_start_times = {}
for v_id, mission in self.vehicle_missions.items():
self.veh_start_times[v_id] = mission.start_time
self.vehicle_ids = list(self.vehicle_missions.keys())
vlist = []
for vehicle_id, start_time in self.veh_start_times.items():
vlist.append((vehicle_id, start_time))
dtype = [("id", int), ("start_time", float)]
vlist = np.array(vlist, dtype=dtype)
vlist = np.sort(vlist, order="start_time")
self.vehicle_ids = list(self.vehicle_missions.keys())
for id in range(len(self.vehicle_ids)):
self.vehicle_ids[id] = f"{vlist[id][0]}"
self.vehicle_itr = np.random.choice(len(self.vehicle_ids))
def close(self):
if self.smarts is not None:
self.smarts.destroy()
class MATrafficSimOrigV:
def __init__(self, scenarios, agent_number, obs_stacked_size=1):
self.scenarios_iterator = Scenario.scenario_variations(scenarios, [])
self._init_scenario()
self.obs_stacked_size = obs_stacked_size
self.n_agents = agent_number
self.agentid_to_vehid = {}
self.agent_ids = [f"agent_{i}" for i in range(self.n_agents)]
self.agent_spec = AgentSpec(
interface=AgentInterface(
max_episode_steps=None,
waypoints=True,
neighborhood_vehicles=True,
ogm=False,
rgb=True,
lidar=False,
action=ActionSpaceType.Imitation,
),
action_adapter=get_action_adapter(),
# observation_adapter=get_observation_adapter(obs_stacked_size),
)
self.smarts = SMARTS(
agent_interfaces={},
traffic_sim=None,
envision=None,
)
def seed(self, seed):
np.random.seed(seed)
def step(self, action):
for agent_id in self.agent_ids:
if agent_id not in action.keys():
continue
agent_action = action[agent_id]
action[agent_id] = self.agent_spec.action_adapter(agent_action)
observations, rewards, dones, _ = self.smarts.step(action)
info = {}
for k in observations.keys():
observations[k] = self.agent_spec.observation_adapter(
observations[k]
)
dones["__all__"] = all(dones.values())
return (
observations,
rewards,
dones,
info,
)
def reset(self):
if self.vehicle_itr + self.n_agents >= (len(self.vehicle_ids) - 1):
self.vehicle_itr = 0
self.vehicle_id = self.vehicle_ids[
self.vehicle_itr : self.vehicle_itr + self.n_agents
]
traffic_history_provider = self.smarts.get_provider_by_type(
TrafficHistoryProvider
)
assert traffic_history_provider
for i in range(self.n_agents):
self.agentid_to_vehid[f"agent_{i}"] = self.vehicle_id[i]
agent_interfaces = {}
history_start_time = self.vehicle_missions[self.vehicle_id[0]].start_time
for agent_id in self.agent_ids:
vehicle = self.agentid_to_vehid[agent_id]
agent_interfaces[agent_id] = self.agent_spec.interface
if history_start_time > self.vehicle_missions[vehicle].start_time:
history_start_time = self.vehicle_missions[vehicle].start_time
traffic_history_provider.start_time = history_start_time
ego_missions = {}
for agent_id in self.agent_ids:
vehicle = self.agentid_to_vehid[agent_id]
ego_missions[agent_id] = replace(
self.vehicle_missions[vehicle],
start_time=self.vehicle_missions[vehicle].start_time
- history_start_time,
)
self.scenario.set_ego_missions(ego_missions)
self.smarts.switch_ego_agents(agent_interfaces)
observations = self.smarts.reset(self.scenario)
for k in observations.keys():
observations[k] = self.agent_spec.observation_adapter(
observations[k]
)
# self.vehicle_itr += self.n_agents
self.vehicle_itr = np.random.randint(0, len(self.vehicle_ids))
return observations
def _init_scenario(self):
self.scenario = next(self.scenarios_iterator)
self.vehicle_missions = self.scenario.discover_missions_of_traffic_histories()
self.veh_start_times = {}
for v_id, mission in self.vehicle_missions.items():
self.veh_start_times[v_id] = mission.start_time
self.vehicle_ids = list(self.vehicle_missions.keys())
vlist = []
for vehicle_id, start_time in self.veh_start_times.items():
vlist.append((vehicle_id, start_time))
dtype = [("id", int), ("start_time", float)]
vlist = np.array(vlist, dtype=dtype)
vlist = np.sort(vlist, order="start_time")
self.vehicle_ids = list(self.vehicle_missions.keys())
for id in range(len(self.vehicle_ids)):
self.vehicle_ids[id] = f"{vlist[id][0]}"
self.vehicle_itr = np.random.choice(len(self.vehicle_ids))
def close(self):
if self.smarts is not None:
self.smarts.destroy()
if __name__ == "__main__":
""" Dummy Rollout """
env = MATrafficSimOrig(["./ngsim"], agent_number=5)
obs = env.reset()
done = {}
n_steps = 10
for step in range(n_steps):
act_n = {}
for agent_id in obs.keys():
if step and done[agent_id]:
continue
act_n[agent_id] = np.random.normal(0, 1, size=(2,))
obs, rew, done, info = env.step(act_n)
print(rew)
print("finished")
env.close()
""" Parallel Rollout """
env_num = 2
env_creator = lambda: MATrafficSimOrig(["./ngsim"], agent_number=5)
vector_env = ParallelEnv([env_creator] * env_num, auto_reset=True)
vec_obs = vector_env.reset()
vec_act = []
for obs in vec_obs:
vec_act.append({a_id: np.random.normal(0, 1, size=(2,)) for a_id in obs.keys()})
vec_next_obs, vec_rew, vec_done, vec_info = vector_env.step(vec_act)
print("parallel finished!")
vector_env.close()
| 35.881757
| 95
| 0.62254
| 1,269
| 10,621
| 4.918834
| 0.115839
| 0.095162
| 0.05479
| 0.038449
| 0.842038
| 0.831464
| 0.831464
| 0.831464
| 0.824095
| 0.824095
| 0
| 0.003407
| 0.281518
| 10,621
| 296
| 96
| 35.881757
| 0.814572
| 0.018172
| 0
| 0.75
| 0
| 0
| 0.016379
| 0
| 0
| 0
| 0
| 0
| 0.012295
| 1
| 0.057377
| false
| 0
| 0.040984
| 0
| 0.131148
| 0.012295
| 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
|
54247f5e937ba00a252142f6bfaefe397774f6d6
| 20,149
|
py
|
Python
|
tests/integration/fixtures/movement_fixtures.py
|
legitishan/PteraSoftware
|
88edd8e3eae61e9de0b481dce9accf95a89a0615
|
[
"MIT"
] | null | null | null |
tests/integration/fixtures/movement_fixtures.py
|
legitishan/PteraSoftware
|
88edd8e3eae61e9de0b481dce9accf95a89a0615
|
[
"MIT"
] | null | null | null |
tests/integration/fixtures/movement_fixtures.py
|
legitishan/PteraSoftware
|
88edd8e3eae61e9de0b481dce9accf95a89a0615
|
[
"MIT"
] | null | null | null |
"""This module creates movement objects to be used as fixtures.
This module contains the following classes:
None
This module contains the following exceptions:
None
This module contains the following functions:
make_static_validation_movement: This function creates a movement object with
static geometry to be used as a fixture.
make_variable_validation_movement: This function creates a movement object with
variable geometry to be used as a fixture.
make_multiple_wing_static_validation_movement: This function creates a movement
object with static, multi-wing geometry to be used as a fixture.
make_multiple_wing_variable_validation_movement: This function creates a movement
object with variable, multi-wing geometry to be used as a fixture.
"""
import pterasoftware as ps
from tests.integration.fixtures import airplane_fixtures
from tests.integration.fixtures import operating_point_fixtures
def make_static_validation_movement():
"""This function creates a movement with static geometry to be used as a fixture.
:return unsteady_validation_movement: Movement
This is a movement object with static geometry to be used as a fixture.
"""
# Construct an airplane object and an operating point object.
unsteady_validation_airplane = (
airplane_fixtures.make_asymmetric_unsteady_validation_airplane()
)
unsteady_validation_operating_point = (
operating_point_fixtures.make_validation_operating_point()
)
# Create a wing cross section movement object associated with this airplane's
# root wing cross section.
unsteady_validation_root_wing_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[0]
)
)
# Create a wing cross section movement object associated with this airplane's tip
# wing cross section.
unsteady_validation_tip_wing_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[1],
)
)
# Create a wing movement object associated with this airplane's wing.
unsteady_validation_wing_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[0],
wing_cross_sections_movements=[
unsteady_validation_root_wing_cross_section_movement,
unsteady_validation_tip_wing_cross_section_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_root_wing_cross_section_movement
del unsteady_validation_tip_wing_cross_section_movement
# Create an airplane movement object associated with this airplane.
unsteady_validation_airplane_movement = ps.movement.AirplaneMovement(
base_airplane=unsteady_validation_airplane,
wing_movements=[unsteady_validation_wing_movement],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane
del unsteady_validation_wing_movement
# Create an operating point movement object associated with this operating point.
unsteady_validation_operating_point_movement = ps.movement.OperatingPointMovement(
base_operating_point=unsteady_validation_operating_point
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_operating_point
# Create a movement object associated with this airplane and operating point.
unsteady_validation_movement = ps.movement.Movement(
airplane_movement=unsteady_validation_airplane_movement,
operating_point_movement=unsteady_validation_operating_point_movement,
num_steps=None,
delta_time=None,
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane_movement
del unsteady_validation_operating_point_movement
# Return the movement fixture.
return unsteady_validation_movement
def make_variable_validation_movement():
"""This function creates a movement with variable geometry to be used as a fixture.
:return unsteady_validation_movement: Movement
This is a movement object with variable geometry to be used as a fixture.
"""
# Construct an airplane object and an operating point object.
unsteady_validation_airplane = (
airplane_fixtures.make_symmetric_unsteady_validation_airplane()
)
unsteady_validation_operating_point = (
operating_point_fixtures.make_validation_operating_point()
)
# Create a wing cross section movement object associated with this airplane's
# root wing cross section.
unsteady_validation_root_wing_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[0],
)
)
# Create a wing cross section movement object associated with this airplane's tip
# wing cross section.
unsteady_validation_tip_wing_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[1],
sweeping_amplitude=30.0,
sweeping_period=1.0,
sweeping_spacing="sine",
pitching_amplitude=30.0,
pitching_period=0.5,
pitching_spacing="sine",
heaving_amplitude=30.0,
heaving_period=0.5,
heaving_spacing="sine",
)
)
# Create a wing movement object associated with this airplane's wing.
unsteady_validation_wing_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[0],
wing_cross_sections_movements=[
unsteady_validation_root_wing_cross_section_movement,
unsteady_validation_tip_wing_cross_section_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_root_wing_cross_section_movement
del unsteady_validation_tip_wing_cross_section_movement
# Create an airplane movement object associated with this airplane.
unsteady_validation_airplane_movement = ps.movement.AirplaneMovement(
base_airplane=unsteady_validation_airplane,
wing_movements=[
unsteady_validation_wing_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane
del unsteady_validation_wing_movement
# Create an operating point movement object associated with this operating point.
unsteady_validation_operating_point_movement = ps.movement.OperatingPointMovement(
base_operating_point=unsteady_validation_operating_point,
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_operating_point
# Create a movement object associated with this airplane and operating point.
unsteady_validation_movement = ps.movement.Movement(
airplane_movement=unsteady_validation_airplane_movement,
operating_point_movement=unsteady_validation_operating_point_movement,
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane_movement
del unsteady_validation_operating_point_movement
# Return the movement fixture.
return unsteady_validation_movement
def make_multiple_wing_static_validation_movement():
"""This function creates a movement object with static, multi-wing geometry to
be used as a fixture.
:return unsteady_validation_movement: Movement
This is a movement object with variable geometry to be used as a fixture.
"""
# Construct an airplane object and an operating point object.
unsteady_validation_airplane = (
airplane_fixtures.make_symmetric_multiple_wing_unsteady_validation_airplane()
)
unsteady_validation_operating_point = (
operating_point_fixtures.make_validation_operating_point()
)
# Create a wing cross section movement object associated with this airplane's
# main wing's root wing cross section.
unsteady_validation_main_wing_root_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[0]
)
)
# Create a wing cross section movement object associated with this airplane's
# main wing's tip wing cross section.
unsteady_validation_main_wing_tip_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[1],
)
)
# Create a wing cross section movement object associated with this airplane's
# horizontal stabilizer's root wing cross section.
unsteady_validation_hstab_root_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
1
].wing_cross_sections[0]
)
)
# Create a wing cross section movement object associated with this airplane's
# horizontal stabilizer's tip wing cross section.
unsteady_validation_hstab_tip_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
1
].wing_cross_sections[1],
)
)
# Create a wing cross section movement object associated with this airplane's
# vertical stabilizer's root wing cross section.
unsteady_validation_vstab_root_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
2
].wing_cross_sections[0]
)
)
# Create a wing cross section movement object associated with this airplane's
# vertical stabilizer's tip wing cross section.
unsteady_validation_vstab_tip_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
2
].wing_cross_sections[1],
)
)
# Create a wing movement object associated with this airplane's main wing.
unsteady_validation_main_wing_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[0],
wing_cross_sections_movements=[
unsteady_validation_main_wing_root_cross_section_movement,
unsteady_validation_main_wing_tip_cross_section_movement,
],
)
# Create a wing movement object associated with this airplane's horizontal
# stabilizer.
unsteady_validation_hstab_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[1],
wing_cross_sections_movements=[
unsteady_validation_hstab_root_cross_section_movement,
unsteady_validation_hstab_tip_cross_section_movement,
],
)
# Create a wing movement object associated with this airplane's vertical stabilizer.
unsteady_validation_vstab_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[2],
wing_cross_sections_movements=[
unsteady_validation_vstab_root_cross_section_movement,
unsteady_validation_vstab_tip_cross_section_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_main_wing_root_cross_section_movement
del unsteady_validation_main_wing_tip_cross_section_movement
del unsteady_validation_hstab_root_cross_section_movement
del unsteady_validation_hstab_tip_cross_section_movement
del unsteady_validation_vstab_root_cross_section_movement
del unsteady_validation_vstab_tip_cross_section_movement
# Create an airplane movement object associated with this airplane.
unsteady_validation_airplane_movement = ps.movement.AirplaneMovement(
base_airplane=unsteady_validation_airplane,
wing_movements=[
unsteady_validation_main_wing_movement,
unsteady_validation_hstab_movement,
unsteady_validation_vstab_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane
del unsteady_validation_main_wing_movement
del unsteady_validation_hstab_movement
del unsteady_validation_vstab_movement
# Create an operating point movement object associated with this operating point.
unsteady_validation_operating_point_movement = ps.movement.OperatingPointMovement(
base_operating_point=unsteady_validation_operating_point
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_operating_point
# Create a movement object associated with this airplane and operating point.
unsteady_validation_movement = ps.movement.Movement(
airplane_movement=unsteady_validation_airplane_movement,
operating_point_movement=unsteady_validation_operating_point_movement,
num_steps=8,
delta_time=1 / 8 / 10,
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane_movement
del unsteady_validation_operating_point_movement
# Return the movement fixture.
return unsteady_validation_movement
def make_multiple_wing_variable_validation_movement():
"""This function creates a movement object with variable, multi-wing geometry to
be used as a fixture.
:return unsteady_validation_movement: Movement
This is a movement object with variable geometry to be used as a fixture.
"""
# Construct an airplane object and an operating point object.
unsteady_validation_airplane = (
airplane_fixtures.make_symmetric_multiple_wing_unsteady_validation_airplane()
)
unsteady_validation_operating_point = (
operating_point_fixtures.make_validation_operating_point()
)
# Create a wing cross section movement object associated with this airplane's
# main wing's root wing cross section.
unsteady_validation_main_wing_root_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[0],
)
)
# Create a wing cross section movement object associated with this airplane's
# main wing's tip wing cross section.
unsteady_validation_main_wing_tip_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
0
].wing_cross_sections[1],
sweeping_amplitude=30.0,
sweeping_period=1.0,
sweeping_spacing="sine",
heaving_amplitude=15.0,
heaving_period=1.0,
heaving_spacing="sine",
pitching_amplitude=15.0,
pitching_period=0.5,
pitching_spacing="sine",
)
)
# Create a wing cross section movement object associated with this airplane's
# horizontal stabilizer's root wing cross section.
unsteady_validation_hstab_root_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
1
].wing_cross_sections[0]
)
)
# Create a wing cross section movement object associated with this airplane's
# horizontal stabilizer's tip wing cross section.
unsteady_validation_hstab_tip_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
1
].wing_cross_sections[1],
)
)
# Create a wing cross section movement object associated with this airplane's
# vertical stabilizer's root wing cross section.
unsteady_validation_vstab_root_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
2
].wing_cross_sections[0]
)
)
# Create a wing cross section movement object associated with this airplane's
# vertical stabilizer's tip wing cross section.
unsteady_validation_vstab_tip_cross_section_movement = (
ps.movement.WingCrossSectionMovement(
base_wing_cross_section=unsteady_validation_airplane.wings[
2
].wing_cross_sections[1],
)
)
# Create a wing movement object associated with this airplane's main wing.
unsteady_validation_main_wing_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[0],
wing_cross_sections_movements=[
unsteady_validation_main_wing_root_cross_section_movement,
unsteady_validation_main_wing_tip_cross_section_movement,
],
)
# Create a wing movement object associated with this airplane's horizontal
# stabilizer.
unsteady_validation_hstab_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[1],
wing_cross_sections_movements=[
unsteady_validation_hstab_root_cross_section_movement,
unsteady_validation_hstab_tip_cross_section_movement,
],
)
# Create a wing movement object associated with this airplane's vertical stabilizer.
unsteady_validation_vstab_movement = ps.movement.WingMovement(
base_wing=unsteady_validation_airplane.wings[2],
wing_cross_sections_movements=[
unsteady_validation_vstab_root_cross_section_movement,
unsteady_validation_vstab_tip_cross_section_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_main_wing_root_cross_section_movement
del unsteady_validation_main_wing_tip_cross_section_movement
del unsteady_validation_hstab_root_cross_section_movement
del unsteady_validation_hstab_tip_cross_section_movement
del unsteady_validation_vstab_root_cross_section_movement
del unsteady_validation_vstab_tip_cross_section_movement
# Create an airplane movement object associated with this airplane.
unsteady_validation_airplane_movement = ps.movement.AirplaneMovement(
base_airplane=unsteady_validation_airplane,
wing_movements=[
unsteady_validation_main_wing_movement,
unsteady_validation_hstab_movement,
unsteady_validation_vstab_movement,
],
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane
del unsteady_validation_main_wing_movement
del unsteady_validation_hstab_movement
del unsteady_validation_vstab_movement
# Create an operating point movement object associated with this operating point.
unsteady_validation_operating_point_movement = ps.movement.OperatingPointMovement(
base_operating_point=unsteady_validation_operating_point
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_operating_point
# Create a movement object associated with this airplane and operating point.
unsteady_validation_movement = ps.movement.Movement(
airplane_movement=unsteady_validation_airplane_movement,
operating_point_movement=unsteady_validation_operating_point_movement,
num_steps=20,
delta_time=1 / 8 / 10,
)
# Delete the now extraneous constructing fixtures.
del unsteady_validation_airplane_movement
del unsteady_validation_operating_point_movement
# Return the movement fixture.
return unsteady_validation_movement
| 39.353516
| 88
| 0.742915
| 2,263
| 20,149
| 6.244808
| 0.041538
| 0.203793
| 0.090575
| 0.071327
| 0.978701
| 0.970988
| 0.966176
| 0.966176
| 0.961081
| 0.951175
| 0
| 0.005119
| 0.2147
| 20,149
| 511
| 89
| 39.430528
| 0.888011
| 0.304531
| 0
| 0.694704
| 0
| 0
| 0.001733
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.012461
| false
| 0
| 0.009346
| 0
| 0.034268
| 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
|
58164fbb311d62841e2b6fe806817cb519ffc188
| 1,089
|
py
|
Python
|
grocery/customer/permissions.py
|
DeepakDk04/bigbasketClone
|
82820d93876a2c3e6caec2725b1c6078e79e3bfb
|
[
"MIT"
] | null | null | null |
grocery/customer/permissions.py
|
DeepakDk04/bigbasketClone
|
82820d93876a2c3e6caec2725b1c6078e79e3bfb
|
[
"MIT"
] | null | null | null |
grocery/customer/permissions.py
|
DeepakDk04/bigbasketClone
|
82820d93876a2c3e6caec2725b1c6078e79e3bfb
|
[
"MIT"
] | null | null | null |
from rest_framework.permissions import BasePermission
class IsOwnerProfile(BasePermission):
"""
Object-level permission to only allow owners of an object to access it.
"""
def has_object_permission(self, request, view, obj):
return obj == request.user.customerprofile
class IsOwnerCustomer(BasePermission):
"""
Object-level permission to only allow owners of an object to access it.
"""
def has_object_permission(self, request, view, obj):
return obj == request.user.customerprofile.customer
class IsOwnerUser(BasePermission):
"""
Object-level permission to only allow owners of an object to access it.
"""
def has_object_permission(self, request, view, obj):
return obj == request.user
class IsCustomerOwnsOrder(BasePermission):
"""
Object-level permission to only allow owners of an object to access it.
"""
def has_object_permission(self, request, view, obj):
allOrders = request.user.customerprofile.customer.myorders.all()
return allOrders.filter(id=obj.id).exists()
| 27.225
| 75
| 0.707071
| 131
| 1,089
| 5.80916
| 0.290076
| 0.105125
| 0.131406
| 0.183968
| 0.706965
| 0.706965
| 0.706965
| 0.706965
| 0.706965
| 0.706965
| 0
| 0
| 0.203857
| 1,089
| 39
| 76
| 27.923077
| 0.877739
| 0.263545
| 0
| 0.285714
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.285714
| false
| 0
| 0.071429
| 0.214286
| 0.928571
| 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
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 9
|
582d0025e5f494fd1a8ac730763094f675e44318
| 1,889
|
py
|
Python
|
reverse_polish_notation/solution.py
|
andriiglukhyi/leetcode
|
22be8c8417b28b2888be5aee82ccfe47f57f1945
|
[
"MIT"
] | 1
|
2018-08-16T09:42:44.000Z
|
2018-08-16T09:42:44.000Z
|
reverse_polish_notation/solution.py
|
andriiglukhyi/leetcode
|
22be8c8417b28b2888be5aee82ccfe47f57f1945
|
[
"MIT"
] | null | null | null |
reverse_polish_notation/solution.py
|
andriiglukhyi/leetcode
|
22be8c8417b28b2888be5aee82ccfe47f57f1945
|
[
"MIT"
] | null | null | null |
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
stack = []
for item in tokens:
try:
int(item)
stack.append(int(item))
except ValueError:
item1 = stack.pop()
item2 = stack.pop()
if item == "*":
if item1 == 0 or item2 == 0:
item3 = 0
item3 = item1*item2
elif item == "/":
if item1 == 0 or item2 == 0:
item3 = 0
item3 = int(float(item2)/item1)
elif item == "+":
item3 = item1+item2
elif item == "-":
item3 = item2-item1
stack.append(item3)
return stack[0]
# faster solution
class Solution:
def evalRPN(self, tokens):
"""
:type tokens: List[str]
:rtype: int
"""
operand = {
'*': True
'/': True
'+': True
'-': True
}
stack = []
for item in tokens:
if item in operand:
item1 = stack.pop()
item2 = stack.pop()
if item == "*":
if item1 == 0 or item2 == 0:
item3 = 0
item3 = item1*item2
elif item == "/":
if item1 == 0 or item2 == 0:
item3 = 0
item3 = int(float(item2)/item1)
elif item == "+":
item3 = item1+item2
elif item == "-":
item3 = item2-item1
stack.append(item3)
else:
stack.append(int(item))
return stack[0]
| 29.515625
| 51
| 0.352567
| 159
| 1,889
| 4.188679
| 0.207547
| 0.072072
| 0.066066
| 0.072072
| 0.786787
| 0.726727
| 0.726727
| 0.726727
| 0.726727
| 0.726727
| 0
| 0.064665
| 0.541556
| 1,889
| 64
| 52
| 29.515625
| 0.704388
| 0.007941
| 0
| 0.792453
| 0
| 0
| 0.006901
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | null | 0
| 0
| null | null | 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 8
|
58979a1283be5582b34ca19308893220a48e751b
| 143
|
py
|
Python
|
zvt/factors/__init__.py
|
freedom6xiaobai/zvt
|
f4ba510a30f1014cc0e48b85370b0d3936bd851a
|
[
"MIT"
] | 1
|
2019-10-28T08:03:26.000Z
|
2019-10-28T08:03:26.000Z
|
zvt/factors/__init__.py
|
freedom6xiaobai/zvt
|
f4ba510a30f1014cc0e48b85370b0d3936bd851a
|
[
"MIT"
] | null | null | null |
zvt/factors/__init__.py
|
freedom6xiaobai/zvt
|
f4ba510a30f1014cc0e48b85370b0d3936bd851a
|
[
"MIT"
] | null | null | null |
# -*- coding: utf-8 -*-
from zvt.factors.fundamental_factor import *
from zvt.factors.technical_factor import *
def init_factors():
pass
| 17.875
| 44
| 0.72028
| 19
| 143
| 5.263158
| 0.684211
| 0.14
| 0.28
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.008264
| 0.153846
| 143
| 7
| 45
| 20.428571
| 0.818182
| 0.146853
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.25
| true
| 0.25
| 0.5
| 0
| 0.75
| 0
| 1
| 0
| 0
| null | 0
| 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
| 1
| 1
| 1
| 0
| 1
| 0
|
0
| 8
|
58a129d3a11c27deb7801c5efea0bb32fb2908d5
| 4,041
|
py
|
Python
|
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/mb_20010914.py
|
aleasims/Peach
|
bb56841e943d719d5101fee0a503ed34308eda04
|
[
"MIT"
] | null | null | null |
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/mb_20010914.py
|
aleasims/Peach
|
bb56841e943d719d5101fee0a503ed34308eda04
|
[
"MIT"
] | null | null | null |
dependencies/src/4Suite-XML-1.0.2/test/Xml/Xslt/Borrowed/mb_20010914.py
|
aleasims/Peach
|
bb56841e943d719d5101fee0a503ed34308eda04
|
[
"MIT"
] | 1
|
2020-07-26T03:57:45.000Z
|
2020-07-26T03:57:45.000Z
|
# At the time of this writing,
# 4XSLT generates a traceback when you do an apply-templates on a result tree
# fragment. It should generate a friendly (but equally fatal) error.
#
from Xml.Xslt import test_harness
sheet_1 = """\
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exslt="http://exslt.org/common"
exclude-result-prefixes="exslt">
<xsl:output method="xml" indent="yes"/>
<!--
This template processes the root node of an arbitrary source tree
-->
<xsl:template match="/">
<!-- a result tree fragment containing a root node and an element -->
<xsl:variable name="myTree">
<myElement/>
</xsl:variable>
<!--
The output should be a myResult element that contains the result
of processing the nodes in the $myTree fragment.
-->
<myResult>
<xsl:apply-templates select="exslt:node-set($myTree)" mode="foo">
<xsl:with-param name="myParameter" select="'hello world'"/>
</xsl:apply-templates>
</myResult>
</xsl:template>
<!-- This template processes the root node of the fragment -->
<xsl:template match="/" mode="foo">
<xsl:param name="myParameter"/>
<note>
<xsl:text>Processing the root node of the fragment. </xsl:text>
<xsl:value-of select="$myParameter"/>
</note>
<xsl:apply-templates mode="foo"/> <!-- note we do not pass the parameter -->
</xsl:template>
<!-- This template processes the 'myElement' node of the fragment -->
<xsl:template match="myElement" mode="foo">
<xsl:param name="myParameter"/>
<note>
<xsl:text>Processing the 'myElement' node of the fragment. </xsl:text>
<xsl:value-of select="$myParameter"/>
</note>
<note>
<xsl:text>This element has </xsl:text>
<xsl:value-of select="count(ancestor::node())"/>
<xsl:text> ancestor(s).</xsl:text>
</note>
</xsl:template>
</xsl:stylesheet>"""
expected_1 = """\
<?xml version='1.0' encoding='UTF-8'?>
<myResult>
<note>Processing the root node of the fragment. hello world</note>
<note>Processing the 'myElement' node of the fragment. </note>
<note>This element has 1 ancestor(s).</note>
</myResult>"""
sheet_2 = """\
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exslt="http://exslt.org/common"
exclude-result-prefixes="exslt">
<xsl:output method="xml" indent="yes"/>
<!--
This template processes the root node of an arbitrary source tree
-->
<xsl:template match="/">
<!-- a result tree fragment containing a root node and an element -->
<xsl:variable name="myTree">
<myElement/>
</xsl:variable>
<!--
The output should be a myResult element that contains the result
of processing the nodes in the $myTree fragment.
-->
<myResult>
<xsl:apply-templates select="exslt:node-set($myTree)" mode="foo">
<xsl:with-param name="myParameter" select="'hello world'"/>
</xsl:apply-templates>
</myResult>
</xsl:template>
<!-- This template processes the 'myElement' node of the fragment -->
<xsl:template match="myElement" mode="foo">
<xsl:param name="myParameter"/>
<note>
<xsl:text>Processing the 'myElement' node of the fragment. </xsl:text>
<xsl:value-of select="$myParameter"/>
</note>
</xsl:template>
</xsl:stylesheet>"""
expected_2 = """\
<?xml version='1.0' encoding='UTF-8'?>
<myResult>
<note>Processing the 'myElement' node of the fragment. </note>
</myResult>"""
def Test(tester):
source = test_harness.FileInfo(string=sheet_1)
sheet = test_harness.FileInfo(string=sheet_1)
test_harness.XsltTest(tester, source, [sheet], expected_1,
title='Case 1')
source = test_harness.FileInfo(string=sheet_2)
sheet = test_harness.FileInfo(string=sheet_2)
test_harness.XsltTest(tester, source, [sheet], expected_2,
title='Case 2')
return
| 30.847328
| 80
| 0.646622
| 533
| 4,041
| 4.870544
| 0.204503
| 0.025424
| 0.031202
| 0.058937
| 0.849384
| 0.849384
| 0.759245
| 0.701464
| 0.699923
| 0.670262
| 0
| 0.012262
| 0.192774
| 4,041
| 130
| 81
| 31.084615
| 0.783568
| 0.042316
| 0
| 0.76699
| 1
| 0.019417
| 0.857956
| 0.077102
| 0
| 0
| 0
| 0
| 0
| 1
| 0.009709
| false
| 0.009709
| 0.009709
| 0
| 0.029126
| 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
| 1
| 0
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 8
|
54390c130f9cde87d5d44b44ff662c2c099e7e28
| 13,281
|
py
|
Python
|
src/probing-tasks/replicate/edge_probing_utils.py
|
SwiftPredator/How-Does-Bert-Answer-QA-DLP2021
|
fd2683eefac96885cd3f1db11aac7782eaad11a5
|
[
"MIT"
] | null | null | null |
src/probing-tasks/replicate/edge_probing_utils.py
|
SwiftPredator/How-Does-Bert-Answer-QA-DLP2021
|
fd2683eefac96885cd3f1db11aac7782eaad11a5
|
[
"MIT"
] | null | null | null |
src/probing-tasks/replicate/edge_probing_utils.py
|
SwiftPredator/How-Does-Bert-Answer-QA-DLP2021
|
fd2683eefac96885cd3f1db11aac7782eaad11a5
|
[
"MIT"
] | null | null | null |
from transformers.models.bert.modeling_bert import BertPreTrainedModel, BertModel
from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data as data
from typing import Tuple
class BertEdgeProbingSingleSpan(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.num_layers = config.num_hidden_layers
self.projection_size = 256
self.hidden_size = 256
self.bert = BertModel(config, add_pooling_layer=False)
# Disable autograd for all parameters of the BertModel.
for param in self.bert.parameters():
param.requires_grad = False
self.projection1 = nn.Linear(config.hidden_size, self.projection_size)
self.attention1 = nn.Linear(self.projection_size, 1)
self.linear1 = nn.Linear(self.projection_size, self.hidden_size)
self.linear2 = nn.Linear(self.hidden_size, self.hidden_size)
self.output = nn.Linear(self.hidden_size, self.num_labels)
self.sigmoid = nn.Sigmoid()
self.init_weights()
def forward(
self,
input_ids=None,
span1s=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
"""Calculates the output of the net.
The most important inputs are::
input_ids:: tokenized sequence of shape (N, L, E)
N=batch size, L=max sequence length, E=embedding dimension
span1s:: masks for span1 of shape (N, L)
"""
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# outputs[0] has shape (N, L, E).
span1 = outputs[0] * span1s.unsqueeze(-1)
span1_projected = self.projection1(span1)
# span1_projected has shape (N, L, 256), but is zero on all sequence elements not in the span.
attention1 = self.attention1(span1_projected).squeeze(-1)
attention1 = F.softmax(attention1, 1).unsqueeze(2)
mlp_input = torch.bmm(torch.transpose(span1_projected, 1, 2), attention1).squeeze(2)
# mlp_input has shape (N, 256).
mlp_output = self.sigmoid(self.linear1(mlp_input))
mlp_output = self.sigmoid(self.linear2(mlp_output))
mlp_output = self.sigmoid(self.output(mlp_output))
return mlp_output
class BertEdgeProbingTwoSpan(BertPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.num_layers = config.num_hidden_layers
self.projection_size = 256
self.hidden_size = 256
self.bert = BertModel(config, add_pooling_layer=False)
# Disable autograd for all parameters of the BertModel.
for param in self.bert.parameters():
param.requires_grad = False
self.projection1 = nn.Linear(config.hidden_size, self.projection_size)
self.projection2 = nn.Linear(config.hidden_size, self.projection_size)
self.attention1 = nn.Linear(self.projection_size, 1)
self.attention2 = nn.Linear(self.projection_size, 1)
self.linear1 = nn.Linear(2*self.projection_size, self.hidden_size)
self.linear2 = nn.Linear(self.hidden_size, self.hidden_size)
self.output = nn.Linear(self.hidden_size, self.num_labels)
self.sigmoid = nn.Sigmoid()
self.init_weights()
def forward(
self,
input_ids=None,
span1s=None,
span2s=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
"""Calculates the output of the net.
The most important inputs are::
input_ids:: tokenized sequence of shape (N, L, E)
N=batch size, L=max sequence length, E=embedding dimension
span1s:: masks for span1 of shape (N, L)
span2s:: masks for span2 of shape (N, L)
"""
outputs = self.bert(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# outputs[0] has shape (N, L, E)
span1 = outputs[0] * span1s.unsqueeze(-1)
span2 = outputs[0] * span2s.unsqueeze(-1)
span1_projected = self.projection1(span1)
span2_projected = self.projection2(span2)
# span1_projected has shape (N, L, 256), but is zero on all sequence elements not in the span.
attention1 = self.attention1(span1_projected).squeeze(-1)
attention2 = self.attention2(span2_projected).squeeze(-1)
attention1 = F.softmax(attention1, 1).unsqueeze(2)
attention2 = F.softmax(attention2, 1).unsqueeze(2)
mlp_input1 = torch.bmm(torch.transpose(span1_projected, 1, 2), attention1).squeeze(2)
mlp_input2 = torch.bmm(torch.transpose(span2_projected, 1, 2), attention2).squeeze(2)
mlp_input = torch.cat((mlp_input1, mlp_input2), dim=1)
# mlp_input has shape (N, 512).
mlp_output = self.sigmoid(self.linear1(mlp_input))
mlp_output = self.sigmoid(self.linear2(mlp_output))
mlp_output = self.sigmoid(self.output(mlp_output))
return mlp_output
class RobertaEdgeProbingSingleSpan(RobertaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.num_layers = config.num_hidden_layers
self.projection_size = 256
self.hidden_size = 256
self.roberta = RobertaModel(config, add_pooling_layer=False)
# Disable autograd for all parameters of the BertModel.
for param in self.roberta.parameters():
param.requires_grad = False
self.projection1 = nn.Linear(config.hidden_size, self.projection_size)
self.attention1 = nn.Linear(self.projection_size, 1)
self.linear1 = nn.Linear(self.projection_size, self.hidden_size)
self.linear2 = nn.Linear(self.hidden_size, self.hidden_size)
self.output = nn.Linear(self.hidden_size, self.num_labels)
self.sigmoid = nn.Sigmoid()
self.init_weights()
def forward(
self,
input_ids=None,
span1s=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
"""Calculates the output of the net.
The most important inputs are::
input_ids:: tokenized sequence of shape (N, L, E)
N=batch size, L=max sequence length, E=embedding dimension
span1s:: masks for span1 of shape (N, L)
"""
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# outputs[0] has shape (N, L, E).
span1 = outputs[0] * span1s.unsqueeze(-1)
span1_projected = self.projection1(span1)
# span1_projected has shape (N, L, 256), but is zero on all sequence elements not in the span.
attention1 = self.attention1(span1_projected).squeeze(-1)
attention1 = F.softmax(attention1, 1).unsqueeze(2)
mlp_input = torch.bmm(torch.transpose(span1_projected, 1, 2), attention1).squeeze(2)
# mlp_input has shape (N, 256).
mlp_output = self.sigmoid(self.linear1(mlp_input))
mlp_output = self.sigmoid(self.linear2(mlp_output))
mlp_output = self.sigmoid(self.output(mlp_output))
return mlp_output
class RobertaEdgeProbingTwoSpan(RobertaPreTrainedModel):
def __init__(self, config):
super().__init__(config)
self.num_labels = config.num_labels
self.num_layers = config.num_hidden_layers
self.projection_size = 256
self.hidden_size = 256
self.roberta = RobertaModel(config, add_pooling_layer=False)
# Disable autograd for all parameters of the RobertaModel.
for param in self.roberta.parameters():
param.requires_grad = False
self.projection1 = nn.Linear(config.hidden_size, self.projection_size)
self.projection2 = nn.Linear(config.hidden_size, self.projection_size)
self.attention1 = nn.Linear(self.projection_size, 1)
self.attention2 = nn.Linear(self.projection_size, 1)
self.linear1 = nn.Linear(2*self.projection_size, self.hidden_size)
self.linear2 = nn.Linear(self.hidden_size, self.hidden_size)
self.output = nn.Linear(self.hidden_size, self.num_labels)
self.sigmoid = nn.Sigmoid()
self.init_weights()
def forward(
self,
input_ids=None,
span1s=None,
span2s=None,
attention_mask=None,
token_type_ids=None,
position_ids=None,
head_mask=None,
inputs_embeds=None,
output_attentions=None,
output_hidden_states=None,
return_dict=None,
):
"""Calculates the output of the net.
The most important inputs are::
input_ids:: tokenized sequence of shape (N, L, E)
N=batch size, L=max sequence length, E=embedding dimension
span1s:: masks for span1 of shape (N, L)
span2s:: masks for span2 of shape (N, L)
"""
outputs = self.roberta(
input_ids,
attention_mask=attention_mask,
token_type_ids=token_type_ids,
position_ids=position_ids,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
# outputs[0] has shape (N, L, E)
span1 = outputs[0] * span1s.unsqueeze(-1)
span2 = outputs[0] * span2s.unsqueeze(-1)
span1_projected = self.projection1(span1)
span2_projected = self.projection2(span2)
# span1_projected has shape (N, L, 256), but is zero on all sequence elements not in the span.
attention1 = self.attention1(span1_projected).squeeze(-1)
attention2 = self.attention2(span2_projected).squeeze(-1)
attention1 = F.softmax(attention1, 1).unsqueeze(2)
attention2 = F.softmax(attention2, 1).unsqueeze(2)
mlp_input1 = torch.bmm(torch.transpose(span1_projected, 1, 2), attention1).squeeze(2)
mlp_input2 = torch.bmm(torch.transpose(span2_projected, 1, 2), attention2).squeeze(2)
mlp_input = torch.cat((mlp_input1, mlp_input2), dim=1)
# mlp_input has shape (N, 512).
mlp_output = self.sigmoid(self.linear1(mlp_input))
mlp_output = self.sigmoid(self.linear2(mlp_output))
mlp_output = self.sigmoid(self.output(mlp_output))
return mlp_output
class JiantDatasetSingleSpan(data.Dataset):
def __init__(self, encodings) -> None:
super().__init__()
self.encodings = encodings
def __getitem__(self, index) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
tokens = self.encodings.input_ids[index]
span1_mask = self.encodings.span1_masks[index]
label = self.encodings.labels[index]
return tokens, span1_mask, label
def __len__(self):
return len(self.encodings.input_ids)
class JiantDatasetTwoSpan(data.Dataset):
def __init__(self, encodings) -> None:
super().__init__()
self.encodings = encodings
def __getitem__(self, index) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
tokens = self.encodings.input_ids[index]
span1_mask = self.encodings.span1_masks[index]
span2_mask = self.encodings.span2_masks[index]
label = self.encodings.labels[index]
return tokens, span1_mask, span2_mask, label
def __len__(self):
return len(self.encodings.input_ids)
| 38.054441
| 102
| 0.641292
| 1,604
| 13,281
| 5.083541
| 0.082918
| 0.031396
| 0.037773
| 0.03532
| 0.944567
| 0.944567
| 0.944567
| 0.944567
| 0.944567
| 0.944567
| 0
| 0.02558
| 0.267073
| 13,281
| 348
| 103
| 38.163793
| 0.812102
| 0.135758
| 0
| 0.91129
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.056452
| false
| 0
| 0.028226
| 0.008065
| 0.141129
| 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
|
544ba4e0d5d16d14e846f60f5d6635e9919a6f7b
| 116
|
py
|
Python
|
atlas/foundations_rest_api/src/test/__init__.py
|
DeepLearnI/atlas
|
8aca652d7e647b4e88530b93e265b536de7055ed
|
[
"Apache-2.0"
] | 296
|
2020-03-16T19:55:00.000Z
|
2022-01-10T19:46:05.000Z
|
atlas/foundations_rest_api/src/test/__init__.py
|
DeepLearnI/atlas
|
8aca652d7e647b4e88530b93e265b536de7055ed
|
[
"Apache-2.0"
] | 57
|
2020-03-17T11:15:57.000Z
|
2021-07-10T14:42:27.000Z
|
atlas/foundations_rest_api/src/test/__init__.py
|
DeepLearnI/atlas
|
8aca652d7e647b4e88530b93e265b536de7055ed
|
[
"Apache-2.0"
] | 38
|
2020-03-17T21:06:05.000Z
|
2022-02-08T03:19:34.000Z
|
import os
os.environ['TZ'] = 'EST'
from test.utils import *
from test.v2beta import *
from test.filters import *
| 12.888889
| 26
| 0.706897
| 18
| 116
| 4.555556
| 0.555556
| 0.292683
| 0.341463
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.010417
| 0.172414
| 116
| 8
| 27
| 14.5
| 0.84375
| 0
| 0
| 0
| 0
| 0
| 0.043478
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.8
| 0
| 0.8
| 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
|
49ac0670935e01653b249bbac149f52b4f8bdfd3
| 126,423
|
py
|
Python
|
HatakPoker/Luta.py
|
lsbloo/PokemonPython
|
ca98c0922f7f8076f6163ca44ad48e9992d3322c
|
[
"Apache-2.0"
] | 1
|
2020-04-12T20:28:42.000Z
|
2020-04-12T20:28:42.000Z
|
HatakPoker/Luta.py
|
lsbloo/PokemonPython
|
ca98c0922f7f8076f6163ca44ad48e9992d3322c
|
[
"Apache-2.0"
] | null | null | null |
HatakPoker/Luta.py
|
lsbloo/PokemonPython
|
ca98c0922f7f8076f6163ca44ad48e9992d3322c
|
[
"Apache-2.0"
] | null | null | null |
"""
Luta
"""
from Player import *
from poke_inimigos import *
#Neste modulo estara contida as funcoes da luta entre o player e o inimigo
#
cash = 100
jogando = True
print()
print("Voce deseja atacar?")
res = int(input("Digite (1)= Atk: "))
if res == 1:
if chart == 1:
print("Charmander Possue 3 ataques...")
print("Ember,flametower e fireblast...")
if chart == 2:
print("Squirtle Possue 3 ataques...")
print("Bubles,Warteball e Blubleam!!")
print()
if chart == 3:
print("Bulbasaur Possue 3 ataques...")
print("WineVip,Razor Leaf e Leaf Store!!")
print()
#if chart == 4:
#print("Gloom Possue 3 ataques...")
#print("Poison Job,Acid e Poison Gás!!")
#print()
#if chart == 5:
#print("Golbat Possue 3 ataques...")
#print("Bite,Wirldtril e Wing Attack!!")
#print()
#if chart == 6:
#print("Graveler Possue 3 ataques...")
#print("Rock Trown,Rock Slide e EarthPower!!")
#print()
elif res != 1:
jogando = False
print("Fim de JOGO!")
print("End Of Game!")
if chart1 == 1:
print("Geodude Possue 3 ataques...")
print("Rock Smash,RockSlide e EarthPower...")
print()
if chart1 == 2:
print("Shiny Horsea Possue 3 ataques...")
print("Bubbles,Warteball e HydroPump...")
print()
if chart1 == 3:
print("Golden Possue 3 ataques...")
print("Aquatail,Bubbleam e Horn Attack...")
print()
if chart1 == 4:
print("Vulpix Possue 3 ataques...")
print("Ember,Flametower e Fireblast...")
print()
if chart1 == 5:
print("Oddish Possue 3 ataques...")
print("Acid,Absorb e Poison Gás...")
print()
if chart1 == 6:
print("Shiny Tentacool Possue 3 ataques...")
print("Warteball,Aquatail e HydroPump...")
print()
def jogo():
global jogando,vida_geodude,atk_charmander_cd1,atk_charmander_cd2,vida_shiny_horsea,vida_golden,vida_vulpix,vida_geodude,player_vida
global player_inimigo
global vida_charmander
global vida_oddish
global vida_shiny_tentacool
global vida_squirte
global vida_bulbarsaur
global cash, Porcao
#uma porcao cura 3000 de Life...
Porcao = 3000
buy = not False
while jogando == True:
#CHARMANDER
if chart == 1 and chart1 == 1: #CHAMANDER X GEODUDE
print("-------------------")
print("Charmander!,Eu escolho você")
#Erro nessa funcao!
#ja consertei as funcoes do player
#Falta consertar as funcoes do Inimigo
#Para colocar aq
print("Digite (1)-para usar ember,(2)-para usar flametower,(3)-para usar fireblast")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Charmander Use Ember!!")
vida_geodude -= atk_charmander_cd1
print("Vida do Geodude",vida_geodude)
if vida_geodude <= 0:
print("Geodude,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude,Contra-Ataca")
vida_charmander -= atk_geodude_cd2
print("Vida do seu charmander",vida_charmander)
#POtions MArket
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Charmander use Flametower!!")
vida_geodude -= atk_charmander_cd2
print("Vida do Geodude",vida_geodude)
if vida_geodude <= 0:
print("Geodude,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude,Contra-Ataca")
vida_charmander -= atk_geodude_cd2
print("Vida do seu charmander",vida_charmander)
#POtions MArket
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Charmander use FireBlast!!")
vida_geodude -= atk_charmander_cd3
print("Vida do Geodude",vida_geodude)
if vida_geodude <=0:
print("Geodude,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude,Contra-Ataca")
vida_charmander -= atk_geodude_cd2
print("Vida do seu charmander",vida_charmander)
#POtions MArket
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif chart == 1 and chart1 == 2: # CHARMANDER X SHINY HORSEA
print("-------------------")
print("Charmander!,Eu escolho você")
print("Digite (1)-para usar ember,(2)-para usar flametower,(3)-para usar fireblast")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Charmander Use Ember!!")
vida_shiny_horsea -= atk_charmander_cd1
print("Vida do Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <= 0:
print("Shiny Horsea,Morreu")
#
try:
print("Você tem a chance de matar seu inimigo")
print("Antes que ele coloque outro pokemon:")
print()
print("Charmander use Ember")
player_inimigo -= atk_charmander_cd1
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo:")
print()
print("Shiny Horsea,Contra-Ataca")
vida_charmander -= atk_horsea_cd2
print("Vida do seu charmander",vida_charmander)
print("Vida do seu charmander",vida_charmander)
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
#CONSEGUIR COLOCAR A CURA DOS POKEMON IMPORTANDO A FUNCAO NPC DO MODULO.
#MAS ELA MEIO QUE FICOU FICTICIA.. MAS COLOQUEI UMA CURA MAIOR PARA O POKEMON...
#AINDA EM TESTES...
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Charmander Use Flametower!!")
vida_shiny_horsea -= atk_horsea_cd2
print("Vida do Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
print("Shiny Horsea,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea,Contra-Ataca")
vida_charmander -= atk_horsea_cd2
print("Vida do seu charmander",vida_charmander)
#POTIONS MAKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Charmander use FireBlast!!")
vida_shiny_horsea -= atk_charmander_cd3
print("Vida do Geodude",vida_shiny_horsea)
if vida_shiny_horsea <= 0:
print("Shiny Horsea,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea,Contra-Ataca")
vida_charmander -= atk_horsea_cd2
print("Vida do seu charmander",vida_charmander)
#POTIONS MAKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif chart == 1 and chart1 == 3: #CHAMANDER X GOLDEN
print("-------------------")
print("Charmander!,Eu escolho você")
print("Digite (1)-para usar ember,(2)-para usar flametower,(3)-para usar fireblast")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Charmander Use Ember!!")
vida_golden -= atk_charmander_cd1
print("Vida do Golden",vida_golden)
if vida_golden <= 0:
print("Golden,Morreu")
try:
print("Você tem a chance de matar seu inimigo")
print("Antes que ele coloque outro pokemon:")
print()
print("Charmander use Ember")
player_inimigo -= atk_charmander_cd1
if player_inimigo <= 0:
print("Vida do Inimigo",player_inimigo)
print("Voce o Derrotou")
break
except:
print("Deseja matar outro inimigo:")
print()
print("Golden,Contra-Ataca")
vida_charmander -= atk_golden_cd2
print("Vida do seu charmander",vida_charmander)
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Charmander use Flametower!!")
vida_golden -= atk_charmander_cd2
print("Vida do Golden",vida_golden)
if vida_golden <= 0:
print("Golden,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Golden,Contra-Ataca")
vida_charmander -= atk_golden_cd2
print("Vida do seu charmander",vida_golden)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Charmander use FireBlast!!")
vida_golden -= atk_charmander_cd3
print("Vida do Geodude",vida_golden)
if vida_golden <= 0:
print("Golden,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Golden,Contra-Ataca")
vida_charmander -= atk_golden_cd2
print("Vida do seu charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif chart == 1 and chart1 == 4: #CHAMANDER X VULPIX
print("-------------------")
print("Charmander!,Eu escolho você")
charmander()
print("Digite (1)-para usar ember,(2)-para usar flametower,(3)-para usar fireblast")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Charmander Use Ember!!")
vida_vulpix -= atk_charmander_cd1
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <= 0:
print("Vulpix ,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Vulpix,Contra-Ataca")
vida_charmander -= atk_vulpix_cd2
print("Vida do seu charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res ==2:
print("Charmander Use Flametower!!")
vida_vulpix -= atk_charmander_cd2
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <= 0:
print("Vulpix,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Vulpix,Contra-Ataca")
vida_charmander -= atk_vulpix_cd2
print("Vida do seu charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Charmander use FireBlast!!")
vida_vulpix -= atk_charmander_cd3
print("Vida do Geodude",vida_vulpix)
if vida_vulpix <= 0:
print("Vulpix,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Vulpix,Contra-Ataca")
vida_charmander -= atk_vulpix_cd2
print("Vida do seu charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif chart == 1 and chart1 == 5: #CHAMANDER X ODDISH
print("-------------------")
print("Charmander!,Eu escolho você")
print("Digite (1)-para usar ember,(2)-para usar flametower,(3)-para usar fireblast")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Charmander Use Ember!!")
vida_oddish -= atk_charmander_cd1
print("Vida do Oddish",vida_oddish)
if vida_oddish <= 0:
print("Oddish,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_charmander -= atk_oddish_cd2
print("Vida do charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Charmander use Flametower!!")
vida_oddish -= atk_charmander_cd2
print("Vida do Oddish",vida_oddish)
if vida_oddish <= 0:
print("Oddish,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_charmander -= atk_oddish_cd2
print("Vida do charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Charmander use FireBlast!!")
vida_oddish -= atk_charmander_cd3
print("Vida do Oddish",vida_oddish)
if vida_oddish <= 0:
print("Oddish,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_charmander -= atk_oddish_cd2
print("Vida do charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif chart == 1 and chart1 == 6: #CHARMANDER X SHINY TENTACOOL
print("-------------------")
print("Charmander!,Eu escolho você")
print("Digite (1)-para usar ember,(2)-para usar flametower,(3)-para usar fireblast")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Charmander Use Ember!!")
vida_shiny_tentacool -= atk_charmander_cd1
print("Vida do Shiny Tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
print("Shiny Tentacool,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_charmander -= atk_tentacool_cd2
print("vida do charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Charmander use Flametower!!")
vida_shiny_tentacool -= atk_charmander_cd2
print("Vida do Shiny tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <= 0:
print("Shiny Tentacool,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_charmander -= atk_tentacool_cd2
print("vida do charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Charmander use FireBlast!!")
vida_shiny_tentacool -= atk_charmander_cd3
print("Vida do Shiny Tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
print("Shiny Tentacool,Morreu")
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
print("----------------")
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_charmander -= atk_tentacool_cd2
print("vida do charmander",vida_charmander)
#POTIONS MARKET
if vida_charmander <=0:
print()
print("Seu Charmander Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_charmander += Porcao
print("Seu charmander Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
#Squirtle
if chart == 2 and chart1 == 1: #SQUIRTLE X GEODUDE
print("---------------------")
print("Squirtle,Eu escolho você")
print()
print("Digite (1)-para usar Bubles,(2)-para usar Warteball,(3)-para usar Blubleam")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Squirtle,use Bubles")
vida_geodude -= atk_squirte_cd1
print("Vida do Geodude",vida_geodude)
if vida_geodude <= 0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude,Contra-Ataca")
vida_squirte -= atk_geodude_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Squirtle,use Warteball")
vida_geodude -= atk_squirte_cd2
print("Vida do Geodude",vida_geodude)
if vida_geodude <= 0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude,Contra-Ataca")
vida_squirte -= atk_geodude_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Squirtle,use Blubleam")
vida_geodude -= atk_squirte_cd3
print("Vida do Geodude",vida_geodude)
if vida_geodude <= 0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Charmander use Ember!!")
player_inimigo -= atk_charmander_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude,Contra-Ataca")
vida_squirte -= atk_geodude_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
if chart == 2 and chart1 == 2: #SQUIRTLE X SHINY HORSEA
print("---------------------")
print("Squirtle,Eu escolho você")
print()
print("Digite (1)-para usar Bubles,(2)-para usar Warteball,(3)-para usar Blubleam")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Squirtle,use Bubbles")
vida_shiny_horsea -= atk_squirte_cd1
print("Vida da Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbles!!")
player_inimigo -= atk_squirte_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea,Contra-Ataca")
vida_squirte -= atk_horsea_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Squirtle,use Warteball")
vida_shiny_horsea -= atk_squirte_cd2
print("Vida da Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Warteball !!")
player_inimigo -= atk_squirte_cd2
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea,Contra-Ataca")
vida_squirte -= atk_horsea_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Squirtle,use Bubbleam")
vida_shiny_horsea -= atk_squirte_cd3
print("Vida da Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbleam !!")
player_inimigo -= atk_squirte_cd3
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea,Contra-Ataca")
vida_squirte -= atk_horsea_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
if chart == 2 and chart1 == 3: # SQUIRTLE X GOLDEN
print("---------------------")
print("Squirtle,Eu escolho você")
print()
print("Digite (1)-para usar Bubles,(2)-para usar Warteball,(3)-para usar Blubleam")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Squirtle,use Bubbles")
vida_golden -= atk_squirte_cd1
print("Vida do Golden",vida_golden)
if vida_golden <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbles !!")
player_inimigo -= atk_squirte_cd1
print("Vida do Seu inimigo",player_inimigo)
if player_inimigo <= 0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print()
print("Golden,Contra-Ataca")
vida_squirte -= atk_golden_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Squirtle,use Warteball")
vida_golden -= atk_squirte_cd2
print("Vida do Golden",vida_golden)
if vida_golden <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Warteball")
player_inimigo -= atk_squirte_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print()
print("Golden,Contra-Ataca")
vida_squirte -= atk_golden_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Squirtle,use Bubbleam")
vida_golden -= atk_squirte_cd3
print("Vida do Golden",vida_golden)
if vida_golden <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Warteball")
player_inimigo -= atk_squirte_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print()
print("Golden,Contra-Ataca")
vida_squirte -= atk_golden_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
if chart == 2 and chart1 == 4: # SQUIRTLE X VULPIX
print("---------------------")
print("Squirtle,Eu escolho você")
print()
print("Digite (1)-para usar Bubles,(2)-para usar Warteball,(3)-para usar Blubleam")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Squirtle use Bubbles")
vida_vulpix -= atk_squirte_cd1
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbles")
player_inimigo -= atk_squirte_cd1
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print()
print("Golden,Contra-Ataca")
vida_squirte -= atk_vulpix_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Squirtle use Warteball")
vida_vulpix -= atk_squirte_cd2
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Warteball")
player_inimigo -= atk_squirte_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print()
print("Golden,Contra-Ataca")
vida_squirte -= atk_vulpix_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Squirtle use Bubbleam")
vida_vulpix -= atk_squirte_cd3
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbleam")
player_inimigo -= atk_squirte_cd3
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print()
print("Golden,Contra-Ataca")
vida_squirte -= atk_vulpix_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
if chart == 2 and chart1 == 5: #SQUIRTLE X ODDISH
print("---------------------")
print("Squirtle,Eu escolho você")
print()
print("Digite (1)-para usar Bubles,(2)-para usar Warteball,(3)-para usar Blubleam")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Squirtle , use Bubbles")
vida_oddish -= atk_squirte_cd1
print("Vida do Oddish",vida_oddish)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbles")
player_inimigo -= atk_squirte_cd1
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_squirte -= atk_oddish_cd2
print("Vida do Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Squirtle , use Warteball")
vida_oddish -= atk_squirte_cd2
print("Vida do Oddish",vida_oddish)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Warteball")
player_inimigo -= atk_squirte_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_squirte -= atk_oddish_cd2
print("Vida do Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res ==3:
print("Squirtle , use Bubbleam")
vida_oddish -= atk_squirte_cd1
print("Vida do Oddish",vida_oddish)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbleam")
player_inimigo -= atk_squirte_cd3
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_squirte -= atk_oddish_cd2
print("Vida do Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
if chart == 2 and chart1 == 6: #SQUIRTLE X SHINY TENTACOOL
print("---------------------")
print("Squirtle,Eu escolho você")
print()
print("Digite (1)-para usar Bubles,(2)-para usar Warteball,(3)-para usar Blubleam")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Squirtle,use Bubbles")
vida_shiny_tentacool -= atk_squirte_cd1
print("Vida do Shiny Tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbles")
player_inimigo -= atk_squirte_cd1
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_squirte -= atk_tentacool_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Squirte, use Warteball")
vida_shiny_tentacool -= atk_squirte_cd2
print("Vida do Shiny Tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Warteball")
player_inimigo -= atk_squirte_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_squirte -= atk_tentacool_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Squirtle,use Bubbleam")
vida_shiny_tentacool -= atk_squirte_cd3
print("Vida do Shiny Tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Squirtle use Bubbleam")
player_inimigo -= atk_squirte_cd3
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_squirte -= atk_tentacool_cd2
print("Vida do seu Squirtle",vida_squirte)
#POTIONS MARKET
if vida_squirte <=0:
print()
print("Seu Squirtle Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_squirte += Porcao
print("Seu squirtle Foi curado ,Life Atual",vida_charmander)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
#Bulbasaur
if chart == 3 and chart1 == 1: #BUBALSAUR X GEODUDE
print("---------------------")
print("Bulbasaur,Eu escolho você")
print()
print("Digite (1)-para usar WineVip,(2)-para usar Razor Leaf,(3)-para usar Leaf Store")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Bulbasaur, use WineVip")
vida_geodude -= atk_bulbarsaur_cd1
print("Vida do Geodude",vida_geodude)
if vida_geodude <= 0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbasaur use Wine Vip")
player_inimigo -= atk_bulbarsaur_cd1
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude ,Contra-Ataca")
vida_bulbarsaur -= atk_geodude_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Bulbarsaur , use Razor Leaf")
vida_geodude -= atk_bulbarsaur_cd2
print("Vida do Geodude",vida_geodude)
if vida_geodude <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbasaur use Razor Leaf")
player_inimigo -= atk_bulbarsaur_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude ,Contra-Ataca")
vida_bulbarsaur -= atk_geodude_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur<=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res ==3:
print("Bulbarsaur, use Leaf Store")
vida_geodude -= atk_bulbarsaur_cd3
print("Vida do Geodude",vida_geodude)
if vida_geodude <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbasaur use Leaf Store")
player_inimigo -= atk_bulbarsaur_cd3
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Geodude ,Contra-Ataca")
vida_bulbarsaur -= atk_geodude_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur<=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_geodude_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
#Bulbarsaur
if chart == 3 and chart1 == 2: #BULBASAUR X SHINY HORSEA
print("---------------------")
print("Bulbasaur,Eu escolho você")
print()
print("Digite (1)-para usar WineVip,(2)-para usar Razor Leaf,(3)-para usar Leaf Store")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Bulbarsaur use WineVip")
vida_shiny_horsea -= atk_bulbarsaur_cd1
print("Vida da Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbasaur use WineVip")
player_inimigo -= atk_bulbarsaur_cd1
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea ,Contra-Ataca")
vida_bulbarsaur -= atk_horsea_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Bulbarsaur use RazorLeaf")
vida_shiny_horsea -= atk_bulbarsaur_cd2
print("Vida da Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbasaur use Razor Leaf")
player_inimigo -= atk_bulbarsaur_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea ,Contra-Ataca")
vida_bulbarsaur -= atk_horsea_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Bulbarsaur use Leaf Store")
vida_shiny_horsea -= atk_bulbarsaur_cd3
print("Vida da Shiny Horsea",vida_shiny_horsea)
if vida_shiny_horsea <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbasaur use Leaf Store")
player_inimigo -= atk_bulbarsaur_cd3
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Shiny Horsea ,Contra-Ataca")
vida_bulbarsaur -= atk_horsea_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_horsea_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
#BULBASAUR
if chart == 3 and chart1 == 3: #BULBASAUR X GOLDEN
print("---------------------")
print("Bulbasaur,Eu escolho você")
print()
print("Digite (1)-para usar WineVip,(2)-para usar Razor Leaf,(3)-para usar Leaf Store")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Bulbarsaur,Use WineVip")
vida_golden -= atk_bulbarsaur_cd1
print("Vida do Golden",vida_golden)
if vida_golden <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbarsaur use WineVip")
player_inimigo -= atk_bulbarsaur_cd1
print("Vida do Seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Golden,Contra-Ataca")
vida_bulbarsaur -= atk_golden_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Bulbarsaur,Use Razor Leaf")
vida_golden -= atk_bulbarsaur_cd2
print("Vida do Golden",vida_golden)
if vida_golden <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbarsaur use Razor Leaf")
player_inimigo -= atk_bulbarsaur_cd2
print("Vida do Seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Golden,Contra-Ataca")
vida_bulbarsaur -= atk_golden_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Bulbarsaur,Use Leaf Store")
vida_golden -= atk_bulbarsaur_cd3
print("Vida do Golden",vida_golden)
if vida_golden <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke!")
print()
print("Bulbarsaur use Leaf Store")
player_inimigo -= atk_bulbarsaur_cd3
print("Vida do Seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Golden,Contra-Ataca")
vida_bulbarsaur -= atk_golden_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_squirtle <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_golden_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
#Bulbasaur
if chart == 3 and chart1 == 4: #BULBASAUR X VULPIX
print("---------------------")
print("Bulbasaur,Eu escolho você")
print()
print("Digite (1)-para usar WineVip,(2)-para usar Razor Leaf,(3)-para usar Leaf Store")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Bulbarsaur, use WineVip")
vida_vulpix -= atk_bulbarsaur_cd1
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke ")
print()
print("Bulbasaur use WineVip")
player_inimigo -= atk_bulbarsaur_cd1
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Vulpix,Contra-Ataca")
vida_bulbarsaur -= atk_vulpix_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Bulbarsaur, use Razor Leaf")
vida_vulpix -= atk_bulbarsaur_cd2
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke ")
print()
print("Bulbasaur use Razor Leaf")
player_inimigo -= atk_bulbarsaur_cd2
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Vulpix,Contra-Ataca")
vida_bulbarsaur -= atk_vulpix_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_squirtle <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Bulbarsaur, use Leaf Store")
vida_vulpix -= atk_bulbarsaur_cd3
print("Vida do Vulpix",vida_vulpix)
if vida_vulpix <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke ")
print()
print("Bulbasaur use Leaf Store")
player_inimigo -= atk_bulbarsaur_cd3
print("Vida do seu Inimigo",player_inimigo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Inimigo",player_inimigo)
break
except:
print("Deseja matar outro inimigo?")
print()
print("Vulpix,Contra-Ataca")
vida_bulbarsaur -= atk_vulpix_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_vulpix_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
#bulbasaur
if chart == 3 and chart1 == 5: #BULBASAUR X ODDISH
print("---------------------")
print("Bulbasaur,Eu escolho você")
print()
print("Digite (1)-para usar WineVip,(2)-para usar Razor Leaf,(3)-para usar Leaf Store")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Bulbarsaur,use WineVip")
vida_oddish -= atk_bulbarsaur_cd1
print("Vida do Oddish",vida_oddish)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke")
print()
print("Bulbasaur, use WineVip")
player_inimigo -= atk_bulbarsaur_cd1
print("Vida do Seu Inimigo",player_inimgo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Seu Inimigo",player_inimigo)
break
except:
print("Deseja matar outro Inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_bulbarsaur -= atk_oddish_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Bulbarsaur,use Razor Leaf")
vida_oddish -= atk_bulbarsaur_cd2
print("Vida do Oddish",vida_oddish)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke")
print()
print("Bulbasaur, use Razor Leaf")
player_inimigo -= atk_bulbarsaur_cd2
print("Vida do Seu Inimigo",player_inimgo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Seu Inimigo",player_inimigo)
break
except:
print("Deseja matar outro Inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_bulbarsaur -= atk_oddish_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Bulbarsaur,use Leaf Store")
vida_oddish -= atk_bulbarsaur_cd3
print("Vida do Oddish",vida_oddish)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke")
print()
print("Bulbasaur, use Leaf Store")
player_inimigo -= atk_bulbarsaur_cd3
print("Vida do Seu Inimigo",player_inimgo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Seu Inimigo",player_inimigo)
break
except:
print("Deseja matar outro Inimigo?")
print()
print("Oddish,Contra-Ataca")
vida_bulbarsaur -= atk_oddish_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_oddish_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
if chart == 3 and chart1 == 6: #BULBASAUR X SHINY TENTACOOL
print("---------------------")
print("Bulbasaur,Eu escolho você")
print()
print("Digite (1)-para usar WineVip,(2)-para usar Razor Leaf,(3)-para usar Leaf Store")
res = int(input("(1),(2),(3): "))
if res == 1:
print("Bulbarsaur,use WineVip")
vida_shiny_tentacool -= atk_bulbarsaur_cd1
print("Vida do Shiny Tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke")
print()
print("Bulbasaur, use WineVip")
player_inimigo -= atk_bulbarsaur_cd1
print("Vida do Seu Inimigo",player_inimgo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Seu Inimigo",player_inimigo)
break
except:
print("Deseja matar outro Inimigo?")
print()
print("Shiny tentacool,Contra-Ataca")
vida_bulbarsaur -= atk_tentacool_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 2:
print("Bulbarsaur,use Razor Leaf")
vida_shiny_tentacool -= atk_bulbarsaur_cd2
print("Vida do Shiny tentacool",vida_shiny_tentacool)
if vida_shiny_tentacool <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke")
print()
print("Bulbasaur, use Razor Leaf")
player_inimigo -= atk_bulbarsaur_cd2
print("Vida do Seu Inimigo",player_inimgo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Seu Inimigo",player_inimigo)
break
except:
print("Deseja matar outro Inimigo?")
print()
print("Shiny tentacool,Contra-Ataca")
vida_bulbarsaur -= atk_tentacool_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaure <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
elif res == 3:
print("Bulbarsaur,use Leaf Store")
vida_shiny_tentacool -= atk_bulbarsaur_cd3
print("Vida do Shiny tentacool",vida_shiny_tentacool)
if vida_oddish <=0:
try:
print("Voce tem a chance de matar seu inimigo!!")
print("Antes que ele coloque outro poke")
print()
print("Bulbasaur, use Leaf Store")
player_inimigo -= atk_bulbarsaur_cd3
print("Vida do Seu Inimigo",player_inimgo)
if player_inimigo <=0:
print("Voce o Derrotou")
print("Vida do Seu Inimigo",player_inimigo)
break
except:
print("Deseja matar outro Inimigo?")
print()
print("Shiny Tentacool,Contra-Ataca")
vida_bulbarsaur -= atk_tentacool_cd2
print("Vida do seu Bulbarsaur",vida_bulbarsaur)
#POTIONS MARKET
if vida_bulbarsaur <=0:
print()
print("Seu Bulbasaur Morreu")
fly = input("Deseja comprar Potions: [S-sim/N-nao]: ")
if fly == "S" or fly == "sim":
from NPCS import NPC
vida_bulbarsaur += Porcao
print("Seu Bulbasaur Foi curado ,Life Atual",vida_bulbarsaur)
else:
print("Voce esta Vulneravel aos ataques!!")
player_vida -= atk_tentacool_cd2
print("OHH NAOOO!!")
print("Voce foi atacado sua é vida é de:",player_vida)
if player_vida <=0:
print("END OF GAME")
print()
print("VOCE PERDEU!!")
break
def main():
jogo()
main()
| 45.32915
| 137
| 0.397973
| 10,625
| 126,423
| 4.611765
| 0.017976
| 0.049408
| 0.046918
| 0.029714
| 0.95798
| 0.94849
| 0.937347
| 0.93602
| 0.931878
| 0.931878
| 0
| 0.011527
| 0.523789
| 126,423
| 2,788
| 138
| 45.345409
| 0.802372
| 0.014649
| 0
| 0.941677
| 0
| 0.002554
| 0.229283
| 0.003698
| 0
| 0
| 0
| 0
| 0
| 1
| 0.000851
| false
| 0
| 0.02384
| 0
| 0.024691
| 0.556833
| 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
| 1
|
0
| 9
|
49c6d1c0184e26d7d0da34d808818001dcc8bf3a
| 46,512
|
py
|
Python
|
sdk/python/pulumi_azure/synapse/spark_pool.py
|
henriktao/pulumi-azure
|
f1cbcf100b42b916da36d8fe28be3a159abaf022
|
[
"ECL-2.0",
"Apache-2.0"
] | 109
|
2018-06-18T00:19:44.000Z
|
2022-02-20T05:32:57.000Z
|
sdk/python/pulumi_azure/synapse/spark_pool.py
|
henriktao/pulumi-azure
|
f1cbcf100b42b916da36d8fe28be3a159abaf022
|
[
"ECL-2.0",
"Apache-2.0"
] | 663
|
2018-06-18T21:08:46.000Z
|
2022-03-31T20:10:11.000Z
|
sdk/python/pulumi_azure/synapse/spark_pool.py
|
henriktao/pulumi-azure
|
f1cbcf100b42b916da36d8fe28be3a159abaf022
|
[
"ECL-2.0",
"Apache-2.0"
] | 41
|
2018-07-19T22:37:38.000Z
|
2022-03-14T10:56:26.000Z
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from . import outputs
from ._inputs import *
__all__ = ['SparkPoolArgs', 'SparkPool']
@pulumi.input_type
class SparkPoolArgs:
def __init__(__self__, *,
node_size: pulumi.Input[str],
node_size_family: pulumi.Input[str],
synapse_workspace_id: pulumi.Input[str],
auto_pause: Optional[pulumi.Input['SparkPoolAutoPauseArgs']] = None,
auto_scale: Optional[pulumi.Input['SparkPoolAutoScaleArgs']] = None,
cache_size: Optional[pulumi.Input[int]] = None,
compute_isolation_enabled: Optional[pulumi.Input[bool]] = None,
dynamic_executor_allocation_enabled: Optional[pulumi.Input[bool]] = None,
library_requirement: Optional[pulumi.Input['SparkPoolLibraryRequirementArgs']] = None,
name: Optional[pulumi.Input[str]] = None,
node_count: Optional[pulumi.Input[int]] = None,
session_level_packages_enabled: Optional[pulumi.Input[bool]] = None,
spark_config: Optional[pulumi.Input['SparkPoolSparkConfigArgs']] = None,
spark_events_folder: Optional[pulumi.Input[str]] = None,
spark_log_folder: Optional[pulumi.Input[str]] = None,
spark_version: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
The set of arguments for constructing a SparkPool resource.
:param pulumi.Input[str] node_size: The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
:param pulumi.Input[str] node_size_family: The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
:param pulumi.Input[str] synapse_workspace_id: The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input['SparkPoolAutoPauseArgs'] auto_pause: An `auto_pause` block as defined below.
:param pulumi.Input['SparkPoolAutoScaleArgs'] auto_scale: An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[int] cache_size: The cache size in the Spark Pool.
:param pulumi.Input[bool] compute_isolation_enabled: Indicates whether compute isolation is enabled or not. Defaults to `false`.
:param pulumi.Input[bool] dynamic_executor_allocation_enabled: Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
:param pulumi.Input['SparkPoolLibraryRequirementArgs'] library_requirement: A `library_requirement` block as defined below.
:param pulumi.Input[str] name: The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[int] node_count: The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[bool] session_level_packages_enabled: Indicates whether session level packages are enabled or not. Defaults to `false`.
:param pulumi.Input['SparkPoolSparkConfigArgs'] spark_config: A `spark_config` block as defined below.
:param pulumi.Input[str] spark_events_folder: The Spark events folder. Defaults to `/events`.
:param pulumi.Input[str] spark_log_folder: The default folder where Spark logs will be written. Defaults to `/logs`.
:param pulumi.Input[str] spark_version: The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
pulumi.set(__self__, "node_size", node_size)
pulumi.set(__self__, "node_size_family", node_size_family)
pulumi.set(__self__, "synapse_workspace_id", synapse_workspace_id)
if auto_pause is not None:
pulumi.set(__self__, "auto_pause", auto_pause)
if auto_scale is not None:
pulumi.set(__self__, "auto_scale", auto_scale)
if cache_size is not None:
pulumi.set(__self__, "cache_size", cache_size)
if compute_isolation_enabled is not None:
pulumi.set(__self__, "compute_isolation_enabled", compute_isolation_enabled)
if dynamic_executor_allocation_enabled is not None:
pulumi.set(__self__, "dynamic_executor_allocation_enabled", dynamic_executor_allocation_enabled)
if library_requirement is not None:
pulumi.set(__self__, "library_requirement", library_requirement)
if name is not None:
pulumi.set(__self__, "name", name)
if node_count is not None:
pulumi.set(__self__, "node_count", node_count)
if session_level_packages_enabled is not None:
pulumi.set(__self__, "session_level_packages_enabled", session_level_packages_enabled)
if spark_config is not None:
pulumi.set(__self__, "spark_config", spark_config)
if spark_events_folder is not None:
pulumi.set(__self__, "spark_events_folder", spark_events_folder)
if spark_log_folder is not None:
pulumi.set(__self__, "spark_log_folder", spark_log_folder)
if spark_version is not None:
pulumi.set(__self__, "spark_version", spark_version)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="nodeSize")
def node_size(self) -> pulumi.Input[str]:
"""
The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
"""
return pulumi.get(self, "node_size")
@node_size.setter
def node_size(self, value: pulumi.Input[str]):
pulumi.set(self, "node_size", value)
@property
@pulumi.getter(name="nodeSizeFamily")
def node_size_family(self) -> pulumi.Input[str]:
"""
The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
"""
return pulumi.get(self, "node_size_family")
@node_size_family.setter
def node_size_family(self, value: pulumi.Input[str]):
pulumi.set(self, "node_size_family", value)
@property
@pulumi.getter(name="synapseWorkspaceId")
def synapse_workspace_id(self) -> pulumi.Input[str]:
"""
The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
"""
return pulumi.get(self, "synapse_workspace_id")
@synapse_workspace_id.setter
def synapse_workspace_id(self, value: pulumi.Input[str]):
pulumi.set(self, "synapse_workspace_id", value)
@property
@pulumi.getter(name="autoPause")
def auto_pause(self) -> Optional[pulumi.Input['SparkPoolAutoPauseArgs']]:
"""
An `auto_pause` block as defined below.
"""
return pulumi.get(self, "auto_pause")
@auto_pause.setter
def auto_pause(self, value: Optional[pulumi.Input['SparkPoolAutoPauseArgs']]):
pulumi.set(self, "auto_pause", value)
@property
@pulumi.getter(name="autoScale")
def auto_scale(self) -> Optional[pulumi.Input['SparkPoolAutoScaleArgs']]:
"""
An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
"""
return pulumi.get(self, "auto_scale")
@auto_scale.setter
def auto_scale(self, value: Optional[pulumi.Input['SparkPoolAutoScaleArgs']]):
pulumi.set(self, "auto_scale", value)
@property
@pulumi.getter(name="cacheSize")
def cache_size(self) -> Optional[pulumi.Input[int]]:
"""
The cache size in the Spark Pool.
"""
return pulumi.get(self, "cache_size")
@cache_size.setter
def cache_size(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "cache_size", value)
@property
@pulumi.getter(name="computeIsolationEnabled")
def compute_isolation_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether compute isolation is enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "compute_isolation_enabled")
@compute_isolation_enabled.setter
def compute_isolation_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "compute_isolation_enabled", value)
@property
@pulumi.getter(name="dynamicExecutorAllocationEnabled")
def dynamic_executor_allocation_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "dynamic_executor_allocation_enabled")
@dynamic_executor_allocation_enabled.setter
def dynamic_executor_allocation_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "dynamic_executor_allocation_enabled", value)
@property
@pulumi.getter(name="libraryRequirement")
def library_requirement(self) -> Optional[pulumi.Input['SparkPoolLibraryRequirementArgs']]:
"""
A `library_requirement` block as defined below.
"""
return pulumi.get(self, "library_requirement")
@library_requirement.setter
def library_requirement(self, value: Optional[pulumi.Input['SparkPoolLibraryRequirementArgs']]):
pulumi.set(self, "library_requirement", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="nodeCount")
def node_count(self) -> Optional[pulumi.Input[int]]:
"""
The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
"""
return pulumi.get(self, "node_count")
@node_count.setter
def node_count(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "node_count", value)
@property
@pulumi.getter(name="sessionLevelPackagesEnabled")
def session_level_packages_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether session level packages are enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "session_level_packages_enabled")
@session_level_packages_enabled.setter
def session_level_packages_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "session_level_packages_enabled", value)
@property
@pulumi.getter(name="sparkConfig")
def spark_config(self) -> Optional[pulumi.Input['SparkPoolSparkConfigArgs']]:
"""
A `spark_config` block as defined below.
"""
return pulumi.get(self, "spark_config")
@spark_config.setter
def spark_config(self, value: Optional[pulumi.Input['SparkPoolSparkConfigArgs']]):
pulumi.set(self, "spark_config", value)
@property
@pulumi.getter(name="sparkEventsFolder")
def spark_events_folder(self) -> Optional[pulumi.Input[str]]:
"""
The Spark events folder. Defaults to `/events`.
"""
return pulumi.get(self, "spark_events_folder")
@spark_events_folder.setter
def spark_events_folder(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "spark_events_folder", value)
@property
@pulumi.getter(name="sparkLogFolder")
def spark_log_folder(self) -> Optional[pulumi.Input[str]]:
"""
The default folder where Spark logs will be written. Defaults to `/logs`.
"""
return pulumi.get(self, "spark_log_folder")
@spark_log_folder.setter
def spark_log_folder(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "spark_log_folder", value)
@property
@pulumi.getter(name="sparkVersion")
def spark_version(self) -> Optional[pulumi.Input[str]]:
"""
The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
"""
return pulumi.get(self, "spark_version")
@spark_version.setter
def spark_version(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "spark_version", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
@pulumi.input_type
class _SparkPoolState:
def __init__(__self__, *,
auto_pause: Optional[pulumi.Input['SparkPoolAutoPauseArgs']] = None,
auto_scale: Optional[pulumi.Input['SparkPoolAutoScaleArgs']] = None,
cache_size: Optional[pulumi.Input[int]] = None,
compute_isolation_enabled: Optional[pulumi.Input[bool]] = None,
dynamic_executor_allocation_enabled: Optional[pulumi.Input[bool]] = None,
library_requirement: Optional[pulumi.Input['SparkPoolLibraryRequirementArgs']] = None,
name: Optional[pulumi.Input[str]] = None,
node_count: Optional[pulumi.Input[int]] = None,
node_size: Optional[pulumi.Input[str]] = None,
node_size_family: Optional[pulumi.Input[str]] = None,
session_level_packages_enabled: Optional[pulumi.Input[bool]] = None,
spark_config: Optional[pulumi.Input['SparkPoolSparkConfigArgs']] = None,
spark_events_folder: Optional[pulumi.Input[str]] = None,
spark_log_folder: Optional[pulumi.Input[str]] = None,
spark_version: Optional[pulumi.Input[str]] = None,
synapse_workspace_id: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None):
"""
Input properties used for looking up and filtering SparkPool resources.
:param pulumi.Input['SparkPoolAutoPauseArgs'] auto_pause: An `auto_pause` block as defined below.
:param pulumi.Input['SparkPoolAutoScaleArgs'] auto_scale: An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[int] cache_size: The cache size in the Spark Pool.
:param pulumi.Input[bool] compute_isolation_enabled: Indicates whether compute isolation is enabled or not. Defaults to `false`.
:param pulumi.Input[bool] dynamic_executor_allocation_enabled: Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
:param pulumi.Input['SparkPoolLibraryRequirementArgs'] library_requirement: A `library_requirement` block as defined below.
:param pulumi.Input[str] name: The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[int] node_count: The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[str] node_size: The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
:param pulumi.Input[str] node_size_family: The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
:param pulumi.Input[bool] session_level_packages_enabled: Indicates whether session level packages are enabled or not. Defaults to `false`.
:param pulumi.Input['SparkPoolSparkConfigArgs'] spark_config: A `spark_config` block as defined below.
:param pulumi.Input[str] spark_events_folder: The Spark events folder. Defaults to `/events`.
:param pulumi.Input[str] spark_log_folder: The default folder where Spark logs will be written. Defaults to `/logs`.
:param pulumi.Input[str] spark_version: The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
:param pulumi.Input[str] synapse_workspace_id: The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
if auto_pause is not None:
pulumi.set(__self__, "auto_pause", auto_pause)
if auto_scale is not None:
pulumi.set(__self__, "auto_scale", auto_scale)
if cache_size is not None:
pulumi.set(__self__, "cache_size", cache_size)
if compute_isolation_enabled is not None:
pulumi.set(__self__, "compute_isolation_enabled", compute_isolation_enabled)
if dynamic_executor_allocation_enabled is not None:
pulumi.set(__self__, "dynamic_executor_allocation_enabled", dynamic_executor_allocation_enabled)
if library_requirement is not None:
pulumi.set(__self__, "library_requirement", library_requirement)
if name is not None:
pulumi.set(__self__, "name", name)
if node_count is not None:
pulumi.set(__self__, "node_count", node_count)
if node_size is not None:
pulumi.set(__self__, "node_size", node_size)
if node_size_family is not None:
pulumi.set(__self__, "node_size_family", node_size_family)
if session_level_packages_enabled is not None:
pulumi.set(__self__, "session_level_packages_enabled", session_level_packages_enabled)
if spark_config is not None:
pulumi.set(__self__, "spark_config", spark_config)
if spark_events_folder is not None:
pulumi.set(__self__, "spark_events_folder", spark_events_folder)
if spark_log_folder is not None:
pulumi.set(__self__, "spark_log_folder", spark_log_folder)
if spark_version is not None:
pulumi.set(__self__, "spark_version", spark_version)
if synapse_workspace_id is not None:
pulumi.set(__self__, "synapse_workspace_id", synapse_workspace_id)
if tags is not None:
pulumi.set(__self__, "tags", tags)
@property
@pulumi.getter(name="autoPause")
def auto_pause(self) -> Optional[pulumi.Input['SparkPoolAutoPauseArgs']]:
"""
An `auto_pause` block as defined below.
"""
return pulumi.get(self, "auto_pause")
@auto_pause.setter
def auto_pause(self, value: Optional[pulumi.Input['SparkPoolAutoPauseArgs']]):
pulumi.set(self, "auto_pause", value)
@property
@pulumi.getter(name="autoScale")
def auto_scale(self) -> Optional[pulumi.Input['SparkPoolAutoScaleArgs']]:
"""
An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
"""
return pulumi.get(self, "auto_scale")
@auto_scale.setter
def auto_scale(self, value: Optional[pulumi.Input['SparkPoolAutoScaleArgs']]):
pulumi.set(self, "auto_scale", value)
@property
@pulumi.getter(name="cacheSize")
def cache_size(self) -> Optional[pulumi.Input[int]]:
"""
The cache size in the Spark Pool.
"""
return pulumi.get(self, "cache_size")
@cache_size.setter
def cache_size(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "cache_size", value)
@property
@pulumi.getter(name="computeIsolationEnabled")
def compute_isolation_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether compute isolation is enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "compute_isolation_enabled")
@compute_isolation_enabled.setter
def compute_isolation_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "compute_isolation_enabled", value)
@property
@pulumi.getter(name="dynamicExecutorAllocationEnabled")
def dynamic_executor_allocation_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "dynamic_executor_allocation_enabled")
@dynamic_executor_allocation_enabled.setter
def dynamic_executor_allocation_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "dynamic_executor_allocation_enabled", value)
@property
@pulumi.getter(name="libraryRequirement")
def library_requirement(self) -> Optional[pulumi.Input['SparkPoolLibraryRequirementArgs']]:
"""
A `library_requirement` block as defined below.
"""
return pulumi.get(self, "library_requirement")
@library_requirement.setter
def library_requirement(self, value: Optional[pulumi.Input['SparkPoolLibraryRequirementArgs']]):
pulumi.set(self, "library_requirement", value)
@property
@pulumi.getter
def name(self) -> Optional[pulumi.Input[str]]:
"""
The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="nodeCount")
def node_count(self) -> Optional[pulumi.Input[int]]:
"""
The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
"""
return pulumi.get(self, "node_count")
@node_count.setter
def node_count(self, value: Optional[pulumi.Input[int]]):
pulumi.set(self, "node_count", value)
@property
@pulumi.getter(name="nodeSize")
def node_size(self) -> Optional[pulumi.Input[str]]:
"""
The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
"""
return pulumi.get(self, "node_size")
@node_size.setter
def node_size(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "node_size", value)
@property
@pulumi.getter(name="nodeSizeFamily")
def node_size_family(self) -> Optional[pulumi.Input[str]]:
"""
The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
"""
return pulumi.get(self, "node_size_family")
@node_size_family.setter
def node_size_family(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "node_size_family", value)
@property
@pulumi.getter(name="sessionLevelPackagesEnabled")
def session_level_packages_enabled(self) -> Optional[pulumi.Input[bool]]:
"""
Indicates whether session level packages are enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "session_level_packages_enabled")
@session_level_packages_enabled.setter
def session_level_packages_enabled(self, value: Optional[pulumi.Input[bool]]):
pulumi.set(self, "session_level_packages_enabled", value)
@property
@pulumi.getter(name="sparkConfig")
def spark_config(self) -> Optional[pulumi.Input['SparkPoolSparkConfigArgs']]:
"""
A `spark_config` block as defined below.
"""
return pulumi.get(self, "spark_config")
@spark_config.setter
def spark_config(self, value: Optional[pulumi.Input['SparkPoolSparkConfigArgs']]):
pulumi.set(self, "spark_config", value)
@property
@pulumi.getter(name="sparkEventsFolder")
def spark_events_folder(self) -> Optional[pulumi.Input[str]]:
"""
The Spark events folder. Defaults to `/events`.
"""
return pulumi.get(self, "spark_events_folder")
@spark_events_folder.setter
def spark_events_folder(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "spark_events_folder", value)
@property
@pulumi.getter(name="sparkLogFolder")
def spark_log_folder(self) -> Optional[pulumi.Input[str]]:
"""
The default folder where Spark logs will be written. Defaults to `/logs`.
"""
return pulumi.get(self, "spark_log_folder")
@spark_log_folder.setter
def spark_log_folder(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "spark_log_folder", value)
@property
@pulumi.getter(name="sparkVersion")
def spark_version(self) -> Optional[pulumi.Input[str]]:
"""
The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
"""
return pulumi.get(self, "spark_version")
@spark_version.setter
def spark_version(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "spark_version", value)
@property
@pulumi.getter(name="synapseWorkspaceId")
def synapse_workspace_id(self) -> Optional[pulumi.Input[str]]:
"""
The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
"""
return pulumi.get(self, "synapse_workspace_id")
@synapse_workspace_id.setter
def synapse_workspace_id(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "synapse_workspace_id", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
"""
A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
return pulumi.get(self, "tags")
@tags.setter
def tags(self, value: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]):
pulumi.set(self, "tags", value)
class SparkPool(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
auto_pause: Optional[pulumi.Input[pulumi.InputType['SparkPoolAutoPauseArgs']]] = None,
auto_scale: Optional[pulumi.Input[pulumi.InputType['SparkPoolAutoScaleArgs']]] = None,
cache_size: Optional[pulumi.Input[int]] = None,
compute_isolation_enabled: Optional[pulumi.Input[bool]] = None,
dynamic_executor_allocation_enabled: Optional[pulumi.Input[bool]] = None,
library_requirement: Optional[pulumi.Input[pulumi.InputType['SparkPoolLibraryRequirementArgs']]] = None,
name: Optional[pulumi.Input[str]] = None,
node_count: Optional[pulumi.Input[int]] = None,
node_size: Optional[pulumi.Input[str]] = None,
node_size_family: Optional[pulumi.Input[str]] = None,
session_level_packages_enabled: Optional[pulumi.Input[bool]] = None,
spark_config: Optional[pulumi.Input[pulumi.InputType['SparkPoolSparkConfigArgs']]] = None,
spark_events_folder: Optional[pulumi.Input[str]] = None,
spark_log_folder: Optional[pulumi.Input[str]] = None,
spark_version: Optional[pulumi.Input[str]] = None,
synapse_workspace_id: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
"""
Manages a Synapse Spark Pool.
## Import
Synapse Spark Pool can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:synapse/sparkPool:SparkPool example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Synapse/workspaces/workspace1/bigDataPools/sparkPool1
```
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['SparkPoolAutoPauseArgs']] auto_pause: An `auto_pause` block as defined below.
:param pulumi.Input[pulumi.InputType['SparkPoolAutoScaleArgs']] auto_scale: An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[int] cache_size: The cache size in the Spark Pool.
:param pulumi.Input[bool] compute_isolation_enabled: Indicates whether compute isolation is enabled or not. Defaults to `false`.
:param pulumi.Input[bool] dynamic_executor_allocation_enabled: Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
:param pulumi.Input[pulumi.InputType['SparkPoolLibraryRequirementArgs']] library_requirement: A `library_requirement` block as defined below.
:param pulumi.Input[str] name: The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[int] node_count: The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[str] node_size: The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
:param pulumi.Input[str] node_size_family: The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
:param pulumi.Input[bool] session_level_packages_enabled: Indicates whether session level packages are enabled or not. Defaults to `false`.
:param pulumi.Input[pulumi.InputType['SparkPoolSparkConfigArgs']] spark_config: A `spark_config` block as defined below.
:param pulumi.Input[str] spark_events_folder: The Spark events folder. Defaults to `/events`.
:param pulumi.Input[str] spark_log_folder: The default folder where Spark logs will be written. Defaults to `/logs`.
:param pulumi.Input[str] spark_version: The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
:param pulumi.Input[str] synapse_workspace_id: The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: SparkPoolArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Manages a Synapse Spark Pool.
## Import
Synapse Spark Pool can be imported using the `resource id`, e.g.
```sh
$ pulumi import azure:synapse/sparkPool:SparkPool example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/providers/Microsoft.Synapse/workspaces/workspace1/bigDataPools/sparkPool1
```
:param str resource_name: The name of the resource.
:param SparkPoolArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(SparkPoolArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
auto_pause: Optional[pulumi.Input[pulumi.InputType['SparkPoolAutoPauseArgs']]] = None,
auto_scale: Optional[pulumi.Input[pulumi.InputType['SparkPoolAutoScaleArgs']]] = None,
cache_size: Optional[pulumi.Input[int]] = None,
compute_isolation_enabled: Optional[pulumi.Input[bool]] = None,
dynamic_executor_allocation_enabled: Optional[pulumi.Input[bool]] = None,
library_requirement: Optional[pulumi.Input[pulumi.InputType['SparkPoolLibraryRequirementArgs']]] = None,
name: Optional[pulumi.Input[str]] = None,
node_count: Optional[pulumi.Input[int]] = None,
node_size: Optional[pulumi.Input[str]] = None,
node_size_family: Optional[pulumi.Input[str]] = None,
session_level_packages_enabled: Optional[pulumi.Input[bool]] = None,
spark_config: Optional[pulumi.Input[pulumi.InputType['SparkPoolSparkConfigArgs']]] = None,
spark_events_folder: Optional[pulumi.Input[str]] = None,
spark_log_folder: Optional[pulumi.Input[str]] = None,
spark_version: Optional[pulumi.Input[str]] = None,
synapse_workspace_id: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = SparkPoolArgs.__new__(SparkPoolArgs)
__props__.__dict__["auto_pause"] = auto_pause
__props__.__dict__["auto_scale"] = auto_scale
__props__.__dict__["cache_size"] = cache_size
__props__.__dict__["compute_isolation_enabled"] = compute_isolation_enabled
__props__.__dict__["dynamic_executor_allocation_enabled"] = dynamic_executor_allocation_enabled
__props__.__dict__["library_requirement"] = library_requirement
__props__.__dict__["name"] = name
__props__.__dict__["node_count"] = node_count
if node_size is None and not opts.urn:
raise TypeError("Missing required property 'node_size'")
__props__.__dict__["node_size"] = node_size
if node_size_family is None and not opts.urn:
raise TypeError("Missing required property 'node_size_family'")
__props__.__dict__["node_size_family"] = node_size_family
__props__.__dict__["session_level_packages_enabled"] = session_level_packages_enabled
__props__.__dict__["spark_config"] = spark_config
__props__.__dict__["spark_events_folder"] = spark_events_folder
__props__.__dict__["spark_log_folder"] = spark_log_folder
__props__.__dict__["spark_version"] = spark_version
if synapse_workspace_id is None and not opts.urn:
raise TypeError("Missing required property 'synapse_workspace_id'")
__props__.__dict__["synapse_workspace_id"] = synapse_workspace_id
__props__.__dict__["tags"] = tags
super(SparkPool, __self__).__init__(
'azure:synapse/sparkPool:SparkPool',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None,
auto_pause: Optional[pulumi.Input[pulumi.InputType['SparkPoolAutoPauseArgs']]] = None,
auto_scale: Optional[pulumi.Input[pulumi.InputType['SparkPoolAutoScaleArgs']]] = None,
cache_size: Optional[pulumi.Input[int]] = None,
compute_isolation_enabled: Optional[pulumi.Input[bool]] = None,
dynamic_executor_allocation_enabled: Optional[pulumi.Input[bool]] = None,
library_requirement: Optional[pulumi.Input[pulumi.InputType['SparkPoolLibraryRequirementArgs']]] = None,
name: Optional[pulumi.Input[str]] = None,
node_count: Optional[pulumi.Input[int]] = None,
node_size: Optional[pulumi.Input[str]] = None,
node_size_family: Optional[pulumi.Input[str]] = None,
session_level_packages_enabled: Optional[pulumi.Input[bool]] = None,
spark_config: Optional[pulumi.Input[pulumi.InputType['SparkPoolSparkConfigArgs']]] = None,
spark_events_folder: Optional[pulumi.Input[str]] = None,
spark_log_folder: Optional[pulumi.Input[str]] = None,
spark_version: Optional[pulumi.Input[str]] = None,
synapse_workspace_id: Optional[pulumi.Input[str]] = None,
tags: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None) -> 'SparkPool':
"""
Get an existing SparkPool resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[pulumi.InputType['SparkPoolAutoPauseArgs']] auto_pause: An `auto_pause` block as defined below.
:param pulumi.Input[pulumi.InputType['SparkPoolAutoScaleArgs']] auto_scale: An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[int] cache_size: The cache size in the Spark Pool.
:param pulumi.Input[bool] compute_isolation_enabled: Indicates whether compute isolation is enabled or not. Defaults to `false`.
:param pulumi.Input[bool] dynamic_executor_allocation_enabled: Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
:param pulumi.Input[pulumi.InputType['SparkPoolLibraryRequirementArgs']] library_requirement: A `library_requirement` block as defined below.
:param pulumi.Input[str] name: The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[int] node_count: The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
:param pulumi.Input[str] node_size: The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
:param pulumi.Input[str] node_size_family: The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
:param pulumi.Input[bool] session_level_packages_enabled: Indicates whether session level packages are enabled or not. Defaults to `false`.
:param pulumi.Input[pulumi.InputType['SparkPoolSparkConfigArgs']] spark_config: A `spark_config` block as defined below.
:param pulumi.Input[str] spark_events_folder: The Spark events folder. Defaults to `/events`.
:param pulumi.Input[str] spark_log_folder: The default folder where Spark logs will be written. Defaults to `/logs`.
:param pulumi.Input[str] spark_version: The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
:param pulumi.Input[str] synapse_workspace_id: The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
:param pulumi.Input[Mapping[str, pulumi.Input[str]]] tags: A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = _SparkPoolState.__new__(_SparkPoolState)
__props__.__dict__["auto_pause"] = auto_pause
__props__.__dict__["auto_scale"] = auto_scale
__props__.__dict__["cache_size"] = cache_size
__props__.__dict__["compute_isolation_enabled"] = compute_isolation_enabled
__props__.__dict__["dynamic_executor_allocation_enabled"] = dynamic_executor_allocation_enabled
__props__.__dict__["library_requirement"] = library_requirement
__props__.__dict__["name"] = name
__props__.__dict__["node_count"] = node_count
__props__.__dict__["node_size"] = node_size
__props__.__dict__["node_size_family"] = node_size_family
__props__.__dict__["session_level_packages_enabled"] = session_level_packages_enabled
__props__.__dict__["spark_config"] = spark_config
__props__.__dict__["spark_events_folder"] = spark_events_folder
__props__.__dict__["spark_log_folder"] = spark_log_folder
__props__.__dict__["spark_version"] = spark_version
__props__.__dict__["synapse_workspace_id"] = synapse_workspace_id
__props__.__dict__["tags"] = tags
return SparkPool(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter(name="autoPause")
def auto_pause(self) -> pulumi.Output[Optional['outputs.SparkPoolAutoPause']]:
"""
An `auto_pause` block as defined below.
"""
return pulumi.get(self, "auto_pause")
@property
@pulumi.getter(name="autoScale")
def auto_scale(self) -> pulumi.Output[Optional['outputs.SparkPoolAutoScale']]:
"""
An `auto_scale` block as defined below. Exactly one of `node_count` or `auto_scale` must be specified.
"""
return pulumi.get(self, "auto_scale")
@property
@pulumi.getter(name="cacheSize")
def cache_size(self) -> pulumi.Output[Optional[int]]:
"""
The cache size in the Spark Pool.
"""
return pulumi.get(self, "cache_size")
@property
@pulumi.getter(name="computeIsolationEnabled")
def compute_isolation_enabled(self) -> pulumi.Output[Optional[bool]]:
"""
Indicates whether compute isolation is enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "compute_isolation_enabled")
@property
@pulumi.getter(name="dynamicExecutorAllocationEnabled")
def dynamic_executor_allocation_enabled(self) -> pulumi.Output[Optional[bool]]:
"""
Indicates whether Dynamic Executor Allocation is enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "dynamic_executor_allocation_enabled")
@property
@pulumi.getter(name="libraryRequirement")
def library_requirement(self) -> pulumi.Output[Optional['outputs.SparkPoolLibraryRequirement']]:
"""
A `library_requirement` block as defined below.
"""
return pulumi.get(self, "library_requirement")
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
The name which should be used for this Synapse Spark Pool. Changing this forces a new Synapse Spark Pool to be created.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="nodeCount")
def node_count(self) -> pulumi.Output[Optional[int]]:
"""
The number of nodes in the Spark Pool. Exactly one of `node_count` or `auto_scale` must be specified.
"""
return pulumi.get(self, "node_count")
@property
@pulumi.getter(name="nodeSize")
def node_size(self) -> pulumi.Output[str]:
"""
The level of node in the Spark Pool. Possible value is `Small`, `Medium` and `Large`.
"""
return pulumi.get(self, "node_size")
@property
@pulumi.getter(name="nodeSizeFamily")
def node_size_family(self) -> pulumi.Output[str]:
"""
The kind of nodes that the Spark Pool provides. Possible value is `MemoryOptimized`.
"""
return pulumi.get(self, "node_size_family")
@property
@pulumi.getter(name="sessionLevelPackagesEnabled")
def session_level_packages_enabled(self) -> pulumi.Output[Optional[bool]]:
"""
Indicates whether session level packages are enabled or not. Defaults to `false`.
"""
return pulumi.get(self, "session_level_packages_enabled")
@property
@pulumi.getter(name="sparkConfig")
def spark_config(self) -> pulumi.Output[Optional['outputs.SparkPoolSparkConfig']]:
"""
A `spark_config` block as defined below.
"""
return pulumi.get(self, "spark_config")
@property
@pulumi.getter(name="sparkEventsFolder")
def spark_events_folder(self) -> pulumi.Output[Optional[str]]:
"""
The Spark events folder. Defaults to `/events`.
"""
return pulumi.get(self, "spark_events_folder")
@property
@pulumi.getter(name="sparkLogFolder")
def spark_log_folder(self) -> pulumi.Output[Optional[str]]:
"""
The default folder where Spark logs will be written. Defaults to `/logs`.
"""
return pulumi.get(self, "spark_log_folder")
@property
@pulumi.getter(name="sparkVersion")
def spark_version(self) -> pulumi.Output[Optional[str]]:
"""
The Apache Spark version. Possible values are `2.4` and `3.1`. Defaults to `2.4`.
"""
return pulumi.get(self, "spark_version")
@property
@pulumi.getter(name="synapseWorkspaceId")
def synapse_workspace_id(self) -> pulumi.Output[str]:
"""
The ID of the Synapse Workspace where the Synapse Spark Pool should exist. Changing this forces a new Synapse Spark Pool to be created.
"""
return pulumi.get(self, "synapse_workspace_id")
@property
@pulumi.getter
def tags(self) -> pulumi.Output[Optional[Mapping[str, str]]]:
"""
A mapping of tags which should be assigned to the Synapse Spark Pool.
"""
return pulumi.get(self, "tags")
| 50.501629
| 214
| 0.676363
| 5,585
| 46,512
| 5.389436
| 0.042972
| 0.086977
| 0.090897
| 0.039468
| 0.943854
| 0.933588
| 0.925382
| 0.920465
| 0.915216
| 0.895615
| 0
| 0.003117
| 0.22061
| 46,512
| 920
| 215
| 50.556522
| 0.827205
| 0.308265
| 0
| 0.85045
| 1
| 0
| 0.145895
| 0.070132
| 0
| 0
| 0
| 0
| 0
| 1
| 0.165766
| false
| 0.001802
| 0.012613
| 0
| 0.277477
| 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
|
3f8d5307507dbfdb510940fb426c35502a0054b3
| 23,126
|
py
|
Python
|
Wang2020Collaborative/tools/convert_caffemodel_to_pth/normalise_vgg/model.py
|
czczup/URST
|
000ec9f7728f12ffad989ec1d07b1dd579514133
|
[
"Apache-2.0"
] | 119
|
2021-03-21T18:30:51.000Z
|
2022-03-29T07:28:33.000Z
|
Wang2020Collaborative/tools/convert_caffemodel_to_pth/normalise_vgg/model.py
|
czczup/URST
|
000ec9f7728f12ffad989ec1d07b1dd579514133
|
[
"Apache-2.0"
] | 5
|
2021-04-02T14:26:03.000Z
|
2022-01-12T12:59:17.000Z
|
Wang2020Collaborative/tools/convert_caffemodel_to_pth/normalise_vgg/model.py
|
czczup/URST
|
000ec9f7728f12ffad989ec1d07b1dd579514133
|
[
"Apache-2.0"
] | 16
|
2021-03-21T18:30:53.000Z
|
2022-03-29T07:28:34.000Z
|
import numpy as np
import os
import torch.nn as nn
import torch
import torchfile
from utils import load_param_from_t7 as load_param
pjoin = os.path.join
# Original VGG19
# Encoder1/Decoder1
class Encoder1(nn.Module):
def __init__(self, model=None, fixed=False):
super(Encoder1, self).__init__()
self.fixed = fixed
self.conv0 = nn.Conv2d( 3, 3,1,1,0)
self.conv11 = nn.Conv2d( 3, 64,3,1,0, dilation=1)
self.relu = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=False)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 0, self.conv0)
load_param(t7_model, 2, self.conv11)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.conv0(input)
y = self.relu(self.conv11(self.pad(y)))
return y
def forward_branch(self, input):
out0 = self.conv0(input)
out11 = self.relu(self.conv11(self.pad(out0)))
return out11,
class Decoder1(nn.Module):
def __init__(self, model=None, fixed=False):
super(Decoder1, self).__init__()
self.fixed = fixed
self.conv11 = nn.Conv2d( 64, 3,3,1,0, dilation=1)
self.relu = nn.ReLU(inplace=True)
self.unpool = nn.UpsamplingNearest2d(scale_factor=2)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 1, self.conv11)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.relu(self.conv11(self.pad(input)))
return y
def forward_branch(self, input):
out11 = self.relu(self.conv11(self.pad(input)))
return out11,
# Encoder2/Decoder2
class Encoder2(nn.Module):
def __init__(self, model=None, fixed=False):
super(Encoder2, self).__init__()
self.fixed = fixed
self.conv0 = nn.Conv2d( 3, 3,1,1,0)
self.conv11 = nn.Conv2d( 3, 64,3,1,0, dilation=1)
self.conv12 = nn.Conv2d( 64, 64,3,1,0, dilation=1)
self.conv21 = nn.Conv2d( 64,128,3,1,0)
self.relu = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(kernel_size=2,stride=2,return_indices=False)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 0, self.conv0)
load_param(t7_model, 2, self.conv11)
load_param(t7_model, 5, self.conv12)
load_param(t7_model, 9, self.conv21)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.conv0(input)
y = self.relu(self.conv11(self.pad(y)))
y = self.relu(self.conv12(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv21(self.pad(y)))
return y
def forward_branch(self, input):
out0 = self.conv0(input)
out11 = self.relu(self.conv11(self.pad(out0)))
out12 = self.relu(self.conv12(self.pad(out11)))
out12 = self.pool(out12)
out21 = self.relu(self.conv21(self.pad(out12)))
return out11, out21
class Decoder2(nn.Module):
def __init__(self, model=None, fixed=False):
super(Decoder2, self).__init__()
self.fixed = fixed
self.conv21 = nn.Conv2d(128, 64,3,1,0)
self.conv12 = nn.Conv2d( 64, 64,3,1,0, dilation=1)
self.conv11 = nn.Conv2d( 64, 3,3,1,0, dilation=1)
self.relu = nn.ReLU(inplace=True)
self.unpool = nn.UpsamplingNearest2d(scale_factor=2)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 1, self.conv21)
load_param(t7_model, 5, self.conv12)
load_param(t7_model, 8, self.conv11)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.relu(self.conv21(self.pad(input)))
y = self.unpool(y)
y = self.relu(self.conv12(self.pad(y)))
y = self.relu(self.conv11(self.pad(y)))
return y
def forward_branch(self, input):
out21 = self.relu(self.conv21(self.pad(input)))
out21 = self.unpool(out21)
out12 = self.relu(self.conv12(self.pad(out21)))
out11 = self.relu(self.conv11(self.pad(out12)))
return out21, out11
# Encoder3/Decoder3
class Encoder3(nn.Module):
def __init__(self, model=None, fixed=False):
super(Encoder3, self).__init__()
self.fixed = fixed
self.conv0 = nn.Conv2d( 3, 3,1,1,0)
self.conv11 = nn.Conv2d( 3, 64,3,1,0) # conv1_1
self.conv12 = nn.Conv2d( 64, 64,3,1,0) # conv1_2
self.conv21 = nn.Conv2d( 64,128,3,1,0) # conv2_1
self.conv22 = nn.Conv2d(128,128,3,1,0) # conv2_2
self.conv31 = nn.Conv2d(128,256,3,1,0) # conv3_1
self.relu = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(kernel_size=2,stride=2,return_indices=False)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 0, self.conv0)
load_param(t7_model, 2, self.conv11)
load_param(t7_model, 5, self.conv12)
load_param(t7_model, 9, self.conv21)
load_param(t7_model, 12, self.conv22)
load_param(t7_model, 16, self.conv31)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.conv0(input)
y = self.relu(self.conv11(self.pad(y)))
y = self.relu(self.conv12(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv21(self.pad(y)))
y = self.relu(self.conv22(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv31(self.pad(y)))
return y
def forward_branch(self, input):
out0 = self.conv0(input)
out11 = self.relu(self.conv11(self.pad(out0)))
out12 = self.relu(self.conv12(self.pad(out11)))
out12 = self.pool(out12)
out21 = self.relu(self.conv21(self.pad(out12)))
out22 = self.relu(self.conv22(self.pad(out21)))
out22 = self.pool(out22)
out31 = self.relu(self.conv31(self.pad(out22)))
return out11, out21, out31
class Decoder3(nn.Module):
def __init__(self, model=None, fixed=False):
super(Decoder3, self).__init__()
self.fixed = fixed
self.conv31 = nn.Conv2d(256,128,3,1,0)
self.conv22 = nn.Conv2d(128,128,3,1,0)
self.conv21 = nn.Conv2d(128, 64,3,1,0)
self.conv12 = nn.Conv2d( 64, 64,3,1,0)
self.conv11 = nn.Conv2d( 64, 3,3,1,0)
self.relu = nn.ReLU(inplace=True)
self.unpool = nn.UpsamplingNearest2d(scale_factor=2)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 1, self.conv31)
load_param(t7_model, 5, self.conv22)
load_param(t7_model, 8, self.conv21)
load_param(t7_model, 12, self.conv12)
load_param(t7_model, 15, self.conv11)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.relu(self.conv31(self.pad(input)))
y = self.unpool(y)
y = self.relu(self.conv22(self.pad(y)))
y = self.relu(self.conv21(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv12(self.pad(y)))
y = self.relu(self.conv11(self.pad(y)))
return y
def forward_branch(self, input):
out31 = self.relu(self.conv31(self.pad(input)))
out31 = self.unpool(out31)
out22 = self.relu(self.conv22(self.pad(out31)))
out21 = self.relu(self.conv21(self.pad(out22)))
out21 = self.unpool(out21)
out12 = self.relu(self.conv12(self.pad(out21)))
out11 = self.relu(self.conv11(self.pad(out12)))
return out31, out21, out11
# Encoder4/Decoder4
class Encoder4(nn.Module):
def __init__(self, model=None, fixed=False):
super(Encoder4, self).__init__()
self.fixed = fixed
self.conv0 = nn.Conv2d( 3, 3,1,1,0)
self.conv11 = nn.Conv2d( 3, 64,3,1,0) # conv1_1
self.conv12 = nn.Conv2d( 64, 64,3,1,0) # conv1_2
self.conv21 = nn.Conv2d( 64,128,3,1,0) # conv2_1
self.conv22 = nn.Conv2d(128,128,3,1,0) # conv2_2
self.conv31 = nn.Conv2d(128,256,3,1,0) # conv3_1
self.conv32 = nn.Conv2d(256,256,3,1,0) # conv3_2
self.conv33 = nn.Conv2d(256,256,3,1,0) # conv3_3
self.conv34 = nn.Conv2d(256,256,3,1,0) # conv3_4
self.conv41 = nn.Conv2d(256,512,3,1,0) # conv4_1
self.relu = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(kernel_size=2,stride=2,return_indices=False)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 0, self.conv0)
load_param(t7_model, 2, self.conv11)
load_param(t7_model, 5, self.conv12)
load_param(t7_model, 9, self.conv21)
load_param(t7_model, 12, self.conv22)
load_param(t7_model, 16, self.conv31)
load_param(t7_model, 19, self.conv32)
load_param(t7_model, 22, self.conv33)
load_param(t7_model, 25, self.conv34)
load_param(t7_model, 29, self.conv41)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.conv0(input)
y = self.relu(self.conv11(self.pad(y)))
y = self.relu(self.conv12(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv21(self.pad(y)))
y = self.relu(self.conv22(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv31(self.pad(y)))
y = self.relu(self.conv32(self.pad(y)))
y = self.relu(self.conv33(self.pad(y)))
y = self.relu(self.conv34(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv41(self.pad(y)))
return y
def forward_branch(self, input):
out0 = self.conv0(input)
out11 = self.relu(self.conv11(self.pad(out0)))
out12 = self.relu(self.conv12(self.pad(out11)))
out12 = self.pool(out12)
out21 = self.relu(self.conv21(self.pad(out12)))
out22 = self.relu(self.conv22(self.pad(out21)))
out22 = self.pool(out22)
out31 = self.relu(self.conv31(self.pad(out22)))
out32 = self.relu(self.conv32(self.pad(out31)))
out33 = self.relu(self.conv33(self.pad(out32)))
out34 = self.relu(self.conv34(self.pad(out33)))
out34 = self.pool(out34)
out41 = self.relu(self.conv41(self.pad(out34)))
return out11, out21, out31, out41
class Decoder4(nn.Module):
def __init__(self, model=None, fixed=False):
super(Decoder4, self).__init__()
self.fixed = fixed
self.conv41 = nn.Conv2d(512,256,3,1,0)
self.conv34 = nn.Conv2d(256,256,3,1,0)
self.conv33 = nn.Conv2d(256,256,3,1,0)
self.conv32 = nn.Conv2d(256,256,3,1,0)
self.conv31 = nn.Conv2d(256,128,3,1,0)
self.conv22 = nn.Conv2d(128,128,3,1,0)
self.conv21 = nn.Conv2d(128, 64,3,1,0)
self.conv12 = nn.Conv2d( 64, 64,3,1,0)
self.conv11 = nn.Conv2d( 64, 3,3,1,0)
self.relu = nn.ReLU(inplace=True)
self.unpool = nn.UpsamplingNearest2d(scale_factor=2)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 1, self.conv41)
load_param(t7_model, 5, self.conv34)
load_param(t7_model, 8, self.conv33)
load_param(t7_model, 11, self.conv32)
load_param(t7_model, 14, self.conv31)
load_param(t7_model, 18, self.conv22)
load_param(t7_model, 21, self.conv21)
load_param(t7_model, 25, self.conv12)
load_param(t7_model, 28, self.conv11)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.relu(self.conv41(self.pad(input)))
y = self.unpool(y)
y = self.relu(self.conv34(self.pad(y)))
y = self.relu(self.conv33(self.pad(y)))
y = self.relu(self.conv32(self.pad(y)))
y = self.relu(self.conv31(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv22(self.pad(y)))
y = self.relu(self.conv21(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv12(self.pad(y)))
y = self.relu(self.conv11(self.pad(y)))
return y
def forward_norule(self, input):
y = self.relu(self.conv41(self.pad(input)))
y = self.unpool(y)
y = self.relu(self.conv34(self.pad(y)))
y = self.relu(self.conv33(self.pad(y)))
y = self.relu(self.conv32(self.pad(y)))
y = self.relu(self.conv31(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv22(self.pad(y)))
y = self.relu(self.conv21(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv12(self.pad(y)))
y = self.conv11(self.pad(y))
return y
def forward_branch(self, input):
out41 = self.relu(self.conv41(self.pad(input)))
out41 = self.unpool(out41)
out34 = self.relu(self.conv34(self.pad(out41)))
out33 = self.relu(self.conv33(self.pad(out34)))
out32 = self.relu(self.conv32(self.pad(out33)))
out31 = self.relu(self.conv31(self.pad(out32)))
out31 = self.unpool(out31)
out22 = self.relu(self.conv22(self.pad(out31)))
out21 = self.relu(self.conv21(self.pad(out22)))
out21 = self.unpool(out21)
out12 = self.relu(self.conv12(self.pad(out21)))
out11 = self.relu(self.conv11(self.pad(out12)))
return out41, out31, out21, out11
# Encoder5/Decoder5
class Encoder5(nn.Module):
def __init__(self, model=None, fixed=False):
super(Encoder5, self).__init__()
self.fixed = fixed
self.conv0 = nn.Conv2d( 3, 3,1,1,0)
self.conv0.weight = nn.Parameter(torch.from_numpy(np.array(
[[[[0]],[[0]],[[255]]],
[[[0]],[[255]],[[0]]],
[[[255]],[[0]],[[0]]]])).float())
self.conv0.bias = nn.Parameter(torch.from_numpy(np.array(
[-103.939,-116.779,-123.68])).float())
self.conv11 = nn.Conv2d( 3, 64,3,1,0) # conv1_1
self.conv12 = nn.Conv2d( 64, 64,3,1,0) # conv1_2
self.conv21 = nn.Conv2d( 64,128,3,1,0) # conv2_1
self.conv22 = nn.Conv2d(128,128,3,1,0) # conv2_2
self.conv31 = nn.Conv2d(128,256,3,1,0) # conv3_1
self.conv32 = nn.Conv2d(256,256,3,1,0) # conv3_2
self.conv33 = nn.Conv2d(256,256,3,1,0) # conv3_3
self.conv34 = nn.Conv2d(256,256,3,1,0) # conv3_4
self.conv41 = nn.Conv2d(256,512,3,1,0) # conv4_1
self.conv42 = nn.Conv2d(512,512,3,1,0) # conv4_2
self.conv43 = nn.Conv2d(512,512,3,1,0) # conv4_3
self.conv44 = nn.Conv2d(512,512,3,1,0) # conv4_4
self.conv51 = nn.Conv2d(512,512,3,1,0) # conv5_1
self.relu = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(kernel_size=2,stride=2,return_indices=False)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
## load from my normalised t7 model, which has no conv0 layer.
# load_param(t7_model, 0, self.conv11)
# load_param(t7_model, 2, self.conv12)
# load_param(t7_model, 5, self.conv21)
# load_param(t7_model, 7, self.conv22)
# load_param(t7_model, 10, self.conv31)
# load_param(t7_model, 12, self.conv32)
# load_param(t7_model, 14, self.conv33)
# load_param(t7_model, 16, self.conv34)
# load_param(t7_model, 19, self.conv41)
# load_param(t7_model, 21, self.conv42)
# load_param(t7_model, 23, self.conv43)
# load_param(t7_model, 25, self.conv44)
# load_param(t7_model, 28, self.conv51)
# load_param(t7_model, 30, self.conv52)
load_param(t7_model, 0, self.conv0)
load_param(t7_model, 2, self.conv11)
load_param(t7_model, 5, self.conv12)
load_param(t7_model, 9, self.conv21)
load_param(t7_model, 12, self.conv22)
load_param(t7_model, 16, self.conv31)
load_param(t7_model, 19, self.conv32)
load_param(t7_model, 22, self.conv33)
load_param(t7_model, 25, self.conv34)
load_param(t7_model, 29, self.conv41)
load_param(t7_model, 32, self.conv42)
load_param(t7_model, 35, self.conv43)
load_param(t7_model, 38, self.conv44)
load_param(t7_model, 42, self.conv51)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.conv0(input)
y = self.relu(self.conv11(self.pad(y)))
y = self.relu(self.conv12(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv21(self.pad(y)))
y = self.relu(self.conv22(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv31(self.pad(y)))
y = self.relu(self.conv32(self.pad(y)))
y = self.relu(self.conv33(self.pad(y)))
y = self.relu(self.conv34(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv41(self.pad(y)))
y = self.relu(self.conv42(self.pad(y)))
y = self.relu(self.conv43(self.pad(y)))
y = self.relu(self.conv44(self.pad(y)))
y = self.pool(y)
y = self.relu(self.conv51(self.pad(y)))
return y
def forward_branch(self, input):
out0 = self.conv0(input)
out11 = self.relu(self.conv11(self.pad(out0)))
out12 = self.relu(self.conv12(self.pad(out11)))
out12 = self.pool(out12)
out21 = self.relu(self.conv21(self.pad(out12)))
out22 = self.relu(self.conv22(self.pad(out21)))
out22 = self.pool(out22)
out31 = self.relu(self.conv31(self.pad(out22)))
out32 = self.relu(self.conv32(self.pad(out31)))
out33 = self.relu(self.conv33(self.pad(out32)))
out34 = self.relu(self.conv34(self.pad(out33)))
out34 = self.pool(out34)
out41 = self.relu(self.conv41(self.pad(out34)))
out42 = self.relu(self.conv42(self.pad(out41)))
out43 = self.relu(self.conv43(self.pad(out42)))
out44 = self.relu(self.conv44(self.pad(out43)))
out44 = self.pool(out44)
out51 = self.relu(self.conv51(self.pad(out44)))
return out11, out21, out31, out41, out51
class Decoder5(nn.Module):
def __init__(self, model=None, fixed=False):
super(Decoder5, self).__init__()
self.fixed = fixed
self.conv51 = nn.Conv2d(512,512,3,1,0)
self.conv44 = nn.Conv2d(512,512,3,1,0)
self.conv43 = nn.Conv2d(512,512,3,1,0)
self.conv42 = nn.Conv2d(512,512,3,1,0)
self.conv41 = nn.Conv2d(512,256,3,1,0)
self.conv34 = nn.Conv2d(256,256,3,1,0)
self.conv33 = nn.Conv2d(256,256,3,1,0)
self.conv32 = nn.Conv2d(256,256,3,1,0)
self.conv31 = nn.Conv2d(256,128,3,1,0)
self.conv22 = nn.Conv2d(128,128,3,1,0)
self.conv21 = nn.Conv2d(128, 64,3,1,0)
self.conv12 = nn.Conv2d( 64, 64,3,1,0)
self.conv11 = nn.Conv2d( 64, 3,3,1,0)
self.relu = nn.ReLU(inplace=True)
self.unpool = nn.UpsamplingNearest2d(scale_factor=2)
self.pad = nn.ReflectionPad2d((1,1,1,1))
if model:
assert(os.path.splitext(model)[1] in {".t7", ".pth"})
if model.endswith(".t7"):
t7_model = torchfile.load(model)
load_param(t7_model, 1, self.conv51)
load_param(t7_model, 5, self.conv44)
load_param(t7_model, 8, self.conv43)
load_param(t7_model, 11, self.conv42)
load_param(t7_model, 14, self.conv41)
load_param(t7_model, 18, self.conv34)
load_param(t7_model, 21, self.conv33)
load_param(t7_model, 24, self.conv32)
load_param(t7_model, 27, self.conv31)
load_param(t7_model, 31, self.conv22)
load_param(t7_model, 34, self.conv21)
load_param(t7_model, 38, self.conv12)
load_param(t7_model, 41, self.conv11)
else:
self.load_state_dict(torch.load(model, map_location=lambda storage, location: storage))
if fixed:
for param in self.parameters():
param.requires_grad = False
def forward(self, input):
y = self.relu(self.conv51(self.pad(input)))
y = self.unpool(y)
y = self.relu(self.conv44(self.pad(y)))
y = self.relu(self.conv43(self.pad(y)))
y = self.relu(self.conv42(self.pad(y)))
y = self.relu(self.conv41(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv34(self.pad(y)))
y = self.relu(self.conv33(self.pad(y)))
y = self.relu(self.conv32(self.pad(y)))
y = self.relu(self.conv31(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv22(self.pad(y)))
y = self.relu(self.conv21(self.pad(y)))
y = self.unpool(y)
y = self.relu(self.conv12(self.pad(y)))
y = self.relu(self.conv11(self.pad(y)))
return y
def forward_branch(self, input):
out51 = self.relu(self.conv51(self.pad(input)))
out51 = self.unpool(out51)
out44 = self.relu(self.conv44(self.pad(out51)))
out43 = self.relu(self.conv43(self.pad(out44)))
out42 = self.relu(self.conv42(self.pad(out43)))
out41 = self.relu(self.conv41(self.pad(out42)))
out41 = self.unpool(out41)
out34 = self.relu(self.conv34(self.pad(out41)))
out33 = self.relu(self.conv33(self.pad(out34)))
out32 = self.relu(self.conv32(self.pad(out33)))
out31 = self.relu(self.conv31(self.pad(out32)))
out31 = self.unpool(out31)
out22 = self.relu(self.conv22(self.pad(out31)))
out21 = self.relu(self.conv21(self.pad(out22)))
out21 = self.unpool(out21)
out12 = self.relu(self.conv12(self.pad(out21)))
out11 = self.relu(self.conv11(self.pad(out12)))
return out51, out41, out31, out21, out11
| 37.360258
| 95
| 0.628816
| 3,621
| 23,126
| 3.919083
| 0.04612
| 0.070538
| 0.11162
| 0.091325
| 0.944613
| 0.940032
| 0.860404
| 0.825946
| 0.813191
| 0.796914
| 0
| 0.108878
| 0.210456
| 23,126
| 619
| 96
| 37.360258
| 0.668328
| 0.039436
| 0
| 0.818692
| 0
| 0
| 0.004512
| 0
| 0
| 0
| 0
| 0
| 0.018692
| 1
| 0.057944
| false
| 0
| 0.011215
| 0
| 0.127103
| 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
|
3fdb02c6d3699ad240a87943f54b26ea41de6a4e
| 92
|
py
|
Python
|
graphgallery/nn/layers/__init__.py
|
Sharpiless/GraphGallery
|
5e8895cc2ca2fc06a31bfc58bc3b7a52e1ceddd0
|
[
"MIT"
] | 1
|
2020-11-22T10:14:58.000Z
|
2020-11-22T10:14:58.000Z
|
graphgallery/nn/layers/__init__.py
|
mengliu1998/GraphGallery
|
025ac09e883f3e1e1b02000e086830c935884a6e
|
[
"MIT"
] | null | null | null |
graphgallery/nn/layers/__init__.py
|
mengliu1998/GraphGallery
|
025ac09e883f3e1e1b02000e086830c935884a6e
|
[
"MIT"
] | 1
|
2020-11-22T10:14:59.000Z
|
2020-11-22T10:14:59.000Z
|
from graphgallery.nn.layers import tf_layers
from graphgallery.nn.layers import th_layers
| 18.4
| 44
| 0.847826
| 14
| 92
| 5.428571
| 0.5
| 0.421053
| 0.473684
| 0.631579
| 0.789474
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.108696
| 92
| 4
| 45
| 23
| 0.926829
| 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
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 8
|
3fdd6643482684cc225fcd823760c49c1037ffa7
| 3,643
|
py
|
Python
|
geld_automat.py
|
armansj/geldAutomat
|
46c89c27721fae9ec09c25033c674f277dc5fe26
|
[
"MIT"
] | 1
|
2021-12-23T17:41:35.000Z
|
2021-12-23T17:41:35.000Z
|
geld_automat.py
|
armansj/geldAutomat
|
46c89c27721fae9ec09c25033c674f277dc5fe26
|
[
"MIT"
] | null | null | null |
geld_automat.py
|
armansj/geldAutomat
|
46c89c27721fae9ec09c25033c674f277dc5fe26
|
[
"MIT"
] | null | null | null |
def z_bank():
z_bank_profit=0.96
def withdraw():
new_amount=0
withdrawal=float(input("please enter how many geld you want give from your account: \t"))
new_amount=current_amount-withdrawal
if new_amount<0:
print(f"you money is less than {withdrawal}")
print(f"your new amount is : \t {new_amount*z_bank_profit}")
with open("saver.txt",'w',encoding = 'utf-8') as file:
file.write(f"new Amount After Withdraw : {new_amount*z_bank_profit}\n")
def deposit():
deposit=float(input("please enter how much you want put in your account: \t"))
new_amount=current_amount+deposit
print(f"your final amount is:\t {new_amount*z_bank_profit}")
with open("saver.txt",'w',encoding = 'utf-8') as file:
file.write(f"new Amount After Deposit : {new_amount*z_bank_profit}\n")
print("welcome to ziraat bank!\n")
print("vorsicht your transactron with this card have 4% profit for atm")
pass_code=int(input("please enter your pass: \t"))
if pass_code==1111:
print("great password is currect \n")
print("welcome to our bank")
while True:
current_amount=float(input("please enter your account amount: \t"))
ask_for_withraw_or_deposit=input("please enter do you want widthraw or deposit? : \t(w widraw / d for deposit)\t")
if ask_for_withraw_or_deposit=='w':
print("you want to widthraw!")
withdraw()
elif ask_for_withraw_or_deposit=='d':
print("you want to deposit!")
deposit()
else:
print(f"pass is wrong Try again ")
z_bank()
def s_bank():
s_bank_profit=0
def withdraw():
new_amount=0
withdrawal=float(input("please enter how many geld you want give from your account: \t"))
new_amount=current_amount-withdrawal
if new_amount<0:
print(f"you money is less than {withdrawal}")
print(f"your new amount is : \t {new_amount}")
with open('saver.txt', 'w') as file:
file.write(f"my new amount After Withdraw {new_amount}\n")
def deposit():
deposit=float(input("please enter how much you want put in your account: \t"))
new_amount=current_amount+deposit
print(f"your final amount is:\t {new_amount}")
with open('saver.txt', 'w') as file:
file.write(f"my new amount After deposit {new_amount}\n")
print("welcome to sparkasse bank!\n")
print("vorsicht your transactron with this card have 0% profit for atm")
pass_code=int(input("please enter your pass: \t"))
if pass_code==2222:
print("great password is currect \n")
print("welcome to Sparkasse bank")
while True:
current_amount=float(input("please enter your account amount: \t"))
ask_for_withraw_or_deposit=input("please enter do you want widraw or deposit? : \t(w widraw / d for deposit)\t")
if ask_for_withraw_or_deposit=='w':
print("you want to widraw!")
withdraw()
elif ask_for_withraw_or_deposit=='d':
print("you want to deposit!")
deposit()
else:
print("pass is wrong Try again")
s_bank()
card_holder=input("please enter you cardholder Bank:(s,z) : \t")
if card_holder=='z':
z_bank()
elif card_holder=='s':
s_bank()
| 25.124138
| 126
| 0.584957
| 499
| 3,643
| 4.128257
| 0.178357
| 0.096117
| 0.085437
| 0.061165
| 0.903884
| 0.885437
| 0.826214
| 0.826214
| 0.826214
| 0.785437
| 0
| 0.007921
| 0.30689
| 3,643
| 144
| 127
| 25.298611
| 0.807921
| 0
| 0
| 0.613333
| 0
| 0.026667
| 0.399395
| 0.029687
| 0
| 0
| 0
| 0
| 0
| 1
| 0.08
| false
| 0.106667
| 0
| 0
| 0.08
| 0.266667
| 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
| 0
| 0
| 1
| 0
| 0
| 0
| 0
|
0
| 7
|
3ff9e0ca20a28cb926b50e10863cd2357f4d20f4
| 16,474
|
py
|
Python
|
process_dictionary.py
|
tehruhn/quantum-overlapping-tomo
|
ae80bbd4a93fc1a5be1700d28a3b82740470c51d
|
[
"Apache-2.0"
] | 6
|
2019-11-19T06:05:15.000Z
|
2021-07-23T15:46:24.000Z
|
process_dictionary.py
|
tehruhn/quantum-overlapping-tomo
|
ae80bbd4a93fc1a5be1700d28a3b82740470c51d
|
[
"Apache-2.0"
] | null | null | null |
process_dictionary.py
|
tehruhn/quantum-overlapping-tomo
|
ae80bbd4a93fc1a5be1700d28a3b82740470c51d
|
[
"Apache-2.0"
] | 4
|
2019-11-20T00:42:21.000Z
|
2020-02-20T03:19:28.000Z
|
import itertools
import re
from calculate_s import calculate_s
def get_number_of_measurements(result_dict):
number_of_data_points = 0
for key, value in result_dict.items():
number_of_data_points += value
return number_of_data_points
# XXYYZZ
# IXIYIZ
# ALL Z - XIYIZI (WRONG)
def process_dictionary_xx_yy_zz(circuit_name, output):
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# print(list_of_keys)
num_qubits = len(list_of_keys[0])
# print(num_qubits)
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s1 - s2 - s3 + s4) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
# print(s1)
answer.append(total)
return answer
def process_dictionary_ix_iy_iz(circuit_name, output):
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# print(list_of_keys)
num_qubits = len(list_of_keys[0])
# print(num_qubits)
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# # find two indices to fix
# first = i[0]
# second = i[1]
# # fix 00 and sum
# zz = []
# s1 = 0
# for j in list_of_keys:
# if j[first] == "0" and j[second] == "0":
# zz.append(j)
# for k in zz:
# s1 += dictionary[k]
# # fix 01 and sum
# zo = []
# s2 = 0
# for j in list_of_keys:
# if j[first] == "0" and j[second] == "1":
# zo.append(j)
# for k in zo:
# s2 += dictionary[k]
# # fix 10 and sum
# oz = []
# s3 = 0
# for j in list_of_keys:
# if j[first] == "1" and j[second] == "0":
# oz.append(j)
# for k in oz:
# s3 += dictionary[k]
# # fix 11 and sum
# oo = []
# s4 = 0
# for j in list_of_keys:
# if j[first] == "1" and j[second] == "1":
# oo.append(j)
# for k in oo:
# s4 += dictionary[k]
# total = (s4 + s2 - s3 - s1)/8192
# # print(s1, s2, s3, s4)
first = combination[0]
second = combination[1]
# print(first, second)
s0 = 0
zero = []
for j in list_of_keys:
if j[second] == "0":
zero.append(j)
for k in zero:
s0 += dictionary[k]
s1 = 0
one = []
for j in list_of_keys:
if j[second] == "1":
one.append(j)
for k in one:
s1 += dictionary[k]
total = (s1 - s0) / get_number_of_measurements(dictionary)
answer.append(total)
return answer
def process_dictionary_xi_yi_zi(circuit_name, output):
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# print(list_of_keys)
num_qubits = len(list_of_keys[0])
# print(num_qubits)
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s3 - s2 - s1) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
def process_dictionary_xy12(num_qubits, output, hash_functions):
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# finds hash function that splits differently
hnum = 0
for j in range(len(hash_functions)):
if hash_functions[j][first] != hash_functions[j][second]:
hnum = j
circuit_name = str(hnum) + "_0"
# print(circuit_name)
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s1 - s3 - s2) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
def process_dictionary_yx12(num_qubits, output, hash_functions):
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# finds hash function that splits differently
hnum = 0
for j in range(len(hash_functions)):
if hash_functions[j][first] != hash_functions[j][second]:
hnum = j
circuit_name = str(hnum) + "_1"
# print(circuit_name)
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s1 - s3 - s2) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
def process_dictionary_xz12(num_qubits, output, hash_functions):
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
# print(list_of_nums)
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
# print(i)
first = combination[0]
second = combination[1]
# finds hash function that splits differently
hnum = 0
for j in range(len(hash_functions)):
if hash_functions[j][first] != hash_functions[j][second]:
hnum = j
circuit_name = str(hnum) + "_2"
# print(circuit_name)
dictionary = output[circuit_name]
# print(dictionary)
# print(first, second)
# print(hash_functions[hnum][first], hash_functions[hnum][second])
# print("this was it")
# if first==0 and second==1:
# print(circuit_name)
# print(dictionary)
# if first==2 and second==3:
# print(circuit_name)
# print(dictionary)
list_of_keys = list(dictionary.keys())
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s1 - s3 - s2) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
def process_dictionary_zx12(num_qubits, output, hash_functions):
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# finds hash function that splits differently
hnum = 0
for j in range(len(hash_functions)):
if hash_functions[j][first] != hash_functions[j][second]:
hnum = j
circuit_name = str(hnum) + "_3"
# print(circuit_name)
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s1 - s3 - s2) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
def process_dictionary_yz12(num_qubits, output, hash_functions):
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# finds hash function that splits differently
hnum = 0
for j in range(len(hash_functions)):
if hash_functions[j][first] != hash_functions[j][second]:
hnum = j
circuit_name = str(hnum) + "_4"
# print(circuit_name)
dictionary = output[circuit_name]
# if first ==2 and second ==3:
# print(dictionary)
list_of_keys = list(dictionary.keys())
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s1 - s3 - s2) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
def process_dictionary_zy12(num_qubits, output, hash_functions):
# list of numbers to iterate on
list_of_nums = list(range(num_qubits))
answer = []
for combination in itertools.combinations(list_of_nums, 2):
# find two indices to fix
first = combination[0]
second = combination[1]
# finds hash function that splits differently
hnum = 0
for j in range(len(hash_functions)):
if hash_functions[j][first] != hash_functions[j][second]:
hnum = j
circuit_name = str(hnum) + "_5"
# print(circuit_name)
dictionary = output[circuit_name]
list_of_keys = list(dictionary.keys())
# fix 00 and sum
zz = []
s1 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "0":
zz.append(j)
for k in zz:
s1 += dictionary[k]
# fix 01 and sum
zo = []
s2 = 0
for j in list_of_keys:
if j[first] == "0" and j[second] == "1":
zo.append(j)
for k in zo:
s2 += dictionary[k]
# fix 10 and sum
oz = []
s3 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "0":
oz.append(j)
for k in oz:
s3 += dictionary[k]
# fix 11 and sum
oo = []
s4 = 0
for j in list_of_keys:
if j[first] == "1" and j[second] == "1":
oo.append(j)
for k in oo:
s4 += dictionary[k]
total = (s4 + s1 - s3 - s2) / get_number_of_measurements(dictionary)
# print(s1, s2, s3, s4)
answer.append(total)
return answer
| 28.600694
| 76
| 0.492352
| 2,179
| 16,474
| 3.589261
| 0.050023
| 0.06214
| 0.067766
| 0.037591
| 0.931978
| 0.917402
| 0.912927
| 0.896688
| 0.884158
| 0.877765
| 0
| 0.040471
| 0.39705
| 16,474
| 575
| 77
| 28.650435
| 0.746904
| 0.168447
| 0
| 0.904762
| 0
| 0
| 0.005752
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.026455
| false
| 0
| 0.007937
| 0
| 0.060847
| 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
|
b7499e5a824d8e3379f8522a4f69e9dfe1bb3536
| 10,501
|
py
|
Python
|
ml/paraphrase/paraphraser_dataloader.py
|
DavidThe4sian/marvin
|
1dddd8cdb8be55d3b553df1b2cf89e8b6b0538b6
|
[
"MIT"
] | 4
|
2021-05-14T02:23:52.000Z
|
2021-12-28T10:33:18.000Z
|
ml/paraphrase/paraphraser_dataloader.py
|
DavidThe4sian/marvin
|
1dddd8cdb8be55d3b553df1b2cf89e8b6b0538b6
|
[
"MIT"
] | null | null | null |
ml/paraphrase/paraphraser_dataloader.py
|
DavidThe4sian/marvin
|
1dddd8cdb8be55d3b553df1b2cf89e8b6b0538b6
|
[
"MIT"
] | 3
|
2021-05-31T06:38:59.000Z
|
2021-09-29T02:44:22.000Z
|
import os, json
import torch
from torch.utils.data import TensorDataset
from tqdm import tqdm
import numpy as np
import pandas as pd
def load_dataset(data_dir, tokenizer, mode, delimiter = "<|endoftext|>", prefix = "paraphrase: ", n_proc = 16):
all_input_ids = None
all_input_attention_mask = None
all_output_ids = None
filename = os.path.join(data_dir, f"{mode}_processed.txt")
with open(filename,'r') as fob:
data = fob.readlines()
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
chunk = [x.split(delimiter) for x in chunk]
inputs = tokenizer([prefix+x[0] for x in chunk], padding="max_length", return_tensors='pt', truncation = True)
outputs = tokenizer([x[1] for x in chunk], padding="max_length", return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_input_attention_mask = inputs['input_ids'], inputs['attention_mask']
all_output_ids = outputs['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, inputs['input_ids']),0)
all_input_attention_mask = torch.cat((all_input_attention_mask, inputs['attention_mask']), 0)
all_output_ids = torch.cat((all_output_ids, outputs['input_ids']),0)
assert len(all_input_ids) == len(all_input_attention_mask)
assert len(all_input_ids) == len(all_output_ids)
dataset = TensorDataset(all_input_ids, all_input_attention_mask, all_output_ids)
return dataset
def load_dataset_style(data_dir, tokenizer, mode, task, delimiter = "<|endoftext|>", prefix = "paraphrase: ", n_proc = 16):
all_input_ids = None
all_attention_mask = None
config_file = os.path.join(data_dir, task, "config.json")
config = json.load(open(config_file))
filename = os.path.join(data_dir, task, config['input_files'][mode])
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
tokenized = tokenizer([prefix+x for x in list(chunk[0])], padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask)
return dataset
def load_dataset_pseudo(data_dir, tokenizer, mode, tasks, n_proc = 16):
all_input_ids = None
all_attention_mask = None
all_output_ids = None
for t, task in enumerate(tasks) :
filename = os.path.join(data_dir, task, mode+'.csv')
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
temp = 'transfer: ' + chunk[0] + ' | input: '+chunk[1] + ' | output: '+chunk[3]
tokenized = tokenizer(list(temp), padding='max_length', return_tensors='pt', truncation = True)
output = tokenizer(list(chunk[2]), padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
all_output_ids = output['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_output_ids = torch.cat((all_output_ids, output['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_output_ids)
return dataset
def load_dataset_pseudo2(data_dir, tokenizer, mode, tasks, n_proc = 16):
all_input_ids = None
all_attention_mask = None
all_output_ids = None
for t, task in enumerate(tasks) :
filename = os.path.join(data_dir, task, mode+'.csv')
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
temp = 'transfer: ' + chunk[0] + ' | input '+task+': '+chunk[1] + ' | output '+task+': '+chunk[3]
tokenized = tokenizer(list(temp), padding='max_length', return_tensors='pt', truncation = True)
output = tokenizer(list(chunk[2]), padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
all_output_ids = output['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_output_ids = torch.cat((all_output_ids, output['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_output_ids)
return dataset
def load_dataset_pseudo_binary(data_dir, tokenizer, mode, tasks, n_proc = 16):
all_input_ids = None
all_attention_mask = None
all_output_ids = None
for t, task in enumerate(tasks) :
print(task, mode)
filename = os.path.join(data_dir, task, mode+'_binary.csv')
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
temp = 'transfer: ' + chunk[0] + ' | target: '+task
tokenized = tokenizer(list(temp), padding='max_length', return_tensors='pt', truncation = True)
output = tokenizer(list(chunk[1]), padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
all_output_ids = output['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_output_ids = torch.cat((all_output_ids, output['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_output_ids)
return dataset
def load_dataset_pseudo_binary_single(data_dir, tokenizer, mode, tasks, n_proc = 16):
all_input_ids = None
all_attention_mask = None
all_output_ids = None
for t, task in enumerate(tasks) :
print(task, mode)
filename = os.path.join(data_dir, task, mode+'_binary.csv')
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
temp = 'transfer: ' + chunk[0]
tokenized = tokenizer(list(temp), padding='max_length', return_tensors='pt', truncation = True)
output = tokenizer(list(chunk[1]), padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
all_output_ids = output['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_output_ids = torch.cat((all_output_ids, output['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_output_ids)
return dataset
def load_dataset_pseudo_joint(data_dir, tokenizer, mode, tasks, n_proc = 16):
all_input_ids = None
all_attention_mask = None
all_output_ids = None
for t, task in enumerate(tasks) :
filename = os.path.join(data_dir, task, mode+'.csv')
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
temp = 'transfer: ' + chunk[0] + ' | input formality: '+chunk[1] + ' | input emotion: '+chunk[2] +' | output formality: '+chunk[4] +' | output emotion: '+chunk[5]
tokenized = tokenizer(list(temp), padding='max_length', return_tensors='pt', truncation = True)
output = tokenizer(list(chunk[3]), padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
all_output_ids = output['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_output_ids = torch.cat((all_output_ids, output['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_output_ids)
return dataset
def load_dataset_pseudo_diff(data_dir, tokenizer, mode, tasks, n_proc = 16):
all_input_ids = None
all_attention_mask = None
all_output_ids = None
for t, task in enumerate(tasks) :
filename = os.path.join(data_dir, task, mode+'.csv')
data = pd.read_csv(filename, header=None)
chunk_size = len(data)//n_proc + 1
for chunk in tqdm(np.array_split(data, chunk_size)):
temp = 'transfer: ' + chunk[0] + ' | input to output: '+chunk[2]
tokenized = tokenizer(list(temp), padding='max_length', return_tensors='pt', truncation = True)
output = tokenizer(list(chunk[1]), padding='max_length', return_tensors='pt', truncation = True)
if all_input_ids is None:
all_input_ids, all_attention_mask = tokenized['input_ids'], tokenized['attention_mask']
all_output_ids = output['input_ids']
else:
all_input_ids = torch.cat((all_input_ids, tokenized['input_ids']),0)
all_output_ids = torch.cat((all_output_ids, output['input_ids']),0)
all_attention_mask = torch.cat((all_attention_mask, tokenized['attention_mask']), 0)
dataset = TensorDataset(all_input_ids, all_attention_mask, all_output_ids)
return dataset
| 56.762162
| 174
| 0.655271
| 1,416
| 10,501
| 4.558616
| 0.070621
| 0.099148
| 0.085205
| 0.034702
| 0.902246
| 0.891867
| 0.874516
| 0.846011
| 0.846011
| 0.840899
| 0
| 0.008851
| 0.225312
| 10,501
| 185
| 175
| 56.762162
| 0.784634
| 0
| 0
| 0.764368
| 0
| 0
| 0.096934
| 0
| 0
| 0
| 0
| 0
| 0.011494
| 1
| 0.045977
| false
| 0
| 0.034483
| 0
| 0.126437
| 0.011494
| 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
|
4d4471f30d2b67931afdf9b3051322fda0686abe
| 38,177
|
py
|
Python
|
Archive/Franken_Standard_Static_RS_Sketch.py
|
RoryRose/Meso-scale-Cantilevers-Abaqus-Automation
|
471b4f065caf75c289e4967e2f06867480f69c42
|
[
"BSD-2-Clause"
] | null | null | null |
Archive/Franken_Standard_Static_RS_Sketch.py
|
RoryRose/Meso-scale-Cantilevers-Abaqus-Automation
|
471b4f065caf75c289e4967e2f06867480f69c42
|
[
"BSD-2-Clause"
] | null | null | null |
Archive/Franken_Standard_Static_RS_Sketch.py
|
RoryRose/Meso-scale-Cantilevers-Abaqus-Automation
|
471b4f065caf75c289e4967e2f06867480f69c42
|
[
"BSD-2-Clause"
] | null | null | null |
# -*- coding: mbcs -*-
# Do not delete the following import lines
from abaqus import *
from abaqusConstants import *
import __main__
#set names
import section
import regionToolset
import displayGroupMdbToolset as dgm
import part
import material
import assembly
import step
import interaction
import load
import mesh
import optimization
import job
import sketch
import visualization
import xyPlot
import displayGroupOdbToolset as dgo
import connectorBehavior
import csv
import time
# from datetime import datetime
# from matplotlib import pyplot as plt
#set working directory#
AbqFDir = r"C:\Users\trin3150\Documents\Abaqus\liltemp" #directory location for abaqus to use (best if local)
os.chdir(AbqFDir)
filename = 'VariablesCSV.csv' #must be placed into the working directory of abaqus (AbqFDir)
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
NumOfColumns = len(header_row)
NumOfTests = int(NumOfColumns-1)
# print(NumOfTests)
for i in range(1,NumOfTests):
print("\nData column = %d" % i)
with open(filename) as f:
reader = csv.reader(f)
variables, values = [], []
for row in reader:
# print(row)
current_var = row[0]
print(current_var)
# variables.append(current_var)
test_val = row[i]
print(test_val)
if len(test_val) > 0:
if isinstance(test_val, float):
current_value = float(test_val)
exec("%s = %f" % (current_var,current_value))
elif isinstance(test_val, str):
current_value = test_val
exec("%s = %s" % (current_var,current_value))
# values.append(current_value)
elif isinstance(test_val, int):
current_value = test_val
exec("%s = %d" % (current_var,current_value))
else:
exec("%s = %s" % (current_var,''))
else:
exec("%s = %s" % (current_var,''))
#initialise session#
mdb.Model(name=ModelName, modelType=STANDARD_EXPLICIT)
session.viewports['Viewport: 1'].setValues(displayedObject=None)
s = mdb.models[ModelName].ConstrainedSketch(name=ModelName, sheetSize=0.006)
g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
s.sketchOptions.setValues(decimalPlaces=4)
s.setPrimaryObject(option=STANDALONE)
#create sketch#
s.ConstructionLine(point1=(-0.000275, 0.0), point2=(0.0, 0.0))
s.HorizontalConstraint(entity=g[2], addUndoState=False)
s.Line(point1=(0.001, 0.0), point2=(0.001, 0.000500000040978193))
s.VerticalConstraint(entity=g[3], addUndoState=False)
s.PerpendicularConstraint(entity1=g[2], entity2=g[3], addUndoState=False)
s.CoincidentConstraint(entity1=v[0], entity2=g[2], addUndoState=False)
s.Line(point1=(0.001, 0.000500000040978193), point2=(0.000199999946542084,
0.000500000040978193))
s.HorizontalConstraint(entity=g[4], addUndoState=False)
s.PerpendicularConstraint(entity1=g[3], entity2=g[4], addUndoState=False)
s.Line(point1=(0.000199999946542084, 0.000500000040978193), point2=(
0.000199999946542086, 0.000299999978020787))
s.VerticalConstraint(entity=g[5], addUndoState=False)
s.PerpendicularConstraint(entity1=g[4], entity2=g[5], addUndoState=False)
s.Line(point1=(0.000199999946542086, 0.000299999978020787), point2=(
-0.000199999946542084, 0.000299999978020786))
s.HorizontalConstraint(entity=g[6], addUndoState=False)
s.PerpendicularConstraint(entity1=g[5], entity2=g[6], addUndoState=False)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00432733,
farPlane=0.00510076, width=0.0044371, height=0.00238451,
cameraPosition=(0.000222518, -0.000264382, 0.00471405), cameraTarget=(
0.000222518, -0.000264382, 0))
s.Line(point1=(-0.0006, 0.0005), point2=(-0.0006, 0.000900000050477684))
s.VerticalConstraint(entity=g[7], addUndoState=False)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00446327,
farPlane=0.00496482, width=0.00254243, height=0.00136631,
cameraPosition=(0.000816576, -7.76535e-005, 0.00471405), cameraTarget=(
0.000816576, -7.76535e-005, 0))
s.CoincidentConstraint(entity1=v[0], entity2=g[2])
s.CoincidentConstraint(entity1=v[0], entity2=g[2])
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00430264,
farPlane=0.00512545, width=0.00472032, height=0.00253671,
cameraPosition=(0.00169525, -0.0002707, 0.00471405), cameraTarget=(
0.00169525, -0.0002707, 0))
s.ArcByStartEndTangent(point1=(-0.000199999946542084, 0.000299999978020786),
point2=(-0.0006, 0.0005), entity=g[6])
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00418711,
farPlane=0.00524098, width=0.00604588, height=0.00324907,
cameraPosition=(0.00227586, -0.000336939, 0.00471405), cameraTarget=(
0.00227586, -0.000336939, 0))
s.ObliqueDimension(vertex1=v[0], vertex2=v[1], textPoint=(0.00150307640433311,
0.000271040771622211), value=h2/2)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00418711,
farPlane=0.00524098, width=0.00534214, height=0.00287088,
cameraPosition=(0.0021428, -0.000269356, 0.00471405), cameraTarget=(
0.0021428, -0.000269356, 0))
s.ObliqueDimension(vertex1=v[1], vertex2=v[2], textPoint=(0.000699343276210129,
0.000803338829427958), value=d2)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00439284,
farPlane=0.00503525, width=0.00325641, height=0.00175, cameraPosition=(
0.00121375, -6.2817e-005, 0.00471405), cameraTarget=(0.00121375,
-6.2817e-005, 0))
s.DistanceDimension(entity1=v[3], entity2=g[2], textPoint=(
0.000447663362137973, 0.000127766688819975), value=h1/2)
s.ObliqueDimension(vertex1=v[3], vertex2=v[4], textPoint=(5.98803162574768e-05,
0.00025412073591724), value=d1)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00449064,
farPlane=0.00493745, width=0.00226492, height=0.00121717,
cameraPosition=(0.000547788, 0.00012291, 0.00471405), cameraTarget=(
0.000547788, 0.00012291, 0))
session.viewports['Viewport: 1'].view.setValues(cameraPosition=(0.000257903,
0.000124375, 0.00471405), cameraTarget=(0.000257903, 0.000124375, 0))
s.DistanceDimension(entity1=v[5], entity2=g[2], textPoint=(
-0.000490404781885445, 3.7224919651635e-05), value=h3/2)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00451665,
farPlane=0.00491145, width=0.00226492, height=0.00121717,
cameraPosition=(0.000194848, 7.78864e-005, 0.00471405), cameraTarget=(
0.000194848, 7.78864e-005, 0))
s.DistanceDimension(entity1=g[7], entity2=g[5], textPoint=(
-0.000194330961676314, 0.0004374721320346), value=d3)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00449065,
farPlane=0.00493745, width=0.00226492, height=0.00121717,
cameraPosition=(0.0001934, 7.74268e-005, 0.00471405), cameraTarget=(
0.0001934, 7.74268e-005, 0))
s.FixedConstraint(entity=v[5])
session.viewports['Viewport: 1'].view.setValues(width=0.00240949,
height=0.00129486, cameraPosition=(0.000164645, 6.88886e-005,
0.00471405), cameraTarget=(0.000164645, 6.88886e-005, 0))
s.copyMirror(mirrorLine=g[2], objectList=(g[3], g[4], g[5], g[6], g[8], g[7]))
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00452849,
farPlane=0.00489961, width=0.00212902, height=0.00114414,
cameraPosition=(0.00011629, 6.14514e-005, 0.00471405), cameraTarget=(
0.00011629, 6.14514e-005, 0))
s.delete(objectList=(c[27], ))
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00444508,
farPlane=0.00498302, width=0.00308612, height=0.00165849,
cameraPosition=(0.000404486, -7.53105e-007, 0.00471405), cameraTarget=(
0.000404486, -7.53105e-007, 0))
s.Arc3Points(point1=(-0.000499999971191242, 0.000600000050477684), point2=(
-0.000499999971191242, -0.000600000050477684), point3=(-0.000775, 0.0))
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.0051597,
farPlane=0.00523016, width=0.000231577, height=0.000150995,
cameraPosition=(-0.000437469, 0.000592363, 0.00519493), cameraTarget=(
-0.000437469, 0.000592363, 0))
s.CoincidentConstraint(entity1=v[16], entity2=v[6])
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00510653,
farPlane=0.00528333, width=0.000581073, height=0.000378878,
cameraPosition=(-0.000318599, -0.000388514, 0.00519493), cameraTarget=(
-0.000318599, -0.000388514, 0))
session.viewports['Viewport: 1'].view.setValues(cameraPosition=(-0.000324365,
-0.000537245, 0.00519493), cameraTarget=(-0.000324365, -0.000537245,
0))
s.CoincidentConstraint(entity1=v[14], entity2=v[17])
s.DistanceDimension(entity1=v[18], entity2=g[7], textPoint=(
-0.000617911980953068, -6.11209543421865e-06), value=d4)
s.RadialDimension(curve=g[15], textPoint=(-0.000789811310824007,
0.000176487024873495), radius=r2)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00493921,
farPlane=0.0053339, width=0.00129724, height=0.000845841,
cameraPosition=(-0.000360502, 6.41261e-006, 0.00513656), cameraTarget=(
-0.000360502, 6.41261e-006, 0))
s.CoincidentConstraint(entity1=v[18], entity2=g[2])
#extrude sketch#
p = mdb.models[ModelName].Part(name=PrtName, dimensionality=THREE_D,
type=DEFORMABLE_BODY)
p = mdb.models[ModelName].parts[PrtName]
p.BaseSolidExtrude(sketch=s, depth=t)
s.unsetPrimaryObject()
p = mdb.models[ModelName].parts[PrtName]
session.viewports['Viewport: 1'].setValues(displayedObject=p)
del mdb.models[ModelName].sketches[ModelName]
#create partitions#
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#1 ]', ), )
e, v1, d1 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e[10], cells=pickedCells,
point=p.InterestingPoint(edge=e[10], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#3 ]', ), )
e1, v2, d2 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e1[27], cells=pickedCells,
point=p.InterestingPoint(edge=e1[27], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#9 ]', ), )
e, v1, d1 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e[21], cells=pickedCells,
point=p.InterestingPoint(edge=e[41], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#f ]', ), )
f = p.faces
p.PartitionCellByExtendFace(extendFace=f[31], cells=pickedCells)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#a8 ]', ), )
f1 = p.faces
p.PartitionCellByExtendFace(extendFace=f1[29], cells=pickedCells)
session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=ON,
engineeringFeatures=ON)
session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
referenceRepresentation=OFF)
#assign material#
mdb.models[ModelName].Material(name='Material-1')
mdb.models[ModelName].materials['Material-1'].Density(table=((dens, ), ))
mdb.models[ModelName].materials['Material-1'].Elastic(table=((E,
PRat), ))
#section part#
mdb.models[ModelName].HomogeneousSolidSection(name='Section-1',
material='Material-1', thickness=None)
del mdb.models[ModelName].sections['Section-1']
mdb.models[ModelName].HomogeneousSolidSection(name='Section-1',
material='Material-1', thickness=None)
a = mdb.models[ModelName].rootAssembly
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(
optimizationTasks=OFF, geometricRestrictions=OFF, stopConditions=OFF)
#create assembly#
a = mdb.models[ModelName].rootAssembly
a.DatumCsysByDefault(CARTESIAN)
p = mdb.models[ModelName].parts[PrtName]
a.Instance(name=InstName, part=p, dependent=ON)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00449812,
farPlane=0.00733091, width=0.00257805, height=0.00212468,
cameraPosition=(-0.0037457, 0.00262778, 0.00409448), cameraUpVector=(
-0.17802, 0.407271, -0.895789), cameraTarget=(-0.000287169,
3.21561e-005, 1.49071e-005))
#create useful sets#
a = mdb.models[ModelName].rootAssembly
f1 = a.instances[InstName].faces
faces1 = f1.getSequenceFromMask(mask=('[#0 #1004 ]', ), )
a.Set(faces=faces1, name=EncName)
a = mdb.models[ModelName].rootAssembly
v1 = a.instances[InstName].vertices
verts1 = v1.getSequenceFromMask(mask=('[#8000000 ]', ), )
a.Set(vertices=verts1, name=CentFreeName)
a = mdb.models[ModelName].rootAssembly
c1 = a.instances[InstName].cells
cells1 = c1.getSequenceFromMask(mask=('[#3ff ]', ), )
a.Set(cells=cells1, name='whole_prt')
a = mdb.models[ModelName].rootAssembly
f1 = a.instances[InstName].faces
faces1 = f1.getSequenceFromMask(mask=('[#50048 ]', ), )
a.Set(faces=faces1, name=TopSetName)
p1 = mdb.models[ModelName].parts[PrtName]
session.viewports['Viewport: 1'].setValues(displayedObject=p1)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#3ff ]', ), )
region = p.Set(cells=cells, name=WholePrt)
#section part#
p = mdb.models[ModelName].parts[PrtName]
p.SectionAssignment(region=region, sectionName='Section-1', offset=0.0,
offsetType=MIDDLE_SURFACE, offsetField='',
thicknessAssignment=FROM_SECTION)
#create new partitions#
pickedCells = c.getSequenceFromMask(mask=('[#41 ]', ), )
e, v, d = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e[60], cells=pickedCells,
point=p.InterestingPoint(edge=e[60], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#c00 ]', ), )
e1, v1, d1 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e1[84], cells=pickedCells,
point=p.InterestingPoint(edge=e1[84], rule=MIDDLE))
session.viewports['Viewport: 1'].partDisplay.setValues(mesh=ON)
session.viewports['Viewport: 1'].partDisplay.meshOptions.setValues(
meshTechnique=ON)
session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
referenceRepresentation=OFF)
#create undeformable material#
mdb.models[ModelName].Material(name='Material-2')
mdb.models[ModelName].materials['Material-2'].Density(table=((dens, ), ))
mdb.models[ModelName].materials['Material-2'].Elastic(table=((2e+15, PRat), ))
#delete old section assignment#
del mdb.models[ModelName].parts[PrtName].sectionAssignments[0]
#create new section assignment#
mdb.models[ModelName].HomogeneousSolidSection(name='Section-2',
material='Material-2', thickness=None)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#202f ]', ), )
region = p.Set(cells=cells, name='Undeformable-mat')
p = mdb.models[ModelName].parts[PrtName]
p.SectionAssignment(region=region, sectionName='Section-2', offset=0.0,
offsetType=MIDDLE_SURFACE, offsetField='',
thicknessAssignment=FROM_SECTION)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#1fd0 ]', ), )
region = p.Set(cells=cells, name='deformable-mat')
p = mdb.models[ModelName].parts[PrtName]
p.SectionAssignment(region=region, sectionName='Section-1', offset=0.0,
offsetType=MIDDLE_SURFACE, offsetField='',
thicknessAssignment=FROM_SECTION)
#generate new mesh#
p = mdb.models[ModelName].parts[PrtName]
p.seedPart(size=MeshSeedSize, deviationFactor=0.1, minSizeFactor=0.1)
p.generateMesh()
elemType1 = mesh.ElemType(elemCode=C3D20R, elemLibrary=STANDARD)
elemType2 = mesh.ElemType(elemCode=C3D15, elemLibrary=STANDARD)
elemType3 = mesh.ElemType(elemCode=C3D10, elemLibrary=STANDARD)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#3fff ]', ), )
pickedRegions =(cells, )
p.setElementType(regions=pickedRegions, elemTypes=(elemType1, elemType2,
elemType3))
#create steps#
a = mdb.models[ModelName].rootAssembly
a.regenerate()
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(
adaptiveMeshConstraints=ON)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00469895,
farPlane=0.00712223, width=0.00188493, height=0.000775242,
viewOffsetX=0.000207475, viewOffsetY=-0.000125154)
mdb.models[ModelName].StaticStep(name=SName, previous='Initial')
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
#regenerate part#
a.regenerate()
session.viewports['Viewport: 1'].setValues(displayedObject=a)
#create history output request#
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
regionDef=mdb.models[ModelName].rootAssembly.sets[CentFreeName]
mdb.models[ModelName].HistoryOutputRequest(name='H-Output-2',
createStepName=SName, variables=('U3', ), region=regionDef,
sectionPoints=DEFAULT, rebar=EXCLUDE)
#create forces#
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
a = mdb.models[ModelName].rootAssembly
region = a.sets[CentFreeName]
mdb.models[ModelName].ConcentratedForce(name='Load-2', createStepName=SName,
region=region, cf3=-1.0, distributionType=UNIFORM, field='',
localCsys=None)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
#create BCs#
a = mdb.models[ModelName].rootAssembly
region = a.sets[EncName]
mdb.models[ModelName].EncastreBC(name='BC-2', createStepName=SName,
region=region, localCsys=None)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=OFF, bcs=OFF,
predefinedFields=OFF, connectors=OFF)
#create job#
mdb.Job(name=JobName, model=ModelName, description='', type=ANALYSIS,
atTime=None, waitMinutes=0, waitHours=0, queue=None, memory=90,
memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,
modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='',
scratch='', resultsFormat=ODB, multiprocessingMode=DEFAULT, numCpus=NumCPUs,
numDomains=NumCPUs, numGPUs=0)
#create inp file#
mdb.jobs[JobName].writeInput(consistencyChecking=OFF)
#run job#
mdb.jobs[JobName].submit(consistencyChecking=OFF)#mdb.jobs['Job'+str(d[i])].submit(consistencyChecking=OFF)
#wait for job to finish#
mdb.jobs[JobName].waitForCompletion()#mdb.jobs['Job'+str(d[i])].waitForCompletion()
#create xy data#
a = mdb.models[ModelName].rootAssembly
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.mdbData.summary()
o3 = session.openOdb(
name=ODBName+JobName+'.odb')
session.viewports['Viewport: 1'].setValues(displayedObject=o3)
odb = session.odbs[JobName+'.odb']#odb = session.odbs[ODBName+JobName+'.odb']
xy1 = session.XYDataFromHistory(name='Data-1', odb=odb,
outputVariableName='Spatial displacement: U3 at Node 7 in NSET CENTER_OF_FREE_END',
steps=(SName, ), )
c1 = session.Curve(xyData=xy1)
#create output .rpt file#
x0 = session.xyDataObjects['Data-1']
session.writeXYReport(fileName=RPTName+'.rpt', xyData=(x0))
time.sleep(2)# -*- coding: mbcs -*-
# Do not delete the following import lines
from abaqus import *
from abaqusConstants import *
import __main__
#set names
import section
import regionToolset
import displayGroupMdbToolset as dgm
import part
import material
import assembly
import step
import interaction
import load
import mesh
import optimization
import job
import sketch
import visualization
import xyPlot
import displayGroupOdbToolset as dgo
import connectorBehavior
import csv
import time
# from datetime import datetime
# from matplotlib import pyplot as plt
#set working directory#
AbqFDir = r"C:\Users\trin3150\Documents\Abaqus\liltemp" #directory location for abaqus to use (best if local)
os.chdir(AbqFDir)
filename = 'VariablesCSV.csv' #must be placed into the working directory of abaqus (AbqFDir)
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
NumOfColumns = len(header_row)
NumOfTests = int(NumOfColumns-1)
# print(NumOfTests)
for i in range(1,NumOfTests):
print("\nData column = %d" % i)
with open(filename) as f:
reader = csv.reader(f)
variables, values = [], []
for row in reader:
# print(row)
current_var = row[0]
print(current_var)
# variables.append(current_var)
test_val = row[i]
print(test_val)
if len(test_val) > 0:
if isinstance(test_val, float):
current_value = float(test_val)
exec("%s = %f" % (current_var,current_value))
elif isinstance(test_val, str):
current_value = test_val
exec("%s = %s" % (current_var,current_value))
# values.append(current_value)
elif isinstance(test_val, int):
current_value = test_val
exec("%s = %d" % (current_var,current_value))
else:
exec("%s = %s" % (current_var,''))
else:
exec("%s = %s" % (current_var,''))
#initialise session#
mdb.Model(name=ModelName, modelType=STANDARD_EXPLICIT)
session.viewports['Viewport: 1'].setValues(displayedObject=None)
s = mdb.models[ModelName].ConstrainedSketch(name=ModelName, sheetSize=0.006)
g, v, d, c = s.geometry, s.vertices, s.dimensions, s.constraints
#create sketch#
s.sketchOptions.setValues(decimalPlaces=4)
s.setPrimaryObject(option=STANDALONE)
s.Line(point1=(-0.0003, 0.0002), point2=(0.0, 0.0002))
s.HorizontalConstraint(entity=g[2], addUndoState=False)
s.Line(point1=(0.0, 0.0002), point2=(0.0, 0.0004))
s.VerticalConstraint(entity=g[3], addUndoState=False)
s.PerpendicularConstraint(entity1=g[2], entity2=g[3], addUndoState=False)
s.Line(point1=(0.0, 0.0004), point2=(0.0003,
0.0004))
s.HorizontalConstraint(entity=g[4], addUndoState=False)
s.PerpendicularConstraint(entity1=g[3], entity2=g[4], addUndoState=False)
s.Line(point1=(0.0003, 0.0004), point2=(
0.0003, -0.0002))
s.VerticalConstraint(entity=g[5], addUndoState=False)
s.PerpendicularConstraint(entity1=g[4], entity2=g[5], addUndoState=False)
s.Line(point1=(0.0003, -0.0002), point2=(0.0,
-0.0002))
s.HorizontalConstraint(entity=g[6], addUndoState=False)
s.PerpendicularConstraint(entity1=g[5], entity2=g[6], addUndoState=False)
s.Line(point1=(0.0, -0.0002), point2=(0.0,
-7.5e-05))
s.VerticalConstraint(entity=g[7], addUndoState=False)
s.PerpendicularConstraint(entity1=g[6], entity2=g[7], addUndoState=False)
s.Line(point1=(0.0, -7.5e-05), point2=(-0.0003,
-7.5e-05))
s.HorizontalConstraint(entity=g[8], addUndoState=False)
s.PerpendicularConstraint(entity1=g[7], entity2=g[8], addUndoState=False)
s.Arc3Points(point1=(-0.0003, 0.0002), point2=(-0.0005, 0.00035), point3=(
-0.000425, 0.00025))
s.Arc3Points(point1=(-0.0003, -7.5e-05), point2=(
-0.0005, -0.0002), point3=(-0.000425, -0.0001))
s.Line(point1=(-0.0005, 0.00035), point2=(-0.0005, 0.0007))
s.VerticalConstraint(entity=g[11], addUndoState=False)
s.Line(point1=(-0.0005, -0.0002), point2=(-0.0005, -0.0005))
s.VerticalConstraint(entity=g[12], addUndoState=False)
s.Arc3Points(point1=(-0.0005, -0.0005), point2=(-0.0005,
0.0007), point3=(-0.000775, 0.0))
s.ConstructionLine(point1=(0.0, 0.0), point2=(5e-05, 0.0))
s.HorizontalConstraint(entity=g[14], addUndoState=False)
s.SymmetryConstraint(entity1=g[4], entity2=g[6], symmetryAxis=g[14])
s.SymmetryConstraint(entity1=g[2], entity2=g[8], symmetryAxis=g[14])
s.SymmetryConstraint(entity1=g[9], entity2=g[10], symmetryAxis=g[14])
s.SymmetryConstraint(entity1=v[13], entity2=v[12], symmetryAxis=g[14])
s.ObliqueDimension(vertex1=v[3], vertex2=v[4], textPoint=(0.0004,
1.4e-05), value=h2)
s.ObliqueDimension(vertex1=v[4], vertex2=v[5], textPoint=(0.00012,
-0.0005), value=d2)
s.DistanceDimension(entity1=g[2], entity2=g[8], textPoint=(
-0.00013, -3.4e-06), value=d1)
s.DistanceDimension(entity1=g[11], entity2=g[3], textPoint=(6e-07, 0.0),
value=d3)
s.DistanceDimension(entity1=v[14], entity2=g[12], textPoint=(
-0.00068, -0.0002), value=d4)
s.RadialDimension(curve=g[13], textPoint=(-0.0008,
0.0007), radius=r2)
s.TangentConstraint(entity1=g[9], entity2=g[2])
s.RadialDimension(curve=g[9], textPoint=(-0.0005,
0.0003), radius=r1)
s.dragEntity(entity=v[9], points=((-0.00106096395802383, 0.000567404644683332),
(-0.00105, 0.000575), (-0.0008, 0.000375), (-0.000625, 0.00025), (
-0.00055, 0.000225)))
s.dragEntity(entity=v[11], points=((-0.001136249659634, -0.000296156967864238),
(-0.001125, -0.0003), (-0.000725, -0.000125), (-0.000575, -7.5e-05), (
-0.00055, -7.5e-05)))
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00436022,
farPlane=0.00506787, width=0.00263219, height=0.00225061,
cameraPosition=(0.000328496, 0.000331514, 0.00471405), cameraTarget=(
0.000328496, 0.000331514, 0))
s.undo()
s.undo()
s.undo()
s.ObliqueDimension(vertex1=v[0], vertex2=v[1], textPoint=(
-0.00037, 0.0003), value=d1)
s.RadialDimension(curve=g[9], textPoint=(-0.0006,
0.0004), radius=r1)
s.dragEntity(entity=v[9], points=((-0.000970904952102452,
0.000316688240342015), (-0.000975, 0.000325), (-0.000775, 0.0002), (
-0.000675, 0.00015), (-0.00065, 0.00015)))
s.dragEntity(entity=v[11], points=((-0.000897071345175977,
-0.000221790082393968), (-0.0009, -0.000225), (-0.000675, -0.00015), (
-0.000625, -0.000125)))
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00405714,
farPlane=0.00537095, width=0.00431811, height=0.00369213,
cameraPosition=(0.000859323, 0.000700032, 0.00471405), cameraTarget=(
0.000859323, 0.000700032, 0))
#extrude sketch#
p = mdb.models[ModelName].Part(name=PrtName, dimensionality=THREE_D,
type=DEFORMABLE_BODY)
p = mdb.models[ModelName].parts[PrtName]
p.BaseSolidExtrude(sketch=s, depth=t)
s.unsetPrimaryObject()
p = mdb.models[ModelName].parts[PrtName]
session.viewports['Viewport: 1'].setValues(displayedObject=p)
del mdb.models[ModelName].sketches[ModelName]
#create partitions#
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#1 ]', ), )
e, v1, d1 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e[10], cells=pickedCells,
point=p.InterestingPoint(edge=e[10], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#3 ]', ), )
e1, v2, d2 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e1[27], cells=pickedCells,
point=p.InterestingPoint(edge=e1[27], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#9 ]', ), )
e, v1, d1 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e[21], cells=pickedCells,
point=p.InterestingPoint(edge=e[41], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#f ]', ), )
f = p.faces
p.PartitionCellByExtendFace(extendFace=f[31], cells=pickedCells)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#a8 ]', ), )
f1 = p.faces
p.PartitionCellByExtendFace(extendFace=f1[29], cells=pickedCells)
session.viewports['Viewport: 1'].partDisplay.setValues(sectionAssignments=ON,
engineeringFeatures=ON)
session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
referenceRepresentation=OFF)
#assign material#
mdb.models[ModelName].Material(name='Material-1')
mdb.models[ModelName].materials['Material-1'].Density(table=((dens, ), ))
mdb.models[ModelName].materials['Material-1'].Elastic(table=((E,
PRat), ))
#section part#
mdb.models[ModelName].HomogeneousSolidSection(name='Section-1',
material='Material-1', thickness=None)
del mdb.models[ModelName].sections['Section-1']
mdb.models[ModelName].HomogeneousSolidSection(name='Section-1',
material='Material-1', thickness=None)
a = mdb.models[ModelName].rootAssembly
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(
optimizationTasks=OFF, geometricRestrictions=OFF, stopConditions=OFF)
#create assembly#
a = mdb.models[ModelName].rootAssembly
a.DatumCsysByDefault(CARTESIAN)
p = mdb.models[ModelName].parts[PrtName]
a.Instance(name=InstName, part=p, dependent=ON)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00449812,
farPlane=0.00733091, width=0.00257805, height=0.00212468,
cameraPosition=(-0.0037457, 0.00262778, 0.00409448), cameraUpVector=(
-0.17802, 0.407271, -0.895789), cameraTarget=(-0.000287169,
3.21561e-005, 1.49071e-005))
#create useful sets#
a = mdb.models[ModelName].rootAssembly
f1 = a.instances[InstName].faces
faces1 = f1.getSequenceFromMask(mask=('[#0 #1004 ]', ), )
a.Set(faces=faces1, name=EncName)
a = mdb.models[ModelName].rootAssembly
v1 = a.instances[InstName].vertices
verts1 = v1.getSequenceFromMask(mask=('[#8000000 ]', ), )
a.Set(vertices=verts1, name=CentFreeName)
a = mdb.models[ModelName].rootAssembly
c1 = a.instances[InstName].cells
cells1 = c1.getSequenceFromMask(mask=('[#3ff ]', ), )
a.Set(cells=cells1, name='whole_prt')
a = mdb.models[ModelName].rootAssembly
f1 = a.instances[InstName].faces
faces1 = f1.getSequenceFromMask(mask=('[#50048 ]', ), )
a.Set(faces=faces1, name=TopSetName)
p1 = mdb.models[ModelName].parts[PrtName]
session.viewports['Viewport: 1'].setValues(displayedObject=p1)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#3ff ]', ), )
region = p.Set(cells=cells, name=WholePrt)
#section part#
p = mdb.models[ModelName].parts[PrtName]
p.SectionAssignment(region=region, sectionName='Section-1', offset=0.0,
offsetType=MIDDLE_SURFACE, offsetField='',
thicknessAssignment=FROM_SECTION)
#create new partitions#
pickedCells = c.getSequenceFromMask(mask=('[#41 ]', ), )
e, v, d = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e[60], cells=pickedCells,
point=p.InterestingPoint(edge=e[60], rule=MIDDLE))
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
pickedCells = c.getSequenceFromMask(mask=('[#c00 ]', ), )
e1, v1, d1 = p.edges, p.vertices, p.datums
p.PartitionCellByPlanePointNormal(normal=e1[84], cells=pickedCells,
point=p.InterestingPoint(edge=e1[84], rule=MIDDLE))
session.viewports['Viewport: 1'].partDisplay.setValues(mesh=ON)
session.viewports['Viewport: 1'].partDisplay.meshOptions.setValues(
meshTechnique=ON)
session.viewports['Viewport: 1'].partDisplay.geometryOptions.setValues(
referenceRepresentation=OFF)
#create undeformable material#
mdb.models[ModelName].Material(name='Material-2')
mdb.models[ModelName].materials['Material-2'].Density(table=((dens, ), ))
mdb.models[ModelName].materials['Material-2'].Elastic(table=((2e+15, PRat), ))
#delete old section assignment#
del mdb.models[ModelName].parts[PrtName].sectionAssignments[0]
#create new section assignment#
mdb.models[ModelName].HomogeneousSolidSection(name='Section-2',
material='Material-2', thickness=None)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#202f ]', ), )
region = p.Set(cells=cells, name='Undeformable-mat')
p = mdb.models[ModelName].parts[PrtName]
p.SectionAssignment(region=region, sectionName='Section-2', offset=0.0,
offsetType=MIDDLE_SURFACE, offsetField='',
thicknessAssignment=FROM_SECTION)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#1fd0 ]', ), )
region = p.Set(cells=cells, name='deformable-mat')
p = mdb.models[ModelName].parts[PrtName]
p.SectionAssignment(region=region, sectionName='Section-1', offset=0.0,
offsetType=MIDDLE_SURFACE, offsetField='',
thicknessAssignment=FROM_SECTION)
#generate new mesh#
p = mdb.models[ModelName].parts[PrtName]
p.seedPart(size=MeshSeedSize, deviationFactor=0.1, minSizeFactor=0.1)
p.generateMesh()
elemType1 = mesh.ElemType(elemCode=C3D20R, elemLibrary=STANDARD)
elemType2 = mesh.ElemType(elemCode=C3D15, elemLibrary=STANDARD)
elemType3 = mesh.ElemType(elemCode=C3D10, elemLibrary=STANDARD)
p = mdb.models[ModelName].parts[PrtName]
c = p.cells
cells = c.getSequenceFromMask(mask=('[#3fff ]', ), )
pickedRegions =(cells, )
p.setElementType(regions=pickedRegions, elemTypes=(elemType1, elemType2,
elemType3))
#create steps#
a = mdb.models[ModelName].rootAssembly
a.regenerate()
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(
adaptiveMeshConstraints=ON)
session.viewports['Viewport: 1'].view.setValues(nearPlane=0.00469895,
farPlane=0.00712223, width=0.00188493, height=0.000775242,
viewOffsetX=0.000207475, viewOffsetY=-0.000125154)
mdb.models[ModelName].StaticStep(name=SName, previous='Initial')
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
#regenerate part#
a.regenerate()
session.viewports['Viewport: 1'].setValues(displayedObject=a)
#create history output request#
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
regionDef=mdb.models[ModelName].rootAssembly.sets[CentFreeName]
mdb.models[ModelName].HistoryOutputRequest(name='H-Output-2',
createStepName=SName, variables=('U3', ), region=regionDef,
sectionPoints=DEFAULT, rebar=EXCLUDE)
#create forces#
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
a = mdb.models[ModelName].rootAssembly
region = a.sets[CentFreeName]
mdb.models[ModelName].ConcentratedForce(name='Load-2', createStepName=SName,
region=region, cf3=-1.0, distributionType=UNIFORM, field='',
localCsys=None)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(step=SName)
#create BCs#
a = mdb.models[ModelName].rootAssembly
region = a.sets[EncName]
mdb.models[ModelName].EncastreBC(name='BC-2', createStepName=SName,
region=region, localCsys=None)
session.viewports['Viewport: 1'].assemblyDisplay.setValues(loads=OFF, bcs=OFF,
predefinedFields=OFF, connectors=OFF)
#create job#
mdb.Job(name=JobName, model=ModelName, description='', type=ANALYSIS,
atTime=None, waitMinutes=0, waitHours=0, queue=None, memory=90,
memoryUnits=PERCENTAGE, getMemoryFromAnalysis=True,
explicitPrecision=SINGLE, nodalOutputPrecision=SINGLE, echoPrint=OFF,
modelPrint=OFF, contactPrint=OFF, historyPrint=OFF, userSubroutine='',
scratch='', resultsFormat=ODB, multiprocessingMode=DEFAULT, numCpus=NumCPUs,
numDomains=NumCPUs, numGPUs=0)
#create inp file#
mdb.jobs[JobName].writeInput(consistencyChecking=OFF)
#run job#
mdb.jobs[JobName].submit(consistencyChecking=OFF)#mdb.jobs['Job'+str(d[i])].submit(consistencyChecking=OFF)
#wait for job to finish#
mdb.jobs[JobName].waitForCompletion()#mdb.jobs['Job'+str(d[i])].waitForCompletion()
#create xy data#
a = mdb.models[ModelName].rootAssembly
session.viewports['Viewport: 1'].setValues(displayedObject=a)
session.mdbData.summary()
o3 = session.openOdb(
name=ODBName+JobName+'.odb')
session.viewports['Viewport: 1'].setValues(displayedObject=o3)
odb = session.odbs[JobName+'.odb']#odb = session.odbs[ODBName+JobName+'.odb']
xy1 = session.XYDataFromHistory(name='Data-1', odb=odb,
outputVariableName='Spatial displacement: U3 at Node 7 in NSET CENTER_OF_FREE_END',
steps=(SName, ), )
c1 = session.Curve(xyData=xy1)
#create output .rpt file#
x0 = session.xyDataObjects['Data-1']
session.writeXYReport(fileName=RPTName+'.rpt', xyData=(x0))
time.sleep(2)
| 49.070694
| 111
| 0.679912
| 4,577
| 38,177
| 5.652392
| 0.13546
| 0.032701
| 0.065401
| 0.060879
| 0.878049
| 0.837501
| 0.807738
| 0.795021
| 0.771559
| 0.750184
| 0
| 0.123425
| 0.170626
| 38,177
| 778
| 112
| 49.070694
| 0.693649
| 0.048799
| 0
| 0.764706
| 0
| 0
| 0.048173
| 0.002322
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.063128
| 0
| 0.063128
| 0.008608
| 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
|
4d461a31d56eb46b132a33eaade293d24cf06d87
| 129
|
py
|
Python
|
app/api/__init__.py
|
farbodab/flatteningthecurve
|
692fd9c8d78355e1208ff85a2cd1038da11c392f
|
[
"MIT"
] | 1
|
2020-03-24T23:46:29.000Z
|
2020-03-24T23:46:29.000Z
|
app/api/__init__.py
|
farbodab/flatteningthecurve
|
692fd9c8d78355e1208ff85a2cd1038da11c392f
|
[
"MIT"
] | 13
|
2021-02-08T20:51:14.000Z
|
2022-03-12T00:43:30.000Z
|
app/api/__init__.py
|
farbodab/flatteningthecurve
|
692fd9c8d78355e1208ff85a2cd1038da11c392f
|
[
"MIT"
] | 3
|
2020-06-09T20:24:29.000Z
|
2020-06-09T20:26:16.000Z
|
from flask import Blueprint
bp = Blueprint('api', __name__,cli_group='viz')
from app.api import routes
from app.api import vis
| 18.428571
| 47
| 0.767442
| 21
| 129
| 4.47619
| 0.619048
| 0.148936
| 0.212766
| 0.340426
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.139535
| 129
| 6
| 48
| 21.5
| 0.846847
| 0
| 0
| 0
| 0
| 0
| 0.046512
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.75
| 0
| 0.75
| 0.5
| 1
| 0
| 0
| null | 0
| 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
| 1
|
0
| 7
|
4d4ac5918518a5dcc1d82981a6270f53df6b63b2
| 223
|
py
|
Python
|
eda/accuracy/__init__.py
|
alexklapheke/eda
|
027b3b94fe7d308cdb7cf3637551f4db75142f24
|
[
"MIT"
] | null | null | null |
eda/accuracy/__init__.py
|
alexklapheke/eda
|
027b3b94fe7d308cdb7cf3637551f4db75142f24
|
[
"MIT"
] | null | null | null |
eda/accuracy/__init__.py
|
alexklapheke/eda
|
027b3b94fe7d308cdb7cf3637551f4db75142f24
|
[
"MIT"
] | null | null | null |
from .accuracy import accuracy_metrics
from .accuracy import multiaccuracy
from .accuracy import multiaccuracy_heatmap
from .accuracy import fuzzy_accuracy
from .accuracy import cohens_kappa
from .accuracy import test_LINE
| 31.857143
| 43
| 0.865471
| 29
| 223
| 6.482759
| 0.37931
| 0.382979
| 0.574468
| 0.329787
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.107623
| 223
| 6
| 44
| 37.166667
| 0.944724
| 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
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 8
|
4d6d91790d7be074d9b064c256e05c22db66c53f
| 6,630
|
py
|
Python
|
src/batch_pred_struct/menv_server/plotting.py
|
vam-sin/deepcys
|
db56c43748147eeeff96d95294bf1df43fbbaf8a
|
[
"MIT"
] | null | null | null |
src/batch_pred_struct/menv_server/plotting.py
|
vam-sin/deepcys
|
db56c43748147eeeff96d95294bf1df43fbbaf8a
|
[
"MIT"
] | 4
|
2020-11-13T17:15:10.000Z
|
2022-02-09T23:26:45.000Z
|
src/batch_pred_struct/menv_server/plotting.py
|
vam-sin/deepcys
|
db56c43748147eeeff96d95294bf1df43fbbaf8a
|
[
"MIT"
] | null | null | null |
import matplotlib.pyplot as plt
from pylab import *
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.cm as cm
import numpy as np
import string
import math
import sys
import re
input_file = sys.argv[1]
A = []
for index, line in enumerate(open(input_file)):
A.append(line.split()[1])
myset = set(A)
chains = list(myset)
no_of_chains = len(chains)
if no_of_chains < 5:
xDict = {}
yDict = {}
for item in chains:
listx = []
listy = []
with open(input_file) as f:
for line in f:
tok = line.split()
if tok[1] == item:
listx.append(re.sub('[a-zA-Z]+','',tok[2]))
listy.append(tok[9])
f.close()
xDict[item] = np.asarray(listx).astype(np.float)
yDict[item] = np.asarray(listy).astype(np.float)
number_of_subplots = no_of_chains
m = cm.ScalarMappable(cmap=cm.jet)
for v,item in zip(range(number_of_subplots),chains):
v = v+1
m.set_array(yDict[item])
ax1 = plt.subplot(number_of_subplots,1,v)
#ax1.set_ylim(-0.5,1.5)
l=ax1.scatter(xDict[item],yDict[item],c=yDict[item], cmap=plt.cm.get_cmap("gist_rainbow"), edgecolors='None',alpha=0.75 ,label='Colour based on rHpy values')
#l = ax1.plot(xDict[item],yDict[item])
ax1.set_title('chain: %s'%(item))
ax1.set_xlabel('Residue Numbers')
ax1.set_ylabel('rHpy', fontsize=15)
plt.tight_layout(rect = [0,0.01,1,0.95])
protein = input_file[:-9]
plt.suptitle('Graphical representation of Microenvironment of %s protein'%(protein.split('/')[-1:][0]))
# fig = matplotlib.pyplot.gcf()
# fig.set_size_inches(19.5,10.5)
#plt.show()
plt.savefig("%s.png"%(protein),bbox_inches='tight',dpi=200)
elif 4 < no_of_chains < 10:
subplots_adjust(hspace=0.75)
subplots_adjust(top=0.9)
subplots_adjust(bottom=-1.2)
xDict = {}
yDict = {}
for item in chains:
listx = []
listy = []
with open(input_file) as f:
for line in f:
tok = line.split()
if tok[1] == item:
listx.append(re.sub('[a-zA-Z]+','',tok[2]))
listy.append(tok[9])
f.close()
xDict[item] = np.asarray(listx).astype(np.float)
yDict[item] = np.asarray(listy).astype(np.float)
number_of_subplots = no_of_chains
m = cm.ScalarMappable(cmap=cm.jet)
for v,item in zip(range(number_of_subplots),chains):
v = v+1
m.set_array(yDict[item])
ax1 = plt.subplot(number_of_subplots,3,v)
#ax1.set_ylim(-0.5,1.5)
l=ax1.scatter(xDict[item],yDict[item],c=yDict[item], cmap=plt.cm.get_cmap("gist_rainbow"), edgecolors='None',alpha=0.75 ,label='Colour based on rHpy values')
#l = ax1.plot(xDict[item],yDict[item])
ax1.set_title('chain: %s'%(item))
ax1.set_xlabel('Residue Numbers')
ax1.set_ylabel('rHpy', fontsize=15)
#plt.colorbar(l)
#plt.tight_layout()
#rect = [0,0.01,1,0.95]
protein = input_file[:-9]
plt.suptitle('Graphical representation of Microenvironment of %s protein'%(protein.split('/')[-1:][0]))
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(19.5,10.5)
#plt.show()
plt.savefig("%s.png"%(protein),bbox_inches='tight')
elif 9 < no_of_chains < 13:
subplots_adjust(hspace=0.75)
subplots_adjust(top=0.9)
subplots_adjust(bottom=-1.5)
xDict = {}
yDict = {}
for item in chains:
listx = []
listy = []
with open(input_file) as f:
for line in f:
tok = line.split()
if tok[1] == item:
listx.append(re.sub('[a-zA-Z]+','',tok[2]))
listy.append(tok[9])
f.close()
xDict[item] = np.asarray(listx).astype(np.float)
yDict[item] = np.asarray(listy).astype(np.float)
number_of_subplots = no_of_chains
m = cm.ScalarMappable(cmap=cm.jet)
for v,item in zip(range(number_of_subplots),chains):
v = v+1
m.set_array(yDict[item])
ax1 = plt.subplot(number_of_subplots,3,v)
#ax1.set_ylim(-0.5,1.5)
l=ax1.scatter(xDict[item],yDict[item],c=yDict[item], cmap=plt.cm.get_cmap("gist_rainbow"), edgecolors='None',alpha=0.75 ,label='Colour based on rHpy values')
#l = ax1.plot(xDict[item],yDict[item])
ax1.set_title('chain: %s'%(item))
ax1.set_xlabel('Residue Numbers')
ax1.set_ylabel('rHpy', fontsize=15)
#plt.colorbar(l)
#plt.tight_layout()
#rect = [0,0.01,1,0.95]
protein = input_file[:-9]
plt.suptitle('Graphical representation of Microenvironment of %s protein'%(protein.split('/')[-1:][0]))
# manager = plt.get_current_fig_manager()
# manager.resize(*manager.window.maxsize())
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(19.5,10.5)
#plt.show()
plt.savefig("%s.png"%(protein),bbox_inches='tight')
else :
subplots_adjust(hspace=0.75)
subplots_adjust(top=0.9)
subplots_adjust(bottom=-1.2)
xDict = {}
yDict = {}
for item in chains:
listx = []
listy = []
with open(input_file) as f:
for line in f:
tok = line.split()
if tok[1] == item:
listx.append(re.sub('[a-zA-Z]+','',tok[2]))
listy.append(tok[9])
f.close()
xDict[item] = np.asarray(listx).astype(np.float)
yDict[item] = np.asarray(listy).astype(np.float)
number_of_subplots = no_of_chains
m = cm.ScalarMappable(cmap=cm.jet)
for v,item in zip(range(number_of_subplots),chains):
v = v+1
m.set_array(yDict[item])
ax1 = plt.subplot(number_of_subplots,5,v)
#ax1.set_ylim(-0.5,1.5)
l=ax1.scatter(xDict[item],yDict[item],c=yDict[item], cmap=plt.cm.get_cmap("gist_rainbow"), edgecolors='None',alpha=0.75 ,label='Colour based on rHpy values')
#l = ax1.plot(xDict[item],yDict[item])
ax1.set_title('chain: %s'%(item))
ax1.set_xlabel('Residue Numbers')
ax1.set_ylabel('rHpy', fontsize=15)
#plt.colorbar(l)
#plt.tight_layout()
#rect = [0,0.01,1,0.95]
protein = input_file[:-9]
plt.suptitle('Graphical representation of Microenvironment of %s protein'%(protein.split('/')[-1:][0]))
# manager = plt.get_current_fig_manager()
# manager.resize(*manager.window.maxsize())
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(19.5,10.5)
#plt.show()
plt.savefig("%s.png"%(protein),bbox_inches='tight')
| 30.837209
| 165
| 0.593514
| 968
| 6,630
| 3.948347
| 0.140496
| 0.047096
| 0.050235
| 0.037677
| 0.911826
| 0.911826
| 0.911826
| 0.911826
| 0.911826
| 0.911826
| 0
| 0.037059
| 0.242986
| 6,630
| 214
| 166
| 30.981308
| 0.724447
| 0.100452
| 0
| 0.826389
| 0
| 0
| 0.101061
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.0625
| 0
| 0.0625
| 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
|
4d78df662fab8d128ed4259c48780fc8e18bebec
| 283
|
py
|
Python
|
pixelcnn/__init__.py
|
jrmylee/pixelcnn
|
77bf8eb43547bc8ff1e254d961d81141900c0a58
|
[
"MIT"
] | 2
|
2020-05-18T18:04:22.000Z
|
2020-05-18T19:00:11.000Z
|
pixelcnn/__init__.py
|
jrmylee/pixelcnn
|
77bf8eb43547bc8ff1e254d961d81141900c0a58
|
[
"MIT"
] | 3
|
2020-01-27T02:47:02.000Z
|
2022-02-09T23:38:40.000Z
|
pixelcnn/__init__.py
|
jrmylee/pixelcnn
|
77bf8eb43547bc8ff1e254d961d81141900c0a58
|
[
"MIT"
] | 2
|
2020-05-18T19:02:54.000Z
|
2021-12-02T07:07:03.000Z
|
"""Author: Brandon Trabucco, Copyright 2020, MIT License"""
from pixelcnn.pixelcnn import PixelCNN
from pixelcnn.pixelcnn import ConditionalPixelCNN
from pixelcnn.pixelcnn_plus_plus import PixelCNNPlusPlus
from pixelcnn.pixelcnn_plus_plus import ConditionalPixelCNNPlusPlus
| 35.375
| 68
| 0.840989
| 31
| 283
| 7.548387
| 0.451613
| 0.205128
| 0.34188
| 0.222222
| 0.290598
| 0.290598
| 0
| 0
| 0
| 0
| 0
| 0.015936
| 0.113074
| 283
| 7
| 69
| 40.428571
| 0.916335
| 0.187279
| 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
|
1510dbbaf45fcc87bb436cd2c379f00ee7538efd
| 3,947
|
py
|
Python
|
souffle/math/maxmin.py
|
pauljxtan/souffle
|
7dcb8a99e0c9749089f07a5cc2732747944cbac6
|
[
"MIT"
] | 2
|
2019-08-16T15:15:08.000Z
|
2019-11-07T03:18:08.000Z
|
souffle/math/maxmin.py
|
pauljxtan/mathsci
|
7dcb8a99e0c9749089f07a5cc2732747944cbac6
|
[
"MIT"
] | 1
|
2019-09-15T15:52:13.000Z
|
2019-09-15T15:52:13.000Z
|
souffle/math/maxmin.py
|
pauljxtan/mathsci
|
7dcb8a99e0c9749089f07a5cc2732747944cbac6
|
[
"MIT"
] | 1
|
2019-11-07T03:16:23.000Z
|
2019-11-07T03:16:23.000Z
|
"""
Finding the maxima and minima of functions.
"""
import math
from souffle.constants import GOLDEN_RATIO
def golden_ratio_min(f, x1, x4, delta, n_iter=0):
"""
Recursively computes a local minimum of a function f, given an initial
search bracket (x1, x4).
@type f: function
@type x1: number
@param x1: start of initial search bracket
@type x4: number
@param x4: end of initial search bracket
@type delta: number
@param delta: desired accuracy
@type n_iter: number
@param n_iter: iteration counter
@rtype: number, number
@return: final value, iteration counter
"""
# Compute x2 and x3 from x1 and x4 according to the golden ratio rule
x3 = x1 + (1 / GOLDEN_RATIO) * (x4 - x1)
x1_x4_mid = (x1 + x4) / 2
x2 = x1_x4_mid - (x3 - x1_x4_mid)
# Evaluate the function at each point
f1 = f(x1)
f2 = f(x2)
f3 = f(x3)
f4 = f(x4)
# Check that at least one of f(x2), f(x3) is less than both f(x1) and f(x4)
#if not ((f2 < f1 and f2 < f4) or (f3 < f1 and f3 < f4)):
# raise ValueError("Neither f(x2) nor f(x3) is less than both f(x1) "\
# "and f(x4)")
# If f(x2) < f(x3), x3 becomes x4, x2 becomes x3
if f2 < f3:
x4 = x3
x3 = x2
# Compute the new x2
x1_x4_mid = (x1 + x4) / 2
x2 = x1_x4_mid - (x3 - x1_x4_mid)
# Evaluate the function at the new x2
f2 = f(x2)
# If f(x2) > f(x3), x2 becomes x1, x3 becomes x2
else:
x1 = x2
x2 = x3
# Compute the new x3
x3 = x1 + (1 / GOLDEN_RATIO) * (x4 - x1)
# Evaluate the function at the new x3
f3 = f(x3)
n_iter += 1
# If we have reached the desired accuracy, return the midpoint of x2 and x3
if abs(x4 - x1) < delta:
x_mid = (x2 + x3) / 2
return x_mid, n_iter
# Otherwise, repeat procedure
else:
return golden_ratio_min(f, x1, x4, delta, n_iter)
def golden_ratio_max(f, x1, x4, delta, n_iter=0):
"""
Recursively computes a local maximum of a function f, given an initial
search bracket (x1, x4).
@type f: function
@type x1: number
@param x1: start of initial search bracket
@type x4: number
@param x4: end of initial search bracket
@type delta: number
@param delta: desired accuracy
@type n_iter: number
@param n_iter: iteration counter
@rtype: number, number
@return: final value, iteration counter
"""
# Compute x2 and x3 from x1 and x4 according to the golden ratio rule
x3 = x1 + (1 / GOLDEN_RATIO) * (x4 - x1)
x1_x4_mid = (x1 + x4) / 2
x2 = x1_x4_mid - (x3 - x1_x4_mid)
# Evaluate the function at each point
f1 = -f(x1)
f2 = -f(x2)
f3 = -f(x3)
f4 = -f(x4)
# Check that at least one of -f(x2), -f(x3) is less than
# both -f(x1) and -f(x4)
#if not ((f2 < f1 and f2 < f4) or (f3 < f1 and f3 < f4)):
# raise ValueError("Neither -f(x2) nor -f(x3) is less than both -f(x1) "\
# "and -f(x4)")
# If -f(x2) < -f(x3), x3 becomes x4, x2 becomes x3
if f2 < f3:
x4 = x3
x3 = x2
# Compute the new x2
x1_x4_mid = (x1 + x4) / 2
x2 = x1_x4_mid - (x3 - x1_x4_mid)
# Evaluate the function at the new x2
f2 = -f(x2)
# If f(x2) > f(x3), x2 becomes x1, x3 becomes x2
else:
x1 = x2
x2 = x3
# Compute the new x3
x3 = x1 + (1 / GOLDEN_RATIO) * (x4 - x1)
# Evaluate the function at the new x3
f3 = -f(x3)
n_iter += 1
# If we have reached the desired accuracy, return the midpoint of x2 and x3
if abs(x4 - x1) < delta:
x_mid = (x2 + x3) / 2
return x_mid, n_iter
# Otherwise, repeat procedure
else:
return golden_ratio_max(f, x1, x4, delta, n_iter)
| 30.129771
| 80
| 0.555359
| 625
| 3,947
| 3.4224
| 0.1488
| 0.041141
| 0.039271
| 0.025245
| 0.951847
| 0.951847
| 0.951847
| 0.951847
| 0.951847
| 0.921926
| 0
| 0.083878
| 0.341525
| 3,947
| 130
| 81
| 30.361538
| 0.73913
| 0.560426
| 0
| 0.807692
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.038462
| false
| 0
| 0.038462
| 0
| 0.153846
| 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
|
1288eea01b75cff46753c0e186e58f32ffd0b6a2
| 19,341
|
py
|
Python
|
mpsp/src/active_members_parser.py
|
danielfireman-ifal/coletores
|
7bb3237ceb6376a536cde3435ded62ea6b9a4502
|
[
"MIT"
] | 18
|
2019-10-30T01:18:40.000Z
|
2022-03-15T11:52:45.000Z
|
mpsp/src/active_members_parser.py
|
danielfireman-ifal/coletores
|
7bb3237ceb6376a536cde3435ded62ea6b9a4502
|
[
"MIT"
] | 174
|
2019-11-01T18:57:16.000Z
|
2021-09-18T02:35:27.000Z
|
mpsp/src/active_members_parser.py
|
danielfireman-ifal/coletores
|
7bb3237ceb6376a536cde3435ded62ea6b9a4502
|
[
"MIT"
] | 9
|
2020-01-16T16:33:46.000Z
|
2022-01-13T07:39:00.000Z
|
import pandas as pd
import math
import parser
# Due to the different format of the spreadsheets, a specific parser is required for a few months
# Contains the parsers for monthly remuneration worksheets for active members:
# parse_jan_19: January 2019
# parse_feb_to_may_19: February to May 2019
# parse_jun_19: June 2019
# Adjust existing spreadsheet variations
def format_value(element):
if element == None:
return 0.0
if type(element) == str and "-" in element:
return 0.0
if element == "#N/DISP":
return 0.0
return element
# Parser for Active Members - January 2019
def parse_jan_19(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
alimentacao = format_value(row[16]) # Auxilio alimentação
moradia = format_value(row[17]) # Auxilio moradia
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
remuneracoes_temporarias = format_value(
row[18]
) # Outras Remunerações Temporárias
total_descontos = format_value(row[14])
contribuicao_previdenciaria = format_value(row[11])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
imposto_renda = format_value(row[12])
total_indenizacoes = alimentacao + moradia
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"housing_aid": moradia,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
# Retenção por teto constitucional
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# Parser for Active Members - February to May 2019
def parse_feb_to_may_19(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
alimentacao = format_value(row[16]) # Auxilio alimentação
ferias_pc = format_value(row[17]) # Férias em pecunia
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
remuneracoes_temporarias = format_value(
row[18]
) # Outras Remunerações Temporárias
total_descontos = format_value(row[14])
contribuicao_previdenciaria = format_value(row[11])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
imposto_renda = format_value(row[12])
total_indenizacoes = alimentacao + ferias_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + remuneracoes_temporarias
)
total_bruto = (
total_gratificacoes + total_indenizacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"ferias em pecunia": ferias_pc,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# Parser for Active Members - June 2019
def parse_jun_19(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
alimentacao = format_value(row[15]) # Auxilio alimentação
ferias_pc = format_value(row[16]) # Férias em pecunia
licensa_pc = format_value(row[17]) # Licença Prêmio em Pecúnia
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
remuneracoes_temporarias = format_value(
row[18]
) # Outras Remunerações Temporárias
total_descontos = format_value(row[13])
contribuicao_previdenciaria = format_value(row[11])
imposto_renda = format_value(row[12])
total_indenizacoes = alimentacao + ferias_pc + licensa_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"ferias em pecunia": ferias_pc,
"LP em pecunia": licensa_pc,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporarias": remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# January to May - 2018
def parse_jan_to_may_18(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
contribuicao_previdenciaria = format_value(row[11])
imposto_renda = format_value(row[12])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
total_descontos = format_value(row[14])
alimentacao = format_value(row[16]) # Auxilio alimentação
moradia = format_value(row[17]) # Auxilio moradia
ferias_pc = format_value(row[18])
licensa_pc = format_value(row[19])
outras_remuneracoes_temporarias = format_value(
row[20]
) # Gratificação Cumulativa, Gratific. Serv. Nat. Especial Art. 2 Ato 40, Gratific. Atuação Especial Ato 709/2011
total_indenizacoes = alimentacao + moradia + ferias_pc + licensa_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + outras_remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"housing_aid": moradia,
"vacation_pecuniary": ferias_pc,
"premium_license_pecuniary": licensa_pc
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ outras_remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": outras_remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
# Retenção por teto constitucional
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
# Juny to December - 2018
def parse_june_to_dec_18(file_name):
rows = parser.read_data(file_name).to_numpy()
begin_row = parser.get_begin_row(rows)
end_row = parser.get_end_row(rows, begin_row, file_name)
typeE = parser.type_employee(file_name)
activeE = "inativos" not in file_name
employees = {}
curr_row = 0
for row in rows:
if curr_row < begin_row:
curr_row += 1
continue
matricula = str(int(row[0])) # convert to string by removing the '.0'
name = row[1].strip() # removes blank spaces present in some cells
role = row[2] # cargo
workplace = row[3] # Lotação
sal_base = format_value(row[4]) # Salário Base
outras_remuneracoes = format_value(
row[5]
) # Outras Verbas Remuneratórias, Legais ou Judiciais
comissao = format_value(row[6]) # Função de Confiança ou Cargo em Comissão
grat_natal = format_value(row[7]) # Gratificação Natalina (13º sal.)
ferias = format_value(row[8]) # Férias (1/3 Constiticional)
permanencia = format_value(row[9]) # Abono de Permanência
contribuicao_previdenciaria = format_value(row[11])
imposto_renda = format_value(row[12])
teto_constitucional = format_value(row[13]) # Retenção por teto constitucional
total_descontos = format_value(row[14])
alimentacao = format_value(row[16]) # Auxilio alimentação
moradia = format_value(row[17]) # Auxilio moradia
ferias_pc = format_value(row[18])
outras_remuneracoes_temporarias = format_value(
row[19]
) # Gratificação Cumulativa, Gratific. Serv. Nat. Especial Art. 2 Ato 40, Gratific. Atuação Especial Ato 709/2011
total_indenizacoes = alimentacao + moradia + ferias_pc
total_gratificacoes = (
comissao + grat_natal + ferias + permanencia + outras_remuneracoes_temporarias
)
total_bruto = (
total_indenizacoes + total_gratificacoes + sal_base + outras_remuneracoes
)
employees[matricula] = {
"reg": matricula,
"name": name,
"role": role,
"type": typeE,
"workplace": workplace,
"active": activeE,
"income": {
"total": round(total_bruto, 2),
"wage": sal_base + outras_remuneracoes,
"perks": {
"total": round(total_indenizacoes, 2),
"food": alimentacao,
"housing_aid": moradia,
"vacation_pecuniary": ferias_pc,
},
"other": { # Gratificações
"total": round(total_gratificacoes, 2),
"trust_position": comissao,
"others_total": grat_natal
+ ferias
+ permanencia
+ outras_remuneracoes_temporarias,
"others": {
"Gratificação Natalina": grat_natal,
"Férias (1/3 constitucional)": ferias,
"Abono de Permanência": permanencia,
"Outras remunerações temporárias": outras_remuneracoes_temporarias,
},
},
},
"discounts": { # Discounts Object. Using abs to garantee numbers are positivo (spreadsheet have negative discounts).
"total": abs(total_descontos),
"prev_contribution": abs(contribuicao_previdenciaria),
# Retenção por teto constitucional
"ceil_retention": abs(teto_constitucional),
"income_tax": abs(imposto_renda),
},
}
curr_row += 1
if curr_row > end_row:
break
return employees
| 40.890063
| 129
| 0.565586
| 1,926
| 19,341
| 5.467809
| 0.108515
| 0.072073
| 0.0904
| 0.024689
| 0.935239
| 0.927832
| 0.919666
| 0.913778
| 0.913778
| 0.913778
| 0
| 0.021013
| 0.347965
| 19,341
| 473
| 130
| 40.890063
| 0.814051
| 0.166589
| 0
| 0.810427
| 0
| 0
| 0.090484
| 0.00156
| 0
| 0
| 0
| 0
| 0
| 1
| 0.014218
| false
| 0
| 0.007109
| 0
| 0.042654
| 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
|
12d40193c9922dd7c8bdc5cbe846ab0a1ec4bb7e
| 704
|
py
|
Python
|
pynumdiff/total_variation_regularization/__init__.py
|
fossabot/PyNumDiff
|
dccad2ad7a875f2ecccb0db2bb6e2afa392916d1
|
[
"MIT"
] | null | null | null |
pynumdiff/total_variation_regularization/__init__.py
|
fossabot/PyNumDiff
|
dccad2ad7a875f2ecccb0db2bb6e2afa392916d1
|
[
"MIT"
] | null | null | null |
pynumdiff/total_variation_regularization/__init__.py
|
fossabot/PyNumDiff
|
dccad2ad7a875f2ecccb0db2bb6e2afa392916d1
|
[
"MIT"
] | null | null | null |
from pynumdiff.total_variation_regularization.__total_variation_regularization__ import iterative_velocity as iterative_velocity
from pynumdiff.total_variation_regularization.__total_variation_regularization__ import velocity as velocity
from pynumdiff.total_variation_regularization.__total_variation_regularization__ import acceleration as acceleration
from pynumdiff.total_variation_regularization.__total_variation_regularization__ import jerk as jerk
from pynumdiff.total_variation_regularization.__total_variation_regularization__ import jerk_sliding as jerk_sliding
from pynumdiff.total_variation_regularization.__total_variation_regularization__ import smooth_acceleration as smooth_acceleration
| 100.571429
| 130
| 0.931818
| 78
| 704
| 7.717949
| 0.166667
| 0.27907
| 0.55814
| 0.269103
| 0.787375
| 0.787375
| 0.787375
| 0.787375
| 0.787375
| 0.538206
| 0
| 0
| 0.051136
| 704
| 6
| 131
| 117.333333
| 0.901198
| 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
| 1
| 1
| 1
| 1
| 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
| 12
|
12e1e7dc687a64e98127941d38304b080ca4bbf6
| 158
|
py
|
Python
|
db/data/autotest_files/pyta/student_files/submission.py
|
Xyene/Markus
|
c99d1a793101ccb5b24b9e6d3104bba73b06df35
|
[
"MIT"
] | 149
|
2015-01-03T08:27:59.000Z
|
2022-03-24T20:11:33.000Z
|
db/data/autotest_files/pyta/student_files/submission.py
|
Xyene/Markus
|
c99d1a793101ccb5b24b9e6d3104bba73b06df35
|
[
"MIT"
] | 1,472
|
2015-01-02T21:01:26.000Z
|
2022-03-24T16:14:31.000Z
|
db/data/autotest_files/pyta/student_files/submission.py
|
Xyene/Markus
|
c99d1a793101ccb5b24b9e6d3104bba73b06df35
|
[
"MIT"
] | 143
|
2015-01-05T22:18:17.000Z
|
2022-02-24T03:11:35.000Z
|
def return_true():
return True
def return_false():
return False
def loop():
while True:
pass
def return_json():
return ']}[{"\\'
| 10.533333
| 20
| 0.56962
| 19
| 158
| 4.578947
| 0.421053
| 0.310345
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.291139
| 158
| 14
| 21
| 11.285714
| 0.776786
| 0
| 0
| 0
| 0
| 0
| 0.044304
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.444444
| true
| 0.111111
| 0
| 0.333333
| 0.777778
| 0
| 1
| 0
| 0
| null | 1
| 0
| 0
| 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
| 1
| 1
| 1
| 0
| 1
| 1
| 0
|
0
| 7
|
425fb13d6d7ed189f88cac1a8f938c424a8f8bc7
| 6,524
|
py
|
Python
|
tests/test_use_cases/test_auth.py
|
astsu-dev/tv-schedule
|
1cea36147e66b7163df6f7098cfda4d43f3bdde2
|
[
"MIT"
] | null | null | null |
tests/test_use_cases/test_auth.py
|
astsu-dev/tv-schedule
|
1cea36147e66b7163df6f7098cfda4d43f3bdde2
|
[
"MIT"
] | null | null | null |
tests/test_use_cases/test_auth.py
|
astsu-dev/tv-schedule
|
1cea36147e66b7163df6f7098cfda4d43f3bdde2
|
[
"MIT"
] | null | null | null |
import datetime
from unittest import mock
import uuid
import pytest
from tvsched.application.exceptions.auth import UserAlreadyExistsError, UserNotFoundError
from tvsched.application.models.auth import (
UserAdd,
UserInRepo,
UserLogIn,
UserWithRoleAdd,
UserInRepoAdd,
)
from tvsched.application.use_cases.auth.add_user_use_case import AddUserUseCase
from tvsched.application.use_cases.auth.add_user_with_role_use_case import (
AddUserWithRoleUseCase,
)
from tvsched.application.use_cases.auth.log_in_user_use_case import LogInUserUseCase
from tvsched.entities.auth import Role
@pytest.mark.asyncio
async def test_add_user_with_role_use_case() -> None:
repo = mock.AsyncMock()
logger = mock.Mock()
use_case = AddUserWithRoleUseCase(repo, logger)
username = "user"
password_hash = "hash"
role = Role.USER
user_with_role = UserWithRoleAdd(username=username, password="password", role=role)
with mock.patch(
"tvsched.application.use_cases.auth.add_user_with_role_use_case.hash_password"
) as hash_password:
hash_password.return_value = password_hash
await use_case.execute(user_with_role)
repo.add_user.assert_awaited_once_with(
UserInRepoAdd(username=username, password_hash=password_hash, role=role)
)
assert logger.info.call_count == 2
@pytest.mark.asyncio
async def test_add_user_with_role_use_case_when_user_already_exists() -> None:
repo = mock.AsyncMock()
logger = mock.Mock()
use_case = AddUserWithRoleUseCase(repo, logger)
username = "user"
password_hash = "hash"
role = Role.USER
user_with_role = UserWithRoleAdd(username=username, password="password", role=role)
repo.add_user.side_effect = UserAlreadyExistsError(username)
with mock.patch(
"tvsched.application.use_cases.auth.add_user_with_role_use_case.hash_password"
) as hash_password:
hash_password.return_value = password_hash
with pytest.raises(UserAlreadyExistsError):
await use_case.execute(user_with_role)
repo.add_user.assert_awaited_once_with(
UserInRepoAdd(username=username, password_hash=password_hash, role=role)
)
assert logger.info.call_count == 2
@pytest.mark.asyncio
async def test_add_user_use_case() -> None:
repo = mock.AsyncMock()
logger = mock.Mock()
use_case = AddUserUseCase(repo, logger)
username = "user"
password_hash = "hash"
role = Role.USER
user_add = UserAdd(username=username, password="password")
with mock.patch(
"tvsched.application.use_cases.auth.add_user_with_role_use_case.hash_password"
) as hash_password:
hash_password.return_value = password_hash
await use_case.execute(user_add)
repo.add_user.assert_awaited_once_with(
UserInRepoAdd(username=username, password_hash=password_hash, role=role)
)
assert logger.info.call_count == 2
@pytest.mark.asyncio
async def test_add_user_use_case_when_user_already_exists() -> None:
repo = mock.AsyncMock()
logger = mock.Mock()
use_case = AddUserUseCase(repo, logger)
username = "user"
password_hash = "hash"
role = Role.USER
user_add = UserAdd(username=username, password="password")
repo.add_user.side_effect = UserAlreadyExistsError(username)
with mock.patch(
"tvsched.application.use_cases.auth.add_user_with_role_use_case.hash_password"
) as hash_password:
hash_password.return_value = password_hash
with pytest.raises(UserAlreadyExistsError):
await use_case.execute(user_add)
repo.add_user.assert_awaited_once_with(
UserInRepoAdd(username=username, password_hash=password_hash, role=role)
)
assert logger.info.call_count == 2
@pytest.mark.asyncio
async def test_log_in_user_use_case() -> None:
repo = mock.AsyncMock()
logger = mock.Mock()
use_case = LogInUserUseCase(
repo,
logger,
jwt_secret="secret",
jwt_expires_in=datetime.timedelta(seconds=3600),
jwt_algorithm="HS256",
)
username = "user"
password = "password"
password_hash = "$2b$12$7H.90bastmQ1Lqo0sVLxguLfmdW6pqLTT7Ky8IzPi/B/h.BRLTKgm"
role = Role.USER
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7ImlkIjoiYjZlZDc0N2YtZDNkOS00OTYyLWEwOTAtMjllMjYyM2EzZjYzIiwicm9sZSI6IlVTRVIifSwic3ViIjoiYjZlZDc0N2YtZDNkOS00OTYyLWEwOTAtMjllMjYyM2EzZjYzIiwiaWF0IjoxNjQzNTI2NzEzLCJleHAiOjE2NDM1MzAzMTN9.bLUDVQeJKSH4W75fVZ5VrbjB_OGo7HOpBB-cLzGbbbc"
user_log_in = UserLogIn(username=username, password=password)
repo.get_user_by_username.return_value = UserInRepo(
id=uuid.UUID("b6ed747f-d3d9-4962-a090-29e2623a3f63"),
username=username,
password_hash=password_hash,
role=role,
)
with mock.patch(
"tvsched.application.use_cases.auth.log_in_user_use_case.create_access_token_for_user"
) as create_access_token_for_user:
create_access_token_for_user.return_value = token
res = await use_case.execute(user_log_in)
assert res == token
repo.get_user_by_username.assert_awaited_once_with(username)
assert logger.info.call_count == 2
@pytest.mark.asyncio
async def test_log_in_user_use_case_when_user_not_exist() -> None:
repo = mock.AsyncMock()
logger = mock.Mock()
use_case = LogInUserUseCase(
repo,
logger,
jwt_secret="secret",
jwt_expires_in=datetime.timedelta(seconds=3600),
jwt_algorithm="HS256",
)
username = "user"
password = "password"
password_hash = "$2b$12$7H.90bastmQ1Lqo0sVLxguLfmdW6pqLTT7Ky8IzPi/B/h.BRLTKgm"
role = Role.USER
token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjp7ImlkIjoiYjZlZDc0N2YtZDNkOS00OTYyLWEwOTAtMjllMjYyM2EzZjYzIiwicm9sZSI6IlVTRVIifSwic3ViIjoiYjZlZDc0N2YtZDNkOS00OTYyLWEwOTAtMjllMjYyM2EzZjYzIiwiaWF0IjoxNjQzNTI2NzEzLCJleHAiOjE2NDM1MzAzMTN9.bLUDVQeJKSH4W75fVZ5VrbjB_OGo7HOpBB-cLzGbbbc"
user_log_in = UserLogIn(username=username, password=password)
repo.get_user_by_username.side_effect = UserNotFoundError(username)
with mock.patch(
"tvsched.application.use_cases.auth.log_in_user_use_case.create_access_token_for_user"
) as create_access_token_for_user:
create_access_token_for_user.return_value = token
with pytest.raises(UserNotFoundError):
await use_case.execute(user_log_in)
repo.get_user_by_username.assert_awaited_once_with(username)
assert logger.info.call_count == 2
| 33.979167
| 291
| 0.75
| 763
| 6,524
| 6.096986
| 0.12844
| 0.040628
| 0.028375
| 0.050301
| 0.894884
| 0.893164
| 0.892304
| 0.880267
| 0.861995
| 0.860275
| 0
| 0.022853
| 0.168302
| 6,524
| 191
| 292
| 34.157068
| 0.834501
| 0
| 0
| 0.728477
| 0
| 0
| 0.198038
| 0.181177
| 0
| 0
| 0
| 0
| 0.086093
| 1
| 0
| false
| 0.205298
| 0.066225
| 0
| 0.066225
| 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
| 1
| 0
| 0
| 0
| 0
|
0
| 8
|
42a670e3b22d78a5ff43f26ca2bd27190abacbb3
| 160
|
py
|
Python
|
src/lto/accounts/ecdsa/__init__.py
|
mustafa-travisci/lto-api.python
|
0493a46b69575e94d09a038dadf472b46f88d036
|
[
"MIT"
] | null | null | null |
src/lto/accounts/ecdsa/__init__.py
|
mustafa-travisci/lto-api.python
|
0493a46b69575e94d09a038dadf472b46f88d036
|
[
"MIT"
] | null | null | null |
src/lto/accounts/ecdsa/__init__.py
|
mustafa-travisci/lto-api.python
|
0493a46b69575e94d09a038dadf472b46f88d036
|
[
"MIT"
] | null | null | null |
from lto.accounts.ecdsa.account_ecdsa import AccountECDSA as Account
from lto.accounts.ecdsa.account_factory_ecdsa import AccountFactoryECDSA as AccountFactory
| 53.333333
| 90
| 0.8875
| 21
| 160
| 6.619048
| 0.52381
| 0.100719
| 0.215827
| 0.28777
| 0.388489
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.075
| 160
| 2
| 91
| 80
| 0.939189
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 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
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 7
|
c420096761ac294668c6a81e4385058f45a521fd
| 10,587
|
py
|
Python
|
test/programytest/rdf/test_collection.py
|
cdoebler1/AIML2
|
ee692ec5ea3794cd1bc4cc8ec2a6b5e5c20a0d6a
|
[
"MIT"
] | 345
|
2016-11-23T22:37:04.000Z
|
2022-03-30T20:44:44.000Z
|
test/programytest/rdf/test_collection.py
|
MikeyBeez/program-y
|
00d7a0c7d50062f18f0ab6f4a041068e119ef7f0
|
[
"MIT"
] | 275
|
2016-12-07T10:30:28.000Z
|
2022-02-08T21:28:33.000Z
|
test/programytest/rdf/test_collection.py
|
VProgramMist/modified-program-y
|
f32efcafafd773683b3fe30054d5485fe9002b7d
|
[
"MIT"
] | 159
|
2016-11-28T18:59:30.000Z
|
2022-03-20T18:02:44.000Z
|
import unittest
from programy.rdf.collection import RDFCollection
class RDFCollectionTests(unittest.TestCase):
def test_properties(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
self.assertEquals({}, collection.entities)
self.assertEquals({}, collection.entities_to_ids)
self.assertEquals({}, collection.stores)
self.assertEquals({}, collection.entities_to_stores)
self.assertEquals([], collection.subjects())
self.assertEquals([], collection.predicates('ACCOUNT'))
self.assertEquals([], collection.objects('ACCOUNT', 'HASSIZE'))
self.assertIsNone(collection.storename("BANKING"))
def test_add_collection(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
self.assertIsNone(collection.storename("BANKING"))
self.assertFalse(collection.has_object('ACCOUNTX', 'hasSize', "0"))
self.assertFalse(collection.has_object('ACCOUNT', 'hasSizeX', "0"))
self.assertFalse(collection.has_object('ACCOUNT', 'hasSize', "§"))
self.assertEquals(['ACCOUNT'], collection.subjects())
self.assertEquals(['HASSIZE'], collection.predicates('ACCOUNT'))
self.assertEquals([], collection.predicates('ACCOUNTXX'))
self.assertEquals([['0']], collection.objects('ACCOUNT', 'HASSIZE'))
self.assertEquals([], collection.objects('ACCOUNT', 'HASSIZEXX'))
def test_add_collection_with_rdfstore_entityid(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANKING", rdf_store="file", entityid="1")
collection.add_entity("ACCOUNT", "hasSize", "0", "BANKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
self.assertFalse(collection.has_object('ACCOUNTX', 'hasSize', "0"))
self.assertFalse(collection.has_object('ACCOUNT', 'hasSizeX', "0"))
self.assertFalse(collection.has_object('ACCOUNT', 'hasSize', "§"))
self.assertEquals("file", collection.storename("BANKING"))
self.assertEquals("BANKING", collection.entities_to_stores["ACCOUNT"])
entities = collection.entities_to_ids["1"]
self.assertIsNotNone(entities)
self.assertEquals(1, len(entities))
self.assertEquals({'HASSIZE': ['0', '0']}, entities[0].predicates)
def test_add_multi_object_collection(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACTOR", "ISA", "PERSON", "TEST")
collection.add_entity("ACTOR", "ISA", "MAN", "TEST")
self.assertTrue(collection.has_subject('ACTOR'))
self.assertTrue(collection.has_predicate('ACTOR', 'ISA'))
self.assertTrue(collection.has_object('ACTOR', 'ISA', "PERSON"))
self.assertTrue(collection.has_object('ACTOR', 'ISA', "MAN"))
def test_delete_collection_subject(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNT")
self.assertFalse(collection.has_subject('ACCOUNT'))
def test_delete_collection_subject_not_exists(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNTX")
self.assertTrue(collection.has_subject('ACCOUNT'))
def test_delete_collection_subject_predicate(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNT", "hasSize")
self.assertFalse(collection.has_subject('ACCOUNT'))
def test_delete_collection_subject_predicate_no_exists_no_obj(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNT", "hasSizeX")
self.assertTrue(collection.has_subject('ACCOUNT'))
def test_delete_collection_subject_predicate_no_exists_with_obj(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNT", "hasSizeX", "0")
self.assertTrue(collection.has_subject('ACCOUNT'))
def test_delete_collection_subject_predicate_object(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNT", "hasSize", "0")
self.assertFalse(collection.has_subject('ACCOUNT'))
self.assertFalse(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertFalse(collection.has_object('ACCOUNT', 'hasSize', "0"))
def test_delete_collection_subject_predicate_diff_object(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANKING", "BANIKING")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
collection.delete_entity("ACCOUNT", "hasSize", "1")
self.assertTrue(collection.has_subject('ACCOUNT'))
self.assertTrue(collection.has_predicate('ACCOUNT', 'hasSize'))
self.assertTrue(collection.has_object('ACCOUNT', 'hasSize', "0"))
def test_add_collection_multiple_with_entityid(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANKING", entityid="1")
collection.add_entity("ACCOUNT", "hasValue", "1", "BANKING", entityid="1")
self.assertEquals("BANKING", collection.entities_to_stores["ACCOUNT"])
entities = collection.entities_to_ids["1"]
self.assertIsNotNone(entities)
self.assertEquals(1, len(entities))
self.assertEquals({'HASSIZE': ['0'], 'HASVALUE': ['1']}, entities[0].predicates)
def test_add_collection_multiple_with_entityid2(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", "BANKING", entityid="1")
collection.add_entity("BALANCE", "hasValue", "1", "BANKING", entityid="1")
self.assertEquals("BANKING", collection.entities_to_stores["ACCOUNT"])
entities = collection.entities_to_ids["1"]
self.assertIsNotNone(entities)
self.assertEquals(2, len(entities))
self.assertEquals({'HASSIZE': ['0']}, entities[0].predicates)
self.assertEquals({'HASVALUE': ['1']}, entities[1].predicates)
def test_empty_all(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", rdf_name="BANKING", rdf_store="TEST", entityid="1")
collection.add_entity("BALANCE", "hasValue", "1", rdf_name="BANKING", rdf_store="TEST", entityid="2")
collection.add_entity("WALKING", "hasSize", "0", rdf_name="ACTIVITY", rdf_store="TEST", entityid="3")
collection.add_entity("RUNNING", "hasValue", "1", rdf_name="ACTIVITY", rdf_store="TEST", entityid="4")
self.assertEquals("BANKING", collection.entities_to_stores['ACCOUNT'])
self.assertEquals("ACTIVITY", collection.entities_to_stores['RUNNING'])
self.assertTrue(collection.contains('BANKING'))
self.assertTrue(collection.contains('ACTIVITY'))
collection.empty()
self.assertFalse(collection.contains('BANKING'))
self.assertFalse(collection.contains('ACTIVITY'))
def test_empty_by_name(self):
collection = RDFCollection()
self.assertIsNotNone(collection)
collection.add_entity("ACCOUNT", "hasSize", "0", rdf_name="BANKING", rdf_store="TEST", entityid="1")
collection.add_entity("BALANCE", "hasValue", "1", rdf_name="BANKING", rdf_store="TEST", entityid="2")
collection.add_entity("WALKING", "hasSize", "0", rdf_name="ACTIVITY", rdf_store="TEST", entityid="3")
collection.add_entity("RUNNING", "hasValue", "1", rdf_name="ACTIVITY", rdf_store="TEST", entityid="4")
self.assertEquals("BANKING", collection.entities_to_stores['ACCOUNT'])
self.assertEquals("ACTIVITY", collection.entities_to_stores['RUNNING'])
self.assertTrue(collection.contains('BANKING'))
self.assertTrue(collection.contains('ACTIVITY'))
collection.empty("BANKING")
self.assertFalse(collection.contains('BANKING'))
self.assertTrue(collection.contains('ACTIVITY'))
| 43.747934
| 110
| 0.681213
| 1,064
| 10,587
| 6.605263
| 0.071429
| 0.088788
| 0.143426
| 0.142146
| 0.911924
| 0.85074
| 0.78543
| 0.767501
| 0.750427
| 0.750427
| 0
| 0.008061
| 0.168036
| 10,587
| 241
| 111
| 43.929461
| 0.789623
| 0
| 0
| 0.662791
| 0
| 0
| 0.147634
| 0
| 0
| 0
| 0
| 0
| 0.598837
| 1
| 0.087209
| false
| 0
| 0.011628
| 0
| 0.104651
| 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
|
c43aad35a5d48f0d2f4e14ff48b0e8f4c2eeedb0
| 237
|
py
|
Python
|
src/cbc_sdk/credential_providers/__init__.py
|
kphsugntuedutw/carbon-black-cloud-sdk-python
|
5277be067223bc3eda0348c57b2a0004fa70f3e9
|
[
"MIT"
] | null | null | null |
src/cbc_sdk/credential_providers/__init__.py
|
kphsugntuedutw/carbon-black-cloud-sdk-python
|
5277be067223bc3eda0348c57b2a0004fa70f3e9
|
[
"MIT"
] | null | null | null |
src/cbc_sdk/credential_providers/__init__.py
|
kphsugntuedutw/carbon-black-cloud-sdk-python
|
5277be067223bc3eda0348c57b2a0004fa70f3e9
|
[
"MIT"
] | null | null | null |
from __future__ import absolute_import
from .file_credential_provider import FileCredentialProvider
from .environ_credential_provider import EnvironCredentialProvider
from .registry_credential_provider import RegistryCredentialProvider
| 39.5
| 68
| 0.915612
| 23
| 237
| 8.956522
| 0.521739
| 0.262136
| 0.349515
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.07173
| 237
| 5
| 69
| 47.4
| 0.936364
| 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
|
671ef52d901285811ff7bbfeaa341c5620365fb8
| 27,105
|
py
|
Python
|
newscout_web/analytics/views.py
|
rsqwerty/newscout_web
|
8be095cc3e1a95d6ccf5cd8c43d3f13746b263f2
|
[
"Apache-2.0"
] | null | null | null |
newscout_web/analytics/views.py
|
rsqwerty/newscout_web
|
8be095cc3e1a95d6ccf5cd8c43d3f13746b263f2
|
[
"Apache-2.0"
] | null | null | null |
newscout_web/analytics/views.py
|
rsqwerty/newscout_web
|
8be095cc3e1a95d6ccf5cd8c43d3f13746b263f2
|
[
"Apache-2.0"
] | null | null | null |
import pytz
import calendar
from itertools import groupby
from operator import itemgetter
from datetime import datetime, time, timedelta
from django.views.generic.base import TemplateView
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from api.v1.views import create_response
from api.v1.exception_handler import create_error_response
from event_tracking.models import Event
class IndexView(TemplateView):
template_name = "analytics_index.html"
def get_context_data(self, **kwargs):
context = super(IndexView, self).get_context_data(**kwargs)
return context
class ParseDateRange():
tz = pytz.timezone('Asia/Kolkata')
def parse_datetime(self, date_range):
first_date = date_range.split('-')[0].strip()
first_date_obj = datetime.strptime(first_date, '%m/%d/%Y %H:%M:%S')
first_date_obj = datetime.combine(first_date_obj, time.min)
last_date = date_range.split('-')[-1].strip()
last_date_obj = datetime.strptime(last_date, '%m/%d/%Y %H:%M:%S')
last_date_obj = datetime.combine(last_date_obj, time.max)
# first_aware = first_date_obj.replace(tzinfo=self.tz)
# last_aware = last_date_obj.replace(tzinfo=self.tz)
# first_date_obj = first_aware.astimezone(pytz.UTC)
# last_date_obj = last_aware.astimezone(pytz.UTC)
return first_date_obj, last_date_obj
def get_default_date_range(self):
end_date = datetime.now().date()
start_date = end_date - timedelta(days=6)
start_date = datetime.combine(start_date, time.min)
end_date = datetime.combine(end_date, time.max)
# start_aware = start_date.replace(tzinfo=self.tz)
# end_aware = end_date.replace(tzinfo=self.tz)
# start_date_obj = start_aware.astimezone(pytz.UTC)
# end_date_obj = end_aware.astimezone(pytz.UTC)
return start_date, end_date, ""
def get_date_range(self, date_range):
if date_range:
if date_range == "today":
date = datetime.now().date()
start_date = datetime.combine(date, time.min)
end_date = datetime.combine(date, time.max)
return start_date, end_date, ""
elif date_range == "yesterday":
date = datetime.now().date() - timedelta(days=1)
start_date = datetime.combine(date, time.min)
end_date = datetime.combine(date, time.max)
return start_date, end_date, ""
elif date_range == "7days":
return self.get_default_date_range()
elif date_range == "30days":
date = datetime.now().date() - timedelta(days=30)
start_date = datetime.combine(date, time.min)
end_date = datetime.combine(datetime.now().date(), time.max)
return start_date, end_date, ""
elif date_range == "last_month":
date = datetime.now().date()
y, m = calendar.prevmonth(date.year, date.month)
start_date = datetime(y, m, 1)
end_date = datetime(y, m, calendar.monthlen(y, m))
end_date = datetime.combine(end_date, time.max)
return start_date, end_date, ""
else:
try:
start_date, end_date = self.parse_datetime(date_range)
return start_date, end_date, ""
except Exception as e:
return "", "", create_error_response(
{"Msg": "Invalid date range"})
else:
start_date, end_date, error = self.get_default_date_range()
return start_date, end_date, error
class AllArticlesOpen(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [{
"$match": {
"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match": {
"$or": [{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$project": {
"_id": 0, "datePartDay": {
"$concat": [{"$substr": [
{"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},
"platform": "$platform"}},
{"$group": {"_id": "$datePartDay", "count": {"$sum": 1}}},
{"$project": {
"_id": 0, "dateStr": "$_id",
"dateObj": {
"$dateFromString": {"dateString": "$_id"}},
"count": "$count"}},
{"$group": {
"_id":"count","avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match": {"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}
]}},
{"$project": {"_id": 0, "datePartDay": {
"$concat": [
{"$substr": [
{"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},
"platform": "$platform"}},
{"$group": {"_id": "$datePartDay", "count": {"$sum": 1}}},
{"$project": {
"_id": 0, "dateStr": "$_id", "dateObj": {"$dateFromString": {"dateString": "$_id"}},
"count": "$count"}},
{"$sort": {"dateObj": 1}}]
data = list(self.events.collection.aggregate(pipeline))
if data:
max_func = lambda x: x["count"]
max_values = max(data, key=max_func)
avg = self.get_avg(start_date, end_date)
res = {
"data": data,
"max": {"count": max_values["count"],
"dateStr": max_values["dateStr"]}
}
no_data = False
else:
res = {
"data": [{"dateStr": "0", "dateObj": "0", "count": 0}],
"max": {"count": None, "dateStr": None},
"dateStr": 0,
"avg_count": 0
}
no_data = True
avg = {"avg_count": 0}
return Response(create_response(
{"result": res, "no_data": no_data, "avg_count": avg["avg_count"]}))
class ArticlesPerPlatform(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match":
{"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$project":
{"_id": 0,
"datePartDay": {
"$concat": [
{"$substr": [ {"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},
"platform": "$platform"}},
{"$group":
{"_id":
{"datePartDay": "$datePartDay",
"platform": "$platform"}, "count": {"$sum": 1}}},
{"$project":
{"_id": 0,
"dateObj":
{"$dateFromString":
{"dateString": "$_id.datePartDay"}},
"count": "$count",
"platform": "$_id.platform",
"dateStr": "$_id.datePartDay"}},
{"$group": {
"_id":"$platform","avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match":
{"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$project":
{"_id": 0,
"datePartDay": {
"$concat": [
{"$substr": [ {"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},
"platform": "$platform"}},
{"$group":
{"_id":
{"datePartDay": "$datePartDay",
"platform": "$platform"}, "count": {"$sum": 1}}},
{"$project":
{"_id": 0,
"dateObj":
{"$dateFromString":
{"dateString": "$_id.datePartDay"}},
"count": "$count",
"platform": "$_id.platform",
"dateStr": "$_id.datePartDay"}},
{"$sort": {"dateObj": 1}}]
data = list(self.events.collection.aggregate(pipeline))
if data:
res = []
for key, values in groupby(data, itemgetter("dateStr")):
d = {"dateStr": key}
for v in values:
d[v["platform"]] = v["count"]
res.append(d)
no_data = False
avg = self.get_avg(start_date, end_date)
else:
res = {"dateStr": None, "web": 0, "android": 0, "ios": 0}
no_data = True
avg = {"avg_count": 0}
return Response(create_response({"result": res, "no_data": no_data, "avg_count": avg["avg_count"]}))
class ArticlesPerCategory(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match":
{"ts": {
"$gte": start_date, "$lte": end_date}}},
{"$match":
{"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$group": {"_id":
{"category_id": "$category_id",
"category_name": "$category_name"},
"count": {"$sum": 1}}},
{"$group": {
"_id":"$category_id","avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match":
{"ts": {
"$gte": start_date, "$lte": end_date}}},
{"$match":
{"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$group": {"_id":
{"category_id": "$category_id",
"category_name": "$category_name"},
"count": {"$sum": 1}}},
{"$project": {
"_id": 0, "category_id": "$_id.category_id",
"category_name": "$_id.category_name", "count": "$count"}}]
data = list(self.events.collection.aggregate(pipeline))
no_data = False
if not data:
data = [{"category_id":0, "category_name": None, "count": 0}]
no_data = True
avg = {"avg_count": 0}
else:
avg = self.get_avg(start_date, end_date)
return Response(create_response(
{"result": data, "no_data": no_data, "avg_count": avg["avg_count"]}))
class InteractionsPerCategory(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$group": {"_id": {"category": "$category_id",
"category_name": "$category_name", "action":"$action"},
"count": {"$sum": 1}}},
{"$group": {"_id": {"category": "$_id.category",
"category_name": "$_id.category_name"},
"total": {"$sum": "$count"} }},
{"$group": {
"_id":"$category", "avg_count": {"$avg":"$total"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$group": {"_id": {"category": "$category_id",
"category_name": "$category_name", "action":"$action"},
"count": {"$sum": 1}}},
{"$group": {"_id": {"category": "$_id.category",
"category_name": "$_id.category_name"},
"total": {"$sum": "$count"} }},
{"$project": {"_id": 0, "category_id": "$_id.category",
"category_name": "$_id.category_name",
"total_interactions": "$total"}}]
data = list(self.events.collection.aggregate(pipeline))
no_data = False
if not data:
data = [{
"category_id": None,
"category_name": None,
"total_transactions": 0}]
no_data = True
avg = {"avg_count": 0}
else:
avg = self.get_avg(start_date, end_date)
return Response(create_response(
{"result": data, "no_data": no_data, "avg_count": avg["avg_count"]}))
class ArticlesPerAuthor(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match": {"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$group": {"_id": "$author_name", "count": {"$sum": 1}}},
{"$group": {
"_id":"_id", "avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match": {"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$group": {"_id": "$author_name", "count": {"$sum": 1}}},
{"$project": {
"_id": 0, "name": "$_id", "article_count": "$count"}}
]
data = list(self.events.collection.aggregate(pipeline))
no_data = False
if not data:
data = [{"name": None, "article_count": 0}]
no_data = True
avg = {"avg_count": 0}
else:
avg = self.get_avg(start_date, end_date)
return Response(create_response(
{"result": data, "no_data": no_data, "avg_count": avg["avg_count"]}))
class InteractionsPerAuthor(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match": {"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$group": {"_id": {
"action": "$action",
"author_name":"$author_name"}, "count": {"$sum": 1}}},
{"$group": {
"_id":"_id", "avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}
]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match": {"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$group": {"_id": {
"action": "$action",
"author_name":"$author_name"}, "count": {"$sum": 1}}},
{"$project": {
"_id": 0, "author": "$_id.author_name",
"action": "$_id.action", "count": "$count"}},
{"$sort": {"author": 1}}
]
data = list(self.events.collection.aggregate(pipeline))
if data:
res = []
for key, values in groupby(data, itemgetter("author")):
d = {"author": key}
for v in values:
d[v["action"]] = v["count"]
res.append(d)
no_data = False
avg = self.get_avg(start_date, end_date)
else:
res = [{
"author": None,
"article_details": 0,
"article_search_details": 0}]
no_data = True
avg = {"avg_count": 0}
return Response(create_response(
{"result": res, "no_data": no_data, "avg_count": avg["avg_count"]}))
class ArticlesPerSession(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match":{"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$project":{
"_id": 0,
"datePartDay": {
"$concat": [
{"$substr": [ {"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},"sid": "$sid"}},
{"$group": {
"_id": {
"datePartDay": "$datePartDay",
"sid": "$sid"},
"count": {"$sum": 1}}},
{"$project": {
"_id": 0,
"dateObj": {
"$dateFromString":{"dateString": "$_id.datePartDay"}},
"count": "$count",
"sid": "$_id.sid",
"dateStr": "$_id.datePartDay"}},
{"$group": {
"_id":"$dateStr",
"avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0,
"dateStr": "$_id",
"avg_count": {"$round": ["$avg_count", 1]}}},
{"$group": {
"_id":"dateStr", "avg_count": {"$avg":"$avg_count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$match":{"$or": [
{"action": "article_detail"},
{"action": "article_search_details"}]}},
{"$project":{
"_id": 0,
"datePartDay": {
"$concat": [
{"$substr": [ {"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},"sid": "$sid"}},
{"$group": {
"_id": {
"datePartDay": "$datePartDay",
"sid": "$sid"},
"count": {"$sum": 1}}},
{"$project": {
"_id": 0,
"dateObj": {
"$dateFromString":{"dateString": "$_id.datePartDay"}},
"count": "$count",
"sid": "$_id.sid",
"dateStr": "$_id.datePartDay"}},
{"$group": {
"_id":"$dateStr",
"avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0,
"dateStr": "$_id",
"avg_count": {"$round": ["$avg_count", 1]}}},
{"$sort": {"dateStr": -1}}]
data = list(self.events.collection.aggregate(pipeline))
if data:
res = {"data": data}
no_data = False
avg = self.get_avg(start_date, end_date)
else:
res = {
"data": [{"dateStr": None, "avg_count": 0}]
}
no_data = True
avg = {"avg_count": 0}
return Response(create_response(
{"result": res, "no_data": no_data, "avg_count": avg["avg_count"]}))
class InteractionsPerSession(APIView, ParseDateRange):
permission_classes = (AllowAny,)
events = Event()
def get_avg(self, start_date, end_date):
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$project":{
"_id": 0,
"datePartDay": {
"$concat": [
{"$substr": [ {"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},"sid": "$sid"}},
{"$group": {
"_id": {
"datePartDay": "$datePartDay",
"sid": "$sid"},
"count": {"$sum": 1}}},
{"$project": {
"_id": 0,
"dateObj": {
"$dateFromString":{"dateString": "$_id.datePartDay"}},
"count": "$count",
"sid": "$_id.sid",
"dateStr": "$_id.datePartDay"}},
{"$group": {
"_id":"$dateStr",
"avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0,
"dateStr": "$_id",
"avg_count": {"$round": ["$avg_count", 1]}}},
{"$group": {
"_id":"dateStr", "avg_count": {"$avg":"$avg_count"}}},
{"$project": {
"_id":0, "avg_count": {"$round": ["$avg_count", 1]}}}]
data = list(self.events.collection.aggregate(pipeline))
if not data:
return {"avg_count": 0}
return data[0]
def get(self, request):
date_range = request.GET.get("date_range")
start_date, end_date, error = self.get_date_range(date_range)
if error:
return Response(error, status=400)
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$group": {"_id": "$sid", "count": {"$sum": 1}}},
{"$project": {"_id": 0, "sid": "$_id", "count": "$count"}}
]
pipeline = [
{"$match": {"ts": {"$gte": start_date, "$lte": end_date}}},
{"$project":{
"_id": 0,
"datePartDay": {
"$concat": [
{"$substr": [ {"$dayOfMonth" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$month" : "$ts"}, 0, 2]}, "-",
{"$substr" : [{"$year" : "$ts"}, 0, 4]}]},"sid": "$sid"}},
{"$group": {
"_id": {
"datePartDay": "$datePartDay",
"sid": "$sid"},
"count": {"$sum": 1}}},
{"$project": {
"_id": 0,
"dateObj": {
"$dateFromString":{"dateString": "$_id.datePartDay"}},
"count": "$count",
"sid": "$_id.sid",
"dateStr": "$_id.datePartDay"}},
{"$group": {
"_id":"$dateStr",
"avg_count": {"$avg":"$count"}}},
{"$project": {
"_id":0,
"dateStr": "$_id",
"avg_count": {"$round": ["$avg_count", 1]}}},
{"$sort": {"dateStr": -1}}]
data = list(self.events.collection.aggregate(pipeline))
no_data = False
if not data:
data = [{"dateStr": None, "avg_count": 0}]
no_data = True
avg = {"avg_count": 0}
else:
avg = self.get_avg(start_date, end_date)
return Response(create_response(
{"result": data, "no_data": no_data, "avg_count": avg["avg_count"]}))
| 38.229901
| 108
| 0.446892
| 2,494
| 27,105
| 4.629912
| 0.068565
| 0.056811
| 0.035334
| 0.047112
| 0.822118
| 0.802806
| 0.78869
| 0.767732
| 0.751797
| 0.751797
| 0
| 0.011159
| 0.368493
| 27,105
| 708
| 109
| 38.283898
| 0.663434
| 0.014425
| 0
| 0.793496
| 0
| 0
| 0.213181
| 0.01071
| 0
| 0
| 0
| 0
| 0
| 1
| 0.03252
| false
| 0
| 0.019512
| 0
| 0.16748
| 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
|
6747ca33797217e8b4706d257c1d8e02c193bbbe
| 4,595
|
py
|
Python
|
tests/test_collapse_to_triangle.py
|
umeier/quantized-mesh-tile
|
c38c927efdffff40d6041b0526a5ff95d0852a24
|
[
"MIT"
] | 76
|
2016-04-25T08:33:05.000Z
|
2022-02-07T21:38:58.000Z
|
tests/test_collapse_to_triangle.py
|
umeier/quantized-mesh-tile
|
c38c927efdffff40d6041b0526a5ff95d0852a24
|
[
"MIT"
] | 41
|
2016-06-03T09:15:58.000Z
|
2021-01-26T22:49:46.000Z
|
tests/test_collapse_to_triangle.py
|
umeier/quantized-mesh-tile
|
c38c927efdffff40d6041b0526a5ff95d0852a24
|
[
"MIT"
] | 21
|
2016-03-23T13:46:43.000Z
|
2021-05-19T06:17:30.000Z
|
# -*- coding: utf-8 -*-
import unittest
from quantized_mesh_tile.utils import collapseIntoTriangles
def toString(t):
return ','.join([str(i) for i in t])
class TestCollapseIntoTriangle(unittest.TestCase):
def testCollapseFourNodes(self):
coords = [
[1, 1, 1],
[1, 2, 1],
[2, 1, 1],
[3, 2, 2]
]
triangles = collapseIntoTriangles(coords)
self.assertEqual(len(triangles), 2)
self.assertEqual(len(triangles[0]), 3)
self.assertEqual(len(triangles[1]), 3)
self.assertEqual(toString(triangles[0][0]), '1,1,1')
self.assertEqual(toString(triangles[0][1]), '2,1,1')
self.assertEqual(toString(triangles[0][2]), '1,2,1')
self.assertEqual(toString(triangles[1][0]), '1,1,1')
self.assertEqual(toString(triangles[1][1]), '2,1,1')
self.assertEqual(toString(triangles[1][2]), '3,2,2')
def testCollapseFiveNodes(self):
coords = [
[1, 1, 1],
[1, 2, 1],
[2, 1, 1],
[3, 2, 2],
[2, 3, 3]
]
triangles = collapseIntoTriangles(coords)
self.assertEqual(len(triangles), 3)
self.assertEqual(len(triangles[0]), 3)
self.assertEqual(len(triangles[1]), 3)
self.assertEqual(len(triangles[2]), 3)
self.assertEqual(toString(triangles[0][0]), '1,1,1')
self.assertEqual(toString(triangles[0][1]), '2,1,1')
self.assertEqual(toString(triangles[0][2]), '1,2,1')
self.assertEqual(toString(triangles[1][0]), '1,1,1')
self.assertEqual(toString(triangles[1][1]), '3,2,2')
self.assertEqual(toString(triangles[1][2]), '2,1,1')
self.assertEqual(toString(triangles[2][0]), '1,1,1')
self.assertEqual(toString(triangles[2][1]), '3,2,2')
self.assertEqual(toString(triangles[2][2]), '2,3,3')
def testCollapseSixNodes(self):
coords = [
[1, 1, 1],
[1, 2, 1],
[2, 1, 1],
[3, 2, 2],
[2, 3, 3],
[5, 2, 1]
]
triangles = collapseIntoTriangles(coords)
self.assertEqual(len(triangles), 4)
self.assertEqual(len(triangles[0]), 3)
self.assertEqual(len(triangles[1]), 3)
self.assertEqual(len(triangles[2]), 3)
self.assertEqual(len(triangles[3]), 3)
self.assertEqual(toString(triangles[0][0]), '1,1,1')
self.assertEqual(toString(triangles[0][1]), '2,1,1')
self.assertEqual(toString(triangles[0][2]), '1,2,1')
self.assertEqual(toString(triangles[1][0]), '3,2,2')
self.assertEqual(toString(triangles[1][1]), '5,2,1')
self.assertEqual(toString(triangles[1][2]), '2,3,3')
self.assertEqual(toString(triangles[2][0]), '1,1,1')
self.assertEqual(toString(triangles[2][1]), '3,2,2')
self.assertEqual(toString(triangles[2][2]), '2,1,1')
self.assertEqual(toString(triangles[3][0]), '1,1,1')
self.assertEqual(toString(triangles[3][1]), '3,2,2')
self.assertEqual(toString(triangles[3][2]), '5,2,1')
def testCollapseSevenNodes(self):
coords = [
[1, 1, 1],
[1, 2, 1],
[2, 1, 1],
[3, 2, 2],
[2, 3, 3],
[5, 2, 1],
[6, 6, 6]
]
triangles = collapseIntoTriangles(coords)
self.assertEqual(len(triangles), 5)
self.assertEqual(len(triangles[0]), 3)
self.assertEqual(len(triangles[1]), 3)
self.assertEqual(len(triangles[2]), 3)
self.assertEqual(len(triangles[3]), 3)
self.assertEqual(len(triangles[4]), 3)
self.assertEqual(toString(triangles[0][0]), '1,1,1')
self.assertEqual(toString(triangles[0][1]), '2,1,1')
self.assertEqual(toString(triangles[0][2]), '1,2,1')
self.assertEqual(toString(triangles[1][0]), '3,2,2')
self.assertEqual(toString(triangles[1][1]), '5,2,1')
self.assertEqual(toString(triangles[1][2]), '2,3,3')
self.assertEqual(toString(triangles[2][0]), '1,1,1')
self.assertEqual(toString(triangles[2][1]), '3,2,2')
self.assertEqual(toString(triangles[2][2]), '2,1,1')
self.assertEqual(toString(triangles[3][0]), '1,1,1')
self.assertEqual(toString(triangles[3][1]), '5,2,1')
self.assertEqual(toString(triangles[3][2]), '3,2,2')
self.assertEqual(toString(triangles[4][0]), '1,1,1')
self.assertEqual(toString(triangles[4][1]), '5,2,1')
self.assertEqual(toString(triangles[4][2]), '6,6,6')
| 35.620155
| 60
| 0.560392
| 603
| 4,595
| 4.266998
| 0.064677
| 0.349786
| 0.375437
| 0.522347
| 0.897007
| 0.889623
| 0.887291
| 0.774971
| 0.690634
| 0.690634
| 0
| 0.0891
| 0.245267
| 4,595
| 128
| 61
| 35.898438
| 0.652826
| 0.00457
| 0
| 0.660194
| 0
| 0
| 0.04615
| 0
| 0
| 0
| 0
| 0
| 0.582524
| 1
| 0.048544
| false
| 0
| 0.019417
| 0.009709
| 0.087379
| 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
| 0
| 0
| 0
| 0
|
0
| 9
|
679096df06a7f1e97070398fa58cf00c6f6d3eba
| 54,428
|
py
|
Python
|
src/oci/data_science/data_science_client_composite_operations.py
|
LaudateCorpus1/oci-python-sdk
|
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
src/oci/data_science/data_science_client_composite_operations.py
|
LaudateCorpus1/oci-python-sdk
|
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
src/oci/data_science/data_science_client_composite_operations.py
|
LaudateCorpus1/oci-python-sdk
|
b0d3ce629d5113df4d8b83b7a6502b2c5bfa3015
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
import oci # noqa: F401
from oci.util import WAIT_RESOURCE_NOT_FOUND # noqa: F401
class DataScienceClientCompositeOperations(object):
"""
This class provides a wrapper around :py:class:`~oci.data_science.DataScienceClient` and offers convenience methods
for operations that would otherwise need to be chained together. For example, instead of performing an action
on a resource (e.g. launching an instance, creating a load balancer) and then using a waiter to wait for the resource
to enter a given state, you can call a single method in this class to accomplish the same functionality
"""
def __init__(self, client, **kwargs):
"""
Creates a new DataScienceClientCompositeOperations object
:param DataScienceClient client:
The service client which will be wrapped by this object
"""
self.client = client
def activate_model_and_wait_for_state(self, model_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.activate_model` and waits for the :py:class:`~oci.data_science.models.Model` acted upon
to enter the given state(s).
:param str model_id: (required)
The `OCID`__ of the model.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Model.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.activate_model`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.activate_model(model_id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_model(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def activate_model_deployment_and_wait_for_state(self, model_deployment_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.activate_model_deployment` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str model_deployment_id: (required)
The `OCID`__ of the model deployment.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.activate_model_deployment`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.activate_model_deployment(model_deployment_id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def activate_notebook_session_and_wait_for_state(self, notebook_session_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.activate_notebook_session` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str notebook_session_id: (required)
The `OCID`__ of the notebook session.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.activate_notebook_session`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.activate_notebook_session(notebook_session_id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_job_and_wait_for_state(self, create_job_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.create_job` and waits for the :py:class:`~oci.data_science.models.Job` acted upon
to enter the given state(s).
:param oci.data_science.models.CreateJobDetails create_job_details: (required)
Details for creating a new job.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Job.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.create_job`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_job(create_job_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_job(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_job_run_and_wait_for_state(self, create_job_run_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.create_job_run` and waits for the :py:class:`~oci.data_science.models.JobRun` acted upon
to enter the given state(s).
:param oci.data_science.models.CreateJobRunDetails create_job_run_details: (required)
Details for creating a new job run.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.JobRun.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.create_job_run`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_job_run(create_job_run_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_job_run(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_model_and_wait_for_state(self, create_model_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.create_model` and waits for the :py:class:`~oci.data_science.models.Model` acted upon
to enter the given state(s).
:param oci.data_science.models.CreateModelDetails create_model_details: (required)
Details for creating a new model.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Model.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.create_model`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_model(create_model_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_model(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_model_deployment_and_wait_for_state(self, create_model_deployment_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.create_model_deployment` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param oci.data_science.models.CreateModelDeploymentDetails create_model_deployment_details: (required)
Details for creating a new model deployment.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.create_model_deployment`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_model_deployment(create_model_deployment_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_notebook_session_and_wait_for_state(self, create_notebook_session_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.create_notebook_session` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param oci.data_science.models.CreateNotebookSessionDetails create_notebook_session_details: (required)
Details for creating a new notebook session.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.create_notebook_session`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_notebook_session(create_notebook_session_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def create_project_and_wait_for_state(self, create_project_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.create_project` and waits for the :py:class:`~oci.data_science.models.Project` acted upon
to enter the given state(s).
:param oci.data_science.models.CreateProjectDetails create_project_details: (required)
Details for creating a new project.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Project.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.create_project`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.create_project(create_project_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_project(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def deactivate_model_and_wait_for_state(self, model_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.deactivate_model` and waits for the :py:class:`~oci.data_science.models.Model` acted upon
to enter the given state(s).
:param str model_id: (required)
The `OCID`__ of the model.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Model.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.deactivate_model`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.deactivate_model(model_id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_model(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def deactivate_model_deployment_and_wait_for_state(self, model_deployment_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.deactivate_model_deployment` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str model_deployment_id: (required)
The `OCID`__ of the model deployment.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.deactivate_model_deployment`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.deactivate_model_deployment(model_deployment_id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def deactivate_notebook_session_and_wait_for_state(self, notebook_session_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.deactivate_notebook_session` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str notebook_session_id: (required)
The `OCID`__ of the notebook session.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.deactivate_notebook_session`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.deactivate_notebook_session(notebook_session_id, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def delete_job_and_wait_for_state(self, job_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.delete_job` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str job_id: (required)
The `OCID`__ of the job.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.delete_job`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = None
try:
operation_result = self.client.delete_job(job_id, **operation_kwargs)
except oci.exceptions.ServiceError as e:
if e.status == 404:
return WAIT_RESOURCE_NOT_FOUND
else:
raise e
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def delete_job_run_and_wait_for_state(self, job_run_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.delete_job_run` and waits for the :py:class:`~oci.data_science.models.JobRun` acted upon
to enter the given state(s).
:param str job_run_id: (required)
The `OCID`__ of the job run.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.JobRun.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.delete_job_run`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
initial_get_result = self.client.get_job_run(job_run_id)
operation_result = None
try:
operation_result = self.client.delete_job_run(job_run_id, **operation_kwargs)
except oci.exceptions.ServiceError as e:
if e.status == 404:
return WAIT_RESOURCE_NOT_FOUND
else:
raise e
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
try:
waiter_result = oci.wait_until(
self.client,
initial_get_result,
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
succeed_on_not_found=True,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def delete_model_and_wait_for_state(self, model_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.delete_model` and waits for the :py:class:`~oci.data_science.models.Model` acted upon
to enter the given state(s).
:param str model_id: (required)
The `OCID`__ of the model.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Model.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.delete_model`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
initial_get_result = self.client.get_model(model_id)
operation_result = None
try:
operation_result = self.client.delete_model(model_id, **operation_kwargs)
except oci.exceptions.ServiceError as e:
if e.status == 404:
return WAIT_RESOURCE_NOT_FOUND
else:
raise e
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
try:
waiter_result = oci.wait_until(
self.client,
initial_get_result,
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
succeed_on_not_found=True,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def delete_model_deployment_and_wait_for_state(self, model_deployment_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.delete_model_deployment` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str model_deployment_id: (required)
The `OCID`__ of the model deployment.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.delete_model_deployment`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = None
try:
operation_result = self.client.delete_model_deployment(model_deployment_id, **operation_kwargs)
except oci.exceptions.ServiceError as e:
if e.status == 404:
return WAIT_RESOURCE_NOT_FOUND
else:
raise e
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def delete_notebook_session_and_wait_for_state(self, notebook_session_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.delete_notebook_session` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str notebook_session_id: (required)
The `OCID`__ of the notebook session.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.delete_notebook_session`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = None
try:
operation_result = self.client.delete_notebook_session(notebook_session_id, **operation_kwargs)
except oci.exceptions.ServiceError as e:
if e.status == 404:
return WAIT_RESOURCE_NOT_FOUND
else:
raise e
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def delete_project_and_wait_for_state(self, project_id, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.delete_project` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str project_id: (required)
The `OCID`__ of the project.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.delete_project`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = None
try:
operation_result = self.client.delete_project(project_id, **operation_kwargs)
except oci.exceptions.ServiceError as e:
if e.status == 404:
return WAIT_RESOURCE_NOT_FOUND
else:
raise e
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_job_and_wait_for_state(self, job_id, update_job_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.update_job` and waits for the :py:class:`~oci.data_science.models.Job` acted upon
to enter the given state(s).
:param str job_id: (required)
The `OCID`__ of the job.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.data_science.models.UpdateJobDetails update_job_details: (required)
Details for updating a job.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Job.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.update_job`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_job(job_id, update_job_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_job(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_job_run_and_wait_for_state(self, job_run_id, update_job_run_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.update_job_run` and waits for the :py:class:`~oci.data_science.models.JobRun` acted upon
to enter the given state(s).
:param str job_run_id: (required)
The `OCID`__ of the job run.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.data_science.models.UpdateJobRunDetails update_job_run_details: (required)
Details for updating a job.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.JobRun.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.update_job_run`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_job_run(job_run_id, update_job_run_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_job_run(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_model_and_wait_for_state(self, model_id, update_model_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.update_model` and waits for the :py:class:`~oci.data_science.models.Model` acted upon
to enter the given state(s).
:param str model_id: (required)
The `OCID`__ of the model.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.data_science.models.UpdateModelDetails update_model_details: (required)
Details for updating a model. You can update the `displayName`, `description`, `freeformTags`, and `definedTags` properties.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Model.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.update_model`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_model(model_id, update_model_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_model(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_model_deployment_and_wait_for_state(self, model_deployment_id, update_model_deployment_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.update_model_deployment` and waits for the :py:class:`~oci.data_science.models.WorkRequest`
to enter the given state(s).
:param str model_deployment_id: (required)
The `OCID`__ of the model deployment.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.data_science.models.UpdateModelDeploymentDetails update_model_deployment_details: (required)
Details for updating a model deployment. Some of the properties of `modelDeploymentConfigurationDetails` or `CategoryLogDetails` can also be updated with zero down time
when the model deployment's lifecycle state is ACTIVE or NEEDS_ATTENTION i.e `instanceShapeName`, `instanceCount` and `modelId`, separately `loadBalancerShape` or
`CategoryLogDetails` can also be updated independently. All of the fields can be updated when the deployment is in the INACTIVE lifecycle state. Changes will take effect the next
time the model deployment is activated.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.WorkRequest.status`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.update_model_deployment`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_model_deployment(model_deployment_id, update_model_deployment_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.headers['opc-work-request-id']
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_work_request(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'status') and getattr(r.data, 'status').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_notebook_session_and_wait_for_state(self, notebook_session_id, update_notebook_session_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.update_notebook_session` and waits for the :py:class:`~oci.data_science.models.NotebookSession` acted upon
to enter the given state(s).
:param str notebook_session_id: (required)
The `OCID`__ of the notebook session.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.data_science.models.UpdateNotebookSessionDetails update_notebook_session_details: (required)
Details for updating a notebook session. `notebookSessionConfigurationDetails` can only be updated while the notebook session is in the `INACTIVE` state.
Changes to the `notebookSessionConfigurationDetails` take effect the next time the `ActivateNotebookSession` action is invoked on the notebook session resource.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.NotebookSession.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.update_notebook_session`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_notebook_session(notebook_session_id, update_notebook_session_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_notebook_session(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
def update_project_and_wait_for_state(self, project_id, update_project_details, wait_for_states=[], operation_kwargs={}, waiter_kwargs={}):
"""
Calls :py:func:`~oci.data_science.DataScienceClient.update_project` and waits for the :py:class:`~oci.data_science.models.Project` acted upon
to enter the given state(s).
:param str project_id: (required)
The `OCID`__ of the project.
__ https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm
:param oci.data_science.models.UpdateProjectDetails update_project_details: (required)
Details for updating a project. You can update the `displayName`, `description`, `freeformTags`, and `definedTags` properties.
:param list[str] wait_for_states:
An array of states to wait on. These should be valid values for :py:attr:`~oci.data_science.models.Project.lifecycle_state`
:param dict operation_kwargs:
A dictionary of keyword arguments to pass to :py:func:`~oci.data_science.DataScienceClient.update_project`
:param dict waiter_kwargs:
A dictionary of keyword arguments to pass to the :py:func:`oci.wait_until` function. For example, you could pass ``max_interval_seconds`` or ``max_interval_seconds``
as dictionary keys to modify how long the waiter function will wait between retries and the maximum amount of time it will wait
"""
operation_result = self.client.update_project(project_id, update_project_details, **operation_kwargs)
if not wait_for_states:
return operation_result
lowered_wait_for_states = [w.lower() for w in wait_for_states]
wait_for_resource_id = operation_result.data.id
try:
waiter_result = oci.wait_until(
self.client,
self.client.get_project(wait_for_resource_id),
evaluate_response=lambda r: getattr(r.data, 'lifecycle_state') and getattr(r.data, 'lifecycle_state').lower() in lowered_wait_for_states,
**waiter_kwargs
)
result_to_return = waiter_result
return result_to_return
except Exception as e:
raise oci.exceptions.CompositeOperationError(partial_results=[operation_result], cause=e)
| 52.084211
| 245
| 0.685125
| 7,084
| 54,428
| 5.014399
| 0.037691
| 0.041974
| 0.0527
| 0.033782
| 0.945499
| 0.940685
| 0.931704
| 0.919543
| 0.911069
| 0.911069
| 0
| 0.000939
| 0.236514
| 54,428
| 1,044
| 246
| 52.1341
| 0.85388
| 0.472698
| 0
| 0.824945
| 0
| 0
| 0.02824
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.054705
| false
| 0
| 0.004376
| 0
| 0.179431
| 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
|
67aaef97e0f2615fa3cf955cd7d838843901f72d
| 7,777
|
py
|
Python
|
commonroad/tests/scenario/test_trajectory.py
|
CommonRoad/commonroad-io
|
93824961da9c41eb7768b5cf1acbed9a07446dc2
|
[
"BSD-3-Clause"
] | 3
|
2022-01-05T09:10:18.000Z
|
2022-03-22T15:09:43.000Z
|
commonroad/tests/scenario/test_trajectory.py
|
CommonRoad/commonroad-io
|
93824961da9c41eb7768b5cf1acbed9a07446dc2
|
[
"BSD-3-Clause"
] | null | null | null |
commonroad/tests/scenario/test_trajectory.py
|
CommonRoad/commonroad-io
|
93824961da9c41eb7768b5cf1acbed9a07446dc2
|
[
"BSD-3-Clause"
] | null | null | null |
import unittest
import numpy as np
from commonroad.scenario.trajectory import State, Trajectory
from commonroad.common.util import Interval
class TestTrajectory(unittest.TestCase):
def test_constructor(self):
self.assertRaises(AssertionError, Trajectory, 0, list())
states = list()
states.append(State(**{'position': np.array([1.35, -2.4]), 'orientation': 0.87, 'time_step': 0}))
states.append(State(**{'position': np.array([2.35, -2.4]), 'orientation': 0.97, 'time_step': 1}))
states.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 1.07, 'time_step': 2}))
states.append(State(**{'position': np.array([4.35, -2.4]), 'orientation': 1.17, 'time_step': 3}))
states.append(State(**{'position': np.array([5.35, -2.4]), 'orientation': 1.27, 'time_step': 4}))
states.append(State(**{'position': np.array([6.35, -2.4]), 'orientation': 1.37, 'time_step': 5}))
states.append(State(**{'position': np.array([7.35, -2.4]), 'orientation': 1.47, 'time_step': 6}))
states.append(State(**{'position': np.array([8.35, -2.4]), 'orientation': 1.57, 'time_step': 7}))
states.append(State(**{'position': np.array([9.35, -2.4]), 'orientation': 1.67, 'time_step': 8}))
trajectory = Trajectory(0, states)
self.assertEqual(len(trajectory.state_list), len(states))
self.assertEqual(trajectory.state_list, states)
self.assertRaises(AssertionError, Trajectory, 0.67, states)
states = list()
states.append(State(**{'position': np.array([1.35, -2.4]), 'orientation': 0.87, 'time_step': 0}))
states.append(State(**{'position': np.array([2.35, -2.4]), 'orientation': 0.97, 'time_step': 1}))
states.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 1.07, 'time_step': 2}))
states.append(State(**{'position': np.array([4.35, -2.4]), 'orientation': 1.17, 'time_step': 3}))
states.append(State(**{'position': np.array([5.35, -2.4]), 'orientation': 1.27, 'time_step': 4}))
states.append(State(**{'position': np.array([6.35, -2.4]), 'orientation': 1.37, 'time_step': 5}))
states.append(State(**{'position': np.array([7.35, -2.4]), 'orientation': 1.47, 'time_step': 6}))
states.append(State(**{'position': np.array([8.35, -2.4]), 'orientation': 1.57, 'time_step': 7}))
states.append(State(**{'position': np.array([9.35, -2.4]), 'orientation': 1.67, 'time_step': 8}))
trajectory = Trajectory(0, states)
self.assertEqual(len(trajectory.state_list), len(states))
self.assertEqual(trajectory.state_list, states)
states[-1].time_step = Interval(8, 10)
self.assertRaises(AssertionError, Trajectory, 0, states)
states.append(Interval(0, 1))
self.assertRaises(AssertionError, Trajectory, 0, states)
states = list()
states.append(State(**{'position': np.array([1.35, -2.4]), 'orientation': 0.87, 'time_step': 0}))
states.append(State(**{'position': np.array([2.35, -2.4]), 'velocity': 4.97, 'time_step': 1}))
states.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 1.07, 'time_step': 2}))
self.assertRaises(AssertionError, Trajectory, 0, states)
def test_translate_rotate(self):
states = list()
states.append(State(**{'position': np.array([1.35, -2.4]), 'orientation': 0.87, 'time_step': 0}))
states.append(State(**{'position': np.array([2.35, -2.4]), 'orientation': 0.97, 'time_step': 1}))
states.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 1.07, 'time_step': 2}))
states.append(State(**{'position': np.array([4.35, -2.4]), 'orientation': 1.17, 'time_step': 3}))
states.append(State(**{'position': np.array([5.35, -2.4]), 'orientation': 1.27, 'time_step': 4}))
translation = np.array([2.0, 0.0])
angle = 0.0
states_new = list()
states_new.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 0.87, 'time_step': 0}))
states_new.append(State(**{'position': np.array([4.35, -2.4]), 'orientation': 0.97, 'time_step': 1}))
states_new.append(State(**{'position': np.array([5.35, -2.4]), 'orientation': 1.07, 'time_step': 2}))
states_new.append(State(**{'position': np.array([6.35, -2.4]), 'orientation': 1.17, 'time_step': 3}))
states_new.append(State(**{'position': np.array([7.35, -2.4]), 'orientation': 1.27, 'time_step': 4}))
trajectory = Trajectory(0, states)
trajectory.translate_rotate(translation, angle)
for i, state in enumerate(trajectory.state_list):
self.assertAlmostEqual(state.position[0], states_new[i].position[0])
self.assertAlmostEqual(state.position[1], states_new[i].position[1])
def test_state_at_time_step(self):
states = list()
states.append(State(**{'position': np.array([1.35, -2.4]), 'orientation': 0.87, 'time_step': 0}))
states.append(State(**{'position': np.array([2.35, -2.4]), 'orientation': 0.97, 'time_step': 1}))
states.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 1.07, 'time_step': 2}))
states.append(State(**{'position': np.array([4.35, -2.4]), 'orientation': 1.17, 'time_step': 3}))
states.append(State(**{'position': np.array([5.35, -2.4]), 'orientation': 1.27, 'time_step': 4}))
trajectory = Trajectory(0, states)
self.assertEqual(trajectory.state_at_time_step(2), states[2])
states = list()
states.append(State(**{'position': np.array([1.35, -2.4]), 'orientation': 0.87, 'time_step': 6}))
states.append(State(**{'position': np.array([2.35, -2.4]), 'orientation': 0.97, 'time_step': 7}))
states.append(State(**{'position': np.array([3.35, -2.4]), 'orientation': 1.07, 'time_step': 8}))
states.append(State(**{'position': np.array([4.35, -2.4]), 'orientation': 1.17, 'time_step': 9}))
states.append(State(**{'position': np.array([5.35, -2.4]), 'orientation': 1.27, 'time_step': 10}))
trajectory = Trajectory(6, states)
self.assertEqual(trajectory.state_at_time_step(2), None)
self.assertEqual(trajectory.state_at_time_step(9), states[3])
self.assertEqual(trajectory.state_at_time_step(10), states[4])
def test_interpolate_states(self):
states = list()
states.append(State(**{'time_step': 5, 'position': np.array([0, 0]), 'velocity': 0, 'orientation': 10}))
states.append(State(**{'time_step': 5, 'position': np.array([5, 5]), 'velocity': 5, 'orientation': 15}))
states.append(State(**{'time_step': 5, 'position': np.array([10, 10]), 'velocity': 10, 'orientation': 20}))
time = np.array([0,5,10])
traj_new = Trajectory.resample_continuous_time_state_list(states, time, 2.5, 4)
x_t = np.interp(np.arange(0,2.5*4+2.5,2.5), time, [0, 5, 10])
for i, x in enumerate(traj_new.state_list):
self.assertEqual(x.velocity, x_t[i])
self.assertEqual(x.time_step, i)
self.assertEqual(x.position[0], x_t[i])
self.assertEqual(x.position[1], x_t[i])
self.assertEqual(x.orientation, 10+x_t[i])
traj_new = Trajectory.resample_continuous_time_state_list(states, time, 2.5, 2, initial_time_cont=5)
x_t = np.interp(np.arange(5, 2.5 * 4 + 2.5, 2.5), time, [0, 5, 10])
for i, x in enumerate(traj_new.state_list):
self.assertEqual(x.velocity, x_t[i])
self.assertEqual(x.time_step, i)
self.assertEqual(x.position[0], x_t[i])
self.assertEqual(x.position[1], x_t[i])
self.assertEqual(x.orientation, 10 + x_t[i])
if __name__ == '__main__':
unittest.main()
| 59.366412
| 115
| 0.605761
| 1,109
| 7,777
| 4.143372
| 0.073039
| 0.090533
| 0.143634
| 0.187378
| 0.843961
| 0.826115
| 0.805005
| 0.762568
| 0.762568
| 0.716213
| 0
| 0.073334
| 0.175903
| 7,777
| 131
| 116
| 59.366412
| 0.643626
| 0
| 0
| 0.566038
| 0
| 0
| 0.162124
| 0
| 0
| 0
| 0
| 0
| 0.235849
| 1
| 0.037736
| false
| 0
| 0.037736
| 0
| 0.084906
| 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
|
22024319ed36a0fcc20f2c87a42c490e3007570c
| 24,170
|
py
|
Python
|
transfo/model.py
|
qianyingw/rob-kiwi
|
938a8c655ca328696d7b43878497365fc91d9edb
|
[
"MIT"
] | 1
|
2020-03-13T05:07:50.000Z
|
2020-03-13T05:07:50.000Z
|
transfo/model.py
|
qianyingw/rob-kiwi
|
938a8c655ca328696d7b43878497365fc91d9edb
|
[
"MIT"
] | null | null | null |
transfo/model.py
|
qianyingw/rob-kiwi
|
938a8c655ca328696d7b43878497365fc91d9edb
|
[
"MIT"
] | null | null | null |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 14:56:39 2020
@author: qwang
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from transformers import BertPreTrainedModel, BertConfig, BertModel
# from transformers import AlbertPreTrainedModel, AlbertConfig, AlbertModel
# from hgf.modeling_utils import SequenceSummary
#%%
class BertPoolLinear(BertPreTrainedModel):
def __init__(self, config: BertConfig):
super().__init__(config)
self.config = config
self.bert = BertModel(config)
# self.seq_summary = SequenceSummary(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
if config.pool_method_chunks == 'mean_max':
self.fc = nn.Linear(config.hidden_size*2, config.num_labels)
else:
self.fc = nn.Linear(config.hidden_size, config.num_labels)
self.fc_bn = nn.BatchNorm1d(config.num_labels)
self.init_weights()
# Default: freeze bert
for name, param in self.bert.named_parameters():
param.requires_grad = False
# Unfreeze layers
if config.unfreeze == "pooler":
for name, param in self.bert.named_parameters():
if "pooler" in name:
param.requires_grad = True
if config.unfreeze == "enc-1":
n_layer = sum([1 for name, _ in self.bert.named_parameters() if "encoder.layer" in name])
last_layer = "encoder.layer." + str(int(n_layer/16-1)) # each enc layer has 16 pars
for name, param in self.bert.named_parameters():
if last_layer in name:
param.requires_grad = True
if config.unfreeze == "enc-1_pooler":
n_layer = sum([1 for name, _ in self.bert.named_parameters() if "encoder.layer" in name])
last_layer = "encoder.layer." + str(int(n_layer/16-1)) # each enc layer has 16 pars
for name, param in self.bert.named_parameters():
if last_layer in name or "pooler" in name:
param.requires_grad = True
def forward(self, doc):
"""
Input:
doc: [batch_size, n_chunks, 3, max_chunk_len]
n_chunks is the number of chunks within the batch (same for each doc after PadDoc)
Returns:
out: [batch_size, output_dim]
"""
batch_size = doc.shape[0]
hidden_pooled_layers = []
for k in range(batch_size):
# Each doc is considered as a special 'batch' and each chunk is an element of the special 'bert_batch'
# n_chunks is the temporary 'bert_batch_size', max_chunk_len corresponds to 'seq_len'
bert_output_k = self.bert(input_ids = doc[k,:,0], # [n_chunks, max_chunk_len]
attention_mask = doc[k,:,1],
token_type_ids = doc[k,:,2])
# pooled_k = bert_output_k[1].unsqueeze(0)
hidden_states_k = bert_output_k[2] # each element in the tuple: [n_chunks, max_chunk_len, hidden_size]
# Average pooling over last [pool_layers] layers
hidden_list_k = list(hidden_states_k[self.config.pool_layers:])
hidden_stack_k = torch.stack(hidden_list_k) # [n_pooled_layers, n_chunks, max_chunk_len, hidden_size]
hidden_pooled_layers_k = torch.mean(hidden_stack_k, dim=0) # [n_chunks, max_chunk_len, hidden_size]
hidden_pooled_layers.append(hidden_pooled_layers_k)
hidden_pooled_layers = torch.stack(hidden_pooled_layers) # [batch_size, n_chunks, max_chunk_len, hidden_size]
# Pooling within each chunk (over 512 word tokens of individual chunk)
if self.config.pool_method == 'mean':
hidden_pooled = torch.mean(hidden_pooled_layers, dim=2) # [batch_size, n_chunks, hidden_size]
elif self.config.pool_method == 'max':
hidden_pooled = torch.max(hidden_pooled_layers, dim=2).values # [batch_size, n_chunks, hidden_size]
elif self.config.pool_method == 'mean_max':
hidden_pooled_mean = torch.mean(hidden_pooled_layers, dim=2) # [batch_size, n_chunks, hidden_size]
hidden_pooled_max = torch.max(hidden_pooled_layers, dim=2).values # [batch_size, n_chunks, hidden_size]
hidden_pooled = torch.cat((hidden_pooled_mean, hidden_pooled_max), dim=1) # [batch_size, n_chunks*2, hidden_size]
elif self.config.pool_method == 'cls':
hidden_pooled = hidden_pooled_layers[:,:,0,:] # [batch_size, n_chunks, hidden_size]
else: # pool_method is None
hidden_pooled = hidden_pooled_layers.view(batch_size, -1, self.config.hidden_size) # [batch_size, n_chunks*max_chunk_len, hidden_size]
dp = self.dropout(hidden_pooled) # [batch_size, ?, hidden_size]
# ? can be n_chunks, n_chunks*2 or n_chunks*max_chunk_len)
# Pooling over chunks
if self.config.pool_method_chunks == 'mean':
dp_pooled = torch.mean(dp, dim=1) # [batch_size, hidden_size]
if self.config.pool_method_chunks == 'max':
dp_pooled = torch.max(dp, dim=1).values # [batch_size, hidden_size]
if self.config.pool_method_chunks == 'mean_max':
dp_pooled_mean = torch.mean(dp, dim=1) # [batch_size, hidden_size]
dp_pooled_max = torch.max(dp, dim=1).values # [batch_size, hidden_size]
dp_pooled = torch.cat((dp_pooled_mean, dp_pooled_max), dim=1) # [batch_size, 2*hidden_size]
if self.config.pool_method_chunks == 'cls':
dp_pooled = dp[:,0,:] # [batch_size, hidden_size]
out = self.fc(dp_pooled) # [batch_size, num_labels]
out = self.fc_bn(out)
out = F.softmax(out, dim=1) # [batch_size, num_labels]
return out
#%%
class BertPoolLSTM(BertPreTrainedModel):
def __init__(self, config: BertConfig):
super().__init__(config)
self.config = config
self.bert = BertModel(config)
# self.seq_summary = SequenceSummary(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.lstm = nn.LSTM(input_size = config.hidden_size, hidden_size = config.hidden_size,
num_layers = 1, dropout = 0,
batch_first = True, bidirectional = False)
self.fc = nn.Linear(config.hidden_size, config.num_labels)
self.fc_bn = nn.BatchNorm1d(config.num_labels)
self.init_weights()
# Default: freeze bert
for name, param in self.bert.named_parameters():
param.requires_grad = False
# Unfreeze layers
if config.unfreeze == "pooler":
for name, param in self.bert.named_parameters():
if "pooler" in name:
param.requires_grad = True
if config.unfreeze == "enc-1":
n_layer = sum([1 for name, _ in self.bert.named_parameters() if "encoder.layer" in name])
last_layer = "encoder.layer." + str(int(n_layer/16-1)) # each enc layer has 16 pars
for name, param in self.bert.named_parameters():
if last_layer in name:
param.requires_grad = True
if config.unfreeze == "enc-1_pooler":
n_layer = sum([1 for name, _ in self.bert.named_parameters() if "encoder.layer" in name])
last_layer = "encoder.layer." + str(int(n_layer/16-1)) # each enc layer has 16 pars
for name, param in self.bert.named_parameters():
if last_layer in name or "pooler" in name:
param.requires_grad = True
def forward(self, doc):
"""
Input:
doc: [batch_size, n_chunks, 3, max_chunk_len]
n_chunks is the number of chunks within the batch (same for each doc after PadDoc)
Returns:
out: [batch_size, output_dim]
"""
batch_size = doc.shape[0]
hidden_pooled_layers = []
for k in range(batch_size):
# Each doc is considered as a special 'batch' and each chunk is an element of the special 'bert_batch'
# n_chunks is the temporary 'bert_batch_size', max_chunk_len corresponds to 'seq_len'
bert_output_k = self.bert(input_ids = doc[k,:,0], # [n_chunks, max_chunk_len]
attention_mask = doc[k,:,1],
token_type_ids = doc[k,:,2])
# pooled_k = bert_output_k[1].unsqueeze(0)
hidden_states_k = bert_output_k[2] # each element in the tuple: [n_chunks, max_chunk_len, hidden_size]
# Average pooling over last [pool_layers] layers
hidden_list_k = list(hidden_states_k[self.config.pool_layers:])
hidden_stack_k = torch.stack(hidden_list_k) # [n_pooled_layers, n_chunks, max_chunk_len, hidden_size]
hidden_pooled_layers_k = torch.mean(hidden_stack_k, dim=0) # [n_chunks, max_chunk_len, hidden_size]
hidden_pooled_layers.append(hidden_pooled_layers_k)
hidden_pooled_layers = torch.stack(hidden_pooled_layers) # [batch_size, n_chunks, max_chunk_len, hidden_size]
# Pooling within each chunk (over 512 word tokens of individual chunk)
if self.config.pool_method == 'mean':
hidden_pooled = torch.mean(hidden_pooled_layers, dim=2) # [batch_size, n_chunks, hidden_size]
elif self.config.pool_method == 'max':
hidden_pooled = torch.max(hidden_pooled_layers, dim=2).values # [batch_size, n_chunks, hidden_size]
elif self.config.pool_method == 'mean_max':
hidden_pooled_mean = torch.mean(hidden_pooled_layers, dim=2) # [batch_size, n_chunks, hidden_size]
hidden_pooled_max = torch.max(hidden_pooled_layers, dim=2).values # [batch_size, n_chunks, hidden_size]
hidden_pooled = torch.cat((hidden_pooled_mean, hidden_pooled_max), dim=1) # [batch_size, n_chunks*2, hidden_size]
elif self.config.pool_method == 'cls':
hidden_pooled = hidden_pooled_layers[:,:,0,:] # [batch_size, n_chunks, hidden_size]
else: # pool_method is None
hidden_pooled = hidden_pooled_layers.view(batch_size, -1, self.config.hidden_size) # [batch_size, n_chunks*max_chunk_len, hidden_size]
dp = self.dropout(hidden_pooled) # [batch_size, ?, hidden_size]
# ? can be n_chunks, n_chunks*2 or n_chunks*max_chunk_len)
# output: [batch_size, ?, n_directions*hidden_size], output features from last layer for each t
# h_n: [n_layers*n_directions, batch_size, hidden_size], hidden state for t=seq_len
# c_n: [n_layers*n_directions, batch_size, hidden_size], cell state fir t=seq_len
output, (h_n, c_n) = self.lstm(dp)
h_n = h_n.squeeze(0) # [batch_size, hidden_size]
out = self.fc(h_n) # [batch_size, num_labels]
out = self.fc_bn(out)
out = F.softmax(out, dim=1) # [batch_size, num_labels]
return out
#%%
class BertPoolConv(BertPreTrainedModel):
def __init__(self, config: BertConfig):
super().__init__(config)
self.config = config
self.bert = BertModel(config)
# self.seq_summary = SequenceSummary(config)
self.dropout = nn.Dropout(config.hidden_dropout_prob)
self.convs = nn.ModuleList([nn.Conv2d(in_channels = 1,
out_channels = config.num_filters,
kernel_size = (fsize, config.hidden_size)) for fsize in config.filter_sizes
])
self.fc = nn.Linear(config.num_filters * len(config.filter_sizes), config.num_labels)
self.fc_bn = nn.BatchNorm1d(config.num_labels)
self.init_weights()
# Default: freeze bert
for name, param in self.bert.named_parameters():
param.requires_grad = False
# Unfreeze layers
if config.unfreeze == "pooler":
for name, param in self.bert.named_parameters():
if "pooler" in name:
param.requires_grad = True
if config.unfreeze == "enc-1":
n_layer = sum([1 for name, _ in self.bert.named_parameters() if "encoder.layer" in name])
last_layer = "encoder.layer." + str(int(n_layer/16-1)) # each enc layer has 16 pars
for name, param in self.bert.named_parameters():
if last_layer in name:
param.requires_grad = True
if config.unfreeze == "enc-1_pooler":
n_layer = sum([1 for name, _ in self.bert.named_parameters() if "encoder.layer" in name])
last_layer = "encoder.layer." + str(int(n_layer/16-1)) # each enc layer has 16 pars
for name, param in self.bert.named_parameters():
if last_layer in name or "pooler" in name:
param.requires_grad = True
def forward(self, doc):
"""
Input:
doc: [batch_size, n_chunks, 3, max_chunk_len]
n_chunks is the number of chunks within the batch (same for each doc after PadDoc)
Returns:
out: [batch_size, output_dim]
"""
batch_size = doc.shape[0]
hidden_pooled_layers = []
for k in range(batch_size):
# Each doc is considered as a special 'batch' and each chunk is an element of the special 'bert_batch'
# n_chunks is the temporary 'bert_batch_size', max_chunk_len corresponds to 'seq_len'
bert_output_k = self.bert(input_ids = doc[k,:,0], # [n_chunks, max_chunk_len]
attention_mask = doc[k,:,1],
token_type_ids = doc[k,:,2])
# pooled_k = bert_output_k[1].unsqueeze(0)
hidden_states_k = bert_output_k[2] # each element in the tuple: [n_chunks, max_chunk_len, hidden_size]
# Average pooling over last [pool_layers] layers
hidden_list_k = list(hidden_states_k[self.config.pool_layers:])
hidden_stack_k = torch.stack(hidden_list_k) # [n_pooled_layers, n_chunks, max_chunk_len, hidden_size]
hidden_pooled_layers_k = torch.mean(hidden_stack_k, dim=0) # [n_chunks, max_chunk_len, hidden_size]
hidden_pooled_layers.append(hidden_pooled_layers_k)
hidden_pooled_layers = torch.stack(hidden_pooled_layers) # [batch_size, n_chunks, max_chunk_len, hidden_size]
# Pooling within each chunk (over 512 word tokens of individual chunk)
if self.config.pool_method == 'mean':
hidden_pooled = torch.mean(hidden_pooled_layers, dim=2) # [batch_size, n_chunks, hidden_size]
elif self.config.pool_method == 'max':
hidden_pooled = torch.max(hidden_pooled_layers, dim=2).values # [batch_size, n_chunks, hidden_size]
elif self.config.pool_method == 'mean_max':
hidden_pooled_mean = torch.mean(hidden_pooled_layers, dim=2) # [batch_size, n_chunks, hidden_size]
hidden_pooled_max = torch.max(hidden_pooled_layers, dim=2).values # [batch_size, n_chunks, hidden_size]
hidden_pooled = torch.cat((hidden_pooled_mean, hidden_pooled_max), dim=1) # [batch_size, n_chunks*2, hidden_size]
elif self.config.pool_method == 'cls':
hidden_pooled = hidden_pooled_layers[:,:,0,:] # [batch_size, n_chunks, hidden_size]
else: # pool_method is None
hidden_pooled = hidden_pooled_layers.view(batch_size, -1, self.config.hidden_size) # [batch_size, n_chunks*max_chunk_len, hidden_size]
hidden_pooled = hidden_pooled.unsqueeze(1) # [batch_size, 1, ?, hidden_size]
hidden_conved = [F.relu(conv(hidden_pooled)) for conv in self.convs] # hidden_conved[i]: [batch_size, n_filters, (?-fsize+1), 1]
hidden_conved = [conv.squeeze(3) for conv in hidden_conved] # hidden_conved[i]: [batch_size, n_filters, (?-fsize+1)]
hc_pooled = [F.max_pool1d(conv, conv.shape[2]) for conv in hidden_conved] # hc_pooled[i]: [batch_size, n_filters, 1]
hc_pooled = [pool.squeeze(2) for pool in hc_pooled] # hc_pooled[i]: [batch_size, n_filters]
cat = torch.cat(hc_pooled, dim=1) # [batch_size, n_filters * len(filter_sizes)]
dp = self.dropout(cat)
out = self.fc(dp) # # [batch_size, num_labels]
out = self.fc_bn(out)
out = F.softmax(out, dim=1) # [batch_size, num_labels]
return out
#%%
# class AlbertLinear(AlbertPreTrainedModel):
# def __init__(self, config: AlbertConfig):
# super().__init__(config)
# self.albert = AlbertModel(config)
# self.dropout = nn.Dropout(config.hidden_dropout_prob)
# self.fc = nn.Linear(config.hidden_size, config.num_labels)
# self.fc_bn = nn.BatchNorm1d(config.num_labels)
# # self.fc = nn.Linear(config.hidden_size * config.n_chunks, config.num_labels)
# self.init_weights()
# # Default: freeze albert
# for name, param in self.albert.named_parameters():
# param.requires_grad = False
# # Unfreeze layers
# if config.unfreeze == "pooler":
# for name, param in self.albert.named_parameters():
# if "pooler" in name:
# param.requires_grad = True
# def forward(self, doc):
# """
# Input:
# doc: [batch_size, num_chunks, 3, max_chunk_len]
# Returns:
# out: [batch_size, output_dim]
# """
# batch_size = doc.shape[0]
# pooled = self.albert(input_ids = doc[0,:,0],
# attention_mask = doc[0,:,1],
# token_type_ids = doc[0,:,2])[1].unsqueeze(0)
# for i in range(batch_size-1):
# pool_i = self.albert(input_ids = doc[i+1,:,0],
# attention_mask = doc[i+1,:,1],
# token_type_ids = doc[i+1,:,2])[1]
# pooled = torch.cat((pooled, pool_i.unsqueeze(0)), dim=0)
# dp = self.dropout(pooled) # [batch_size, num_chunks, hidden_size]
# # concat = dp.view(batch_size, -1) # [batch_size, num_chunks*hidden_size]
# if self.albert.config.linear_max == True:
# dp = torch.max(dp, dim=1).values # [batch_size, hidden_size]
# else:
# dp = torch.mean(dp, dim=1) # [batch_size, hidden_size]
# # dp = dp.sum(dim=1) # [batch_size, hidden_size]
# out = self.fc(dp) # [batch_size, num_labels]
# out = self.fc_bn(out)
# out = F.softmax(out, dim=1) # [batch_size, num_labels]
# return out
#%%
# class AlbertLSTM(AlbertPreTrainedModel):
# def __init__(self, config: AlbertConfig):
# super().__init__(config)
# self.albert = AlbertModel(config)
# self.dropout = nn.Dropout(config.hidden_dropout_prob)
# self.lstm = nn.LSTM(input_size = config.hidden_size, hidden_size = config.hidden_size,
# num_layers = 1, dropout = 0,
# batch_first = True, bidirectional = False)
# self.fc = nn.Linear(config.hidden_size, config.num_labels)
# self.fc_bn = nn.BatchNorm1d(config.num_labels)
# self.tanh = nn.Tanh()
# self.init_weights()
# # Default: freeze albert
# for name, param in self.albert.named_parameters():
# param.requires_grad = False
# # Unfreeze layers
# if config.unfreeze == "embed":
# for name, param in self.albert.named_parameters():
# if "embeddings" in name:
# param.requires_grad = True
# if config.unfreeze == "embed_enc0":
# for name, param in self.albert.named_parameters():
# if "embeddings" in name or "encoder" in name:
# param.requires_grad = True
# if config.unfreeze == "embed_enc0_pooler":
# for name, param in self.albert.named_parameters():
# param.requires_grad = True
# if config.unfreeze == "enc0":
# for name, param in self.albert.named_parameters():
# if "encoder" in name:
# param.requires_grad = True
# if config.unfreeze == "enc0_pooler":
# for name, param in self.albert.named_parameters():
# if "encoder" in name or "pooler" in name:
# param.requires_grad = True
# if config.unfreeze == "embed_pooler":
# for name, param in self.albert.named_parameters():
# if "embed" in name or "pooler" in name:
# param.requires_grad = True
# if config.unfreeze == "pooler":
# for name, param in self.albert.named_parameters():
# if "pooler" in name:
# param.requires_grad = True
# def forward(self, doc):
# """
# Input:
# doc: [batch_size, num_chunks, 3, max_chunk_len]
# Returns:
# out: [batch_size, output_dim]
# """
# batch_size = doc.shape[0]
# pooled = self.albert(input_ids = doc[0,:,0],
# attention_mask = doc[0,:,1],
# token_type_ids = doc[0,:,2])[1].unsqueeze(0)
# for i in range(batch_size-1):
# # Output of BertModel: (last_hidden_state, pooler_output, hidden_states, attentions)
# # Last layer hidden-state of the first token of the sequence (classification token)
# pool_i = self.albert(input_ids = doc[i+1,:,0],
# attention_mask = doc[i+1,:,1],
# token_type_ids = doc[i+1,:,2])[1]
# pooled = torch.cat((pooled, pool_i.unsqueeze(0)), dim=0)
# dp = self.dropout(pooled) # [batch_size, num_chunks, bert_hidden_size]
# # output: [batch_size, num_chunks, n_directions*hidden_size], output features from last layer for each t
# # h_n: [n_layers*n_directions, batch_size, hidden_size], hidden state for t=seq_len
# # c_n: [n_layers*n_directions, batch_size, hidden_size], cell state fir t=seq_len
# output, (h_n, c_n) = self.lstm(dp)
# # h_n = output[:,-1,].squeeze(1) # [batch_size, hidden_size]
# h_n = h_n.squeeze(0) # [batch_size, hidden_size]
# out = self.fc(h_n) # [batch_size, num_labels]
# out = self.fc_bn(out)
# out = F.softmax(out, dim=1) # [batch_size, num_labels]
# # out = self.tanh(out) # [batch_size, num_labels]
# return out
| 48.631791
| 147
| 0.570335
| 2,993
| 24,170
| 4.336786
| 0.065486
| 0.063097
| 0.049923
| 0.033282
| 0.910478
| 0.903082
| 0.891988
| 0.882897
| 0.870955
| 0.863328
| 0
| 0.012602
| 0.326976
| 24,170
| 497
| 148
| 48.631791
| 0.785332
| 0.458875
| 0
| 0.807882
| 0
| 0
| 0.027466
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.029557
| false
| 0
| 0.019704
| 0
| 0.078818
| 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
|
2204d61ba92f503f1a570e6d58ec68553416d4cc
| 21,463
|
py
|
Python
|
PyMORUSTESTCASES.py
|
SparkDustJoe/PyMORUS
|
419138e5440a5f6cc49fb10369d447e6f9532432
|
[
"Unlicense"
] | 1
|
2021-11-30T07:36:12.000Z
|
2021-11-30T07:36:12.000Z
|
PyMORUSTESTCASES.py
|
SparkDustJoe/PyMORUS
|
419138e5440a5f6cc49fb10369d447e6f9532432
|
[
"Unlicense"
] | null | null | null |
PyMORUSTESTCASES.py
|
SparkDustJoe/PyMORUS
|
419138e5440a5f6cc49fb10369d447e6f9532432
|
[
"Unlicense"
] | null | null | null |
from collections import namedtuple;
def PyMorusCases(word_width):
"""
Return list of namedtuple TestCase 'P AD K IV C T' for either 32-bit or 64-bit flavor of Morus
Payload, Additional Data, Key, IV/Nonce, Ciphertext, and Tag
"""
TestCase = namedtuple('TestCase', 'P AD K IV C T');
assert word_width in (32, 64);
cases = []
if (word_width == 32):
cases.append(TestCase( # 0
P=None,
AD=None,
K=bytes(16),
IV=bytes(16),
C=bytearray(0),
T=bytearray.fromhex('e407fb2255b1314dbfadccfef8102da8')
));
cases.append(TestCase( # 1
P=bytearray.fromhex('01'),
AD=None,
K=bytes(16),
IV=bytes(16),
C=bytearray.fromhex('26'),
T=bytearray.fromhex('ff1c7a66849675f509f428369c06e8d6')
));
cases.append(TestCase( # 2
P=None,
AD=bytearray.fromhex('01'),
K=bytes(16),
IV=bytes(16),
C=bytearray(0),
T=bytearray.fromhex('1d229cca8ef97ee7c1524326e8dfadba')
));
cases.append(TestCase( # 3
P=bytearray.fromhex('00'),
AD=bytearray.fromhex('00'),
K=bytearray.fromhex('01000000000000000000000000000000'),
IV=bytes(16),
C=bytearray.fromhex('d2'),
T=bytearray.fromhex('4b15ab1cb7cc83791deb6aa9315f4c86')
));
cases.append(TestCase( # 4
P=bytearray.fromhex('00'),
AD=bytearray.fromhex('00'),
K=bytes(16),
IV=bytearray.fromhex('01000000000000000000000000000000'),
C=bytearray.fromhex('a7'),
T=bytearray.fromhex('640b0d536f59b6a8d16bf773b49a5be7')
));
cases.append(TestCase( # 5
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('01010101010101010101010101010101'),
IV=bytearray.fromhex('01010101010101010101010101010101'),
C=bytearray.fromhex('fb5d640c97e673b66abffcc45e72b420'),
T=bytearray.fromhex('8ed9998761d8900f6d72cc5656186848')
));
cases.append(TestCase( # 6
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('512b6a397e8f830e5755b2793d384d90'),
T=bytearray.fromhex('f9842b369701cd29acf2c39907930373')
));
cases.append(TestCase( # 7
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('01010101010101010101010101010101'),
IV=bytearray.fromhex('01010101010101010101010101010101'),
C=bytearray.fromhex('fb5d640c97e673b66abffcc45e72b420'),
T=bytearray.fromhex('8ed9998761d8900f6d72cc5656186848')
));
cases.append(TestCase( # 8
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('512b6a397e8f830e5755b2793d384d90'),
T=bytearray.fromhex('f9842b369701cd29acf2c39907930373')
));
elif (word_width == 64):
#64-bit with 16-byte keys
cases.append(TestCase( # 0
P=None,
AD=None,
K=bytes(16),
IV=bytes(16),
C=bytearray(0),
T=bytearray.fromhex('5bd2cba68ea7e72f6b3d0c155f39f962')
));
cases.append(TestCase( # 1
P=bytearray.fromhex('01'),
AD=None,
K=bytes(16),
IV=bytes(16),
C=bytearray.fromhex('ba'),
T=bytearray.fromhex('ec1942a315a84695432a1255e6197878')
));
cases.append(TestCase( # 2
P=None,
AD=bytearray.fromhex('01'),
K=bytes(16),
IV=bytes(16),
C=bytearray(0),
T=bytearray.fromhex('590caa148b848d7614315685377a0d42')
));
cases.append(TestCase( # 3
P=bytearray.fromhex('00'),
AD=bytearray.fromhex('00'),
K=bytearray.fromhex('01000000000000000000000000000000'),
IV=bytes(16),
C=bytearray.fromhex('cf'),
T=bytearray.fromhex('f9f0a331e3de3293b9dd2e65ba820009')
));
cases.append(TestCase( # 4
P=bytearray.fromhex('00'),
AD=bytearray.fromhex('00'),
K=bytes(16),
IV=bytearray.fromhex('01000000000000000000000000000000'),
C=bytearray.fromhex('09'),
T=bytearray.fromhex('c957f9ca617876b5205155cd936eb9bb')
));
cases.append(TestCase( # 5
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('01010101010101010101010101010101'),
IV=bytearray.fromhex('01010101010101010101010101010101'),
C=bytearray.fromhex('8831c1e547f7272ccae2ced2997cca44'),
T=bytearray.fromhex('43c058e1c32e21f82313c50dc95aa68a')
));
cases.append(TestCase( # 6
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('b64ee39fc045475e97b41bd08277b4cb'),
T=bytearray.fromhex('e989740eb075f75bd57a43a250f53765')
));
cases.append(TestCase( # 7
P=bytearray.fromhex('00070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8'),
AD=bytearray.fromhex('00050a0f14191e23282d32373c41464b50555a5f64696e73787d82878c91969ba0a5aaafb4b9be'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('0861b4924850e8a945e60ec08a1b04f3c77dd2b05ccb05c05c567be8cdfd458228a390c4117b66d71fade7f89902e4d500389a275cb0ce5685f3a21beb6d6519f465b96f1eaf9eeea2'),
T=bytearray.fromhex('5e43f30fa0adb318083a795fc23df52c')
));
cases.append(TestCase( # 8
P=bytearray.fromhex('00070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a'),
AD=bytearray.fromhex('00050a0f14191e23282d32373c41464b50555a5f64696e73787d82878c91969ba0a5aaafb4b9bec3c8cdd2d7dce1e6ebf0f5faff04090e13181d22272c31363b40454a4f54595e63686d72777c81868b90959a9fa4a9aeb3b8bdc2c7ccd1d6dbe0e5eaeff4f9fe03080d12171c21262b30353a3f44494e53585d62676c71767b80858a8f94999ea3a8adb2b7bcc1c6cbd0d5dadfe4e9eef3f8fd02070c11161b20252a2f34393e43484d52575c61666b70757a7f84898e93989da2a7acb1b6bbc0c5cacfd4d9dee3e8edf2f7fc01060b10151a1f24292e33383d42474c51565b60656a6f74797e83888d92979ca1a6abb0b5babfc4c9ced3d8dde2e7ecf1f6fb00050a0f14191e23282d32373c41464b50555a5f64696e73787d82878c91969ba0a5aaafb4b9bec3c8cdd2d7dce1e6ebf0f5faff04090e13181d22272c31363b40454a4f54595e63686d72777c81868b90959a9fa4a9aeb3b8bdc2c7ccd1d6dbe0e5eaeff4f9fe03080d12171c21262b30353a3f44494e53585d62676c71767b80858a8f94999ea3a8adb2b7bcc1c6cbd0d5dadfe4e9eef3f8fd02070c11161b20252a2f34393e43484d52575c61666b70757a7f84898e93989da2a7acb1b6bbc0c5cacfd4d9dee3e8edf2f7fc01060b10151a1f24292e33383d42474c51565b60656a6f74797e83888d92979ca1a6abb0b5babfc4c9ced3d8dde2e7ecf1f6fb0005'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('091689ea18d82110c2097aa984977c2258f42f0c12886c1baefb0822b193389429d6214aa951b45870ae279569c162577fe0f7b381251af868da0f9f220c6618dc4f1d6db02914a33b2def945ce0fe771f1302165ab64c06da2bd60f194a198482b24b00b684c102bc5cfaaeda435803a6a772a076cb50371b0cac7c7179ebc1ea7c5924864c56d3857f996af4325a8b24bf2d0d1647c5597d3eb38f46494178166c3c0934af203ac307dd3b73930000b82ddfae385fe0844c9018c69049ab65470ec110cf7f8ad69415c691b4806fdf37bf470ab2ad6e253957f0ce64a09376adec893dbbfd03dd368688f7702692f72cdba5368a05210554d2b6d4d876bf49277353c5347a902045becbfdc1c5346df0abe5e90099332fddd61bccff267919cb07ca0c2595c6c740d299fd37c9c2667d7b444937872fca68e574a00c1e558023f8a4a4e22fabfdbc45dfb0ef5af173d104852a82dc5bf6cea4cdb2ede955f2ef29b1b642e55dff38455b8dd572bc734da52c9325bea8061fd30ebafef1ceafdb877b5f88f3a38423018088fd91854f5f1edcb09ca14d404862bab3b242e820504f400931e1d7d83d6c8f9f3c95b1f9e984f94d6afe1276ad5c8a70d364e36c4d9d43f12c586d0813e98584eacc423f476bbbdf23536dbafab19447fbf628974c6973a653e8c4af61c8eadc1eb844f87206fbb6eeeba9224e9b3d5536df047eb8fef6aa2403ca64c191c6c6c50e714473cc97ac0435154fd7dd958df88e30eb27bc42069bda9f03a3e5c1fcf358b1b10ef557b2b1658c4972df71f2d2069e7520dc791ca5fd23deb43178b6ac32498b998d3f9a792a8b6d4a6454a18d7b7fca879262f3ca567e055e7c30575e48bd24efdb49fb3898d604c48ecb0d0333e400c95d2dca5b816637c7ad6622bbf2146d1e7162535141ba1bb8db7171c6158f2f7e9363f27c29a72c02cbfb2d38463288dac1e4916ac9f0b4084cba34d35d37856a7505e5974dfeb9a24b6dc7fd6b067eb5121244748452443a8fdbbd86e87986f5fc9952c68d100bd4c62c12b40b1dcd75291b8715775c785228c3daaae3ae5de25d96c2cdf6992c72bebd19bdaebef70c53116e15826f58a58ea4f25cc12dae10f8437636436ecd05bde3f470a4a97aba0840b37b9609722bcd81d55fa7e6d8be38f9be11b087a98cafad28f33154ead815a057629715985d183b0a828e0391cab9744265b84fdad5de2f0c188255e26778c2e3fbd8cd72e2e8ae9246c6a6fa4fd6ec9472c03c4fbdfea82d35cb32593e0175dc65438fd769bfcb62bacb368c246db2d6031910df0d5bfd3ca16f449a58e444a502147024544363ac6cc691b6cd5614a215b9d7bdfa151ee4412f84a2ff51084102777e3a1d5bd0420aac5f4db96465212cc0bd66d00a4494b9ec73d83453db49f77c30b253de79c8b337668c681766f8631d9a'),
T=bytearray.fromhex('5397afda1e9784245d0a915f84b7f510')
));
#64-bit but now with 32-byte keys
cases.append(TestCase( # 9 (0)
P=None,
AD=None,
K=bytes(32),
IV=bytes(16),
C=bytearray(0),
T=bytearray.fromhex('5bd2cba68ea7e72f6b3d0c155f39f962')
));
cases.append(TestCase( # 10 (1)
P=bytearray.fromhex('01'),
AD=None,
K=bytes(32),
IV=bytes(16),
C=bytearray.fromhex('ba'),
T=bytearray.fromhex('ec1942a315a84695432a1255e6197878')
));
cases.append(TestCase( # 11 (2)
P=None,
AD=bytearray.fromhex('01'),
K=bytes(32),
IV=bytes(16),
C=bytearray(0),
T=bytearray.fromhex('590caa148b848d7614315685377a0d42')
));
cases.append(TestCase( # 12 (3)
P=bytearray.fromhex('00'),
AD=bytearray.fromhex('00'),
K=bytearray.fromhex('0100000000000000000000000000000000000000000000000000000000000000'),
IV=bytes(16),
C=bytearray.fromhex('99'),
T=bytearray.fromhex('3452c0f33fb548d09f7bb50a53dd2f72')
));
cases.append(TestCase( # 13 (4)
P=bytearray.fromhex('00'),
AD=bytearray.fromhex('00'),
K=bytes(32),
IV=bytearray.fromhex('01000000000000000000000000000000'),
C=bytearray.fromhex('09'),
T=bytearray.fromhex('c957f9ca617876b5205155cd936eb9bb')
));
cases.append(TestCase( # 14 (5)
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('0101010101010101010101010101010101010101010101010101010101010101'),
IV=bytearray.fromhex('01010101010101010101010101010101'),
C=bytearray.fromhex('8831c1e547f7272ccae2ced2997cca44'),
T=bytearray.fromhex('43c058e1c32e21f82313c50dc95aa68a')
));
cases.append(TestCase( # 15 (6)
P=bytearray.fromhex('01010101010101010101010101010101'),
AD=bytearray.fromhex('01010101010101010101010101010101'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('aecb6f5991a11746831740e4d45b6c26'),
T=bytearray.fromhex('c3107488470f05e6828472ac0264045d')
));
cases.append(TestCase( # 16 (7)
P=bytearray.fromhex('00070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8'),
AD=bytearray.fromhex('00050a0f14191e23282d32373c41464b50555a5f64696e73787d82878c91969ba0a5aaafb4b9be'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('3e440c73993c55074d4749d6cd8ceddebb95ea8d2387062237349123c75959bfa3ff44b18395a0bfc834d5f2de24845bffdba576afab00e798ad5a166689288373f84ead85eb77aa2d'),
T=bytearray.fromhex('f3166bbf6f94a1932b4b2471e8437206')
));
cases.append(TestCase( # 17 (8)
P=bytearray.fromhex('00070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a31383f464d545b626970777e858c939aa1a8afb6bdc4cbd2d9e0e7eef5fc030a11181f262d343b424950575e656c737a81888f969da4abb2b9c0c7ced5dce3eaf1f8ff060d141b222930373e454c535a61686f767d848b9299a0a7aeb5bcc3cad1d8dfe6edf4fb020910171e252c333a41484f565d646b727980878e959ca3aab1b8bfc6cdd4dbe2e9f0f7fe050c131a21282f363d444b525960676e757c838a91989fa6adb4bbc2c9d0d7dee5ecf3fa01080f161d242b323940474e555c636a71787f868d949ba2a9b0b7bec5ccd3dae1e8eff6fd040b121920272e353c434a51585f666d747b828990979ea5acb3bac1c8cfd6dde4ebf2f900070e151c232a'),
AD=bytearray.fromhex('00050a0f14191e23282d32373c41464b50555a5f64696e73787d82878c91969ba0a5aaafb4b9bec3c8cdd2d7dce1e6ebf0f5faff04090e13181d22272c31363b40454a4f54595e63686d72777c81868b90959a9fa4a9aeb3b8bdc2c7ccd1d6dbe0e5eaeff4f9fe03080d12171c21262b30353a3f44494e53585d62676c71767b80858a8f94999ea3a8adb2b7bcc1c6cbd0d5dadfe4e9eef3f8fd02070c11161b20252a2f34393e43484d52575c61666b70757a7f84898e93989da2a7acb1b6bbc0c5cacfd4d9dee3e8edf2f7fc01060b10151a1f24292e33383d42474c51565b60656a6f74797e83888d92979ca1a6abb0b5babfc4c9ced3d8dde2e7ecf1f6fb00050a0f14191e23282d32373c41464b50555a5f64696e73787d82878c91969ba0a5aaafb4b9bec3c8cdd2d7dce1e6ebf0f5faff04090e13181d22272c31363b40454a4f54595e63686d72777c81868b90959a9fa4a9aeb3b8bdc2c7ccd1d6dbe0e5eaeff4f9fe03080d12171c21262b30353a3f44494e53585d62676c71767b80858a8f94999ea3a8adb2b7bcc1c6cbd0d5dadfe4e9eef3f8fd02070c11161b20252a2f34393e43484d52575c61666b70757a7f84898e93989da2a7acb1b6bbc0c5cacfd4d9dee3e8edf2f7fc01060b10151a1f24292e33383d42474c51565b60656a6f74797e83888d92979ca1a6abb0b5babfc4c9ced3d8dde2e7ecf1f6fb0005'),
K=bytearray.fromhex('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'),
IV=bytearray.fromhex('000306090c0f1215181b1e2124272a2d'),
C=bytearray.fromhex('a4e9b76daa84ea04c2a945e8728b3c476f326672d31e8175763026aa4299e741ebdc8b1f2fe7806b5d9aed247a9cde143f96072faeecfe9c163453b4f4997b1320abfa545e0d4fd41c2baea1cfa9dae3919d4fa79faef0d8b63a358f9547d717a0112949c6434dfe765c75737c03b1056333234194027d4d769fbc41728d0eff5222fbce4337940158722904150c1dffbd0b0c2b425f5fe40c957d255997f6f1c197838812422eed0b42a53b9453d945b0aad293ecb9995a73ade4be202dab53f418b7bb66c62ce93739cc35b9654c65d636fb590787c4f22eb22f7a5e8a7ae78861300ac6adcddd2996a19f972357de8fc67d831f58bf79841ae1ece222dff2fb01f914ed73f10381050e2124536984a7b4dbf34e9a34d5a89c0786a96e2744af0e8b52f078be56657427786cbba83d67a4ad0c86d1f1868794b0cba951cf6c82db3ac4515387ffa3dfe150d16cf12b9e6dc5b7e5363a0de44ccfbb4a7af903e598b17d3672df37edb021d40a4c4621ca63008f9f01cbfdd4c295e0052fe0ffa4888da92554b3a61c374c5012f2930c3d109d94fd71d490f84bc4b7a4c5d7d55ac47418e21bc71172b4a8e953a198b84b63b617ae7734b9a446669682f467b8ccd4d590e9a35f87cc470068a7474aeb6303b0a4c2c2e1f75466ba928b2dbb1f763ad52ff8f022998733c38f2782a2a0e13f4eb7ce26777bfd76f9a08d589e416c8d24a3f757d6429a016b17b3e9f93f6ff094b6d7df4fd8ea829be3414a4c33f1a00a32823eb860b27de16259db37b5b570eb33e0b4f12eb155d46dcaafae222b6473b3c26ec180f445a9fbdad924d36b48fef3ac92f6a57c5a59081f93715b31127617060afea2246d17e263db3c5125f792aea3dca2c48f9886a170ebe21458b1fd021340c3ee0e08f729d0aec2d80c270488708cbcec32efc602cfd07996a10b9e5f31488c75d0cb73ace8ee23c4118b9e730d043ba34c4997853d6943153234cbd06f5487b0fafc20318efbed01261d3dbd874b4b1b449b529f6175dbf07738252baf57106fe8c900c22605a6c9935b623da4020b243e3755d1938e15e135b124675055133411918517b0a25ab0106e4c3f04313d82b75d2cd13908628ba267c5d91d04d49a7f592d64f7a6f5a19aabc6904da0402bb1e456356ad0c4261338e0c810789ab6cc95b228123bfc9c1e6b6075c3c4f571dd0bdbf3399e70a49edc2532c610bb411bfe4a6b79abf909599235721d7b4ce09966aa726fd2b3d224428b67e719c412b6cde3d46fd0faffe86d245e0745bd41d3181a768f640e59d7b3242c22d7d8a62cd68e5bd736f5379ad19896fd3bce1adae3c994aab45792a98eef931d700000f6081a8d1040972682f50382aa1db59352adf5593685e4ce813fba616f0c546915d897565c3dd0239bb2dfedf364db8f07bfb431d19acb0d67454fa38f28da'),
T=bytearray.fromhex('2463e5794bc56c06e9aa7da25dbe5dfd')
));
else:
return None;
return cases;
if (__name__ == "__main__"):
print(len(PyMorusCases(32)));
print(len(PyMorusCases(64)));
print("PyMorusTESTCASES.py **NOT A STANDALONE MODULE!**");
| 89.803347
| 2,098
| 0.804128
| 810
| 21,463
| 21.292593
| 0.15679
| 0.111324
| 0.029744
| 0.006958
| 0.672001
| 0.669972
| 0.668464
| 0.664695
| 0.66168
| 0.659013
| 0
| 0.506591
| 0.137586
| 21,463
| 238
| 2,099
| 90.180672
| 0.425176
| 0.014443
| 0
| 0.826087
| 0
| 0
| 0.659891
| 0.653684
| 0
| 1
| 0
| 0
| 0.004348
| 1
| 0.004348
| false
| 0
| 0.004348
| 0
| 0.017391
| 0.013043
| 0
| 0
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 1
| 0
| 0
| 1
| 1
| null | 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 9
|
2208a1106b34c9dde125fbbd87a94fa3980d988b
| 8,208
|
py
|
Python
|
tests/test_names.py
|
zanachka/spidermon
|
d2840b6bbb6ba6d8a0ef633deac66588d243e615
|
[
"BSD-3-Clause"
] | 405
|
2019-01-10T13:06:09.000Z
|
2022-03-30T20:14:58.000Z
|
tests/test_names.py
|
zanachka/spidermon
|
d2840b6bbb6ba6d8a0ef633deac66588d243e615
|
[
"BSD-3-Clause"
] | 226
|
2019-01-04T13:31:17.000Z
|
2022-03-28T21:06:10.000Z
|
tests/test_names.py
|
zanachka/spidermon
|
d2840b6bbb6ba6d8a0ef633deac66588d243e615
|
[
"BSD-3-Clause"
] | 87
|
2019-01-07T10:23:26.000Z
|
2022-02-22T04:38:04.000Z
|
import pytest
from .fixtures.names import *
NAMES = [
"UnnamedMonitor/A Test",
"UnnamedMonitor/test_without_name",
"Class Monitor/A Test",
"Class Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"UnnamedMonitor/A Test",
"UnnamedMonitor/test_without_name",
"Class Monitor/A Test",
"Class Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"UnnamedMonitor/A Test",
"UnnamedMonitor/test_without_name",
"Class Monitor/A Test",
"Class Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"UnnamedMonitor/A Test",
"UnnamedMonitor/test_without_name",
"Class Monitor/A Test",
"Class Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
]
MONITOR_NAMES = [
"UnnamedMonitor",
"UnnamedMonitor",
"Class Monitor",
"Class Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"UnnamedMonitor",
"UnnamedMonitor",
"Class Monitor",
"Class Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"UnnamedMonitor",
"UnnamedMonitor",
"Class Monitor",
"Class Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"UnnamedMonitor",
"UnnamedMonitor",
"Class Monitor",
"Class Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
"Instance Monitor",
]
METHOD_NAMES = [
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
"A Test",
"test_without_name",
]
FULL_NAMES_UNNNAMED_SUITE = [
"UnnamedMonitor/A Test",
"UnnamedMonitor/test_without_name",
"Class Monitor/A Test",
"Class Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"Instance Monitor/A Test",
"Instance Monitor/test_without_name",
"The Child Suite/UnnamedMonitor/A Test",
"The Child Suite/UnnamedMonitor/test_without_name",
"The Child Suite/Class Monitor/A Test",
"The Child Suite/Class Monitor/test_without_name",
"The Child Suite/Instance Monitor/A Test",
"The Child Suite/Instance Monitor/test_without_name",
"The Child Suite/Instance Monitor/A Test",
"The Child Suite/Instance Monitor/test_without_name",
"Instance Suite Name/UnnamedMonitor/A Test",
"Instance Suite Name/UnnamedMonitor/test_without_name",
"Instance Suite Name/Class Monitor/A Test",
"Instance Suite Name/Class Monitor/test_without_name",
"Instance Suite Name/Instance Monitor/A Test",
"Instance Suite Name/Instance Monitor/test_without_name",
"Instance Suite Name/Instance Monitor/A Test",
"Instance Suite Name/Instance Monitor/test_without_name",
"Instance Suite Name/UnnamedMonitor/A Test",
"Instance Suite Name/UnnamedMonitor/test_without_name",
"Instance Suite Name/Class Monitor/A Test",
"Instance Suite Name/Class Monitor/test_without_name",
"Instance Suite Name/Instance Monitor/A Test",
"Instance Suite Name/Instance Monitor/test_without_name",
"Instance Suite Name/Instance Monitor/A Test",
"Instance Suite Name/Instance Monitor/test_without_name",
]
FULL_NAMES_NAMED_SUITE = [
"The Top Suite/UnnamedMonitor/A Test",
"The Top Suite/UnnamedMonitor/test_without_name",
"The Top Suite/Class Monitor/A Test",
"The Top Suite/Class Monitor/test_without_name",
"The Top Suite/Instance Monitor/A Test",
"The Top Suite/Instance Monitor/test_without_name",
"The Top Suite/Instance Monitor/A Test",
"The Top Suite/Instance Monitor/test_without_name",
"The Top Suite/The Child Suite/UnnamedMonitor/A Test",
"The Top Suite/The Child Suite/UnnamedMonitor/test_without_name",
"The Top Suite/The Child Suite/Class Monitor/A Test",
"The Top Suite/The Child Suite/Class Monitor/test_without_name",
"The Top Suite/The Child Suite/Instance Monitor/A Test",
"The Top Suite/The Child Suite/Instance Monitor/test_without_name",
"The Top Suite/The Child Suite/Instance Monitor/A Test",
"The Top Suite/The Child Suite/Instance Monitor/test_without_name",
"The Top Suite/Instance Suite Name/UnnamedMonitor/A Test",
"The Top Suite/Instance Suite Name/UnnamedMonitor/test_without_name",
"The Top Suite/Instance Suite Name/Class Monitor/A Test",
"The Top Suite/Instance Suite Name/Class Monitor/test_without_name",
"The Top Suite/Instance Suite Name/Instance Monitor/A Test",
"The Top Suite/Instance Suite Name/Instance Monitor/test_without_name",
"The Top Suite/Instance Suite Name/Instance Monitor/A Test",
"The Top Suite/Instance Suite Name/Instance Monitor/test_without_name",
"The Top Suite/Instance Suite Name/UnnamedMonitor/A Test",
"The Top Suite/Instance Suite Name/UnnamedMonitor/test_without_name",
"The Top Suite/Instance Suite Name/Class Monitor/A Test",
"The Top Suite/Instance Suite Name/Class Monitor/test_without_name",
"The Top Suite/Instance Suite Name/Instance Monitor/A Test",
"The Top Suite/Instance Suite Name/Instance Monitor/test_without_name",
"The Top Suite/Instance Suite Name/Instance Monitor/A Test",
"The Top Suite/Instance Suite Name/Instance Monitor/test_without_name",
]
@pytest.fixture
def named_top_suite():
return NamedTopSuite()
@pytest.fixture
def unnamed_top_suite():
return UnnamedTopSuite()
def test_names(named_top_suite, unnamed_top_suite):
_check_names(generated_names=_generate_names(named_top_suite), expected_names=NAMES)
_check_names(
generated_names=_generate_names(unnamed_top_suite), expected_names=NAMES
)
def test_monitor_names(named_top_suite, unnamed_top_suite):
_check_names(
generated_names=_generate_monitor_names(named_top_suite),
expected_names=MONITOR_NAMES,
)
_check_names(
generated_names=_generate_monitor_names(unnamed_top_suite),
expected_names=MONITOR_NAMES,
)
def test_method_names(named_top_suite, unnamed_top_suite):
_check_names(
generated_names=_generate_method_names(named_top_suite),
expected_names=METHOD_NAMES,
)
_check_names(
generated_names=_generate_method_names(unnamed_top_suite),
expected_names=METHOD_NAMES,
)
def test_full_names(named_top_suite, unnamed_top_suite):
_check_names(
generated_names=_generate_full_names(named_top_suite),
expected_names=FULL_NAMES_NAMED_SUITE,
)
_check_names(
generated_names=_generate_full_names(unnamed_top_suite),
expected_names=FULL_NAMES_UNNNAMED_SUITE,
)
def _generate_names(suite):
return [test.name for test in suite.all_monitors]
def _generate_monitor_names(suite):
return [test.monitor_name for test in suite.all_monitors]
def _generate_method_names(suite):
return [test.method_name for test in suite.all_monitors]
def _generate_full_names(suite):
return [test.full_name for test in suite.all_monitors]
def _check_names(generated_names, expected_names):
assert len(generated_names) == len(expected_names)
for generated_name, expected_name in zip(generated_names, expected_names):
assert generated_name == expected_name
| 32.571429
| 88
| 0.720882
| 1,058
| 8,208
| 5.334594
| 0.035917
| 0.056697
| 0.170092
| 0.140326
| 0.917789
| 0.899008
| 0.84107
| 0.810418
| 0.759391
| 0.718994
| 0
| 0
| 0.180312
| 8,208
| 251
| 89
| 32.701195
| 0.838882
| 0
| 0
| 0.725225
| 0
| 0
| 0.584795
| 0.179337
| 0
| 0
| 0
| 0
| 0.009009
| 1
| 0.04955
| false
| 0
| 0.009009
| 0.027027
| 0.085586
| 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
|
223697c42127b219beb41c2ac0f2064ffe490b52
| 8,495
|
py
|
Python
|
tests/user/test_views.py
|
uktrade/market-access-api
|
850a59880f8f62263784bcd9c6b3362e447dbc7a
|
[
"MIT"
] | null | null | null |
tests/user/test_views.py
|
uktrade/market-access-api
|
850a59880f8f62263784bcd9c6b3362e447dbc7a
|
[
"MIT"
] | 51
|
2018-05-31T12:16:31.000Z
|
2022-03-08T09:36:48.000Z
|
tests/user/test_views.py
|
uktrade/market-access-api
|
850a59880f8f62263784bcd9c6b3362e447dbc7a
|
[
"MIT"
] | 2
|
2019-12-24T09:47:42.000Z
|
2021-02-09T09:36:51.000Z
|
from unittest.mock import patch
import pytest
from rest_framework import status
from rest_framework.reverse import reverse
from api.core.test_utils import APITestMixin, create_test_user
class TestUserView(APITestMixin):
"""User view test case."""
@patch("api.user.staff_sso.StaffSSO.get_logged_in_user_details")
def test_who_am_i_authenticated(self, mock_sso_api):
"""Who am I."""
user_test = create_test_user()
api_client = self.create_api_client(user=user_test)
mock_sso_api.return_value = self.sso_user_data_1
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data["email"] == self.sso_user_data_1["email"]
assert (
response_data["username"] == f"{user_test.first_name} {user_test.last_name}"
)
@patch("api.user.staff_sso.StaffSSO.get_logged_in_user_details")
def test_who_am_i_email_as_username(self, mock_sso_api):
"""Who am I, when email is set in username"""
user_test = create_test_user(username="Testo@Useri.com")
api_client = self.create_api_client(user=user_test)
mock_sso_api.return_value = self.sso_user_data_1
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data["email"] == self.sso_user_data_1["email"]
assert (
response_data["username"] == f"{user_test.first_name} {user_test.last_name}"
)
@patch("api.user.staff_sso.StaffSSO.get_logged_in_user_details")
def test_who_am_i_no_username(self, mock_sso_api):
"""Who am I, when email is set in username"""
user_test = create_test_user(email="Test.Email@Useri.com", username="")
api_client = self.create_api_client(user=user_test)
mock_sso_api.return_value = self.sso_user_data_1
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data["email"] == self.sso_user_data_1["email"]
assert (
response_data["username"] == f"{user_test.first_name} {user_test.last_name}"
)
@patch("api.user.staff_sso.StaffSSO.get_logged_in_user_details")
def test_who_am_i_no_username_no_email(self, mock_sso_api):
"""Who am I, when email is set in username"""
user_test = create_test_user(email="", username="")
api_client = self.create_api_client(user=user_test)
mock_sso_api.return_value = self.sso_user_data_1
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data["email"] == self.sso_user_data_1["email"]
assert (
response_data["username"] == f"{user_test.first_name} {user_test.last_name}"
)
@patch("api.user.staff_sso.StaffSSO.get_logged_in_user_details")
def test_who_am_sso_data_none(self, mock_sso_api):
"""Who am I, when email is set in username"""
user_test = create_test_user(email="Test.Email@Useri.com", username="")
api_client = self.create_api_client(user=user_test)
mock_sso_api.return_value = None
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data["email"] == "Test.Email@Useri.com"
assert (
response_data["username"] == f"{user_test.first_name} {user_test.last_name}"
)
assert response_data["first_name"] == user_test.first_name
assert response_data["last_name"] == user_test.last_name
@pytest.mark.skip(
reason="it was not being picked up by the runner due to the leading _"
)
def test_user_country(self):
"""Test user's country"""
user_test = create_test_user(location="ba6ee1ca-5d95-e211-a939-e4115bead28a")
api_client = self.create_api_client(user=user_test)
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data == {
"id": user_test.id,
"username": user_test.username,
"last_login": None,
"first_name": user_test.first_name,
"last_name": user_test.last_name,
"email": user_test.email,
"location": "ba6ee1ca-5d95-e211-a939-e4115bead28a",
"internal": False,
"permitted_applications": None,
"user_profile": None,
}
@pytest.mark.skip(
reason="it was not being picked up by the runner due to the leading _"
)
def test_user_internal(self):
"""Test user's internal flag"""
user_test = create_test_user(internal=True)
api_client = self.create_api_client(user=user_test)
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data == {
"id": user_test.id,
"username": user_test.username,
"last_login": None,
"first_name": user_test.first_name,
"last_name": user_test.last_name,
"email": user_test.email,
"location": None,
"internal": True,
"permitted_applications": None,
"user_profile": None,
}
@pytest.mark.skip(
reason="it was not being picked up by the runner due to the leading _"
)
def test_user_profile(self):
"""Test user's internal flag"""
profile = {
"internal": False,
"watch_lists": {
"watch_list_1": {"country": "955f66a0-5d95-e211-a939-e4115bead28a"}
},
}
user_test = create_test_user(user_profile=profile)
api_client = self.create_api_client(user=user_test)
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data == {
"id": user_test.id,
"username": user_test.username,
"last_login": None,
"first_name": user_test.first_name,
"last_name": user_test.last_name,
"email": user_test.email,
"location": None,
"internal": False,
"permitted_applications": None,
"user_profile": {
"internal": False,
"watch_lists": {
"watch_list_1": {"country": "955f66a0-5d95-e211-a939-e4115bead28a"}
},
},
}
@pytest.mark.skip(
reason="it was not being picked up by the runner due to the leading _"
)
def test_user_edit_add_new_profile(self):
"""Test user's internal flag"""
user_test = create_test_user(internal=True)
api_client = self.create_api_client(user=user_test)
url = reverse("who_am_i")
response = api_client.get(url)
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert response_data == {
"id": user_test.id,
"username": user_test.username,
"last_login": None,
"first_name": user_test.first_name,
"last_name": user_test.last_name,
"email": user_test.email,
"location": None,
"internal": True,
"permitted_applications": None,
"user_profile": None,
}
edit_response = self.api_client.patch(
url,
format="json",
data={
"user_profile": {
"internal": False,
"watch_lists": {
"watch_list_1": {
"country": "955f66a0-5d95-e211-a939-e4115bead28a"
}
},
}
},
)
assert edit_response.status_code == status.HTTP_200_OK
| 32.926357
| 88
| 0.606357
| 1,052
| 8,495
| 4.559886
| 0.096958
| 0.083385
| 0.022514
| 0.050031
| 0.912237
| 0.894934
| 0.869502
| 0.841359
| 0.841359
| 0.841359
| 0
| 0.022735
| 0.285462
| 8,495
| 257
| 89
| 33.054475
| 0.767545
| 0.033902
| 0
| 0.705882
| 0
| 0
| 0.20488
| 0.092325
| 0
| 0
| 0
| 0
| 0.139037
| 1
| 0.048128
| false
| 0
| 0.026738
| 0
| 0.080214
| 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
|
224dbbe320a658a9bb6cf854393c7e3fa85632ec
| 6,446
|
py
|
Python
|
graphtheory/seriesparallel/spmate.py
|
gitter-badger/graphs-dict
|
2be1a5b140feb050eec799d6cadf6de5eef01745
|
[
"BSD-3-Clause"
] | null | null | null |
graphtheory/seriesparallel/spmate.py
|
gitter-badger/graphs-dict
|
2be1a5b140feb050eec799d6cadf6de5eef01745
|
[
"BSD-3-Clause"
] | 1
|
2020-02-11T13:54:53.000Z
|
2020-02-11T17:08:49.000Z
|
graphtheory/seriesparallel/spmate.py
|
gitter-badger/graphs-dict
|
2be1a5b140feb050eec799d6cadf6de5eef01745
|
[
"BSD-3-Clause"
] | 1
|
2020-02-09T16:51:06.000Z
|
2020-02-09T16:51:06.000Z
|
#!/usr/bin/python
from graphtheory.structures.edges import Edge
from graphtheory.seriesparallel.spnodes import btree_count_iter
class SPGraphMatching:
"""Find a maximum matching for sp-graphs."""
def __init__(self, graph, root):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError("the graph is directed")
self.graph = graph # series-parallel graph
self.root = root # binary sp-tree
self.mate_set = set() # set with mate edges
self.mate = dict((node, None) for node in self.graph.iternodes())
self.cardinality = 0 # size of mate set
import sys
recursionlimit = sys.getrecursionlimit()
sys.setrecursionlimit(max(self.graph.v() * 2, recursionlimit))
def run(self):
"""Executable pseudocode."""
arg2 = self._visit(self.root)
self.mate_set.update(max(arg2, key=len))
self.cardinality = len(self.mate_set)
# Translate mate_set to mate.
for edge in self.mate_set: # O(V) time
self.mate[edge.source] = edge.target
self.mate[edge.target] = edge.source
def _compose_series(self, arg1, arg2):
"""Compose results for series operation."""
r00a, r01a, r10a, r11a = arg1
r00b, r01b, r10b, r11b = arg2
r00 = max(r00a|r00b, r01a|r00b, r00a|r10b, key=len)
r01 = max(r00a|r01b, r01a|r01b, r00a|r11b, key=len)
r10 = max(r10a|r00b, r11a|r00b, r10a|r10b, key=len)
r11 = max(r10a|r01b, r10a|r11b, r11a|r01b, key=len)
return (r00, r01, r10, r11)
def _compose_parallel(self, arg1, arg2):
"""Compose results for parallel operation."""
r00a, r01a, r10a, r11a = arg1
r00b, r01b, r10b, r11b = arg2
r00 = r00a|r00b
r01 = max(r00a|r01b, r01a|r00b, key=len)
r10 = max(r10a|r00b, r00a|r10b, key=len)
r11 = max(r00a|r11b, r01a|r10b, r10a|r01b, r11a|r00b, key=len)
return (r00, r01, r10, r11)
def _compose_jackknife(self, arg1, arg2):
"""Compose results for jackknife operation."""
r00a, r01a, r10a, r11a = arg1
r00b, r01b, r10b, r11b = arg2
r00 = max(r00a|r00b, r00a|r01b, key=len)
r01 = max(r00a|r10b, r00a|r11b, r01a|r00b, r01a|r01b, key=len)
r10 = max(r10a|r00b, r10a|r01b, key=len)
r11 = max(r11a|r00b, r11a|r01b, r10a|r10b, r10a|r11b, key=len)
return (r00, r01, r10, r11)
def _visit(self, node):
"""Traversing postorder."""
if node.type == "edge":
# r01, r10 faktycznie sa niepoprawne (to jest r00),
# ale takie przyjecie upraszcza przetwarzanie..
# Kolejnosc (r00, r01, r10, r11).
if node.source <= node.target:
edge = Edge(node.source, node.target)
else:
edge = Edge(node.target, node.source)
return (set(), set(), set(), set([edge]))
arg1 = self._visit(node.left)
arg2 = self._visit(node.right)
if node.type == "series":
return self._compose_series(arg1, arg2)
elif node.type == "parallel":
return self._compose_parallel(arg1, arg2)
elif node.type == "jackknife":
return self._compose_jackknife(arg1, arg2)
else:
raise ValueError("bad node type")
class SPTreeMatching:
"""Find a maximum matching for sp-trees."""
def __init__(self, root):
"""The algorithm initialization."""
self.root = root # binary sp-tree
self.mate_set = set() # set with mate edges
self.mate = dict()
self.cardinality = 0 # size of mate set
import sys
recursionlimit = sys.getrecursionlimit()
sys.setrecursionlimit(max(btree_count_iter(self.root), recursionlimit))
def run(self):
"""Executable pseudocode."""
arg2 = self._visit(self.root)
self.mate_set.update(max(arg2, key=len))
self.cardinality = len(self.mate_set)
# Translate mate_set to mate.
for edge in self.mate_set: # O(V) time
self.mate[edge.source] = edge.target
self.mate[edge.target] = edge.source
def _compose_series(self, arg1, arg2):
"""Compose results for series operation."""
r00a, r01a, r10a, r11a = arg1
r00b, r01b, r10b, r11b = arg2
r00 = max(r00a|r00b, r01a|r00b, r00a|r10b, key=len)
r01 = max(r00a|r01b, r01a|r01b, r00a|r11b, key=len)
r10 = max(r10a|r00b, r11a|r00b, r10a|r10b, key=len)
r11 = max(r10a|r01b, r10a|r11b, r11a|r01b, key=len)
return (r00, r01, r10, r11)
def _compose_parallel(self, arg1, arg2):
"""Compose results for parallel operation."""
r00a, r01a, r10a, r11a = arg1
r00b, r01b, r10b, r11b = arg2
r00 = r00a|r00b
r01 = max(r00a|r01b, r01a|r00b, key=len)
r10 = max(r10a|r00b, r00a|r10b, key=len)
r11 = max(r00a|r11b, r01a|r10b, r10a|r01b, r11a|r00b, key=len)
return (r00, r01, r10, r11)
def _compose_jackknife(self, arg1, arg2):
"""Compose results for jackknife operation."""
r00a, r01a, r10a, r11a = arg1
r00b, r01b, r10b, r11b = arg2
r00 = max(r00a|r00b, r00a|r01b, key=len)
r01 = max(r00a|r10b, r00a|r11b, r01a|r00b, r01a|r01b, key=len)
r10 = max(r10a|r00b, r10a|r01b, key=len)
r11 = max(r11a|r00b, r11a|r01b, r10a|r10b, r10a|r11b, key=len)
return (r00, r01, r10, r11)
def _visit(self, node):
"""Traversing postorder."""
if node.type == "edge":
# r01, r10 faktycznie sa niepoprawne (to jest r00),
# ale takie przyjecie upraszcza przetwarzanie..
# Kolejnosc (r00, r01, r10, r11).
if node.source <= node.target:
edge = Edge(node.source, node.target)
else:
edge = Edge(node.target, node.source)
return (set(), set(), set(), set([edge]))
arg1 = self._visit(node.left)
arg2 = self._visit(node.right)
if node.type == "series":
return self._compose_series(arg1, arg2)
elif node.type == "parallel":
return self._compose_parallel(arg1, arg2)
elif node.type == "jackknife":
return self._compose_jackknife(arg1, arg2)
else:
raise ValueError("bad node type")
# EOF
| 39.790123
| 79
| 0.584238
| 824
| 6,446
| 4.503641
| 0.135922
| 0.038804
| 0.023713
| 0.025869
| 0.892482
| 0.892482
| 0.879008
| 0.879008
| 0.879008
| 0.879008
| 0
| 0.115939
| 0.289482
| 6,446
| 161
| 80
| 40.037267
| 0.694323
| 0.146292
| 0
| 0.890756
| 0
| 0
| 0.018655
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.10084
| false
| 0
| 0.033613
| 0
| 0.268908
| 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
|
2259ea42d8e7f8922a8acbea561b8a664e97e8c7
| 127
|
py
|
Python
|
myshopify/translate/__init__.py
|
mortendaehli/my-shopify-inventory-utils
|
92f3598efb9c05ed706709f3021f8d12fa93ab50
|
[
"Unlicense"
] | null | null | null |
myshopify/translate/__init__.py
|
mortendaehli/my-shopify-inventory-utils
|
92f3598efb9c05ed706709f3021f8d12fa93ab50
|
[
"Unlicense"
] | 27
|
2022-02-06T17:48:01.000Z
|
2022-02-11T13:57:38.000Z
|
myshopify/translate/__init__.py
|
mortendaehli/my-shopify-inventory-utils
|
92f3598efb9c05ed706709f3021f8d12fa93ab50
|
[
"Unlicense"
] | null | null | null |
from myshopify.translate.deep_learning import DeepTranslator
from myshopify.translate.google_translate import GoogleTranslator
| 42.333333
| 65
| 0.905512
| 14
| 127
| 8.071429
| 0.642857
| 0.230089
| 0.389381
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.062992
| 127
| 2
| 66
| 63.5
| 0.94958
| 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
|
97e8066fb98bb7667f78d80bb99a433777040dbf
| 3,330
|
py
|
Python
|
Lib/test/test_str2unicode.py
|
jimmyyu2004/jython
|
5b4dc2d54d01a6fda8c55d07b2608167e7a40769
|
[
"CNRI-Jython"
] | 332
|
2015-08-22T12:43:56.000Z
|
2022-03-17T01:05:43.000Z
|
Lib/test/test_str2unicode.py
|
Pandinosaurus/jython3
|
def4f8ec47cb7a9c799ea4c745f12badf92c5769
|
[
"CNRI-Jython"
] | 36
|
2015-05-30T08:39:19.000Z
|
2022-03-04T20:42:33.000Z
|
Lib/test/test_str2unicode.py
|
Pandinosaurus/jython3
|
def4f8ec47cb7a9c799ea4c745f12badf92c5769
|
[
"CNRI-Jython"
] | 74
|
2015-05-29T17:18:53.000Z
|
2022-01-15T14:06:44.000Z
|
import unittest
class TestStrReturnsUnicode(unittest.TestCase):
def test_join(self):
self.assertEqual(str, type(''.join(['blah'])))
def test_replace(self):
self.assertEqual(str, type('hello'.replace('o', 'o')))
def test_string_formatting_s(self):
self.assertEqual(str, type('%s' % 'x'))
self.assertEqual(str, type('%s %s' % ('x', 'y')))
self.assertEqual(str, type('%(x)s' % {'x' : 'x'}))
def test_string_formatting_r(self):
self.assertEqual(str, type('%r' % 'x'))
self.assertEqual(str, type('%r %r' % ('x', 'y')))
self.assertEqual(str, type('%(x)r' % {'x' : 'x'}))
def test_string_formatting_c(self):
self.assertEqual(str, type('%c' % 'x'))
self.assertEqual(str, type('%c %c' % ('x', 'y')))
self.assertEqual(str, type('%(x)c' % {'x' : 'x'}))
class TestStrReturnsStr(unittest.TestCase):
def test_join(self):
self.assertEqual(str, type(''.join(['blah'])))
def test_replace(self):
self.assertEqual(str, type('hello'.replace('o', 'oo')))
def test_string_formatting_s(self):
self.assertEqual(str, type('%s' % 'x'))
self.assertEqual(str, type('%s %s' % ('x', 'y')))
self.assertEqual(str, type('%(x)s' % {'x' : 'xxx'}))
def test_string_formatting_r(self):
self.assertEqual(str, type('%r' % 'x'))
self.assertEqual(str, type('%r %r' % ('x', 'y')))
self.assertEqual(str, type('%(x)r' % {'x' : 'x'}))
def test_string_formatting_c(self):
self.assertEqual(str, type('%c' % 'x'))
self.assertEqual(str, type('%c %c' % ('x', 'y')))
self.assertEqual(str, type('%(x)c' % {'x' : 'x'}))
class TestUnicodeReturnsUnicode(unittest.TestCase):
def test_join(self):
self.assertEqual(str, type(''.join(['blah'])))
self.assertEqual(str, type(''.join(['blah'])))
def test_replace(self):
self.assertEqual(str, type('hello'.replace('o', 'o')))
self.assertEqual(str, type('hello'.replace('o', 'o')))
self.assertEqual(str, type('hello'.replace('o', 'o')))
self.assertEqual(str, type('hello'.replace('o', 'o')))
def test_string_formatting_s(self):
self.assertEqual(str, type('%s' % 'x'))
self.assertEqual(str, type('%s' % 'x'))
self.assertEqual(str, type('%s %s' % ('x', 'y')))
self.assertEqual(str, type('%s %s' % ('x', 'y')))
self.assertEqual(str, type('%(x)s' % {'x' : 'x'}))
self.assertEqual(str, type('%(x)s' % {'x' : 'x'}))
def test_string_formatting_r(self):
self.assertEqual(str, type('%r' % 'x'))
self.assertEqual(str, type('%r' % 'x'))
self.assertEqual(str, type('%r %r' % ('x', 'y')))
self.assertEqual(str, type('%r %r' % ('x', 'y')))
self.assertEqual(str, type('%(x)r' % {'x' : 'x'}))
self.assertEqual(str, type('%(x)r' % {'x' : 'x'}))
def test_string_formatting_c(self):
self.assertEqual(str, type('%c' % 'x'))
self.assertEqual(str, type('%c' % 'x'))
self.assertEqual(str, type('%c %c' % ('x', 'y')))
self.assertEqual(str, type('%c %c' % ('x', 'y')))
self.assertEqual(str, type('%(x)c' % {'x' : 'x'}))
self.assertEqual(str, type('%(x)c' % {'x' : 'x'}))
if __name__ == '__main__':
unittest.main()
| 36.593407
| 63
| 0.542042
| 433
| 3,330
| 4.073903
| 0.069284
| 0.391156
| 0.469388
| 0.573696
| 0.938209
| 0.938209
| 0.938209
| 0.938209
| 0.923469
| 0.923469
| 0
| 0
| 0.215015
| 3,330
| 90
| 64
| 37
| 0.674828
| 0
| 0
| 0.880597
| 0
| 0
| 0.081982
| 0
| 0
| 0
| 0
| 0
| 0.686567
| 1
| 0.223881
| false
| 0
| 0.014925
| 0
| 0.283582
| 0
| 0
| 0
| 0
| null | 1
| 1
| 1
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 12
|
3f0a81ab208ad27fae853d8e465fdebf8542d1c8
| 29,001
|
py
|
Python
|
inception_score.py
|
tasbolat1/DGflow
|
6ce22095a0d33f4da3c15f093aa365ba6cabbac9
|
[
"MIT"
] | 15
|
2021-02-03T13:34:03.000Z
|
2022-02-16T03:33:23.000Z
|
inception_score.py
|
tasbolat1/DGflow
|
6ce22095a0d33f4da3c15f093aa365ba6cabbac9
|
[
"MIT"
] | null | null | null |
inception_score.py
|
tasbolat1/DGflow
|
6ce22095a0d33f4da3c15f093aa365ba6cabbac9
|
[
"MIT"
] | 4
|
2021-05-13T05:31:19.000Z
|
2022-02-16T06:57:16.000Z
|
"""This file is a modification of inception_score.py in
https://github.com/mattya/chainer-inception-score
"""
import math
import chainer
from chainer import Chain
from chainer import functions as F
from chainer import links as L
from chainer import Variable
from tqdm.auto import tqdm
def inception_score(model, ims, batch_size=100, splits=10, verbose=False):
"""Compute the inception score for given images.
Default batch_size is 100 and split size is 10. Please refer to the
official implementation. It is recommended to to use at least 50000
images to obtain a reliable score.
Reference:
https://github.com/openai/improved-gan/blob/master/inception_score/model.py
"""
n, c, w, h = ims.shape
n_batches = int(math.ceil(float(n) / float(batch_size)))
xp = model.xp
if verbose:
print('Batch size:', batch_size)
print('Total number of images:', n)
print('Total number of batches:', n_batches)
# Compute the softmax predicitions for for all images, split into batches
# in order to fit in memory
ys = xp.empty((n, 1008), dtype=xp.float32) # Softmax container
for i in tqdm(range(n_batches)):
# print('Running batch', i+1, '/', n_batches, '...')
batch_start = (i * batch_size)
batch_end = min((i + 1) * batch_size, n)
ims_batch = ims[batch_start:batch_end]
ims_batch = xp.asarray(ims_batch) # To GPU if using CuPy
ims_batch = Variable(ims_batch)
# Resize image to the shape expected by the inception module
if (w, h) != (299, 299):
ims_batch = F.resize_images(ims_batch, (299, 299)) # bilinear
# Feed images to the inception module to get the softmax predictions
with chainer.using_config('train', False), \
chainer.using_config('enable_backprop', False):
y = model(ims_batch)
ys[batch_start:batch_end] = y.data
# Compute the inception score based on the softmax predictions of the
# inception module.
scores = xp.empty((splits), dtype=xp.float32) # Split inception scores
for i in range(splits):
part = ys[(i * n // splits):((i + 1) * n // splits), :]
kl = part * (xp.log(part) -
xp.log(xp.expand_dims(xp.mean(part, 0), 0)))
kl = xp.mean(xp.sum(kl, 1))
scores[i] = xp.exp(kl)
return xp.mean(scores), xp.std(scores)
class Mixed(Chain):
def __init__(self, trunk):
super().__init__()
for name, link in trunk:
self.add_link(name, link)
self.trunk = trunk
def __call__(self, x):
hs = []
for name, _ in self.trunk:
h = getattr(self, name)(x)
hs.append(h)
return F.concat(hs)
class AveragePooling2D(chainer.Link):
def __init__(self, ksize, stride=None, pad=0):
super().__init__()
self.ksize = ksize
self.stride = stride
self.pad = pad
def forward(self, x):
return F.average_pooling_2d(x, self.ksize, self.stride, self.pad)
class MaxPooling2D(chainer.Link):
def __init__(self, ksize, stride=None, pad=0):
super().__init__()
self.ksize = ksize
self.stride = stride
self.pad = pad
def forward(self, x):
return F.max_pooling_2d(x, self.ksize, self.stride, self.pad)
class Tower(Chain):
def __init__(self, trunk):
super().__init__()
for name, link in trunk:
if not name.startswith('_'):
self.add_link(name, link)
self.trunk = trunk
def __call__(self, x):
h = x
for name, f in self.trunk:
if not name.startswith('_'): # Link
if 'bn' in name:
h = getattr(self, name)(h)
else:
h = getattr(self, name)(h)
else: # AveragePooling2D, MaxPooling2D or relu
h = f(h)
return h
class Inception(Chain):
def __init__(self):
super().__init__(
conv=L.Convolution2D(3, 32, 3, stride=2, pad=0),
conv_1=L.Convolution2D(32, 32, 3, stride=1, pad=0),
conv_2=L.Convolution2D(32, 64, 3, stride=1, pad=1),
conv_3=L.Convolution2D(64, 80, 1, stride=1, pad=0),
conv_4=L.Convolution2D(80, 192, 3, stride=1, pad=0),
bn_conv=L.BatchNormalization(32),
bn_conv_1=L.BatchNormalization(32),
bn_conv_2=L.BatchNormalization(64),
bn_conv_3=L.BatchNormalization(80),
bn_conv_4=L.BatchNormalization(192),
mixed=Mixed([
('conv', Tower([
('conv', L.Convolution2D(192, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(192, 48, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(48)),
('_relu', F.relu),
('conv_1', L.Convolution2D(48, 64, 5, stride=1, pad=2)),
('bn_conv_1', L.BatchNormalization(64)),
('_relu_1', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(192, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu),
('conv_1', L.Convolution2D(64, 96, 3, stride=1, pad=1)),
('bn_conv_1', L.BatchNormalization(96)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(96, 96, 3, stride=1, pad=1)),
('bn_conv_2', L.BatchNormalization(96)),
('_relu_2', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(192, 32, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(32)),
('_relu', F.relu)
]))
]),
mixed_1=Mixed([
('conv', Tower([
('conv', L.Convolution2D(256, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(256, 48, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(48)),
('_relu', F.relu),
('conv_1', L.Convolution2D(48, 64, 5, stride=1, pad=2)),
('bn_conv_1', L.BatchNormalization(64)),
('_relu_1', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(256, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu),
('conv_1', L.Convolution2D(64, 96, 3, stride=1, pad=1)),
('bn_conv_1', L.BatchNormalization(96)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(96, 96, 3, stride=1, pad=1)),
('bn_conv_2', L.BatchNormalization(96)),
('_relu_2', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(256, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu)
]))
]),
mixed_2=Mixed([
('conv', Tower([
('conv', L.Convolution2D(288, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(288, 48, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(48)),
('_relu', F.relu),
('conv_1', L.Convolution2D(48, 64, 5, stride=1, pad=2)),
('bn_conv_1', L.BatchNormalization(64)),
('_relu_1', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(288, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu),
('conv_1', L.Convolution2D(64, 96, 3, stride=1, pad=1)),
('bn_conv_1', L.BatchNormalization(96)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(96, 96, 3, stride=1, pad=1)),
('bn_conv_2', L.BatchNormalization(96)),
('_relu_2', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(288, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu)
]))
]),
mixed_3=Mixed([
('conv', Tower([
('conv', L.Convolution2D(288, 384, 3, stride=2, pad=0)),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(288, 64, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(64)),
('_relu', F.relu),
('conv_1', L.Convolution2D(64, 96, 3, stride=1, pad=1)),
('bn_conv_1', L.BatchNormalization(96)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(96, 96, 3, stride=2, pad=0)),
('bn_conv_2', L.BatchNormalization(96)),
('_relu_2', F.relu)
])),
('pool', Tower([
('_pooling', MaxPooling2D(3, 2, pad=0))
]))
]),
mixed_4=Mixed([
('conv', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(768, 128, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(128)),
('_relu', F.relu),
('conv_1', L.Convolution2D(128, 128, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_1', L.BatchNormalization(128)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(128, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_2', L.BatchNormalization(192)),
('_relu_2', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(768, 128, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(128)),
('_relu', F.relu),
('conv_1', L.Convolution2D(128, 128, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_1', L.BatchNormalization(128)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(128, 128, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_2', L.BatchNormalization(128)),
('_relu_2', F.relu),
('conv_3', L.Convolution2D(128, 128, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_3', L.BatchNormalization(128)),
('_relu_3', F.relu),
('conv_4', L.Convolution2D(128, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_4', L.BatchNormalization(192)),
('_relu_4', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
]))
]),
mixed_5=Mixed([
('conv', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(768, 160, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(160)),
('_relu', F.relu),
('conv_1', L.Convolution2D(160, 160, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_1', L.BatchNormalization(160)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(160, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_2', L.BatchNormalization(192)),
('_relu_2', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(768, 160, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(160)),
('_relu', F.relu),
('conv_1', L.Convolution2D(160, 160, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_1', L.BatchNormalization(160)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(160, 160, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_2', L.BatchNormalization(160)),
('_relu_2', F.relu),
('conv_3', L.Convolution2D(160, 160, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_3', L.BatchNormalization(160)),
('_relu_3', F.relu),
('conv_4', L.Convolution2D(160, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_4', L.BatchNormalization(192)),
('_relu_4', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
]))
]),
mixed_6=Mixed([
('conv', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(768, 160, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(160)),
('_relu', F.relu),
('conv_1', L.Convolution2D(160, 160, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_1', L.BatchNormalization(160)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(160, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_2', L.BatchNormalization(192)),
('_relu_2', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(768, 160, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(160)),
('_relu', F.relu),
('conv_1', L.Convolution2D(160, 160, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_1', L.BatchNormalization(160)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(160, 160, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_2', L.BatchNormalization(160)),
('_relu_2', F.relu),
('conv_3', L.Convolution2D(160, 160, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_3', L.BatchNormalization(160)),
('_relu_3', F.relu),
('conv_4', L.Convolution2D(160, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_4', L.BatchNormalization(192)),
('_relu_4', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
]))
]),
mixed_7=Mixed([
('conv', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
])),
('tower', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu),
('conv_1', L.Convolution2D(192, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_1', L.BatchNormalization(192)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(192, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_2', L.BatchNormalization(192)),
('_relu_2', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu),
('conv_1', L.Convolution2D(192, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_1', L.BatchNormalization(192)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(192, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_2', L.BatchNormalization(192)),
('_relu_2', F.relu),
('conv_3', L.Convolution2D(192, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_3', L.BatchNormalization(192)),
('_relu_3', F.relu),
('conv_4', L.Convolution2D(192, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_4', L.BatchNormalization(192)),
('_relu_4', F.relu)
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
]))
]),
mixed_8=Mixed([
('tower', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu),
('conv_1', L.Convolution2D(192, 320, 3, stride=2, pad=0)),
('bn_conv_1', L.BatchNormalization(320)),
('_relu_1', F.relu)
])),
('tower_1', Tower([
('conv', L.Convolution2D(768, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu),
('conv_1', L.Convolution2D(192, 192, (1, 7), stride=1,
pad=(0, 3))),
('bn_conv_1', L.BatchNormalization(192)),
('_relu_1', F.relu),
('conv_2', L.Convolution2D(192, 192, (7, 1), stride=1,
pad=(3, 0))),
('bn_conv_2', L.BatchNormalization(192)),
('_relu_2', F.relu),
('conv_3', L.Convolution2D(192, 192, 3, stride=2, pad=0)),
('bn_conv_3', L.BatchNormalization(192)),
('_relu_3', F.relu)
])),
('pool', Tower([
('_pooling', MaxPooling2D(3, 2, pad=0))
]))
]),
mixed_9=Mixed([
('conv', Tower([
('conv', L.Convolution2D(1280, 320, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(320)),
('_relu', F.relu),
])),
('tower', Tower([
('conv', L.Convolution2D(1280, 384, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu),
('mixed', Mixed([
('conv', Tower([
('conv', L.Convolution2D(384, 384, (1, 3),
stride=1, pad=(0, 1))),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu),
])),
('conv_1', Tower([
('conv_1', L.Convolution2D(384, 384, (3, 1),
stride=1, pad=(1, 0))),
('bn_conv_1', L.BatchNormalization(384)),
('_relu_1', F.relu),
]))
]))
])),
('tower_1', Tower([
('conv', L.Convolution2D(1280, 448, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(448)),
('_relu', F.relu),
('conv_1', L.Convolution2D(448, 384, 3, stride=1, pad=1)),
('bn_conv_1', L.BatchNormalization(384)),
('_relu_1', F.relu),
('mixed', Mixed([
('conv', Tower([
('conv', L.Convolution2D(384, 384, (1, 3),
stride=1, pad=(0, 1))),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu),
])),
('conv_1', Tower([
('conv_1', L.Convolution2D(384, 384, (3, 1),
stride=1, pad=(1, 0))),
('bn_conv_1', L.BatchNormalization(384)),
('_relu_1', F.relu),
]))
]))
])),
('tower_2', Tower([
('_pooling', AveragePooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(1280, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
]))
]),
mixed_10=Mixed([
('conv', Tower([
('conv', L.Convolution2D(2048, 320, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(320)),
('_relu', F.relu),
])),
('tower', Tower([
('conv', L.Convolution2D(2048, 384, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu),
('mixed', Mixed([
('conv', Tower([
('conv', L.Convolution2D(384, 384, (1, 3),
stride=1, pad=(0, 1))),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu),
])),
('conv_1', Tower([
('conv_1', L.Convolution2D(384, 384, (3, 1),
stride=1, pad=(1, 0))),
('bn_conv_1', L.BatchNormalization(384)),
('_relu_1', F.relu),
]))
]))
])),
('tower_1', Tower([
('conv', L.Convolution2D(2048, 448, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(448)),
('_relu', F.relu),
('conv_1', L.Convolution2D(448, 384, 3, stride=1, pad=1)),
('bn_conv_1', L.BatchNormalization(384)),
('_relu_1', F.relu),
('mixed', Mixed([
('conv', Tower([
('conv', L.Convolution2D(384, 384, (1, 3),
stride=1, pad=(0, 1))),
('bn_conv', L.BatchNormalization(384)),
('_relu', F.relu)
])),
('conv_1', Tower([
('conv_1', L.Convolution2D(384, 384, (3, 1),
stride=1, pad=(1, 0))),
('bn_conv_1', L.BatchNormalization(384)),
('_relu_1', F.relu)
]))
]))
])),
('tower_2', Tower([
('_pooling', MaxPooling2D(3, 1, pad=1)),
('conv', L.Convolution2D(2048, 192, 1, stride=1, pad=0)),
('bn_conv', L.BatchNormalization(192)),
('_relu', F.relu)
]))
]),
logit=L.Linear(2048, 1008)
)
def __call__(self, x, get_feature=False):
"""Input dims are (batch_size, 3, 299, 299)."""
# assert x.shape[1:] == (3, 299, 299)
x -= 128.0
x *= 0.0078125
h = F.relu(self.bn_conv(self.conv(x)))
# assert h.shape[1:] == (32, 149, 149)
h = F.relu(self.bn_conv_1(self.conv_1(h)))
# assert h.shape[1:] == (32, 147, 147)
h = F.relu(self.bn_conv_2(self.conv_2(h)))
# assert h.shape[1:] == (64, 147, 147)
h = F.max_pooling_2d(h, 3, stride=2, pad=0)
# assert h.shape[1:] == (64, 73, 73)
h = F.relu(self.bn_conv_3(self.conv_3(h)))
# assert h.shape[1:] == (80, 73, 73)
h = F.relu(self.bn_conv_4(self.conv_4(h)))
# assert h.shape[1:] == (192, 71, 71)
h = F.max_pooling_2d(h, 3, stride=2, pad=0)
# assert h.shape[1:] == (192, 35, 35)
h = self.mixed(h)
# assert h.shape[1:] == (256, 35, 35)
h = self.mixed_1(h)
# assert h.shape[1:] == (288, 35, 35)
h = self.mixed_2(h)
# assert h.shape[1:] == (288, 35, 35)
h = self.mixed_3(h)
# assert h.shape[1:] == (768, 17, 17)
h = self.mixed_4(h)
# assert h.shape[1:] == (768, 17, 17)
h = self.mixed_5(h)
# assert h.shape[1:] == (768, 17, 17)
h = self.mixed_6(h)
# assert h.shape[1:] == (768, 17, 17)
h = self.mixed_7(h)
# assert h.shape[1:] == (768, 17, 17)
h = self.mixed_8(h)
# assert h.shape[1:] == (1280, 8, 8)
h = self.mixed_9(h)
# assert h.shape[1:] == (2048, 8, 8)
h = self.mixed_10(h)
# assert h.shape[1:] == (2048, 8, 8)
h = F.average_pooling_2d(h, 8, 1)
# assert h.shape[1:] == (2048, 1, 1)
h = F.reshape(h, (-1, 2048))
if get_feature:
return h
else:
h = self.logit(h)
h = F.softmax(h)
# assert h.shape[1:] == (1008,)
return h
| 43.676205
| 79
| 0.402572
| 3,000
| 29,001
| 3.726667
| 0.069333
| 0.053131
| 0.079606
| 0.05805
| 0.800894
| 0.770036
| 0.745349
| 0.734258
| 0.726297
| 0.714937
| 0
| 0.105869
| 0.440123
| 29,001
| 663
| 80
| 43.742081
| 0.582682
| 0.057722
| 0
| 0.765845
| 0
| 0
| 0.079263
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.019366
| false
| 0
| 0.012324
| 0.003521
| 0.052817
| 0.005282
| 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
|
3f6da26171db265b4e539018ef8f222e64d6e05c
| 15,384
|
py
|
Python
|
test/color/test_hls.py
|
pmeier/kornia
|
57f5aeb605d0c69de88a0a1aa1563cee52d4bfaf
|
[
"ECL-2.0",
"Apache-2.0"
] | 5
|
2021-04-15T01:20:01.000Z
|
2022-01-12T14:12:54.000Z
|
test/color/test_hls.py
|
pmeier/kornia
|
57f5aeb605d0c69de88a0a1aa1563cee52d4bfaf
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
test/color/test_hls.py
|
pmeier/kornia
|
57f5aeb605d0c69de88a0a1aa1563cee52d4bfaf
|
[
"ECL-2.0",
"Apache-2.0"
] | 1
|
2022-01-26T13:39:34.000Z
|
2022-01-26T13:39:34.000Z
|
import pytest
import kornia
import kornia.testing as utils # test utils
from kornia.constants import pi
import math
import torch
from torch.autograd import gradcheck
from torch.testing import assert_allclose
class TestRgbToHls:
def test_rgb_to_hls(self, device):
data = torch.tensor([[[0.4237059, 0.1935902, 0.8585021, 0.3790484, 0.1389151],
[0.5933651, 0.0474544, 0.2801555, 0.1691061, 0.9221829],
[0.2351739, 0.5852075, 0.5789326, 0.8411915, 0.5960411],
[0.0290176, 0.6459382, 0.8581501, 0.4755400, 0.7735767],
[0.9497226, 0.0919441, 0.5462211, 0.7836787, 0.6403612]],
[[0.2280025, 0.1352853, 0.7999730, 0.6658246, 0.4910861],
[0.3499791, 0.1250734, 0.6315800, 0.4785843, 0.8477826],
[0.3646359, 0.2415122, 0.5301932, 0.0782518, 0.8710389],
[0.6957581, 0.6162295, 0.6259052, 0.1753750, 0.6737530],
[0.7678874, 0.9825978, 0.0234877, 0.2485284, 0.8159551]],
[[0.7330830, 0.9015747, 0.0229067, 0.4280063, 0.5400181],
[0.0037299, 0.3259412, 0.3467951, 0.9575506, 0.1525899],
[0.9660432, 0.5287710, 0.6654660, 0.3797526, 0.4981400],
[0.7422802, 0.9926301, 0.5334370, 0.7852844, 0.4397180],
[0.2281681, 0.2560037, 0.5134379, 0.5800887, 0.8685090]]])
data = data.to(device)
# OpenCV
h_expected = torch.tensor([[4.5945477, 4.268469, 0.9738468, 2.2731707, 3.269344],
[0.6149417, 3.8969188, 2.292972, 3.7777472, 0.9459598],
[4.003296, 5.4079432, 4.566101, 5.869351, 1.8194631],
[3.2098956, 4.271444, 0.29820946, 4.7041655, 0.7340856],
[0.78329855, 2.2872903, 5.3016634, 5.634379, 3.382815]])
h_expected = h_expected.to(device)
l_expected = torch.tensor([[0.48054275, 0.51843, 0.44070444, 0.5224365, 0.33946657],
[0.2985475, 0.18669781, 0.45586777, 0.5633283, 0.5373864],
[0.6006086, 0.41335985, 0.5978296, 0.45972168, 0.6845894],
[0.38564888, 0.80442977, 0.6957935, 0.48032972, 0.6066474],
[0.5889454, 0.53727096, 0.2848544, 0.5161035, 0.7544351]])
l_expected = l_expected.to(device)
s_expected = torch.tensor([[0.5255313, 0.79561585, 0.9480225, 0.30024928, 0.59078425],
[0.98750657, 0.7458223, 0.3854456, 0.90278864, 0.8317882],
[0.9149786, 0.4157338, 0.16817844, 0.82978433, 0.5911325],
[0.9247565, 0.9623155, 0.53370523, 0.63488615, 0.4243758],
[0.8776869, 0.96239233, 0.91754496, 0.55295944, 0.46453667]])
s_expected = s_expected.to(device)
f = kornia.color.RgbToHls()
result = f(data)
h = result[0, :, :]
l = result[1, :, :]
s = result[2, :, :]
assert_allclose(h, h_expected)
assert_allclose(l, l_expected)
assert_allclose(s, s_expected)
def test_batch_rgb_to_hls(self, device):
data = torch.tensor([[[0.4237059, 0.1935902, 0.8585021, 0.3790484, 0.1389151],
[0.5933651, 0.0474544, 0.2801555, 0.1691061, 0.9221829],
[0.2351739, 0.5852075, 0.5789326, 0.8411915, 0.5960411],
[0.0290176, 0.6459382, 0.8581501, 0.4755400, 0.7735767],
[0.9497226, 0.0919441, 0.5462211, 0.7836787, 0.6403612]],
[[0.2280025, 0.1352853, 0.7999730, 0.6658246, 0.4910861],
[0.3499791, 0.1250734, 0.6315800, 0.4785843, 0.8477826],
[0.3646359, 0.2415122, 0.5301932, 0.0782518, 0.8710389],
[0.6957581, 0.6162295, 0.6259052, 0.1753750, 0.6737530],
[0.7678874, 0.9825978, 0.0234877, 0.2485284, 0.8159551]],
[[0.7330830, 0.9015747, 0.0229067, 0.4280063, 0.5400181],
[0.0037299, 0.3259412, 0.3467951, 0.9575506, 0.1525899],
[0.9660432, 0.5287710, 0.6654660, 0.3797526, 0.4981400],
[0.7422802, 0.9926301, 0.5334370, 0.7852844, 0.4397180],
[0.2281681, 0.2560037, 0.5134379, 0.5800887, 0.8685090]]])
data = data.to(device)
# OpenCV
expected = torch.tensor([[[4.5945477, 4.268469, 0.9738468, 2.2731707, 3.269344],
[0.6149417, 3.8969188, 2.292972, 3.7777472, 0.9459598],
[4.003296, 5.4079432, 4.566101, 5.869351, 1.8194631],
[3.2098956, 4.271444, 0.29820946, 4.7041655, 0.7340856],
[0.78329855, 2.2872903, 5.3016634, 5.634379, 3.382815]],
[[0.48054275, 0.51843, 0.44070444, 0.5224365, 0.33946657],
[0.2985475, 0.18669781, 0.45586777, 0.5633283, 0.5373864],
[0.6006086, 0.41335985, 0.5978296, 0.45972168, 0.6845894],
[0.38564888, 0.80442977, 0.6957935, 0.48032972, 0.6066474],
[0.5889454, 0.53727096, 0.2848544, 0.5161035, 0.7544351]],
[[0.5255313, 0.79561585, 0.9480225, 0.30024928, 0.59078425],
[0.98750657, 0.7458223, 0.3854456, 0.90278864, 0.8317882],
[0.9149786, 0.4157338, 0.16817844, 0.82978433, 0.5911325],
[0.9247565, 0.9623155, 0.53370523, 0.63488615, 0.4243758],
[0.8776869, 0.96239233, 0.91754496, 0.55295944, 0.46453667]]])
expected = expected.to(device)
# Kornia
f = kornia.color.RgbToHls()
data = data.repeat(2, 1, 1, 1) # 2x3x5x5
expected = expected.repeat(2, 1, 1, 1) # 2x3x5x5
assert_allclose(f(data), expected)
def test_nan_rgb_to_hls(self, device):
data = torch.ones(1, 5, 5).to(device) # 3x5x5
data = data.repeat(2, 3, 1, 1) # 2x3x5x5
# OpenCV
expected = torch.cat([torch.zeros(1, 5, 5), torch.ones(1, 5, 5), torch.zeros(1, 5, 5)], dim=0).to(device)
expected = expected.repeat(2, 1, 1, 1) # 2x3x5x5
# Kornia
f = kornia.color.RgbToHls()
assert_allclose(f(data), expected)
def test_gradcheck(self, device):
data = torch.rand(3, 5, 5).to(device) # 3x5x5
data = utils.tensor_to_gradcheck_var(data) # to var
assert gradcheck(kornia.color.RgbToHls(), (data,),
raise_exception=True)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
@torch.jit.script
def op_script(data: torch.Tensor) -> torch.Tensor:
return kornia.rgb_to_hls(data)
data = torch.tensor([[[[21., 22.],
[22., 22.]],
[[13., 14.],
[14., 14.]],
[[8., 8.],
[8., 8.]]]]) # 3x2x2
data = data.to(device)
actual = op_script(data)
expected = kornia.rgb_to_hls(data)
assert_allclose(actual, expected)
class TestHlsToRgb:
def test_hls_to_rgb(self, device):
data = torch.tensor([[[0.5513626, 0.8487718, 0.1822479, 0.2851745, 0.2669488],
[0.7596772, 0.4565057, 0.6181599, 0.3852497, 0.7746902],
[0.5742747, 0.1957062, 0.7530835, 0.2104362, 0.9449323],
[0.9918052, 0.2437515, 0.4718738, 0.8502576, 0.1675640],
[0.9210159, 0.0538564, 0.5801026, 0.6110542, 0.3768399]],
[[0.4111853, 0.0183454, 0.7832276, 0.2975794, 0.1139528],
[0.6207729, 0.1073406, 0.8335325, 0.5700451, 0.2594557],
[0.7520493, 0.5097187, 0.4719872, 0.9477938, 0.1640292],
[0.8973427, 0.6455371, 0.7567374, 0.3159562, 0.8135307],
[0.0855004, 0.6645504, 0.9923756, 0.6209313, 0.2356791]],
[[0.4734681, 0.0422099, 0.7405791, 0.9671807, 0.1793800],
[0.8221875, 0.7219887, 0.3627397, 0.4403201, 0.0024084],
[0.0803350, 0.9432759, 0.0241543, 0.8292291, 0.7745832],
[0.3707901, 0.0851424, 0.5805428, 0.1098685, 0.4238486],
[0.1058410, 0.0816052, 0.5792874, 0.9578886, 0.6281684]]]) # 3x5x5
data = data.to(device)
# OpenCV
r_expected = torch.tensor([[0.21650219, 0.01911971, 0.91374826, 0.1760952, 0.10979544],
[0.6569808, 0.02984191, 0.77314806, 0.3807273, 0.25964087],
[0.7321301, 0.8110298, 0.4724091, 0.96834683, 0.2910835],
[0.935407, 0.6478001, 0.615513, 0.3506698, 0.89171433],
[0.0945498, 0.6919248, 0.98795897, 0.25782573, 0.08763295]])
r_expected = r_expected.to(device)
g_expected = torch.tensor([[0.48587522, 0.017571, 0.9437648, 0.5853925, 0.13439366],
[0.30897713, 0.18483935, 0.8082967, 0.75936294, 0.25883088],
[0.7542145, 0.97218925, 0.46058673, 0.9910847, 0.03697497],
[0.8592784, 0.675717, 0.8979618, 0.28124255, 0.8925654],
[0.07645091, 0.6548674, 0.99254686, 0.500144, 0.38372523]])
g_expected = g_expected.to(device)
b_expected = torch.tensor([[0.60586834, 0.01897625, 0.62269044, 0.00976634, 0.09351197],
[0.93256867, 0.14439031, 0.89391685, 0.49867177, 0.2600806],
[0.7719684, 0.04724807, 0.48338777, 0.904503, 0.12093388],
[0.8630215, 0.6153573, 0.85029656, 0.34361976, 0.73449594],
[0.08502806, 0.6371759, 0.99679226, 0.9840369, 0.16492467]])
b_expected = b_expected.to(device)
# Kornia
f = kornia.color.HlsToRgb()
data[0] = 2 * pi * data[0]
result = f(data)
r = result[0, :, :]
g = result[1, :, :]
b = result[2, :, :]
assert_allclose(r, r_expected)
assert_allclose(g, g_expected)
assert_allclose(b, b_expected)
def test_batch_hls_to_rgb(self, device):
data = torch.tensor([[[0.5513626, 0.8487718, 0.1822479, 0.2851745, 0.2669488],
[0.7596772, 0.4565057, 0.6181599, 0.3852497, 0.7746902],
[0.5742747, 0.1957062, 0.7530835, 0.2104362, 0.9449323],
[0.9918052, 0.2437515, 0.4718738, 0.8502576, 0.1675640],
[0.9210159, 0.0538564, 0.5801026, 0.6110542, 0.3768399]],
[[0.4111853, 0.0183454, 0.7832276, 0.2975794, 0.1139528],
[0.6207729, 0.1073406, 0.8335325, 0.5700451, 0.2594557],
[0.7520493, 0.5097187, 0.4719872, 0.9477938, 0.1640292],
[0.8973427, 0.6455371, 0.7567374, 0.3159562, 0.8135307],
[0.0855004, 0.6645504, 0.9923756, 0.6209313, 0.2356791]],
[[0.4734681, 0.0422099, 0.7405791, 0.9671807, 0.1793800],
[0.8221875, 0.7219887, 0.3627397, 0.4403201, 0.0024084],
[0.0803350, 0.9432759, 0.0241543, 0.8292291, 0.7745832],
[0.3707901, 0.0851424, 0.5805428, 0.1098685, 0.4238486],
[0.1058410, 0.0816052, 0.5792874, 0.9578886, 0.6281684]]]) # 3x5x5
data = data.to(device)
data[0] = 2 * pi * data[0]
data = data.repeat(2, 1, 1, 1) # 2x3x5x5
# OpenCV
expected = torch.tensor([[[0.21650219, 0.01911971, 0.91374826, 0.1760952, 0.10979544],
[0.6569808, 0.02984191, 0.77314806, 0.3807273, 0.25964087],
[0.7321301, 0.8110298, 0.4724091, 0.96834683, 0.2910835],
[0.935407, 0.6478001, 0.615513, 0.3506698, 0.89171433],
[0.0945498, 0.6919248, 0.98795897, 0.25782573, 0.08763295]],
[[0.48587522, 0.017571, 0.9437648, 0.5853925, 0.13439366],
[0.30897713, 0.18483935, 0.8082967, 0.75936294, 0.25883088],
[0.7542145, 0.97218925, 0.46058673, 0.9910847, 0.03697497],
[0.8592784, 0.675717, 0.8979618, 0.28124255, 0.8925654],
[0.07645091, 0.6548674, 0.99254686, 0.500144, 0.38372523]],
[[0.60586834, 0.01897625, 0.62269044, 0.00976634, 0.09351197],
[0.93256867, 0.14439031, 0.89391685, 0.49867177, 0.2600806],
[0.7719684, 0.04724807, 0.48338777, 0.904503, 0.12093388],
[0.8630215, 0.6153573, 0.85029656, 0.34361976, 0.73449594],
[0.08502806, 0.6371759, 0.99679226, 0.9840369, 0.16492467]]])
expected = expected.to(device)
expected = expected.repeat(2, 1, 1, 1) # 2x3x2x2
# Kornia
f = kornia.color.HlsToRgb()
assert_allclose(f(data), expected)
data[:, 0] += 2 * pi
assert_allclose(f(data), expected)
data[:, 0] -= 4 * pi
assert_allclose(f(data), expected)
def test_gradcheck(self, device):
data = torch.rand(3, 5, 5).to(device) # 3x5x5
data[0] = 2 * pi * data[0]
data = utils.tensor_to_gradcheck_var(data) # to var
assert gradcheck(kornia.color.HlsToRgb(), (data,),
raise_exception=True)
@pytest.mark.skip(reason="turn off all jit for a while")
def test_jit(self, device):
@torch.jit.script
def op_script(data: torch.tensor) -> torch.Tensor:
return kornia.hls_to_rgb(data)
data = torch.tensor([[[[21., 22.],
[22., 22.]],
[[13., 14.],
[14., 14.]],
[[8., 8.],
[8., 8.]]]]) # 3x2x2
data = data.to(device)
actual = op_script(data)
expected = kornia.hls_to_rgb(data)
assert_allclose(actual, expected)
| 50.605263
| 113
| 0.486349
| 1,788
| 15,384
| 4.139821
| 0.213087
| 0.02675
| 0.016212
| 0.017968
| 0.895434
| 0.866658
| 0.857201
| 0.828155
| 0.815996
| 0.806809
| 0
| 0.527079
| 0.37708
| 15,384
| 303
| 114
| 50.772277
| 0.24533
| 0.011505
| 0
| 0.6875
| 0
| 0
| 0.003689
| 0
| 0
| 0
| 0
| 0
| 0.071429
| 1
| 0.049107
| false
| 0
| 0.035714
| 0
| 0.102679
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 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
| 8
|
58faf930ac72397c7256d4fae0c25c38d243b03e
| 192
|
py
|
Python
|
src/fastapi_aad_auth/mixins/__init__.py
|
Alex-Chekh/fastapi_aad_auth
|
4ad21fa76e7422da5d0799695bb547cd3e6224e0
|
[
"MIT"
] | 29
|
2020-09-04T08:39:42.000Z
|
2022-01-21T08:43:48.000Z
|
src/fastapi_aad_auth/mixins/__init__.py
|
Alex-Chekh/fastapi_aad_auth
|
4ad21fa76e7422da5d0799695bb547cd3e6224e0
|
[
"MIT"
] | 86
|
2020-07-30T20:51:19.000Z
|
2022-03-30T16:55:24.000Z
|
src/fastapi_aad_auth/mixins/__init__.py
|
Alex-Chekh/fastapi_aad_auth
|
4ad21fa76e7422da5d0799695bb547cd3e6224e0
|
[
"MIT"
] | 11
|
2020-10-16T07:17:16.000Z
|
2022-02-09T17:13:55.000Z
|
"""Mixins for use in objects."""
from fastapi_aad_auth.mixins.logging import LoggingMixin # noqa F401
from fastapi_aad_auth.mixins.not_authenticated import NotAuthenticatedMixin # noqa F401
| 48
| 88
| 0.822917
| 26
| 192
| 5.884615
| 0.653846
| 0.143791
| 0.183007
| 0.235294
| 0.313725
| 0
| 0
| 0
| 0
| 0
| 0
| 0.035088
| 0.109375
| 192
| 3
| 89
| 64
| 0.859649
| 0.244792
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 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
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 7
|
18a40fabc45b5365a0c2ac1da7d6247b6a205620
| 4,445
|
py
|
Python
|
test/unit/test_tincoind_data_shims.py
|
paulus99/sentinel
|
e2729d9563009c6901ae0807ddb2888b93542281
|
[
"MIT"
] | 1
|
2019-04-08T01:45:23.000Z
|
2019-04-08T01:45:23.000Z
|
test/unit/test_tincoind_data_shims.py
|
paulus99/sentinel
|
e2729d9563009c6901ae0807ddb2888b93542281
|
[
"MIT"
] | null | null | null |
test/unit/test_tincoind_data_shims.py
|
paulus99/sentinel
|
e2729d9563009c6901ae0807ddb2888b93542281
|
[
"MIT"
] | 1
|
2019-04-15T03:48:50.000Z
|
2019-04-15T03:48:50.000Z
|
import pytest
import sys
import os
os.environ['SENTINEL_CONFIG'] = os.path.normpath(os.path.join(os.path.dirname(__file__), '../test_sentinel.conf'))
sys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '../../lib')))
import tincoinlib
@pytest.fixture
def sentinel_proposal_hex():
return '5b2270726f706f73616c222c207b22656e645f65706f6368223a20313439313032323830302c20226e616d65223a2022626565722d7265696d62757273656d656e742d37222c20227061796d656e745f61646472657373223a2022795965384b77796155753559737753596d4233713372797838585455753979375569222c20227061796d656e745f616d6f756e74223a20372e30303030303030302c202273746172745f65706f6368223a20313438333235303430302c202275726c223a202268747470733a2f2f6461736863656e7472616c2e636f6d2f626565722d7265696d62757273656d656e742d37227d5d'
@pytest.fixture
def sentinel_superblock_hex():
return '5b227375706572626c6f636b222c207b226576656e745f626c6f636b5f686569676874223a2036323530302c20227061796d656e745f616464726573736573223a2022795965384b77796155753559737753596d42337133727978385854557539793755697c795443363268755234595145506e39414a486a6e517878726548536267416f617456222c20227061796d656e745f616d6f756e7473223a2022357c33227d5d'
@pytest.fixture
def tincoind_proposal_hex():
return '5b5b2270726f706f73616c222c207b22656e645f65706f6368223a20313439313336383430302c20226e616d65223a2022626565722d7265696d62757273656d656e742d39222c20227061796d656e745f61646472657373223a2022795965384b77796155753559737753596d4233713372797838585455753979375569222c20227061796d656e745f616d6f756e74223a2034392e30303030303030302c202273746172745f65706f6368223a20313438333235303430302c202274797065223a20312c202275726c223a202268747470733a2f2f7777772e6461736863656e7472616c2e6f72672f702f626565722d7265696d62757273656d656e742d39227d5d5d'
@pytest.fixture
def tincoind_superblock_hex():
return '5b5b2274726967676572222c207b226576656e745f626c6f636b5f686569676874223a2036323530302c20227061796d656e745f616464726573736573223a2022795965384b77796155753559737753596d42337133727978385854557539793755697c795443363268755234595145506e39414a486a6e517878726548536267416f617456222c20227061796d656e745f616d6f756e7473223a2022357c33222c202274797065223a20327d5d5d'
# ========================================================================
def test_SHIM_deserialise_from_tincoind(tincoind_proposal_hex, tincoind_superblock_hex):
assert tincoinlib.SHIM_deserialise_from_tincoind(tincoind_proposal_hex) == '5b2270726f706f73616c222c207b22656e645f65706f6368223a20313439313336383430302c20226e616d65223a2022626565722d7265696d62757273656d656e742d39222c20227061796d656e745f61646472657373223a2022795965384b77796155753559737753596d4233713372797838585455753979375569222c20227061796d656e745f616d6f756e74223a2034392e30303030303030302c202273746172745f65706f6368223a20313438333235303430302c202275726c223a202268747470733a2f2f7777772e6461736863656e7472616c2e6f72672f702f626565722d7265696d62757273656d656e742d39227d5d'
assert tincoinlib.SHIM_deserialise_from_tincoind(tincoind_superblock_hex) == '5b227375706572626c6f636b222c207b226576656e745f626c6f636b5f686569676874223a2036323530302c20227061796d656e745f616464726573736573223a2022795965384b77796155753559737753596d42337133727978385854557539793755697c795443363268755234595145506e39414a486a6e517878726548536267416f617456222c20227061796d656e745f616d6f756e7473223a2022357c33227d5d'
def test_SHIM_serialise_for_tincoind(sentinel_proposal_hex, sentinel_superblock_hex):
assert tincoinlib.SHIM_serialise_for_tincoind(sentinel_proposal_hex) == '5b5b2270726f706f73616c222c207b22656e645f65706f6368223a20313439313032323830302c20226e616d65223a2022626565722d7265696d62757273656d656e742d37222c20227061796d656e745f61646472657373223a2022795965384b77796155753559737753596d4233713372797838585455753979375569222c20227061796d656e745f616d6f756e74223a20372e30303030303030302c202273746172745f65706f6368223a20313438333235303430302c202274797065223a20312c202275726c223a202268747470733a2f2f6461736863656e7472616c2e636f6d2f626565722d7265696d62757273656d656e742d37227d5d5d'
assert tincoinlib.SHIM_serialise_for_tincoind(sentinel_superblock_hex) == '5b5b2274726967676572222c207b226576656e745f626c6f636b5f686569676874223a2036323530302c20227061796d656e745f616464726573736573223a2022795965384b77796155753559737753596d42337133727978385854557539793755697c795443363268755234595145506e39414a486a6e517878726548536267416f617456222c20227061796d656e745f616d6f756e7473223a2022357c33222c202274797065223a20327d5d5d'
| 113.974359
| 584
| 0.934758
| 135
| 4,445
| 30.377778
| 0.266667
| 0.008778
| 0.015606
| 0.019751
| 0.101683
| 0.095343
| 0.095343
| 0.019995
| 0.019995
| 0.019995
| 0
| 0.683556
| 0.023172
| 4,445
| 38
| 585
| 116.973684
| 0.26094
| 0.016198
| 0
| 0.166667
| 0
| 0
| 0.778998
| 0.773507
| 0
| 1
| 0
| 0
| 0.166667
| 1
| 0.25
| false
| 0
| 0.166667
| 0.166667
| 0.583333
| 0
| 0
| 0
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| null | 1
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
| 1
| 0
|
0
| 10
|
18b3b2b5474b570a2fb385332f6f0a15e4e60b24
| 9,560
|
py
|
Python
|
test/propagation_warn_only_test.py
|
velniukas/jenkinsflow
|
ca09c4044fc9da683b2233404e071fad506167b8
|
[
"BSD-3-Clause"
] | 12
|
2015-03-05T14:57:58.000Z
|
2021-03-30T09:22:04.000Z
|
test/propagation_warn_only_test.py
|
lhupfeldt/jenkinsflow
|
0eda66ea4ac4ef9cd2e07149cc9a33f93a6c40b0
|
[
"BSD-3-Clause"
] | 3
|
2015-02-23T04:32:11.000Z
|
2016-03-06T11:51:04.000Z
|
test/propagation_warn_only_test.py
|
velniukas/jenkinsflow
|
ca09c4044fc9da683b2233404e071fad506167b8
|
[
"BSD-3-Clause"
] | 4
|
2015-05-28T06:08:04.000Z
|
2019-08-26T09:35:24.000Z
|
# Copyright (c) 2012 - 2015 Lars Hupfeldt Nielsen, Hupfeldt IT
# All rights reserved. This work is under a BSD license, see LICENSE.TXT.
from pytest import raises
from jenkinsflow.flow import serial, parallel, FailedChildJobException, FailedChildJobsException, FinalResultException, Propagation, BuildResult
from .framework import api_select
def test_propagation_warn_only_serial(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j12_fail', max_fails=1, expect_invocations=1, expect_order=2, serial=True)
api.job('j13', max_fails=0, expect_invocations=0, expect_order=None)
with raises(FinalResultException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3, propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl1:
ctrl1.invoke('j11')
ctrl1.invoke('j12_fail')
ctrl1.invoke('j13')
assert exinfo.value.result == BuildResult.UNSTABLE
assert ctrl1.result == exinfo.value.result
return 77
def test_propagation_warn_only_parallel(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j1_fail', max_fails=1, expect_invocations=1, expect_order=1)
api.job('j2', max_fails=0, expect_invocations=1, expect_order=1)
with raises(FinalResultException) as exinfo:
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3, propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl1:
ctrl1.invoke('j1_fail')
ctrl1.invoke('j2')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_serial_parallel(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=2, serial=True)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=2)
api.job('j23', max_fails=0, expect_invocations=1, expect_order=2)
with raises(FinalResultException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.parallel(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl2:
ctrl2.invoke('j21')
ctrl2.invoke('j22_fail')
ctrl2.invoke('j23')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_parallel_serial(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=1, serial=True)
api.job('j23', max_fails=0, expect_invocations=0, expect_order=None)
with raises(FinalResultException) as exinfo:
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl2:
ctrl2.invoke('j21')
ctrl2.invoke('j22_fail')
ctrl2.invoke('j23')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_serial_serial(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=2)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=2)
api.job('j23', max_fails=0, expect_invocations=0, expect_order=None)
with raises(FinalResultException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl2:
ctrl2.invoke('j21')
ctrl2.invoke('j22_fail')
ctrl2.invoke('j23')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_parallel_parallel(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=1)
api.job('j23', max_fails=0, expect_invocations=1, expect_order=1)
with raises(FinalResultException) as exinfo:
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3, raise_if_unsuccessful=True) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.parallel(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl2:
ctrl2.invoke('j21')
ctrl2.invoke('j22_fail')
ctrl2.invoke('j23')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_serial_serial_continue(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=2)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=3)
api.job('j23', max_fails=0, expect_invocations=1, expect_order=4)
with raises(FinalResultException) as exinfo:
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as ctrl2:
ctrl2.invoke('j21')
with ctrl2.serial(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl3:
ctrl3.invoke('j22_fail')
ctrl2.invoke('j23')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_parallel_serial_continue(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=1)
api.job('j23', max_fails=0, expect_invocations=1, expect_order=1)
with raises(FinalResultException) as exinfo:
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as ctrl2:
ctrl2.invoke('j21')
with ctrl2.serial(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl3:
ctrl3.invoke('j22_fail')
ctrl2.invoke('j23')
assert exinfo.value.result == BuildResult.UNSTABLE
return 77
def test_propagation_warn_only_nested_serial_serial_continue_fail(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=2)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=3)
api.job('j23_fail', max_fails=1, expect_invocations=1, expect_order=4)
with raises(FailedChildJobException):
with serial(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as ctrl2:
ctrl2.invoke('j21')
with ctrl2.serial(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl3:
ctrl3.invoke('j22_fail')
ctrl2.invoke('j23_fail')
def test_propagation_warn_only_nested_parallel_serial_continue_fail(api_type):
with api_select.api(__file__, api_type, login=True) as api:
api.flow_job()
api.job('j11', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j21', max_fails=0, expect_invocations=1, expect_order=1)
api.job('j22_fail', max_fails=1, expect_invocations=1, expect_order=1)
api.job('j23_fail', max_fails=1, expect_invocations=1, expect_order=1)
with raises(FailedChildJobsException):
with parallel(api, timeout=70, job_name_prefix=api.job_name_prefix, report_interval=3) as ctrl1:
ctrl1.invoke('j11')
with ctrl1.serial() as ctrl2:
ctrl2.invoke('j21')
with ctrl2.serial(propagation=Propagation.FAILURE_TO_UNSTABLE) as ctrl3:
ctrl3.invoke('j22_fail')
ctrl2.invoke('j23_fail')
| 46.183575
| 153
| 0.662343
| 1,269
| 9,560
| 4.713948
| 0.07171
| 0.047141
| 0.102307
| 0.136409
| 0.923771
| 0.918923
| 0.911902
| 0.906219
| 0.902541
| 0.895687
| 0
| 0.051604
| 0.233787
| 9,560
| 206
| 154
| 46.407767
| 0.765051
| 0.013808
| 0
| 0.788462
| 0
| 0
| 0.035862
| 0
| 0
| 0
| 0
| 0
| 0.057692
| 1
| 0.064103
| false
| 0
| 0.019231
| 0
| 0.134615
| 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
|
e1384d594ff2e3343aeca05a411b8a1e85345109
| 92
|
py
|
Python
|
tests/test_a_logic.py
|
oz123/bottle_blueprint
|
a496afc5ee14e0825c37876ab8aed8062c9a53e6
|
[
"MIT"
] | null | null | null |
tests/test_a_logic.py
|
oz123/bottle_blueprint
|
a496afc5ee14e0825c37876ab8aed8062c9a53e6
|
[
"MIT"
] | null | null | null |
tests/test_a_logic.py
|
oz123/bottle_blueprint
|
a496afc5ee14e0825c37876ab8aed8062c9a53e6
|
[
"MIT"
] | null | null | null |
def test_addition():
assert 4 == 2 + 2
def test_addition_again():
assert 6 == 3 + 3
| 11.5
| 26
| 0.608696
| 15
| 92
| 3.533333
| 0.6
| 0.264151
| 0.566038
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.088235
| 0.26087
| 92
| 7
| 27
| 13.142857
| 0.691176
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.5
| 1
| 0.5
| true
| 0
| 0
| 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
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 1
| 0
| 1
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 7
|
bedb725f3ea6f5df050b5c757b477116a29769a6
| 2,331
|
py
|
Python
|
day1.py
|
jlucangelio/adventofcode-2017
|
339cd4488dd6b398a664845199e19ba38f173afa
|
[
"MIT"
] | null | null | null |
day1.py
|
jlucangelio/adventofcode-2017
|
339cd4488dd6b398a664845199e19ba38f173afa
|
[
"MIT"
] | null | null | null |
day1.py
|
jlucangelio/adventofcode-2017
|
339cd4488dd6b398a664845199e19ba38f173afa
|
[
"MIT"
] | null | null | null |
INPUT = "6592822488931338589815525425236818285229555616392928433262436847386544514648645288129834834862363847542262953164877694234514375164927616649264122487182321437459646851966649732474925353281699895326824852555747127547527163197544539468632369858413232684269835288817735678173986264554586412678364433327621627496939956645283712453265255261565511586373551439198276373843771249563722914847255524452675842558622845416218195374459386785618255129831539984559644185369543662821311686162137672168266152494656448824719791398797359326412235723234585539515385352426579831251943911197862994974133738196775618715739412713224837531544346114877971977411275354168752719858889347588136787894798476123335894514342411742111135337286449968879251481449757294167363867119927811513529711239534914119292833111624483472466781475951494348516125474142532923858941279569675445694654355314925386833175795464912974865287564866767924677333599828829875283753669783176288899797691713766199641716546284841387455733132519649365113182432238477673375234793394595435816924453585513973119548841577126141962776649294322189695375451743747581241922657947182232454611837512564776273929815169367899818698892234618847815155578736875295629917247977658723868641411493551796998791839776335793682643551875947346347344695869874564432566956882395424267187552799458352121248147371938943799995158617871393289534789214852747976587432857675156884837634687257363975437535621197887877326295229195663235129213398178282549432599455965759999159247295857366485345759516622427833518837458236123723353817444545271644684925297477149298484753858863551357266259935298184325926848958828192317538375317946457985874965434486829387647425222952585293626473351211161684297351932771462665621764392833122236577353669215833721772482863775629244619639234636853267934895783891823877845198326665728659328729472456175285229681244974389248235457688922179237895954959228638193933854787917647154837695422429184757725387589969781672596568421191236374563718951738499591454571728641951699981615249635314789251239677393251756396"
# INPUT = "91212129"
# INPUT = "1122"
s = 0
for i in range(len(INPUT)):
if INPUT[i] == INPUT[(i+1) % len(INPUT)]:
s += int(INPUT[i])
print s
s = 0
for i in range(len(INPUT)):
if INPUT[i] == INPUT[(i+len(INPUT)/2) % len(INPUT)]:
s += int(INPUT[i])
print s
| 137.117647
| 2,048
| 0.940798
| 52
| 2,331
| 42.173077
| 0.307692
| 0.016416
| 0.00456
| 0.005472
| 0.053808
| 0.053808
| 0.053808
| 0.053808
| 0.03192
| 0.03192
| 0
| 0.910058
| 0.031746
| 2,331
| 16
| 2,049
| 145.6875
| 0.061586
| 0.014157
| 0
| 0.727273
| 0
| 0
| 0.888017
| 0.888017
| 0
| 1
| 0
| 0
| 0
| 0
| null | null | 0
| 0
| null | null | 0.181818
| 0
| 0
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 1
| 0
| 0
| 1
| 1
| null | 1
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 10
|
831151ad3494e217c7d896577e7096ec487b3f0a
| 8,869
|
py
|
Python
|
export_helper_op.py
|
mdbridges1/Export_Helper
|
a40a37a2709f7f76c40ff273370eccdba500c1c9
|
[
"CC-BY-4.0"
] | 3
|
2020-05-27T16:47:53.000Z
|
2021-01-27T21:45:31.000Z
|
export_helper_op.py
|
mdbridges1/Export_Helper
|
a40a37a2709f7f76c40ff273370eccdba500c1c9
|
[
"CC-BY-4.0"
] | 3
|
2020-05-28T08:36:28.000Z
|
2020-05-28T09:35:28.000Z
|
export_helper_op.py
|
mdbridges1/Export_Helper
|
a40a37a2709f7f76c40ff273370eccdba500c1c9
|
[
"CC-BY-4.0"
] | 1
|
2021-01-27T21:45:35.000Z
|
2021-01-27T21:45:35.000Z
|
import bpy
import os
import math
class EXPORTOBJ_OT_Operator(bpy.types.Operator):
bl_idname = "object.export_obj"
bl_label = "Export OBJ"
bl_description = "Export OBJ"
def execute(self, context):
obj_dir = '.\OBJ'
blend_file_path = bpy.data.filepath
directory = os.path.dirname(blend_file_path)
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.select_all(action='DESELECT')
if os.path.isdir(directory + obj_dir) == False:
os.makedirs(directory + obj_dir)
i = 0
for i in range(len(bpy.context.scene.objects)):
obj_name = bpy.context.scene.objects[i].name
bpy.data.objects[obj_name].select_set(True)
target_file_obj = os.path.join(directory + obj_dir, obj_name + '.obj')
obj_loc = bpy.data.objects[obj_name].location.copy() # copy location
bpy.data.objects[obj_name].location = (0,0,0) # move object to world origin
bpy.ops.export_scene.obj(
filepath=target_file_obj,
check_existing=False,
filter_glob="*.obj;*.mtl",
use_selection=True,
use_animation=False,
use_mesh_modifiers=True,
use_edges=True,
use_smooth_groups=False,
use_smooth_groups_bitflags=False,
use_normals=True,
use_uvs=True,
use_materials=True,
use_triangles=False,
use_nurbs=False,
use_vertex_groups=False,
use_blen_objects=True,
group_by_object=False,
group_by_material=False,
keep_vertex_order=False,
global_scale=1,
path_mode='AUTO',
axis_forward='-Z',
axis_up='Y')
bpy.data.objects[obj_name].location = obj_loc # set object back to it's original location
bpy.ops.object.select_all(action='DESELECT')
i =+ 1
return {'FINISHED'}
class EXPORTFBX_OT_Operator(bpy.types.Operator):
bl_idname = "object.export_fbx"
bl_label = "Export FBX"
bl_description = "Export FBX"
def execute(self, context):
fbx_dir = '.\FBX'
blend_file_path = bpy.data.filepath
directory = os.path.dirname(blend_file_path)
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.select_all(action='DESELECT')
if os.path.isdir(directory + fbx_dir) == False:
os.makedirs(directory + fbx_dir)
i = 0
for i in range(len(bpy.context.scene.objects)):
obj_name = bpy.context.scene.objects[i].name
bpy.data.objects[obj_name].select_set(True)
target_file_fbx = os.path.join(directory + fbx_dir, obj_name + '.fbx')
obj_loc = bpy.data.objects[obj_name].location.copy() # copy location
bpy.data.objects[obj_name].location = (0,0,0) # move object to world origin
bpy.ops.export_scene.fbx(
filepath=target_file_fbx,
check_existing=False,
filter_glob="*.fbx",
use_selection=True,
use_active_collection=False,
global_scale=1,
apply_unit_scale=True,
apply_scale_options='FBX_SCALE_NONE',
bake_space_transform=False,
object_types={'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'},
use_mesh_modifiers=True,
use_mesh_modifiers_render=True,
mesh_smooth_type='FACE',
use_subsurf=False,
use_mesh_edges=False,
use_tspace=False,
use_custom_props=False,
add_leaf_bones=True,
primary_bone_axis='Y',
secondary_bone_axis='X',
use_armature_deform_only=False,
armature_nodetype='NULL',
bake_anim=True,
bake_anim_use_all_bones=True,
bake_anim_use_nla_strips=True,
bake_anim_use_all_actions=True,
bake_anim_force_startend_keying=True,
bake_anim_step=1,
bake_anim_simplify_factor=1,
path_mode='AUTO',
embed_textures=False,
batch_mode='OFF',
use_batch_own_dir=True,
use_metadata=True,
axis_forward='-Z',
axis_up='Y')
bpy.data.objects[obj_name].location = obj_loc # set object back to it's original location
bpy.ops.object.select_all(action='DESELECT')
i =+ 1
return {'FINISHED'}
class EXPORTUNITYFBX_OT_Operator(bpy.types.Operator):
bl_idname = "object.export_unityfbx"
bl_label = "Export Unity_FBX"
bl_description = "Export Unity_FBX"
def execute(self, context):
unity_dir = '.\FBX_Unity'
blend_file_path = bpy.data.filepath
directory = os.path.dirname(blend_file_path)
bpy.ops.object.mode_set(mode = 'OBJECT')
bpy.ops.object.select_all(action='DESELECT')
if os.path.isdir(directory + unity_dir) == False:
os.makedirs(directory + unity_dir)
i = 0
for i in range(len(bpy.context.scene.objects)):
obj_name = bpy.context.scene.objects[i].name
bpy.data.objects[obj_name].select_set(True)
target_file_fbx = os.path.join(directory + unity_dir, obj_name + '.fbx')
# Unity Faff
# Prevents, error - need to warn user
bpy.ops.object.make_single_user(type='SELECTED_OBJECTS', object=True, obdata=True)
# Would prefer to set_rotation? if possible.
bpy.ops.transform.rotate(value = math.pi, orient_axis='Z', orient_type='GLOBAL')
bpy.ops.transform.rotate(value = (math.pi / 2), orient_axis='X', orient_type='GLOBAL')
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
bpy.ops.transform.rotate(value = (-math.pi / 2), orient_axis='X', orient_type='GLOBAL')
obj_loc = bpy.data.objects[obj_name].location.copy() # copy location
bpy.data.objects[obj_name].location = (0,0,0) # move object to world origin
bpy.ops.export_scene.fbx(
filepath=target_file_fbx,
check_existing=False,
filter_glob="*.fbx",
use_selection=True,
use_active_collection=False,
global_scale=1,
apply_unit_scale=True,
apply_scale_options='FBX_SCALE_UNITS',
bake_space_transform=False,
object_types={'EMPTY', 'CAMERA', 'LIGHT', 'ARMATURE', 'MESH', 'OTHER'},
use_mesh_modifiers=True,
use_mesh_modifiers_render=True,
mesh_smooth_type='FACE',
use_subsurf=False,
use_mesh_edges=False,
use_tspace=False,
use_custom_props=False,
add_leaf_bones=True,
primary_bone_axis='Y',
secondary_bone_axis='X',
use_armature_deform_only=False,
armature_nodetype='NULL',
bake_anim=True,
bake_anim_use_all_bones=True,
bake_anim_use_nla_strips=True,
bake_anim_use_all_actions=True,
bake_anim_force_startend_keying=True,
bake_anim_step=1,
bake_anim_simplify_factor=1,
path_mode='AUTO',
embed_textures=False,
batch_mode='OFF',
use_batch_own_dir=True,
use_metadata=True,
axis_forward='-Z',
axis_up='Y')
## More Unity Faff, putting objects back to original state for user.
bpy.ops.transform.rotate(value = math.pi, orient_axis='Z', orient_type='GLOBAL')
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
bpy.data.objects[obj_name].location = obj_loc # set object back to it's original location
bpy.ops.object.select_all(action='DESELECT')
i =+ 1
return {'FINISHED'}
| 40.131222
| 106
| 0.539745
| 989
| 8,869
| 4.55814
| 0.176946
| 0.025288
| 0.046584
| 0.045253
| 0.811003
| 0.771074
| 0.771074
| 0.771074
| 0.771074
| 0.740461
| 0
| 0.00428
| 0.367685
| 8,869
| 221
| 107
| 40.131222
| 0.799572
| 0.046341
| 0
| 0.723164
| 0
| 0
| 0.055691
| 0.002675
| 0
| 0
| 0
| 0
| 0
| 1
| 0.016949
| false
| 0
| 0.016949
| 0
| 0.118644
| 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
|
8313162e0cd6747b63fb5810b549d0f47146b2fc
| 1,720
|
py
|
Python
|
tests/test_percentage_based_circuit_breaker.py
|
eelabs/circuit-breaker-python
|
21f4a4fa6b6d7388afb6483b586746e45a58497d
|
[
"Apache-2.0"
] | null | null | null |
tests/test_percentage_based_circuit_breaker.py
|
eelabs/circuit-breaker-python
|
21f4a4fa6b6d7388afb6483b586746e45a58497d
|
[
"Apache-2.0"
] | 21
|
2020-06-08T04:48:29.000Z
|
2022-03-26T14:24:25.000Z
|
tests/test_percentage_based_circuit_breaker.py
|
eelabs/circuit-breaker-python
|
21f4a4fa6b6d7388afb6483b586746e45a58497d
|
[
"Apache-2.0"
] | null | null | null |
from requests_circuit_breaker import PercentageCircuitBreaker
from requests_circuit_breaker.storage import InMemoryStorage
def test_percentage_failed_should_not_trip_breaker_when_less_than_minimum_error_count_reached():
breaker = PercentageCircuitBreaker("my_service", ttl=10, percent_failed=50, re_enable_after_seconds=60, storage=InMemoryStorage(), minimum_failures=3)
assert breaker.is_closed is True
breaker.register_error(None, None, 10)
breaker.register_error(None, None, 10)
breaker.register_success(None, None, 10)
breaker.register_success(None, None, 10)
assert breaker.is_closed is True
breaker.register_error(None, None, 10)
assert breaker.is_closed is False
def test_percentage_failed_should_not_trip_breaker_when_minimum_events_exceeded_but_failures_below_threshold():
breaker = PercentageCircuitBreaker("my_service", ttl=10, percent_failed=50, re_enable_after_seconds=60, storage=InMemoryStorage(), minimum_failures=2)
breaker.register_error(None, None, 10)
breaker.register_error(None, None, 10)
breaker.register_success(None, None, 10)
breaker.register_success(None, None, 10)
breaker.register_success(None, None, 10)
assert breaker.is_closed is True
def test_tripped_breaker_does_not_reset_on_success_within_re_enable_time():
breaker = PercentageCircuitBreaker("my_service", ttl=10, percent_failed=50, re_enable_after_seconds=60, storage=InMemoryStorage(), minimum_failures=2)
breaker.register_error(None, None, 10)
breaker.register_error(None, None, 10)
breaker.register_error(None, None, 10)
assert breaker.is_closed is False
breaker.register_success(None, None, 10)
assert breaker.is_closed is False
| 46.486486
| 154
| 0.801744
| 234
| 1,720
| 5.551282
| 0.235043
| 0.161663
| 0.107775
| 0.117783
| 0.808314
| 0.808314
| 0.808314
| 0.808314
| 0.808314
| 0.732102
| 0
| 0.032322
| 0.118605
| 1,720
| 36
| 155
| 47.777778
| 0.824538
| 0
| 0
| 0.785714
| 0
| 0
| 0.017442
| 0
| 0
| 0
| 0
| 0
| 0.214286
| 1
| 0.107143
| false
| 0
| 0.071429
| 0
| 0.178571
| 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
|
55ffb0c9f99fb6af30b17008bc9b23a373a9a73c
| 16,796
|
py
|
Python
|
train/model_search.py
|
JsBlueCat/SACN
|
19abce5ac3d8e5880c4334a2192a78b86f106701
|
[
"Apache-2.0"
] | null | null | null |
train/model_search.py
|
JsBlueCat/SACN
|
19abce5ac3d8e5880c4334a2192a78b86f106701
|
[
"Apache-2.0"
] | null | null | null |
train/model_search.py
|
JsBlueCat/SACN
|
19abce5ac3d8e5880c4334a2192a78b86f106701
|
[
"Apache-2.0"
] | null | null | null |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from operations import *
from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
PRIMITIVES = [
'none',
'max_pool_3x3',
'avg_pool_3x3',
'skip_connect',
'sep_conv_3x3',
'sep_conv_5x5',
'dil_conv_3x3',
'dil_conv_5x5'
]
class MixedOp(nn.Module):
def __init__(self, C, stride):
super(MixedOp, self).__init__()
self._ops = nn.ModuleList()
for primitive in PRIMITIVES:
op = OPS[primitive](C, stride, False)
if 'pool' in primitive:
op = nn.Sequential(op, nn.BatchNorm2d(C, affine=False))
self._ops.append(op)
def forward(self, x, weights):
return sum(w * op(x) for w, op in zip(weights, self._ops))
class Cell(nn.Module):
def __init__(self, steps, multiplier, C_prev_prev, C_prev, C, reduction, reduction_prev):
super(Cell, self).__init__()
self.reduction = reduction
if reduction_prev:
self.preprocess0 = FactorizedReduce(C_prev_prev, C, affine=False)
else:
self.preprocess0 = ReLUConvBN(
C_prev_prev, C, 1, 1, 0, affine=False)
self.preprocess1 = ReLUConvBN(C_prev, C, 1, 1, 0, affine=False)
self._steps = steps
self._multiplier = multiplier
self._ops = nn.ModuleList()
self._bns = nn.ModuleList()
for i in range(self._steps):
for j in range(2+i):
stride = 2 if reduction and j < 2 else 1
op = MixedOp(C, stride)
self._ops.append(op)
def forward(self, s0, s1, weights):
s0 = self.preprocess0(s0)
s1 = self.preprocess1(s1)
states = [s0, s1]
offset = 0
for i in range(self._steps):
s = sum(self._ops[offset+j](h, weights[offset+j])
for j, h in enumerate(states))
offset += len(states)
states.append(s)
return torch.cat(states[-self._multiplier:], dim=1)
class SACN_1(nn.Module):
def __init__(self, C, layers, criterion, steps=4, multiplier=4, stem_multiplier=3):
super(SACN_1, self).__init__()
self._C = C
self._layers = layers
self._criterion = criterion
self._steps = steps
self._multiplier = multiplier
'''
for stem_multiplier we experimently define
it to be 3, because it can be divide by 3
we define 1/3 layer and 2/3 layer to be re-
duction cell we use 3X3 as the SACN paper did
'''
C_curr = stem_multiplier*C
self.stem = nn.Sequential(
nn.Conv2d(3, C_curr, 3, padding=1, bias=False),
nn.BatchNorm2d(C_curr)
)
C_prev_prev, C_prev, C_curr = C_curr, C_curr, C
self.cells = nn.ModuleList()
reduction_prev = False
for i in range(layers):
if i in [layers//3, 2*layers//3]:
C_curr *= 2
reduction = True
else:
reduction = False
cell = Cell(steps, multiplier, C_prev_prev, C_prev,
C_curr, reduction, reduction_prev)
reduction_prev = reduction
self.cells += [cell]
C_prev_prev, C_prev = C_prev, multiplier*C_curr
# global_pooling to a n*m dim tensor
# self.global_pooling = nn.AdaptiveAvgPool2d(1)
self.global_conv = nn.Conv2d(C_prev, C_prev, kernel_size=6, stride=1)
'''
detect face and non-face
'''
self.classifier_face = nn.Conv2d(C_prev, 1, kernel_size=1, stride=1)
'''
bounding box regression that have 3 parameters
a b w as shown in paper SACN
'''
self.bounding_box_regression = nn.Conv2d(
C_prev, 3, kernel_size=1, stride=1)
'''
the RIP rotate
'''
self.classifier_rip = nn.Conv2d(C_prev, 1, kernel_size=1, stride=1)
self._initialize_alphas()
def forward(self, input):
# input is a 4d tensor that represent a picture
# _n, _c, h, w = input.size()
s0 = s1 = self.stem(input)
for i, cell in enumerate(self.cells):
if cell.reduction:
weights = F.softmax(self.alphas_reduce, dim=-1)
else:
weights = F.softmax(self.alphas_normal, dim=-1)
s0, s1 = s1, cell(s0, s1, weights)
# self.global_pooling = nn.AdaptiveAvgPool2d((h//24, w//24))
# out = self.global_pooling(s1)
out = self.global_conv(s1)
# print(out.size())
# print(out.view(out.size(0), -1).size())
face_prob = torch.sigmoid(
self.classifier_face(out))
bounding_box = self.bounding_box_regression(out)
rip = torch.sigmoid(self.classifier_rip(out))
return face_prob, bounding_box, rip
def _loss(self, input, gt_label, box_target, target_rig):
face_prob, bounding_box, rip = self(input)
return self._criterion(gt_label, face_prob, box_target, bounding_box, target_rig, rip)
def _initialize_alphas(self):
k = sum(1 for i in range(self._steps) for j in range(i+2))
num_ops = len(PRIMITIVES)
self.alphas_normal = Variable(1e-3 *
torch.randn(k, num_ops).cuda(), requires_grad=True)
self.alphas_reduce = Variable(1e-3 *
torch.randn(k, num_ops).cuda(), requires_grad=True)
self._arch_parameters = [
self.alphas_normal,
self.alphas_reduce
]
def arch_parameters(self):
return self._arch_parameters
def genotype(self):
def _parse(weights):
'''
a work queue algorism as introduced in google's paper
'''
gene = []
n = 2
start = 0
for i in range(self._steps):
'''
just like traversing the level of a tree
'''
end = start + n
W = weights[start: end].copy()
edges = sorted(range(i + 2), key=lambda x: -max(
W[x][k] for k in range(len(W[x])) if k != PRIMITIVES.index('none')))[: 2]
for j in edges:
k_best = None
for k in range(len(W[j])):
if k != PRIMITIVES.index('none'):
if k_best is None or W[j][k] > W[j][k_best]:
k_best = k
gene.append((PRIMITIVES[k_best], j))
start = end
n += 1
return gene
gene_normal = _parse(
F.softmax(self.alphas_normal, dim=-1).data.cpu().numpy()
)
gene_reduce = _parse(
F.softmax(self.alphas_reduce, dim=-1).data.cpu().numpy()
)
concat = range(2+self._steps-self._multiplier, self._steps + 2)
genotype = Genotype(
normal=gene_normal, normal_concat=concat,
reduce=gene_reduce, reduce_concat=concat
)
return genotype
class SACN_2(nn.Module):
def __init__(self, C, layers, criterion, steps=4, multiplier=4, stem_multiplier=3):
super(SACN_2, self).__init__()
self._C = C
self._layers = layers
self._criterion = criterion
self._steps = steps
self._multiplier = multiplier
'''
for stem_multiplier we experimently define
it to be 3, because it can be divide by 3
we define 1/3 layer and 2/3 layer to be re-
duction cell we use 3X3 as the SACN paper did
'''
C_curr = stem_multiplier*C
self.stem = nn.Sequential(
nn.Conv2d(3, C_curr, 3, padding=1, bias=False),
nn.BatchNorm2d(C_curr)
)
C_prev_prev, C_prev, C_curr = C_curr, C_curr, C
self.cells = nn.ModuleList()
reduction_prev = False
for i in range(layers):
if i in [layers//3, 2*layers//3]:
C_curr *= 2
reduction = True
else:
reduction = False
cell = Cell(steps, multiplier, C_prev_prev, C_prev,
C_curr, reduction, reduction_prev)
reduction_prev = reduction
self.cells += [cell]
C_prev_prev, C_prev = C_prev, multiplier*C_curr
# global_pooling to a 1 dim tensor
self.global_pooling = nn.AdaptiveAvgPool2d(1)
'''
detect face and non-face
'''
self.classifier_face = nn.Linear(C_prev, 1)
'''
bounding box regression that have 3 parameters
a b w as shown in paper SACN
'''
self.bounding_box_regression = nn.Linear(C_prev, 3)
'''
the RIP rotate
'''
self.classifier_rip = nn.Linear(C_prev, 3)
self._initialize_alphas()
def forward(self, input):
# input is a 4d tensor that represent a picture
s0 = s1 = self.stem(input)
for i, cell in enumerate(self.cells):
if cell.reduction:
weights = F.softmax(self.alphas_reduce, dim=-1)
else:
weights = F.softmax(self.alphas_normal, dim=-1)
s0, s1 = s1, cell(s0, s1, weights)
out = self.global_pooling(s1)
face_prob = torch.sigmoid(
self.classifier_face(out.view(out.size(0), -1)))
bounding_box = self.bounding_box_regression(out.view(out.size(0), -1))
rip = torch.sigmoid(self.classifier_rip(out.view(out.size(0), -1)))
return face_prob, bounding_box, rip
def _loss(self, input, gt_label, box_target, target_rig):
face_prob, bounding_box, rip = self(input)
return self._criterion(gt_label, face_prob, box_target, bounding_box, target_rig, rip)
def _initialize_alphas(self):
k = sum(1 for i in range(self._steps) for j in range(i+2))
num_ops = len(PRIMITIVES)
self.alphas_normal = Variable(1e-3 *
torch.randn(k, num_ops).cuda(), requires_grad=True)
self.alphas_reduce = Variable(1e-3 *
torch.randn(k, num_ops).cuda(), requires_grad=True)
self._arch_parameters = [
self.alphas_normal,
self.alphas_reduce
]
def arch_parameters(self):
return self._arch_parameters
def genotype(self):
def _parse(weights):
'''
a work queue algorism as introduced in google's paper
'''
gene = []
n = 2
start = 0
for i in range(self._steps):
'''
just like traversing the level of a tree
'''
end = start + n
W = weights[start:end].copy()
edges = sorted(range(i + 2), key=lambda x: -max(
W[x][k] for k in range(len(W[x])) if k != PRIMITIVES.index('none')))[:2]
for j in edges:
k_best = None
for k in range(len(W[j])):
if k != PRIMITIVES.index('none'):
if k_best is None or W[j][k] > W[j][k_best]:
k_best = k
gene.append((PRIMITIVES[k_best], j))
start = end
n += 1
return gene
gene_normal = _parse(
F.softmax(self.alphas_normal, dim=-1).data.cpu().numpy()
)
gene_reduce = _parse(
F.softmax(self.alphas_reduce, dim=-1).data.cpu().numpy()
)
concat = range(2+self._steps-self._multiplier, self._steps + 2)
genotype = Genotype(
normal=gene_normal, normal_concat=concat,
reduce=gene_reduce, reduce_concat=concat
)
return genotype
class SACN_3(nn.Module):
def __init__(self, C, layers, criterion, steps=4, multiplier=4, stem_multiplier=3):
super(SACN_3, self).__init__()
self._C = C
self._layers = layers
self._criterion = criterion
self._steps = steps
self._multiplier = multiplier
'''
for stem_multiplier we experimently define
it to be 3, because it can be divide by 3
we define 1/3 layer and 2/3 layer to be re-
duction cell we use 3X3 as the SACN paper did
'''
C_curr = stem_multiplier*C
self.stem = nn.Sequential(
nn.Conv2d(3, C_curr, 3, padding=1, bias=False),
nn.BatchNorm2d(C_curr)
)
C_prev_prev, C_prev, C_curr = C_curr, C_curr, C
self.cells = nn.ModuleList()
reduction_prev = False
for i in range(layers):
if i in [layers//3, 2*layers//3]:
C_curr *= 2
reduction = True
else:
reduction = False
cell = Cell(steps, multiplier, C_prev_prev, C_prev,
C_curr, reduction, reduction_prev)
reduction_prev = reduction
self.cells += [cell]
C_prev_prev, C_prev = C_prev, multiplier*C_curr
# global_pooling to a 1 dim tensor
self.global_pooling = nn.AdaptiveAvgPool2d(1)
'''
detect face and non-face
'''
self.classifier_face = nn.Linear(C_prev, 1)
'''
bounding box regression that have 3 parameters
a b w as shown in paper SACN
'''
self.bounding_box_regression = nn.Linear(C_prev, 3)
'''
the RIP rotate
'''
self.classifier_rip = nn.Linear(C_prev, 1)
self._initialize_alphas()
def forward(self, input):
# input is a 4d tensor that represent a picture
s0 = s1 = self.stem(input)
for i, cell in enumerate(self.cells):
if cell.reduction:
weights = F.softmax(self.alphas_reduce, dim=-1)
else:
weights = F.softmax(self.alphas_normal, dim=-1)
s0, s1 = s1, cell(s0, s1, weights)
out = self.global_pooling(s1)
face_prob = torch.sigmoid(
self.classifier_face(out.view(out.size(0), -1)))
bounding_box = self.bounding_box_regression(out.view(out.size(0), -1))
rip = self.classifier_rip(out.view(out.size(0), -1))
return face_prob, bounding_box, rip
def _loss(self, input, gt_label, box_target, target_rig):
face_prob, bounding_box, rip = self(input)
return self._criterion(gt_label, face_prob, box_target, bounding_box, target_rig, rip)
def _initialize_alphas(self):
k = sum(1 for i in range(self._steps) for j in range(i+2))
num_ops = len(PRIMITIVES)
self.alphas_normal = Variable(1e-3 *
torch.randn(k, num_ops).cuda(), requires_grad=True)
self.alphas_reduce = Variable(1e-3 *
torch.randn(k, num_ops).cuda(), requires_grad=True)
self._arch_parameters = [
self.alphas_normal,
self.alphas_reduce
]
def arch_parameters(self):
return self._arch_parameters
def genotype(self):
def _parse(weights):
'''
a work queue algorism as introduced in google's paper
'''
gene = []
n = 2
start = 0
for i in range(self._steps):
'''
just like traversing the level of a tree
'''
end = start + n
W = weights[start:end].copy()
edges = sorted(range(i + 2), key=lambda x: -max(
W[x][k] for k in range(len(W[x])) if k != PRIMITIVES.index('none')))[:2]
for j in edges:
k_best = None
for k in range(len(W[j])):
if k != PRIMITIVES.index('none'):
if k_best is None or W[j][k] > W[j][k_best]:
k_best = k
gene.append((PRIMITIVES[k_best], j))
start = end
n += 1
return gene
gene_normal = _parse(
F.softmax(self.alphas_normal, dim=-1).data.cpu().numpy()
)
gene_reduce = _parse(
F.softmax(self.alphas_reduce, dim=-1).data.cpu().numpy()
)
concat = range(2+self._steps-self._multiplier, self._steps + 2)
genotype = Genotype(
normal=gene_normal, normal_concat=concat,
reduce=gene_reduce, reduce_concat=concat
)
return genotype
| 36.433839
| 94
| 0.541677
| 2,127
| 16,796
| 4.090738
| 0.089798
| 0.021262
| 0.014481
| 0.013792
| 0.874267
| 0.863234
| 0.855189
| 0.832893
| 0.814159
| 0.814159
| 0
| 0.021617
| 0.355501
| 16,796
| 460
| 95
| 36.513043
| 0.782171
| 0.037033
| 0
| 0.756598
| 0
| 0
| 0.011316
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.073314
| false
| 0
| 0.017595
| 0.01173
| 0.155425
| 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
|
3629f4489aaa855ccca2c96c033a1b067c630bfe
| 952
|
py
|
Python
|
prediction_flow/transformers/column/tests/test_category_encoder.py
|
dydcfg/prediction-flow
|
332068f521bba51acc8600fe72e36e92c331bef1
|
[
"MIT"
] | 211
|
2019-08-02T23:04:40.000Z
|
2022-03-18T06:36:25.000Z
|
prediction_flow/transformers/column/tests/test_category_encoder.py
|
dydcfg/prediction-flow
|
332068f521bba51acc8600fe72e36e92c331bef1
|
[
"MIT"
] | 18
|
2019-08-10T07:13:05.000Z
|
2022-03-17T10:45:30.000Z
|
prediction_flow/transformers/column/tests/test_category_encoder.py
|
dydcfg/prediction-flow
|
332068f521bba51acc8600fe72e36e92c331bef1
|
[
"MIT"
] | 51
|
2019-08-02T23:04:41.000Z
|
2021-12-24T02:48:58.000Z
|
from prediction_flow.transformers.column import CategoryEncoder
def test_str_inputs():
category_encoder = CategoryEncoder(min_cnt=1)
input_terms = ['this', 'is', 'a', 'simple', 'test']
category_encoder.fit(input_terms)
transformed = category_encoder.transform(input_terms)
assert set(transformed) == {1, 2, 3, 4, 5}
assert category_encoder.dimension() == 7
def test_int_inputs():
category_encoder = CategoryEncoder(min_cnt=1)
input_terms = [345, 3434, 23, 88, 4]
category_encoder.fit(input_terms)
transformed = category_encoder.transform(input_terms)
assert set(transformed) == {1, 2, 3, 4, 5}
assert category_encoder.dimension() == 7
def test_unseen_inputs():
category_encoder = CategoryEncoder(min_cnt=1)
input_terms = [345, 3434, 23, 88, 4]
category_encoder.fit(input_terms)
transformed = category_encoder.transform([345, 5343])
assert set(transformed) == {4, 6}
| 23.8
| 63
| 0.702731
| 122
| 952
| 5.245902
| 0.336066
| 0.257813
| 0.098438
| 0.16875
| 0.809375
| 0.809375
| 0.809375
| 0.809375
| 0.809375
| 0.726563
| 0
| 0.061224
| 0.176471
| 952
| 39
| 64
| 24.410256
| 0.755102
| 0
| 0
| 0.666667
| 0
| 0
| 0.017857
| 0
| 0
| 0
| 0
| 0
| 0.238095
| 1
| 0.142857
| false
| 0
| 0.047619
| 0
| 0.190476
| 0
| 0
| 0
| 0
| null | 1
| 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
| 8
|
3d25c028a71631d0f3830c1ddcb6841aa7d43187
| 28,462
|
bzl
|
Python
|
fsharp/nuget/nuget.bzl
|
ashwin153/rules_proto_grpc
|
093ffe3d6303bcd848121db4fa347ba6c9d3985a
|
[
"Apache-2.0"
] | 162
|
2019-07-15T22:35:30.000Z
|
2022-03-28T21:16:29.000Z
|
fsharp/nuget/nuget.bzl
|
ashwin153/rules_proto_grpc
|
093ffe3d6303bcd848121db4fa347ba6c9d3985a
|
[
"Apache-2.0"
] | 166
|
2019-07-18T16:07:51.000Z
|
2022-03-31T17:35:39.000Z
|
fsharp/nuget/nuget.bzl
|
ashwin153/rules_proto_grpc
|
093ffe3d6303bcd848121db4fa347ba6c9d3985a
|
[
"Apache-2.0"
] | 92
|
2019-08-21T04:15:24.000Z
|
2022-03-11T18:42:54.000Z
|
"""Generated nuget packages"""
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "dotnet_nuget_new", "nuget_package")
# Backwards compatibility definitions
def nuget_protobuf_packages():
nuget_rules_proto_grpc_packages()
def nuget_grpc_packages():
nuget_rules_proto_grpc_packages()
def no_op():
# Function that does nothing, to be placeholder in below function. This prevents it being a
# syntax error when nuget2bazel is first run
pass
def nuget_rules_proto_grpc_packages():
"""Nuget packages"""
no_op()
### Generated by the tool
nuget_package(
name = "system.buffers",
package = "system.buffers",
version = "4.5.1",
sha256 = "c30b3dd2c7e2f4cee4b823d692fd42118309b42ab1f5007f923d329a5b0d6b12",
)
nuget_package(
name = "system.numerics.vectors",
package = "system.numerics.vectors",
version = "4.5.0",
sha256 = "a9d49320581fda1b4f4be6212c68c01a22cdf228026099c20a8eabefcf90f9cf",
)
nuget_package(
name = "system.runtime.compilerservices.unsafe",
package = "system.runtime.compilerservices.unsafe",
version = "4.7.1",
sha256 = "52fca80d5f0ed286371cf1b519b039e9855dbf04c611f8d8479816d4eec82b85",
core_lib = {
"netcoreapp2.0": "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp2.1": "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp2.2": "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp3.0": "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp3.1": "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"net5.0": "lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
},
core_ref = {
"netcoreapp2.0": "ref/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp2.1": "ref/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp2.2": "ref/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp3.0": "ref/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll",
"netcoreapp3.1": "ref/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll",
"net5.0": "ref/netstandard2.0/System.Runtime.CompilerServices.Unsafe.dll",
},
core_files = {
"netcoreapp2.0": [
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.xml",
],
"netcoreapp2.1": [
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.xml",
],
"netcoreapp2.2": [
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.xml",
],
"netcoreapp3.0": [
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.xml",
],
"netcoreapp3.1": [
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.xml",
],
"net5.0": [
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.dll",
"lib/netcoreapp2.0/System.Runtime.CompilerServices.Unsafe.xml",
],
},
)
nuget_package(
name = "system.memory",
package = "system.memory",
version = "4.5.4",
sha256 = "dec0847f33b8823e4260672d97d657411461c00ada3107ec7bbcb32a845eeb91",
core_lib = {
"netcoreapp2.0": "lib/netstandard2.0/System.Memory.dll",
},
core_deps = {
"netcoreapp2.0": [
"@system.runtime.compilerservices.unsafe//:netcoreapp2.0_core",
],
},
core_files = {
"netcoreapp2.0": [
"lib/netstandard2.0/System.Memory.dll",
"lib/netstandard2.0/System.Memory.xml",
],
},
)
nuget_package(
name = "google.protobuf",
package = "google.protobuf",
version = "3.18.0",
sha256 = "7f08d1f6ba43c687183ad52a4ce7c44b2f52562378d5e18de18d4bf90d7fae51",
core_lib = {
"netcoreapp2.0": "lib/netstandard2.0/Google.Protobuf.dll",
"netcoreapp2.1": "lib/netstandard2.0/Google.Protobuf.dll",
"netcoreapp2.2": "lib/netstandard2.0/Google.Protobuf.dll",
"netcoreapp3.0": "lib/netstandard2.0/Google.Protobuf.dll",
"netcoreapp3.1": "lib/netstandard2.0/Google.Protobuf.dll",
"net5.0": "lib/net5.0/Google.Protobuf.dll",
},
core_deps = {
"netcoreapp2.0": [
"@system.memory//:netcoreapp2.0_core",
"@system.runtime.compilerservices.unsafe//:netcoreapp2.0_core",
],
"netcoreapp2.1": [
"@system.memory//:netcoreapp2.1_core",
"@system.runtime.compilerservices.unsafe//:netcoreapp2.1_core",
],
"netcoreapp2.2": [
"@system.memory//:netcoreapp2.2_core",
"@system.runtime.compilerservices.unsafe//:netcoreapp2.2_core",
],
"netcoreapp3.0": [
"@system.memory//:netcoreapp3.0_core",
"@system.runtime.compilerservices.unsafe//:netcoreapp3.0_core",
],
"netcoreapp3.1": [
"@system.memory//:netcoreapp3.1_core",
"@system.runtime.compilerservices.unsafe//:netcoreapp3.1_core",
],
},
core_files = {
"netcoreapp2.0": [
"lib/netstandard2.0/Google.Protobuf.dll",
"lib/netstandard2.0/Google.Protobuf.pdb",
"lib/netstandard2.0/Google.Protobuf.xml",
],
"netcoreapp2.1": [
"lib/netstandard2.0/Google.Protobuf.dll",
"lib/netstandard2.0/Google.Protobuf.pdb",
"lib/netstandard2.0/Google.Protobuf.xml",
],
"netcoreapp2.2": [
"lib/netstandard2.0/Google.Protobuf.dll",
"lib/netstandard2.0/Google.Protobuf.pdb",
"lib/netstandard2.0/Google.Protobuf.xml",
],
"netcoreapp3.0": [
"lib/netstandard2.0/Google.Protobuf.dll",
"lib/netstandard2.0/Google.Protobuf.pdb",
"lib/netstandard2.0/Google.Protobuf.xml",
],
"netcoreapp3.1": [
"lib/netstandard2.0/Google.Protobuf.dll",
"lib/netstandard2.0/Google.Protobuf.pdb",
"lib/netstandard2.0/Google.Protobuf.xml",
],
"net5.0": [
"lib/net5.0/Google.Protobuf.dll",
"lib/net5.0/Google.Protobuf.pdb",
"lib/net5.0/Google.Protobuf.xml",
],
},
)
nuget_package(
name = "grpc.core.api",
package = "grpc.core.api",
version = "2.40.0",
sha256 = "79246badf1942f3966341894e2f1a9447c4ab3a7bbfd94b2879b5789c8cd7925",
core_lib = {
"netcoreapp2.0": "lib/netstandard2.0/Grpc.Core.Api.dll",
"netcoreapp2.1": "lib/netstandard2.0/Grpc.Core.Api.dll",
"netcoreapp2.2": "lib/netstandard2.0/Grpc.Core.Api.dll",
"netcoreapp3.0": "lib/netstandard2.0/Grpc.Core.Api.dll",
"netcoreapp3.1": "lib/netstandard2.0/Grpc.Core.Api.dll",
"net5.0": "lib/netstandard2.0/Grpc.Core.Api.dll",
},
core_deps = {
"netcoreapp2.0": [
"@system.memory//:netcoreapp2.0_core",
],
"netcoreapp2.1": [
"@system.memory//:netcoreapp2.1_core",
],
"netcoreapp2.2": [
"@system.memory//:netcoreapp2.2_core",
],
"netcoreapp3.0": [
"@system.memory//:netcoreapp3.0_core",
],
"netcoreapp3.1": [
"@system.memory//:netcoreapp3.1_core",
],
"net5.0": [
"@system.memory//:net5.0_core",
],
},
core_files = {
"netcoreapp2.0": [
"lib/netstandard2.0/Grpc.Core.Api.dll",
"lib/netstandard2.0/Grpc.Core.Api.pdb",
"lib/netstandard2.0/Grpc.Core.Api.xml",
],
"netcoreapp2.1": [
"lib/netstandard2.0/Grpc.Core.Api.dll",
"lib/netstandard2.0/Grpc.Core.Api.pdb",
"lib/netstandard2.0/Grpc.Core.Api.xml",
],
"netcoreapp2.2": [
"lib/netstandard2.0/Grpc.Core.Api.dll",
"lib/netstandard2.0/Grpc.Core.Api.pdb",
"lib/netstandard2.0/Grpc.Core.Api.xml",
],
"netcoreapp3.0": [
"lib/netstandard2.0/Grpc.Core.Api.dll",
"lib/netstandard2.0/Grpc.Core.Api.pdb",
"lib/netstandard2.0/Grpc.Core.Api.xml",
],
"netcoreapp3.1": [
"lib/netstandard2.0/Grpc.Core.Api.dll",
"lib/netstandard2.0/Grpc.Core.Api.pdb",
"lib/netstandard2.0/Grpc.Core.Api.xml",
],
"net5.0": [
"lib/netstandard2.0/Grpc.Core.Api.dll",
"lib/netstandard2.0/Grpc.Core.Api.pdb",
"lib/netstandard2.0/Grpc.Core.Api.xml",
],
},
)
nuget_package(
name = "grpc.core",
package = "grpc.core",
version = "2.40.0",
sha256 = "b3d74d4d24e4bea1bf4be48849cf4c8ec5da51cf45d8f4c05338a5f76fa0a80e",
core_lib = {
"netcoreapp2.0": "lib/netstandard2.0/Grpc.Core.dll",
"netcoreapp2.1": "lib/netstandard2.0/Grpc.Core.dll",
"netcoreapp2.2": "lib/netstandard2.0/Grpc.Core.dll",
"netcoreapp3.0": "lib/netstandard2.0/Grpc.Core.dll",
"netcoreapp3.1": "lib/netstandard2.0/Grpc.Core.dll",
"net5.0": "lib/netstandard2.0/Grpc.Core.dll",
},
core_deps = {
"netcoreapp2.0": [
"@grpc.core.api//:netcoreapp2.0_core",
"@system.memory//:netcoreapp2.0_core",
],
"netcoreapp2.1": [
"@grpc.core.api//:netcoreapp2.1_core",
"@system.memory//:netcoreapp2.1_core",
],
"netcoreapp2.2": [
"@grpc.core.api//:netcoreapp2.2_core",
"@system.memory//:netcoreapp2.2_core",
],
"netcoreapp3.0": [
"@grpc.core.api//:netcoreapp3.0_core",
"@system.memory//:netcoreapp3.0_core",
],
"netcoreapp3.1": [
"@grpc.core.api//:netcoreapp3.1_core",
"@system.memory//:netcoreapp3.1_core",
],
"net5.0": [
"@grpc.core.api//:net5.0_core",
"@system.memory//:net5.0_core",
],
},
core_files = {
"netcoreapp2.0": [
"lib/netstandard2.0/Grpc.Core.dll",
"lib/netstandard2.0/Grpc.Core.pdb",
"lib/netstandard2.0/Grpc.Core.xml",
# Patched in by regenerate_packages.sh
# Can't use select() here, so must just specify all
"runtimes/win-x64/native/grpc_csharp_ext.x64.dll",
"runtimes/win-x86/native/grpc_csharp_ext.x86.dll",
"runtimes/linux-arm64/native/libgrpc_csharp_ext.arm64.so",
"runtimes/linux-x64/native/libgrpc_csharp_ext.x64.so",
"runtimes/osx-x64/native/libgrpc_csharp_ext.x64.dylib",
],
"netcoreapp2.1": [
"lib/netstandard2.0/Grpc.Core.dll",
"lib/netstandard2.0/Grpc.Core.pdb",
"lib/netstandard2.0/Grpc.Core.xml",
# Patched in by regenerate_packages.sh
# Can't use select() here, so must just specify all
"runtimes/win-x64/native/grpc_csharp_ext.x64.dll",
"runtimes/win-x86/native/grpc_csharp_ext.x86.dll",
"runtimes/linux-arm64/native/libgrpc_csharp_ext.arm64.so",
"runtimes/linux-x64/native/libgrpc_csharp_ext.x64.so",
"runtimes/osx-x64/native/libgrpc_csharp_ext.x64.dylib",
],
"netcoreapp2.2": [
"lib/netstandard2.0/Grpc.Core.dll",
"lib/netstandard2.0/Grpc.Core.pdb",
"lib/netstandard2.0/Grpc.Core.xml",
# Patched in by regenerate_packages.sh
# Can't use select() here, so must just specify all
"runtimes/win-x64/native/grpc_csharp_ext.x64.dll",
"runtimes/win-x86/native/grpc_csharp_ext.x86.dll",
"runtimes/linux-arm64/native/libgrpc_csharp_ext.arm64.so",
"runtimes/linux-x64/native/libgrpc_csharp_ext.x64.so",
"runtimes/osx-x64/native/libgrpc_csharp_ext.x64.dylib",
],
"netcoreapp3.0": [
"lib/netstandard2.0/Grpc.Core.dll",
"lib/netstandard2.0/Grpc.Core.pdb",
"lib/netstandard2.0/Grpc.Core.xml",
# Patched in by regenerate_packages.sh
# Can't use select() here, so must just specify all
"runtimes/win-x64/native/grpc_csharp_ext.x64.dll",
"runtimes/win-x86/native/grpc_csharp_ext.x86.dll",
"runtimes/linux-arm64/native/libgrpc_csharp_ext.arm64.so",
"runtimes/linux-x64/native/libgrpc_csharp_ext.x64.so",
"runtimes/osx-x64/native/libgrpc_csharp_ext.x64.dylib",
],
"netcoreapp3.1": [
"lib/netstandard2.0/Grpc.Core.dll",
"lib/netstandard2.0/Grpc.Core.pdb",
"lib/netstandard2.0/Grpc.Core.xml",
# Patched in by regenerate_packages.sh
# Can't use select() here, so must just specify all
"runtimes/win-x64/native/grpc_csharp_ext.x64.dll",
"runtimes/win-x86/native/grpc_csharp_ext.x86.dll",
"runtimes/linux-arm64/native/libgrpc_csharp_ext.arm64.so",
"runtimes/linux-x64/native/libgrpc_csharp_ext.x64.so",
"runtimes/osx-x64/native/libgrpc_csharp_ext.x64.dylib",
],
"net5.0": [
"lib/netstandard2.0/Grpc.Core.dll",
"lib/netstandard2.0/Grpc.Core.pdb",
"lib/netstandard2.0/Grpc.Core.xml",
# Patched in by regenerate_packages.sh
# Can't use select() here, so must just specify all
"runtimes/win-x64/native/grpc_csharp_ext.x64.dll",
"runtimes/win-x86/native/grpc_csharp_ext.x86.dll",
"runtimes/linux-arm64/native/libgrpc_csharp_ext.arm64.so",
"runtimes/linux-x64/native/libgrpc_csharp_ext.x64.so",
"runtimes/osx-x64/native/libgrpc_csharp_ext.x64.dylib",
],
},
)
nuget_package(
name = "grpc",
package = "grpc",
version = "2.40.0",
sha256 = "931cf1271355b8ed3ce8a35aa1feb312b62398a4f0aa2e54767318b0adfda498",
core_deps = {
"netcoreapp2.0": [
"@grpc.core//:netcoreapp2.0_core",
],
"netcoreapp2.1": [
"@grpc.core//:netcoreapp2.1_core",
],
"netcoreapp2.2": [
"@grpc.core//:netcoreapp2.2_core",
],
"netcoreapp3.0": [
"@grpc.core//:netcoreapp3.0_core",
],
"netcoreapp3.1": [
"@grpc.core//:netcoreapp3.1_core",
],
"net5.0": [
"@grpc.core//:net5.0_core",
],
},
)
nuget_package(
name = "fsharp.core",
package = "fsharp.core",
version = "5.0.1",
sha256 = "58f932b639c7953871cd894fbe6a4808c7d1fb800d4e258d1a3100e8ba007010",
core_lib = {
"netcoreapp2.0": "lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"netcoreapp2.1": "lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"netcoreapp2.2": "lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"netcoreapp3.0": "lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"netcoreapp3.1": "lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"net5.0": "lib/netstandard2.0/cs/FSharp.Core.resources.dll",
},
core_files = {
"netcoreapp2.0": [
"lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"lib/netstandard2.0/de/FSharp.Core.resources.dll",
"lib/netstandard2.0/es/FSharp.Core.resources.dll",
"lib/netstandard2.0/fr/FSharp.Core.resources.dll",
"lib/netstandard2.0/FSharp.Core.dll",
"lib/netstandard2.0/FSharp.Core.xml",
"lib/netstandard2.0/it/FSharp.Core.resources.dll",
"lib/netstandard2.0/ja/FSharp.Core.resources.dll",
"lib/netstandard2.0/ko/FSharp.Core.resources.dll",
"lib/netstandard2.0/pl/FSharp.Core.resources.dll",
"lib/netstandard2.0/pt-BR/FSharp.Core.resources.dll",
"lib/netstandard2.0/ru/FSharp.Core.resources.dll",
"lib/netstandard2.0/tr/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hans/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hant/FSharp.Core.resources.dll",
],
"netcoreapp2.1": [
"lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"lib/netstandard2.0/de/FSharp.Core.resources.dll",
"lib/netstandard2.0/es/FSharp.Core.resources.dll",
"lib/netstandard2.0/fr/FSharp.Core.resources.dll",
"lib/netstandard2.0/FSharp.Core.dll",
"lib/netstandard2.0/FSharp.Core.xml",
"lib/netstandard2.0/it/FSharp.Core.resources.dll",
"lib/netstandard2.0/ja/FSharp.Core.resources.dll",
"lib/netstandard2.0/ko/FSharp.Core.resources.dll",
"lib/netstandard2.0/pl/FSharp.Core.resources.dll",
"lib/netstandard2.0/pt-BR/FSharp.Core.resources.dll",
"lib/netstandard2.0/ru/FSharp.Core.resources.dll",
"lib/netstandard2.0/tr/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hans/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hant/FSharp.Core.resources.dll",
],
"netcoreapp2.2": [
"lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"lib/netstandard2.0/de/FSharp.Core.resources.dll",
"lib/netstandard2.0/es/FSharp.Core.resources.dll",
"lib/netstandard2.0/fr/FSharp.Core.resources.dll",
"lib/netstandard2.0/FSharp.Core.dll",
"lib/netstandard2.0/FSharp.Core.xml",
"lib/netstandard2.0/it/FSharp.Core.resources.dll",
"lib/netstandard2.0/ja/FSharp.Core.resources.dll",
"lib/netstandard2.0/ko/FSharp.Core.resources.dll",
"lib/netstandard2.0/pl/FSharp.Core.resources.dll",
"lib/netstandard2.0/pt-BR/FSharp.Core.resources.dll",
"lib/netstandard2.0/ru/FSharp.Core.resources.dll",
"lib/netstandard2.0/tr/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hans/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hant/FSharp.Core.resources.dll",
],
"netcoreapp3.0": [
"lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"lib/netstandard2.0/de/FSharp.Core.resources.dll",
"lib/netstandard2.0/es/FSharp.Core.resources.dll",
"lib/netstandard2.0/fr/FSharp.Core.resources.dll",
"lib/netstandard2.0/FSharp.Core.dll",
"lib/netstandard2.0/FSharp.Core.xml",
"lib/netstandard2.0/it/FSharp.Core.resources.dll",
"lib/netstandard2.0/ja/FSharp.Core.resources.dll",
"lib/netstandard2.0/ko/FSharp.Core.resources.dll",
"lib/netstandard2.0/pl/FSharp.Core.resources.dll",
"lib/netstandard2.0/pt-BR/FSharp.Core.resources.dll",
"lib/netstandard2.0/ru/FSharp.Core.resources.dll",
"lib/netstandard2.0/tr/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hans/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hant/FSharp.Core.resources.dll",
],
"netcoreapp3.1": [
"lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"lib/netstandard2.0/de/FSharp.Core.resources.dll",
"lib/netstandard2.0/es/FSharp.Core.resources.dll",
"lib/netstandard2.0/fr/FSharp.Core.resources.dll",
"lib/netstandard2.0/FSharp.Core.dll",
"lib/netstandard2.0/FSharp.Core.xml",
"lib/netstandard2.0/it/FSharp.Core.resources.dll",
"lib/netstandard2.0/ja/FSharp.Core.resources.dll",
"lib/netstandard2.0/ko/FSharp.Core.resources.dll",
"lib/netstandard2.0/pl/FSharp.Core.resources.dll",
"lib/netstandard2.0/pt-BR/FSharp.Core.resources.dll",
"lib/netstandard2.0/ru/FSharp.Core.resources.dll",
"lib/netstandard2.0/tr/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hans/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hant/FSharp.Core.resources.dll",
],
"net5.0": [
"lib/netstandard2.0/cs/FSharp.Core.resources.dll",
"lib/netstandard2.0/de/FSharp.Core.resources.dll",
"lib/netstandard2.0/es/FSharp.Core.resources.dll",
"lib/netstandard2.0/fr/FSharp.Core.resources.dll",
"lib/netstandard2.0/FSharp.Core.dll",
"lib/netstandard2.0/FSharp.Core.xml",
"lib/netstandard2.0/it/FSharp.Core.resources.dll",
"lib/netstandard2.0/ja/FSharp.Core.resources.dll",
"lib/netstandard2.0/ko/FSharp.Core.resources.dll",
"lib/netstandard2.0/pl/FSharp.Core.resources.dll",
"lib/netstandard2.0/pt-BR/FSharp.Core.resources.dll",
"lib/netstandard2.0/ru/FSharp.Core.resources.dll",
"lib/netstandard2.0/tr/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hans/FSharp.Core.resources.dll",
"lib/netstandard2.0/zh-Hant/FSharp.Core.resources.dll",
],
},
)
nuget_package(
name = "protobuf.fsharp",
package = "protobuf.fsharp",
version = "0.1.3",
sha256 = "80765ef815e39bde8d61ed5279073ee3d0b443e419fd39ced6bfdd07698973cd",
core_lib = {
"netcoreapp2.0": "lib/netstandard2.0/Protobuf.FSharp.dll",
"netcoreapp2.1": "lib/netstandard2.0/Protobuf.FSharp.dll",
"netcoreapp2.2": "lib/netstandard2.0/Protobuf.FSharp.dll",
"netcoreapp3.0": "lib/netstandard2.0/Protobuf.FSharp.dll",
"netcoreapp3.1": "lib/netstandard2.0/Protobuf.FSharp.dll",
"net5.0": "lib/netstandard2.0/Protobuf.FSharp.dll",
},
core_deps = {
"netcoreapp2.0": [
"@fsharp.core//:netcoreapp2.0_core",
"@google.protobuf//:netcoreapp2.0_core",
],
"netcoreapp2.1": [
"@fsharp.core//:netcoreapp2.1_core",
"@google.protobuf//:netcoreapp2.1_core",
],
"netcoreapp2.2": [
"@fsharp.core//:netcoreapp2.2_core",
"@google.protobuf//:netcoreapp2.2_core",
],
"netcoreapp3.0": [
"@fsharp.core//:netcoreapp3.0_core",
"@google.protobuf//:netcoreapp3.0_core",
],
"netcoreapp3.1": [
"@fsharp.core//:netcoreapp3.1_core",
"@google.protobuf//:netcoreapp3.1_core",
],
"net5.0": [
"@fsharp.core//:net5.0_core",
"@google.protobuf//:net5.0_core",
],
},
core_files = {
"netcoreapp2.0": [
"lib/netstandard2.0/Protobuf.FSharp.dll",
],
"netcoreapp2.1": [
"lib/netstandard2.0/Protobuf.FSharp.dll",
],
"netcoreapp2.2": [
"lib/netstandard2.0/Protobuf.FSharp.dll",
],
"netcoreapp3.0": [
"lib/netstandard2.0/Protobuf.FSharp.dll",
],
"netcoreapp3.1": [
"lib/netstandard2.0/Protobuf.FSharp.dll",
],
"net5.0": [
"lib/netstandard2.0/Protobuf.FSharp.dll",
],
},
)
### End of generated by the tool
dotnet_nuget_new(
name = "grpc-fsharp",
build_file_content = """
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_import_binary", "core_import_library")
core_import_library(
name = "Protobuf.FSharp.dll",
src = select(
{
"@io_bazel_rules_dotnet//dotnet/toolchain:2.1.200_config": "tools/netcoreapp2.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.1.502_config": "tools/netcoreapp2.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.1.503_config": "tools/netcoreapp2.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.2.101_config": "tools/netcoreapp2.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.2.402_config": "tools/netcoreapp2.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:3.0.100_config": "tools/netcoreapp2.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:3.1.100_config": "tools/netcoreapp3.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:3.1.407_config": "tools/netcoreapp3.1/any/Protobuf.FSharp.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:5.0.201_config": "tools/net5.0/any/Protobuf.FSharp.dll",
},
),
version = "0.1.3",
deps = [
"@fsharp.core//:lib",
"@google.protobuf//:lib",
],
)
core_import_binary(
name = "bin",
src = select(
{
"@io_bazel_rules_dotnet//dotnet/toolchain:2.1.200_config": "tools/netcoreapp2.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.1.502_config": "tools/netcoreapp2.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.1.503_config": "tools/netcoreapp2.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.2.101_config": "tools/netcoreapp2.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:2.2.402_config": "tools/netcoreapp2.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:3.0.100_config": "tools/netcoreapp2.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:3.1.100_config": "tools/netcoreapp3.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:3.1.407_config": "tools/netcoreapp3.1/any/FSharp.GrpcCodeGenerator.dll",
"@io_bazel_rules_dotnet//dotnet/toolchain:5.0.201_config": "tools/net5.0/any/FSharp.GrpcCodeGenerator.dll",
},
),
deps = [":Protobuf.FSharp.dll"],
version = "0.1.5",
visibility = ["//visibility:public"],
)
""",
package = "grpc-fsharp",
version = "0.1.5",
sha256 = "f5577eaa2e092c739a9b92f9574461ae6839ee1c59c9c0129ef561a2ec2ff563",
)
| 46.506536
| 126
| 0.562223
| 2,986
| 28,462
| 5.27361
| 0.052579
| 0.152728
| 0.181876
| 0.115832
| 0.860481
| 0.840605
| 0.819331
| 0.780403
| 0.740014
| 0.694799
| 0
| 0.073978
| 0.292355
| 28,462
| 611
| 127
| 46.582651
| 0.70786
| 0.027475
| 0
| 0.66782
| 1
| 0.031142
| 0.627835
| 0.550038
| 0
| 0
| 0
| 0
| 0
| 1
| 0.00692
| true
| 0.00173
| 0.00519
| 0
| 0.012111
| 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
| 1
| 0
| 1
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
|
0
| 11
|
e9f03a9cca620d53bee93ec7ba520f33c0adc59f
| 24,895
|
py
|
Python
|
tests/ut/python/mindrecord/test_tfrecord_to_mr.py
|
GuoSuiming/mindspore
|
48afc4cfa53d970c0b20eedfb46e039db2a133d5
|
[
"Apache-2.0"
] | 3,200
|
2020-02-17T12:45:41.000Z
|
2022-03-31T20:21:16.000Z
|
tests/ut/python/mindrecord/test_tfrecord_to_mr.py
|
forwhat461/mindspore
|
59a277756eb4faad9ac9afcc7fd526e8277d4994
|
[
"Apache-2.0"
] | 176
|
2020-02-12T02:52:11.000Z
|
2022-03-28T22:15:55.000Z
|
tests/ut/python/mindrecord/test_tfrecord_to_mr.py
|
forwhat461/mindspore
|
59a277756eb4faad9ac9afcc7fd526e8277d4994
|
[
"Apache-2.0"
] | 621
|
2020-03-09T01:31:41.000Z
|
2022-03-30T03:43:19.000Z
|
# Copyright 2020 Huawei Technologies Co., Ltd.
#
# 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.
"""test tfrecord to mindrecord tool"""
import collections
from importlib import import_module
import os
from string import punctuation
import numpy as np
import pytest
from mindspore import log as logger
from mindspore.mindrecord import FileReader
from mindspore.mindrecord import TFRecordToMR
SupportedTensorFlowVersion = '1.13.0-rc1'
try:
tf = import_module("tensorflow") # just used to convert tfrecord to mindrecord
except ModuleNotFoundError:
logger.warning("tensorflow module not found.")
tf = None
TFRECORD_DATA_DIR = "../data/mindrecord/testTFRecordData"
TFRECORD_FILE_NAME = "test.tfrecord"
MINDRECORD_FILE_NAME = "test.mindrecord"
PARTITION_NUM = 1
def cast_name(key):
"""
Cast schema names which containing special characters to valid names.
Here special characters means any characters in
'!"#$%&\'()*+,./:;<=>?@[\\]^`{|}~
Valid names can only contain a-z, A-Z, and 0-9 and _
Args:
key (str): original key that might contains special characters.
Returns:
str, casted key that replace the special characters with "_". i.e. if
key is "a b" then returns "a_b".
"""
special_symbols = set('{}{}'.format(punctuation, ' '))
special_symbols.remove('_')
new_key = ['_' if x in special_symbols else x for x in key]
casted_key = ''.join(new_key)
return casted_key
def verify_data(transformer, reader):
"""
Verify the data by read from mindrecord
If in 1.x.x version, use old version to receive that iteration
"""
if tf.__version__ < '2.0.0':
tf_iter = transformer.tfrecord_iterator_oldversion()
else:
tf_iter = transformer.tfrecord_iterator()
mr_iter = reader.get_next()
count = 0
for tf_item, mr_item in zip(tf_iter, mr_iter):
count = count + 1
assert len(tf_item) == len(mr_item)
for key, value in tf_item.items():
logger.info("key: {}, tfrecord: value: {}, mindrecord: value: {}".format(key, value,
mr_item[cast_name(key)]))
if isinstance(value, np.ndarray):
assert (value == mr_item[cast_name(key)]).all()
else:
assert value == mr_item[cast_name(key)]
assert count == 10
def generate_tfrecord():
def create_int_feature(values):
if isinstance(values, list):
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) # values: [int, int, int]
else:
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=[values])) # values: int
return feature
def create_float_feature(values):
if isinstance(values, list):
feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) # values: [float, float]
else:
feature = tf.train.Feature(float_list=tf.train.FloatList(value=[values])) # values: float
return feature
def create_bytes_feature(values):
if isinstance(values, bytes):
feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) # values: bytes
else:
# values: string
feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[bytes(values, encoding='utf-8')]))
return feature
writer = tf.io.TFRecordWriter(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
example_count = 0
for i in range(10):
file_name = "000" + str(i) + ".jpg"
image_bytes = bytes(str("aaaabbbbcccc" + str(i)), encoding="utf-8")
int64_scalar = i
float_scalar = float(i)
int64_list = [i, i+1, i+2, i+3, i+4, i+1234567890]
float_list = [float(i), float(i+1), float(i+2.8), float(i+3.2),
float(i+4.4), float(i+123456.9), float(i+98765432.1)]
features = collections.OrderedDict()
features["file_name"] = create_bytes_feature(file_name)
features["image_bytes"] = create_bytes_feature(image_bytes)
features["int64_scalar"] = create_int_feature(int64_scalar)
features["float_scalar"] = create_float_feature(float_scalar)
features["int64_list"] = create_int_feature(int64_list)
features["float_list"] = create_float_feature(float_list)
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
example_count += 1
writer.close()
logger.info("Write {} rows in tfrecord.".format(example_count))
def generate_tfrecord_with_special_field_name():
def create_int_feature(values):
if isinstance(values, list):
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) # values: [int, int, int]
else:
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=[values])) # values: int
return feature
def create_bytes_feature(values):
if isinstance(values, bytes):
feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[values])) # values: bytes
else:
# values: string
feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[bytes(values, encoding='utf-8')]))
return feature
writer = tf.io.TFRecordWriter(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
example_count = 0
for i in range(10):
label = i
image_bytes = bytes(str("aaaabbbbcccc" + str(i)), encoding="utf-8")
features = collections.OrderedDict()
features["image/class/label"] = create_int_feature(label)
features["image/encoded"] = create_bytes_feature(image_bytes)
tf_example = tf.train.Example(features=tf.train.Features(feature=features))
writer.write(tf_example.SerializeToString())
example_count += 1
writer.close()
logger.info("Write {} rows in tfrecord.".format(example_count))
def test_tfrecord_to_mindrecord():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([], tf.int64),
"float_scalar": tf.io.FixedLenFeature([], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
tfrecord_transformer.transform()
assert os.path.exists(MINDRECORD_FILE_NAME)
assert os.path.exists(MINDRECORD_FILE_NAME + ".db")
fr_mindrecord = FileReader(MINDRECORD_FILE_NAME)
verify_data(tfrecord_transformer, fr_mindrecord)
os.remove(MINDRECORD_FILE_NAME)
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_scalar_with_1():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([1], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
tfrecord_transformer.transform()
assert os.path.exists(MINDRECORD_FILE_NAME)
assert os.path.exists(MINDRECORD_FILE_NAME + ".db")
fr_mindrecord = FileReader(MINDRECORD_FILE_NAME)
verify_data(tfrecord_transformer, fr_mindrecord)
os.remove(MINDRECORD_FILE_NAME)
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_scalar_with_1_list_small_len_exception():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([1], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([2], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
with pytest.raises(ValueError):
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_list_with_diff_type_exception():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([1], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.float32),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
with pytest.raises(ValueError):
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_list_without_bytes_type():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([1], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict)
tfrecord_transformer.transform()
assert os.path.exists(MINDRECORD_FILE_NAME)
assert os.path.exists(MINDRECORD_FILE_NAME + ".db")
fr_mindrecord = FileReader(MINDRECORD_FILE_NAME)
verify_data(tfrecord_transformer, fr_mindrecord)
os.remove(MINDRECORD_FILE_NAME)
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_scalar_with_2_exception():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([2], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
with pytest.raises(ValueError):
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_scalar_string_with_1_exception():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([1], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([1], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
with pytest.raises(ValueError):
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_scalar_bytes_with_10_exception():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([10], tf.string),
"int64_scalar": tf.io.FixedLenFeature([1], tf.int64),
"float_scalar": tf.io.FixedLenFeature([1], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
with pytest.raises(ValueError):
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image_bytes"])
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_exception_bytes_fields_is_not_string_type():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([], tf.int64),
"float_scalar": tf.io.FixedLenFeature([], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
with pytest.raises(ValueError):
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["int64_list"])
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_exception_bytes_fields_is_not_list():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"file_name": tf.io.FixedLenFeature([], tf.string),
"image_bytes": tf.io.FixedLenFeature([], tf.string),
"int64_scalar": tf.io.FixedLenFeature([], tf.int64),
"float_scalar": tf.io.FixedLenFeature([], tf.float32),
"int64_list": tf.io.FixedLenFeature([6], tf.int64),
"float_list": tf.io.FixedLenFeature([7], tf.float32),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
with pytest.raises(ValueError):
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, "")
tfrecord_transformer.transform()
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
def test_tfrecord_to_mindrecord_with_special_field_name():
"""test transform tfrecord to mindrecord."""
if not tf or tf.__version__ < SupportedTensorFlowVersion:
# skip the test
logger.warning("Module tensorflow is not found or version wrong, \
please use pip install it / reinstall version >= {}.".format(SupportedTensorFlowVersion))
return
generate_tfrecord_with_special_field_name()
assert os.path.exists(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
feature_dict = {"image/class/label": tf.io.FixedLenFeature([], tf.int64),
"image/encoded": tf.io.FixedLenFeature([], tf.string),
}
if os.path.exists(MINDRECORD_FILE_NAME):
os.remove(MINDRECORD_FILE_NAME)
if os.path.exists(MINDRECORD_FILE_NAME + ".db"):
os.remove(MINDRECORD_FILE_NAME + ".db")
tfrecord_transformer = TFRecordToMR(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME),
MINDRECORD_FILE_NAME, feature_dict, ["image/encoded"])
tfrecord_transformer.transform()
assert os.path.exists(MINDRECORD_FILE_NAME)
assert os.path.exists(MINDRECORD_FILE_NAME + ".db")
fr_mindrecord = FileReader(MINDRECORD_FILE_NAME)
verify_data(tfrecord_transformer, fr_mindrecord)
os.remove(MINDRECORD_FILE_NAME)
os.remove(MINDRECORD_FILE_NAME + ".db")
os.remove(os.path.join(TFRECORD_DATA_DIR, TFRECORD_FILE_NAME))
| 43.675439
| 116
| 0.657321
| 3,011
| 24,895
| 5.190634
| 0.078047
| 0.078316
| 0.119777
| 0.061936
| 0.842088
| 0.828588
| 0.821934
| 0.818351
| 0.818351
| 0.818351
| 0
| 0.014109
| 0.22848
| 24,895
| 569
| 117
| 43.752197
| 0.799604
| 0.076361
| 0
| 0.766585
| 0
| 0
| 0.055758
| 0.001533
| 0
| 0
| 0
| 0
| 0.056511
| 1
| 0.04914
| false
| 0
| 0.02457
| 0
| 0.115479
| 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
|
1835d6a3b92f018f29c9b99ac6f2080c57d7c699
| 1,320
|
py
|
Python
|
mi_daniel.py
|
2218084076/hotpoor_autoclick_xhs
|
a52446ba691ac19e43410a465dc63f940c0e444d
|
[
"Apache-2.0"
] | 1
|
2021-12-21T10:42:46.000Z
|
2021-12-21T10:42:46.000Z
|
mi_daniel.py
|
2218084076/hotpoor_autoclick_xhs
|
a52446ba691ac19e43410a465dc63f940c0e444d
|
[
"Apache-2.0"
] | null | null | null |
mi_daniel.py
|
2218084076/hotpoor_autoclick_xhs
|
a52446ba691ac19e43410a465dc63f940c0e444d
|
[
"Apache-2.0"
] | null | null | null |
import os
import time
import pyautogui
n=1
while True:
time.sleep(5)
# os.system("adb -s 869e65410721 shell input tap 283 500")
# time.sleep(1)
# os.system("adb -s 869e65410721 shell input tap 1012 155")
# time.sleep(1)
# os.system("adb -s 869e65410721 shell input tap 324 1997")
pyautogui.click(1538,336)
time.sleep(1)
pyautogui.hotkey('ctrl','a')
time.sleep(1)
pyautogui.hotkey('ctrl','v')
time.sleep(1)
pyautogui.click(1400,397)
time.sleep(20)
print(n)
# pyautogui.click(1536,251)
# time.sleep(2)
# os.system("adb -s 869e65410721 shell input tap 71 120")
# time.sleep(1)
# os.system("adb -s 869e65410721 shell input tap 263 1457")
# time.sleep(1)
# os.system("adb -s 869e65410721 shell input tap 1012 155")
# time.sleep(1)
# os.system("adb -s 869e65410721 shell input tap 324 1997")
pyautogui.click(1538,336)
time.sleep(1)
pyautogui.hotkey('ctrl', 'a')
time.sleep(1)
pyautogui.hotkey('ctrl','v')
time.sleep(1)
pyautogui.click(1400,397)
time.sleep(20)
# pyautogui.click(1536, 251)
# time.sleep(2)
# os.system("adb -s 869e65410721 shell input tap 71 120")
# time.sleep(2)
# os.system("adb -s 869e65410721 shell input swipe 528 1926 528 262 1000")
print(n)
n+=1
| 28.085106
| 78
| 0.635606
| 200
| 1,320
| 4.195
| 0.23
| 0.18236
| 0.131108
| 0.128725
| 0.877235
| 0.877235
| 0.877235
| 0.877235
| 0.833135
| 0.833135
| 0
| 0.223953
| 0.22197
| 1,320
| 47
| 79
| 28.085106
| 0.592989
| 0.527273
| 0
| 0.72
| 0
| 0
| 0.033058
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.12
| 0
| 0.12
| 0.08
| 0
| 0
| 0
| null | 0
| 0
| 0
| 1
| 1
| 1
| 1
| 1
| 1
| 0
| 1
| 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
|
1851b7b04a769aa7d75ef65ded311cda5e18afc6
| 3,683
|
py
|
Python
|
parachuteCore/menulist.py
|
aguilarjose11/ParachuteTimeSheetTimeMngmntSystem
|
9cc6b179a114be930eb3c5abe86cd21e15a9db45
|
[
"MIT"
] | 1
|
2018-12-18T15:15:21.000Z
|
2018-12-18T15:15:21.000Z
|
parachuteCore/menulist.py
|
aguilarjose11/ParachuteTimeSheetTimeMngmntSystem
|
9cc6b179a114be930eb3c5abe86cd21e15a9db45
|
[
"MIT"
] | 3
|
2019-01-17T01:55:16.000Z
|
2019-02-21T16:27:35.000Z
|
parachuteCore/menulist.py
|
aguilarjose11/ParachuteTimeSheetTimeMngmntSystem
|
9cc6b179a114be930eb3c5abe86cd21e15a9db45
|
[
"MIT"
] | 1
|
2019-01-16T21:51:08.000Z
|
2019-01-16T21:51:08.000Z
|
# menulist.py contains all menus used in timesheet.py
from parachuteCore import menu
from parachuteCore.tstools import getcmdxandy, _Getch
# --- personalized classes ---
import sys
import os
import colorama
colorama.init(convert=True)
getch = _Getch()
class mainMenu(menu.Menu):
def getchoice(self, choice):
key = ord(getch())
if key == 72:
if choice > 0:
choice = choice - 1
sys.stdout.write("\033[{0};5H ".format(4 + (choice + 1)))
sys.stdout.write("\033[{0};5H->".format(4 + choice))
return choice
elif key == 80:
if choice < 2:
choice = choice + 1
sys.stdout.write("\033[{0};5H ".format(4 + (choice - 1)))
sys.stdout.write("\033[{0};5H->".format(4 + choice))
return choice
elif key == 27:
exit(0)
elif key == 13:
return str(choice)
else:
return choice
def menu(self):
os.system('cls')
sys.stdout.write("\t\t\t\033[38;2;20;10;100mWelcome to OU's Offline timesheets!\033[0m \n\n\n")
sys.stdout.write(" -> \033[32mLog In\033[0m\n")
sys.stdout.write("\t\033[32mRegister\033[0m\n")
sys.stdout.write("\t\033[32mexit\033[0m\n")
class registerMenu(menu.Menu):
def __init__(self):
pass
def getchoice(self, choice):
key = ord(getch())
if key == 72:
if choice > 0:
choice = choice - 1
sys.stdout.write("\033[{0};5H ".format(6 + (choice + 1)))
sys.stdout.write("\033[{0};5H->".format(6 + choice))
return choice
elif key == 80:
if choice < 4:
choice = choice + 1
sys.stdout.write("\033[{0};5H ".format(6 + (choice - 1)))
sys.stdout.write("\033[{0};5H->".format(6 + choice))
return choice
elif key == 27:
exit(0)
elif key == 13:
return str(choice)
else:
return choice
def menu(self):
os.system('cls')
sys.stdout.write("\t\t\t\033[34;1m User registration window\033[0m\n\n")
sys.stdout.write("\n\n\n")
sys.stdout.write(" -> \033[35;1mEmployee Name: \033[0m\n")
sys.stdout.write("\t\033[35;1mDepartment: \033[0m\n")
sys.stdout.write("\t\033[35;1mUsername: \033[0m\n")
sys.stdout.write("\t\033[35;1mPassword: \033[0m\n")
sys.stdout.write("\t\033[36;1mSubmit\033[0m\n")
class loginMenu(menu.Menu):
def __init__(self):
pass
def getchoice(self, choice):
key = ord(getch())
if key == 72:
if choice > 0:
choice = choice - 1
sys.stdout.write("\033[{0};5H ".format(6 + (choice + 1)))
sys.stdout.write("\033[{0};5H\033[33m->\033[0;0m".format(6 + choice))
return choice
elif key == 80:
if choice < 2:
choice = choice + 1
sys.stdout.write("\033[{0};5H ".format(6 + (choice - 1)))
sys.stdout.write("\033[{0};5H\033[33m->\033[0;0m".format(6 + choice))
return choice
elif key == 27:
exit(0)
elif key == 13:
return str(choice)
else:
return choice
def menu(self):
os.system('cls')
sys.stdout.write("\t\t\t\033[34;1m Log In window\033[0m\n\n")
sys.stdout.write("\n\n\n")
sys.stdout.write("\033[33m -> \033[0;0m\033[35;1mUsername: \033[0m\n")
sys.stdout.write("\t\033[35;1mPassword: \033[0m\n")
sys.stdout.write("\t\033[36;1mSubmit\033[0m\n")
| 32.026087
| 103
| 0.517513
| 501
| 3,683
| 3.784431
| 0.171657
| 0.132911
| 0.206751
| 0.134494
| 0.800633
| 0.795886
| 0.795886
| 0.785338
| 0.760021
| 0.735232
| 0
| 0.115706
| 0.317133
| 3,683
| 114
| 104
| 32.307018
| 0.638171
| 0.021721
| 0
| 0.760417
| 0
| 0.041667
| 0.204444
| 0.086389
| 0
| 0
| 0
| 0
| 0
| 1
| 0.083333
| false
| 0.041667
| 0.052083
| 0
| 0.291667
| 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
|
a1169fcb278ddb2687fddbbef49ffc47e4711b0e
| 63,650
|
py
|
Python
|
quark/tests/test_ipam.py
|
sumanthns/quark
|
4f0d00608827271439ee0c2dfc22729dbbb17763
|
[
"Apache-2.0"
] | null | null | null |
quark/tests/test_ipam.py
|
sumanthns/quark
|
4f0d00608827271439ee0c2dfc22729dbbb17763
|
[
"Apache-2.0"
] | null | null | null |
quark/tests/test_ipam.py
|
sumanthns/quark
|
4f0d00608827271439ee0c2dfc22729dbbb17763
|
[
"Apache-2.0"
] | null | null | null |
# Copyright (c) 2014 OpenStack Foundation
#
# 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.
import contextlib
import mock
import netaddr
from neutron.common import exceptions
from neutron.common import rpc
from oslo.config import cfg
from oslo.db import exception as db_exc
from quark.db import models
from quark import exceptions as q_exc
import quark.ipam
from quark.tests import test_base
class QuarkIpamBaseTest(test_base.TestBase):
def setUp(self):
super(QuarkIpamBaseTest, self).setUp()
patcher = mock.patch("neutron.common.rpc.messaging")
patcher.start()
self.addCleanup(patcher.stop)
rpc.init(mock.MagicMock())
self.ipam = quark.ipam.QuarkIpamANY()
self.reuse_after = cfg.CONF.QUARK.ipam_reuse_after
class FakeContext(object):
def __enter__(*args, **kwargs):
pass
def __exit__(*args, **kwargs):
pass
self.context.session.begin = FakeContext
self.context.session.add = mock.Mock()
class QuarkMacAddressAllocateDeallocated(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, mac_find=True):
address = dict(id=1, address=0)
mac_range = dict(id=1, first_address=0, last_address=255,
next_auto_assign_mac=0)
with contextlib.nested(
mock.patch("quark.db.api.mac_address_find"),
mock.patch("quark.db.api."
"mac_address_range_find_allocation_counts"),
mock.patch("quark.db.api.mac_address_update"),
mock.patch("quark.db.api.mac_address_create")
) as (addr_find, mac_range_count, mac_update, mac_create):
if mac_find:
addr_find.return_value = address
else:
addr_find.side_effect = [None, None]
mac_range_count.return_value = (mac_range, 0)
mac_create.return_value = address
yield mac_update, mac_create
def test_allocate_mac_address_find_deallocated(self):
with self._stubs(True) as (mac_update, mac_create):
self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertTrue(mac_update.called)
self.assertFalse(mac_create.called)
def test_allocate_mac_address_creates_new_mac(self):
with self._stubs(False) as (mac_update, mac_create):
self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertFalse(mac_update.called)
self.assertTrue(mac_create.called)
class QuarkNewMacAddressAllocation(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, addresses=None, ranges=None):
if not addresses:
addresses = [None]
with contextlib.nested(
mock.patch("quark.db.api.mac_address_find"),
mock.patch("quark.db.api."
"mac_address_range_find_allocation_counts"),
) as (mac_find, mac_range_count):
mac_find.side_effect = addresses
mac_range_count.return_value = ranges
yield
def test_allocate_new_mac_address_specific(self):
mar = dict(id=1, first_address=0, last_address=255,
next_auto_assign_mac=0)
with self._stubs(ranges=(mar, 0), addresses=[None, None]):
address = self.ipam.allocate_mac_address(self.context, 0, 0, 0,
mac_address=254)
self.assertEqual(address["address"], 254)
def test_allocate_new_mac_address_in_empty_range(self):
mar = dict(id=1, first_address=0, last_address=255,
next_auto_assign_mac=0)
with self._stubs(ranges=(mar, 0), addresses=[None, None]):
address = self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertEqual(address["address"], 0)
def test_allocate_new_mac_in_partially_allocated_range(self):
mar = dict(id=1, first_address=0, last_address=255,
next_auto_assign_mac=1)
with self._stubs(ranges=(mar, 0), addresses=[None, None]):
address = self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertEqual(address["address"], 1)
def test_allocate_mac_no_ranges_fails(self):
with self._stubs(ranges=[]):
with self.assertRaises(exceptions.MacAddressGenerationFailure):
self.ipam.allocate_mac_address(self.context, 0, 0, 0)
def test_allocate_mac_no_available_range_fails(self):
mar = dict(id=1, first_address=0, last_address=0,
next_auto_assign_mac=0)
ranges = [(mar, 0)]
with self._stubs(ranges=ranges):
with self.assertRaises(exceptions.MacAddressGenerationFailure):
self.ipam.allocate_mac_address(self.context, 0, 0, 0)
def test_allocate_mac_last_mac_in_range_closes_range(self):
mar = dict(id=1, first_address=0, last_address=1,
next_auto_assign_mac=1)
with self._stubs(ranges=(mar, 0), addresses=[None, None]):
address = self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertEqual(address["address"], 1)
self.assertEqual(mar["next_auto_assign_mac"], -1)
def test_allocate_mac_range_unexpectedly_filled_closes(self):
mar = dict(id=1, first_address=0, last_address=1,
next_auto_assign_mac=1)
with self._stubs(ranges=(mar, 4), addresses=[None, None]):
with self.assertRaises(exceptions.MacAddressGenerationFailure):
self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertEqual(mar["next_auto_assign_mac"], -1)
class QuarkNewMacAddressAllocationCreateConflict(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, addresses=None, ranges=None):
if not addresses:
addresses = [None]
with contextlib.nested(
mock.patch("quark.db.api.mac_address_find"),
mock.patch("quark.db.api.mac_address_create"),
mock.patch("quark.db.api."
"mac_address_range_find_allocation_counts"),
) as (mac_find, mac_create, mac_range_count):
mac_find.side_effect = [None, None]
mac_create.side_effect = addresses
mac_range_count.return_value = ranges
yield
def test_allocate_existing_mac_fails_and_retries(self):
mar = dict(id=1, first_address=0, last_address=255,
next_auto_assign_mac=0)
mac = dict(id=1, address=254)
with self._stubs(ranges=(mar, 0), addresses=[Exception, mac]):
address = self.ipam.allocate_mac_address(self.context, 0, 0, 0,
mac_address=254)
self.assertEqual(address["address"], 254)
class QuarkNewMacAddressReallocationDeadlocks(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, addresses=None, ranges=None):
if not addresses:
addresses = [None]
old_override = cfg.CONF.QUARK.mac_address_retry_max
cfg.CONF.set_override('mac_address_retry_max', 1, 'QUARK')
with contextlib.nested(
mock.patch("quark.db.api.mac_address_find"),
mock.patch("quark.db.api.mac_address_create"),
mock.patch("quark.db.api."
"mac_address_range_find_allocation_counts"),
) as (mac_find, mac_create, mac_range_count):
mac_find.side_effect = [Exception, None]
mac_create.side_effect = addresses
mac_range_count.return_value = ranges
yield mac_find
cfg.CONF.set_override('mac_address_retry_max', old_override, 'QUARK')
def test_reallocate_mac_deadlock_raises_retry(self):
mar = dict(id=1, first_address=0, last_address=255,
next_auto_assign_mac=0)
mac = dict(id=1, address=254)
with self._stubs(ranges=(mar, 0), addresses=[Exception, mac]) as (
mac_find):
with self.assertRaises(exceptions.MacAddressGenerationFailure):
self.ipam.allocate_mac_address(self.context, 0, 0, 0)
self.assertEqual(mac_find.call_count, 1)
class QuarkMacAddressDeallocation(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, mac):
with contextlib.nested(
mock.patch("quark.db.api.mac_address_find"),
mock.patch("quark.db.api.mac_address_update")
) as (mac_find,
mac_update):
mac_update.return_value = mac
mac_find.return_value = mac
yield mac_update
def test_deallocate_mac(self):
mac = dict(id=1, address=1)
with self._stubs(mac=mac) as mac_update:
self.ipam.deallocate_mac_address(self.context, mac["address"])
self.assertTrue(mac_update.called)
def test_deallocate_mac_mac_not_found_fails(self):
with self._stubs(mac=None) as mac_update:
self.assertRaises(exceptions.NotFound,
self.ipam.deallocate_mac_address, self.context,
0)
self.assertFalse(mac_update.called)
class QuarkIPAddressDeallocation(QuarkIpamBaseTest):
def test_deallocate_ips_by_port(self):
port_dict = dict(ip_addresses=[], device_id="foo")
addr_dict = dict(subnet_id=1, address_readable=None,
created_at=None, used_by_tenant_id=1)
port = models.Port()
port.update(port_dict)
addr = models.IPAddress()
addr.update(addr_dict)
port["ip_addresses"].append(addr)
self.ipam.deallocate_ips_by_port(self.context, port)
# ORM takes care of other model if one model is modified
self.assertTrue(len(addr["ports"]) == 0 or
len(port["ip_addresses"]) == 0)
self.assertTrue(addr["deallocated"])
def test_deallocate_ip_address_specific_ip(self):
port_dict = dict(ip_addresses=[], device_id="foo")
addr_dict = dict(subnet_id=1, address_readable="0.0.0.0",
created_at=None, used_by_tenant_id=1,
address=0)
port = models.Port()
port.update(port_dict)
addr = models.IPAddress()
addr.update(addr_dict)
port["ip_addresses"].append(addr)
to_delete = netaddr.IPAddress(addr["address"])
self.ipam.deallocate_ips_by_port(self.context, port,
ip_address=to_delete)
# ORM takes care of other model if one model is modified
self.assertTrue(len(addr["ports"]) == 0 or
len(port["ip_addresses"]) == 0)
self.assertTrue(addr["deallocated"])
def test_deallocate_ip_address_specific_ip_not_on_port_noop(self):
port_dict = dict(ip_addresses=[], device_id="foo")
addr_dict = dict(subnet_id=1, address_readable="0.0.0.0",
created_at=None, used_by_tenant_id=1,
address=0)
port = models.Port()
port.update(port_dict)
addr = models.IPAddress()
addr.update(addr_dict)
port["ip_addresses"].append(addr)
to_delete = netaddr.IPAddress(1)
self.ipam.deallocate_ips_by_port(self.context, port,
ip_address=to_delete)
# ORM takes care of other model if one model is modified
self.assertTrue(len(addr["ports"]) == 1 or
len(port["ip_addresses"]) == 1)
self.assertFalse(addr["deallocated"])
def test_deallocate_ip_address_multiple_ports_no_deallocation(self):
port_dict = dict(ip_addresses=[])
addr_dict = dict(deallocated=False)
port = models.Port()
port.update(port_dict)
addr = models.IPAddress()
addr.update(addr_dict)
port["ip_addresses"].append(addr)
addr["ports"].append(port)
self.ipam.deallocate_ips_by_port(self.context, port)
# ORM takes care of other model if one model is modified
self.assertTrue(len(addr["ports"]) == 1 or
len(port["ip_addresses"]) == 0)
self.assertFalse(addr["deallocated"])
class QuarkIpamTestBothIpAllocation(QuarkIpamBaseTest):
def setUp(self):
super(QuarkIpamTestBothIpAllocation, self).setUp()
self.ipam = quark.ipam.QuarkIpamBOTH()
self.v6_fip = netaddr.IPAddress("feed::")
self.v6_lip = netaddr.IPAddress("feed::ff:ffff")
self.v46_val = netaddr.IPAddress("::ffff:0.0.0.4").value
@contextlib.contextmanager
def _stubs(self, addresses=None, subnets=None):
if not addresses:
addresses = [None, None]
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.subnet_find_allocation_counts"),
mock.patch("quark.db.api.subnet_find")
) as (addr_find, subnet_alloc_find, subnet_find):
addr_find.side_effect = addresses
if subnets and len(subnets[0]):
subnet_find.return_value = [subnets[0][0][0]]
subnet_alloc_find.side_effect = subnets
yield
def test_allocate_new_ip_address_two_empty_subnets(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=1,
ip_policy=None)
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
with self._stubs(subnets=[[(subnet4, 0)], [(subnet6, 0)]],
addresses=[None, None, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(address[0]["address"],
netaddr.IPAddress('::ffff:0.0.0.1').value)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], self.v6_fip.value + 1)
self.assertEqual(address[1]["version"], 6)
def test_allocate_new_ip_address_one_v4_subnet_open(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=2,
ip_policy=None)
with self._stubs(subnets=[[(subnet4, 0)], []],
addresses=[None, None, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 1)
self.assertEqual(address[0]["version"], 4)
def test_allocate_new_ip_address_one_v6_subnet_open(self):
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
with self._stubs(subnets=[[], [(subnet6, 0)]],
addresses=[None, None, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 1)
self.assertEqual(address[0]["version"], 6)
def test_allocate_provided_ip_address_one_v6_subnet_open(self):
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
with self._stubs(subnets=[[], [(subnet6, 0)]],
addresses=[None, None, None, None]):
address = []
ip_address = netaddr.IPAddress("feed::13")
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
ip_addresses=[ip_address])
self.assertEqual(len(address), 1)
self.assertEqual(ip_address,
netaddr.IPAddress(address[0]['address']))
def test_allocate_new_ip_address_no_avail_subnets(self):
with self._stubs(subnets=[[], []],
addresses=[None, None, None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0)
def test_reallocate_deallocated_v4_ip(self):
network = netaddr.IPNetwork("feed::/104")
fip = network.first
lip = network.last
subnet6 = dict(id=1, first_ip=fip, last_ip=lip,
cidr="feed::/104", ip_version=6,
next_auto_assign_ip=fip + 1,
ip_policy=None)
network = netaddr.IPNetwork("0.0.0.0/24")
first = network.ipv6().first
last = network.ipv6().last
target_ip = first + 4
address = models.IPAddress()
address["address"] = target_ip
address["version"] = 4
address["subnet"] = models.Subnet(cidr="0.0.0.0/24", first_ip=first,
last_ip=last,
next_auto_assign_ip=first)
with self._stubs(subnets=[[(subnet6, 0)]],
addresses=[address, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], target_ip)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], fip + 1)
self.assertEqual(address[1]["version"], 6)
def test_reallocate_deallocated_v4_ip_passed_subnets(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=None)
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
address = models.IPAddress()
address["address"] = self.v46_val
address["version"] = 4
address["subnet"] = models.Subnet(cidr="0.0.0.0/24")
with self._stubs(subnets=[[(subnet6, 0)]],
addresses=[address, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
subnets=[subnet4['id']])
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], self.v46_val)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], self.v6_fip.value + 1)
self.assertEqual(address[1]["version"], 6)
def test_reallocate_deallocated_v4_ip_shared_net(self):
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
address = models.IPAddress()
address["address"] = self.v46_val
address["version"] = 4
address["subnet"] = models.Subnet(cidr="0.0.0.0/24")
with self._stubs(subnets=[[(subnet6, 0)]],
addresses=[address, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
segment_id="cell01")
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], self.v46_val)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], self.v6_fip.value + 1)
self.assertEqual(address[1]["version"], 6)
def test_reallocate_deallocated_v4_ip_shared_net_no_subs_raises(self):
with self._stubs(subnets=[], addresses=[None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0,
segment_id="cell01")
def test_reallocate_deallocated_v4_ip_no_avail_subnets(self):
address = models.IPAddress()
address["address"] = self.v46_val
address["version"] = 4
address["subnet"] = models.Subnet(cidr="0.0.0.0/24")
with self._stubs(subnets=[[]],
addresses=[address, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 1)
self.assertEqual(address[0]["address"], self.v46_val)
self.assertEqual(address[0]["version"], 4)
def test_reallocate_deallocated_v6_ip(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=1,
ip_policy=None)
address = models.IPAddress()
address["address"] = netaddr.IPAddress(4).ipv6()
address["version"] = 6
address["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
with self._stubs(subnets=[[(subnet4, 0)]],
addresses=[address, None, None]):
addresses = []
self.ipam.allocate_ip_address(self.context, addresses, 0, 0, 0)
self.assertEqual(len(addresses), 2)
self.assertEqual(addresses[0]["address"], address["address"])
self.assertEqual(addresses[0]["version"], 6)
self.assertEqual(addresses[1]["address"],
netaddr.IPAddress('::ffff:0.0.0.1').value)
self.assertEqual(addresses[1]["version"], 4)
def test_reallocate_v6_with_mac_generates_rfc_address(self):
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=0,
ip_policy=None)
address = models.IPAddress()
address["address"] = self.v46_val
address["version"] = 4
address["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
mac = models.MacAddress()
mac["address"] = netaddr.EUI("AA:BB:CC:DD:EE:FF")
with self._stubs(subnets=[[(subnet6, 0)]],
addresses=[address, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
mac_address=mac)
generated_v6 = netaddr.IPAddress("feed::a8bb:ccff:fedd:eeff")
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], self.v46_val)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], generated_v6.value)
self.assertEqual(address[1]["version"], 6)
def test_reallocate_v6_with_mac_generates_exceeds_limit_raises(self):
subnet6 = dict(cidr="feed::/104",
first_ip=self.v6_fip.value,
id=1,
ip_version=6,
ip_policy=None,
last_ip=self.v6_lip.value,
next_auto_assign_ip=0)
address = models.IPAddress()
address["address"] = self.v46_val
address["version"] = 4
address["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
mac = models.MacAddress()
mac["address"] = netaddr.EUI("AA:BB:CC:DD:EE:FF")
old_override = cfg.CONF.QUARK.v6_allocation_attempts
cfg.CONF.set_override('v6_allocation_attempts', 0, 'QUARK')
with self._stubs(subnets=[[(subnet6, 0)]],
addresses=[address, None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0,
mac_address=mac)
cfg.CONF.set_override('v6_allocation_attempts', old_override, 'QUARK')
def test_reallocate_deallocated_v6_ip_as_string_address(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=1,
ip_policy=None)
address = models.IPAddress()
address["address"] = str(self.v46_val)
address["version"] = 6
address["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
with self._stubs(subnets=[[(subnet4, 0)]],
addresses=[address, None, None]):
addresses = []
self.ipam.allocate_ip_address(self.context, addresses, 0, 0, 0)
self.assertEqual(len(addresses), 2)
self.assertEqual(addresses[0]["address"], str(self.v46_val))
self.assertEqual(addresses[0]["version"], 6)
self.assertEqual(addresses[1]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
self.assertEqual(addresses[1]["version"], 4)
def test_reallocate_deallocated_v4_v6(self):
address1 = models.IPAddress()
address1["address"] = self.v46_val
address1["version"] = 4
address1["subnet"] = models.Subnet(cidr="0.0.0.0/24")
address2 = models.IPAddress()
address2["address"] = netaddr.IPAddress(42).ipv6()
address2["version"] = 6
address2["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
with self._stubs(subnets=[[]],
addresses=[address1, address2]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], self.v46_val)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], address2["address"])
self.assertEqual(address[1]["version"], 6)
class QuarkIpamTestBothRequiredIpAllocation(QuarkIpamBaseTest):
def setUp(self):
super(QuarkIpamTestBothRequiredIpAllocation, self).setUp()
self.ipam = quark.ipam.QuarkIpamBOTHREQ()
self.v6_fip = netaddr.IPAddress("feed::")
self.v6_lip = netaddr.IPAddress("feed::ff:ffff")
self.v46_val = netaddr.IPAddress("::ffff:0.0.0.4").value
@contextlib.contextmanager
def _stubs(self, addresses=None, subnets=None):
if not addresses:
addresses = [None, None]
self.context.session.add = mock.Mock()
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.subnet_find_allocation_counts")
) as (addr_find, subnet_find):
addr_find.side_effect = addresses
subnet_find.side_effect = subnets
yield
def test_allocate_new_ip_address_two_empty_subnets(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=1,
ip_policy=None)
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
with self._stubs(subnets=[[(subnet4, 0)], [(subnet6, 0)]],
addresses=[None, None, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], self.v6_fip.value + 1)
self.assertEqual(address[1]["version"], 6)
def test_allocate_new_ip_address_one_v4_subnet_open(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=2,
ip_policy=None)
with self._stubs(subnets=[[(subnet4, 0)], []],
addresses=[None, None, None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(self.context, [], 0, 0, 0)
def test_allocate_new_ip_address_one_v6_subnet_open(self):
subnet6 = dict(id=1, first_ip=self.v6_fip, last_ip=self.v6_lip,
cidr="feed::/104", ip_version=6,
next_auto_assign_ip=2,
ip_policy=None)
with self._stubs(subnets=[[], [(subnet6, 0)]],
addresses=[None, None, None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(self.context, [], 0, 0, 0)
def test_allocate_new_ip_address_no_avail_subnets(self):
with self._stubs(subnets=[[], []],
addresses=[None, None, None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0)
def test_reallocate_deallocated_v4_ip(self):
subnet6 = dict(id=66, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=self.v6_fip.value + 1,
ip_policy=None)
address = models.IPAddress()
address["address"] = 4
address["version"] = 4
address["subnet"] = models.Subnet(cidr="0.0.0.0/24")
with self._stubs(subnets=[[(subnet6, 0)]],
addresses=[address, None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], 4)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], self.v6_fip.value + 1)
self.assertEqual(address[1]["version"], 6)
def test_reallocate_deallocated_v6_ip(self):
subnet4 = dict(id=1, first_ip=0, last_ip=255, cidr="0.0.0.0/24",
ip_version=4, next_auto_assign_ip=1,
ip_policy=None)
address = models.IPAddress()
address["address"] = 4
address["version"] = 6
address["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
with self._stubs(subnets=[[(subnet4, 0)]],
addresses=[address, None, None]):
addresses = []
self.ipam.allocate_ip_address(self.context, addresses, 0, 0, 0)
self.assertEqual(len(addresses), 2)
self.assertEqual(addresses[0]["address"], address["address"])
self.assertEqual(addresses[0]["version"], 6)
self.assertEqual(addresses[1]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
self.assertEqual(addresses[1]["version"], 4)
def test_reallocate_deallocated_v4_v6(self):
address1 = models.IPAddress()
address1["address"] = self.v46_val
address1["version"] = 4
address1["subnet"] = models.Subnet(cidr="0.0.0.0/24")
address2 = models.IPAddress()
address2["address"] = 42
address2["version"] = 6
address2["subnet"] = models.Subnet(cidr="::ffff:0:0/96")
with self._stubs(subnets=[[]],
addresses=[address1, address2]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(len(address), 2)
self.assertEqual(address[0]["address"], self.v46_val)
self.assertEqual(address[0]["version"], 4)
self.assertEqual(address[1]["address"], address2["address"])
self.assertEqual(address[1]["version"], 6)
def test_allocate_allocate_ip_unsatisfied_strategy_fails(self):
old_override = cfg.CONF.QUARK.ip_address_retry_max
cfg.CONF.set_override('ip_address_retry_max', 1, 'QUARK')
subnet4 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=1,
ip_policy=None)
subnet6 = dict(id=1, first_ip=self.v6_fip.value,
last_ip=self.v6_lip.value, cidr="feed::/104",
ip_version=6, next_auto_assign_ip=-2,
ip_policy=dict(
size=2,
exclude=[
models.IPPolicyCIDR(cidr="feed::/128"),
models.IPPolicyCIDR(cidr="feed::ff:ffff/128")]))
with self._stubs(subnets=[[(subnet4, 0)], [(subnet6, 0)]],
addresses=[None, None, None, None]):
address = []
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
cfg.CONF.set_override('ip_address_retry_max', old_override, 'QUARK')
class QuarkIpamBoth(QuarkIpamBaseTest):
def setUp(self):
super(QuarkIpamBoth, self).setUp()
self.ipam = quark.ipam.QuarkIpamBOTH()
self.v4 = models.IPAddress()
self.v4["version"] = 4
self.v6 = models.IPAddress()
self.v6["version"] = 6
def test_is_strategy_satisfied_v4_only_fails(self):
self.assertFalse(self.ipam.is_strategy_satisfied([self.v4, None]))
def test_is_strategy_satisfied_v6_only_fails(self):
self.assertFalse(self.ipam.is_strategy_satisfied([None, self.v6]))
def test_is_strategy_satisfied_none_fails(self):
self.assertFalse(self.ipam.is_strategy_satisfied([None, None]))
def test_is_strategy_satisfied_both_passes(self):
self.assertTrue(self.ipam.is_strategy_satisfied([self.v4, self.v6]))
class QuarkIpamBothRequired(QuarkIpamBaseTest):
def setUp(self):
super(QuarkIpamBothRequired, self).setUp()
self.ipam = quark.ipam.QuarkIpamBOTHREQ()
self.v4 = models.IPAddress()
self.v4["version"] = 4
self.v6 = models.IPAddress()
self.v6["version"] = 6
def test_is_strategy_satisfied_v4_only_fails(self):
self.assertFalse(self.ipam.is_strategy_satisfied([self.v4, None]))
def test_is_strategy_satisfied_v6_only_fails(self):
self.assertFalse(self.ipam.is_strategy_satisfied([None, self.v6]))
def test_is_strategy_satisfied_none_fails(self):
self.assertFalse(self.ipam.is_strategy_satisfied([None, None]))
def test_is_strategy_satisfied_both_passes(self):
self.assertTrue(self.ipam.is_strategy_satisfied([self.v4, self.v6]))
class QuarkIpamAllocateFromV6Subnet(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, policies=None, ip_address=None, deallocated=True):
self.context.session.add = mock.Mock()
ip_mod = None
if ip_address:
ip_mod = models.IPAddress()
ip_mod["address"] = ip_address.value
ip_mod["deallocated"] = deallocated
with contextlib.nested(
mock.patch("quark.db.models.IPPolicy.get_ip_policy_cidrs"),
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.ip_address_create"),
mock.patch("quark.db.api.ip_address_update")
) as (policy_find, ip_address_find, ip_create, ip_update):
policy_find.return_value = policies
ip_address_find.return_value = ip_mod
ip_create.return_value = ip_mod
ip_update.return_value = ip_mod
yield policy_find, ip_address_find, ip_create, ip_update
def test_reallocate_v6_with_mac_fails_policy_raises(self):
port_id = "945af340-ed34-4fec-8c87-853a2df492b4"
subnet6 = dict(id=1, first_ip=0, last_ip=0,
cidr="feed::/104", ip_version=6,
next_auto_assign_ip=0,
ip_policy=None)
mac = models.MacAddress()
mac["address"] = netaddr.EUI("AA:BB:CC:DD:EE:FF")
old_override = cfg.CONF.QUARK.v6_allocation_attempts
cfg.CONF.set_override('v6_allocation_attempts', 1, 'QUARK')
policy = netaddr.IPSet(["feed::/64"])
with self._stubs(policies=policy):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam._allocate_from_v6_subnet(self.context, 0, subnet6,
port_id, self.reuse_after,
mac_address=mac)
cfg.CONF.set_override('v6_allocation_attempts', old_override, 'QUARK')
def test_reallocate_v6_with_mac(self):
port_id = "945af340-ed34-4fec-8c87-853a2df492b4"
subnet6 = dict(id=1, first_ip=0, last_ip=0,
cidr="feed::/104", ip_version=6,
next_auto_assign_ip=0,
ip_policy=None)
mac = models.MacAddress()
mac["address"] = netaddr.EUI("AA:BB:CC:DD:EE:FF")
old_override = cfg.CONF.QUARK.v6_allocation_attempts
cfg.CONF.set_override('v6_allocation_attempts', 1, 'QUARK')
ip_address = netaddr.IPAddress("fe80::")
with self._stubs(policies=[], ip_address=ip_address) as (
policy_find, ip_find, ip_create, ip_update):
a = self.ipam._allocate_from_v6_subnet(self.context, 0, subnet6,
port_id, self.reuse_after,
mac_address=mac)
self.assertEqual(ip_address.value, a["address"])
self.assertEqual(1, ip_update.call_count)
self.assertEqual(0, ip_create.call_count)
cfg.CONF.set_override('v6_allocation_attempts', old_override, 'QUARK')
def test_allocate_v6_with_ip_and_no_mac(self):
fip = netaddr.IPAddress('fe80::')
ip_address = netaddr.IPAddress("fe80::7")
lip = netaddr.IPAddress('fe80::FF:FFFF')
port_id = "945af340-ed34-4fec-8c87-853a2df492b4"
subnet6 = dict(id=1, first_ip=fip, last_ip=lip,
cidr="feed::/104", ip_version=6,
next_auto_assign_ip=fip, ip_policy=None)
with self._stubs(policies=[], ip_address=ip_address) as (
policy_find, ip_find, ip_create, ip_update):
a = self.ipam._allocate_from_v6_subnet(self.context, 0, subnet6,
port_id, self.reuse_after,
ip_address=ip_address)
self.assertEqual(a['address'], ip_address.value)
class QuarkIpamAllocateV6IPGeneration(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, ip_addresses, create_ip_return, update_ip_return):
self.context.session.add = mock.Mock()
ip_mods = []
for ip in ip_addresses:
ip_mod = models.IPAddress()
ip_mod.update(ip)
ip_mods.append(ip_mod)
old_override = cfg.CONF.QUARK.v6_allocation_attempts
cfg.CONF.set_override('v6_allocation_attempts', 2, 'QUARK')
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.ip_address_create"),
mock.patch("quark.db.api.ip_address_update")
) as (ip_address_find, ip_create, ip_update):
ip_address_find.side_effect = ip_mods
ip_create.return_value = create_ip_return
ip_update.return_value = update_ip_return
yield ip_address_find, ip_create, ip_update
cfg.CONF.set_override('v6_allocation_attempts', old_override, 'QUARK')
def test_reallocate_v6_with_mac_already_exists(self):
port_id = "945af340-ed34-4fec-8c87-853a2df492b4"
subnet6 = dict(id=1, first_ip=0, last_ip=0,
cidr="feed::/104", ip_version=6,
next_auto_assign_ip=0,
ip_policy=None)
ip1 = {"address": netaddr.IPAddress("fe80::").value,
"deallocated": False}
ip2 = {"address": netaddr.IPAddress("fe81::").value,
"deallocated": True}
mac = models.MacAddress()
mac["address"] = netaddr.EUI("AA:BB:CC:DD:EE:FF")
with self._stubs([ip1, ip2], ip2, ip2) as (
ip_find, ip_create, ip_update):
self.ipam._allocate_from_v6_subnet(self.context, 0, subnet6,
port_id, self.reuse_after,
mac_address=mac)
self.assertEqual(1, ip_update.call_count)
self.assertEqual(0, ip_create.call_count)
class QuarkNewIPAddressAllocation(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, addresses=None, subnets=None):
if not addresses:
addresses = [None]
self.context.session.add = mock.Mock()
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.subnet_find_allocation_counts")
) as (addr_find, subnet_find):
addr_find.side_effect = addresses
subnet_find.return_value = subnets
yield
def test_allocate_new_ip_address_in_empty_range(self):
subnet = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=1, exclude=[
models.IPPolicyCIDR(cidr="0.0.0.0/32")]))
with self._stubs(subnets=[(subnet, 0)], addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
version=4)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
def test_allocate_ip_one_full_one_open_subnet(self):
subnet1 = dict(id=1, first_ip=0, last_ip=0,
cidr="0.0.0.0/32", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=1, exclude=[
models.IPPolicyCIDR(cidr="0.0.0.0/32")]))
subnet2 = dict(id=2, first_ip=256, last_ip=512,
cidr="0.0.1.0/24", ip_version=4,
next_auto_assign_ip=256,
ip_policy=dict(
size=1,
exclude=[models.IPPolicyCIDR(cidr="0.0.1.0/32")]))
subnets = [(subnet1, 1), (subnet2, 0)]
with self._stubs(subnets=subnets, addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.1.1").value)
self.assertEqual(address[0]["subnet_id"], 2)
def test_allocate_ip_no_subnet_fails(self):
with self._stubs(subnets=[]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(self.context, [], 0, 0, 0)
def test_allocate_ip_no_available_subnet_fails(self):
subnet1 = dict(id=1, first_ip=0, last_ip=0, next_auto_assign_ip=0,
cidr="0.0.0.0/32", ip_version=4,
ip_policy=dict(
size=1,
exclude=[models.IPPolicyCIDR(cidr="0.0.0.0/32")]))
with self._stubs(subnets=[(subnet1, 1)]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(self.context, [], 0, 0, 0)
def test_allocate_ip_two_open_subnets_choses_first(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=1, exclude=[
models.IPPolicyCIDR(cidr="0.0.0.0/32")]))
subnet2 = dict(id=2, first_ip=256, last_ip=510,
cidr="0.0.1.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=1, exclude=[
models.IPPolicyCIDR(cidr="0.0.1.0/32")]))
subnets = [(subnet1, 1), (subnet2, 1)]
with self._stubs(subnets=subnets, addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
self.assertEqual(address[0]["subnet_id"], 1)
def test_find_requested_ip_subnet(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=None)
subnets = [(subnet1, 1)]
with self._stubs(subnets=subnets, addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(
self.context, address, 0, 0, 0, ip_addresses=["0.0.0.240"])
self.assertEqual(address[0]["address"],
netaddr.IPAddress('::ffff:0.0.0.240').value)
self.assertEqual(address[0]["subnet_id"], 1)
def test_no_valid_subnet_for_requested_ip_fails(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.1.0/24", ip_version=4)
subnets = [(subnet1, 1)]
with self._stubs(subnets=subnets, addresses=[None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(
self.context, [], 0, 0, 0, ip_addresses=["0.0.0.240"])
class QuarkIPAddressAllocationTestRetries(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, address=None, subnets=None):
self.context.session.add = mock.Mock()
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.ip_address_create"),
mock.patch("quark.ipam.QuarkIpam._notify_new_addresses"),
mock.patch("quark.db.api.subnet_find_allocation_counts")
) as (addr_find, addr_create, notify, subnet_find):
addr_find.side_effect = [None, None, None]
addr_create.side_effect = address
subnet_find.return_value = subnets
yield
def test_allocate_allocated_ip_fails_and_retries(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255, next_auto_assign_ip=1,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=None)
subnets = [(subnet1, 1)]
addr_found = dict(id=1, address=2)
with self._stubs(subnets=subnets,
address=[q_exc.IPAddressRetryableFailure,
addr_found]):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0)
self.assertEqual(subnet1["next_auto_assign_ip"], 3)
self.assertEqual(addr[0]["address"], 2)
def test_allocate_explicit_already_allocated_fails_and_retries(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255, next_auto_assign_ip=1,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=None)
subnets = [(subnet1, 1), (subnet1, 1)]
addr_found = dict(id=1, address=1)
with self._stubs(subnets=subnets,
address=[q_exc.IPAddressRetryableFailure,
addr_found]):
with self.assertRaises(exceptions.IpAddressInUse):
self.ipam.allocate_ip_address(
self.context, [], 0, 0, 0, ip_addresses=["0.0.0.1"])
def test_allocate_implicit_already_allocated_fails_and_retries(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255, next_auto_assign_ip=1,
cidr="::/64", ip_version=6,
ip_policy=None)
subnets = [(subnet1, 1), (subnet1, 1)]
addr_found = dict(id=1, address=1)
with self._stubs(subnets=subnets,
address=[db_exc.DBDuplicateEntry, addr_found]):
with mock.patch("quark.ipam.generate_v6") as gv6:
gv6.return_value = (1, 2)
ret_addrs = []
self.ipam.allocate_ip_address(
self.context, ret_addrs, 0, 0, 0,
mac_address=dict(address=mock.MagicMock())),
self.assertEqual(ret_addrs, [addr_found])
def test_allocate_specific_subnet_ip_not_in_subnet_fails(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255, next_auto_assign_ip=1,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=None)
subnets = [(subnet1, 1), (subnet1, 1)]
addr_found = dict(id=1, address=256)
with self._stubs(subnets=subnets,
address=[q_exc.IPAddressRetryableFailure,
addr_found]):
with self.assertRaises(q_exc.IPAddressNotInSubnet):
self.ipam.allocate_ip_address(
self.context, [], 0, 0, 0, ip_addresses=["0.0.1.0"],
subnets=subnet1)
def test_allocate_specific_subnet_unusable_fails(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255, next_auto_assign_ip=1,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=None,
do_not_use=1)
subnets = []
addr_found = dict(id=1, address=256)
with self._stubs(subnets=subnets,
address=[q_exc.IPAddressRetryableFailure,
addr_found]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(
self.context, [], 0, 0, 0, ip_addresses=["0.0.1.0"],
subnets=subnet1)
def test_allocate_last_ip_closes_subnet(self):
subnet1 = dict(id=1, first_ip=0, last_ip=1, next_auto_assign_ip=1,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=None)
subnets = [(subnet1, 1)]
addr_found = dict(id=1, address=1)
with self._stubs(subnets=subnets, address=[addr_found]):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0)
self.assertEqual(subnet1["next_auto_assign_ip"], -1)
self.assertEqual(addr[0]["address"], 1)
class QuarkIPAddressAllocateDeallocated(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, ip_find, subnet, address, addresses_found,
sub_found=True):
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.ip_address_update"),
mock.patch("quark.ipam.QuarkIpamANY._choose_available_subnet")
) as (addr_find, addr_update, choose_subnet):
if ip_find:
addr_find.return_value = address
else:
address["id"] = None
addr_find.side_effect = addresses_found
addr_update.return_value = address
choose_subnet.return_value = [subnet]
if not sub_found:
choose_subnet.return_value = []
yield choose_subnet
def test_allocate_finds_deallocated_ip_succeeds(self):
subnet = dict(id=1, ip_version=4, next_auto_assign_ip=0,
cidr="0.0.0.0/24", ip_policy=None)
address = dict(id=1, address=1, subnet=subnet)
addresses_found = [None, address, None]
with self._stubs(
True, subnet, address, addresses_found
) as (choose_subnet):
ipaddress = []
self.ipam.allocate_ip_address(self.context, ipaddress, 0, 0, 0)
self.assertIsNotNone(ipaddress[0]['id'])
self.assertFalse(choose_subnet.called)
def test_allocate_finds_deallocated_ip_out_of_range_deletes(self):
subnet = dict(id=1, ip_version=4, next_auto_assign_ip=2,
cidr="0.0.0.0/29", ip_policy=None)
address = dict(id=1, address=254)
address2 = dict(id=1, address=1)
address["subnet"] = subnet
addresses_found = [address, address2]
self.context.session.delete = mock.Mock()
with self._stubs(False, subnet, address, addresses_found,
sub_found=True):
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0)
self.assertTrue(self.context.session.delete.called)
self.assertEqual(len(addr), 1)
self.context.session.delete = mock.Mock()
def test_allocate_finds_no_deallocated_creates_new_ip(self):
subnet = dict(id=1, ip_version=4, next_auto_assign_ip=2,
cidr="0.0.0.0/24", first_ip=0, last_ip=255,
ip_policy=None)
address = dict(id=1, address=0)
addresses_found = [None, address, None]
with self._stubs(
False, subnet, address, addresses_found
) as (choose_subnet):
ipaddress = []
self.ipam.allocate_ip_address(self.context, ipaddress, 0, 0, 0)
self.assertIsNotNone(ipaddress[0]['id'])
self.assertEqual(ipaddress[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
self.assertTrue(choose_subnet.called)
class TestQuarkIpPoliciesIpAllocation(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, addresses=None, subnets=None):
if not addresses:
addresses = [None]
self.context.session.add = mock.Mock()
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.subnet_find_allocation_counts")
) as (addr_find, subnet_find):
addr_find.side_effect = addresses
subnet_find.return_value = subnets
yield
def test_first_ip_is_not_network_ip_by_default(self):
network = netaddr.IPNetwork("192.168.0.0/24")
first = network.ipv6().first
last = network.ipv6().last
subnet = dict(id=1, first_ip=first, last_ip=last,
cidr="192.168.0.0/24", ip_version=4,
next_auto_assign_ip=first,
ip_policy=dict(size=1, exclude=[
models.IPPolicyCIDR(cidr="192.168.0.0/32")]))
with self._stubs(subnets=[(subnet, 0)], addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
version=4)
self.assertEqual(address[0]["address"], first + 1)
def test_subnet_full_based_on_ip_policy(self):
subnet = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=256, exclude=[
models.IPPolicyCIDR(cidr="0.0.0.0/24")]))
with self._stubs(subnets=[(subnet, 0)], addresses=[None, None]):
with self.assertRaises(exceptions.IpAddressGenerationFailure):
self.ipam.allocate_ip_address(self.context, [], 0, 0, 0,
version=4)
def test_ip_policy_on_subnet(self):
old_override = cfg.CONF.QUARK.ip_address_retry_max
cfg.CONF.set_override('ip_address_retry_max', 3, 'QUARK')
subnet = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=2, exclude=[
models.IPPolicyCIDR(cidr="0.0.0.0/31")]))
with self._stubs(subnets=[(subnet, 0)], addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
version=4)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.2").value)
cfg.CONF.set_override('ip_address_retry_max', old_override, 'QUARK')
def test_ip_policy_on_both_subnet_preferred(self):
subnet = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=dict(size=1, exclude=[
models.IPPolicyCIDR(cidr="0.0.0.0/32")]))
with self._stubs(subnets=[(subnet, 0)], addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(self.context, address, 0, 0, 0,
version=4)
self.assertEqual(address[0]["address"],
netaddr.IPAddress("::ffff:0.0.0.1").value)
def test_ip_policy_allows_specified_ip(self):
subnet1 = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
ip_policy=dict(exclude=[
models.IPPolicyCIDR(cidr="0.0.0.240/32")]))
subnets = [(subnet1, 1)]
with self._stubs(subnets=subnets, addresses=[None, None]):
address = []
self.ipam.allocate_ip_address(
self.context, address, 0, 0, 0, ip_addresses=["0.0.0.240"])
self.assertEqual(address[0]["address"],
netaddr.IPAddress('::ffff:0.0.0.240').value)
class QuarkIPAddressAllocationNotifications(QuarkIpamBaseTest):
@contextlib.contextmanager
def _stubs(self, address, addresses=None, subnets=None, deleted_at=None):
address = models.IPAddress(**address)
if not addresses:
addresses = [None]
with contextlib.nested(
mock.patch("quark.db.api.ip_address_find"),
mock.patch("quark.db.api.ip_address_create"),
mock.patch("quark.db.api.subnet_find_allocation_counts"),
mock.patch("neutron.common.rpc.get_notifier"),
mock.patch("neutron.openstack.common.timeutils.utcnow"),
) as (addr_find, addr_create, subnet_find, notify, time):
addr_find.side_effect = addresses
addr_create.return_value = address
subnet_find.return_value = subnets
time.return_value = deleted_at
yield notify
def test_allocation_notification(self):
subnet = dict(id=1, first_ip=0, last_ip=255,
cidr="0.0.0.0/24", ip_version=4,
next_auto_assign_ip=0,
ip_policy=None)
address = dict(address=0, created_at="123", subnet_id=1,
address_readable="0.0.0.0", used_by_tenant_id=1)
with self._stubs(
address,
subnets=[(subnet, 1)],
addresses=[None, None]
) as notify:
addr = []
self.ipam.allocate_ip_address(self.context, addr, 0, 0, 0,
version=4)
notify.assert_called_once_with("network")
notify.return_value.info.assert_called_once_with(
self.context,
"ip_block.address.create",
dict(ip_block_id=address["subnet_id"],
ip_address="0.0.0.0",
device_ids=[],
created_at=address["created_at"],
used_by_tenant_id=1))
def test_deallocation_notification(self):
addr_dict = dict(address=0, created_at="123", subnet_id=1,
address_readable="0.0.0.0", used_by_tenant_id=1)
address = models.IPAddress()
address.update(addr_dict)
port_dict = dict(ip_addresses=[address], device_id="foo")
port = models.Port()
port.update(port_dict)
address["ports"] = [port]
with self._stubs(dict(), deleted_at="456") as notify:
self.ipam.deallocate_ips_by_port(self.context, port)
notify.assert_called_once_with("network")
notify.return_value.info.assert_called_once_with(
self.context,
"ip_block.address.delete",
dict(ip_block_id=address["subnet_id"],
ip_address="0.0.0.0",
device_ids=["foo"],
created_at=address["created_at"],
deleted_at="456",
used_by_tenant_id=1))
class QuarkIpamTestV6IpGeneration(QuarkIpamBaseTest):
def test_rfc2462_generates_valid_ip(self):
mac = netaddr.EUI("AA:BB:CC:DD:EE:FF")
cidr = "fe80::/120"
ip = quark.ipam.rfc2462_ip(mac, cidr)
self.assertEqual(ip,
netaddr.IPAddress('fe80::a8bb:ccff:fedd:eeff').value)
def test_rfc3041_generates_valid_ip(self):
# Use a one-time generated UUID so the output is predictable
port_id = "945af340-ed34-4fec-8c87-853a2df492b4"
cidr = "fe80::/120"
ip = quark.ipam.rfc3041_ip(port_id, cidr).next()
self.assertEqual(ip,
netaddr.IPAddress('fe80::40c9:a95:d83a:2ffa').value)
def test_v6_generator(self):
mac = netaddr.EUI("AA:BB:CC:DD:EE:FF")
cidr = "fe80::/120"
port_id = "945af340-ed34-4fec-8c87-853a2df492b4"
cidr = "fe80::/120"
gen = quark.ipam.generate_v6(mac, port_id, cidr)
ip = gen.next()
self.assertEqual(ip,
netaddr.IPAddress('fe80::a8bb:ccff:fedd:eeff').value)
ip = gen.next()
self.assertEqual(ip,
netaddr.IPAddress('fe80::40c9:a95:d83a:2ffa').value)
| 45.659971
| 79
| 0.58187
| 7,626
| 63,650
| 4.625754
| 0.050747
| 0.017916
| 0.014713
| 0.017009
| 0.83853
| 0.801962
| 0.777894
| 0.749206
| 0.723863
| 0.712297
| 0
| 0.04077
| 0.298649
| 63,650
| 1,393
| 80
| 45.692749
| 0.749446
| 0.013181
| 0
| 0.705882
| 0
| 0
| 0.079231
| 0.032759
| 0
| 0
| 0
| 0
| 0.128418
| 1
| 0.082022
| false
| 0.004143
| 0.009114
| 0
| 0.107705
| 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
|
a118a981980fc511877aef6cb6e6d47e85126f2e
| 107
|
py
|
Python
|
content_b_variables/ex6_whitespaces.py
|
Alyssonmach/learning-python-with-codes
|
e5ef70f3b56712e98449b3053eb34416b8025cb1
|
[
"MIT"
] | 3
|
2020-11-28T08:26:54.000Z
|
2020-12-23T18:37:37.000Z
|
content_b_variables/ex6_whitespaces.py
|
Alyssonmach/learning-python-with-codes
|
e5ef70f3b56712e98449b3053eb34416b8025cb1
|
[
"MIT"
] | 1
|
2020-10-22T02:05:11.000Z
|
2020-10-22T02:05:53.000Z
|
content_b_variables/ex6_whitespaces.py
|
Alyssonmach/learning-python-with-codes
|
e5ef70f3b56712e98449b3053eb34416b8025cb1
|
[
"MIT"
] | null | null | null |
print('\n Python \n C++ \n Java')
print('\n\t Python \n\t C++ \n\t Java')
print('\n Python \n C++ \n Java')
| 35.666667
| 39
| 0.560748
| 24
| 107
| 2.5
| 0.25
| 0.3
| 0.4
| 0.433333
| 0.633333
| 0.633333
| 0.633333
| 0
| 0
| 0
| 0
| 0
| 0.158879
| 107
| 3
| 40
| 35.666667
| 0.666667
| 0
| 0
| 0.666667
| 0
| 0
| 0.722222
| 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
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 1
|
0
| 8
|
a1318d227c60a35cf659a3a24f5d58882377646f
| 25,594
|
py
|
Python
|
test/emulator/test_server.py
|
hatchbed/sick_scan_xd
|
10262b6aaeae2586515650a5b089f4490095bcb6
|
[
"Apache-2.0"
] | 18
|
2019-12-03T02:34:08.000Z
|
2022-01-24T01:36:44.000Z
|
test/emulator/test_server.py
|
hatchbed/sick_scan_xd
|
10262b6aaeae2586515650a5b089f4490095bcb6
|
[
"Apache-2.0"
] | 17
|
2019-09-02T07:44:07.000Z
|
2022-03-31T09:40:09.000Z
|
test/emulator/test_server.py
|
hatchbed/sick_scan_xd
|
10262b6aaeae2586515650a5b089f4490095bcb6
|
[
"Apache-2.0"
] | 17
|
2019-08-14T06:54:01.000Z
|
2022-01-19T03:15:53.000Z
|
"""
A simple test server for sick_scan_base. A listening tcp socket is opened, incoming connections are accepted and some basic cola telegrams are responded on client requests.
Note: This is just a simple test server for basic unittests of sick_scan_base drivers. It does not emulate any real lidar sensor.
Usage:
python test_server.py --scandata_file=<scandatafile> --scandata_frequency=<freq> --tcp_port=<int>
Example:
python ../test/emulator/test_server.py --scandata_file=../test/emulator/scandata/20210302_lms511.pcapng.scandata.txt --scandata_frequency=2.0 --tcp_port=2112
"""
import argparse
import datetime
import select
import socket
import time
# Decodes and returns the payload length of a cola message, i.e. returns message_payload_length in a message := { 4 byte STX 0x02020202 } + { 4 byte message_payload_length } + { message_payload } + { 1 byte CRC }
def parseBinaryColaPayloadLength(payload):
length = 0
if len(payload) > 7 and payload.startswith(b"\x02\x02\x02\x02"):
length = (payload[4] << 24) + (payload[5] << 16) + (payload[6] << 8) + (payload[7] << 0)
return length
# Returns a string as bytearray
def stringToByteArray(message):
return bytearray(message.encode())
# Removes optional ":" from message and returns hex values as bytearray
def hexStringToByteArray(message):
message_hex = message.replace(":", "")
return bytearray.fromhex(message_hex)
"""
ColaLMDscandataGenerator generates LMDscandata from a list of predefined cola scandatatelegrams.
"""
class ColaLMDscandataGenerator:
# Constructor
def __init__(self, scandata_file):
self.LMDscandata_list = []
self.read_index = -1;
with open(scandata_file, 'r') as f:
self.LMDscandata_list = [line.strip() for line in f]
print("ColaLMDscandataGenerator: {} scandata telegrams from file {}".format(len(self.LMDscandata_list), scandata_file))
if len(self.LMDscandata_list) <= 0: # at least one hardcoded scandata
self.LMDscandata_list = [ "02:02:02:02:00:00:0d:d8:73:53:4e:20:4c:4d:44:73:63:61:6e:64:61:74:61:20:00:00:00:01:01:14:58:56:01:00:d3:52:d4:d4:f4:75:09:51:f4:75:a8:e6:00:00:00:00:00:00:00:00:09:c4:00:00:02:1c:00:00:00:01:44:49:53:54:31:3f:80:00:00:00:00:00:00:ff:ff:3c:b0:06:83:04:75:05:19:05:13:05:1b:05:13:05:1b:05:1b:05:1b:05:19:05:1f:05:1f:05:22:05:23:05:21:05:22:05:1d:05:24:05:28:05:21:05:24:05:1e:05:28:05:24:05:27:05:28:05:26:05:28:05:2d:05:2e:05:30:05:32:05:2e:05:30:05:31:05:34:05:31:05:37:05:37:05:3f:05:3b:05:35:05:3d:05:37:05:40:05:3b:05:41:05:44:05:45:05:3d:05:45:05:49:05:43:05:47:05:48:05:4a:05:4d:05:4a:05:4c:05:4b:05:51:05:51:05:54:05:57:05:4f:05:57:05:56:05:59:05:56:05:58:05:59:05:62:05:5d:05:5f:05:64:05:65:05:68:05:67:05:63:05:6b:05:64:05:72:05:70:05:71:05:71:05:6f:05:74:05:70:05:74:05:73:05:7b:05:7f:05:7e:05:88:05:87:05:84:05:83:05:8a:05:81:05:8c:05:8c:05:8a:05:8f:05:95:05:93:05:9b:05:9a:05:9f:05:9a:05:9e:05:a4:05:a8:05:a0:05:a4:05:a8:05:b0:05:ad:05:af:05:b4:05:b2:05:bc:05:bc:05:ba:05:b9:05:bf:05:c1:05:c9:05:cb:05:ce:05:d1:05:cf:05:d4:05:d2:05:da:05:db:05:d9:05:db:05:de:05:e6:05:e7:05:e6:05:ea:05:f3:05:f3:05:f5:05:f8:05:f9:05:fb:06:00:06:08:05:fe:06:0d:06:0d:06:0d:06:15:06:10:06:14:06:18:06:25:06:24:06:26:06:24:06:20:06:1d:06:0f:06:12:05:fe:05:fc:05:fc:05:f7:05:ec:05:e4:05:e1:05:e0:05:db:05:d6:05:ce:05:c2:05:c0:05:b8:05:ae:05:aa:05:a9:05:a6:05:9b:05:a0:05:8b:05:91:05:8d:05:86:05:84:05:77:05:81:05:76:05:75:05:68:05:62:05:5b:05:54:05:51:05:4c:05:52:05:4d:05:46:05:40:05:39:05:35:05:34:05:32:05:2f:05:21:05:29:05:21:05:20:05:16:05:0c:05:0c:05:04:05:08:05:04:04:ff:04:f7:04:fb:04:f7:04:ec:04:e8:04:e9:04:f0:04:e7:04:e3:04:dc:04:d9:04:df:04:d7:04:ce:04:ca:04:c4:04:c2:04:b9:04:be:04:bd:04:b8:04:ae:04:aa:04:b2:04:ac:04:a8:04:9c:04:a4:04:a2:04:9f:04:9b:04:96:04:91:04:91:04:94:04:8c:04:8a:04:8a:04:80:04:80:04:7c:04:76:04:74:04:77:04:6f:04:68:04:72:04:6f:04:6a:04:63:04:64:04:62:04:5d:04:5f:04:5d:04:57:04:55:04:56:04:58:04:4c:04:50:04:4e:04:53:04:49:04:4f:04:47:04:40:04:3e:04:3d:04:39:04:3a:04:32:04:31:04:32:04:30:04:28:04:26:04:25:04:2c:04:23:04:22:04:20:04:22:04:18:04:21:04:18:04:16:04:18:04:1d:04:11:04:1a:04:15:04:16:04:14:04:11:04:13:04:0d:04:0c:04:02:03:fc:03:fd:04:04:03:f7:03:f7:03:f9:03:f2:03:f4:03:f2:03:f3:03:f6:03:f3:03:e7:03:f1:03:eb:03:ee:03:e6:03:ea:03:e1:03:de:03:e8:03:e8:03:e4:03:df:03:e4:03:dd:03:db:03:d9:03:dc:03:db:03:dc:03:d3:03:d3:03:d2:03:d2:03:ca:03:c0:03:c5:03:c3:03:c4:03:c6:03:bf:03:c2:03:c5:03:c0:03:bf:03:ba:03:b9:03:b4:03:b9:03:b5:03:b4:03:b6:03:b1:03:bc:03:b0:03:b1:03:b3:03:b2:03:b0:03:a8:03:ae:03:a9:03:ad:03:ae:03:a7:03:b9:03:a3:03:af:03:ab:03:a6:03:9e:03:99:03:9e:03:98:03:9d:03:98:03:95:03:9e:03:9a:03:94:03:93:03:96:03:95:03:95:03:94:03:97:03:90:03:91:03:8d:03:92:03:8d:03:92:03:88:03:86:03:8b:03:80:03:8b:03:89:03:88:03:83:03:86:03:84:03:86:03:88:03:7b:03:8a:03:84:03:84:03:84:03:7e:03:84:03:7d:03:71:03:79:03:77:03:6b:03:71:03:73:03:71:03:6e:03:6c:03:6c:03:4e:02:c1:02:61:02:2c:02:20:02:00:01:fc:01:ec:01:e9:01:e6:01:e3:01:e2:01:e4:01:de:01:da:01:de:01:dd:01:ce:01:d7:01:df:01:d5:01:db:01:d4:01:dc:01:de:01:d7:01:d5:01:d7:01:d0:01:d3:01:d0:01:d5:01:d1:01:c9:01:d2:01:d1:01:cf:01:ce:01:ce:01:cf:01:c3:01:cc:01:c8:01:c5:01:cb:01:d1:01:c7:01:c3:01:c8:01:c4:01:ca:01:bc:01:c2:01:c3:01:c4:01:bd:01:bd:01:c1:01:c0:01:cc:01:c0:01:c0:01:bc:01:b6:01:bb:01:b9:01:c0:01:bc:01:bd:01:b9:01:b8:01:bb:01:b4:01:bb:01:be:01:b5:01:b8:01:b5:01:b6:01:b4:01:b5:01:b3:01:ba:01:b6:01:bb:01:af:01:b3:01:b0:01:b9:01:b2:01:b2:01:b2:01:ad:01:ad:01:ad:01:ae:01:b7:01:ac:01:ac:01:ab:01:b9:01:b0:01:b8:01:bf:01:c7:01:c8:01:db:02:09:02:30:02:58:02:a9:03:28:03:60:03:6a:03:70:03:6b:03:6c:03:6d:03:72:03:79:03:7e:03:80:03:85:03:80:03:84:03:8e:03:87:03:81:03:8d:03:91:03:92:03:9f:03:a1:03:97:03:a7:03:a5:03:9e:03:9e:03:ab:03:a2:03:b0:03:ac:03:ad:03:b1:03:c0:03:d8:03:e4:03:da:03:ce:03:ae:03:9d:03:9c:03:9e:03:a2:03:9a:03:a6:03:a8:03:ab:03:a9:03:af:03:a8:03:ad:03:af:03:b0:03:b3:03:ae:03:b9:03:be:03:c1:03:c5:03:cb:03:cb:03:c6:03:c8:03:d0:03:d1:03:cf:03:d5:03:dc:03:df:03:df:03:df:03:e7:03:f6:04:05:04:00:03:f3:03:e5:03:d8:03:cf:03:ca:03:cc:03:d2:03:d0:03:d1:03:d3:03:d8:03:de:03:e0:03:da:03:ec:03:e5:03:e9:03:ed:03:f2:03:ea:03:ee:03:fc:03:f5:03:fc:03:f8:03:fb:03:ff:03:ff:04:0c:04:07:04:0a:04:11:04:18:04:21:04:32:04:28:04:1a:04:10:04:06:04:03:04:09:04:0a:04:08:04:0e:04:16:04:17:04:19:04:1b:04:17:04:1a:04:1e:04:21:04:29:04:2a:04:24:04:39:04:2f:04:3b:04:32:04:39:04:39:04:3f:04:4d:04:43:04:40:04:47:04:42:04:41:04:40:04:49:04:4b:04:4d:04:4d:04:4c:04:4d:04:5a:04:52:04:57:04:59:04:5d:04:64:04:6d:04:67:04:67:04:70:04:73:04:71:04:6d:04:77:04:76:04:7e:04:86:04:84:04:86:04:81:04:88:04:88:04:88:04:85:04:89:04:8f:04:92:04:8f:04:94:04:99:04:a1:04:a7:04:a3:04:a7:04:ac:04:b2:04:af:04:be:04:c1:04:be:04:c8:04:cc:04:cc:04:d1:04:d2:04:d4:04:cd:04:d0:04:d2:04:d4:04:e1:04:e5:04:e8:04:e8:04:f1:04:fb:04:fa:04:fb:05:01:05:01:05:02:05:0b:05:12:05:1d:05:1c:05:1a:05:1c:05:1c:05:17:05:23:05:23:05:2c:05:36:05:38:05:38:05:40:05:4a:05:47:05:48:05:52:05:53:05:5a:05:5a:05:7c:05:87:05:ad:05:d9:06:45:06:8b:06:c8:06:d0:06:85:06:52:06:0b:05:d9:05:b9:05:aa:05:a6:05:c1:06:0c:06:cb:06:f6:07:28:07:2f:07:3a:07:46:07:43:07:13:06:c9:06:6e:06:39:06:1c:06:2b:06:6b:06:f8:07:50:07:47:06:e8:06:81:06:5b:06:4b:06:41:06:4e:06:59:06:7b:06:9a:06:c1:06:ff:07:8e:07:d5:07:ff:07:88:07:33:06:e6:06:c6:06:cf:06:e0:07:18:07:64:08:0d:08:58:08:76:08:7d:08:88:08:91:08:47:08:1a:07:ef:07:ed:08:48:08:cf:09:21:09:71:09:84:09:20:08:4a:07:e8:07:ad:07:9f:07:93:07:ab:07:fe:09:1c:09:38:08:a9:08:46:08:13:07:ee:07:d5:07:dd:07:e7:08:12:08:84:08:9a:08:7b:08:57:08:44:08:25:08:31:08:3f:08:56:08:90:08:c3:08:b4:08:9f:08:8a:08:7d:08:80:08:90:08:b5:08:f5:09:04:08:f5:08:eb:08:ec:08:f5:09:12:09:47:09:64:09:5b:09:52:09:5b:09:75:09:a2:09:c2:09:c0:09:c3:09:cb:09:e9:0a:2b:0a:3b:0a:50:0a:98:0a:b7:0a:c1:0a:eb:0b:09:0b:03:0b:00:0b:1b:0b:50:0b:60:0b:4f:0a:ed:0a:6f:0a:30:0a:21:0a:10:0a:14:0a:11:0a:07:0a:05:0a:07:09:f4:09:d6:09:ba:09:9c:09:91:09:81:09:7a:09:7b:09:7c:09:78:09:75:09:76:09:75:09:70:09:70:09:6d:09:6e:09:69:09:69:09:62:09:68:09:63:09:61:09:62:09:61:09:51:09:58:09:59:09:55:09:54:09:51:09:4c:09:50:09:42:09:47:09:41:09:45:09:43:09:41:09:45:09:42:09:45:09:38:09:3a:09:3d:09:3c:09:31:09:3a:09:47:09:4b:09:54:09:7d:09:7f:09:78:09:6d:09:61:09:60:09:52:09:59:09:62:09:6b:09:71:09:6f:09:6e:09:6f:09:6d:09:6e:09:6c:09:69:09:6b:09:66:09:62:09:6a:09:6a:09:67:09:6b:09:6a:09:62:09:64:09:69:09:63:09:61:09:5e:09:6a:09:5f:09:61:09:5f:09:5f:09:61:09:67:09:64:09:63:09:5e:09:66:09:5d:09:61:09:66:09:60:09:5f:09:5c:09:62:09:63:09:66:09:67:09:6b:09:6f:09:75:09:7f:03:ee:03:ba:03:56:03:43:03:2c:03:25:03:1c:03:1f:03:16:03:18:03:11:03:0f:03:00:03:03:02:fb:02:fb:02:fe:02:f3:02:ee:02:ec:02:ec:02:e3:02:e2:02:d9:02:db:02:d9:02:d6:02:d2:02:cf:02:c8:02:ca:02:c3:02:b9:02:be:02:b8:02:b3:02:b6:02:b2:02:ae:02:ab:02:a6:02:a3:02:a0:02:97:02:93:02:90:02:98:02:8b:02:8a:02:84:02:84:02:82:02:86:02:7f:02:83:02:7b:02:77:02:79:02:77:02:6f:02:77:02:69:02:70:02:6d:02:71:02:68:02:66:02:62:02:5d:02:5f:02:60:02:68:02:5d:02:5a:02:55:02:5c:02:56:02:5a:02:57:02:5c:02:59:02:61:02:57:02:5d:02:5e:02:62:02:68:02:65:02:62:02:68:02:6b:02:69:02:6a:02:6a:02:6c:02:72:02:6f:02:70:00:01:52:53:53:49:31:3f:80:00:00:00:00:00:00:ff:ff:3c:b0:06:83:04:75:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fc:ef:e9:f0:f6:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:f8:f4:f1:e3:e4:e6:e5:e4:e2:e4:e4:e5:ef:e3:e8:ed:e7:e4:e7:e5:e6:e3:e6:df:e6:e5:e6:e4:e0:e3:e6:ec:e2:e6:e7:e5:e3:e5:e3:e2:e3:de:e4:dd:e7:e2:e1:e3:e4:e0:de:e2:e1:e5:e4:e7:e6:e2:df:e3:e2:e1:e0:e1:e7:e2:e2:dd:e3:e8:e3:e0:e2:e0:e4:e1:e8:e6:e0:db:dd:e4:e1:e5:de:e5:e3:e1:e2:e4:e0:e0:e0:de:e0:e1:df:e3:e8:e7:e2:e2:e1:e0:e2:e1:dc:db:df:df:e0:e4:e6:e0:e1:e1:e3:dd:e5:dd:e7:e5:e7:e2:e0:e1:e5:e6:e3:e1:e6:e2:e2:df:df:df:e4:e2:e5:df:e6:e3:e3:e3:e6:e2:e6:e4:e7:e6:e4:e7:e5:e6:e3:e9:eb:e5:e9:ea:e8:e6:e8:eb:e6:eb:e6:e9:e8:e1:e8:e6:e5:e5:e4:e2:e8:ea:e7:e5:e7:e8:ea:ea:e4:eb:e4:ea:e6:eb:e9:ee:eb:eb:ec:e8:e9:ea:ea:e8:eb:eb:e9:e9:e9:f0:eb:ef:ec:f0:ed:f1:ea:ed:eb:ee:ed:ea:ee:ee:ec:ec:ed:f0:ec:ef:f2:f4:ed:ef:eb:ef:f1:f2:ea:f2:f0:ec:e8:f2:ea:f3:ec:ef:f1:ee:ed:ef:ef:f2:ef:ef:ec:ed:f0:f4:ec:ef:f5:f0:ee:f3:ee:f0:ef:f7:f3:f5:f3:f1:f5:f9:f7:f6:f4:f6:f8:f5:f0:ec:f2:fe:fe:fe:fe:fe:fd:eb:e8:ed:ec:e9:e8:e2:e4:ea:e6:e2:ea:ef:e9:ee:e6:ee:ed:e9:e7:ed:eb:eb:e8:ed:ee:e9:eb:ee:eb:e8:ed:ed:e8:eb:ea:e2:e5:e4:e6:e3:e5:e4:e3:e1:e9:eb:e9:e9:e6:e7:ec:e6:e2:e6:e3:e3:e4:e7:eb:e1:e4:e2:e4:e8:e7:e6:ed:e7:e8:ec:e6:e3:e5:e4:e6:e5:e3:e4:e6:eb:e7:ec:eb:e8:e7:e5:e6:eb:ea:e6:db:d1:c7:bb:b4:b7:b6:b5:c6:ec:fe:fe:fa:e7:d9:d9:e5:e0:e2:e1:e5:e2:e8:e4:e1:e2:e3:de:de:db:de:de:dc:e2:dd:df:df:e0:d9:dd:e0:e0:e0:e0:db:de:eb:fe:fe:fe:fe:fb:e8:e5:dd:df:db:e2:dd:dc:dd:db:dc:e1:d5:d8:d8:d4:db:db:d9:d9:df:db:db:db:da:de:d6:db:d9:e1:d8:da:e0:ec:f7:fe:fe:fe:ef:e0:da:dd:dc:db:d7:da:dd:dc:dd:d8:dd:d8:db:dd:da:d8:d8:e0:d8:dd:da:dc:d5:d8:dc:dc:de:e4:e8:f4:fe:fe:fd:f4:e0:dc:da:de:db:db:dc:d9:da:dd:d7:db:d6:db:d9:dc:d9:dd:d8:df:d9:dd:da:de:e1:e2:e5:e9:e3:e8:df:e6:e5:df:db:dc:da:da:d9:df:db:da:db:da:da:da:d9:dd:d9:d5:dc:e0:e0:e4:e3:e6:e1:e4:ea:e5:e1:df:dd:dc:d8:db:dd:db:df:d7:db:dc:d7:d7:dd:e0:dc:e0:de:e3:e3:ea:e8:e4:e1:df:db:dd:df:dd:da:d8:da:df:e3:dd:db:da:df:e1:e4:e8:e7:e5:e9:e2:e6:dc:db:df:e0:da:e0:e4:e4:dc:df:df:e2:d9:f7:fe:fe:fe:fe:fe:fe:f8:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fc:fd:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:f2:e9:e7:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:f7:fa:f4:f5:fa:fe:fe:fe:fe:fe:fe:fe:fc:fe:fe:fe:fe:fe:fe:fe:fe:fe:f5:ed:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:f1:ea:fe:fe:fe:fe:fe:f4:eb:ed:e8:f4:f9:fb:f1:ea:e5:e9:ef:f8:f7:fa:eb:ec:ed:f5:fb:f7:e6:e8:ee:f5:f6:f5:f6:fb:fe:fe:fe:fe:ea:e9:ed:ef:e7:df:d5:d6:bc:be:cf:d4:e2:e8:ec:f1:ef:f7:f4:ef:eb:e6:e2:e5:e6:e9:e9:e9:e9:e9:e8:e7:e7:ea:ec:e8:e6:ed:e4:e8:e9:e8:e5:ea:f1:ec:ea:eb:e8:ed:e5:f0:eb:ea:ea:e6:ec:ea:e9:e9:e7:f2:ec:e8:dd:e3:e2:d4:c7:d8:eb:ed:ee:f7:f6:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:fe:f0:d8:fe:fe:c2:c4:bd:bf:be:bf:be:bf:be:c1:bc:c1:bd:be:c1:bf:bf:be:c5:bf:c3:c6:c5:c2:c4:c5:c6:c5:c8:c6:bf:c3:c1:c4:c5:c7:c2:c7:c9:c5:c4:c5:c2:c6:c9:c7:c3:c2:c4:c5:c5:c3:c4:c8:c3:c3:c3:c6:c6:c4:c8:c6:c7:c3:cb:c7:c8:c5:c7:c8:c3:c3:c7:ca:cc:cf:d5:d4:d1:d9:d0:d0:d2:d2:d2:d0:d1:d3:d3:d4:d2:d2:d0:d3:ce:d0:00:00:00:00:00:00:00:01:07:b2:01:01:03:1f:1e:00:0e:29:00:00:00:45" ]
def getNextScandata(self):
self.read_index = self.read_index + 1;
if self.read_index >= len(self.LMDscandata_list):
self.read_index = 0
return self.LMDscandata_list[self.read_index]
"""
ColaResponseMap maps a cola request like "sMN SetAccessMode" to a binary cola response.
"""
class ColaResponseMap:
# Constructor
def __init__(self):
self.mapped_response = {
"sMN SetAccessMode": "02:02:02:02:00:00:00:13:73:41:4e:20:53:65:74:41:63:63:65:73:73:4d:6f:64:65:20:01:38" ,
"sWN EIHstCola": "02:02:02:02:00:00:00:0e:73:57:41:20:45:49:48:73:74:43:6f:6c:61:20:07",
"sRN FirmwareVersion": "02:02:02:02:00:00:00:1f:73:52:41:20:46:69:72:6d:77:61:72:65:56:65:72:73:69:6f:6e:20:00:09:56:31:2e:38:30:20:20:20:20:43",
"sRN SCdevicestate": "02:02:02:02:00:00:00:13:73:52:41:20:53:43:64:65:76:69:63:65:73:74:61:74:65:20:00:1f",
"sRN ODoprh": "02:02:02:02:00:00:00:0f:73:52:41:20:4f:44:6f:70:72:68:20:00:00:04:ab:c1",
"sRN ODpwrc": "02:02:02:02:00:00:00:0f:73:52:41:20:4f:44:70:77:72:63:20:00:00:00:63:1e",
"sRN LocationName": "02:02:02:02:00:00:00:1e:73:52:41:20:4c:6f:63:61:74:69:6f:6e:4e:61:6d:65:20:00:0b:53:4e:20:31:38:31:31:30:35:35:30:45",
"sRN LMPoutputRange": "02:02:02:02:00:00:00:21:73:52:41:20:4c:4d:50:6f:75:74:70:75:74:52:61:6e:67:65:20:00:01:00:00:06:83:ff:ff:3c:b0:00:1c:3a:90:cf",
"sWN LMPoutputRange": "02:02:02:02:00:00:00:13:73:57:41:20:4c:4d:50:6f:75:74:70:75:74:52:61:6e:67:65:20:74",
"sRN field000": "02:02:02:02:00:00:00:4c:73:52:41:20:66:69:65:6c:64:30:30:30:20:40:00:00:00:00:00:00:00:00:00:06:83:ff:ff:3c:b0:02:01:00:01:00:03:01:2c:ff:ff:01:62:01:d2:ff:ff:01:a3:01:e6:ff:ff:00:ce:00:00:00:00:00:00:00:01:00:0b:73:65:67:6d:65:6e:74:65:64:5f:31:00:00:6a",
"sRN field001": "02:02:02:02:00:00:00:54:73:52:41:20:66:69:65:6c:64:30:30:31:20:40:00:00:00:00:00:00:00:00:00:06:83:ff:ff:3c:b0:01:02:00:00:00:01:00:0d:bb:a0:00:7d:00:00:00:00:00:00:00:c8:00:00:00:c8:00:00:00:00:00:01:00:15:72:65:63:74:61:6e:67:6c:65:5f:66:69:65:6c:64:5f:30:5f:64:65:67:00:00:0d",
"sRN field002": "02:02:02:02:00:00:00:4f:73:52:41:20:66:69:65:6c:64:30:30:32:20:40:00:00:00:00:00:00:00:00:00:06:83:ff:ff:3c:b0:01:03:00:00:00:01:00:0f:75:6b:00:7f:00:06:dd:d0:00:00:00:c8:00:00:00:c8:00:00:00:00:00:01:00:10:72:65:63:74:66:69:65:6c:64:5f:34:35:5f:64:65:67:00:00:0b",
"sRN field003": "02:02:02:02:00:00:00:52:73:52:41:20:66:69:65:6c:64:30:30:33:20:40:00:00:00:00:00:00:00:00:00:06:83:ff:ff:3c:b0:03:04:00:00:00:00:00:00:00:01:00:1b:77:40:00:fa:00:00:00:00:00:00:03:e8:00:00:01:2c:09:60:00:00:05:dc:00:01:00:0d:64:79:6e:61:6d:69:63:5f:66:69:65:6c:64:00:00:9a",
"sRN field004": "02:02:02:02:00:00:00:2d:73:52:41:20:66:69:65:6c:64:30:30:34:20:40:00:00:00:00:00:00:00:00:00:13:88:ff:ff:3c:b0:02:00:00:00:00:00:00:00:00:00:00:01:00:00:00:00:62",
"sRN field005": "02:02:02:02:00:00:00:2d:73:52:41:20:66:69:65:6c:64:30:30:35:20:40:00:00:00:00:00:00:00:00:00:13:88:ff:ff:3c:b0:02:00:00:00:00:00:00:00:00:00:00:01:00:00:00:00:63",
"sRN field006": "02:02:02:02:00:00:00:2d:73:52:41:20:66:69:65:6c:64:30:30:36:20:40:00:00:00:00:00:00:00:00:00:13:88:ff:ff:3c:b0:02:00:00:00:00:00:00:00:00:00:00:01:00:00:00:00:60",
"sRN field007": "02:02:02:02:00:00:00:2d:73:52:41:20:66:69:65:6c:64:30:30:37:20:40:00:00:00:00:00:00:00:00:00:13:88:ff:ff:3c:b0:02:00:00:00:00:00:00:00:00:00:00:01:00:00:00:00:61",
"sRN field008": "02:02:02:02:00:00:00:2d:73:52:41:20:66:69:65:6c:64:30:30:38:20:40:00:00:00:00:00:00:00:00:00:13:88:ff:ff:3c:b0:02:00:00:00:00:00:00:00:00:00:00:01:00:00:00:00:6e",
"sRN field009": "02:02:02:02:00:00:00:2d:73:52:41:20:66:69:65:6c:64:30:30:39:20:40:00:00:00:00:00:00:00:00:00:13:88:ff:ff:3c:b0:02:00:00:00:00:00:00:00:00:00:00:01:00:00:00:00:6f",
"sRN field010": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:30:20:00:33",
"sRN field011": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:31:20:00:32",
"sRN field012": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:32:20:00:31",
"sRN field013": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:33:20:00:30",
"sRN field014": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:34:20:00:37",
"sRN field015": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:35:20:00:36",
"sRN field016": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:36:20:00:35",
"sRN field017": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:37:20:00:34",
"sRN field018": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:38:20:00:3b",
"sRN field019": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:31:39:20:00:3a",
"sRN field020": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:30:20:00:30",
"sRN field021": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:31:20:00:31",
"sRN field022": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:32:20:00:32",
"sRN field023": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:33:20:00:33",
"sRN field024": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:34:20:00:34",
"sRN field025": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:35:20:00:35",
"sRN field026": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:36:20:00:36",
"sRN field027": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:37:20:00:37",
"sRN field028": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:38:20:00:38",
"sRN field029": "02:02:02:02:00:00:00:0e:73:52:41:20:66:69:65:6c:64:30:32:39:20:00:39",
"sRN LIDinputstate": "02:02:02:02:00:00:00:29:73:52:41:20:4c:49:44:69:6e:70:75:74:73:74:61:74:65:20:00:00:00:29:74:2d:00:00:00:00:00:01:07:b2:01:01:00:00:02:00:07:99:50:28",
"sWN LMDscandatacfg": "02:02:02:02:00:00:00:13:73:57:41:20:4c:4d:44:73:63:61:6e:64:61:74:61:63:66:67:20:4d",
"sRN LMDscandatacfg": "02:02:02:02:00:00:00:20:73:52:41:20:4c:4d:44:73:63:61:6e:64:61:74:61:63:66:67:20:01:00:01:00:00:00:00:00:00:00:01:00:01:48",
"sMN LMCstartmea": "02:02:02:02:00:00:00:12:73:41:4e:20:4c:4d:43:73:74:61:72:74:6d:65:61:73:20:00:44",
"sMN Run": "02:02:02:02:00:00:00:09:73:41:4e:20:52:75:6e:20:01:34",
"sEN LMDscandata": "02:02:02:02:00:00:00:11:73:45:41:20:4c:4d:44:73:63:61:6e:64:61:74:61:20:01:3c",
"sEN LFErec": "02:02:02:02:00:00:00:0c:73:45:41:20:4c:46:45:72:65:63:20:01:4d",
"sEN LIDoutputstate": "02:02:02:02:00:00:00:14:73:45:41:20:4c:49:44:6f:75:74:70:75:74:73:74:61:74:65:20:01:5f",
"sEN LIDinputstate": "02:02:02:02:00:00:00:13:73:45:41:20:4c:49:44:69:6e:70:75:74:73:74:61:74:65:20:01:36"
}
# Search for a mapped response given a cola request and returns key and response as strings
def findBinaryResponse(self, request):
for key, response in self.mapped_response.items():
if request.find(stringToByteArray(key)) >= 0:
return key, response
return "", ""
"""
TestServer connects to a tcp client, receives binary cola telegrams and sends a response to the client.
"""
class TestServer:
# Constructor
def __init__(self, tcp_port = 2112):
self.tcp_port = tcp_port
# Waits for an incoming tcp connection and connects to the tcp client
def connect(self):
self.serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.serversocket.bind(("", self.tcp_port))
print("TestServer: listening on tcp port {}".format(self.tcp_port))
self.serversocket.listen(1)
(clientsocket, clientaddress) = self.serversocket.accept()
self.clientsocket = clientsocket
self.clientaddress = clientaddress
self.clientsocket.setblocking(0)
print("TestServer: tcp connection to {} established".format(self.clientaddress))
# Receives a binary cola telegram and returns its payload (i.e. the telegram without header and CRC)
def receiveBinaryTelegram(self, recv_timeout_sec):
ready_to_recv = select.select([self.clientsocket], [], [], recv_timeout_sec)
if not ready_to_recv[0]:
return ""
header = self.clientsocket.recv(8)
payload_length = parseBinaryColaPayloadLength(header) # message := { 4 byte STX 0x02020202 } + { 4 byte message_payload_length } + { message_payload } + { 1 byte CRC }
if payload_length <= 1:
print("## ERROR TestServer.receiveBinaryTelegram(): unexpected payload_length {} in received header {}".format(payload_length, header))
return header
payload = bytearray(b"")
while len(payload) < payload_length:
chunk = self.clientsocket.recv(payload_length - len(payload))
payload = payload + chunk
crc = bytearray(b"")
while len(crc) < 1:
crc = self.clientsocket.recv(1)
print("TestServer.receiveBinaryTelegram(): received {} byte telegram {}".format((len(header) + len(payload) + 1), payload))
return payload
# Sends a binary cola telegram "as is"
def sendBinaryTelegram(self, telegram, verbosity):
if verbosity > 1:
print("TestServer.sendBinaryTelegram(): sending {} byte telegram {}".format((len(telegram)), telegram))
elif verbosity > 0:
print("TestServer.sendBinaryTelegram(): sending {} byte telegram".format(len(telegram)))
self.clientsocket.send(telegram)
# Runs the message loop, i.e. receives binary cola telegrams and sends a response to the client
def run(self, send_scandata_frequency, scandata_file):
response_map = ColaResponseMap()
scandata_generator = ColaLMDscandataGenerator(scandata_file)
receive_timeout = max(0.001, 1.0 / send_scandata_frequency)
time_to_send_scandata = datetime.datetime.now() + datetime.timedelta(seconds=3600*24*364)
print("TestServer: running main loop...")
while True:
# Receive a cola telegram
received_telegram = self.receiveBinaryTelegram(receive_timeout)
if len(received_telegram) <= 0: # timeout (no message rececived)
if datetime.datetime.now() >= time_to_send_scandata: # send LMDscandata
scandata_str = scandata_generator.getNextScandata()
self.sendBinaryTelegram(hexStringToByteArray(scandata_str), 1)
time_to_send_scandata = datetime.datetime.now() + datetime.timedelta(seconds=receive_timeout)
continue;
# Lookup for keywords and send a response from predefined (mapped) responses
request_key, response_str = response_map.findBinaryResponse(received_telegram)
if len(request_key) > 0 and len(response_str) > 0: # request and response found in map, send response to client
print("TestServer: received {}: {}".format(request_key, received_telegram))
self.sendBinaryTelegram(hexStringToByteArray(response_str), 2)
if request_key.find("sMN Run") >= 0: # start to send LMDscandata in 2 seconds
time_to_send_scandata = datetime.datetime.now() + datetime.timedelta(seconds=2)
elif len(received_telegram) > 0: # request not found in map
print("## ERROR TestServer: received unsupported telegram {}".format(received_telegram))
time.sleep(0.01)
if __name__ == "__main__":
# Configuration
tcp_port = 2112 # tcp port to listen for tcp connections
send_data_frequency = 2.0 # send LMDscandata with 2 Hz
scandata_file = "../test/emulator/scandata/20210302_lms511.pcapng.scandata.txt" # read LMDscandata from file
# Overwrite with command line arguments
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("--scandata_file", help="scandata filepath", default=scandata_file, type=str)
arg_parser.add_argument("--scandata_frequency", help="frequency in Hz to send scandata telegrams", default=send_data_frequency, type=float)
arg_parser.add_argument("--tcp_port", help="tcp port to listen for tcp connections", default=tcp_port, type=int)
cli_args = arg_parser.parse_args()
scandata_file = cli_args.scandata_file
send_data_frequency = cli_args.scandata_frequency
tcp_port = cli_args.tcp_port
# Run test server
server = TestServer(tcp_port)
server.connect()
server.run(send_data_frequency, scandata_file)
| 115.288288
| 10,700
| 0.655779
| 6,330
| 25,594
| 2.626224
| 0.084676
| 0.082531
| 0.098532
| 0.124158
| 0.288799
| 0.251143
| 0.239112
| 0.22263
| 0.212043
| 0.195079
| 0
| 0.336239
| 0.099086
| 25,594
| 221
| 10,701
| 115.809955
| 0.384725
| 0.073806
| 0
| 0
| 0
| 0.302469
| 0.731615
| 0.681146
| 0
| 0
| 0
| 0
| 0
| 1
| 0.074074
| false
| 0
| 0.030864
| 0.006173
| 0.179012
| 0.061728
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 7
|
a15376c189682f5e1aec0bdb795e9774ca5565b3
| 18,001
|
py
|
Python
|
build/langs.py
|
fourpoints/plusMarkup
|
0b8ef4b871044c5bf83fa7f867bad953e938d603
|
[
"MIT"
] | 1
|
2017-07-10T18:26:15.000Z
|
2017-07-10T18:26:15.000Z
|
build/langs.py
|
fourpoints/plusMarkup
|
0b8ef4b871044c5bf83fa7f867bad953e938d603
|
[
"MIT"
] | null | null | null |
build/langs.py
|
fourpoints/plusMarkup
|
0b8ef4b871044c5bf83fa7f867bad953e938d603
|
[
"MIT"
] | null | null | null |
"""
Language interpreting classes.
TODO:
* This file is riddled with pasta. Make more parent classes where it's needed.
* Make attributes attach to last attribute in custom tags.
* Ignore closing tags for selfclosing tags in custom tags.
* A tags .au-attributes are ignored in custom tags if the attribute doesn't in its custom tag.
* Multiline attributes will use the indentation of the last attribute line.
* Ignore space after attributes
* def __init__(**kwargs, attributes = {}) does not create new dict for new calls (?)
"""
from .blocks import *
from .tags import *
from .filemanager import *
from functools import partial, update_wrapper
class Lang:
def __init__(self, I, O, block, offset = 0, tag = None, attributes = {}):
self.I = I #Input/read file
self.O = O #Output/write file
self.offset = False #Set to True if one wants to offset the block back to the base (0-indentation)
self.tag = tag #this is a string
self.attributes = attributes #this is a dictionary
self.block = update_wrapper(partial(block, self), block) #defined in blocks.py; defines a method for the class.
# Languages
class Blank(Lang):
def next_token(self, *args):
return self.I.match(HTML.escape, HTML.newfile, *HTML.tokens, *args)
def opening_tag(self):
pass
def closing_tag(self):
pass
def routine(self, token):
if token == '+' or token == '@':
tag, attributes, has_bracketed_content, selfclosing = self.I.tagattr()
if tag == '': #empty tag
self.O.indents(count = self.I.indent_count)
self.O.write(token+' ')
return
Lang = getlang(tag)
if selfclosing:
lang = Lang(I = self.I, O = self.O, block = selfclosing_block, tag = tag, attributes = attributes)
elif has_bracketed_content:
lang = Lang(I = self.I, O = self.O, block = bracketed_block, tag = tag, attributes = attributes)
else:
if token == '+':
lang = Lang(I = self.I, O = self.O, block = indented_block, tag = tag, attributes = attributes)
else: #if token == '@':
lang = Lang(I = self.I, O = self.O, block = wrapping_block, tag = tag, attributes = attributes)
lang.block()
elif token == "//":
self.O.indents(count = self.I.indent_count)
self.O.write(f"<!-- {self.I.popto(len(self.I.line)).strip()} -->")
elif token == '+("':
self.O.indents(count = self.I.indent_count)
index, end = self.I.match('")')
filename = self.I.popto(index)
self.I.popto(len(end))
with open(filename, mode='r') as read_file:
IFile = Filereader(read_file, indent = INDENT, offset = self.I.indent_count)
#Define block type
lang = Blank(I = IFile, O = self.O, block = wrapping_block, tag = None, attributes = {})
#Start default interpreter
lang.block()
elif token == '\\':
self.O.write(self.I.popto(1))
class HTML(Lang):
tokens = {'+', '@', '//'}
newfile = '+("'
escape = '\\'
def __init__(self, **kwa):
super().__init__(**kwa)
def next_token(self, *args):
return self.I.match(HTML.escape, HTML.newfile, *HTML.tokens, *args)
def opening_tag(self):
self.O.indents(count = self.I.indent_count)
opening_tag = f"<{self.tag}"
for name, value in self.attributes.items():
if value:
opening_tag += f' {name}="{value}"'
else: #binary attribute
opening_tag += f' {name}'
if self.tag.lower() not in SELFCLOSING:
opening_tag += '>'
else:
opening_tag += '>'
self.O.write(opening_tag)
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
self.O.write(f'</{self.tag}>')
def routine(self, token):
if token == '+' or token == '@':
tag, attributes, has_bracketed_content, selfclosing = self.I.tagattr()
print(tag)
if tag == '': #empty tag
self.O.indents(count = self.I.indent_count)
self.O.write(token+' ')
return
Lang = getlang(tag)
if selfclosing:
lang = Lang(I = self.I, O = self.O, block = selfclosing_block, tag = tag, attributes = attributes)
elif has_bracketed_content:
lang = Lang(I = self.I, O = self.O, block = bracketed_block, tag = tag, attributes = attributes)
else:
if token == '+':
lang = Lang(I = self.I, O = self.O, block = indented_block, tag = tag, attributes = attributes)
else: #if token == '@':
lang = Lang(I = self.I, O = self.O, block = wrapping_block, tag = tag, attributes = attributes)
lang.block()
elif token == '//':
self.O.indents(count = self.I.indent_count)
self.O.write(f"<!-- {self.I.popto(len(self.I.line)).strip()} -->")
elif token == '+("':
self.O.indents(count = self.I.indent_count)
index, end = self.I.match('")')
filename = self.I.popto(index)
self.I.popto(len(end))
with open(filename, mode='r') as read_file:
IFile = Filereader(read_file, indent = INDENT, offset = self.I.indent_count)
#Define block type
lang = Blank(I = IFile, O = self.O, block = wrapping_block, tag = None, attributes = {})
#Start default interpreter
lang.block()
elif token == '\\':
self.O.indents(count = self.I.indent_count)
self.O.write(self.I.popto(1))
class CustomHTML(Lang):
def __init__(self, **kwa):
super().__init__(**kwa)
self.offset = has_offset(self.tag)
def next_token(self, *args):
return self.I.match(HTML.escape, HTML.newfile, *HTML.tokens, *args)
def opening_tag(self):
"""pls rewrite, this is uglee"""
if (not self.O.empty_line) and self.offset:
self.O.newline()
self.O.indents(count = self.I.indent_count)
tags_and_attributes_from_json = get_tags_and_attributes_from_json(self.tag)
first_tag = tags_and_attributes_from_json.pop(0)
if "attributes" in first_tag:
self.O.write(f'<{first_tag.get("html5tag")}')
for name, value in first_tag["attributes"].items():
if name in self.attributes and value:
self.O.write(f' {name}="{value} {self.attributes[name]}"')
self.attributes.pop(name)
elif value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
else:
self.O.write(f'<{first_tag.get("html5tag")}')
for name, value in self.attributes.items():
if value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
for tag in tags_and_attributes_from_json:
if "attributes" in tag:
self.O.write(f'<{tag.get("html5tag")}')
for name, value in tag["attributes"].items():
if value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
else:
self.O.write(f'<{tag.get("html5tag")}')
self.O.write('>')
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
for tag in reversed(get_tags_and_attributes_from_json(self.tag)):
self.O.write(f'</{tag.get("html5tag")}>')
def routine(self, token):
if token == '+' or token == '@':
tag, attributes, has_bracketed_content, selfclosing = self.I.tagattr()
if tag == '': #empty tag
self.O.indents(count = self.I.indent_count)
self.O.write(token)
return
Lang = getlang(tag)
if selfclosing:
lang = Lang(I = self.I, O = self.O, block = selfclosing_block, tag = tag, attributes = attributes)
elif has_bracketed_content:
lang = Lang(I = self.I, O = self.O, block = bracketed_block, tag = tag, attributes = attributes)
else:
if token == '+':
lang = Lang(I = self.I, O = self.O, block = indented_block, tag = tag, attributes = attributes)
else: #if token == '@':
lang = Lang(I = self.I, O = self.O, block = wrapping_block, tag = tag, attributes = attributes)
lang.block()
elif token == "//":
self.O.indents(count = self.I.indent_count)
self.O.write(f"<!-- {self.I.popto(len(self.I.line)).strip()} -->")
elif token == '+("':
self.O.indents(count = self.I.indent_count)
index, end = self.I.match('")')
filename = self.I.popto(index)
self.I.popto(len(end))
with open(filename, mode='r') as read_file:
IFile = Filereader(read_file, indent = INDENT, offset = self.I.indent_count)
#Define block type
lang = Blank(I = IFile, O = self.O, block = wrapping_block, tag = None, attributes = {})
#Start default interpreter
lang.block()
elif token == '\\':
self.O.indents(count = self.I.indent_count)
self.O.write(self.I.popto(1))
class CustomNonHTML(Lang):
def __init__(self, **kwa):
super().__init__(**kwa)
self.offset = has_offset(self.tag)
def next_token(self, *args):
return self.I.match(*args)
def opening_tag(self):
"""pls rewrite, this is uglee"""
if (not self.O.empty_line) and self.offset:
self.O.newline()
self.O.indents(count = self.I.indent_count)
tags_and_attributes_from_json = None
if self.block.__name__ == "bracketed_block":
inline_tag = f"{self.tag}-inline"
try:
tags_and_attributes_from_json = get_tags_and_attributes_from_json(inline_tag)
except KeyError:
tags_and_attributes_from_json = get_tags_and_attributes_from_json(self.tag)
else:
tags_and_attributes_from_json = get_tags_and_attributes_from_json(self.tag)
print(self.I.line_number)
first_tag = tags_and_attributes_from_json.pop(0)
if "attributes" in first_tag:
self.O.write(f'<{first_tag.get("html5tag")}')
for name, value in first_tag["attributes"].items():
if name in self.attributes and value:
self.O.write(f' {name}="{value} {self.attributes[name]}"')
self.attributes.pop(name)
elif value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
else:
self.O.write(f'<{first_tag.get("html5tag")}')
for name, value in self.attributes.items():
if value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
for tag in tags_and_attributes_from_json:
if "attributes" in tag:
self.O.write(f'<{tag.get("html5tag")}')
for name, value in tag["attributes"].items():
if value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
else:
self.O.write(f'<{tag.get("html5tag")}')
self.O.write('>')
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
for tag in reversed(get_tags_and_attributes_from_json(self.tag)):
self.O.write(f'</{tag.get("html5tag")}>')
def routine(self, token):
if token == '+' or token == '@':
tag, attributes, has_bracketed_content, selfclosing = self.I.tagattr()
if tag == '': #empty tag
self.O.indents(count = self.I.indent_count)
self.O.write(token)
return
Lang = getlang(tag)
if selfclosing:
lang = Lang(I = self.I, O = self.O, block = selfclosing_block, tag = tag, attributes = attributes)
elif has_bracketed_content:
lang = Lang(I = self.I, O = self.O, block = bracketed_block, tag = tag, attributes = attributes)
else:
if token == '+':
lang = Lang(I = self.I, O = self.O, block = indented_block, tag = tag, attributes = attributes)
else: #if token == '@':
lang = Lang(I = self.I, O = self.O, block = wrapping_block, tag = tag, attributes = attributes)
lang.block()
elif token == "//":
self.O.indents(count = self.I.indent_count)
self.O.write(f"<!-- {self.I.popto(len(self.I.line)).strip()} -->")
elif token == '+("':
self.O.indents(count = self.I.indent_count)
index, end = self.I.match('")')
filename = self.I.popto(index)
self.I.popto(len(end))
with open(filename, mode='r') as read_file:
IFile = Filereader(read_file, indent = INDENT, offset = self.I.indent_count)
#Define block type
lang = Blank(I = IFile, O = self.O, block = wrapping_block, tag = None, attributes = {})
#Start default interpreter
lang.block()
elif token == '\\':
self.O.indents(count = self.I.indent_count)
self.O.write(self.I.popto(1))
class Pre(Lang):
def __init__(self, **kwa):
super().__init__(**kwa)
self.offset = True
def next_token(self, *args):
return self.I.match(HTML.escape, HTML.newfile, *HTML.tokens, *args)
def opening_tag(self):
if not self.O.empty_line:
self.O.newline()
self.O.indents(count = self.I.indent_count)
opening_tag = f"<{self.tag}"
for name, value in self.attributes.items():
if value:
opening_tag += f' {name}="{value}"'
else: #binary attribute
opening_tag += f' {name}'
if self.tag.lower() not in SELFCLOSING:
opening_tag += '>'
else:
opening_tag += '>'
self.O.write(opening_tag)
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
self.O.write(f'</{self.tag}>')
def routine(self, token):
if token == '+' or token == '@':
tag, attributes, has_bracketed_content, selfclosing = self.I.tagattr()
if tag == '': #empty tag
self.O.indents(count = self.I.indent_count)
self.O.write(token)
return
Lang = getlang(tag)
if selfclosing:
lang = Lang(I = self.I, O = self.O, block = selfclosing_block, tag = tag, attributes = attributes)
elif has_bracketed_content:
lang = Lang(I = self.I, O = self.O, block = bracketed_block, tag = tag, attributes = attributes)
else:
if token == '+':
lang = Lang(I = self.I, O = self.O, block = indented_block, tag = tag, attributes = attributes)
else: #if token == '@':
lang = Lang(I = self.I, O = self.O, block = wrapping_block, tag = tag, attributes = attributes)
lang.block()
elif token == "//":
self.O.indents(count = self.I.indent_count)
self.O.write(f"<!-- {self.I.popto(len(self.I.line)).strip()} -->")
elif token == '+("':
self.O.indents(count = self.I.indent_count)
index, end = self.I.match('")')
filename = self.I.popto(index)
self.I.popto(len(end))
with open(filename, mode='r') as read_file:
IFile = Filereader(read_file, indent = INDENT, offset = self.I.indent_count)
#Define block type
lang = Blank(I = IFile, O = self.O, block = wrapping_block, tag = None, attributes = {})
#Start default interpreter
lang.block()
elif token == '\\':
self.O.indents(count = self.I.indent_count)
self.O.write(self.I.popto(1))
class Script(Lang):
def __init__(self, **kwa):
super().__init__(**kwa)
def next_token(self, *args):
return self.I.match(*args)
def opening_tag(self):
self.O.indents(count = self.I.indent_count)
opening_tag = f"<{self.tag}"
for name, value in self.attributes.items():
if value:
opening_tag += f' {name}="{value}"'
else: #binary attribute
opening_tag += f' {name}'
if self.tag.lower() not in SELFCLOSING:
opening_tag += '>'
else:
opening_tag += '>'
self.O.write(opening_tag)
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
self.O.write(f'</{self.tag}>')
class CSS(Lang):
def __init__(self, **kwa):
super().__init__(**kwa)
def next_token(self, *args):
return self.I.match(*args)
def opening_tag(self):
self.O.indents(count = self.I.indent_count)
opening_tag = f"<{self.tag}"
for name, value in self.attributes.items():
if value:
opening_tag += f' {name}="{value}"'
else: #binary attribute
opening_tag += f' {name}'
if self.tag.lower() not in SELFCLOSING:
opening_tag += '>'
else:
opening_tag += '>'
self.O.write(opening_tag)
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
self.O.write(f'</{self.tag}>')
class Jax(Lang):
tokens = {'\\\\'}
def __init__(self, **kwa):
super().__init__(**kwa)
def next_token(self, *args):
return self.I.match(*Jax.tokens, *args)
def routine(self, token):
self.O.indents(count = self.I.indent_count)
if token == '\\\\':
tag, attributes, has_bracketed_content, selfclosing = self.I.tagattr()
if "id" in attributes:
label = attributes["id"]
self.O.write(rf"\\\label{{{label}}}")
else:
self.O.write('\\\\')
def opening_tag(self):
tags = get_tags_and_attributes_from_json(self.tag)
self.O.indents(count = self.I.indent_count)
self.O.write(rf"\begin{{{tags[0].get('jaxtag')}}}")
if "id" in self.attributes:
label = self.attributes["id"]
self.O.write(rf"\label{{{label}}}")
def closing_tag(self):
tags = get_tags_and_attributes_from_json(self.tag)
self.O.indents(count = self.I.indent_count)
self.O.write(rf"\end{{{tags[0].get('jaxtag')}}}")
class Python(Lang):
def __init__(self, **kwa):
super().__init__(**kwa)
self.offset = True
def next_token(self, *args):
return self.I.match(*args)
def opening_tag(self):
if (not self.O.empty_line) and self.offset:
self.O.newline()
self.O.indents(count = self.I.indent_count)
tags_and_attributes_from_json = get_tags_and_attributes_from_json(self.tag)
first_tag = tags_and_attributes_from_json.pop(0)
if "attributes" in first_tag:
self.O.write(f'<{first_tag.get("html5tag")}')
for name, value in first_tag["attributes"].items():
if name in self.attributes and value:
self.O.write(f' {name}="{value} {self.attributes[name]}"')
elif value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
self.O.write('>')
else:
self.O.write(f'<{first_tag.get("html5tag")}>')
for tag in tags_and_attributes_from_json:
if "attributes" in tag:
self.O.write(f'<{tag.get("html5tag")}')
for name, value in tag["attributes"].items():
if value:
self.O.write(f' {name}="{value}"')
else: #binary attribute
self.O.write(f' {name}')
self.O.write('>')
else:
self.O.write(f'<{tag.get("html5tag")}>')
def closing_tag(self):
self.O.indents(count = self.I.indent_count)
for tag in reversed(get_tags_and_attributes_from_json(self.tag)):
self.O.write(f'</{tag.get("html5tag")}>')
def routine(self, token):
pass
| 33.459108
| 114
| 0.632243
| 2,590
| 18,001
| 4.259073
| 0.066795
| 0.061644
| 0.059831
| 0.042879
| 0.890762
| 0.890762
| 0.890762
| 0.890762
| 0.881425
| 0.87798
| 0
| 0.001885
| 0.204322
| 18,001
| 537
| 115
| 33.521415
| 0.768275
| 0.072885
| 0
| 0.890411
| 0
| 0
| 0.092281
| 0.044091
| 0
| 0
| 0
| 0.001862
| 0
| 1
| 0.098174
| false
| 0.006849
| 0.009132
| 0.020548
| 0.171233
| 0.004566
| 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
|
a16049e5c288db1d510f2d52369f2bd97234b48c
| 10,016
|
py
|
Python
|
api/migrations/0001_initial.py
|
jcasmer/grow_control_backend-
|
6a18a137e0a16138607413925727d7e5f8486777
|
[
"BSD-3-Clause"
] | 1
|
2019-05-11T14:45:47.000Z
|
2019-05-11T14:45:47.000Z
|
api/migrations/0001_initial.py
|
jcasmer/grow_control_backend-
|
6a18a137e0a16138607413925727d7e5f8486777
|
[
"BSD-3-Clause"
] | 6
|
2021-03-18T20:45:02.000Z
|
2021-09-22T17:41:38.000Z
|
api/migrations/0001_initial.py
|
jcasmer/grow_control_backend-
|
6a18a137e0a16138607413925727d7e5f8486777
|
[
"BSD-3-Clause"
] | null | null | null |
# Generated by Django 2.0.4 on 2018-04-15 23:14
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Advices',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creación')),
('updated_at', models.DateTimeField(null=True, verbose_name='Fecha de modificación')),
('deleted', models.BooleanField(default=False, verbose_name='Eliminado')),
('description', models.TextField(verbose_name='Descripción')),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='api_advices_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Creado por')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Childs',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creación')),
('updated_at', models.DateTimeField(null=True, verbose_name='Fecha de modificación')),
('deleted', models.BooleanField(default=False, verbose_name='Eliminado')),
('document', models.CharField(max_length=20, verbose_name='Documento')),
('name', models.CharField(max_length=150, verbose_name='Nombre')),
('gender', models.CharField(choices=[('Masculino', 'Masculino'), ('Femenino', 'Femenino')], max_length=50, verbose_name='Genero')),
('date_born', models.DateTimeField(verbose_name='Fecha de nacimiento')),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='api_childs_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Creado por')),
('updated_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='api_childs_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Modificado por')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ChildsDetail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creación')),
('updated_at', models.DateTimeField(null=True, verbose_name='Fecha de modificación')),
('deleted', models.BooleanField(default=False, verbose_name='Eliminado')),
('age', models.CharField(max_length=3, verbose_name='Edad')),
('height', models.FloatField(verbose_name='Altura')),
('weight', models.FloatField(verbose_name='Peso')),
('child', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.Childs', verbose_name='Niño(a)')),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='api_childsdetail_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Creado por')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Parents',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creación')),
('updated_at', models.DateTimeField(null=True, verbose_name='Fecha de modificación')),
('deleted', models.BooleanField(default=False, verbose_name='Eliminado')),
('document_type', models.CharField(choices=[('Cedula', 'Cédula'), ('Cedula Extranjeria', 'Extranjería')], max_length=100, verbose_name='Tipo de documento')),
('document', models.CharField(max_length=20, verbose_name='Documento')),
('name', models.CharField(max_length=150, verbose_name='Nombre')),
('age', models.CharField(max_length=3, verbose_name='Edad')),
('gender', models.CharField(choices=[('Masculino', 'Masculino'), ('Femenino', 'Femenino')], max_length=50, verbose_name='Genero')),
('phone_number', models.CharField(max_length=20, verbose_name='Teléfono')),
('email', models.EmailField(max_length=254, verbose_name='Correo Electrónico')),
('social_stratum', models.CharField(choices=[('0', 'Estrato 0'), ('1', 'Estrato 1'), ('2', 'Estrato 2'), ('3', 'Estrato 3'), ('4', 'Estrato 4'), ('5', 'Estrato 5'), ('6', 'Estrato 6')], max_length=3, verbose_name='Estrato')),
('height', models.FloatField(verbose_name='Altura')),
('weight', models.FloatField(verbose_name='Peso')),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='api_parents_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Creado por')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='ParentsChilds',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('child', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.Childs', verbose_name='Niño(a)')),
('parent', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.Parents', verbose_name='Adulto')),
],
),
migrations.CreateModel(
name='Relationship',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creación')),
('updated_at', models.DateTimeField(null=True, verbose_name='Fecha de modificación')),
('deleted', models.BooleanField(default=False, verbose_name='Eliminado')),
('name', models.CharField(max_length=150, verbose_name='Parentesco')),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='api_relationship_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Creado por')),
('updated_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='api_relationship_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Modificado por')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='TypeDiagnostic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Fecha de creación')),
('updated_at', models.DateTimeField(null=True, verbose_name='Fecha de modificación')),
('deleted', models.BooleanField(default=False, verbose_name='Eliminado')),
('name', models.CharField(max_length=150, verbose_name='Tipo Diagnostico')),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='api_typediagnostic_created_by', to=settings.AUTH_USER_MODEL, verbose_name='Creado por')),
('updated_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='api_typediagnostic_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Modificado por')),
],
options={
'abstract': False,
},
),
migrations.AddField(
model_name='parents',
name='relationship',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.Relationship', verbose_name='Parentesco'),
),
migrations.AddField(
model_name='parents',
name='updated_by',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='api_parents_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Modificado por'),
),
migrations.AddField(
model_name='childsdetail',
name='type_diagnostic',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.TypeDiagnostic', verbose_name='Tipo de Diagnostico'),
),
migrations.AddField(
model_name='childsdetail',
name='updated_by',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='api_childsdetail_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Modificado por'),
),
migrations.AddField(
model_name='advices',
name='type_diagnostic',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='api.TypeDiagnostic', verbose_name='Tipo de Diagnostico'),
),
migrations.AddField(
model_name='advices',
name='updated_by',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, related_name='api_advices_updated_by', to=settings.AUTH_USER_MODEL, verbose_name='Modificado por'),
),
]
| 63.392405
| 241
| 0.629692
| 1,066
| 10,016
| 5.698874
| 0.125704
| 0.114074
| 0.043786
| 0.068807
| 0.859588
| 0.856132
| 0.839671
| 0.83358
| 0.83358
| 0.819424
| 0
| 0.007761
| 0.228135
| 10,016
| 157
| 242
| 63.796178
| 0.778036
| 0.004493
| 0
| 0.693333
| 1
| 0
| 0.191092
| 0.029692
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.02
| 0
| 0.046667
| 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
|
62bae79013c89f80f9627c5ed622b81269aecb2d
| 8,086
|
py
|
Python
|
venv/lib/python3.8/site-packages/spaceone/api/power_scheduler/v1/domain_pb2_grpc.py
|
choonho/plugin-prometheus-mon-webhook
|
afa7d65d12715fd0480fb4f92a9c62da2d6128e0
|
[
"Apache-2.0"
] | null | null | null |
venv/lib/python3.8/site-packages/spaceone/api/power_scheduler/v1/domain_pb2_grpc.py
|
choonho/plugin-prometheus-mon-webhook
|
afa7d65d12715fd0480fb4f92a9c62da2d6128e0
|
[
"Apache-2.0"
] | null | null | null |
venv/lib/python3.8/site-packages/spaceone/api/power_scheduler/v1/domain_pb2_grpc.py
|
choonho/plugin-prometheus-mon-webhook
|
afa7d65d12715fd0480fb4f92a9c62da2d6128e0
|
[
"Apache-2.0"
] | null | null | null |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2
from spaceone.api.power_scheduler.v1 import domain_pb2 as spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2
class DomainStub(object):
"""Missing associated documentation comment in .proto file."""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.enable = channel.unary_unary(
'/spaceone.api.power_scheduler.v1.Domain/enable',
request_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.SerializeToString,
response_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainInfo.FromString,
)
self.disable = channel.unary_unary(
'/spaceone.api.power_scheduler.v1.Domain/disable',
request_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.SerializeToString,
response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString,
)
self.get = channel.unary_unary(
'/spaceone.api.power_scheduler.v1.Domain/get',
request_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.SerializeToString,
response_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainInfo.FromString,
)
self.list = channel.unary_unary(
'/spaceone.api.power_scheduler.v1.Domain/list',
request_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainQuery.SerializeToString,
response_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainsInfo.FromString,
)
class DomainServicer(object):
"""Missing associated documentation comment in .proto file."""
def enable(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def disable(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def get(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def list(self, request, context):
"""Missing associated documentation comment in .proto file."""
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!')
def add_DomainServicer_to_server(servicer, server):
rpc_method_handlers = {
'enable': grpc.unary_unary_rpc_method_handler(
servicer.enable,
request_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.FromString,
response_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainInfo.SerializeToString,
),
'disable': grpc.unary_unary_rpc_method_handler(
servicer.disable,
request_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.FromString,
response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString,
),
'get': grpc.unary_unary_rpc_method_handler(
servicer.get,
request_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.FromString,
response_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainInfo.SerializeToString,
),
'list': grpc.unary_unary_rpc_method_handler(
servicer.list,
request_deserializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainQuery.FromString,
response_serializer=spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainsInfo.SerializeToString,
),
}
generic_handler = grpc.method_handlers_generic_handler(
'spaceone.api.power_scheduler.v1.Domain', rpc_method_handlers)
server.add_generic_rpc_handlers((generic_handler,))
# This class is part of an EXPERIMENTAL API.
class Domain(object):
"""Missing associated documentation comment in .proto file."""
@staticmethod
def enable(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, '/spaceone.api.power_scheduler.v1.Domain/enable',
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.SerializeToString,
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainInfo.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def disable(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, '/spaceone.api.power_scheduler.v1.Domain/disable',
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.SerializeToString,
google_dot_protobuf_dot_empty__pb2.Empty.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def get(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, '/spaceone.api.power_scheduler.v1.Domain/get',
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainRequest.SerializeToString,
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainInfo.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
@staticmethod
def list(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, '/spaceone.api.power_scheduler.v1.Domain/list',
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainQuery.SerializeToString,
spaceone_dot_api_dot_power__scheduler_dot_v1_dot_domain__pb2.DomainsInfo.FromString,
options, channel_credentials,
insecure, call_credentials, compression, wait_for_ready, timeout, metadata)
| 48.419162
| 131
| 0.697626
| 866
| 8,086
| 6.053118
| 0.118938
| 0.085464
| 0.058756
| 0.071347
| 0.880771
| 0.87562
| 0.863983
| 0.821061
| 0.796261
| 0.73636
| 0
| 0.009668
| 0.232501
| 8,086
| 166
| 132
| 48.710843
| 0.834998
| 0.077789
| 0
| 0.593985
| 1
| 0
| 0.081517
| 0.053893
| 0
| 0
| 0
| 0
| 0
| 1
| 0.075188
| false
| 0
| 0.022556
| 0.030075
| 0.150376
| 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
|
62d8c2b145fc42197294d8d024dcc48c49f01a28
| 9,646
|
py
|
Python
|
tool/LITESCRIPT.py
|
Err0r-ICA/JAR
|
443e68f786f724d4874fbd2f5b34c8818c1fcb32
|
[
"MIT"
] | 55
|
2020-04-18T11:02:34.000Z
|
2022-02-27T14:03:16.000Z
|
tool/LITESCRIPT.py
|
yabuna/JAR
|
443e68f786f724d4874fbd2f5b34c8818c1fcb32
|
[
"MIT"
] | 2
|
2020-06-17T15:20:45.000Z
|
2021-12-21T04:17:16.000Z
|
tool/LITESCRIPT.py
|
yabuna/JAR
|
443e68f786f724d4874fbd2f5b34c8818c1fcb32
|
[
"MIT"
] | 18
|
2020-04-25T21:02:11.000Z
|
2021-10-31T04:15:16.000Z
|
import marshal
exec(marshal.loads('''c\x00\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00@\x00\x00\x00s\xf6\x01\x00\x00d\x00\x00GHd\x01\x00GHd\x02\x00GHd\x03\x00GHd\x04\x00GHe\x00\x00d\x05\x00d\x06\x00\x83\x02\x00Z\x01\x00e\x02\x00d\x07\x00\x83\x01\x00Z\x03\x00e\x02\x00d\x08\x00\x83\x01\x00Z\x04\x00e\x02\x00d\t\x00\x83\x01\x00Z\x05\x00e\x02\x00d\n\x00\x83\x01\x00Z\x06\x00e\x02\x00d\x0b\x00\x83\x01\x00Z\x07\x00e\x02\x00d\x0c\x00\x83\x01\x00Z\x08\x00e\x02\x00d\r\x00\x83\x01\x00Z\t\x00e\x02\x00d\x0e\x00\x83\x01\x00Z\n\x00d\x0f\x00Z\x0b\x00e\x03\x00Z\x0c\x00d\x10\x00Z\r\x00e\x04\x00Z\x0e\x00d\x11\x00Z\x0f\x00e\x05\x00Z\x10\x00d\x12\x00Z\x11\x00d\x13\x00Z\x12\x00e\x06\x00Z\x13\x00d\x14\x00Z\x14\x00e\x07\x00Z\x15\x00d\x15\x00Z\x16\x00e\x08\x00Z\x17\x00d\x16\x00Z\x18\x00e\t\x00Z\x19\x00d\x17\x00Z\x1a\x00e\n\x00Z\x1b\x00d\x18\x00Z\x1c\x00d\x04\x00GHd\x19\x00GHe\x01\x00j\x1d\x00e\x0b\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x0c\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\r\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x0e\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x0f\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x10\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x11\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x12\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x13\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x14\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x15\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x16\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x17\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x18\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x19\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x1a\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x1b\x00\x83\x01\x00\x01e\x01\x00j\x1d\x00e\x1c\x00\x83\x01\x00\x01e\x01\x00j\x1e\x00\x83\x00\x00\x01d\x1a\x00S(\x1b\x00\x00\x00s@\x01\x00\x00\x1b[31;1m\n __ _____________________ __________ ________ ______\n / / / _/_ __/ ____/ ___// ____/ __ \\/ _/ __ \\/_ __/\n / / / / / / / __/ \\__ \\/ / / /_/ // // /_/ / / / \n \x1b[37;1m/ /____/ / / / / /___ ___/ / /___/ _, _// // ____/ / / \n/_____/___/ /_/ /_____//____/\\____/_/ |_/___/_/ /_/ \ns>\x00\x00\x00\x1b[36;1m[+]\x1b[31;1m================BETA===============\x1b[36;1m[+]sg\x00\x00\x00\x1b[32;1m Coder By : Z3R0_5TR\n Email : zerostr1337@gmail.com\n Team : Indonesia Security Lites>\x00\x00\x00\x1b[36;1m[+]\x1b[31;1m===================================\x1b[36;1m[+]s>\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m===================================\x1b[31;1m[+]s\x0c\x00\x00\x00hasilsc.htmlt\x01\x00\x00\x00ws-\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Tulis judul title :\x1b[31;1m s2\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Masukkan pesan pembuka :\x1b[31;1m s5\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Masukkan warna background :\x1b[31;1m s8\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Masukkan font di atas gambar :\x1b[31;1m s8\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Masukkan link gambar jpg/png :\x1b[31;1m s/\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Masukkan warna font :\x1b[31;1m s?\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Masukkan tulisan (<br> untuk enter) :\x1b[31;1m s%\x00\x00\x00\x1b[31;1m[+]\x1b[36;1m Thanks To :\x1b[31;1m s\x15\x00\x00\x00<html>\n<head>\n<title>s\xed\x0e\x00\x00</title>\n<font class="hk2" style="text-shadow: 1px -1px 8px;" face="tahoma">\n<font color="grey">\n<font size="5">\n<link rel=\'stylesheet\' id\'skebggallery-css\' href=\'http://shop4brides.ru/wp-content/themes/irex-lite/SketchBoard/functions/sketch-background-gallery/inc/front/css/skebggallery.css?ver=4.0.1\' type=\'text/css\' media=\'all\' />\n\t\t\t <script type=\'text/javascript\' src=\'http://shop4brides.ru/wp-includes/js/jquery/jquery.js?ver=1.11.1\'></script>\n <script type=\'text/javascript\' src=\'http://shop4brides.ru/wp-content/themes/irex-lite/SketchBoard/functions/sketch-background-gallery/inc/front/js/skebggallery.js?ver=4.0.1\'></script> \n\t\t\t <style> .error { text-align: center; font-family: \'Gilda Display\', serif; -webkit-animation: noise-3 1s linear infinite; animation: noise-3 1s linear infinite; overflow: default; } .info { text-align: center; width: 200px; height: 60px; margin: auto; position: absolute; top: 280px; bottom: 0; left: 20px; right: 0; -webkit-animation: noise-3 1s linear infinite; animation: noise-3 1s linear infinite; } .info:after { content: \'OWNED\'; font-family: OCR-A; font-size: 100px; text-align: center; width: 800px; margin: auto; position: absolute; top: 20px; bottom: 0; left: 40px; right: 0; opacity: 0; color: white; -webkit-animation: noise-1 .2s linear infinite; animation: noise-1 .2s linear infinite; } @-webkit-keyframes noise-1 { 0%, 20%, 40%, 60%, 70%, 90% {opacity: 0;} 10% {opacity: .1;} 50% {opacity: .5; left: -6px;} 80% {opacity: .3;} 100% {opacity: .6; left: 2px;} } @keyframes noise-1 { 0%, 20%, 40%, 60%, 70%, 90% {opacity: 0;} 10% {opacity: .1;} 50% {opacity: .5; left: -6px;} 80% {opacity: .3;} 100% {opacity: .6; left: 2px;} } @-webkit-keyframes noise-2 { 0%, 20%, 40%, 60%, 70%, 90% {opacity: 0;} 10% {opacity: .1;} 50% {opacity: .5; left: 6px;} 80% {opacity: .3;} 100% {opacity: .6; left: -2px;} } @keyframes noise-2 { 0%, 20%, 40%, 60%, 70%, 90% {opacity: 0;} 10% {opacity: .1;} 50% {opacity: .5; left: 6px;} 80% {opacity: .3;} 100% {opacity: .6; left: -2px;} } @-webkit-keyframes noise { 0%, 3%, 5%, 42%, 44%, 100% {opacity: 1; -webkit-transform: scaleY(1); transform: scaleY(1);} 4.3% {opacity: 1; -webkit-transform: scaleY(1.7); transform: scaleY(1.7);} 43% {opacity: 1; -webkit-transform: scaleX(1.5); transform: scaleX(1.5);} } @keyframes noise { 0%, 3%, 5%, 42%, 44%, 100% {opacity: 1; -webkit-transform: scaleY(1); transform: scaleY(1);} 4.3% {opacity: 1; -webkit-transform: scaleY(1.7); transform: scaleY(1.7);} 43% {opacity: 1; -webkit-transform: scaleX(1.5); transform: scaleX(1.5);} } @-webkit-keyframes noise-3 { 0%,3%,5%,42%,44%,100% {opacity: 1; -webkit-transform: scaleY(1); transform: scaleY(1);} 4.3% {opacity: 1; -webkit-transform: scaleY(4); transform: scaleY(4);} 43% {opacity: 1; -webkit-transform: scaleX(10) rotate(60deg); transform: scaleX(10) rotate (60deg);} } @keyframes noise-3 { 0%,3%,5%,42%,44%,100% {opacity: 1; -webkit-transform: scaleY(1); transform: scaleY(1);} 4.3% {opacity: 1; -webkit-transform: scaleY(4); transform: scaleY(4);} 43% {opacity: 1; -webkit-transform: scaleX(10) rotate(60deg); transform: scaleX(10) rotate (60deg);} } .wrap { top: 30%; left: 25%; height: 200px; margin-top: -100px; position: absolute; } code { color: white; } span.blue { color: #48beef; } span.comment { color: #7f8c8d; } span.orange { color: #f39c12; } span.green { color: #33cc33; } .viewFull { font-family:OCR-A; color:orange; text-decoration:; } \t } @media only screen and (min-height: 500px) { .viewFull{ display:none; \t \t} } \t</style> <center> <style> img { filter:alpha(opacity=70); -moz-opacity:0.7; opacity:0.7; } img:hover { filter:alpha(opacity=100); -moz-opacity:.0; opacity:1.0; } </style>\n\t\t\t <link href="https://fonts.googleapis.com/css?family=Chicle|Yatra+One" rel="stylesheet" type="text/css" >\n<script>\nalert("s$\x00\x00\x00");\n</script>\n</head>\n<body bgcolor=sW\x00\x00\x00>\n<script type="text/javascript" src="http://htmlfreecodes.com/codes/rain.js"></script>sA\x00\x00\x00<br><div class="error">\n<font color="red" size="7" face="Chicle">s2\x00\x00\x00\n<center>\n</font><br>\n<img style="width:50%" src="s\x15\x00\x00\x00"></div>\n<font color=s,\x00\x00\x00>\n<br>\n<b><font face="courier new" size=\'6\'>s\x9e\x01\x00\x00\n<marquee behavior="scroll" direction="left" scrollamount="90" scrolldelay="40" width="100%">\n<font color="green">___________________________________________________________</font></marquee>\n<div style="text-shadow: 0px 0px 10px green;"><span style="color: white;"><font face="transformers"><b>Thanks To : <marquee scrollamount="5" direction="left" width="50%"><span style="color: red;"> <span style="color: red;">s\xfd\x01\x00\x00<span style="color: red;"></b></marquee></font></div><script type="text/rocketscript">/*<![CDATA[*/new TypingText(document.getElementById("message"), 90, function(i){ var ar= new Array("_", " ", "_", " "); return "" +ar[i.length % ar.length]; });//Type out examples:TypingText.runAll();/*]]>*/</script>\n<marquee behavior="scroll" direction="right" scrollamount="90" scrolldelay="40" width="100%">\n<font color="green">___________________________________________________________</font></marquee>\n</body>\n</html>sV\x00\x00\x00\x1b[32;1mBerhasil Membuat Script di Memori Internal\nDengan Nama "hasilsc.html" ^^\x1b[37;1mN(\x1f\x00\x00\x00t\x04\x00\x00\x00opent\x02\x00\x00\x00sct\t\x00\x00\x00raw_inputt\x05\x00\x00\x00titlet\x05\x00\x00\x00alertt\x07\x00\x00\x00bgcolort\x04\x00\x00\x00fdagt\x03\x00\x00\x00imgt\x02\x00\x00\x00wft\x03\x00\x00\x00isit\x03\x00\x00\x00thxt\x06\x00\x00\x00mulai1t\x02\x00\x00\x00m1t\x06\x00\x00\x00mulai2t\x02\x00\x00\x00m2t\x06\x00\x00\x00mulai3t\x02\x00\x00\x00m3t\x06\x00\x00\x00mulai4t\x07\x00\x00\x00mulai03t\x03\x00\x00\x00m03t\x07\x00\x00\x00mulai04t\x02\x00\x00\x00m4t\x06\x00\x00\x00mulai5t\x02\x00\x00\x00m5t\x06\x00\x00\x00mulai7t\x02\x00\x00\x00m7t\x06\x00\x00\x00mulai8t\x02\x00\x00\x00m8t\x06\x00\x00\x00mulai9t\x05\x00\x00\x00writet\x05\x00\x00\x00close(\x00\x00\x00\x00(\x00\x00\x00\x00(\x00\x00\x00\x00s\x03\x00\x00\x00<s>t\x08\x00\x00\x00<module>\t\x00\x00\x00sh\x00\x00\x00\x05\x01\x05\x03\x05\x01\x05\x01\x05\x01\x0f\x01\x0c\x01\x0c\x01\x0c\x01\x0c\x01\x0c\x01\x0c\x01\x0c\x01\x0c\x03\x06\x01\x06\x0c\x06\x01\x06\x05\x06\x01\x06\x03\x06\x02\x06\x01\x06\x04\x06\x01\x06\x03\x06\x01\x06\x04\x06\x01\x06\x05\x06\x01\x06\x06\x06\x01\x05\x01\x05\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01\r\x01'''))
| 3,215.333333
| 9,630
| 0.68982
| 1,706
| 9,646
| 3.756155
| 0.19109
| 0.101124
| 0.057584
| 0.039326
| 0.489856
| 0.449282
| 0.434145
| 0.413702
| 0.409956
| 0.308208
| 0
| 0.208301
| 0.070807
| 9,646
| 3
| 9,630
| 3,215.333333
| 0.506638
| 0
| 0
| 0
| 0
| 0.5
| 0.995542
| 0.478022
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.5
| 0
| 0.5
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 1
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 1
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 9
|
1a25379a006c45169111c4d0f3c35394a6cd87dd
| 431,753
|
py
|
Python
|
src/libspec/arm/scripts/specification/ARMv7DecodingSpec.py
|
agustingianni/retools
|
0df67fe6f21895644936c5896a33770431d86a1d
|
[
"MIT"
] | 80
|
2017-08-08T08:42:12.000Z
|
2022-03-03T13:12:05.000Z
|
src/libspec/arm/scripts/specification/ARMv7DecodingSpec.py
|
agustingianni/retools
|
0df67fe6f21895644936c5896a33770431d86a1d
|
[
"MIT"
] | 16
|
2017-08-02T14:17:07.000Z
|
2021-04-30T10:17:01.000Z
|
src/libspec/arm/scripts/specification/ARMv7DecodingSpec.py
|
agustingianni/retools
|
0df67fe6f21895644936c5896a33770431d86a1d
|
[
"MIT"
] | 6
|
2017-10-02T07:47:46.000Z
|
2020-08-18T22:03:48.000Z
|
instructions = [
{
"name" : "ADC Immediate",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "ADC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 01010 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADC Immediate",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0010101 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "ADC Register",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADCS <Rdn>, <Rm>:ADC<c> <Rdn>, <Rm>",
"pattern" : "0100000101 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock();
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "ADC Register",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "ADC{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101011010 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADC Register",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADC{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0000101 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "ADC (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADC{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0000101 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs);
setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "ADD (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADDS <Rd>, <Rn>, #<imm32>:ADD<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "0001110 imm3#3 Rn#3 Rd#3",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = !InITBlock(); imm32 = ZeroExtend(imm3, 32);"""
} , {
"name" : "ADD (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADDS <Rdn>, #<imm32>:ADD<c> <Rdn>, #<imm32>",
"pattern" : "00110 Rdn#3 imm8#8",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); setflags = !InITBlock(); imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "ADD (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "ADD{S}<c>.W <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 01000 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMN (immediate);
if Rn == '1101' then SEE ADD (SP plus immediate);
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d == 13 || (d == 15 && S == '0') || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "ADD (immediate, Thumb)",
"encoding" : "T4",
"version" : "ARMv6T2, ARMv7",
"format" : "ADDW<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 100000 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE ADR;
if Rn == '1101' then SEE ADD (SP plus immediate);
d = UInt(Rd); n = UInt(Rn); setflags = FALSE; imm32 = ZeroExtend(i:imm3:imm8, 32);
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADD (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0010100 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rn == '1111' && S == '0' then SEE ADR;
if Rn == '1101' then SEE ADD (SP plus immediate);
if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "ADD (register, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADDS <Rd>, <Rn>, <Rm>:ADD<c> <Rd>, <Rn>, <Rm>",
"pattern" : "0001100 Rm#3 Rn#3 Rd#3",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "ADD (register, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD<c> <Rdn>, <Rm>",
"pattern" : "01000100 DN#1 Rm#4 Rdn#3",
"decoder" : """if (DN:Rdn) == '1101' || Rm == '1101' then SEE ADD (SP plus register, Thumb);
d = UInt(DN:Rdn); n = d; m = UInt(Rm); setflags = FALSE; (shift_t, shift_n) = (SRType_LSL, 0);
if n == 15 && m == 15 then UNPREDICTABLE;
if d == 15 && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "ADD (register, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "ADD{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101011000 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMN (register);
if Rn == '1101' then SEE ADD (SP plus register, Thumb);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d == 13 || (d == 15 && S == '0') || n == 15 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADD (register, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0000100 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
if Rn == '1101' then SEE ADD (SP plus register, ARM);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "ADD (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0000100 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs);
setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "ADD (SP plus immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD<c> <Rd>, SP, #<imm32>",
"pattern" : "10101 Rd#3 imm8#8",
"decoder" : """d = UInt(Rd); setflags = FALSE; imm32 = ZeroExtend(imm8:'00', 32);"""
} , {
"name" : "ADD (SP plus immediate)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD<c> SP, #<imm32>",
"pattern" : "101100000 imm7#7",
"decoder" : """d = 13; setflags = FALSE; imm32 = ZeroExtend(imm7:'00', 32);"""
} , {
"name" : "ADD (SP plus immediate)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "ADD{S}<c>.W <Rd>, SP, #<imm32>",
"pattern" : "11110 i#1 01000 S#1 11010 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMN (immediate);
d = UInt(Rd); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d == 15 && S == '0' then UNPREDICTABLE;"""
} , {
"name" : "ADD (SP plus immediate)",
"encoding" : "T4",
"version" : "ARMv6T2, ARMv7",
"format" : "ADDW<c> <Rd>, SP, #<imm32>",
"pattern" : "11110 i#1 10000011010 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); setflags = FALSE; imm32 = ZeroExtend(i:imm3:imm8, 32);
if d == 15 then UNPREDICTABLE;"""
} , {
"name" : "ADD (SP plus immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD{S}<c> <Rd>, SP, #<imm32>",
"pattern" : "cond#4 0010100 S#1 1101 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "ADD (SP plus register, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD<c> <Rdm>, SP, <Rdm>",
"pattern" : "01000100 DM#1 1101 Rdm#3",
"decoder" : """d = UInt(DM:Rdm); m = UInt(DM:Rdm); setflags = FALSE;
if d == 15 && InITBlock() && !LastInITBlock() then UNPREDICTABLE;
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "ADD (SP plus register, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD<c> SP, <Rm>",
"pattern" : "01000100 1 Rm#4 101",
"decoder" : """if Rm == '1101' then SEE encoding T1;
d = 13; m = UInt(Rm); setflags = FALSE; (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "ADD (SP plus register, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "ADD{S}<c>.W <Rd>, SP, <Rm>{, <shift>}",
"pattern" : "11101011000 S#1 11010 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMN (register);
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d == 13 && (shift_t != SRType_LSL || shift_n > 3) then UNPREDICTABLE;
if (d == 15 && S == '0') || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADD (SP plus register, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADD{S}<c> <Rd>, SP, <Rm>{, <shift>}",
"pattern" : "cond#4 0000100 S#1 1101 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "ADR",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADR<c> <Rd>, #<imm32>",
"pattern" : "10100 Rd#3 imm8#8",
"decoder" : """d = UInt(Rd); imm32 = ZeroExtend(imm8:'00', 32); add = TRUE;"""
} , {
"name" : "ADR",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SUB<c>.W <Rd>, pc, #<imm32>",
"pattern" : "11110 i#1 10101011110 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); imm32 = ZeroExtend(i:imm3:imm8, 32); add = FALSE;
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADR",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "ADD<c>.W <Rd>, pc, #<imm32>",
"pattern" : "11110 i#1 10000011110 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); imm32 = ZeroExtend(i:imm3:imm8, 32); add = TRUE;
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ADR",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ADR<c> <Rd>, pc, #<imm32>",
"pattern" : "cond#4 001010001111 Rd#4 imm12#12",
"decoder" : """d = UInt(Rd); imm32 = ARMExpandImm(imm12); add = TRUE;"""
} , {
"name" : "ADR",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB<c> <Rd>, pc, #<imm32>",
"pattern" : "cond#4 001001001111 Rd#4 imm12#12",
"decoder" : """d = UInt(Rd); imm32 = ARMExpandImm(imm12); add = FALSE;"""
} , {
"name" : "AND (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "AND{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 00000 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rd == '1111' && S == '1' then SEE TST (immediate);
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1');
imm12 = i:imm3:imm8;
imm32 = ThumbExpandImm(imm12);
if d == 13 || (d == 15 && S == '0') || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "AND (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "AND{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0010000 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1');
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "AND (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ANDS <Rdn>, <Rm>:AND<c> <Rdn>, <Rm>",
"pattern" : "0100000000 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "AND (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "AND{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101010000 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE TST (register);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d == 13 || (d == 15 && S == '0') || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "AND (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "AND{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0000000 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "AND (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "AND{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0000000 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "ASR (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ASRS <Rd>, <Rm>, #<shift_n>:ASR<c> <Rd>, <Rm>, #<shift_n>",
"pattern" : "00010 imm5#5 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = !InITBlock(); (-, shift_n) = DecodeImmShift('10', imm5);"""
} , {
"name" : "ASR (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "ASR{S}<c>.W <Rd>, <Rm>, #<shift_n>",
"pattern" : "11101010010 S#1 11110 imm3#3 Rd#4 imm2#2 10 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = (S == '1'); (-, shift_n) = DecodeImmShift('10', imm3:imm2);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ASR (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ASR{S}<c> <Rd>, <Rm>, #<shift_n>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 imm5#5 100 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(-, shift_n) = DecodeImmShift('10', imm5);"""
} , {
"name" : "ASR (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ASRS <Rdn>, <Rm>:ASR<c> <Rdn>, <Rm>",
"pattern" : "0100000100 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock();"""
} , {
"name" : "ASR (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "ASR{S}<c>.W <Rd>, <Rn>, <Rm>",
"pattern" : "11111010010 S#1 Rn#4 1111 Rd#4 0000 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ASR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ASR{S}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 Rm#4 0101 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "B",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "B<c> #<label>",
"pattern" : "1101 cond#4 imm8#8",
"decoder" : """if cond == '1110' then UNDEFINED;
if cond == '1111' then SEE SVC;
imm32 = SignExtend(imm8:'0', 32);
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "B",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "B #<label>",
"pattern" : "11100 imm11#11",
"decoder" : """imm32 = SignExtend(imm11:'0', 32);
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "B",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "B<c>.W #<label>",
"pattern" : "11110 S#1 cond#4 imm6#6 10 J1#1 0 J2#1 imm11#11",
"decoder" : """if cond<3:1> == '111' then SEE "Related encodings";
imm32 = SignExtend(S:J2:J1:imm6:imm11:'0', 32);
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "B",
"encoding" : "T4",
"version" : "ARMv6T2, ARMv7",
"format" : "B.W #<label>",
"pattern" : "11110 S#1 imm10#10 10 J1#1 1 J2#1 imm11#11",
"decoder" : """I1 = NOT(J1 EOR S); I2 = NOT(J2 EOR S); imm32 = SignExtend(S:I1:I2:imm10:imm11:'0', 32);
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "BFC",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "BFC<c> <Rd>, #<lsb>, #<width>",
"pattern" : "11110011011011110 imm3#3 Rd#4 imm2#2 0 msb#5",
"decoder" : """d = UInt(Rd); msbit = UInt(msb); lsbit = UInt(imm3:imm2);
if d IN {13,15} then UNPREDICTABLE;
if msbit < lsbit then UNPREDICTABLE;"""
} , {
"name" : "BFC",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "BFC<c> <Rd>, #<lsb>, #<width>",
"pattern" : "cond#4 0111110 msb#5 Rd#4 lsb#5 0011111",
"decoder" : """d = UInt(Rd); msbit = UInt(msb); lsbit = UInt(lsb);
if d == 15 then UNPREDICTABLE;
if msbit < lsbit then UNPREDICTABLE;"""
} , {
"name" : "BFI",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "BFI<c> <Rd>, <Rn>, #<lsb>, #<width>",
"pattern" : "111100110110 Rn#4 0 imm3#3 Rd#4 imm2#2 0 msb#5",
"decoder" : """if Rn == '1111' then SEE BFC;
d = UInt(Rd); n = UInt(Rn); msbit = UInt(msb); lsbit = UInt(imm3:imm2);
if d IN {13,15} || n == 13 then UNPREDICTABLE;
if msbit < lsbit then UNPREDICTABLE;"""
} , {
"name" : "BFI",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "BFI<c> <Rd>, <Rn>, #<lsb>, #<width>",
"pattern" : "cond#4 0111110 msb#5 Rd#4 lsb#5 001 Rn#4",
"decoder" : """if Rn == '1111' then SEE BFC;
d = UInt(Rd); n = UInt(Rn); msbit = UInt(msb); lsbit = UInt(lsb);
if d == 15 then UNPREDICTABLE;
if msbit < lsbit then UNPREDICTABLE;"""
} , {
"name" : "BIC (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "BIC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 00001 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm12 = i:imm3:imm8; imm32 = ThumbExpandImm(imm12);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "BIC (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BIC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0011110 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1');
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "BIC (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BICS <Rdn>, <Rm>:BIC<c> <Rdn>, <Rm>",
"pattern" : "0100001110 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "BIC (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "BIC{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101010001 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "BIC (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BIC{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0001110 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "BIC (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BIC{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0001110 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "BKPT",
"encoding" : "T1",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "BKPT #<imm32>",
"pattern" : "10111110 imm8#8",
"decoder" : """imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "BKPT",
"encoding" : "A1",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "BKPT #<imm32>",
"pattern" : "cond#4 00010010 imm12#12 0111 imm4#4",
"decoder" : """imm32 = ZeroExtend(imm12:imm4, 32);
if cond != '1110' then UNPREDICTABLE;
"""
} , {
"name" : "BL, BLX (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BL<c> #<label>",
"pattern" : "11110 S#1 imm10#10 11 J1#1 1 J2#1 imm11#11",
"decoder" : """I1 = NOT(J1 EOR S); I2 = NOT(J2 EOR S); imm32 = SignExtend(S:I1:I2:imm10:imm11:'0', 32);
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "BL, BLX (immediate)",
"encoding" : "T2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "BLX<c> #<label>",
"pattern" : "11110 S#1 imm10H#10 11 J1#1 0 J2#1 imm10L#10 H#1",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE || H == '1' then UNDEFINED;
I1 = NOT(J1 EOR S); I2 = NOT(J2 EOR S); imm32 = SignExtend(S:I1:I2:imm10H:imm10L:'00', 32); targetInstrSet = InstrSet_ARM;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "BL, BLX (immediate)",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "BLX #<label>",
"pattern" : "1111101 H#1 imm24#24",
"decoder" : """imm32 = SignExtend(imm24:H:'0', 32); targetInstrSet = InstrSet_Thumb;"""
} , {
"name" : "BL, BLX (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BL<c> #<label>",
"pattern" : "cond#4 1011 imm24#24",
"decoder" : """imm32 = SignExtend(imm24:'00', 32); targetInstrSet = InstrSet_ARM; if cond == '1111' then SEE BL, BLX (immediate);"""
} , {
"name" : "B",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "B<c> #<label>",
"pattern" : "cond#4 1010 imm24#24",
"decoder" : """imm32 = SignExtend(imm24:'00', 32);"""
} , {
"name" : "BLX (register)",
"encoding" : "T1",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "BLX<c> <Rm>",
"pattern" : "010001111 Rm#4 000",
"decoder" : """m = UInt(Rm);
if m == 15 then UNPREDICTABLE;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "BLX (register)",
"encoding" : "A1",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "BLX<c> <Rm>",
"pattern" : "cond#4 000100101111111111110011 Rm#4",
"decoder" : """m = UInt(Rm);
if m == 15 then UNPREDICTABLE;"""
} , {
"name" : "BX",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BX<c> <Rm>",
"pattern" : "010001110 Rm#4 000",
"decoder" : """m = UInt(Rm);
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "BX",
"encoding" : "A1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "BX<c> <Rm>",
"pattern" : "cond#4 000100101111111111110001 Rm#4",
"decoder" : """m = UInt(Rm);"""
} , {
"name" : "BXJ",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "BXJ<c> <Rm>",
"pattern" : "111100111100 Rm#4 1000111100000000",
"decoder" : """m = UInt(Rm);
if m IN {13,15} then UNPREDICTABLE;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "BXJ",
"encoding" : "A1",
"version" : "ARMv5TEJ, ARMv6All, ARMv7",
"format" : "BXJ<c> <Rm>",
"pattern" : "cond#4 000100101111111111110010 Rm#4",
"decoder" : """m = UInt(Rm);
if m == 15 then UNPREDICTABLE;"""
} , {
"name" : "CPS (Thumb)",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "10110110011 im#1 0 A#1 I#1 F#1",
"decoder" : """if A:I:F == '000' then UNPREDICTABLE;
enable = (im == '0');
disable = (im == '1');
changemode = FALSE;
affectA = (A == '1');
affectI = (I == '1');
affectF = (F == '1');
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "CPS (Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "111100111010111110000 imod#2 M#1 A#1 I#1 F#1 mode#5",
"decoder" : """if imod == '00' && M == '0' then SEE "Hint instructions";
if mode != '00000' && M == '0' then UNPREDICTABLE;
if (imod<1> == '1' && A:I:F == '000') || (imod<1> == '0' && A:I:F != '000') then UNPREDICTABLE;
enable = (imod == '10');
disable = (imod == '11');
changemode = (M == '1');
affectA = (A == '1');
affectI = (I == '1');
affectF = (F == '1');
if imod == '01' || InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "CPS (ARM)",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "111100010000 imod#2 M#1 00000000 A#1 I#1 F#1 0 mode#5",
"decoder" : """if mode != '00000' && M == '0' then UNPREDICTABLE;
if (imod<1> == '1' && A:I:F == '000') || (imod<1> == '0' && A:I:F != '000') then UNPREDICTABLE;
enable = (imod == '10');
disable = (imod == '11');
changemode = (M == '1');
affectA = (A == '1');
affectI = (I == '1');
affectF = (F == '1');
if (imod == '00' && M == '0') || imod == '01' then UNPREDICTABLE;"""
} , {
"name" : "CBNZ, CBZ",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CB{N}Z <Rn>, #<label>",
"pattern" : "1011 op#1 0 i#1 1 imm5#5 Rn#3",
"decoder" : """n = UInt(Rn); imm32 = ZeroExtend(i:imm5:'0', 32); nonzero = (op == '1');
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "CDP, CDP2",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CDP<c> <coproc>, #<opc1>, <CRd>, <CRn>, <CRm>, #<opc2>",
"pattern" : "11101110 opc1#4 CRn#4 CRd#4 coproc#4 opc2#3 0 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "Floating-point instructions";
cp = UInt(coproc);"""
} , {
"name" : "CDP, CDP2",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "CDP2 <coproc>, #<opc1>, <CRd>, <CRn>, <CRm>, #<opc2>",
"pattern" : "11111110 opc1#4 CRn#4 CRd#4 coproc#4 opc2#3 0 CRm#4",
"decoder" : """cp = UInt(coproc);"""
} , {
"name" : "CDP, CDP2",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CDP<c> <coproc>, #<opc1>, <CRd>, <CRn>, <CRm>, #<opc2>",
"pattern" : "cond#4 1110 opc1#4 CRn#4 CRd#4 coproc#4 opc2#3 0 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "Floating-point instructions";
cp = UInt(coproc);"""
} , {
"name" : "CDP, CDP2",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CDP2<c> <coproc>, #<opc1>, <CRd>, <CRn>, <CRm>, #<opc2>",
"pattern" : "11111110 opc1#4 CRn#4 CRd#4 coproc#4 opc2#3 0 CRm#4",
"decoder" : """cp = UInt(coproc);"""
} , {
"name" : "CLREX",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "CLREX<c>",
"pattern" : "11110011101111111000111100101111",
"decoder" : """NOP();"""
} , {
"name" : "CLREX",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "CLREX",
"pattern" : "11110101011111111111000000011111",
"decoder" : """NOP();"""
} , {
"name" : "CLZ",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CLZ<c> <Rd>, <Rm>",
"pattern" : "111110101011 Rm_#4 1111 Rd#4 1000 Rm#4",
"decoder" : """if !Consistent(Rm) then UNPREDICTABLE;
d = UInt(Rd); m = UInt(Rm);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "CLZ",
"encoding" : "A1",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "CLZ<c> <Rd>, <Rm>",
"pattern" : "cond#4 000101101111 Rd#4 11110001 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm);
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "CMN (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CMN<c> <Rn>, #<imm32>",
"pattern" : "11110 i#1 010001 Rn#4 0 imm3#3 1111 imm8#8",
"decoder" : """n = UInt(Rn); imm32 = ThumbExpandImm(i:imm3:imm8);
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "CMN (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMN<c> <Rn>, #<imm32>",
"pattern" : "cond#4 00110111 Rn#4 0000 imm12#12",
"decoder" : """n = UInt(Rn); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "CMN (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMN<c> <Rn>, <Rm>",
"pattern" : "0100001011 Rm#3 Rn#3",
"decoder" : """n = UInt(Rn); m = UInt(Rm); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "CMN (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CMN<c>.W <Rn>, <Rm>{, <shift>}",
"pattern" : "111010110001 Rn#4 0 imm3#3 1111 imm2#2 type#2 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if n == 15 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "CMN (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMN<c> <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 00010111 Rn#4 0000 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "CMN (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMN<c> <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 00010111 Rn#4 0000 Rs#4 0 type#2 1 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); s = UInt(Rs);
shift_t = DecodeRegShift(type);
if n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "CMP (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMP<c> <Rn>, #<imm32>",
"pattern" : "00101 Rn#3 imm8#8",
"decoder" : """n = UInt(Rn); imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "CMP (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CMP<c>.W <Rn>, #<imm32>",
"pattern" : "11110 i#1 011011 Rn#4 0 imm3#3 1111 imm8#8",
"decoder" : """n = UInt(Rn); imm32 = ThumbExpandImm(i:imm3:imm8);
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "CMP (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMP<c> <Rn>, #<imm32>",
"pattern" : "cond#4 00110101 Rn#4 0000 imm12#12",
"decoder" : """n = UInt(Rn); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "CMP (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMP<c> <Rn>, <Rm>",
"pattern" : "0100001010 Rm#3 Rn#3",
"decoder" : """n = UInt(Rn); m = UInt(Rm); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "CMP (register)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMP<c> <Rn>, <Rm>",
"pattern" : "01000101 N#1 Rm#4 Rn#3",
"decoder" : """n = UInt(N:Rn); m = UInt(Rm);
(shift_t, shift_n) = (SRType_LSL, 0);
if n < 8 && m < 8 then UNPREDICTABLE;
if n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "CMP (register)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "CMP<c>.W <Rn>, <Rm>{, <shift>}",
"pattern" : "111010111011 Rn#4 0 imm3#3 1111 imm2#2 type#2 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if n == 15 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "CMP (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMP<c> <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 00010101 Rn#4 0000 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "CMP (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CMP<c> <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 00010101 Rn#4 0000 Rs#4 0 type#2 1 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); s = UInt(Rs);
shift_t = DecodeRegShift(type);
if n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "DBG",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "DBG<c> #<option>",
"pattern" : "1111001110101111100000001111 option#4",
"decoder" : """NOP();"""
} , {
"name" : "DBG",
"encoding" : "A1",
"version" : "ARMv7",
"format" : "DBG<c> #<option>",
"pattern" : "cond#4 001100100000111100001111 option#4",
"decoder" : """NOP();"""
} , {
"name" : "DMB",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "DMB<c> <option>",
"pattern" : "1111001110111111100011110101 option#4",
"decoder" : """NOP();"""
} , {
"name" : "DMB",
"encoding" : "A1",
"version" : "ARMv7",
"format" : "DMB <option>",
"pattern" : "1111010101111111111100000101 option#4",
"decoder" : """NOP();"""
} , {
"name" : "DSB",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "DSB<c> <option>",
"pattern" : "1111001110111111100011110100 option#4",
"decoder" : """NOP();"""
} , {
"name" : "DSB",
"encoding" : "A1",
"version" : "ARMv7",
"format" : "DSB <option>",
"pattern" : "1111010101111111111100000100 option#4",
"decoder" : """NOP();"""
} , {
"name" : "EOR (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "EOR{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 00100 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rd == '1111' && S == '1' then SEE TEQ (immediate);
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1');
imm12 = i:imm3:imm8;
imm32 = ThumbExpandImm(imm12);
if d == 13 || (d == 15 && S == '0') || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "EOR (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "EOR{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0010001 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1');
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "EOR (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "EORS <Rdn>, <Rm>:EOR<c> <Rdn>, <Rm>",
"pattern" : "0100000001 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "EOR (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "EOR{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101010100 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE TEQ (register);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d == 13 || (d == 15 && S == '0') || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "EOR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "EOR{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0000001 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "EOR (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "EOR{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0000001 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "ISB",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "ISB<c> <option>",
"pattern" : "1111001110111111100011110110 option#4",
"decoder" : """NOP();"""
} , {
"name" : "ISB",
"encoding" : "A1",
"version" : "ARMv7",
"format" : "ISB <option>",
"pattern" : "1111010101111111111100000110 option#4",
"decoder" : """NOP();"""
} , {
"name" : "IT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "10111111 firstcond#4 mask#4",
"decoder" : """if mask == '0000' then SEE "Related encodings";
if firstcond == '1111' || (firstcond == '1110' && BitCount(mask) != 1) then UNPREDICTABLE;
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "RFE",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "RFEDB<c> <Rn>{!}",
"pattern" : "1110100000 W#1 1 Rn#4 1100000000000000",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then UNPREDICTABLE;
n = UInt(Rn); wback = (W == '1'); increment = FALSE; wordhigher = FALSE; if n == 15 then UNPREDICTABLE;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "RFE",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "RFE{IA}<c> <Rn>{!}",
"pattern" : "1110100110 W#1 1 Rn#4 1100000000000000",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then UNPREDICTABLE;
n = UInt(Rn); wback = (W == '1'); increment = TRUE; wordhigher = FALSE; if n == 15 then UNPREDICTABLE;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "RFE",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "RFE<amode> <Rn>{!}",
"pattern" : "1111100 P#1 U#1 0 W#1 1 Rn#4 0000101000000000",
"decoder" : """n = UInt(Rn); wback = (W == '1'); inc = (U == '1'); wordhigher = (P == U); if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDC, LDC2 (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1110110 P#1 U#1 D#1 W#1 1 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDC, LDC2 (literal);
if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');"""
} , {
"name" : "LDC, LDC2 (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1111110 P#1 U#1 D#1 W#1 1 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDC, LDC2 (literal);
if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then UNDEFINED;
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');"""
} , {
"name" : "LDC, LDC2 (immediate)",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "1111110 P#1 U#1 D#1 W#1 1 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDC, LDC2 (literal);
if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then UNDEFINED;
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');"""
} , {
"name" : "LDC, LDC2 (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 110 P#1 U#1 D#1 W#1 1 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDC, LDC2 (literal);
if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');"""
} , {
"name" : "LDC, LDC2 (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1110110 P#1 U#1 D#1 W#1 11111 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
index = (P == '1'); add = (U == '1'); cp = UInt(coproc); imm32 = ZeroExtend(imm8:'00', 32);
if W == '1' || (P == '0' && CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "LDC, LDC2 (literal)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1111110 P#1 U#1 D#1 W#1 11111 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then UNDEFINED;
index = (P == '1'); add = (U == '1'); cp = UInt(coproc); imm32 = ZeroExtend(imm8:'00', 32);
if W == '1' || (P == '0' && CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "LDC, LDC2 (literal)",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "1111110 P#1 U#1 D#1 W#1 11111 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then UNDEFINED;
index = (P == '1'); add = (U == '1'); cp = UInt(coproc); imm32 = ZeroExtend(imm8:'00', 32);
if W == '1' || (P == '0' && CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "LDC, LDC2 (literal)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 110 P#1 U#1 D#1 W#1 11111 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MRRC, MRRC2;
if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
index = (P == '1'); add = (U == '1'); cp = UInt(coproc); imm32 = ZeroExtend(imm8:'00', 32);
if W == '1' || (P == '0' && CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "LDM/LDMIA/LDMFD (Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "11001 Rn#3 register_list#8",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "ThumbEE instructions";
n = UInt(Rn); registers = '00000000':register_list; wback = (registers<n> == '0');
if BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "LDM/LDMIA/LDMFD (Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDM<c>.W <Rn>{!}, <registers>",
"pattern" : "1110100010 W#1 1 Rn#4 P#1 M#1 0 register_list#13",
"decoder" : """if W == '1' && Rn == '1101' then SEE POP (Thumb);
n = UInt(Rn); registers = P:M:'0':register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 2 || (P == '1' && M == '1') then UNPREDICTABLE;
if registers<15> == '1' && InITBlock() && !LastInITBlock() then UNPREDICTABLE;
if wback && registers<n> == '1' then UNPREDICTABLE;"""
} , {
"name" : "LDM/LDMIA/LDMFD (ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDM<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 100010 W#1 1 Rn#4 register_list#16",
"decoder" : """if W == '1' && Rn == '1101' && BitCount(register_list) > 1 then SEE POP (ARM);
n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;
if wback && registers<n> == '1' && ArchVersion() >= 7 then UNPREDICTABLE;"""
} , {
"name" : "LDMDA/LDMFA",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDMDA<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 100000 W#1 1 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;
if wback && registers<n> == '1' && ArchVersion() >= 7 then UNPREDICTABLE;"""
} , {
"name" : "LDMDB/LDMEA",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDMDB<c> <Rn>{!}, <registers>",
"pattern" : "1110100100 W#1 1 Rn#4 P#1 M#1 0 register_list#13",
"decoder" : """n = UInt(Rn); registers = P:M:'0':register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 2 || (P == '1' && M == '1') then UNPREDICTABLE;
if registers<15> == '1' && InITBlock() && !LastInITBlock() then UNPREDICTABLE;
if wback && registers<n> == '1' then UNPREDICTABLE;"""
} , {
"name" : "LDMDB/LDMEA",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDMDB<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 100100 W#1 1 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;
if wback && registers<n> == '1' && ArchVersion() >= 7 then UNPREDICTABLE;"""
} , {
"name" : "LDMIB/LDMED",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDMIB<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 100110 W#1 1 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;
if wback && registers<n> == '1' && ArchVersion() >= 7 then UNPREDICTABLE;"""
} , {
"name" : "LDR (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDR<c> <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "01101 imm5#5 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm5:'00', 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "LDR (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDR<c> <Rt>, [SP{, #<imm32>}]",
"pattern" : "10011 Rt#3 imm8#8",
"decoder" : """t = UInt(Rt); n = 13; imm32 = ZeroExtend(imm8:'00', 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "LDR (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "LDR<c>.W <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "111110001101 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then SEE LDR (literal);
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t == 15 && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "LDR (immediate, Thumb)",
"encoding" : "T4",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "111110000101 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDR (literal);
if P == '1' && U == '1' && W == '0' then SEE LDRT;
if Rn == '1101' && P == '0' && U == '1' && W == '1' && imm8 == '00000100' then SEE POP;
if P == '0' && W == '0' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn);
imm32 = ZeroExtend(imm8, 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if (wback && n == t) || (t == 15 && InITBlock() && !LastInITBlock()) then UNPREDICTABLE;"""
} , {
"name" : "PLD, PLDW (immediate)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "PLD{W} [<Rn>, #+/-<imm32>]",
"pattern" : "11110101 U#1 R#1 01 Rn#4 1111 imm12#12",
"decoder" : """n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); add = (U == '1'); is_pldw = (R == '0');"""
} , {
"name" : "PLD (literal)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "PLD [pc, #+/-<imm32>]",
"pattern" : "11110101 U#1 10111111111 imm12#12",
"decoder" : """imm32 = ZeroExtend(imm12, 32); add = (U == '1');"""
} , {
"name" : "PLD, PLDW (register)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "PLD{W} [<Rn>, +/-<Rm>{, <shift>}]",
"pattern" : "11110111 U#1 R#1 01 Rn#4 1111 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); add = (U == '1'); is_pldw = (R == '0'); (shift_t, shift_n) = DecodeImmShift(type, imm5);
if m == 15 || (n == 15 && is_pldw) then UNPREDICTABLE;"""
} , {
"name" : "PLI (register)",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "PLI<c> [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "111110010001 Rn#4 1111000000 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE PLI (immediate, literal);
n = UInt(Rn); m = UInt(Rm); add = TRUE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "PLI (register)",
"encoding" : "A1",
"version" : "ARMv7",
"format" : "PLI [<Rn>, +/-<Rm>{, <shift>}]",
"pattern" : "11110110 U#1 101 Rn#4 1111 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); add = (U == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);
if m == 15 then UNPREDICTABLE;"""
} , {
"name" : "PLI (immediate, literal)",
"encoding" : "A1",
"version" : "ARMv7",
"format" : "PLI [<Rn>, #+/-<imm32>]",
"pattern" : "11110100 U#1 101 Rn#4 1111 imm12#12",
"decoder" : """n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); add = (U == '1');"""
} , {
"name" : "LDR (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 010 P#1 U#1 0 W#1 1 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then SEE LDR (literal);
if P == '0' && W == '1' then SEE LDRT;
if Rn == '1101' && P == '0' && U == '1' && W == '0' && imm12 == '000000000100' then SEE POP;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if wback && n == t then UNPREDICTABLE;"""
} , {
"name" : "LDR (literal)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDR<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "01001 Rt#3 imm8#8",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm8:'00', 32); add = TRUE;"""
} , {
"name" : "LDR (literal)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDR<c>.W <Rt>, [pc, #+/-<imm32>]",
"pattern" : "11111000 U#1 1011111 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');
if t == 15 && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "LDR (literal)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDR<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "cond#4 0101 U#1 0011111 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');"""
} , {
"name" : "LDR (register, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDR<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0101100 Rm#3 Rn#3 Rt#3",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "Modified operation in ThumbEE";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "LDR (register, Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDR<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "111110000101 Rn#4 Rt#4 000000 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE LDR (literal);
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if m IN {13,15} then UNPREDICTABLE;
if t == 15 && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "LDR (register, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 011 P#1 U#1 0 W#1 1 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE LDRT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);
if m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDRB (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRB<c> <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "01111 imm5#5 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm5, 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "LDRB (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRB<c>.W <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "111110001001 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE PLD;
if Rn == '1111' then SEE LDRB (literal);
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRB (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "111110000001 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if Rt == '1111' && P == '1' && U == '0' && W == '0' then SEE PLD, PLDW (immediate);
if Rn == '1111' then SEE LDRB (literal);
if P == '1' && U == '1' && W == '0' then SEE LDRBT;
if P == '0' && W == '0' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32);
index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t == 13 || (t == 15 && W == '1') || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRB (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 010 P#1 U#1 1 W#1 1 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then SEE LDRB (literal);
if P == '0' && W == '1' then SEE LDRBT;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if t == 15 || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRB (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRB<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "11111000 U#1 0011111 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE PLD;
t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRB (literal)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRB<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "cond#4 0101 U#1 1011111 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');
if t == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRB (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRB<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0101110 Rm#3 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "LDRB (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRB<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "111110000001 Rn#4 Rt#4 000000 imm2#2 Rm#4",
"decoder" : """if Rt == '1111' then SEE PLD;
if Rn == '1111' then SEE LDRB (literal);
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRB (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 011 P#1 U#1 1 W#1 1 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE LDRBT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);
if t == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDRBT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRBT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110000001 Rn#4 Rt#4 1110 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDRB (literal);
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRBT",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRBT<c> <Rt>, [<Rn>], #+/-<imm32>",
"pattern" : "cond#4 0100 U#1 111 Rn#4 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm12, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "LDRBT",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRBT<c> <Rt>, [<Rn>], +/-<Rm>{, <shift>}",
"pattern" : "cond#4 0110 U#1 111 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE; (shift_t, shift_n) = DecodeImmShift(type, imm5);
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;
if ArchVersion() < 6 && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDRD (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1110100 P#1 U#1 1 W#1 1 Rn#4 Rt#4 Rt2#4 imm8#8",
"decoder" : """if P == '0' && W == '0' then SEE "Related encodings";
if Rn == '1111' then SEE LDRD (literal);
t = UInt(Rt); t2 = UInt(Rt2); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if wback && (n == t || n == t2) then UNPREDICTABLE;
if t IN {13,15} || t2 IN {13,15} || t == t2 then UNPREDICTABLE;"""
} , {
"name" : "LDRD (immediate)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 1 W#1 0 Rn#4 Rt#4 imm4H#4 1101 imm4L#4",
"decoder" : """if Rn == '1111' then SEE LDRD (literal);
if Rt<0> == '1' then UNPREDICTABLE;
t = UInt(Rt); t2 = t+1; n = UInt(Rn); imm32 = ZeroExtend(imm4H:imm4L, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if P == '0' && W == '1' then UNPREDICTABLE;
if wback && (n == t || n == t2) then UNPREDICTABLE;
if t2 == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRD (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRD<c> <Rt>, <Rt2>, [pc, #+/-<imm32>]",
"pattern" : "1110100 P#1 U#1 1 W#1 11111 Rt#4 Rt2#4 imm8#8",
"decoder" : """if P == '0' && W == '0' then SEE "Related encodings";
t = UInt(Rt); t2 = UInt(Rt2);
imm32 = ZeroExtend(imm8:'00', 32); add = (U == '1');
if t IN {13,15} || t2 IN {13,15} || t == t2 then UNPREDICTABLE;
if W == '1' then UNPREDICTABLE;"""
} , {
"name" : "LDRD (literal)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "LDRD<c> <Rt>, <Rt2>, [pc, #+/-<imm32>]",
"pattern" : "cond#4 0001 U#1 1001111 Rt#4 imm4H#4 1101 imm4L#4",
"decoder" : """if Rt<0> == '1' then UNPREDICTABLE;
t = UInt(Rt); t2 = t+1; imm32 = ZeroExtend(imm4H:imm4L, 32); add = (U == '1');
if t2 == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRD (register)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 0 W#1 0 Rn#4 Rt#4 00001101 Rm#4",
"decoder" : """if Rt<0> == '1' then UNPREDICTABLE;
t = UInt(Rt); t2 = t+1; n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if P == '0' && W == '1' then UNPREDICTABLE;
if t2 == 15 || m == 15 || m == t || m == t2 then UNPREDICTABLE;
if wback && (n == 15 || n == t || n == t2) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDREX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDREX<c> <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "111010000101 Rn#4 Rt#4 1111 imm8#8",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32);
if t IN {13,15} || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "LDREX<c> <Rt>, [<Rn>]",
"pattern" : "cond#4 00011001 Rn#4 Rt#4 111110011111",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = Zeros(32);
if t == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREXB",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "LDREXB<c> <Rt>, [<Rn>]",
"pattern" : "111010001101 Rn#4 Rt#4 111101001111",
"decoder" : """t = UInt(Rt); n = UInt(Rn);
if t IN {13,15} || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREXB",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "LDREXB<c> <Rt>, [<Rn>]",
"pattern" : "cond#4 00011101 Rn#4 Rt#4 111110011111",
"decoder" : """t = UInt(Rt); n = UInt(Rn);
if t == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREXD",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "LDREXD<c> <Rt>, <Rt2>, [<Rn>]",
"pattern" : "111010001101 Rn#4 Rt#4 Rt2#4 01111111",
"decoder" : """t = UInt(Rt); t2 = UInt(Rt2); n = UInt(Rn);
if t IN {13,15} || t2 IN {13,15} || t == t2 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREXD",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "LDREXD<c> <Rt>, <Rt2>, [<Rn>]",
"pattern" : "cond#4 00011011 Rn#4 Rt#4 111110011111",
"decoder" : """t = UInt(Rt); t2 = t+1; n = UInt(Rn);
if Rt<0> == '1' || Rt == '1110' || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREXH",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "LDREXH<c> <Rt>, [<Rn>]",
"pattern" : "111010001101 Rn#4 Rt#4 111101011111",
"decoder" : """t = UInt(Rt); n = UInt(Rn);
if t IN {13,15} || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDREXH",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "LDREXH<c> <Rt>, [<Rn>]",
"pattern" : "cond#4 00011111 Rn#4 Rt#4 111110011111",
"decoder" : """t = UInt(Rt); n = UInt(Rn);
if t == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRH (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRH<c> <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "10001 imm5#5 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm5:'0', 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "LDRH (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRH<c>.W <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "111110001011 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE "Related instructions";
if Rn == '1111' then SEE LDRH (literal);
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRH (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "111110000011 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDRH (literal);
if Rt == '1111' && P == '1' && U == '0' && W == '0' then SEE "Related instructions";
if P == '1' && U == '1' && W == '0' then SEE LDRHT;
if P == '0' && W == '0' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32);
index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t ==13 || (t ==15 && W == '1') || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRH (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 1 W#1 1 Rn#4 Rt#4 imm4H#4 1011 imm4L#4",
"decoder" : """if Rn == '1111' then SEE LDRH (literal);
if P == '0' && W == '1' then SEE LDRHT;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm4H:imm4L, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if t == 15 || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRH (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRH<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "11111000 U#1 0111111 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE "Related instructions";
t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRH (literal)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRH<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "cond#4 0001 U#1 1011111 Rt#4 imm4H#4 1011 imm4L#4",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm4H:imm4L, 32); add = (U == '1');
if t == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRH (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRH<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0101101 Rm#3 Rn#3 Rt#3",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "Modified operation in ThumbEE";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = TRUE; add = TRUE; wback = FALSE;
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "LDRH (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRH<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "111110000011 Rn#4 Rt#4 000000 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE LDRH (literal);
if Rt == '1111' then SEE "Related instructions";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE;
wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRH (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 0 W#1 1 Rn#4 Rt#4 00001011 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE LDRHT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = (SRType_LSL, 0);
if t == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDRHT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRHT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110000011 Rn#4 Rt#4 1110 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDRH (literal);
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRHT",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRHT<c> <Rt>, [<Rn>]{, #+/-<imm32>}",
"pattern" : "cond#4 0000 U#1 111 Rn#4 Rt#4 imm4H#4 1011 imm4L#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm4H:imm4L, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "LDRHT",
"encoding" : "A2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRHT<c> <Rt>, [<Rn>], +/-<Rm>",
"pattern" : "cond#4 0000 U#1 011 Rn#4 Rt#4 00001011 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE;
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSB<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110011001 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE PLI;
if Rn == '1111' then SEE LDRSB (literal);
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "111110010001 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if Rt == '1111' && P == '1' && U == '0' && W == '0' then SEE PLI;
if Rn == '1111' then SEE LDRSB (literal);
if P == '1' && U == '1' && W == '0' then SEE LDRSBT;
if P == '0' && W == '0' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32);
index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t == 13 || (t == 15 && W == '1') || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 1 W#1 1 Rn#4 Rt#4 imm4H#4 1101 imm4L#4",
"decoder" : """if Rn == '1111' then SEE LDRSB (literal);
if P == '0' && W == '1' then SEE LDRSBT;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm4H:imm4L, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if t == 15 || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSB<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "11111001 U#1 0011111 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE PLI;
t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (literal)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRSB<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "cond#4 0001 U#1 1011111 Rt#4 imm4H#4 1101 imm4L#4",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm4H:imm4L, 32); add = (U == '1');
if t == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRSB<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0101011 Rm#3 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); add = TRUE; wback = FALSE; index = TRUE;
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "LDRSB (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSB<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "111110010001 Rn#4 Rt#4 000000 imm2#2 Rm#4",
"decoder" : """if Rt == '1111' then SEE PLI;
if Rn == '1111' then SEE LDRSB (literal);
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRSB (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 0 W#1 1 Rn#4 Rt#4 00001101 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE LDRSBT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = (SRType_LSL, 0);
if t == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDRSBT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSBT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110010001 Rn#4 Rt#4 1110 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDRSB (literal);
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRSBT",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSBT<c> <Rt>, [<Rn>]{, #+/-<imm32>}",
"pattern" : "cond#4 0000 U#1 111 Rn#4 Rt#4 imm4H#4 1101 imm4L#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm4H:imm4L, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "LDRSBT",
"encoding" : "A2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSBT<c> <Rt>, [<Rn>], +/-<Rm>",
"pattern" : "cond#4 0000 U#1 011 Rn#4 Rt#4 00001101 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE;
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSH<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110011011 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then SEE LDRSH (literal);
if Rt == '1111' then SEE "Related instructions";
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "111110010011 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDRSH (literal);
if Rt == '1111' && P == '1' && U == '0' && W == '0' then SEE "Related instructions";
if P == '1' && U == '1' && W == '0' then SEE LDRSHT;
if P == '0' && W == '0' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32);
index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t == 13 || (t == 15 && W == '1') || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 1 W#1 1 Rn#4 Rt#4 imm4H#4 1111 imm4L#4",
"decoder" : """if Rn == '1111' then SEE LDRSH (literal);
if P == '0' && W == '1' then SEE LDRSHT;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm4H:imm4L, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if t == 15 || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSH<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "11111001 U#1 0111111 Rt#4 imm12#12",
"decoder" : """if Rt == '1111' then SEE "Related instructions";
t = UInt(Rt); imm32 = ZeroExtend(imm12, 32); add = (U == '1');
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (literal)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRSH<c> <Rt>, [pc, #+/-<imm32>]",
"pattern" : "cond#4 0001 U#1 1011111 Rt#4 imm4H#4 1111 imm4L#4",
"decoder" : """t = UInt(Rt); imm32 = ZeroExtend(imm4H:imm4L, 32); add = (U == '1');
if t == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRSH<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0101111 Rm#3 Rn#3 Rt#3",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "Modified operation in ThumbEE";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = TRUE; add = TRUE; wback = FALSE;
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "LDRSH (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSH<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "111110010011 Rn#4 Rt#4 000000 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE LDRSH (literal);
if Rt == '1111' then SEE "Related instructions";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRSH (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 P#1 U#1 0 W#1 1 Rn#4 Rt#4 00001111 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE LDRSHT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = (SRType_LSL, 0);
if t == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "LDRSHT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSHT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110010011 Rn#4 Rt#4 1110 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDRSH (literal);
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRSHT",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSHT<c> <Rt>, [<Rn>]{, #+/-<imm32>}",
"pattern" : "cond#4 0000 U#1 111 Rn#4 Rt#4 imm4H#4 1111 imm4L#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm4H:imm4L, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "LDRSHT",
"encoding" : "A2",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRSHT<c> <Rt>, [<Rn>], +/-<Rm>",
"pattern" : "cond#4 0000 U#1 011 Rn#4 Rt#4 00001111 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE;
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "LDRT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "LDRT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "111110000101 Rn#4 Rt#4 1110 imm8#8",
"decoder" : """if Rn == '1111' then SEE LDR (literal);
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LDRT",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRT<c> <Rt>, [<Rn>]{, #+/-<imm32>}",
"pattern" : "cond#4 0100 U#1 011 Rn#4 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm12, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "LDRT",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDRT<c> <Rt>, [<Rn>], +/-<Rm>{, <shift>}",
"pattern" : "cond#4 0110 U#1 011 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE; (shift_t, shift_n) = DecodeImmShift(type, imm5);
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;
if ArchVersion() < 6 && m == n then UNPREDICTABLE;"""
} , {
"name" : "LSL (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSLS <Rd>, <Rm>, #<imm32>:LSL<c> <Rd>, <Rm>, #<imm32>",
"pattern" : "00000 imm5#5 Rm#3 Rd#3",
"decoder" : """if imm5 == '00000' then SEE MOV (register, Thumb);
d = UInt(Rd); m = UInt(Rm); setflags = !InITBlock(); (-, shift_n) = DecodeImmShift('00', imm5); imm32 = shift_n;"""
} , {
"name" : "LSL (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LSL{S}<c>.W <Rd>, <Rm>, #<imm32>",
"pattern" : "11101010010 S#1 11110 imm3#3 Rd#4 imm2#2 00 Rm#4",
"decoder" : """if (imm3:imm2) == '00000' then SEE MOV (register, Thumb);
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1'); (-, shift_n) = DecodeImmShift('00', imm3:imm2); imm32 = shift_n;
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LSL (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSL{S}<c> <Rd>, <Rm>, #<imm32>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 imm5#5 000 Rm#4",
"decoder" : """if imm5 == '00000' then SEE MOV (register, ARM);
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(-, shift_n) = DecodeImmShift('00', imm5); imm32 = shift_n;"""
} , {
"name" : "LSL (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSLS <Rdn>, <Rm>:LSL<c> <Rdn>, <Rm>",
"pattern" : "0100000010 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock();"""
} , {
"name" : "LSL (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LSL{S}<c>.W <Rd>, <Rn>, <Rm>",
"pattern" : "11111010000 S#1 Rn#4 1111 Rd#4 0000 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LSL (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSL{S}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 Rm#4 0001 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "LSR (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSRS <Rd>, <Rm>, #<shift_n>:LSR<c> <Rd>, <Rm>, #<shift_n>",
"pattern" : "00001 imm5#5 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = !InITBlock(); (-, shift_n) = DecodeImmShift('01', imm5);"""
} , {
"name" : "LSR (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LSR{S}<c>.W <Rd>, <Rm>, #<shift_n>",
"pattern" : "11101010010 S#1 11110 imm3#3 Rd#4 imm2#2 01 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = (S == '1'); (-, shift_n) = DecodeImmShift('01', imm3:imm2);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LSR (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSR{S}<c> <Rd>, <Rm>, #<shift_n>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 imm5#5 010 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(-, shift_n) = DecodeImmShift('01', imm5);"""
} , {
"name" : "LSR (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSRS <Rdn>, <Rm>:LSR<c> <Rdn>, <Rm>",
"pattern" : "0100000011 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock();"""
} , {
"name" : "LSR (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "LSR{S}<c>.W <Rd>, <Rn>, <Rm>",
"pattern" : "11111010001 S#1 Rn#4 1111 Rd#4 0000 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "LSR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LSR{S}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 Rm#4 0011 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "MCR, MCR2",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MCR<c> <coproc>, #<opc1>, <Rt>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "11101110 opc1#3 0 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); cp = UInt(coproc);
if t == 15 || (t == 13 && (CurrentInstrSet() != InstrSet_ARM)) then UNPREDICTABLE;"""
} , {
"name" : "MCR, MCR2",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "MCR2 <coproc>, #<opc1>, <Rt>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "11111110 opc1#3 0 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); cp = UInt(coproc);
if t == 15 || (t == 13 && (CurrentInstrSet() != InstrSet_ARM)) then UNPREDICTABLE;"""
} , {
"name" : "MCR, MCR2",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MCR<c> <coproc>, #<opc1>, <Rt>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "cond#4 1110 opc1#3 0 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); cp = UInt(coproc);
if t == 15 || (t == 13 && (CurrentInstrSet() != InstrSet_ARM)) then UNPREDICTABLE;"""
} , {
"name" : "MCR, MCR2",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MCR2<c> <coproc>, #<opc1>, <Rt>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "11111110 opc1#3 0 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); cp = UInt(coproc);
if t == 15 || (t == 13 && (CurrentInstrSet() != InstrSet_ARM)) then UNPREDICTABLE;"""
} , {
"name" : "MCRR, MCRR2",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MCRR<c> <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "111011000100 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MCRR, MCRR2",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MCRR2<c> <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "111011000100 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MCRR, MCRR2",
"encoding" : "A2",
"version" : "ARMv6All, ARMv7",
"format" : "MCRR2 <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "111111000100 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MCRR, MCRR2",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "MCRR<c> <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "cond#4 11000100 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MLA",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MLA<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "111110110000 Rn#4 Ra#4 Rd#4 0000 Rm#4",
"decoder" : """if Ra == '1111' then SEE MUL;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); setflags = FALSE;
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "MLA",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MLA{S}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0000001 S#1 Rd#4 Ra#4 Rm#4 1001 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); setflags = (S == '1');
if d == 15 || n == 15 || m == 15 || a == 15 then UNPREDICTABLE;
if ArchVersion() < 6 && d == n then UNPREDICTABLE;"""
} , {
"name" : "MLS",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MLS<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "111110110000 Rn#4 Ra#4 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra);
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MLS",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "MLS<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 00000110 Rd#4 Ra#4 Rm#4 1001 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra);
if d == 15 || n == 15 || m == 15 || a == 15 then UNPREDICTABLE;"""
} , {
"name" : "MOV (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MOVS <Rd>, #<imm32>:MOV<c> <Rd>, #<imm32>",
"pattern" : "00100 Rd#3 imm8#8",
"decoder" : """d = UInt(Rd); setflags = !InITBlock(); imm12 = imm8; imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "MOV (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MOV{S}<c>.W <Rd>, #<imm32>",
"pattern" : "11110 i#1 00010 S#1 11110 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); setflags = (S == '1'); imm12 = i:imm3:imm8; imm32 = ThumbExpandImm(imm12);
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MOV (immediate)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "MOVW<c> <Rd>, #<imm32>",
"pattern" : "11110 i#1 100100 imm4#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); setflags = FALSE; imm32 = ZeroExtend(imm4:i:imm3:imm8, 32);
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MOV (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MOV{S}<c> <Rd>, #<imm32>",
"pattern" : "cond#4 0011101 S#1 0000 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "MOV (immediate)",
"encoding" : "A2",
"version" : "ARMv6T2, ARMv7",
"format" : "MOVW<c> <Rd>, #<imm32>",
"pattern" : "cond#4 00110000 imm4#4 Rd#4 imm12#12",
"decoder" : """d = UInt(Rd); setflags = FALSE; imm32 = ZeroExtend(imm4:imm12, 32);
if d == 15 then UNPREDICTABLE;"""
} , {
"name" : "MOV (register, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MOV<c> <Rd>, <Rm>",
"pattern" : "01000110 D#1 Rm#4 Rd#3",
"decoder" : """d = UInt(D:Rd); m = UInt(Rm); setflags = FALSE;
if d == 15 && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "MOV (register, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MOVS <Rd>, <Rm>",
"pattern" : "0000000000 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = TRUE;
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "MOV (register, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "MOV{S}<c>.W <Rd>, <Rm>",
"pattern" : "11101010010 S#1 11110000 Rd#4 0000 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
if setflags && (d IN {13,15} || m IN {13,15}) then UNPREDICTABLE;
if !setflags && (d == 15 || m == 15 || (d == 13 && m == 13)) then UNPREDICTABLE;"""
} , {
"name" : "MOV (register, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MOV{S}<c> <Rd>, <Rm>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 00000000 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');"""
} , {
"name" : "MOVT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MOVT<c> <Rd>, #<imm32>",
"pattern" : "11110 i#1 101100 imm4#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); imm32 = imm4:i:imm3:imm8;
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MOVT",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "MOVT<c> <Rd>, #<imm32>",
"pattern" : "cond#4 00110100 imm4#4 Rd#4 imm12#12",
"decoder" : """d = UInt(Rd); imm32 = imm4:imm12;
if d == 15 then UNPREDICTABLE;"""
} , {
"name" : "MRC, MRC2",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MRC<c> <coproc>, #<opc1>, <R0_R14_APSR_nzcv>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "11101110 opc1#3 1 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); cp = UInt(coproc);
if t == 13 && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRC, MRC2",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "MRC2 <coproc>, #<opc1>, <R0_R14_APSR_nzcv>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "11111110 opc1#3 1 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); cp = UInt(coproc);
if t == 13 && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRC, MRC2",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MRC<c> <coproc>, #<opc1>, <R0_R14_APSR_nzcv>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "cond#4 1110 opc1#3 1 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); cp = UInt(coproc);
if t == 13 && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRC, MRC2",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MRC2<c> <coproc>, #<opc1>, <R0_R14_APSR_nzcv>, <CRn>, <CRm>{, #<opc2>}",
"pattern" : "11111110 opc1#3 1 CRn#4 Rt#4 coproc#4 opc2#3 1 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); cp = UInt(coproc);
if t == 13 && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRRC, MRRC2",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MRRC<c> <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "111011000101 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 || t == t2 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRRC, MRRC2",
"encoding" : "A2",
"version" : "ARMv6All, ARMv7",
"format" : "MRRC2 <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "111111000101 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 || t == t2 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRRC, MRRC2",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "MRRC<c> <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "cond#4 11000101 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 || t == t2 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRRC, MRRC2",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MRRC2<c> <coproc>, #<opc1>, <Rt>, <Rt2>, <CRm>",
"pattern" : "111111000101 Rt2#4 Rt#4 coproc#4 opc1#4 CRm#4",
"decoder" : """if coproc IN "101x" then UNDEFINED;
t = UInt(Rt); t2 = UInt(Rt2); cp = UInt(coproc);
if t == 15 || t2 == 15 || t == t2 then UNPREDICTABLE;
if (t == 13 || t2 == 13) && (CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "MRS",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MRS<c> <Rd>, <spec_reg>",
"pattern" : "11110011111 R#1 11111000 Rd#4 00000000",
"decoder" : """d = UInt(Rd); read_spsr = (R == '1');
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MRS",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MRS<c> <Rd>, <spec_reg>",
"pattern" : "cond#4 00010 R#1 001111 Rd#4 000000000000",
"decoder" : """d = UInt(Rd); read_spsr = (R == '1');
if d == 15 then UNPREDICTABLE;"""
} , {
"name" : "MSR (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MSR<c> <spec_reg>, #<imm32>",
"pattern" : "cond#4 00110 R#1 10 mask#4 1111 imm12#12",
"decoder" : """if mask == '00' then SEE "Related encodings";
imm32 = ARMExpandImm(imm12); write_nzcvq = (mask<1> == '1'); write_g = (mask<0> == '1');"""
} , {
"name" : "MSR (register)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MSR<c> <spec_reg>, <Rn>",
"pattern" : "11110011100 R#1 Rn#4 1000 mask#4 00000000",
"decoder" : """n = UInt(Rn); write_spsr = (R == '1');
if mask == '0000' then UNPREDICTABLE;
if n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MSR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MSR<c> <spec_reg>, <Rn>",
"pattern" : "cond#4 00010 R#1 10 mask#4 111100000000 Rn#4",
"decoder" : """n = UInt(Rn); write_spsr = (R == '1');
if mask == '0000' then UNPREDICTABLE;
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "MUL",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MULS <Rdm>, <Rn>, <Rdm>:MUL<c> <Rdm>, <Rn>, <Rdm>",
"pattern" : "0100001101 Rn#3 Rdm#3",
"decoder" : """d = UInt(Rdm); n = UInt(Rn); m = UInt(Rdm); setflags = !InITBlock();
if ArchVersion() < 6 && d == n then UNPREDICTABLE;"""
} , {
"name" : "MUL",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MUL<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110110000 Rn#4 1111 Rd#4 0000 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = FALSE;
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MUL",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MUL{S}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0000000 S#1 Rd#4 0000 Rm#4 1001 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if ArchVersion() < 6 && d == n then UNPREDICTABLE;"""
} , {
"name" : "MVN (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "MVN{S}<c> <Rd>, #<imm32>",
"pattern" : "11110 i#1 00011 S#1 11110 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); setflags = (S == '1');
imm12 = i:imm3:imm8;
imm32 = ThumbExpandImm(imm12);
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MVN (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MVN{S}<c> <Rd>, #<imm32>",
"pattern" : "cond#4 0011111 S#1 0000 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); setflags = (S == '1');
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "MVN (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MVNS <Rd>, <Rm>:MVN<c> <Rd>, <Rm>",
"pattern" : "0100001111 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "MVN (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "MVN{S}<c>.W <Rd>, <Rm>{, <shift>}",
"pattern" : "11101010011 S#1 11110 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "MVN (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MVN{S}<c> <Rd>, <Rm>{, <shift>}",
"pattern" : "cond#4 0001111 S#1 0000 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "MVN (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "MVN{S}<c> <Rd>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0001111 S#1 0000 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); s = UInt(Rs);
setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "NOP",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "NOP<c>",
"pattern" : "1011111100000000",
"decoder" : """NOP();"""
} , {
"name" : "NOP",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "NOP<c>.W",
"pattern" : "11110011101011111000000000000000",
"decoder" : """NOP();"""
} , {
"name" : "NOP",
"encoding" : "A1",
"version" : "ARMv6K, ARMv6T2, ARMv7",
"format" : "NOP<c>",
"pattern" : "cond#4 0011001000001111000000000000",
"decoder" : """NOP();"""
} , {
"name" : "ORN (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "ORN{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 00011 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE MVN (immediate);
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm12 = i:imm3:imm8; imm32 = ThumbExpandImm(imm12);
if d IN {13,15} || n == 13 then UNPREDICTABLE;"""
} , {
"name" : "ORN (register)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "ORN{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101010011 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE MVN (register);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ORR (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "ORR{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "11110 i#1 00010 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE MOV (immediate);
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm12 = i:imm3:imm8; imm32 = ThumbExpandImm(imm12);
if d IN {13,15} || n == 13 then UNPREDICTABLE;"""
} , {
"name" : "ORR (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ORR{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0011100 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1');
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "ORR (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ORRS <Rdn>, <Rm>:ORR<c> <Rdn>, <Rm>",
"pattern" : "0100001100 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "ORR (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "ORR{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "11101010010 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE "Related encodings";
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ORR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ORR{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0001100 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "ORR (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ORR{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0001100 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "PKH",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "11101010110 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 tb#1 T#1 Rm#4",
"decoder" : """if S == '1' || T == '1' then UNDEFINED;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); tbform = (tb == '1');
(shift_t, shift_n) = DecodeImmShift(tb:'0', imm3:imm2);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "PKH",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 01101000 Rn#4 Rd#4 imm5#5 tb#1 01 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); tbform = (tb == '1');
(shift_t, shift_n) = DecodeImmShift(tb:'0', imm5);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "PLD, PLDW (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "PLD{W}<c> [<Rn>, #<imm32>]",
"pattern" : "1111100010 W#1 1 Rn#4 1111 imm12#12",
"decoder" : """if Rn == '1111' then SEE PLD (literal);
n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); add = TRUE; is_pldw = (W == '1');"""
} , {
"name" : "PLD, PLDW (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "PLD{W}<c> [<Rn>, #-<imm32>]",
"pattern" : "1111100000 W#1 1 Rn#4 11111100 imm8#8",
"decoder" : """if Rn == '1111' then SEE PLD (literal);
n = UInt(Rn); imm32 = ZeroExtend(imm8, 32); add = FALSE; is_pldw = (W == '1');"""
} , {
"name" : "PLD (literal)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "PLD<c> [pc, #+/-<imm32>]",
"pattern" : "11111000 U#1 00111111111 imm12#12",
"decoder" : """imm32 = ZeroExtend(imm12, 32); add = (U == '1');"""
} , {
"name" : "PLD, PLDW (register)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "PLD{W}<c> [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "1111100000 W#1 1 Rn#4 1111000000 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE PLD (literal);
n = UInt(Rn); m = UInt(Rm); add = TRUE; is_pldw = (W == '1'); (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "PLI (immediate, literal)",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "PLI<c> [<Rn>, #<imm32>]",
"pattern" : "111110011001 Rn#4 1111 imm12#12",
"decoder" : """if Rn == '1111' then SEE encoding T3;
n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); add = TRUE;"""
} , {
"name" : "PLI (immediate, literal)",
"encoding" : "T2",
"version" : "ARMv7",
"format" : "PLI<c> [<Rn>, #-<imm32>]",
"pattern" : "111110010001 Rn#4 11111100 imm8#8",
"decoder" : """if Rn == '1111' then SEE encoding T3;
n = UInt(Rn); imm32 = ZeroExtend(imm8, 32); add = FALSE;"""
} , {
"name" : "PLI (immediate, literal)",
"encoding" : "T3",
"version" : "ARMv7",
"format" : "PLI<c> [pc, #+/-<imm32>]",
"pattern" : "11111001 U#1 00111111111 imm12#12",
"decoder" : """n = 15; imm32 = ZeroExtend(imm12, 32); add = (U == '1');"""
} , {
"name" : "POP (Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "POP<c> <registers>",
"pattern" : "1011110 P#1 register_list#8",
"decoder" : """registers = P:'0000000':register_list; UnalignedAllowed = FALSE;
if BitCount(registers) < 1 then UNPREDICTABLE;
if registers<15> == '1' && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "POP (Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "POP<c>.W <registers>",
"pattern" : "1110100010111101 P#1 M#1 0 register_list#13",
"decoder" : """registers = P:M:'0':register_list; UnalignedAllowed = FALSE;
if BitCount(registers) < 2 || (P == '1' && M == '1') then UNPREDICTABLE;
if registers<15> == '1' && InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "POP (Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "POP<c>.W <registers>",
"pattern" : "1111100001011101 Rt#4 101100000100",
"decoder" : """t = UInt(Rt); registers = Zeros(16); registers = 1 << t; UnalignedAllowed = TRUE;
if t == 13 || (t == 15 && InITBlock() && !LastInITBlock()) then UNPREDICTABLE;"""
} , {
"name" : "POP (ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "POP<c> <registers>",
"pattern" : "cond#4 100010111101 register_list#16",
"decoder" : """if BitCount(register_list) < 2 then SEE LDM/LDMIA/LDMFD (ARM);
registers = register_list; UnalignedAllowed = FALSE;
if registers<13> == '1' && ArchVersion() >= 7 then UNPREDICTABLE;"""
} , {
"name" : "POP (ARM)",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "POP<c> <registers>",
"pattern" : "cond#4 010010011101 Rt#4 000000000100",
"decoder" : """t = UInt(Rt); registers = Zeros(16); registers = 1 << t; UnalignedAllowed = TRUE;
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "PUSH",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "PUSH<c> <registers>",
"pattern" : "1011010 M#1 register_list#8",
"decoder" : """registers = '0':M:'000000':register_list; UnalignedAllowed = FALSE;
if BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "PUSH",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "PUSH<c>.W <registers>",
"pattern" : "11101001001011010 M#1 0 register_list#13",
"decoder" : """registers = '0':M:'0':register_list; UnalignedAllowed = FALSE;
if BitCount(registers) < 2 then UNPREDICTABLE;"""
} , {
"name" : "PUSH",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "PUSH<c>.W <registers>",
"pattern" : "1111100001001101 Rt#4 110100000100",
"decoder" : """t = UInt(Rt); registers = Zeros(16); registers = 1 << t; UnalignedAllowed = TRUE;
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "PUSH",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "PUSH<c> <registers>",
"pattern" : "cond#4 100100101101 register_list#16",
"decoder" : """if BitCount(register_list) < 2 then SEE STMDB (STMFD);
registers = register_list; UnalignedAllowed = FALSE;"""
} , {
"name" : "PUSH",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "PUSH<c> <registers>",
"pattern" : "cond#4 010100101101 Rt#4 000000000100",
"decoder" : """t = UInt(Rt); registers = Zeros(16); registers = 1 << t; UnalignedAllowed = TRUE;
if t == 13 then UNPREDICTABLE;"""
} , {
"name" : "QADD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QADD<c> <Rd>, <Rm>, <Rn>",
"pattern" : "111110101000 Rn#4 1111 Rd#4 1000 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QADD",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "QADD<c> <Rd>, <Rm>, <Rn>",
"pattern" : "cond#4 00010000 Rn#4 Rd#4 00000101 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QADD16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110101001 Rn#4 1111 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QADD16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "QADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 01100010 Rn#4 Rd#4 11110001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QADD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110101000 Rn#4 1111 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QADD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "QADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 01100010 Rn#4 Rd#4 11111001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QASX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110101010 Rn#4 1111 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QASX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "QASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 01100010 Rn#4 Rd#4 11110011 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QDADD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QDADD<c> <Rd>, <Rm>, <Rn>",
"pattern" : "111110101000 Rn#4 1111 Rd#4 1001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QDADD",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "QDADD<c> <Rd>, <Rm>, <Rn>",
"pattern" : "cond#4 00010100 Rn#4 Rd#4 00000101 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QDSUB",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QDSUB<c> <Rd>, <Rm>, <Rn>",
"pattern" : "111110101000 Rn#4 1111 Rd#4 1011 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QDSUB",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "QDSUB<c> <Rd>, <Rm>, <Rn>",
"pattern" : "cond#4 00010110 Rn#4 Rd#4 00000101 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QSAX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110101110 Rn#4 1111 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QSAX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "QSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 01100010 Rn#4 Rd#4 11110101 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QSUB",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QSUB<c> <Rd>, <Rm>, <Rn>",
"pattern" : "111110101000 Rn#4 1111 Rd#4 1010 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QSUB",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "QSUB<c> <Rd>, <Rm>, <Rn>",
"pattern" : "cond#4 00010010 Rn#4 Rd#4 00000101 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QSUB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110101101 Rn#4 1111 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QSUB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "QSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 01100010 Rn#4 Rd#4 11110111 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "QSUB8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "QSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "111110101100 Rn#4 1111 Rd#4 0001 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "QSUB8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "QSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 01100010 Rn#4 Rd#4 11111111 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "RBIT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "RBIT<c> <Rd>, <Rm>",
"pattern" : "111110101001 Rm_#4 1111 Rd#4 1010 Rm#4",
"decoder" : """if !Consistent(Rm) then UNPREDICTABLE;
d = UInt(Rd); m = UInt(Rm);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "RBIT",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "RBIT<c> <Rd>, <Rm>",
"pattern" : "cond#4 011011111111 Rd#4 11110011 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm);
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "REV",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "REV<c> <Rd>, <Rm>",
"pattern" : "1011101000 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm);"""
} , {
"name" : "REV",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "REV<c>.W <Rd>, <Rm>",
"pattern" : "111110101001 Rm_#4 1111 Rd#4 1000 Rm#4",
"decoder" : """if !Consistent(Rm) then UNPREDICTABLE;
d = UInt(Rd); m = UInt(Rm);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "REV",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "REV<c> <Rd>, <Rm>",
"pattern" : "cond#4 011010111111 Rd#4 11110011 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm);
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "REV16",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "REV16<c> <Rd>, <Rm>",
"pattern" : "1011101001 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm);"""
} , {
"name" : "REV16",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "REV16<c>.W <Rd>, <Rm>",
"pattern" : "111110101001 Rm_#4 1111 Rd#4 1001 Rm#4",
"decoder" : """if !Consistent(Rm) then UNPREDICTABLE;
d = UInt(Rd); m = UInt(Rm);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "REV16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "REV16<c> <Rd>, <Rm>",
"pattern" : "cond#4 011010111111 Rd#4 11111011 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm);
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "REVSH",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "REVSH<c> <Rd>, <Rm>",
"pattern" : "1011101011 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm);"""
} , {
"name" : "REVSH",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "REVSH<c>.W <Rd>, <Rm>",
"pattern" : "111110101001 Rm_#4 1111 Rd#4 1011 Rm#4",
"decoder" : """if !Consistent(Rm) then UNPREDICTABLE;
d = UInt(Rd); m = UInt(Rm);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "REVSH",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "REVSH<c> <Rd>, <Rm>",
"pattern" : "cond#4 011011111111 Rd#4 11111011 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm);
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "ROR (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "ROR{S}<c> <Rd>, <Rm>, #<shift_n>",
"pattern" : "11101010010 S#1 11110 imm3#3 Rd#4 imm2#2 11 Rm#4",
"decoder" : """if (imm3:imm2) == '00000' then SEE RRX;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1'); (-, shift_n) = DecodeImmShift('11', imm3:imm2);
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ROR (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ROR{S}<c> <Rd>, <Rm>, #<shift_n>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 imm5#5 110 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
if imm5 == '00000' then SEE RRX;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(-, shift_n) = DecodeImmShift('11', imm5);"""
} , {
"name" : "ROR (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RORS <Rdn>, <Rm>:ROR<c> <Rdn>, <Rm>",
"pattern" : "0100000111 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock();"""
} , {
"name" : "ROR (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "ROR{S}<c>.W <Rd>, <Rn>, <Rm>",
"pattern" : "11111010011 S#1 Rn#4 1111 Rd#4 0000 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "ROR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "ROR{S}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 Rm#4 0111 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "RRX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "RRX{S}<c> <Rd>, <Rm>",
"pattern" : "11101010010 S#1 11110000 Rd#4 0011 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "RRX",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RRX{S}<c> <Rd>, <Rm>",
"pattern" : "cond#4 0001101 S#1 0000 Rd#4 00000110 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');"""
} , {
"name" : "RSB (immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSB{S} <Rd>, <Rn>, #<imm32>",
"pattern" : "0 1 0 0 0 0 1 0 0 1 Rn#3 Rd#3",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = !InITBlock(); imm32 = Zeros(32);"""
} , {
"name" : "RSB (immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "RSB{S}<c>.W <Rd>, <Rn>, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 0 1 1 1 0 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "RSB (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSB{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0 0 1 0 0 1 1 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "RSB (register)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "RSB{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "1 1 1 0 1 0 1 1 1 1 0 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "RSB (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSB{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 0 0 1 1 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "RSB (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSB{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0 0 0 0 0 1 1 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "RSC (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0 0 1 0 1 1 1 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "RSC (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSC{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 0 1 1 1 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "RSC (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "RSC{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0 0 0 0 1 1 1 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "SADD16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 1 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SADD16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 0 1 Rn#4 Rd#4 1 1 1 1 0 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SADD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 0 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SADD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 0 1 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SASX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 1 0 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SASX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 0 1 Rn#4 Rd#4 1 1 1 1 0 0 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SBC (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SBC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 0 1 0 1 1 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SBC (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SBC{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0 0 1 0 1 1 0 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "SBC (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SBCS <Rdn>, <Rm>:SBC<c> <Rdn>, <Rm>",
"pattern" : "0 1 0 0 0 0 0 1 1 0 Rm#3 Rdn#3",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "SBC (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SBC{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "1 1 1 0 1 0 1 1 0 1 1 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SBC (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SBC{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 0 1 1 0 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "SBC (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SBC{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0 0 0 0 1 1 0 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "SBFX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SBFX<c> <Rd>, <Rn>, #<lsb>, #<widthminus1>",
"pattern" : "1 1 1 1 0 0 1 1 0 1 0 0 Rn#4 0 imm3#3 Rd#4 imm2#2 0 widthm1#5",
"decoder" : """d = UInt(Rd); n = UInt(Rn);
lsbit = UInt(imm3:imm2); widthminus1 = UInt(widthm1);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SBFX",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "SBFX<c> <Rd>, <Rn>, #<lsb>, #<widthminus1>",
"pattern" : "cond#4 0 1 1 1 1 0 1 widthm1#5 Rd#4 lsb#5 1 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn);
lsbit = UInt(lsb); widthminus1 = UInt(widthm1);
if d == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "SDIV",
"encoding" : "T1",
"version" : "ARMv7R, ARMv7VE",
"format" : "SDIV<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 0 0 1 Rn#4 1 1 1 1 Rd#4 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SDIV",
"encoding" : "A1",
"version" : "ARMv7VE",
"format" : "SDIV<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 0 0 1 Rd#4 1 1 1 1 Rm#4 0 0 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SEL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SEL<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 1 0 Rn#4 1 1 1 1 Rd#4 1 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SEL",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SEL<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 1 0 0 0 Rn#4 Rd#4 1 1 1 1 1 0 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SETEND",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "SETEND <endian_specifier>",
"pattern" : "1 0 1 1 0 1 1 0 0 1 0 1 E#1 0 0 0",
"decoder" : """set_bigend = (E == '1');
if InITBlock() then UNPREDICTABLE;"""
} , {
"name" : "SETEND",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SETEND <endian_specifier>",
"pattern" : "1 1 1 1 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 E#1 0 0 0 0 0 0 0 0 0",
"decoder" : """set_bigend = (E == '1');"""
} , {
"name" : "SEV",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "SEV<c>",
"pattern" : "1 0 1 1 1 1 1 1 0 1 0 0 0 0 0 0",
"decoder" : """NOP();"""
} , {
"name" : "SEV",
"encoding" : "T2",
"version" : "ARMv7",
"format" : "SEV<c>.W",
"pattern" : "1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0",
"decoder" : """NOP();"""
} , {
"name" : "SEV",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "SEV<c>",
"pattern" : "cond#4 0 0 1 1 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 1 0 0",
"decoder" : """NOP();"""
} , {
"name" : "SHADD16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SHADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 1 Rn#4 1 1 1 1 Rd#4 0 0 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SHADD16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SHADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 1 1 Rn#4 Rd#4 1 1 1 1 0 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SHADD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SHADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 0 Rn#4 1 1 1 1 Rd#4 0 0 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SHADD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SHADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 1 1 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SHASX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SHASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 1 0 Rn#4 1 1 1 1 Rd#4 0 0 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SHASX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SHASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 1 1 Rn#4 Rd#4 1 1 1 1 0 0 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SHSAX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SHSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 1 0 Rn#4 1 1 1 1 Rd#4 0 0 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SHSAX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SHSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 1 1 Rn#4 Rd#4 1 1 1 1 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SHSUB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SHSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 1 Rn#4 1 1 1 1 Rd#4 0 0 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SHSUB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SHSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 1 1 Rn#4 Rd#4 1 1 1 1 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SHSUB8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SHSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 0 Rn#4 1 1 1 1 Rd#4 0 0 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SHSUB8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SHSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 1 1 Rn#4 Rd#4 1 1 1 1 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMLABB, SMLABT, SMLATB, SMLATT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLA<x><y><c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 0 0 1 Rn#4 Ra#4 Rd#4 0 0 N#1 M#1 Rm#4",
"decoder" : """if Ra == '1111' then SEE SMULBB, SMULBT, SMULTB, SMULTT;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra);
n_high = (N == '1'); m_high = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "SMLABB, SMLABT, SMLATB, SMLATT",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "SMLA<x><y><c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 0 0 1 0 0 0 0 Rd#4 Ra#4 Rm#4 1 M#1 N#1 0 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); n_high = (N == '1'); m_high = (M == '1');
if d == 15 || n == 15 || m == 15 || a == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMLAD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLAD{X}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 0 1 0 Rn#4 Ra#4 Rd#4 0 0 0 M#1 Rm#4",
"decoder" : """if Ra == '1111' then SEE SMUAD;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra);
m_swap = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "SMLAD",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMLAD{X}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 1 1 1 0 0 0 0 Rd#4 Ra#4 Rm#4 0 0 M#1 1 Rn#4",
"decoder" : """if Ra == '1111' then SEE SMUAD;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); m_swap = (M == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMLAL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLAL<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 1 0 0 Rn#4 RdLo#4 RdHi#4 0 0 0 0 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = FALSE;
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMLAL",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SMLAL{S}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 0 1 1 1 S#1 RdHi#4 RdLo#4 Rm#4 1 0 0 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;
if ArchVersion() < 6 && (dHi == n || dLo == n) then UNPREDICTABLE;"""
} , {
"name" : "SMLALBB, SMLALBT, SMLALTB, SMLALTT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLAL<x><y><c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 1 0 0 Rn#4 RdLo#4 RdHi#4 1 0 N#1 M#1 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm);
n_high = (N == '1'); m_high = (M == '1');
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMLALBB, SMLALBT, SMLALTB, SMLALTT",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "SMLAL<x><y><c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 1 0 1 0 0 RdHi#4 RdLo#4 Rm#4 1 M#1 N#1 0 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); n_high = (N == '1'); m_high = (M == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMLALD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLALD{X}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 1 0 0 Rn#4 RdLo#4 RdHi#4 1 1 0 M#1 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMLALD",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMLALD{X}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 1 0 0 RdHi#4 RdLo#4 Rm#4 0 0 M#1 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMLAWB, SMLAWT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLAW<y><c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 0 1 1 Rn#4 Ra#4 Rd#4 0 0 0 M#1 Rm#4",
"decoder" : """if Ra == '1111' then SEE SMULWB, SMULWT;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); m_high = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "SMLAWB, SMLAWT",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "SMLAW<y><c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 0 0 1 0 0 1 0 Rd#4 Ra#4 Rm#4 1 M#1 0 0 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); m_high = (M == '1');
if d == 15 || n == 15 || m == 15 || a == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMLSD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLSD{X}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 0 0 Rn#4 Ra#4 Rd#4 0 0 0 M#1 Rm#4",
"decoder" : """if Ra == '1111' then SEE SMUSD;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); m_swap = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "SMLSD",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMLSD{X}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 1 1 1 0 0 0 0 Rd#4 Ra#4 Rm#4 0 1 M#1 1 Rn#4",
"decoder" : """if Ra == '1111' then SEE SMUSD;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); m_swap = (M == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMLSLD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMLSLD{X}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 1 0 1 Rn#4 RdLo#4 RdHi#4 1 1 0 M#1 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMLSLD",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMLSLD{X}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 1 0 0 RdHi#4 RdLo#4 Rm#4 0 1 M#1 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMMLA",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMMLA{R}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 0 1 Rn#4 Ra#4 Rd#4 0 0 0 R#1 Rm#4",
"decoder" : """if Ra == '1111' then SEE SMMUL;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); round = (R == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "SMMLA",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMMLA{R}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 1 1 1 0 1 0 1 Rd#4 Ra#4 Rm#4 0 0 R#1 1 Rn#4",
"decoder" : """if Ra == '1111' then SEE SMMUL;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); round = (R == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMMLS",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMMLS{R}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 1 0 Rn#4 Ra#4 Rd#4 0 0 0 R#1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); round = (R == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SMMLS",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMMLS{R}<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 1 1 1 0 1 0 1 Rd#4 Ra#4 Rm#4 1 1 R#1 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra); round = (R == '1');
if d == 15 || n == 15 || m == 15 || a == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMMUL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMMUL{R}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 0 1 Rn#4 1 1 1 1 Rd#4 0 0 0 R#1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); round = (R == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SMMUL",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMMUL{R}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 1 0 1 Rd#4 1 1 1 1 Rm#4 0 0 R#1 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); round = (R == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMUAD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMUAD{X}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 0 0 1 0 Rn#4 1 1 1 1 Rd#4 0 0 0 M#1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SMUAD",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMUAD{X}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 0 0 0 Rd#4 1 1 1 1 Rm#4 0 0 M#1 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMULBB, SMULBT, SMULTB, SMULTT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMUL<x><y><c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 0 0 0 1 Rn#4 1 1 1 1 Rd#4 0 0 N#1 M#1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
n_high = (N == '1'); m_high = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SMULBB, SMULBT, SMULTB, SMULTT",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "SMUL<x><y><c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 1 0 1 1 0 Rd#4 0 0 0 0 Rm#4 1 M#1 N#1 0 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
n_high = (N == '1'); m_high = (M == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMULL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMULL<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 0 0 0 Rn#4 RdLo#4 RdHi#4 0 0 0 0 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = FALSE;
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "SMULL",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SMULL{S}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 0 1 1 0 S#1 RdHi#4 RdLo#4 Rm#4 1 0 0 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;
if ArchVersion() < 6 && (dHi == n || dLo == n) then UNPREDICTABLE;"""
} , {
"name" : "SMULWB, SMULWT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMULW<y><c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 0 0 1 1 Rn#4 1 1 1 1 Rd#4 0 0 0 M#1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); m_high = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SMULWB, SMULWT",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "SMULW<y><c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 1 0 0 1 0 Rd#4 0 0 0 0 Rm#4 1 M#1 1 0 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); m_high = (M == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SMUSD",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SMUSD{X}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 0 0 Rn#4 1 1 1 1 Rd#4 0 0 0 M#1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SMUSD",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SMUSD{X}<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 0 0 0 Rd#4 1 1 1 1 Rm#4 0 1 M#1 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); m_swap = (M == '1');
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SSAT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SSAT<c> <Rd>, #<saturate_to>, <Rn>{, <shift>}",
"pattern" : "1 1 1 1 0 0 1 1 0 0 sh#1 0 Rn#4 0 imm3#3 Rd#4 imm2#2 0 sat_imm#5",
"decoder" : """if sh == '1' && (imm3:imm2) == '00000' then SEE SSAT16;
d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm)+1; (shift_t, shift_n) = DecodeImmShift(sh:'0', imm3:imm2);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SSAT",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SSAT<c> <Rd>, #<saturate_to>, <Rn>{, <shift>}",
"pattern" : "cond#4 0 1 1 0 1 0 1 sat_imm#5 Rd#4 imm5#5 sh#1 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm)+1; (shift_t, shift_n) = DecodeImmShift(sh:'0', imm5);
if d == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "SSAT16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SSAT16<c> <Rd>, #<saturate_to>, <Rn>",
"pattern" : "1 1 1 1 0 0 1 1 0 0 1 0 Rn#4 0 0 0 0 Rd#4 0 0 0 0 sat_imm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm)+1;
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SSAT16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SSAT16<c> <Rd>, #<saturate_to>, <Rn>",
"pattern" : "cond#4 0 1 1 0 1 0 1 0 sat_imm#4 Rd#4 1 1 1 1 0 0 1 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm)+1;
if d == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "SSAX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 1 0 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SSAX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 0 1 Rn#4 Rd#4 1 1 1 1 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SSUB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 1 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SSUB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 0 1 Rn#4 Rd#4 1 1 1 1 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SSUB8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 0 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SSUB8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 0 0 1 Rn#4 Rd#4 1 1 1 1 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "STC, STC2",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MCRR, MCRR2;
if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "STC, STC2",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MCRR, MCRR2;
if coproc IN "101x" then UNDEFINED;
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "STC, STC2",
"encoding" : "A2",
"version" : "ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MCRR, MCRR2;
if coproc IN "101x" then UNDEFINED;
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "STC, STC2",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 CRd#4 coproc#4 imm8#8",
"decoder" : """if P == '0' && U == '0' && D == '0' && W == '0' then UNDEFINED;
if P == '0' && U == '0' && D == '1' && W == '0' then SEE MCRR, MCRR2;
if coproc IN "101x" then SEE "AdvancedSIMD and Floating-point";
n = UInt(Rn); cp = UInt(coproc);
imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "STM (STMIA, STMEA)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STM<c> <Rn>!, <registers>",
"pattern" : "1 1 0 0 0 Rn#3 register_list#8",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "ThumbEE instructions";
n = UInt(Rn); registers = '00000000':register_list; wback = TRUE;
if BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "STM (STMIA, STMEA)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "STM<c>.W <Rn>{!}, <registers>",
"pattern" : "1 1 1 0 1 0 0 0 1 0 W#1 0 Rn#4 0 M#1 0 register_list#13",
"decoder" : """n = UInt(Rn); registers = '0':M:'0':register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 2 then UNPREDICTABLE;
if wback && registers<n> == '1' then UNPREDICTABLE;"""
} , {
"name" : "STM (STMIA, STMEA)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STM<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 1 0 0 0 1 0 W#1 0 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "STMDA (STMED)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STMDA<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 1 0 0 0 0 0 W#1 0 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "STMDB (STMFD)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "STMDB<c> <Rn>{!}, <registers>",
"pattern" : "1 1 1 0 1 0 0 1 0 0 W#1 0 Rn#4 0 M#1 0 register_list#13",
"decoder" : """if W == '1' && Rn == '1101' then SEE PUSH;
n = UInt(Rn); registers = '0':M:'0':register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 2 then UNPREDICTABLE;
if wback && registers<n> == '1' then UNPREDICTABLE;"""
} , {
"name" : "STMDB (STMFD)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STMDB<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 1 0 0 1 0 0 W#1 0 Rn#4 register_list#16",
"decoder" : """if W == '1' && Rn == '1101' && BitCount(register_list) >= 2 then SEE PUSH;
n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "STMIB (STMFA)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STMIB<c> <Rn>{!}, <registers>",
"pattern" : "cond#4 1 0 0 1 1 0 W#1 0 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; wback = (W == '1');
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "STR (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STR<c> <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "0 1 1 0 0 imm5#5 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm5:'00', 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "STR (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STR<c> <Rt>, [SP, #<imm32>]",
"pattern" : "1 0 0 1 0 Rt#3 imm8#8",
"decoder" : """t = UInt(Rt); n = 13; imm32 = ZeroExtend(imm8:'00', 32);
index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "STR (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "STR<c>.W <Rt>, [<Rn>, #<imm32>]",
"pattern" : "1 1 1 1 1 0 0 0 1 1 0 0 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t == 15 then UNPREDICTABLE;"""
} , {
"name" : "STR (immediate, Thumb)",
"encoding" : "T4",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 0 0 1 0 0 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if P == '1' && U == '1' && W == '0' then SEE STRT;
if Rn == '1101' && P == '1' && U == '0' && W == '1' && imm8 == '00000100' then SEE PUSH;
if Rn == '1111' || (P == '0' && W == '0') then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32);
index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t == 15 || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "STR (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 1 0 P#1 U#1 0 W#1 0 Rn#4 Rt#4 imm12#12",
"decoder" : """if P == '0' && W == '1' then SEE STRT;
if Rn == '1101' && P == '1' && U == '0' && W == '1' && imm12 == '000000000100' then SEE PUSH;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if wback && (n == 15 || n == t) then UNPREDICTABLE;"""
} , {
"name" : "STR (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STR<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0 1 0 1 0 0 0 Rm#3 Rn#3 Rt#3",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "Modified operation in ThumbEE";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = TRUE; add = TRUE; wback = FALSE;
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "STR (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "STR<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "1 1 1 1 1 0 0 0 0 1 0 0 Rn#4 Rt#4 0 0 0 0 0 0 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t == 15 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STR (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 1 1 P#1 U#1 0 W#1 0 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE STRT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);
if m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "STRB (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRB<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "0 1 1 1 0 imm5#5 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm5, 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "STRB (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "STRB<c>.W <Rt>, [<Rn>, #<imm32>]",
"pattern" : "1 1 1 1 1 0 0 0 1 0 0 0 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRB (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 0 0 0 0 0 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if P == '1' && U == '1' && W == '0' then SEE STRBT;
if Rn == '1111' || (P == '0' && W == '0') then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t IN {13,15} || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "STRB (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 1 0 P#1 U#1 1 W#1 0 Rn#4 Rt#4 imm12#12",
"decoder" : """if P == '0' && W == '1' then SEE STRBT;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if t == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;"""
} , {
"name" : "STRB (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRB<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0 1 0 1 0 1 0 Rm#3 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "STRB (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "STRB<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "1 1 1 1 1 0 0 0 0 0 0 0 Rn#4 Rt#4 0 0 0 0 0 0 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRB (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 1 1 P#1 U#1 1 W#1 0 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE STRBT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);
if t == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "STRBT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "STRBT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "1 1 1 1 1 0 0 0 0 0 0 0 Rn#4 Rt#4 1 1 1 0 imm8#8",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRBT",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRBT<c> <Rt>, [<Rn>], #+/-<imm32>",
"pattern" : "cond#4 0 1 0 0 U#1 1 1 0 Rn#4 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm12, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "STRBT",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRBT<c> <Rt>, [<Rn>], +/-<Rm>{, <shift>}",
"pattern" : "cond#4 0 1 1 0 U#1 1 1 0 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE; (shift_t, shift_n) = DecodeImmShift(type, imm5);
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;
if ArchVersion() < 6 && m == n then UNPREDICTABLE;"""
} , {
"name" : "STRD (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 0 0 P#1 U#1 1 W#1 0 Rn#4 Rt#4 Rt2#4 imm8#8",
"decoder" : """if P == '0' && W == '0' then SEE "Related encodings";
t = UInt(Rt); t2 = UInt(Rt2); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if wback && (n == t || n == t2) then UNPREDICTABLE;
if n == 15 || t IN {13,15} || t2 IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRD (immediate)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 0 0 P#1 U#1 1 W#1 0 Rn#4 Rt#4 imm4H#4 1 1 1 1 imm4L#4",
"decoder" : """if Rt<0> == '1' then UNPREDICTABLE;
t = UInt(Rt); t2 = t+1; n = UInt(Rn); imm32 = ZeroExtend(imm4H:imm4L, 32); index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if P == '0' && W == '1' then UNPREDICTABLE;
if wback && (n == 15 || n == t || n == t2) then UNPREDICTABLE;
if t2 == 15 then UNPREDICTABLE;"""
} , {
"name" : "STRD (register)",
"encoding" : "A1",
"version" : "ARMv5TEAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 0 0 P#1 U#1 0 W#1 0 Rn#4 Rt#4 0 0 0 0 1 1 1 1 Rm#4",
"decoder" : """if Rt<0> == '1' then UNPREDICTABLE;
t = UInt(Rt); t2 = t+1; n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if P == '0' && W == '1' then UNPREDICTABLE;
if t2 == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t || n == t2) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "STREX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "STREX<c> <Rd>, <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "1 1 1 0 1 0 0 0 0 1 0 0 Rn#4 Rt#4 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32);
if d IN {13,15} || t IN {13,15} || n == 15 then UNPREDICTABLE;
if d == n || d == t then UNPREDICTABLE;"""
} , {
"name" : "STREX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "STREX<c> <Rd>, <Rt>, [<Rn>]",
"pattern" : "cond#4 0 0 0 1 1 0 0 0 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rt#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); n = UInt(Rn); imm32 = Zeros(32);
if d == 15 || t == 15 || n == 15 then UNPREDICTABLE;
if d == n || d == t then UNPREDICTABLE;"""
} , {
"name" : "STREXB",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "STREXB<c> <Rd>, <Rt>, [<Rn>]",
"pattern" : "1 1 1 0 1 0 0 0 1 1 0 0 Rn#4 Rt#4 1 1 1 1 0 1 0 0 Rd#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); n = UInt(Rn);
if d IN {13,15} || t IN {13,15} || n == 15 then UNPREDICTABLE;
if d == n || d == t then UNPREDICTABLE;"""
} , {
"name" : "STREXB",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "STREXB<c> <Rd>, <Rt>, [<Rn>]",
"pattern" : "cond#4 0 0 0 1 1 1 0 0 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rt#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); n = UInt(Rn);
if d == 15 || t == 15 || n == 15 then UNPREDICTABLE;
if d == n || d == t then UNPREDICTABLE;"""
} , {
"name" : "STREXD",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "STREXD<c> <Rd>, <Rt>, <Rt2>, [<Rn>]",
"pattern" : "1 1 1 0 1 0 0 0 1 1 0 0 Rn#4 Rt#4 Rt2#4 0 1 1 1 Rd#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); t2 = UInt(Rt2); n = UInt(Rn);
if d IN {13,15} || t IN {13,15} || t2 IN {13,15} || n == 15 then UNPREDICTABLE;
if d == n || d == t || d == t2 then UNPREDICTABLE;"""
} , {
"name" : "STREXD",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "STREXD<c> <Rd>, <Rt>, <Rt2>, [<Rn>]",
"pattern" : "cond#4 0 0 0 1 1 0 1 0 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rt#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); t2 = t+1; n = UInt(Rn);
if d == 15 || Rt<0> == '1' || Rt == '1110' || n == 15 then UNPREDICTABLE;
if d == n || d == t || d == t2 then UNPREDICTABLE;"""
} , {
"name" : "STREXH",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "STREXH<c> <Rd>, <Rt>, [<Rn>]",
"pattern" : "1 1 1 0 1 0 0 0 1 1 0 0 Rn#4 Rt#4 1 1 1 1 0 1 0 1 Rd#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); n = UInt(Rn);
if d IN {13,15} || t IN {13,15} || n == 15 then UNPREDICTABLE;
if d == n || d == t then UNPREDICTABLE;"""
} , {
"name" : "STREXH",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "STREXH<c> <Rd>, <Rt>, [<Rn>]",
"pattern" : "cond#4 0 0 0 1 1 1 1 0 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rt#4",
"decoder" : """d = UInt(Rd); t = UInt(Rt); n = UInt(Rn);
if d == 15 || t == 15 || n == 15 then UNPREDICTABLE;
if d == n || d == t then UNPREDICTABLE;"""
} , {
"name" : "STRH (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRH<c> <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "1 0 0 0 0 imm5#5 Rn#3 Rt#3",
"decoder" : """t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm5:'0', 32); index = TRUE; add = TRUE; wback = FALSE;"""
} , {
"name" : "STRH (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "STRH<c>.W <Rt>, [<Rn>{, #<imm32>}]",
"pattern" : "1 1 1 1 1 0 0 0 1 0 1 0 Rn#4 Rt#4 imm12#12",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm12, 32); index = TRUE; add = TRUE; wback = FALSE;
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRH (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 0 0 0 1 0 Rn#4 Rt#4 1 P#1 U#1 W#1 imm8#8",
"decoder" : """if P == '1' && U == '1' && W == '0' then SEE STRHT;
if Rn == '1111' || (P == '0' && W == '0') then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm8, 32); index = (P == '1'); add = (U == '1'); wback = (W == '1');
if t IN {13,15} || (wback && n == t) then UNPREDICTABLE;"""
} , {
"name" : "STRH (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 0 0 P#1 U#1 1 W#1 0 Rn#4 Rt#4 imm4H#4 1 0 1 1 imm4L#4",
"decoder" : """if P == '0' && W == '1' then SEE STRHT;
t = UInt(Rt); n = UInt(Rn); imm32 = ZeroExtend(imm4H:imm4L, 32);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1');
if t == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;"""
} , {
"name" : "STRH (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRH<c> <Rt>, [<Rn>, <Rm>]",
"pattern" : "0 1 0 1 0 0 1 Rm#3 Rn#3 Rt#3",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then SEE "Modified operation in ThumbEE";
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = TRUE; add = TRUE; wback = FALSE;
(shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "STRH (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "STRH<c>.W <Rt>, [<Rn>, <Rm>{, LSL #<shift_n>}]",
"pattern" : "1 1 1 1 1 0 0 0 0 0 1 0 Rn#4 Rt#4 0 0 0 0 0 0 imm2#2 Rm#4",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = TRUE; add = TRUE; wback = FALSE; (shift_t, shift_n) = (SRType_LSL, UInt(imm2));
if t IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRH (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 0 0 0 P#1 U#1 0 W#1 0 Rn#4 Rt#4 0 0 0 0 1 0 1 1 Rm#4",
"decoder" : """if P == '0' && W == '1' then SEE STRHT;
t = UInt(Rt); n = UInt(Rn); m = UInt(Rm);
index = (P == '1'); add = (U == '1'); wback = (P == '0') || (W == '1'); (shift_t, shift_n) = (SRType_LSL, 0);
if t == 15 || m == 15 then UNPREDICTABLE;
if wback && (n == 15 || n == t) then UNPREDICTABLE;
if ArchVersion() < 6 && wback && m == n then UNPREDICTABLE;"""
} , {
"name" : "STRHT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "STRHT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "1 1 1 1 1 0 0 0 0 0 1 0 Rn#4 Rt#4 1 1 1 0 imm8#8",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRHT",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "STRHT<c> <Rt>, [<Rn>]{, #+/-<imm32>}",
"pattern" : "cond#4 0 0 0 0 U#1 1 1 0 Rn#4 Rt#4 imm4H#4 1 0 1 1 imm4L#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm4H:imm4L, 32);
if t == 15 || n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "STRHT",
"encoding" : "A2",
"version" : "ARMv6T2, ARMv7",
"format" : "STRHT<c> <Rt>, [<Rn>], +/-<Rm>",
"pattern" : "cond#4 0 0 0 0 U#1 0 1 0 Rn#4 Rt#4 0 0 0 0 1 0 1 1 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE;
if t == 15 || n == 15 || n == t || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "STRT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "STRT<c> <Rt>, [<Rn>, #<imm32>]",
"pattern" : "1 1 1 1 1 0 0 0 0 1 0 0 Rn#4 Rt#4 1 1 1 0 imm8#8",
"decoder" : """if Rn == '1111' then UNDEFINED;
t = UInt(Rt); n = UInt(Rn); postindex = FALSE; add = TRUE; register_form = FALSE; imm32 = ZeroExtend(imm8, 32);
if t IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "STRT",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRT<c> <Rt>, [<Rn>]{, #+/-<imm32>}",
"pattern" : "cond#4 0 1 0 0 U#1 0 1 0 Rn#4 Rt#4 imm12#12",
"decoder" : """t = UInt(Rt); n = UInt(Rn); postindex = TRUE; add = (U == '1'); register_form = FALSE; imm32 = ZeroExtend(imm12, 32);
if n == 15 || n == t then UNPREDICTABLE;"""
} , {
"name" : "STRT",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STRT<c> <Rt>, [<Rn>], +/-<Rm>{, <shift>}",
"pattern" : "cond#4 0 1 1 0 U#1 0 1 0 Rn#4 Rt#4 imm5#5 type#2 0 Rm#4",
"decoder" : """t = UInt(Rt); n = UInt(Rn); m = UInt(Rm); postindex = TRUE; add = (U == '1'); register_form = TRUE; (shift_t, shift_n) = DecodeImmShift(type, imm5);
if n == 15 || n == t || m == 15 then UNPREDICTABLE;
if ArchVersion() < 6 && m == n then UNPREDICTABLE;"""
} , {
"name" : "SUB (immediate, Thumb)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUBS <Rd>, <Rn>, #<imm32>:SUB<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "0 0 0 1 1 1 1 imm3#3 Rn#3 Rd#3",
"decoder" : """d = UInt(Rd); n = UInt(Rn); setflags = !InITBlock(); imm32 = ZeroExtend(imm3, 32);"""
} , {
"name" : "SUB (immediate, Thumb)",
"encoding" : "T2",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUBS <Rdn>, #<imm32>:SUB<c> <Rdn>, #<imm32>",
"pattern" : "0 0 1 1 1 Rdn#3 imm8#8",
"decoder" : """d = UInt(Rdn); n = UInt(Rdn); setflags = !InITBlock(); imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "SUB (immediate, Thumb)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "SUB{S}<c>.W <Rd>, <Rn>, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 0 1 1 0 1 S#1 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMP (immediate);
if Rn == '1101' then SEE SUB (SP minus immediate);
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d == 13 || (d == 15 && S == '0') || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "SUB (immediate, Thumb)",
"encoding" : "T4",
"version" : "ARMv6T2, ARMv7",
"format" : "SUBW<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 1 0 1 0 1 0 Rn#4 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rn == '1111' then SEE ADR;
if Rn == '1101' then SEE SUB (SP minus immediate);
d = UInt(Rd); n = UInt(Rn); setflags = FALSE; imm32 = ZeroExtend(i:imm3:imm8, 32);
if d IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SUB (immediate, ARM)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB{S}<c> <Rd>, <Rn>, #<imm32>",
"pattern" : "cond#4 0 0 1 0 0 1 0 S#1 Rn#4 Rd#4 imm12#12",
"decoder" : """if Rn == '1111' && S == '0' then SEE ADR;
if Rn == '1101' then SEE SUB (SP minus immediate);
if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); n = UInt(Rn); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "SUB (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUBS <Rd>, <Rn>, <Rm>:SUB<c> <Rd>, <Rn>, <Rm>",
"pattern" : "0 0 0 1 1 0 1 Rm#3 Rn#3 Rd#3",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = !InITBlock(); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "SUB (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SUB{S}<c>.W <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "1 1 1 0 1 0 1 1 1 0 1 S#1 Rn#4 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMP (register);
if Rn == '1101' then SEE SUB (SP minus register);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d == 13 || (d == 15 && S == '0') || n == 15 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SUB (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB{S}<c> <Rd>, <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 0 0 1 0 S#1 Rn#4 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
if Rn == '1101' then SEE SUB (SP minus register);
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1'); (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "SUB (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB{S}<c> <Rd>, <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0 0 0 0 0 1 0 S#1 Rn#4 Rd#4 Rs#4 0 type#2 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); s = UInt(Rs); setflags = (S == '1'); shift_t = DecodeRegShift(type);
if d == 15 || n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "SUB (SP minus immediate)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB<c> SP, #<imm32>",
"pattern" : "1 0 1 1 0 0 0 0 1 imm7#7",
"decoder" : """d = 13; setflags = FALSE; imm32 = ZeroExtend(imm7:'00', 32);"""
} , {
"name" : "SUB (SP minus immediate)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SUB{S}<c>.W <Rd>, SP, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 0 1 1 0 1 S#1 1 1 0 1 0 imm3#3 Rd#4 imm8#8",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMP (immediate);
d = UInt(Rd); setflags = (S == '1'); imm32 = ThumbExpandImm(i:imm3:imm8);
if d == 15 && S == '0' then UNPREDICTABLE;"""
} , {
"name" : "SUB (SP minus immediate)",
"encoding" : "T3",
"version" : "ARMv6T2, ARMv7",
"format" : "SUBW<c> <Rd>, SP, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 1 0 1 0 1 0 1 1 0 1 0 imm3#3 Rd#4 imm8#8",
"decoder" : """d = UInt(Rd); setflags = FALSE; imm32 = ZeroExtend(i:imm3:imm8, 32);
if d == 15 then UNPREDICTABLE;"""
} , {
"name" : "SUB (SP minus immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB{S}<c> <Rd>, SP, #<imm32>",
"pattern" : "cond#4 0 0 1 0 0 1 0 S#1 1 1 0 1 Rd#4 imm12#12",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); setflags = (S == '1'); imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "SUB (SP minus register)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SUB{S}<c> <Rd>, SP, <Rm>{, <shift>}",
"pattern" : "1 1 1 0 1 0 1 1 1 0 1 S#1 1 1 0 1 0 imm3#3 Rd#4 imm2#2 type#2 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE CMP (register);
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if d == 13 && (shift_t != SRType_LSL || shift_n > 3) then UNPREDICTABLE;
if (d == 15 && S == '0') || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SUB (SP minus register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SUB{S}<c> <Rd>, SP, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 0 0 1 0 S#1 1 1 0 1 Rd#4 imm5#5 type#2 0 Rm#4",
"decoder" : """if Rd == '1111' && S == '1' then SEE SUBS PC, LR and related instructions;
d = UInt(Rd); m = UInt(Rm); setflags = (S == '1');
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "SVC",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SVC<c> #<imm32>",
"pattern" : "1 1 0 1 1 1 1 1 imm8#8",
"decoder" : """imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "SVC",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "SVC<c> #<imm32>",
"pattern" : "cond#4 1 1 1 1 imm24#24",
"decoder" : """imm32 = ZeroExtend(imm24, 32);"""
} , {
"name" : "SWP, SWPB",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv7, ARMv7VE",
"format" : "SWP{B}<c> <Rt>, <Rt2>, [<Rn>]",
"pattern" : "cond#4 0 0 0 1 0 B#1 0 0 Rn#4 Rt#4 0 0 0 0 1 0 0 1 Rt2#4",
"decoder" : """t = UInt(Rt); t2 = UInt(Rt2); n = UInt(Rn); size = if B == '1' then 1 else 4;
if t == 15 || t2 == 15 || n == 15 || n == t || n == t2 then UNPREDICTABLE;"""
} , {
"name" : "SXTAB",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SXTAB<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 1 0 0 Rn#4 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE SXTB;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SXTAB",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTAB<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 0 1 0 Rn#4 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """if Rn == '1111' then SEE SXTB;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SXTAB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SXTAB16<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 1 0 Rn#4 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE SXTB16;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SXTAB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTAB16<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 0 0 0 Rn#4 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """if Rn == '1111' then SEE SXTB16;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SXTAH",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SXTAH<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 0 0 Rn#4 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE SXTH;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SXTAH",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTAH<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 0 1 1 Rn#4 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """if Rn == '1111' then SEE SXTH;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SXTB",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTB<c> <Rd>, <Rm>",
"pattern" : "1 0 1 1 0 0 1 0 0 1 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = 0;"""
} , {
"name" : "SXTB",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SXTB<c>.W <Rd>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 1 0 0 1 1 1 1 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SXTB",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTB<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 0 1 0 1 1 1 1 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SXTB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SXTB16<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 1 0 1 1 1 1 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SXTB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTB16<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 0 0 0 1 1 1 1 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "SXTH",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTH<c> <Rd>, <Rm>",
"pattern" : "1 0 1 1 0 0 1 0 0 0 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = 0;"""
} , {
"name" : "SXTH",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SXTH<c>.W <Rd>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 0 0 1 1 1 1 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "SXTH",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SXTH<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 0 1 1 1 1 1 1 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "TBB",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "TBB<c> [<Rn>, <Rm>]",
"pattern" : "1 1 1 0 1 0 0 0 1 1 0 1 Rn#4 1 1 1 1 0 0 0 0 0 0 0 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); is_tbh = 0;
if n == 13 || m IN {13,15} then UNPREDICTABLE;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "TBH",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "TBH<c> [<Rn>, <Rm>, LSL #1]",
"pattern" : "1 1 1 0 1 0 0 0 1 1 0 1 Rn#4 1 1 1 1 0 0 0 0 0 0 0 1 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); is_tbh = 1;
if n == 13 || m IN {13,15} then UNPREDICTABLE;
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "TEQ (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "TEQ<c> <Rn>, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 0 0 1 0 0 1 Rn#4 0 imm3#3 1 1 1 1 imm8#8",
"decoder" : """n = UInt(Rn);
imm12 = i:imm3:imm8;
imm32 = ThumbExpandImm(imm12);
if n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "TEQ (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TEQ<c> <Rn>, #<imm32>",
"pattern" : "cond#4 0 0 1 1 0 0 1 1 Rn#4 0 0 0 0 imm12#12",
"decoder" : """n = UInt(Rn);
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "TEQ (register)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "TEQ<c> <Rn>, <Rm>{, <shift>}",
"pattern" : "1 1 1 0 1 0 1 0 1 0 0 1 Rn#4 0 imm3#3 1 1 1 1 imm2#2 type#2 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "TEQ (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TEQ<c> <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 1 0 0 1 1 Rn#4 0 0 0 0 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "TEQ (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TEQ<c> <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0 0 0 1 0 0 1 1 Rn#4 0 0 0 0 Rs#4 0 type#2 1 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); s = UInt(Rs);
shift_t = DecodeRegShift(type);
if n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "TST (immediate)",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "TST<c> <Rn>, #<imm32>",
"pattern" : "1 1 1 1 0 i#1 0 0 0 0 0 1 Rn#4 0 imm3#3 1 1 1 1 imm8#8",
"decoder" : """n = UInt(Rn);
imm12 = i:imm3:imm8;
imm32 = ThumbExpandImm(imm12);
if n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "TST (immediate)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TST<c> <Rn>, #<imm32>",
"pattern" : "cond#4 0 0 1 1 0 0 0 1 Rn#4 0 0 0 0 imm12#12",
"decoder" : """n = UInt(Rn);
imm32 = ARMExpandImm(imm12);"""
} , {
"name" : "TST (register)",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TST<c> <Rn>, <Rm>",
"pattern" : "0 1 0 0 0 0 1 0 0 0 Rm#3 Rn#3",
"decoder" : """n = UInt(Rn); m = UInt(Rm); (shift_t, shift_n) = (SRType_LSL, 0);"""
} , {
"name" : "TST (register)",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "TST<c>.W <Rn>, <Rm>{, <shift>}",
"pattern" : "1 1 1 0 1 0 1 0 0 0 0 1 Rn#4 0 imm3#3 1 1 1 1 imm2#2 type#2 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm3:imm2);
if n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "TST (register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TST<c> <Rn>, <Rm>{, <shift>}",
"pattern" : "cond#4 0 0 0 1 0 0 0 1 Rn#4 0 0 0 0 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm);
(shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "TST (register-shifted register)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "TST<c> <Rn>, <Rm>, <type> <Rs>",
"pattern" : "cond#4 0 0 0 1 0 0 0 1 Rn#4 0 0 0 0 Rs#4 0 type#2 1 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); s = UInt(Rs);
shift_t = DecodeRegShift(type);
if n == 15 || m == 15 || s == 15 then UNPREDICTABLE;"""
} , {
"name" : "UADD16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 1 Rn#4 1 1 1 1 Rd#4 0 1 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UADD16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 0 1 Rn#4 Rd#4 1 1 1 1 0 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UADD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 0 Rn#4 1 1 1 1 Rd#4 0 1 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UADD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 0 1 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UASX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 1 0 Rn#4 1 1 1 1 Rd#4 0 1 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UASX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 0 1 Rn#4 Rd#4 1 1 1 1 0 0 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UBFX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UBFX<c> <Rd>, <Rn>, #<lsb>, #<widthminus1>",
"pattern" : "1 1 1 1 0 0 1 1 1 1 0 0 Rn#4 0 imm3#3 Rd#4 imm2#2 0 widthm1#5",
"decoder" : """d = UInt(Rd); n = UInt(Rn);
lsbit = UInt(imm3:imm2); widthminus1 = UInt(widthm1);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UBFX",
"encoding" : "A1",
"version" : "ARMv6T2, ARMv7",
"format" : "UBFX<c> <Rd>, <Rn>, #<lsb>, #<widthminus1>",
"pattern" : "cond#4 0 1 1 1 1 1 1 widthm1#5 Rd#4 lsb#5 1 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn);
lsbit = UInt(lsb); widthminus1 = UInt(widthm1);
if d == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "UDF",
"encoding" : "T1",
"version" : "ARMv4T, ARMv5TAll, ARMv6, ARMv7",
"format" : "UDF<c> #<imm32>",
"pattern" : "1 1 0 1 1 1 1 0 imm8#8",
"decoder" : """imm32 = ZeroExtend(imm8, 32);"""
} , {
"name" : "UDF",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "UDF<c>.W #<imm32>",
"pattern" : "1 1 1 1 0 1 1 1 1 1 1 1 imm4#4 1 0 1 0 imm12#12",
"decoder" : """imm32 = ZeroExtend(imm4:imm12, 32);"""
} , {
"name" : "UDF",
"encoding" : "A1",
"version" : "ARMv4T, ARMv5TAll, ARMv6, ARMv7",
"format" : "UDF #<imm32>",
"pattern" : "1 1 1 0 0 1 1 1 1 1 1 1 imm12#12 1 1 1 1 imm4#4",
"decoder" : """imm32 = ZeroExtend(imm12:imm4, 32);"""
} , {
"name" : "UDIV",
"encoding" : "T1",
"version" : "ARMv7R, ARMv7VE",
"format" : "UDIV<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 0 1 1 Rn#4 1 1 1 1 Rd#4 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UDIV",
"encoding" : "A1",
"version" : "ARMv7VE",
"format" : "UDIV<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 0 0 1 1 Rd#4 1 1 1 1 Rm#4 0 0 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UHADD16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UHADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 1 Rn#4 1 1 1 1 Rd#4 0 1 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UHADD16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UHADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 1 Rn#4 Rd#4 1 1 1 1 0 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UHADD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UHADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 0 Rn#4 1 1 1 1 Rd#4 0 1 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UHADD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UHADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 1 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UHASX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UHASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 1 0 Rn#4 1 1 1 1 Rd#4 0 1 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UHASX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UHASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 1 Rn#4 Rd#4 1 1 1 1 0 0 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UHSAX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UHSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 1 0 Rn#4 1 1 1 1 Rd#4 0 1 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UHSAX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UHSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 1 Rn#4 Rd#4 1 1 1 1 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UHSUB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UHSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 1 Rn#4 1 1 1 1 Rd#4 0 1 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UHSUB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UHSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 1 Rn#4 Rd#4 1 1 1 1 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UHSUB8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UHSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 0 Rn#4 1 1 1 1 Rd#4 0 1 1 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UHSUB8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UHSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 1 Rn#4 Rd#4 1 1 1 1 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UMAAL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UMAAL<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 1 1 0 Rn#4 RdLo#4 RdHi#4 0 1 1 0 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm);
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "UMAAL",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UMAAL<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 0 0 1 0 0 RdHi#4 RdLo#4 Rm#4 1 0 0 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm);
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "UMLAL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UMLAL<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 1 1 0 Rn#4 RdLo#4 RdHi#4 0 0 0 0 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = FALSE;
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "UMLAL",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "UMLAL{S}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 0 1 0 1 S#1 RdHi#4 RdLo#4 Rm#4 1 0 0 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;
if ArchVersion() < 6 && (dHi == n || dLo == n) then UNPREDICTABLE;"""
} , {
"name" : "UMULL",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UMULL<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 1 0 1 0 Rn#4 RdLo#4 RdHi#4 0 0 0 0 Rm#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = FALSE;
if dLo IN {13,15} || dHi IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;"""
} , {
"name" : "UMULL",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "UMULL{S}<c> <RdLo>, <RdHi>, <Rn>, <Rm>",
"pattern" : "cond#4 0 0 0 0 1 0 0 S#1 RdHi#4 RdLo#4 Rm#4 1 0 0 1 Rn#4",
"decoder" : """dLo = UInt(RdLo); dHi = UInt(RdHi); n = UInt(Rn); m = UInt(Rm); setflags = (S == '1');
if dLo == 15 || dHi == 15 || n == 15 || m == 15 then UNPREDICTABLE;
if dHi == dLo then UNPREDICTABLE;
if ArchVersion() < 6 && (dHi == n || dLo == n) then UNPREDICTABLE;"""
} , {
"name" : "UQADD16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UQADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 1 Rn#4 1 1 1 1 Rd#4 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UQADD16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UQADD16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 0 Rn#4 Rd#4 1 1 1 1 0 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UQADD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UQADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 0 0 Rn#4 1 1 1 1 Rd#4 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UQADD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UQADD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 0 Rn#4 Rd#4 1 1 1 1 1 0 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UQASX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UQASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 0 1 0 Rn#4 1 1 1 1 Rd#4 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UQASX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UQASX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 0 Rn#4 Rd#4 1 1 1 1 0 0 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UQSAX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UQSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 1 0 Rn#4 1 1 1 1 Rd#4 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UQSAX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UQSAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 0 Rn#4 Rd#4 1 1 1 1 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UQSUB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UQSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 1 Rn#4 1 1 1 1 Rd#4 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UQSUB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UQSUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 0 Rn#4 Rd#4 1 1 1 1 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UQSUB8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UQSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 0 Rn#4 1 1 1 1 Rd#4 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UQSUB8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UQSUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 1 0 Rn#4 Rd#4 1 1 1 1 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "USAD8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USAD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 1 1 Rn#4 1 1 1 1 Rd#4 0 0 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "USAD8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USAD8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 1 1 0 0 0 Rd#4 1 1 1 1 Rm#4 0 0 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "USADA8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USADA8<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "1 1 1 1 1 0 1 1 0 1 1 1 Rn#4 Ra#4 Rd#4 0 0 0 0 Rm#4",
"decoder" : """if Ra == '1111' then SEE USAD8;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra);
if d IN {13,15} || n IN {13,15} || m IN {13,15} || a == 13 then UNPREDICTABLE;"""
} , {
"name" : "USADA8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USADA8<c> <Rd>, <Rn>, <Rm>, <Ra>",
"pattern" : "cond#4 0 1 1 1 1 0 0 0 Rd#4 Ra#4 Rm#4 0 0 0 1 Rn#4",
"decoder" : """if Ra == '1111' then SEE USAD8;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); a = UInt(Ra);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "USAT",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USAT<c> <Rd>, #<saturate_to>, <Rn>{, <shift>}",
"pattern" : "1 1 1 1 0 0 1 1 1 0 sh#1 0 Rn#4 0 imm3#3 Rd#4 imm2#2 0 sat_imm#5",
"decoder" : """if sh == '1' && (imm3:imm2) == '00000' then SEE USAT16;
d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm); (shift_t, shift_n) = DecodeImmShift(sh:'0', imm3:imm2);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "USAT",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USAT<c> <Rd>, #<saturate_to>, <Rn>{, <shift>}",
"pattern" : "cond#4 0 1 1 0 1 1 1 sat_imm#5 Rd#4 imm5#5 sh#1 0 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm); (shift_t, shift_n) = DecodeImmShift(sh:'0', imm5);
if d == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "USAT16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USAT16<c> <Rd>, #<saturate_to>, <Rn>",
"pattern" : "1 1 1 1 0 0 1 1 1 0 1 0 Rn#4 0 0 0 0 Rd#4 0 0 0 0 sat_imm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm);
if d IN {13,15} || n IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "USAT16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USAT16<c> <Rd>, #<saturate_to>, <Rn>",
"pattern" : "cond#4 0 1 1 0 1 1 1 0 sat_imm#4 Rd#4 1 1 1 1 0 0 1 1 Rn#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); saturate_to = UInt(sat_imm);
if d == 15 || n == 15 then UNPREDICTABLE;"""
} , {
"name" : "USAX",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 1 0 Rn#4 1 1 1 1 Rd#4 0 1 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "USAX",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USAX<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 0 1 Rn#4 Rd#4 1 1 1 1 0 1 0 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "USUB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 1 Rn#4 1 1 1 1 Rd#4 0 1 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "USUB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USUB16<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 0 1 Rn#4 Rd#4 1 1 1 1 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "USUB8",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "USUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "1 1 1 1 1 0 1 0 1 1 0 0 Rn#4 1 1 1 1 Rd#4 0 1 0 0 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d IN {13,15} || n IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "USUB8",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "USUB8<c> <Rd>, <Rn>, <Rm>",
"pattern" : "cond#4 0 1 1 0 0 1 0 1 Rn#4 Rd#4 1 1 1 1 1 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); n = UInt(Rn); m = UInt(Rm);
if d == 15 || n == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UXTAB",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UXTAB<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 1 0 1 Rn#4 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE UXTB;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UXTAB",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTAB<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 1 1 0 Rn#4 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """if Rn == '1111' then SEE UXTB;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UXTAB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UXTAB16<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 1 1 Rn#4 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE UXTB16;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UXTAB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTAB16<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 1 0 0 Rn#4 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """if Rn == '1111' then SEE UXTB16;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UXTAH",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UXTAH<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 0 1 Rn#4 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """if Rn == '1111' then SEE UXTH;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || n == 13 || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UXTAH",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTAH<c> <Rd>, <Rn>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 1 1 1 Rn#4 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """if Rn == '1111' then SEE UXTH;
d = UInt(Rd); n = UInt(Rn); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UXTB",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTB<c> <Rd>, <Rm>",
"pattern" : "1 0 1 1 0 0 1 0 1 1 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = 0;"""
} , {
"name" : "UXTB",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "UXTB<c>.W <Rd>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 1 0 1 1 1 1 1 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UXTB",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTB<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 1 1 0 1 1 1 1 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UXTB16",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "UXTB16<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 1 1 1 1 1 1 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UXTB16",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTB16<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 1 0 0 1 1 1 1 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "UXTH",
"encoding" : "T1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTH<c> <Rd>, <Rm>",
"pattern" : "1 0 1 1 0 0 1 0 1 0 Rm#3 Rd#3",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = 0;"""
} , {
"name" : "UXTH",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "UXTH<c>.W <Rd>, <Rm>{, <rotation>}",
"pattern" : "1 1 1 1 1 0 1 0 0 0 0 1 1 1 1 1 1 1 1 1 Rd#4 1 0 rotate#2 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d IN {13,15} || m IN {13,15} then UNPREDICTABLE;"""
} , {
"name" : "UXTH",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "UXTH<c> <Rd>, <Rm>{, <rotation>}",
"pattern" : "cond#4 0 1 1 0 1 1 1 1 1 1 1 1 Rd#4 rotate#2 0 0 0 1 1 1 Rm#4",
"decoder" : """d = UInt(Rd); m = UInt(Rm); rotation = UInt(rotate:'000');
if d == 15 || m == 15 then UNPREDICTABLE;"""
} , {
"name" : "WFE",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "WFE<c>",
"pattern" : "1 0 1 1 1 1 1 1 0 0 1 0 0 0 0 0",
"decoder" : """NOP();"""
} , {
"name" : "WFE",
"encoding" : "T2",
"version" : "ARMv7",
"format" : "WFE<c>.W",
"pattern" : "1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0",
"decoder" : """NOP();"""
} , {
"name" : "WFE",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "WFE<c>",
"pattern" : "cond#4 0 0 1 1 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 0",
"decoder" : """NOP();"""
} , {
"name" : "WFI",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "WFI<c>",
"pattern" : "1 0 1 1 1 1 1 1 0 0 1 1 0 0 0 0",
"decoder" : """NOP();"""
} , {
"name" : "WFI",
"encoding" : "T2",
"version" : "ARMv7",
"format" : "WFI<c>.W",
"pattern" : "1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1",
"decoder" : """NOP();"""
} , {
"name" : "WFI",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "WFI<c>",
"pattern" : "cond#4 0 0 1 1 0 0 1 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1",
"decoder" : """NOP();"""
} , {
"name" : "YIELD",
"encoding" : "T1",
"version" : "ARMv7",
"format" : "YIELD<c>",
"pattern" : "1 0 1 1 1 1 1 1 0 0 0 1 0 0 0 0",
"decoder" : """NOP();"""
} , {
"name" : "YIELD",
"encoding" : "T2",
"version" : "ARMv7",
"format" : "YIELD<c>.W",
"pattern" : "1 1 1 1 0 0 1 1 1 0 1 0 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1",
"decoder" : """NOP();"""
} , {
"name" : "YIELD",
"encoding" : "A1",
"version" : "ARMv6K, ARMv7",
"format" : "YIELD<c>",
"pattern" : "cond#4 0011001000001111000000000001",
"decoder" : """NOP();"""
} , {
"name" : "ERET",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7VE",
"format" : "ERET",
"pattern" : "111100111101111010001111 imm8#8",
"decoder" : """if imm8 != '00000000' then SEE SUBS PC, LR and related instructions;"""
} , {
"name" : "ERET",
"encoding" : "A1",
"version" : "ARMv7VE",
"format" : "ERET",
"pattern" : "cond#4 0001011000000000000001101110",
"decoder" : """NOP();"""
} , {
"name" : "HVC",
"encoding" : "T1",
"version" : "ARMv7VE",
"format" : "HVC #<imm32>",
"pattern" : "111101111110 imm4#4 1000 imm12#12",
"decoder" : """if InITBlock() then UNPREDICTABLE;
imm32 = imm4:imm12;"""
} , {
"name" : "HVC",
"encoding" : "A1",
"version" : "ARMv7VE",
"format" : "HVC #<imm32>",
"pattern" : "cond#4 00010100 imm12#12 0111 imm4#4",
"decoder" : """if cond != '1110' then UNPREDICTABLE;
imm32 = imm12:imm4;"""
} , {
"name" : "LDM (exception return)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDM<amode><c> <Rn>{!}, <registers_with_pc> ^",
"pattern" : "cond#4 100 P#1 U#1 1 W#1 1 Rn#4 1 register_list#15",
"decoder" : """n = UInt(Rn);
registers = register_list;
wback = (W == '1');
increment = (U == '1');
wordhigher = (P == U);
if n == 15 then UNPREDICTABLE;
if wback && registers<n> == '1' && ArchVersion() >= 7 then UNPREDICTABLE;"""
} , {
"name" : "LDM (User registers)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "LDM<amode><c> <Rn>, <registers_without_pc> ^",
"pattern" : "cond#4 100 P#1 U#1 101 Rn#4 0 register_list#15",
"decoder" : """n = UInt(Rn);
registers = register_list;
increment = (U == '1');
wordhigher = (P == U);
if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "MRS (Banked register)",
"encoding" : "T1",
"version" : "ARMv7VE",
"format" : "MRS<c> <Rd>, <banked_reg>",
"pattern" : "11110011111 R#1 m1#4 1000 Rd#4 001 m#1 0000",
"decoder" : """d = UInt(Rd); read_spsr = (R == '1'); if d IN {13,15} then UNPREDICTABLE;
SYSm = m:m1;"""
} , {
"name" : "MRS (Banked register)",
"encoding" : "A1",
"version" : "ARMv7VE",
"format" : "MRS<c> <Rd>, <banked_reg>",
"pattern" : "cond#4 00010 R#1 00 m1#4 Rd#4 001 m#1 00000000",
"decoder" : """d = UInt(Rd); read_spsr = (R == '1'); if d == 15 then UNPREDICTABLE;
SYSm = m:m1;"""
} , {
"name" : "SMC (previously SMI)",
"encoding" : "T1",
"version" : "ARMSecurityExtension",
"format" : "SMC<c> #<imm32>",
"pattern" : "111101111111 imm4#4 1000000000000000",
"decoder" : """imm32 = ZeroExtend(imm4, 32); if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "SMC (previously SMI)",
"encoding" : "T2",
"version" : "ARMSecurityExtension",
"format" : "SMC<c> #<imm32>",
"pattern" : "cond#4 000101100000000000000111 imm4#4",
"decoder" : """imm32 = ZeroExtend(imm4, 32);"""
} , {
"name" : "SRS, Thumb",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SRSDB<c> SP{!}, #<mode>",
"pattern" : "1110100000 W#1 0110111000000000 mode#5",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then UNPREDICTABLE;
wback = (W == '1'); increment = FALSE; wordhigher = FALSE;"""
} , {
"name" : "SRS, Thumb",
"encoding" : "T2",
"version" : "ARMv6T2, ARMv7",
"format" : "SRS{IA}<c> SP{!}, #<mode>",
"pattern" : "1110100110 W#1 0110111000000000 mode#5",
"decoder" : """if CurrentInstrSet() == InstrSet_ThumbEE then UNPREDICTABLE;
wback = (W == '1'); increment = TRUE; wordhigher = FALSE;"""
} , {
"name" : "SRS, ARM",
"encoding" : "A1",
"version" : "ARMv6All, ARMv7",
"format" : "SRS<amode> SP{!}, #<mode>",
"pattern" : "1111100 P#1 U#1 1 W#1 0110100000101000 mode#5",
"decoder" : """wback = (W == '1'); increment = (U == '1'); wordhigher = (P == U);"""
} , {
"name" : "STM (User registers)",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "STM<amode><c> <Rn>, <registers> ^",
"pattern" : "cond#4 100 P#1 U#1 100 Rn#4 register_list#16",
"decoder" : """n = UInt(Rn); registers = register_list; increment = (U == '1'); wordhigher = (P == U); if n == 15 || BitCount(registers) < 1 then UNPREDICTABLE;"""
} , {
"name" : "SUBS PC, LR, Thumb",
"encoding" : "T1",
"version" : "ARMv6T2, ARMv7",
"format" : "SUBS<c> PC, LR, #<imm32>",
"pattern" : "111100111101111010001111 imm8#8",
"decoder" : """if IsZero(imm8) then SEE ERET;
if CurrentInstrSet() == InstrSet_ThumbEE then UNPREDICTABLE;
if CurrentModeIsHyp() then UNDEFINED;
n = 14; imm32 = ZeroExtend(imm8, 32);
if InITBlock() && !LastInITBlock() then UNPREDICTABLE;"""
} , {
"name" : "SUBS PC, LR and related instructions, ARM",
"encoding" : "A1",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 001 opcode_#4 1 Rn#4 1111 imm12#12",
"decoder" : """n = UInt(Rn); imm32 = ARMExpandImm(imm12); register_form = FALSE;"""
} , {
"name" : "SUBS PC, LR and related instructions, ARM",
"encoding" : "A2",
"version" : "ARMv4All, ARMv5TAll, ARMv6All, ARMv7",
"format" : "CUSTOM",
"pattern" : "cond#4 000 opcode_#4 1 Rn#4 1111 imm5#5 type#2 0 Rm#4",
"decoder" : """n = UInt(Rn); m = UInt(Rm); register_form = TRUE; (shift_t, shift_n) = DecodeImmShift(type, imm5);"""
} , {
"name" : "VABA, VABAL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1'); long_destination = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABA, VABAL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1'); long_destination = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABA, VABAL",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 0 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); long_destination = TRUE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VABA, VABAL",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 0 1 0 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); long_destination = TRUE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VABD, VABDL (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1'); long_destination = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABD, VABDL (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1'); long_destination = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABD, VABDL (integer)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "VABDL.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 1 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); long_destination = TRUE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VABD, VABDL (integer)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "VABDL.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 0 1 1 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); long_destination = TRUE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VABD (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABD (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABS",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 1 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
advsimd = TRUE; floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABS",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 1 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
advsimd = TRUE; floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VABS",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 0 0 0 Vd#4 1 0 1 sz#1 1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VABS",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 0 0 0 Vd#4 1 0 1 sz#1 1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VACGE, VACGT, VACLE, VACLT",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
or_equal = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VACGE, VACGT, VACLE, VACLT",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
or_equal = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VADD (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VADD (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VADD (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VADD (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VADD (floating-point)",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 D#1 1 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VADD (floating-point)",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 D#1 1 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VADDHN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VADDHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize; d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VADDHN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VADDHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize; d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VADDL, VADDW",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 0 0 op#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' || (op == '1' && Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize; is_vaddw = (op == '1'); d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VADDL, VADDW",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 0 0 0 op#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' || (op == '1' && Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize; is_vaddw = (op == '1'); d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VAND (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 0 0 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VAND (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 0 0 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VBIC (immediate)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 i#1 1 1 1 1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 1 1 imm4#4",
"decoder" : """if cmode<0> == '0' || cmode<3:2> == '11' then SEE "Related encodings";
if Q == '1' && Vd<0> == '1' then UNDEFINED;
imm64 = AdvSIMDExpandImm('1', cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VBIC (immediate)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 i#1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 1 1 imm4#4",
"decoder" : """if cmode<0> == '0' || cmode<3:2> == '11' then SEE "Related encodings";
if Q == '1' && Vd<0> == '1' then UNDEFINED;
imm64 = AdvSIMDExpandImm('1', cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VBIC (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 0 1 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VBIC (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 0 1 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VBIF, VBIT, VBSL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 op#2 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if op == '00' then SEE VEOR;
if op == '01' then operation = VBitOps_VBSL;
if op == '10' then operation = VBitOps_VBIT;
if op == '11' then operation = VBitOps_VBIF;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VBIF, VBIT, VBSL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 op#2 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if op == '00' then SEE VEOR;
if op == '01' then operation = VBitOps_VBSL;
if op == '10' then operation = VBitOps_VBIT;
if op == '11' then operation = VBitOps_VBIF;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCEQ (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
int_operation = TRUE; esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCEQ (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
int_operation = TRUE; esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCEQ (register)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
int_operation = FALSE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCEQ (register)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
int_operation = FALSE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCEQ (immediate #0)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCEQ (immediate #0)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGE (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 0 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
type = if U == '1' then VCGEtype_unsigned else VCGEtype_signed;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGE (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 0 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
type = if U == '1' then VCGEtype_unsigned else VCGEtype_signed;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGE (register)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
type = VCGEtype_fp; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGE (register)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
type = VCGEtype_fp; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGE (immediate #0)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 0 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGE (immediate #0)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 0 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGT (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 0 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
type = if U == '1' then VCGTtype_unsigned else VCGTtype_signed;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGT (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 0 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
type = if U == '1' then VCGTtype_unsigned else VCGTtype_signed;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGT (register)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
type = VCGTtype_fp; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGT (register)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
type = VCGTtype_fp; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGT (immediate #0)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCGT (immediate #0)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLE (immediate #0)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLE (immediate #0)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 0 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLS",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLS",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLT (immediate #0)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 1 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLT (immediate #0)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 1 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLZ",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 0 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCLZ",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 0 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCMP, VCMPE",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 1 0 0 Vd#4 1 0 1 sz#1 E#1 1 M#1 0 Vm#4",
"decoder" : """dp_operation = (sz == '1'); quiet_nan_exc = (E == '1'); with_zero = FALSE; d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VCMP, VCMPE",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 1 0 0 Vd#4 1 0 1 sz#1 E#1 1 M#1 0 Vm#4",
"decoder" : """dp_operation = (sz == '1'); quiet_nan_exc = (E == '1'); with_zero = FALSE; d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VCMP, VCMPE",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 1 0 1 Vd#4 1 0 1 sz#1 E#1 1 0 0 0 0 0 0",
"decoder" : """dp_operation = (sz == '1'); quiet_nan_exc = (E == '1'); with_zero = TRUE; d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);"""
} , {
"name" : "VCMP, VCMPE",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 1 0 1 Vd#4 1 0 1 sz#1 E#1 1 0 0 0 0 0 0",
"decoder" : """dp_operation = (sz == '1'); quiet_nan_exc = (E == '1'); with_zero = TRUE; d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);"""
} , {
"name" : "VCNT",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size != '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8; elements = 8;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCNT",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size != '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8; elements = 8;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCVT (between floating-point and integer, AdvancedSIMD)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "111111111 D#1 11 size#2 11 Vd#4 011 op#2 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size != '10' then UNDEFINED;
to_integer = (op<1> == '1'); unsigned_ = (op<0> == '1'); esize = 32; elements = 2;
if to_integer then
round_zero = TRUE;
else
round_nearest = TRUE;
endif
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCVT (between floating-point and integer, AdvancedSIMD)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "111100111 D#1 11 size#2 11 Vd#4 011 op#2 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size != '10' then UNDEFINED;
to_integer = (op<1> == '1'); unsigned_ = (op<0> == '1'); esize = 32; elements = 2;
if to_integer then
round_zero = TRUE;
else
round_nearest = TRUE;
endif
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCVT, VCVTR (between floating-point and integer, Floating-point)",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 1 opc2#3 Vd#4 1 0 1 sz#1 op#1 1 M#1 0 Vm#4",
"decoder" : """if opc2 != '000' && !(opc2 IN "10x") then SEE "Related encodings";
to_integer = (opc2<2> == '1'); dp_operation = (sz == 1);
if to_integer then
unsigned_ = (opc2<0> == '0');
round_zero = (op == '1');
d = UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);
else
unsigned_ = (op == '0');
round_nearest = FALSE;
m = UInt(Vm:M);
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
endif"""
} , {
"name" : "VCVT, VCVTR (between floating-point and integer, Floating-point)",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 1 opc2#3 Vd#4 1 0 1 sz#1 op#1 1 M#1 0 Vm#4",
"decoder" : """if opc2 != '000' && !(opc2 IN "10x") then SEE "Related encodings";
to_integer = (opc2<2> == '1'); dp_operation = (sz == 1);
if to_integer then
unsigned_ = (opc2<0> == '0');
round_zero = (op == '1');
d = UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);
else
unsigned_ = (op == '0');
round_nearest = FALSE;
m = UInt(Vm:M);
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
endif"""
} , {
"name" : "VCVT (between floating-point and fixed-point, AdvancedSIMD)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 1 1 1 op#1 0 Q#1 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if imm6 IN "0xxxxx" then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
to_fixed = (op == '1'); unsigned_ = (U == '1');
if to_fixed then
round_zero = TRUE;
else
round_nearest = TRUE;
endif
imm32 = imm6;
esize = 32; frac_bits = 64 - UInt(imm6); elements = 2;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCVT (between floating-point and fixed-point, AdvancedSIMD)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 1 1 1 op#1 0 Q#1 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if imm6 IN "0xxxxx" then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
to_fixed = (op == '1'); unsigned_ = (U == '1');
if to_fixed then
round_zero = TRUE;
else
round_nearest = TRUE;
endif
imm32 = imm6;
esize = 32; frac_bits = 64 - UInt(imm6); elements = 2;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VCVT (between floating-point and fixed-point, Floating-point)",
"encoding" : "T1",
"version" : "VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 1 op#1 1 U#1 Vd#4 1 0 1 sf#1 sx#1 1 i#1 0 imm4#4",
"decoder" : """to_fixed = (op == '1');
dp_operation = (sf == '1');
unsigned_ = (U == '1');
size = if sx == '0' then 16 else 32;
frac_bits = size - UInt(imm4:i);
if to_fixed then
round_zero = TRUE;
else
round_nearest = TRUE;
endif
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
if frac_bits < 0 then UNPREDICTABLE;"""
} , {
"name" : "VCVT (between floating-point and fixed-point, Floating-point)",
"encoding" : "A1",
"version" : "VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 1 op#1 1 U#1 Vd#4 1 0 1 sf#1 sx#1 1 i#1 0 imm4#4",
"decoder" : """to_fixed = (op == '1');
dp_operation = (sf == '1');
unsigned_ = (U == '1');
size = if sx == '0' then 16 else 32;
frac_bits = size - UInt(imm4:i);
if to_fixed then
round_zero = TRUE;
else
round_nearest = TRUE;
endif
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
if frac_bits < 0 then UNPREDICTABLE;"""
} , {
"name" : "VCVT (between double-precision and single-precision)",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 1 1 1 Vd#4 1 0 1 sz#1 1 1 M#1 0 Vm#4",
"decoder" : """double_to_single = (sz == '1');
d = if double_to_single then UInt(Vd:D) else UInt(D:Vd);
m = if double_to_single then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VCVT (between double-precision and single-precision)",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 1 1 1 Vd#4 1 0 1 sz#1 1 1 M#1 0 Vm#4",
"decoder" : """double_to_single = (sz == '1');
d = if double_to_single then UInt(Vd:D) else UInt(D:Vd);
m = if double_to_single then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VCVT (between half-precision and single-precision, AdvancedSIMD)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 1 1 op#1 0 0 M#1 0 Vm#4",
"decoder" : """half_to_single = (op == '1');
if size != '01' then UNDEFINED;
if half_to_single && Vd<0> == '1' then UNDEFINED;
if !half_to_single && Vm<0> == '1' then UNDEFINED;
esize = 16; elements = 4;
m = UInt(M:Vm); d = UInt(D:Vd);"""
} , {
"name" : "VCVT (between half-precision and single-precision, AdvancedSIMD)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 1 1 op#1 0 0 M#1 0 Vm#4",
"decoder" : """half_to_single = (op == '1');
if size != '01' then UNDEFINED;
if half_to_single && Vd<0> == '1' then UNDEFINED;
if !half_to_single && Vm<0> == '1' then UNDEFINED;
esize = 16; elements = 4;
m = UInt(M:Vm); d = UInt(D:Vd);"""
} , {
"name" : "VCVTB, VCVTT",
"encoding" : "T1",
"version" : "VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 0 1 op#1 Vd#4 1 0 1 0 T#1 1 M#1 0 Vm#4",
"decoder" : """half_to_single = (op == '0');
lowbit = if T == '1' then 16 else 0; m = UInt(Vm:M); d = UInt(Vd:D);"""
} , {
"name" : "VCVTB, VCVTT",
"encoding" : "A1",
"version" : "VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 0 1 op#1 Vd#4 1 0 1 0 T#1 1 M#1 0 Vm#4",
"decoder" : """half_to_single = (op == '0');
lowbit = if T == '1' then 16 else 0; m = UInt(Vm:M); d = UInt(Vd:D);"""
} , {
"name" : "VDIV",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 0 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VDIV",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 0 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VDUP (scalar)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 imm4#4 Vd#4 1 1 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if imm4 IN "x000" then UNDEFINED;
if Q == '1' && Vd<0> == '1' then UNDEFINED;
case imm4 of
when "xxx1" esize = 8; elements = 8; index = UInt(imm4<3:1>);
when "xx10" esize = 16; elements = 4; index = UInt(imm4<3:2>);
when "x100" esize = 32; elements = 2; index = UInt(imm4<3>);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VDUP (scalar)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 imm4#4 Vd#4 1 1 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if imm4 IN "x000" then UNDEFINED;
if Q == '1' && Vd<0> == '1' then UNDEFINED;
case imm4 of
when "xxx1" esize = 8; elements = 8; index = UInt(imm4<3:1>);
when "xx10" esize = 16; elements = 4; index = UInt(imm4<3:2>);
when "x100" esize = 32; elements = 2; index = UInt(imm4<3>);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VDUP (ARM core register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 b#1 Q#1 0 Vd#4 Rt#4 1 0 1 1 D#1 0 e#1 1 0 0 0 0",
"decoder" : """if Q == '1' && Vd<0> == '1' then UNDEFINED;
d = UInt(D:Vd); t = UInt(Rt);
regs = if Q == '0' then 1 else 2;
case b:e of
when '00' esize = 32; elements = 2;
when '01' esize = 16; elements = 4;
when '10' esize = 8; elements = 8;
when '11' UNDEFINED;
endcase
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VDUP (ARM core register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 b#1 Q#1 0 Vd#4 Rt#4 1 0 1 1 D#1 0 e#1 1 0 0 0 0",
"decoder" : """if Q == '1' && Vd<0> == '1' then UNDEFINED;
d = UInt(D:Vd); t = UInt(Rt);
regs = if Q == '0' then 1 else 2;
case b:e of
when '00' esize = 32; elements = 2;
when '01' esize = 16; elements = 4;
when '10' esize = 8; elements = 8;
when '11' UNDEFINED;
endcase
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VEOR",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 0 0 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VEOR",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 0 0 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VEXT",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 1 1 Vn#4 Vd#4 imm4#4 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if Q == '0' && imm4<3> == '1' then UNDEFINED;
imm32 = imm4; quadword_operation = (Q == '1'); position = 8 * UInt(imm4);
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VEXT",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 1 1 Vn#4 Vd#4 imm4#4 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if Q == '0' && imm4<3> == '1' then UNDEFINED;
imm32 = imm4; quadword_operation = (Q == '1'); position = 8 * UInt(imm4);
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VFMA, VFMS",
"encoding" : "T1",
"version" : "AdvancedSIMDv2",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; op1_neg = (op == '1'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VFMA, VFMS",
"encoding" : "A1",
"version" : "AdvancedSIMDv2",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; op1_neg = (op == '1'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VFMA, VFMS",
"encoding" : "T2",
"version" : "VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then UNPREDICTABLE;
advsimd = FALSE; dp_operation = (sz == '1'); op1_neg = (op == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VFMA, VFMS",
"encoding" : "A2",
"version" : "VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then UNPREDICTABLE;
advsimd = FALSE; dp_operation = (sz == '1'); op1_neg = (op == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VFNMA, VFNMS",
"encoding" : "T1",
"version" : "VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 0 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then UNPREDICTABLE;
op1_neg = (op == '1');
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N); m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VFNMA, VFNMS",
"encoding" : "A1",
"version" : "VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 0 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then UNPREDICTABLE;
op1_neg = (op == '1');
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VHADD, VHSUB",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 0 op#1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
add = (op == '0'); unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VHADD, VHSUB",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 0 op#1 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
add = (op == '0'); unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VLD1 (multiple single elements)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """case type of
when '0111'
regs = 1;
if align<1> == '1' then UNDEFINED;
when '1010'
regs = 2;
if align == '11' then UNDEFINED;
when '0110'
regs = 3;
if align<1> == '1' then UNDEFINED;
when '0010'
regs = 4;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLD1 (multiple single elements)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """case type of
when '0111'
regs = 1;
if align<1> == '1' then UNDEFINED;
when '1010'
regs = 2;
if align == '11' then UNDEFINED;
when '0110'
regs = 3;
if align<1> == '1' then UNDEFINED;
when '0010'
regs = 4;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLD1 (single element to one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 size#2 0 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD1 (single element to all lanes);
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); alignment = 1;
when '01'
if index_align<1> != '0' then UNDEFINED;
ebytes = 2; esize = 16;
index = UInt(index_align<3:2>);
alignment = if index_align<0> == '0' then 1 else 2;
when '10'
if index_align<2> != '0' then UNDEFINED;
if index_align<1:0> != '00' && index_align<1:0> != '11' then UNDEFINED;
ebytes = 4;
esize = 32;
index = UInt(index_align<3>);
alignment = if index_align<1:0> == '00' then 1 else 4;
endcase
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "VLD1 (single element to one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 size#2 0 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD1 (single element to all lanes);
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); alignment = 1;
when '01'
if index_align<1> != '0' then UNDEFINED;
ebytes = 2; esize = 16;
index = UInt(index_align<3:2>);
alignment = if index_align<0> == '0' then 1 else 2;
when '10'
if index_align<2> != '0' then UNDEFINED;
if index_align<1:0> != '00' && index_align<1:0> != '11' then UNDEFINED;
ebytes = 4;
esize = 32;
index = UInt(index_align<3>);
alignment = if index_align<1:0> == '00' then 1 else 4;
endcase
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "VLD1 (single element to all lanes)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 1 1 0 0 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' || (size == '00' && a == '1') then UNDEFINED;
ebytes = 1 << UInt(size);
elements = 8 DIV ebytes;
regs = if T == '0' then 1 else 2;
alignment = if a == '0' then 1 else ebytes;
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLD1 (single element to all lanes)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 1 1 0 0 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' || (size == '00' && a == '1') then UNDEFINED;
ebytes = 1 << UInt(size);
elements = 8 DIV ebytes;
regs = if T == '0' then 1 else 2;
alignment = if a == '0' then 1 else ebytes;
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLD2 (multiple 2-element structures)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '1000'
regs = 1; inc = 1;
if align == '11' then UNDEFINED;
when '1001'
regs = 1; inc = 2;
if align == '11' then UNDEFINED;
when '0011'
regs = 2; inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLD2 (multiple 2-element structures)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '1000'
regs = 1; inc = 1;
if align == '11' then UNDEFINED;
when '1001'
regs = 1; inc = 2;
if align == '11' then UNDEFINED;
when '0011'
regs = 2; inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLD2 (single 2-element structure to one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 size#2 0 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD2 (single 2-element structure to all lanes);
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 2;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 4;
when '10'
if index_align<1> != '0' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
endcase
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD2 (single 2-element structure to one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 size#2 0 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD2 (single 2-element structure to all lanes);
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 2;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 4;
when '10'
if index_align<1> != '0' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
endcase
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD2 (single 2-element structure to all lanes)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 1 1 0 1 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
ebytes = 1 << UInt(size);
elements = 8 DIV ebytes;
alignment = if a == '0' then 1 else 2*ebytes;
inc = if T == '0' then 1 else 2;
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD2 (single 2-element structure to all lanes)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 1 1 0 1 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
ebytes = 1 << UInt(size);
elements = 8 DIV ebytes;
alignment = if a == '0' then 1 else 2*ebytes;
inc = if T == '0' then 1 else 2;
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD3 (multiple 3-element structures)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' || align<1> == '1' then UNDEFINED;
case type of
when '0100'
inc = 1;
when '0101'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align<0> == '0' then 1 else 8;
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD3 (multiple 3-element structures)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' || align<1> == '1' then UNDEFINED;
case type of
when '0100'
inc = 1;
when '0101'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align<0> == '0' then 1 else 8;
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD3 (single 3-element structure to one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 size#2 1 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD3 (single 3-element structure to all lanes);
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
when '01'
if index_align<0> != '0' then UNDEFINED;
ebytes = 2; esize = 16; index = UInt(index_align<3:2>); inc = if index_align<1> == '0' then 1 else 2;
when '10'
if index_align<1:0> != '00' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>); inc = if index_align<2> == '0' then 1 else 2;
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD3 (single 3-element structure to one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 size#2 1 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD3 (single 3-element structure to all lanes);
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
when '01'
if index_align<0> != '0' then UNDEFINED;
ebytes = 2; esize = 16; index = UInt(index_align<3:2>); inc = if index_align<1> == '0' then 1 else 2;
when '10'
if index_align<1:0> != '00' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>); inc = if index_align<2> == '0' then 1 else 2;
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD3 (single 3-element structure to all lanes)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 1 1 1 0 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' || a == '1' then UNDEFINED;
ebytes = 1 << UInt(size); elements = 8 DIV ebytes;
inc = if T == '0' then 1 else 2;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD3 (single 3-element structure to all lanes)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 1 1 1 0 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' || a == '1' then UNDEFINED;
ebytes = 1 << UInt(size); elements = 8 DIV ebytes;
inc = if T == '0' then 1 else 2;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD4 (multiple 4-element structures)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '0000'
inc = 1;
when '0001'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD4 (multiple 4-element structures)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 1 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '0000'
inc = 1;
when '0001'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD4 (single 4-element structure to one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 size#2 1 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD4 (single 4-element structure to all lanes);
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 4;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
when '10'
if index_align<1:0> == '11' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<1:0> == '00' then 1 else 4 << UInt(index_align<1:0>);
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD4 (single 4-element structure to one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 size#2 1 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then SEE VLD4 (single 4-element structure to all lanes);
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 4;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
when '10'
if index_align<1:0> == '11' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<1:0> == '00' then 1 else 4 << UInt(index_align<1:0>);
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD4 (single 4-element structure to all lanes)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 1 0 Rn#4 Vd#4 1 1 1 1 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' && a == '0' then UNDEFINED;
if size == '11' then
ebytes = 4; elements = 2; alignment = 16;
else
ebytes = 1 << UInt(size); elements = 8 DIV ebytes;
if size == '10' then
alignment = if a == '0' then 1 else 8;
else
alignment = if a == '0' then 1 else 4*ebytes;
endif
endif
inc = if T == '0' then 1 else 2;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLD4 (single 4-element structure to all lanes)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 1 0 Rn#4 Vd#4 1 1 1 1 size#2 T#1 a#1 Rm#4",
"decoder" : """if size == '11' && a == '0' then UNDEFINED;
if size == '11' then
ebytes = 4; elements = 2; alignment = 16;
else
ebytes = 1 << UInt(size); elements = 8 DIV ebytes;
if size == '10' then
alignment = if a == '0' then 1 else 8;
else
alignment = if a == '0' then 1 else 4*ebytes;
endif
endif
inc = if T == '0' then 1 else 2;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VLDM",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VLDM{mode} <Rn>{!}, <list>",
"pattern" : "1 1 1 0 1 1 0 P#1 U#1 D#1 W#1 1 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '0' && U == '1' && W == '1' && Rn == '1101' then SEE VPOP;
if P == '1' && W == '0' then SEE VLDR;
if P == U && W == '1' then UNDEFINED;
single_regs = FALSE; add = (U == '1'); wback = (W == '1');
d = UInt(D:Vd); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLDM",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VLDM{mode}<c> <Rn>{!}, <list>",
"pattern" : "cond#4 1 1 0 P#1 U#1 D#1 W#1 1 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '0' && U == '1' && W == '1' && Rn == '1101' then SEE VPOP;
if P == '1' && W == '0' then SEE VLDR;
if P == U && W == '1' then UNDEFINED;
single_regs = FALSE; add = (U == '1'); wback = (W == '1');
d = UInt(D:Vd); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLDM",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VLDM{mode} <Rn>{!}, <list>",
"pattern" : "1 1 1 0 1 1 0 P#1 U#1 D#1 W#1 1 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '0' && U == '1' && W == '1' && Rn == '1101' then SEE VPOP;
if P == '1' && W == '0' then SEE VLDR;
if P == U && W == '1' then UNDEFINED;
single_regs = TRUE; add = (U == '1'); wback = (W == '1'); d = UInt(Vd:D); n = UInt(Rn);
imm32 = ZeroExtend(imm8:'00', 32); regs = UInt(imm8);
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLDM",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VLDM{mode}<c> <Rn>{!}, <list>",
"pattern" : "cond#4 1 1 0 P#1 U#1 D#1 W#1 1 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '0' && U == '1' && W == '1' && Rn == '1101' then SEE VPOP;
if P == '1' && W == '0' then SEE VLDR;
if P == U && W == '1' then UNDEFINED;
single_regs = TRUE; add = (U == '1'); wback = (W == '1'); d = UInt(Vd:D); n = UInt(Rn);
imm32 = ZeroExtend(imm8:'00', 32); regs = UInt(imm8);
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VLDR",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VLDR <Dd>, [<Rn>{, #+/-<imm>}]",
"pattern" : "1 1 1 0 1 1 0 1 U#1 D#1 0 1 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_reg = FALSE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32); d = UInt(D:Vd); n = UInt(Rn);"""
} , {
"name" : "VLDR",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VLDR<c> <Dd>, [<Rn>{, #+/-<imm>}]",
"pattern" : "cond#4 1 1 0 1 U#1 D#1 0 1 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_reg = FALSE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32); d = UInt(D:Vd); n = UInt(Rn);"""
} , {
"name" : "VLDR",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VLDR <Sd>, [<Rn>{, #+/-<imm>}]",
"pattern" : "1 1 1 0 1 1 0 1 U#1 D#1 0 1 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_reg = TRUE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32); d = UInt(Vd:D); n = UInt(Rn);"""
} , {
"name" : "VLDR",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VLDR<c> <Sd>, [<Rn>{, #+/-<imm>}]",
"pattern" : "cond#4 1 1 0 1 U#1 D#1 0 1 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_reg = TRUE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32); d = UInt(Vd:D); n = UInt(Rn);"""
} , {
"name" : "VMAX, VMIN (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 1 0 N#1 Q#1 M#1 op#1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
maximum = (op == '0'); unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMAX, VMIN (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 1 0 N#1 Q#1 M#1 op#1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
maximum = (op == '0'); unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMAX, VMIN (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
maximum = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMAX, VMIN (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
maximum = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 op#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
add = (op == '0'); long_destination = FALSE;
unsigned_ = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 op#1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
add = (op == '0'); long_destination = FALSE;
unsigned_ = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (integer)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 0 op#1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
add = (op == '0'); long_destination = TRUE; unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (integer)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 1 0 op#1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
add = (op == '0'); long_destination = TRUE; unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VMLA, VMLS (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; add = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMLA, VMLS (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; add = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMLA, VMLS (floating-point)",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 D#1 0 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1'); add = (op == '0');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VMLA, VMLS (floating-point)",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 D#1 0 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1'); add = (op == '0');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (by scalar)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 Q#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 op#1 0 F#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || (F == '1' && size == '01') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = FALSE;
add = (op == '0'); floating_point = (F == '1'); long_destination = FALSE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (by scalar)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 Q#1 1 D#1 size#2 Vn#4 Vd#4 0 op#1 0 F#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || (F == '1' && size == '01') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = FALSE;
add = (op == '0'); floating_point = (F == '1'); long_destination = FALSE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (by scalar)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 op#1 1 0 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); add = (op == '0'); floating_point = FALSE; long_destination = TRUE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = 1;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMLA, VMLAL, VMLS, VMLSL (by scalar)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 0 op#1 1 0 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); add = (op == '0'); floating_point = FALSE; long_destination = TRUE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = 1;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMOV (immediate)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 i#1 1 1 1 1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 op#1 1 imm4#4",
"decoder" : """if op == '0' && cmode<0> == '1' && cmode<3:2> != '11' then SEE VORR (immediate);
if op == '1' && cmode != '1110' then SEE "Related encodings";
if Q == '1' && Vd<0> == '1' then UNDEFINED;
single_register = FALSE; advsimd = TRUE; imm64 = AdvSIMDExpandImm(op, cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMOV (immediate)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 i#1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 op#1 1 imm4#4",
"decoder" : """if op == '0' && cmode<0> == '1' && cmode<3:2> != '11' then SEE VORR (immediate);
if op == '1' && cmode != '1110' then SEE "Related encodings";
if Q == '1' && Vd<0> == '1' then UNDEFINED;
single_register = FALSE; advsimd = TRUE; imm64 = AdvSIMDExpandImm(op, cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMOV (immediate)",
"encoding" : "T2",
"version" : "VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 imm4H#4 Vd#4 1 0 1 sz#1 0 0 0 0 imm4L#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
single_register = (sz == '0'); advsimd = FALSE;
if single_register then
d = UInt(Vd:D);
imm32 = VFPExpandImm(imm4H:imm4L, 32);
else
d = UInt(D:Vd);
imm64 = VFPExpandImm(imm4H:imm4L, 64);
regs = 1;
endif"""
} , {
"name" : "VMOV (immediate)",
"encoding" : "A2",
"version" : "VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 imm4H#4 Vd#4 1 0 1 sz#1 0 0 0 0 imm4L#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
single_register = (sz == '0'); advsimd = FALSE;
if single_register then
d = UInt(Vd:D); imm32 = VFPExpandImm(imm4H:imm4L, 32);
else
d = UInt(D:Vd); imm64 = VFPExpandImm(imm4H:imm4L, 64); regs = 1;
endif"""
} , {
"name" : "VMOV (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 1 0 Vm_#4 Vd#4 0 0 0 1 M_#1 Q#1 M#1 1 Vm#4",
"decoder" : """if !Consistent(M) || !Consistent(Vm) then SEE VORR (register);
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
single_register = FALSE; advsimd = TRUE;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMOV (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 1 0 Vm_#4 Vd#4 0 0 0 1 M_#1 Q#1 M#1 1 Vm#4",
"decoder" : """if !Consistent(M) || !Consistent(Vm) then SEE VORR (register);
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
single_register = FALSE; advsimd = TRUE;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMOV (register)",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 0 0 0 Vd#4 1 0 1 sz#1 0 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
single_register = (sz == '0'); advsimd = FALSE;
if single_register then
d = UInt(Vd:D); m = UInt(Vm:M);
else
d = UInt(D:Vd); m = UInt(M:Vm); regs = 1;
endif"""
} , {
"name" : "VMOV (register)",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 0 0 0 Vd#4 1 0 1 sz#1 0 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
single_register = (sz == '0'); advsimd = FALSE;
if single_register then
d = UInt(Vd:D); m = UInt(Vm:M);
else
d = UInt(D:Vd); m = UInt(M:Vm); regs = 1;
endif"""
} , {
"name" : "VMOV (ARM core register to scalar)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VMOV.<size> <Dd[x]>, <Rt>",
"pattern" : "1 1 1 0 1 1 1 0 0 opc1#2 0 Vd#4 Rt#4 1 0 1 1 D#1 opc2#2 1 0 0 0 0",
"decoder" : """case opc1:opc2 of
when "1xxx" advsimd = TRUE; esize = 8; index = UInt(opc1<0>:opc2);
when "0xx1" advsimd = TRUE; esize = 16; index = UInt(opc1<0>:opc2<1>);
when "0x00" advsimd = FALSE; esize = 32; index = UInt(opc1<0>);
when "0x10" UNDEFINED;
endcase
d = UInt(D:Vd); t = UInt(Rt);
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VMOV (ARM core register to scalar)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VMOV<c>.<size> <Dd[x]>, <Rt>",
"pattern" : "cond#4 1 1 1 0 0 opc1#2 0 Vd#4 Rt#4 1 0 1 1 D#1 opc2#2 1 0 0 0 0",
"decoder" : """case opc1:opc2 of
when "1xxx" advsimd = TRUE; esize = 8; index = UInt(opc1<0>:opc2);
when "0xx1" advsimd = TRUE; esize = 16; index = UInt(opc1<0>:opc2<1>);
when "0x00" advsimd = FALSE; esize = 32; index = UInt(opc1<0>);
when "0x10" UNDEFINED;
endcase
d = UInt(D:Vd); t = UInt(Rt);
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VMOV (scalar to ARM core register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VMOV.<dt> <Rt>, <Dn[x]>",
"pattern" : "1 1 1 0 1 1 1 0 U#1 opc1#2 1 Vn#4 Rt#4 1 0 1 1 N#1 opc2#2 1 0 0 0 0",
"decoder" : """case U:opc1:opc2 of
when "x1xxx" advsimd = TRUE; esize = 8; index = UInt(opc1<0>:opc2);
when "x0xx1" advsimd = TRUE; esize = 16; index = UInt(opc1<0>:opc2<1>);
when "00x00" advsimd = FALSE; esize = 32; index = UInt(opc1<0>);
when "10x00" UNDEFINED;
when "x0x10" UNDEFINED;
endcase
t = UInt(Rt); n = UInt(N:Vn); unsigned_ = (U == '1');
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VMOV (scalar to ARM core register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VMOV<c>.<dt> <Rt>, <Dn[x]>",
"pattern" : "cond#4 1 1 1 0 U#1 opc1#2 1 Vn#4 Rt#4 1 0 1 1 N#1 opc2#2 1 0 0 0 0",
"decoder" : """case U:opc1:opc2 of
when "x1xxx" advsimd = TRUE; esize = 8; index = UInt(opc1<0>:opc2);
when "x0xx1" advsimd = TRUE; esize = 16; index = UInt(opc1<0>:opc2<1>);
when "00x00" advsimd = FALSE; esize = 32; index = UInt(opc1<0>);
when "10x00" UNDEFINED;
when "x0x10" UNDEFINED;
endcase
t = UInt(Rt); n = UInt(N:Vn); unsigned_ = (U == '1');
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VMOV (between ARM core register and single-precision register)",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 0 0 op#1 Vn#4 Rt#4 1 0 1 0 N#1 0 0 1 0 0 0 0",
"decoder" : """to_arm_register = (op == '1'); t = UInt(Rt); n = UInt(Vn:N);
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VMOV (between ARM core register and single-precision register)",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 0 0 op#1 Vn#4 Rt#4 1 0 1 0 N#1 0 0 1 0 0 0 0",
"decoder" : """to_arm_register = (op == '1'); t = UInt(Rt); n = UInt(Vn:N);
if t == 15 || (CurrentInstrSet() != InstrSet_ARM && t == 13) then UNPREDICTABLE;"""
} , {
"name" : "VMOV (between two ARM core registers and two single-precision registers)",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 0 0 0 1 0 op#1 Rt2#4 Rt#4 1 0 1 0 0 0 M#1 1 Vm#4",
"decoder" : """to_arm_registers = (op == '1'); t = UInt(Rt); t2 = UInt(Rt2); m = UInt(Vm:M);
if t == 15 || t2 == 15 || m == 31 then UNPREDICTABLE;
if CurrentInstrSet() != InstrSet_ARM && (t == 13 || t2 == 13) then UNPREDICTABLE;
if to_arm_registers && t == t2 then UNPREDICTABLE;"""
} , {
"name" : "VMOV (between two ARM core registers and two single-precision registers)",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 0 0 0 1 0 op#1 Rt2#4 Rt#4 1 0 1 0 0 0 M#1 1 Vm#4",
"decoder" : """to_arm_registers = (op == '1'); t = UInt(Rt); t2 = UInt(Rt2); m = UInt(Vm:M);
if t == 15 || t2 == 15 || m == 31 then UNPREDICTABLE;
if CurrentInstrSet() != InstrSet_ARM && (t == 13 || t2 == 13) then UNPREDICTABLE;
if to_arm_registers && t == t2 then UNPREDICTABLE;"""
} , {
"name" : "VMOV (between two ARM core registers and a doubleword extension register)",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 0 0 0 1 0 op#1 Rt2#4 Rt#4 1 0 1 1 0 0 M#1 1 Vm#4",
"decoder" : """to_arm_registers = (op == '1'); t = UInt(Rt); t2 = UInt(Rt2); m = UInt(M:Vm);
if t == 15 || t2 == 15 then UNPREDICTABLE;
if CurrentInstrSet() != InstrSet_ARM && (t == 13 || t2 == 13) then UNPREDICTABLE;
if to_arm_registers && t == t2 then UNPREDICTABLE;"""
} , {
"name" : "VMOV (between two ARM core registers and a doubleword extension register)",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 0 0 0 1 0 op#1 Rt2#4 Rt#4 1 0 1 1 0 0 M#1 1 Vm#4",
"decoder" : """to_arm_registers = (op == '1'); t = UInt(Rt); t2 = UInt(Rt2); m = UInt(M:Vm);
if t == 15 || t2 == 15 then UNPREDICTABLE;
if CurrentInstrSet() != InstrSet_ARM && (t == 13 || t2 == 13) then UNPREDICTABLE;
if to_arm_registers && t == t2 then UNPREDICTABLE;"""
} , {
"name" : "VMOVL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VMOVL.<dt> <Qd>, <Dm>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm3#3 0 0 0 Vd#4 1 0 1 0 0 0 M#1 1 Vm#4",
"decoder" : """if imm3 == '000' then SEE "Related encodings";
if imm3 != '001' && imm3 != '010' && imm3 != '100' then SEE VSHLL;
if Vd<0> == '1' then UNDEFINED;
esize = 8 * UInt(imm3);
unsigned_ = (U == '1'); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VMOVL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VMOVL.<dt> <Qd>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm3#3 0 0 0 Vd#4 1 0 1 0 0 0 M#1 1 Vm#4",
"decoder" : """if imm3 == '000' then SEE "Related encodings";
if imm3 != '001' && imm3 != '010' && imm3 != '100' then SEE VSHLL;
if Vd<0> == '1' then UNDEFINED;
esize = 8 * UInt(imm3);
unsigned_ = (U == '1'); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VMOVN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VMOVN.<dt> <Dd>, <Qm>",
"pattern" : "111111111 D#1 11 size#2 10 Vd#4 001000 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VMOVN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VMOVN.<dt> <Dd>, <Qm>",
"pattern" : "111100111 D#1 11 size#2 10 Vd#4 001000 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VMRS",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VMRS <Rt>, <spec_reg>",
"pattern" : "111011101111 reg#4 Rt#4 101000010000",
"decoder" : """t = UInt(Rt); if t == 13 && CurrentInstrSet() != InstrSet_ARM then UNPREDICTABLE;
if t == 15 && reg != '0001' then UNPREDICTABLE;"""
} , {
"name" : "VMRS",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VMRS<c> <Rt>, <spec_reg>",
"pattern" : "cond#4 11101111 reg#4 Rt#4 101000010000",
"decoder" : """t = UInt(Rt); if t == 13 && CurrentInstrSet() != InstrSet_ARM then UNPREDICTABLE;
if t == 15 && reg != '0001' then UNPREDICTABLE;"""
} , {
"name" : "VMSR",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VMSR <spec_reg>, <Rt>",
"pattern" : "111011101110 reg#4 Rt#4 101000010000",
"decoder" : """t = UInt(Rt); if t == 15 || (t == 13 && CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "VMSR",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VMSR<c> <spec_reg>, <Rt>",
"pattern" : "cond#4 11101110 reg#4 Rt#4 101000010000",
"decoder" : """t = UInt(Rt); if t == 15 || (t == 13 && CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;"""
} , {
"name" : "VMUL, VMULL (integer and polynomial)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 op#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if size == '11' || (op == '1' && size != '00') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
polynomial = (op == '1'); long_destination = FALSE;
unsigned_ = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMUL, VMULL (integer and polynomial)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 op#1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if size == '11' || (op == '1' && size != '00') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
polynomial = (op == '1'); long_destination = FALSE;
unsigned_ = FALSE;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMUL, VMULL (integer and polynomial)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "VMULL.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 1 op#1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if op == '1' && (U != '0' || size != '00') then UNDEFINED;
if Vd<0> == '1' then UNDEFINED;
polynomial = (op == '1'); long_destination = TRUE; unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VMUL, VMULL (integer and polynomial)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "VMULL.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 1 1 op#1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if op == '1' && (U != '0' || size != '00') then UNDEFINED;
if Vd<0> == '1' then UNDEFINED;
polynomial = (op == '1'); long_destination = TRUE; unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = 1;"""
} , {
"name" : "VMUL (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMUL (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMUL (floating-point)",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 D#1 1 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VMUL (floating-point)",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 D#1 1 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VMUL, VMULL (by scalar)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 Q#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 0 0 F#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || (F == '1' && size == '01') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = FALSE;
floating_point = (F == '1'); long_destination = FALSE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMUL, VMULL (by scalar)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 Q#1 1 D#1 size#2 Vn#4 Vd#4 1 0 0 F#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || (F == '1' && size == '01') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = FALSE;
floating_point = (F == '1'); long_destination = FALSE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMUL, VMULL (by scalar)",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "VMULL.<dt> <Qd>, <Dn>, <Dm[x]>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 0 1 0 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); long_destination = TRUE; floating_point = FALSE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = 1;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMUL, VMULL (by scalar)",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "VMULL.<dt> <Qd>, <Dn>, <Dm[x]>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 1 0 1 0 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
unsigned_ = (U == '1'); long_destination = TRUE; floating_point = FALSE;
d = UInt(D:Vd); n = UInt(N:Vn); regs = 1;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VMVN (immediate)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 i#1 1 1 1 1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 1 1 imm4#4",
"decoder" : """if (cmode<0> == '1' && cmode<3:2> != '11') || cmode<3:1> == '111' then SEE "Related encodings";
if Q == '1' && Vd<0> == '1' then UNDEFINED;
imm64 = AdvSIMDExpandImm('1', cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMVN (immediate)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 i#1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 1 1 imm4#4",
"decoder" : """if (cmode<0> == '1' && cmode<3:2> != '11') || cmode<3:1> == '111' then SEE "Related encodings";
if Q == '1' && Vd<0> == '1' then UNDEFINED;
imm64 = AdvSIMDExpandImm('1', cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMVN (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size != '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VMVN (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 0 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size != '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VNEG",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 1 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
advsimd = TRUE; floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VNEG",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 1 Vd#4 0 F#1 1 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (F == '1' && size != '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
advsimd = TRUE; floating_point = (F == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VNEG",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 0 0 1 Vd#4 1 0 1 sz#1 0 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VNEG",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 0 0 1 Vd#4 1 0 1 sz#1 0 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VNMLA, VNMLS, VNMUL",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 D#1 0 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
type = if op == '1' then VFPNegMul_VNMLA else VFPNegMul_VNMLS; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VNMLA, VNMLS, VNMUL",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 D#1 0 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 op#1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
type = if op == '1' then VFPNegMul_VNMLA else VFPNegMul_VNMLS; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VNMLA, VNMLS, VNMUL",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 D#1 1 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
type = VFPNegMul_VNMUL;
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VNMLA, VNMLS, VNMUL",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 D#1 1 0 Vn#4 Vd#4 1 0 1 sz#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
type = VFPNegMul_VNMUL;
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VORN (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 1 1 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VORN (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 1 1 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VORR (immediate)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 i#1 1 1 1 1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 0 1 imm4#4",
"decoder" : """if cmode<0> == '0' || cmode<3:2> == '11' then SEE VMOV (immediate);
if Q == '1' && Vd<0> == '1' then UNDEFINED;
imm64 = AdvSIMDExpandImm('0', cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VORR (immediate)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 i#1 1 D#1 0 0 0 imm3#3 Vd#4 cmode#4 0 Q#1 0 1 imm4#4",
"decoder" : """if cmode<0> == '0' || cmode<3:2> == '11' then SEE VMOV (immediate);
if Q == '1' && Vd<0> == '1' then UNDEFINED;
imm64 = AdvSIMDExpandImm('0', cmode, i:imm3:imm4);
d = UInt(D:Vd); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VORR (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 1 0 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if N == M && Vn == Vm then SEE VMOV (register);
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VORR (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 1 0 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if N == M && Vn == Vm then SEE VMOV (register);
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VPADAL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 1 0 op#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (op == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VPADAL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 1 0 op#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (op == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VPADD (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VPADD.<dt> <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if size == '11' || Q == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPADD (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VPADD.<dt> <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if size == '11' || Q == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPADD (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VPADD.F32 <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if sz == '1' || Q == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPADD (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VPADD.F32 <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if sz == '1' || Q == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPADDL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 0 1 0 op#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (op == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VPADDL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 0 1 0 op#1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (op == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VPMAX, VPMIN (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VP<op>.<dt> <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 1 0 N#1 Q#1 M#1 op#1 Vm#4",
"decoder" : """if size == '11' || Q == '1' then UNDEFINED;
maximum = (op == '0'); unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPMAX, VPMIN (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VP<op>.<dt> <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 1 0 1 0 N#1 Q#1 M#1 op#1 Vm#4",
"decoder" : """if size == '11' || Q == '1' then UNDEFINED;
maximum = (op == '0'); unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPMAX, VPMIN (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VP<op>.F32 <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if sz == '1' || Q == '1' then UNDEFINED;
maximum = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPMAX, VPMIN (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VP<op>.F32 <Dd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 op#1 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if sz == '1' || Q == '1' then UNDEFINED;
maximum = (op == '0'); esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VPOP",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VPOP <list>",
"pattern" : "1 1 1 0 1 1 0 0 1 D#1 1 1 1 1 0 1 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_regs = FALSE; d = UInt(D:Vd); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPOP",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VPOP<c> <list>",
"pattern" : "cond#4 1 1 0 0 1 D#1 1 1 1 1 0 1 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_regs = FALSE; d = UInt(D:Vd); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPOP",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VPOP <list>",
"pattern" : "1 1 1 0 1 1 0 0 1 D#1 1 1 1 1 0 1 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_regs = TRUE; d = UInt(Vd:D);
imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8);
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPOP",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VPOP<c> <list>",
"pattern" : "cond#4 1 1 0 0 1 D#1 1 1 1 1 0 1 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_regs = TRUE; d = UInt(Vd:D);
imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8);
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPUSH",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VPUSH <list>",
"pattern" : "1 1 1 0 1 1 0 1 0 D#1 1 0 1 1 0 1 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_regs = FALSE; d = UInt(D:Vd); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPUSH",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VPUSH<c> <list>",
"pattern" : "cond#4 1 1 0 1 0 D#1 1 0 1 1 0 1 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_regs = FALSE; d = UInt(D:Vd); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPUSH",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VPUSH <list>",
"pattern" : "1 1 1 0 1 1 0 1 0 D#1 1 0 1 1 0 1 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_regs = TRUE; d = UInt(Vd:D);
imm32 = ZeroExtend(imm8:'00', 32); regs = UInt(imm8);
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VPUSH",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VPUSH<c> <list>",
"pattern" : "cond#4 1 1 0 1 0 D#1 1 0 1 1 0 1 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_regs = TRUE; d = UInt(Vd:D);
imm32 = ZeroExtend(imm8:'00', 32); regs = UInt(imm8);
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VQABS",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 1 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQABS",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 1 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQADD",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 0 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQADD",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 0 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQDMLAL, VQDMLSL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VQD<op>.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 0 op#1 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
add = (op == '0');
scalar_form = FALSE; d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
esize = 8 << UInt(size); elements = 64 DIV esize;"""
} , {
"name" : "VQDMLAL, VQDMLSL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VQD<op>.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 size#2 Vn#4 Vd#4 1 0 op#1 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
add = (op == '0');
scalar_form = FALSE; d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
esize = 8 << UInt(size); elements = 64 DIV esize;"""
} , {
"name" : "VQDMLAL, VQDMLSL",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "VQD<op>.<dt> <Qd>, <Dn>, <Dm[x]>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 op#1 1 1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
add = (op == '0');
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn);
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQDMLAL, VQDMLSL",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "VQD<op>.<dt> <Qd>, <Dn>, <Dm[x]>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 size#2 Vn#4 Vd#4 0 op#1 1 1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
add = (op == '0');
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn);
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQDMULH",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '00' || size == '11' then UNDEFINED;
scalar_form = FALSE; esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQDMULH",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '00' || size == '11' then UNDEFINED;
scalar_form = FALSE; esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQDMULH",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 Q#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 1 0 0 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQDMULH",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 Q#1 1 D#1 size#2 Vn#4 Vd#4 1 1 0 0 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQDMULL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VQDMULL.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 1 0 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
scalar_form = FALSE; d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
esize = 8 << UInt(size); elements = 64 DIV esize;"""
} , {
"name" : "VQDMULL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VQDMULL.<dt> <Qd>, <Dn>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 size#2 Vn#4 Vd#4 1 1 0 1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
scalar_form = FALSE; d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
esize = 8 << UInt(size); elements = 64 DIV esize;"""
} , {
"name" : "VQDMULL",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "VQDMULL.<dt> <Qd>, <Dn>, <Dm[x]>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn);
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQDMULL",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "VQDMULL.<dt> <Qd>, <Dn>, <Dm[x]>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' || Vd<0> == '1' then UNDEFINED;
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn);
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQMOVN, VQMOVUN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VQMOV{U}N.<type><size> <Dd>, <Qm>",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 1 0 op#2 M#1 0 Vm#4",
"decoder" : """if op == '00' then SEE VMOVN;
if size == '11' || Vm<0> == '1' then UNDEFINED;
src_unsigned = (op == '11'); dest_unsigned = (op<0> == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VQMOVN, VQMOVUN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VQMOV{U}N.<type><size> <Dd>, <Qm>",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 1 0 op#2 M#1 0 Vm#4",
"decoder" : """if op == '00' then SEE VMOVN;
if size == '11' || Vm<0> == '1' then UNDEFINED;
src_unsigned = (op == '11'); dest_unsigned = (op<0> == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VQNEG",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 1 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQNEG",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 1 1 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQRDMULH",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '00' || size == '11' then UNDEFINED;
scalar_form = FALSE; esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQRDMULH",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 1 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '00' || size == '11' then UNDEFINED;
scalar_form = FALSE; esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQRDMULH",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 Q#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 1 1 0 1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQRDMULH",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 Q#1 1 D#1 size#2 Vn#4 Vd#4 1 1 0 1 N#1 1 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if size == '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vn<0> == '1') then UNDEFINED;
scalar_form = TRUE; d = UInt(D:Vd); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;
if size == '01' then esize = 16; elements = 4; m = UInt(Vm<2:0>); index = UInt(M:Vm<3>);
if size == '10' then esize = 32; elements = 2; m = UInt(Vm); index = UInt(M);"""
} , {
"name" : "VQRSHL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQRSHL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQRSHRN, VQRSHRUN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VQRSHR{U}N.<type><size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 1 0 0 op#1 0 1 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if U == '0' && op == '0' then SEE VRSHRN;
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
imm32 = imm6;
src_unsigned = (U == '1' && op == '1'); dest_unsigned = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VQRSHRN, VQRSHRUN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VQRSHR{U}N.<type><size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 1 0 0 op#1 0 1 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if U == '0' && op == '0' then SEE VRSHRN;
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
imm32 = imm6;
src_unsigned = (U == '1' && op == '1'); dest_unsigned = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VQSHL (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQSHL (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQSHL, VQSHLU (immediate)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 1 1 op#1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if U == '0' && op == '0' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "001xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "01xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
when "1xxxxxx" esize = 64; elements = 1; shift_amount = UInt(imm6);
endcase
src_unsigned = (U == '1' && op == '1'); dest_unsigned = (U == '1');
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQSHL, VQSHLU (immediate)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 0 1 1 op#1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if U == '0' && op == '0' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "001xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "01xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
when "1xxxxxx" esize = 64; elements = 1; shift_amount = UInt(imm6);
endcase
src_unsigned = (U == '1' && op == '1'); dest_unsigned = (U == '1');
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQSHRN, VQSHRUN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VQSHR{U}N.<type><size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 1 0 0 op#1 0 0 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if U == '0' && op == '0' then SEE VSHRN;
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
src_unsigned = (U == '1' && op == '1'); dest_unsigned = (U == '1');
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VQSHRN, VQSHRUN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VQSHR{U}N.<type><size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 1 0 0 op#1 0 0 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if U == '0' && op == '0' then SEE VSHRN;
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
src_unsigned = (U == '1' && op == '1'); dest_unsigned = (U == '1');
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VQSUB",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 0 1 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VQSUB",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 0 1 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRADDHN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VRADDHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VRADDHN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VRADDHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VRECPE",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 1 Vd#4 0 1 0 F#1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size != '10' then UNDEFINED;
floating_point = (F == '1'); esize = 32; elements = 2;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRECPE",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 1 Vd#4 0 1 0 F#1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size != '10' then UNDEFINED;
floating_point = (F == '1'); esize = 32; elements = 2;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRECPS",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRECPS",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 0 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VREV16, VREV32, VREV64",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 0 0 op#2 Q#1 M#1 0 Vm#4",
"decoder" : """if UInt(op)+UInt(size) >= 3 then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
groupsize = (1 << (3-UInt(op)-UInt(size)));
groupsize_minus_one = groupsize-1;
esize_minus_one = esize-1;
reverse_mask = groupsize_minus_one<esize_minus_one:0>;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VREV16, VREV32, VREV64",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 0 0 Vd#4 0 0 0 op#2 Q#1 M#1 0 Vm#4",
"decoder" : """if UInt(op)+UInt(size) >= 3 then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
groupsize = (1 << (3-UInt(op)-UInt(size)));
groupsize_minus_one = groupsize-1;
esize_minus_one = esize-1;
reverse_mask = groupsize_minus_one<esize_minus_one:0>;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRHADD",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRHADD",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 0 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSHL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSHL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSHR",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 0 1 0 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSHR",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 0 0 1 0 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSHRN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VRSHRN.I<size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 imm6#6 Vd#4 1 0 0 0 0 1 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VRSHRN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VRSHRN.I<size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 imm6#6 Vd#4 1 0 0 0 0 1 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VRSQRTE",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 1 Vd#4 0 1 0 F#1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size != '10' then UNDEFINED;
floating_point = (F == '1'); esize = 32; elements = 2;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSQRTE",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 1 Vd#4 0 1 0 F#1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size != '10' then UNDEFINED;
floating_point = (F == '1'); esize = 32; elements = 2;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSQRTS",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSQRTS",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 1 1 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSRA",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 0 1 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSRA",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 0 0 1 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VRSUBHN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VRSUBHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VRSUBHN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VRSUBHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VSHL (immediate)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 imm6#6 Vd#4 0 1 0 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if L:imm6 IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "001xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "01xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
when "1xxxxxx" esize = 64; elements = 1; shift_amount = UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSHL (immediate)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 imm6#6 Vd#4 0 1 0 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if L:imm6 IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "001xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "01xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
when "1xxxxxx" esize = 64; elements = 1; shift_amount = UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSHL (register)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSHL (register)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 0 D#1 size#2 Vn#4 Vd#4 0 1 0 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vm<0> == '1' || Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); n = UInt(N:Vn); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSHLL",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VSHLL.<type><size> <Qd>, <Dm>, #<shift_amount>",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 1 0 1 0 0 0 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "01xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "1xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
endcase
if shift_amount == 0 then SEE VMOVL;
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VSHLL",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VSHLL.<type><size> <Qd>, <Dm>, #<shift_amount>",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 1 0 1 0 0 0 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if Vd<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "01xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "1xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
endcase
if shift_amount == 0 then SEE VMOVL;
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VSHLL",
"encoding" : "T2",
"version" : "AdvancedSIMD",
"format" : "VSHLL.<type><size> <Qd>, <Dm>, #<shift_amount>",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 1 1 0 0 M#1 0 Vm#4",
"decoder" : """if size == '11' || Vd<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); shift_amount = esize;
unsigned_ = FALSE;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VSHLL",
"encoding" : "A2",
"version" : "AdvancedSIMD",
"format" : "VSHLL.<type><size> <Qd>, <Dm>, #<shift_amount>",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 1 1 0 0 M#1 0 Vm#4",
"decoder" : """if size == '11' || Vd<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); shift_amount = esize;
unsigned_ = FALSE;
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VSHR",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 0 0 0 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSHR",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 0 0 0 0 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSHRN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VSHRN.I<size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 imm6#6 Vd#4 1 0 0 0 0 0 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VSHRN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VSHRN.I<size> <Dd>, <Qm>, #<shift_amount>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 imm6#6 Vd#4 1 0 0 0 0 0 M#1 1 Vm#4",
"decoder" : """if imm6 IN "000xxx" then SEE "Related encodings";
if Vm<0> == '1' then UNDEFINED;
case imm6 of
when "001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "01xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "1xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VSLI",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 1 0 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "001xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "01xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
when "1xxxxxx" esize = 64; elements = 1; shift_amount = UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSLI",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 imm6#6 Vd#4 0 1 0 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = UInt(imm6) - 8;
when "001xxxx" esize = 16; elements = 4; shift_amount = UInt(imm6) - 16;
when "01xxxxx" esize = 32; elements = 2; shift_amount = UInt(imm6) - 32;
when "1xxxxxx" esize = 64; elements = 1; shift_amount = UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSQRT",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 1 D#1 1 1 0 0 0 1 Vd#4 1 0 1 sz#1 1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VSQRT",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 1 D#1 1 1 0 0 0 1 Vd#4 1 0 1 sz#1 1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VSRA",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 0 0 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSRA",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 imm6#6 Vd#4 0 0 0 1 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
unsigned_ = (U == '1'); d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSRI",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 imm6#6 Vd#4 0 1 0 0 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSRI",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 imm6#6 Vd#4 0 1 0 0 L#1 Q#1 M#1 1 Vm#4",
"decoder" : """if (L:imm6) IN "0000xxx" then SEE "Related encodings";
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
case L:imm6 of
when "0001xxx" esize = 8; elements = 8; shift_amount = 16 - UInt(imm6);
when "001xxxx" esize = 16; elements = 4; shift_amount = 32 - UInt(imm6);
when "01xxxxx" esize = 32; elements = 2; shift_amount = 64 - UInt(imm6);
when "1xxxxxx" esize = 64; elements = 1; shift_amount = 64 - UInt(imm6);
endcase
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VST1 (multiple single elements)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """case type of
when '0111'
regs = 1;
if align<1> == '1' then UNDEFINED;
when '1010'
regs = 2;
if align == '11' then UNDEFINED;
when '0110'
regs = 3;
if align<1> == '1' then UNDEFINED;
when '0010'
regs = 4;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VST1 (multiple single elements)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """case type of
when '0111'
regs = 1;
if align<1> == '1' then UNDEFINED;
when '1010'
regs = 2;
if align == '11' then UNDEFINED;
when '0110'
regs = 3;
if align<1> == '1' then UNDEFINED;
when '0010'
regs = 4;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VST1 (single element from one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 0 0 Rn#4 Vd#4 size#2 0 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); alignment = 1;
when '01'
if index_align<1> != '0' then UNDEFINED;
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
alignment = if index_align<0> == '0' then 1 else 2;
when '10'
if index_align<2> != '0' then UNDEFINED;
if index_align<1:0> != '00' && index_align<1:0> != '11' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
alignment = if index_align<1:0> == '00' then 1 else 4;
endcase
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "VST1 (single element from one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 0 0 Rn#4 Vd#4 size#2 0 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); alignment = 1;
when '01'
if index_align<1> != '0' then UNDEFINED;
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
alignment = if index_align<0> == '0' then 1 else 2;
when '10'
if index_align<2> != '0' then UNDEFINED;
if index_align<1:0> != '00' && index_align<1:0> != '11' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
alignment = if index_align<1:0> == '00' then 1 else 4;
endcase
d = UInt(D:Vd); n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 then UNPREDICTABLE;"""
} , {
"name" : "VST2 (multiple 2-element structures)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '1000'
regs = 1; inc = 1;
if align == '11' then UNDEFINED;
when '1001'
regs = 1; inc = 2;
if align == '11' then UNDEFINED;
when '0011'
regs = 2; inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VST2 (multiple 2-element structures)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '1000'
regs = 1; inc = 1;
if align == '11' then UNDEFINED;
when '1001'
regs = 1; inc = 2;
if align == '11' then UNDEFINED;
when '0011'
regs = 2; inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2+regs > 32 then UNPREDICTABLE;"""
} , {
"name" : "VST2 (single 2-element structure from one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 0 0 Rn#4 Vd#4 size#2 0 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 2;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 4;
when '10'
if index_align<1> != '0' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
endcase
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST2 (single 2-element structure from one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 0 0 Rn#4 Vd#4 size#2 0 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 2;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 4;
when '10'
if index_align<1> != '0' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
endcase
d = UInt(D:Vd); d2 = d + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d2 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST3 (multiple 3-element structures)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' || align<1> == '1' then UNDEFINED;
case type of
when '0100'
inc = 1;
when '0101'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align<0> == '0' then 1 else 8;
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST3 (multiple 3-element structures)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' || align<1> == '1' then UNDEFINED;
case type of
when '0100'
inc = 1;
when '0101'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align<0> == '0' then 1 else 8;
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST3 (single 3-element structure from one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 0 0 Rn#4 Vd#4 size#2 1 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
when '01'
if index_align<0> != '0' then UNDEFINED;
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
when '10'
if index_align<1:0> != '00' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST3 (single 3-element structure from one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 0 0 Rn#4 Vd#4 size#2 1 0 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
if index_align<0> != '0' then UNDEFINED;
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
when '01'
if index_align<0> != '0' then UNDEFINED;
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
when '10'
if index_align<1:0> != '00' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d3 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST4 (multiple 4-element structures)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '0000'
inc = 1;
when '0001'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST4 (multiple 4-element structures)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 0 D#1 0 0 Rn#4 Vd#4 type#4 size#2 align#2 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case type of
when '0000'
inc = 1;
when '0001'
inc = 2;
otherwise
SEE "Related encodings";
endcase
alignment = if align == '00' then 1 else 4 << UInt(align);
ebytes = 1 << UInt(size); esize = 8 * ebytes; elements = 8 DIV ebytes;
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST4 (single 4-element structure from one lane)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 0 0 1 1 D#1 0 0 Rn#4 Vd#4 size#2 1 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 4;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
when '10'
if index_align<1:0> == '11' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<1:0> == '00' then 1 else 4 << UInt(index_align<1:0>);
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VST4 (single 4-element structure from one lane)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 1 0 0 1 D#1 0 0 Rn#4 Vd#4 size#2 1 1 index_align#4 Rm#4",
"decoder" : """if size == '11' then UNDEFINED;
case size of
when '00'
ebytes = 1; esize = 8; index = UInt(index_align<3:1>); inc = 1;
alignment = if index_align<0> == '0' then 1 else 4;
when '01'
ebytes = 2; esize = 16; index = UInt(index_align<3:2>);
inc = if index_align<1> == '0' then 1 else 2;
alignment = if index_align<0> == '0' then 1 else 8;
when '10'
if index_align<1:0> == '11' then UNDEFINED;
ebytes = 4; esize = 32; index = UInt(index_align<3>);
inc = if index_align<2> == '0' then 1 else 2;
alignment = if index_align<1:0> == '00' then 1 else 4 << UInt(index_align<1:0>);
endcase
d = UInt(D:Vd); d2 = d + inc; d3 = d2 + inc; d4 = d3 + inc; n = UInt(Rn); m = UInt(Rm);
wback = (m != 15); register_index = (m != 15 && m != 13);
if n == 15 || d4 > 31 then UNPREDICTABLE;"""
} , {
"name" : "VSTM",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VSTM{mode} <Rn>{!}, <list>",
"pattern" : "1 1 1 0 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '1' && U == '0' && W == '1' && Rn == '1101' then SEE VPUSH;
if P == '1' && W == '0' then SEE VSTR;
if P == U && W == '1' then UNDEFINED;
single_regs = FALSE; add = (U == '1'); wback = (W == '1');
d = UInt(D:Vd); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VSTM",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VSTM{mode}<c> <Rn>{!}, <list>",
"pattern" : "cond#4 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '1' && U == '0' && W == '1' && Rn == '1101' then SEE VPUSH;
if P == '1' && W == '0' then SEE VSTR;
if P == U && W == '1' then UNDEFINED;
single_regs = FALSE; add = (U == '1'); wback = (W == '1');
d = UInt(D:Vd); n = UInt(Rn); imm32 = ZeroExtend(imm8:'00', 32);
regs = UInt(imm8) DIV 2;
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || regs > 16 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VSTM",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VSTM{mode} <Rn>{!}, <list>",
"pattern" : "1 1 1 0 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '1' && U == '0' && W == '1' && Rn == '1101' then SEE VPUSH;
if P == '1' && W == '0' then SEE VSTR;
if P == U && W == '1' then UNDEFINED;
single_regs = TRUE; add = (U == '1'); wback = (W == '1'); d = UInt(Vd:D); n = UInt(Rn);
imm32 = ZeroExtend(imm8:'00', 32); regs = UInt(imm8);
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VSTM",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VSTM{mode}<c> <Rn>{!}, <list>",
"pattern" : "cond#4 1 1 0 P#1 U#1 D#1 W#1 0 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """if P == '0' && U == '0' && W == '0' then SEE "Related encodings";
if P == '1' && U == '0' && W == '1' && Rn == '1101' then SEE VPUSH;
if P == '1' && W == '0' then SEE VSTR;
if P == U && W == '1' then UNDEFINED;
single_regs = TRUE; add = (U == '1'); wback = (W == '1'); d = UInt(Vd:D); n = UInt(Rn);
imm32 = ZeroExtend(imm8:'00', 32); regs = UInt(imm8);
if n == 15 && (wback || CurrentInstrSet() != InstrSet_ARM) then UNPREDICTABLE;
if regs == 0 || (d+regs) > 32 then UNPREDICTABLE;"""
} , {
"name" : "VSTR",
"encoding" : "T1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VSTR <Dd>, [<Rn>{, #+/-<imm32>}]",
"pattern" : "1 1 1 0 1 1 0 1 U#1 D#1 0 0 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_reg = FALSE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32);
d = UInt(D:Vd); n = UInt(Rn);
if n == 15 && CurrentInstrSet() != InstrSet_ARM then UNPREDICTABLE;"""
} , {
"name" : "VSTR",
"encoding" : "A1",
"version" : "VFPv2, VFPv3, VFPv4, AdvancedSIMD",
"format" : "VSTR<c> <Dd>, [<Rn>{, #+/-<imm32>}]",
"pattern" : "cond#4 1 1 0 1 U#1 D#1 0 0 Rn#4 Vd#4 1 0 1 1 imm8#8",
"decoder" : """single_reg = FALSE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32);
d = UInt(D:Vd); n = UInt(Rn);
if n == 15 && CurrentInstrSet() != InstrSet_ARM then UNPREDICTABLE;"""
} , {
"name" : "VSTR",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VSTR <Sd>, [<Rn>{, #+/-<imm32>}]",
"pattern" : "1 1 1 0 1 1 0 1 U#1 D#1 0 0 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_reg = TRUE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32);
d = UInt(Vd:D); n = UInt(Rn);
if n == 15 && CurrentInstrSet() != InstrSet_ARM then UNPREDICTABLE;"""
} , {
"name" : "VSTR",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "VSTR<c> <Sd>, [<Rn>{, #+/-<imm32>}]",
"pattern" : "cond#4 1 1 0 1 U#1 D#1 0 0 Rn#4 Vd#4 1 0 1 0 imm8#8",
"decoder" : """single_reg = TRUE; add = (U == '1'); imm32 = ZeroExtend(imm8:'00', 32);
d = UInt(Vd:D); n = UInt(Rn);
if n == 15 && CurrentInstrSet() != InstrSet_ARM then UNPREDICTABLE;"""
} , {
"name" : "VSUB (integer)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSUB (integer)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSUB (floating-point)",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSUB (floating-point)",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 0 0 D#1 1 sz#1 Vn#4 Vd#4 1 1 0 1 N#1 Q#1 M#1 0 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if sz == '1' then UNDEFINED;
advsimd = TRUE; esize = 32; elements = 2;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSUB (floating-point)",
"encoding" : "T2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 0 0 D#1 1 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VSUB (floating-point)",
"encoding" : "A2",
"version" : "VFPv2, VFPv3, VFPv4",
"format" : "CUSTOM",
"pattern" : "cond#4 1 1 1 0 0 D#1 1 1 Vn#4 Vd#4 1 0 1 sz#1 N#1 1 M#1 0 Vm#4",
"decoder" : """if FPSCR.LEN != '000' || FPSCR.STRIDE != '00' then SEE "VFP vectors";
advsimd = FALSE; dp_operation = (sz == '1');
d = if dp_operation then UInt(D:Vd) else UInt(Vd:D);
n = if dp_operation then UInt(N:Vn) else UInt(Vn:N);
m = if dp_operation then UInt(M:Vm) else UInt(Vm:M);"""
} , {
"name" : "VSUBHN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "VSUBHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 0 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 1 1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VSUBHN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "VSUBHN.<dt> <Dd>, <Qn>, <Qm>",
"pattern" : "1 1 1 1 0 0 1 0 1 D#1 size#2 Vn#4 Vd#4 0 1 1 0 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vn<0> == '1' || Vm<0> == '1' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VSUBL, VSUBW",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 U#1 1 1 1 1 1 D#1 size#2 Vn#4 Vd#4 0 0 1 op#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' || (op == '1' && Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize; is_vsubw = (op == '1');
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VSUBL, VSUBW",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 U#1 1 D#1 size#2 Vn#4 Vd#4 0 0 1 op#1 N#1 0 M#1 0 Vm#4",
"decoder" : """if size == '11' then SEE "Related encodings";
if Vd<0> == '1' || (op == '1' && Vn<0> == '1') then UNDEFINED;
unsigned_ = (U == '1');
esize = 8 << UInt(size); elements = 64 DIV esize; is_vsubw = (op == '1');
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);"""
} , {
"name" : "VSWP",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size != '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VSWP",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 0 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size != '00' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VTBL, VTBX",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "V<op>.8 <Dd>, <list>, <Dm>",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 Vn#4 Vd#4 1 0 len#2 N#1 op#1 M#1 0 Vm#4",
"decoder" : """is_vtbl = (op == '0'); length = UInt(len)+1;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
if n+length > 32 then UNPREDICTABLE;"""
} , {
"name" : "VTBL, VTBX",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "V<op>.8 <Dd>, <list>, <Dm>",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 Vn#4 Vd#4 1 0 len#2 N#1 op#1 M#1 0 Vm#4",
"decoder" : """is_vtbl = (op == '0'); length = UInt(len)+1;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm);
if n+length > 32 then UNPREDICTABLE;"""
} , {
"name" : "VTRN",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 0 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VTRN",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 0 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VTST",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 1 1 1 1 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VTST",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 0 0 0 1 0 0 D#1 size#2 Vn#4 Vd#4 1 0 0 0 N#1 Q#1 M#1 1 Vm#4",
"decoder" : """if Q == '1' && (Vd<0> == '1' || Vn<0> == '1' || Vm<0> == '1') then UNDEFINED;
if size == '11' then UNDEFINED;
esize = 8 << UInt(size); elements = 64 DIV esize;
d = UInt(D:Vd); n = UInt(N:Vn); m = UInt(M:Vm); regs = if Q == '0' then 1 else 2;"""
} , {
"name" : "VUZP",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (Q == '0' && size == '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
quadword_operation = (Q == '1'); esize = 8 << UInt(size);
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VUZP",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 1 0 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (Q == '0' && size == '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
quadword_operation = (Q == '1'); esize = 8 << UInt(size);
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VZIP",
"encoding" : "T1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 1 1 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (Q == '0' && size == '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
quadword_operation = (Q == '1'); esize = 8 << UInt(size);
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , {
"name" : "VZIP",
"encoding" : "A1",
"version" : "AdvancedSIMD",
"format" : "CUSTOM",
"pattern" : "1 1 1 1 0 0 1 1 1 D#1 1 1 size#2 1 0 Vd#4 0 0 0 1 1 Q#1 M#1 0 Vm#4",
"decoder" : """if size == '11' || (Q == '0' && size == '10') then UNDEFINED;
if Q == '1' && (Vd<0> == '1' || Vm<0> == '1') then UNDEFINED;
quadword_operation = (Q == '1'); esize = 8 << UInt(size);
d = UInt(D:Vd); m = UInt(M:Vm);"""
} , ]
| 45.205005
| 167
| 0.510653
| 68,693
| 431,753
| 3.190412
| 0.014747
| 0.031429
| 0.026392
| 0.018306
| 0.972048
| 0.958432
| 0.919273
| 0.894378
| 0.856447
| 0.824643
| 0
| 0.112875
| 0.26089
| 431,753
| 9,550
| 168
| 45.209738
| 0.5739
| 0
| 0
| 0.839372
| 0
| 0.188901
| 0.806292
| 0.012593
| 0
| 0
| 0.000037
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 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
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 8
|
c553091037a20e5927986060da1c198a4c541c5c
| 43,081
|
py
|
Python
|
py-scripts/sandbox/html_template.py
|
alexman69420/lanforge-scripts
|
81e5683c6a6b0eae9336c0bc1b52124e44e7b2be
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 11
|
2017-10-09T13:15:53.000Z
|
2022-02-10T15:43:20.000Z
|
py-scripts/sandbox/html_template.py
|
MynaITLabs/lanforge-scripts
|
c905e2a12662f0e3304f0ac29b509c95f09983ce
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 5
|
2017-10-16T14:27:46.000Z
|
2021-10-13T13:15:33.000Z
|
py-scripts/sandbox/html_template.py
|
MynaITLabs/lanforge-scripts
|
c905e2a12662f0e3304f0ac29b509c95f09983ce
|
[
"BSD-2-Clause-FreeBSD",
"BSD-3-Clause"
] | 11
|
2020-03-26T06:43:24.000Z
|
2022-03-18T19:18:21.000Z
|
""" This script is used for DFS Test Report generation
it has generic methods inside which can be used for other test report generation
date - 11- feb - 2021
-Nikita Yadav
"""
import os.path
import sys
print(sys.path)
sys.path.append('/home/lanforge/.local/lib/python3.6/site-packages')
import pdfkit
# dev complete
def report_banner(date):
banner_data = """
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<title>LANforge Report</title>
</head>
<title>DFS TEST </title></head>
<body>
<div class='Section report_banner-1000x205' style='background-image:url("/home/lanforge/LANforgeGUI_5.4.3/images/report_banner-1000x205.jpg");background-repeat:no-repeat;padding:0;margin:0;min-width:1000px; min-height:205px;width:1000px; height:205px;max-width:1000px; max-height:205px;'>
<br>
<img align='right' style='padding:25;margin:5;width:200px;' src="/home/lanforge/LANforgeGUI_5.4.3/images/CandelaLogo2-90dpi-200x90-trans.png" border='0' />
<div class='HeaderStyle'>
<br>
<h1 class='TitleFontPrint' style='color:darkgreen;'> Dynamic Frequency Selection </h1>
<h3 class='TitleFontPrint' style='color:darkgreen;'>""" + date + """</h3>
</div>
</div>
<br><br>
"""
return str(banner_data)
# dev complete
def test_objective(objective="The DFS Test is designed to test the Performance of the Netgear Access Point.Dynamic frequency selection is a technology that is designed to ensure that wireless devices operating in the unlicensed WLAN 5 GHz bands are able to detect when they may be interfering with military and weather radar systems and automatically switch over to another frequency where they will not cause any disturbance. "):
test_objective = """
<!-- Test Objective -->
<h3 align='left'>Objective</h3>
<p align='left' width='900'>""" + str(objective) + """</p>
<br>
"""
return str(test_objective)
def radar_detect_discription(data= " This Table will give you results in YES or NO if the AP detects the Radar"):
test_radar = """
<!-- Radar Detect status -->
<h3 align='left'>Radar Detection Detail</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(test_radar)
def client_connection_detail(data = "This Table will give you results in seconds which is measured value of the time taken by the client to connect and generate traffic after Radar detection"):
test_client = """
<!-- client connection time -->
<h3 align='left'>Client Connection Details</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(test_client)
def detection_time_details(data= "This Table will give you results in seconds which is measured value of the time difference when the radar was sent and detected"):
test_detection = """
<!-- detection time -->
<h3 align='left'>Detection Time Details</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(test_detection)
def switched_channel_details(data = "This Table will give you result value of channel number to which the client switches after radar detection X - channel never set in AP AUTO - State when we cannot determine the channel at which the client is associated"):
switch_channel = """
<!-- switched channe;l -->
<h3 align='left'>Switcing Channel Details</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(switch_channel)
# dev complete
def test_setup_information(test_setup_data=None):
if test_setup_data is None:
return None
else:
var = ""
for i in test_setup_data:
var = var + "<tr><td>" + i + "</td><td colspan='3'>" + str(test_setup_data[i]) + "</td></tr>"
setup_information = """
<!-- Test Setup Information -->
<table width='700px' border='1' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<th colspan='2'>Test Setup Information</th>
</tr>
<tr>
<td>Device Under Test</td>
<td>
<table width='100%' border='0' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
""" + var + """
</table>
</td>
</tr>
</table>
<br>
"""
return str(setup_information)
# yet to test on dev level
def graph_html(graph_path=""):
graph_html_obj = """
<!-- Detection Time Graph -->
<h3>Detection Time Graph</h3>
<img align='center' style='padding:15;margin:5;width:1000px;' src=""" + graph_path + """ border='1' />
<br><br>
"""
return str(graph_html_obj)
def bar_plot(ax, data, x_axis_info=[], colors=None, total_width=0.8, single_width=1, legend=True):
# Check if colors where provided, otherwhise use the default color cycle
if colors is None:
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
# Number of bars per group
n_bars = len(data)
# The width of a single bar
bar_width = total_width / n_bars
# List containing handles for the drawn bars, used for the legend
bars = []
# Iterate over all data
for i, (name, values) in enumerate(data.items()):
# The offset in x direction of that bar
x_offset = (i - n_bars / 2) * bar_width + bar_width / 2
# print(values)
# Draw a bar for every value of that type
for x, y in enumerate(values):
bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])
# Add a handle to the last drawn bar, which we'll need for the legend
bars.append(bar[0])
# Draw legend if we need
if legend:
ax.legend(bars, data.keys(), bbox_to_anchor=(1.1, 1.05))
ax.set_ylabel('Time in seconds')
ax.set_xlabel('Channels')
# ax.set_xticks(1)
x_data = x_axis_info
idx = np.asarray([i for i in range(len(x_data))])
ax.set_xticks(idx)
ax.set_xticklabels(x_data)
def generate_graph(result_data, x_axis_info, graph_path):
detection_data = dict.fromkeys(result_data.keys())
for i in detection_data:
try:
detection_data[i] = result_data[i]['detection_time_lst']
except:
detection_data[i] = []
print(detection_data)
fig, ax = plt.subplots()
bar_plot(ax, detection_data, x_axis_info=x_axis_info, total_width=.8, single_width=1.2)
my_dpi = 96
figure = plt.gcf() # get current figure
figure.set_size_inches(18, 6)
# when saving, specify the DPI
str(datetime.now()).split(",")[0].replace(" ", "-").split(".")[0]
plt.savefig(graph_path + "/image.png", dpi=my_dpi)
return str(graph_html(graph_path + "/image.png"))
# yet to test on dev level
def add_radar_table(result_data, row_head_list=None, col_head_list=None):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
radar_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["radar_lst"]
final_data = ""
for i in fcc_type:
if i == "YES":
final_data = final_data + "<td colspan='1' bgcolor='#90EE90'>YES</td>"
else:
final_data = final_data + "<td colspan='1' bgcolor='orange'>NO</td>"
radar_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
radar_html_struct[col]) + "</tr>"
radar_html = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Radar Detected </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return str(radar_html)
# yet to test on dev level
def add_client_cx_table(result_data, row_head_list, col_head_list):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
client_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["connection_time_lst"]
final_data = ""
for i in fcc_type:
if i == 0:
final_data = final_data + "<td colspan='1'bgcolor='pink'>" + str(i) + "</td>"
else:
final_data = final_data + "<td colspan='1' bgcolor='yellow'>" + str(i) + "</td>"
client_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
client_html_struct[col]) + "</tr>"
client_cx_html = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Client Connection Time (sec) </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return str(client_cx_html)
# yet to test on dev level
def add_detection_table(result_data, row_head_list, col_head_list):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
detection_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["detection_time_lst"]
final_data = ""
for i in fcc_type:
if i == 0:
final_data = final_data + "<td colspan='1' bgcolor='GREEN'>" + str(i) + " </td>"
else:
final_data = final_data + "<td colspan='1'bgcolor='BLUE'>" + str(i) + " </td>"
detection_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
detection_html_struct[col]) + "</tr>"
detection_html = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Detection Time (sec) </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return detection_html
# yet to test on dev level
def add_switched_channel_table(result_data, row_head_list, col_head_list):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
switched_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["switched_ch_lst"]
final_data = ""
for i in fcc_type:
if i == "X" or i == "AUTO":
final_data = final_data + "<td colspan='1'bgcolor='#C6FECC'>" + str(i) + "</td>"
elif i == " - ":
final_data = final_data + "<td colspan='1'bgcolor='#CCC6FE'>" + str(i) + "</td>"
else:
final_data = final_data + "<td colspan='1'bgcolor=' #FEE8C6'>" + str(i) + "</td>"
switched_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
switched_html_struct[col]) + "</tr>"
switched_data = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Switched Channel </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return switched_data
'''def input_usedinformation(ip ="", user="", passwd="", radio= "", help= ""):
setup_information = """
<!-- Input Used Information -->
<table width='700px' border='1' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<th colspan='2'>Input Given Information</th>
</tr>
<tr>
<td>Input used in script</td>
<td>
<table width='100%' border='0' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<td>AP ip</td>
<td colspan='3'>""" + ip + """</td>
</tr>
<tr>
<td>user name</td>
<td colspan='3'>""" + user + """</td>
</tr>
<tr>
<td>password</td>
<td colspan='3'>""" + passwd + """</td>
</tr>
<tr>
<td>radio</td>
<td colspan='3'>""" + radio + """</td>
</tr>
<tr>
<td>help</td>
<td colspan='3'>""" + help + """</td>
</tr>
</table>
</td>
</tr>
</table>
<br>
"""
return str(setup_information)'''
def input_setup_info_table(input_setup_info=None):
if input_setup_info is None:
return None
else:
var = ""
for i in input_setup_info:
var = var + "<tr><td>" + i + "</td><td colspan='3'>" + str(input_setup_info[i]) + "</td></tr>"
setup_information = """
<!-- Test Setup Information -->
<table width='700px' border='1' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<th colspan='2'>Input Setup Information</th>
</tr>
<tr>
<td>Information</td>
<td>
<table width='100%' border='0' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
""" + var + """
</table>
</td>
</tr>
</table>
<br>
"""
return str(setup_information)
def generate_report(result_data=None,
date=None,
test_setup_info={},
input_setup_info = {},
test_channel=None,
graph_path="/home/lanforge/html-reports/dfs"):
# Need to pass this to test_setup_information()
input_setup_info = input_setup_info
test_setup_data = test_setup_info
test_chal = test_channel
# test_setup_data = {
# "AP Name": "TestAP",
# "SSID": "NETGEAR",f
# "Number of Stations": "1",
# "Test Duration": "5:00 Mins"
# }
"""result_data = {'FCC0': {'switched_ch_lst': ["1"], 'detection_time_lst': [1, 5], 'radar_lst': ['NO', 'YES'],
'connection_time_lst': [0, 65]}
}"""
reports_root = graph_path + "/" + str(date)
if path.exists(graph_path):
os.mkdir(reports_root)
print("Reports Root is Created")
else:
os.mkdir(graph_path)
os.mkdir(reports_root)
print("Reports Root is created")
print("Generating Reports in : ", reports_root)
html_report = report_banner(date) + \
test_setup_information(test_setup_data) + \
test_objective() + \
generate_graph(result_data, test_chal, graph_path=reports_root) + \
radar_detect_discription() + \
add_radar_table(result_data, result_data.keys(), test_chal) + \
client_connection_detail() + \
add_client_cx_table(result_data, result_data.keys(), test_chal) + \
detection_time_details() + \
add_detection_table(result_data, result_data.keys(), test_chal) + \
switched_channel_details() + \
add_switched_channel_table(result_data, result_data.keys(), test_chal) + \
input_setup_info_table(input_setup_info)
# write the html_report into a file in /home/lanforge/html_reports in a directory named DFS_TEST and html_report name should be having a timesnap with it
f = open(reports_root + "/report.html", "a")
# f = open("report.html", "a")
f.write(html_report)
f.close()
# write logic to generate pdf here
pdfkit.from_file(reports_root + "/report.html", reports_root + "/report.pdf")
# test blocks from here
if __name__ == '__main__':
generate_report()
# generate_graph()
""" This script is used for DFS Test Report generation
it has generic methods inside which can be used for other test report generation
date - 11- feb - 2021
-Nikita Yadav
"""
from matplotlib import pyplot as plt
from datetime import datetime
import numpy as np
import os.path
from os import path
import sys
print(sys.path)
sys.path.append('/home/lanforge/.local/lib/python3.6/site-packages')
import pdfkit
# dev complete
def report_banner(date):
banner_data = """
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<title>LANforge Report</title>
</head>
<title>DFS TEST </title></head>
<body>
<div class='Section report_banner-1000x205' style='background-image:url("/home/lanforge/LANforgeGUI_5.4.3/images/report_banner-1000x205.jpg");background-repeat:no-repeat;padding:0;margin:0;min-width:1000px; min-height:205px;width:1000px; height:205px;max-width:1000px; max-height:205px;'>
<br>
<img align='right' style='padding:25;margin:5;width:200px;' src="/home/lanforge/LANforgeGUI_5.4.3/images/CandelaLogo2-90dpi-200x90-trans.png" border='0' />
<div class='HeaderStyle'>
<br>
<h1 class='TitleFontPrint' style='color:darkgreen;'> Dynamic Frequency Selection </h1>
<h3 class='TitleFontPrint' style='color:darkgreen;'>""" + date + """</h3>
</div>
</div>
<br><br>
"""
return str(banner_data)
# dev complete
def test_objective(objective="The DFS Test is designed to test the Performance of the Netgear Access Point.Dynamic frequency selection is a technology that is designed to ensure that wireless devices operating in the unlicensed WLAN 5 GHz bands are able to detect when they may be interfering with military and weather radar systems and automatically switch over to another frequency where they will not cause any disturbance. "):
test_objective = """
<!-- Test Objective -->
<h3 align='left'>Objective</h3>
<p align='left' width='900'>""" + str(objective) + """</p>
<br>
"""
return str(test_objective)
def radar_detect_discription(data= " This Table will give you results in YES or NO if the AP detects the Radar"):
test_radar = """
<!-- Radar Detect status -->
<h3 align='left'>Radar Detection Detail</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(test_radar)
def client_connection_detail(data = "This Table will give you results in seconds which is measured value of the time taken by the client to connect and generate traffic after Radar detection"):
test_client = """
<!-- client connection time -->
<h3 align='left'>Client Connection Details</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(test_client)
def detection_time_details(data= "This Table will give you results in seconds which is measured value of the time difference when the radar was sent and detected"):
test_detection = """
<!-- detection time -->
<h3 align='left'>Detection Time Details</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(test_detection)
def switched_channel_details(data = "This Table will give you result value of channel number to which the client switches after radar detection X - channel never set in AP AUTO - State when we cannot determine the channel at which the client is associated"):
switch_channel = """
<!-- switched channe;l -->
<h3 align='left'>Switcing Channel Details</h3>
<p align='left' width='900'>""" + str(data) + """</p>
<br>
"""
return str(switch_channel)
# dev complete
def test_setup_information(test_setup_data=None):
if test_setup_data is None:
return None
else:
var = ""
for i in test_setup_data:
var = var + "<tr><td>" + i + "</td><td colspan='3'>" + str(test_setup_data[i]) + "</td></tr>"
setup_information = """
<!-- Test Setup Information -->
<table width='700px' border='1' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<th colspan='2'>Test Setup Information</th>
</tr>
<tr>
<td>Device Under Test</td>
<td>
<table width='100%' border='0' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
""" + var + """
</table>
</td>
</tr>
</table>
<br>
"""
return str(setup_information)
# yet to test on dev level
def graph_html(graph_path=""):
graph_html_obj = """
<!-- Detection Time Graph -->
<h3>Detection Time Graph</h3>
<img align='center' style='padding:15;margin:5;width:1000px;' src=""" + graph_path + """ border='1' />
<br><br>
"""
return str(graph_html_obj)
def bar_plot(ax, data, x_axis_info=[], colors=None, total_width=0.8, single_width=1, legend=True):
# Check if colors where provided, otherwhise use the default color cycle
if colors is None:
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']
# Number of bars per group
n_bars = len(data)
# The width of a single bar
bar_width = total_width / n_bars
# List containing handles for the drawn bars, used for the legend
bars = []
# Iterate over all data
for i, (name, values) in enumerate(data.items()):
# The offset in x direction of that bar
x_offset = (i - n_bars / 2) * bar_width + bar_width / 2
# print(values)
# Draw a bar for every value of that type
for x, y in enumerate(values):
bar = ax.bar(x + x_offset, y, width=bar_width * single_width, color=colors[i % len(colors)])
# Add a handle to the last drawn bar, which we'll need for the legend
bars.append(bar[0])
# Draw legend if we need
if legend:
ax.legend(bars, data.keys(), bbox_to_anchor=(1.1, 1.05))
ax.set_ylabel('Time in seconds')
ax.set_xlabel('Channels')
# ax.set_xticks(1)
x_data = x_axis_info
idx = np.asarray([i for i in range(len(x_data))])
ax.set_xticks(idx)
ax.set_xticklabels(x_data)
def generate_graph(result_data, x_axis_info, graph_path):
detection_data = dict.fromkeys(result_data.keys())
for i in detection_data:
try:
detection_data[i] = result_data[i]['detection_time_lst']
except:
detection_data[i] = []
print(detection_data)
fig, ax = plt.subplots()
bar_plot(ax, detection_data, x_axis_info=x_axis_info, total_width=.8, single_width=1.2)
my_dpi = 96
figure = plt.gcf() # get current figure
figure.set_size_inches(18, 6)
# when saving, specify the DPI
str(datetime.now()).split(",")[0].replace(" ", "-").split(".")[0]
plt.savefig(graph_path + "/image.png", dpi=my_dpi)
return str(graph_html(graph_path + "/image.png"))
# yet to test on dev level
def add_radar_table(result_data, row_head_list=None, col_head_list=None):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
radar_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["radar_lst"]
final_data = ""
for i in fcc_type:
if i == "YES":
final_data = final_data + "<td colspan='1' bgcolor='#90EE90'>YES</td>"
else:
final_data = final_data + "<td colspan='1' bgcolor='orange'>NO</td>"
radar_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
radar_html_struct[col]) + "</tr>"
radar_html = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Radar Detected </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return str(radar_html)
# yet to test on dev level
def add_client_cx_table(result_data, row_head_list, col_head_list):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
client_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["connection_time_lst"]
final_data = ""
for i in fcc_type:
if i == 0:
final_data = final_data + "<td colspan='1'bgcolor='pink'>" + str(i) + "</td>"
else:
final_data = final_data + "<td colspan='1' bgcolor='yellow'>" + str(i) + "</td>"
client_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
client_html_struct[col]) + "</tr>"
client_cx_html = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Client Connection Time (sec) </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return str(client_cx_html)
# yet to test on dev level
def add_detection_table(result_data, row_head_list, col_head_list):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
detection_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["detection_time_lst"]
final_data = ""
for i in fcc_type:
if i == 0:
final_data = final_data + "<td colspan='1' bgcolor='GREEN'>" + str(i) + " </td>"
else:
final_data = final_data + "<td colspan='1'bgcolor='BLUE'>" + str(i) + " </td>"
detection_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
detection_html_struct[col]) + "</tr>"
detection_html = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Detection Time (sec) </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return detection_html
# yet to test on dev level
def add_switched_channel_table(result_data, row_head_list, col_head_list):
var_row = "<th></th>"
for row in col_head_list:
var_row = var_row + "<th>" + row + "</th>"
switched_html_struct = dict.fromkeys(list(result_data.keys()))
for fcc in list(result_data.keys()):
fcc_type = result_data[fcc]["switched_ch_lst"]
final_data = ""
for i in fcc_type:
if i == "X" or i == "AUTO":
final_data = final_data + "<td colspan='1'bgcolor='#C6FECC'>" + str(i) + "</td>"
elif i == " - ":
final_data = final_data + "<td colspan='1'bgcolor='#CCC6FE'>" + str(i) + "</td>"
else:
final_data = final_data + "<td colspan='1'bgcolor=' #FEE8C6'>" + str(i) + "</td>"
switched_html_struct[fcc] = final_data
var_col = ""
for col in row_head_list:
var_col = var_col + "<tr><td>" + str(col) + "</td><!-- Add Variable Here -->" + str(
switched_html_struct[col]) + "</tr>"
switched_data = """
<!-- Radar Detected Table -->
<table width='1000px' border='1' cellpadding='2' cellspacing='0' >
<tr>
<th colspan='2'>Switched Channel </th>
</tr>
<table width='1000px' border='1' >
<tr>
""" + var_row + """
</tr>
""" + var_col + """
</table>
</table>
<br><br><br><br><br><br><br>
"""
return switched_data
'''def input_usedinformation(ip ="", user="", passwd="", radio= "", help= ""):
setup_information = """
<!-- Input Used Information -->
<table width='700px' border='1' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<th colspan='2'>Input Given Information</th>
</tr>
<tr>
<td>Input used in script</td>
<td>
<table width='100%' border='0' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<td>AP ip</td>
<td colspan='3'>""" + ip + """</td>
</tr>
<tr>
<td>user name</td>
<td colspan='3'>""" + user + """</td>
</tr>
<tr>
<td>password</td>
<td colspan='3'>""" + passwd + """</td>
</tr>
<tr>
<td>radio</td>
<td colspan='3'>""" + radio + """</td>
</tr>
<tr>
<td>help</td>
<td colspan='3'>""" + help + """</td>
</tr>
</table>
</td>
</tr>
</table>
<br>
"""
return str(setup_information)'''
def input_setup_info_table(input_setup_info=None):
if input_setup_info is None:
return None
else:
var = ""
for i in input_setup_info:
var = var + "<tr><td>" + i + "</td><td colspan='3'>" + str(input_setup_info[i]) + "</td></tr>"
setup_information = """
<!-- Test Setup Information -->
<table width='700px' border='1' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
<tr>
<th colspan='2'>Input Setup Information</th>
</tr>
<tr>
<td>Information</td>
<td>
<table width='100%' border='0' cellpadding='2' cellspacing='0' style='border-top-color: gray; border-top-style: solid; border-top-width: 1px; border-right-color: gray; border-right-style: solid; border-right-width: 1px; border-bottom-color: gray; border-bottom-style: solid; border-bottom-width: 1px; border-left-color: gray; border-left-style: solid; border-left-width: 1px'>
""" + var + """
</table>
</td>
</tr>
</table>
<br>
"""
return str(setup_information)
def generate_report(result_data=None,
date=None,
test_setup_info={},
input_setup_info = {},
test_channel=None,
graph_path="/home/lanforge/html-reports/dfs"):
# Need to pass this to test_setup_information()
input_setup_info = input_setup_info
test_setup_data = test_setup_info
test_chal = test_channel
# test_setup_data = {
# "AP Name": "TestAP",
# "SSID": "NETGEAR",f
# "Number of Stations": "1",
# "Test Duration": "5:00 Mins"
# }
"""result_data = {'FCC0': {'switched_ch_lst': ["1"], 'detection_time_lst': [1, 5], 'radar_lst': ['NO', 'YES'],
'connection_time_lst': [0, 65]}
}"""
reports_root = graph_path + "/" + str(date)
if path.exists(graph_path):
os.mkdir(reports_root)
print("Reports Root is Created")
else:
os.mkdir(graph_path)
os.mkdir(reports_root)
print("Reports Root is created")
print("Generating Reports in : ", reports_root)
html_report = report_banner(date) + \
test_setup_information(test_setup_data) + \
test_objective() + \
generate_graph(result_data, test_chal, graph_path=reports_root) + \
radar_detect_discription() + \
add_radar_table(result_data, result_data.keys(), test_chal) + \
client_connection_detail() + \
add_client_cx_table(result_data, result_data.keys(), test_chal) + \
detection_time_details() + \
add_detection_table(result_data, result_data.keys(), test_chal) + \
switched_channel_details() + \
add_switched_channel_table(result_data, result_data.keys(), test_chal) + \
input_setup_info_table(input_setup_info)
# write the html_report into a file in /home/lanforge/html_reports in a directory named DFS_TEST and html_report name should be having a timesnap with it
f = open(reports_root + "/report.html", "a")
# f = open("report.html", "a")
f.write(html_report)
f.close()
# write logic to generate pdf here
pdfkit.from_file(reports_root + "/report.html", reports_root + "/report.pdf")
# test blocks from here
if __name__ == '__main__':
generate_report()
# generate_graph()
| 42.824056
| 430
| 0.507463
| 4,920
| 43,081
| 4.285772
| 0.077846
| 0.028455
| 0.034146
| 0.012141
| 0.995068
| 0.995068
| 0.995068
| 0.995068
| 0.995068
| 0.995068
| 0
| 0.020456
| 0.359996
| 43,081
| 1,005
| 431
| 42.866667
| 0.744306
| 0.052877
| 0
| 0.994083
| 0
| 0.035503
| 0.542177
| 0.06083
| 0
| 0
| 0
| 0
| 0
| 1
| 0.047337
| false
| 0
| 0.014793
| 0
| 0.109467
| 0.014793
| 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
|
3d9ed6b6a6e334b9616e027c95d6ceac9e6a0714
| 116
|
py
|
Python
|
ApproxSrc/__init__.py
|
sirius0000/SR-Mongoose
|
068068c7fbc6d1b1bb33ffa31529dda55580b7f2
|
[
"MIT"
] | 5
|
2021-07-08T12:28:27.000Z
|
2022-03-10T16:44:25.000Z
|
ApproxSrc/__init__.py
|
sirius0000/SR-Mongoose
|
068068c7fbc6d1b1bb33ffa31529dda55580b7f2
|
[
"MIT"
] | null | null | null |
ApproxSrc/__init__.py
|
sirius0000/SR-Mongoose
|
068068c7fbc6d1b1bb33ffa31529dda55580b7f2
|
[
"MIT"
] | 2
|
2021-10-20T04:29:11.000Z
|
2022-03-10T16:44:29.000Z
|
from .modules.approx_Conv2d import *
from .modules.approx_Conv2d_dist import *
from .modules.approx_Linear import *
| 29
| 41
| 0.818966
| 16
| 116
| 5.6875
| 0.4375
| 0.362637
| 0.56044
| 0.505495
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.019231
| 0.103448
| 116
| 3
| 42
| 38.666667
| 0.855769
| 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
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 7
|
9ab1c9e6f10c6c550754e7583fccce33e9b780be
| 2,786
|
py
|
Python
|
trello/tokens.py
|
LazyTarget/trello-py
|
b2e53e75c95f6080fdadca713838c121c800272b
|
[
"BSD-3-Clause"
] | 51
|
2016-06-15T03:18:07.000Z
|
2022-03-29T11:49:47.000Z
|
trello/tokens.py
|
LazyTarget/trello-py
|
b2e53e75c95f6080fdadca713838c121c800272b
|
[
"BSD-3-Clause"
] | 10
|
2015-03-23T20:18:26.000Z
|
2022-03-21T21:39:44.000Z
|
trello/tokens.py
|
LazyTarget/trello-py
|
b2e53e75c95f6080fdadca713838c121c800272b
|
[
"BSD-3-Clause"
] | 23
|
2015-10-23T13:15:01.000Z
|
2022-03-29T11:49:52.000Z
|
from .base import ApiBase
import requests
class Tokens(ApiBase):
__module__ = 'trello'
def __init__(self, apikey, token=None):
self._apikey = apikey
self._token = token
def get(self, token, fields=None, webhooks=None):
resp = requests.get(f"https://trello.com/1/tokens/{token}", params={"key": self._apikey, "token": self._token, "fields": fields, "webhooks": webhooks}, data=None)
return self.raise_or_json(resp)
def get_field(self, field, token):
resp = requests.get(f"https://trello.com/1/tokens/{token}/{field}", params={"key": self._apikey, "token": self._token}, data=None)
return self.raise_or_json(resp)
def get_member(self, token, fields=None):
resp = requests.get(f"https://trello.com/1/tokens/{token}/member", params={"key": self._apikey, "token": self._token, "fields": fields}, data=None)
return self.raise_or_json(resp)
def get_member_field(self, field, token):
resp = requests.get(f"https://trello.com/1/tokens/{token}/member/{field}", params={"key": self._apikey, "token": self._token}, data=None)
return self.raise_or_json(resp)
def get_webhook(self, token):
resp = requests.get(f"https://trello.com/1/tokens/{token}/webhooks", params={"key": self._apikey, "token": self._token}, data=None)
return self.raise_or_json(resp)
def get_webhook_idWebhook(self, idWebhook, token):
resp = requests.get(f"https://trello.com/1/tokens/{token}/webhooks/{idWebhook}", params={"key": self._apikey, "token": self._token}, data=None)
return self.raise_or_json(resp)
def update_webhook(self, token, callbackURL, idModel, description=None):
resp = requests.put(f"https://trello.com/1/tokens/{token}/webhooks", params={"key": self._apikey, "token": self._token}, data={"callbackURL": callbackURL, "idModel": idModel, "description": description})
return self.raise_or_json(resp)
def new_webhook(self, token, callbackURL, idModel, description=None):
resp = requests.post(f"https://trello.com/1/tokens/{token}/webhooks", params={"key": self._apikey, "token": self._token}, data={"callbackURL": callbackURL, "idModel": idModel, "description": description})
return self.raise_or_json(resp)
def delete(self, token):
resp = requests.delete(f"https://trello.com/1/tokens/{token}", params={"key": self._apikey, "token": self._token}, data=None)
return self.raise_or_json(resp)
def delete_webhook_idWebhook(self, idWebhook, token):
resp = requests.delete(f"https://trello.com/1/tokens/{token}/webhooks/{idWebhook}", params={"key": self._apikey, "token": self._token}, data=None)
return self.raise_or_json(resp)
| 54.627451
| 213
| 0.666547
| 369
| 2,786
| 4.867209
| 0.113821
| 0.085189
| 0.091871
| 0.083519
| 0.88363
| 0.88363
| 0.88363
| 0.855234
| 0.848552
| 0.748886
| 0
| 0.004312
| 0.167624
| 2,786
| 50
| 214
| 55.72
| 0.77016
| 0
| 0
| 0.27027
| 0
| 0
| 0.224132
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.297297
| false
| 0
| 0.054054
| 0
| 0.675676
| 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
|
b109054bfee5b2e7ce9e79b4e1178b41630bf1dc
| 79
|
py
|
Python
|
tests/test_pdftools.py
|
pmgagne/pdftools
|
81af25dee263d5187b26a818694656db54cd0d72
|
[
"MIT"
] | 59
|
2018-05-04T11:05:33.000Z
|
2022-02-07T23:22:22.000Z
|
tests/test_pdftools.py
|
pmgagne/pdftools
|
81af25dee263d5187b26a818694656db54cd0d72
|
[
"MIT"
] | 13
|
2018-04-10T16:38:32.000Z
|
2022-01-17T21:31:18.000Z
|
tests/test_pdftools.py
|
pmgagne/pdftools
|
81af25dee263d5187b26a818694656db54cd0d72
|
[
"MIT"
] | 17
|
2019-01-23T02:41:03.000Z
|
2022-03-02T20:34:03.000Z
|
import pytest
def test_pdftools_import():
from pdftools import pdftools
| 11.285714
| 33
| 0.772152
| 10
| 79
| 5.9
| 0.6
| 0.474576
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.189873
| 79
| 6
| 34
| 13.166667
| 0.921875
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| true
| 0
| 1
| 0
| 1.333333
| 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
|
b14d9c6f44ed932447971357124ac82ca4816c45
| 11,211
|
py
|
Python
|
tests/test_util_query.py
|
jorisvandenbossche/pydov
|
8b909209e63455fb06251d73e32958d66c6e14ed
|
[
"MIT"
] | null | null | null |
tests/test_util_query.py
|
jorisvandenbossche/pydov
|
8b909209e63455fb06251d73e32958d66c6e14ed
|
[
"MIT"
] | null | null | null |
tests/test_util_query.py
|
jorisvandenbossche/pydov
|
8b909209e63455fb06251d73e32958d66c6e14ed
|
[
"MIT"
] | null | null | null |
"""Module grouping tests for the pydov.util.query module."""
import pandas as pd
import numpy as np
import pytest
from pydov.util.dovutil import build_dov_url
from pydov.util.query import (
PropertyInList,
Join,
)
class TestPropertyInList(object):
"""Test the PropertyInList query expression."""
def test(self):
"""Test the PropertyInList expression with a standard list.
Test whether the generated query is correct.
"""
l = ['a', 'b', 'c']
query = PropertyInList('methode', l)
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}Or'
assert len(list(xml)) == 3
for f in xml:
assert f.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = f.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'methode'
literal = f.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l.remove(literal.text)
assert len(l) == 0
def test_duplicate(self):
"""Test the PropertyInList expression with a list containing
duplicates.
Test whether the generated query is correct and does not contain the
duplicate entry twice.
"""
l = ['a', 'a', 'b', 'c']
l_output = ['a', 'b', 'c']
query = PropertyInList('methode', l)
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}Or'
assert len(list(xml)) == 3
for f in xml:
assert f.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = f.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'methode'
literal = f.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l_output.remove(literal.text)
assert len(l_output) == 0
def test_list_single(self):
"""Test the PropertyInList expression with a list containing
a single item.
Test whether the generated query is correct and does contain only a
single PropertyIsEqualTo.
"""
l = ['a']
query = PropertyInList('methode', l)
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'methode'
literal = xml.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l.remove(literal.text)
assert len(l) == 0
def test_list_single_duplicate(self):
"""Test the PropertyInList expression with a list containing
a single duplicated item.
Test whether the generated query is correct and does contain only a
single PropertyIsEqualTo.
"""
l = ['a', 'a']
l_output = ['a']
query = PropertyInList('methode', l)
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'methode'
literal = xml.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l_output
l_output.remove(literal.text)
assert len(l_output) == 0
def test_emptylist(self):
"""Test the PropertyInList expression with an empty list.
Test whether a ValueError is raised.
"""
with pytest.raises(ValueError):
l = []
PropertyInList('methode', l)
def test_nolist(self):
"""Test the PropertyInList expression with a string instead of a list.
Test whether a ValueError is raised.
"""
with pytest.raises(ValueError):
l = 'goed'
PropertyInList('betrouwbaarheid', l)
class TestJoin(object):
"""Test the Join query expression."""
def test(self):
"""Test the Join expression with a standard dataframe.
Test whether the generated query is correct.
"""
l = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1986-068843'),
build_dov_url('data/boring/1980-068861')]
df = pd.DataFrame({
'pkey_boring': pd.Series(l),
'diepte_tot_m': pd.Series([10, 20, 30])
})
query = Join(df, 'pkey_boring')
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}Or'
assert len(list(xml)) == 3
for f in xml:
assert f.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = f.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'pkey_boring'
literal = f.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l.remove(literal.text)
assert len(l) == 0
def test_duplicate(self):
"""Test the Join expression with a column containing
duplicates.
Test whether the generated query is correct and does not contain the
duplicate entry twice.
"""
l = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1980-068861')]
l_output = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1980-068861')]
df = pd.DataFrame({
'pkey_boring': pd.Series(l),
'diepte_tot_m': pd.Series([10, 20, 30])
})
query = Join(df, 'pkey_boring')
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}Or'
assert len(list(xml)) == 2
for f in xml:
assert f.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = f.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'pkey_boring'
literal = f.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l_output.remove(literal.text)
assert len(l_output) == 0
def test_wrongcolumn(self):
"""Test the Join expression with a join_column not available in the
dataframe.
Test whether a ValueError is raised.
"""
with pytest.raises(ValueError):
l = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1986-068843'),
build_dov_url('data/boring/1980-068861')]
df = pd.DataFrame({
'pkey_boring': pd.Series(l),
'diepte_tot_m': pd.Series([10, 20, 30])
})
Join(df, 'pkey_sondering')
def test_single(self):
"""Test the Join expression with a dataframe containing a single row.
Test whether the generated query is correct and does contain only a
single PropertyIsEqualTo.
"""
l = [build_dov_url('data/boring/1986-068853')]
df = pd.DataFrame({
'pkey_boring': pd.Series(l),
'diepte_tot_m': pd.Series([10])
})
query = Join(df, 'pkey_boring')
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'pkey_boring'
literal = xml.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l.remove(literal.text)
assert len(l) == 0
def test_single_duplicate(self):
"""Test the Join expression with a dataframe containing two
identical keys.
Test whether the generated query is correct and does contain only a
single PropertyIsEqualTo.
"""
l = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1986-068853')]
l_output = [build_dov_url('data/boring/1986-068853')]
df = pd.DataFrame({
'pkey_boring': pd.Series(l),
'diepte_tot_m': pd.Series([10, 20])
})
query = Join(df, 'pkey_boring')
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = xml.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'pkey_boring'
literal = xml.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l_output
l_output.remove(literal.text)
assert len(l_output) == 0
def test_empty(self):
"""Test the Join expression with an empty dataframe.
Test whether a ValueError is raised
"""
df = pd.DataFrame({
'pkey_boring': [np.nan, np.nan],
'diepte_tot_m': pd.Series([10, 20])
})
with pytest.raises(ValueError):
Join(df, 'pkey_boring')
def test_on(self):
"""Test the Join expression with a standard dataframe and 'on'.
Test whether the generated query is correct.
"""
l = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1986-068843'),
build_dov_url('data/boring/1980-068861')]
df = pd.DataFrame({
'pkey_boring': pd.Series(l),
'diepte_tot_m': pd.Series([10, 20, 30])
})
query = Join(df, on='pkey_boring')
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}Or'
assert len(list(xml)) == 3
for f in xml:
assert f.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = f.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'pkey_boring'
literal = f.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l.remove(literal.text)
assert len(l) == 0
def test_using(self):
"""Test the Join expression with a standard dataframe and 'on' and
'using'.
Test whether the generated query is correct.
"""
l = [build_dov_url('data/boring/1986-068853'),
build_dov_url('data/boring/1986-068843'),
build_dov_url('data/boring/1980-068861')]
df = pd.DataFrame({
'boringfiche': pd.Series(l),
'diepte_tot_m': pd.Series([10, 20, 30])
})
query = Join(df, on='pkey_boring', using='boringfiche')
xml = query.toXML()
assert xml.tag == '{http://www.opengis.net/ogc}Or'
assert len(list(xml)) == 3
for f in xml:
assert f.tag == '{http://www.opengis.net/ogc}PropertyIsEqualTo'
propertyname = f.find('./{http://www.opengis.net/ogc}PropertyName')
assert propertyname.text == 'pkey_boring'
literal = f.find('./{http://www.opengis.net/ogc}Literal')
assert literal.text in l
l.remove(literal.text)
assert len(l) == 0
| 29.737401
| 79
| 0.576577
| 1,368
| 11,211
| 4.643275
| 0.086988
| 0.039673
| 0.079345
| 0.096348
| 0.904754
| 0.89704
| 0.886335
| 0.851071
| 0.84068
| 0.815649
| 0
| 0.033501
| 0.291767
| 11,211
| 376
| 80
| 29.816489
| 0.766499
| 0.173936
| 0
| 0.78607
| 0
| 0
| 0.266584
| 0.054768
| 0
| 0
| 0
| 0
| 0.258706
| 1
| 0.069652
| false
| 0
| 0.024876
| 0
| 0.104478
| 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
|
4909c40c73f35d1a2a96e058acea6c8aa1ef1a2d
| 3,567
|
py
|
Python
|
dev-support/docker/docker/bin/test/ambaribuild_test.py
|
Syndra/Ambari-source
|
717526b2bf3636622212b14de0d3d298a20c7370
|
[
"Apache-2.0"
] | 5
|
2017-07-20T11:15:10.000Z
|
2020-04-16T15:42:55.000Z
|
dev-support/docker/docker/bin/test/ambaribuild_test.py
|
Syndra/Ambari-source
|
717526b2bf3636622212b14de0d3d298a20c7370
|
[
"Apache-2.0"
] | 8
|
2020-06-18T17:31:19.000Z
|
2022-03-02T08:32:03.000Z
|
dev-support/docker/docker/bin/test/ambaribuild_test.py
|
Syndra/Ambari-source
|
717526b2bf3636622212b14de0d3d298a20c7370
|
[
"Apache-2.0"
] | 12
|
2017-05-17T09:48:01.000Z
|
2021-08-05T19:01:25.000Z
|
#!/usr/bin/python
# coding: utf-8
# 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.
from bin import ambaribuild
# TODO move this to a proper location
def unittest():
# parse
result = ambaribuild.parse(["test"])
assert result.is_deep_clean == False
assert result.is_test == True
assert result.is_rebuild == False
assert result.stack_distribution == None
assert result.supplemental_distribution == None
assert result.is_install_server == False
assert result.is_install_agent == False
assert result.is_deploy == False
assert result.is_server_debug == False
result = ambaribuild.parse(["server"])
assert result.is_deep_clean == False
assert result.is_test == False
assert result.is_rebuild == False
assert result.stack_distribution == None
assert result.supplemental_distribution == None
assert result.is_install_server == True
assert result.is_install_agent == False
assert result.is_deploy == False
assert result.is_server_debug == False
result = ambaribuild.parse(["agent"])
assert result.is_deep_clean == False
assert result.is_test == False
assert result.is_rebuild == False
assert result.stack_distribution == None
assert result.supplemental_distribution == None
assert result.is_install_server == True
assert result.is_install_agent == True
assert result.is_deploy == False
assert result.is_server_debug == False
result = ambaribuild.parse(["agent", "-b"])
assert result.is_deep_clean == False
assert result.is_test == False
assert result.is_rebuild == True
assert result.stack_distribution == None
assert result.supplemental_distribution == None
assert result.is_install_server == True
assert result.is_install_agent == True
assert result.is_deploy == False
assert result.is_server_debug == False
result = ambaribuild.parse(["deploy", "-d"])
assert result.is_deep_clean == False
assert result.is_test == False
assert result.is_rebuild == False
assert result.stack_distribution == None
assert result.supplemental_distribution == None
assert result.is_install_server == True
assert result.is_install_agent == True
assert result.is_deploy == True
assert result.is_server_debug == True
result = ambaribuild.parse(["deploy", "-b", "-s", "BIGTOP", "-d", "-c"])
assert result.is_deep_clean == True
assert result.is_test == False
assert result.is_rebuild == True
assert result.stack_distribution == "BIGTOP"
assert result.supplemental_distribution == None
assert result.is_install_server == True
assert result.is_install_agent == True
assert result.is_deploy == True
assert result.is_server_debug == True
result = ambaribuild.parse(["deploy", "-b", "-s", "HDP", "-x", "BigInsights", "-c"])
assert result.is_deep_clean == True
assert result.is_test == False
assert result.is_rebuild == True
assert result.stack_distribution == "HDP"
assert result.supplemental_distribution == "BigInsights"
assert result.is_install_server == True
assert result.is_install_agent == True
assert result.is_deploy == True
assert result.is_server_debug == False
if __name__ == "__main__":
unittest()
| 35.67
| 85
| 0.759181
| 494
| 3,567
| 5.281377
| 0.208502
| 0.289766
| 0.262936
| 0.131085
| 0.750096
| 0.750096
| 0.748179
| 0.748179
| 0.748179
| 0.748179
| 0
| 0.001632
| 0.141295
| 3,567
| 99
| 86
| 36.030303
| 0.850147
| 0.171573
| 0
| 0.783784
| 0
| 0
| 0.036067
| 0
| 0
| 0
| 0
| 0.010101
| 0.851351
| 1
| 0.013514
| false
| 0
| 0.013514
| 0
| 0.027027
| 0
| 0
| 0
| 0
| null | 1
| 1
| 0
| 0
| 1
| 1
| 1
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| null | 0
| 0
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 10
|
493c340d34129f90aa712d135f382876c0500a7b
| 7,969
|
py
|
Python
|
engines/var.py
|
MikelEulate/timecop
|
033306f20f9748065e396a9aace0591e632cf9e0
|
[
"Apache-2.0"
] | null | null | null |
engines/var.py
|
MikelEulate/timecop
|
033306f20f9748065e396a9aace0591e632cf9e0
|
[
"Apache-2.0"
] | null | null | null |
engines/var.py
|
MikelEulate/timecop
|
033306f20f9748065e396a9aace0591e632cf9e0
|
[
"Apache-2.0"
] | null | null | null |
import numpy as np
import pandas as pd
from sklearn.metrics import mean_squared_error,mean_absolute_error
import pyflux as pf
import helpers as h
def univariate_anomaly_VAR(lista_datos):
lista_puntos = np.arange(0, len(lista_datos),1)
df = pd.DataFrame()
df['valores'] = lista_datos
tam_train = int(len(df)*0.7)
#print tam_train
df_train = df[:tam_train]
print('Tamanio train: {}'.format(df_train.shape))
df_test = df[tam_train:]
print('Tamanio test: {}'.format(df_test.shape))
model = pf.VAR(df_train,lags=15)
x = model.fit()
#model.plot_z(list(range(0,6)),figsize=(15,5))
#model.plot_fit(figsize=(8,5))
#model.plot_predict_is(h=8, figsize=((8,5)))
#model.plot_predict(past_values=20, h=6, figsize=(8,5))
future_forecast_pred = model.predict(len(df_test))
future_forecast_pred = future_forecast_pred[['valores']]
list_test = df_test['valores'].values
list_future_forecast_pred = future_forecast_pred['valores'].values
#mse_test = (list_future_forecast_pred - list_test)
#mse_abs_test = abs(mse_test)
mse = mean_squared_error(list_test, list_future_forecast_pred)
print('El error medio del modelo_test es: {}'.format(mse))
rmse = np.sqrt(mse)
print('El root error medio del modelo_test es: {}'.format(rmse))
mae = mean_absolute_error(list_test, list_future_forecast_pred)
df_aler = pd.DataFrame()
df_aler['real_value'] = list_test
df_aler['expected value'] = list_future_forecast_pred
df_aler['mse'] = mse
df_aler['puntos'] = future_forecast_pred.index
df_aler.set_index('puntos',inplace=True)
df_aler['mae'] = mae
df_aler['anomaly_score'] = abs(df_aler['expected value']-df_aler['real_value'])/df_aler['mae']
df_aler = df_aler[(df_aler['anomaly_score']> 2)]
max = df_aler['anomaly_score'].max()
min = df_aler['anomaly_score'].min()
df_aler['anomaly_score']= ( df_aler['anomaly_score'] - min ) /(max - min)
df_aler_ult = df_aler[:5]
df_aler_ult = df_aler_ult[(df_aler_ult.index==df_aler.index.max())|(df_aler_ult.index==((df_aler.index.max())-1))
|(df_aler_ult.index==((df_aler.index.max())-2))|(df_aler_ult.index==((df_aler.index.max())-3))
|(df_aler_ult.index==((df_aler.index.max())-4))]
if len(df_aler_ult) == 0:
exists_anom_last_5 = 'FALSE'
else:
exists_anom_last_5 = 'TRUE'
max = df_aler_ult['anomaly_score'].max()
min = df_aler_ult['anomaly_score'].min()
print df_aler_ult
df_aler_ult['anomaly_score'] = ( df_aler_ult['anomaly_score'] - min ) /(max - min)
#####forecast#####
model_for = pf.VAR(df,lags=5)
x_for = model_for.fit()
#model.plot_z(list(range(0,6)),figsize=(15,5))
#model.plot_fit(figsize=(8,5))
future_forecast_pred_for = model_for.predict(5)
df_result_forecast = future_forecast_pred_for.reset_index()
df_result_forecast = df_result_forecast.rename(columns = {'index':'step'})
print df.head(5)
print df.tail(5)
engine_output={}
engine_output['rmse'] = rmse
engine_output['mse'] = mse
engine_output['mae'] = mae
engine_output['present_status']=exists_anom_last_5
engine_output['present_alerts']=df_aler_ult.to_dict(orient='record')
engine_output['past']=df_aler.to_dict(orient='record')
engine_output['engine']='VAR'
engine_output['future']= df_result_forecast.to_dict(orient='record')
test_values = pd.DataFrame(future_forecast_pred.values,index = df_test.index,columns=['expected value'])
test_values['step'] = test_values.index
engine_output['debug'] = test_values.to_dict(orient='record')
return (engine_output)
def anomaly_VAR(list_var):
df_var = pd.DataFrame()
for i in range(len(list_var)):
df_var['var_{}'.format(i)] = list_var[i]
df_var['var_{}'.format(i)] = list_var[i]
tam_train = int(len(df_var)*0.7)
#print tam_train
df_train = df_var[:tam_train]
print('Tamanio train: {}'.format(df_train.shape))
df_test = df_var[tam_train:]
print('Tamanio test: {}'.format(df_test.shape))
lags = int(round(len(df_test)/2))
model = pf.VAR(df_train,lags=lags)
x = model.fit()
#model.plot_z(list(range(0,6)),figsize=(15,5))
#model.plot_fit(figsize=(8,5))
#model.plot_predict_is(h=90, figsize=((8,5)))
#model.plot_predict(past_values=len(df_train), h=len(df_test), figsize=(8,5))
future_forecast_pred = model.predict(len(df_test))
future_forecast_pred = future_forecast_pred[['var_0']]
list_test = df_test['var_0'].values
list_future_forecast_pred = future_forecast_pred['var_0'].values
#mse_test = (list_future_forecast_pred - list_test)
#mse_abs_test = abs(mse_test)
mse = mean_squared_error(list_test, list_future_forecast_pred)
print('El error medio del modelo_test es: {}'.format(mse))
rmse = np.sqrt(mse)
print('El root error medio del modelo_test es: {}'.format(rmse))
mae = mean_absolute_error(list_test, list_future_forecast_pred)
df_aler = pd.DataFrame()
df_aler['real_value'] = list_test
df_aler['expected value'] = list_future_forecast_pred
df_aler['mse'] = mse
df_aler['puntos'] = future_forecast_pred.index
df_aler.set_index('puntos',inplace=True)
df_aler['mae'] = mae
df_aler['anomaly_score'] = abs(df_aler['expected value']-df_aler['real_value'])/df_aler['mae']
df_aler = df_aler[(df_aler['anomaly_score']> 2)]
max = df_aler['anomaly_score'].max()
min = df_aler['anomaly_score'].min()
df_aler['anomaly_score']= ( df_aler['anomaly_score'] - min ) /(max - min)
df_aler_ult = df_aler[:5]
df_aler_ult = df_aler_ult[(df_aler_ult.index==df_aler.index.max())|(df_aler_ult.index==((df_aler.index.max())-1))
|(df_aler_ult.index==((df_aler.index.max())-2))|(df_aler_ult.index==((df_aler.index.max())-3))
|(df_aler_ult.index==((df_aler.index.max())-4))]
if len(df_aler_ult) == 0:
exists_anom_last_5 = 'FALSE'
else:
exists_anom_last_5 = 'TRUE'
max = df_aler_ult['anomaly_score'].max()
min = df_aler_ult['anomaly_score'].min()
print df_aler_ult
df_aler_ult['anomaly_score'] = ( df_aler_ult['anomaly_score'] - min ) /(max - min)
#####forecast#####
model_for = pf.VAR(df_var,lags=5)
x_for = model_for.fit()
#model.plot_z(list(range(0,6)),figsize=(15,5))
#model.plot_fit(figsize=(8,5))
future_forecast_pred_for = model_for.predict(5)
future_forecast_pred_for = future_forecast_pred_for[['var_0']]
df_result_forecast = future_forecast_pred_for.reset_index()
df_result_forecast = df_result_forecast.rename(columns = {'index':'step'})
engine_output={}
engine_output['rmse'] = rmse
engine_output['mse'] = mse
engine_output['mae'] = mae
engine_output['present_status']=exists_anom_last_5
engine_output['present_alerts']=df_aler_ult.to_dict(orient='record')
engine_output['past']=df_aler.to_dict(orient='record')
engine_output['engine']='VAR'
engine_output['future']= df_result_forecast.to_dict(orient='record')
engine_output['rmse'] = rmse
engine_output['mse'] = mse
engine_output['mae'] = mae
engine_output['present_status']=exists_anom_last_5
engine_output['present_alerts']=df_aler_ult.to_dict(orient='record')
engine_output['past']=df_aler.to_dict(orient='record')
engine_output['engine']='VAR'
engine_output['future']= df_result_forecast.to_dict(orient='record')
test_values = pd.DataFrame(future_forecast_pred.values,index = df_test.index,columns=['expected value'])
test_values['step'] = test_values.index
engine_output['debug'] = test_values.to_dict(orient='record')
return (engine_output)
| 35.896396
| 123
| 0.665454
| 1,182
| 7,969
| 4.134518
| 0.098139
| 0.100675
| 0.05709
| 0.044199
| 0.913035
| 0.902189
| 0.892368
| 0.889503
| 0.835482
| 0.818703
| 0
| 0.012573
| 0.181579
| 7,969
| 221
| 124
| 36.058824
| 0.736737
| 0.089723
| 0
| 0.774648
| 0
| 0
| 0.13872
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | null | 0
| 0.035211
| null | null | 0.084507
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 8
|
4994c16664ef399bdc559cd12507cc70d032d9ef
| 20,954
|
py
|
Python
|
simple_history/tests/tests/test_commands.py
|
rdurica/django-simple-history
|
84d17f40be68e9ac7744b773451be83720c4c13a
|
[
"BSD-3-Clause"
] | 911
|
2015-01-05T13:21:17.000Z
|
2020-06-07T07:11:53.000Z
|
simple_history/tests/tests/test_commands.py
|
rdurica/django-simple-history
|
84d17f40be68e9ac7744b773451be83720c4c13a
|
[
"BSD-3-Clause"
] | 492
|
2015-01-01T18:20:20.000Z
|
2020-06-06T17:34:01.000Z
|
simple_history/tests/tests/test_commands.py
|
rdurica/django-simple-history
|
84d17f40be68e9ac7744b773451be83720c4c13a
|
[
"BSD-3-Clause"
] | 307
|
2015-02-01T00:45:51.000Z
|
2020-06-06T15:39:29.000Z
|
from contextlib import contextmanager
from datetime import datetime, timedelta
from io import StringIO
from django.core import management
from django.test import TestCase
from simple_history import models as sh_models
from simple_history.management.commands import (
clean_duplicate_history,
clean_old_history,
populate_history,
)
from ..models import (
Book,
CustomManagerNameModel,
Place,
Poll,
PollWithExcludeFields,
Restaurant,
)
@contextmanager
def replace_registry(new_value=None):
hidden_registry = sh_models.registered_models
sh_models.registered_models = new_value or {}
try:
yield
except Exception:
raise
finally:
sh_models.registered_models = hidden_registry
class TestPopulateHistory(TestCase):
command_name = "populate_history"
command_error = (management.CommandError, SystemExit)
def test_no_args(self):
out = StringIO()
management.call_command(self.command_name, stdout=out, stderr=StringIO())
self.assertIn(populate_history.Command.COMMAND_HINT, out.getvalue())
def test_bad_args(self):
test_data = (
(populate_history.Command.MODEL_NOT_HISTORICAL, ("tests.place",)),
(populate_history.Command.MODEL_NOT_FOUND, ("invalid.model",)),
(populate_history.Command.MODEL_NOT_FOUND, ("bad_key",)),
)
for msg, args in test_data:
out = StringIO()
self.assertRaises(
self.command_error,
management.call_command,
self.command_name,
*args,
stdout=StringIO(),
stderr=out,
)
self.assertIn(msg, out.getvalue())
def test_auto_populate(self):
Poll.objects.create(question="Will this populate?", pub_date=datetime.now())
Poll.history.all().delete()
management.call_command(
self.command_name, auto=True, stdout=StringIO(), stderr=StringIO()
)
self.assertEqual(Poll.history.all().count(), 1)
def test_populate_with_custom_batch_size(self):
Poll.objects.create(question="Will this populate?", pub_date=datetime.now())
Poll.history.all().delete()
management.call_command(
self.command_name,
auto=True,
batchsize=500,
stdout=StringIO(),
stderr=StringIO(),
)
self.assertEqual(Poll.history.all().count(), 1)
def test_specific_populate(self):
Poll.objects.create(question="Will this populate?", pub_date=datetime.now())
Poll.history.all().delete()
Book.objects.create(isbn="9780007117116")
Book.history.all().delete()
management.call_command(
self.command_name, "tests.book", stdout=StringIO(), stderr=StringIO()
)
self.assertEqual(Book.history.all().count(), 1)
self.assertEqual(Poll.history.all().count(), 0)
def test_failing_wont_save(self):
Poll.objects.create(question="Will this populate?", pub_date=datetime.now())
Poll.history.all().delete()
self.assertRaises(
self.command_error,
management.call_command,
self.command_name,
"tests.poll",
"tests.invalid_model",
stdout=StringIO(),
stderr=StringIO(),
)
self.assertEqual(Poll.history.all().count(), 0)
def test_multi_table(self):
data = {"rating": 5, "name": "Tea 'N More"}
Restaurant.objects.create(**data)
Restaurant.updates.all().delete()
management.call_command(
self.command_name, "tests.restaurant", stdout=StringIO(), stderr=StringIO()
)
update_record = Restaurant.updates.all()[0]
for attr, value in data.items():
self.assertEqual(getattr(update_record, attr), value)
def test_existing_objects(self):
data = {"rating": 5, "name": "Tea 'N More"}
out = StringIO()
Restaurant.objects.create(**data)
pre_call_count = Restaurant.updates.count()
management.call_command(
self.command_name, "tests.restaurant", stdout=StringIO(), stderr=out
)
self.assertEqual(Restaurant.updates.count(), pre_call_count)
self.assertIn(populate_history.Command.EXISTING_HISTORY_FOUND, out.getvalue())
def test_no_historical(self):
out = StringIO()
with replace_registry({"test_place": Place}):
management.call_command(self.command_name, auto=True, stdout=out)
self.assertIn(populate_history.Command.NO_REGISTERED_MODELS, out.getvalue())
def test_batch_processing_with_batch_size_less_than_total(self):
data = [
Poll(id=1, question="Question 1", pub_date=datetime.now()),
Poll(id=2, question="Question 2", pub_date=datetime.now()),
Poll(id=3, question="Question 3", pub_date=datetime.now()),
Poll(id=4, question="Question 4", pub_date=datetime.now()),
]
Poll.objects.bulk_create(data)
management.call_command(
self.command_name,
auto=True,
batchsize=3,
stdout=StringIO(),
stderr=StringIO(),
)
self.assertEqual(Poll.history.count(), 4)
def test_stdout_not_printed_when_verbosity_is_0(self):
out = StringIO()
Poll.objects.create(question="Question 1", pub_date=datetime.now())
management.call_command(
self.command_name,
auto=True,
batchsize=3,
stdout=out,
stderr=StringIO(),
verbosity=0,
)
self.assertEqual(out.getvalue(), "")
def test_stdout_printed_when_verbosity_is_not_specified(self):
out = StringIO()
Poll.objects.create(question="Question 1", pub_date=datetime.now())
management.call_command(
self.command_name, auto=True, batchsize=3, stdout=out, stderr=StringIO()
)
self.assertNotEqual(out.getvalue(), "")
def test_excluded_fields(self):
poll = PollWithExcludeFields.objects.create(
question="Will this work?", pub_date=datetime.now()
)
PollWithExcludeFields.history.all().delete()
management.call_command(
self.command_name,
"tests.pollwithexcludefields",
auto=True,
stdout=StringIO(),
stderr=StringIO(),
)
initial_history_record = PollWithExcludeFields.history.all()[0]
self.assertEqual(initial_history_record.question, poll.question)
class TestCleanDuplicateHistory(TestCase):
command_name = "clean_duplicate_history"
command_error = (management.CommandError, SystemExit)
def test_no_args(self):
out = StringIO()
management.call_command(self.command_name, stdout=out, stderr=StringIO())
self.assertIn(clean_duplicate_history.Command.COMMAND_HINT, out.getvalue())
def test_bad_args(self):
test_data = (
(clean_duplicate_history.Command.MODEL_NOT_HISTORICAL, ("tests.place",)),
(clean_duplicate_history.Command.MODEL_NOT_FOUND, ("invalid.model",)),
(clean_duplicate_history.Command.MODEL_NOT_FOUND, ("bad_key",)),
)
for msg, args in test_data:
out = StringIO()
self.assertRaises(
self.command_error,
management.call_command,
self.command_name,
*args,
stdout=StringIO(),
stderr=out,
)
self.assertIn(msg, out.getvalue())
def test_no_historical(self):
out = StringIO()
with replace_registry({"test_place": Place}):
management.call_command(self.command_name, auto=True, stdout=out)
self.assertIn(
clean_duplicate_history.Command.NO_REGISTERED_MODELS, out.getvalue()
)
def test_auto_dry_run(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
p.save()
# not related to dry_run test, just for increasing coverage :)
# create instance with single-entry history older than "minutes"
# so it is skipped
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
h = p.history.first()
h.history_date -= timedelta(hours=1)
h.save()
self.assertEqual(Poll.history.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name,
auto=True,
minutes=50,
dry=True,
stdout=out,
stderr=StringIO(),
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 3)
def test_auto_cleanup(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
self.assertEqual(Poll.history.all().count(), 2)
p.question = "Maybe this one won't...?"
p.save()
self.assertEqual(Poll.history.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name, auto=True, stdout=out, stderr=StringIO()
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 2)
def test_auto_cleanup_verbose(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
p.question = "Maybe this one won't...?"
p.save()
self.assertEqual(Poll.history.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name,
"tests.poll",
auto=True,
verbosity=2,
stdout=out,
stderr=StringIO(),
)
self.assertEqual(
out.getvalue(),
"<class 'simple_history.tests.models.Poll'> has 3 historical entries\n"
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 2)
def test_auto_cleanup_dated(self):
the_time_is_now = datetime.now()
p = Poll.objects.create(
question="Will this be deleted?", pub_date=the_time_is_now
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 3)
p.question = "Or this one...?"
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 5)
for h in Poll.history.all()[2:]:
h.history_date -= timedelta(hours=1)
h.save()
management.call_command(
self.command_name,
auto=True,
minutes=50,
stdout=StringIO(),
stderr=StringIO(),
)
self.assertEqual(Poll.history.all().count(), 4)
def test_auto_cleanup_dated_extra_one(self):
the_time_is_now = datetime.now()
p = Poll.objects.create(
question="Will this be deleted?", pub_date=the_time_is_now
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 3)
p.question = "Or this one...?"
p.save()
p.save()
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 7)
for h in Poll.history.all()[2:]:
h.history_date -= timedelta(hours=1)
h.save()
management.call_command(
self.command_name,
auto=True,
minutes=50,
stdout=StringIO(),
stderr=StringIO(),
)
# even though only the last 2 entries match the date range
# the "extra_one" (the record before the oldest match)
# is identical to the oldest match, so oldest match is deleted
self.assertEqual(Poll.history.all().count(), 5)
def test_auto_cleanup_custom_history_field(self):
m = CustomManagerNameModel.objects.create(name="John")
self.assertEqual(CustomManagerNameModel.log.all().count(), 1)
m.save()
self.assertEqual(CustomManagerNameModel.log.all().count(), 2)
m.name = "Ivan"
m.save()
self.assertEqual(CustomManagerNameModel.log.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name, auto=True, stdout=out, stderr=StringIO()
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.CustomManagerNameModel'>\n",
)
self.assertEqual(CustomManagerNameModel.log.all().count(), 2)
def test_auto_cleanup_with_excluded_fields(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
self.assertEqual(Poll.history.all().count(), 1)
p.pub_date = p.pub_date + timedelta(days=1)
p.save()
self.assertEqual(Poll.history.all().count(), 2)
out = StringIO()
management.call_command(
self.command_name,
auto=True,
excluded_fields=("pub_date",),
stdout=out,
stderr=StringIO(),
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 1)
class TestCleanOldHistory(TestCase):
command_name = "clean_old_history"
command_error = (management.CommandError, SystemExit)
def test_no_args(self):
out = StringIO()
management.call_command(self.command_name, stdout=out, stderr=StringIO())
self.assertIn(clean_old_history.Command.COMMAND_HINT, out.getvalue())
def test_bad_args(self):
test_data = (
(clean_old_history.Command.MODEL_NOT_HISTORICAL, ("tests.place",)),
(clean_old_history.Command.MODEL_NOT_FOUND, ("invalid.model",)),
(clean_old_history.Command.MODEL_NOT_FOUND, ("bad_key",)),
)
for msg, args in test_data:
out = StringIO()
self.assertRaises(
self.command_error,
management.call_command,
self.command_name,
*args,
stdout=StringIO(),
stderr=out,
)
self.assertIn(msg, out.getvalue())
def test_no_historical(self):
out = StringIO()
with replace_registry({"test_place": Place}):
management.call_command(self.command_name, auto=True, stdout=out)
self.assertIn(clean_old_history.Command.NO_REGISTERED_MODELS, out.getvalue())
def test_auto_dry_run(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
p.save()
# not related to dry_run test, just for increasing coverage :)
# create instance with single-entry history older than "minutes"
# so it is skipped
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
h = p.history.first()
h.history_date -= timedelta(days=31)
h.save()
self.assertEqual(Poll.history.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name,
auto=True,
days=20,
dry=True,
stdout=out,
stderr=StringIO(),
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 3)
def test_auto_cleanup(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
self.assertEqual(Poll.history.all().count(), 2)
p.question = "Maybe this one won't...?"
p.save()
self.assertEqual(Poll.history.all().count(), 3)
out = StringIO()
h = p.history.first()
h.history_date -= timedelta(days=40)
h.save()
management.call_command(
self.command_name, auto=True, stdout=out, stderr=StringIO()
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 2)
def test_auto_cleanup_verbose(self):
p = Poll.objects.create(
question="Will this be deleted?", pub_date=datetime.now()
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
p.question = "Maybe this one won't...?"
p.save()
h = p.history.first()
h.history_date -= timedelta(days=40)
h.save()
self.assertEqual(Poll.history.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name,
"tests.poll",
auto=True,
verbosity=2,
stdout=out,
stderr=StringIO(),
)
self.assertEqual(
out.getvalue(),
"<class 'simple_history.tests.models.Poll'> has 1 old historical entries\n"
"Removed 1 historical records for "
"<class 'simple_history.tests.models.Poll'>\n",
)
self.assertEqual(Poll.history.all().count(), 2)
def test_auto_cleanup_dated(self):
the_time_is_now = datetime.now()
p = Poll.objects.create(
question="Will this be deleted?", pub_date=the_time_is_now
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 3)
p.question = "Or this one...?"
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 5)
for h in Poll.history.all()[2:]:
h.history_date -= timedelta(days=30)
h.save()
management.call_command(
self.command_name,
auto=True,
days=20,
stdout=StringIO(),
stderr=StringIO(),
)
self.assertEqual(Poll.history.all().count(), 2)
def test_auto_cleanup_dated_extra_one(self):
the_time_is_now = datetime.now()
p = Poll.objects.create(
question="Will this be deleted?", pub_date=the_time_is_now
)
self.assertEqual(Poll.history.all().count(), 1)
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 3)
p.question = "Or this one...?"
p.save()
p.save()
p.save()
p.save()
self.assertEqual(Poll.history.all().count(), 7)
for h in Poll.history.all()[2:]:
h.history_date -= timedelta(days=30)
h.save()
management.call_command(
self.command_name,
auto=True,
days=20,
stdout=StringIO(),
stderr=StringIO(),
)
# We will remove the 3 ones that we are marking as old
self.assertEqual(Poll.history.all().count(), 2)
def test_auto_cleanup_custom_history_field(self):
m = CustomManagerNameModel.objects.create(name="John")
self.assertEqual(CustomManagerNameModel.log.all().count(), 1)
m.save()
self.assertEqual(CustomManagerNameModel.log.all().count(), 2)
m.name = "Ivan"
m.save()
h = m.log.first()
h.history_date -= timedelta(days=40)
h.save()
self.assertEqual(CustomManagerNameModel.log.all().count(), 3)
out = StringIO()
management.call_command(
self.command_name, auto=True, stdout=out, stderr=StringIO()
)
self.assertEqual(
out.getvalue(),
"Removed 1 historical records for "
"<class 'simple_history.tests.models.CustomManagerNameModel'>\n",
)
self.assertEqual(CustomManagerNameModel.log.all().count(), 2)
| 34.182708
| 87
| 0.5849
| 2,316
| 20,954
| 5.136442
| 0.086356
| 0.080699
| 0.057666
| 0.091796
| 0.838013
| 0.827589
| 0.812038
| 0.79573
| 0.770595
| 0.76034
| 0
| 0.008979
| 0.293071
| 20,954
| 612
| 88
| 34.238562
| 0.7941
| 0.0241
| 0
| 0.710575
| 0
| 0
| 0.089392
| 0.023926
| 0
| 0
| 0
| 0
| 0.146568
| 1
| 0.061224
| false
| 0
| 0.014842
| 0
| 0.092764
| 0.003711
| 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
|
b8cf79e7f412d2373a77240f0f0459387f104160
| 26,072
|
py
|
Python
|
nn_trainer/models/networks/networks_2d.py
|
nabrooks/nn-trainer
|
bb58e2cb50d65c682820fb598c4eedb8413aaf77
|
[
"MIT"
] | null | null | null |
nn_trainer/models/networks/networks_2d.py
|
nabrooks/nn-trainer
|
bb58e2cb50d65c682820fb598c4eedb8413aaf77
|
[
"MIT"
] | null | null | null |
nn_trainer/models/networks/networks_2d.py
|
nabrooks/nn-trainer
|
bb58e2cb50d65c682820fb598c4eedb8413aaf77
|
[
"MIT"
] | null | null | null |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
def init_weights(net, init_type='normal', gain=0.02):
def init_func(m):
classname = m.__class__.__name__
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
if init_type == 'normal':
init.normal_(m.weight.data, 0.0, gain)
elif init_type == 'xavier':
init.xavier_normal_(m.weight.data, gain=gain)
elif init_type == 'kaiming':
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
elif init_type == 'orthogonal':
init.orthogonal_(m.weight.data, gain=gain)
else:
raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
if hasattr(m, 'bias') and m.bias is not None:
init.constant_(m.bias.data, 0.0)
elif classname.find('BatchNorm2d') != -1:
init.normal_(m.weight.data, 1.0, gain)
init.constant_(m.bias.data, 0.0)
print('initialize network with %s' % init_type)
net.apply(init_func)
class conv_block(nn.Module):
def __init__(self,ch_in,ch_out):
super(conv_block,self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(ch_in, ch_out, kernel_size=3,stride=1,padding=1,bias=True),
nn.BatchNorm2d(ch_out),
nn.ReLU(inplace=True),
nn.Conv2d(ch_out, ch_out, kernel_size=3,stride=1,padding=1,bias=True),
nn.BatchNorm2d(ch_out),
nn.ReLU(inplace=True)
)
def forward(self,x):
x = self.conv(x)
return x
class up_conv(nn.Module):
def __init__(self,ch_in,ch_out):
super(up_conv,self).__init__()
self.up = nn.Sequential(
nn.Upsample(scale_factor=2),
nn.Conv2d(ch_in,ch_out,kernel_size=3,stride=1,padding=1,bias=True),
nn.BatchNorm2d(ch_out),
nn.ReLU(inplace=True)
)
def forward(self,x):
x = self.up(x)
return x
class Recurrent_block(nn.Module):
def __init__(self,ch_out,t=2):
super(Recurrent_block,self).__init__()
self.t = t
self.ch_out = ch_out
self.conv = nn.Sequential(
nn.Conv2d(ch_out,ch_out,kernel_size=3,stride=1,padding=1,bias=True),
nn.BatchNorm2d(ch_out),
nn.ReLU(inplace=True)
)
def forward(self,x):
for i in range(self.t):
if i==0:
x1 = self.conv(x)
x1 = self.conv(x+x1)
return x1
class RRCNN_block(nn.Module):
def __init__(self,ch_in,ch_out,t=2):
super(RRCNN_block,self).__init__()
self.RCNN = nn.Sequential(
Recurrent_block(ch_out,t=t),
Recurrent_block(ch_out,t=t)
)
self.Conv_1x1 = nn.Conv2d(ch_in,ch_out,kernel_size=1,stride=1,padding=0)
def forward(self,x):
x = self.Conv_1x1(x)
x1 = self.RCNN(x)
return x+x1
class single_conv(nn.Module):
def __init__(self,ch_in,ch_out):
super(single_conv,self).__init__()
self.conv = nn.Sequential(
nn.Conv2d(ch_in, ch_out, kernel_size=3,stride=1,padding=1,bias=True),
nn.BatchNorm2d(ch_out),
nn.ReLU(inplace=True)
)
def forward(self,x):
x = self.conv(x)
return x
class Attention_block(nn.Module):
def __init__(self,F_g,F_l,F_int):
super(Attention_block,self).__init__()
self.W_g = nn.Sequential(
nn.Conv2d(F_g, F_int, kernel_size=1,stride=1,padding=0,bias=True),
nn.BatchNorm2d(F_int)
)
self.W_x = nn.Sequential(
nn.Conv2d(F_l, F_int, kernel_size=1,stride=1,padding=0,bias=True),
nn.BatchNorm2d(F_int)
)
self.psi = nn.Sequential(
nn.Conv2d(F_int, 1, kernel_size=1,stride=1,padding=0,bias=True),
nn.BatchNorm2d(1),
nn.Sigmoid()
)
self.relu = nn.ReLU(inplace=True)
def forward(self,g,x):
g1 = self.W_g(g)
x1 = self.W_x(x)
psi = self.relu(g1+x1)
psi = self.psi(psi)
return x*psi
class U_Net_2D(nn.Module):
def __init__(self,img_ch=3,output_ch=1):
super(U_Net_2D,self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
self.Conv4 = conv_block(ch_in=256,ch_out=512)
self.Conv5 = conv_block(ch_in=512,ch_out=1024)
self.Up5 = up_conv(ch_in=1024,ch_out=512)
self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self, x):
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
x4 = self.Maxpool(x3)
x4 = self.Conv4(x4)
x5 = self.Maxpool(x4)
x5 = self.Conv5(x5)
# decoding + concat path
d5 = self.Up5(x5)
d5 = torch.cat((x4, d5), dim=1)
d5 = self.Up_conv5(d5)
d4 = self.Up4(d5)
d4 = torch.cat((x3, d4), dim=1)
d4 = self.Up_conv4(d4)
d3 = self.Up3(d4)
d3 = torch.cat((x2, d3), dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1, d2), dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return d1
class U_Net_2D_Mod(nn.Module):
def __init__(self,img_ch=3,output_ch=1):
super(U_Net_2D_Mod,self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
self.Conv4 = conv_block(ch_in=256,ch_out=512)
#self.Conv5 = conv_block(ch_in=512,ch_out=1024)
#self.Up5 = up_conv(ch_in=1024,ch_out=512)
#self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self, x):
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
x4 = self.Maxpool(x3)
x4 = self.Conv4(x4)
# decoding + concat path
#d5 = self.Up5(x5)
#d5 = torch.cat((x4, d5), dim=1)
#d5 = self.Up_conv5(d5)
d4 = self.Up4(x4)
d4 = torch.cat((x3, d4), dim=1)
d4 = self.Up_conv4(d4)
d3 = self.Up3(d4)
d3 = torch.cat((x2, d3), dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1, d2), dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return d1
class U_Net_2D_Mod_2(nn.Module):
def __init__(self,img_ch=3,output_ch=1):
super(U_Net_2D_Mod_2, self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
#self.Conv4 = conv_block(ch_in=256,ch_out=512)
#self.Conv5 = conv_block(ch_in=512,ch_out=1024)
#self.Up5 = up_conv(ch_in=1024,ch_out=512)
#self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
#self.Up4 = up_conv(ch_in=512,ch_out=256)
#self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self, x):
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
#x4 = self.Maxpool(x3)
#x4 = self.Conv4(x4)
# decoding + concat path
#d5 = self.Up5(x5)
#d5 = torch.cat((x4, d5), dim=1)
#d5 = self.Up_conv5(d5)
#d4 = self.Up4(x4)
#d4 = torch.cat((x3, d4), dim=1)
#d4 = self.Up_conv4(d4)
d3 = self.Up3(x3)
d3 = torch.cat((x2, d3), dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1, d2), dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return d1
class U_Net_2D_Mod_Critic(nn.Module):
def __init__(self, img_width, img_height, img_ch=1, is_sigmoid_out=False):
super(U_Net_2D_Mod_Critic,self).__init__()
self.img_width = img_width
self.img_height = img_height
self.img_ch = img_ch
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
self.Conv4 = conv_block(ch_in=256,ch_out=512)
#self.Conv5 = conv_block(ch_in=512,ch_out=1024)
#self.Up5 = up_conv(ch_in=1024,ch_out=512)
#self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64, 1,kernel_size=1,stride=1,padding=0)
self.fc1 = nn.Linear(img_height * img_width, 1)
if is_sigmoid_out:
self.sig_out = nn.Sigmoid()
def forward(self, output, input):
x = torch.cat([output, input], axis=1)
batch_size = x.shape[0]
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
x4 = self.Maxpool(x3)
x4 = self.Conv4(x4)
# decoding + concat path
#d5 = self.Up5(x5)
#d5 = torch.cat((x4, d5), dim=1)
#d5 = self.Up_conv5(d5)
d4 = self.Up4(x4)
d4 = torch.cat((x3, d4), dim=1)
d4 = self.Up_conv4(d4)
d3 = self.Up3(d4)
d3 = torch.cat((x2, d3), dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1, d2), dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
d1 = d1.view(batch_size, 1, self.img_width * self.img_height)
d1 = self.fc1(d1)
return d1
class U_Net_2D_Mod_2_Critic(nn.Module):
def __init__(self, img_width, img_height, img_ch=1, is_sigmoid_out=False):
super(U_Net_2D_Mod_2_Critic,self).__init__()
self.img_width = img_width
self.img_height = img_height
self.img_ch = img_ch
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
#self.Conv4 = conv_block(ch_in=256,ch_out=512)
#self.Conv5 = conv_block(ch_in=512,ch_out=1024)
#self.Up5 = up_conv(ch_in=1024,ch_out=512)
#self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
#self.Up4 = up_conv(ch_in=512,ch_out=256)
#self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64, 1,kernel_size=1,stride=1,padding=0)
self.fc1 = nn.Linear(img_height * img_width, 1)
if is_sigmoid_out:
self.sig_out = nn.Sigmoid()
def forward(self, output, input):
x = torch.cat([output, input], axis=1)
batch_size = x.shape[0]
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
#x4 = self.Maxpool(x3)
#x4 = self.Conv4(x4)
# decoding + concat path
#d5 = self.Up5(x5)
#d5 = torch.cat((x4, d5), dim=1)
#d5 = self.Up_conv5(d5)
#d4 = self.Up4(x4)
#d4 = torch.cat((x3, d4), dim=1)
#d4 = self.Up_conv4(d4)
d3 = self.Up3(x3)
d3 = torch.cat((x2, d3), dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1, d2), dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
d1 = d1.view(batch_size, 1, self.img_width * self.img_height)
d1 = self.fc1(d1)
return d1
class R2U_Net_2D(nn.Module):
def __init__(self,img_ch=3,output_ch=1,t=2):
super(R2U_Net_2D,self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Upsample = nn.Upsample(scale_factor=2)
self.RRCNN1 = RRCNN_block(ch_in=img_ch,ch_out=64,t=t)
self.RRCNN2 = RRCNN_block(ch_in=64,ch_out=128,t=t)
self.RRCNN3 = RRCNN_block(ch_in=128,ch_out=256,t=t)
self.RRCNN4 = RRCNN_block(ch_in=256,ch_out=512,t=t)
self.RRCNN5 = RRCNN_block(ch_in=512,ch_out=1024,t=t)
self.Up5 = up_conv(ch_in=1024,ch_out=512)
self.Up_RRCNN5 = RRCNN_block(ch_in=1024, ch_out=512,t=t)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Up_RRCNN4 = RRCNN_block(ch_in=512, ch_out=256,t=t)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_RRCNN3 = RRCNN_block(ch_in=256, ch_out=128,t=t)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_RRCNN2 = RRCNN_block(ch_in=128, ch_out=64,t=t)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self,x):
# encoding path
x1 = self.RRCNN1(x)
x2 = self.Maxpool(x1)
x2 = self.RRCNN2(x2)
x3 = self.Maxpool(x2)
x3 = self.RRCNN3(x3)
x4 = self.Maxpool(x3)
x4 = self.RRCNN4(x4)
x5 = self.Maxpool(x4)
x5 = self.RRCNN5(x5)
# decoding + concat path
d5 = self.Up5(x5)
d5 = torch.cat((x4,d5),dim=1)
d5 = self.Up_RRCNN5(d5)
d4 = self.Up4(d5)
d4 = torch.cat((x3,d4),dim=1)
d4 = self.Up_RRCNN4(d4)
d3 = self.Up3(d4)
d3 = torch.cat((x2,d3),dim=1)
d3 = self.Up_RRCNN3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1,d2),dim=1)
d2 = self.Up_RRCNN2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return d1
class AttU_Net_2D(nn.Module):
def __init__(self,img_ch=3,output_ch=1):
super(AttU_Net_2D,self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
self.Conv4 = conv_block(ch_in=256,ch_out=512)
self.Conv5 = conv_block(ch_in=512,ch_out=1024)
self.Up5 = up_conv(ch_in=1024,ch_out=512)
self.Att5 = Attention_block(F_g=512,F_l=512,F_int=256)
self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Att4 = Attention_block(F_g=256,F_l=256,F_int=128)
self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Att3 = Attention_block(F_g=128,F_l=128,F_int=64)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Att2 = Attention_block(F_g=64,F_l=64,F_int=32)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self,x):
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
x4 = self.Maxpool(x3)
x4 = self.Conv4(x4)
x5 = self.Maxpool(x4)
x5 = self.Conv5(x5)
# decoding + concat path
d5 = self.Up5(x5)
x4 = self.Att5(g=d5,x=x4)
d5 = torch.cat((x4,d5),dim=1)
d5 = self.Up_conv5(d5)
d4 = self.Up4(d5)
x3 = self.Att4(g=d4,x=x3)
d4 = torch.cat((x3,d4),dim=1)
d4 = self.Up_conv4(d4)
d3 = self.Up3(d4)
x2 = self.Att3(g=d3,x=x2)
d3 = torch.cat((x2,d3),dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
x1 = self.Att2(g=d2,x=x1)
d2 = torch.cat((x1,d2),dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return d1
class R2AttU_Net_2D(nn.Module):
def __init__(self,img_ch=3,output_ch=1,t=2):
super(R2AttU_Net_2D,self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Upsample = nn.Upsample(scale_factor=2)
self.RRCNN1 = RRCNN_block(ch_in=img_ch,ch_out=64,t=t)
self.RRCNN2 = RRCNN_block(ch_in=64,ch_out=128,t=t)
self.RRCNN3 = RRCNN_block(ch_in=128,ch_out=256,t=t)
self.RRCNN4 = RRCNN_block(ch_in=256,ch_out=512,t=t)
self.RRCNN5 = RRCNN_block(ch_in=512,ch_out=1024,t=t)
self.Up5 = up_conv(ch_in=1024,ch_out=512)
self.Att5 = Attention_block(F_g=512,F_l=512,F_int=256)
self.Up_RRCNN5 = RRCNN_block(ch_in=1024, ch_out=512,t=t)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Att4 = Attention_block(F_g=256,F_l=256,F_int=128)
self.Up_RRCNN4 = RRCNN_block(ch_in=512, ch_out=256,t=t)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Att3 = Attention_block(F_g=128,F_l=128,F_int=64)
self.Up_RRCNN3 = RRCNN_block(ch_in=256, ch_out=128,t=t)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Att2 = Attention_block(F_g=64,F_l=64,F_int=32)
self.Up_RRCNN2 = RRCNN_block(ch_in=128, ch_out=64,t=t)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self,x):
# encoding path
x1 = self.RRCNN1(x)
x2 = self.Maxpool(x1)
x2 = self.RRCNN2(x2)
x3 = self.Maxpool(x2)
x3 = self.RRCNN3(x3)
x4 = self.Maxpool(x3)
x4 = self.RRCNN4(x4)
x5 = self.Maxpool(x4)
x5 = self.RRCNN5(x5)
# decoding + concat path
d5 = self.Up5(x5)
x4 = self.Att5(g=d5,x=x4)
d5 = torch.cat((x4,d5),dim=1)
d5 = self.Up_RRCNN5(d5)
d4 = self.Up4(d5)
x3 = self.Att4(g=d4,x=x3)
d4 = torch.cat((x3,d4),dim=1)
d4 = self.Up_RRCNN4(d4)
d3 = self.Up3(d4)
x2 = self.Att3(g=d3,x=x2)
d3 = torch.cat((x2,d3),dim=1)
d3 = self.Up_RRCNN3(d3)
d2 = self.Up2(d3)
x1 = self.Att2(g=d2,x=x1)
d2 = torch.cat((x1,d2),dim=1)
d2 = self.Up_RRCNN2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return 1D
class R2AttU_Net_2D_Mod(nn.Module):
def __init__(self,img_ch=3,output_ch=1,t=2):
super(R2AttU_Net_2D_Mod,self).__init__()
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Upsample = nn.Upsample(scale_factor=2)
self.RRCNN1 = RRCNN_block(ch_in=img_ch,ch_out=64,t=t)
self.RRCNN2 = RRCNN_block(ch_in=64,ch_out=128,t=t)
self.RRCNN3 = RRCNN_block(ch_in=128,ch_out=256,t=t)
self.RRCNN4 = RRCNN_block(ch_in=256,ch_out=512,t=t)
#self.RRCNN5 = RRCNN_block(ch_in=512,ch_out=1024,t=t)
#self.Up5 = up_conv(ch_in=1024,ch_out=512)
#self.Att5 = Attention_block(F_g=512,F_l=512,F_int=256)
#self.Up_RRCNN5 = RRCNN_block(ch_in=1024, ch_out=512,t=t)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Att4 = Attention_block(F_g=256,F_l=256,F_int=128)
self.Up_RRCNN4 = RRCNN_block(ch_in=512, ch_out=256,t=t)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Att3 = Attention_block(F_g=128,F_l=128,F_int=64)
self.Up_RRCNN3 = RRCNN_block(ch_in=256, ch_out=128,t=t)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Att2 = Attention_block(F_g=64,F_l=64,F_int=32)
self.Up_RRCNN2 = RRCNN_block(ch_in=128, ch_out=64,t=t)
self.Conv_1x1 = nn.Conv2d(64,output_ch,kernel_size=1,stride=1,padding=0)
def forward(self,x):
# encoding path
x1 = self.RRCNN1(x)
x2 = self.Maxpool(x1)
x2 = self.RRCNN2(x2)
x3 = self.Maxpool(x2)
x3 = self.RRCNN3(x3)
x4 = self.Maxpool(x3)
x4 = self.RRCNN4(x4)
#x5 = self.Maxpool(x4)
#x5 = self.RRCNN5(x5)
# decoding + concat path
#d5 = self.Up5(x5)
#x4 = self.Att5(g=d5,x=x4)
#d5 = torch.cat((x4,d5),dim=1)
#d5 = self.Up_RRCNN5(d5)
d4 = self.Up4(x4)
x3 = self.Att4(g=d4,x=x3)
d4 = torch.cat((x3,d4),dim=1)
d4 = self.Up_RRCNN4(d4)
d3 = self.Up3(d4)
x2 = self.Att3(g=d3,x=x2)
d3 = torch.cat((x2,d3),dim=1)
d3 = self.Up_RRCNN3(d3)
d2 = self.Up2(d3)
x1 = self.Att2(g=d2,x=x1)
d2 = torch.cat((x1,d2),dim=1)
d2 = self.Up_RRCNN2(d2)
d1 = self.Conv_1x1(d2)
return torch.tanh(d1)
#return 1D
class U_Net_Critic_2D(nn.Module):
def __init__(self, img_width, img_height, img_ch=1, is_sigmoid_out=False):
super(U_Net_Critic_2D,self).__init__()
self.img_width = img_width
self.img_height = img_height
self.img_ch = img_ch
self.Maxpool = nn.MaxPool2d(kernel_size=2,stride=2)
self.Conv1 = conv_block(ch_in=img_ch,ch_out=64)
self.Conv2 = conv_block(ch_in=64,ch_out=128)
self.Conv3 = conv_block(ch_in=128,ch_out=256)
self.Conv4 = conv_block(ch_in=256,ch_out=512)
self.Conv5 = conv_block(ch_in=512,ch_out=1024)
self.Up5 = up_conv(ch_in=1024,ch_out=512)
self.Up_conv5 = conv_block(ch_in=1024, ch_out=512)
self.Up4 = up_conv(ch_in=512,ch_out=256)
self.Up_conv4 = conv_block(ch_in=512, ch_out=256)
self.Up3 = up_conv(ch_in=256,ch_out=128)
self.Up_conv3 = conv_block(ch_in=256, ch_out=128)
self.Up2 = up_conv(ch_in=128,ch_out=64)
self.Up_conv2 = conv_block(ch_in=128, ch_out=64)
self.Conv_1x1 = nn.Conv2d(64, 1,kernel_size=1,stride=1,padding=0)
self.fc1 = nn.Linear(img_height * img_width, 1)
if is_sigmoid_out:
self.sig_out = nn.Sigmoid()
def forward(self, output, input):
x = torch.cat([output, input], axis=1)
batch_size = x.shape[0]
# encoding path
x1 = self.Conv1(x)
x2 = self.Maxpool(x1)
x2 = self.Conv2(x2)
x3 = self.Maxpool(x2)
x3 = self.Conv3(x3)
x4 = self.Maxpool(x3)
x4 = self.Conv4(x4)
x5 = self.Maxpool(x4)
x5 = self.Conv5(x5)
# decoding + concat path
d5 = self.Up5(x5)
d5 = torch.cat((x4, d5), dim=1)
d5 = self.Up_conv5(d5)
d4 = self.Up4(d5)
d4 = torch.cat((x3, d4), dim=1)
d4 = self.Up_conv4(d4)
d3 = self.Up3(d4)
d3 = torch.cat((x2, d3), dim=1)
d3 = self.Up_conv3(d3)
d2 = self.Up2(d3)
d2 = torch.cat((x1, d2), dim=1)
d2 = self.Up_conv2(d2)
d1 = self.Conv_1x1(d2)
d1 = d1.view(batch_size, 1, self.img_width * self.img_height)
d1 = self.fc1(d1)
return d1
return #torch.tanh(d1)
# ==================== test =========================================
def test():
img_width = 16
img_height = 320
v0 = torch.ones((1, 1, int(img_height/2), img_width), dtype=torch.float32).to('cuda:0')
v1 = torch.zeros((1, 1, int(img_height/2), img_width), dtype=torch.float32).to('cuda:0')
v = torch.cat([v0, v1], axis=2)
gm = U_Net_2D(1, 1).to('cuda:0')
dm = U_Net_Critic_2D(img_width, img_height).to('cuda:0')
o = gm(v)
f = dm(o)
print(o.shape)
print(f.shape)
import matplotlib
import matplotlib.pyplot as plt
import torchvision
v_new = torchvision.transforms.F.affine(v, angle=0, translate=(0,0), scale=1, shear=(0, -10))
v = v.cpu()
v_new = v_new.cpu()
plt.imshow(v[0,0,:,:])
plt.show()
plt.imshow(v_new[0,0,:,:])
plt.show()
| 29.627273
| 102
| 0.571034
| 4,246
| 26,072
| 3.281441
| 0.044748
| 0.054547
| 0.058135
| 0.058781
| 0.904902
| 0.889973
| 0.885236
| 0.874686
| 0.873394
| 0.872605
| 0
| 0.107769
| 0.288547
| 26,072
| 879
| 103
| 29.660978
| 0.643377
| 0.083154
| 0
| 0.783784
| 0
| 0
| 0.00701
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.063063
| false
| 0
| 0.012613
| 0
| 0.135135
| 0.005405
| 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
|
7719faa0527fcb7a3bcaaf5d27805dbecb213f99
| 6,308
|
py
|
Python
|
cogs/nsfw.py
|
KittyKart/EpicBot
|
c92e05548cf26dbecbf1a87bec4e409c0cf34e22
|
[
"MIT"
] | 1
|
2021-03-19T04:27:17.000Z
|
2021-03-19T04:27:17.000Z
|
cogs/nsfw.py
|
imkrvishal/EpicBot
|
40be2f456905c18a2f25a7b7f4d8d071fac8e5c6
|
[
"MIT"
] | null | null | null |
cogs/nsfw.py
|
imkrvishal/EpicBot
|
40be2f456905c18a2f25a7b7f4d8d071fac8e5c6
|
[
"MIT"
] | null | null | null |
import discord
import requests
import datetime
from discord.ext.commands import cooldown, BucketType
from discord.ext.commands import (CommandOnCooldown)
from discord.ext import commands
class NSFW(commands.Cog):
def __init__(self, client):
self.client = client
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def hentai(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://shiro.gg/api/images/nsfw/hentai")
realResponse = response.json()
embed = discord.Embed(
title = "There you go!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def cum(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://nekos.life/api/v2/img/cum")
realResponse = response.json()
embed = discord.Embed(
title = "There you go!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def thighs(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://shiro.gg/api/images/nsfw/thighs")
realResponse = response.json()
embed = discord.Embed(
title = "Thighs!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def nekogif(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://nekos.life/api/v2/img/nsfw_neko_gif")
realResponse = response.json()
embed = discord.Embed(
title = "Gifs!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def boobs(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://nekos.life/api/v2/img/boobs")
realResponse = response.json()
embed = discord.Embed(
title = "boooooobs!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def blowjob(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://nekos.life/api/v2/img/blowjob")
realResponse = response.json()
embed = discord.Embed(
title = "Yummy!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def pussy(self, ctx):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
response = requests.get("https://nekos.life/api/v2/img/pussy")
realResponse = response.json()
embed = discord.Embed(
title = "Yummy!",
color = 0xFFC0CB
)
embed.set_image(url = realResponse['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
@commands.cooldown(1, 5, commands.BucketType.user)
@commands.command()
async def spank(self, ctx, user: discord.Member = None):
if ctx.channel.id == 768722875972452352:
await ctx.send("No.")
return
if ctx.channel.is_nsfw():
if user == None:
await ctx.message.reply("Who do you want to spank? Mention them next time idiot.")
return
if user == ctx.author:
await ctx.message.reply("How lonely are you? Don't spank yourself!")
return
response = requests.get("https://nekos.life/api/v2/img/spank").json()
embed = discord.Embed(
title = "Damn!",
description = f"{user.mention} got spanked by {ctx.author.mention}",
color = 0xFFC0CB
)
embed.set_image(url = response['url'])
await ctx.message.reply(embed = embed)
else:
await ctx.message.reply("This command can only be used in a NSFW channel.")
def setup(client):
client.add_cog(NSFW(client))
| 32.854167
| 98
| 0.559131
| 705
| 6,308
| 4.970213
| 0.147518
| 0.059361
| 0.077055
| 0.10274
| 0.843893
| 0.820491
| 0.812215
| 0.772831
| 0.772831
| 0.76113
| 0
| 0.042935
| 0.327996
| 6,308
| 191
| 99
| 33.026178
| 0.783675
| 0
| 0
| 0.705882
| 0
| 0
| 0.148859
| 0
| 0
| 0
| 0.010146
| 0
| 0
| 1
| 0.013072
| false
| 0
| 0.039216
| 0
| 0.124183
| 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
|
621fa4fd6c77128b4efab15903ce6e446ef82f41
| 6,006
|
py
|
Python
|
tests/test_multiprocess.py
|
tanbro/sqlalchemy-dlock
|
9deadeb89f90d2a7512e9de8b038e0261604ba20
|
[
"BSD-3-Clause"
] | null | null | null |
tests/test_multiprocess.py
|
tanbro/sqlalchemy-dlock
|
9deadeb89f90d2a7512e9de8b038e0261604ba20
|
[
"BSD-3-Clause"
] | 2
|
2022-03-14T08:56:06.000Z
|
2022-03-23T06:57:03.000Z
|
tests/test_multiprocess.py
|
tanbro/sqlalchemy-dlock
|
9deadeb89f90d2a7512e9de8b038e0261604ba20
|
[
"BSD-3-Clause"
] | null | null | null |
from contextlib import closing
from multiprocessing import Barrier, Process
from time import sleep, time
from unittest import TestCase
from uuid import uuid4
from sqlalchemy_dlock import sadlock
from .engines import ENGINES
class MultiProcessTestCase(TestCase):
def test_non_blocking_success(self):
key = uuid4().hex
for i in range(len(ENGINES)):
bar = Barrier(2)
def fn1(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with sadlock(conn, key) as lock:
self.assertTrue(lock.acquired)
self.assertFalse(lock.acquired)
b.wait()
def fn2(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with closing(sadlock(conn, key)) as lock:
b.wait()
self.assertTrue(lock.acquire(False))
p1 = Process(target=fn1, args=(i, bar))
p2 = Process(target=fn2, args=(i, bar))
p1.start()
p2.start()
p1.join()
p2.join()
self.assertEqual(p1.exitcode, 0)
self.assertEqual(p2.exitcode, 0)
def test_non_blocking_fail(self):
key = uuid4().hex
delay = 1
for i in range(len(ENGINES)):
bar = Barrier(2)
def fn1(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with sadlock(conn, key) as lock:
self.assertTrue(lock.acquired)
b.wait()
sleep(delay)
self.assertTrue(lock.acquired)
self.assertFalse(lock.acquired)
def fn2(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with closing(sadlock(conn, key)) as lock:
b.wait()
self.assertFalse(lock.acquire(False))
p1 = Process(target=fn1, args=(i, bar))
p2 = Process(target=fn2, args=(i, bar))
p1.start()
p2.start()
p1.join()
p2.join()
self.assertEqual(p1.exitcode, 0)
self.assertEqual(p2.exitcode, 0)
def test_timeout_success(self):
key = uuid4().hex
delay = 1
timeout = 3
for i in range(len(ENGINES)):
bar = Barrier(2)
def fn1(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with sadlock(conn, key) as lock:
self.assertTrue(lock.acquired)
b.wait()
sleep(delay)
self.assertTrue(lock.acquired)
self.assertFalse(lock.acquired)
def fn2(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with closing(sadlock(conn, key)) as lock:
b.wait()
ts = time()
self.assertTrue(lock.acquire(timeout=timeout))
self.assertGreaterEqual(time() - ts, delay)
self.assertGreaterEqual(timeout, time() - ts)
self.assertTrue(lock.acquired)
p1 = Process(target=fn1, args=(i, bar))
p2 = Process(target=fn2, args=(i, bar))
p1.start()
p2.start()
p1.join()
p2.join()
self.assertEqual(p1.exitcode, 0)
self.assertEqual(p2.exitcode, 0)
def test_timeout_fail(self):
key = uuid4().hex
delay = 3
timeout = 1
for i in range(len(ENGINES)):
bar = Barrier(2)
def fn1(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with sadlock(conn, key) as lock:
self.assertTrue(lock.acquired)
b.wait()
sleep(delay)
self.assertTrue(lock.acquired)
self.assertFalse(lock.acquired)
def fn2(engine_index, b):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with closing(sadlock(conn, key)) as lock:
b.wait()
ts = time()
self.assertFalse(lock.acquire(timeout=timeout))
self.assertGreaterEqual(time() - ts, timeout)
self.assertFalse(lock.acquired)
p1 = Process(target=fn1, args=(i, bar))
p2 = Process(target=fn2, args=(i, bar))
p1.start()
p2.start()
p1.join()
p2.join()
self.assertEqual(p1.exitcode, 0)
self.assertEqual(p2.exitcode, 0)
def test_release_omitted(self):
key = uuid4().hex
for i in range(len(ENGINES)):
def fn1(engine_index):
engine = ENGINES[engine_index]
lock = sadlock(engine.connect(), key)
self.assertTrue(lock.acquire(False))
def fn2(engine_index):
engine = ENGINES[engine_index]
with engine.connect() as conn:
with closing(sadlock(conn, key)) as lock:
self.assertTrue(lock.acquire(False))
p1 = Process(target=fn1, args=(i,))
p2 = Process(target=fn2, args=(i,))
p1.start()
p1.join()
p2.start()
p2.join()
self.assertEqual(p1.exitcode, 0)
self.assertEqual(p2.exitcode, 0)
| 32.117647
| 71
| 0.482184
| 608
| 6,006
| 4.708882
| 0.111842
| 0.076842
| 0.075445
| 0.083828
| 0.841425
| 0.826057
| 0.777855
| 0.777855
| 0.731401
| 0.731401
| 0
| 0.024404
| 0.42008
| 6,006
| 186
| 72
| 32.290323
| 0.797588
| 0
| 0
| 0.815068
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.219178
| 1
| 0.10274
| false
| 0
| 0.047945
| 0
| 0.157534
| 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
|
6255acc743608c154fa956d49e078a60f63fe515
| 6,678
|
py
|
Python
|
Chapter 3/3.4_3.5_3.6_3.7.py
|
adrian88szymanski/Python_Crash_Course_Eric_Matthes
|
74e9a627e3e044ea30e4a8579843d95fe8e4fc14
|
[
"MIT"
] | 8
|
2021-07-21T02:52:49.000Z
|
2022-02-08T20:47:09.000Z
|
Chapter 3/3.4_3.5_3.6_3.7.py
|
barbarian47/Python_Crash_Course_Eric_Matthes
|
74e9a627e3e044ea30e4a8579843d95fe8e4fc14
|
[
"MIT"
] | null | null | null |
Chapter 3/3.4_3.5_3.6_3.7.py
|
barbarian47/Python_Crash_Course_Eric_Matthes
|
74e9a627e3e044ea30e4a8579843d95fe8e4fc14
|
[
"MIT"
] | 7
|
2021-06-10T12:27:56.000Z
|
2022-01-29T13:53:15.000Z
|
#! python3
print("3.4")
names = ['Albert Einstein', 'Julius Cesar', 'Winston Churchill', 'Peter Parker', 'John Snow']
print("I want to invite you to dinner ", names[0])
print("I want to invite you to dinner ", names[1])
print("I want to invite you to dinner ", names[2])
print("I want to invite you to dinner ", names[3])
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
msg = "I want to invite you to dinner "
print(msg, names[0])
print("3.5")
names = ['Albert Einstein', 'Julius Cesar', 'Winston Churchill', 'Peter Parker', 'John Snow']
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("John Snow is unable to come to dinner.")
unable_come = 'John Snow'
names.remove(unable_come)
print(names)
names.append('Stephen Hawking')
print(names)
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("3.6")
names = ['Albert Einstein', 'Julius Cesar', 'Winston Churchill', 'Peter Parker', 'John Snow']
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("John Snow is unable to come to dinner.")
unable_come = 'John Snow'
names.remove(unable_come)
print(names)
names.append('Stephen Hawking')
print(names)
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("\nI found a big table\t")
names.insert(0, 'Harry Potter')
names.insert(2, 'Elon Musk')
names.append('Platon')
print("\n")
print(names)
print("\n")
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[5], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[6], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[7], ".", "Please send me a reply if you come.")
print("3.7")
names = ['Albert Einstein', 'Julius Cesar', 'Winston Churchill', 'Peter Parker', 'John Snow']
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("John Snow is unable to come to dinner.")
unable_come = 'John Snow'
names.remove(unable_come)
print(names)
names.append('Stephen Hawking')
print(names)
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("\nI found a big table\t")
names.insert(0, 'Harry Potter')
names.insert(2, 'Elon Musk')
names.append('Platon')
print("\n")
print(names)
print("\n")
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[2], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[3], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[4], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[5], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[6], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[7], ".", "Please send me a reply if you come.")
print("\n")
remove_person = names.pop()
names.pop()
print("Sorry ", remove_person, ".", "I can't invite you because my table has only two seats.")
print(names)
print("\n")
remove_person = names.pop()
names.pop()
print("Sorry ", remove_person, ".", "I can't invite you because my table has only two seats.")
print(names)
print("\n")
remove_person = names.pop()
names.pop()
print("Sorry ", remove_person, ".", "I can't invite you because my table has only two seats.")
print(names)
print("\n")
print("I want to invite you to dinner ", names[0], ".", "Please send me a reply if you come.")
print("I want to invite you to dinner ", names[1], ".", "Please send me a reply if you come.")
del names[0]
del names[0]
print(names)
| 54.737705
| 94
| 0.666667
| 1,206
| 6,678
| 3.681592
| 0.053068
| 0.115541
| 0.085135
| 0.158108
| 0.984685
| 0.984685
| 0.984685
| 0.979279
| 0.979279
| 0.979279
| 0
| 0.012459
| 0.17071
| 6,678
| 122
| 95
| 54.737705
| 0.789274
| 0.001348
| 0
| 0.912281
| 0
| 0
| 0.62948
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0
| 0
| 0
| 0.754386
| 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
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
|
0
| 9
|
626f0558ed069d28753468e1498837d3da45f902
| 2,674
|
py
|
Python
|
src/graph_transpiler/webdnn/backend/fallback/kernels/__init__.py
|
urantialife/webdnn
|
dedc5da424288594cdfa605a015ddc7a3afcf2b7
|
[
"MIT"
] | 1
|
2021-04-09T15:55:35.000Z
|
2021-04-09T15:55:35.000Z
|
src/graph_transpiler/webdnn/backend/fallback/kernels/__init__.py
|
urantialife/webdnn
|
dedc5da424288594cdfa605a015ddc7a3afcf2b7
|
[
"MIT"
] | null | null | null |
src/graph_transpiler/webdnn/backend/fallback/kernels/__init__.py
|
urantialife/webdnn
|
dedc5da424288594cdfa605a015ddc7a3afcf2b7
|
[
"MIT"
] | null | null | null |
from webdnn.backend.fallback.kernels import abs
from webdnn.backend.fallback.kernels import acos
from webdnn.backend.fallback.kernels import acosh
from webdnn.backend.fallback.kernels import asin
from webdnn.backend.fallback.kernels import asinh
from webdnn.backend.fallback.kernels import atan
from webdnn.backend.fallback.kernels import atanh
from webdnn.backend.fallback.kernels import average_pooling_2d
from webdnn.backend.fallback.kernels import broadcast
from webdnn.backend.fallback.kernels import clipped_relu
from webdnn.backend.fallback.kernels import concat
from webdnn.backend.fallback.kernels import convolution_2d
from webdnn.backend.fallback.kernels import cos
from webdnn.backend.fallback.kernels import cosh
from webdnn.backend.fallback.kernels import elementwise
from webdnn.backend.fallback.kernels import elementwise_add
from webdnn.backend.fallback.kernels import elementwise_div
from webdnn.backend.fallback.kernels import elementwise_mul
from webdnn.backend.fallback.kernels import elementwise_pow
from webdnn.backend.fallback.kernels import elu
from webdnn.backend.fallback.kernels import exp
from webdnn.backend.fallback.kernels import greater
from webdnn.backend.fallback.kernels import greater_equal
from webdnn.backend.fallback.kernels import hard_sigmoid
from webdnn.backend.fallback.kernels import leaky_relu
from webdnn.backend.fallback.kernels import linear
from webdnn.backend.fallback.kernels import local_response_normalization
from webdnn.backend.fallback.kernels import log
from webdnn.backend.fallback.kernels import max_pooling_2d
from webdnn.backend.fallback.kernels import normalize
from webdnn.backend.fallback.kernels import reinterpret_axis
from webdnn.backend.fallback.kernels import relu
from webdnn.backend.fallback.kernels import reshape
from webdnn.backend.fallback.kernels import rsqrt
from webdnn.backend.fallback.kernels import scalar_add
from webdnn.backend.fallback.kernels import scalar_mul
from webdnn.backend.fallback.kernels import scalar_pow
from webdnn.backend.fallback.kernels import select
from webdnn.backend.fallback.kernels import sigmoid
from webdnn.backend.fallback.kernels import sin
from webdnn.backend.fallback.kernels import sinh
from webdnn.backend.fallback.kernels import softmax
from webdnn.backend.fallback.kernels import softplus
from webdnn.backend.fallback.kernels import softsign
from webdnn.backend.fallback.kernels import split_axis
from webdnn.backend.fallback.kernels import sqrt
from webdnn.backend.fallback.kernels import tan
from webdnn.backend.fallback.kernels import tanh
from webdnn.backend.fallback.kernels import tensordot
from webdnn.backend.fallback.kernels import threshold_relu
| 52.431373
| 72
| 0.86911
| 371
| 2,674
| 6.207547
| 0.15903
| 0.217108
| 0.369084
| 0.54277
| 0.894051
| 0.894051
| 0.432045
| 0.040816
| 0
| 0
| 0
| 0.001213
| 0.074794
| 2,674
| 50
| 73
| 53.48
| 0.929669
| 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
| 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
|
628a39ba151ef5fdf59496c02e3adaf9b42c51a7
| 159
|
py
|
Python
|
pdip/cqrs/generator/domain/generator.py
|
ahmetcagriakca/pdip
|
c4c16d5666a740154cabdc6762cd44d98b7bdde8
|
[
"MIT"
] | 2
|
2021-12-09T21:07:46.000Z
|
2021-12-11T22:18:01.000Z
|
pdip/cqrs/generator/domain/generator.py
|
fmuyilmaz/pdip
|
f7e30b0c04d9e85ef46b0b7094fafd3ce18bccab
|
[
"MIT"
] | null | null | null |
pdip/cqrs/generator/domain/generator.py
|
fmuyilmaz/pdip
|
f7e30b0c04d9e85ef46b0b7094fafd3ce18bccab
|
[
"MIT"
] | 3
|
2021-11-15T00:47:00.000Z
|
2021-12-17T11:35:45.000Z
|
from abc import ABC
from .generate_config import GenerateConfig
class Generator(ABC):
def generate(self, generate_config: GenerateConfig):
pass
| 17.666667
| 56
| 0.754717
| 19
| 159
| 6.210526
| 0.578947
| 0.237288
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.188679
| 159
| 8
| 57
| 19.875
| 0.914729
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.2
| false
| 0.2
| 0.4
| 0
| 0.8
| 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
| 1
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 1
| 0
|
0
| 7
|
628a7ba2b65be7e61942cb27d81ea7aa096e49fb
| 15,045
|
py
|
Python
|
artikcloud/apis/registrations_api.py
|
artikcloud/artikcloud-python-dev
|
683cd8304f031913bcd581d1eb78ee0efbc5c113
|
[
"Apache-2.0"
] | null | null | null |
artikcloud/apis/registrations_api.py
|
artikcloud/artikcloud-python-dev
|
683cd8304f031913bcd581d1eb78ee0efbc5c113
|
[
"Apache-2.0"
] | null | null | null |
artikcloud/apis/registrations_api.py
|
artikcloud/artikcloud-python-dev
|
683cd8304f031913bcd581d1eb78ee0efbc5c113
|
[
"Apache-2.0"
] | null | null | null |
# coding: utf-8
"""
ARTIK Cloud API
No descripton provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
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.
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class RegistrationsApi(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 confirm_user(self, registration_info, **kwargs):
"""
Confirm User
This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device.
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.confirm_user(registration_info, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param DeviceRegConfirmUserRequest registration_info: Device Registration information. (required)
:return: DeviceRegConfirmUserResponseEnvelope
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.confirm_user_with_http_info(registration_info, **kwargs)
else:
(data) = self.confirm_user_with_http_info(registration_info, **kwargs)
return data
def confirm_user_with_http_info(self, registration_info, **kwargs):
"""
Confirm User
This call updates the registration request issued earlier by associating it with an authenticated user and captures all additional information required to add a new device.
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.confirm_user_with_http_info(registration_info, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param DeviceRegConfirmUserRequest registration_info: Device Registration information. (required)
:return: DeviceRegConfirmUserResponseEnvelope
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['registration_info']
all_params.append('callback')
all_params.append('_return_http_data_only')
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 confirm_user" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'registration_info' is set
if ('registration_info' not in params) or (params['registration_info'] is None):
raise ValueError("Missing the required parameter `registration_info` when calling `confirm_user`")
resource_path = '/devices/registrations/pin'.replace('{format}', 'json')
path_params = {}
query_params = {}
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'registration_info' in params:
body_params = params['registration_info']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type([])
# Authentication setting
auth_settings = ['artikcloud_oauth']
return self.api_client.call_api(resource_path, 'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='DeviceRegConfirmUserResponseEnvelope',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def get_request_status_for_user(self, request_id, **kwargs):
"""
Get Request Status For User
This call checks the status of the request so users can poll and know when registration is complete.
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_request_status_for_user(request_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str request_id: Request ID. (required)
:return: DeviceRegStatusResponseEnvelope
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.get_request_status_for_user_with_http_info(request_id, **kwargs)
else:
(data) = self.get_request_status_for_user_with_http_info(request_id, **kwargs)
return data
def get_request_status_for_user_with_http_info(self, request_id, **kwargs):
"""
Get Request Status For User
This call checks the status of the request so users can poll and know when registration is complete.
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_request_status_for_user_with_http_info(request_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str request_id: Request ID. (required)
:return: DeviceRegStatusResponseEnvelope
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['request_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
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_request_status_for_user" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'request_id' is set
if ('request_id' not in params) or (params['request_id'] is None):
raise ValueError("Missing the required parameter `request_id` when calling `get_request_status_for_user`")
resource_path = '/devices/registrations/{requestId}/status'.replace('{format}', 'json')
path_params = {}
if 'request_id' in params:
path_params['requestId'] = params['request_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'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type([])
# Authentication setting
auth_settings = ['artikcloud_oauth']
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='DeviceRegStatusResponseEnvelope',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
def unregister_device(self, device_id, **kwargs):
"""
Unregister Device
This call clears any associations from the secure device registration.
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.unregister_device(device_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str device_id: Device ID. (required)
:return: UnregisterDeviceResponseEnvelope
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.unregister_device_with_http_info(device_id, **kwargs)
else:
(data) = self.unregister_device_with_http_info(device_id, **kwargs)
return data
def unregister_device_with_http_info(self, device_id, **kwargs):
"""
Unregister Device
This call clears any associations from the secure device registration.
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.unregister_device_with_http_info(device_id, callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:param str device_id: Device ID. (required)
:return: UnregisterDeviceResponseEnvelope
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['device_id']
all_params.append('callback')
all_params.append('_return_http_data_only')
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 unregister_device" % key
)
params[key] = val
del params['kwargs']
# verify the required parameter 'device_id' is set
if ('device_id' not in params) or (params['device_id'] is None):
raise ValueError("Missing the required parameter `device_id` when calling `unregister_device`")
resource_path = '/devices/{deviceId}/registrations'.replace('{format}', 'json')
path_params = {}
if 'device_id' in params:
path_params['deviceId'] = params['device_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'])
if not header_params['Accept']:
del header_params['Accept']
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type([])
# Authentication setting
auth_settings = ['artikcloud_oauth']
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='UnregisterDeviceResponseEnvelope',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'))
| 41.219178
| 180
| 0.597607
| 1,566
| 15,045
| 5.532567
| 0.144955
| 0.055402
| 0.018006
| 0.024931
| 0.834257
| 0.789243
| 0.773546
| 0.757618
| 0.748038
| 0.715489
| 0
| 0.00099
| 0.328681
| 15,045
| 364
| 181
| 41.332418
| 0.856832
| 0.384447
| 0
| 0.650307
| 1
| 0
| 0.165369
| 0.054245
| 0
| 0
| 0
| 0
| 0
| 1
| 0.042945
| false
| 0
| 0.042945
| 0
| 0.147239
| 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
|
6585d0c84f9437285a9d3bea5db514b1a57dbede
| 5,354
|
py
|
Python
|
pymtl3_net/mmxbar/test/adapters_test.py
|
cornell-brg/ocn-posh
|
7f8bfd800627364cfc37dc5d6a36333ee2e48c99
|
[
"BSD-3-Clause"
] | 3
|
2019-06-07T13:27:06.000Z
|
2019-07-16T19:00:23.000Z
|
pymtl3_net/mmxbar/test/adapters_test.py
|
cornell-brg/ocn-posh
|
7f8bfd800627364cfc37dc5d6a36333ee2e48c99
|
[
"BSD-3-Clause"
] | 12
|
2019-07-23T02:29:31.000Z
|
2019-07-25T11:07:00.000Z
|
pymtl3_net/mmxbar/test/adapters_test.py
|
cornell-brg/posh-ocn
|
7f8bfd800627364cfc37dc5d6a36333ee2e48c99
|
[
"BSD-3-Clause"
] | null | null | null |
'''
==========================================================================
adapters_test.py
==========================================================================
Unit tests for network adapters.
Author : Yanghui Ou
Date : Apr 14, 2020
'''
from pymtl3 import *
from pymtl3.stdlib.mem import mk_mem_msg, MemMsgType
from ..adapters import ReqAdapter, RespAdapter
#-------------------------------------------------------------------------
# constants
#-------------------------------------------------------------------------
Req, Resp = mk_mem_msg( 8, 32, 32 )
rd = MemMsgType.READ
wr = MemMsgType.WRITE
#-------------------------------------------------------------------------
# test case: req sanity check
#-------------------------------------------------------------------------
def test_req_sanity_check():
dut = ReqAdapter( Req, Resp, id=0, num_requesters=4, num_responders=1,
max_req_in_flight=8 )
dut.elaborate()
dut.apply( DefaultPassGroup(linetrace=True) )
dut.sim_reset()
dut.sim_tick()
dut.sim_tick()
#-------------------------------------------------------------------------
# test case: resp sanity check
#-------------------------------------------------------------------------
def test_resp_sanity_check():
dut = RespAdapter( Req, Resp, id=0, num_requesters=4, num_responders=1 )
dut.elaborate()
dut.apply( DefaultPassGroup(linetrace=True) )
dut.sim_reset()
dut.sim_tick()
dut.sim_tick()
#-------------------------------------------------------------------------
# test case: req adhoc
#-------------------------------------------------------------------------
def test_req_adhoc():
dut = ReqAdapter( Req, Resp, id=2, num_requesters=16, num_responders=1,
max_req_in_flight=16 )
print()
dut.elaborate()
dut.apply( DefaultPassGroup(linetrace=True) )
dut.minion.resp.rdy @= b1(1)
dut.master.req.rdy @= b1(1)
dut.sim_reset()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.sim_eval_combinational()
dut.print_line_trace()
# cycle 3
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(1)
dut.minion.req.msg @= Req( rd, 0xa0, 0x1000, 0, 0 )
dut.sim_eval_combinational()
dut.print_line_trace()
assert dut.master.req.val
assert dut.master.req.msg.payload.opaque[0:4] == 2
assert dut.master.req.msg.payload.opaque[4:8] == 15
# cycle 4
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(1)
dut.minion.req.msg @= Req( wr, 0xb0, 0x2000, 0, 0xfaceb00c )
dut.sim_eval_combinational()
dut.print_line_trace()
# cycle 5
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(1)
dut.minion.req.msg @= Req( rd, 0xc0, 0x3000, 0, 0 )
dut.sim_eval_combinational()
dut.print_line_trace()
# cycle 6
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(0)
dut.sim_eval_combinational()
dut.print_line_trace()
# cycle 7
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(0)
dut.sim_eval_combinational()
dut.print_line_trace()
# cycle 8
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(0)
dut.master.resp.val @= b1(1)
dut.master.resp.msg.dst @= b4(2)
dut.master.resp.msg.payload @= Resp( wr, 0xe2, 0, 0, 0 )
dut.sim_eval_combinational()
dut.print_line_trace()
assert dut.minion.resp.val
assert dut.minion.resp.msg.opaque == 0xb0
# cycle 9
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(0)
dut.master.resp.val @= b1(0)
dut.sim_eval_combinational()
dut.print_line_trace()
#-------------------------------------------------------------------------
# test case: resp adhoc
#-------------------------------------------------------------------------
def test_resp_adhoc():
dut = RespAdapter( Req, Resp, id=0, num_requesters=16, num_responders=1 )
print()
dut.elaborate()
dut.apply( DefaultPassGroup(linetrace=True) )
dut.minion.resp.rdy @= b1(1)
dut.master.req.rdy @= b1(1)
dut.sim_reset()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.sim_eval_combinational()
dut.print_line_trace()
# cycle 3
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(1)
dut.minion.req.msg.dst @= b1(0)
dut.minion.req.msg.payload @= Req( rd, 0xf2, 0x1000, 0, 0 )
dut.sim_eval_combinational()
dut.print_line_trace()
assert dut.master.req.val
assert dut.master.req.msg == Req( rd, 0xf2, 0x1000, 0, 0 )
# cycle 4
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(0)
dut.master.resp.val @= b1(1)
dut.master.resp.msg @= Resp( rd, 0xf2, 0, 0, 0xfaceb00c )
dut.sim_eval_combinational()
dut.print_line_trace()
assert dut.minion.resp.val
assert dut.minion.resp.msg.dst == 2
assert dut.minion.resp.msg.payload == Resp( rd, 0xf2, 0, 0, 0xfaceb00c )
# cycle 5
dut.sim_tick()
assert dut.minion.req.rdy
assert dut.master.resp.rdy
dut.minion.req.val @= b1(0)
dut.master.resp.val @= b1(0)
dut.sim_eval_combinational()
dut.print_line_trace()
| 23.690265
| 75
| 0.571535
| 722
| 5,354
| 4.106648
| 0.124654
| 0.103204
| 0.109275
| 0.07285
| 0.831366
| 0.812142
| 0.781788
| 0.751771
| 0.73457
| 0.73457
| 0
| 0.034166
| 0.14718
| 5,354
| 225
| 76
| 23.795556
| 0.615199
| 0.217221
| 0
| 0.765625
| 0
| 0
| 0
| 0
| 0
| 0
| 0.023082
| 0
| 0.265625
| 1
| 0.03125
| false
| 0.03125
| 0.023438
| 0
| 0.054688
| 0.109375
| 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
|
658d00bdec83aec5664e06cd1e498c21ab7bc42f
| 1,277
|
py
|
Python
|
local/ctc_token_fst.py
|
mobvoi/lstm_ctc
|
594223fb5bc264ef20b5de645e1c00673758dba5
|
[
"Apache-2.0"
] | 44
|
2019-01-03T01:52:49.000Z
|
2021-10-09T07:48:52.000Z
|
local/ctc_token_fst.py
|
Jhonzhang/lstm_ctc
|
594223fb5bc264ef20b5de645e1c00673758dba5
|
[
"Apache-2.0"
] | null | null | null |
local/ctc_token_fst.py
|
Jhonzhang/lstm_ctc
|
594223fb5bc264ef20b5de645e1c00673758dba5
|
[
"Apache-2.0"
] | 19
|
2019-02-13T02:53:00.000Z
|
2021-05-26T14:34:39.000Z
|
#!/usr/bin/env python
# Apache 2.0
import sys
fread = open(sys.argv[1], 'r')
#print '0 0 <blk> <eps>'
#nodeX = 1
#for entry in fread.readlines():
# entry = entry.replace('\n','').strip()
# fields = entry.split(' ')
# phone = fields[0]
# if phone == '<eps>' or phone == '<blk>':
# continue
#
# if '#' in phone:
# print str(0) + ' ' + str(0) + ' ' + '<eps>' + ' ' + phone;
# else:
# print str(0) + ' ' + str(nodeX) + ' ' + phone + ' ' + phone;
# print str(nodeX) + ' ' + str(nodeX) + ' ' + phone + ' <eps>';
# print str(nodeX) + ' ' + str(0) + ' ' + '<eps> <eps>';
# nodeX += 1
#print '0'
print '0 1 <eps> <eps>'
print '1 1 <blk> <eps>'
print '2 2 <blk> <eps>'
print '2 0 <eps> <eps>'
nodeX = 3
for entry in fread.readlines():
entry = entry.replace('\n','').strip()
fields = entry.split(' ')
phone = fields[0]
if phone == '<eps>' or phone == '<blk>':
continue
if '#' in phone:
print str(0) + ' ' + str(0) + ' ' + '<eps>' + ' ' + phone;
else:
print str(1) + ' ' + str(nodeX) + ' ' + phone + ' ' + phone;
print str(nodeX) + ' ' + str(nodeX) + ' ' + phone + ' <eps>';
print str(nodeX) + ' ' + str(2) + ' ' + '<eps> <eps>';
nodeX += 1
print '0'
fread.close()
| 25.54
| 69
| 0.46437
| 164
| 1,277
| 3.615854
| 0.213415
| 0.107926
| 0.08769
| 0.107926
| 0.762226
| 0.762226
| 0.701518
| 0.701518
| 0.701518
| 0.701518
| 0
| 0.031974
| 0.289742
| 1,277
| 49
| 70
| 26.061224
| 0.62183
| 0.436962
| 0
| 0
| 0
| 0
| 0.154506
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | null | 0
| 0.045455
| null | null | 0.409091
| 0
| 0
| 0
| null | 0
| 0
| 0
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 1
|
0
| 7
|
659358da79c8dc23baeed3ef9991aa626c4f5a09
| 165
|
py
|
Python
|
api/namex/resources/auto_analyse/paths/bc_name_analysis/issues/end_designation_more_than_once.py
|
sumesh-aot/namex
|
53e11aed5ea550b71b7b983f1b57b65db5a06766
|
[
"Apache-2.0"
] | 1
|
2020-02-21T05:49:14.000Z
|
2020-02-21T05:49:14.000Z
|
api/namex/resources/auto_analyse/paths/bc_name_analysis/issues/end_designation_more_than_once.py
|
sumesh-aot/namex
|
53e11aed5ea550b71b7b983f1b57b65db5a06766
|
[
"Apache-2.0"
] | null | null | null |
api/namex/resources/auto_analyse/paths/bc_name_analysis/issues/end_designation_more_than_once.py
|
sumesh-aot/namex
|
53e11aed5ea550b71b7b983f1b57b65db5a06766
|
[
"Apache-2.0"
] | null | null | null |
from namex.resources.auto_analyse.issues import EndDesignationMoreThanOnceIssue
class BcEndDesignationMoreThanOnceIssue(EndDesignationMoreThanOnceIssue):
pass
| 27.5
| 79
| 0.884848
| 12
| 165
| 12.083333
| 0.916667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.078788
| 165
| 5
| 80
| 33
| 0.953947
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0.333333
| 0.333333
| 0
| 0.666667
| 0
| 1
| 0
| 1
| 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
| 0
| 1
| 1
| 1
| 0
| 1
| 0
|
0
| 7
|
65a0a13f2ad94e31e63e84528a6acf8e6159622d
| 42
|
py
|
Python
|
db/functions/__init__.py
|
laraib-sidd/Prom-Bot
|
104c60ee548c9a9cd758d6a7c70abbfa42321c72
|
[
"MIT"
] | 1
|
2020-08-20T08:54:51.000Z
|
2020-08-20T08:54:51.000Z
|
db/functions/__init__.py
|
laraib-sidd/Prom-Bot
|
104c60ee548c9a9cd758d6a7c70abbfa42321c72
|
[
"MIT"
] | null | null | null |
db/functions/__init__.py
|
laraib-sidd/Prom-Bot
|
104c60ee548c9a9cd758d6a7c70abbfa42321c72
|
[
"MIT"
] | null | null | null |
from . import db_func
from . import lists
| 14
| 21
| 0.761905
| 7
| 42
| 4.428571
| 0.714286
| 0.645161
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.190476
| 42
| 2
| 22
| 21
| 0.911765
| 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
|
65df499dc1b62676664c4781491d14c1a8ff5f75
| 163
|
wsgi
|
Python
|
orion2mysql/server.wsgi
|
fistar-angel/fre_se
|
d626202a94c328b4e0210b57ef1770a86eb6b8b1
|
[
"Apache-2.0"
] | null | null | null |
orion2mysql/server.wsgi
|
fistar-angel/fre_se
|
d626202a94c328b4e0210b57ef1770a86eb6b8b1
|
[
"Apache-2.0"
] | null | null | null |
orion2mysql/server.wsgi
|
fistar-angel/fre_se
|
d626202a94c328b4e0210b57ef1770a86eb6b8b1
|
[
"Apache-2.0"
] | null | null | null |
import sys
#sys.path.insert(0, "/opt/wirecloud_angel/orion2mysql")
sys.path.insert(0, "/opt/fre_package/orion2mysql")
from datahandler import app as application
| 23.285714
| 55
| 0.785276
| 24
| 163
| 5.25
| 0.666667
| 0.111111
| 0.206349
| 0.222222
| 0.269841
| 0
| 0
| 0
| 0
| 0
| 0
| 0.026846
| 0.08589
| 163
| 6
| 56
| 27.166667
| 0.818792
| 0.331288
| 0
| 0
| 0
| 0
| 0.261682
| 0.261682
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0.666667
| 0
| 0.666667
| 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
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 7
|
0297006f5ce43c66b70f83625a730aae249735bc
| 122
|
py
|
Python
|
ir_sim/env/__init__.py
|
hanruihua/intelligent-robot-simulator
|
f77cc3878543f3ff2226408c3369f82771a6f6f9
|
[
"MIT"
] | 11
|
2021-12-10T03:05:01.000Z
|
2022-03-27T12:30:20.000Z
|
ir_sim/env/__init__.py
|
bearswang/intelligent-robot-simulator
|
2fe276a11684f91c917eae58f6de438c69fab9e6
|
[
"MIT"
] | null | null | null |
ir_sim/env/__init__.py
|
bearswang/intelligent-robot-simulator
|
2fe276a11684f91c917eae58f6de438c69fab9e6
|
[
"MIT"
] | 5
|
2021-11-24T13:13:17.000Z
|
2022-03-26T09:46:43.000Z
|
from ir_sim.env.env_base import env_base
from ir_sim.env.env_robot import env_robot
from ir_sim.env.env_car import env_car
| 40.666667
| 42
| 0.860656
| 27
| 122
| 3.555556
| 0.296296
| 0.1875
| 0.28125
| 0.375
| 0.46875
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.090164
| 122
| 3
| 43
| 40.666667
| 0.864865
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 1
| 0
| 1
| 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
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 1
| 0
|
0
| 7
|
02a114ad6edad6ce121b3d887ebad152b7039d2d
| 110
|
py
|
Python
|
polyphony/_internal/_verilog.py
|
ktok07b6/polyphony
|
657c5c7440520db6b4985970bd50547407693ac4
|
[
"MIT"
] | 83
|
2015-11-30T09:59:13.000Z
|
2021-08-03T09:12:28.000Z
|
polyphony/_internal/_verilog.py
|
jesseclin/polyphony
|
657c5c7440520db6b4985970bd50547407693ac4
|
[
"MIT"
] | 4
|
2017-02-10T01:43:11.000Z
|
2020-07-14T03:52:25.000Z
|
polyphony/_internal/_verilog.py
|
jesseclin/polyphony
|
657c5c7440520db6b4985970bd50547407693ac4
|
[
"MIT"
] | 11
|
2016-11-18T14:39:15.000Z
|
2021-02-23T10:05:20.000Z
|
@builtin
def write(fmt:str, *args) -> None:
pass
@builtin
def display(fmt:str, *args) -> None:
pass
| 12.222222
| 36
| 0.618182
| 16
| 110
| 4.25
| 0.5625
| 0.294118
| 0.294118
| 0.411765
| 0.529412
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.218182
| 110
| 8
| 37
| 13.75
| 0.790698
| 0
| 0
| 0.666667
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| false
| 0.333333
| 0
| 0
| 0.333333
| 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
| 1
| 0
| 1
| 0
| 0
| 0
| 0
|
0
| 7
|
02c848669aef406a5d1df66b3fbc55b24400ccf7
| 129
|
py
|
Python
|
api/core/utilities.py
|
sourcery-ai-bot/twitter-clone-server-fastapi
|
5ba34303da6b12b61ecb8c1a712bd1a1c318c4bf
|
[
"MIT"
] | 10
|
2021-06-08T18:35:58.000Z
|
2022-03-26T15:56:26.000Z
|
api/core/utilities.py
|
sourcery-ai-bot/twitter-clone-server-fastapi
|
5ba34303da6b12b61ecb8c1a712bd1a1c318c4bf
|
[
"MIT"
] | 10
|
2021-05-04T04:41:01.000Z
|
2021-07-01T03:37:53.000Z
|
api/core/utilities.py
|
sourcery-ai-bot/twitter-clone-server-fastapi
|
5ba34303da6b12b61ecb8c1a712bd1a1c318c4bf
|
[
"MIT"
] | 5
|
2021-06-14T18:47:56.000Z
|
2022-03-26T15:56:30.000Z
|
import uuid as uuidlib
def generate_random_uuid():
# Generate a UUID as a confirmation key
return str(uuidlib.uuid4())
| 18.428571
| 43
| 0.728682
| 19
| 129
| 4.842105
| 0.684211
| 0.130435
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.009709
| 0.20155
| 129
| 6
| 44
| 21.5
| 0.883495
| 0.286822
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.333333
| true
| 0
| 0.333333
| 0.333333
| 1
| 0
| 1
| 0
| 0
| null | 0
| 0
| 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
| 1
| 0
| 1
| 1
| 1
| 0
|
0
| 8
|
02e4fba2d68c525e0726e27cc63babd07c62676c
| 137
|
py
|
Python
|
IVTp/2014/SOBOLEV_M_V/task_2_24.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
IVTp/2014/SOBOLEV_M_V/task_2_24.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
IVTp/2014/SOBOLEV_M_V/task_2_24.py
|
YukkaSarasti/pythonintask
|
eadf4245abb65f4400a3bae30a4256b4658e009c
|
[
"Apache-2.0"
] | null | null | null |
print('Великое благо, что святые отцы оставили нам своим опытом испытанные советы. Чаще заглядывай в книги. \n\t\t\t Иоанн (Алексеев).')
| 68.5
| 136
| 0.766423
| 22
| 137
| 4.772727
| 0.909091
| 0.038095
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.131387
| 137
| 1
| 137
| 137
| 0.882353
| 0
| 0
| 0
| 0
| 1
| 0.927007
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| true
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 1
| 1
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 1
|
0
| 7
|
f304bfa9320269595d7fd9fc9ebea43cc56dd504
| 1,659
|
py
|
Python
|
AppServer/lib/django-1.2/tests/regressiontests/special_headers/tests.py
|
loftwah/appscale
|
586fc1347ebc743d7a632de698f4dbfb09ae38d6
|
[
"Apache-2.0"
] | 790
|
2015-01-03T02:13:39.000Z
|
2020-05-10T19:53:57.000Z
|
AppServer/lib/django-1.2/tests/regressiontests/special_headers/tests.py
|
nlake44/appscale
|
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
|
[
"Apache-2.0"
] | 1,361
|
2015-01-08T23:09:40.000Z
|
2020-04-14T00:03:04.000Z
|
AppServer/lib/django-1.2/tests/regressiontests/special_headers/tests.py
|
nlake44/appscale
|
6944af660ca4cb772c9b6c2332ab28e5ef4d849f
|
[
"Apache-2.0"
] | 155
|
2015-01-08T22:59:31.000Z
|
2020-04-08T08:01:53.000Z
|
from django.test import TestCase
from django.contrib.auth.models import User
class SpecialHeadersTest(TestCase):
fixtures = ['data.xml']
def test_xheaders(self):
user = User.objects.get(username='super')
response = self.client.get('/special_headers/article/1/')
# import pdb; pdb.set_trace()
self.failUnless('X-Object-Type' not in response)
self.client.login(username='super', password='secret')
response = self.client.get('/special_headers/article/1/')
self.failUnless('X-Object-Type' in response)
user.is_staff = False
user.save()
response = self.client.get('/special_headers/article/1/')
self.failUnless('X-Object-Type' not in response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.get('/special_headers/article/1/')
self.failUnless('X-Object-Type' not in response)
def test_xview(self):
user = User.objects.get(username='super')
response = self.client.head('/special_headers/xview/')
self.failUnless('X-View' not in response)
self.client.login(username='super', password='secret')
response = self.client.head('/special_headers/xview/')
self.failUnless('X-View' in response)
user.is_staff = False
user.save()
response = self.client.head('/special_headers/xview/')
self.failUnless('X-View' not in response)
user.is_staff = True
user.is_active = False
user.save()
response = self.client.head('/special_headers/xview/')
self.failUnless('X-View' not in response)
| 40.463415
| 65
| 0.643159
| 207
| 1,659
| 5.072464
| 0.231884
| 0.114286
| 0.171429
| 0.08
| 0.849524
| 0.849524
| 0.849524
| 0.849524
| 0.801905
| 0.801905
| 0
| 0.003103
| 0.223026
| 1,659
| 40
| 66
| 41.475
| 0.811482
| 0.016275
| 0
| 0.777778
| 0
| 0
| 0.193865
| 0.122699
| 0
| 0
| 0
| 0
| 0
| 1
| 0.055556
| false
| 0.055556
| 0.055556
| 0
| 0.166667
| 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
| 1
| 0
| 0
| 0
| 0
|
0
| 8
|
b85e90f5bbe689906ee844f986eb2f619ec1cd36
| 2,284
|
py
|
Python
|
Deep Learning - Project 2/18L-1879/P2_18L-1879/Pycharm Project/vgga16.py
|
taimurzahid/FASTDeepLearning
|
cfb2417f0bed43838e5c2401105f7f03552c6734
|
[
"MIT"
] | null | null | null |
Deep Learning - Project 2/18L-1879/P2_18L-1879/Pycharm Project/vgga16.py
|
taimurzahid/FASTDeepLearning
|
cfb2417f0bed43838e5c2401105f7f03552c6734
|
[
"MIT"
] | null | null | null |
Deep Learning - Project 2/18L-1879/P2_18L-1879/Pycharm Project/vgga16.py
|
taimurzahid/FASTDeepLearning
|
cfb2417f0bed43838e5c2401105f7f03552c6734
|
[
"MIT"
] | null | null | null |
from keras.models import Sequential
from keras.layers.core import Flatten, Dense, Dropout
from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D
from keras.optimizers import SGD
import cv2, numpy as np
def VGG_16(weights_path=None, input_shape=(256, 256, 3), num_classes = 7):
model = Sequential()
model.add(ZeroPadding2D((1, 1), input_shape=input_shape))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(64, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(128, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(256, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(ZeroPadding2D((1, 1)))
model.add(Convolution2D(512, 3, 3, activation='relu'))
model.add(MaxPooling2D((2, 2), strides=(2, 2)))
model.add(Flatten())
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(4096, activation='relu'))
model.add(Dropout(0.5))
#model.add(Dense(1000, activation='softmax'))
model.add(Dense(num_classes, activation='softmax'))
if weights_path:
model.load_weights(weights_path)
return model
| 39.37931
| 82
| 0.655429
| 308
| 2,284
| 4.827922
| 0.165584
| 0.204438
| 0.191661
| 0.221923
| 0.732347
| 0.71688
| 0.71688
| 0.71688
| 0.71688
| 0.71688
| 0
| 0.08971
| 0.170315
| 2,284
| 57
| 83
| 40.070175
| 0.694987
| 0.019264
| 0
| 0.723404
| 0
| 0
| 0.030706
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.021277
| false
| 0
| 0.106383
| 0
| 0.148936
| 0
| 0
| 0
| 0
| null | 1
| 1
| 1
| 0
| 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
| 9
|
b246484445dec7e9aed6d76d17a95af2e23b1f57
| 12,731
|
py
|
Python
|
unittest/test/cases.py
|
masszhou/spconv_lite
|
16f59cd99a9c360d0cfd47d9f5c1db8033ea3b07
|
[
"Apache-2.0"
] | 22
|
2021-01-21T15:23:30.000Z
|
2022-02-28T13:45:29.000Z
|
unittest/test/cases.py
|
masszhou/spconv_lite
|
16f59cd99a9c360d0cfd47d9f5c1db8033ea3b07
|
[
"Apache-2.0"
] | 1
|
2022-01-12T03:48:47.000Z
|
2022-01-12T03:48:47.000Z
|
unittest/test/cases.py
|
masszhou/spconv_lite
|
16f59cd99a9c360d0cfd47d9f5c1db8033ea3b07
|
[
"Apache-2.0"
] | 6
|
2021-01-23T03:03:06.000Z
|
2022-03-21T13:57:27.000Z
|
# Created by Zhiliang Zhou on 2020
# a simplified version of spconv
#
# original implemented by Yan Yan, https://github.com/traveller59/spconv
# ----------------------------------------------------------------
# Copyright 2019 Yan Yan
#
# 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.
from torch import nn
import spconv_lite as spconv
class Conv3dTestTorch(nn.Module):
def __init__(self,
num_layers,
ndim,
shape,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation):
super().__init__()
layers = [
nn.Conv3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False)
]
for i in range(1, num_layers):
layers.append(
nn.Conv3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False))
self.net = nn.Sequential(*layers, )
self.shape = shape
def forward(self, x):
return self.net(x) # .dense()
class SparseConv3dTestTorch(nn.Module):
def __init__(self,
num_layers,
ndim,
shape,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
algo=spconv.ConvAlgo.Native):
super().__init__()
layers = [
spconv.SparseConv3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False,
use_hash=False,
algo=algo)
]
for i in range(1, num_layers):
layers.append(
spconv.SparseConv3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False,
use_hash=False,
algo=algo))
self.net = spconv.SparseSequential(*layers, )
# self.grid = torch.full([3, *shape], -1, dtype=torch.int32).cuda()
self.grid = None
self.shape = shape
def forward(self, features, coors, batch_size):
coors = coors.int()
x = spconv.SparseConvTensor(features, coors, self.shape, batch_size, self.grid)
return self.net(x) # .dense()
class SubMConv3dTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, in_channels, out_channels, kernel_size, stride, padding, dilation, algo=spconv.ConvAlgo.Native):
super().__init__()
layers = [
spconv.SubMConv3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False,
algo=algo)
]
for i in range(1, num_layers):
layers.append(
spconv.SubMConv3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False,
algo=algo))
self.net = spconv.SparseSequential(*layers, )
# self.grid = torch.full([3, *shape], -1, dtype=torch.int32).cuda()
self.grid = None
self.shape = shape
def forward(self, features, coors, batch_size):
coors = coors.int() # .cpu()
x = spconv.SparseConvTensor(features, coors, self.shape, batch_size, self.grid)
return self.net(x) # .dense()
class SparseDeConv3dTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, in_channels, out_channels, kernel_size, stride, padding, dilation):
super().__init__()
layers = [
spconv.SparseConvTranspose3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False)
]
for i in range(1, num_layers):
layers.append(
spconv.SparseConvTranspose3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False))
self.net = spconv.SparseSequential(*layers, )
self.shape = shape
def forward(self, features, coors, batch_size):
coors = coors.int()
x = spconv.SparseConvTensor(features, coors, self.shape, batch_size)
return self.net(x) # .dense()
class DeConv3dTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, in_channels, out_channels, kernel_size, stride, padding, dilation):
super().__init__()
layers = [
nn.ConvTranspose3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False)
]
for i in range(1, num_layers):
layers.append(
nn.ConvTranspose3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False))
self.net = nn.Sequential(*layers, )
self.shape = shape
def forward(self, x):
return self.net(x) # .dense()
class SparseDeConv3dTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, in_channels, out_channels, kernel_size, stride, padding, dilation):
super().__init__()
layers = [
spconv.SparseConvTranspose3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False)
]
for i in range(1, num_layers):
layers.append(
spconv.SparseConvTranspose3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False))
self.net = spconv.SparseSequential(*layers, )
self.shape = shape
def forward(self, features, coors, batch_size):
coors = coors.int()
x = spconv.SparseConvTensor(features, coors, self.shape, batch_size)
return self.net(x) # .dense()
class DeConv3dTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, in_channels, out_channels, kernel_size, stride, padding, dilation):
super().__init__()
layers = [
nn.ConvTranspose3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False)
]
for i in range(1, num_layers):
layers.append(
nn.ConvTranspose3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False))
self.net = nn.Sequential(*layers, )
self.shape = shape
def forward(self, x):
return self.net(x) # .dense()
class SubMConv3dTestTorch(nn.Module):
def __init__(self,
num_layers,
ndim,
shape,
in_channels,
out_channels,
kernel_size,
stride,
padding,
dilation,
algo=spconv.ConvAlgo.Native):
super().__init__()
layers = [
spconv.SubMConv3d(in_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False,
algo=algo)
]
for i in range(1, num_layers):
layers.append(
spconv.SubMConv3d(out_channels,
out_channels,
kernel_size,
stride,
padding=padding,
dilation=dilation,
bias=False,
algo=algo))
self.net = spconv.SparseSequential(*layers, )
# self.grid = torch.full([3, *shape], -1, dtype=torch.int32).cuda()
self.grid = None
self.shape = shape
def forward(self, features, coors, batch_size):
coors = coors.int() # .cpu()
x = spconv.SparseConvTensor(features, coors, self.shape, batch_size, self.grid)
return self.net(x) # .dense()
class SparseMaxPoolTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, kernel_size, stride, padding,
dilation):
super().__init__()
layers = [
spconv.SparseMaxPool3d(kernel_size, stride, padding, dilation)
]
for i in range(1, num_layers):
layers.append(spconv.SparseMaxPool3d(kernel_size, stride, padding, dilation))
self.net = spconv.SparseSequential(*layers, )
self.shape = shape
def forward(self, features, coors, batch_size):
coors = coors.int()
x = spconv.SparseConvTensor(features, coors, self.shape, batch_size)
return self.net(x) # .dense()
class MaxPool3dTestTorch(nn.Module):
def __init__(self, num_layers, ndim, shape, kernel_size, stride, padding,
dilation):
super().__init__()
layers = [nn.MaxPool3d(kernel_size, stride, padding, dilation)]
for i in range(1, num_layers):
layers.append(nn.MaxPool3d(kernel_size, stride, padding, dilation))
self.net = nn.Sequential(*layers, )
self.shape = shape
def forward(self, x):
return self.net(x) # .dense()
| 38.578788
| 144
| 0.448747
| 1,040
| 12,731
| 5.307692
| 0.134615
| 0.063768
| 0.086957
| 0.125
| 0.872464
| 0.872464
| 0.872464
| 0.852536
| 0.852536
| 0.851087
| 0
| 0.009653
| 0.471055
| 12,731
| 329
| 145
| 38.696049
| 0.810068
| 0.082162
| 0
| 0.913669
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.071942
| false
| 0
| 0.007194
| 0.014388
| 0.151079
| 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
|
b274c483538e9a8dfcbb47fb93454f2ffe1c37e0
| 6,912
|
py
|
Python
|
release/stubs.min/System/Drawing/__init___parts/ToolboxBitmapAttribute.py
|
YKato521/ironpython-stubs
|
b1f7c580de48528490b3ee5791b04898be95a9ae
|
[
"MIT"
] | null | null | null |
release/stubs.min/System/Drawing/__init___parts/ToolboxBitmapAttribute.py
|
YKato521/ironpython-stubs
|
b1f7c580de48528490b3ee5791b04898be95a9ae
|
[
"MIT"
] | null | null | null |
release/stubs.min/System/Drawing/__init___parts/ToolboxBitmapAttribute.py
|
YKato521/ironpython-stubs
|
b1f7c580de48528490b3ee5791b04898be95a9ae
|
[
"MIT"
] | null | null | null |
class ToolboxBitmapAttribute(Attribute, _Attribute):
"""
Allows you to specify an icon to represent a control in a container,such as the Microsoft Visual Studio Form Designer.
ToolboxBitmapAttribute(imageFile: str)
ToolboxBitmapAttribute(t: Type)
ToolboxBitmapAttribute(t: Type,name: str)
"""
def Equals(self, value):
"""
Equals(self: ToolboxBitmapAttribute,value: object) -> bool
Indicates whether the specified object is a System.Drawing.ToolboxBitmapAttribute object and is
identical to this System.Drawing.ToolboxBitmapAttribute object.
value: The System.Object to test.
Returns: This method returns true if value is both a System.Drawing.ToolboxBitmapAttribute object and is
identical to this System.Drawing.ToolboxBitmapAttribute object.
"""
pass
def GetHashCode(self):
"""
GetHashCode(self: ToolboxBitmapAttribute) -> int
Gets a hash code for this System.Drawing.ToolboxBitmapAttribute object.
Returns: The hash code for this System.Drawing.ToolboxBitmapAttribute object.
"""
pass
def GetImage(self, *__args):
"""
GetImage(self: ToolboxBitmapAttribute,type: Type,large: bool) -> Image
Gets the small or large System.Drawing.Image associated with this
System.Drawing.ToolboxBitmapAttribute object.
type: If this System.Drawing.ToolboxBitmapAttribute object does not already have a small image,this
method searches for a bitmap resource in the assembly that defines the type specified by the
component type. For example,if you pass typeof(ControlA) to the type parameter,then this
method searches the assembly that defines ControlA.
large: Specifies whether this method returns a large image (true) or a small image (false). The small
image is 16 by 16,and the large image is 32 by 32.
Returns: An System.Drawing.Image associated with this System.Drawing.ToolboxBitmapAttribute object.
GetImage(self: ToolboxBitmapAttribute,type: Type,imgName: str,large: bool) -> Image
Gets the small or large System.Drawing.Image associated with this
System.Drawing.ToolboxBitmapAttribute object.
type: If this System.Drawing.ToolboxBitmapAttribute object does not already have a small image,this
method searches for an embedded bitmap resource in the assembly that defines the type specified
by the component type. For example,if you pass typeof(ControlA) to the type parameter,then
this method searches the assembly that defines ControlA.
imgName: The name of the embedded bitmap resource.
large: Specifies whether this method returns a large image (true) or a small image (false). The small
image is 16 by 16,and the large image is 32 by 32.
Returns: An System.Drawing.Image associated with this System.Drawing.ToolboxBitmapAttribute object.
GetImage(self: ToolboxBitmapAttribute,type: Type) -> Image
Gets the small System.Drawing.Image associated with this System.Drawing.ToolboxBitmapAttribute
object.
type: If this System.Drawing.ToolboxBitmapAttribute object does not already have a small image,this
method searches for a bitmap resource in the assembly that defines the type specified by the
type parameter. For example,if you pass typeof(ControlA) to the type parameter,then this
method searches the assembly that defines ControlA.
Returns: The small System.Drawing.Image associated with this System.Drawing.ToolboxBitmapAttribute object.
GetImage(self: ToolboxBitmapAttribute,component: object) -> Image
Gets the small System.Drawing.Image associated with this System.Drawing.ToolboxBitmapAttribute
object.
component: If this System.Drawing.ToolboxBitmapAttribute object does not already have a small image,this
method searches for a bitmap resource in the assembly that defines the type of the object
specified by the component parameter. For example,if you pass an object of type ControlA to the
component parameter,then this method searches the assembly that defines ControlA.
Returns: The small System.Drawing.Image associated with this System.Drawing.ToolboxBitmapAttribute object.
GetImage(self: ToolboxBitmapAttribute,component: object,large: bool) -> Image
Gets the small or large System.Drawing.Image associated with this
System.Drawing.ToolboxBitmapAttribute object.
component: If this System.Drawing.ToolboxBitmapAttribute object does not already have a small image,this
method searches for a bitmap resource in the assembly that defines the type of the object
specified by the component parameter. For example,if you pass an object of type ControlA to the
component parameter,then this method searches the assembly that defines ControlA.
large: Specifies whether this method returns a large image (true) or a small image (false). The small
image is 16 by 16,and the large image is 32 by 32.
Returns: An System.Drawing.Image object associated with this System.Drawing.ToolboxBitmapAttribute object.
"""
pass
@staticmethod
def GetImageFromResource(t, imageName, large):
"""
GetImageFromResource(t: Type,imageName: str,large: bool) -> Image
Returns an System.Drawing.Image object based on a bitmap resource that is embedded in an
assembly.
t: This method searches for an embedded bitmap resource in the assembly that defines the type
specified by the t parameter. For example,if you pass typeof(ControlA) to the t parameter,then
this method searches the assembly that defines ControlA.
imageName: The name of the embedded bitmap resource.
large: Specifies whether this method returns a large image (true)or a small image (false). The small
image is 16 by 16,and the large image is 32 x 32.
Returns: An System.Drawing.Image object based on the retrieved bitmap.
"""
pass
def __eq__(self, *args):
""" x.__eq__(y) <==> x==y """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, *__args):
"""
__new__(cls: type,imageFile: str)
__new__(cls: type,t: Type)
__new__(cls: type,t: Type,name: str)
"""
pass
def __ne__(self, *args):
pass
Default = None
# variables with complex values
| 27.320158
| 221
| 0.703414
| 876
| 6,912
| 5.466895
| 0.125571
| 0.08958
| 0.153477
| 0.179787
| 0.821675
| 0.80664
| 0.805805
| 0.788891
| 0.748799
| 0.748799
| 0
| 0.006087
| 0.239439
| 6,912
| 252
| 222
| 27.428571
| 0.904889
| 0.844039
| 0
| 0.5
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.4
| false
| 0.4
| 0
| 0
| 0.5
| 0
| 0
| 0
| 0
| null | 0
| 0
| 1
| 1
| 1
| 1
| 1
| 1
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
| 0
|
0
| 10
|
b2b12c54a0c48247af7cecebf8ba800823d9c66e
| 14,498
|
py
|
Python
|
examples/Python/callback_service.py
|
Sabse95/Snowboy_REST_API_Project
|
0c70ff076eb0e03950b7a9f90232d560c22e52a4
|
[
"Apache-2.0"
] | null | null | null |
examples/Python/callback_service.py
|
Sabse95/Snowboy_REST_API_Project
|
0c70ff076eb0e03950b7a9f90232d560c22e52a4
|
[
"Apache-2.0"
] | null | null | null |
examples/Python/callback_service.py
|
Sabse95/Snowboy_REST_API_Project
|
0c70ff076eb0e03950b7a9f90232d560c22e52a4
|
[
"Apache-2.0"
] | null | null | null |
import sys
import configuration
import request_service
#callbackservice includes callback funktions for 20 hotwords
def callback_1():
nummer = 0
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_2():
nummer = 1
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_3():
nummer = 2
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_4():
nummer = 3
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_5():
nummer = 4
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_6():
nummer = 5
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_7():
nummer = 6
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_8():
nummer = 7
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_9():
nummer = 8
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_10():
nummer = 9
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_11():
nummer = 10
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_12():
nummer = 11
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_13():
nummer = 12
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_14():
nummer = 13
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_15():
nummer = 14
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_16():
nummer = 15
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_17():
nummer = 16
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_18():
nummer = 17
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_19():
nummer = 18
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def callback_20():
nummer = 19
name = configuration.name_search(nummer)
print "Hotword found: ", name
methode = configuration.read_httpmethod(name)
data = configuration.read_bodyData(name)
url = configuration.read_endpoint(name)
if methode == "GET":
request_service.get_request(url)
elif methode == "get":
request_service.get_request(url)
elif methode == "POST":
request_service.post_request(url, data)
elif methode == "post":
request_service.post_request(url, data)
#print "Callback", nummer
def anzahl_callbacks_waehlen():
status= configuration.size_of_config()
if status == 1:
callbacks = [callback_1]
return callbacks
elif status == 2:
callbacks = [callback_1, callback_2]
return callbacks
elif status == 3:
callbacks = [callback_1, callback_2, callback_3]
return callbacks
elif status == 4:
callbacks = [callback_1, callback_2, callback_3, callback_4]
return callbacks
elif status == 5:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5]
return callbacks
elif status == 6:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6]
return callbacks
elif status == 7:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7]
return callbacks
elif status == 8:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8]
return callbacks
elif status == 9:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9]
return callbacks
elif status == 10:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10]
return callbacks
elif status == 11:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11]
return callbacks
elif status == 12:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12]
return callbacks
elif status == 13:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13]
return callbacks
elif status == 14:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14]
return callbacks
elif status == 15:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14, callback_15]
return callbacks
elif status == 16:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14, callback_15, callback_16]
return callbacks
elif status == 17:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14, callback_15, callback_16, callback_17]
return callbacks
elif status == 18:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14, callback_15, callback_16, callback_17, callback_18]
return callbacks
elif status == 19:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14, callback_15, callback_16, callback_17, callback_18, callback_19]
return callbacks
elif status == 20:
callbacks = [callback_1, callback_2, callback_3, callback_4, callback_5, callback_6, callback_7, callback_8, callback_9, callback_10,
callback_11, callback_12, callback_13, callback_14, callback_15, callback_16, callback_17, callback_18, callback_19, callback_20]
return callbacks
if __name__ == "__main__":
callback_1()
callback_2()
callback_3()
callback_4()
callback_5()
callback_6()
callback_7()
callback_8()
callback_9()
callback_10()
callback_11()
callback_12()
callback_13()
callback_14()
callback_15()
callback_16()
callback_17()
callback_18()
callback_19()
callback_20()
| 32.653153
| 136
| 0.75369
| 1,926
| 14,498
| 5.412253
| 0.030633
| 0.108787
| 0.065234
| 0.092095
| 0.913373
| 0.910783
| 0.910783
| 0.907329
| 0.907329
| 0.903012
| 0
| 0.032003
| 0.135743
| 14,498
| 443
| 137
| 32.726862
| 0.79992
| 0.037178
| 0
| 0.732323
| 0
| 0
| 0.042187
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | null | 0
| 0.007576
| null | null | 0.050505
| 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
| 1
| 0
| 0
| 0
| 0
| 0
| 0
| 0
|
0
| 8
|
a233c904c806ef9306f7b35fea5c25e3c7ef5392
| 9,434
|
py
|
Python
|
views/window_dragable.py
|
life-game-player/Hephaestus
|
0c695193d8d2d8c70061e2e26ec8c718544342c6
|
[
"MIT"
] | null | null | null |
views/window_dragable.py
|
life-game-player/Hephaestus
|
0c695193d8d2d8c70061e2e26ec8c718544342c6
|
[
"MIT"
] | null | null | null |
views/window_dragable.py
|
life-game-player/Hephaestus
|
0c695193d8d2d8c70061e2e26ec8c718544342c6
|
[
"MIT"
] | null | null | null |
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtGui import QCursor
class WindowDragable(QtWidgets.QWidget):
def __init__(self):
super().__init__()
# 鼠标状态
self.setMouseTracking(True)
self.edge_range = 4
self.mouse_pos = None # 鼠标相对于窗口的位置
self.is_left_button_pressed = False
def mousePressEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.is_left_button_pressed = True
mouse_x = event.globalPos().x()
mouse_y = event.globalPos().y()
rect_window = self.rect()
topleft_point = self.mapToGlobal(rect_window.topLeft())
rightbottom_point = self.mapToGlobal(rect_window.bottomRight())
if (
(topleft_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (topleft_point.x() + self.edge_range) and
(topleft_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (topleft_point.y() + self.edge_range)
):
self.mouse_pos = 'LEFTTOP' # 鼠标位于窗口左上角
elif (
(rightbottom_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (rightbottom_point.x() + self.edge_range) and
(topleft_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (topleft_point.y() + self.edge_range)
):
self.mouse_pos = 'RIGHTTOP'
elif (
(topleft_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (topleft_point.x() + self.edge_range) and
(rightbottom_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (rightbottom_point.y() + self.edge_range)
):
self.mouse_pos = 'LEFTBOTTOM'
elif (
(rightbottom_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (rightbottom_point.x() + self.edge_range) and
(rightbottom_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (rightbottom_point.y() + self.edge_range)
):
self.mouse_pos = 'RIGHTBOTTOM'
elif (
(topleft_point.x() + self.edge_range) < mouse_x and
mouse_x < (rightbottom_point.x() - self.edge_range) and
(topleft_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (topleft_point.y() + self.edge_range)
):
self.mouse_pos = 'TOP'
elif (
(topleft_point.x() + self.edge_range) < mouse_x and
mouse_x < (rightbottom_point.x() - self.edge_range) and
(rightbottom_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (rightbottom_point.y() + self.edge_range)
):
self.mouse_pos = 'BOTTOM'
else:
self.drag_pos = event.globalPos() # 拖拽起始点坐标
self.setCursor(
QCursor(QtCore.Qt.OpenHandCursor)
)
event.accept()
def mouseMoveEvent(self, event):
mouse_x = event.globalPos().x()
mouse_y = event.globalPos().y()
rect_window = self.rect()
topleft_point = self.mapToGlobal(rect_window.topLeft())
rightbottom_point = self.mapToGlobal(rect_window.bottomRight())
if not self.is_left_button_pressed:
# 仅改变鼠标形状
if (
(topleft_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (topleft_point.x() + self.edge_range) and
(topleft_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (topleft_point.y() + self.edge_range)
):
# 左上
self.setCursor(
QCursor(QtCore.Qt.SizeFDiagCursor)
) # 设置鼠标形状
elif (
(rightbottom_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (rightbottom_point.x() + self.edge_range) and
(topleft_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (topleft_point.y() + self.edge_range)
):
# 右上
self.setCursor(
QCursor(QtCore.Qt.SizeBDiagCursor)
) # 设置鼠标形状
elif (
(topleft_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (topleft_point.x() + self.edge_range) and
(rightbottom_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (rightbottom_point.y() + self.edge_range)
):
# 左下
self.setCursor(
QCursor(QtCore.Qt.SizeBDiagCursor)
) # 设置鼠标形状
elif (
(rightbottom_point.x() - self.edge_range) <= mouse_x and
mouse_x <= (rightbottom_point.x() + self.edge_range) and
(rightbottom_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (rightbottom_point.y() + self.edge_range)
):
# 右下
self.setCursor(
QCursor(QtCore.Qt.SizeFDiagCursor)
) # 设置鼠标形状
elif (
(topleft_point.x() + self.edge_range) < mouse_x and
mouse_x < (rightbottom_point.x() - self.edge_range) and
(topleft_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (topleft_point.y() + self.edge_range)
):
# 上
self.setCursor(
QCursor(QtCore.Qt.SizeVerCursor)
) # 设置鼠标形状
elif (
(topleft_point.x() + self.edge_range) < mouse_x and
mouse_x < (rightbottom_point.x() - self.edge_range) and
(rightbottom_point.y() - self.edge_range) <= mouse_y and
mouse_y <= (rightbottom_point.y() + self.edge_range)
):
# 下
self.setCursor(
QCursor(QtCore.Qt.SizeVerCursor)
) # 设置鼠标形状
else:
self.setCursor(
QCursor(QtCore.Qt.ArrowCursor)
) # 设置鼠标形状
elif self.mouse_pos is None:
# 拖拽改变窗口位置
self.move(self.pos() + event.globalPos() - self.drag_pos)
self.drag_pos = event.globalPos()
event.accept()
else:
rect_new = QtCore.QRect(topleft_point, rightbottom_point)
if self.mouse_pos == 'LEFTTOP':
if (
self.window_min_width <
rightbottom_point.x() - mouse_x <
self.window_max_width
):
rect_new.setLeft(mouse_x)
if (
self.window_min_height <
rightbottom_point.y() - mouse_y <
self.window_max_height
):
rect_new.setTop(mouse_y)
if self.mouse_pos == 'TOP':
if (
self.window_min_height <
rightbottom_point.y() - mouse_y <
self.window_max_height
):
rect_new.setTop(mouse_y)
if self.mouse_pos == 'RIGHTBOTTOM':
if (
self.window_min_width <
mouse_x - topleft_point.x() <
self.window_max_width
):
rect_new.setRight(mouse_x)
if (
self.window_min_height <
mouse_y - topleft_point.y() <
self.window_max_height
):
rect_new.setBottom(mouse_y)
if self.mouse_pos == 'BOTTOM':
if (
self.window_min_height <
mouse_y - topleft_point.y() <
self.window_max_height
):
rect_new.setBottom(mouse_y)
if self.mouse_pos == 'RIGHTTOP':
if (
self.window_min_width <
mouse_x - topleft_point.x() <
self.window_max_width
):
rect_new.setRight(mouse_x)
if (
self.window_min_height <
rightbottom_point.y() - mouse_y <
self.window_max_height
):
rect_new.setTop(mouse_y)
if self.mouse_pos == 'LEFTBOTTOM':
if (
self.window_min_width <
rightbottom_point.x() - mouse_x <
self.window_max_width
):
rect_new.setLeft(mouse_x)
if (
self.window_min_height <
mouse_y - topleft_point.y() <
self.window_max_height
):
rect_new.setBottom(mouse_y)
self.setGeometry(rect_new)
def mouseReleaseEvent(self, event):
if event.button() == QtCore.Qt.LeftButton:
self.mouse_pos = None
self.is_left_button_pressed = False
self.setCursor(
QCursor(QtCore.Qt.ArrowCursor)
)
event.accept()
| 40.144681
| 75
| 0.485266
| 937
| 9,434
| 4.585912
| 0.091782
| 0.091226
| 0.148243
| 0.078194
| 0.856179
| 0.828252
| 0.797068
| 0.776588
| 0.73656
| 0.716081
| 0
| 0.000729
| 0.418486
| 9,434
| 234
| 76
| 40.316239
| 0.782537
| 0.01219
| 0
| 0.816038
| 0
| 0
| 0.009678
| 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0.018868
| false
| 0
| 0.014151
| 0
| 0.037736
| 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
|
a26153f91db204dc79646be4980ef4ce6ceddfd4
| 145
|
py
|
Python
|
odin/visual/__init__.py
|
tirkarthi/odin-ai
|
7900bef82ad8801d0c73880330d5b24d9ff7cd06
|
[
"MIT"
] | 7
|
2020-12-29T19:35:58.000Z
|
2022-01-31T21:01:30.000Z
|
odin/visual/__init__.py
|
tirkarthi/odin-ai
|
7900bef82ad8801d0c73880330d5b24d9ff7cd06
|
[
"MIT"
] | 3
|
2020-02-06T16:44:17.000Z
|
2020-09-26T05:26:14.000Z
|
odin/visual/__init__.py
|
tirkarthi/odin-ai
|
7900bef82ad8801d0c73880330d5b24d9ff7cd06
|
[
"MIT"
] | 6
|
2019-02-14T01:36:28.000Z
|
2020-10-30T13:16:32.000Z
|
from odin.visual.animation import *
from odin.visual.base import Visualizer
from odin.visual.bashplot import *
from odin.visual.figures import *
| 29
| 39
| 0.813793
| 21
| 145
| 5.619048
| 0.428571
| 0.271186
| 0.474576
| 0.338983
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.110345
| 145
| 4
| 40
| 36.25
| 0.914729
| 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
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| null | 0
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| 1
| 0
| 0
| 0
|
0
| 7
|
a270704150622fe29e960dc530eefa854fba84ea
| 224
|
py
|
Python
|
users/emails.py
|
JeffersonBC/eshop-index-back
|
66a11ad2ee86b9cd4dd49bcb34f676db3281153b
|
[
"MIT"
] | null | null | null |
users/emails.py
|
JeffersonBC/eshop-index-back
|
66a11ad2ee86b9cd4dd49bcb34f676db3281153b
|
[
"MIT"
] | null | null | null |
users/emails.py
|
JeffersonBC/eshop-index-back
|
66a11ad2ee86b9cd4dd49bcb34f676db3281153b
|
[
"MIT"
] | null | null | null |
from djmail import template_mail
class AccountActivationEmail(template_mail.TemplateMail):
name = "account_activation"
class AccountPasswordResetEmail(template_mail.TemplateMail):
name = "account_password_reset"
| 22.4
| 60
| 0.821429
| 22
| 224
| 8.090909
| 0.636364
| 0.202247
| 0.269663
| 0.314607
| 0.393258
| 0
| 0
| 0
| 0
| 0
| 0
| 0
| 0.116071
| 224
| 9
| 61
| 24.888889
| 0.89899
| 0
| 0
| 0
| 0
| 0
| 0.178571
| 0.098214
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0.4
| 0.2
| 0
| 1
| 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
| 1
| 0
| 0
| 1
| 0
|
0
| 7
|
a27b9c77efc3fd132b2f45a5d4e9992de0c30b7e
| 4,058
|
py
|
Python
|
QuestionnaireColorCueNew/migrations/0003_auto_20200802_0911.py
|
AdityaKapoor74/Supervised_Categorization_Study
|
1ce29de95c8ccc2b848e2d06463719858e57b942
|
[
"MIT"
] | null | null | null |
QuestionnaireColorCueNew/migrations/0003_auto_20200802_0911.py
|
AdityaKapoor74/Supervised_Categorization_Study
|
1ce29de95c8ccc2b848e2d06463719858e57b942
|
[
"MIT"
] | null | null | null |
QuestionnaireColorCueNew/migrations/0003_auto_20200802_0911.py
|
AdityaKapoor74/Supervised_Categorization_Study
|
1ce29de95c8ccc2b848e2d06463719858e57b942
|
[
"MIT"
] | null | null | null |
# Generated by Django 2.0.2 on 2020-08-02 09:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('QuestionnaireColorCueNew', '0002_auto_20200709_1755'),
]
operations = [
migrations.CreateModel(
name='CommonFeatureTable',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('set_number', models.IntegerField(default=None)),
('block_number', models.IntegerField(default=None)),
('sequence_number', models.IntegerField(default=None)),
('file_name', models.CharField(default=None, max_length=150)),
('user_option', models.CharField(default=None, max_length=10)),
('correct_option', models.CharField(default=None, max_length=10)),
('rule_based', models.IntegerField(default=None)),
('time_taken', models.FloatField(default=None)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='QuestionnaireColorCueNew.UserDetails')),
],
options={
'verbose_name_plural': 'Common Feature Test Table',
},
),
migrations.CreateModel(
name='TransferStimuliTable',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('set_number', models.IntegerField(default=None)),
('block_number', models.IntegerField(default=None)),
('sequence_number', models.IntegerField(default=None)),
('file_name', models.CharField(default=None, max_length=150)),
('user_option', models.CharField(default=None, max_length=10)),
('rule_based', models.IntegerField(default=None)),
('time_taken', models.FloatField(default=None)),
('timestamp', models.DateTimeField(auto_now_add=True)),
('user_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='QuestionnaireColorCueNew.UserDetails')),
],
options={
'verbose_name_plural': 'Transfer Stimuli Table',
},
),
migrations.AddField(
model_name='userresponse_common_features_test_set1',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_common_features_test_set3',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_common_features_test_set4',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_common_features_test_set5',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_test_set1',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_test_set2',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_test_set3',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_test_set4',
name='time_taken',
field=models.FloatField(default=None),
),
migrations.AddField(
model_name='userresponse_test_set5',
name='time_taken',
field=models.FloatField(default=None),
),
]
| 41.835052
| 135
| 0.591917
| 377
| 4,058
| 6.145889
| 0.233422
| 0.11394
| 0.109193
| 0.128183
| 0.854985
| 0.854985
| 0.854985
| 0.854985
| 0.83211
| 0.83211
| 0
| 0.017987
| 0.28758
| 4,058
| 96
| 136
| 42.270833
| 0.783466
| 0.011089
| 0
| 0.733333
| 1
| 0
| 0.19995
| 0.094989
| 0
| 0
| 0
| 0
| 0
| 1
| 0
| false
| 0
| 0.022222
| 0
| 0.055556
| 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
|
a290b7c2b1db208f93086253d800258f77424d37
| 325,638
|
py
|
Python
|
habib-7.py
|
Habibvip/habib-bd
|
4be47587f0cdb2a985bdb0fa98e3403917d708ad
|
[
"Apache-2.0"
] | null | null | null |
habib-7.py
|
Habibvip/habib-bd
|
4be47587f0cdb2a985bdb0fa98e3403917d708ad
|
[
"Apache-2.0"
] | null | null | null |
habib-7.py
|
Habibvip/habib-bd
|
4be47587f0cdb2a985bdb0fa98e3403917d708ad
|
[
"Apache-2.0"
] | null | null | null |
�
x�bc @ s! d d l Z e j d � d Ud S( i����Ns�� c |� @ s� d d d d d d d d d d d
d d d
d d d d d d d d d d d d d d d d d d d d d d d! d" d d d# d$ d% d& |