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
867f742c81d326d71b75b1e142683299875f9a8a
292
py
Python
tests/effects/not_an_effect.py
RatJuggler/led-shim-effects
3c63f5f2ce3f35f52e784489deb9212757c18cd2
[ "MIT" ]
1
2021-04-17T16:18:14.000Z
2021-04-17T16:18:14.000Z
tests/effects/not_an_effect.py
RatJuggler/led-shim-effects
3c63f5f2ce3f35f52e784489deb9212757c18cd2
[ "MIT" ]
12
2019-07-26T18:01:56.000Z
2019-08-31T15:35:17.000Z
tests/effects/not_an_effect.py
RatJuggler/led-shim-demo
3c63f5f2ce3f35f52e784489deb9212757c18cd2
[ "MIT" ]
null
null
null
class NotAnEffect(): """ Not an effect (doesn't inherit from AbstractEffect). """ def __init__(self) -> None: pass def compose(self) -> None: pass # pragma: no cover def __repr__(self) -> str: return "NotAnEffect()" # pragma: no cover
18.25
56
0.561644
32
292
4.875
0.6875
0.102564
0.153846
0
0
0
0
0
0
0
0
0
0.315068
292
15
57
19.466667
0.78
0.297945
0
0.285714
0
0
0.069892
0
0
0
0
0
0
1
0.428571
false
0.285714
0
0.142857
0.714286
0
0
0
0
null
0
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
0
1
0
1
1
0
0
4
8688c685dfadb6f668bd82427459ad3b28b13833
177
py
Python
src/radish/step_testing/__init__.py
radish-bdd/radish2
4ea71291aac8700ec2b284b7f2bbf79bf2970324
[ "MIT" ]
182
2015-06-27T16:17:17.000Z
2022-03-19T11:49:10.000Z
src/radish/step_testing/__init__.py
radish-bdd/radish2
4ea71291aac8700ec2b284b7f2bbf79bf2970324
[ "MIT" ]
357
2015-11-06T19:30:19.000Z
2022-03-28T19:49:04.000Z
src/radish/step_testing/__init__.py
radish-bdd/radish2
4ea71291aac8700ec2b284b7f2bbf79bf2970324
[ "MIT" ]
52
2015-08-22T08:36:37.000Z
2022-03-01T06:04:06.000Z
""" radish ~~~~~~ The root from red to green. BDD tooling for Python. :copyright: (c) 2019 by Timo Furrer <tuxtimo@gmail.com> :license: MIT, see LICENSE for more details. """
17.7
55
0.683616
27
177
4.481481
0.925926
0
0
0
0
0
0
0
0
0
0
0.027211
0.169492
177
9
56
19.666667
0.795918
0.949153
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
86a1ced20f007b8f96a9c9ca249a13a8a0374696
309
py
Python
onelogin_rules/onelogin_threshold_accounts_modified.py
panther-labs/panther-cli
4e5c0a21570e1a02dada990fd91e324416afac96
[ "MIT" ]
4
2019-10-17T19:33:29.000Z
2019-10-21T15:23:30.000Z
onelogin_rules/onelogin_threshold_accounts_modified.py
jacknagz/panther-analysis
fceab78ba5624136776596ee1b25fa0dc8a02a42
[ "Apache-2.0" ]
null
null
null
onelogin_rules/onelogin_threshold_accounts_modified.py
jacknagz/panther-analysis
fceab78ba5624136776596ee1b25fa0dc8a02a42
[ "Apache-2.0" ]
null
null
null
def rule(event): # filter events; event type 11 is an actor_user changed user password return event.get("event_type_id") == 11 def title(event): return ( f"User [{event.get('actor_user_name', '<UNKNOWN_USER>')}] has exceeded the user" f" account password change threshold" )
28.090909
88
0.66343
44
309
4.522727
0.590909
0.090452
0
0
0
0
0
0
0
0
0
0.016667
0.223301
309
10
89
30.9
0.8125
0.216828
0
0
0
0
0.516667
0.125
0
0
0
0
0
1
0.285714
false
0.142857
0
0.285714
0.571429
0
0
0
0
null
0
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
0
1
0
1
1
0
0
4
86b0286b72b13b7980a6988db933151076f0f714
172
py
Python
factorizer/tensor_network/utils.py
pashtari/factorizer
730f295b403a90c1c691f99b529d5d32b635d0c6
[ "Apache-2.0" ]
7
2022-03-05T00:43:29.000Z
2022-03-07T01:23:08.000Z
factorizer/tensor_network/utils.py
pashtari/factorizer
730f295b403a90c1c691f99b529d5d32b635d0c6
[ "Apache-2.0" ]
null
null
null
factorizer/tensor_network/utils.py
pashtari/factorizer
730f295b403a90c1c691f99b529d5d32b635d0c6
[ "Apache-2.0" ]
1
2022-03-21T05:28:23.000Z
2022-03-21T05:28:23.000Z
from typing import Sequence from numbers import Number from functools import reduce from operator import mul def prod(x: Sequence[Number]): return reduce(mul, x, 1)
17.2
30
0.767442
26
172
5.076923
0.576923
0
0
0
0
0
0
0
0
0
0
0.007042
0.174419
172
9
31
19.111111
0.922535
0
0
0
0
0
0
0
0
0
0
0
0
1
0.166667
false
0
0.666667
0.166667
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
1
0
0
0
4
86b81320cf26ec0ac6024d6f890879331f0fae60
4,583
py
Python
deprecated/us-rates.py
btrr/covid19-epicenters
4134967f6dbbdeb5ad91a435dc72d905e9886fd6
[ "MIT" ]
1
2020-04-02T15:48:28.000Z
2020-04-02T15:48:28.000Z
deprecated/us-rates.py
btrr/covid19-epicenters
4134967f6dbbdeb5ad91a435dc72d905e9886fd6
[ "MIT" ]
null
null
null
deprecated/us-rates.py
btrr/covid19-epicenters
4134967f6dbbdeb5ad91a435dc72d905e9886fd6
[ "MIT" ]
null
null
null
import datetime import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as ticker from matplotlib.dates import MO, TU, WE, TH, FR, SA, SU dates = ['2/14/2020', '2/15/2020', '2/16/2020', '2/17/2020', '2/18/2020', '2/19/2020', '2/20/2020', '2/21/2020', '2/22/2020', '2/23/2020', '2/24/2020', '2/25/2020', '2/26/2020', '2/27/2020', '2/28/2020', '2/29/2020', '3/1/2020', '3/2/2020', '3/3/2020', '3/4/2020', '3/5/2020', '3/6/2020', '3/7/2020', '3/8/2020', '3/9/2020', '3/10/2020', '3/11/2020', '3/12/2020', '3/13/2020', '3/14/2020', '3/15/2020', '3/16/2020', '3/17/2020', '3/18/2020', '3/19/2020', '3/20/2020', '3/21/2020', '3/22/2020', '3/23/2020', '3/24/2020', '3/25/2020', '3/26/2020', '3/27/2020', '3/28/2020', '3/29/2020', '3/30/2020', '3/31/2020', '4/1/2020', '4/2/2020', '4/3/2020', '4/4/2020', '4/5/2020', '4/6/2020', '4/7/2020', '4/8/2020', '4/9/2020', '4/10/2020', '4/11/2020', '4/12/2020', '4/13/2020', '4/14/2020', '4/15/2020', '4/16/2020', '4/17/2020', '4/18/2020', '4/19/2020', '4/20/2020', '4/21/2020', '4/22/2020', '4/23/2020', '4/24/2020', '4/25/2020', '4/26/2020', '4/27/2020', '4/28/2020', '4/29/2020', '4/30/2020', '5/1/2020', '5/2/2020', '5/3/2020', '5/4/2020', '5/5/2020', '5/6/2020', '5/7/2020', '5/8/2020', '5/9/2020', '5/10/2020', '5/11/2020', '5/12/2020', '5/13/2020', '5/14/2020', '5/15/2020', '5/16/2020', '5/17/2020', '5/18/2020', '5/19/2020', '5/20/2020', '5/21/2020', '5/22/2020', '5/23/2020', '5/24/2020', '5/25/2020', '5/26/2020', '5/27/2020', '5/28/2020', '5/29/2020', '5/30/2020', '5/31/2020', '6/1/2020', '6/2/2020', '6/3/2020', '6/4/2020', '6/5/2020', '6/6/2020', '6/7/2020', '6/8/2020', '6/9/2020', '6/10/2020', '6/11/2020', '6/12/2020', '6/13/2020', '6/14/2020', '6/15/2020', '6/16/2020', '6/17/2020', '6/18/2020', '6/19/2020', '6/20/2020', '6/21/2020', '6/22/2020', '6/23/2020', '6/24/2020', '6/25/2020', '6/26/2020', '6/27/2020', '6/28/2020', '6/29/2020', '6/30/2020', '7/01/2020', '7/02/2020'] # format dates x_values = [datetime.datetime.strptime(d, "%m/%d/%Y").date() for d in dates] ax = plt.gca() formatter = mdates.DateFormatter("%m/%d") ax.xaxis.set_major_formatter(formatter) # create x-axis ax.xaxis.set_major_locator(mdates.WeekdayLocator(byweekday=(MO, TU, WE, TH, FR, SA, SU), interval=7)) # minor tick = daily ax.xaxis.set_minor_locator(mdates.WeekdayLocator(byweekday=(MO, TU, WE, TH, FR, SA, SU))) # format y-axis ax.get_yaxis().set_major_formatter(ticker.FuncFormatter(lambda x, pos: format(int(x), ','))) # recovery rate recoveries = [0, 25, 25, 25, 25, 25, 35.71, 35.71, 35.71, 35.71, 35.71, 42.86, 40, 40, 31.58, 29.17, 21.43, 15.79, 10.59, 8.11, 5.14, 5.95, 4.25, 3.02, 2.33, 1.6, 1.24, .94, .74, 1.73, 1.71, 1.72, 1.89, 1.33, .91, .84, .72, .55, .69, .72, .61, 2.27, 2.44, 2.67, 3.25, 3.43, 3.9, 4.17, 4.31, 4.49, 4.82, 5.39, 5.39, 5.51, 5.38, 5.64, 5.53, 5.8, 5.9, 6.39, 6.43, 7.69, 8.68, 8.69, 9.42, 9.45, 9.33, 10.35, 10.12, 9.96, 12.29, 12.66, 12.36, 14.14, 14.12, 14.27, 14.66, 14.75, 15.43, 15.48, 16.03, 16.78, 17.47, 17.41, 17.54, 18.31, 19.41, 19.59, 21.82, 22.47, 22.59, 22.77, 23.28, 23.45, 23.79, 23.79, 24.03, 24.41, 25.37, 27.72, 27.67, 28.15, 28.78, 29.07, 29.18, 29.98, 30.47, 33.73, 34.29, 35.6, 37.54, 38.39, 39.32, 39.53, 39.66, 39.93, 40.47, 41.05, 41.06, 41.85, 41.91, 42.25, 42.84, 42.99, 43.26, 43.28, 43.82, 43.94, 43.72, 44.21, 44.33, 44.47, 44.24, 44.1, 43.83, 43.6, 43.91, 44.18, 44.11, 44.19] # mortality rate deaths = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4.17, 4.76, 10.53, 10.59, 9.91, 6.29, 5.56, 5.38, 4.23, 4.03, 3.31, 3.07, 2.57, 2.27, 1.98, 1.77, 1.74, 1.71, 1.52, 1.46, 1.32, 1.26, 1.26, 1.21, 1.29, 1.4, 1.41, 1.58, 1.68, 1.73, 1.86, 2.05, 2.23, 2.41, 2.56, 2.72, 2.86, 2.96, 3.22, 3.43, 3.58, 3.76, 3.89, 3.96, 4.05, 4.27, 4.45, 4.56, 4.66, 4.71, 4.77, 4.83, 5, 5.08, 5.12, 5.13, 5.13, 5.11, 5.12, 5.21, 5.33, 5.38, 5.38, 5.38, 5.36, 5.34, 5.44, 5.47, 5.59, 5.6, 5.61, 5.59, 5.58, 5.61, 5.65, 5.68, 5.68, 5.67, 5.65, 5.62, 5.64, 5.66, 5.65, 5.65, 5.63, 5.6, 5.57, 5.55, 5.57, 5.57, 5.56, 5.54, 5.51, 5.49, 5.48, 5.48, 5.46, 5.44, 5.41, 5.38, 5.36, 5.38, 5.37, 5.36, 5.33, 5.3, 5.26, 5.23, 5.21, 5.18, 5.15, 5.11, 5.06, 5.01, 4.96, 4.93, 4.88, 4.82, 4.76, 4.69, 4.63, 4.58, 4.52, 4.46, 4.39] # create the graph plt.plot(x_values, recoveries, color='#12cfdf', linewidth=2) plt.plot(x_values, deaths, color='#C70039', linewidth=2) # text labels plt.title('Covid-19 in the United States: Recovery Rate vs Mortality Rate') plt.xlabel('Date') plt.ylabel('Percent') plt.legend(['Recovery Rate', 'Mortality Rate'], loc='upper left') plt.show()
117.512821
1,792
0.573642
1,120
4,583
2.336607
0.15625
0.059228
0.014903
0.018342
0.064578
0.056935
0.056935
0.051586
0.043943
0.043943
0
0.450942
0.119354
4,583
39
1,793
117.512821
0.197473
0.025529
0
0
0
0
0.305518
0
0
0
0
0
0
1
0
false
0
0.227273
0
0.227273
0
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
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
86e023f4b8de38cb447e4baad0d4e4fa495b9a42
48
py
Python
garrus/calibrations/__init__.py
sleep3r/garrus
28096ca0d6166117be23e740a68831396ba92a7e
[ "Apache-2.0" ]
13
2021-04-06T15:00:41.000Z
2021-06-12T21:27:46.000Z
garrus/calibrations/__init__.py
sleep3r/garrus
28096ca0d6166117be23e740a68831396ba92a7e
[ "Apache-2.0" ]
null
null
null
garrus/calibrations/__init__.py
sleep3r/garrus
28096ca0d6166117be23e740a68831396ba92a7e
[ "Apache-2.0" ]
1
2021-04-26T04:25:59.000Z
2021-04-26T04:25:59.000Z
from .scaling import Platt __all__ = ["Platt"]
12
26
0.708333
6
48
5
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.166667
48
3
27
16
0.75
0
0
0
0
0
0.104167
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
4
8108810c9267b52a7223d339efbd19b2b24d2187
50
py
Python
python_modules/libraries/dagstermill/dagstermill/version.py
zzztimbo/dagster
5cf8f159183a80d2364e05bb30362e2798a7af37
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagstermill/dagstermill/version.py
zzztimbo/dagster
5cf8f159183a80d2364e05bb30362e2798a7af37
[ "Apache-2.0" ]
null
null
null
python_modules/libraries/dagstermill/dagstermill/version.py
zzztimbo/dagster
5cf8f159183a80d2364e05bb30362e2798a7af37
[ "Apache-2.0" ]
null
null
null
__version__ = '0.7.5' __nightly__ = '2020.03.20'
12.5
26
0.66
8
50
3.125
1
0
0
0
0
0
0
0
0
0
0
0.255814
0.14
50
3
27
16.666667
0.325581
0
0
0
0
0
0.3
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
810f9026a49b830c8d2e943ae4e2452218fa8e9b
140
py
Python
angr/engines/vex/statements/imark.py
mariusmue/angr
f8304c4b1f0097a721a6692b02a45cabaae137c5
[ "BSD-2-Clause" ]
2
2018-12-03T23:14:56.000Z
2018-12-03T23:15:57.000Z
angr/engines/vex/statements/imark.py
mariusmue/angr
f8304c4b1f0097a721a6692b02a45cabaae137c5
[ "BSD-2-Clause" ]
null
null
null
angr/engines/vex/statements/imark.py
mariusmue/angr
f8304c4b1f0097a721a6692b02a45cabaae137c5
[ "BSD-2-Clause" ]
1
2019-08-07T01:42:01.000Z
2019-08-07T01:42:01.000Z
from . import SimIRStmt class SimIRStmt_IMark(SimIRStmt): def _execute(self): self.state.history.recent_instruction_count += 1
23.333333
56
0.742857
17
140
5.882353
0.823529
0
0
0
0
0
0
0
0
0
0
0.008621
0.171429
140
5
57
28
0.853448
0
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
0.75
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
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
811454b5d7dd913655f136c04d2e9cbb2faae196
6,691
py
Python
psr/views.py
cocoemily/paleocore2
34b9ba30358963a0a1c8ae7252ed7c5ef178a758
[ "MIT" ]
null
null
null
psr/views.py
cocoemily/paleocore2
34b9ba30358963a0a1c8ae7252ed7c5ef178a758
[ "MIT" ]
null
null
null
psr/views.py
cocoemily/paleocore2
34b9ba30358963a0a1c8ae7252ed7c5ef178a758
[ "MIT" ]
null
null
null
import tempfile # Django Libraries from django.conf import settings from django.views import generic # App Libraries from .forms import * from .utilities import * class ImportShapefile(generic.FormView): template_name = "admin/psr/import_file.html" form_class = UploadShapefile context_object_name = 'upload' success_url = '../?last_import__exact=1' def get_import_shp_file(self): return self.request.FILES['shpfileUpload'] def get_import_dbf_file(self): return self.request.FILES['shpfileDataUpload'] def get_photos(self): return self.request.FILES.getlist('photoUpload') def get_import_file_path(self): import_file = self.get_import_file() file_extension = self.get_import_file_extension() # get the file extension file_path = os.path.join(settings.MEDIA_ROOT) return file_path + "/" + import_file.name def get_import_file_extension(self): import_file = self.get_import_file() import_file_name = import_file.name return import_file_name[import_file_name.rfind('.') + 1:] # get the file extension def import_shapefile_data(self): shp = self.get_import_shp_file() tempshp, tempshpname = tempfile.mkstemp() try: for chunk in shp.chunks(): os.write(tempshp, chunk) except: raise Exception("Problem with input file %s" % shp.name) finally: os.close(tempshp) dbf = self.get_import_dbf_file() tempdbf, tempdbfname = tempfile.mkstemp() try: for chunk in dbf.chunks(): os.write(tempdbf, chunk) except: raise Exception("Problem with input file %s" % dbf.name) finally: os.close(tempdbf) if "geologicalcontext" in self.request.path.split("/"): print("GeoContext") GeologicalContext.objects.all().update(last_import=False) import_geo_contexts(tempshpname, tempdbfname, self.get_photos()) #elif "occurrence" in self.request.path.split("/"): else: print("Occurrence") Occurrence.objects.all().update(last_import=False) import_survey_occurrences(tempshpname, tempdbfname) subtype_archaeology(survey=True) def form_valid(self, form): self.import_shapefile_data() return super(ImportShapefile, self).form_valid(form) class ImportShapefileDirectory(generic.FormView): template_name = "admin/psr/import_file.html" form_class = UploadShapefileDirectory context_object_name = 'upload' success_url = '../?last_import__exact=1' def get_import_files(self): return self.request.FILES.getlist('shapefileUpload') def get_shp_file(self): for f in self.get_import_files(): if f.name.endswith(".shp"): return f def get_dbf_file(self): for f in self.get_import_files(): if f.name.endswith(".dbf"): return f def get_photos(self): img = [] for f in self.get_import_files(): if f.name.endswith(".jpg"): img.append(f) return img def import_shapefile_data(self): shp = self.get_shp_file() tempshp, tempshpname = tempfile.mkstemp() try: for chunk in shp.chunks(): os.write(tempshp, chunk) except: raise Exception("Problem with input file %s" % shp.name) finally: os.close(tempshp) dbf = self.get_dbf_file() tempdbf, tempdbfname = tempfile.mkstemp() try: for chunk in dbf.chunks(): os.write(tempdbf, chunk) except: raise Exception("Problem with input file %s" % dbf.name) finally: os.close(tempdbf) if "geologicalcontext" in self.request.path.split("/"): print("GeoContext") GeologicalContext.objects.all().update(last_import=False) import_geo_contexts(tempshpname, tempdbfname, self.get_photos()) # elif "occurrence" in self.request.path.split("/"): else: print("Occurrence") Occurrence.objects.all().update(last_import=False) import_survey_occurrences(tempshpname, tempdbfname, self.get_photos()) def form_valid(self, form): self.import_shapefile_data() return super(ImportShapefileDirectory, self).form_valid(form) class ImportAccessDatabase(generic.FormView): template_name = "admin/psr/import_file.html" form_class = UploadMDB context_object_name = 'upload' success_url = '../?last_import__exact=1' def get_import_file(self): return self.request.FILES['mdbUpload'] def get_import_file_path(self): import_file = self.get_import_file() file_extension = self.get_import_file_extension() # get the file extension file_path = os.path.join(settings.MEDIA_ROOT) return file_path + "/" + import_file.name def get_import_file_extension(self): import_file = self.get_import_file() import_file_name = import_file.name return import_file_name[import_file_name.rfind('.') + 1:] # get the file extension def import_excavated_instances(self): file = self.get_import_file() fsplit = file.name.split(".") name = fsplit[0].split("_") if name.__len__() == 1: lname = name[0].capitalize() else: if name[1].isdigit(): lname = name[0].capitalize() + " " + name[1] else: #will there ever be geological context names with more than three? lname = name[0].capitalize() + " " + name[1].capitalize() ExcavationOccurrence.objects.all().update(last_import=False) parse_mdb(file.temporary_file_path(), lname) subtype_finds(survey = False) subtype_archaeology(survey = False) def form_valid(self, form): self.import_excavated_instances() return super(ImportAccessDatabase, self).form_valid(form) class ImportJSON(generic.FormView): template_name = "admin/psr/import_file.html" form_class = UploadJSON context_object_name = 'upload' success_url = '../?last_import__exact=1' def get_import_file(self): return self.request.FILES['jsonUpload'] def import_geo_contexts(self): GeologicalContext.objects.all().update(last_import=False) import_geo_context_from_json(self.get_import_file()) def form_valid(self, form): self.import_geo_contexts() return super(ImportJSON, self).form_valid(form)
33.623116
91
0.638768
783
6,691
5.223499
0.168582
0.07824
0.044499
0.033252
0.764303
0.739853
0.689242
0.674572
0.659169
0.645232
0
0.002815
0.256613
6,691
198
92
33.792929
0.819461
0.043043
0
0.623377
0
0
0.078054
0.031284
0
0
0
0
0
1
0.136364
false
0
0.435065
0.038961
0.811688
0.025974
0
0
0
null
0
0
0
0
1
0
0
0
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
1
0
1
0
0
4
81415c3e11b9d96232709e5d21349024a258a8aa
93
py
Python
appreview/apps.py
IsaiahKe/awward-mimic
8a5ff40d9acfbdc5323c7e9b6b8e7438f9a85d21
[ "MIT" ]
null
null
null
appreview/apps.py
IsaiahKe/awward-mimic
8a5ff40d9acfbdc5323c7e9b6b8e7438f9a85d21
[ "MIT" ]
null
null
null
appreview/apps.py
IsaiahKe/awward-mimic
8a5ff40d9acfbdc5323c7e9b6b8e7438f9a85d21
[ "MIT" ]
null
null
null
from django.apps import AppConfig class AppreviewConfig(AppConfig): name = 'appreview'
15.5
33
0.763441
10
93
7.1
0.9
0
0
0
0
0
0
0
0
0
0
0
0.16129
93
5
34
18.6
0.910256
0
0
0
0
0
0.096774
0
0
0
0
0
0
1
0
false
0
0.333333
0
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
d48f26dee07e7d24d934d5bad44acad6464f4d6d
395
py
Python
syft/frameworks/torch/tensors/interpreters/__init__.py
theoptips/PySyft
4b68c3c6fbe0c18cdf87dfe6ddc3c2071a71f1cc
[ "Apache-2.0" ]
1
2019-07-23T20:36:18.000Z
2019-07-23T20:36:18.000Z
syft/frameworks/torch/tensors/interpreters/__init__.py
theoptips/PySyft
4b68c3c6fbe0c18cdf87dfe6ddc3c2071a71f1cc
[ "Apache-2.0" ]
null
null
null
syft/frameworks/torch/tensors/interpreters/__init__.py
theoptips/PySyft
4b68c3c6fbe0c18cdf87dfe6ddc3c2071a71f1cc
[ "Apache-2.0" ]
1
2021-02-12T12:11:44.000Z
2021-02-12T12:11:44.000Z
from .abstract import AbstractTensor # noqa: F401 from .native import TorchTensor # noqa: F401 from .precision import FixedPrecisionTensor # noqa: F401 from .additive_shared import AdditiveSharingTensor # noqa: F401 from .multi_pointer import MultiPointerTensor # noqa: F401 from .large_precision import LargePrecisionTensor # noqa: F401 from .autograd import AutogradTensor # noqa: F401
49.375
64
0.805063
45
395
7
0.444444
0.177778
0.228571
0
0
0
0
0
0
0
0
0.061947
0.141772
395
7
65
56.428571
0.867257
0.192405
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
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
0
1
0
1
0
0
0
0
4
d4c207ae215ab2f2c1bf91873828c92f0243d0e9
214
py
Python
looking_for_group/releasenotes/apps.py
andrlik/looking-for-group
0b1cecb37ef0f6d75692fd188130e2c60d09b7d2
[ "BSD-3-Clause" ]
null
null
null
looking_for_group/releasenotes/apps.py
andrlik/looking-for-group
0b1cecb37ef0f6d75692fd188130e2c60d09b7d2
[ "BSD-3-Clause" ]
null
null
null
looking_for_group/releasenotes/apps.py
andrlik/looking-for-group
0b1cecb37ef0f6d75692fd188130e2c60d09b7d2
[ "BSD-3-Clause" ]
null
null
null
from django.apps import AppConfig class ReleasenotesConfig(AppConfig): name = "looking_for_group.releasenotes" verbose_name = "Release Notes" def ready(self): from . import receivers # noqa
21.4
43
0.714953
24
214
6.25
0.833333
0
0
0
0
0
0
0
0
0
0
0
0.21028
214
9
44
23.777778
0.887574
0.018692
0
0
0
0
0.206731
0.144231
0
0
0
0
0
1
0.166667
false
0
0.333333
0
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
d4c2884d23aea23271c49e4296861b3cfd4e3e5c
220
py
Python
praw/models/list/moderated.py
NedJunk/praw
dd75d91e5574f1499cbef445dd68eb71445629df
[ "BSD-2-Clause" ]
1
2022-02-04T04:17:04.000Z
2022-02-04T04:17:04.000Z
praw/models/list/moderated.py
seanwallawalla-forks/praw
849d2edbf26549e3e1b97e72479cdba78c96ddb1
[ "BSD-2-Clause" ]
2
2020-06-27T20:47:08.000Z
2020-07-06T17:25:00.000Z
praw/models/list/moderated.py
seanwallawalla-forks/praw
849d2edbf26549e3e1b97e72479cdba78c96ddb1
[ "BSD-2-Clause" ]
1
2020-07-11T06:28:50.000Z
2020-07-11T06:28:50.000Z
"""Provide the ModeratedList class.""" from .base import BaseList class ModeratedList(BaseList): """A list of moderated :class:`.Subreddit` objects. Works just like a regular list.""" CHILD_ATTRIBUTE = "data"
24.444444
90
0.713636
27
220
5.777778
0.777778
0
0
0
0
0
0
0
0
0
0
0
0.163636
220
8
91
27.5
0.847826
0.513636
0
0
0
0
0.041667
0
0
0
0
0
0
1
0
false
0
0.333333
0
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
d4d576f227cc1e6f6c42cd9396983b3d45a05f1f
567
py
Python
processor/vmcompilerinfo.py
paulscottrobson/color-forth-tokenised
2f16f1009483f7fc5da701ca1a3ea7221ae771d4
[ "MIT" ]
3
2018-01-04T11:02:18.000Z
2018-01-04T21:31:08.000Z
processor/vmcompilerinfo.py
paulscottrobson/color-forth-16-bit
2f16f1009483f7fc5da701ca1a3ea7221ae771d4
[ "MIT" ]
1
2020-06-15T18:25:59.000Z
2020-06-28T20:02:03.000Z
processor/vmcompilerinfo.py
paulscottrobson/color-forth-tokenised
2f16f1009483f7fc5da701ca1a3ea7221ae771d4
[ "MIT" ]
null
null
null
# # Generated by generate.py # class VMCompilerInfo: def getWordList(self): return ["@","c@","!","c!",">r","r>",";","[literal]","[bzero]","[halt]","[nop]","+","nand","2/","0=","[temp]","[codebase]","[dictionary]","cursor!","screen!","keyboard@","blockread@","[stackreset]","blockwrite!","0","1","2","-1","dup","drop","swap","over","?dup","not","and","or","xor","1+","1-","negate","-","2*","0<","+!","[exec]","[next]"] def getDictionaryBase(self): return 0x0100 def getCodeBase(self): return 0x1200 def getBaseLoadAddress(self): return 0x0000
43.615385
345
0.560847
65
567
4.892308
0.707692
0.125786
0
0
0
0
0
0
0
0
0
0.048263
0.08642
567
12
346
47.25
0.565637
0.042328
0
0
1
0
0.362454
0
0
0
0.033457
0
0
1
0.444444
false
0
0
0.444444
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
4
d4e891788694e1da667ace7942f9b9c99d101112
778
py
Python
pyforms/terminal/Controls/ControlButton.py
sunj1/my_pyforms
d92c37cbddb3ff34fe1ace3874e0116c09e7c0cf
[ "MIT" ]
null
null
null
pyforms/terminal/Controls/ControlButton.py
sunj1/my_pyforms
d92c37cbddb3ff34fe1ace3874e0116c09e7c0cf
[ "MIT" ]
null
null
null
pyforms/terminal/Controls/ControlButton.py
sunj1/my_pyforms
d92c37cbddb3ff34fe1ace3874e0116c09e7c0cf
[ "MIT" ]
null
null
null
from pyforms.terminal.Controls.ControlBase import ControlBase class ControlButton(ControlBase): def initControl(self): return "controls.push(new ControlButton('%s', '%s'));" % ( self._label, self._name ) def load(self, data): pass def save(self, data): pass def pressed(self): self._value() ############################################################################ @property def label(self): return ControlBase.lable.fget(self) @label.setter def label(self, value): ControlBase.label.fset(self, value) ############################################################################ @property def value(self): return None @value.setter def value(self, value): self._value = value
24.3125
111
0.512853
74
778
5.337838
0.391892
0.113924
0.060759
0.075949
0
0
0
0
0
0
0
0
0.195373
778
31
112
25.096774
0.63099
0
0
0.25
0
0
0.071885
0
0
0
0
0
0
1
0.5
false
0.125
0.0625
0.1875
0.625
0
0
0
0
null
0
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
0
1
0
1
1
0
0
4
d4efa9e1a11b839023c99dcefa0adfc9a2e379a0
1,399
py
Python
parsers/asp/dlvhex/DLVHEXParserVisitor.py
MikeCoder96/EmbASP-Python
60898633db9fa3786989bfe7b4c77c5381315e7a
[ "MIT" ]
1
2020-03-28T14:28:40.000Z
2020-03-28T14:28:40.000Z
parsers/asp/dlvhex/DLVHEXParserVisitor.py
MikeCoder96/EmbASP-Python
60898633db9fa3786989bfe7b4c77c5381315e7a
[ "MIT" ]
null
null
null
parsers/asp/dlvhex/DLVHEXParserVisitor.py
MikeCoder96/EmbASP-Python
60898633db9fa3786989bfe7b4c77c5381315e7a
[ "MIT" ]
5
2020-03-29T15:48:05.000Z
2021-09-07T22:05:04.000Z
# Generated from DLVHEXParser.g4 by ANTLR 4.7 from antlr4 import * # This class defines a complete generic visitor for a parse tree produced by DLVHEXParser. class DLVHEXParserVisitor(ParseTreeVisitor): # Visit a parse tree produced by DLVHEXParser#GroundQuery. def visitGroundQuery(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#Model. def visitModel(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#atoms. def visitAtoms(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#cost. def visitCost(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#level. def visitLevel(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#output. def visitOutput(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#predicate_atom. def visitPredicate_atom(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#term. def visitTerm(self, ctx): return self.visitChildren(ctx) # Visit a parse tree produced by DLVHEXParser#witness. def visitWitness(self, ctx): return self.visitChildren(ctx)
26.396226
90
0.707648
174
1,399
5.678161
0.275862
0.060729
0.101215
0.182186
0.67004
0.67004
0.604251
0.566802
0.566802
0.566802
0
0.003673
0.221587
1,399
52
91
26.903846
0.903581
0.427448
0
0.45
1
0
0
0
0
0
0
0
0
1
0.45
false
0
0.05
0.45
1
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
4
be274c4c403c3a8bf343b0978573abb2ba5eb98b
1,387
py
Python
torch2trt/converters/__init__.py
jsjason/torch2trt
5f513034a0b651b07a2930775ff94aa75533c6fb
[ "MIT" ]
null
null
null
torch2trt/converters/__init__.py
jsjason/torch2trt
5f513034a0b651b07a2930775ff94aa75533c6fb
[ "MIT" ]
null
null
null
torch2trt/converters/__init__.py
jsjason/torch2trt
5f513034a0b651b07a2930775ff94aa75533c6fb
[ "MIT" ]
null
null
null
# dummy converters throw warnings method encountered import tensorrt as trt from .dummy_converters import * # supported converters will override dummy converters from .AdaptiveAvgPool2d import * from .BatchNorm1d import * from .BatchNorm2d import * from .Conv import * from .Conv1d import * from .Conv2d import * from .ConvTranspose import * from .ConvTranspose2d import * from .Identity import * from .Linear import * from .LogSoftmax import * from .ReLU import * from .ReLU6 import * from .activation import * from .adaptive_avg_pool2d import * from .adaptive_max_pool2d import * from .add import * from .avg_pool import * from .batch_norm import * from .cat import * from .chunk import * from .clamp import * from .compare import * from .div import * from .getitem import * from .identity import * from .instance_norm import * from .interpolate import * from .max import * from .max_pool2d import * from .mean import * from .min import * from .mul import * from .normalize import * from .narrow import * from .pad import * from .permute import * from .pow import * from .prelu import * from .prod import * from .relu import * from .relu6 import * from .reshape import * from .sigmoid import * from .softmax import * from .split import * from .stack import * from .sub import * from .sum import * from .tanh import * from .transpose import * from .unary import * from .view import *
23.116667
53
0.750541
187
1,387
5.518717
0.347594
0.503876
0.046512
0.046512
0.129845
0.075581
0.075581
0.075581
0
0
0
0.009557
0.170151
1,387
59
54
23.508475
0.887055
0.07354
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
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
0
1
0
1
0
1
0
0
4
0781ab81757bcaf7c5d6b765e1379b4dc87f8d5e
216
py
Python
tests/test_appregister/questions_error.py
andrewebdev/django-appregister
cea086c10ad6b0b84639a828ef3bbfb8d4fb810a
[ "MIT" ]
null
null
null
tests/test_appregister/questions_error.py
andrewebdev/django-appregister
cea086c10ad6b0b84639a828ef3bbfb8d4fb810a
[ "MIT" ]
null
null
null
tests/test_appregister/questions_error.py
andrewebdev/django-appregister
cea086c10ad6b0b84639a828ef3bbfb8d4fb810a
[ "MIT" ]
null
null
null
# This file, on purpose, raises an ImportError. It is used in the tests to # verify that ImportErrors are not lost (by mistaking the import error for this # file not existing) from fake_module_name import something
36
79
0.787037
36
216
4.666667
0.861111
0.095238
0
0
0
0
0
0
0
0
0
0
0.175926
216
5
80
43.2
0.94382
0.782407
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
4
078ba282ab2ee62cce28ff52e1dbc82371d27fc6
705
py
Python
tests/test_normalize.py
Bystroushaak/normalize_cz_unicode
916cd199381f4b73f2e1e4a530e393790fb43a21
[ "MIT" ]
null
null
null
tests/test_normalize.py
Bystroushaak/normalize_cz_unicode
916cd199381f4b73f2e1e4a530e393790fb43a21
[ "MIT" ]
2
2015-05-21T12:39:04.000Z
2020-09-26T08:03:06.000Z
tests/test_normalize.py
Bystroushaak/normalize_cz_unicode
916cd199381f4b73f2e1e4a530e393790fb43a21
[ "MIT" ]
null
null
null
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== from __future__ import unicode_literals from normalize_cz_unicode import normalize # Tests ======================================================================= def test_normalize_czech_set(): assert normalize("ařěščýřčš") == "ařěščýřčš" def test_normalize(): assert normalize("😭") == "?" assert normalize("Ǎ") == "A" # unbreakable and small space assert normalize(" ") == " " assert normalize(" ") == " " def test_strange_dashes(): assert normalize("spojovník — a ― další") == "spojovník - a - další"
25.178571
79
0.521986
66
705
5.424242
0.590909
0.251397
0.089385
0
0
0
0
0
0
0
0
0.005059
0.158865
705
27
80
26.111111
0.593592
0.367376
0
0.181818
0
0
0.155251
0
0
0
0
0
0.545455
1
0.272727
true
0
0.181818
0
0.454545
0
0
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
1
0
1
1
0
0
0
0
0
0
4
07a180564a85bc99c31c9dbd045c090d60e6d122
28,583
py
Python
neutron_fwaas/tests/unit/extensions/test_firewall.py
mail2nsrajesh/neutron-fwaas
8d7cc87711c279789af70af4034b5f4f45dc41b0
[ "Apache-2.0" ]
null
null
null
neutron_fwaas/tests/unit/extensions/test_firewall.py
mail2nsrajesh/neutron-fwaas
8d7cc87711c279789af70af4034b5f4f45dc41b0
[ "Apache-2.0" ]
null
null
null
neutron_fwaas/tests/unit/extensions/test_firewall.py
mail2nsrajesh/neutron-fwaas
8d7cc87711c279789af70af4034b5f4f45dc41b0
[ "Apache-2.0" ]
null
null
null
# Copyright 2013 Big Switch Networks, Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import copy import mock from neutron.tests import base from neutron.tests.unit.api.v2 import test_base as test_api_v2 from neutron.tests.unit.extensions import base as test_api_v2_extension from neutron_lib.db import constants as db_const from oslo_utils import uuidutils from webob import exc import webtest from neutron_fwaas.common import fwaas_constants from neutron_fwaas.extensions import firewall _uuid = uuidutils.generate_uuid _get_path = test_api_v2._get_path _long_name = 'x' * (db_const.NAME_FIELD_SIZE + 1) _long_description = 'y' * (db_const.DESCRIPTION_FIELD_SIZE + 1) class FirewallExtensionTestCase(test_api_v2_extension.ExtensionTestCase): fmt = 'json' def setUp(self): super(FirewallExtensionTestCase, self).setUp() plural_mappings = {'firewall_policy': 'firewall_policies'} self._setUpExtension( 'neutron_fwaas.extensions.firewall.FirewallPluginBase', fwaas_constants.FIREWALL, firewall.RESOURCE_ATTRIBUTE_MAP, firewall.Firewall, 'fw', plural_mappings=plural_mappings) def test_create_firewall(self): fw_id = _uuid() project_id = _uuid() data = {'firewall': {'description': 'descr_firewall1', 'name': 'firewall1', 'admin_state_up': True, 'firewall_policy_id': _uuid(), 'shared': False, 'project_id': project_id, 'tenant_id': project_id}} return_value = copy.copy(data['firewall']) return_value.update({'id': fw_id}) # since 'shared' is hidden del return_value['shared'] instance = self.plugin.return_value instance.create_firewall.return_value = return_value res = self.api.post(_get_path('fw/firewalls', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_firewall.assert_called_with(mock.ANY, firewall=data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall', res) self.assertEqual(return_value, res['firewall']) def test_create_firewall_invalid_long_name(self): project_id = _uuid() data = {'firewall': {'description': 'descr_firewall1', 'name': _long_name, 'admin_state_up': True, 'firewall_policy_id': _uuid(), 'shared': False, 'project_id': project_id, 'tenant_id': project_id}} res = self.api.post(_get_path('fw/firewalls', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt, status=exc.HTTPBadRequest.code) self.assertIn('Invalid input for name', res.body.decode('utf-8')) def test_create_firewall_invalid_long_description(self): project_id = _uuid() data = {'firewall': {'description': _long_description, 'name': 'firewall1', 'admin_state_up': True, 'firewall_policy_id': _uuid(), 'shared': False, 'project_id': project_id, 'tenant_id': project_id}} res = self.api.post(_get_path('fw/firewalls', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt, status=exc.HTTPBadRequest.code) self.assertIn('Invalid input for description', res.body.decode('utf-8')) def test_firewall_list(self): fw_id = _uuid() return_value = [{'tenant_id': _uuid(), 'id': fw_id}] instance = self.plugin.return_value instance.get_firewalls.return_value = return_value res = self.api.get(_get_path('fw/firewalls', fmt=self.fmt)) instance.get_firewalls.assert_called_with(mock.ANY, fields=mock.ANY, filters=mock.ANY) self.assertEqual(exc.HTTPOk.code, res.status_int) def test_firewall_get(self): fw_id = _uuid() return_value = {'tenant_id': _uuid(), 'id': fw_id} instance = self.plugin.return_value instance.get_firewall.return_value = return_value res = self.api.get(_get_path('fw/firewalls', id=fw_id, fmt=self.fmt)) instance.get_firewall.assert_called_with(mock.ANY, fw_id, fields=mock.ANY) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall', res) self.assertEqual(return_value, res['firewall']) def test_firewall_update(self): fw_id = _uuid() update_data = {'firewall': {'name': 'new_name'}} return_value = {'tenant_id': _uuid(), 'id': fw_id} instance = self.plugin.return_value instance.update_firewall.return_value = return_value res = self.api.put(_get_path('fw/firewalls', id=fw_id, fmt=self.fmt), self.serialize(update_data)) instance.update_firewall.assert_called_with(mock.ANY, fw_id, firewall=update_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall', res) self.assertEqual(return_value, res['firewall']) def test_firewall_delete(self): self._test_entity_delete('firewall') def _test_create_firewall_rule(self, src_port, dst_port): rule_id = _uuid() project_id = _uuid() data = {'firewall_rule': {'description': 'descr_firewall_rule1', 'name': 'rule1', 'shared': False, 'protocol': 'tcp', 'ip_version': 4, 'source_ip_address': '192.168.0.1', 'destination_ip_address': '127.0.0.1', 'source_port': src_port, 'destination_port': dst_port, 'action': 'allow', 'enabled': True, 'project_id': project_id, 'tenant_id': project_id}} expected_ret_val = copy.copy(data['firewall_rule']) expected_ret_val['source_port'] = str(src_port) expected_ret_val['destination_port'] = str(dst_port) expected_call_args = copy.copy(expected_ret_val) expected_ret_val['id'] = rule_id instance = self.plugin.return_value instance.create_firewall_rule.return_value = expected_ret_val res = self.api.post(_get_path('fw/firewall_rules', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_firewall_rule.assert_called_with( mock.ANY, firewall_rule={'firewall_rule': expected_call_args}) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall_rule', res) self.assertEqual(expected_ret_val, res['firewall_rule']) def test_create_firewall_rule_with_integer_ports(self): self._test_create_firewall_rule(1, 10) def test_create_firewall_rule_with_string_ports(self): self._test_create_firewall_rule('1', '10') def test_create_firewall_rule_with_port_range(self): self._test_create_firewall_rule('1:20', '30:40') def test_create_firewall_rule_invalid_long_name(self): project_id = _uuid() data = {'firewall_rule': {'description': 'descr_firewall_rule1', 'name': _long_name, 'shared': False, 'protocol': 'tcp', 'ip_version': 4, 'source_ip_address': '192.168.0.1', 'destination_ip_address': '127.0.0.1', 'source_port': 1, 'destination_port': 1, 'action': 'allow', 'enabled': True, 'project_id': project_id, 'tenant_id': project_id}} res = self.api.post(_get_path('fw/firewall_rules', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt, status=exc.HTTPBadRequest.code) self.assertIn('Invalid input for name', res.body.decode('utf-8')) def test_create_firewall_rule_invalid_long_description(self): project_id = _uuid() data = {'firewall_rule': {'description': _long_description, 'name': 'rule1', 'shared': False, 'protocol': 'tcp', 'ip_version': 4, 'source_ip_address': '192.168.0.1', 'destination_ip_address': '127.0.0.1', 'source_port': 1, 'destination_port': 1, 'action': 'allow', 'enabled': True, 'project_id': project_id, 'tenant_id': project_id}} res = self.api.post(_get_path('fw/firewall_rules', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt, status=exc.HTTPBadRequest.code) self.assertIn('Invalid input for description', res.body.decode('utf-8')) def test_firewall_rule_list(self): rule_id = _uuid() return_value = [{'tenant_id': _uuid(), 'id': rule_id}] instance = self.plugin.return_value instance.get_firewall_rules.return_value = return_value res = self.api.get(_get_path('fw/firewall_rules', fmt=self.fmt)) instance.get_firewall_rules.assert_called_with(mock.ANY, fields=mock.ANY, filters=mock.ANY) self.assertEqual(exc.HTTPOk.code, res.status_int) def test_firewall_rule_get(self): rule_id = _uuid() return_value = {'tenant_id': _uuid(), 'id': rule_id} instance = self.plugin.return_value instance.get_firewall_rule.return_value = return_value res = self.api.get(_get_path('fw/firewall_rules', id=rule_id, fmt=self.fmt)) instance.get_firewall_rule.assert_called_with(mock.ANY, rule_id, fields=mock.ANY) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall_rule', res) self.assertEqual(return_value, res['firewall_rule']) def test_firewall_rule_update(self): rule_id = _uuid() update_data = {'firewall_rule': {'action': 'deny'}} return_value = {'tenant_id': _uuid(), 'id': rule_id} instance = self.plugin.return_value instance.update_firewall_rule.return_value = return_value res = self.api.put(_get_path('fw/firewall_rules', id=rule_id, fmt=self.fmt), self.serialize(update_data)) instance.update_firewall_rule.assert_called_with( mock.ANY, rule_id, firewall_rule=update_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall_rule', res) self.assertEqual(return_value, res['firewall_rule']) def test_firewall_rule_delete(self): self._test_entity_delete('firewall_rule') def test_create_firewall_policy(self): policy_id = _uuid() project_id = _uuid() data = {'firewall_policy': {'description': 'descr_firewall_policy1', 'name': 'new_fw_policy1', 'shared': False, 'firewall_rules': [_uuid(), _uuid()], 'audited': False, 'project_id': project_id, 'tenant_id': project_id}} return_value = copy.copy(data['firewall_policy']) return_value.update({'id': policy_id}) instance = self.plugin.return_value instance.create_firewall_policy.return_value = return_value res = self.api.post(_get_path('fw/firewall_policies', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt) instance.create_firewall_policy.assert_called_with( mock.ANY, firewall_policy=data) self.assertEqual(exc.HTTPCreated.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall_policy', res) self.assertEqual(return_value, res['firewall_policy']) def test_create_firewall_policy_invalid_long_name(self): project_id = _uuid() data = {'firewall_policy': {'description': 'descr_firewall_policy1', 'name': _long_name, 'shared': False, 'firewall_rules': [_uuid(), _uuid()], 'audited': False, 'project_id': project_id, 'tenant_id': project_id}} res = self.api.post(_get_path('fw/firewall_policies', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt, status=exc.HTTPBadRequest.code) self.assertIn('Invalid input for name', res.body.decode('utf-8')) def test_create_firewall_policy_invalid_long_description(self): project_id = _uuid() data = {'firewall_policy': {'description': _long_description, 'name': 'new_fw_policy1', 'shared': False, 'firewall_rules': [_uuid(), _uuid()], 'audited': False, 'project_id': project_id, 'tenant_id': project_id}} res = self.api.post(_get_path('fw/firewall_policies', fmt=self.fmt), self.serialize(data), content_type='application/%s' % self.fmt, status=exc.HTTPBadRequest.code) self.assertIn('Invalid input for description', res.body.decode('utf-8')) def test_firewall_policy_list(self): policy_id = _uuid() return_value = [{'tenant_id': _uuid(), 'id': policy_id}] instance = self.plugin.return_value instance.get_firewall_policies.return_value = return_value res = self.api.get(_get_path('fw/firewall_policies', fmt=self.fmt)) instance.get_firewall_policies.assert_called_with(mock.ANY, fields=mock.ANY, filters=mock.ANY) self.assertEqual(exc.HTTPOk.code, res.status_int) def test_firewall_policy_get(self): policy_id = _uuid() return_value = {'tenant_id': _uuid(), 'id': policy_id} instance = self.plugin.return_value instance.get_firewall_policy.return_value = return_value res = self.api.get(_get_path('fw/firewall_policies', id=policy_id, fmt=self.fmt)) instance.get_firewall_policy.assert_called_with(mock.ANY, policy_id, fields=mock.ANY) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall_policy', res) self.assertEqual(return_value, res['firewall_policy']) def test_firewall_policy_update(self): policy_id = _uuid() update_data = {'firewall_policy': {'audited': True}} return_value = {'tenant_id': _uuid(), 'id': policy_id} instance = self.plugin.return_value instance.update_firewall_policy.return_value = return_value res = self.api.put(_get_path('fw/firewall_policies', id=policy_id, fmt=self.fmt), self.serialize(update_data)) instance.update_firewall_policy.assert_called_with( mock.ANY, policy_id, firewall_policy=update_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertIn('firewall_policy', res) self.assertEqual(return_value, res['firewall_policy']) def test_firewall_policy_update_malformed_rules(self): # emulating client request when no rule uuids are provided for # --firewall_rules parameter update_data = {'firewall_policy': {'firewall_rules': True}} # have to check for generic AppError self.assertRaises( webtest.AppError, self.api.put, _get_path('fw/firewall_policies', id=_uuid(), fmt=self.fmt), self.serialize(update_data)) def test_firewall_policy_delete(self): self._test_entity_delete('firewall_policy') def test_firewall_policy_insert_rule(self): firewall_policy_id = _uuid() firewall_rule_id = _uuid() ref_firewall_rule_id = _uuid() insert_data = {'firewall_rule_id': firewall_rule_id, 'insert_before': ref_firewall_rule_id, 'insert_after': None} return_value = {'firewall_policy': {'tenant_id': _uuid(), 'id': firewall_policy_id, 'firewall_rules': [ref_firewall_rule_id, firewall_rule_id]}} instance = self.plugin.return_value instance.insert_rule.return_value = return_value path = _get_path('fw/firewall_policies', id=firewall_policy_id, action="insert_rule", fmt=self.fmt) res = self.api.put(path, self.serialize(insert_data)) instance.insert_rule.assert_called_with(mock.ANY, firewall_policy_id, insert_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertEqual(return_value, res) def test_firewall_policy_remove_rule(self): firewall_policy_id = _uuid() firewall_rule_id = _uuid() remove_data = {'firewall_rule_id': firewall_rule_id} return_value = {'firewall_policy': {'tenant_id': _uuid(), 'id': firewall_policy_id, 'firewall_rules': []}} instance = self.plugin.return_value instance.remove_rule.return_value = return_value path = _get_path('fw/firewall_policies', id=firewall_policy_id, action="remove_rule", fmt=self.fmt) res = self.api.put(path, self.serialize(remove_data)) instance.remove_rule.assert_called_with(mock.ANY, firewall_policy_id, remove_data) self.assertEqual(exc.HTTPOk.code, res.status_int) res = self.deserialize(res) self.assertEqual(return_value, res) class TestFirewallAttributeValidators(base.BaseTestCase): def test_validate_port_range(self): msg = firewall._validate_port_range(None) self.assertIsNone(msg) msg = firewall._validate_port_range('10') self.assertIsNone(msg) msg = firewall._validate_port_range(10) self.assertIsNone(msg) msg = firewall._validate_port_range(-1) self.assertEqual("Invalid port '-1'", msg) msg = firewall._validate_port_range('66000') self.assertEqual("Invalid port '66000'", msg) msg = firewall._validate_port_range('10:20') self.assertIsNone(msg) msg = firewall._validate_port_range('1:65535') self.assertIsNone(msg) msg = firewall._validate_port_range('0:65535') self.assertEqual("Invalid port '0'", msg) msg = firewall._validate_port_range('1:65536') self.assertEqual("Invalid port '65536'", msg) msg = firewall._validate_port_range('abc:efg') self.assertEqual("Port 'abc' is not a valid number", msg) msg = firewall._validate_port_range('1:efg') self.assertEqual("Port 'efg' is not a valid number", msg) msg = firewall._validate_port_range('-1:10') self.assertEqual("Invalid port '-1'", msg) msg = firewall._validate_port_range('66000:10') self.assertEqual("Invalid port '66000'", msg) msg = firewall._validate_port_range('10:66000') self.assertEqual("Invalid port '66000'", msg) msg = firewall._validate_port_range('1:-10') self.assertEqual("Invalid port '-10'", msg) def test_validate_ip_or_subnet_or_none(self): msg = firewall._validate_ip_or_subnet_or_none(None) self.assertIsNone(msg) msg = firewall._validate_ip_or_subnet_or_none('1.1.1.1') self.assertIsNone(msg) msg = firewall._validate_ip_or_subnet_or_none('1.1.1.0/24') self.assertIsNone(msg) ip_addr = '1111.1.1.1' msg = firewall._validate_ip_or_subnet_or_none(ip_addr) self.assertEqual( ("'%s' is not a valid IP address and " "'%s' is not a valid IP subnet") % (ip_addr, ip_addr), msg) ip_addr = '1.1.1.1 has whitespace' msg = firewall._validate_ip_or_subnet_or_none(ip_addr) self.assertEqual( ("'%s' is not a valid IP address and " "'%s' is not a valid IP subnet") % (ip_addr, ip_addr), msg) ip_addr = '111.1.1.1\twhitespace' msg = firewall._validate_ip_or_subnet_or_none(ip_addr) self.assertEqual( ("'%s' is not a valid IP address and " "'%s' is not a valid IP subnet") % (ip_addr, ip_addr), msg) ip_addr = '111.1.1.1\nwhitespace' msg = firewall._validate_ip_or_subnet_or_none(ip_addr) self.assertEqual( ("'%s' is not a valid IP address and " "'%s' is not a valid IP subnet") % (ip_addr, ip_addr), msg) # Valid - IPv4 cidr = "10.0.2.0/24" msg = firewall._validate_ip_or_subnet_or_none(cidr, None) self.assertIsNone(msg) # Valid - IPv6 without final octets cidr = "fe80::/24" msg = firewall._validate_ip_or_subnet_or_none(cidr, None) self.assertIsNone(msg) # Valid - IPv6 with final octets cidr = "fe80::0/24" msg = firewall._validate_ip_or_subnet_or_none(cidr, None) self.assertIsNone(msg) cidr = "fe80::" msg = firewall._validate_ip_or_subnet_or_none(cidr, None) self.assertIsNone(msg) # Invalid - IPv6 with final octets, missing mask cidr = "fe80::0" msg = firewall._validate_ip_or_subnet_or_none(cidr, None) self.assertIsNone(msg) # Invalid - Address format error cidr = 'invalid' msg = firewall._validate_ip_or_subnet_or_none(cidr, None) self.assertEqual( ("'%s' is not a valid IP address and " "'%s' is not a valid IP subnet") % (cidr, cidr), msg) class TestFirewallConvertProtocols(base.BaseTestCase): def test_convert_protocol_string_integer(self): res = firewall.convert_protocol("0") self.assertEqual(0, res) res = firewall.convert_protocol("255") self.assertEqual(255, res) def test_convert_protocol_digit(self): res = firewall.convert_protocol(0) self.assertEqual(0, res) res = firewall.convert_protocol(255) self.assertEqual(255, res) def test_convert_protocol_another_types(self): res = lambda: firewall.convert_protocol(['abc']) self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) res = lambda: firewall.convert_protocol({1: 'foo'}) self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) res = lambda: firewall.convert_protocol((1, 100)) self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) res = lambda: firewall.convert_protocol(object) self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) def test_convert_protocol_invalid_digit(self): res = lambda: firewall.convert_protocol("-1") self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) res = lambda: firewall.convert_protocol("256") self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) def test_convert_protocol_name(self): res = firewall.convert_protocol("tcp") self.assertEqual("tcp", res) res = firewall.convert_protocol("UDP") self.assertEqual("udp", res) res = firewall.convert_protocol("Icmp") self.assertEqual("icmp", res) def test_convert_protocol_invalid_name(self): res = lambda: firewall.convert_protocol("foo") self.assertRaises(firewall.FirewallRuleInvalidProtocol, res) class TestConvertActionToCaseInsensitive(base.BaseTestCase): def test_convert_action_to_case_insensitive_none(self): res = firewall.convert_action_to_case_insensitive(None) self.assertIsNone(res) def test_convert_action_to_case_insensitive_value(self): res = firewall.convert_action_to_case_insensitive("foo") self.assertEqual("foo", res) res = firewall.convert_action_to_case_insensitive("Bar") self.assertEqual("bar", res) res = firewall.convert_action_to_case_insensitive("BAZ") self.assertEqual("baz", res)
42.345185
77
0.557044
3,008
28,583
4.985705
0.094415
0.049143
0.035474
0.023471
0.795359
0.773555
0.740348
0.70214
0.671068
0.605321
0
0.013656
0.344156
28,583
674
78
42.408012
0.786354
0.031382
0
0.589552
0
0
0.124033
0.007375
0
0
0
0
0.188433
1
0.070896
false
0
0.020522
0
0.100746
0
0
0
0
null
0
0
0
0
1
1
1
0
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
4
07a22daa7d12b2725dc4f8ae200d49a840a6c783
309
py
Python
s04_variaveis_tipos_de_dados/s04_exercicios/s04_exercicio_14.py
adeogliari/GeekUniversity_Python
1b6badc45ca1dfbaa2f42196fb2dedac417b866e
[ "MIT" ]
null
null
null
s04_variaveis_tipos_de_dados/s04_exercicios/s04_exercicio_14.py
adeogliari/GeekUniversity_Python
1b6badc45ca1dfbaa2f42196fb2dedac417b866e
[ "MIT" ]
null
null
null
s04_variaveis_tipos_de_dados/s04_exercicios/s04_exercicio_14.py
adeogliari/GeekUniversity_Python
1b6badc45ca1dfbaa2f42196fb2dedac417b866e
[ "MIT" ]
null
null
null
""" 14) Leia um ângulo em graus e apresente-o convertido em radianos. A fórmula de conversão é: R = G * r / 180, sendo G o ângulo em graus e R em radianos e r = 3.14. """ angulo_graus = float(input('Digite o ângulo em graus: \n')) print(f'O ângulo {angulo_graus}º é: {angulo_graus * 3.14 / 180} radianos')
34.333333
162
0.682848
59
309
3.525424
0.474576
0.115385
0.1875
0.134615
0
0
0
0
0
0
0
0.056225
0.194175
309
8
163
38.625
0.779116
0.524272
0
0
0
0
0.666667
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
0
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
1
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
4
07ad5a56cae31506682577e06528009b7d9ea760
125
py
Python
useful/text_to_mp3/test01.py
xmark2/practice
738c52b56530e15fbe141bb352a19c4471dc4c91
[ "BSD-2-Clause" ]
null
null
null
useful/text_to_mp3/test01.py
xmark2/practice
738c52b56530e15fbe141bb352a19c4471dc4c91
[ "BSD-2-Clause" ]
null
null
null
useful/text_to_mp3/test01.py
xmark2/practice
738c52b56530e15fbe141bb352a19c4471dc4c91
[ "BSD-2-Clause" ]
null
null
null
from gtts import gTTS import os tts = gTTS(text='Good morning', lang='en') tts.save("good.mp3") os.system("mpg321 good.mp3")
20.833333
42
0.712
22
125
4.045455
0.636364
0.224719
0
0
0
0
0
0
0
0
0
0.045045
0.112
125
5
43
25
0.756757
0
0
0
0
0
0.296
0
0
0
0
0
0
1
0
false
0
0.4
0
0.4
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
0
0
0
1
0
0
0
0
4
07af434a860b58de1e3322111fb1896e565d344a
1,846
py
Python
calc/migrations/0004_speedups.py
ifireball/sos-calc
9941c543534306c77fe0f08be55af68d5514a2c8
[ "MIT" ]
null
null
null
calc/migrations/0004_speedups.py
ifireball/sos-calc
9941c543534306c77fe0f08be55af68d5514a2c8
[ "MIT" ]
null
null
null
calc/migrations/0004_speedups.py
ifireball/sos-calc
9941c543534306c77fe0f08be55af68d5514a2c8
[ "MIT" ]
1
2021-05-19T14:10:21.000Z
2021-05-19T14:10:21.000Z
# Generated by Django 3.1.5 on 2021-01-08 07:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('calc', '0003_auto_20210106_1104'), ] operations = [ migrations.CreateModel( name='Speedups', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('day', models.DateField()), ('training_1m', models.IntegerField(default=0)), ('training_5m', models.IntegerField(default=0)), ('training_1h', models.IntegerField(default=0)), ('healing_1m', models.IntegerField(default=0)), ('healing_5m', models.IntegerField(default=0)), ('healing_1h', models.IntegerField(default=0)), ('construction_1m', models.IntegerField(default=0)), ('construction_5m', models.IntegerField(default=0)), ('construction_1h', models.IntegerField(default=0)), ('research_1m', models.IntegerField(default=0)), ('research_5m', models.IntegerField(default=0)), ('research_1h', models.IntegerField(default=0)), ('generic_1m', models.IntegerField(default=0)), ('generic_5m', models.IntegerField(default=0)), ('generic_1h', models.IntegerField(default=0)), ('generic_3h', models.IntegerField(default=0)), ('generic_8h', models.IntegerField(default=0)), ('account', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='calc.account')), ], options={ 'unique_together': {('account', 'day')}, }, ), ]
42.930233
114
0.568797
176
1,846
5.823864
0.357955
0.298537
0.414634
0.43122
0.563902
0.068293
0
0
0
0
0
0.049094
0.282774
1,846
42
115
43.952381
0.725076
0.024377
0
0
1
0
0.153974
0.012785
0
0
0
0
0
1
0
false
0
0.055556
0
0.138889
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
07daecc6e79df8189f9c1f48f0d403fdab1eada3
127
py
Python
ex0010.py
EwertonRosendo/PastaDeExercicios
68d23194b87ce1c8405c70fcceb3378955815d7d
[ "MIT" ]
null
null
null
ex0010.py
EwertonRosendo/PastaDeExercicios
68d23194b87ce1c8405c70fcceb3378955815d7d
[ "MIT" ]
null
null
null
ex0010.py
EwertonRosendo/PastaDeExercicios
68d23194b87ce1c8405c70fcceb3378955815d7d
[ "MIT" ]
null
null
null
valor = float(input("quantos reais você tem? ")) print("com {} reais você pode comprar {} dolares!" .format(valor, valor/3.27))
63.5
78
0.692913
19
127
4.631579
0.789474
0.204545
0
0
0
0
0
0
0
0
0
0.027027
0.125984
127
2
78
63.5
0.765766
0
0
0
0
0
0.515625
0
0
0
0
0
0
1
0
false
0
0
0
0
0.5
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
0
0
0
0
0
0
1
0
4
07e0422e29d42c5054ed756b98e82d3969036b50
20
py
Python
data/studio21_generated/introductory/4552/starter_code.py
vijaykumawat256/Prompt-Summarization
614f5911e2acd2933440d909de2b4f86653dc214
[ "Apache-2.0" ]
null
null
null
data/studio21_generated/introductory/4552/starter_code.py
vijaykumawat256/Prompt-Summarization
614f5911e2acd2933440d909de2b4f86653dc214
[ "Apache-2.0" ]
null
null
null
data/studio21_generated/introductory/4552/starter_code.py
vijaykumawat256/Prompt-Summarization
614f5911e2acd2933440d909de2b4f86653dc214
[ "Apache-2.0" ]
null
null
null
def rankings(arr):
10
18
0.7
3
20
4.666667
1
0
0
0
0
0
0
0
0
0
0
0
0.15
20
2
19
10
0.823529
0
0
0
0
0
0
0
0
0
0
0
0
0
null
null
0
0
null
null
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
4
07e806147d966487cd943688f145855f519df54b
7,011
py
Python
test/test_create_dataset.py
usc-isi-i2/datamart-api
da0792786fc342fc3cd6fbfcdeacae0eac6bff0d
[ "MIT" ]
null
null
null
test/test_create_dataset.py
usc-isi-i2/datamart-api
da0792786fc342fc3cd6fbfcdeacae0eac6bff0d
[ "MIT" ]
113
2020-06-22T18:40:53.000Z
2021-07-06T04:18:40.000Z
test/test_create_dataset.py
usc-isi-i2/datamart-api
da0792786fc342fc3cd6fbfcdeacae0eac6bff0d
[ "MIT" ]
1
2020-10-23T07:37:51.000Z
2020-10-23T07:37:51.000Z
import unittest from requests import get import pandas as pd from io import StringIO from test.utility import create_dataset, create_dataset_with_edges, delete_dataset class TestCreateDataset(unittest.TestCase): def setUp(self): self.url = 'http://localhost:12543' self.expected_response = {'name': 'Unit Test Dataset', 'description': 'will be deleted in this unit test', 'url': 'http://unittest101.org', 'dataset_id': 'unittestdataset'} def test_create_dataset_blank_description_url(self): expected_response = [{'error': 'Metadata field: description, cannot be blank'}, {'error': 'Metadata field: url, cannot be blank'}] response = create_dataset(self.url, description='', url='') self.assertEqual(response.status_code, 400) self.assertEqual(expected_response, response.json()) def test_create_dataset_blank_all_fields(self): expected_response = [{'error': 'Metadata field: name, cannot be blank'}, {'error': 'Metadata field: dataset_id, cannot be blank'}, {'error': 'Metadata field: description, cannot be blank'}, {'error': 'Metadata field: url, cannot be blank'}] response = create_dataset(self.url, name='', description='', url='', dataset_id='') self.assertEqual(response.status_code, 400) self.assertEqual(expected_response, response.json()) def test_create_dataset_3(self): delete_dataset(self.url) response = create_dataset(self.url) self.assertEqual(response.status_code, 201) response = get(f'{self.url}/metadata/datasets').json() d_metadata = None for x in response: if x['dataset_id'] == self.expected_response['dataset_id']: d_metadata = x self.assertTrue('name' in d_metadata) self.assertTrue('description' in d_metadata) self.assertTrue('dataset_id' in d_metadata) self.assertTrue('url' in d_metadata) self.assertTrue('last_update_precision' in d_metadata) self.assertTrue('last_update' in d_metadata) self.assertEqual(self.expected_response['dataset_id'], d_metadata['dataset_id']) self.assertEqual(self.expected_response['name'], d_metadata['name']) self.assertEqual(self.expected_response['url'], d_metadata['url']) self.assertEqual(self.expected_response['description'], d_metadata['description']) # delete the dataset for future runs delete_dataset(self.url) def test_create_dataset_edges(self): delete_dataset(self.url) r = create_dataset(self.url, return_edges=True) expected_labels = [ 'P31', 'label', 'P1476', 'description', 'P2699', 'P1813', 'P5017' ] df = pd.read_csv(StringIO(r.text), sep='\t') self.assertTrue(len(df) == 7) for i, row in df.iterrows(): self.assertEqual(row['node1'], 'Qunittestdataset') self.assertTrue(row['label'] in expected_labels) if row['label'] == 'P31': self.assertEqual(row['node2'], 'Q1172284') if row['label'] == 'label': self.assertEqual(row['node2'], 'Unit Test Dataset') if row['label'] == 'P1476': self.assertEqual(row['node2'], 'Unit Test Dataset') if row['label'] == 'description': self.assertEqual(row['node2'], 'will be deleted in this unit test') if row['label'] == 'P2699': self.assertEqual(row['node2'], 'http://unittest101.org') if row['label'] == 'P1813': self.assertEqual(row['node2'], 'unittestdataset') # test the actual response from API as well response = get(f'{self.url}/metadata/datasets').json() d_metadata = None for x in response: if x['dataset_id'] == self.expected_response['dataset_id']: d_metadata = x self.assertTrue('name' in d_metadata) self.assertTrue('description' in d_metadata) self.assertTrue('dataset_id' in d_metadata) self.assertTrue('url' in d_metadata) self.assertTrue('last_update_precision' in d_metadata) self.assertTrue('last_update' in d_metadata) self.assertEqual(self.expected_response['dataset_id'], d_metadata['dataset_id']) self.assertEqual(self.expected_response['name'], d_metadata['name']) self.assertEqual(self.expected_response['url'], d_metadata['url']) self.assertEqual(self.expected_response['description'], d_metadata['description']) # delete the dataset for future runs delete_dataset(self.url) def test_create_dataset_with_edges(self): delete_dataset(self.url) response = create_dataset_with_edges(self.url) self.assertEqual(response.status_code, 201) response = get(f'{self.url}/metadata/datasets').json() d_metadata = None for x in response: if x['dataset_id'] == self.expected_response['dataset_id']: d_metadata = x self.assertTrue('name' in d_metadata) self.assertTrue('description' in d_metadata) self.assertTrue('dataset_id' in d_metadata) self.assertTrue('url' in d_metadata) self.assertTrue('last_update_precision' in d_metadata) self.assertTrue('last_update' in d_metadata) self.assertEqual(self.expected_response['dataset_id'], d_metadata['dataset_id']) self.assertEqual(self.expected_response['name'], d_metadata['name']) self.assertEqual(self.expected_response['url'], d_metadata['url']) self.assertEqual(self.expected_response['description'], d_metadata['description']) # delete the dataset for future runs delete_dataset(self.url) def test_create_dataset_with_edges_fail_1(self): delete_dataset(self.url) response = create_dataset_with_edges(self.url, delete_labels=['P31']) self.assertEqual(response.status_code, 400) result = response.json() self.assertTrue('Error' in result) self.assertTrue('Missing required properties' in result['Error']) self.assertTrue('P31' in result['Missing_Required_Properties']) def test_create_dataset_with_edges_fail_2(self): delete_dataset(self.url) response = create_dataset_with_edges(self.url, extra_edges=[('P131', 'Q115')]) self.assertEqual(response.status_code, 400) result = response.json() self.assertTrue('Error' in result) self.assertTrue('Properties not recognized' in result['Error']) self.assertTrue('P131' in result['Properties_Not_Recognized'])
39.167598
94
0.622165
794
7,011
5.29597
0.13728
0.077051
0.085612
0.064209
0.759096
0.73912
0.707253
0.685612
0.674911
0.674911
0
0.017675
0.257595
7,011
178
95
39.38764
0.790202
0.020824
0
0.543307
0
0
0.191545
0.029009
0
0
0
0
0.417323
1
0.062992
false
0
0.03937
0
0.110236
0
0
0
0
null
0
0
0
0
1
1
0
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
4
58013e4328942781af3a8376b05428855e45fdb3
217
py
Python
audionmf/fileformats/audio_format.py
argoneuscze/AudioNMF
04f360653bb0df3d5ed19bf2eb1459bff16a944c
[ "MIT" ]
null
null
null
audionmf/fileformats/audio_format.py
argoneuscze/AudioNMF
04f360653bb0df3d5ed19bf2eb1459bff16a944c
[ "MIT" ]
null
null
null
audionmf/fileformats/audio_format.py
argoneuscze/AudioNMF
04f360653bb0df3d5ed19bf2eb1459bff16a944c
[ "MIT" ]
null
null
null
from abc import ABC class AudioFormat(ABC): def fill_audio_data(self, input_fd, audio_data): raise NotImplementedError def write_file(self, audio_data, output_fd): raise NotImplementedError
21.7
52
0.732719
28
217
5.428571
0.607143
0.177632
0
0
0
0
0
0
0
0
0
0
0.207373
217
9
53
24.111111
0.883721
0
0
0.333333
0
0
0
0
0
0
0
0
0
1
0.333333
false
0
0.166667
0
0.666667
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
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
6afbe18064c46737cdbc4c8ca1ea9d07b79003b0
5,057
py
Python
blueoil/converter/core/data_types.py
msakai/blueoil
0c9160b524b17482d59ae48a0c11384f1d26dccc
[ "Apache-2.0" ]
248
2018-10-19T01:48:42.000Z
2022-01-31T02:34:24.000Z
blueoil/converter/core/data_types.py
oatawa1/blueoil
6a5f1cc1fb78c86423338f99cb9dbf506a76f3d6
[ "Apache-2.0" ]
1,102
2018-10-19T04:50:34.000Z
2021-08-02T04:22:10.000Z
blueoil/converter/core/data_types.py
oatawa1/blueoil
6a5f1cc1fb78c86423338f99cb9dbf506a76f3d6
[ "Apache-2.0" ]
110
2018-10-19T01:49:02.000Z
2022-01-31T02:34:26.000Z
# -*- coding: utf-8 -*- # Copyright 2018 The Blueoil Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================= from typing import List import numpy as np def quantized_packed_type(t): return f"QuantizedPacked<{t}>" class DataType(object): def __str__(self) -> str: return type(self).__name__ @classmethod def pytype(cls): raise NotImplementedError @classmethod def cpptype(cls): raise NotImplementedError @classmethod def nptype(cls): raise NotImplementedError @classmethod def name(cls): return cls.__name__ def __eq__(self, other): return type(self).__name__ == type(other).__name__ class Primitive(DataType): @classmethod def is_primitive(cls): True class Special(DataType): @classmethod def is_primitive(cls): False class Int(Special): @classmethod def pytype(cls): return int @classmethod def cpptype(cls): return 'int' class UInt(Special): @classmethod def cpptype(cls): return 'unsigned' class Int8(Primitive): @classmethod def cpptype(cls): return 'int8_t' @classmethod def nptype(cls): return np.int8 class Uint8(Primitive): @classmethod def cpptype(cls): return 'uint8_t' @classmethod def nptype(cls): return np.uint8 class Int16(Primitive): @classmethod def cpptype(cls): return 'int16_t' @classmethod def nptype(cls): return np.int16 class Uint16(Primitive): @classmethod def cpptype(cls): return 'uint16_t' @classmethod def nptype(cls): return np.uint16 class Int32(Primitive): @classmethod def cpptype(cls): return 'int32_t' @classmethod def nptype(cls): return np.int32 class Uint32(Primitive): @classmethod def cpptype(cls): return 'uint32_t' @classmethod def nptype(cls): return np.uint32 class PackedUint32(Primitive): @classmethod def cpptype(cls): return 'QuantizedPacked<uint32_t>' @classmethod def nptype(cls): return np.uint32 class Int64(Primitive): @classmethod def cpptype(cls): return 'int64_t' @classmethod def nptype(cls): return np.int64 class Uint64(Primitive): @classmethod def cpptype(cls): return 'uint64_t' @classmethod def nptype(cls): return np.uint64 class PackedUint64(Primitive): @classmethod def cpptype(cls): return 'QuantizedPacked<uint64_t>' @classmethod def nptype(cls): return np.uint64 class Float(Special, float): @classmethod def pytype(cls): return float @classmethod def cpptype(cls): return 'float' class Float32(Primitive, float): @classmethod def cpptype(cls): return 'float' @classmethod def nptype(cls): return np.float32 class Float64(Primitive, float): @classmethod def cpptype(cls): return 'double' @classmethod def nptype(cls): return np.float64 class String(DataType): @classmethod def cpptype(cls): return 'std::string' class Void(DataType): @classmethod def pytype(cls): return None @classmethod def cpptype(cls): return 'void' class Any(DataType): @classmethod def cpptype(cls): return 'std::any' class Bool(DataType): @classmethod def cpptype(cls): return 'bool' @classmethod def nptype(cls): return np.bool_ class Size(DataType): @classmethod def cpptype(cls): return 'size_t' class Shape(DataType, List[Size]): @classmethod def cpptype(cls): return 'shape_t' class Vec(DataType, List[Primitive]): @classmethod def cpptype(cls): return 'vec_t' class QUANTIZED_NOT_PACKED(Primitive): @classmethod def cpptype(cls): return 'QUANTIZED_NOT_PACKED' @classmethod def nptype(cls): return np.int8 class QUANTIZED_PACKED(Primitive): @classmethod def cpptype(cls): return 'QUANTIZED_PACKED' @classmethod def nptype(cls): return np.uint32 class QUANTIZED_PACKED_KERNEL(Primitive): @classmethod def cpptype(cls): return 'QUANTIZED_PACKED_KERNEL' @classmethod def nptype(cls): return np.uint32
17.681818
79
0.628436
568
5,057
5.503521
0.225352
0.223928
0.174664
0.199616
0.619002
0.513436
0.324056
0.15547
0.0627
0.0627
0
0.020535
0.268143
5,057
285
80
17.74386
0.824102
0.134072
0
0.602151
0
0
0.059363
0.016732
0
0
0
0
0
1
0.284946
false
0
0.010753
0.258065
0.704301
0
0
0
0
null
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
4
ed4ba3be9b0f06376beb33301db27b2a59640493
79
py
Python
data_labeling_examples/bulk_labeling_python/bounding_box_config.py
wprichard/oci-data-science-ai-samples
f1da6c26e60ad70958bad6b26cc733db960fe371
[ "UPL-1.0", "Apache-2.0" ]
null
null
null
data_labeling_examples/bulk_labeling_python/bounding_box_config.py
wprichard/oci-data-science-ai-samples
f1da6c26e60ad70958bad6b26cc733db960fe371
[ "UPL-1.0", "Apache-2.0" ]
null
null
null
data_labeling_examples/bulk_labeling_python/bounding_box_config.py
wprichard/oci-data-science-ai-samples
f1da6c26e60ad70958bad6b26cc733db960fe371
[ "UPL-1.0", "Apache-2.0" ]
2
2022-03-28T07:27:28.000Z
2022-03-28T21:18:36.000Z
# the path of the csv file PATH = "/Users/puneetmittal/Desktop/input_data.csv"
26.333333
51
0.759494
13
79
4.538462
0.769231
0
0
0
0
0
0
0
0
0
0
0
0.126582
79
2
52
39.5
0.855072
0.303797
0
0
0
0
0.792453
0.792453
0
0
0
0
0
1
0
false
0
0
0
0
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
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
ed52e07e9565a75e06f5bce419897cac34d51b9d
21
py
Python
django_outlook/__init__.py
weijia/django-outlook
3f6b22e3ec34890c9b84699a22b2e39b8cadc723
[ "MIT" ]
null
null
null
django_outlook/__init__.py
weijia/django-outlook
3f6b22e3ec34890c9b84699a22b2e39b8cadc723
[ "MIT" ]
2
2018-12-26T19:10:02.000Z
2021-11-15T17:47:55.000Z
django_outlook/__init__.py
weijia/django-outlook
3f6b22e3ec34890c9b84699a22b2e39b8cadc723
[ "MIT" ]
null
null
null
__version__="0.1.2"
10.5
20
0.666667
4
21
2.5
1
0
0
0
0
0
0
0
0
0
0
0.157895
0.095238
21
1
21
21
0.368421
0
0
0
0
0
0.25
0
0
0
0
0
0
1
0
false
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
ed6d0c199b2073e530245f93ebc9ff453bf8e1bc
608
py
Python
project1/srv/model/users.py
mission-liao/flask_template
59bc2572914363ec14baff7a99ba7ca06b16bed5
[ "MIT" ]
null
null
null
project1/srv/model/users.py
mission-liao/flask_template
59bc2572914363ec14baff7a99ba7ca06b16bed5
[ "MIT" ]
null
null
null
project1/srv/model/users.py
mission-liao/flask_template
59bc2572914363ec14baff7a99ba7ca06b16bed5
[ "MIT" ]
null
null
null
from __future__ import absolute_import from ..api import login_serializer, sql from flask.ext.login import UserMixin class Users(UserMixin, sql.Model): """ class Users only kept static information here. For dynamic info, ex. last-login, we would kept them in other table """ id = sql.Column(sql.Integer, sql.Sequence('user_id_seq', start=1, increment=1), primary_key=True) email = sql.Column(sql.String(255), unique=True) password = sql.Column(sql.LargeBinary, nullable=False) def get_auth_token(self): return login_serializer.dumps(self.email, self.password)
32
101
0.723684
87
608
4.91954
0.655172
0.063084
0.084112
0
0
0
0
0
0
0
0
0.00994
0.172697
608
18
102
33.777778
0.840954
0.189145
0
0
0
0
0.023504
0
0
0
0
0
0
1
0.111111
false
0.222222
0.333333
0.111111
1
0
0
0
0
null
0
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
0
0
1
1
1
1
0
0
4
71f88332454b3656f6a92117f04c48ad2718ac26
157
py
Python
desafios resolvidos/des014.py
EduardoWS/desafios-de-python
1f64115827c6928c3e597c769b0cdb196ae9aa44
[ "MIT" ]
2
2021-04-02T23:15:57.000Z
2021-04-10T22:04:13.000Z
desafios resolvidos/des014.py
EduardoWS/desafios-de-python
1f64115827c6928c3e597c769b0cdb196ae9aa44
[ "MIT" ]
null
null
null
desafios resolvidos/des014.py
EduardoWS/desafios-de-python
1f64115827c6928c3e597c769b0cdb196ae9aa44
[ "MIT" ]
null
null
null
print() print('=' * 40) temp = int(input('Temp em ºC: ')) conv = ((temp/5) * 9) + 32 print() print(f'{temp}ºC = {conv}ºF') print() print('=' * 40) print()
13.083333
33
0.535032
25
157
3.36
0.52
0.357143
0.285714
0
0
0
0
0
0
0
0
0.062016
0.178344
157
11
34
14.272727
0.589147
0
0
0.666667
0
0
0.210191
0
0
0
0
0
0
1
0
false
0
0
0
0
0.777778
1
0
0
null
1
1
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
0
0
0
0
0
0
1
0
4
9c0296af3cab7d13455541f1831ecc3271e24c4b
720
py
Python
pyefun/wxefun/component/ScrollBar.py
nuo010/pyefun
c1c4dfcfd382a67df005a66958da95aa13c30686
[ "Apache-2.0" ]
94
2021-05-19T04:09:29.000Z
2022-03-27T04:02:30.000Z
pyefun/wxefun/component/ScrollBar.py
1431241631/pyefun
ac2290d4bcc8de16c195d2782f3eacd26e5e6ed4
[ "Apache-2.0" ]
11
2021-05-22T06:44:19.000Z
2021-12-27T11:16:06.000Z
pyefun/wxefun/component/ScrollBar.py
1431241631/pyefun
ac2290d4bcc8de16c195d2782f3eacd26e5e6ed4
[ "Apache-2.0" ]
21
2021-05-22T21:08:09.000Z
2022-02-24T02:39:06.000Z
import wx from .wxControl import * class 滚动条(wx.ScrollBar, 公用方法): pass def 取页面大小(self): return self.GetPageSize() def 取最大位置(self): return self.GetRange() def 取当前位置(self): return self.GetThumbPosition() def 取滑块大小(self): return self.GetThumbSize() def 是否为垂直滚动条(self): return self.IsVertical() @组件_异常检测 def 置当前位置(self,位置): return self.SetThumbPosition() def 置滚动条属性(self,当前位置,滑块大小,最大位置,页面大小,是否重绘=True): """ 假设您希望使用相同的字体显示50行文本。窗口的大小设置为一次只能看到16行。您将使用: scrollbar.SetScrollbar(0, 16, 50, 15) 页面大小比拇指大小小1,因此上一页的最后一行将在下一页可见,以帮助定向用户 """ return self.SetScrollbar(当前位置,滑块大小,最大位置,页面大小,是否重绘)
20.571429
58
0.629167
79
720
5.721519
0.56962
0.154867
0.154867
0.070796
0.088496
0
0
0
0
0
0
0.022599
0.2625
720
34
59
21.176471
0.828625
0.166667
0
0
0
0
0
0
0
0
0
0
0
1
0.368421
false
0.052632
0.105263
0.315789
0.894737
0
0
0
0
null
0
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
0
1
0
1
1
0
0
4
9c0779a89c3e6ff5bd227901bb8ceaa71e6421e1
7,572
py
Python
src/front-door/azext_front_door/_help.py
mayank88mahajan/azure-cli-extensions
8bd389a1877bffd14052bec5519ce75dc6fc34cf
[ "MIT" ]
1
2019-05-10T19:58:09.000Z
2019-05-10T19:58:09.000Z
src/front-door/azext_front_door/_help.py
mayank88mahajan/azure-cli-extensions
8bd389a1877bffd14052bec5519ce75dc6fc34cf
[ "MIT" ]
null
null
null
src/front-door/azext_front_door/_help.py
mayank88mahajan/azure-cli-extensions
8bd389a1877bffd14052bec5519ce75dc6fc34cf
[ "MIT" ]
null
null
null
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- from knack.help_files import helps from azext_front_door.vendored_sdks.models import MatchCondition, Operator # region FrontDoor helps['network front-door'] = """ type: group short-summary: Manage Front Doors. """ helps['network front-door create'] = """ type: command short-summary: Create a Front Door. """ helps['network front-door list'] = """ type: command short-summary: List Front Doors. """ helps['network front-door show'] = """ type: command short-summary: Get the details of a Front Door. """ helps['network front-door update'] = """ type: command short-summary: Update settings of a Front Door. """ helps['network front-door delete'] = """ type: command short-summary: Delete a Front Door. """ # endregion # region FrontDoor BackendPool helps['network front-door backend-pool'] = """ type: group short-summary: Manage Front Door backend pools. """ helps['network front-door backend-pool create'] = """ type: command short-summary: Create a Front Door backend pool. long-summary: > Since a backend pool must contain a backend, this command also creates the first backend. To add additional backends, use the `az network front-door backend-pool backend add` command. """ helps['network front-door backend-pool list'] = """ type: command short-summary: List Front Door backend pools. """ helps['network front-door backend-pool show'] = """ type: command short-summary: Get the details of a Front Door backend pool. """ helps['network front-door backend-pool delete'] = """ type: command short-summary: Delete a Front Door backend pool. """ # endregion # region FrontDoor BackendPool Backend helps['network front-door backend-pool backend'] = """ type: group short-summary: Manage backends of Front Door backend pools. """ helps['network front-door backend-pool backend add'] = """ type: command short-summary: Add a backend to a Front Door backend pool. """ helps['network front-door backend-pool backend list'] = """ type: command short-summary: List backends of a Front Door backend pool. """ helps['network front-door backend-pool backend remove'] = """ type: command short-summary: Remove a backend from a Front Door backend pool. """ # endregion # region FrontDoor FrontendEndpoint helps['network front-door frontend-endpoint'] = """ type: group short-summary: Manage Front Door frontend endpoints. """ helps['network front-door frontend-endpoint create'] = """ type: command short-summary: Create a Front Door frontend endpoint. """ helps['network front-door frontend-endpoint list'] = """ type: command short-summary: List Front Door frontend endpoints. """ helps['network front-door frontend-endpoint show'] = """ type: command short-summary: Get the details of a Front Door frontend endpoint. """ helps['network front-door frontend-endpoint delete'] = """ type: command short-summary: Delete a Front Door frontend endpoint. """ # endregion # region FrontDoor LoadBalancingSettings helps['network front-door load-balancing'] = """ type: group short-summary: Manage Front Door load-balancing settings. """ helps['network front-door load-balancing create'] = """ type: command short-summary: Create Front Door load-balancing settings. """ helps['network front-door load-balancing list'] = """ type: command short-summary: List Front Door load-balancing settingss. """ helps['network front-door load-balancing show'] = """ type: command short-summary: Get the details of a Front Door load-balancing settings bundle. """ helps['network front-door load-balancing delete'] = """ type: command short-summary: Delete Front Door load-balancing settings. """ # endregion # region FrontDoor HealthProbeSettings helps['network front-door probe'] = """ type: group short-summary: Manage Front Door health probe settings. """ helps['network front-door probe create'] = """ type: command short-summary: Create Front Door health probe settings. """ helps['network front-door probe list'] = """ type: command short-summary: List Front Door health probe settings. """ helps['network front-door probe show'] = """ type: command short-summary: Get the details of a Front Door health probe settings bundle. """ helps['network front-door probe delete'] = """ type: command short-summary: Delete Front Door health probe settings. """ # endregion # region FrontDoor RoutingRule helps['network front-door routing-rule'] = """ type: group short-summary: Manage Front Door routing rules. """ helps['network front-door routing-rule create'] = """ type: command short-summary: Create a Front Door routing rule. """ helps['network front-door routing-rule list'] = """ type: command short-summary: List Front Door routing rules. """ helps['network front-door routing-rule show'] = """ type: command short-summary: Get the details of a Front Door routing rule. """ helps['network front-door routing-rule delete'] = """ type: command short-summary: Delete a Front Door routing rule. """ # endregion # region WAFPolicy helps['network waf-policy'] = """ type: group short-summary: Manage WebApplication Firewall (WAF) policies. """ helps['network waf-policy create'] = """ type: command short-summary: Create a WAF policy. """ helps['network waf-policy list'] = """ type: command short-summary: List WAF policies. """ helps['network waf-policy show'] = """ type: command short-summary: Get the details of a WAF policy. """ helps['network waf-policy update'] = """ type: command short-summary: Update settings of a WAF policy. """ helps['network waf-policy delete'] = """ type: command short-summary: Delete a WAF policy. """ helps['network waf-policy set-managed-ruleset'] = """ type: command short-summary: Configure Azure-managed ruleset. """ helps['network waf-policy custom-rule'] = """ type: group short-summary: Manage WAF policy custom rules. """ helps['network waf-policy custom-rule create'] = """ type: command short-summary: Create a WAF policy custom rule. parameters: - name: --match-condition short-summary: Match condition for the rule. long-summary: | Usage: --match-condition VARIABLE OPERATOR [VALUE [VALUE ...]] Variable allowed values: {variables} Operator allowed values: {operators} Multiple match conditions can be specified by using more than one `--match-condition` argument. """.format( variables=', '.join([x.value for x in MatchCondition]), operators=', '.join([x.value for x in Operator]) ) helps['network waf-policy custom-rule list'] = """ type: command short-summary: List WAF policy custom rules. """ helps['network waf-policy custom-rule show'] = """ type: command short-summary: Get the details of a WAF policy custom rule. """ helps['network waf-policy custom-rule delete'] = """ type: command short-summary: Delete a WAF policy custom rule. """ # endregion
27.139785
107
0.666403
930
7,572
5.421505
0.135484
0.12495
0.120587
0.173344
0.774693
0.731654
0.61186
0.534708
0.433955
0.312574
0
0
0.191495
7,572
278
108
27.23741
0.823587
0.086503
0
0.453659
0
0
0.827291
0
0
0
0
0
0
1
0
true
0
0.009756
0
0.009756
0
0
0
0
null
0
0
1
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
9c13f58e1d9952e71809b433af943d4c7b79a07c
68
py
Python
marketpsych/__init__.py
marketpsych/sftp
dbff90233b01bdf06fe8f9d09f0ac86292f5cb6a
[ "MIT" ]
2
2021-07-08T03:12:09.000Z
2021-09-27T08:31:20.000Z
marketpsych/__init__.py
marketpsych/sftp
dbff90233b01bdf06fe8f9d09f0ac86292f5cb6a
[ "MIT" ]
null
null
null
marketpsych/__init__.py
marketpsych/sftp
dbff90233b01bdf06fe8f9d09f0ac86292f5cb6a
[ "MIT" ]
3
2021-09-12T21:08:31.000Z
2022-01-11T16:21:38.000Z
from .sftp import * from .mpwidgets import * __version__ = "0.0.15"
17
24
0.705882
10
68
4.4
0.7
0
0
0
0
0
0
0
0
0
0
0.070175
0.161765
68
3
25
22.666667
0.701754
0
0
0
0
0
0.088235
0
0
0
0
0
0
1
0
false
0
0.666667
0
0.666667
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
9c5c583c8e39fdc1766ed96248de563bd28dbe1e
633
py
Python
info/migrations/0003_auto_20180708_1547.py
MrRobot100/applibro
19552ee8171c7006f1a9799dd642993f082317ea
[ "MIT" ]
null
null
null
info/migrations/0003_auto_20180708_1547.py
MrRobot100/applibro
19552ee8171c7006f1a9799dd642993f082317ea
[ "MIT" ]
3
2019-11-30T15:45:33.000Z
2021-06-10T20:32:28.000Z
info/migrations/0003_auto_20180708_1547.py
ParserKnight/django-app-book
19552ee8171c7006f1a9799dd642993f082317ea
[ "MIT" ]
null
null
null
# Generated by Django 2.0.7 on 2018-07-08 15:47 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('info', '0002_auto_20180708_1526'), ] operations = [ migrations.AlterModelOptions( name='front', options={'verbose_name_plural': 'categories'}, ), migrations.AlterModelOptions( name='informacion', options={'verbose_name_plural': 'categories'}, ), migrations.AlterModelOptions( name='usuarios', options={'verbose_name_plural': 'categories'}, ), ]
24.346154
58
0.582938
55
633
6.545455
0.618182
0.225
0.258333
0.2
0.455556
0.361111
0.361111
0.361111
0
0
0
0.069663
0.296998
633
25
59
25.32
0.739326
0.07109
0
0.473684
1
0
0.235495
0.039249
0
0
0
0
0
1
0
false
0
0.052632
0
0.210526
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
9c689e142c0399552fc87adad5963f6d375ac94b
85
py
Python
bazel/apps.py
blowUA/mezz
caf909ad6dd48a61e735bbff7203573f0a61c0d7
[ "MIT" ]
null
null
null
bazel/apps.py
blowUA/mezz
caf909ad6dd48a61e735bbff7203573f0a61c0d7
[ "MIT" ]
null
null
null
bazel/apps.py
blowUA/mezz
caf909ad6dd48a61e735bbff7203573f0a61c0d7
[ "MIT" ]
null
null
null
from django.apps import AppConfig class BazelConfig(AppConfig): name = 'bazel'
14.166667
33
0.741176
10
85
6.3
0.9
0
0
0
0
0
0
0
0
0
0
0
0.176471
85
5
34
17
0.9
0
0
0
0
0
0.058824
0
0
0
0
0
0
1
0
false
0
0.333333
0
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
92bccf5bd5ddec677655a1c9e66ec125d8601994
177
py
Python
wavegui/__init__.py
pyflow/wavegui
7465d2c032ff959db90589e2595b69f205dd0568
[ "MIT" ]
1
2021-06-04T06:22:10.000Z
2021-06-04T06:22:10.000Z
wavegui/__init__.py
pyflow/wavegui
7465d2c032ff959db90589e2595b69f205dd0568
[ "MIT" ]
null
null
null
wavegui/__init__.py
pyflow/wavegui
7465d2c032ff959db90589e2595b69f205dd0568
[ "MIT" ]
1
2021-06-24T03:40:56.000Z
2021-06-24T03:40:56.000Z
__version__ = '0.1.0' from .core import Ref, data, pack, Expando from .types import * from .session import AsyncPage, Query from .main import WaveApp app = WaveApp() Q = Query
19.666667
42
0.728814
27
177
4.62963
0.666667
0
0
0
0
0
0
0
0
0
0
0.020408
0.169492
177
9
43
19.666667
0.829932
0
0
0
0
0
0.02809
0
0
0
0
0
0
1
0
false
0
0.571429
0
0.571429
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
92c432eb33e327e065f7931fc33047fc2553c738
321
py
Python
api/drinks/serializers/uom.py
gthole/drink-stash
873393fddeaa8f58a8b70d082fbff60175901f97
[ "MIT" ]
7
2019-03-11T22:43:38.000Z
2022-02-21T13:18:39.000Z
api/drinks/serializers/uom.py
gthole/drink-stash
873393fddeaa8f58a8b70d082fbff60175901f97
[ "MIT" ]
62
2018-10-13T17:39:07.000Z
2022-02-26T06:21:41.000Z
api/drinks/serializers/uom.py
gthole/drink-stash
873393fddeaa8f58a8b70d082fbff60175901f97
[ "MIT" ]
1
2020-10-31T16:10:59.000Z
2020-10-31T16:10:59.000Z
from rest_framework.serializers import BaseSerializer from django.shortcuts import get_object_or_404 from drinks.models import Uom class UomSerializer(BaseSerializer): def to_internal_value(self, data): return get_object_or_404(Uom, name=data) def to_representation(self, obj): return obj.name
26.75
53
0.778816
44
321
5.454545
0.613636
0.075
0.091667
0.116667
0
0
0
0
0
0
0
0.022305
0.161994
321
11
54
29.181818
0.869888
0
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.375
0.25
1
0
0
0
0
null
0
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
0
0
1
1
1
0
0
4
92c52809b8a754034d56b59276f08e842138362a
3,892
py
Python
streaming_data_types/fbschemas/action_response_answ/ActionResponse.py
geishm-ansto/python-streaming-data-types
0018bec680b31130a559c3113d959f611d6dc6c3
[ "BSD-2-Clause" ]
null
null
null
streaming_data_types/fbschemas/action_response_answ/ActionResponse.py
geishm-ansto/python-streaming-data-types
0018bec680b31130a559c3113d959f611d6dc6c3
[ "BSD-2-Clause" ]
9
2020-03-03T13:27:35.000Z
2021-07-05T13:41:13.000Z
streaming_data_types/fbschemas/action_response_answ/ActionResponse.py
geishm-ansto/python-streaming-data-types
0018bec680b31130a559c3113d959f611d6dc6c3
[ "BSD-2-Clause" ]
1
2020-08-05T07:15:17.000Z
2020-08-05T07:15:17.000Z
# automatically generated by the FlatBuffers compiler, do not modify # namespace: import flatbuffers from flatbuffers.compat import import_numpy np = import_numpy() class ActionResponse(object): __slots__ = ["_tab"] @classmethod def GetRootAsActionResponse(cls, buf, offset): n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) x = ActionResponse() x.Init(buf, n + offset) return x @classmethod def ActionResponseBufferHasIdentifier(cls, buf, offset, size_prefixed=False): return flatbuffers.util.BufferHasIdentifier( buf, offset, b"\x61\x6E\x73\x77", size_prefixed=size_prefixed ) # ActionResponse def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # ActionResponse def ServiceId(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) if o != 0: return self._tab.String(o + self._tab.Pos) return None # ActionResponse def JobId(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) if o != 0: return self._tab.String(o + self._tab.Pos) return None # ActionResponse def Action(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) return 0 # ActionResponse def Outcome(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) return 0 # ActionResponse def StatusCode(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) if o != 0: return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) return 0 # ActionResponse def StopTime(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) if o != 0: return self._tab.Get( flatbuffers.number_types.Uint64Flags, o + self._tab.Pos ) return 0 # ActionResponse def Message(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) if o != 0: return self._tab.String(o + self._tab.Pos) return None # ActionResponse def CommandId(self): o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) if o != 0: return self._tab.String(o + self._tab.Pos) return None def ActionResponseStart(builder): builder.StartObject(8) def ActionResponseAddServiceId(builder, serviceId): builder.PrependUOffsetTRelativeSlot( 0, flatbuffers.number_types.UOffsetTFlags.py_type(serviceId), 0 ) def ActionResponseAddJobId(builder, jobId): builder.PrependUOffsetTRelativeSlot( 1, flatbuffers.number_types.UOffsetTFlags.py_type(jobId), 0 ) def ActionResponseAddAction(builder, action): builder.PrependInt8Slot(2, action, 0) def ActionResponseAddOutcome(builder, outcome): builder.PrependInt8Slot(3, outcome, 0) def ActionResponseAddStatusCode(builder, statusCode): builder.PrependInt32Slot(4, statusCode, 0) def ActionResponseAddStopTime(builder, stopTime): builder.PrependUint64Slot(5, stopTime, 0) def ActionResponseAddMessage(builder, message): builder.PrependUOffsetTRelativeSlot( 6, flatbuffers.number_types.UOffsetTFlags.py_type(message), 0 ) def ActionResponseAddCommandId(builder, commandId): builder.PrependUOffsetTRelativeSlot( 7, flatbuffers.number_types.UOffsetTFlags.py_type(commandId), 0 ) def ActionResponseEnd(builder): return builder.EndObject()
28.617647
88
0.677544
435
3,892
5.917241
0.227586
0.067988
0.136752
0.16317
0.461927
0.461927
0.398213
0.398213
0.371018
0.371018
0
0.020205
0.224306
3,892
135
89
28.82963
0.832395
0.054471
0
0.318182
1
0
0.005453
0
0
0
0
0
0
1
0.238636
false
0
0.034091
0.022727
0.511364
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
92c9485171f000d8d175ecd167c78df245f1e87b
1,271
py
Python
example/example.py
yigitsener/cosdem_project
ea4e100eb17c9444fa43c2bf6fbbabebc5b850ae
[ "MIT" ]
null
null
null
example/example.py
yigitsener/cosdem_project
ea4e100eb17c9444fa43c2bf6fbbabebc5b850ae
[ "MIT" ]
null
null
null
example/example.py
yigitsener/cosdem_project
ea4e100eb17c9444fa43c2bf6fbbabebc5b850ae
[ "MIT" ]
null
null
null
from cosdem import Cosdem # file_name = "example/sample_data.csv" # # analyze = Cosdem(file_name) # # print(analyze.report()) """ -- Descriptive Statistics -- Feature_A Feature_B Count 36.000 36.000 Mean 98.250 98.139 Quantile-25 97.000 97.000 Median (Q-50) 99.000 98.000 Quantile-75 99.000 99.000 Std 1.461 1.437 Variance 2.136 2.066 Skewness -0.520 -0.502 Kurtosis -0.818 -0.446 -- Homogeneity Tests of Variances -- Test Statistic P-value Levene 0.056 0.814 Bartlett 0.010 0.922 -- Normality Test: Shapiro Wilk -- Test Statistic P-value Feature_A 0.895 0.002 Feature_B 0.917 0.010 -- Statistical Difference Tests -- Test Statistic P-value T-test 0.325 0.746 Mann Whitney U 615.000 0.354 -- Correlation Tests -- Test Statistic P-value Pearson 0.935 0.0 Spearman 0.940 0.0 Kendall 0.889 0.0 -- Regression Result -- R Square Adjusted R Square P-Value Coefficient Bias 0 0.935 0.933 0.0 0.92 7.775 """
25.42
59
0.521637
173
1,271
3.791908
0.549133
0.018293
0.085366
0.115854
0.073171
0
0
0
0
0
0
0.226563
0.395751
1,271
50
60
25.42
0.627604
0.070024
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
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
4
92d12b4d4c0bf7e8681b5d4c158de1f1e8e2bf8d
226
py
Python
aioesphomeapi/__init__.py
oxan/aioesphomeapi
7d36ed8ce5f9bcab2637800724fe5aa93634838b
[ "MIT" ]
null
null
null
aioesphomeapi/__init__.py
oxan/aioesphomeapi
7d36ed8ce5f9bcab2637800724fe5aa93634838b
[ "MIT" ]
null
null
null
aioesphomeapi/__init__.py
oxan/aioesphomeapi
7d36ed8ce5f9bcab2637800724fe5aa93634838b
[ "MIT" ]
null
null
null
# flake8: noqa from .client import APIClient from .connection import APIConnection, ConnectionParams from .core import MESSAGE_TYPE_TO_PROTO, APIConnectionError from .model import * from .reconnect_logic import ReconnectLogic
32.285714
59
0.845133
27
226
6.925926
0.703704
0
0
0
0
0
0
0
0
0
0
0.004975
0.110619
226
6
60
37.666667
0.925373
0.053097
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
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
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
92fd289f6e66b6938d5c84e370da94d89fc97a10
651
py
Python
src/arrays/1029_Two_City_Scheduling.py
tmbothe/Data-Structures-and-algorithms
ba6bd0b302d16f84694acee1e1eb5d7f948ceeb2
[ "MIT" ]
null
null
null
src/arrays/1029_Two_City_Scheduling.py
tmbothe/Data-Structures-and-algorithms
ba6bd0b302d16f84694acee1e1eb5d7f948ceeb2
[ "MIT" ]
null
null
null
src/arrays/1029_Two_City_Scheduling.py
tmbothe/Data-Structures-and-algorithms
ba6bd0b302d16f84694acee1e1eb5d7f948ceeb2
[ "MIT" ]
null
null
null
def twoCitySchedCost(costs): result={'A':[],'B':[]} costs.sort(key = lambda x: x[0]-x[1]) print(costs) n=len(costs)//2 total = 0 for cost in costs[:n]: total+=cost[0] for cost in costs[n:]: total+=cost[1] return total if __name__ =='__main__': costs = [[10,20],[30,200],[400,50],[30,20]] print(twoCitySchedCost(costs)) #110 costs = [[259,770],[448,54],[926,667],[184,139],[840,118],[577,469]] print(twoCitySchedCost(costs)) #1859 costs = [[515,563],[451,713],[537,709],[343,819],[855,779],[457,60],[650,359],[631,42]] print(twoCitySchedCost(costs)) #3086
18.083333
91
0.557604
95
651
3.736842
0.642105
0.23662
0.219718
0.056338
0.140845
0.140845
0.140845
0.140845
0
0
0
0.226563
0.213518
651
35
92
18.6
0.466797
0.016897
0
0.166667
0
0
0.015823
0
0
0
0
0
0
1
0.055556
false
0
0
0
0.111111
0.222222
0
0
0
null
1
1
0
0
0
0
0
0
0
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
4
130d10344dd7bd76f5b000a2f574ffd05656892d
1,033
py
Python
pyvalidator/constraints/__init__.py
TangoMan75/pyvalidator
277743353bc03b660c420228d355d59f10f944b6
[ "MIT" ]
null
null
null
pyvalidator/constraints/__init__.py
TangoMan75/pyvalidator
277743353bc03b660c420228d355d59f10f944b6
[ "MIT" ]
null
null
null
pyvalidator/constraints/__init__.py
TangoMan75/pyvalidator
277743353bc03b660c420228d355d59f10f944b6
[ "MIT" ]
null
null
null
#!/bin/python3 # -*- coding: utf-8 -*- """ This file is part of the TangoMan PyValidator package. (c) "Matthias Morin" <mat@tangoman.io> This source file is subject to the MIT license that is bundled with this source code in the file LICENSE. """ from pyvalidator.constraints.abstract_validator import AbstractValidator from pyvalidator.constraints.alias_validator import AliasValidator from pyvalidator.constraints.any_validator import AnyValidator from pyvalidator.constraints.callable_validator import CallableValidator from pyvalidator.constraints.class_validator import ClassValidator from pyvalidator.constraints.collections_validator import DictValidator from pyvalidator.constraints.collections_validator import ListValidator from pyvalidator.constraints.collections_validator import UnionValidator from pyvalidator.constraints.not_blank_validator import NotBlankValidator from pyvalidator.constraints.nullable_validator import NullableValidator from pyvalidator.constraints.stdtype_validator import StdtypeValidator
43.041667
73
0.8606
118
1,033
7.432203
0.457627
0.188141
0.326112
0.126568
0.177879
0.177879
0
0
0
0
0
0.002128
0.090029
1,033
23
74
44.913043
0.930851
0.229429
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
1
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
0
1
0
1
0
1
0
0
4
1312f28f238a6e14510725642b75dd8b9f29b24e
1,626
py
Python
custom_user/signals.py
COS301-SE-2020/ctrlintelligencecapstone
ddfc92408ed296c6bf64b2dd071b948a1446ede8
[ "MIT" ]
null
null
null
custom_user/signals.py
COS301-SE-2020/ctrlintelligencecapstone
ddfc92408ed296c6bf64b2dd071b948a1446ede8
[ "MIT" ]
null
null
null
custom_user/signals.py
COS301-SE-2020/ctrlintelligencecapstone
ddfc92408ed296c6bf64b2dd071b948a1446ede8
[ "MIT" ]
1
2021-05-18T02:53:10.000Z
2021-05-18T02:53:10.000Z
from django.dispatch import reciever from django_rest_passwordreset.signals import rest_password_token_created @reciever(rest_password_token_created) def password_reset_token_created(sender, instance, reset_password_token, *args, **kwargs): """ Handles password reset tokens When a token is created, an e-mail needs to be sent to the user :param sender: View Class that sent the signal :param instance: View Instance that sent the signal :param reset_password_token: Token Model Object :param args: :param kwargs: :return: """ # TODO: Send email with token etc pass # send an e-mail to the user # context = { # 'current_user': reset_password_token.user, # 'username': reset_password_token.user.username, # 'email': reset_password_token.user.email, # 'reset_password_url': "{}?token={}".format( # instance.request.build_absolute_uri(reverse('password_reset:reset-password-confirm')), # reset_password_token.key) # } # # render email text # email_html_message = render_to_string('email/user_reset_password.html', context) # email_plaintext_message = render_to_string('email/user_reset_password.txt', context) # msg = EmailMultiAlternatives( # # title: # "Password Reset for {title}".format(title="Some website title"), # # message: # email_plaintext_message, # # from: # "noreply@somehost.local", # # to: # [reset_password_token.user.email] # ) # msg.attach_alternative(email_html_message, "text/html") # msg.send()
36.133333
100
0.674662
195
1,626
5.379487
0.384615
0.13632
0.120114
0.083889
0.232602
0.081983
0.081983
0.081983
0
0
0
0
0.222017
1,626
45
101
36.133333
0.829249
0.718942
0
0
0
0
0
0
0
0
0
0.022222
0
1
0.2
false
0.8
0.4
0
0.6
0
0
0
0
null
0
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
1
0
0
0
0
1
1
0
1
0
0
4
132b83a0f3674184abd5e78484bec904938ba218
141
py
Python
src/tess_atlas/config.py
dfm/tess-atlas
0831d15b65ce2ac345dd3f7a4eac8a14883dcccc
[ "MIT" ]
10
2019-03-26T19:47:03.000Z
2021-12-15T11:44:31.000Z
src/tess_atlas/config.py
dfm/tess-atlas
0831d15b65ce2ac345dd3f7a4eac8a14883dcccc
[ "MIT" ]
98
2019-03-27T16:12:02.000Z
2022-03-15T21:32:09.000Z
src/tess_atlas/config.py
dfm/tess-atlas
0831d15b65ce2ac345dd3f7a4eac8a14883dcccc
[ "MIT" ]
7
2019-03-26T19:47:11.000Z
2020-10-07T03:26:21.000Z
# -*- coding: utf-8 -*- import os OUTPUT_DIR = os.environ.get( "TESS_ATLAS_OUTPUT_DIR", os.path.join(os.path.abspath("."), "output") )
17.625
73
0.638298
21
141
4.095238
0.666667
0.209302
0.255814
0
0
0
0
0
0
0
0
0.008264
0.141844
141
7
74
20.142857
0.702479
0.148936
0
0
0
0
0.237288
0.177966
0
0
0
0
0
1
0
false
0
0.25
0
0.25
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
0
0
0
0
0
0
0
4
1333c05fdd7381dfb2f0b5cf89b26d23bb3d32cf
558
py
Python
src/py310/lesson03/slicing.py
UWPCE-Python-Course-2-Materials/py310_sp2021
584e37b9d96654c1241fc787d157c292301d5bf7
[ "MIT" ]
null
null
null
src/py310/lesson03/slicing.py
UWPCE-Python-Course-2-Materials/py310_sp2021
584e37b9d96654c1241fc787d157c292301d5bf7
[ "MIT" ]
null
null
null
src/py310/lesson03/slicing.py
UWPCE-Python-Course-2-Materials/py310_sp2021
584e37b9d96654c1241fc787d157c292301d5bf7
[ "MIT" ]
2
2021-06-03T02:59:49.000Z
2021-06-14T20:42:12.000Z
names = [ 'andy', 'sue', 'fred', 'jim', 'carol' ] assert names[0] == 'andy' assert names[4] == 'carol' assert names[-1] == 'carol' assert names[-2] == 'jim' assert names[0:2] == ['andy', 'sue'] assert names[1:2] == ['sue'] assert names[3:] == ['jim', 'carol'] assert names[-2:] == ['jim', 'carol'] assert names[::-1] == ['carol', 'jim', 'fred', 'sue', 'andy'] assert names == ['andy', 'sue', 'fred', 'jim', 'carol'] names.reverse() assert names == ['carol', 'jim', 'fred', 'sue', 'andy'] assert names[1:5:2] == ['jim', 'sue']
16.909091
61
0.516129
74
558
3.891892
0.189189
0.458333
0.277778
0.197917
0.614583
0.357639
0.208333
0
0
0
0
0.030973
0.189964
558
32
62
17.4375
0.606195
0
0
0
0
0
0.224014
0
0
0
0
0
0.6
1
0
false
0
0
0
0
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
4
134a3639b15813ec816b40c2adf1bd34ddf361ef
3,300
py
Python
teste.py
marcelocmedeiros/Jogo-da-Forca
cfdd7866c079a196f9082706a0c8e548f6d34955
[ "MIT" ]
null
null
null
teste.py
marcelocmedeiros/Jogo-da-Forca
cfdd7866c079a196f9082706a0c8e548f6d34955
[ "MIT" ]
null
null
null
teste.py
marcelocmedeiros/Jogo-da-Forca
cfdd7866c079a196f9082706a0c8e548f6d34955
[ "MIT" ]
null
null
null
# A def vai imprimir a forca para cada erro e caso erre 6x tmb imprime a msg "Lamento! Perdeu!" def forca(x=0): if x==0: print("------------") print("| |") print("| ") print("| ") print("| ") print("| ") print("| ") print("|") elif x==1: print("------------") print("| |") print("| 0") print("| ") print("| ") print("| ") print("| ") print("|") elif x==2: print("------------") print("| |") print("| 0") print("| |") print("| ") print("| ") print("| ") print("|") elif x==3: print("------------") print("| |") print("| 0") print("| -|") print("| ") print("| ") print("| ") print("|") elif x==4: print("------------ ") print("| | ") print("| 0 ") print("| -|- ") print("| ") print("| ") print("| ") print("|") elif x==5: print("------------ ") print("| | ") print("| 0 ") print("| -|- ") print("| / ") print("| ") print("| ") print("|") elif x==6: print("------------ ") print("| | ") print("| 0 ") print("| -|- ") print("| / \\ ") print("| ") print("| Lamento! Perdeu! ") print("|") #VARIAVEIS GLOBAIS erros=0 # acumulador de erros até 6 #RECEBE PALAVRA INICIAL palavra=input('Informe a palavra: '); # lista que recebe '_' para cada letra de palavra temp=[] for letra in palavra: temp.append('_') # laço while pq não se sabe a quantidade de letra da palavra while True: print('\n'*20) # limpa a tela forca(erros) # chamei a def q imprime desenho da forca #imprime a adivinhacao com os traços de cada letra da palavra print('\n\nAdivinhe: ', end='') # usa o for p impresão '_' de cada letra em palavra for let in temp: # end=' ' assim o print imprime os espaços na mesma linha print(let, end=' ') print('\n'*2) # da dois espaços para baixo #Verifica se perdeu if erros==6: break #sai do jogo (sai do while) #Verificar se o jogador ganhou ganhouJogo=True # usando for let na lista temp for let in temp: # enquanto let tiver espaço vazio ganhouJogo=False e jogo continua if let=='_': ganhouJogo=False # caso não tenha mais espaço vazio break Venceu if ganhouJogo: print('\nPARABÉNS VENCEDOR!!!') break #captura a letra do usuario letraDig=input("Informe uma letra: ") #verifica se acertou alguma letra errouLetra=True # i percorre cada indice da lista que recebeu palavra for i, let in enumerate(palavra): # verifica se acertou add a letra if palavra[i]==letraDig: # lista temp recebe a letra no indice correspondente da palavra temp[i]=palavra[i] # então não soma erro dar um novo loop p informa outra letra errouLetra=False # caso erre soma +1 até chegar 6 q break e perdeu! if errouLetra: erros=erros+1
29.20354
95
0.472424
364
3,300
4.271978
0.346154
0.270096
0.279743
0.205788
0.200643
0.200643
0.2
0.171061
0.14791
0.14791
0
0.011418
0.36303
3,300
113
96
29.20354
0.728354
0.313939
0
0.602151
0
0
0.336757
0
0
0
0
0
0
1
0.010753
false
0
0
0
0.010753
0.655914
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
1
0
4
134bdac2aa8a7566f35b455c8b54856402b58039
34
py
Python
tests/__init__.py
fanifieiev/pyeo
a8e0b15606d431db3c0431c6e76b306d136ded68
[ "MIT" ]
1
2020-02-10T22:12:28.000Z
2020-02-10T22:12:28.000Z
tests/__init__.py
fanifieiev/pyeo
a8e0b15606d431db3c0431c6e76b306d136ded68
[ "MIT" ]
null
null
null
tests/__init__.py
fanifieiev/pyeo
a8e0b15606d431db3c0431c6e76b306d136ded68
[ "MIT" ]
null
null
null
"""Unit test package for pyeo."""
17
33
0.647059
5
34
4.4
1
0
0
0
0
0
0
0
0
0
0
0
0.147059
34
1
34
34
0.758621
0.794118
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
1
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
1354152b5f1734f4f868ea41ba8fb6d7df46c95e
12,623
py
Python
apps/reader/tests.py
Matt-Payne/NewsBlur
e0b9990cad73e4d1a1caba7865b5c957c6029e18
[ "MIT" ]
null
null
null
apps/reader/tests.py
Matt-Payne/NewsBlur
e0b9990cad73e4d1a1caba7865b5c957c6029e18
[ "MIT" ]
null
null
null
apps/reader/tests.py
Matt-Payne/NewsBlur
e0b9990cad73e4d1a1caba7865b5c957c6029e18
[ "MIT" ]
null
null
null
from utils import json_functions as json from django.test.client import Client from django.test import TestCase from django.core.urlresolvers import reverse from django.conf import settings from mongoengine.connection import connect, disconnect from apps.reader.models import UserSubscriptionFolders class ReaderTest(TestCase): fixtures = ['../../rss_feeds/fixtures/rss_feeds.json', 'subscriptions.json', 'stories.json', '../../rss_feeds/fixtures/gawker1.json'] def setUp(self): disconnect() settings.MONGODB = connect('test_newsblur') self.client = Client() def tearDown(self): settings.MONGODB.drop_database('test_newsblur') def test_api_feeds(self): self.client.login(username='conesus', password='test') response = self.client.get(reverse('load-feeds')) content = json.decode(response.content) self.assertEquals(len(content['feeds']), 10) self.assertEquals(content['feeds']['1']['feed_title'], 'Gawker') self.assertEquals(content['folders'], [{'Tech': [1, 4, 5, {'Deep Tech': [6, 7]}]}, 2, 3, 8, 9, {'Blogs': [8, 9]}, 1]) def test_delete_feed(self): self.client.login(username='conesus', password='test') response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [{'Tech': [1, 4, 5, {'Deep Tech': [6, 7]}]}, 2, 3, 8, 9, {'Blogs': [8, 9]}, 1]) # Delete feed response = self.client.post(reverse('delete-feed'), {'feed_id': 1, 'in_folder': ''}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [2, 3, 8, 9, {'Tech': [1, 4, 5, {'Deep Tech': [6, 7]}]}, {'Blogs': [8, 9]}]) # Delete feed response = self.client.post(reverse('delete-feed'), {'feed_id': 9, 'in_folder': 'Blogs'}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [2, 3, 8, 9, {'Tech': [1, 4, 5, {'Deep Tech': [6, 7]}]}, {'Blogs': [8]}]) # Delete feed response = self.client.post(reverse('delete-feed'), {'feed_id': 5, 'in_folder': 'Tech'}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [2, 3, 8, 9, {'Tech': [1, 4, {'Deep Tech': [6, 7]}]}, {'Blogs': [8]}]) # Delete feed response = self.client.post(reverse('delete-feed'), {'feed_id': 4, 'in_folder': 'Tech'}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [2, 3, 8, 9, {'Tech': [1, {'Deep Tech': [6, 7]}]}, {'Blogs': [8]}]) # Delete feed response = self.client.post(reverse('delete-feed'), {'feed_id': 8, 'in_folder': ''}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [2, 3, 9, {'Tech': [1, {'Deep Tech': [6, 7]}]}, {'Blogs': [8]}]) def test_delete_feed__multiple_folders(self): self.client.login(username='conesus', password='test') response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [{'Tech': [1, 4, 5, {'Deep Tech': [6, 7]}]}, 2, 3, 8, 9, {'Blogs': [8, 9]}, 1]) # Delete feed response = self.client.post(reverse('delete-feed'), {'feed_id': 1}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [2, 3, 8, 9, {'Tech': [1, 4, 5, {'Deep Tech': [6, 7]}]}, {'Blogs': [8, 9]}]) def test_move_feeds_by_folder(self): self.client.login(username='Dejal', password='test') response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [5299728, 644144, 1187026, {"Brainiacs & Opinion": [569, 38, 3581, 183139, 1186180, 15]}, {"Science & Technology": [731503, 140145, 1272495, 76, 161, 39, {"Hacker": [5985150, 3323431]}]}, {"Humor": [212379, 3530, 5994357]}, {"Videos": [3240, 5168]}]) # Move feeds by folder response = self.client.post(reverse('move-feeds-by-folder-to-folder'), {u'feeds_by_folder': u'[\n [\n "5994357",\n "Humor"\n ],\n [\n "3530",\n "Humor"\n ]\n]', u'to_folder': u'Brainiacs & Opinion'}) response = json.decode(response.content) self.assertEquals(response['code'], 1) response = self.client.get(reverse('load-feeds')) feeds = json.decode(response.content) self.assertEquals(feeds['folders'], [5299728, 644144, 1187026, {"Brainiacs & Opinion": [569, 38, 3581, 183139, 1186180, 15, 5994357, 3530]}, {"Science & Technology": [731503, 140145, 1272495, 76, 161, 39, {"Hacker": [5985150, 3323431]}]}, {"Humor": [212379]}, {"Videos": [3240, 5168]}]) def test_load_single_feed(self): # from django.conf import settings # from django.db import connection # settings.DEBUG = True # connection.queries = [] self.client.login(username='conesus', password='test') url = reverse('load-single-feed', kwargs=dict(feed_id=1)) response = self.client.get(url) feed = json.decode(response.content) self.assertEquals(len(feed['feed_tags']), 0) self.assertEquals(len(feed['classifiers']['tags']), 0) # self.assert_(connection.queries) # settings.DEBUG = False def test_compact_user_subscription_folders(self): usf = UserSubscriptionFolders.objects.get(user=User.objects.all()[0]) usf.folders = '[2, 3, {"Bloglets": [423, 424, 425]}, {"Blogs": [426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, {"People": [471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 867, 946, 947, 948]}, {"Tumblrs": [529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549]}, {"Photo Blogs": [550, 551, 552, 553, 554, 555, 556]}, {"Travel": [557, 558, 559]}, {"People": [471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 522, 523, 524, 525, 526, 527, 528, 507, 520, 867]}, {"Tumblrs": [529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549]}, {"Photo Blogs": [550, 551, 552, 553, 554, 555, 556]}, {"Travel": [558, 559, 557]}, 943, {"Link Blogs": [467, 468, 469, 470]}, {"People": [471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 504, 505, 506, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 522, 523, 525, 526, 527, 528]}, {"Tumblrs": [529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549]}, {"Photo Blogs": [550, 551, 552, 553, 554, 555, 556]}, {"Travel": [558, 559]}]}, {"Code": [560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583]}, {"Cooking": [584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 873, 953]}, {"Meta": [598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608]}, {"New York": [609, 610, 611, 612, 613, 614]}, {"San Francisco": [615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 875]}, {"Tech": [635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 184, 661, 662, 663, 664, 665, 666]}, {"Comics & Cartoons": [667, 668, 669, 670, 671, 672, 673, 63, 674, 675, 676, 677, 678, 679, 680, 681, 682, 109, 683, 684, 685, 958]}, {"Hardware": [686, 687, 688, 689, 690, 691, 692]}, {"Wood": []}, {"Newsletters": [693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 724, 719, 720, 721, 722, 723, 725, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 895]}, {"Woodworking": [784, 785, 786, 787, 788, 789, 790, 791, 792, 793]}, {"Twitter": [794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 838, 915]}, {"News": [808, 809, 810, 811, 812, 813, 814, 815, 816, 817]}, {"Home": [818, 819, 820, 821, 822, 823]}, {"Facebook": [824, 825, 826]}, {"Art": [827, 828]}, {"Science": [403, 404, 405, 401, 402]}, {"Boston": [829, 830]}, {"mobility": [831, 832, 833, 834, 835, 836, 837, 963]}, {"Biking": []}, {"A Muted Folder": [1]}, 1, {"Any Broken Feeds": [916]}, {"Any Broken Feeds, Although Some of These Work Fine": [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 840, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 841, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 842, 50, 51, 52, 53, 54, 843, 56, 57, 58, 59, 60, 61, 62, 63, 844, 917, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 918, 130, 131, 132, 846, 134, 135, 136, 919, 138, 139, 140, 141, 142, 143, 144, 145, 847, 147, 848, 149, 150, 151, 152, 153, 154, 849, 156, 157, 158, 936, 160, 850, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 1, 185, 186, 187, 188, 189, 851, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 852, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 853, 243, 854, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 856, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 939, 281, 282, 283, 284, 285, 940, 287, 288, 289, 857, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 858, 354, 355, 859, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 860, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, {"Ubuntu": [396, 397, 398, 399, 400]}, {"Science": [401, 402, 403, 404, 405]}, {"Music": [406, 407, 408, 409, 410, 411, 412]}, {"NYTimes": [413]}, {"Test": [414]}, {"Organizer": [415, 416, 417]}, {"Adult": [418, 419, 861, 421]}, {"Test": []}, 422]}]' usf.save() dupe_folders = usf.folders usf.compact() compact_folders = usf.folders self.assertNotEquals(dupe_folders, compact_folders)
89.524823
5,825
0.585835
1,903
12,623
3.860221
0.529164
0.034032
0.046556
0.064661
0.484617
0.473999
0.465287
0.44269
0.44269
0.439695
0
0.333735
0.210726
12,623
140
5,826
90.164286
0.403593
0.020597
0
0.447917
0
0.020833
0.555592
0.008584
0
0
0
0
0.239583
1
0.083333
false
0.052083
0.072917
0
0.177083
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
1
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
4
135e1517cf0436ccceeb561a3777bdf11ea10dff
66
py
Python
dotbak/core/exc.py
datafolklabs/dotbak
c2d63a8f2c5d36d4e57a98f55602cd32a8f846ad
[ "BSD-3-Clause" ]
2
2021-01-18T01:46:29.000Z
2021-10-06T01:57:06.000Z
dotbak/core/exc.py
datafolklabs/dotbak
c2d63a8f2c5d36d4e57a98f55602cd32a8f846ad
[ "BSD-3-Clause" ]
2
2021-09-30T19:53:53.000Z
2021-12-18T19:45:05.000Z
dotbak/core/exc.py
datafolklabs/dotbak
c2d63a8f2c5d36d4e57a98f55602cd32a8f846ad
[ "BSD-3-Clause" ]
null
null
null
class DotBakError(Exception): """Generic errors.""" pass
13.2
29
0.636364
6
66
7
1
0
0
0
0
0
0
0
0
0
0
0
0.212121
66
4
30
16.5
0.807692
0.227273
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
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
0
0
0
0
null
0
0
0
0
0
0
1
1
0
0
0
0
0
4
137c7ef69ef2de77801e3d582694243c1b210fc0
198
py
Python
Modules/Backend/backend.py
bus6479/QCAD
b660d07639e44b099dccc1213e87bae737db716d
[ "MIT" ]
1
2018-10-05T06:33:56.000Z
2018-10-05T06:33:56.000Z
Modules/Backend/backend.py
GyunghunKim/QCAD
b660d07639e44b099dccc1213e87bae737db716d
[ "MIT" ]
null
null
null
Modules/Backend/backend.py
GyunghunKim/QCAD
b660d07639e44b099dccc1213e87bae737db716d
[ "MIT" ]
1
2018-09-01T02:35:50.000Z
2018-09-01T02:35:50.000Z
# Module for class Backend from .. import Module class Backend(object): def __init__(self): pass @staticmethod def run(quantum_circuit: Module, initial_state=[]): ...
16.5
55
0.636364
22
198
5.454545
0.772727
0.2
0
0
0
0
0
0
0
0
0
0
0.257576
198
11
56
18
0.816327
0.121212
0
0
0
0
0
0
0
0
0
0
0
1
0.285714
false
0.142857
0.142857
0
0.571429
0
1
0
0
null
0
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
0
1
0
0
1
0
0
4
1392b8b7a6943e4d4ece96fd9ec850af1c9e5d7b
153
py
Python
mission/configure.py
cuauv/software
5ad4d52d603f81a7f254f365d9b0fe636d03a260
[ "BSD-3-Clause" ]
70
2015-11-16T18:04:01.000Z
2022-03-05T09:04:02.000Z
mission/configure.py
cuauv/software
5ad4d52d603f81a7f254f365d9b0fe636d03a260
[ "BSD-3-Clause" ]
1
2016-08-03T05:13:19.000Z
2016-08-03T06:19:39.000Z
mission/configure.py
cuauv/software
5ad4d52d603f81a7f254f365d9b0fe636d03a260
[ "BSD-3-Clause" ]
34
2015-12-15T17:29:23.000Z
2021-11-18T14:15:12.000Z
#!/usr/bin/env python3 from build import ninja_common build = ninja_common.Build('mission') build.install('auv-mission-runner', f='mission/runner.py')
21.857143
58
0.75817
23
153
4.956522
0.652174
0.192982
0.280702
0
0
0
0
0
0
0
0
0.007143
0.084967
153
6
59
25.5
0.807143
0.137255
0
0
0
0
0.320611
0
0
0
0
0
0
1
0
false
0
0.333333
0
0.333333
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
0
0
0
1
0
0
0
0
4
13b316f5736e6f6085e0d206d70dfcfb604ee2c3
357
py
Python
lims/users/permissions.py
sqilz/LIMS-Backend
b64e1fa512f89e4492803d44c6b8c35e4d4724cc
[ "MIT" ]
12
2017-03-01T10:39:36.000Z
2022-01-04T06:17:19.000Z
lims/users/permissions.py
sqilz/LIMS-Backend
b64e1fa512f89e4492803d44c6b8c35e4d4724cc
[ "MIT" ]
29
2017-04-25T14:05:08.000Z
2021-06-21T14:41:53.000Z
lims/users/permissions.py
sqilz/LIMS-Backend
b64e1fa512f89e4492803d44c6b8c35e4d4724cc
[ "MIT" ]
4
2017-10-11T16:22:53.000Z
2021-02-23T15:45:21.000Z
from rest_framework import permissions class UserIsOwnerAccessOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): return obj.user == request.user or request.user.is_staff class IsSuperUser(permissions.BasePermission): def has_permission(self, request, view): return request.user.is_superuser
25.5
64
0.770308
42
357
6.404762
0.547619
0.122677
0.208178
0.230483
0
0
0
0
0
0
0
0
0.154062
357
13
65
27.461538
0.890728
0
0
0
0
0
0
0
0
0
0
0
0
1
0.285714
false
0
0.142857
0.285714
1
0
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
4
13bfd48a8256a6d868107dbee4a7c2729f28bf3c
288
py
Python
SmartFoxServer_PRO_1.6.6/Server/lib/Lib/test/test_janoninner.py
ChisdealHD/DetlasWorldLinux
336465a4df1a48c9a273329fc7a09d8099c4e4d5
[ "MIT" ]
8
2016-11-24T09:38:31.000Z
2021-04-23T13:04:48.000Z
SmartFoxServer_PRO_1.6.6/Server/lib/Lib/test/test_janoninner.py
ChisdealHD/DetlasWorldLinux
336465a4df1a48c9a273329fc7a09d8099c4e4d5
[ "MIT" ]
4
2018-02-22T07:42:13.000Z
2021-12-13T10:53:09.000Z
SmartFoxServer_PRO_1.6.6/Server/lib/Lib/test/test_janoninner.py
ChisdealHD/DetlasWorldLinux
336465a4df1a48c9a273329fc7a09d8099c4e4d5
[ "MIT" ]
4
2018-12-04T12:21:05.000Z
2021-02-05T08:00:14.000Z
# test of PR#201 import sys from test_support import * print_test('Java Anonymous Inner Classes (test_janoninner.py)', 1) print_test('importing', 2) import javatests.AnonInner print_test('instantiating', 2) x = javatests.AnonInner() print_test('invoking', 2) assert x.doit() == 2000
18
66
0.75
42
288
5
0.619048
0.171429
0.219048
0.257143
0
0
0
0
0
0
0
0.043651
0.125
288
15
67
19.2
0.789683
0.045139
0
0
0
0
0.290441
0
0
0
0
0
0.111111
1
0
false
0
0.444444
0
0.444444
0.444444
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
1
0
4
b938d9c60558ca9fb4b4f103e15e5c6330999ab0
2,994
py
Python
pdfx/extractor.py
DontWorry33/pdfx
ed3039315cf65731eb8a2f89df97298dc2a34d9e
[ "Apache-2.0" ]
null
null
null
pdfx/extractor.py
DontWorry33/pdfx
ed3039315cf65731eb8a2f89df97298dc2a34d9e
[ "Apache-2.0" ]
null
null
null
pdfx/extractor.py
DontWorry33/pdfx
ed3039315cf65731eb8a2f89df97298dc2a34d9e
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/python # -*- coding: utf-8 -*- """ Regexes for reference matching Web url matching: * http://daringfireball.net/2010/07/improved_regex_for_matching_urls * https://gist.github.com/gruber/8891611 """ from __future__ import (absolute_import, division, print_function, unicode_literals) import re # arXiv.org ARXIV_REGEX = r"""arxiv:\s?([^\s,]+)""" ARXIV_REGEX2 = r"""arxiv.org/abs/([^\s,]+)""" # DOI DOI_REGEX = r"""DOI:\s?([^\s,]+)""" # URL URL_REGEX = r"""(?i)\b((?:https?:(?:/{1,3}|[a-z0-9%])|[a-z0-9.\-]+[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)/)(?:[^\s()<>{}\[\]]+|\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\))+(?:\([^\s()]*?\([^\s()]+\)[^\s()]*?\)|\([^\s]+?\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])|(?:(?<!@)[a-z0-9]+(?:[.\-][a-z0-9]+)*[.](?:com|net|org|edu|gov|mil|aero|asia|biz|cat|coop|info|int|jobs|mobi|museum|name|post|pro|tel|travel|xxx|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|dd|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|Ja|sk|sl|sm|sn|so|sr|ss|st|su|sv|sx|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))""" def extract_urls(text): return set(re.findall(URL_REGEX, text, re.IGNORECASE)) def extract_arxiv(text): res = re.findall(ARXIV_REGEX, text, re.IGNORECASE) + \ re.findall(ARXIV_REGEX2, text, re.IGNORECASE) return set([r.strip(".") for r in res]) def extract_doi(text): res = set(re.findall(DOI_REGEX, text, re.IGNORECASE)) return set([r.strip(".") for r in res]) if __name__ == "__main__": print(extract_arxiv("arxiv:123 . arxiv: 345 455 http://arxiv.org/abs/876"))
69.627907
2,009
0.623246
725
2,994
2.533793
0.466207
0.011976
0.013065
0.015242
0.697877
0.697877
0.697877
0.697877
0.697877
0.692433
0
0.013418
0.054108
2,994
42
2,010
71.285714
0.634534
0.072144
0
0.111111
0
0.055556
0.762111
0.727766
0
0
0
0
0
1
0.166667
false
0
0.111111
0.055556
0.444444
0.111111
0
0
0
null
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
1
1
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
b93f5a89380e6fd6da815553e10eb3941bc3d67f
692
py
Python
python/fbs/Output.py
oliverlee/biketest
074b0b03455021c52a13efe583b1816bc5daad4e
[ "BSD-2-Clause" ]
3
2016-12-14T01:22:27.000Z
2020-04-07T05:15:04.000Z
python/fbs/Output.py
oliverlee/biketest
074b0b03455021c52a13efe583b1816bc5daad4e
[ "BSD-2-Clause" ]
7
2017-01-12T15:20:57.000Z
2017-07-02T16:09:37.000Z
python/fbs/Output.py
oliverlee/biketest
074b0b03455021c52a13efe583b1816bc5daad4e
[ "BSD-2-Clause" ]
1
2020-04-07T05:15:05.000Z
2020-04-07T05:15:05.000Z
# automatically generated, do not modify # namespace: fbs import flatbuffers class Output(object): __slots__ = ['_tab'] # Output def Init(self, buf, pos): self._tab = flatbuffers.table.Table(buf, pos) # Output def Y0(self): return self._tab.Get(flatbuffers.number_types.Float64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) # Output def Y1(self): return self._tab.Get(flatbuffers.number_types.Float64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8)) def CreateOutput(builder, y0, y1): builder.Prep(8, 16) builder.PrependFloat64(y1) builder.PrependFloat64(y0) return builder.Offset()
28.833333
144
0.721098
89
692
5.426966
0.426966
0.072464
0.182195
0.070393
0.434783
0.434783
0.434783
0.434783
0.434783
0.434783
0
0.032759
0.16185
692
23
145
30.086957
0.8
0.106936
0
0
1
0
0.006536
0
0
0
0
0
0
1
0.333333
false
0
0.083333
0.166667
0.666667
0
0
0
0
null
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
1
0
0
0
1
0
0
0
4
b93fc2bcba0a5dd3c9bc3ad719d817e6c2df94b5
208
py
Python
cfights/python3_solutions/algos/heaps/kthLargestElm.py
Developernation/codefights
68f8559f4132210b2cdaf396b1dd0a8e017d3402
[ "MIT" ]
null
null
null
cfights/python3_solutions/algos/heaps/kthLargestElm.py
Developernation/codefights
68f8559f4132210b2cdaf396b1dd0a8e017d3402
[ "MIT" ]
1
2018-08-15T14:39:32.000Z
2018-08-15T14:39:32.000Z
cfights/python3_solutions/algos/heaps/kthLargestElm.py
Developernation/codefights
68f8559f4132210b2cdaf396b1dd0a8e017d3402
[ "MIT" ]
null
null
null
# Find the kth largest element in an unsorted array. This will be the kth # largest element in sorted order, not the kth distinct element. def kthLargestElement(nums, k): nums.sort() return nums[-k]
29.714286
73
0.730769
33
208
4.606061
0.666667
0.118421
0.171053
0.263158
0.289474
0
0
0
0
0
0
0
0.197115
208
6
74
34.666667
0.91018
0.644231
0
0
0
0
0
0
0
0
0
0
0
1
0.333333
false
0
0
0
0.666667
0
0
0
0
null
0
0
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
0
0
0
1
0
0
4
b94f94932652cb026cec4ec2ba2901854c7d9940
1,585
py
Python
scrapy_po/webpage.py
ivanprado/scrapy-po
a0776e763f8c64e81edfe4eb04e8fb3e6b2b5b9e
[ "BSD-3-Clause" ]
null
null
null
scrapy_po/webpage.py
ivanprado/scrapy-po
a0776e763f8c64e81edfe4eb04e8fb3e6b2b5b9e
[ "BSD-3-Clause" ]
null
null
null
scrapy_po/webpage.py
ivanprado/scrapy-po
a0776e763f8c64e81edfe4eb04e8fb3e6b2b5b9e
[ "BSD-3-Clause" ]
null
null
null
# -*- coding: utf-8 -*- import abc import attr import parsel from .page_inputs import ResponseData class PageObject(abc.ABC): """ All web page objects should inherit from this class. It is a marker for a middleware to pick anargument and populate it. Instead of inheriting you can also use ``PageObject.register(MyWebPage)``. """ pass @attr.s(auto_attribs=True) class WebPage(PageObject): """ Default WebPage class. It uses basic response data (html, url), and provides xpath / css shortcuts. This class is most useful as a base class for page objects, when extraction logic is similar to what's usually happening in scrapy spider callbacks. """ response: ResponseData _cached_selector = None @property def selector(self) -> parsel.Selector: from parsel.selector import Selector if self._cached_selector is None: self._cached_selector = Selector(self.html) return self._cached_selector @property def url(self): return self.response.url @property def html(self): return self.response.html def xpath(self, query, **kwargs): return self.selector.xpath(query, **kwargs) def css(self, query): return self.selector.css(query) class ItemPage(WebPage): @abc.abstractmethod def to_item(self): pass def callback_for(page_cls): """ Helper for defining callbacks for pages with to_item methods """ def parse(*args, page: page_cls): return page.to_item() # type: ignore return parse
23.656716
78
0.671924
207
1,585
5.067633
0.458937
0.047664
0.051478
0.041945
0
0
0
0
0
0
0
0.000834
0.243533
1,585
66
79
24.015152
0.874062
0.343218
0
0.147059
0
0
0
0
0
0
0
0
0
1
0.235294
false
0.058824
0.147059
0.147059
0.735294
0
0
0
0
null
0
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
0
1
0
1
1
0
0
4
b95b147b91f99128ff8357ad2f1b60143d7ab012
3,419
py
Python
send_messages.py
nateGeorge/udacity_review_assigner
ad40cfe6946a8358308cb9f645709b97afc358ca
[ "MIT" ]
null
null
null
send_messages.py
nateGeorge/udacity_review_assigner
ad40cfe6946a8358308cb9f645709b97afc358ca
[ "MIT" ]
null
null
null
send_messages.py
nateGeorge/udacity_review_assigner
ad40cfe6946a8358308cb9f645709b97afc358ca
[ "MIT" ]
null
null
null
# followed this guide: http://stackabuse.com/how-to-send-emails-with-gmail-using-python/ import smtplib import os import textwrap def get_env_vars(): ''' gets gmail uname/pass, phone number to text, and email to send to ''' gmail_user = os.getenv('udacity_gmail_uname') + '@gmail.com' gmail_password = os.getenv('udacity_gmail_pass') phone_email = os.getenv('my_phone_num_email') email_addr = os.getenv('my_email_addr') return gmail_user, gmail_password, phone_email, email_addr def compose_email(from_addr, to, link, project): ''' sends email with link to udacity project to review args: from_line -- string; email address the message is from to -- list of strings; email addresses the message is to link -- string; link to udacity project to review ''' subject = '%s review assigned' % (project) body = "You've been assigned a review for {}!\n\nCheck this link: {}".format(project, link) email_text = ("From: %s\n" "To: %s\n" "Subject: %s\n" "" "%s") % (from_addr, ", ".join(to), subject, body) return email_text def compose_error(from_addr, to, error, tb): ''' sends email with link to udacity project to review args: from_line -- string; email address the message is from to -- list of strings; email addresses the message is to link -- string; link to udacity project to review ''' subject = 'Error on Udacity server: {}'.format(error) body = "Error: {}".format(error) email_text = ("From: %s\n" "To: %s\n" "Subject: %s\n" "" "%s") % (from_addr, ", ".join(to), subject, body) return email_text def send_messages(link, project, text=True): ''' sends text and email notifying of reviews assigned args: link -- string; link to udacity review that has been assigned text -- boolean; if True will send a text message ''' gmail_user, gmail_password, phone_email, email_addr = get_env_vars() to = [email_addr] if text: to = [phone_email, email_addr] email_text = compose_email(from_addr=gmail_user, to=to, link=link, project=project) print email_text try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_password) server.sendmail(gmail_user, to, email_text) server.close() except: print 'Something went wrong...' print 'Couldn\'t email' def send_error(error, tb, text=True): ''' sends text and email notifying of reviews assigned args: link -- string; link to udacity review that has been assigned text -- boolean; if True will send a text message ''' gmail_user, gmail_password, phone_email, email_addr = get_env_vars() to = [email_addr] if text: to = [phone_email, email_addr] email_text = compose_error(from_addr=gmail_user, to=to, error=error, tb=tb) print email_text try: server = smtplib.SMTP('smtp.gmail.com', 587) server.ehlo() server.starttls() server.login(gmail_user, gmail_password) server.sendmail(gmail_user, to, email_text) server.close() except: print 'Something went wrong...' print 'Couldn\'t email'
31.953271
95
0.624452
458
3,419
4.510917
0.209607
0.043562
0.040658
0.053243
0.708132
0.708132
0.687803
0.687803
0.667957
0.667957
0
0.002389
0.265575
3,419
106
96
32.254717
0.82039
0.025154
0
0.688525
0
0
0.148683
0
0
0
0
0
0
0
null
null
0.098361
0.04918
null
null
0.098361
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
1
0
0
1
0
0
0
0
0
4
b961e1194461636c5143ed2a90aa3d1a93cb7df5
188
py
Python
wled/exceptions.py
sinclairpaul/python-wled
7cec61e2cff1bad3173823b4ae4c100f33febdfe
[ "MIT" ]
null
null
null
wled/exceptions.py
sinclairpaul/python-wled
7cec61e2cff1bad3173823b4ae4c100f33febdfe
[ "MIT" ]
null
null
null
wled/exceptions.py
sinclairpaul/python-wled
7cec61e2cff1bad3173823b4ae4c100f33febdfe
[ "MIT" ]
null
null
null
"""Exceptions for WLED.""" class WLEDError(Exception): """Generic WLED exception.""" pass class WLEDConnectionError(WLEDError): """WLED connection exception.""" pass
13.428571
37
0.659574
17
188
7.294118
0.588235
0.209677
0
0
0
0
0
0
0
0
0
0
0.196809
188
13
38
14.461538
0.821192
0.37766
0
0.5
0
0
0
0
0
0
0
0
0
1
0
true
0.5
0
0
0.5
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
0
1
1
0
0
0
0
0
4
b96aac687e754356cbc18f6f9fcfe2f463317395
148
py
Python
conf_site/sponsorship/apps.py
jasongrout/conf_site
6b3beb21de8d847cba65dcb6da84464b40739d48
[ "MIT" ]
null
null
null
conf_site/sponsorship/apps.py
jasongrout/conf_site
6b3beb21de8d847cba65dcb6da84464b40739d48
[ "MIT" ]
null
null
null
conf_site/sponsorship/apps.py
jasongrout/conf_site
6b3beb21de8d847cba65dcb6da84464b40739d48
[ "MIT" ]
null
null
null
from __future__ import unicode_literals from django.apps import AppConfig class SponsorshipConfig(AppConfig): name = "conf_site.sponsorship"
18.5
39
0.810811
17
148
6.705882
0.823529
0
0
0
0
0
0
0
0
0
0
0
0.135135
148
7
40
21.142857
0.890625
0
0
0
0
0
0.141892
0.141892
0
0
0
0
0
1
0
false
0
0.5
0
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
b98202fed85d7604b05db5fb2e2e2f5c08445121
585
py
Python
src/trying_tests/test_triangle.py
olga-erokhina/team13
7c800d125d7cbea5f943ff8841bcfc90c4deba11
[ "MIT" ]
1
2021-03-22T08:23:53.000Z
2021-03-22T08:23:53.000Z
src/trying_tests/test_triangle.py
olga-erokhina/team13
7c800d125d7cbea5f943ff8841bcfc90c4deba11
[ "MIT" ]
6
2021-03-18T08:28:01.000Z
2021-04-06T18:27:28.000Z
src/trying_tests/test_triangle.py
olga-erokhina/team13
7c800d125d7cbea5f943ff8841bcfc90c4deba11
[ "MIT" ]
1
2021-04-06T15:19:45.000Z
2021-04-06T15:19:45.000Z
import unittest import triangle as tf class test_area_triangle(unittest.TestCase): def test_area_triangle(self): """ Test triangle area """ self.assertEqual(tf.area_triangle(0, 0), 0) self.assertEqual(tf.area_triangle(1, 1), 0.5 * 1 * 1) self.assertEqual(tf.area_triangle(2, 2), 0.5 * 2 * 2) def test_values(self): """ Check that input >=0 """ self.assertRaises(ValueError, tf.area_triangle, -5, 1) self.assertRaises(ValueError, tf.area_triangle, 1, -5) self.assertRaises(ValueError, tf.area_triangle, -5, -5)
34.411765
63
0.647863
82
585
4.487805
0.268293
0.26087
0.228261
0.171196
0.567935
0.331522
0.222826
0
0
0
0
0.048035
0.217094
585
16
64
36.5625
0.755459
0.068376
0
0
0
0
0
0
0
0
0
0
0.545455
1
0.181818
false
0
0.181818
0
0.454545
0
0
0
0
null
1
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
1
0
0
0
0
0
0
0
0
0
4
b98610396c872cdd74d91d75e8af9ed05fcb7422
160
py
Python
api/core/database/__init__.py
LaudateCorpus1/api
bf684a60390ed09000ad209c9afa5e577c89ca08
[ "MIT" ]
null
null
null
api/core/database/__init__.py
LaudateCorpus1/api
bf684a60390ed09000ad209c9afa5e577c89ca08
[ "MIT" ]
1
2021-06-14T19:41:21.000Z
2021-06-14T19:41:21.000Z
api/core/database/__init__.py
LaudateCorpus1/api
bf684a60390ed09000ad209c9afa5e577c89ca08
[ "MIT" ]
null
null
null
""" The database package of the Python Discord API. This package contains the ORM models, migrations, and other functionality related to database interop. """
22.857143
53
0.78125
22
160
5.681818
0.818182
0
0
0
0
0
0
0
0
0
0
0
0.15625
160
6
54
26.666667
0.925926
0.94375
0
null
0
null
0
0
null
0
0
0
null
1
null
true
0
0
null
null
null
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
b9cbcf05cb8bbc960c2adac677704e01b6dfaf15
17,611
py
Python
restrictedroleperms/restrictedroleperms.py
kreus7/OB13-Cogs
2e5d3d772d2f6e1ae1d92545648898d314fe851e
[ "MIT" ]
null
null
null
restrictedroleperms/restrictedroleperms.py
kreus7/OB13-Cogs
2e5d3d772d2f6e1ae1d92545648898d314fe851e
[ "MIT" ]
null
null
null
restrictedroleperms/restrictedroleperms.py
kreus7/OB13-Cogs
2e5d3d772d2f6e1ae1d92545648898d314fe851e
[ "MIT" ]
null
null
null
from redbot.core import commands, Config from redbot.core.utils.chat_formatting import humanize_list import discord import typing from .rrp_converters import ExplicitAll class RestrictedRolePerms(commands.Cog): """ Restricted Permissions for Roles Gives restricted permissions to certain roles to mention/assign other roles. """ def __init__(self, bot): self.bot = bot self.config = Config.get_conf(self, identifier=14000605, force_registration=True) default_guild = { "mentionable": {"toggle": False, "rules": {}, "message": None, "success": None}, "assignable": {"toggle": False, "rules": {}, "message": None, "success": None} } self.config.register_guild(**default_guild) @staticmethod async def _has_rule(rules, author_roles, role1): perms = False for ar in author_roles: found = rules.get(ar) if found and role1 in found: perms = True elif found and "any" in found: perms = None print(rules.keys(), author_roles) return perms @commands.guild_only() @commands.group(name="rrp") async def _rrp(self, ctx: commands.Context): """RestrictedRolePerms Commands""" @_rrp.command(name="allowmentions") async def _allow_mentions(self, ctx: commands.Context, role: discord.Role): """Set a role to be mentionable.""" rules = await self.config.guild(ctx.guild).mentionable() if not rules['toggle']: return await ctx.send("The mentionability feature is toggled off for this server.") has_perms = await self._has_rule(rules['rules'], [str(r.id) for r in ctx.author.roles], role.id) if (has_perms is False) or (has_perms is None and role >= ctx.author.top_role): if rules['message']: return await ctx.send(rules['message']) return await ctx.send(f"Unfortunately, no rules were found allowing you to toggle mentionability for {role.mention}.") try: await role.edit(mentionable=True, reason=f"RRP: toggled by {ctx.author.display_name}#{ctx.author.discriminator}") except discord.Forbidden: return await ctx.send("I do not have permissions to edit this role!") except discord.HTTPException: return await ctx.send("Something went wrong while editing this role.") if rules['success']: return await ctx.send(rules['success'][0].replace("{role}", role.name).replace("{role.mention}", role.mention)) return await ctx.send(f"{role.mention} has been set to be mentionable by everyone.") @_rrp.command(name="denymentions") async def _deny_mentions(self, ctx: commands.Context, role: discord.Role): """Set a role to be non-mentionable.""" rules = await self.config.guild(ctx.guild).mentionable() if not rules['toggle']: return await ctx.send("The mentionability feature is toggled off for this server.") has_perms = await self._has_rule(rules['rules'], [str(r.id) for r in ctx.author.roles], role.id) if (has_perms is False) or (has_perms is None and role >= ctx.author.top_role): if rules['message']: return await ctx.send(rules['message']) return await ctx.send(f"Unfortunately, no rules were found allowing you to toggle mentionability for {role.mention}.") try: await role.edit(mentionable=False, reason=f"RRP: toggled by {ctx.author.display_name}#{ctx.author.discriminator}") except discord.Forbidden: return await ctx.send("I do not have permissions to edit this role!") except discord.HTTPException: return await ctx.send("Something went wrong while editing this role.") if rules['success']: return await ctx.send(rules['success'][1].replace("{role}", role.name).replace("{role.mention}", role.mention)) return await ctx.send(f"{role.mention} has been set to be not mentionable by everyone.") @_rrp.command(name="assignrole") async def _assign_role(self, ctx: commands.Context, member: discord.Member, role: discord.Role): """Assign a role to a member.""" rules = await self.config.guild(ctx.guild).assignable() if not rules['toggle']: return await ctx.send("The role assignment feature is toggled off for this server.") has_perms = await self._has_rule(rules['rules'], [str(r.id) for r in ctx.author.roles], role.id) if (has_perms is False) or (has_perms is None and role >= ctx.author.top_role): if rules['message']: return await ctx.send(rules['message']) return await ctx.send(f"Unfortunately, no rules were found allowing you to assign {role.mention}.") try: await member.add_roles(role, reason=f"RRP: assigned by {ctx.author.display_name}#{ctx.author.discriminator}") except discord.Forbidden: return await ctx.send("I do not have permissions to assign this role!") except discord.HTTPException: return await ctx.send("Something went wrong while assigning this role.") if rules['success']: return await ctx.send(rules['success'][0].replace("{role}", role.name).replace("{role.mention}", role.mention).replace("{member}", f"{member.display_name}").replace("{member.mention}", member.mention)) return await ctx.send(f"{role.mention} has been assigned to {member.mention}.") @_rrp.command(name="removerole") async def _remove_role(self, ctx: commands.Context, member: discord.Member, role: discord.Role): """Remove a role from a member.""" rules = await self.config.guild(ctx.guild).assignable() if not rules['toggle']: return await ctx.send("The role assignment feature is toggled off for this server.") has_perms = await self._has_rule(rules['rules'], [str(r.id) for r in ctx.author.roles], role.id) if (has_perms is False) or (has_perms is None and role >= ctx.author.top_role): if rules['message']: return await ctx.send(rules['message']) return await ctx.send(f"Unfortunately, no rules were found allowing you to assign {role.mention}.") if role not in member.roles: return await ctx.send("The member did not have the role!") try: await member.remove_roles(role, reason=f"RRP: removed by {ctx.author.display_name}#{ctx.author.discriminator}") except discord.Forbidden: return await ctx.send("I do not have permissions to remove this role!") except discord.HTTPException: return await ctx.send("Something went wrong while removing this role.") if rules['success']: return await ctx.send(rules['success'][1].replace("{role}", role.name).replace("{role.mention}", role.mention).replace("{member}", f"{member.display_name}").replace("{member.mention}", member.mention)) return await ctx.send(f"{role.mention} has been removed from {member.mention}.") @commands.admin() @commands.guild_only() @commands.group(name="rrpset") async def _rrpset(self, ctx: commands.Context): """RestrictedRolePerms Settings""" @_rrpset.command(name="view", aliases=["viewrules"]) async def _view(self, ctx: commands.Context): """View the current rules for RestrictedRolePerms.""" rules = await self.config.guild(ctx.guild).all() mentionable = rules['mentionable'] assignable = rules['assignable'] e = discord.Embed(title="RestrictedRolePerms Rules", color=await ctx.embed_color()) mentionable_rules = f""" **Toggle:** {mentionable["toggle"]} **Error Message:** {mentionable['message'] if mentionable['message'] else "Default"} **Success Message:** {f"{mentionable['success'][0]}, {mentionable['success'][1]}" if mentionable['success'] else "Default"} **Rules:** {"None" if not mentionable['rules'] else ""}\n""" for r0, r1 in mentionable["rules"].items(): mentionable_rules += f"{ctx.guild.get_role(int(r0)).name} can toggle mentionability for {humanize_list([ctx.guild.get_role(int(r2)) for r2 in r1])}" e.add_field(name="Mentionable", inline=False, value=mentionable_rules) assignable_rules = f""" **Toggle:** {assignable["toggle"]} **Error Message:** {assignable['message'] if assignable['message'] else "Default"} **Success Message:** {f"{assignable['success'][0]}, {assignable['success'][1]}" if assignable['success'] else "Default"} **Rules:** {"None" if not assignable['rules'] else ""}\n""" for r0, r1 in assignable["rules"].items(): assignable_rules += f"{ctx.guild.get_role(int(r0)).name} can assign {humanize_list([ctx.guild.get_role(int(r2)) for r2 in r1])}" e.add_field(name="Assignable", inline=False, value=assignable_rules) return await ctx.send(embed=e) @_rrpset.group(name="addrule") async def _add_rule(self, ctx: commands.Context): """Add a rule to give certain roles restricted permissions.""" @_add_rule.command(name="mentionable") async def _add_mentionable(self, ctx: commands.Context, role_to_give_perms_to: discord.Role, *roles_to_allow_to_be_made_mentionable: typing.Union[discord.Role, ExplicitAll]): """ Allow a certain role to make a few other roles mentionable through RRP. For `roles_to_allow_to_be_made_mentionable`, either input a list of roles or `all` to allow perms for all roles below the given role. """ # Hierarchy checks if role_to_give_perms_to >= ctx.author.top_role and ctx.author != ctx.guild.owner: return await ctx.send("The role you want to give perms to is above you in the role hierarchy!") if "all" not in roles_to_allow_to_be_made_mentionable: for rm in roles_to_allow_to_be_made_mentionable: if rm >= role_to_give_perms_to: return await ctx.send(f"{rm.mention} is above {role_to_give_perms_to.mention} in the role hierarchy!") async with self.config.guild(ctx.guild).mentionable.rules() as rules: if rules.get(str(role_to_give_perms_to.id)): return await ctx.send("There is already a rule for that role! Please remove it first using `[p]rrpset removerule`.") if "all" not in roles_to_allow_to_be_made_mentionable: rules[str(role_to_give_perms_to.id)] = [r.id for r in roles_to_allow_to_be_made_mentionable] return await ctx.send(f"{role_to_give_perms_to.mention} is now allowed to toggle mentionability for {humanize_list([r.mention for r in roles_to_allow_to_be_made_mentionable])}") else: rules[str(role_to_give_perms_to.id)] = ["all"] return await ctx.send(f"{role_to_give_perms_to.mention} is now allowed to toggle mentionability for all roles below it.") @_add_rule.command(name="assignable") async def _add_assignable(self, ctx: commands.Context, role_to_give_perms_to: discord.Role, *roles_to_allow_to_be_assigned: typing.Union[discord.Role, ExplicitAll]): """ Allow a certain role to assign a few other roles through RRP. For `roles_to_allow_to_be_assigned`, either input a list of roles or `all` to allow perms for all roles below the given role. """ # Hierarchy checks if role_to_give_perms_to >= ctx.author.top_role and ctx.author != ctx.guild.owner: return await ctx.send("The role you want to give perms to is above you in the role hierarchy!") if "all" not in roles_to_allow_to_be_assigned: for ra in roles_to_allow_to_be_assigned: if ra >= role_to_give_perms_to: return await ctx.send(f"{ra.mention} is above {role_to_give_perms_to.mention} in the role hierarchy!") async with self.config.guild(ctx.guild).assignable.rules() as rules: if rules.get(str(role_to_give_perms_to.id)): return await ctx.send("There is already a rule for that role! Please remove it first using `[p]rrpset removerule`.") if "all" not in roles_to_allow_to_be_assigned: rules[str(role_to_give_perms_to.id)] = [r.id for r in roles_to_allow_to_be_assigned] return await ctx.send(f"{role_to_give_perms_to.mention} is now allowed to assign {humanize_list([r.mention for r in roles_to_allow_to_be_assigned])}") else: rules[str(role_to_give_perms_to.id)] = ["all"] return await ctx.send(f"{role_to_give_perms_to.mention} is now allowed to assign all roles below it.") @_rrpset.group(name="removerule") async def _remove_rule(self, ctx: commands.Context): """Remove a rule to give certain roles restricted permissions.""" @_remove_rule.command(name="mentionable") async def _rem_mentionable(self, ctx: commands.Context, role: discord.Role): """Disallow a certain role to make a few other roles mentionable through RRP.""" async with self.config.guild(ctx.guild).mentionable.rules() as rules: if not rules.get(str(role.id)): return await ctx.send("There weren't any mentionability rules for that role!") del rules[str(role.id)] return await ctx.send(f"The mentionability rule for {role.mention} has been removed.") @_remove_rule.command(name="assignable") async def _rem_assignable(self, ctx: commands.Context, role: discord.Role): """Disallow a certain role to assign a few other roles through RRP.""" async with self.config.guild(ctx.guild).assignable.rules() as rules: if not rules.get(str(role.id)): return await ctx.send("There weren't any assignability rules for that role!") del rules[str(role.id)] return await ctx.send(f"The assignability rule for {role.mention} has been removed.") @_rrpset.group(name="toggle") async def _toggle(self, ctx: commands.Context): """Toggle whether each RRP feature is active.""" @_toggle.command(name="mentionable") async def _toggle_mentionable(self, ctx: commands.Context, true_or_false: bool): """Toggle RRP mentionability commands.""" await self.config.guild(ctx.guild).mentionable.toggle.set(true_or_false) return await ctx.tick() @_toggle.command(name="assignable") async def _toggle_assignable(self, ctx: commands.Context, true_or_false: bool): """Toggle RRP role assignment commands.""" await self.config.guild(ctx.guild).assignable.toggle.set(true_or_false) return await ctx.tick() @_rrpset.group(name="norulemessage") async def _no_rule_message(self, ctx: commands.Context): """Customize the error message sent when no rules are found giving the user restricted permissions.""" @_no_rule_message.command(name="mentionable") async def _no_rule_message_mentionable(self, ctx: commands.Context, *, message: str = None): """Customize the mentionability error message (leave empty to reset).""" await self.config.guild(ctx.guild).mentionable.message.set(message) return await ctx.tick() @_no_rule_message.command(name="assignable") async def _no_rule_message_assignable(self, ctx: commands.Context, *, message: str = None): """Customize the role assignment error message (leave empty to reset).""" await self.config.guild(ctx.guild).assignable.message.set(message) return await ctx.tick() @_rrpset.group(name="successmessage") async def _success_message(self, ctx: commands.Context): """Customize the error message sent when no rules are found giving the user restricted permissions.""" @_success_message.command(name="mentionable") async def _success_message_mentionable(self, ctx: commands.Context, *, message: str = None): """ Customize the mentionability success message (leave empty to reset). You can put in `{role}` or `{role.mention}`, which will be replaced with the role that is modified. Please format the message like so: `message for allowmentions//message for denymentions`. """ success_messages = message.split("//") if not len(success_messages) > 1: return await ctx.send("Please separate the 2 messages with `//`.") await self.config.guild(ctx.guild).mentionable.success.set((success_messages[0].strip(), success_messages[1].strip())) return await ctx.tick() @_success_message.command(name="assignable") async def _success_message_assignable(self, ctx: commands.Context, *, message: str = None): """ Customize the role assignment success message (leave empty to reset). You can put in `{role}` or `{role.mention}`, which will be replaced with the role that is assigned/removed. Also, you can put in `{member}` or `{member.mention}`, which will be replaced with the member. Please format the message like so: `message for assignrole//message for removerole`. """ success_messages = message.split("//") if not len(success_messages) > 1: return await ctx.send("Please separate the 2 messages with `//`.") await self.config.guild(ctx.guild).assignable.success.set((success_messages[0].strip(), success_messages[1].strip())) return await ctx.tick()
53.528875
213
0.664982
2,383
17,611
4.783466
0.097356
0.037196
0.063865
0.072638
0.801562
0.771647
0.724099
0.67155
0.650934
0.642863
0
0.002755
0.216796
17,611
328
214
53.692073
0.823679
0.008233
0
0.40724
0
0.027149
0.281643
0.065776
0
0
0
0
0
1
0.004525
false
0
0.022624
0
0.271493
0.004525
0
0
0
null
0
0
0
1
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
b9d8ec240fb398b2254a68c6bc56f95585e9a402
102
py
Python
gentelella.py
bsurnida/flask-gentelella
0501aedf105c7336a398786598b5bd6c2ccaeb51
[ "MIT" ]
1
2021-02-08T06:40:23.000Z
2021-02-08T06:40:23.000Z
gentelella.py
kchennen/flask-gentelella
ce63e32c0c07dc751335c63a83b58c82bc7b8b4d
[ "MIT" ]
null
null
null
gentelella.py
kchennen/flask-gentelella
ce63e32c0c07dc751335c63a83b58c82bc7b8b4d
[ "MIT" ]
null
null
null
from app import create_app, db from flask_migrate import Migrate app = create_app() Migrate(app, db)
17
33
0.784314
17
102
4.529412
0.411765
0.233766
0
0
0
0
0
0
0
0
0
0
0.147059
102
5
34
20.4
0.885057
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.5
0
0.5
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
0
0
0
1
0
0
0
0
4
6a0ca9bafc30356e62e63adb23caa26677f2aaa1
349
py
Python
app/queues.py
riQQ/mtgatracker
fbf45637a13e7081312f7fa181da2d8932891ab2
[ "MIT" ]
240
2018-06-01T07:31:38.000Z
2022-03-01T14:32:10.000Z
app/queues.py
riQQ/mtgatracker
fbf45637a13e7081312f7fa181da2d8932891ab2
[ "MIT" ]
303
2018-05-30T16:59:14.000Z
2022-03-25T18:23:12.000Z
app/queues.py
riQQ/mtgatracker
fbf45637a13e7081312f7fa181da2d8932891ab2
[ "MIT" ]
72
2018-06-03T00:08:59.000Z
2022-03-25T04:59:48.000Z
import multiprocessing all_die_queue = multiprocessing.Queue() block_read_queue = multiprocessing.Queue() json_blob_queue = multiprocessing.Queue() game_state_change_queue = multiprocessing.Queue() decklist_change_queue = multiprocessing.Queue() general_output_queue = multiprocessing.Queue() collection_state_change_queue = multiprocessing.Queue()
38.777778
55
0.853868
39
349
7.230769
0.410256
0.496454
0.620567
0.329787
0.255319
0
0
0
0
0
0
0
0.065903
349
9
55
38.777778
0.865031
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.125
0
0.125
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
0
0
0
0
0
0
0
4
6a1901c1674978ed3eaa1f4ad711e6a6dd98b8bd
221
py
Python
pygmalion/utilities/__init__.py
BFavier/pygmalion
76391431e55fa1c28dc7a1822f2917bf8487b94b
[ "MIT" ]
null
null
null
pygmalion/utilities/__init__.py
BFavier/pygmalion
76391431e55fa1c28dc7a1822f2917bf8487b94b
[ "MIT" ]
null
null
null
pygmalion/utilities/__init__.py
BFavier/pygmalion
76391431e55fa1c28dc7a1822f2917bf8487b94b
[ "MIT" ]
null
null
null
from ._cross_validation import split, kfold from ._metrics import MSE, RMSE, R2, accuracy, confusion_matrix, GPU_info from ._ploting import plot_fitting, plot_bounding_boxes, plot_matrix from ._decorators import document
44.2
73
0.837104
31
221
5.612903
0.709677
0
0
0
0
0
0
0
0
0
0
0.005076
0.108597
221
4
74
55.25
0.878173
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
4
6a23c553a35d19c961a233c37717cda28c168d83
8,321
py
Python
src/scripts/swagger_client/models/inline_response2001_data_attributes.py
shipyardbuild/circleci-orb
5cc1393aac44ff62b95db5ec725702d8a7dbb216
[ "MIT" ]
null
null
null
src/scripts/swagger_client/models/inline_response2001_data_attributes.py
shipyardbuild/circleci-orb
5cc1393aac44ff62b95db5ec725702d8a7dbb216
[ "MIT" ]
4
2021-09-01T21:15:02.000Z
2022-01-04T18:37:48.000Z
src/scripts/swagger_client/models/inline_response2001_data_attributes.py
shipyardbuild/circleci-orb
5cc1393aac44ff62b95db5ec725702d8a7dbb216
[ "MIT" ]
null
null
null
# coding: utf-8 """ Shipyard API The official OpenAPI spec for the Shipyard API. # noqa: E501 OpenAPI spec version: 0.1 Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six class InlineResponse2001DataAttributes(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'bypass_token': 'str', 'paused': 'bool', 'stopped': 'bool', 'projects': 'list[InlineResponse2001DataAttributesProjects]', 'ready': 'bool', 'name': 'str', 'processing': 'bool', 'url': 'str' } attribute_map = { 'bypass_token': 'bypass_token', 'paused': 'paused', 'stopped': 'stopped', 'projects': 'projects', 'ready': 'ready', 'name': 'name', 'processing': 'processing', 'url': 'url' } def __init__(self, bypass_token=None, paused=None, stopped=None, projects=None, ready=None, name=None, processing=None, url=None): # noqa: E501 """InlineResponse2001DataAttributes - a model defined in Swagger""" # noqa: E501 self._bypass_token = None self._paused = None self._stopped = None self._projects = None self._ready = None self._name = None self._processing = None self._url = None self.discriminator = None if bypass_token is not None: self.bypass_token = bypass_token if paused is not None: self.paused = paused if stopped is not None: self.stopped = stopped if projects is not None: self.projects = projects if ready is not None: self.ready = ready if name is not None: self.name = name if processing is not None: self.processing = processing if url is not None: self.url = url @property def bypass_token(self): """Gets the bypass_token of this InlineResponse2001DataAttributes. # noqa: E501 :return: The bypass_token of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: str """ return self._bypass_token @bypass_token.setter def bypass_token(self, bypass_token): """Sets the bypass_token of this InlineResponse2001DataAttributes. :param bypass_token: The bypass_token of this InlineResponse2001DataAttributes. # noqa: E501 :type: str """ self._bypass_token = bypass_token @property def paused(self): """Gets the paused of this InlineResponse2001DataAttributes. # noqa: E501 :return: The paused of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: bool """ return self._paused @paused.setter def paused(self, paused): """Sets the paused of this InlineResponse2001DataAttributes. :param paused: The paused of this InlineResponse2001DataAttributes. # noqa: E501 :type: bool """ self._paused = paused @property def stopped(self): """Gets the stopped of this InlineResponse2001DataAttributes. # noqa: E501 :return: The stopped of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: bool """ return self._stopped @stopped.setter def stopped(self, stopped): """Sets the stopped of this InlineResponse2001DataAttributes. :param stopped: The stopped of this InlineResponse2001DataAttributes. # noqa: E501 :type: bool """ self._stopped = stopped @property def projects(self): """Gets the projects of this InlineResponse2001DataAttributes. # noqa: E501 :return: The projects of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: list[InlineResponse2001DataAttributesProjects] """ return self._projects @projects.setter def projects(self, projects): """Sets the projects of this InlineResponse2001DataAttributes. :param projects: The projects of this InlineResponse2001DataAttributes. # noqa: E501 :type: list[InlineResponse2001DataAttributesProjects] """ self._projects = projects @property def ready(self): """Gets the ready of this InlineResponse2001DataAttributes. # noqa: E501 :return: The ready of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: bool """ return self._ready @ready.setter def ready(self, ready): """Sets the ready of this InlineResponse2001DataAttributes. :param ready: The ready of this InlineResponse2001DataAttributes. # noqa: E501 :type: bool """ self._ready = ready @property def name(self): """Gets the name of this InlineResponse2001DataAttributes. # noqa: E501 :return: The name of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: str """ return self._name @name.setter def name(self, name): """Sets the name of this InlineResponse2001DataAttributes. :param name: The name of this InlineResponse2001DataAttributes. # noqa: E501 :type: str """ self._name = name @property def processing(self): """Gets the processing of this InlineResponse2001DataAttributes. # noqa: E501 :return: The processing of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: bool """ return self._processing @processing.setter def processing(self, processing): """Sets the processing of this InlineResponse2001DataAttributes. :param processing: The processing of this InlineResponse2001DataAttributes. # noqa: E501 :type: bool """ self._processing = processing @property def url(self): """Gets the url of this InlineResponse2001DataAttributes. # noqa: E501 :return: The url of this InlineResponse2001DataAttributes. # noqa: E501 :rtype: str """ return self._url @url.setter def url(self, url): """Sets the url of this InlineResponse2001DataAttributes. :param url: The url of this InlineResponse2001DataAttributes. # noqa: E501 :type: str """ self._url = url def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(InlineResponse2001DataAttributes, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, InlineResponse2001DataAttributes): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
28.399317
148
0.600288
844
8,321
5.81872
0.136256
0.039096
0.247607
0.205254
0.449196
0.367746
0.355325
0.222154
0.107514
0.015475
0
0.042895
0.31078
8,321
292
149
28.496575
0.813426
0.387814
0
0.076336
1
0
0.060131
0.010763
0
0
0
0
0
1
0.167939
false
0.083969
0.022901
0
0.320611
0.015267
0
0
0
null
0
1
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
4
6a241dfa2e72e1d486aed6f347d8b153339ae9e6
339
py
Python
gen_proto_with_import/puppet_message.py
huan/python-betterproto-issue
d06391b9e2aa203a5366e1d00a57d181ffeb5678
[ "Apache-2.0" ]
null
null
null
gen_proto_with_import/puppet_message.py
huan/python-betterproto-issue
d06391b9e2aa203a5366e1d00a57d181ffeb5678
[ "Apache-2.0" ]
null
null
null
gen_proto_with_import/puppet_message.py
huan/python-betterproto-issue
d06391b9e2aa203a5366e1d00a57d181ffeb5678
[ "Apache-2.0" ]
null
null
null
# Generated by the protocol buffer compiler. DO NOT EDIT! # sources: puppet_message/base.proto # plugin: python-betterproto from dataclasses import dataclass import betterproto @dataclass class DingRequest(betterproto.Message): data: str = betterproto.string_field(1) @dataclass class DingResponse(betterproto.Message): pass
19.941176
58
0.787611
40
339
6.625
0.75
0.10566
0
0
0
0
0
0
0
0
0
0.003425
0.138643
339
16
59
21.1875
0.90411
0.348083
0
0.25
1
0
0
0
0
0
0
0
0
1
0
true
0.125
0.25
0
0.625
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
1
1
0
0
1
0
0
4
6a3bc0ed30c4636645b5e623d691fd188343104c
136
py
Python
warbend/util/memoize.py
int19h/warbend
1cee2aa547309a15ed02a879a1f3a153f17bbfc4
[ "MIT" ]
4
2018-08-03T13:29:53.000Z
2020-04-16T08:16:07.000Z
warbend/util/memoize.py
int19h/warbend
1cee2aa547309a15ed02a879a1f3a153f17bbfc4
[ "MIT" ]
1
2019-08-19T22:45:02.000Z
2019-09-20T14:18:44.000Z
warbend/util/memoize.py
int19h/warbend
1cee2aa547309a15ed02a879a1f3a153f17bbfc4
[ "MIT" ]
null
null
null
from __future__ import absolute_import, division, print_function from functools32 import lru_cache as memoize memoize = memoize(None)
22.666667
64
0.838235
18
136
5.944444
0.722222
0.261682
0
0
0
0
0
0
0
0
0
0.016807
0.125
136
5
65
27.2
0.882353
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0.666667
0
0.666667
0.333333
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
0
0
0
1
0
0
0
0
4
dbe020aec5626a09284feb5b4f03abedcacab311
8,106
py
Python
nova/tests/functional/api_sample_tests/test_quota_sets.py
bopopescu/nova-token
ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2
[ "Apache-2.0" ]
null
null
null
nova/tests/functional/api_sample_tests/test_quota_sets.py
bopopescu/nova-token
ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2
[ "Apache-2.0" ]
null
null
null
nova/tests/functional/api_sample_tests/test_quota_sets.py
bopopescu/nova-token
ec98f69dea7b3e2b9013b27fd55a2c1a1ac6bfb2
[ "Apache-2.0" ]
2
2017-07-20T17:31:34.000Z
2020-07-24T02:42:19.000Z
begin_unit comment|'# Copyright 2012 Nebula, Inc.' nl|'\n' comment|'# Copyright 2013 IBM Corp.' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' name|'from' name|'oslo_config' name|'import' name|'cfg' newline|'\n' nl|'\n' name|'from' name|'nova' op|'.' name|'tests' op|'.' name|'functional' op|'.' name|'api_sample_tests' name|'import' name|'api_sample_base' newline|'\n' nl|'\n' DECL|variable|CONF name|'CONF' op|'=' name|'cfg' op|'.' name|'CONF' newline|'\n' name|'CONF' op|'.' name|'import_opt' op|'(' string|"'osapi_compute_extension'" op|',' nl|'\n' string|"'nova.api.openstack.compute.legacy_v2.extensions'" op|')' newline|'\n' nl|'\n' nl|'\n' DECL|class|QuotaSetsSampleJsonTests name|'class' name|'QuotaSetsSampleJsonTests' op|'(' name|'api_sample_base' op|'.' name|'ApiSampleTestBaseV21' op|')' op|':' newline|'\n' DECL|variable|ADMIN_API indent|' ' name|'ADMIN_API' op|'=' name|'True' newline|'\n' DECL|variable|extension_name name|'extension_name' op|'=' string|'"os-quota-sets"' newline|'\n' nl|'\n' DECL|member|_get_flags name|'def' name|'_get_flags' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'f' op|'=' name|'super' op|'(' name|'QuotaSetsSampleJsonTests' op|',' name|'self' op|')' op|'.' name|'_get_flags' op|'(' op|')' newline|'\n' name|'f' op|'[' string|"'osapi_compute_extension'" op|']' op|'=' name|'CONF' op|'.' name|'osapi_compute_extension' op|'[' op|':' op|']' newline|'\n' name|'f' op|'[' string|"'osapi_compute_extension'" op|']' op|'.' name|'append' op|'(' string|"'nova.api.openstack.compute.'" nl|'\n' string|"'contrib.server_group_quotas.'" nl|'\n' string|"'Server_group_quotas'" op|')' newline|'\n' name|'f' op|'[' string|"'osapi_compute_extension'" op|']' op|'.' name|'append' op|'(' string|"'nova.api.openstack.compute.'" nl|'\n' string|"'contrib.quotas.Quotas'" op|')' newline|'\n' name|'f' op|'[' string|"'osapi_compute_extension'" op|']' op|'.' name|'append' op|'(' string|"'nova.api.openstack.compute.'" nl|'\n' string|"'contrib.extended_quotas.Extended_quotas'" op|')' newline|'\n' name|'f' op|'[' string|"'osapi_compute_extension'" op|']' op|'.' name|'append' op|'(' string|"'nova.api.openstack.compute.'" nl|'\n' string|"'contrib.user_quotas.User_quotas'" op|')' newline|'\n' name|'return' name|'f' newline|'\n' nl|'\n' DECL|member|test_show_quotas dedent|'' name|'def' name|'test_show_quotas' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to show quotas.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_get' op|'(' string|"'os-quota-sets/fake_tenant'" op|')' newline|'\n' name|'self' op|'.' name|'_verify_response' op|'(' string|"'quotas-show-get-resp'" op|',' op|'{' op|'}' op|',' name|'response' op|',' number|'200' op|')' newline|'\n' nl|'\n' DECL|member|test_show_quotas_defaults dedent|'' name|'def' name|'test_show_quotas_defaults' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to show quotas defaults.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_get' op|'(' string|"'os-quota-sets/fake_tenant/defaults'" op|')' newline|'\n' name|'self' op|'.' name|'_verify_response' op|'(' string|"'quotas-show-defaults-get-resp'" op|',' nl|'\n' op|'{' op|'}' op|',' name|'response' op|',' number|'200' op|')' newline|'\n' nl|'\n' DECL|member|test_show_quotas_detail dedent|'' name|'def' name|'test_show_quotas_detail' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to show quotas detail.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_get' op|'(' string|"'os-quota-sets/fake_tenant/detail'" op|')' newline|'\n' name|'self' op|'.' name|'_verify_response' op|'(' string|"'quotas-show-detail-get-resp'" op|',' nl|'\n' op|'{' op|'}' op|',' name|'response' op|',' number|'200' op|')' newline|'\n' nl|'\n' DECL|member|test_update_quotas dedent|'' name|'def' name|'test_update_quotas' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to update quotas.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_put' op|'(' string|"'os-quota-sets/fake_tenant'" op|',' nl|'\n' string|"'quotas-update-post-req'" op|',' nl|'\n' op|'{' op|'}' op|')' newline|'\n' name|'self' op|'.' name|'_verify_response' op|'(' string|"'quotas-update-post-resp'" op|',' op|'{' op|'}' op|',' name|'response' op|',' number|'200' op|')' newline|'\n' nl|'\n' DECL|member|test_delete_quotas dedent|'' name|'def' name|'test_delete_quotas' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to delete quota.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_delete' op|'(' string|"'os-quota-sets/fake_tenant'" op|')' newline|'\n' name|'self' op|'.' name|'assertEqual' op|'(' number|'202' op|',' name|'response' op|'.' name|'status_code' op|')' newline|'\n' name|'self' op|'.' name|'assertEqual' op|'(' string|"''" op|',' name|'response' op|'.' name|'content' op|')' newline|'\n' nl|'\n' DECL|member|test_update_quotas_force dedent|'' name|'def' name|'test_update_quotas_force' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to update quotas.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_put' op|'(' string|"'os-quota-sets/fake_tenant'" op|',' nl|'\n' string|"'quotas-update-force-post-req'" op|',' nl|'\n' op|'{' op|'}' op|')' newline|'\n' name|'return' name|'self' op|'.' name|'_verify_response' op|'(' string|"'quotas-update-force-post-resp'" op|',' op|'{' op|'}' op|',' nl|'\n' name|'response' op|',' number|'200' op|')' newline|'\n' nl|'\n' DECL|member|test_show_quotas_for_user dedent|'' name|'def' name|'test_show_quotas_for_user' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to show quotas for user.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_get' op|'(' string|"'os-quota-sets/fake_tenant?user_id=1'" op|')' newline|'\n' name|'self' op|'.' name|'_verify_response' op|'(' string|"'user-quotas-show-get-resp'" op|',' op|'{' op|'}' op|',' name|'response' op|',' number|'200' op|')' newline|'\n' nl|'\n' DECL|member|test_delete_quotas_for_user dedent|'' name|'def' name|'test_delete_quotas_for_user' op|'(' name|'self' op|')' op|':' newline|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_delete' op|'(' string|"'os-quota-sets/fake_tenant?user_id=1'" op|')' newline|'\n' name|'self' op|'.' name|'assertEqual' op|'(' number|'202' op|',' name|'response' op|'.' name|'status_code' op|')' newline|'\n' name|'self' op|'.' name|'assertEqual' op|'(' string|"''" op|',' name|'response' op|'.' name|'content' op|')' newline|'\n' nl|'\n' DECL|member|test_update_quotas_for_user dedent|'' name|'def' name|'test_update_quotas_for_user' op|'(' name|'self' op|')' op|':' newline|'\n' comment|'# Get api sample to update quotas for user.' nl|'\n' indent|' ' name|'response' op|'=' name|'self' op|'.' name|'_do_put' op|'(' string|"'os-quota-sets/fake_tenant?user_id=1'" op|',' nl|'\n' string|"'user-quotas-update-post-req'" op|',' nl|'\n' op|'{' op|'}' op|')' newline|'\n' name|'return' name|'self' op|'.' name|'_verify_response' op|'(' string|"'user-quotas-update-post-resp'" op|',' op|'{' op|'}' op|',' nl|'\n' name|'response' op|',' number|'200' op|')' newline|'\n' dedent|'' dedent|'' endmarker|'' end_unit
14.846154
88
0.635825
1,222
8,106
4.100655
0.121931
0.085013
0.075833
0.047895
0.746558
0.719218
0.685292
0.647376
0.628617
0.615246
0
0.00616
0.098816
8,106
545
89
14.873395
0.679808
0
0
0.862385
0
0
0.440908
0.154453
0
0
0
0
0.007339
0
null
null
0
0.005505
null
null
0
0
0
0
null
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
null
0
0
0
0
1
0
0
0
0
0
0
0
0
4
dbe76d7dd9e4d8849d35ac151e5f6d7926b58a5a
18
py
Python
deneme1.py
ozgur67/bot
35f103603fba65de362284d355cc697ead291a9b
[ "MIT" ]
null
null
null
deneme1.py
ozgur67/bot
35f103603fba65de362284d355cc697ead291a9b
[ "MIT" ]
null
null
null
deneme1.py
ozgur67/bot
35f103603fba65de362284d355cc697ead291a9b
[ "MIT" ]
null
null
null
a=2 b=3 print(a+b)
6
10
0.611111
7
18
1.571429
0.714286
0
0
0
0
0
0
0
0
0
0
0.125
0.111111
18
3
10
6
0.5625
0
0
0
0
0
0
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
1
1
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
0
0
0
0
0
0
0
4
e00b2120380740af093cffc4d5c21e77f4c5e1ba
148
py
Python
bom1/tests/test_timestamp_to_seconds.py
vstenby/Best-of-Mat1
e2e131684ed0229e8e762965ea03e653718c1fed
[ "MIT" ]
9
2020-11-17T17:13:48.000Z
2022-02-08T21:24:16.000Z
bom1/tests/test_timestamp_to_seconds.py
vstenby/Best-of-Mat1
e2e131684ed0229e8e762965ea03e653718c1fed
[ "MIT" ]
null
null
null
bom1/tests/test_timestamp_to_seconds.py
vstenby/Best-of-Mat1
e2e131684ed0229e8e762965ea03e653718c1fed
[ "MIT" ]
2
2021-09-20T17:39:00.000Z
2022-02-02T13:02:42.000Z
import bom1 import pytest def test_timestamp_to_seconds(): s = bom1.timestamp_to_seconds('00:00:00.00') assert s == 0 return
16.444444
48
0.655405
22
148
4.181818
0.590909
0.130435
0.391304
0
0
0
0
0
0
0
0
0.099099
0.25
148
9
49
16.444444
0.72973
0
0
0
0
0
0.073826
0
0
0
0
0
0.166667
1
0.166667
false
0
0.333333
0
0.666667
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
0
0
0
1
0
0
0
0
4
e03b59102250e426065dbd4e54934ac562137845
147
py
Python
web_sample/server.py
pygics-exp/samples
ee118ff81d582696b57cdb76dfc2b49304cb825e
[ "Apache-2.0" ]
null
null
null
web_sample/server.py
pygics-exp/samples
ee118ff81d582696b57cdb76dfc2b49304cb825e
[ "Apache-2.0" ]
null
null
null
web_sample/server.py
pygics-exp/samples
ee118ff81d582696b57cdb76dfc2b49304cb825e
[ "Apache-2.0" ]
null
null
null
# -*- coding: utf-8 -*- ''' Created on 2017. 5. 29. @author: HyechurnJang ''' import pygics pygics.server('0.0.0.0', 80, '../web_sample')
16.333333
45
0.571429
21
147
3.952381
0.809524
0.072289
0.072289
0
0
0
0
0
0
0
0
0.117647
0.190476
147
9
45
16.333333
0.579832
0.462585
0
0
0
0
0.3125
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
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
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
e042443560192f450ee2993db34f5d2c3b002cb4
247
py
Python
ccapi/requests/exports/__init__.py
stcstores/ccapi
cc137efa7344b8552e122d30899616bfdbd6af0b
[ "MIT" ]
1
2018-09-11T11:53:22.000Z
2018-09-11T11:53:22.000Z
ccapi/requests/exports/__init__.py
stcstores/ccapi
cc137efa7344b8552e122d30899616bfdbd6af0b
[ "MIT" ]
24
2018-09-11T13:57:53.000Z
2022-03-18T10:18:36.000Z
ccapi/requests/exports/__init__.py
stcstores/ccapi
cc137efa7344b8552e122d30899616bfdbd6af0b
[ "MIT" ]
1
2018-09-12T12:04:58.000Z
2018-09-12T12:04:58.000Z
"""Reqests for exports.""" from .getproductexportupdate import GetProductExportUpdate from .requestproductexport import RequestProductExport from .viewfile import ViewFile __all__ = ["GetProductExportUpdate", "RequestProductExport", "ViewFile"]
30.875
72
0.825911
19
247
10.526316
0.473684
0
0
0
0
0
0
0
0
0
0
0
0.089069
247
7
73
35.285714
0.888889
0.080972
0
0
0
0
0.226244
0.099548
0
0
0
0
0
1
0
false
0
0.75
0
0.75
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
0
0
1
0
0
0
0
4
e04bf423c156fc3ef2c8e0f9aafbd32522ae60ba
75
py
Python
dingdian/entrypoint.py
jfzhang95/web_spider
9ad31d9cbbdf2a4bddfed8e649d5e0fa1b24d1b6
[ "MIT" ]
null
null
null
dingdian/entrypoint.py
jfzhang95/web_spider
9ad31d9cbbdf2a4bddfed8e649d5e0fa1b24d1b6
[ "MIT" ]
null
null
null
dingdian/entrypoint.py
jfzhang95/web_spider
9ad31d9cbbdf2a4bddfed8e649d5e0fa1b24d1b6
[ "MIT" ]
1
2020-05-16T06:55:36.000Z
2020-05-16T06:55:36.000Z
from scrapy.cmdline import execute execute(['scrapy', 'crawl', 'dingdian'])
37.5
40
0.746667
9
75
6.222222
0.777778
0
0
0
0
0
0
0
0
0
0
0
0.08
75
2
40
37.5
0.811594
0
0
0
0
0
0.25
0
0
0
0
0
0
1
0
true
0
0.5
0
0.5
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
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
e05c181c2d89f2c847142e7802c5ada14a54cefc
127
py
Python
run.py
t-bence/home_server
8b2e32920bc7337610d32fc2f150dbda20a218e2
[ "MIT" ]
null
null
null
run.py
t-bence/home_server
8b2e32920bc7337610d32fc2f150dbda20a218e2
[ "MIT" ]
null
null
null
run.py
t-bence/home_server
8b2e32920bc7337610d32fc2f150dbda20a218e2
[ "MIT" ]
null
null
null
#!/usr/bin/python from app import app app.jinja_env.add_extension('jinja2.ext.do') app.run(host='0.0.0.0', port=80, debug=True)
31.75
44
0.732283
26
127
3.5
0.769231
0.065934
0.065934
0
0
0
0
0
0
0
0
0.058824
0.062992
127
4
45
31.75
0.705882
0.125984
0
0
0
0
0.18018
0
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
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
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
0ed5ef7fe5723f335163052606eea9f713d2ec55
148
py
Python
src/huehue/bridge/__init__.py
zenware/huehue
dfd2c4d814afba7e41033b89b6b0f1ab0daa9b05
[ "MIT" ]
2
2020-11-09T16:26:51.000Z
2020-11-09T17:45:17.000Z
src/huehue/bridge/__init__.py
zenware/huehue
dfd2c4d814afba7e41033b89b6b0f1ab0daa9b05
[ "MIT" ]
1
2020-08-30T22:07:44.000Z
2020-09-04T00:50:10.000Z
src/huehue/bridge/__init__.py
zenware/huehue
dfd2c4d814afba7e41033b89b6b0f1ab0daa9b05
[ "MIT" ]
null
null
null
class Bridge: __ipaddress = None __username = None def __init__(self): pass def discover_bridges(self): pass
13.454545
31
0.581081
15
148
5.133333
0.733333
0.207792
0
0
0
0
0
0
0
0
0
0
0.358108
148
11
32
13.454545
0.810526
0
0
0.285714
0
0
0
0
0
0
0
0
0
1
0.285714
false
0.285714
0
0
0.714286
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
0
1
0
0
0
0
0
4
0edae5d2bb90a8adbb1bfa96ae0b1f0ee166b019
164
py
Python
run-debug-webhooks.py
MiniCodeMonkey/machine
010f2c85a9e037aa3e4a3a26f7bc0e673be68b37
[ "ISC" ]
101
2015-01-14T19:05:09.000Z
2021-03-07T10:57:24.000Z
run-debug-webhooks.py
MiniCodeMonkey/machine
010f2c85a9e037aa3e4a3a26f7bc0e673be68b37
[ "ISC" ]
470
2015-01-01T20:27:47.000Z
2022-01-31T20:26:27.000Z
run-debug-webhooks.py
MiniCodeMonkey/machine
010f2c85a9e037aa3e4a3a26f7bc0e673be68b37
[ "ISC" ]
52
2015-01-07T16:29:37.000Z
2020-12-14T06:46:09.000Z
#!/usr/bin/env python ''' Run openaddr.ci.webhooks.app in Flask debug mode. ''' from openaddr.ci.web import app if __name__ == '__main__': app.run(debug=True)
20.5
53
0.695122
26
164
4.076923
0.769231
0.188679
0
0
0
0
0
0
0
0
0
0
0.146341
164
7
54
23.428571
0.757143
0.426829
0
0
0
0
0.093023
0
0
0
0
0
0
1
0
true
0
0.333333
0
0.333333
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
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
0
0
0
4
0ee7c4c42f067d2e1463a66d26e33534da7b0e5f
3,877
py
Python
backend/config.py
marionthefourth/peekachu
d958985996d19ba5d52d35052fd67332805a870d
[ "MIT" ]
null
null
null
backend/config.py
marionthefourth/peekachu
d958985996d19ba5d52d35052fd67332805a870d
[ "MIT" ]
null
null
null
backend/config.py
marionthefourth/peekachu
d958985996d19ba5d52d35052fd67332805a870d
[ "MIT" ]
null
null
null
short_sample_text = "Our booked passenger showed in a moment that it was his name. The guard, the coachman, and the " \ "two other passengers eyed him distrustfully." medium_sample_text = "It was the year of Our Lord one thousand seven hundred and seventy-five. Spiritual revelations " \ "were conceded to England at that favoured period, as at this. Mrs. Southcott had recently " \ "attained her five-and-twentieth blessed birthday, of whom a prophetic private in the Life " \ "Guards had heralded the sublime appearance by announcing that arrangements were made for the " \ "swallowing up of London and Westminster. Even the Cock-lane ghost had been laid only a round " \ "dozen of years, after rapping out its messages, as the spirits of this very year last past " \ "(supernaturally deficient in originality) rapped out theirs. Mere messages in the earthly " \ "order of events had lately come to the English Crown and People, from a congress of British " \ "subjects in America: which, strange to relate, have proved more important to the human race " \ "than any communications yet received through any of the chickens of the Cock-lane brood." large_sample_text = "There was a steaming mist in all the hollows, and it had roamed in its forlornness up the hill, " \ "like an evil spirit, seeking rest and finding none. A clammy and intensely cold mist, it made " \ "its slow way through the air in ripples that visibly followed and overspread one another, as " \ "the waves of an unwholesome sea might do. It was dense enough to shut out everything from the " \ "light of the coach-lamps but these its own workings, and a few yards of road; and the reek of " \ "the labouring horses steamed into it, as if they had made it all.\nTwo other passengers, " \ "besides the one, were plodding up the hill by the side of the mail. All three were wrapped to " \ "the cheekbones and over the ears, and wore jack-boots. Not one of the three could have said, " \ "from anything he saw, what either of the other two was like; and each was hidden under almost " \ "as many wrappers from the eyes of the mind, as from the eyes of the body, of his two " \ "companions. In those days, travellers were very shy of being confidential on a short notice, " \ "for anybody on the road might be a robber or in league with robbers. As to the latter, when " \ "every posting-house and ale-house could produce somebody in “the Captain’s” pay, ranging from " \ "the landlord to the lowest stable non-descript, it was the likeliest thing upon the cards. So " \ "the guard of the Dover mail thought to himself, that Friday night in November, one thousand " \ "seven hundred and seventy-five, lumbering up Shooter’s Hill, as he stood on his own particular " \ "perch behind the mail, beating his feet, and keeping an eye and a hand on the arm-chest before " \ "him, where a loaded blunderbuss lay at the top of six or eight loaded horse-pistols, deposited " \ "on the passengers, the passengers suspected one another and the guard, they all suspected " \ "everybody else, and the coachman was sure of nothing but the horses; as to which cattle he " \ "could with a clear conscience have taken his oath on the two Testaments that they were not " \ "fit for the journey."
104.783784
120
0.636317
554
3,877
4.442238
0.527076
0.020317
0.006501
0.018692
0.043072
0.030069
0.030069
0
0
0
0
0
0.31674
3,877
36
121
107.694444
0.92903
0
0
0
0
0.294118
0.779211
0
0
0
0
0
0
1
0
false
0.117647
0.029412
0
0.029412
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
1
0
null
0
0
0
0
0
0
0
1
0
0
0
0
0
4
0ee8ebe101ff3f74de18a18ea2b3b328b3288a6b
175
py
Python
python-exercises/while_loop.py
nakonovalov/Python-for-beginners
f19bf104dfec129cf86706484bcd49043698bd71
[ "MIT" ]
158
2018-10-03T23:36:48.000Z
2022-03-25T00:16:00.000Z
python-exercises/while_loop.py
nakonovalov/Python-for-beginners
f19bf104dfec129cf86706484bcd49043698bd71
[ "MIT" ]
10
2018-10-11T03:52:28.000Z
2019-12-04T02:51:28.000Z
python-exercises/while_loop.py
nakonovalov/Python-for-beginners
f19bf104dfec129cf86706484bcd49043698bd71
[ "MIT" ]
40
2018-10-03T10:47:28.000Z
2022-02-22T19:55:46.000Z
# A simple while loop example user_input = input('Hey how are you ') while user_input != 'stop copying me': print(user_input) user_input = input() else: print('UGHH Fine')
25
39
0.714286
28
175
4.321429
0.642857
0.297521
0.231405
0
0
0
0
0
0
0
0
0
0.165714
175
7
40
25
0.828767
0.154286
0
0
0
0
0.272109
0
0
0
0
0
0
1
0
false
0
0
0
0
0.333333
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
0
0
0
0
0
0
0
4
0efaf952df582503e4d476032aa0c070cca9c13f
4,385
py
Python
online_recommend/test/test3.py
hfhfn/db_recommend
3a9f03157bb81e295f8cff30fbc7ad2a8cfdf963
[ "MIT" ]
null
null
null
online_recommend/test/test3.py
hfhfn/db_recommend
3a9f03157bb81e295f8cff30fbc7ad2a8cfdf963
[ "MIT" ]
null
null
null
online_recommend/test/test3.py
hfhfn/db_recommend
3a9f03157bb81e295f8cff30fbc7ad2a8cfdf963
[ "MIT" ]
null
null
null
# i = 1 # print("=" * 20 + str(i) + "=" * 20) # print("=======1=======") # list_3 = lambda:[x for x in range(10)] # print(list_3()) # print("=======2=======") # i= 0 # list = [(lambda: i) for x in range(10)] # for j in range(len(list)): # print(list[j](),end='')# # print() # print("========3======") # list = [(lambda: x) for x in range(10)] # for j in range(len(list)): # print(list[j](),end='')# # print() # print("========4======") # list = [lambda: x for x in range(10)] # for j in range(len(list)): # print(list[j](),end='') from datetime import datetime, timedelta import time # t1 = 1384876800 # t2 = 1385049599 # t3 = int(time.time()) # print(t3) # t = t3 - t3 % (3600 * 24) # print(t) # print(t3) # t8 = datetime.now() # print(t8) # t = time.localtime(t) # tt = time.localtime(t2) # time_tmp = time.strftime('%Y-%m-%d %H:%M:%S', t) # print(time_tmp) # dt1 = datetime.utcfromtimestamp(t1) # dt2 = datetime.utcfromtimestamp(t2) # dt3 = datetime.utcfromtimestamp(t) # print(type(dt3)) # print(dt3) # print(dt2 - dt1) # t00 = timedelta(1, 86399) # t0 = timedelta(days=30) # t000 = int(t0.total_seconds()) # print(t3 - t000) # print(time) # print((dt2 - dt1).seconds) # print((dt2 - dt1).days) # print((dt3-dt2).total_seconds()) # print((dt3-dt2).seconds/3600) # print((dt3-dt2).days) # import pytz # tz = pytz.timezone('Asia/Shanghai') # t4 = datetime.fromtimestamp(1537431607,tz) # t5 = t4.strftime('%Y-%m-%d %H:%M:%S') # t6 = t4.strftime('%Y-%m-%d') # # t7 = datetime.strptime(t5, '%Y-%m-%d %H:%M:%S') # print(t4, t6, type(t5), type(t7)) # print((t7-t0).date()) from datetime import datetime, timedelta # _yester = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) # print(_yester) # start = datetime.strftime(_yester + timedelta(days=0, hours=-1, minutes=0), "%Y-%m-%d %H:%M:%S") # end = datetime.strftime(_yester, "%Y-%m-%d") # end = datetime.strftime(dt3, "%Y%m%d") # print(start) # print(end[-2:]) # print(type(datetime.now())) # print(type(datetime.today().year)) # print(datetime.today().strftime('%Y-%m-%d')) # a = '美国队长(普通话版)' # # print(list(a)) # # print(a.split()) # import jieba # print(jieba.lcut(a)) # print(len(a)) import numpy as np # import math # a = 1/(np.log2(10)+1) # b = 1/(np.log2(500)+1) # c = 1/(np.log2(1000)+1) # d = 1/(np.log2(5000)+1) # print(a/b, b/c, c/d) # a = 1/(np.log10(10)+1) # b = 1/(np.log10(500)+1) # c = 1/(np.log10(1000)+1) # d = 1/(np.log10(5000)+1) # print(a/b, b/c, c/d) # a = 1/(math.logs(10,100)+1) # b = 1/(math.logs(500,100)+1) # c = 1/(math.logs(1000,100)+1) # d = 1/(math.logs(5000,100)+1) # print(a/b, b/c, c/d) # print(1 / np.exp(0.1), 1 / np.exp(2)) # print(1 / 2**0.1, 1 / 2**2) # a = [1, 4, 7] # b = [2, 5, 8] # c = [3, 6, 9] # print(list(zip(a, b, c))) # print(np.array(c) + 2) # from utils import day_timestamp # def test(t): # print('hello world') # print(t) # # from apscheduler.schedulers.blocking import BlockingScheduler # from apscheduler.executors.pool import ProcessPoolExecutor # executors = { # 'default': ProcessPoolExecutor(3) # } # # scheduler = BlockingScheduler(executors=executors) # # scheduler.add_job(test, "cron", day_of_week='*', hour='12', minute='45', second='10') # # scheduler.add_job(test, "cron", day='*', hour='13', minute='9', second='10', args=[day_timestamp]) # scheduler.add_job(test, "cron", second='*', args=[day_timestamp]) # scheduler.start() # import os # print(os.listdir('data/data_count')) # for a in os.walk('data'): # print(a) import time import datetime # # 今天日期 # today = datetime.date.today() # print(today.day) # # 昨天时间 # yesterday = today - datetime.timedelta(days=1) # # # from datetime import datetime # # date_str = datetime.strftime(today, "%Y%m%d") # date_str = today.strftime("%Y%m%d") # yesterday_str = yesterday.strftime("%Y%m%d") # # timestamp = int(time.mktime(time.strptime(str(yesterday), '%Y-%m-%d'))) # 零点时间戳 # print(timestamp) # print(type(today)) # print(yesterday) # print(date_str) # print(yesterday_str) # a = 24 # b = 28 # c = a // 10 + 1 # d = b // 10 # e = int(a / 10) # f = int(b / 10) # # print(c, d, e, f) # print("time.time(): %f " % time.time()) # print(time.localtime( time.time() )) # print(time.asctime( time.localtime(time.time()) )) # print(int(time.time()) - (int(time.time()) % (3600 * 24)) - 3600 * 8) # a = 1590087600 - (1590087600 + 3600 * 8) % (3600 * 24) # print(a)
25.346821
102
0.598176
700
4,385
3.712857
0.211429
0.009234
0.013851
0.025394
0.220854
0.128511
0.103886
0.085417
0.0808
0.0808
0
0.082571
0.152109
4,385
172
103
25.494186
0.61646
0.893501
0
0.666667
0
0
0
0
0
0
0
0
0
1
0
true
0
1
0
1
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
1
0
1
0
0
4
1609688a059214449baf1c6d58a7f1bebf9308dc
115
py
Python
codes_auto/236.lowest-common-ancestor-of-a-binary-tree.py
smartmark-pro/leetcode_record
6504b733d892a705571eb4eac836fb10e94e56db
[ "MIT" ]
null
null
null
codes_auto/236.lowest-common-ancestor-of-a-binary-tree.py
smartmark-pro/leetcode_record
6504b733d892a705571eb4eac836fb10e94e56db
[ "MIT" ]
null
null
null
codes_auto/236.lowest-common-ancestor-of-a-binary-tree.py
smartmark-pro/leetcode_record
6504b733d892a705571eb4eac836fb10e94e56db
[ "MIT" ]
null
null
null
# # @lc app=leetcode.cn id=236 lang=python3 # # [236] lowest-common-ancestor-of-a-binary-tree # None # @lc code=end
16.428571
47
0.695652
20
115
4
0.9
0
0
0
0
0
0
0
0
0
0
0.069307
0.121739
115
7
48
16.428571
0.722772
0.852174
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0
0
0
0
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
1
0
0
0
0
0
0
null
0
0
0
0
0
0
1
0
0
0
0
0
0
4
16341fb5d4f7a950444769b200c6c317044cae6d
438,209
py
Python
Lib/test/test_compiler/test_static.py
BMariscal/cinder
6495673a16af5e90acc6098ee4cce5972d113322
[ "CNRI-Python-GPL-Compatible" ]
1
2021-11-04T07:39:43.000Z
2021-11-04T07:39:43.000Z
Lib/test/test_compiler/test_static.py
BMariscal/cinder
6495673a16af5e90acc6098ee4cce5972d113322
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
Lib/test/test_compiler/test_static.py
BMariscal/cinder
6495673a16af5e90acc6098ee4cce5972d113322
[ "CNRI-Python-GPL-Compatible" ]
null
null
null
import ast import asyncio import dis import gc import inspect import itertools import re import string import sys import unittest import warnings from array import array from collections import UserDict from compiler import consts, walk from compiler.consts38 import CO_NO_FRAME, CO_TINY_FRAME, CO_STATICALLY_COMPILED from compiler.optimizer import AstOptimizer from compiler.pycodegen import PythonCodeGenerator, make_compiler from compiler.static import ( prim_name_to_type, BOOL_TYPE, BYTES_TYPE, COMPLEX_EXACT_TYPE, Class, Object, DICT_TYPE, DYNAMIC, FLOAT_TYPE, INT_TYPE, LIST_EXACT_TYPE, LIST_TYPE, NONE_TYPE, OBJECT_TYPE, PRIM_OP_ADD_INT, PRIM_OP_DIV_INT, PRIM_OP_GT_INT, PRIM_OP_LT_INT, STR_EXACT_TYPE, STR_TYPE, DeclarationVisitor, Function, StaticCodeGenerator, SymbolTable, TypeBinder, TypedSyntaxError, Value, TUPLE_EXACT_TYPE, TUPLE_TYPE, INT_EXACT_TYPE, FLOAT_EXACT_TYPE, SET_EXACT_TYPE, ELLIPSIS_TYPE, FAST_LEN_ARRAY, FAST_LEN_LIST, FAST_LEN_TUPLE, FAST_LEN_INEXACT, FAST_LEN_DICT, FAST_LEN_SET, SEQ_ARRAY_INT8, SEQ_ARRAY_INT16, SEQ_ARRAY_INT32, SEQ_ARRAY_INT64, SEQ_ARRAY_UINT8, SEQ_ARRAY_UINT16, SEQ_ARRAY_UINT32, SEQ_ARRAY_UINT64, SEQ_LIST, SEQ_LIST_INEXACT, SEQ_TUPLE, SEQ_REPEAT_INEXACT_SEQ, SEQ_REPEAT_INEXACT_NUM, SEQ_REPEAT_PRIMITIVE_NUM, SEQ_REPEAT_REVERSED, SEQ_SUBSCR_UNCHECKED, TYPED_BOOL, TYPED_INT8, TYPED_INT16, TYPED_INT32, TYPED_INT64, TYPED_UINT8, TYPED_UINT16, TYPED_UINT32, TYPED_UINT64, FAST_LEN_STR, DICT_EXACT_TYPE, TYPED_DOUBLE, ) from compiler.symbols import SymbolVisitor from contextlib import contextmanager from copy import deepcopy from io import StringIO from os import path from test.support import maybe_get_event_loop_policy from textwrap import dedent from types import CodeType, MemberDescriptorType, ModuleType from typing import Generic, Optional, Tuple, TypeVar from unittest import TestCase, skip, skipIf from unittest.mock import Mock, patch import cinder import xxclassloader from __static__ import ( Array, Vector, chkdict, int32, int64, int8, make_generic_type, StaticGeneric, is_type_static, ) from cinder import StrictModule from .common import CompilerTest IS_MULTITHREADED_COMPILE_TEST = False try: import cinderjit IS_MULTITHREADED_COMPILE_TEST = cinderjit.is_test_multithreaded_compile_enabled() except ImportError: cinderjit = None RICHARDS_PATH = path.join( path.dirname(__file__), "..", "..", "..", "Tools", "benchmarks", "richards_static.py", ) PRIM_NAME_TO_TYPE = { "cbool": TYPED_BOOL, "int8": TYPED_INT8, "int16": TYPED_INT16, "int32": TYPED_INT32, "int64": TYPED_INT64, "uint8": TYPED_UINT8, "uint16": TYPED_UINT16, "uint32": TYPED_UINT32, "uint64": TYPED_UINT64, } def type_mismatch(from_type: str, to_type: str) -> str: return re.escape(f"type mismatch: {from_type} cannot be assigned to {to_type}") def optional(type: str) -> str: return f"Optional[{type}]" def init_xxclassloader(): codestr = """ from typing import Generic, TypeVar, _tp_cache from __static__.compiler_flags import nonchecked_dicts # Setup a test for typing T = TypeVar('T') U = TypeVar('U') class XXGeneric(Generic[T, U]): d = {} def foo(self, t: T, u: U) -> str: return str(t) + str(u) @classmethod def __class_getitem__(cls, elem_type): if elem_type in XXGeneric.d: return XXGeneric.d[elem_type] XXGeneric.d[elem_type] = type( f"XXGeneric[{elem_type[0].__name__}, {elem_type[1].__name__}]", (object, ), { "foo": XXGeneric.foo, "__slots__":(), } ) return XXGeneric.d[elem_type] """ code = make_compiler( inspect.cleandoc(codestr), "", "exec", generator=StaticCodeGenerator, modname="xxclassloader", ).getCode() d = {} exec(code, d, d) xxclassloader.XXGeneric = d["XXGeneric"] class StaticTestBase(CompilerTest): def compile( self, code, generator=StaticCodeGenerator, modname="<module>", optimize=0, peephole_enabled=True, ast_optimizer_enabled=True, ): if ( not peephole_enabled or not ast_optimizer_enabled or generator is not StaticCodeGenerator ): return super().compile( code, generator, modname, optimize, peephole_enabled, ast_optimizer_enabled, ) symtable = SymbolTable() code = inspect.cleandoc("\n" + code) tree = ast.parse(code) return symtable.compile(modname, f"{modname}.py", tree, optimize) def type_error(self, code, pattern): with self.assertRaisesRegex(TypedSyntaxError, pattern): self.compile(code) _temp_mod_num = 0 def _temp_mod_name(self): StaticTestBase._temp_mod_num += 1 return sys._getframe().f_back.f_back.f_back.f_code.co_name + str( StaticTestBase._temp_mod_num ) @contextmanager def in_module(self, code, name=None, code_gen=StaticCodeGenerator, optimize=0): if name is None: name = self._temp_mod_name() try: compiled = self.compile(code, code_gen, name, optimize) m = type(sys)(name) d = m.__dict__ sys.modules[name] = m exec(compiled, d) d["__name__"] = name yield d finally: if not IS_MULTITHREADED_COMPILE_TEST: # don't throw a new exception if we failed to compile if name in sys.modules: del sys.modules[name] d.clear() gc.collect() @contextmanager def in_strict_module( self, code, name=None, code_gen=StaticCodeGenerator, optimize=0, enable_patching=False, ): if name is None: name = self._temp_mod_name() try: compiled = self.compile(code, code_gen, name, optimize) d = {"__name__": name} m = StrictModule(d, enable_patching) sys.modules[name] = m exec(compiled, d) yield m finally: if not IS_MULTITHREADED_COMPILE_TEST: # don't throw a new exception if we failed to compile if name in sys.modules: del sys.modules[name] d.clear() gc.collect() def run_code(self, code, generator=None, modname=None, peephole_enabled=True): if modname is None: modname = self._temp_mod_name() d = super().run_code(code, generator, modname, peephole_enabled) if IS_MULTITHREADED_COMPILE_TEST: sys.modules[modname] = d return d @property def base_size(self): class C: __slots__ = () return sys.getsizeof(C()) @property def ptr_size(self): return 8 if sys.maxsize > 2 ** 32 else 4 def assert_jitted(self, func): if cinderjit is None: return self.assertTrue(cinderjit.is_jit_compiled(func), func.__name__) def assert_not_jitted(self, func): if cinderjit is None: return self.assertFalse(cinderjit.is_jit_compiled(func)) def assert_not_jitted(self, func): if cinderjit is None: return self.assertFalse(cinderjit.is_jit_compiled(func)) def setUp(self): # ensure clean classloader/vtable slate for all tests cinder.clear_classloader_caches() # ensure our async tests don't change the event loop policy policy = maybe_get_event_loop_policy() self.addCleanup(lambda: asyncio.set_event_loop_policy(policy)) def subTest(self, **kwargs): cinder.clear_classloader_caches() return super().subTest(**kwargs) def make_async_func_hot(self, func): async def make_hot(): for i in range(50): await func() asyncio.run(make_hot()) class StaticCompilationTests(StaticTestBase): @classmethod def setUpClass(cls): init_xxclassloader() @classmethod def tearDownClass(cls): if not IS_MULTITHREADED_COMPILE_TEST: del xxclassloader.XXGeneric def test_static_import_unknown(self) -> None: codestr = """ from __static__ import does_not_exist """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_static_import_star(self) -> None: codestr = """ from __static__ import * """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_reveal_type(self) -> None: codestr = """ def f(x: int): reveal_type(x or None) """ with self.assertRaisesRegex( TypedSyntaxError, r"reveal_type\(x or None\): 'Optional\[int\]'", ): self.compile(codestr) def test_reveal_type_local(self) -> None: codestr = """ def f(x: int | None): if x is not None: reveal_type(x) """ with self.assertRaisesRegex( TypedSyntaxError, r"reveal_type\(x\): 'int', 'x' has declared type 'Optional\[int\]' and local type 'int'", ): self.compile(codestr) def test_redefine_local_type(self) -> None: codestr = """ class C: pass class D: pass def f(): x: C = C() x: D = D() """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_mixed_chain_assign(self) -> None: codestr = """ class C: pass class D: pass def f(): x: C = C() y: D = D() x = y = D() """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("foo.D", "foo.C")): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_bool_cast(self) -> None: codestr = """ from __static__ import cast class D: pass def f(x) -> bool: y: bool = cast(bool, x) return y """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_typing_overload(self) -> None: """Typing overloads are ignored, don't cause member name conflict.""" codestr = """ from typing import Optional, overload class C: @overload def foo(self, x: int) -> int: ... def foo(self, x: Optional[int]) -> Optional[int]: return x def f(x: int) -> Optional[int]: return C().foo(x) """ self.assertReturns(codestr, "Optional[int]") def test_mixed_binop(self): with self.assertRaisesRegex( TypedSyntaxError, "cannot add int64 and Exact\\[int\\]" ): self.bind_module( """ from __static__ import ssize_t def f(): x: ssize_t = 1 y = 1 x + y """ ) with self.assertRaisesRegex( TypedSyntaxError, "cannot add Exact\\[int\\] and int64" ): self.bind_module( """ from __static__ import ssize_t def f(): x: ssize_t = 1 y = 1 y + x """ ) def test_mixed_binop_okay(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 1 y = x + 1 return box(y) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(), 2) def test_mixed_binop_okay_1(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 1 y = 1 + x return box(y) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(), 2) def test_inferred_primitive_type(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 1 y = x return box(y) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(), 1) @skipIf(cinderjit is None, "not jitting") def test_tiny_frame(self): codestr = """ from __static__.compiler_flags import tinyframe import sys def f(): return 123 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertTrue(f.__code__.co_flags & CO_TINY_FRAME) self.assertEqual(f(), 123) self.assert_jitted(f) def test_deep_attr_chain(self): """this shouldn't explode exponentially""" codestr = """ def f(x): return x.x.x.x.x.x.x """ class C: def __init__(self): self.x = self orig_bind_attr = Object.bind_attr call_count = 0 def bind_attr(*args): nonlocal call_count call_count += 1 return orig_bind_attr(*args) with patch("compiler.static.Object.bind_attr", bind_attr): with self.in_module(codestr) as mod: f = mod["f"] x = C() self.assertEqual(f(x), x) # Initially this would be 63 when we were double visiting self.assertLess(call_count, 10) @skipIf(cinderjit is None, "not jitting") def test_no_frame(self): codestr = """ from __static__.compiler_flags import noframe def f(): return 456 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertTrue(f.__code__.co_flags & CO_NO_FRAME) self.assertEqual(f(), 456) self.assert_jitted(f) @skipIf(cinderjit is None, "not jitting") def test_no_frame_generator(self): codestr = """ from __static__.compiler_flags import noframe def g(): for i in range(10): yield i def f(): return list(g()) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertTrue(f.__code__.co_flags & CO_NO_FRAME) self.assertEqual(f(), list(range(10))) self.assert_jitted(f) @skipIf(cinderjit is None, "not jitting") def test_tiny_frame_generator(self): codestr = """ from __static__.compiler_flags import tinyframe def g(): for i in range(10): yield i def f(): return list(g()) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertTrue(f.__code__.co_flags & CO_TINY_FRAME) self.assertEqual(f(), list(range(10))) self.assert_jitted(f) def test_subclass_binop(self): codestr = """ class C: pass class D(C): pass def f(x: C, y: D): return x + y """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "f") self.assertInBytecode(f, "BINARY_ADD") def test_exact_invoke_function(self): codestr = """ def f() -> str: return ", ".join(['1','2','3']) """ f = self.find_code(self.compile(codestr)) with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode( f, "INVOKE_FUNCTION", (("builtins", "str", "join"), 2) ) f() def test_multiply_list_exact_by_int(self): codestr = """ def f() -> int: l = [1, 2, 3] * 2 return len(l) """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), 6) def test_multiply_list_exact_by_int_reverse(self): codestr = """ def f() -> int: l = 2 * [1, 2, 3] return len(l) """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), 6) def test_int_bad_assign(self): with self.assertRaisesRegex( TypedSyntaxError, "str cannot be used in a context where an int is expected" ): code = self.compile( """ from __static__ import ssize_t def f(): x: ssize_t = 'abc' """, StaticCodeGenerator, ) def test_sign_extend(self): codestr = f""" from __static__ import int16, int64, box def testfunc(): x: int16 = -40 y: int64 = x return box(y) """ code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), -40) def test_field_size(self): for type in [ "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", ]: codestr = f""" from __static__ import {type}, box class C{type}: def __init__(self): self.a: {type} = 1 self.b: {type} = 1 def testfunc(c: C{type}): c.a = 2 c.b = 3 return box(c.a + c.b) """ with self.subTest(type=type): with self.in_module(codestr) as mod: C = mod["C" + type] f = mod["testfunc"] self.assertEqual(f(C()), 5) def test_field_sign_ext(self): """tests that we do the correct sign extension when loading from a field""" for type, val in [ ("int32", 65537), ("int16", 256), ("int8", 0x7F), ("uint32", 65537), ]: codestr = f""" from __static__ import {type}, box class C{type}: def __init__(self): self.value: {type} = {val} def testfunc(c: C{type}): return box(c.value) """ with self.subTest(type=type, val=val): with self.in_module(codestr) as mod: C = mod["C" + type] f = mod["testfunc"] self.assertEqual(f(C()), val) def test_field_unsign_ext(self): """tests that we do the correct sign extension when loading from a field""" for type, val, test in [("uint32", 65537, -1)]: codestr = f""" from __static__ import {type}, int64, box class C{type}: def __init__(self): self.value: {type} = {val} def testfunc(c: C{type}): z: int64 = {test} if c.value < z: return True return False """ with self.subTest(type=type, val=val, test=test): with self.in_module(codestr) as mod: C = mod["C" + type] f = mod["testfunc"] self.assertEqual(f(C()), False) def test_field_sign_compare(self): for type, val, test in [("int32", -1, -1)]: codestr = f""" from __static__ import {type}, box class C{type}: def __init__(self): self.value: {type} = {val} def testfunc(c: C{type}): if c.value == {test}: return True return False """ with self.subTest(type=type, val=val, test=test): with self.in_module(codestr) as mod: C = mod["C" + type] f = mod["testfunc"] self.assertTrue(f(C())) def test_mixed_binop_sign(self): """mixed signed/unsigned ops should be promoted to signed""" codestr = """ from __static__ import int8, uint8, box def testfunc(): x: uint8 = 42 y: int8 = 2 return box(x / y) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_DIV_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), 21) codestr = """ from __static__ import int8, uint8, box def testfunc(): x: int8 = 42 y: uint8 = 2 return box(x / y) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_DIV_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), 21) def test_mixed_cmpop_sign(self): """mixed signed/unsigned ops should be promoted to signed""" codestr = """ from __static__ import int8, uint8, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 if tst: x += 1 y += 1 if x < y: return True return False """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "INT_COMPARE_OP", PRIM_OP_LT_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), False) codestr = """ from __static__ import int8, uint8, box def testfunc(tst=False): x: int8 = 42 y: uint8 = 2 if tst: x += 1 y += 1 if x < y: return True return False """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "INT_COMPARE_OP", PRIM_OP_LT_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), False) def test_mixed_add_reversed(self): codestr = """ from __static__ import int8, uint8, int64, box, int16 def testfunc(tst=False): x: int8 = 42 y: int16 = 2 if tst: x += 1 y += 1 return box(y + x) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), 44) def test_mixed_tri_add(self): codestr = """ from __static__ import int8, uint8, int64, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 z: int64 = 3 if tst: x += 1 y += 1 return box(x + y + z) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), 47) def test_mixed_tri_add_unsigned(self): """promote int/uint to int, can't add to uint64""" codestr = """ from __static__ import int8, uint8, uint64, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 z: uint64 = 3 return box(x + y + z) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot add int16 and uint64"): self.compile(codestr, StaticCodeGenerator) def test_store_signed_to_unsigned(self): codestr = """ from __static__ import int8, uint8, uint64, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 x = y """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("int8", "uint8")): self.compile(codestr, StaticCodeGenerator) def test_store_unsigned_to_signed(self): """promote int/uint to int, can't add to uint64""" codestr = """ from __static__ import int8, uint8, uint64, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 y = x """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("uint8", "int8")): self.compile(codestr, StaticCodeGenerator) def test_mixed_assign_larger(self): """promote int/uint to int16""" codestr = """ from __static__ import int8, uint8, int16, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 z: int16 = x + y return box(z) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), 44) def test_mixed_assign_larger_2(self): """promote int/uint to int16""" codestr = """ from __static__ import int8, uint8, int16, box def testfunc(tst=False): x: uint8 = 42 y: int8 = 2 z: int16 z = x + y return box(z) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(), 44) @skipIf(True, "this isn't implemented yet") def test_unwind(self): codestr = f""" from __static__ import int32 def raises(): raise IndexError() def testfunc(): x: int32 = 1 raises() print(x) """ with self.in_module(codestr) as mod: f = mod["testfunc"] with self.assertRaises(IndexError): f() def test_int_constant_range(self): for type, val, low, high in [ ("int8", 128, -128, 127), ("int8", -129, -128, 127), ("int16", 32768, -32768, 32767), ("int16", -32769, -32768, 32767), ("int32", 2147483648, -2147483648, 2147483647), ("int32", -2147483649, -2147483648, 2147483647), ("int64", 9223372036854775808, -9223372036854775808, 9223372036854775807), ("int64", -9223372036854775809, -9223372036854775808, 9223372036854775807), ("uint8", 257, 0, 255), ("uint8", -1, 0, 255), ("uint16", 65537, 0, 65535), ("uint16", -1, 0, 65535), ("uint32", 4294967297, 0, 4294967295), ("uint32", -1, 0, 4294967295), ("uint64", 18446744073709551617, 0, 18446744073709551615), ("uint64", -1, 0, 18446744073709551615), ]: codestr = f""" from __static__ import {type} def testfunc(tst): x: {type} = {val} """ with self.subTest(type=type, val=val, low=low, high=high): with self.assertRaisesRegex( TypedSyntaxError, f"constant {val} is outside of the range {low} to {high} for {type}", ): self.compile(codestr, StaticCodeGenerator) def test_int_assign_float(self): codestr = """ from __static__ import int8 def testfunc(tst): x: int8 = 1.0 """ with self.assertRaisesRegex( TypedSyntaxError, f"float cannot be used in a context where an int is expected", ): self.compile(codestr, StaticCodeGenerator) def test_int_assign_str_constant(self): codestr = """ from __static__ import int8 def testfunc(tst): x: int8 = 'abc' + 'def' """ with self.assertRaisesRegex( TypedSyntaxError, f"str cannot be used in a context where an int is expected", ): self.compile(codestr, StaticCodeGenerator) def test_int_large_int_constant(self): codestr = """ from __static__ import int64 def testfunc(tst): x: int64 = 0x7FFFFFFF + 1 """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (0x80000000, TYPED_INT64)) def test_int_int_constant(self): codestr = """ from __static__ import int64 def testfunc(tst): x: int64 = 0x7FFFFFFE + 1 """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (0x7FFFFFFF, TYPED_INT64)) def test_int_add_mixed_64(self): codestr = """ from __static__ import uint64, int64, box def testfunc(tst): x: uint64 = 0 y: int64 = 1 if tst: x = x + 1 y = y + 2 return box(x + y) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot add uint64 and int64"): self.compile(codestr, StaticCodeGenerator) def test_int_overflow_add(self): tests = [ ("int8", 100, 100, -56), ("int16", 200, 200, 400), ("int32", 200, 200, 400), ("int64", 200, 200, 400), ("int16", 20000, 20000, -25536), ("int32", 40000, 40000, 80000), ("int64", 40000, 40000, 80000), ("int32", 2000000000, 2000000000, -294967296), ("int64", 2000000000, 2000000000, 4000000000), ("int8", 127, 127, -2), ("int16", 32767, 32767, -2), ("int32", 2147483647, 2147483647, -2), ("int64", 9223372036854775807, 9223372036854775807, -2), ("uint8", 200, 200, 144), ("uint16", 200, 200, 400), ("uint32", 200, 200, 400), ("uint64", 200, 200, 400), ("uint16", 40000, 40000, 14464), ("uint32", 40000, 40000, 80000), ("uint64", 40000, 40000, 80000), ("uint32", 2000000000, 2000000000, 4000000000), ("uint64", 2000000000, 2000000000, 4000000000), ("uint8", 1 << 7, 1 << 7, 0), ("uint16", 1 << 15, 1 << 15, 0), ("uint32", 1 << 31, 1 << 31, 0), ("uint64", 1 << 63, 1 << 63, 0), ("uint8", 1 << 6, 1 << 6, 128), ("uint16", 1 << 14, 1 << 14, 32768), ("uint32", 1 << 30, 1 << 30, 2147483648), ("uint64", 1 << 62, 1 << 62, 9223372036854775808), ] for type, x, y, res in tests: codestr = f""" from __static__ import {type}, box def f(): x: {type} = {x} y: {type} = {y} z: {type} = x + y return box(z) """ with self.subTest(type=type, x=x, y=y, res=res): code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(), res, f"{type} {x} {y} {res}") def test_int_unary(self): tests = [ ("int8", "-", 1, -1), ("uint8", "-", 1, (1 << 8) - 1), ("int16", "-", 1, -1), ("int16", "-", 256, -256), ("uint16", "-", 1, (1 << 16) - 1), ("int32", "-", 1, -1), ("int32", "-", 65536, -65536), ("uint32", "-", 1, (1 << 32) - 1), ("int64", "-", 1, -1), ("int64", "-", 1 << 32, -(1 << 32)), ("uint64", "-", 1, (1 << 64) - 1), ("int8", "~", 1, -2), ("uint8", "~", 1, (1 << 8) - 2), ("int16", "~", 1, -2), ("uint16", "~", 1, (1 << 16) - 2), ("int32", "~", 1, -2), ("uint32", "~", 1, (1 << 32) - 2), ("int64", "~", 1, -2), ("uint64", "~", 1, (1 << 64) - 2), ] for type, op, x, res in tests: codestr = f""" from __static__ import {type}, box def testfunc(tst): x: {type} = {x} if tst: x = x + 1 x = {op}x return box(x) """ with self.subTest(type=type, op=op, x=x, res=res): code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(False), res, f"{type} {op} {x} {res}") def test_int_compare(self): tests = [ ("int8", 1, 2, "==", False), ("int8", 1, 2, "!=", True), ("int8", 1, 2, "<", True), ("int8", 1, 2, "<=", True), ("int8", 2, 1, "<", False), ("int8", 2, 1, "<=", False), ("int8", -1, 2, "==", False), ("int8", -1, 2, "!=", True), ("int8", -1, 2, "<", True), ("int8", -1, 2, "<=", True), ("int8", 2, -1, "<", False), ("int8", 2, -1, "<=", False), ("uint8", 1, 2, "==", False), ("uint8", 1, 2, "!=", True), ("uint8", 1, 2, "<", True), ("uint8", 1, 2, "<=", True), ("uint8", 2, 1, "<", False), ("uint8", 2, 1, "<=", False), ("uint8", 255, 2, "==", False), ("uint8", 255, 2, "!=", True), ("uint8", 255, 2, "<", False), ("uint8", 255, 2, "<=", False), ("uint8", 2, 255, "<", True), ("uint8", 2, 255, "<=", True), ("int16", 1, 2, "==", False), ("int16", 1, 2, "!=", True), ("int16", 1, 2, "<", True), ("int16", 1, 2, "<=", True), ("int16", 2, 1, "<", False), ("int16", 2, 1, "<=", False), ("int16", -1, 2, "==", False), ("int16", -1, 2, "!=", True), ("int16", -1, 2, "<", True), ("int16", -1, 2, "<=", True), ("int16", 2, -1, "<", False), ("int16", 2, -1, "<=", False), ("uint16", 1, 2, "==", False), ("uint16", 1, 2, "!=", True), ("uint16", 1, 2, "<", True), ("uint16", 1, 2, "<=", True), ("uint16", 2, 1, "<", False), ("uint16", 2, 1, "<=", False), ("uint16", 65535, 2, "==", False), ("uint16", 65535, 2, "!=", True), ("uint16", 65535, 2, "<", False), ("uint16", 65535, 2, "<=", False), ("uint16", 2, 65535, "<", True), ("uint16", 2, 65535, "<=", True), ("int32", 1, 2, "==", False), ("int32", 1, 2, "!=", True), ("int32", 1, 2, "<", True), ("int32", 1, 2, "<=", True), ("int32", 2, 1, "<", False), ("int32", 2, 1, "<=", False), ("int32", -1, 2, "==", False), ("int32", -1, 2, "!=", True), ("int32", -1, 2, "<", True), ("int32", -1, 2, "<=", True), ("int32", 2, -1, "<", False), ("int32", 2, -1, "<=", False), ("uint32", 1, 2, "==", False), ("uint32", 1, 2, "!=", True), ("uint32", 1, 2, "<", True), ("uint32", 1, 2, "<=", True), ("uint32", 2, 1, "<", False), ("uint32", 2, 1, "<=", False), ("uint32", 4294967295, 2, "!=", True), ("uint32", 4294967295, 2, "<", False), ("uint32", 4294967295, 2, "<=", False), ("uint32", 2, 4294967295, "<", True), ("uint32", 2, 4294967295, "<=", True), ("int64", 1, 2, "==", False), ("int64", 1, 2, "!=", True), ("int64", 1, 2, "<", True), ("int64", 1, 2, "<=", True), ("int64", 2, 1, "<", False), ("int64", 2, 1, "<=", False), ("int64", -1, 2, "==", False), ("int64", -1, 2, "!=", True), ("int64", -1, 2, "<", True), ("int64", -1, 2, "<=", True), ("int64", 2, -1, "<", False), ("int64", 2, -1, "<=", False), ("uint64", 1, 2, "==", False), ("uint64", 1, 2, "!=", True), ("uint64", 1, 2, "<", True), ("uint64", 1, 2, "<=", True), ("uint64", 2, 1, "<", False), ("uint64", 2, 1, "<=", False), ("int64", 2, -1, ">", True), ("uint64", 2, 18446744073709551615, ">", False), ("int64", 2, -1, "<", False), ("uint64", 2, 18446744073709551615, "<", True), ("int64", 2, -1, ">=", True), ("uint64", 2, 18446744073709551615, ">=", False), ("int64", 2, -1, "<=", False), ("uint64", 2, 18446744073709551615, "<=", True), ] for type, x, y, op, res in tests: codestr = f""" from __static__ import {type}, box def testfunc(tst): x: {type} = {x} y: {type} = {y} if tst: x = x + 1 y = y + 2 if x {op} y: return True return False """ with self.subTest(type=type, x=x, y=y, op=op, res=res): code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(False), res, f"{type} {x} {op} {y} {res}") def test_int_compare_unboxed(self): codestr = f""" from __static__ import ssize_t, unbox def testfunc(x, y): x1: ssize_t = unbox(x) y1: ssize_t = unbox(y) if x1 > y1: return True return False """ code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertInBytecode(f, "POP_JUMP_IF_ZERO") self.assertEqual(f(1, 2), False) def test_int_compare_mixed(self): codestr = """ from __static__ import box, ssize_t x = 1 def testfunc(): i: ssize_t = 0 j = 0 while box(i < 100) and x: i = i + 1 j = j + 1 return j """ code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), 100) self.assert_jitted(f) def test_int_compare_or(self): codestr = """ from __static__ import box, ssize_t def testfunc(): i: ssize_t = 0 j = i > 2 or i < -2 return box(j) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["testfunc"] self.assertInBytecode(f, "JUMP_IF_NONZERO_OR_POP") self.assertIs(f(), False) def test_int_compare_and(self): codestr = """ from __static__ import box, ssize_t def testfunc(): i: ssize_t = 0 j = i > 2 and i > 3 return box(j) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["testfunc"] self.assertInBytecode(f, "JUMP_IF_ZERO_OR_POP") self.assertIs(f(), False) def test_disallow_prim_nonprim_union(self): codestr = """ from __static__ import int32 def f(y: int): x: int32 = 2 z = x or y return z """ with self.assertRaisesRegex( TypedSyntaxError, r"invalid union type Union\[int32, int\]; unions cannot include primitive types", ): self.compile(codestr) def test_int_binop(self): tests = [ ("int8", 1, 2, "/", 0), ("int8", 4, 2, "/", 2), ("int8", 4, -2, "/", -2), ("uint8", 0xFF, 0x7F, "/", 2), ("int16", 4, -2, "/", -2), ("uint16", 0xFF, 0x7F, "/", 2), ("uint32", 0xFFFF, 0x7FFF, "/", 2), ("int32", 4, -2, "/", -2), ("uint32", 0xFF, 0x7F, "/", 2), ("uint32", 0xFFFFFFFF, 0x7FFFFFFF, "/", 2), ("int64", 4, -2, "/", -2), ("uint64", 0xFF, 0x7F, "/", 2), ("uint64", 0xFFFFFFFFFFFFFFFF, 0x7FFFFFFFFFFFFFFF, "/", 2), ("int8", 1, -2, "-", 3), ("int8", 1, 2, "-", -1), ("int16", 1, -2, "-", 3), ("int16", 1, 2, "-", -1), ("int32", 1, -2, "-", 3), ("int32", 1, 2, "-", -1), ("int64", 1, -2, "-", 3), ("int64", 1, 2, "-", -1), ("int8", 1, -2, "*", -2), ("int8", 1, 2, "*", 2), ("int16", 1, -2, "*", -2), ("int16", 1, 2, "*", 2), ("int32", 1, -2, "*", -2), ("int32", 1, 2, "*", 2), ("int64", 1, -2, "*", -2), ("int64", 1, 2, "*", 2), ("int8", 1, -2, "&", 0), ("int8", 1, 3, "&", 1), ("int16", 1, 3, "&", 1), ("int16", 1, 3, "&", 1), ("int32", 1, 3, "&", 1), ("int32", 1, 3, "&", 1), ("int64", 1, 3, "&", 1), ("int64", 1, 3, "&", 1), ("int8", 1, 2, "|", 3), ("uint8", 1, 2, "|", 3), ("int16", 1, 2, "|", 3), ("uint16", 1, 2, "|", 3), ("int32", 1, 2, "|", 3), ("uint32", 1, 2, "|", 3), ("int64", 1, 2, "|", 3), ("uint64", 1, 2, "|", 3), ("int8", 1, 3, "^", 2), ("uint8", 1, 3, "^", 2), ("int16", 1, 3, "^", 2), ("uint16", 1, 3, "^", 2), ("int32", 1, 3, "^", 2), ("uint32", 1, 3, "^", 2), ("int64", 1, 3, "^", 2), ("uint64", 1, 3, "^", 2), ("int8", 1, 3, "%", 1), ("uint8", 1, 3, "%", 1), ("int16", 1, 3, "%", 1), ("uint16", 1, 3, "%", 1), ("int32", 1, 3, "%", 1), ("uint32", 1, 3, "%", 1), ("int64", 1, 3, "%", 1), ("uint64", 1, 3, "%", 1), ("int8", 1, -3, "%", 1), ("uint8", 1, 0xFF, "%", 1), ("int16", 1, -3, "%", 1), ("uint16", 1, 0xFFFF, "%", 1), ("int32", 1, -3, "%", 1), ("uint32", 1, 0xFFFFFFFF, "%", 1), ("int64", 1, -3, "%", 1), ("uint64", 1, 0xFFFFFFFFFFFFFFFF, "%", 1), ("int8", 1, 2, "<<", 4), ("uint8", 1, 2, "<<", 4), ("int16", 1, 2, "<<", 4), ("uint16", 1, 2, "<<", 4), ("int32", 1, 2, "<<", 4), ("uint32", 1, 2, "<<", 4), ("int64", 1, 2, "<<", 4), ("uint64", 1, 2, "<<", 4), ("int8", 4, 1, ">>", 2), ("int8", -1, 1, ">>", -1), ("uint8", 0xFF, 1, ">>", 127), ("int16", 4, 1, ">>", 2), ("int16", -1, 1, ">>", -1), ("uint16", 0xFFFF, 1, ">>", 32767), ("int32", 4, 1, ">>", 2), ("int32", -1, 1, ">>", -1), ("uint32", 0xFFFFFFFF, 1, ">>", 2147483647), ("int64", 4, 1, ">>", 2), ("int64", -1, 1, ">>", -1), ("uint64", 0xFFFFFFFFFFFFFFFF, 1, ">>", 9223372036854775807), ] for type, x, y, op, res in tests: codestr = f""" from __static__ import {type}, box def testfunc(tst): x: {type} = {x} y: {type} = {y} if tst: x = x + 1 y = y + 2 z: {type} = x {op} y return box(z), box(x {op} y) """ with self.subTest(type=type, x=x, y=y, op=op, res=res): with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(False), (res, res), f"{type} {x} {op} {y} {res}") def test_primitive_arithmetic(self): cases = [ ("int8", 127, "*", 1, 127), ("int8", -64, "*", 2, -128), ("int8", 0, "*", 4, 0), ("uint8", 51, "*", 5, 255), ("uint8", 5, "*", 0, 0), ("int16", 3123, "*", -10, -31230), ("int16", -32767, "*", -1, 32767), ("int16", -32768, "*", 1, -32768), ("int16", 3, "*", 0, 0), ("uint16", 65535, "*", 1, 65535), ("uint16", 0, "*", 4, 0), ("int32", (1 << 31) - 1, "*", 1, (1 << 31) - 1), ("int32", -(1 << 30), "*", 2, -(1 << 31)), ("int32", 0, "*", 1, 0), ("uint32", (1 << 32) - 1, "*", 1, (1 << 32) - 1), ("uint32", 0, "*", 4, 0), ("int64", (1 << 63) - 1, "*", 1, (1 << 63) - 1), ("int64", -(1 << 62), "*", 2, -(1 << 63)), ("int64", 0, "*", 1, 0), ("uint64", (1 << 64) - 1, "*", 1, (1 << 64) - 1), ("uint64", 0, "*", 4, 0), ("int8", 127, "//", 4, 31), ("int8", -128, "//", 4, -32), ("int8", 0, "//", 4, 0), ("uint8", 255, "//", 5, 51), ("uint8", 0, "//", 5, 0), ("int16", 32767, "//", -1000, -32), ("int16", -32768, "//", -1000, 32), ("int16", 0, "//", 4, 0), ("uint16", 65535, "//", 5, 13107), ("uint16", 0, "//", 4, 0), ("int32", (1 << 31) - 1, "//", (1 << 31) - 1, 1), ("int32", -(1 << 31), "//", 1, -(1 << 31)), ("int32", 0, "//", 1, 0), ("uint32", (1 << 32) - 1, "//", 500, 8589934), ("uint32", 0, "//", 4, 0), ("int64", (1 << 63) - 1, "//", 2, (1 << 62) - 1), ("int64", -(1 << 63), "//", 2, -(1 << 62)), ("int64", 0, "//", 1, 0), ("uint64", (1 << 64) - 1, "//", (1 << 64) - 1, 1), ("uint64", 0, "//", 4, 0), ("int8", 127, "%", 4, 3), ("int8", -128, "%", 4, 0), ("int8", 0, "%", 4, 0), ("uint8", 255, "%", 6, 3), ("uint8", 0, "%", 5, 0), ("int16", 32767, "%", -1000, 767), ("int16", -32768, "%", -1000, -768), ("int16", 0, "%", 4, 0), ("uint16", 65535, "%", 7, 1), ("uint16", 0, "%", 4, 0), ("int32", (1 << 31) - 1, "%", (1 << 31) - 1, 0), ("int32", -(1 << 31), "%", 1, 0), ("int32", 0, "%", 1, 0), ("uint32", (1 << 32) - 1, "%", 500, 295), ("uint32", 0, "%", 4, 0), ("int64", (1 << 63) - 1, "%", 2, 1), ("int64", -(1 << 63), "%", 2, 0), ("int64", 0, "%", 1, 0), ("uint64", (1 << 64) - 1, "%", (1 << 64) - 1, 0), ("uint64", 0, "%", 4, 0), ] for typ, a, op, b, res in cases: for const in ["noconst", "constfirst", "constsecond"]: if const == "noconst": codestr = f""" from __static__ import {typ} def f(a: {typ}, b: {typ}) -> {typ}: return a {op} b """ elif const == "constfirst": codestr = f""" from __static__ import {typ} def f(b: {typ}) -> {typ}: return {a} {op} b """ elif const == "constsecond": codestr = f""" from __static__ import {typ} def f(a: {typ}) -> {typ}: return a {op} {b} """ with self.subTest(typ=typ, a=a, op=op, b=b, res=res, const=const): with self.in_module(codestr) as mod: f = mod["f"] act = None if const == "noconst": act = f(a, b) elif const == "constfirst": act = f(b) elif const == "constsecond": act = f(a) self.assertEqual(act, res) def test_int_binop_type_context(self): codestr = f""" from __static__ import box, int8, int16 def f(x: int8, y: int8) -> int: z: int16 = x * y return box(z) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode( f, "CONVERT_PRIMITIVE", TYPED_INT8 | (TYPED_INT16 << 4) ) self.assertEqual(f(120, 120), 14400) def test_int_compare_mixed_sign(self): tests = [ ("uint16", 10000, "int16", -1, "<", False), ("uint16", 10000, "int16", -1, "<=", False), ("int16", -1, "uint16", 10000, ">", False), ("int16", -1, "uint16", 10000, ">=", False), ("uint32", 10000, "int16", -1, "<", False), ] for type1, x, type2, y, op, res in tests: codestr = f""" from __static__ import {type1}, {type2}, box def testfunc(tst): x: {type1} = {x} y: {type2} = {y} if tst: x = x + 1 y = y + 2 if x {op} y: return True return False """ with self.subTest(type1=type1, x=x, type2=type2, y=y, op=op, res=res): code = self.compile(codestr, StaticCodeGenerator) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(False), res, f"{type} {x} {op} {y} {res}") def test_int_compare64_mixed_sign(self): codestr = """ from __static__ import uint64, int64 def testfunc(tst): x: uint64 = 0 y: int64 = 1 if tst: x = x + 1 y = y + 2 if x < y: return True return False """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator) def test_compile_method(self): code = self.compile( """ from __static__ import ssize_t def f(): x: ssize_t = 42 """, StaticCodeGenerator, ) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (42, TYPED_INT64)) def test_mixed_compare(self): codestr = """ from __static__ import ssize_t, box, unbox def f(a): x: ssize_t = 0 while x != a: pass """ with self.assertRaisesRegex(TypedSyntaxError, "can't compare int64 to dynamic"): self.compile(codestr, StaticCodeGenerator) def test_unbox(self): for size, val in [ ("int8", 126), ("int8", -128), ("int16", 32766), ("int16", -32768), ("int32", 2147483646), ("int32", -2147483648), ("int64", 9223372036854775806), ("int64", -9223372036854775808), ("uint8", 254), ("uint16", 65534), ("uint32", 4294967294), ("uint64", 18446744073709551614), ]: codestr = f""" from __static__ import {size}, box, unbox def f(x): y: {size} = unbox(x) y = y + 1 return box(y) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(val), val + 1) def test_int_loop_inplace(self): codestr = """ from __static__ import ssize_t, box def f(): i: ssize_t = 0 while i < 100: i += 1 return box(i) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(), 100) def test_int_loop(self): codestr = """ from __static__ import ssize_t, box def testfunc(): i: ssize_t = 0 while i < 100: i = i + 1 return box(i) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), 100) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (0, TYPED_INT64)) self.assertInBytecode(f, "LOAD_LOCAL", (0, ("__static__", "int64"))) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) self.assertInBytecode(f, "INT_COMPARE_OP", PRIM_OP_LT_INT) self.assertInBytecode(f, "POP_JUMP_IF_ZERO") def test_int_assert(self): codestr = """ from __static__ import ssize_t, box def testfunc(): i: ssize_t = 0 assert i == 0, "hello there" """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "POP_JUMP_IF_NONZERO") f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), None) def test_int_assert_raises(self): codestr = """ from __static__ import ssize_t, box def testfunc(): i: ssize_t = 0 assert i != 0, "hello there" """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "POP_JUMP_IF_NONZERO") with self.assertRaises(AssertionError): f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), None) def test_int_loop_reversed(self): codestr = """ from __static__ import ssize_t, box def testfunc(): i: ssize_t = 0 while 100 > i: i = i + 1 return box(i) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), 100) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (0, TYPED_INT64)) self.assertInBytecode(f, "LOAD_LOCAL", (0, ("__static__", "int64"))) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) self.assertInBytecode(f, "INT_COMPARE_OP", PRIM_OP_GT_INT) self.assertInBytecode(f, "POP_JUMP_IF_ZERO") def test_int_loop_chained(self): codestr = """ from __static__ import ssize_t, box def testfunc(): i: ssize_t = 0 while -1 < i < 100: i = i + 1 return box(i) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(), 100) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (0, TYPED_INT64)) self.assertInBytecode(f, "LOAD_LOCAL", (0, ("__static__", "int64"))) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) self.assertInBytecode(f, "INT_COMPARE_OP", PRIM_OP_LT_INT) self.assertInBytecode(f, "POP_JUMP_IF_ZERO") def test_compare_subclass(self): codestr = """ class C: pass class D(C): pass x = C() > D() """ code = self.compile(codestr, StaticCodeGenerator) self.assertInBytecode(code, "COMPARE_OP") def test_compat_int_math(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 42 z: ssize_t = 1 + x return box(z) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (42, TYPED_INT64)) self.assertInBytecode(f, "LOAD_LOCAL", (0, ("__static__", "int64"))) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(), 43) def test_unbox_long(self): codestr = """ from __static__ import unbox, int64 def f(): x:int64 = unbox(1) """ self.compile(codestr, StaticCodeGenerator) def test_unbox_str(self): codestr = """ from __static__ import unbox, int64 def f(): x:int64 = unbox('abc') """ with self.in_module(codestr) as mod: f = mod["f"] with self.assertRaisesRegex( TypeError, "(expected int, got str)|(an integer is required)" ): f() def test_unbox_typed(self): codestr = """ from __static__ import int64, box def f(i: object): x = int64(i) return box(x) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(42), 42) self.assertInBytecode(f, "PRIMITIVE_UNBOX") with self.assertRaisesRegex( TypeError, "(expected int, got str)|(an integer is required)" ): self.assertEqual(f("abc"), 42) def test_unbox_typed_bool(self): codestr = """ from __static__ import int64, box def f(i: object): x = int64(i) return box(x) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(42), 42) self.assertInBytecode(f, "PRIMITIVE_UNBOX") self.assertEqual(f(True), 1) self.assertEqual(f(False), 0) def test_unbox_incompat_type(self): codestr = """ from __static__ import int64, box def f(i: str): x:int64 = int64(i) return box(x) """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("str", "int64")): self.compile(codestr) def test_uninit_value(self): codestr = """ from __static__ import box, int64 def f(): x:int64 return box(x) x = 0 """ f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(), 0) def test_uninit_value_2(self): codestr = """ from __static__ import box, int64 def testfunc(x): if x: y:int64 = 42 return box(y) """ f = self.run_code(codestr, StaticCodeGenerator)["testfunc"] self.assertEqual(f(False), 0) def test_bad_box(self): codestr = """ from __static__ import box box('abc') """ with self.assertRaisesRegex( TypedSyntaxError, "can't box non-primitive: Exact\\[str\\]" ): self.compile(codestr, StaticCodeGenerator) def test_bad_unbox(self): codestr = """ from __static__ import unbox, int64 def f(): x:int64 = 42 unbox(x) """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("int64", "dynamic") ): self.compile(codestr, StaticCodeGenerator) def test_bad_box_2(self): codestr = """ from __static__ import box box('abc', 'foo') """ with self.assertRaisesRegex( TypedSyntaxError, "box only accepts a single argument" ): self.compile(codestr, StaticCodeGenerator) def test_bad_unbox_2(self): codestr = """ from __static__ import unbox, int64 def f(): x:int64 = 42 unbox(x, y) """ with self.assertRaisesRegex( TypedSyntaxError, "unbox only accepts a single argument" ): self.compile(codestr, StaticCodeGenerator) def test_int_reassign(self): codestr = """ from __static__ import ssize_t, box def f(): x: ssize_t = 42 z: ssize_t = 1 + x x = 100 x = x + x return box(z) """ code = self.compile(codestr, StaticCodeGenerator) f = self.find_code(code) self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (42, TYPED_INT64)) self.assertInBytecode(f, "LOAD_LOCAL", (0, ("__static__", "int64"))) self.assertInBytecode(f, "PRIMITIVE_BINARY_OP", PRIM_OP_ADD_INT) f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(), 43) def test_assign_to_object(self): codestr = """ def f(): x: object x = None x = 1 x = 'abc' x = [] x = {} x = {1, 2} x = () x = 1.0 x = 1j x = b'foo' x = int x = True x = NotImplemented x = ... """ self.compile(codestr, StaticCodeGenerator) def test_global_call_add(self) -> None: codestr = """ X = ord(42) def f(): y = X + 1 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_type_binder(self) -> None: self.assertEqual(self.bind_expr("42"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("42.0"), FLOAT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("'abc'"), STR_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("b'abc'"), BYTES_TYPE.instance) self.assertEqual(self.bind_expr("3j"), COMPLEX_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("None"), NONE_TYPE.instance) self.assertEqual(self.bind_expr("True"), BOOL_TYPE.instance) self.assertEqual(self.bind_expr("False"), BOOL_TYPE.instance) self.assertEqual(self.bind_expr("..."), ELLIPSIS_TYPE.instance) self.assertEqual(self.bind_expr("f''"), STR_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("f'{x}'"), STR_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("a"), DYNAMIC) self.assertEqual(self.bind_expr("a.b"), DYNAMIC) self.assertEqual(self.bind_expr("a + b"), DYNAMIC) self.assertEqual(self.bind_expr("1 + 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 - 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 // 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 * 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 / 2"), FLOAT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 % 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 & 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 | 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 ^ 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("1 << 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("100 >> 2"), INT_EXACT_TYPE.instance) self.assertEqual(self.bind_stmt("x = 1"), INT_EXACT_TYPE.instance) # self.assertEqual(self.bind_stmt("x: foo = 1").target.comp_type, DYNAMIC) self.assertEqual(self.bind_stmt("x += 1"), DYNAMIC) self.assertEqual(self.bind_expr("a or b"), DYNAMIC) self.assertEqual(self.bind_expr("+a"), DYNAMIC) self.assertEqual(self.bind_expr("not a"), BOOL_TYPE.instance) self.assertEqual(self.bind_expr("lambda: 42"), DYNAMIC) self.assertEqual(self.bind_expr("a if b else c"), DYNAMIC) self.assertEqual(self.bind_expr("x > y"), DYNAMIC) self.assertEqual(self.bind_expr("x()"), DYNAMIC) self.assertEqual(self.bind_expr("x(y)"), DYNAMIC) self.assertEqual(self.bind_expr("x[y]"), DYNAMIC) self.assertEqual(self.bind_expr("x[1:2]"), DYNAMIC) self.assertEqual(self.bind_expr("x[1:2:3]"), DYNAMIC) self.assertEqual(self.bind_expr("x[:]"), DYNAMIC) self.assertEqual(self.bind_expr("{}"), DICT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("{2:3}"), DICT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("{1,2}"), SET_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("[]"), LIST_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("[1,2]"), LIST_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("(1,2)"), TUPLE_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("[x for x in y]"), LIST_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("{x for x in y}"), SET_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("{x:y for x in y}"), DICT_EXACT_TYPE.instance) self.assertEqual(self.bind_expr("(x for x in y)"), DYNAMIC) def body_get(stmt): return stmt.body[0].value self.assertEqual( self.bind_stmt("def f(): return 42", getter=body_get), INT_EXACT_TYPE.instance, ) self.assertEqual(self.bind_stmt("def f(): yield 42", getter=body_get), DYNAMIC) self.assertEqual( self.bind_stmt("def f(): yield from x", getter=body_get), DYNAMIC ) self.assertEqual( self.bind_stmt("async def f(): await x", getter=body_get), DYNAMIC ) self.assertEqual(self.bind_expr("object"), OBJECT_TYPE) self.assertEqual( self.bind_expr("1 + 2", optimize=True), INT_EXACT_TYPE.instance ) def test_if_exp(self) -> None: mod, syms = self.bind_module( """ class C: pass class D: pass x = C() if a else D() """ ) node = mod.body[-1] types = syms.modules["foo"].types self.assertEqual(types[node], DYNAMIC) mod, syms = self.bind_module( """ class C: pass x = C() if a else C() """ ) node = mod.body[-1] types = syms.modules["foo"].types self.assertEqual(types[node.value].name, "foo.C") def test_cmpop(self): codestr = """ from __static__ import int32 def f(): i: int32 = 0 j: int = 0 if i == 0: return 0 if j == 0: return 1 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "f") self.assertInBytecode(x, "INT_COMPARE_OP", 0) self.assertInBytecode(x, "COMPARE_OP", "==") def test_bind_instance(self) -> None: mod, syms = self.bind_module("class C: pass\na: C = C()") assign = mod.body[1] types = syms.modules["foo"].types self.assertEqual(types[assign.target].name, "foo.C") self.assertEqual(repr(types[assign.target]), "<foo.C>") def test_bind_func_def(self) -> None: mod, syms = self.bind_module( """ def f(x: object = None, y: object = None): pass """ ) modtable = syms.modules["foo"] self.assertTrue(isinstance(modtable.children["f"], Function)) def assertReturns(self, code: str, typename: str) -> None: actual = self.bind_final_return(code).name self.assertEqual(actual, typename) def bind_final_return(self, code: str) -> Value: mod, syms = self.bind_module(code) types = syms.modules["foo"].types node = mod.body[-1].body[-1].value return types[node] def bind_stmt( self, code: str, optimize: bool = False, getter=lambda stmt: stmt ) -> ast.stmt: mod, syms = self.bind_module(code, optimize) assert len(mod.body) == 1 types = syms.modules["foo"].types return types[getter(mod.body[0])] def bind_expr(self, code: str, optimize: bool = False) -> Value: mod, syms = self.bind_module(code, optimize) assert len(mod.body) == 1 types = syms.modules["foo"].types return types[mod.body[0].value] def bind_module( self, code: str, optimize: bool = False ) -> Tuple[ast.Module, SymbolTable]: tree = ast.parse(dedent(code)) if optimize: tree = AstOptimizer().visit(tree) symtable = SymbolTable() decl_visit = DeclarationVisitor("foo", "foo.py", symtable) decl_visit.visit(tree) decl_visit.module.finish_bind() s = SymbolVisitor() walk(tree, s) type_binder = TypeBinder(s, "foo.py", symtable, "foo") type_binder.visit(tree) # Make sure we can compile the code, just verifying all nodes are # visited. graph = StaticCodeGenerator.flow_graph("foo", "foo.py", s.scopes[tree]) code_gen = StaticCodeGenerator(None, tree, s, graph, symtable, "foo", optimize) code_gen.visit(tree) return tree, symtable def test_cross_module(self) -> None: acode = """ class C: def f(self): return 42 """ bcode = """ from a import C def f(): x = C() return x.f() """ symtable = SymbolTable() acomp = symtable.compile("a", "a.py", ast.parse(dedent(acode))) bcomp = symtable.compile("b", "b.py", ast.parse(dedent(bcode))) x = self.find_code(bcomp, "f") self.assertInBytecode(x, "INVOKE_METHOD", (("a", "C", "f"), 0)) def test_cross_module_import_time_resolution(self) -> None: class TestSymbolTable(SymbolTable): def import_module(self, name): if name == "a": symtable.add_module("a", "a.py", ast.parse(dedent(acode))) acode = """ class C: def f(self): return 42 """ bcode = """ from a import C def f(): x = C() return x.f() """ symtable = TestSymbolTable() bcomp = symtable.compile("b", "b.py", ast.parse(dedent(bcode))) x = self.find_code(bcomp, "f") self.assertInBytecode(x, "INVOKE_METHOD", (("a", "C", "f"), 0)) def test_cross_module_type_checking(self) -> None: acode = """ class C: def f(self): return 42 """ bcode = """ from typing import TYPE_CHECKING if TYPE_CHECKING: from a import C def f(x: C): return x.f() """ symtable = SymbolTable() symtable.add_module("a", "a.py", ast.parse(dedent(acode))) symtable.add_module("b", "b.py", ast.parse(dedent(bcode))) acomp = symtable.compile("a", "a.py", ast.parse(dedent(acode))) bcomp = symtable.compile("b", "b.py", ast.parse(dedent(bcode))) x = self.find_code(bcomp, "f") self.assertInBytecode(x, "INVOKE_METHOD", (("a", "C", "f"), 0)) def test_primitive_invoke(self) -> None: codestr = """ from __static__ import int8 def f(): x: int8 = 42 print(x.__str__()) """ with self.assertRaisesRegex( TypedSyntaxError, "cannot load attribute from int8" ): self.compile(codestr, StaticCodeGenerator) def test_primitive_call(self) -> None: codestr = """ from __static__ import int8 def f(): x: int8 = 42 print(x()) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot call int8"): self.compile(codestr, StaticCodeGenerator) def test_primitive_subscr(self) -> None: codestr = """ from __static__ import int8 def f(): x: int8 = 42 print(x[42]) """ with self.assertRaisesRegex(TypedSyntaxError, "cannot index int8"): self.compile(codestr, StaticCodeGenerator) def test_primitive_iter(self) -> None: codestr = """ from __static__ import int8 def f(): x: int8 = 42 for a in x: pass """ with self.assertRaisesRegex(TypedSyntaxError, "cannot iterate over int8"): self.compile(codestr, StaticCodeGenerator) def test_pseudo_strict_module(self) -> None: # simulate strict modules where the builtins come from <builtins> code = """ def f(a): x: bool = a """ builtins = ast.Assign( [ast.Name("bool", ast.Store())], ast.Subscript( ast.Name("<builtins>", ast.Load()), ast.Index(ast.Str("bool")), ast.Load(), ), None, ) tree = ast.parse(dedent(code)) tree.body.insert(0, builtins) symtable = SymbolTable() symtable.add_module("a", "a.py", tree) acomp = symtable.compile("a", "a.py", tree) x = self.find_code(acomp, "f") self.assertInBytecode(x, "CAST", ("builtins", "bool")) def test_aug_assign(self) -> None: codestr = """ def f(l): l[0] += 1 """ with self.in_module(codestr) as mod: f = mod["f"] l = [1] f(l) self.assertEqual(l[0], 2) def test_pseudo_strict_module_constant(self) -> None: # simulate strict modules where the builtins come from <builtins> code = """ def f(a): x: bool = a """ builtins = ast.Assign( [ast.Name("bool", ast.Store())], ast.Subscript( ast.Name("<builtins>", ast.Load()), ast.Index(ast.Constant("bool")), ast.Load(), ), None, ) tree = ast.parse(dedent(code)) tree.body.insert(0, builtins) symtable = SymbolTable() symtable.add_module("a", "a.py", tree) acomp = symtable.compile("a", "a.py", tree) x = self.find_code(acomp, "f") self.assertInBytecode(x, "CAST", ("builtins", "bool")) def test_cross_module_inheritance(self) -> None: acode = """ class C: def f(self): return 42 """ bcode = """ from a import C class D(C): def f(self): return 'abc' def f(y): x: C if y: x = D() else: x = C() return x.f() """ symtable = SymbolTable() symtable.add_module("a", "a.py", ast.parse(dedent(acode))) symtable.add_module("b", "b.py", ast.parse(dedent(bcode))) acomp = symtable.compile("a", "a.py", ast.parse(dedent(acode))) bcomp = symtable.compile("b", "b.py", ast.parse(dedent(bcode))) x = self.find_code(bcomp, "f") self.assertInBytecode(x, "INVOKE_METHOD", (("a", "C", "f"), 0)) def test_annotated_function(self): codestr = """ class C: def f(self) -> int: return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] c = C() self.assertEqual(x(c), 2) def test_invoke_new_derived(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x a = x(C()) class D(C): def f(self): return 2 b = x(D()) """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: a, b = mod["a"], mod["b"] self.assertEqual(a, 2) self.assertEqual(b, 4) def test_invoke_explicit_slots(self): codestr = """ class C: __slots__ = () def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x a = x(C()) """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: a = mod["a"] self.assertEqual(a, 2) def test_invoke_new_derived_nonfunc(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class Callable: def __call__(self_, obj): self.assertTrue(isinstance(obj, D)) return 42 class D(C): f = Callable() d = D() self.assertEqual(x(d), 84) def test_invoke_new_derived_nonfunc_slots(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class Callable: def __call__(self_, obj): self.assertTrue(isinstance(obj, D)) return 42 class D(C): __slots__ = () f = Callable() d = D() self.assertEqual(x(d), 84) def test_invoke_new_derived_nonfunc_descriptor(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class Callable: def __call__(self): return 42 class Descr: def __get__(self, inst, ctx): return Callable() class D(C): f = Descr() d = D() self.assertEqual(x(d), 84) def test_invoke_new_derived_nonfunc_data_descriptor(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class Callable: def __call__(self): return 42 class Descr: def __get__(self, inst, ctx): return Callable() def __set__(self, inst, value): raise ValueError("no way") class D(C): f = Descr() d = D() self.assertEqual(x(d), 84) def test_invoke_new_derived_nonfunc_descriptor_inst_override(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class Callable: def __call__(self): return 42 class Descr: def __get__(self, inst, ctx): return Callable() class D(C): f = Descr() d = D() self.assertEqual(x(d), 84) d.__dict__["f"] = lambda x: 100 self.assertEqual(x(d), 200) def test_invoke_new_derived_nonfunc_descriptor_modified(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class Callable: def __call__(self): return 42 class Descr: def __get__(self, inst, ctx): return Callable() def __call__(self, arg): return 23 class D(C): f = Descr() d = D() self.assertEqual(x(d), 84) del Descr.__get__ self.assertEqual(x(d), 46) def test_invoke_dict_override(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) class D(C): def __init__(self): self.f = lambda: 42 d = D() self.assertEqual(x(d), 84) def test_invoke_type_modified(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) C.f = lambda self: 42 self.assertEqual(x(C()), 84) def test_annotated_function_derived(self): codestr = """ class C: def f(self) -> int: return 1 class D(C): def f(self) -> int: return 2 class E(C): pass def x(c: C,): x = c.f() x += c.f() return x """ code = self.compile( codestr, StaticCodeGenerator, modname="test_annotated_function_derived" ) x = self.find_code(code, "x") self.assertInBytecode( x, "INVOKE_METHOD", (("test_annotated_function_derived", "C", "f"), 0) ) with self.in_module(codestr) as mod: x = mod["x"] self.assertEqual(x(mod["C"]()), 2) self.assertEqual(x(mod["D"]()), 4) self.assertEqual(x(mod["E"]()), 2) def test_conditional_init(self): codestr = f""" from __static__ import box, int64 class C: def __init__(self, init=True): if init: self.value: int64 = 1 def f(self) -> int: return box(self.value) """ with self.in_module(codestr) as mod: C = mod["C"] x = C() self.assertEqual(x.f(), 1) x = C(False) self.assertEqual(x.f(), 0) self.assertInBytecode(C.f, "LOAD_FIELD", (mod["__name__"], "C", "value")) def test_error_incompat_assign_local(self): codestr = """ class C: def __init__(self): self.x = None def f(self): x: "C" = self.x """ with self.in_module(codestr) as mod: C = mod["C"] with self.assertRaisesRegex(TypeError, "expected 'C', got 'NoneType'"): C().f() def test_error_incompat_field_non_dynamic(self): codestr = """ class C: def __init__(self): self.x: int = 'abc' """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator) def test_error_incompat_field(self): codestr = """ class C: def __init__(self): self.x: int = 100 def f(self, x): self.x = x """ with self.in_module(codestr) as mod: C = mod["C"] C().f(42) with self.assertRaises(TypeError): C().f("abc") def test_error_incompat_assign_dynamic(self): with self.assertRaises(TypedSyntaxError): code = self.compile( """ class C: x: "C" def __init__(self): self.x = None """, StaticCodeGenerator, ) def test_annotated_class_var(self): codestr = """ class C: x: int """ code = self.compile( codestr, StaticCodeGenerator, modname="test_annotated_class_var" ) def test_annotated_instance_var(self): codestr = """ class C: def __init__(self): self.x: str = 'abc' """ code = self.compile( codestr, StaticCodeGenerator, modname="test_annotated_instance_var" ) # get C from module, and then get __init__ from C code = self.find_code(self.find_code(code)) self.assertInBytecode(code, "STORE_FIELD") def test_load_store_attr_value(self): codestr = """ class C: x: int def __init__(self, value: int): self.x = value def f(self): return self.x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") init = self.find_code(self.find_code(code), "__init__") self.assertInBytecode(init, "STORE_FIELD") f = self.find_code(self.find_code(code), "f") self.assertInBytecode(f, "LOAD_FIELD") with self.in_module(codestr) as mod: C = mod["C"] a = C(42) self.assertEqual(a.f(), 42) def test_load_store_attr(self): codestr = """ class C: x: "C" def __init__(self): self.x = self def g(self): return 42 def f(self): return self.x.g() """ with self.in_module(codestr) as mod: C = mod["C"] a = C() self.assertEqual(a.f(), 42) def test_load_store_attr_init(self): codestr = """ class C: def __init__(self): self.x: C = self def g(self): return 42 def f(self): return self.x.g() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr) as mod: C = mod["C"] a = C() self.assertEqual(a.f(), 42) def test_load_store_attr_init_no_ann(self): codestr = """ class C: def __init__(self): self.x = self def g(self): return 42 def f(self): return self.x.g() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr) as mod: C = mod["C"] a = C() self.assertEqual(a.f(), 42) def test_unknown_annotation(self): codestr = """ def f(a): x: foo = a return x.bar """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") class C: bar = 42 f = self.run_code(codestr, StaticCodeGenerator)["f"] self.assertEqual(f(C()), 42) def test_class_method_invoke(self): codestr = """ class B: def __init__(self, value): self.value = value class D(B): def __init__(self, value): B.__init__(self, value) def f(self): return self.value """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") b_init = self.find_code(self.find_code(code, "B"), "__init__") self.assertInBytecode(b_init, "STORE_FIELD", ("foo", "B", "value")) f = self.find_code(self.find_code(code, "D"), "f") self.assertInBytecode(f, "LOAD_FIELD", ("foo", "B", "value")) with self.in_module(codestr) as mod: D = mod["D"] d = D(42) self.assertEqual(d.f(), 42) def test_slotification(self): codestr = """ class C: x: "unknown_type" """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") C = self.run_code(codestr, StaticCodeGenerator)["C"] self.assertEqual(type(C.x), MemberDescriptorType) def test_slotification_init(self): codestr = """ class C: x: "unknown_type" def __init__(self): self.x = 42 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") C = self.run_code(codestr, StaticCodeGenerator)["C"] self.assertEqual(type(C.x), MemberDescriptorType) def test_slotification_ann_init(self): codestr = """ class C: x: "unknown_type" def __init__(self): self.x: "unknown_type" = 42 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") C = self.run_code(codestr, StaticCodeGenerator)["C"] self.assertEqual(type(C.x), MemberDescriptorType) def test_slotification_typed(self): codestr = """ class C: x: int """ C = self.run_code(codestr, StaticCodeGenerator)["C"] self.assertNotEqual(type(C.x), MemberDescriptorType) def test_slotification_init_typed(self): codestr = """ class C: x: int def __init__(self): self.x = 42 """ with self.in_module(codestr) as mod: C = mod["C"] self.assertNotEqual(type(C.x), MemberDescriptorType) x = C() self.assertEqual(x.x, 42) with self.assertRaisesRegex( TypeError, "expected 'int', got 'str' for attribute 'x'" ) as e: x.x = "abc" def test_slotification_ann_init_typed(self): codestr = """ class C: x: int def __init__(self): self.x: int = 42 """ C = self.run_code(codestr, StaticCodeGenerator)["C"] self.assertNotEqual(type(C.x), MemberDescriptorType) def test_slotification_conflicting_types(self): codestr = """ class C: x: object def __init__(self): self.x: int = 42 """ with self.assertRaisesRegex( TypedSyntaxError, r"conflicting type definitions for slot x in Type\[foo.C\]", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_slotification_conflicting_types_imported(self): self.type_error( """ from typing import Optional class C: x: Optional[int] def __init__(self): self.x: Optional[str] = "foo" """, r"conflicting type definitions for slot x in Type\[<module>.C\]", ) def test_slotification_conflicting_members(self): codestr = """ class C: def x(self): pass x: object """ with self.assertRaisesRegex( TypedSyntaxError, r"slot conflicts with other member x in Type\[foo.C\]" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_slotification_conflicting_function(self): codestr = """ class C: x: object def x(self): pass """ with self.assertRaisesRegex( TypedSyntaxError, r"function conflicts with other member x in Type\[foo.C\]" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_slot_inheritance(self): codestr = """ class B: def __init__(self): self.x = 42 def f(self): return self.x class D(B): def __init__(self): self.x = 100 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr) as mod: D = mod["D"] inst = D() self.assertEqual(inst.f(), 100) def test_del_slot(self): codestr = """ class C: x: object def f(a: C): del a.x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") code = self.find_code(code, name="f") self.assertInBytecode(code, "DELETE_ATTR", "x") def test_uninit_slot(self): codestr = """ class C: x: object def f(a: C): return a.x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") code = self.find_code(code, name="f") with self.in_module(codestr) as mod: with self.assertRaises(AttributeError) as e: f, C = mod["f"], mod["C"] f(C()) self.assertEqual(e.exception.args[0], "x") def test_aug_add(self): codestr = """ class C: def __init__(self): self.x = 1 def f(a: C): a.x += 1 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") code = self.find_code(code, name="f") self.assertInBytecode(code, "LOAD_FIELD", ("foo", "C", "x")) self.assertInBytecode(code, "STORE_FIELD", ("foo", "C", "x")) def test_untyped_attr(self): codestr = """ y = x.load x.store = 42 del x.delete """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") self.assertInBytecode(code, "LOAD_ATTR", "load") self.assertInBytecode(code, "STORE_ATTR", "store") self.assertInBytecode(code, "DELETE_ATTR", "delete") def test_incompat_override(self): codestr = """ class C: x: int class D(C): def x(self): pass """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_redefine_type(self): codestr = """ class C: pass class D: pass def f(a): x: C = C() x: D = D() """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_optional_error(self): codestr = """ from typing import Optional class C: x: Optional["C"] def __init__(self, set): if set: self.x = self else: self.x = None def f(self) -> Optional["C"]: return self.x.x """ with self.assertRaisesRegex( TypedSyntaxError, re.escape("Optional[foo.C]: 'NoneType' object has no attribute 'x'"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_optional_subscript_error(self) -> None: codestr = """ from typing import Optional def f(a: Optional[int]): a[1] """ with self.assertRaisesRegex( TypedSyntaxError, re.escape("Optional[int]: 'NoneType' object is not subscriptable"), ): self.compile(codestr, StaticCodeGenerator) def test_optional_unary_error(self) -> None: codestr = """ from typing import Optional def f(a: Optional[int]): -a """ with self.assertRaisesRegex( TypedSyntaxError, re.escape("Optional[int]: bad operand type for unary -: 'NoneType'"), ): self.compile(codestr, StaticCodeGenerator) def test_optional_assign(self): codestr = """ from typing import Optional class C: def f(self, x: Optional["C"]): if x is None: return self else: p: Optional["C"] = x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_nonoptional_load(self): codestr = """ class C: def __init__(self, y: int): self.y = y def f(c: C) -> int: return c.y """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "f") self.assertInBytecode(f, "LOAD_FIELD", ("foo", "C", "y")) def test_optional_assign_subclass(self): codestr = """ from typing import Optional class B: pass class D(B): pass def f(x: D): a: Optional[B] = x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_optional_assign_subclass_opt(self): codestr = """ from typing import Optional class B: pass class D(B): pass def f(x: Optional[D]): a: Optional[B] = x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_optional_assign_none(self): codestr = """ from typing import Optional class B: pass def f(x: Optional[B]): a: Optional[B] = None """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_optional_union_syntax(self): self.assertReturns( """ from typing import Union class B: pass class C(B): pass def f(x: Union[int, None]) -> int: # can assign None y: Optional[int] = None # can assign subclass z: Optional[B] = C() # can narrow if x is None: return 1 return x """, "int", ) def test_optional_union_syntax_error(self): self.type_error( """ from typing import Union def f(x: Union[int, None]) -> int: return x """, type_mismatch("Optional[int]", "int"), ) def test_union_can_assign_to_broader_union(self): self.assertReturns( """ from typing import Union class B: pass def f(x: Union[int, str]) -> Union[int, str, B]: return x """, "Union[int, str]", ) def test_union_can_assign_to_same_union(self): self.assertReturns( """ from typing import Union def f(x: Union[int, str]) -> Union[int, str]: return x """, "Union[int, str]", ) def test_union_can_assign_from_individual_element(self): self.assertReturns( """ from typing import Union def f(x: int) -> Union[int, str]: return x """, "int", ) def test_union_cannot_assign_from_broader_union(self): self.type_error( """ from typing import Union class B: pass def f(x: Union[int, str, B]) -> Union[int, str]: return x """, type_mismatch( "Union[int, str, <module>.B]", "Union[int, str]", ), ) def test_union_simplify_to_single_type(self): self.assertReturns( """ from typing import Union def f(x: Union[int]) -> int: return x """, "int", ) def test_union_simplify_related(self): self.assertReturns( """ from typing import Union class B: pass class C(B): pass def f(x: Union[B, C]) -> B: return x """, "foo.B", ) def test_union_simplify_identical(self): self.assertReturns( """ from typing import Union def f(x: Union[int, int]) -> int: return x """, "int", ) def test_union_flatten_nested(self): self.assertReturns( """ from typing import Union class B: pass def f(x: Union[int, Union[str, B]]): return x """, "Union[int, str, foo.B]", ) def test_union_deep_simplify(self): self.assertReturns( """ from typing import Union def f(x: Union[Union[int, int], Union[Union[None, None], Union[int, int]]]) -> int: if x is None: return 1 return x """, "int", ) def test_union_dynamic_element(self): self.assertReturns( """ from somewhere import unknown def f(x: Union[int, unknown]): return x """, "dynamic", ) def test_union_or_syntax(self): self.type_error( """ def f(x) -> int: if isinstance(x, int|str): return x return 1 """, type_mismatch("Union[int, str]", "int"), ) def test_union_or_syntax_none(self): self.type_error( """ def f(x) -> int: if isinstance(x, int|None): return x return 1 """, type_mismatch("Optional[int]", "int"), ) def test_union_or_syntax_builtin_type(self): self.compile( """ from typing import Iterator def f(x) -> int: if isinstance(x, bytes | Iterator[bytes]): return 1 return 2 """, StaticCodeGenerator, modname="foo.py", ) def test_union_or_syntax_none_first(self): self.type_error( """ def f(x) -> int: if isinstance(x, None|int): return x return 1 """, type_mismatch("Optional[int]", "int"), ) def test_union_or_syntax_annotation(self): self.type_error( """ def f(x: int|str) -> int: return x """, type_mismatch("Union[int, str]", "int"), ) def test_union_or_syntax_error(self): self.type_error( """ def f(): x = int | "foo" """, r"unsupported operand type(s) for |: Type\[Exact\[int\]\] and Exact\[str\]", ) def test_union_or_syntax_annotation_bad_type(self): # TODO given that len is not unknown/dynamic, but is a known object # with type that is invalid in this position, this should really be an # error. But the current form of `resolve_annotations` doesn't let us # distinguish between unknown/dynamic and bad type. So for now we just # let this go as dynamic. self.assertReturns( """ def f(x: len | int) -> int: return x """, "dynamic", ) def test_union_attr(self): self.assertReturns( """ class A: attr: int class B: attr: str def f(x: A | B): return x.attr """, "Union[int, str]", ) def test_union_attr_error(self): self.type_error( """ class A: attr: int def f(x: A | None): return x.attr """, re.escape( "Optional[<module>.A]: 'NoneType' object has no attribute 'attr'" ), ) # TODO add test_union_call when we have Type[] or Callable[] or # __call__ support. Right now we have no way to construct a Union of # callables that return different types. def test_union_call_error(self): self.type_error( """ def f(x: int | None): return x() """, re.escape("Optional[int]: 'NoneType' object is not callable"), ) def test_union_subscr(self): self.assertReturns( """ from __static__ import CheckedDict def f(x: CheckedDict[int, int] | CheckedDict[int, str]): return x[0] """, "Union[int, str]", ) def test_union_unaryop(self): self.assertReturns( """ def f(x: int | complex): return -x """, "Union[int, complex]", ) def test_union_isinstance_reverse_narrow(self): self.assertReturns( """ def f(x: int | str): if isinstance(x, str): return 1 return x """, "int", ) def test_union_isinstance_reverse_narrow_supertype(self): self.assertReturns( """ class A: pass class B(A): pass def f(x: int | B): if isinstance(x, A): return 1 return x """, "int", ) def test_union_isinstance_reverse_narrow_other_union(self): self.assertReturns( """ class A: pass class B: pass class C: pass def f(x: A | B | C): if isinstance(x, A | B): return 1 return x """, "foo.C", ) def test_union_not_isinstance_narrow(self): self.assertReturns( """ def f(x: int | str): if not isinstance(x, int): return 1 return x """, "int", ) def test_union_isinstance_tuple(self): self.assertReturns( """ class A: pass class B: pass class C: pass def f(x: A | B | C): if isinstance(x, (A, B)): return 1 return x """, "foo.C", ) def test_error_return_int(self): with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int64 cannot be assigned to dynamic" ): code = self.compile( """ from __static__ import ssize_t def f(): y: ssize_t = 1 return y """, StaticCodeGenerator, ) def test_error_mixed_math(self): with self.assertRaises(TypedSyntaxError): code = self.compile( """ from __static__ import ssize_t def f(): y = 1 x: ssize_t = 42 + y """, StaticCodeGenerator, ) def test_error_incompat_return(self): with self.assertRaises(TypedSyntaxError): code = self.compile( """ class D: pass class C: def __init__(self): self.x = None def f(self) -> "C": return D() """, StaticCodeGenerator, ) def test_cast(self): for code_gen in (StaticCodeGenerator, PythonCodeGenerator): codestr = """ from __static__ import cast class C: pass a = C() def f() -> C: return cast(C, a) """ code = self.compile(codestr, code_gen) f = self.find_code(code, "f") if code_gen is StaticCodeGenerator: self.assertInBytecode(f, "CAST", ("<module>", "C")) with self.in_module(codestr, code_gen=code_gen) as mod: C = mod["C"] f = mod["f"] self.assertTrue(isinstance(f(), C)) self.assert_jitted(f) def test_cast_fail(self): for code_gen in (StaticCodeGenerator, PythonCodeGenerator): codestr = """ from __static__ import cast class C: pass def f() -> C: return cast(C, 42) """ code = self.compile(codestr, code_gen) f = self.find_code(code, "f") if code_gen is StaticCodeGenerator: self.assertInBytecode(f, "CAST", ("<module>", "C")) with self.in_module(codestr) as mod: with self.assertRaises(TypeError): f = mod["f"] f() self.assert_jitted(f) def test_cast_wrong_args(self): codestr = """ from __static__ import cast def f(): cast(42) """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator) def test_cast_unknown_type(self): codestr = """ from __static__ import cast def f(): cast(abc, 42) """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator) def test_cast_optional(self): for code_gen in (StaticCodeGenerator, PythonCodeGenerator): codestr = """ from __static__ import cast from typing import Optional class C: pass def f(x) -> Optional[C]: return cast(Optional[C], x) """ code = self.compile(codestr, code_gen) f = self.find_code(code, "f") if code_gen is StaticCodeGenerator: self.assertInBytecode(f, "CAST", ("<module>", "C", "?")) with self.in_module(codestr, code_gen=code_gen) as mod: C = mod["C"] f = mod["f"] self.assertTrue(isinstance(f(C()), C)) self.assertEqual(f(None), None) self.assert_jitted(f) def test_code_flags(self): codestr = """ def func(): print("hi") func() """ module = self.compile(codestr, StaticCodeGenerator) self.assertTrue(module.co_flags & CO_STATICALLY_COMPILED) self.assertTrue( self.find_code(module, name="func").co_flags & CO_STATICALLY_COMPILED ) def test_invoke_kws(self): codestr = """ class C: def f(self, a): return a def func(): a = C() return a.f(a=2) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertEqual(f(), 2) def test_invoke_str_method(self): codestr = """ def func(): a = 'a b c' return a.split() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode( f, "INVOKE_FUNCTION", (("builtins", "str", "split"), 1) ) self.assertEqual(f(), ["a", "b", "c"]) def test_invoke_str_method_arg(self): codestr = """ def func(): a = 'a b c' return a.split('a') """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode( f, "INVOKE_FUNCTION", (("builtins", "str", "split"), 2) ) self.assertEqual(f(), ["", " b c"]) def test_invoke_str_method_kwarg(self): codestr = """ def func(): a = 'a b c' return a.split(sep='a') """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertNotInBytecode(f, "INVOKE_FUNCTION") self.assertNotInBytecode(f, "INVOKE_METHOD") self.assertEqual(f(), ["", " b c"]) def test_invoke_int_method(self): codestr = """ def func(): a = 42 return a.bit_length() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode( f, "INVOKE_FUNCTION", (("builtins", "int", "bit_length"), 1) ) self.assertEqual(f(), 6) def test_invoke_chkdict_method(self): codestr = """ from __static__ import CheckedDict def dict_maker() -> CheckedDict[int, int]: return CheckedDict[int, int]({2:2}) def func(): a = dict_maker() return a.keys() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode( f, "INVOKE_METHOD", ( ( "__static__", "chkdict", (("builtins", "int"), ("builtins", "int")), "keys", ), 0, ), ) self.assertEqual(list(f()), [2]) self.assert_jitted(f) def test_invoke_method_non_static_base(self): codestr = """ class C(Exception): def f(self): return 42 def g(self): return self.f() """ with self.in_module(codestr) as mod: C = mod["C"] self.assertEqual(C().g(), 42) def test_invoke_builtin_func(self): codestr = """ from xxclassloader import foo from __static__ import int64, box def func(): a: int64 = foo() return box(a) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode(f, "INVOKE_FUNCTION", ((("xxclassloader", "foo"), 0))) self.assertEqual(f(), 42) self.assert_jitted(f) def test_invoke_builtin_func_ret_neg(self): # setup xxclassloader as a built-in function for this test, so we can # do a direct invoke xxclassloader = sys.modules["xxclassloader"] try: sys.modules["xxclassloader"] = StrictModule(xxclassloader.__dict__, False) codestr = """ from xxclassloader import neg from __static__ import int64, box def test(): x: int64 = neg() return box(x) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertEqual(test(), -1) finally: sys.modules["xxclassloader"] = xxclassloader def test_invoke_builtin_func_arg(self): codestr = """ from xxclassloader import bar from __static__ import int64, box def func(): a: int64 = bar(42) return box(a) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode(f, "INVOKE_FUNCTION", ((("xxclassloader", "bar"), 1))) self.assertEqual(f(), 42) self.assert_jitted(f) def test_invoke_meth_o(self): codestr = """ from xxclassloader import spamobj def func(): a = spamobj[int]() a.setstate_untyped(42) return a.getstate() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertInBytecode( f, "INVOKE_METHOD", ( ( "xxclassloader", "spamobj", (("builtins", "int"),), "setstate_untyped", ), 1, ), ) self.assertEqual(f(), 42) self.assert_jitted(f) def test_multi_generic(self): codestr = """ from xxclassloader import XXGeneric def func(): a = XXGeneric[int, str]() return a.foo(42, 'abc') """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["func"] self.assertEqual(f(), "42abc") def test_verify_positional_args(self): codestr = """ def x(a: int, b: str) -> None: pass x("a", 2) """ with self.assertRaisesRegex(TypedSyntaxError, "argument type mismatch"): self.compile(codestr, StaticCodeGenerator) def test_verify_positional_args_unordered(self): codestr = """ def x(a: int, b: str) -> None: return y(a, b) def y(a: int, b: str) -> None: pass """ self.compile(codestr, StaticCodeGenerator) def test_verify_kwargs(self): codestr = """ def x(a: int=1, b: str="hunter2") -> None: return x(b="lol", a=23) """ self.compile(codestr, StaticCodeGenerator) def test_verify_kwdefaults(self): codestr = """ def x(*, b: str="hunter2"): return b z = x(b="lol") """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: self.assertEqual(mod["z"], "lol") def test_verify_kwdefaults_no_value(self): codestr = """ def x(*, b: str="hunter2"): return b a = x() """ module = self.compile(codestr, StaticCodeGenerator) # we don't yet support optimized dispatch to kw-only functions self.assertInBytecode(module, "CALL_FUNCTION") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: self.assertEqual(mod["a"], "hunter2") def test_verify_arg_dynamic_type(self): codestr = """ def x(v:str): return 'abc' def y(v): return x(v) """ module = self.compile(codestr, StaticCodeGenerator) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: y = mod["y"] with self.assertRaises(TypeError): y(42) self.assertEqual(y("foo"), "abc") def test_verify_arg_unknown_type(self): codestr = """ def x(x:foo): return b x('abc') """ module = self.compile(codestr, StaticCodeGenerator) self.assertInBytecode(module, "INVOKE_FUNCTION") x = self.find_code(module) self.assertInBytecode(x, "CHECK_ARGS", ()) def test_dict_invoke(self): codestr = """ from __static__ import pydict def f(x): y: pydict = x return y.get('foo') """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "INVOKE_METHOD", (("builtins", "dict", "get"), 1)) self.assertEqual(f({}), None) def test_dict_invoke_ret(self): codestr = """ from __static__ import pydict def g(): return None def f(x): y: pydict = x z = y.get('foo') z = None # should be typed to dynamic return z """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "INVOKE_METHOD", (("builtins", "dict", "get"), 1)) self.assertEqual(f({}), None) def test_verify_kwarg_unknown_type(self): codestr = """ def x(x:foo): return b x(x='abc') """ module = self.compile(codestr, StaticCodeGenerator) self.assertInBytecode(module, "INVOKE_FUNCTION") x = self.find_code(module) self.assertInBytecode(x, "CHECK_ARGS", ()) def test_verify_kwdefaults_too_many(self): codestr = """ def x(*, b: str="hunter2") -> None: return x('abc') """ with self.assertRaisesRegex( TypedSyntaxError, "x takes 0 positional args but 1 was given" ): self.compile(codestr, StaticCodeGenerator) def test_verify_kwdefaults_too_many_class(self): codestr = """ class C: def x(self, *, b: str="hunter2") -> None: return C().x('abc') """ with self.assertRaisesRegex( TypedSyntaxError, "x takes 1 positional args but 2 were given" ): self.compile(codestr, StaticCodeGenerator) def test_verify_kwonly_failure(self): codestr = """ def x(*, a: int=1, b: str="hunter2") -> None: return x(a="hi", b="lol") """ with self.assertRaisesRegex(TypedSyntaxError, "keyword argument type mismatch"): self.compile(codestr, StaticCodeGenerator) def test_verify_kwonly_self_loaded_once(self): codestr = """ class C: def x(self, *, a: int=1) -> int: return 43 def f(): return C().x(a=1) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] io = StringIO() dis.dis(f, file=io) self.assertEqual(1, io.getvalue().count("LOAD_GLOBAL")) def test_call_function_unknown_ret_type(self): codestr = """ from __future__ import annotations def g() -> foo: return 42 def testfunc(): return g() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["testfunc"] self.assertEqual(f(), 42) def test_verify_kwargs_failure(self): codestr = """ def x(a: int=1, b: str="hunter2") -> None: return x(a="hi", b="lol") """ with self.assertRaisesRegex(TypedSyntaxError, "keyword argument type mismatch"): self.compile(codestr, StaticCodeGenerator) def test_verify_mixed_args(self): codestr = """ def x(a: int=1, b: str="hunter2", c: int=14) -> None: return x(12, c=56, b="lol") """ self.compile(codestr, StaticCodeGenerator) def test_kwarg_cast(self): codestr = """ def x(a: int=1, b: str="hunter2", c: int=14) -> None: return def g(a): x(b=a) """ code = self.find_code(self.compile(codestr, StaticCodeGenerator), "g") self.assertInBytecode(code, "CAST", ("builtins", "str")) def test_kwarg_nocast(self): codestr = """ def x(a: int=1, b: str="hunter2", c: int=14) -> None: return def g(): x(b='abc') """ code = self.find_code(self.compile(codestr, StaticCodeGenerator), "g") self.assertNotInBytecode(code, "CAST", ("builtins", "str")) def test_verify_mixed_args_kw_failure(self): codestr = """ def x(a: int=1, b: str="hunter2", c: int=14) -> None: return x(12, c="hi", b="lol") """ with self.assertRaisesRegex(TypedSyntaxError, "keyword argument type mismatch"): self.compile(codestr, StaticCodeGenerator) def test_verify_mixed_args_positional_failure(self): codestr = """ def x(a: int=1, b: str="hunter2", c: int=14) -> None: return x("hi", b="lol") """ with self.assertRaisesRegex( TypedSyntaxError, "positional argument type mismatch" ): self.compile(codestr, StaticCodeGenerator) # Same tests as above, but for methods. def test_verify_positional_args_method(self): codestr = """ class C: def x(self, a: int, b: str) -> None: pass C().x(2, "hi") """ self.compile(codestr, StaticCodeGenerator) def test_verify_positional_args_failure_method(self): codestr = """ class C: def x(self, a: int, b: str) -> None: pass C().x("a", 2) """ with self.assertRaisesRegex( TypedSyntaxError, "positional argument type mismatch" ): self.compile(codestr, StaticCodeGenerator) def test_verify_mixed_args_method(self): codestr = """ class C: def x(self, a: int=1, b: str="hunter2", c: int=14) -> None: return C().x(12, c=56, b="lol") """ self.compile(codestr, StaticCodeGenerator) def test_starargs_invoked_once(self): codestr = """ X = 0 def f(): global X X += 1 return {"a": 1, "b": "foo", "c": 42} class C: def x(self, a: int=1, b: str="hunter2", c: int=14) -> None: return C().x(12, **f()) """ with self.in_module(codestr) as mod: x = mod["X"] self.assertEqual(x, 1) def test_starargs_invoked_in_order(self): codestr = """ X = 1 def f(): global X X += 1 return {"a": 1, "b": "foo"} def make_c(): global X X *= 2 return 42 class C: def x(self, a: int=1, b: str="hunter2", c: int=14) -> None: return def test(): C().x(12, c=make_c(), **f()) """ with self.in_module(codestr) as mod: test = mod["test"] test() x = mod["X"] self.assertEqual(x, 3) def test_verify_mixed_args_kw_failure_method(self): codestr = """ class C: def x(self, a: int=1, b: str="hunter2", c: int=14) -> None: return C().x(12, c=b'lol', b="lol") """ with self.assertRaisesRegex(TypedSyntaxError, "keyword argument type mismatch"): self.compile(codestr, StaticCodeGenerator) def test_verify_mixed_args_positional_failure_method(self): codestr = """ class C: def x(self, a: int=1, b: str="hunter2", c: int=14) -> None: return C().x("hi", b="lol") """ with self.assertRaisesRegex( TypedSyntaxError, "positional argument type mismatch" ): self.compile(codestr, StaticCodeGenerator) def test_generic_kwargs_unsupported(self): # definition is allowed, we just don't do an optimal invoke codestr = """ def f(a: int, b: str, **my_stuff) -> None: pass def g(): return f(1, 'abc', x="y") """ with self.in_module(codestr) as mod: g = mod["g"] self.assertInBytecode(g, "CALL_FUNCTION_KW", 3) def test_generic_kwargs_method_unsupported(self): # definition is allowed, we just don't do an optimal invoke codestr = """ class C: def f(self, a: int, b: str, **my_stuff) -> None: pass def g(): return C().f(1, 'abc', x="y") """ with self.in_module(codestr) as mod: g = mod["g"] self.assertInBytecode(g, "CALL_FUNCTION_KW", 3) def test_generic_varargs_unsupported(self): # definition is allowed, we just don't do an optimal invoke codestr = """ def f(a: int, b: str, *my_stuff) -> None: pass def g(): return f(1, 'abc', "foo") """ with self.in_module(codestr) as mod: g = mod["g"] self.assertInBytecode(g, "CALL_FUNCTION", 3) def test_generic_varargs_method_unsupported(self): # definition is allowed, we just don't do an optimal invoke codestr = """ class C: def f(self, a: int, b: str, *my_stuff) -> None: pass def g(): return C().f(1, 'abc', "foo") """ with self.in_module(codestr) as mod: g = mod["g"] self.assertInBytecode(g, "CALL_METHOD", 3) def test_kwargs_get(self): codestr = """ def test(**foo): print(foo.get('bar')) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertInBytecode( test, "INVOKE_FUNCTION", (("builtins", "dict", "get"), 2) ) def test_varargs_count(self): codestr = """ def test(*foo): print(foo.count('bar')) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertInBytecode( test, "INVOKE_FUNCTION", (("builtins", "tuple", "count"), 2) ) def test_varargs_call(self): codestr = """ def g(*foo): return foo def testfunc(): return g(2) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), (2,)) def test_kwargs_call(self): codestr = """ def g(**foo): return foo def testfunc(): return g(x=2) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), {"x": 2}) def test_index_by_int(self): codestr = """ from __static__ import int32 def f(x): i: int32 = 0 return x[i] """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator) def test_pydict_arg_annotation(self): codestr = """ from __static__ import PyDict def f(d: PyDict[str, int]) -> str: # static python ignores the untrusted generic types return d[3] """ with self.in_module(codestr) as mod: self.assertEqual(mod["f"]({3: "foo"}), "foo") def test_list_get_primitive_int(self): codestr = """ from __static__ import int8 def f(): l = [1, 2, 3] x: int8 = 1 return l[x] """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_GET", SEQ_LIST) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), 2) def test_list_set_primitive_int(self): codestr = """ from __static__ import int8 def f(): l = [1, 2, 3] x: int8 = 1 l[x] = 5 return l """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_SET") with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 5, 3]) def test_list_set_primitive_int_2(self): codestr = """ from __static__ import int64 def f(l1): l2 = [None] * len(l1) i: int64 = 0 for item in l1: l2[i] = item + 1 i += 1 return l2 """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_SET") with self.in_module(codestr) as mod: self.assertEqual(mod["f"]([1, 2000]), [2, 2001]) def test_list_del_primitive_int(self): codestr = """ from __static__ import int8 def f(): l = [1, 2, 3] x: int8 = 1 del l[x] return l """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "LIST_DEL") with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 3]) def test_list_append(self): codestr = """ from __static__ import int8 def f(): l = [1, 2, 3] l.append(4) return l """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "LIST_APPEND", 1) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 2, 3, 4]) def test_unknown_type_unary(self): codestr = """ def x(y): z = -y """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "UNARY_NEGATIVE") def test_unknown_type_binary(self): codestr = """ def x(a, b): z = a + b """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "BINARY_ADD") def test_unknown_type_compare(self): codestr = """ def x(a, b): z = a > b """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "COMPARE_OP") def test_async_func_ret_type(self): codestr = """ async def x(a) -> int: return a """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST") def test_async_func_arg_types(self): codestr = """ async def f(x: int): pass """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "CHECK_ARGS", (0, ("builtins", "int"))) def test_assign_prim_to_class(self): codestr = """ from __static__ import int64 class C: pass def f(): x: C = C() y: int64 = 42 x = y """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("int64", "foo.C")): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_field_refcount(self): codestr = """ class C: def __init__(self): self.x = None def set_x(self, x): self.x = x """ count = 0 with self.in_module(codestr) as mod: C = mod["C"] class X: def __init__(self): nonlocal count count += 1 def __del__(self): nonlocal count count -= 1 c = C() c.set_x(X()) c.set_x(X()) self.assertEqual(count, 1) del c self.assertEqual(count, 0) def test_typed_field_del(self): codestr = """ class D: def __init__(self, counter): self.counter = counter self.counter[0] += 1 def __del__(self): self.counter[0] -= 1 class C: def __init__(self, value: D): self.x: D = value def __del__(self): del self.x """ count = 0 with self.in_module(codestr) as mod: D = mod["D"] counter = [0] d = D(counter) C = mod["C"] a = C(d) del d self.assertEqual(counter[0], 1) del a self.assertEqual(counter[0], 0) def test_typed_field_deleted_attr(self): codestr = """ class C: def __init__(self, value: str): self.x: str = value """ count = 0 with self.in_module(codestr) as mod: C = mod["C"] a = C("abc") del a.x with self.assertRaises(AttributeError): a.x def test_generic_method_ret_type(self): codestr = """ from __static__ import CheckedDict from typing import Optional MAP: CheckedDict[str, Optional[str]] = CheckedDict[str, Optional[str]]({'abc': 'foo', 'bar': None}) def f(x: str) -> Optional[str]: return MAP.get(x) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode( f, "INVOKE_METHOD", ( ( "__static__", "chkdict", (("builtins", "str"), ("builtins", "str", "?")), "get", ), 2, ), ) self.assertEqual(f("abc"), "foo") self.assertEqual(f("bar"), None) def test_attr_generic_optional(self): codestr = """ from typing import Optional def f(x: Optional): return x.foo """ with self.assertRaisesRegex( TypedSyntaxError, "cannot access attribute from unbound Union" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_generic_optional(self): codestr = """ from typing import Optional def f(): x: Optional = 42 """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[int]", "Optional[T]") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_generic_optional_2(self): codestr = """ from typing import Optional def f(): x: Optional = 42 + 1 """ with self.assertRaises(TypedSyntaxError): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_from_generic_optional(self): codestr = """ from typing import Optional class C: pass def f(x: Optional): y: Optional[C] = x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Optional[T]", optional("foo.C")) ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_list_of_dynamic(self): codestr = """ from threading import Thread from typing import List def f(threads: List[Thread]) -> int: return len(threads) """ f = self.find_code(self.compile(codestr), "f") self.assertInBytecode(f, "FAST_LEN") def test_int_swap(self): codestr = """ from __static__ import int64, box def test(): x: int64 = 42 y: int64 = 100 x, y = y, x return box(x), box(y) """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("int64", "dynamic") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_typed_swap(self): codestr = """ def test(a): x: int y: str x, y = 1, a """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST", ("builtins", "str")) self.assertNotInBytecode(f, "CAST", ("builtins", "int")) def test_typed_swap_2(self): codestr = """ def test(a): x: int y: str x, y = a, 'abc' """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST", ("builtins", "int")) self.assertNotInBytecode(f, "CAST", ("builtins", "str")) def test_typed_swap_member(self): codestr = """ class C: def __init__(self): self.x: int = 42 def test(a): x: int y: str C().x, y = a, 'abc' """ f = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), "test" ) self.assertInBytecode(f, "CAST", ("builtins", "int")) self.assertNotInBytecode(f, "CAST", ("builtins", "str")) def test_typed_swap_list(self): codestr = """ def test(a): x: int y: str [x, y] = a, 'abc' """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST", ("builtins", "int")) self.assertNotInBytecode(f, "CAST", ("builtins", "str")) def test_typed_swap_nested(self): codestr = """ def test(a): x: int y: str z: str ((x, y), z) = (a, 'abc'), 'foo' """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST", ("builtins", "int")) self.assertNotInBytecode(f, "CAST", ("builtins", "str")) def test_typed_swap_nested_2(self): codestr = """ def test(a): x: int y: str z: str ((x, y), z) = (1, a), 'foo' """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST", ("builtins", "str")) self.assertNotInBytecode(f, "CAST", ("builtins", "int")) def test_typed_swap_nested_3(self): codestr = """ def test(a): x: int y: int z: str ((x, y), z) = (1, 2), a """ f = self.find_code(self.compile(codestr, StaticCodeGenerator, modname="foo")) self.assertInBytecode(f, "CAST", ("builtins", "str")) # Currently because the tuple gets turned into a constant this is less than # ideal: self.assertInBytecode(f, "CAST", ("builtins", "int")) def test_if_optional(self): codestr = """ from typing import Optional class C: def __init__(self): self.field = 42 def f(x: Optional[C]): if x is not None: return x.field return None """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_return_outside_func(self): codestr = """ return 42 """ with self.assertRaisesRegex(SyntaxError, "'return' outside function"): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_double_decl(self): codestr = """ def f(): x: int x: str """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot redefine local variable x" ): self.compile(codestr, StaticCodeGenerator, modname="foo") codestr = """ def f(): x = 42 x: str """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot redefine local variable x" ): self.compile(codestr, StaticCodeGenerator, modname="foo") codestr = """ def f(): x = 42 x: int """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot redefine local variable x" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_else_optional(self): codestr = """ from typing import Optional class C: def __init__(self): self.field = self def g(x: C): pass def f(x: Optional[C], y: Optional[C]): if x is None: x = y if x is None: return None else: return g(x) else: return g(x) return None """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_else_optional_return(self): codestr = """ from typing import Optional class C: def __init__(self): self.field = self def f(x: Optional[C]): if x is None: return 0 return x.field """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_else_optional_return_two_branches(self): codestr = """ from typing import Optional class C: def __init__(self): self.field = self def f(x: Optional[C]): if x is None: if a: return 0 else: return 2 return x.field """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_else_optional_return_in_else(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: if x is not None: pass else: return 2 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_else_optional_return_in_else_assignment_in_if(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: if x is None: x = 1 else: return 2 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_else_optional_return_in_if_assignment_in_else(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: if x is not None: return 2 else: x = 1 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_narrow_conditional(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x = B() if abc: x = D() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "D", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(True), "abc") self.assertEqual(test(False), None) def test_no_narrow_to_dynamic(self): codestr = """ def f(): return 42 def g(): x: int = 100 x = f() return x.bit_length() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] self.assertInBytecode(g, "CAST", ("builtins", "int")) self.assertInBytecode( g, "INVOKE_METHOD", (("builtins", "int", "bit_length"), 0) ) self.assertEqual(g(), 6) def test_global_uses_decl_type(self): codestr = """ # even though we can locally infer G must be None, # it's not Final so nested scopes can't assume it # remains None G: int | None = None def f() -> int: global G # if we use the local_type for G's type, # x would have a local type of None x: int | None = G if x is None: x = G = 1 return x """ with self.in_strict_module(codestr) as mod: self.assertEqual(mod.f(), 1) def test_module_level_type_narrow(self): codestr = """ def a() -> int | None: return 1 G = a() if G is not None: G += 1 def f() -> int: if G is None: return 0 reveal_type(G) """ with self.assertRaisesRegex(TypedSyntaxError, r"Optional\[int\]"): self.compile(codestr) def test_narrow_conditional_widened(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x = B() if abc: x = D() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(True), "abc") self.assertEqual(test(False), 42) def test_widen_to_dynamic(self): self.assertReturns( """ def f(x, flag): if flag: x = 3 return x """, "dynamic", ) def test_assign_conditional_both_sides(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x = B() if abc: x = D() else: x = D() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "D", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(True), "abc") def test_assign_conditional_invoke_in_else(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x = B() if abc: x = D() else: return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(True), None) def test_assign_else_only(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): if abc: pass else: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(False), 42) def test_assign_test_var(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: if x is None: x = 1 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_while(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x = B() while abc: x = D() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(False), 42) def test_assign_while_test_var(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: while x is None: x = 1 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_while_returns(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: while x is None: return 1 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_while_returns_but_assigns_first(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: y: Optional[int] = 1 while x is None: y = None return 1 return y """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_while_else_reverses_condition(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: while x is None: pass else: return x return 1 """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_continue_condition(self): codestr = """ from typing import Optional def f(x: Optional[str]) -> str: while True: if x is None: continue return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_break_condition(self): codestr = """ from typing import Optional def f(x: Optional[str]) -> str: while True: if x is None: break return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_but_annotated(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x: B = D() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "D", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(False), "abc") def test_assign_while_2(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x: B = D() while abc: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(False), "abc") def test_assign_while_else(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x = B() while abc: pass else: x = D() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(False), "abc") def test_assign_while_else_2(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(abc): x: B = D() while abc: pass else: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(False), 42) def test_assign_try_except_no_initial(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): try: x: B = D() except: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), "abc") def test_narrow_or(self): codestr = """ def f(x: int | None) -> int: if x is None or x > 1: x = 1 return x """ self.compile(codestr) def test_type_of_or(self): codestr = """ def f(x: int, y: str) -> int | str: return x or y """ self.compile(codestr) def test_none_annotation(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> None: return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Optional[int]", "None"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_none_compare(self): codestr = """ def f(x: int | None): if x > 1: x = 1 return x """ with self.assertRaisesRegex( TypedSyntaxError, r"'>' not supported between 'Optional\[int\]' and 'Exact\[int\]'", ): self.compile(codestr) def test_none_compare_reverse(self): codestr = """ def f(x: int | None): if 1 > x: x = 1 return x """ with self.assertRaisesRegex( TypedSyntaxError, r"'>' not supported between 'Exact\[int\]' and 'Optional\[int\]'", ): self.compile(codestr) def test_union_compare(self): codestr = """ def f(x: int | float) -> bool: return x > 0 """ with self.in_strict_module(codestr) as mod: self.assertEqual(mod.f(3), True) self.assertEqual(mod.f(3.1), True) self.assertEqual(mod.f(-3), False) self.assertEqual(mod.f(-3.1), False) def test_global_int(self): codestr = """ X: int = 60 * 60 * 24 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: X = mod["X"] self.assertEqual(X, 60 * 60 * 24) def test_with_traceback(self): codestr = """ def f(): x = Exception() return x.with_traceback(None) """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(type(f()), Exception) self.assertInBytecode( f, "INVOKE_METHOD", (("builtins", "BaseException", "with_traceback"), 1) ) def test_assign_num_to_object(self): codestr = """ def f(): x: object = 42 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "CAST", ("builtins", "object")) def test_assign_num_to_dynamic(self): codestr = """ def f(): x: foo = 42 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "CAST", ("builtins", "object")) def test_assign_dynamic_to_object(self): codestr = """ def f(C): x: object = C() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "CAST", ("builtins", "object")) def test_assign_dynamic_to_dynamic(self): codestr = """ def f(C): x: unknown = C() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "CAST", ("builtins", "object")) def test_assign_constant_to_object(self): codestr = """ def f(): x: object = 42 + 1 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "CAST", ("builtins", "object")) def test_assign_try_except_typing(self): codestr = """ def testfunc(): try: pass except Exception as e: pass return 42 """ # We don't do anything special w/ Exception type yet, but it should compile code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_try_except_typing_predeclared(self): codestr = """ def testfunc(): e: Exception try: pass except Exception as e: pass return 42 """ # We don't do anything special w/ Exception type yet, but it should compile code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_try_except_typing_narrowed(self): codestr = """ class E(Exception): pass def testfunc(): e: Exception try: pass except E as e: pass return 42 """ # We don't do anything special w/ Exception type yet, but it should compile code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_try_except_typing_redeclared_after(self): codestr = """ def testfunc(): try: pass except Exception as e: pass e: int = 42 return 42 """ # We don't do anything special w/ Exception type yet, but it should compile code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_try_except_redeclare(self): codestr = """ def testfunc(): e: int try: pass except Exception as e: pass return 42 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_try_except_redeclare_unknown_type(self): codestr = """ def testfunc(): e: int try: pass except UnknownException as e: pass return 42 """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_try_assign_in_except(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: pass except: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), "abc") def test_assign_try_assign_in_second_except(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: pass except TypeError: pass except: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), "abc") def test_assign_try_assign_in_except_with_var(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: pass except TypeError as e: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), "abc") def test_try_except_finally(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: pass except TypeError: pass finally: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), 42) def test_assign_try_assign_in_try(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: x = B() except: pass return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), 42) def test_assign_try_assign_in_finally(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: pass finally: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), 42) def test_assign_try_assign_in_else(self): codestr = """ class B: def f(self): return 42 class D(B): def f(self): return 'abc' def testfunc(): x: B = D() try: pass except: pass else: x = B() return x.f() """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode(f, "INVOKE_METHOD", (("foo", "B", "f"), 0)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), 42) def test_if_optional_reassign(self): codestr = """ class C: pass def testfunc(abc: Optional[C]): if abc is not None: abc = None """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_widening_assign(self): codestr = """ from __static__ import int8, int16, box def testfunc(): x: int16 y: int8 x = y = 42 return box(x), box(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), (42, 42)) def test_unknown_imported_annotation(self): codestr = """ from unknown_mod import foo def testfunc(): x: foo = 42 return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_widening_assign_reassign(self): codestr = """ from __static__ import int8, int16, box def testfunc(): x: int16 y: int8 x = y = 42 x = 257 return box(x), box(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), (257, 42)) def test_widening_assign_reassign_error(self): codestr = """ from __static__ import int8, int16, box def testfunc(): x: int16 y: int8 x = y = 42 y = 128 return box(x), box(y) """ with self.assertRaisesRegex( TypedSyntaxError, "constant 128 is outside of the range -128 to 127 for int8", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_narrowing_assign_literal(self): codestr = """ from __static__ import int8, int16, box def testfunc(): x: int8 y: int16 x = y = 42 return box(x), box(y) """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_narrowing_assign_out_of_range(self): codestr = """ from __static__ import int8, int16, box def testfunc(): x: int8 y: int16 x = y = 300 return box(x), box(y) """ with self.assertRaisesRegex( TypedSyntaxError, "constant 300 is outside of the range -128 to 127 for int8", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_module_primitive(self): codestr = """ from __static__ import int8 x: int8 """ with self.assertRaisesRegex( TypedSyntaxError, "cannot use primitives in global or closure scope" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_implicit_module_primitive(self): codestr = """ from __static__ import int8 x = y = int8(0) """ with self.assertRaisesRegex( TypedSyntaxError, "cannot use primitives in global or closure scope" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_chained_primitive_to_non_primitive(self): codestr = """ from __static__ import int8 def f(): x: object y: int8 = 42 x = y = 42 """ with self.assertRaisesRegex( TypedSyntaxError, "int8 cannot be assigned to object" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_closure_primitive(self): codestr = """ from __static__ import int8 def f(): x: int8 = 0 def g(): return x """ with self.assertRaisesRegex( TypedSyntaxError, "cannot use primitives in global or closure scope" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_nonlocal_primitive(self): codestr = """ from __static__ import int8 def f(): x: int8 = 0 def g(): nonlocal x x = 1 """ with self.assertRaisesRegex( TypedSyntaxError, "cannot use primitives in global or closure scope" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_dynamic_chained_assign_param(self): codestr = """ from __static__ import int16 def testfunc(y): x: int16 x = y = 42 return box(x) """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[int]", "int16") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_dynamic_chained_assign_param_2(self): codestr = """ from __static__ import int16 def testfunc(y): x: int16 y = x = 42 """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("int16", "dynamic") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_dynamic_chained_assign_1(self): codestr = """ from __static__ import int16, box def testfunc(): x: int16 x = y = 42 return box(x) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), 42) def test_dynamic_chained_assign_2(self): codestr = """ from __static__ import int16, box def testfunc(): x: int16 y = x = 42 return box(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), 42) def test_tuple_assign_list(self): codestr = """ from __static__ import int16, box def testfunc(a: int, b: int): x: int y: str x, y = [a, b] """ with self.assertRaisesRegex(TypedSyntaxError, "int cannot be assigned to str"): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_tuple_assign_tuple(self): codestr = """ from __static__ import int16, box def testfunc(a: int, b: int): x: int y: str x, y = a, b """ with self.assertRaisesRegex(TypedSyntaxError, "int cannot be assigned to str"): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_tuple_assign_constant(self): codestr = """ from __static__ import int16, box def testfunc(): x: int y: str x, y = 1, 1 """ with self.assertRaisesRegex( TypedSyntaxError, r"type mismatch: Exact\[int\] cannot be assigned to str", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_optional_cond(self): codestr = """ from typing import Optional class C: def __init__(self): self.field = 42 def f(x: Optional[C]): return x.field if x is not None else None """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_while_optional_cond(self): codestr = """ from typing import Optional class C: def __init__(self): self.field: Optional["C"] = self def f(x: Optional[C]): while x is not None: val: Optional[C] = x.field if val is not None: x = val """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_if_optional_dependent_conditions(self): codestr = """ from typing import Optional class C: def __init__(self): self.field: Optional[C] = None def f(x: Optional[C]) -> C: if x is not None and x.field is not None: return x if x is None: return C() return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_none_attribute_error(self): codestr = """ def f(): x = None return x.foo """ with self.assertRaisesRegex( TypedSyntaxError, "'NoneType' object has no attribute 'foo'" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_none_call(self): codestr = """ def f(): x = None return x() """ with self.assertRaisesRegex( TypedSyntaxError, "'NoneType' object is not callable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_none_subscript(self): codestr = """ def f(): x = None return x[0] """ with self.assertRaisesRegex( TypedSyntaxError, "'NoneType' object is not subscriptable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_none_unaryop(self): codestr = """ def f(): x = None return -x """ with self.assertRaisesRegex( TypedSyntaxError, "bad operand type for unary -: 'NoneType'" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_vector_import(self): codestr = """ from __static__ import int64, Vector def test() -> Vector[int64]: x: Vector[int64] = Vector[int64]() x.append(1) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertEqual(test(), array("L", [1])) def test_vector_assign_non_primitive(self): codestr = """ from __static__ import int64, Vector def test(abc) -> Vector[int64]: x: Vector[int64] = Vector[int64](2) i: int64 = 0 x[i] = abc """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign a dynamic to int64" ): self.compile(codestr) def test_vector_sizes(self): for signed in ["int", "uint"]: for size in ["8", "16", "32", "64"]: with self.subTest(size=size, signed=signed): int_type = f"{signed}{size}" codestr = f""" from __static__ import {int_type}, Vector def test() -> Vector[{int_type}]: x: Vector[{int_type}] = Vector[{int_type}]() y: {int_type} = 1 x.append(y) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] res = test() self.assertEqual(list(res), [1]) def test_vector_invalid_literal(self): codestr = f""" from __static__ import int8, Vector def test() -> Vector[int8]: x: Vector[int8] = Vector[int8]() x.append(128) return x """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int positional argument type mismatch int8", ): self.compile(codestr) def test_vector_wrong_size(self): codestr = f""" from __static__ import int8, int16, Vector def test() -> Vector[int8]: y: int16 = 1 x: Vector[int8] = Vector[int8]() x.append(y) return x """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int16 positional argument type mismatch int8", ): self.compile(codestr) def test_vector_presized(self): codestr = f""" from __static__ import int8, Vector def test() -> Vector[int8]: x: Vector[int8] = Vector[int8](4) x[1] = 1 return x """ with self.in_module(codestr) as mod: f = mod["test"] self.assertEqual(f(), array("b", [0, 1, 0, 0])) def test_array_import(self): codestr = """ from __static__ import int64, Array def test() -> Array[int64]: x: Array[int64] = Array[int64](1) x[0] = 1 return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertEqual(test(), array("L", [1])) def test_array_create(self): codestr = """ from __static__ import int64, Array def test() -> Array[int64]: x: Array[int64] = Array[int64]([1, 3, 5]) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertEqual(test(), array("l", [1, 3, 5])) def test_array_create_failure(self): # todo - in the future we're going to support this, but for now fail it. codestr = """ from __static__ import int64, Array class C: pass def test() -> Array[C]: return Array[C]([1, 3, 5]) """ with self.assertRaisesRegex( TypedSyntaxError, "Invalid Array element type: foo.C" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_array_call_unbound(self): codestr = """ from __static__ import Array def f() -> Array: return Array([1, 2, 3]) """ with self.assertRaisesRegex( TypedSyntaxError, r"create instances of a generic Type\[Exact\[Array\[T\]\]\]", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_array_assign_wrong_type(self): codestr = """ from __static__ import int64, char, Array def test() -> None: x: Array[int64] = Array[char]([48]) """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Exact[Array[char]]", "Array[int64]", ), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_array_subclass_assign(self): codestr = """ from __static__ import int64, Array class MyArray(Array): pass def y(inexact: Array[int64]): exact = Array[int64]([1]) exact = inexact """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Array[int64]", "Exact[Array[int64]]", ), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_array_types(self): codestr = """ from __static__ import ( int8, int16, int32, int64, uint8, uint16, uint32, uint64, char, double, Array ) from typing import Tuple def test() -> Tuple[Array[int64], Array[char], Array[double]]: x1: Array[int8] = Array[int8]([1, 3, -5]) x2: Array[uint8] = Array[uint8]([1, 3, 5]) x3: Array[int16] = Array[int16]([1, -3, 5]) x4: Array[uint16] = Array[uint16]([1, 3, 5]) x5: Array[int32] = Array[int32]([1, 3, 5]) x6: Array[uint32] = Array[uint32]([1, 3, 5]) x7: Array[int64] = Array[int64]([1, 3, 5]) x8: Array[uint64] = Array[uint64]([1, 3, 5]) x9: Array[char] = Array[char]([ord('a')]) x10: Array[double] = Array[double]([1.1, 3.3, 5.5]) x11: Array[float] = Array[float]([1.1, 3.3, 5.5]) arrays = [ x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, ] first_elements = [] for ar in arrays: first_elements.append(ar[0]) return (arrays, first_elements) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] arrays, first_elements = test() exp_arrays = [ array(*args) for args in [ ("h", [1, 3, -5]), ("H", [1, 3, 5]), ("i", [1, -3, 5]), ("I", [1, 3, 5]), ("l", [1, 3, 5]), ("L", [1, 3, 5]), ("q", [1, 3, 5]), ("Q", [1, 3, 5]), ("b", [ord("a")]), ("d", [1.1, 3.3, 5.5]), ("f", [1.1, 3.3, 5.5]), ] ] exp_first_elements = [ar[0] for ar in exp_arrays] for result, expectation in zip(arrays, exp_arrays): self.assertEqual(result, expectation) for result, expectation in zip(first_elements, exp_first_elements): self.assertEqual(result, expectation) def test_assign_type_propagation(self): codestr = """ def test() -> int: x = 5 return x """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_subtype_handling(self): codestr = """ class B: pass class D(B): pass def f(): b = B() b = D() b = B() """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_subtype_handling_fail(self): codestr = """ class B: pass class D(B): pass def f(): d = D() d = B() """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("foo.B", "foo.D")): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_chained(self): codestr = """ def test() -> str: x: str = "hi" y = x = "hello" return y """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_assign_chained_failure_wrong_target_type(self): codestr = """ def test() -> str: x = 1 y = x = "hello" return y """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[str]", "int") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_chained_assign_type_propagation(self): codestr = """ from __static__ import int64, char, Array def test2() -> Array[char]: x = y = Array[char]([48]) return y """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_chained_assign_type_propagation_failure_redefine(self): codestr = """ from __static__ import int64, char, Array def test2() -> Array[char]: x = Array[int64]([54]) x = y = Array[char]([48]) return y """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Exact[Array[char]]", "Exact[Array[int64]]", ), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_chained_assign_type_propagation_failure_redefine_2(self): codestr = """ from __static__ import int64, char, Array def test2() -> Array[char]: x = Array[int64]([54]) y = x = Array[char]([48]) return y """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Exact[Array[char]]", "Exact[Array[int64]]", ), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_chained_assign_type_inference(self): codestr = """ from __static__ import int64, char, Array def test2(): y = x = 4 x = "hello" return y """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[str]", "int") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_chained_assign_type_inference_2(self): codestr = """ from __static__ import int64, char, Array def test2(): y = x = 4 y = "hello" return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[str]", "int") ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_array_inplace_assign(self): codestr = """ from __static__ import Array, int8 def m() -> Array[int8]: a = Array[int8]([1, 3, -5, -1, 7, 22]) a[0] += 1 return a """ with self.in_module(codestr) as mod: m = mod["m"] self.assertEqual(m()[0], 2) def test_array_subscripting_slice(self): codestr = """ from __static__ import Array, int8 def m() -> Array[int8]: a = Array[int8]([1, 3, -5, -1, 7, 22]) return a[1:3] """ self.compile(codestr, StaticCodeGenerator, modname="foo") @skipIf(cinderjit is not None, "can't report error from JIT") def test_load_uninit_module(self): """verify we don't crash if we receive a module w/o a dictionary""" codestr = """ class C: def __init__(self): self.x: Optional[C] = None """ with self.in_module(codestr) as mod: C = mod["C"] class UninitModule(ModuleType): def __init__(self): # don't call super init pass sys.modules[mod["__name__"]] = UninitModule() with self.assertRaisesRegex( TypeError, r"bad name provided for class loader: \('" + mod["__name__"] + r"', 'C'\), not a class", ): C() def test_module_subclass(self): codestr = """ class C: def __init__(self): self.x: Optional[C] = None """ with self.in_module(codestr) as mod: C = mod["C"] class CustomModule(ModuleType): def __getattr__(self, name): if name == "C": return C sys.modules[mod["__name__"]] = CustomModule(mod["__name__"]) c = C() self.assertEqual(c.x, None) def test_invoke_and_raise_noframe_strictmod(self): codestr = """ from __static__.compiler_flags import noframe def x(): raise TypeError() def y(): return x() """ with self.in_strict_module(codestr) as mod: y = mod.y x = mod.x with self.assertRaises(TypeError): y() self.assert_jitted(x) self.assertInBytecode( y, "INVOKE_FUNCTION", ((mod.__name__, "x"), 0), ) def test_override_okay(self): codestr = """ class B: def f(self) -> "B": return self def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] f = mod["f"] class D(B): def f(self): return self x = f(D()) def test_override_override_inherited(self): codestr = """ from typing import Optional class B: def f(self) -> "Optional[B]": return self class D(B): pass def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] D = mod["D"] f = mod["f"] b = B() d = D() self.assertEqual(f(b), b) self.assertEqual(f(d), d) D.f = lambda self: None self.assertEqual(f(b), b) self.assertEqual(f(d), None) def test_override_bad_ret(self): codestr = """ class B: def f(self) -> "B": return self def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] f = mod["f"] class D(B): def f(self): return 42 with self.assertRaisesRegex( TypeError, "unexpected return type from D.f, expected B, got int" ): f(D()) def test_dynamic_base(self): nonstatic_code = """ class Foo: pass """ with self.in_module( nonstatic_code, code_gen=PythonCodeGenerator, name="nonstatic" ): codestr = """ from nonstatic import Foo class A(Foo): def __init__(self): self.x = 1 def f(self) -> int: return self.x def f(x: A) -> int: return x.f() """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "INVOKE_METHOD") a = mod["A"]() self.assertEqual(f(a), 1) # x is a data descriptor, it takes precedence a.__dict__["x"] = 100 self.assertEqual(f(a), 1) # but methods are normal descriptors, instance # attributes should take precedence a.__dict__["f"] = lambda: 42 self.assertEqual(f(a), 42) def test_invoke_type_modified(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] self.assertEqual(x(C()), 2) C.f = lambda self: 42 self.assertEqual(x(C()), 84) def test_invoke_type_modified_pre_invoke(self): codestr = """ class C: def f(self): return 1 def x(c: C): x = c.f() x += c.f() return x """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") x = self.find_code(code, "x") self.assertInBytecode(x, "INVOKE_METHOD", (("foo", "C", "f"), 0)) with self.in_module(codestr) as mod: x, C = mod["x"], mod["C"] C.f = lambda self: 42 self.assertEqual(x(C()), 84) def test_override_modified_base_class(self): codestr = """ class B: def f(self): return 1 def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] f = mod["f"] B.f = lambda self: 2 class D(B): def f(self): return 3 d = D() self.assertEqual(f(d), 3) def test_override_remove_base_method(self): codestr = """ from typing import Optional class B: def f(self) -> "B": return self class D(B): pass def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] D = mod["D"] f = mod["f"] b = B() d = D() self.assertEqual(f(b), b) self.assertEqual(f(d), d) del B.f with self.assertRaises(AttributeError): f(b) with self.assertRaises(AttributeError): f(d) def test_override_remove_derived_method(self): codestr = """ from typing import Optional class B: def f(self) -> "Optional[B]": return self class D(B): def f(self) -> Optional["B"]: return None def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] D = mod["D"] f = mod["f"] b = B() d = D() self.assertEqual(f(b), b) self.assertEqual(f(d), None) del D.f self.assertEqual(f(b), b) self.assertEqual(f(d), d) def test_override_remove_method(self): codestr = """ from typing import Optional class B: def f(self) -> "Optional[B]": return self def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] f = mod["f"] b = B() self.assertEqual(f(b), b) del B.f with self.assertRaises(AttributeError): f(b) def test_override_remove_method_add_type_check(self): codestr = """ from typing import Optional class B: def f(self) -> "B": return self def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] f = mod["f"] b = B() self.assertEqual(f(b), b) del B.f with self.assertRaises(AttributeError): f(b) B.f = lambda self: None with self.assertRaises(TypeError): f(b) def test_override_update_derived(self): codestr = """ from typing import Optional class B: def f(self) -> "Optional[B]": return self class D(B): pass def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] D = mod["D"] f = mod["f"] b = B() d = D() self.assertEqual(f(b), b) self.assertEqual(f(d), d) B.f = lambda self: None self.assertEqual(f(b), None) self.assertEqual(f(d), None) def test_override_update_derived_2(self): codestr = """ from typing import Optional class B: def f(self) -> "Optional[B]": return self class D1(B): pass class D(D1): pass def f(x: B): return x.f() """ with self.in_module(codestr) as mod: B = mod["B"] D = mod["D"] f = mod["f"] b = B() d = D() self.assertEqual(f(b), b) self.assertEqual(f(d), d) B.f = lambda self: None self.assertEqual(f(b), None) self.assertEqual(f(d), None) def test_method_prologue(self): codestr = """ def f(x: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (0, ("builtins", "str"))) with self.assertRaisesRegex( TypeError, ".*expected 'str' for argument x, got 'int'" ): f(42) def test_method_prologue_2(self): codestr = """ def f(x, y: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (1, ("builtins", "str"))) with self.assertRaisesRegex( TypeError, ".*expected 'str' for argument y, got 'int'" ): f("abc", 42) def test_method_prologue_3(self): codestr = """ def f(x: int, y: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode( f, "CHECK_ARGS", (0, ("builtins", "int"), 1, ("builtins", "str")) ) with self.assertRaisesRegex( TypeError, ".*expected 'str' for argument y, got 'int'" ): f(42, 42) def test_method_prologue_posonly(self): codestr = """ def f(x: int, /, y: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode( f, "CHECK_ARGS", (0, ("builtins", "int"), 1, ("builtins", "str")) ) with self.assertRaisesRegex( TypeError, ".*expected 'str' for argument y, got 'int'" ): f(42, 42) def test_method_prologue_shadowcode(self): codestr = """ def f(x, y: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (1, ("builtins", "str"))) for i in range(100): self.assertEqual(f("abc", "abc"), 42) with self.assertRaisesRegex( TypeError, ".*expected 'str' for argument y, got 'int'" ): f("abc", 42) def test_method_prologue_shadowcode_2(self): codestr = """ def f(x: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (0, ("builtins", "str"))) for i in range(100): self.assertEqual(f("abc"), 42) with self.assertRaisesRegex( TypeError, ".*expected 'str' for argument x, got 'int'" ): f(42) def test_method_prologue_no_annotation(self): codestr = """ def f(x): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", ()) self.assertEqual(f("abc"), 42) def test_method_prologue_kwonly(self): codestr = """ def f(*, x: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (0, ("builtins", "str"))) with self.assertRaisesRegex( TypeError, "f expected 'str' for argument x, got 'int'" ): f(x=42) def test_method_prologue_kwonly_2(self): codestr = """ def f(x, *, y: str): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (1, ("builtins", "str"))) with self.assertRaisesRegex( TypeError, "f expected 'str' for argument y, got 'object'" ): f(1, y=object()) def test_method_prologue_kwonly_3(self): codestr = """ def f(x, *, y: str, z=1): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (1, ("builtins", "str"))) with self.assertRaisesRegex( TypeError, "f expected 'str' for argument y, got 'object'" ): f(1, y=object()) def test_method_prologue_kwonly_4(self): codestr = """ def f(x, *, y: str, **rest): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", (1, ("builtins", "str"))) with self.assertRaisesRegex( TypeError, "f expected 'str' for argument y, got 'object'" ): f(1, y=object(), z=2) def test_method_prologue_kwonly_no_annotation(self): codestr = """ def f(*, x): return 42 """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CHECK_ARGS", ()) f(x=42) def test_package_no_parent(self): codestr = """ class C: def f(self): return 42 """ with self.in_module( codestr, code_gen=StaticCodeGenerator, name="package_no_parent.child" ) as mod: C = mod["C"] self.assertInBytecode( C.f, "CHECK_ARGS", (0, ("package_no_parent.child", "C")) ) self.assertEqual(C().f(), 42) def test_direct_super_init(self): value = 42 expected = value codestr = f""" class Obj: pass class C: def __init__(self, x: Obj): pass class D: def __init__(self): C.__init__(None) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: None positional argument type mismatch foo.C", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_unknown_attr(self): value = 42 expected = value codestr = f""" class C: pass def f(): return C.foo """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "LOAD_ATTR", "foo") def test_descriptor_access(self): value = 42 expected = value codestr = f""" class Obj: abc: int class C: x: Obj def f(): return C.x.abc """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "LOAD_ATTR", "abc") self.assertNotInBytecode(f, "LOAD_FIELD") @skipIf(not path.exists(RICHARDS_PATH), "richards not found") def test_richards(self): with open(RICHARDS_PATH) as f: codestr = f.read() with self.in_module(codestr) as mod: Richards = mod["Richards"] self.assertTrue(Richards().run(1)) def test_unknown_isinstance_bool_ret(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def __eq__(self, other: Any) -> bool: return isinstance(other, C) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] x = C("abc") y = C("foo") self.assertTrue(x == y) def test_unknown_issubclass_bool_ret(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def __eq__(self, other: Any) -> bool: return issubclass(type(other), C) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] x = C("abc") y = C("foo") self.assertTrue(x == y) def test_unknown_isinstance_narrows(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def testfunc(x): if isinstance(x, C): return x.x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: testfunc = mod["testfunc"] self.assertInBytecode(testfunc, "LOAD_FIELD", (mod["__name__"], "C", "x")) def test_unknown_isinstance_narrows_class_attr(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def f(self, other) -> str: if isinstance(other, self.__class__): return other.x return '' """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] self.assertInBytecode( C.f, "LOAD_FIELD", (mod["__name__"], "C", "x"), ) def test_unknown_isinstance_narrows_class_attr_dynamic(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def f(self, other, unknown): if isinstance(other, unknown.__class__): return other.x return '' """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] self.assertInBytecode(C.f, "LOAD_ATTR", "x") def test_unknown_isinstance_narrows_else_correct(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def testfunc(x): if isinstance(x, C): pass else: return x.x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: testfunc = mod["testfunc"] self.assertNotInBytecode( testfunc, "LOAD_FIELD", (mod["__name__"], "C", "x") ) def test_narrow_while_break(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: while x is None: break return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Optional[int]", "int"), ): self.compile(codestr) def test_narrow_while_if_break_else_return(self): codestr = """ from typing import Optional def f(x: Optional[int], y: int) -> int: while x is None: if y > 0: break else: return 42 return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Optional[int]", "int"), ): self.compile(codestr) def test_narrow_while_break_if(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: while True: if x is None: break return x """ self.compile(codestr) def test_narrow_while_continue_if(self): codestr = """ from typing import Optional def f(x: Optional[int]) -> int: while True: if x is None: continue return x """ self.compile(codestr) def test_unknown_param_ann(self): codestr = """ from typing import Any class C: def __init__(self, x: str): self.x: str = x def __eq__(self, other: Any) -> bool: return False """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] x = C("abc") self.assertInBytecode(C.__eq__, "CHECK_ARGS", (0, (mod["__name__"], "C"))) self.assertNotEqual(x, x) def test_class_init_kw(self): codestr = """ class C: def __init__(self, x: str): self.x: str = x def f(): x = C(x='abc') """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "CALL_FUNCTION_KW", 1) def test_ret_type_cast(self): codestr = """ from typing import Any def testfunc(x: str, y: str) -> bool: return x == y """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["testfunc"] self.assertEqual(f("abc", "abc"), True) self.assertInBytecode(f, "CAST", ("builtins", "bool")) def test_bind_boolop_type(self): codestr = """ from typing import Any class C: def f(self) -> bool: return True def g(self) -> bool: return False def x(self) -> bool: return self.f() and self.g() def y(self) -> bool: return self.f() or self.g() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] c = C() self.assertEqual(c.x(), False) self.assertEqual(c.y(), True) def test_decorated_function_ignored_class(self): codestr = """ class C: @property def x(self): return lambda: 42 def y(self): return self.x() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] self.assertNotInBytecode(C.y, "INVOKE_METHOD") self.assertEqual(C().y(), 42) def test_decorated_function_ignored(self): codestr = """ class C: pass def mydecorator(x): return C @mydecorator def f(): return 42 def g(): return f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] g = mod["g"] self.assertNotInBytecode(g, "INVOKE_FUNCTION") self.assertEqual(type(g()), C) def test_static_function_invoke(self): codestr = """ class C: @staticmethod def f(): return 42 def f(): return C.f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode( f, "INVOKE_FUNCTION", ((mod["__name__"], "C", "f"), 0) ) self.assertEqual(f(), 42) def test_static_function_invoke_on_instance(self): codestr = """ class C: @staticmethod def f(): return 42 def f(): return C().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode( f, "INVOKE_FUNCTION", ((mod["__name__"], "C", "f"), 0), ) self.assertEqual(f(), 42) def test_spamobj_no_params(self): codestr = """ from xxclassloader import spamobj def f(): x = spamobj() """ with self.assertRaisesRegex( TypedSyntaxError, r"cannot create instances of a generic Type\[xxclassloader.spamobj\[T\]\]", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_spamobj_error(self): codestr = """ from xxclassloader import spamobj def f(): x = spamobj[int]() return x.error(1) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] with self.assertRaisesRegex(TypeError, "no way!"): f() def test_spamobj_no_error(self): codestr = """ from xxclassloader import spamobj def testfunc(): x = spamobj[int]() return x.error(0) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["testfunc"] self.assertEqual(f(), None) def test_generic_type_box_box(self): codestr = """ from xxclassloader import spamobj def testfunc(): x = spamobj[str]() return (x.getint(), ) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int64 is an invalid return type, expected dynamic", ): code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_generic_type(self): codestr = """ from xxclassloader import spamobj from __static__ import box def testfunc(): x = spamobj[str]() x.setstate('abc') x.setint(42) return (x.getstate(), box(x.getint())) """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode( f, "INVOKE_METHOD", ((("xxclassloader", "spamobj", (("builtins", "str"),), "setstate"), 1)), ) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), ("abc", 42)) def test_ret_void(self): codestr = """ from xxclassloader import spamobj from __static__ import box def testfunc(): x = spamobj[str]() y = x.setstate('abc') return y """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(code, "testfunc") self.assertInBytecode( f, "INVOKE_METHOD", ((("xxclassloader", "spamobj", (("builtins", "str"),), "setstate"), 1)), ) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(test(), None) def test_user_enumerate_list(self): codestr = """ from __static__ import int64, box, clen def f(x: list): i: int64 = 0 res = [] while i < clen(x): elem = x[i] res.append((box(i), elem)) i += 1 return res """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "SEQUENCE_GET", SEQ_LIST_INEXACT) res = f([1, 2, 3]) self.assertEqual(res, [(0, 1), (1, 2), (2, 3)]) def test_user_enumerate_list_nooverride(self): class mylist(list): pass codestr = """ from __static__ import int64, box, clen def f(x: list): i: int64 = 0 res = [] while i < clen(x): elem = x[i] res.append((box(i), elem)) i += 1 return res """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "SEQUENCE_GET", SEQ_LIST_INEXACT) res = f(mylist([1, 2, 3])) self.assertEqual(res, [(0, 1), (1, 2), (2, 3)]) def test_user_enumerate_list_subclass(self): class mylist(list): def __getitem__(self, idx): return list.__getitem__(self, idx) + 1 codestr = """ from __static__ import int64, box, clen def f(x: list): i: int64 = 0 res = [] while i < clen(x): elem = x[i] res.append((box(i), elem)) i += 1 return res """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "SEQUENCE_GET", SEQ_LIST_INEXACT) res = f(mylist([1, 2, 3])) self.assertEqual(res, [(0, 2), (1, 3), (2, 4)]) def test_list_assign_subclass(self): class mylist(list): def __setitem__(self, idx, value): return list.__setitem__(self, idx, value + 1) codestr = """ from __static__ import int64, box, clen def f(x: list): i: int64 = 0 x[i] = 42 """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "SEQUENCE_SET", SEQ_LIST_INEXACT) l = mylist([0]) f(l) self.assertEqual(l[0], 43) def test_inexact_list_negative(self): codestr = """ from __static__ import int64, box, clen def f(x: list): i: int64 = 1 return x[-i] """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "SEQUENCE_GET", SEQ_LIST_INEXACT) res = f([1, 2, 3]) self.assertEqual(res, 3) def test_inexact_list_negative_small_int(self): codestr = """ from __static__ import int64, box, clen def f(x: list): i: int8 = 1 return x[-i] """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] res = f([1, 2, 3]) self.assertEqual(res, 3) def test_inexact_list_large_unsigned(self): codestr = """ from __static__ import uint64 def f(x: list): i: uint64 = 0xffffffffffffffff return x[i] """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: uint64 cannot be assigned to dynamic" ): self.compile(codestr) def test_named_tuple(self): codestr = """ from typing import NamedTuple class C(NamedTuple): x: int y: str def myfunc(x: C): return x.x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["myfunc"] self.assertNotInBytecode(f, "LOAD_FIELD") def test_generic_type_error(self): codestr = """ from xxclassloader import spamobj def testfunc(): x = spamobj[str]() x.setstate(42) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: Exact\\[int\\] positional argument type mismatch str", ): code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_generic_optional_type_param(self): codestr = """ from xxclassloader import spamobj def testfunc(): x = spamobj[str]() x.setstateoptional(None) """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_generic_optional_type_param_2(self): codestr = """ from xxclassloader import spamobj def testfunc(): x = spamobj[str]() x.setstateoptional('abc') """ code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_generic_optional_type_param_error(self): codestr = """ from xxclassloader import spamobj def testfunc(): x = spamobj[str]() x.setstateoptional(42) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: Exact\\[int\\] positional argument type mismatch Optional\\[str\\]", ): code = self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_nested_dict(self): codestr = """ from __static__ import CheckedDict class B: pass class D(B): pass def testfunc(): x = CheckedDict[B, int]({B():42, D():42}) y = CheckedDict[int, CheckedDict[B, int]]({42: x}) return y """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] self.assertEqual(type(test()), chkdict[int, chkdict[B, int]]) def test_compile_dict_setdefault(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[int, str]({42: 'abc', }) x.setdefault(100, 43) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: Exact\\[int\\] positional argument type mismatch Optional\\[str\\]", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_dict_get(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[int, str]({42: 'abc', }) x.get(42, 42) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: Exact\\[int\\] positional argument type mismatch Optional\\[str\\]", ): self.compile(codestr, StaticCodeGenerator, modname="foo") codestr = """ from __static__ import CheckedDict class B: pass class D(B): pass def testfunc(): x = CheckedDict[B, int]({B():42, D():42}) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] self.assertEqual(type(test()), chkdict[B, int]) def test_compile_dict_setitem(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[int, str]({1:'abc'}) x.__setitem__(2, 'def') return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] x = test() self.assertInBytecode( test, "INVOKE_FUNCTION", ( ( "__static__", "chkdict", (("builtins", "int"), ("builtins", "str")), "__setitem__", ), 3, ), ) self.assertEqual(x, {1: "abc", 2: "def"}) def test_compile_dict_setitem_subscr(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[int, str]({1:'abc'}) x[2] = 'def' return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] x = test() self.assertInBytecode( test, "INVOKE_METHOD", ( ( "__static__", "chkdict", (("builtins", "int"), ("builtins", "str")), "__setitem__", ), 2, ), ) self.assertEqual(x, {1: "abc", 2: "def"}) def test_compile_generic_dict_getitem_bad_type(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[str, int]({"abc": 42}) return x[42] """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[int]", "str"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_generic_dict_setitem_bad_type(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[str, int]({"abc": 42}) x[42] = 42 """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[int]", "str"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_generic_dict_setitem_bad_type_2(self): codestr = """ from __static__ import CheckedDict def testfunc(): x = CheckedDict[str, int]({"abc": 42}) x["foo"] = "abc" """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[str]", "int"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_checked_dict_shadowcode(self): codestr = """ from __static__ import CheckedDict class B: pass class D(B): pass def testfunc(): x = CheckedDict[B, int]({B():42, D():42}) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] for i in range(200): self.assertEqual(type(test()), chkdict[B, int]) def test_compile_checked_dict_optional(self): codestr = """ from __static__ import CheckedDict from typing import Optional def testfunc(): x = CheckedDict[str, str | None]({ 'x': None, 'y': 'z' }) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["testfunc"] x = f() x["z"] = None self.assertEqual(type(x), chkdict[str, str | None]) def test_compile_checked_dict_bad_annotation(self): codestr = """ from __static__ import CheckedDict def testfunc(): x: 42 = CheckedDict[str, str]({'abc':'abc'}) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), chkdict[str, str]) def test_compile_checked_dict_ann_differs(self): codestr = """ from __static__ import CheckedDict def testfunc(): x: CheckedDict[int, int] = CheckedDict[str, str]({'abc':'abc'}) return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Exact[chkdict[str, str]]", "chkdict[int, int]", ), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_checked_dict_ann_differs_2(self): codestr = """ from __static__ import CheckedDict def testfunc(): x: int = CheckedDict[str, str]({'abc':'abc'}) return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[chkdict[str, str]]", "int"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_checked_dict_opt_out(self): codestr = """ from __static__.compiler_flags import nonchecked_dicts class B: pass class D(B): pass def testfunc(): x = {B():42, D():42} return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] self.assertEqual(type(test()), dict) def test_compile_checked_dict_explicit_dict(self): codestr = """ from __static__ import pydict class B: pass class D(B): pass def testfunc(): x: pydict = {B():42, D():42} return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), dict) def test_compile_checked_dict_reversed(self): codestr = """ from __static__ import CheckedDict class B: pass class D(B): pass def testfunc(): x = CheckedDict[B, int]({D():42, B():42}) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] self.assertEqual(type(test()), chkdict[B, int]) def test_compile_checked_dict_type_specified(self): codestr = """ from __static__ import CheckedDict class B: pass class D(B): pass def testfunc(): x: CheckedDict[B, int] = CheckedDict[B, int]({D():42}) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] self.assertEqual(type(test()), chkdict[B, int]) def test_compile_checked_dict_with_annotation_comprehension(self): codestr = """ from __static__ import CheckedDict def testfunc(): x: CheckedDict[int, object] = {int(i): object() for i in range(1, 5)} return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), chkdict[int, object]) def test_compile_checked_dict_with_annotation(self): codestr = """ from __static__ import CheckedDict class B: pass def testfunc(): x: CheckedDict[B, int] = {B():42} return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] B = mod["B"] self.assertEqual(type(test()), chkdict[B, int]) def test_compile_checked_dict_with_annotation_wrong_value_type(self): codestr = """ from __static__ import CheckedDict class B: pass def testfunc(): x: CheckedDict[B, int] = {B():'hi'} return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Exact[chkdict[foo.B, Exact[str]]]", "chkdict[foo.B, int]", ), ): self.compile(codestr, modname="foo") def test_compile_checked_dict_with_annotation_wrong_key_type(self): codestr = """ from __static__ import CheckedDict class B: pass def testfunc(): x: CheckedDict[B, int] = {object():42} return x """ with self.assertRaisesRegex( TypedSyntaxError, type_mismatch( "Exact[chkdict[object, Exact[int]]]", "chkdict[foo.B, int]", ), ): self.compile(codestr, modname="foo") def test_compile_checked_dict_wrong_unknown_type(self): codestr = """ def f(x: int): return x def testfunc(iter): return f({x:42 for x in iter}) """ with self.assertRaisesRegex( TypedSyntaxError, "positional argument type mismatch" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_compile_checked_dict_opt_out_dict_call(self): codestr = """ from __static__.compiler_flags import nonchecked_dicts def testfunc(): x = dict(x=42) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), dict) def test_compile_checked_dict_explicit_dict_as_dict(self): codestr = """ from __static__ import pydict as dict class B: pass class D(B): pass def testfunc(): x: dict = {B():42, D():42} return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), dict) def test_compile_checked_dict_from_dict_call(self): codestr = """ def testfunc(): x = dict(x=42) return x """ with self.assertRaisesRegex( TypeError, "cannot create 'dict\\[K, V\\]' instances" ): with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] test() def test_compile_checked_dict_from_dict_call_2(self): codestr = """ def testfunc(): x = dict[str, int](x=42) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), chkdict[str, int]) def test_compile_checked_dict_from_dict_call_3(self): # we emit the chkdict import first before future annotations, but that # should be fine as we're the compiler. codestr = """ from __future__ import annotations def testfunc(): x = dict[str, int](x=42) return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["testfunc"] self.assertEqual(type(test()), chkdict[str, int]) def test_patch_function(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): g() with patch(f"{mod['__name__']}.f", autospec=True, return_value=100) as p: self.assertEqual(g(), 100) def test_patch_async_function(self): codestr = """ class C: async def f(self) -> int: return 42 def g(self): return self.f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] c = C() for i in range(100): try: c.g().send(None) except StopIteration as e: self.assertEqual(e.args[0], 42) with patch(f"{mod['__name__']}.C.f", autospec=True, return_value=100) as p: try: c.g().send(None) except StopIteration as e: self.assertEqual(e.args[0], 100) def test_patch_parentclass_slot(self): codestr = """ class A: def f(self) -> int: return 3 class B(A): pass def a_f_invoker() -> int: return A().f() def b_f_invoker() -> int: return B().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: A = mod["A"] a_f_invoker = mod["a_f_invoker"] b_f_invoker = mod["b_f_invoker"] setattr(A, "f", lambda _: 7) self.assertEqual(a_f_invoker(), 7) self.assertEqual(b_f_invoker(), 7) def test_self_patching_function(self): codestr = """ def x(d, d2=1): pass def removeit(d): global f f = x def f(d): if d: removeit(d) return 42 def g(d): return f(d) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] f = mod["f"] import weakref wr = weakref.ref(f, lambda *args: self.assertEqual(i, -1)) del f for i in range(100): g(False) i = -1 self.assertEqual(g(True), 42) i = 0 self.assertEqual(g(True), None) def test_patch_function_unwatchable_dict(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): g() with patch( f"{mod['__name__']}.f", autospec=True, return_value=100, ) as p: mod[42] = 1 self.assertEqual(g(), 100) def test_patch_function_deleted_func(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): g() del mod["f"] with self.assertRaisesRegex( TypeError, re.escape(f"unknown function ('{mod['__name__']}', 'f')"), ): g() def test_patch_static_function(self): codestr = """ class C: @staticmethod def f(): return 42 def g(): return C.f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): self.assertEqual(g(), 42) with patch(f"{mod['__name__']}.C.f", autospec=True, return_value=100) as p: self.assertEqual(g(), 100) def test_patch_static_function_non_autospec(self): codestr = """ class C: @staticmethod def f(): return 42 def g(): return C.f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): g() with patch(f"{mod['__name__']}.C.f", return_value=100) as p: self.assertEqual(g(), 100) def test_patch_primitive_ret_type(self): for type_name, value, patched in [ ("cbool", True, False), ("cbool", False, True), ("int8", 0, 1), ("int16", 0, 1), ("int32", 0, 1), ("int64", 0, 1), ("uint8", 0, 1), ("uint16", 0, 1), ("uint32", 0, 1), ("uint64", 0, 1), ]: with self.subTest(type_name=type, value=value, patched=patched): codestr = f""" from __static__ import {type_name}, box class C: def f(self) -> {type_name}: return {value!r} def g(): return box(C().f()) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): self.assertEqual(g(), value) with patch(f"{mod['__name__']}.C.f", return_value=patched) as p: self.assertEqual(g(), patched) def test_patch_primitive_ret_type_overflow(self): codestr = f""" from __static__ import int8, box class C: def f(self) -> int8: return 1 def g(): return box(C().f()) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): self.assertEqual(g(), 1) with patch(f"{mod['__name__']}.C.f", return_value=256) as p: with self.assertRaisesRegex( OverflowError, "unexpected return type from C.f, expected " "int8, got out-of-range int \\(256\\)", ): g() def test_invoke_frozen_type(self): codestr = """ from cinder import freeze_type @freeze_type class C: @staticmethod def f(): return 42 def g(): return C.f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] for i in range(100): self.assertEqual(g(), 42) def test_invoke_strict_module(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_strict_module(codestr) as mod: g = mod.g for i in range(100): self.assertEqual(g(), 42) self.assertInBytecode(g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 0)) def test_invoke_with_cell(self): codestr = """ def f(l: list): x = 2 return [x + y for y in l] def g(): return f([1,2,3]) """ with self.in_strict_module(codestr) as mod: g = mod.g self.assertEqual(g(), [3, 4, 5]) self.assertInBytecode(g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 1)) def test_invoke_with_cell_arg(self): codestr = """ def f(l: list, x: int): return [x + y for y in l] def g(): return f([1,2,3], 2) """ with self.in_strict_module(codestr) as mod: g = mod.g self.assertEqual(g(), [3, 4, 5]) self.assertInBytecode(g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 2)) def test_invoke_all_reg_args(self): codestr = """ def target(a, b, c, d, e, f): return a * 2 + b * 3 + c * 4 + d * 5 + e * 6 + f * 7 def testfunc(): return target(1,2,3,4,5,6) """ with self.in_strict_module(codestr) as mod: f = mod.testfunc self.assertInBytecode( f, "INVOKE_FUNCTION", ((mod.__name__, "target"), 6), ) self.assertEqual(f(), 112) def test_invoke_all_extra_args(self): codestr = """ def target(a, b, c, d, e, f, g): return a * 2 + b * 3 + c * 4 + d * 5 + e * 6 + f * 7 + g def testfunc(): return target(1,2,3,4,5,6,7) """ with self.in_strict_module(codestr) as mod: f = mod.testfunc self.assertInBytecode( f, "INVOKE_FUNCTION", ((mod.__name__, "target"), 7), ) self.assertEqual(f(), 119) def test_invoke_strict_module_deep(self): codestr = """ def f0(): return 42 def f1(): return f0() def f2(): return f1() def f3(): return f2() def f4(): return f3() def f5(): return f4() def f6(): return f5() def f7(): return f6() def f8(): return f7() def f9(): return f8() def f10(): return f9() def f11(): return f10() def g(): return f11() """ with self.in_strict_module(codestr) as mod: g = mod.g self.assertEqual(g(), 42) self.assertEqual(g(), 42) self.assertInBytecode(g, "INVOKE_FUNCTION", ((mod.__name__, "f11"), 0)) def test_invoke_strict_module_deep_unjitable(self): codestr = """ def f0(): return 42 def f1(): from sys import * return f0() def f2(): return f1() def f3(): return f2() def f4(): return f3() def f5(): return f4() def f6(): return f5() def f7(): return f6() def f8(): return f7() def f9(): return f8() def f10(): return f9() def f11(): return f10() def g(x): if x: return 0 return f11() """ with self.in_strict_module(codestr) as mod: g = mod.g self.assertEqual(g(True), 0) # we should have done some level of pre-jitting self.assert_not_jitted(mod.f2) self.assert_not_jitted(mod.f1) self.assert_not_jitted(mod.f0) [self.assert_jitted(getattr(mod, f"f{i}")) for i in range(3, 12)] self.assertEqual(g(False), 42) self.assertInBytecode( g, "INVOKE_FUNCTION", ((mod.__name__, "f11"), 0), ) def test_invoke_strict_module_deep_unjitable_many_args(self): codestr = """ def f0(): return 42 def f1(a, b, c, d, e, f, g, h): from sys import * return f0() - a + b - c + d - e + f - g + h - 4 def f2(): return f1(1,2,3,4,5,6,7,8) def f3(): return f2() def f4(): return f3() def f5(): return f4() def f6(): return f5() def f7(): return f6() def f8(): return f7() def f9(): return f8() def f10(): return f9() def f11(): return f10() def g(): return f11() """ with self.in_strict_module(codestr) as mod: g = mod.g f1 = mod.f1 self.assertEqual(g(), 42) self.assertEqual(g(), 42) self.assertInBytecode( g, "INVOKE_FUNCTION", ((mod.__name__, "f11"), 0), ) self.assert_not_jitted(f1) def test_invoke_strict_module_recursive(self): codestr = """ def fib(number): if number <= 1: return number return(fib(number-1) + fib(number-2)) """ with self.in_strict_module(codestr) as mod: fib = mod.fib self.assertInBytecode( fib, "INVOKE_FUNCTION", ((mod.__name__, "fib"), 1), ) self.assertEqual(fib(4), 3) def test_invoke_strict_module_mutual_recursive(self): codestr = """ def fib1(number): if number <= 1: return number return(fib(number-1) + fib(number-2)) def fib(number): if number <= 1: return number return(fib1(number-1) + fib1(number-2)) """ with self.in_strict_module(codestr) as mod: fib = mod.fib fib1 = mod.fib1 self.assertInBytecode( fib, "INVOKE_FUNCTION", ((mod.__name__, "fib1"), 1), ) self.assertInBytecode( fib1, "INVOKE_FUNCTION", ((mod.__name__, "fib"), 1), ) self.assertEqual(fib(0), 0) self.assert_jitted(fib1) self.assertEqual(fib(4), 3) def test_invoke_strict_module_pre_invoked(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_strict_module(codestr) as mod: self.assertEqual(mod.f(), 42) self.assert_jitted(mod.f) g = mod.g self.assertEqual(g(), 42) self.assertInBytecode( g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 0), ) def test_invoke_strict_module_patching(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_strict_module(codestr, enable_patching=True) as mod: g = mod.g for i in range(100): self.assertEqual(g(), 42) self.assertInBytecode(g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 0)) mod.patch("f", lambda: 100) self.assertEqual(g(), 100) def test_invoke_patch_non_vectorcall(self): codestr = """ def f(): return 42 def g(): return f() """ with self.in_strict_module(codestr, enable_patching=True) as mod: g = mod.g self.assertInBytecode(g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 0)) self.assertEqual(g(), 42) mod.patch("f", Mock(return_value=100)) self.assertEqual(g(), 100) def test_patch_method(self): codestr = """ class C: def f(self): pass def g(): return C().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] C = mod["C"] orig = C.f C.f = lambda *args: args for i in range(100): v = g() self.assertEqual(type(v), tuple) self.assertEqual(type(v[0]), C) C.f = orig self.assertEqual(g(), None) def test_patch_method_ret_none_error(self): codestr = """ class C: def f(self) -> None: pass def g(): return C().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] C = mod["C"] C.f = lambda *args: args with self.assertRaisesRegex( TypeError, "unexpected return type from C.f, expected NoneType, got tuple", ): v = g() def test_patch_method_ret_none(self): codestr = """ class C: def f(self) -> None: pass def g(): return C().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] C = mod["C"] C.f = lambda *args: None self.assertEqual(g(), None) def test_patch_method_bad_ret(self): codestr = """ class C: def f(self) -> int: return 42 def g(): return C().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: g = mod["g"] C = mod["C"] C.f = lambda *args: "abc" with self.assertRaisesRegex( TypeError, "unexpected return type from C.f, expected int, got str" ): v = g() def test_primitive_args_funcdef(self): codestr = """ from __static__ import int8, box def n(val: int8): return box(val) def x(): y: int8 = 42 return n(y) """ with self.in_strict_module(codestr) as mod: n = mod.n x = mod.x self.assertEqual(x(), 42) self.assertEqual(mod.n(-128), -128) self.assertEqual(mod.n(127), 127) with self.assertRaises(OverflowError): print(mod.n(-129)) with self.assertRaises(OverflowError): print(mod.n(128)) def test_primitive_args_funcdef_unjitable(self): codestr = """ from __static__ import int8, box def n(val: int8): try: from sys import * except: pass return box(val) def x(): y: int8 = 42 return n(y) """ with self.in_strict_module(codestr) as mod: n = mod.n x = mod.x self.assertEqual(x(), 42) self.assertEqual(mod.n(-128), -128) self.assertEqual(mod.n(127), 127) with self.assertRaises(OverflowError): print(mod.n(-129)) with self.assertRaises(OverflowError): print(mod.n(128)) def test_primitive_args_funcdef_too_many_args(self): codestr = """ from __static__ import int8, box def n(x: int8): return box(x) """ with self.in_strict_module(codestr) as mod: n = mod.n with self.assertRaises(TypeError): print(mod.n(-128, x=2)) with self.assertRaises(TypeError): print(mod.n(-128, 2)) def test_primitive_args_funcdef_missing_starargs(self): codestr = """ from __static__ import int8, box def x(val: int8, *foo): return box(val), foo def y(val: int8, **foo): return box(val), foo """ with self.in_strict_module(codestr) as mod: self.assertEqual(mod.x(-128), (-128, ())) self.assertEqual(mod.y(-128), (-128, {})) def test_primitive_args_many_args(self): codestr = """ from __static__ import int8, int16, int32, int64, uint8, uint16, uint32, uint64, box def x(i8: int8, i16: int16, i32: int32, i64: int64, u8: uint8, u16: uint16, u32: uint32, u64: uint64): return box(i8), box(i16), box(i32), box(i64), box(u8), box(u16), box(u32), box(u64) def y(): return x(1,2,3,4,5,6,7,8) """ with self.in_strict_module(codestr) as mod: self.assertInBytecode(mod.y, "INVOKE_FUNCTION", ((mod.__name__, "x"), 8)) self.assertEqual(mod.y(), (1, 2, 3, 4, 5, 6, 7, 8)) self.assertEqual(mod.x(1, 2, 3, 4, 5, 6, 7, 8), (1, 2, 3, 4, 5, 6, 7, 8)) def test_primitive_args_sizes(self): cases = [ ("cbool", True, False), ("cbool", False, False), ("int8", (1 << 7), True), ("int8", (-1 << 7) - 1, True), ("int8", -1 << 7, False), ("int8", (1 << 7) - 1, False), ("int16", (1 << 15), True), ("int16", (-1 << 15) - 1, True), ("int16", -1 << 15, False), ("int16", (1 << 15) - 1, False), ("int32", (1 << 31), True), ("int32", (-1 << 31) - 1, True), ("int32", -1 << 31, False), ("int32", (1 << 31) - 1, False), ("int64", (1 << 63), True), ("int64", (-1 << 63) - 1, True), ("int64", -1 << 63, False), ("int64", (1 << 63) - 1, False), ("uint8", (1 << 8), True), ("uint8", -1, True), ("uint8", (1 << 8) - 1, False), ("uint8", 0, False), ("uint16", (1 << 16), True), ("uint16", -1, True), ("uint16", (1 << 16) - 1, False), ("uint16", 0, False), ("uint32", (1 << 32), True), ("uint32", -1, True), ("uint32", (1 << 32) - 1, False), ("uint32", 0, False), ("uint64", (1 << 64), True), ("uint64", -1, True), ("uint64", (1 << 64) - 1, False), ("uint64", 0, False), ] for type, val, overflows in cases: codestr = f""" from __static__ import {type}, box def x(val: {type}): return box(val) """ with self.subTest(type=type, val=val, overflows=overflows): with self.in_strict_module(codestr) as mod: if overflows: with self.assertRaises(OverflowError): mod.x(val) else: self.assertEqual(mod.x(val), val) def test_primitive_args_funcdef_missing_kw_call(self): codestr = """ from __static__ import int8, box def testfunc(x: int8, foo): return box(x), foo """ with self.in_strict_module(codestr) as mod: self.assertEqual(mod.testfunc(-128, foo=42), (-128, 42)) def test_primitive_args_funccall(self): codestr = """ from __static__ import int8 def f(foo): pass def n() -> int: x: int8 = 3 return f(x) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int8 positional argument type mismatch dynamic", ): self.compile(codestr, StaticCodeGenerator, modname="foo.py") def test_primitive_args_funccall_int(self): codestr = """ from __static__ import int8 def f(foo: int): pass def n() -> int: x: int8 = 3 return f(x) """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int8 positional argument type mismatch int", ): self.compile(codestr, StaticCodeGenerator, modname="foo.py") def test_primitive_args_typecall(self): codestr = """ from __static__ import int8 def n() -> int: x: int8 = 3 return int(x) """ with self.assertRaisesRegex( TypedSyntaxError, "Call argument cannot be a primitive" ): self.compile(codestr, StaticCodeGenerator, modname="foo.py") def test_primitive_args_typecall_kwarg(self): codestr = """ from __static__ import int8 def n() -> int: x: int8 = 3 return dict(a=x) """ with self.assertRaisesRegex( TypedSyntaxError, "Call argument cannot be a primitive" ): self.compile(codestr, StaticCodeGenerator, modname="foo.py") def test_primitive_args_nonstrict(self): codestr = """ from __static__ import int8, int16, box def f(x: int8, y: int16) -> int16: return x + y def g() -> int: return box(f(1, 300)) """ with self.in_module(codestr) as mod: self.assertEqual(mod["g"](), 301) def test_primitive_args_and_return(self): cases = [ ("cbool", 1), ("cbool", 0), ("int8", -1 << 7), ("int8", (1 << 7) - 1), ("int16", -1 << 15), ("int16", (1 << 15) - 1), ("int32", -1 << 31), ("int32", (1 << 31) - 1), ("int64", -1 << 63), ("int64", (1 << 63) - 1), ("uint8", (1 << 8) - 1), ("uint8", 0), ("uint16", (1 << 16) - 1), ("uint16", 0), ("uint32", (1 << 32) - 1), ("uint32", 0), ("uint64", (1 << 64) - 1), ("uint64", 0), ] for typ, val in cases: if typ == "cbool": op = "or" expected = True other = "cbool(True)" boxed = "bool" else: op = "+" if val <= 0 else "-" expected = val + (1 if op == "+" else -1) other = "1" boxed = "int" with self.subTest(typ=typ, val=val, op=op, expected=expected): codestr = f""" from __static__ import {typ}, box def f(x: {typ}, y: {typ}) -> {typ}: return x {op} y def g() -> {boxed}: return box(f({val}, {other})) """ with self.in_strict_module(codestr) as mod: self.assertEqual(mod.g(), expected) def test_primitive_return(self): cases = [ ("cbool", True), ("cbool", False), ("int8", -1 << 7), ("int8", (1 << 7) - 1), ("int16", -1 << 15), ("int16", (1 << 15) - 1), ("int32", -1 << 31), ("int32", (1 << 31) - 1), ("int64", -1 << 63), ("int64", (1 << 63) - 1), ("uint8", (1 << 8) - 1), ("uint8", 0), ("uint16", (1 << 16) - 1), ("uint16", 0), ("uint32", (1 << 32) - 1), ("uint32", 0), ("uint64", (1 << 64) - 1), ("uint64", 0), ] tf = [True, False] for (type, val), box, strict, error, unjitable in itertools.product( cases, [False], [True], [False], [True] ): if type == "cbool": op = "or" other = "False" boxed = "bool" else: op = "*" other = "1" boxed = "int" unjitable_code = "from sys import *" if unjitable else "" codestr = f""" from __static__ import {type}, box def f(error: bool) -> {type}: {unjitable_code} if error: raise RuntimeError("boom") return {val} """ if box: codestr += f""" def g() -> {boxed}: return box(f({error}) {op} {type}({other})) """ else: codestr += f""" def g() -> {type}: return f({error}) {op} {type}({other}) """ ctx = self.in_strict_module if strict else self.in_module oparg = PRIM_NAME_TO_TYPE[type] with self.subTest( type=type, val=val, strict=strict, box=box, error=error, unjitable=unjitable, ): with ctx(codestr) as mod: f = mod.f if strict else mod["f"] g = mod.g if strict else mod["g"] self.assertInBytecode(f, "RETURN_INT", oparg) if box: self.assertNotInBytecode(g, "RETURN_INT") else: self.assertInBytecode(g, "RETURN_INT", oparg) if error: with self.assertRaisesRegex(RuntimeError, "boom"): g() else: self.assertEqual(g(), val) self.assert_jitted(g) if unjitable: self.assert_not_jitted(f) else: self.assert_jitted(f) def test_primitive_return_recursive(self): codestr = """ from __static__ import int32 def fib(n: int32) -> int32: if n <= 1: return n return fib(n-1) + fib(n-2) """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.fib, "INVOKE_FUNCTION", ((mod.__name__, "fib"), 1), ) self.assertEqual(mod.fib(2), 1) self.assert_jitted(mod.fib) def test_primitive_return_unannotated(self): codestr = """ from __static__ import int32 def f(): x: int32 = 1 return x """ with self.assertRaisesRegex( TypedSyntaxError, "type mismatch: int32 cannot be assigned to dynamic" ): self.compile(codestr) def test_module_level_final_decl(self): codestr = """ from typing import Final x: Final """ with self.assertRaisesRegex( TypedSyntaxError, "Must assign a value when declaring a Final" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_int_compare_to_cbool(self): codestr = """ from __static__ import int64, cbool def foo(i: int64) -> cbool: return i == 0 """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: foo = mod["foo"] self.assertEqual(foo(0), True) self.assertEqual(foo(1), False) def test_int_compare_to_cbool_reversed(self): codestr = """ from __static__ import int64, cbool def foo(i: int64) -> cbool: return 0 == i """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: foo = mod["foo"] self.assertEqual(foo(0), True) self.assertEqual(foo(1), False) def test_inline_primitive(self): codestr = """ from __static__ import int64, cbool, inline @inline def x(i: int64) -> cbool: return i == 1 def foo(i: int64) -> cbool: return i >0 and x(i) """ with self.in_module(codestr, optimize=2) as mod: foo = mod["foo"] self.assertEqual(foo(0), False) self.assertEqual(foo(1), True) self.assertEqual(foo(2), False) self.assertNotInBytecode(foo, "STORE_FAST") self.assertInBytecode(foo, "STORE_LOCAL") def test_final_multiple_typeargs(self): codestr = """ from typing import Final from something import hello x: Final[int, str] = hello() """ with self.assertRaisesRegex( TypedSyntaxError, "Final types can only have a single type arg" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_annotation_nesting(self): with self.assertRaisesRegex( TypedSyntaxError, "Final annotation is only valid in initial declaration" ): self.compile( """ from typing import Final, List x: List[Final[str]] = [] """, StaticCodeGenerator, modname="foo", ) with self.assertRaisesRegex( TypedSyntaxError, "Final annotation is only valid in initial declaration" ): self.compile( """ from typing import Final, List x: List[int | Final] = [] """, StaticCodeGenerator, modname="foo", ) def test_final(self): codestr = """ from typing import Final x: Final = 0xdeadbeef """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_generic(self): codestr = """ from typing import Final x: Final[int] = 0xdeadbeef """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_generic_types(self): codestr = """ from typing import Final def g(i: int) -> int: return i def f() -> int: x: Final[int] = 0xdeadbeef return g(x) """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_uninitialized(self): codestr = """ from typing import Final x: Final """ with self.assertRaisesRegex( TypedSyntaxError, "Must assign a value when declaring a Final" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassign(self): codestr = """ from typing import Final x: Final = 0xdeadbeef x = "something" """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassign_explicit_global(self): codestr = """ from typing import Final a: Final = 1337 def fn(): def fn2(): global a a = 0 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassign_explicit_global_shadowed(self): codestr = """ from typing import Final a: Final = 1337 def fn(): a = 2 def fn2(): global a a = 0 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassign_nonlocal(self): codestr = """ from typing import Final a: Final = 1337 def fn(): def fn2(): nonlocal a a = 0 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassign_nonlocal_shadowed(self): codestr = """ from typing import Final a: Final = 1337 def fn(): a = 3 def fn2(): nonlocal a # should be allowed, we're assigning to the shadowed # value a = 0 """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassigned_in_tuple(self): codestr = """ from typing import Final x: Final = 0xdeadbeef y = 3 x, y = 4, 5 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassigned_in_loop(self): codestr = """ from typing import Final x: Final = 0xdeadbeef for x in [1, 3, 5]: pass """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassigned_in_except(self): codestr = """ from typing import Final def f(): e: Final = 3 try: x = 1 + "2" except Exception as e: pass """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassigned_in_loop_target_tuple(self): codestr = """ from typing import Final x: Final = 0xdeadbeef for x, y in [(1, 2)]: pass """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_reassigned_in_ctxmgr(self): codestr = """ from typing import Final x: Final = 0xdeadbeef with open("lol") as x: pass """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_generic_reassign(self): codestr = """ from typing import Final x: Final[int] = 0xdeadbeef x = 0x5ca1ab1e """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_decl(self): codestr = """ from typing import Final class C: x: Final[int] def __init__(self): self.x = 3 """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_decl_uninitialized(self): codestr = """ from typing import Final class C: x: Final """ with self.assertRaisesRegex( TypedSyntaxError, re.escape("Final attribute not initialized: foo.C:x"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized(self): codestr = """ from typing import Final class C: x: Final = 3 x = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final variable" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_directly(self): codestr = """ from typing import Final class C: x: Final = 3 C.x = 4 """ # Note - this will raise even without the Final, we don't allow assignments to slots with self.assertRaisesRegex( TypedSyntaxError, type_mismatch("Exact[int]", "types.MemberDescriptorType"), ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_in_instance(self): codestr = """ from typing import Final class C: x: Final = 3 C().x = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.C:x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_in_method(self): codestr = """ from typing import Final class C: x: Final = 3 def something(self) -> None: self.x = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.C:x" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_in_subclass_without_annotation(self): codestr = """ from typing import Final class C: x: Final = 3 class D(C): x = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_in_subclass_with_annotation(self): codestr = """ from typing import Final class C: x: Final = 3 class D(C): x: Final[int] = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_in_subclass_init(self): codestr = """ from typing import Final class C: x: Final = 3 class D(C): def __init__(self): self.x = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_reinitialized_in_subclass_init_with_annotation(self): codestr = """ from typing import Final class C: x: Final[int] = 3 class D(C): def __init__(self): self.x: Final[int] = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_class_level_final_decl_in_init_reinitialized_in_subclass_init(self): codestr = """ from typing import Final class C: x: Final[int] def __init__(self) -> None: self.x = 3 class D(C): def __init__(self) -> None: self.x = 4 """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_in_args(self): codestr = """ from typing import Final def f(a: Final) -> None: pass """ with self.assertRaisesRegex( TypedSyntaxError, "Final annotation is only valid in initial declaration", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_returns(self): codestr = """ from typing import Final def f() -> Final[int]: return 1 """ with self.assertRaisesRegex( TypedSyntaxError, "Final annotation is only valid in initial declaration", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_decorator(self): codestr = """ from typing import final class C: @final def f(): pass """ self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_decorator_override(self): codestr = """ from typing import final class C: @final def f(): pass class D(C): def f(): pass """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:f" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_decorator_override_with_assignment(self): codestr = """ from typing import final class C: @final def f(): pass class D(C): f = print """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.D:f" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_decorator_override_transitivity(self): codestr = """ from typing import final class C: @final def f(): pass class D(C): pass class E(D): def f(): pass """ with self.assertRaisesRegex( TypedSyntaxError, "Cannot assign to a Final attribute of foo.E:f" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_decorator_class(self): codestr = """ from typing import final @final class C: def f(self): pass def f(): return C().f() """ c = self.compile(codestr, StaticCodeGenerator, modname="foo") f = self.find_code(c, "f") self.assertInBytecode(f, "INVOKE_FUNCTION") def test_final_decorator_class_inheritance(self): codestr = """ from typing import final @final class C: pass class D(C): pass """ with self.assertRaisesRegex( TypedSyntaxError, "Class `foo.D` cannot subclass a Final class: `foo.C`" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_final_decorator_class_dynamic(self): """We should never mark DYNAMIC_TYPE as final.""" codestr = """ from typing import final, Generic, NamedTuple @final class NT(NamedTuple): x: int class C(Generic): pass """ # No TypedSyntaxError "cannot inherit from Final class 'dynamic'" self.compile(codestr) def test_slotification_decorated(self): codestr = """ class _Inner(): pass def something(klass): return _Inner @something class C: def f(self): pass def f(): return C().f() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "INVOKE_FUNCTION") self.assertNotInBytecode(f, "INVOKE_METHOD") def test_inline_func(self): codestr = """ from __static__ import inline @inline def f(x, y): return x + y def g(): return f(1,2) """ # we only inline at opt level 2 to avoid test patching problems # TODO longer term we might need something better here (e.g. emit both # inlined code and call and a guard to choose); assuming # non-patchability at opt 2 works for IG but isn't generally valid for opt in [0, 1, 2]: with self.subTest(opt=opt): with self.in_module(codestr, optimize=opt) as mod: g = mod["g"] if opt == 2: self.assertInBytecode(g, "LOAD_CONST", 3) else: self.assertInBytecode( g, "INVOKE_FUNCTION", ((mod["__name__"], "f"), 2) ) self.assertEqual(g(), 3) def test_inline_kwarg(self): codestr = """ from __static__ import inline @inline def f(x, y): return x + y def g(): return f(x=1,y=2) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "LOAD_CONST", 3) self.assertEqual(g(), 3) def test_inline_bare_return(self): codestr = """ from __static__ import inline @inline def f(x, y): return def g(): return f(x=1,y=2) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "LOAD_CONST", None) self.assertEqual(g(), None) def test_inline_final(self): codestr = """ from __static__ import inline from typing import Final Y: Final[int] = 42 @inline def f(x): return x + Y def g(): return f(1) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] # We don't currently inline math with finals self.assertInBytecode(g, "LOAD_CONST", 42) self.assertEqual(g(), 43) def test_inline_nested(self): codestr = """ from __static__ import inline @inline def e(x, y): return x + y @inline def f(x, y): return e(x, 3) def g(): return f(1,2) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "LOAD_CONST", 4) self.assertEqual(g(), 4) def test_inline_nested_arg(self): codestr = """ from __static__ import inline @inline def e(x, y): return x + y @inline def f(x, y): return e(x, 3) def g(a,b): return f(a,b) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "LOAD_CONST", 3) self.assertInBytecode(g, "BINARY_ADD") self.assertEqual(g(1, 2), 4) def test_inline_recursive(self): codestr = """ from __static__ import inline @inline def f(x, y): return f(x, y) def g(): return f(1,2) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "INVOKE_FUNCTION", (((mod["__name__"], "f"), 2))) def test_inline_func_default(self): codestr = """ from __static__ import inline @inline def f(x, y = 2): return x + y def g(): return f(1) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "LOAD_CONST", 3) self.assertEqual(g(), 3) def test_inline_arg_type(self): codestr = """ from __static__ import box, inline, int64, int32 @inline def f(x: int64) -> int: return box(x) def g(arg: int) -> int: return f(int64(arg)) """ with self.in_module(codestr, optimize=2) as mod: g = mod["g"] self.assertInBytecode(g, "PRIMITIVE_BOX") self.assertEqual(g(3), 3) def test_augassign_primitive_int(self): codestr = """ from __static__ import int8, box, unbox def a(i: int) -> int: j: int8 = unbox(i) j += 2 return box(j) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: a = mod["a"] self.assertInBytecode(a, "PRIMITIVE_BINARY_OP", 0) self.assertEqual(a(3), 5) def test_primitive_compare_immediate_no_branch_on_result(self): for rev in [True, False]: compare = "0 == xp" if rev else "xp == 0" codestr = f""" from __static__ import box, int64, int32 def f(x: int) -> bool: xp = int64(x) y = {compare} return box(y) """ with self.subTest(rev=rev): with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(3), 0) self.assertEqual(f(0), 1) self.assertIs(f(0), True) def test_type_type_final(self): codestr = """ class A(type): pass """ self.compile(codestr) class StaticRuntimeTests(StaticTestBase): def test_bad_slots_qualname_conflict(self): with self.assertRaises(ValueError): class C: __slots__ = ("x",) __slot_types__ = {"x": ("__static__", "int32")} x = 42 def test_typed_slots_bad_inst(self): class C: __slots__ = ("a",) __slot_types__ = {"a": ("__static__", "int32")} class D: pass with self.assertRaises(TypeError): C.a.__get__(D(), D) def test_typed_slots_bad_slots(self): with self.assertRaises(TypeError): class C: __slots__ = ("a",) __slot_types__ = None def test_typed_slots_bad_slot_dict(self): with self.assertRaises(TypeError): class C: __slots__ = ("__dict__",) __slot_types__ = {"__dict__": "object"} def test_typed_slots_bad_slot_weakerf(self): with self.assertRaises(TypeError): class C: __slots__ = ("__weakref__",) __slot_types__ = {"__weakref__": "object"} def test_typed_slots_object(self): codestr = """ class C: __slots__ = ('a', ) __slot_types__ = {'a': (__name__, 'C')} inst = C() """ with self.in_module(codestr, code_gen=PythonCodeGenerator) as mod: inst, C = mod["inst"], mod["C"] self.assertEqual(C.a.__class__.__name__, "typed_descriptor") with self.assertRaises(TypeError): # type is checked inst.a = 42 with self.assertRaises(TypeError): inst.a = None with self.assertRaises(AttributeError): # is initially unassigned inst.a # can assign correct type inst.a = inst # __sizeof__ doesn't include GC header size self.assertEqual(inst.__sizeof__(), self.base_size + self.ptr_size) # size is +2 words for GC header, one word for reference self.assertEqual(sys.getsizeof(inst), self.base_size + (self.ptr_size * 3)) # subclasses are okay class D(C): pass inst.a = D() def test_allow_weakrefs(self): codestr = """ from __static__ import allow_weakrefs import weakref @allow_weakrefs class C: pass def f(c: C): return weakref.ref(c) """ with self.in_module(codestr) as mod: C = mod["C"] c = C() ref = mod["f"](c) self.assertIs(ref(), c) del c self.assertIs(ref(), None) self.assertEqual(C.__slots__, ("__weakref__",)) def test_dynamic_return(self): codestr = """ from __future__ import annotations from __static__ import allow_weakrefs, dynamic_return import weakref singletons = [] @allow_weakrefs class C: @dynamic_return @staticmethod def make() -> C: return weakref.proxy(singletons[0]) def g(self) -> int: return 1 singletons.append(C()) def f() -> int: c = C.make() return c.g() """ with self.in_strict_module(codestr) as mod: # We don't try to cast the return type of make self.assertNotInBytecode(mod.C.make, "CAST") # We can statically invoke make self.assertInBytecode( mod.f, "INVOKE_FUNCTION", ((mod.__name__, "C", "make"), 0) ) # But we can't statically invoke a method on the returned instance self.assertNotInBytecode(mod.f, "INVOKE_METHOD") self.assertEqual(mod.f(), 1) # We don't mess with __annotations__ self.assertEqual(mod.C.make.__annotations__, {"return": "C"}) def test_generic_type_def_no_create(self): from xxclassloader import spamobj with self.assertRaises(TypeError): spamobj() def test_generic_type_def_bad_args(self): from xxclassloader import spamobj with self.assertRaises(TypeError): spamobj[str, int] def test_generic_type_def_non_type(self): from xxclassloader import spamobj with self.assertRaises(TypeError): spamobj[42] def test_generic_type_inst_okay(self): from xxclassloader import spamobj o = spamobj[str]() o.setstate("abc") def test_generic_type_inst_optional_okay(self): from xxclassloader import spamobj o = spamobj[Optional[str]]() o.setstate("abc") o.setstate(None) def test_generic_type_inst_non_optional_error(self): from xxclassloader import spamobj o = spamobj[str]() with self.assertRaises(TypeError): o.setstate(None) def test_generic_type_inst_bad_type(self): from xxclassloader import spamobj o = spamobj[str]() with self.assertRaises(TypeError): o.setstate(42) def test_generic_type_inst_name(self): from xxclassloader import spamobj self.assertEqual(spamobj[str].__name__, "spamobj[str]") def test_generic_type_inst_name_optional(self): from xxclassloader import spamobj self.assertEqual(spamobj[Optional[str]].__name__, "spamobj[Optional[str]]") def test_generic_type_inst_okay_func(self): from xxclassloader import spamobj o = spamobj[str]() f = o.setstate f("abc") def test_generic_type_inst_optional_okay_func(self): from xxclassloader import spamobj o = spamobj[Optional[str]]() f = o.setstate f("abc") f(None) def test_generic_type_inst_non_optional_error_func(self): from xxclassloader import spamobj o = spamobj[str]() f = o.setstate with self.assertRaises(TypeError): f(None) def test_generic_type_inst_bad_type_func(self): from xxclassloader import spamobj o = spamobj[str]() f = o.setstate with self.assertRaises(TypeError): f(42) def test_generic_int_funcs(self): from xxclassloader import spamobj o = spamobj[str]() o.setint(42) self.assertEqual(o.getint8(), 42) self.assertEqual(o.getint16(), 42) self.assertEqual(o.getint32(), 42) def test_generic_uint_funcs(self): from xxclassloader import spamobj o = spamobj[str]() o.setuint64(42) self.assertEqual(o.getuint8(), 42) self.assertEqual(o.getuint16(), 42) self.assertEqual(o.getuint32(), 42) self.assertEqual(o.getuint64(), 42) def test_generic_int_funcs_overflow(self): from xxclassloader import spamobj o = spamobj[str]() o.setuint64(42) for i, f in enumerate([o.setint8, o.setint16, o.setint32, o.setint]): with self.assertRaises(OverflowError): x = -(1 << ((8 << i) - 1)) - 1 f(x) with self.assertRaises(OverflowError): x = 1 << ((8 << i) - 1) f(x) def test_generic_uint_funcs_overflow(self): from xxclassloader import spamobj o = spamobj[str]() o.setuint64(42) for f in [o.setuint8, o.setuint16, o.setuint32, o.setuint64]: with self.assertRaises(OverflowError): f(-1) for i, f in enumerate([o.setuint8, o.setuint16, o.setuint32, o.setuint64]): with self.assertRaises(OverflowError): x = (1 << (8 << i)) + 1 f(x) def test_generic_type_int_func(self): from xxclassloader import spamobj o = spamobj[str]() o.setint(42) self.assertEqual(o.getint(), 42) with self.assertRaises(TypeError): o.setint("abc") def test_generic_type_str_func(self): from xxclassloader import spamobj o = spamobj[str]() o.setstr("abc") self.assertEqual(o.getstr(), "abc") with self.assertRaises(TypeError): o.setstr(42) def test_generic_type_bad_arg_cnt(self): from xxclassloader import spamobj o = spamobj[str]() with self.assertRaises(TypeError): o.setstr() with self.assertRaises(TypeError): o.setstr("abc", "abc") def test_generic_type_bad_arg_cnt(self): from xxclassloader import spamobj o = spamobj[str]() self.assertEqual(o.twoargs(1, 2), 3) def test_typed_slots_one_missing(self): codestr = """ class C: __slots__ = ('a', 'b') __slot_types__ = {'a': (__name__, 'C')} inst = C() """ with self.in_module(codestr, code_gen=PythonCodeGenerator) as mod: inst, C = mod["inst"], mod["C"] self.assertEqual(C.a.__class__.__name__, "typed_descriptor") with self.assertRaises(TypeError): # type is checked inst.a = 42 def test_typed_slots_optional_object(self): codestr = """ class C: __slots__ = ('a', ) __slot_types__ = {'a': (__name__, 'C', '?')} inst = C() """ with self.in_module(codestr, code_gen=PythonCodeGenerator) as mod: inst, C = mod["inst"], mod["C"] inst.a = None self.assertEqual(inst.a, None) def test_typed_slots_private(self): codestr = """ class C: __slots__ = ('__a', ) __slot_types__ = {'__a': (__name__, 'C', '?')} def __init__(self): self.__a = None inst = C() """ with self.in_module(codestr, code_gen=PythonCodeGenerator) as mod: inst, C = mod["inst"], mod["C"] self.assertEqual(inst._C__a, None) inst._C__a = inst self.assertEqual(inst._C__a, inst) inst._C__a = None self.assertEqual(inst._C__a, None) def test_typed_slots_optional_not_defined(self): codestr = """ class C: __slots__ = ('a', ) __slot_types__ = {'a': (__name__, 'D', '?')} def __init__(self): self.a = None inst = C() class D: pass """ with self.in_module(codestr, code_gen=PythonCodeGenerator) as mod: inst, C = mod["inst"], mod["C"] inst.a = None self.assertEqual(inst.a, None) def test_typed_slots_alignment(self): return codestr = """ class C: __slots__ = ('a', 'b') __slot_types__ {'a': ('__static__', 'int16')} inst = C() """ with self.in_module(codestr, code_gen=PythonCodeGenerator) as mod: inst, C = mod["inst"], mod["C"] inst.a = None self.assertEqual(inst.a, None) def test_typed_slots_primitives(self): slot_types = [ # signed ( ("__static__", "byte"), 0, 1, [(1 << 7) - 1, -(1 << 7)], [1 << 8], ["abc"], ), ( ("__static__", "int8"), 0, 1, [(1 << 7) - 1, -(1 << 7)], [1 << 8], ["abc"], ), ( ("__static__", "int16"), 0, 2, [(1 << 15) - 1, -(1 << 15)], [1 << 15, -(1 << 15) - 1], ["abc"], ), ( ("__static__", "int32"), 0, 4, [(1 << 31) - 1, -(1 << 31)], [1 << 31, -(1 << 31) - 1], ["abc"], ), (("__static__", "int64"), 0, 8, [(1 << 63) - 1, -(1 << 63)], [], [1 << 63]), # unsigned (("__static__", "uint8"), 0, 1, [(1 << 8) - 1, 0], [1 << 8, -1], ["abc"]), ( ("__static__", "uint16"), 0, 2, [(1 << 16) - 1, 0], [1 << 16, -1], ["abc"], ), ( ("__static__", "uint32"), 0, 4, [(1 << 32) - 1, 0], [1 << 32, -1], ["abc"], ), (("__static__", "uint64"), 0, 8, [(1 << 64) - 1, 0], [], [1 << 64]), # pointer ( ("__static__", "ssize_t"), 0, self.ptr_size, [1, sys.maxsize, -sys.maxsize - 1], [], [sys.maxsize + 1, -sys.maxsize - 2], ), # floating point (("__static__", "single"), 0.0, 4, [1.0], [], ["abc"]), (("__static__", "double"), 0.0, 8, [1.0], [], ["abc"]), # misc (("__static__", "char"), "\x00", 1, ["a"], [], ["abc"]), (("__static__", "cbool"), False, 1, [True], [], ["abc", 1]), ] base_size = self.base_size for type_spec, default, size, test_vals, warn_vals, err_vals in slot_types: with self.subTest( type_spec=type_spec, default=default, size=size, test_vals=test_vals, warn_vals=warn_vals, err_vals=err_vals, ): class C: __slots__ = ("a",) __slot_types__ = {"a": type_spec} a = C() self.assertEqual(sys.getsizeof(a), base_size + size, type) self.assertEqual(a.a, default) self.assertEqual(type(a.a), type(default)) for val in test_vals: a.a = val self.assertEqual(a.a, val) with warnings.catch_warnings(): warnings.simplefilter("error", category=RuntimeWarning) for val in warn_vals: with self.assertRaises(RuntimeWarning): a.a = val for val in err_vals: with self.assertRaises((TypeError, OverflowError)): a.a = val def test_invoke_function(self): my_int = "12345" codestr = f""" def x(a: str, b: int) -> str: return a + str(b) def test() -> str: return x("hello", {my_int}) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") test = self.find_code(c, "test") self.assertInBytecode(test, "INVOKE_FUNCTION", (("foo.py", "x"), 2)) with self.in_module(codestr) as mod: test_callable = mod["test"] self.assertEqual(test_callable(), "hello" + my_int) def test_awaited_invoke_function(self): codestr = """ async def f() -> int: return 1 async def g() -> int: return await f() """ with self.in_strict_module(codestr) as mod: self.assertInBytecode(mod.g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 0)) self.assertEqual(asyncio.run(mod.g()), 1) def test_awaited_invoke_function_unjitable(self): codestr = """ async def f() -> int: from os.path import * return 1 async def g() -> int: return await f() """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 0), ) self.assertEqual(asyncio.run(mod.g()), 1) def test_awaited_invoke_function_with_args(self): codestr = """ async def f(a: int, b: int) -> int: return a + b async def g() -> int: return await f(1, 2) """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.g, "INVOKE_FUNCTION", ((mod.__name__, "f"), 2), ) self.assertEqual(asyncio.run(mod.g()), 3) # exercise shadowcode, INVOKE_FUNCTION_CACHED self.make_async_func_hot(mod.g) self.assertEqual(asyncio.run(mod.g()), 3) def test_awaited_invoke_function_indirect_with_args(self): codestr = """ async def f(a: int, b: int) -> int: return a + b async def g() -> int: return await f(1, 2) """ with self.in_module(codestr) as mod: g = mod["g"] self.assertInBytecode( g, "INVOKE_FUNCTION", ((mod["__name__"], "f"), 2), ) self.assertEqual(asyncio.run(g()), 3) # exercise shadowcode, INVOKE_FUNCTION_INDIRECT_CACHED self.make_async_func_hot(g) self.assertEqual(asyncio.run(g()), 3) def test_awaited_invoke_function_future(self): codestr = """ from asyncio import ensure_future async def h() -> int: return 1 async def g() -> None: await ensure_future(h()) async def f(): await g() """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.f, "INVOKE_FUNCTION", ((mod.__name__, "g"), 0), ) asyncio.run(mod.f()) # exercise shadowcode self.make_async_func_hot(mod.f) asyncio.run(mod.f()) def test_awaited_invoke_method(self): codestr = """ class C: async def f(self) -> int: return 1 async def g(self) -> int: return await self.f() """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.C.g, "INVOKE_METHOD", ((mod.__name__, "C", "f"), 0) ) self.assertEqual(asyncio.run(mod.C().g()), 1) def test_awaited_invoke_method_with_args(self): codestr = """ class C: async def f(self, a: int, b: int) -> int: return a + b async def g(self) -> int: return await self.f(1, 2) """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.C.g, "INVOKE_METHOD", ((mod.__name__, "C", "f"), 2), ) self.assertEqual(asyncio.run(mod.C().g()), 3) # exercise shadowcode, INVOKE_METHOD_CACHED async def make_hot(): c = mod.C() for i in range(50): await c.g() asyncio.run(make_hot()) self.assertEqual(asyncio.run(mod.C().g()), 3) def test_awaited_invoke_method_future(self): codestr = """ from asyncio import ensure_future async def h() -> int: return 1 class C: async def g(self) -> None: await ensure_future(h()) async def f(): c = C() await c.g() """ with self.in_strict_module(codestr) as mod: self.assertInBytecode( mod.f, "INVOKE_METHOD", ((mod.__name__, "C", "g"), 0), ) asyncio.run(mod.f()) # exercise shadowcode, INVOKE_METHOD_CACHED self.make_async_func_hot(mod.f) asyncio.run(mod.f()) def test_load_iterable_arg(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def y() -> int: p = ("hi", 0.1, 0.2) return x(1, 3, *p) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 0) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 1) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 2) self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertEqual(y_callable(), 7) def test_load_iterable_arg_default_overridden(self): codestr = """ def x(a: int, b: int, c: str, d: float = 10.1, e: float = 20.1) -> bool: return bool( a == 1 and b == 3 and c == "hi" and d == 0.1 and e == 0.2 ) def y() -> bool: p = ("hi", 0.1, 0.2) return x(1, 3, *p) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG", 3) self.assertNotInBytecode(y, "LOAD_MAPPING_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertTrue(y_callable()) def test_load_iterable_arg_multi_star(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def y() -> int: p = (1, 3) q = ("hi", 0.1, 0.2) return x(*p, *q) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) # we should fallback to the normal Python compiler for this self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG") with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertEqual(y_callable(), 7) def test_load_iterable_arg_star_not_last(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def y() -> int: p = (1, 3, 'abc', 0.1) return x(*p, 1.0) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) # we should fallback to the normal Python compiler for this self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG") with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertEqual(y_callable(), 7) def test_load_iterable_arg_failure(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def y() -> int: p = ("hi", 0.1) return x(1, 3, *p) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 0) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 1) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 2) self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] with self.assertRaises(IndexError): y_callable() def test_load_iterable_arg_sequence(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def y() -> int: p = ["hi", 0.1, 0.2] return x(1, 3, *p) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 0) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 1) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 2) self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertEqual(y_callable(), 7) def test_load_iterable_arg_sequence_1(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def gen(): for i in ["hi", 0.05, 0.2]: yield i def y() -> int: g = gen() return x(1, 3, *g) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 0) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 1) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 2) self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertEqual(y_callable(), 7) def test_load_iterable_arg_sequence_failure(self): codestr = """ def x(a: int, b: int, c: str, d: float, e: float) -> int: return 7 def y() -> int: p = ["hi", 0.1] return x(1, 3, *p) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 0) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 1) self.assertInBytecode(y, "LOAD_ITERABLE_ARG", 2) self.assertNotInBytecode(y, "LOAD_ITERABLE_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] with self.assertRaises(IndexError): y_callable() def test_load_mapping_arg(self): codestr = """ def x(a: int, b: int, c: str, d: float=-0.1, e: float=1.1, f: str="something") -> bool: return bool(f == "yo" and d == 1.0 and e == 1.1) def y() -> bool: d = {"d": 1.0} return x(1, 3, "hi", f="yo", **d) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_MAPPING_ARG", 3) with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertTrue(y_callable()) def test_load_mapping_and_iterable_args_failure_1(self): """ Fails because we don't supply enough positional args """ codestr = """ def x(a: int, b: int, c: str, d: float=2.2, e: float=1.1, f: str="something") -> bool: return bool(a == 1 and b == 3 and f == "yo" and d == 2.2 and e == 1.1) def y() -> bool: return x(1, 3, f="yo") """ with self.assertRaisesRegex( SyntaxError, "Function foo.x expects a value for argument c" ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_load_mapping_arg_failure(self): """ Fails because we supply an extra kwarg """ codestr = """ def x(a: int, b: int, c: str, d: float=2.2, e: float=1.1, f: str="something") -> bool: return bool(a == 1 and b == 3 and f == "yo" and d == 2.2 and e == 1.1) def y() -> bool: return x(1, 3, "hi", f="yo", g="lol") """ with self.assertRaisesRegex( TypedSyntaxError, "Given argument g does not exist in the definition of foo.x", ): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_load_mapping_arg_custom_class(self): """ Fails because we supply a custom class for the mapped args, instead of a dict """ codestr = """ def x(a: int, b: int, c: str="hello") -> bool: return bool(a == 1 and b == 3 and c == "hello") class C: def __getitem__(self, key: str) -> str: if key == "c": return "hi" def keys(self): return ["c"] def y() -> bool: return x(1, 3, **C()) """ with self.in_module(codestr) as mod: y_callable = mod["y"] with self.assertRaisesRegex( TypeError, r"argument after \*\* must be a dict, not C" ): self.assertTrue(y_callable()) def test_load_mapping_arg_use_defaults(self): codestr = """ def x(a: int, b: int, c: str, d: float=-0.1, e: float=1.1, f: str="something") -> bool: return bool(f == "yo" and d == -0.1 and e == 1.1) def y() -> bool: d = {"d": 1.0} return x(1, 3, "hi", f="yo") """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "LOAD_CONST", 1.1) with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertTrue(y_callable()) def test_default_arg_non_const(self): codestr = """ class C: pass def x(val=C()) -> C: return val def f() -> C: return x() """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "CALL_FUNCTION") def test_default_arg_non_const_kw_provided(self): codestr = """ class C: pass def x(val:object=C()): return val def f(): return x(val=42) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertEqual(f(), 42) def test_load_mapping_arg_order(self): codestr = """ def x(a: int, b: int, c: str, d: float=-0.1, e: float=1.1, f: str="something") -> bool: return bool( a == 1 and b == 3 and c == "hi" and d == 1.1 and e == 3.3 and f == "hmm" ) stuff = [] def q() -> float: stuff.append("q") return 1.1 def r() -> float: stuff.append("r") return 3.3 def s() -> str: stuff.append("s") return "hmm" def y() -> bool: return x(1, 3, "hi", f=s(), d=q(), e=r()) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "STORE_FAST", "_pystatic_.0._tmp__d") self.assertInBytecode(y, "LOAD_FAST", "_pystatic_.0._tmp__d") with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertTrue(y_callable()) self.assertEqual(["s", "q", "r"], mod["stuff"]) def test_load_mapping_arg_order_with_variadic_kw_args(self): codestr = """ def x(a: int, b: int, c: str, d: float=-0.1, e: float=1.1, f: str="something", g: str="look-here") -> bool: return bool( a == 1 and b == 3 and c == "hi" and d == 1.1 and e == 3.3 and f == "hmm" and g == "overridden" ) stuff = [] def q() -> float: stuff.append("q") return 1.1 def r() -> float: stuff.append("r") return 3.3 def s() -> str: stuff.append("s") return "hmm" def y() -> bool: kw = {"g": "overridden"} return x(1, 3, "hi", f=s(), **kw, d=q(), e=r()) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "STORE_FAST", "_pystatic_.0._tmp__d") self.assertInBytecode(y, "LOAD_FAST", "_pystatic_.0._tmp__d") with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertTrue(y_callable()) self.assertEqual(["s", "q", "r"], mod["stuff"]) def test_load_mapping_arg_order_with_variadic_kw_args_one_positional(self): codestr = """ def x(a: int, b: int, c: str, d: float=-0.1, e: float=1.1, f: str="something", g: str="look-here") -> bool: return bool( a == 1 and b == 3 and c == "hi" and d == 1.1 and e == 3.3 and f == "hmm" and g == "overridden" ) stuff = [] def q() -> float: stuff.append("q") return 1.1 def r() -> float: stuff.append("r") return 3.3 def s() -> str: stuff.append("s") return "hmm" def y() -> bool: kw = {"g": "overridden"} return x(1, 3, "hi", 1.1, f=s(), **kw, e=r()) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertNotInBytecode(y, "STORE_FAST", "_pystatic_.0._tmp__d") self.assertNotInBytecode(y, "LOAD_FAST", "_pystatic_.0._tmp__d") with self.in_module(codestr) as mod: y_callable = mod["y"] self.assertTrue(y_callable()) self.assertEqual(["s", "r"], mod["stuff"]) def test_vector_generics(self): T = TypeVar("T") VT = Vector[T] VT2 = VT[int64] a = VT2() a.append(42) with self.assertRaisesRegex(TypeError, "Cannot create plain Vector"): VT() def test_vector_invalid_type(self): class C: pass with self.assertRaisesRegex( TypeError, "Invalid type for ArrayElement: C when instantiating Vector" ): Vector[C] def test_vector_wrong_arg_count(self): class C: pass with self.assertRaisesRegex( TypeError, "Incorrect number of type arguments for Vector" ): Vector[int64, int64] def test_generic_type_args(self): T = TypeVar("T") U = TypeVar("U") class C(StaticGeneric[T, U]): pass c_t = make_generic_type(C, (T, int)) self.assertEqual(c_t.__parameters__, (T,)) c_t_s = make_generic_type(c_t, (str,)) self.assertEqual(c_t_s.__name__, "C[str, int]") c_u = make_generic_type(C, (int, U)) self.assertEqual(c_u.__parameters__, (U,)) c_u_t = make_generic_type(c_u, (str,)) self.assertEqual(c_u_t.__name__, "C[int, str]") self.assertFalse(hasattr(c_u_t, "__parameters__")) c_u_t_1 = make_generic_type(c_u, (int,)) c_u_t_2 = make_generic_type(c_t, (int,)) self.assertEqual(c_u_t_1.__name__, "C[int, int]") self.assertIs(c_u_t_1, c_u_t_2) def test_array_slice(self): v = Array[int64]([1, 2, 3, 4]) self.assertEqual(v[1:3], Array[int64]([2, 3])) self.assertEqual(type(v[1:2]), Array[int64]) def test_vector_slice(self): v = Vector[int64]([1, 2, 3, 4]) self.assertEqual(v[1:3], Vector[int64]([2, 3])) self.assertEqual(type(v[1:2]), Vector[int64]) def test_array_deepcopy(self): v = Array[int64]([1, 2, 3, 4]) self.assertEqual(v, deepcopy(v)) self.assertIsNot(v, deepcopy(v)) self.assertEqual(type(v), type(deepcopy(v))) def test_vector_deepcopy(self): v = Vector[int64]([1, 2, 3, 4]) self.assertEqual(v, deepcopy(v)) self.assertIsNot(v, deepcopy(v)) self.assertEqual(type(v), type(deepcopy(v))) def test_nested_generic(self): S = TypeVar("S") T = TypeVar("T") U = TypeVar("U") class F(StaticGeneric[U]): pass class C(StaticGeneric[T]): pass A = F[S] self.assertEqual(A.__parameters__, (S,)) X = C[F[T]] self.assertEqual(X.__parameters__, (T,)) def test_array_len(self): codestr = """ from __static__ import int64, char, double, Array from array import array def y(): return len(Array[int64]([1, 3, 5])) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "FAST_LEN", FAST_LEN_ARRAY) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: y = mod["y"] self.assertEqual(y(), 3) def test_array_isinstance(self): x = Array[int64](0) self.assertTrue(isinstance(x, Array[int64])) self.assertFalse(isinstance(x, Array[int32])) self.assertTrue(issubclass(Array[int64], Array[int64])) self.assertFalse(issubclass(Array[int64], Array[int32])) def test_array_weird_type_constrution(self): self.assertIs( Array[int64], Array[ int64, ], ) def test_array_not_subclassable(self): with self.assertRaises(TypeError): class C(Array[int64]): pass with self.assertRaises(TypeError): class C(Array): pass def test_array_enum(self): codestr = """ from __static__ import Array, clen, int64, box def f(x: Array[int64]): i: int64 = 0 j: int64 = 0 while i < clen(x): j += x[i] i+=1 return box(j) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] a = Array[int64]([1, 2, 3, 4]) self.assertEqual(f(a), 10) with self.assertRaises(TypeError): f(None) def test_optional_array_enum(self): codestr = """ from __static__ import Array, clen, int64, box from typing import Optional def f(x: Optional[Array[int64]]): if x is None: return 42 i: int64 = 0 j: int64 = 0 while i < clen(x): j += x[i] i+=1 return box(j) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] a = Array[int64]([1, 2, 3, 4]) self.assertEqual(f(a), 10) self.assertEqual(f(None), 42) def test_array_len_subclass(self): codestr = """ from __static__ import int64, Array def y(ar: Array[int64]): return len(ar) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "FAST_LEN", FAST_LEN_ARRAY | FAST_LEN_INEXACT) # TODO the below requires Array to be a generic type in C, or else # support for generic annotations for not-generic-in-C types. For now # it's sufficient to validate we emitted FAST_LEN_INEXACT flag. # class MyArray(Array): # def __len__(self): # return 123 # with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: # y = mod["y"] # self.assertEqual(y(MyArray[int64]([1])), 123) def test_nonarray_len(self): codestr = """ class Lol: def __len__(self): return 421 def y(): return len(Lol()) """ y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertNotInBytecode(y, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: y = mod["y"] self.assertEqual(y(), 421) def test_clen(self): codestr = """ from __static__ import box, clen, int64 from typing import List def f(l: List[int]): x: int64 = clen(l) return box(x) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST | FAST_LEN_INEXACT) self.assertEqual(f([1, 2, 3]), 3) class MyList(list): def __len__(self): return 99 self.assertEqual(f(MyList([1, 2])), 99) def test_clen_bad_arg(self): codestr = """ from __static__ import clen def f(l): clen(l) """ with self.assertRaisesRegex( TypedSyntaxError, "bad argument type 'dynamic' for clen()" ): self.compile(codestr) def test_seq_repeat_list(self): codestr = """ def f(): l = [1, 2] return l * 2 """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_LIST) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 2, 1, 2]) def test_seq_repeat_list_reversed(self): codestr = """ def f(): l = [1, 2] return 2 * l """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_LIST | SEQ_REPEAT_REVERSED) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 2, 1, 2]) def test_seq_repeat_primitive(self): codestr = """ from __static__ import int64 def f(): x: int64 = 2 l = [1, 2] return l * x """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_LIST | SEQ_REPEAT_PRIMITIVE_NUM) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 2, 1, 2]) def test_seq_repeat_primitive_reversed(self): codestr = """ from __static__ import int64 def f(): x: int64 = 2 l = [1, 2] return x * l """ f = self.find_code(self.compile(codestr)) self.assertInBytecode( f, "SEQUENCE_REPEAT", SEQ_LIST | SEQ_REPEAT_REVERSED | SEQ_REPEAT_PRIMITIVE_NUM, ) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), [1, 2, 1, 2]) def test_seq_repeat_tuple(self): codestr = """ def f(): t = (1, 2) return t * 2 """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_TUPLE) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), (1, 2, 1, 2)) def test_seq_repeat_tuple_reversed(self): codestr = """ def f(): t = (1, 2) return 2 * t """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_TUPLE | SEQ_REPEAT_REVERSED) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](), (1, 2, 1, 2)) def test_seq_repeat_inexact_list(self): codestr = """ from typing import List def f(l: List[int]): return l * 2 """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_LIST | SEQ_REPEAT_INEXACT_SEQ) with self.in_module(codestr) as mod: self.assertEqual(mod["f"]([1, 2]), [1, 2, 1, 2]) class MyList(list): def __mul__(self, other): return "RESULT" self.assertEqual(mod["f"](MyList([1, 2])), "RESULT") def test_seq_repeat_inexact_tuple(self): codestr = """ from typing import Tuple def f(t: Tuple[int]): return t * 2 """ f = self.find_code(self.compile(codestr)) self.assertInBytecode(f, "SEQUENCE_REPEAT", SEQ_TUPLE | SEQ_REPEAT_INEXACT_SEQ) with self.in_module(codestr) as mod: self.assertEqual(mod["f"]((1, 2)), (1, 2, 1, 2)) class MyTuple(tuple): def __mul__(self, other): return "RESULT" self.assertEqual(mod["f"](MyTuple((1, 2))), "RESULT") def test_seq_repeat_inexact_num(self): codestr = """ def f(num: int): return num * [1, 2] """ f = self.find_code(self.compile(codestr)) self.assertInBytecode( f, "SEQUENCE_REPEAT", SEQ_LIST | SEQ_REPEAT_INEXACT_NUM | SEQ_REPEAT_REVERSED, ) with self.in_module(codestr) as mod: self.assertEqual(mod["f"](2), [1, 2, 1, 2]) class MyInt(int): def __mul__(self, other): return "RESULT" self.assertEqual(mod["f"](MyInt(2)), "RESULT") def test_load_int_const_sizes(self): cases = [ ("int8", (1 << 7), True), ("int8", (-1 << 7) - 1, True), ("int8", -1 << 7, False), ("int8", (1 << 7) - 1, False), ("int16", (1 << 15), True), ("int16", (-1 << 15) - 1, True), ("int16", -1 << 15, False), ("int16", (1 << 15) - 1, False), ("int32", (1 << 31), True), ("int32", (-1 << 31) - 1, True), ("int32", -1 << 31, False), ("int32", (1 << 31) - 1, False), ("int64", (1 << 63), True), ("int64", (-1 << 63) - 1, True), ("int64", -1 << 63, False), ("int64", (1 << 63) - 1, False), ("uint8", (1 << 8), True), ("uint8", -1, True), ("uint8", (1 << 8) - 1, False), ("uint8", 0, False), ("uint16", (1 << 16), True), ("uint16", -1, True), ("uint16", (1 << 16) - 1, False), ("uint16", 0, False), ("uint32", (1 << 32), True), ("uint32", -1, True), ("uint32", (1 << 32) - 1, False), ("uint32", 0, False), ("uint64", (1 << 64), True), ("uint64", -1, True), ("uint64", (1 << 64) - 1, False), ("uint64", 0, False), ] for type, val, overflows in cases: codestr = f""" from __static__ import {type}, box def f() -> int: x: {type} = {val} return box(x) """ with self.subTest(type=type, val=val, overflows=overflows): if overflows: with self.assertRaisesRegex( TypedSyntaxError, "outside of the range" ): self.compile(codestr) else: with self.in_strict_module(codestr) as mod: self.assertEqual(mod.f(), val) def test_load_int_const_signed(self): int_types = [ "int8", "int16", "int32", "int64", ] signs = ["-", ""] values = [12] for type, sign, value in itertools.product(int_types, signs, values): expected = value if sign == "" else -value codestr = f""" from __static__ import {type}, box def y() -> int: x: {type} = {sign}{value} return box(x) """ with self.subTest(type=type, sign=sign, value=value): y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "PRIMITIVE_LOAD_CONST") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: y = mod["y"] self.assertEqual(y(), expected) def test_load_int_const_unsigned(self): int_types = [ "uint8", "uint16", "uint32", "uint64", ] values = [12] for type, value in itertools.product(int_types, values): expected = value codestr = f""" from __static__ import {type}, box def y() -> int: return box({type}({value})) """ with self.subTest(type=type, value=value): y = self.find_code( self.compile(codestr, StaticCodeGenerator, modname="foo"), name="y" ) self.assertInBytecode(y, "PRIMITIVE_LOAD_CONST") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: y = mod["y"] self.assertEqual(y(), expected) def test_primitive_out_of_range(self): codestr = f""" from __static__ import int8, box def f() -> int: x = int8(255) return box(x) """ with self.assertRaisesRegex( TypedSyntaxError, "constant 255 is outside of the range -128 to 127 for int8", ): self.compile(codestr) def test_primitive_conversions(self): cases = [ ("int8", "int8", 5, 5), ("int8", "int16", 5, 5), ("int8", "int32", 5, 5), ("int8", "int64", 5, 5), ("int8", "uint8", -1, 255), ("int8", "uint8", 12, 12), ("int8", "uint16", -1, 65535), ("int8", "uint16", 12, 12), ("int8", "uint32", -1, 4294967295), ("int8", "uint32", 12, 12), ("int8", "uint64", -1, 18446744073709551615), ("int8", "uint64", 12, 12), ("int16", "int8", 5, 5), ("int16", "int8", -1, -1), ("int16", "int8", 32767, -1), ("int16", "int16", 5, 5), ("int16", "int32", -5, -5), ("int16", "int64", -6, -6), ("int16", "uint8", 32767, 255), ("int16", "uint8", -1, 255), ("int16", "uint16", 32767, 32767), ("int16", "uint16", -1, 65535), ("int16", "uint32", 1000, 1000), ("int16", "uint32", -1, 4294967295), ("int16", "uint64", 1414, 1414), ("int16", "uint64", -1, 18446744073709551615), ("int32", "int8", 5, 5), ("int32", "int8", -1, -1), ("int32", "int8", 2147483647, -1), ("int32", "int16", 5, 5), ("int32", "int16", -1, -1), ("int32", "int16", 2147483647, -1), ("int32", "int32", 5, 5), ("int32", "int64", 5, 5), ("int32", "uint8", 5, 5), ("int32", "uint8", 65535, 255), ("int32", "uint8", -1, 255), ("int32", "uint16", 5, 5), ("int32", "uint16", 2147483647, 65535), ("int32", "uint16", -1, 65535), ("int32", "uint32", 5, 5), ("int32", "uint32", -1, 4294967295), ("int32", "uint64", 5, 5), ("int32", "uint64", -1, 18446744073709551615), ("int64", "int8", 5, 5), ("int64", "int8", -1, -1), ("int64", "int8", 65535, -1), ("int64", "int16", 5, 5), ("int64", "int16", -1, -1), ("int64", "int16", 4294967295, -1), ("int64", "int32", 5, 5), ("int64", "int32", -1, -1), ("int64", "int32", 9223372036854775807, -1), ("int64", "int64", 5, 5), ("int64", "uint8", 5, 5), ("int64", "uint8", 65535, 255), ("int64", "uint8", -1, 255), ("int64", "uint16", 5, 5), ("int64", "uint16", 4294967295, 65535), ("int64", "uint16", -1, 65535), ("int64", "uint32", 5, 5), ("int64", "uint32", 9223372036854775807, 4294967295), ("int64", "uint32", -1, 4294967295), ("int64", "uint64", 5, 5), ("int64", "uint64", -1, 18446744073709551615), ("uint8", "int8", 5, 5), ("uint8", "int8", 255, -1), ("uint8", "int16", 255, 255), ("uint8", "int32", 255, 255), ("uint8", "int64", 255, 255), ("uint8", "uint8", 5, 5), ("uint8", "uint16", 255, 255), ("uint8", "uint32", 255, 255), ("uint8", "uint64", 255, 255), ("uint16", "int8", 5, 5), ("uint16", "int8", 65535, -1), ("uint16", "int16", 5, 5), ("uint16", "int16", 65535, -1), ("uint16", "int32", 65535, 65535), ("uint16", "int64", 65535, 65535), ("uint16", "uint8", 65535, 255), ("uint16", "uint16", 65535, 65535), ("uint16", "uint32", 65535, 65535), ("uint16", "uint64", 65535, 65535), ("uint32", "int8", 4, 4), ("uint32", "int8", 4294967295, -1), ("uint32", "int16", 5, 5), ("uint32", "int16", 4294967295, -1), ("uint32", "int32", 65535, 65535), ("uint32", "int32", 4294967295, -1), ("uint32", "int64", 4294967295, 4294967295), ("uint32", "uint8", 4, 4), ("uint32", "uint8", 65535, 255), ("uint32", "uint16", 4294967295, 65535), ("uint32", "uint32", 5, 5), ("uint32", "uint64", 4294967295, 4294967295), ("uint64", "int8", 4, 4), ("uint64", "int8", 18446744073709551615, -1), ("uint64", "int16", 4, 4), ("uint64", "int16", 18446744073709551615, -1), ("uint64", "int32", 4, 4), ("uint64", "int32", 18446744073709551615, -1), ("uint64", "int64", 4, 4), ("uint64", "int64", 18446744073709551615, -1), ("uint64", "uint8", 5, 5), ("uint64", "uint8", 65535, 255), ("uint64", "uint16", 4294967295, 65535), ("uint64", "uint32", 18446744073709551615, 4294967295), ("uint64", "uint64", 5, 5), ] for src, dest, val, expected in cases: codestr = f""" from __static__ import {src}, {dest}, box def y() -> int: x = {dest}({src}({val})) return box(x) """ with self.subTest(src=src, dest=dest, val=val, expected=expected): with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: y = mod["y"] actual = y() self.assertEqual( actual, expected, f"failing case: {[src, dest, val, actual, expected]}", ) def test_no_cast_after_box(self): codestr = """ from __static__ import int64, box def f(x: int) -> int: y = int64(x) + 1 return box(y) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertNotInBytecode(f, "CAST") self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST", (1, TYPED_INT64)) self.assertEqual(f(3), 4) def test_rand(self): codestr = """ from __static__ import rand, RAND_MAX, box, int64 def test(): x: int64 = rand() return box(x) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertEqual(type(test()), int) def test_rand_max_inlined(self): codestr = """ from __static__ import rand, RAND_MAX, box, int64 def f() -> int: x: int64 = rand() // int64(RAND_MAX) return box(x) """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST") self.assertIsInstance(f(), int) def test_array_get_primitive_idx(self): codestr = """ from __static__ import Array, int8, box def m() -> int: content = list(range(121)) a = Array[int8](content) return box(a[int8(111)]) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode(m, "PRIMITIVE_LOAD_CONST", (111, TYPED_INT8)) self.assertInBytecode(m, "SEQUENCE_GET", SEQ_ARRAY_INT8) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] actual = m() self.assertEqual(actual, 111) def test_array_get_nonprimitive_idx(self): codestr = """ from __static__ import Array, int8, box def m() -> int: content = list(range(121)) a = Array[int8](content) return box(a[111]) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode(m, "LOAD_CONST", 111) self.assertNotInBytecode(m, "PRIMITIVE_LOAD_CONST") self.assertInBytecode(m, "PRIMITIVE_UNBOX") self.assertInBytecode(m, "SEQUENCE_GET", SEQ_ARRAY_INT8) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] actual = m() self.assertEqual(actual, 111) def test_array_get_failure(self): codestr = """ from __static__ import Array, int8, box def m() -> int: a = Array[int8]([1, 3, -5]) return box(a[20]) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] with self.assertRaisesRegex(IndexError, "index out of range"): m() def test_array_get_negative_idx(self): codestr = """ from __static__ import Array, int8, box def m() -> int: a = Array[int8]([1, 3, -5]) return box(a[-1]) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] self.assertEqual(m(), -5) def test_array_set_signed(self): int_types = [ "int8", "int16", "int32", "int64", ] seq_types = { "int8": SEQ_ARRAY_INT8, "int16": SEQ_ARRAY_INT16, "int32": SEQ_ARRAY_INT32, "int64": SEQ_ARRAY_INT64, } signs = ["-", ""] value = 77 for type, sign in itertools.product(int_types, signs): codestr = f""" from __static__ import Array, {type} def m() -> Array[{type}]: a = Array[{type}]([1, 3, -5]) a[1] = {sign}{value} return a """ with self.subTest(type=type, sign=sign): val = -value if sign else value c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode( m, "PRIMITIVE_LOAD_CONST", (val, prim_name_to_type[type]) ) self.assertInBytecode(m, "LOAD_CONST", 1) self.assertInBytecode(m, "SEQUENCE_SET", seq_types[type]) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] if sign: expected = -value else: expected = value result = m() self.assertEqual( result, array("q", [1, expected, -5]), f"Failing case: {type}, {sign}", ) def test_array_set_unsigned(self): uint_types = [ "uint8", "uint16", "uint32", "uint64", ] value = 77 seq_types = { "uint8": SEQ_ARRAY_UINT8, "uint16": SEQ_ARRAY_UINT16, "uint32": SEQ_ARRAY_UINT32, "uint64": SEQ_ARRAY_UINT64, } for type in uint_types: codestr = f""" from __static__ import Array, {type} def m() -> Array[{type}]: a = Array[{type}]([1, 3, 5]) a[1] = {value} return a """ with self.subTest(type=type): c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode( m, "PRIMITIVE_LOAD_CONST", (value, prim_name_to_type[type]) ) self.assertInBytecode(m, "LOAD_CONST", 1) self.assertInBytecode(m, "SEQUENCE_SET", seq_types[type]) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] expected = value result = m() self.assertEqual( result, array("q", [1, expected, 5]), f"Failing case: {type}" ) def test_array_set_negative_idx(self): codestr = """ from __static__ import Array, int8 def m() -> Array[int8]: a = Array[int8]([1, 3, -5]) a[-2] = 7 return a """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode(m, "PRIMITIVE_LOAD_CONST", (7, TYPED_INT8)) self.assertInBytecode(m, "LOAD_CONST", -2) self.assertInBytecode(m, "SEQUENCE_SET", SEQ_ARRAY_INT8) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] self.assertEqual(m(), array("h", [1, 7, -5])) def test_array_set_failure(self) -> object: codestr = """ from __static__ import Array, int8 def m() -> Array[int8]: a = Array[int8]([1, 3, -5]) a[-100] = 7 return a """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode(m, "PRIMITIVE_LOAD_CONST", (7, TYPED_INT8)) self.assertInBytecode(m, "SEQUENCE_SET", SEQ_ARRAY_INT8) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] with self.assertRaisesRegex(IndexError, "index out of range"): m() def test_array_set_failure_invalid_subscript(self): codestr = """ from __static__ import Array, int8 def x(): return object() def m() -> Array[int8]: a = Array[int8]([1, 3, -5]) a[x()] = 7 return a """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") m = self.find_code(c, "m") self.assertInBytecode(m, "PRIMITIVE_LOAD_CONST", (7, TYPED_INT8)) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: m = mod["m"] with self.assertRaisesRegex(TypeError, "array indices must be integers"): m() def test_fast_len_list(self): codestr = """ def f(): l = [1, 2, 3, 4, 5, 6, 7] return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 7) def test_fast_len_str(self): codestr = """ def f(): l = "my str!" return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_STR) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 7) def test_fast_len_str_unicode_chars(self): codestr = """ def f(): l = "\U0001F923" # ROFL emoji return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_STR) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 1) def test_fast_len_tuple(self): codestr = """ def f(a, b): l = (a, b) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_TUPLE) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f("a", "b"), 2) def test_fast_len_set(self): codestr = """ def f(a, b): l = {a, b} return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_SET) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f("a", "b"), 2) def test_fast_len_dict(self): codestr = """ def f(): l = {1: 'a', 2: 'b', 3: 'c', 4: 'd'} return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_DICT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 4) def test_fast_len_conditional_list(self): codestr = """ def f(n: int) -> bool: l = [i for i in range(n)] if l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_str(self): codestr = """ def f(n: int) -> bool: l = f"{'a' * n}" if l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_STR) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_loop_conditional_list(self): codestr = """ def f(n: int) -> bool: l = [i for i in range(n)] while l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_loop_conditional_str(self): codestr = """ def f(n: int) -> bool: l = f"{'a' * n}" while l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_STR) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_loop_conditional_tuple(self): codestr = """ def f(n: int) -> bool: l = tuple(i for i in range(n)) while l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_TUPLE) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_loop_conditional_set(self): codestr = """ def f(n: int) -> bool: l = {i for i in range(n)} while l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_SET) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_tuple(self): codestr = """ def f(n: int) -> bool: l = tuple(i for i in range(n)) if l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_TUPLE) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_set(self): codestr = """ def f(n: int) -> bool: l = {i for i in range(n)} if l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_SET) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_dict(self): codestr = """ def f(n: int) -> bool: l = {i: i for i in range(n)} if l: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_DICT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_list_subclass(self): codestr = """ from typing import List class MyList(list): def __len__(self): return 1729 def f(n: int, flag: bool) -> bool: x: List[int] = [i for i in range(n)] if flag: x = MyList([i for i in range(n)]) if x: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for boolean, length in itertools.product((True, False), [0, 7]): self.assertEqual( f(length, boolean), length > 0 or boolean, f"length={length}, flag={boolean}", ) def test_fast_len_conditional_str_subclass(self): codestr = """ class MyStr(str): def __len__(self): return 1729 def f(n: int, flag: bool) -> bool: x: str = f"{'a' * n}" if flag: x = MyStr(f"{'a' * n}") if x: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_STR | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for boolean, length in itertools.product((True, False), [0, 7]): self.assertEqual( f(length, boolean), length > 0 or boolean, f"length={length}, flag={boolean}", ) def test_fast_len_conditional_tuple_subclass(self): codestr = """ class Mytuple(tuple): def __len__(self): return 1729 def f(n: int, flag: bool) -> bool: x = tuple(i for i in range(n)) if flag: x = Mytuple([i for i in range(n)]) if x: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_TUPLE | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for boolean, length in itertools.product((True, False), [0, 7]): self.assertEqual( f(length, boolean), length > 0 or boolean, f"length={length}, flag={boolean}", ) def test_fast_len_conditional_set_subclass(self): codestr = """ class Myset(set): def __len__(self): return 1729 def f(n: int, flag: bool) -> bool: x = set(i for i in range(n)) if flag: x = Myset([i for i in range(n)]) if x: return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_SET | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for boolean, length in itertools.product((True, False), [0, 7]): self.assertEqual( f(length, boolean), length > 0 or boolean, f"length={length}, flag={boolean}", ) def test_fast_len_conditional_list_funcarg(self): codestr = """ def z(b: object) -> bool: return bool(b) def f(n: int) -> bool: l = [i for i in range(n)] if z(l): return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") # Since the list is given to z(), do not optimize the check # with FAST_LEN self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_str_funcarg(self): codestr = """ def z(b: object) -> bool: return bool(b) def f(n: int) -> bool: l = f"{'a' * n}" if z(l): return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") # Since the list is given to z(), do not optimize the check # with FAST_LEN self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_tuple_funcarg(self): codestr = """ def z(b: object) -> bool: return bool(b) def f(n: int) -> bool: l = tuple(i for i in range(n)) if z(l): return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") # Since the tuple is given to z(), do not optimize the check # with FAST_LEN self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_set_funcarg(self): codestr = """ def z(b: object) -> bool: return bool(b) def f(n: int) -> bool: l = set(i for i in range(n)) if z(l): return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") # Since the set is given to z(), do not optimize the check # with FAST_LEN self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_conditional_dict_funcarg(self): codestr = """ def z(b) -> bool: return bool(b) def f(n: int) -> bool: l = {i: i for i in range(n)} if z(l): return True return False """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") # Since the dict is given to z(), do not optimize the check # with FAST_LEN self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] for length in [0, 7]: self.assertEqual(f(length), length > 0) def test_fast_len_list_subclass(self): codestr = """ class mylist(list): def __len__(self): return 1111 def f(): l = mylist([1, 2]) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 1111) def test_fast_len_str_subclass(self): codestr = """ class mystr(str): def __len__(self): return 1111 def f(): s = mystr("a") return len(s) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 1111) def test_fast_len_tuple_subclass(self): codestr = """ class mytuple(tuple): def __len__(self): return 1111 def f(): l = mytuple([1, 2]) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 1111) def test_fast_len_set_subclass(self): codestr = """ class myset(set): def __len__(self): return 1111 def f(): l = myset([1, 2]) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 1111) def test_fast_len_dict_subclass(self): codestr = """ from typing import Dict class mydict(Dict[str, int]): def __len__(self): return 1111 def f(): l = mydict(a=1, b=2) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertNotInBytecode(f, "FAST_LEN") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(), 1111) def test_fast_len_list_subclass_2(self): codestr = """ class mylist(list): def __len__(self): return 1111 def f(x): l = [1, 2] if x: l = mylist([1, 2]) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_LIST | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(True), 1111) def test_fast_len_str_subclass_2(self): codestr = """ class mystr(str): def __len__(self): return 1111 def f(x): s = "abc" if x: s = mystr("pqr") return len(s) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_STR | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(True), 1111) self.assertEqual(f(False), 3) def test_fast_len_tuple_subclass_2(self): codestr = """ class mytuple(tuple): def __len__(self): return 1111 def f(x, a, b): l = (a, b) if x: l = mytuple([a, b]) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_TUPLE | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(True, 1, 2), 1111) def test_fast_len_dict_subclass_2(self): codestr = """ from typing import Dict class mydict(Dict[str, int]): def __len__(self): return 1111 def f(x, a, b): l: Dict[str, int] = {'c': 3} if x: l = mydict(a=1, b=2) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_DICT | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(True, 1, 2), 1111) def test_fast_len_set_subclass_2(self): codestr = """ class myset(set): def __len__(self): return 1111 def f(x, a, b): l = {a, b} if x: l = myset([a, b]) return len(l) """ c = self.compile(codestr, StaticCodeGenerator, modname="foo.py") f = self.find_code(c, "f") self.assertInBytecode(f, "FAST_LEN", FAST_LEN_SET | FAST_LEN_INEXACT) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f(True, 1, 2), 1111) def test_dynamic_type_param(self): """DYNAMIC as type param of generic doesn't render the whole type DYNAMIC.""" codestr = """ from __static__ import int64, clen from nonstatic import Foo from typing import Dict def f(d: Dict[Foo, int]): x: int64 = clen(d) """ self.compile(codestr) def test_checked_dict(self): x = chkdict[str, str]() x["abc"] = "foo" self.assertEqual(repr(x), "{'abc': 'foo'}") x = chkdict[str, int]() x["abc"] = 42 x = chkdict[int, str]() x[42] = "abc" def test_checked_dict_optional(self): x = chkdict[str, Optional[str]]() x["abc"] = None x = chkdict[Optional[str], str]() x[None] = "abc" def test_checked_dict_nonoptional(self): x = chkdict[str, Optional[str]]() with self.assertRaises(TypeError): x[None] = "abc" x = chkdict[Optional[str], str]() with self.assertRaises(TypeError): x["abc"] = None def test_checked_dict_types_enforced(self): x = chkdict[str, str]() with self.assertRaises(TypeError): x[42] = "abc" self.assertEqual(x, {}) with self.assertRaises(TypeError): x["abc"] = 42 self.assertEqual(x, {}) x = chkdict[str, int]() with self.assertRaises(TypeError): x[42] = 42 self.assertEqual(x, {}) with self.assertRaises(TypeError): x["abc"] = "abc" self.assertEqual(x, {}) def test_checked_dict_ctor(self): self.assertEqual(chkdict[str, str](x="abc"), {"x": "abc"}) self.assertEqual(chkdict[str, int](x=42), {"x": 42}) self.assertEqual(chkdict[str, str]({"x": "abc"}), {"x": "abc"}) self.assertEqual(chkdict[str, str]([("a", "b")]), {"a": "b"}) self.assertEqual(chkdict[str, str]([("a", "b")]), {"a": "b"}) self.assertEqual(chkdict[str, str](chkdict[str, str](x="abc")), {"x": "abc"}) self.assertEqual(chkdict[str, str](chkdict[str, object](x="abc")), {"x": "abc"}) self.assertEqual(chkdict[str, str](UserDict(x="abc")), {"x": "abc"}) self.assertEqual(chkdict[str, str](UserDict(x="abc"), x="foo"), {"x": "foo"}) def test_checked_dict_bad_ctor(self): with self.assertRaises(TypeError): chkdict[str, str](None) def test_checked_dict_setdefault(self): x = chkdict[str, str]() x.setdefault("abc", "foo") self.assertEqual(x, {"abc": "foo"}) def test_checked_dict___module__(self): class Lol: pass x = chkdict[int, Lol]() self.assertEqual(type(x).__module__, "__static__") def test_checked_dict_setdefault_bad_values(self): x = chkdict[str, int]() with self.assertRaises(TypeError): x.setdefault("abc", "abc") self.assertEqual(x, {}) with self.assertRaises(TypeError): x.setdefault(42, 42) self.assertEqual(x, {}) def test_checked_dict_fromkeys(self): x = chkdict[str, int].fromkeys("abc", 42) self.assertEqual(x, {"a": 42, "b": 42, "c": 42}) def test_checked_dict_fromkeys_optional(self): x = chkdict[Optional[str], int].fromkeys(["a", "b", "c", None], 42) self.assertEqual(x, {"a": 42, "b": 42, "c": 42, None: 42}) x = chkdict[str, Optional[int]].fromkeys("abc", None) self.assertEqual(x, {"a": None, "b": None, "c": None}) def test_checked_dict_fromkeys_bad_types(self): with self.assertRaises(TypeError): chkdict[str, int].fromkeys([2], 42) with self.assertRaises(TypeError): chkdict[str, int].fromkeys("abc", object()) with self.assertRaises(TypeError): chkdict[str, int].fromkeys("abc") def test_checked_dict_copy(self): x = chkdict[str, str](x="abc") self.assertEqual(type(x), chkdict[str, str]) self.assertEqual(x, {"x": "abc"}) def test_checked_dict_clear(self): x = chkdict[str, str](x="abc") x.clear() self.assertEqual(x, {}) def test_checked_dict_update(self): x = chkdict[str, str](x="abc") x.update(y="foo") self.assertEqual(x, {"x": "abc", "y": "foo"}) x.update({"z": "bar"}) self.assertEqual(x, {"x": "abc", "y": "foo", "z": "bar"}) def test_checked_dict_update_bad_type(self): x = chkdict[str, int]() with self.assertRaises(TypeError): x.update(x="abc") self.assertEqual(x, {}) with self.assertRaises(TypeError): x.update({"x": "abc"}) with self.assertRaises(TypeError): x.update({24: 42}) self.assertEqual(x, {}) def test_checked_dict_keys(self): x = chkdict[str, int](x=2) self.assertEqual(list(x.keys()), ["x"]) x = chkdict[str, int](x=2, y=3) self.assertEqual(list(x.keys()), ["x", "y"]) def test_checked_dict_values(self): x = chkdict[str, int](x=2, y=3) self.assertEqual(list(x.values()), [2, 3]) def test_checked_dict_items(self): x = chkdict[str, int](x=2) self.assertEqual( list(x.items()), [ ("x", 2), ], ) x = chkdict[str, int](x=2, y=3) self.assertEqual(list(x.items()), [("x", 2), ("y", 3)]) def test_checked_dict_pop(self): x = chkdict[str, int](x=2) y = x.pop("x") self.assertEqual(y, 2) with self.assertRaises(KeyError): x.pop("z") def test_checked_dict_popitem(self): x = chkdict[str, int](x=2) y = x.popitem() self.assertEqual(y, ("x", 2)) with self.assertRaises(KeyError): x.popitem() def test_checked_dict_get(self): x = chkdict[str, int](x=2) self.assertEqual(x.get("x"), 2) self.assertEqual(x.get("y", 100), 100) def test_checked_dict_errors(self): x = chkdict[str, int](x=2) with self.assertRaises(TypeError): x.get(100) with self.assertRaises(TypeError): x.get("x", "abc") def test_checked_dict_sizeof(self): x = chkdict[str, int](x=2).__sizeof__() self.assertEqual(type(x), int) def test_checked_dict_getitem(self): x = chkdict[str, int](x=2) self.assertEqual(x.__getitem__("x"), 2) def test_checked_dict_free_list(self): t1 = chkdict[str, int] t2 = chkdict[str, str] x = t1() x_id1 = id(x) del x x = t2() x_id2 = id(x) self.assertEqual(x_id1, x_id2) def test_check_args(self): """ Tests whether CHECK_ARGS can handle variables which are in a Cell, and are a positional arg at index 0. """ codestr = """ def use(i: object) -> object: return i def outer(x: int) -> object: def inner() -> None: use(x) return use(x) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(1), 1) def test_check_args_2(self): """ Tests whether CHECK_ARGS can handle multiple variables which are in a Cell, and are positional args. """ codestr = """ def use(i: object) -> object: return i def outer(x: int, y: str) -> object: def inner() -> None: use(x) use(y) use(x) return use(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(1, "yo"), "yo") # Force JIT-compiled code to go through argument checks after # keyword arg binding self.assertEqual(outer(1, y="yo"), "yo") def test_check_args_3(self): """ Tests whether CHECK_ARGS can handle variables which are in a Cell, and are a positional arg at index > 0. """ codestr = """ def use(i: object) -> object: return i def outer(x: int, y: str) -> object: def inner() -> None: use(y) use(x) return use(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(1, "yo"), "yo") # Force JIT-compiled code to go through argument checks after # keyword arg binding self.assertEqual(outer(1, y="yo"), "yo") def test_check_args_4(self): """ Tests whether CHECK_ARGS can handle variables which are in a Cell, and are a kwarg at index 0. """ codestr = """ def use(i: object) -> object: return i def outer(x: int = 0) -> object: def inner() -> None: use(x) return use(x) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(1), 1) def test_check_args_5(self): """ Tests whether CHECK_ARGS can handle variables which are in a Cell, and are a kw-only arg. """ codestr = """ def use(i: object) -> object: return i def outer(x: int, *, y: str = "lol") -> object: def inner() -> None: use(y) return use(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(1, y="hi"), "hi") def test_check_args_6(self): """ Tests whether CHECK_ARGS can handle variables which are in a Cell, and are a pos-only arg. """ codestr = """ def use(i: object) -> object: return i def outer(x: int, /, y: str) -> object: def inner() -> None: use(y) return use(y) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(1, "hi"), "hi") def test_check_args_7(self): """ Tests whether CHECK_ARGS can handle multiple variables which are in a Cell, and are a mix of positional, pos-only and kw-only args. """ codestr = """ def use(i: object) -> object: return i def outer(x: int, /, y: int, *, z: str = "lol") -> object: def inner() -> None: use(x) use(y) use(z) return use(x), use(y), use(z) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: outer = mod["outer"] self.assertEqual(outer(3, 2, z="hi"), (3, 2, "hi")) def test_str_split(self): codestr = """ def get_str() -> str: return "something here" def test() -> str: a, b = get_str().split(None, 1) return b """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: test = mod["test"] self.assertEqual(test(), "here") def test_vtable_shadow_builtin_subclass_after_init(self): """Shadowing methods on subclass of list after vtables are inited.""" class MyList(list): pass def myreverse(self): return 1 codestr = """ def f(l: list): l.reverse() return l """ f = self.find_code(self.compile(codestr), "f") self.assertInBytecode( f, "INVOKE_METHOD", ((("builtins", "list", "reverse"), 0)) ) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: # Now cause vtables to be inited self.assertEqual(mod["f"]([1, 2]), [2, 1]) # And now patch MyList.reverse = myreverse self.assertEqual(MyList().reverse(), 1) def test_vtable_shadow_builtin_subclass_before_init(self): """Shadowing methods on subclass of list before vtables are inited.""" # Create a subclass of list... class MyList(list): pass def myreverse(self): return 1 # ... and override a slot from list with a non-static func MyList.reverse = myreverse codestr = """ def f(l: list): l.reverse() return l """ f = self.find_code(self.compile(codestr), "f") self.assertInBytecode( f, "INVOKE_METHOD", ((("builtins", "list", "reverse"), 0)) ) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: # Now cause vtables to be inited self.assertEqual(mod["f"]([1, 2]), [2, 1]) # ... and this should not blow up when we remove the override. del MyList.reverse self.assertEqual(MyList().reverse(), None) def test_vtable_shadow_static_subclass(self): """Shadowing methods of a static type before its inited should not bypass typechecks.""" # Define a static type and shadow a subtype method before invoking. codestr = """ class StaticType: def foo(self) -> int: return 1 class SubType(StaticType): pass def goodfoo(self): return 2 SubType.foo = goodfoo def f(x: StaticType) -> int: return x.foo() """ f = self.find_code(self.compile(codestr), "f") self.assertInBytecode( f, "INVOKE_METHOD", ((("<module>", "StaticType", "foo"), 0)) ) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: SubType = mod["SubType"] # Now invoke: self.assertEqual(mod["f"](SubType()), 2) # And replace the function again, forcing us to find the right slot type: def badfoo(self): return "foo" SubType.foo = badfoo with self.assertRaisesRegex(TypeError, "expected int, got str"): mod["f"](SubType()) def test_vtable_shadow_static_subclass_nonstatic_patch(self): """Shadowing methods of a static type before its inited should not bypass typechecks.""" code1 = """ def nonstaticfoo(self): return 2 """ with self.in_module( code1, code_gen=PythonCodeGenerator, name="nonstatic" ) as mod1: # Define a static type and shadow a subtype method with a non-static func before invoking. codestr = """ from nonstatic import nonstaticfoo class StaticType: def foo(self) -> int: return 1 class SubType(StaticType): pass SubType.foo = nonstaticfoo def f(x: StaticType) -> int: return x.foo() def badfoo(self): return "foo" """ code = self.compile(codestr) f = self.find_code(code, "f") self.assertInBytecode( f, "INVOKE_METHOD", ((("<module>", "StaticType", "foo"), 0)) ) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: SubType = mod["SubType"] badfoo = mod["badfoo"] # And replace the function again, forcing us to find the right slot type: SubType.foo = badfoo with self.assertRaisesRegex(TypeError, "expected int, got str"): mod["f"](SubType()) def test_vtable_shadow_grandparent(self): codestr = """ class Base: def foo(self) -> int: return 1 class Sub(Base): pass class Grand(Sub): pass def f(x: Base) -> int: return x.foo() def grandfoo(self): return "foo" """ f = self.find_code(self.compile(codestr), "f") self.assertInBytecode(f, "INVOKE_METHOD", ((("<module>", "Base", "foo"), 0))) with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: Grand = mod["Grand"] grandfoo = mod["grandfoo"] f = mod["f"] # init vtables self.assertEqual(f(Grand()), 1) # patch in an override of the grandparent method Grand.foo = grandfoo with self.assertRaisesRegex(TypeError, "expected int, got str"): f(Grand()) def test_for_iter_list(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: acc.append(i + 1) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(4), [i + 1 for i in range(4)]) def test_for_iter_tuple(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = tuple([i for i in range(n)]) for i in l: acc.append(i + 1) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(4), [i + 1 for i in range(4)]) def test_for_iter_sequence_orelse(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: acc.append(i + 1) else: acc.append(999) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(4), [i + 1 for i in range(4)] + [999]) def test_for_iter_sequence_break(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: if i == 3: break acc.append(i + 1) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(5), [1, 2, 3]) def test_for_iter_sequence_orelse_break(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: if i == 2: break acc.append(i + 1) else: acc.append(999) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(4), [1, 2]) def test_for_iter_sequence_return(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: if i == 3: return acc acc.append(i + 1) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(6), [1, 2, 3]) def test_nested_for_iter_sequence(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: for j in l: acc.append(i + j) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(3), [0, 1, 2, 1, 2, 3, 2, 3, 4]) def test_nested_for_iter_sequence_break(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: for j in l: if j == 2: break acc.append(i + j) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(3), [0, 1, 1, 2, 2, 3]) def test_nested_for_iter_sequence_return(self): codestr = """ from typing import List def f(n: int) -> List: acc = [] l = [i for i in range(n)] for i in l: for j in l: if j == 1: return acc acc.append(i + j) return acc """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(3), [0]) def test_for_iter_unchecked_get(self): """We don't need to check sequence bounds when we've just compared with the list size.""" codestr = """ def f(): l = [1, 2, 3] acc = [] for x in l: acc.append(x) return acc """ with self.in_module(codestr) as mod: f = mod["f"] self.assertInBytecode(f, "SEQUENCE_GET", SEQ_LIST | SEQ_SUBSCR_UNCHECKED) self.assertEqual(f(), [1, 2, 3]) def test_for_iter_list_modified(self): codestr = """ def f(): l = [1, 2, 3, 4, 5] acc = [] for x in l: acc.append(x) l[2:] = [] return acc """ with self.in_module(codestr) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertEqual(f(), [1, 2]) def test_sorted(self): """sorted() builtin returns an Exact[List].""" codestr = """ from typing import Iterable def f(l: Iterable[int]): for x in sorted(l): pass """ with self.in_module(codestr) as mod: f = mod["f"] self.assertNotInBytecode(f, "FOR_ITER") self.assertInBytecode(f, "REFINE_TYPE", ("builtins", "list")) def test_min(self): codestr = """ def f(a: int, b: int) -> int: return min(a, b) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "COMPARE_OP", "<=") self.assertInBytecode(f, "POP_JUMP_IF_FALSE") self.assertEqual(f(1, 3), 1) self.assertEqual(f(3, 1), 1) def test_min_stability(self): codestr = """ def f(a: int, b: int) -> int: return min(a, b) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "COMPARE_OP", "<=") self.assertInBytecode(f, "POP_JUMP_IF_FALSE") # p & q should be different objects, but with same value p = int("11334455667") q = int("11334455667") self.assertNotEqual(id(p), id(q)) # Since p and q are equal, the returned value should be the first arg self.assertEqual(id(f(p, q)), id(p)) self.assertEqual(id(f(q, p)), id(q)) def test_max(self): codestr = """ def f(a: int, b: int) -> int: return max(a, b) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "COMPARE_OP", ">=") self.assertInBytecode(f, "POP_JUMP_IF_FALSE") self.assertEqual(f(1, 3), 3) self.assertEqual(f(3, 1), 3) def test_max_stability(self): codestr = """ def f(a: int, b: int) -> int: return max(a, b) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "COMPARE_OP", ">=") self.assertInBytecode(f, "POP_JUMP_IF_FALSE") # p & q should be different objects, but with same value p = int("11334455667") q = int("11334455667") self.assertNotEqual(id(p), id(q)) # Since p and q are equal, the returned value should be the first arg self.assertEqual(id(f(p, q)), id(p)) self.assertEqual(id(f(q, p)), id(q)) def test_extremum_primitive(self): codestr = """ from __static__ import int8 def f() -> None: a: int8 = 4 b: int8 = 5 min(a, b) """ with self.assertRaisesRegex( TypedSyntaxError, "Call argument cannot be a primitive" ): self.compile(codestr, StaticCodeGenerator, modname="foo.py") def test_extremum_non_specialization_kwarg(self): codestr = """ def f() -> None: a = "4" b = "5" min(a, b, key=int) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "COMPARE_OP") self.assertNotInBytecode(f, "POP_JUMP_IF_FALSE") def test_extremum_non_specialization_stararg(self): codestr = """ def f() -> None: a = [3, 4] min(*a) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "COMPARE_OP") self.assertNotInBytecode(f, "POP_JUMP_IF_FALSE") def test_extremum_non_specialization_dstararg(self): codestr = """ def f() -> None: k = { "default": 5 } min(3, 4, **k) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "COMPARE_OP") self.assertNotInBytecode(f, "POP_JUMP_IF_FALSE") def test_try_return_finally(self): codestr = """ from typing import List def f1(x: List): try: return finally: x.append("hi") """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f1 = mod["f1"] l = [] f1(l) self.assertEqual(l, ["hi"]) def test_cbool(self): for b in ("True", "False"): codestr = f""" from __static__ import cbool def f() -> int: x: cbool = {b} if x: return 1 else: return 2 """ with self.subTest(b=b): with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "PRIMITIVE_LOAD_CONST") self.assertInBytecode( f, "STORE_LOCAL", (0, ("__static__", "cbool")) ) self.assertInBytecode(f, "POP_JUMP_IF_ZERO") self.assertEqual(f(), 1 if b == "True" else 2) def test_cbool_field(self): codestr = """ from __static__ import cbool class C: def __init__(self, x: cbool) -> None: self.x: cbool = x def f(c: C): if c.x: return True return False """ with self.in_module(codestr) as mod: f, C = mod["f"], mod["C"] self.assertInBytecode(f, "LOAD_FIELD", (mod["__name__"], "C", "x")) self.assertInBytecode(f, "POP_JUMP_IF_ZERO") self.assertIs(C(True).x, True) self.assertIs(C(False).x, False) self.assertIs(f(C(True)), True) self.assertIs(f(C(False)), False) def test_cbool_cast(self): codestr = """ from __static__ import cbool def f(y: bool) -> int: x: cbool = y if x: return 1 else: return 2 """ with self.assertRaisesRegex(TypedSyntaxError, type_mismatch("bool", "cbool")): self.compile(codestr, StaticCodeGenerator, modname="foo") def test_primitive_compare_returns_cbool(self): codestr = """ from __static__ import cbool, int64 def f(x: int64, y: int64) -> cbool: return x == y """ with self.in_module(codestr) as mod: f = mod["f"] self.assertIs(f(1, 1), True) self.assertIs(f(1, 2), False) def test_no_cbool_math(self): codestr = """ from __static__ import cbool def f(x: cbool, y: cbool) -> cbool: return x + y """ with self.assertRaisesRegex( TypedSyntaxError, "cbool is not a valid operand type for add" ): self.compile(codestr) def test_chkdict_del(self): codestr = """ def f(): x = {} x[1] = "a" x[2] = "b" del x[1] return x """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] ret = f() self.assertNotIn(1, ret) self.assertIn(2, ret) def test_final_constant_folding_int(self): codestr = """ from typing import Final X: Final[int] = 1337 def plus_1337(i: int) -> int: return i + X """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: plus_1337 = mod["plus_1337"] self.assertInBytecode(plus_1337, "LOAD_CONST", 1337) self.assertNotInBytecode(plus_1337, "LOAD_GLOBAL") self.assertEqual(plus_1337(3), 1340) def test_final_constant_folding_bool(self): codestr = """ from typing import Final X: Final[bool] = True def f() -> bool: return not X """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "LOAD_CONST", True) self.assertNotInBytecode(f, "LOAD_GLOBAL") self.assertFalse(f()) def test_final_constant_folding_str(self): codestr = """ from typing import Final X: Final[str] = "omg" def f() -> str: return X[1] """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "LOAD_CONST", "omg") self.assertNotInBytecode(f, "LOAD_GLOBAL") self.assertEqual(f(), "m") def test_final_constant_folding_disabled_on_nonfinals(self): codestr = """ from typing import Final X: str = "omg" def f() -> str: return X[1] """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "LOAD_CONST", "omg") self.assertInBytecode(f, "LOAD_GLOBAL", "X") self.assertEqual(f(), "m") def test_final_constant_folding_disabled_on_nonconstant_finals(self): codestr = """ from typing import Final def p() -> str: return "omg" X: Final[str] = p() def f() -> str: return X[1] """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertNotInBytecode(f, "LOAD_CONST", "omg") self.assertInBytecode(f, "LOAD_GLOBAL", "X") self.assertEqual(f(), "m") def test_final_constant_folding_shadowing(self): codestr = """ from typing import Final X: Final[str] = "omg" def f() -> str: X = "lol" return X[1] """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertInBytecode(f, "LOAD_CONST", "lol") self.assertNotInBytecode(f, "LOAD_GLOBAL", "omg") self.assertEqual(f(), "o") def test_final_constant_folding_in_module_scope(self): codestr = """ from typing import Final X: Final[int] = 21 y = X + 3 """ c = self.compile(codestr, generator=StaticCodeGenerator, modname="foo.py") self.assertNotInBytecode(c, "LOAD_NAME", "X") with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: self.assertEqual(mod["y"], 24) def test_final_constant_in_module_scope(self): codestr = """ from typing import Final X: Final[int] = 21 """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: self.assertEqual(mod["__final_constants__"], ("X",)) def test_final_nonconstant_in_module_scope(self): codestr = """ from typing import Final def p() -> str: return "omg" X: Final[str] = p() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: self.assertEqual(mod["__final_constants__"], ()) def test_double_load_const(self): codestr = """ from __static__ import double def t(): pi: double = 3.14159 """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: t = mod["t"] self.assertInBytecode(t, "PRIMITIVE_LOAD_CONST", (3.14159, TYPED_DOUBLE)) t() self.assert_jitted(t) def test_double_box(self): codestr = """ from __static__ import double, box def t() -> float: pi: double = 3.14159 return box(pi) """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: t = mod["t"] self.assertInBytecode(t, "PRIMITIVE_LOAD_CONST", (3.14159, TYPED_DOUBLE)) self.assertNotInBytecode(t, "CAST") self.assertEqual(t(), 3.14159) self.assert_jitted(t) def test_none_not(self): codestr = """ def t() -> bool: x = None if not x: return True else: return False """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: t = mod["t"] self.assertInBytecode(t, "POP_JUMP_IF_TRUE") self.assertTrue(t()) def test_unbox_final_inlined(self): for func in ["unbox", "int64"]: with self.subTest(func=func): codestr = f""" from typing import Final from __static__ import int64, unbox MY_FINAL: Final[int] = 111 def t() -> bool: i: int64 = 64 if i < {func}(MY_FINAL): return True else: return False """ with self.in_module(codestr) as mod: t = mod["t"] self.assertInBytecode(t, "PRIMITIVE_LOAD_CONST", (111, TYPED_INT64)) self.assertEqual(t(), True) def test_augassign_inexact(self): codestr = """ def something(): return 3 def t(): a: int = something() b = 0 b += a return b """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: t = mod["t"] self.assertInBytecode(t, "INPLACE_ADD") self.assertEqual(t(), 3) def test_qualname(self): codestr = """ def f(): pass class C: def x(self): pass @staticmethod def sm(): pass @classmethod def cm(): pass def f(self): class G: def y(self): pass return G.y """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] C = mod["C"] self.assertEqual(cinder._get_qualname(f.__code__), "f") self.assertEqual(cinder._get_qualname(C.x.__code__), "C.x") self.assertEqual(cinder._get_qualname(C.sm.__code__), "C.sm") self.assertEqual(cinder._get_qualname(C.cm.__code__), "C.cm") self.assertEqual(cinder._get_qualname(C().f().__code__), "C.f.<locals>.G.y") def test_refine_optional_name(self): codestr = """ from typing import Optional def f(s: Optional[str]) -> bytes: return s.encode("utf-8") if s else b"" """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: f = mod["f"] self.assertEqual(f("A"), b"A") self.assertEqual(f(None), b"") def test_donotcompile_fn(self): codestr = """ from __static__ import _donotcompile def a() -> int: return 1 @_donotcompile def fn() -> None: a() + 2 def fn2() -> None: a() + 2 """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: fn = mod["fn"] self.assertInBytecode(fn, "CALL_FUNCTION") self.assertNotInBytecode(fn, "INVOKE_FUNCTION") self.assertFalse(fn.__code__.co_flags & CO_STATICALLY_COMPILED) self.assertEqual(fn(), None) fn2 = mod["fn2"] self.assertNotInBytecode(fn2, "CALL_FUNCTION") self.assertInBytecode(fn2, "INVOKE_FUNCTION") self.assertTrue(fn2.__code__.co_flags & CO_STATICALLY_COMPILED) self.assertEqual(fn2(), None) def test_donotcompile_method(self): codestr = """ from __static__ import _donotcompile def a() -> int: return 1 class C: @_donotcompile def fn() -> None: a() + 2 def fn2() -> None: a() + 2 c = C() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] fn2 = C.fn2 self.assertNotInBytecode(fn2, "CALL_FUNCTION") self.assertInBytecode(fn2, "INVOKE_FUNCTION") self.assertTrue(fn2.__code__.co_flags & CO_STATICALLY_COMPILED) self.assertEqual(fn2(), None) def test_donotcompile_class(self): codestr = """ from __static__ import _donotcompile def a() -> int: return 1 @_donotcompile class C: def fn() -> None: a() + 2 @_donotcompile class D: a() c = C() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] fn = C.fn self.assertInBytecode(fn, "CALL_FUNCTION") self.assertNotInBytecode(fn, "INVOKE_FUNCTION") self.assertFalse(fn.__code__.co_flags & CO_STATICALLY_COMPILED) self.assertEqual(fn(), None) D = mod["D"] def test_donotcompile_lambda(self): codestr = """ from __static__ import _donotcompile def a() -> int: return 1 class C: @_donotcompile def fn() -> None: z = lambda: a() + 2 z() def fn2() -> None: z = lambda: a() + 2 z() c = C() """ with self.in_module(codestr, code_gen=StaticCodeGenerator) as mod: C = mod["C"] fn = C.fn lambda_code = self.find_code(fn.__code__) self.assertNotInBytecode(lambda_code, "INVOKE_FUNCTION") self.assertFalse(lambda_code.co_flags & CO_STATICALLY_COMPILED) self.assertEqual(fn(), None) fn2 = C.fn2 lambda_code2 = self.find_code(fn2.__code__) self.assertInBytecode(lambda_code2, "INVOKE_FUNCTION") self.assertTrue(lambda_code2.co_flags & CO_STATICALLY_COMPILED) self.assertEqual(fn2(), None) def test_double_binop(self): tests = [ (1.732, 2.0, "+", 3.732), (1.732, 2.0, "-", -0.268), (1.732, 2.0, "/", 0.866), (1.732, 2.0, "*", 3.464), (1.732, 2, "+", 3.732), ] if cinderjit is not None: # test for division by zero tests.append((1.732, 0.0, "/", float("inf"))) for x, y, op, res in tests: codestr = f""" from __static__ import double, box def testfunc(tst): x: double = {x} y: double = {y} z: double = x {op} y return box(z) """ with self.subTest(type=type, x=x, y=y, op=op, res=res): with self.in_module(codestr) as mod: f = mod["testfunc"] self.assertEqual(f(False), res, f"{type} {x} {op} {y} {res}") def test_primitive_stack_spill(self): # Create enough locals that some must get spilled to stack, to test # shuffling stack-spilled values across basic block transitions, and # field reads/writes with stack-spilled values. These can create # mem->mem moves that otherwise wouldn't exist, and trigger issues # like push/pop not supporting 8 or 32 bits on x64. varnames = string.ascii_lowercase[:20] sizes = ["uint8", "int16", "int32", "int64"] for size in sizes: indent = " " * 20 attrs = f"\n{indent}".join(f"{var}: {size}" for var in varnames) inits = f"\n{indent}".join( f"{var}: {size} = {val}" for val, var in enumerate(varnames) ) assigns = f"\n{indent}".join(f"val.{var} = {var}" for var in varnames) reads = f"\n{indent}".join(f"{var} = val.{var}" for var in varnames) indent = " " * 24 incrs = f"\n{indent}".join(f"{var} += 1" for var in varnames) codestr = f""" from __static__ import {size} class C: {attrs} def f(val: C, flag: {size}) -> {size}: {inits} if flag: {incrs} {assigns} {reads} return {' + '.join(varnames)} """ with self.subTest(size=size): with self.in_module(codestr) as mod: f, C = mod["f"], mod["C"] c = C() self.assertEqual(f(c, 0), sum(range(len(varnames)))) for val, var in enumerate(varnames): self.assertEqual(getattr(c, var), val) c = C() self.assertEqual(f(c, 1), sum(range(len(varnames) + 1))) for val, var in enumerate(varnames): self.assertEqual(getattr(c, var), val + 1) def test_class_static_tpflag(self): codestr = """ class A: pass """ with self.in_module(codestr) as mod: A = mod["A"] self.assertTrue(is_type_static(A)) class B: pass self.assertFalse(is_type_static(B)) if __name__ == "__main__": unittest.main()
31.379091
115
0.477989
46,725
438,209
4.318802
0.027651
0.028618
0.021061
0.031002
0.800967
0.756754
0.716734
0.683378
0.646965
0.612371
0
0.033624
0.398883
438,209
13,964
116
31.381338
0.732453
0.017024
0
0.682956
0
0.003872
0.366519
0.002957
0.000086
0
0.000798
0.000358
0.120193
1
0.073389
false
0.013766
0.040867
0.002151
0.191259
0.001205
0
0
0
null
0
0
0
1
1
1
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
4
163db94238c78058f92e5cadb2f54dbefbf0bfa5
138
py
Python
great_expectations/render/view/__init__.py
cicdw/great_expectations
0aecddf7da591df19389c8abadbb1700a51b8739
[ "Apache-2.0" ]
2
2020-05-07T18:16:17.000Z
2020-05-07T18:16:21.000Z
great_expectations/render/view/__init__.py
noncomposmentis/great_expectations
8155b1f20a88aa186745698792856f84d82f33ef
[ "Apache-2.0" ]
1
2020-03-26T12:34:24.000Z
2020-03-26T12:34:24.000Z
great_expectations/render/view/__init__.py
noncomposmentis/great_expectations
8155b1f20a88aa186745698792856f84d82f33ef
[ "Apache-2.0" ]
null
null
null
from .view import ( DefaultJinjaPageView, DefaultJinjaIndexPageView, DefaultJinjaSectionView, DefaultJinjaComponentView )
19.714286
30
0.775362
7
138
15.285714
1
0
0
0
0
0
0
0
0
0
0
0
0.181159
138
6
31
23
0.946903
0
0
0
0
0
0
0
0
0
0
0
0
1
0
true
0
0.166667
0
0.166667
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
0
0
0
0
0
0
4
164b4187393df6f8512dd9509d7d45c178c35539
1,609
py
Python
ludo/test_estrategias.py
tinogomes/mob
1fde311e9c34e9f3d77d1f11f50b803f68a0183d
[ "MIT" ]
null
null
null
ludo/test_estrategias.py
tinogomes/mob
1fde311e9c34e9f3d77d1f11f50b803f68a0183d
[ "MIT" ]
null
null
null
ludo/test_estrategias.py
tinogomes/mob
1fde311e9c34e9f3d77d1f11f50b803f68a0183d
[ "MIT" ]
null
null
null
from estrategias import Veloz, prioridade, sacana import pytest @pytest.mark.parametrize('pinos, passos, ordem', ( # com pinos na base ((0, 0, 0, 0), 1, [1, 2, 3, 4]), # ((1, 0, 0, 0), 1, [2, 3, 4, 1]), # ((2, 1, 0, 0), 1, [1, 2, 3, 4]), # ((3, 2, 1, 0), 1, [1, 2, 3, 4]), # # todos fora da base # ((4, 3, 2, 1), 1, [1, 2, 3, 4]), # ((3, 4, 2, 1), 1, [2, 1, 3, 4]), # ((35, 4, 3, 2), 2, [1, 2, 3, 4]), # ((1, 4, 8, 12), 1, [4, 3, 2, 1]), )) def test_estrategia_sacana(pinos, passos, ordem): assert sacana(pinos, passos) == ordem @pytest.mark.parametrize('pinos, passos, ordem', ( # com pinos na base ((0, 0, 0, 0), 1, [1, 2, 3, 4]), ((1, 0, 0, 0), 1, [1, 2, 3, 4]), ((2, 1, 0, 0), 1, [1, 2, 3, 4]), ((3, 2, 1, 0), 1, [1, 2, 3, 4]), # todos fora da base ((4, 3, 2, 1), 1, [1, 2, 3, 4]), ((3, 4, 2, 1), 1, [2, 1, 3, 4]), ((35, 4, 3, 2), 2, [1, 2, 3, 4]), ((1, 4, 8, 12), 1, [4, 3, 2, 1]), )) def test_estrategia_prioridade(pinos, passos, ordem): assert prioridade(pinos, passos) == ordem @pytest.mark.parametrize('pinos, passos, ordem', ( # posicao # ((0, 0, 0, 0), 1, [1, 2, 3, 4]), ((1, 0, 0, 0), 1, [2, 3, 4, 1]), ((2, 1, 0, 0), 1, [3, 4, 1, 2]), ((3, 2, 1, 0), 1, [4, 1, 2, 3]), ((4, 3, 2, 1), 1, [1, 2, 3, 4]), ((3, 4, 2, 1), 1, [2, 1, 3, 4]), ((35, 4, 3, 2), 1, [2, 3, 4, 1]), ((35, 36, 3, 2), 1, [3, 4, 1, 2]), ((35, 36, 33, 34), 1, [2, 1, 4, 3]), )) def test_estrategia_veloz(pinos, passos, ordem): v = Veloz() assert v.veloz(pinos, passos) == ordem
31.54902
53
0.426352
307
1,609
2.214984
0.114007
0.073529
0.079412
0.1
0.663235
0.642647
0.635294
0.630882
0.625
0.523529
0
0.205754
0.287135
1,609
51
54
31.54902
0.387097
0.195774
0
0.393939
0
0
0.047207
0
0
0
0
0.019608
0.090909
1
0.090909
false
0.272727
0.060606
0
0.151515
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
0
0
0
0
null
0
0
1
0
0
0
0
1
0
0
0
0
0
4
164cb7827ead52f64a08d922ff0e63b4d56775de
85
py
Python
lektor/constants.py
yagebu/lektor
a31d8e57a5b2f4b090072527269c26a65202c736
[ "BSD-3-Clause" ]
4,104
2015-11-16T18:37:51.000Z
2022-03-28T14:28:24.000Z
lektor/constants.py
yagebu/lektor
a31d8e57a5b2f4b090072527269c26a65202c736
[ "BSD-3-Clause" ]
854
2015-12-05T12:19:02.000Z
2022-03-31T16:47:27.000Z
lektor/constants.py
yagebu/lektor
a31d8e57a5b2f4b090072527269c26a65202c736
[ "BSD-3-Clause" ]
442
2015-11-21T10:18:02.000Z
2022-03-29T19:55:17.000Z
# Special value that identifies a target to the primary alt PRIMARY_ALT = "_primary"
28.333333
59
0.788235
13
85
5
0.769231
0.307692
0.523077
0
0
0
0
0
0
0
0
0
0.164706
85
2
60
42.5
0.915493
0.670588
0
0
0
0
0.307692
0
0
0
0
0
0
1
0
false
0
0
0
0
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
0
0
0
0
0
0
0
4
167b2c15fb6edc4d36583d32548de271a6f9aa95
1,646
py
Python
tests/conftest.py
NotPeopling2day/ape-hardhat
f62488c65fefaa3109c671e7623d2dca717323b8
[ "Apache-2.0" ]
null
null
null
tests/conftest.py
NotPeopling2day/ape-hardhat
f62488c65fefaa3109c671e7623d2dca717323b8
[ "Apache-2.0" ]
null
null
null
tests/conftest.py
NotPeopling2day/ape-hardhat
f62488c65fefaa3109c671e7623d2dca717323b8
[ "Apache-2.0" ]
null
null
null
from pathlib import Path import ape import pytest # type: ignore from ape.api.networks import LOCAL_NETWORK_NAME, NetworkAPI from ape.managers.project import ProjectManager from ape_hardhat import HardhatProvider def get_project() -> ProjectManager: return ape.Project(Path(__file__).parent) def get_hardhat_provider(network_api: NetworkAPI): return HardhatProvider( name="hardhat", network=network_api, request_header={}, data_folder=Path("."), provider_settings={}, ) @pytest.fixture(scope="session") def test_accounts(): return ape.accounts.test_accounts @pytest.fixture(scope="session") def sender(test_accounts): return test_accounts[0] @pytest.fixture(scope="session") def receiver(test_accounts): return test_accounts[1] @pytest.fixture(scope="session") def owner(test_accounts): return test_accounts[2] @pytest.fixture(scope="session") def project(): return get_project() @pytest.fixture(scope="session") def networks(): return ape.networks @pytest.fixture(scope="session") def network_api(networks): return networks.ecosystems["ethereum"][LOCAL_NETWORK_NAME] @pytest.fixture(scope="session") def hardhat_disconnected(network_api): provider = get_hardhat_provider(network_api) return provider @pytest.fixture(scope="session") def hardhat_connected(networks, network_api): provider = get_hardhat_provider(network_api) provider.port = "auto" # For better multi-processing support provider.connect() networks.active_provider = provider try: yield provider finally: provider.disconnect()
21.657895
65
0.7339
195
1,646
6
0.297436
0.1
0.138462
0.192308
0.406838
0.138462
0.078632
0.078632
0
0
0
0.002168
0.159174
1,646
75
66
21.946667
0.843208
0.029162
0
0.215686
0
0
0.052038
0
0
0
0
0
0
1
0.215686
false
0
0.117647
0.176471
0.529412
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
4
167f49a60a47089d73b530054396ac1b62b2912c
606
py
Python
src/uff/element_geometry.py
davidbradway/uff.py
118001211018a4fc95d1dd7304ae6335bdf805f9
[ "MIT" ]
7
2021-11-16T17:27:54.000Z
2021-12-25T18:09:35.000Z
src/uff/element_geometry.py
davidbradway/uff.py
118001211018a4fc95d1dd7304ae6335bdf805f9
[ "MIT" ]
6
2021-11-16T17:27:33.000Z
2022-02-04T08:51:06.000Z
src/uff/element_geometry.py
davidbradway/uff.py
118001211018a4fc95d1dd7304ae6335bdf805f9
[ "MIT" ]
1
2021-11-16T19:26:36.000Z
2021-11-16T19:26:36.000Z
from dataclasses import dataclass from uff.perimeter import Perimeter from uff.uff_io import Serializable @dataclass class ElementGeometry(Serializable): """Describes the geometry of an ultrasonic element. Notes: Here we assume that the acoustic center of the element is at origin O = (0; 0; 0) pointing towards Z = (0; 0; 1). The element shape is defined by a closed perimeter contained within the XY -plane, that is in turn composed of an ordered set of uff.position instances. """ perimeter: Perimeter @staticmethod def str_name(): return 'element_geometry'
30.3
117
0.731023
86
606
5.116279
0.627907
0.013636
0
0
0
0
0
0
0
0
0
0.012526
0.209571
606
19
118
31.894737
0.906054
0.533003
0
0
0
0
0.061538
0
0
0
0
0
0
1
0.111111
true
0
0.333333
0.111111
0.777778
0
0
0
0
null
0
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
0
1
0
1
1
1
0
0
4
168b8c130340fdb36c3feb227424a70a5fcfe242
78,018
py
Python
pacu/models/awsapi/dynamodb.py
RyanJarv/Pacu2
27df4bcf296fc8f467d3dc671a47bf9519ce7a24
[ "MIT" ]
1
2022-03-09T14:51:54.000Z
2022-03-09T14:51:54.000Z
pacu/models/awsapi/dynamodb.py
RyanJarv/Pacu2
27df4bcf296fc8f467d3dc671a47bf9519ce7a24
[ "MIT" ]
null
null
null
pacu/models/awsapi/dynamodb.py
RyanJarv/Pacu2
27df4bcf296fc8f467d3dc671a47bf9519ce7a24
[ "MIT" ]
null
null
null
# generated by datamodel-codegen: # filename: openapi.yaml # timestamp: 2021-12-31T02:47:51+00:00 from __future__ import annotations from datetime import datetime from enum import Enum from typing import Annotated, Any, List, Optional from pydantic import BaseModel, Extra, Field class RequestLimitExceeded(BaseModel): __root__: Any class InternalServerError(RequestLimitExceeded): pass class ProvisionedThroughputExceededException(RequestLimitExceeded): pass class ResourceNotFoundException(RequestLimitExceeded): pass class ItemCollectionSizeLimitExceededException(RequestLimitExceeded): pass class TableNotFoundException(RequestLimitExceeded): pass class TableInUseException(RequestLimitExceeded): pass class ContinuousBackupsUnavailableException(RequestLimitExceeded): pass class BackupInUseException(RequestLimitExceeded): pass class LimitExceededException(RequestLimitExceeded): pass class GlobalTableAlreadyExistsException(RequestLimitExceeded): pass class ResourceInUseException(RequestLimitExceeded): pass class BackupNotFoundException(RequestLimitExceeded): pass class ConditionalCheckFailedException(RequestLimitExceeded): pass class TransactionConflictException(RequestLimitExceeded): pass class DescribeEndpointsRequest(BaseModel): pass class ExportNotFoundException(RequestLimitExceeded): pass class GlobalTableNotFoundException(RequestLimitExceeded): pass class DescribeLimitsInput(BaseModel): """ Represents the input of a <code>DescribeLimits</code> operation. Has no content. """ pass class DuplicateItemException(RequestLimitExceeded): pass class TransactionCanceledException(RequestLimitExceeded): pass class TransactionInProgressException(RequestLimitExceeded): pass class IdempotentParameterMismatchException(RequestLimitExceeded): pass class PointInTimeRecoveryUnavailableException(RequestLimitExceeded): pass class InvalidExportTimeException(RequestLimitExceeded): pass class ExportConflictException(RequestLimitExceeded): pass class TableAlreadyExistsException(RequestLimitExceeded): pass class InvalidRestoreTimeException(RequestLimitExceeded): pass class ReplicaAlreadyExistsException(RequestLimitExceeded): pass class ReplicaNotFoundException(RequestLimitExceeded): pass class IndexNotFoundException(RequestLimitExceeded): pass class ArchivalReason(BaseModel): __root__: str class Date(BaseModel): __root__: datetime class BackupArn(BaseModel): __root__: Annotated[str, Field(max_length=1024, min_length=37)] class ArchivalSummary(BaseModel): """ Contains details of a table archival operation. """ ArchivalDateTime: Optional[Date] = None ArchivalReason: Optional[ArchivalReason] = None ArchivalBackupArn: Optional[BackupArn] = None class AttributeAction(Enum): ADD = 'ADD' PUT = 'PUT' DELETE = 'DELETE' class KeySchemaAttributeName(BaseModel): __root__: Annotated[str, Field(max_length=255, min_length=1)] class ScalarAttributeType(Enum): S = 'S' N = 'N' B = 'B' class AttributeDefinition(BaseModel): """ Represents an attribute for describing the key schema for the table and indexes. """ AttributeName: KeySchemaAttributeName AttributeType: ScalarAttributeType class AttributeDefinitions(BaseModel): __root__: List[AttributeDefinition] class AttributeMap(BaseModel): pass class Config: extra = Extra.allow class AttributeName1(BaseModel): __root__: Annotated[str, Field(max_length=65535)] class AttributeNameList(BaseModel): __root__: Annotated[List[AttributeName1], Field(min_items=1)] class AttributeUpdates(BaseModel): pass class Config: extra = Extra.allow class StringAttributeValue(ArchivalReason): pass class NumberAttributeValue(ArchivalReason): pass class BinaryAttributeValue(ArchivalReason): pass class StringSetAttributeValue(BaseModel): __root__: List[StringAttributeValue] class NumberSetAttributeValue(BaseModel): __root__: List[NumberAttributeValue] class BinarySetAttributeValue(BaseModel): __root__: List[BinaryAttributeValue] class MapAttributeValue(AttributeMap): pass class NullAttributeValue(BaseModel): __root__: bool class BooleanAttributeValue(NullAttributeValue): pass class AutoScalingPolicyName(BaseModel): __root__: Annotated[str, Field(max_length=256, min_length=1, regex='\\p{Print}+')] class AutoScalingRoleArn(BaseModel): __root__: Annotated[str, Field(max_length=1600, min_length=1)] class PositiveLongObject(BaseModel): __root__: Annotated[int, Field(ge=1.0)] class BooleanObject(NullAttributeValue): pass class String(ArchivalReason): pass class IntegerObject(BaseModel): __root__: int class Double(BaseModel): __root__: float class Backfilling(NullAttributeValue): pass class BackupCreationDateTime(Date): pass class BackupName(BaseModel): __root__: Annotated[ str, Field(max_length=255, min_length=3, regex='[a-zA-Z0-9_.-]+') ] class BackupSizeBytes(BaseModel): __root__: Annotated[int, Field(ge=0.0)] class BackupStatus(Enum): CREATING = 'CREATING' DELETED = 'DELETED' AVAILABLE = 'AVAILABLE' class BackupType(Enum): USER = 'USER' SYSTEM = 'SYSTEM' AWS_BACKUP = 'AWS_BACKUP' class TableName(BackupName): pass class TableId(BaseModel): __root__: Annotated[ str, Field(regex='[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}') ] class TableArn(ArchivalReason): pass class BackupTypeFilter(Enum): USER = 'USER' SYSTEM = 'SYSTEM' AWS_BACKUP = 'AWS_BACKUP' ALL = 'ALL' class BackupsInputLimit(BaseModel): __root__: Annotated[int, Field(ge=1.0, le=100.0)] class BatchGetRequestMap(BaseModel): pass class Config: extra = Extra.allow class ReturnConsumedCapacity(Enum): """ <p>Determines the level of detail about provisioned throughput consumption that is returned in the response:</p> <ul> <li> <p> <code>INDEXES</code> - The response includes the aggregate <code>ConsumedCapacity</code> for the operation, together with <code>ConsumedCapacity</code> for each table and secondary index that was accessed.</p> <p>Note that some operations, such as <code>GetItem</code> and <code>BatchGetItem</code>, do not access any indexes at all. In these cases, specifying <code>INDEXES</code> will only return <code>ConsumedCapacity</code> information for table(s).</p> </li> <li> <p> <code>TOTAL</code> - The response includes only the aggregate <code>ConsumedCapacity</code> for the operation.</p> </li> <li> <p> <code>NONE</code> - No <code>ConsumedCapacity</code> details are included in the response.</p> </li> </ul> """ INDEXES = 'INDEXES' TOTAL = 'TOTAL' NONE = 'NONE' class BatchGetResponseMap(BaseModel): pass class Config: extra = Extra.allow class ItemList(BaseModel): __root__: List[AttributeMap] class BatchStatementErrorCodeEnum(Enum): ConditionalCheckFailed = 'ConditionalCheckFailed' ItemCollectionSizeLimitExceeded = 'ItemCollectionSizeLimitExceeded' RequestLimitExceeded = 'RequestLimitExceeded' ValidationError = 'ValidationError' ProvisionedThroughputExceeded = 'ProvisionedThroughputExceeded' TransactionConflict = 'TransactionConflict' ThrottlingError = 'ThrottlingError' InternalServerError = 'InternalServerError' ResourceNotFound = 'ResourceNotFound' AccessDenied = 'AccessDenied' DuplicateItem = 'DuplicateItem' class BatchStatementError(BaseModel): """ An error associated with a statement in a PartiQL batch that was run. """ Code: Optional[BatchStatementErrorCodeEnum] = None Message: Optional[String] = None class PartiQLStatement(BaseModel): __root__: Annotated[str, Field(max_length=8192, min_length=1)] class ConsistentRead(NullAttributeValue): pass class BatchStatementResponse(BaseModel): """ A PartiQL batch statement response.. """ Error: Optional[BatchStatementError] = None TableName: Optional[TableName] = None Item: Optional[AttributeMap] = None class BatchWriteItemRequestMap(BaseModel): pass class Config: extra = Extra.allow class ReturnItemCollectionMetrics(Enum): SIZE = 'SIZE' NONE = 'NONE' class ItemCollectionMetricsPerTable(BaseModel): pass class Config: extra = Extra.allow class BilledSizeBytes(BackupSizeBytes): pass class BillingMode(Enum): PROVISIONED = 'PROVISIONED' PAY_PER_REQUEST = 'PAY_PER_REQUEST' class BillingModeSummary(BaseModel): """ Contains the details for the read/write capacity mode. """ BillingMode: Optional[BillingMode] = None LastUpdateToPayPerRequestDateTime: Optional[Date] = None class ConsumedCapacityUnits(Double): pass class Capacity(BaseModel): """ Represents the amount of provisioned throughput capacity consumed on a table or an index. """ ReadCapacityUnits: Optional[ConsumedCapacityUnits] = None WriteCapacityUnits: Optional[ConsumedCapacityUnits] = None CapacityUnits: Optional[ConsumedCapacityUnits] = None class ClientRequestToken(BaseModel): __root__: Annotated[str, Field(max_length=36, min_length=1)] class ClientToken(ArchivalReason): pass class ComparisonOperator(Enum): EQ = 'EQ' NE = 'NE' IN = 'IN' LE = 'LE' LT = 'LT' GE = 'GE' GT = 'GT' BETWEEN = 'BETWEEN' NOT_NULL = 'NOT_NULL' NULL = 'NULL' CONTAINS = 'CONTAINS' NOT_CONTAINS = 'NOT_CONTAINS' BEGINS_WITH = 'BEGINS_WITH' class Key(AttributeMap): pass class ConditionExpression(ArchivalReason): pass class ExpressionAttributeNameMap(BaseModel): pass class Config: extra = Extra.allow class ExpressionAttributeValueMap(AttributeMap): pass class ReturnValuesOnConditionCheckFailure(Enum): ALL_OLD = 'ALL_OLD' NONE = 'NONE' class ConditionCheck(BaseModel): """ Represents a request to perform a check that an item exists or to check the condition of specific attributes of the item. """ Key: Key TableName: TableName ConditionExpression: ConditionExpression ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None ReturnValuesOnConditionCheckFailure: Optional[ ReturnValuesOnConditionCheckFailure ] = None class ConditionalOperator(Enum): AND = 'AND' OR = 'OR' class SecondaryIndexesCapacityMap(BaseModel): pass class Config: extra = Extra.allow class ConsumedCapacity(BaseModel): """ The capacity units consumed by an operation. The data returned includes the total provisioned throughput consumed, along with statistics for the table and any indexes involved in the operation. <code>ConsumedCapacity</code> is only returned if the request asked for it. For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ProvisionedThroughputIntro.html">Provisioned Throughput</a> in the <i>Amazon DynamoDB Developer Guide</i>. """ TableName: Optional[TableName] = None CapacityUnits: Optional[ConsumedCapacityUnits] = None ReadCapacityUnits: Optional[ConsumedCapacityUnits] = None WriteCapacityUnits: Optional[ConsumedCapacityUnits] = None Table: Optional[Capacity] = None LocalSecondaryIndexes: Optional[SecondaryIndexesCapacityMap] = None GlobalSecondaryIndexes: Optional[SecondaryIndexesCapacityMap] = None class ContinuousBackupsStatus(Enum): ENABLED = 'ENABLED' DISABLED = 'DISABLED' class ContributorInsightsAction(Enum): ENABLE = 'ENABLE' DISABLE = 'DISABLE' class ContributorInsightsRule(BaseModel): __root__: Annotated[ str, Field(regex='[A-Za-z0-9][A-Za-z0-9\\-\\_\\.]{0,126}[A-Za-z0-9]') ] class ContributorInsightsRuleList(BaseModel): __root__: List[ContributorInsightsRule] class ContributorInsightsStatus(Enum): ENABLING = 'ENABLING' ENABLED = 'ENABLED' DISABLING = 'DISABLING' DISABLED = 'DISABLED' FAILED = 'FAILED' class IndexName(BackupName): pass class ProvisionedThroughput(BaseModel): """ <p>Represents the provisioned throughput settings for a specified table or index. The settings can be modified using the <code>UpdateTable</code> operation.</p> <p>For current minimum and maximum provisioned throughput values, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html">Service, Account, and Table Quotas</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p> """ ReadCapacityUnits: PositiveLongObject WriteCapacityUnits: PositiveLongObject class RegionName(ArchivalReason): pass class CreateReplicaAction(BaseModel): """ Represents a replica to be added. """ RegionName: RegionName class KMSMasterKeyId(ArchivalReason): pass class ProvisionedThroughputOverride2(BaseModel): """ Replica-specific provisioned throughput settings. If not specified, uses the source table's provisioned throughput settings. """ ReadCapacityUnits: Optional[PositiveLongObject] = None class Delete(BaseModel): """ Represents a request to perform a <code>DeleteItem</code> operation. """ Key: Key TableName: TableName ConditionExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None ReturnValuesOnConditionCheckFailure: Optional[ ReturnValuesOnConditionCheckFailure ] = None class DeleteGlobalSecondaryIndexAction(BaseModel): """ Represents a global secondary index to be deleted from an existing table. """ IndexName: IndexName class ExpectedAttributeMap(BaseModel): pass class Config: extra = Extra.allow class ReturnValue(Enum): NONE = 'NONE' ALL_OLD = 'ALL_OLD' UPDATED_OLD = 'UPDATED_OLD' ALL_NEW = 'ALL_NEW' UPDATED_NEW = 'UPDATED_NEW' class DeleteReplicaAction(CreateReplicaAction): """ Represents a replica to be removed. """ pass class DeleteReplicationGroupMemberAction(CreateReplicaAction): """ Represents a replica to be deleted. """ pass class DeleteRequest(BaseModel): """ Represents a request to perform a <code>DeleteItem</code> operation on an item. """ Key: Key class LastUpdateDateTime(Date): pass class ExportArn(BackupArn): pass class DestinationStatus(Enum): ENABLING = 'ENABLING' ACTIVE = 'ACTIVE' DISABLING = 'DISABLING' DISABLED = 'DISABLED' ENABLE_FAILED = 'ENABLE_FAILED' class Long(IntegerObject): pass class Endpoint(BaseModel): """ An endpoint information details. """ Address: String CachePeriodInMinutes: Long class ExceptionDescription(ArchivalReason): pass class ExceptionName(ArchivalReason): pass class PartiQLNextToken(BaseModel): __root__: Annotated[str, Field(max_length=32768, min_length=1)] class ExportStatus(Enum): IN_PROGRESS = 'IN_PROGRESS' COMPLETED = 'COMPLETED' FAILED = 'FAILED' class ExportStartTime(Date): pass class ExportEndTime(Date): pass class ExportManifest(ArchivalReason): pass class ExportTime(Date): pass class S3Bucket(ArchivalReason): pass class S3BucketOwner(ArchivalReason): pass class S3Prefix(ArchivalReason): pass class S3SseAlgorithm(Enum): AES256 = 'AES256' KMS = 'KMS' class S3SseKmsKeyId(BaseModel): __root__: Annotated[str, Field(max_length=2048, min_length=1)] class FailureCode(ArchivalReason): pass class FailureMessage(ArchivalReason): pass class ExportFormat(Enum): DYNAMODB_JSON = 'DYNAMODB_JSON' ION = 'ION' class ItemCount(BackupSizeBytes): pass class ExportNextToken(ArchivalReason): pass class ExportSummary(BaseModel): """ Summary information about an export task. """ ExportArn: Optional[ExportArn] = None ExportStatus: Optional[ExportStatus] = None class ExportSummaries(BaseModel): __root__: List[ExportSummary] class ExpressionAttributeNameVariable(ArchivalReason): pass class ExpressionAttributeValueVariable(ArchivalReason): pass class FilterConditionMap(BaseModel): pass class Config: extra = Extra.allow class ProjectionExpression(ArchivalReason): pass class Get(BaseModel): """ Specifies an item and related attribute values to retrieve in a <code>TransactGetItem</code> object. """ Key: Key TableName: TableName ProjectionExpression: Optional[ProjectionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None class IndexStatus(Enum): CREATING = 'CREATING' UPDATING = 'UPDATING' DELETING = 'DELETING' ACTIVE = 'ACTIVE' class UpdateGlobalSecondaryIndexAction(BaseModel): """ Represents the new provisioned throughput settings to be applied to a global secondary index. """ IndexName: IndexName ProvisionedThroughput: ProvisionedThroughput class GlobalTableArnString(ArchivalReason): pass class GlobalTableStatus(Enum): CREATING = 'CREATING' ACTIVE = 'ACTIVE' DELETING = 'DELETING' UPDATING = 'UPDATING' class Integer(IntegerObject): pass class ItemCollectionKeyAttributeMap(AttributeMap): pass class ItemCollectionSizeEstimateBound(Double): pass class ItemResponse(BaseModel): """ Details for the requested item. """ Item: Optional[AttributeMap] = None class KMSMasterKeyArn(ArchivalReason): pass class KeyConditions(FilterConditionMap): pass class KeyExpression(ArchivalReason): pass class KeyList(BaseModel): __root__: Annotated[List[Key], Field(max_items=100, min_items=1)] class KeyType(Enum): HASH = 'HASH' RANGE = 'RANGE' class StreamArn(BackupArn): pass class KinesisDataStreamDestination(BaseModel): """ Describes a Kinesis data stream destination. """ StreamArn: Optional[StreamArn] = None DestinationStatus: Optional[DestinationStatus] = None DestinationStatusDescription: Optional[String] = None class TimeRangeLowerBound(Date): pass class TimeRangeUpperBound(Date): pass class NextTokenString(ArchivalReason): pass class ListContributorInsightsLimit(BaseModel): __root__: Annotated[int, Field(le=100.0)] class ListExportsMaxLimit(BaseModel): __root__: Annotated[int, Field(ge=1.0, le=25.0)] class PositiveIntegerObject(PositiveLongObject): pass class ListTablesInputLimit(BackupsInputLimit): pass class TableNameList(BaseModel): __root__: List[TableName] class ResourceArnString(BaseModel): __root__: Annotated[str, Field(max_length=1283, min_length=1)] class NonKeyAttributeName(KeySchemaAttributeName): pass class NonKeyAttributeNameList(BaseModel): __root__: Annotated[List[NonKeyAttributeName], Field(max_items=20, min_items=1)] class NonNegativeLongObject(BackupSizeBytes): pass class PointInTimeRecoverySpecification(BaseModel): """ Represents the settings used to enable point in time recovery. """ PointInTimeRecoveryEnabled: BooleanObject class ProjectionType(Enum): ALL = 'ALL' KEYS_ONLY = 'KEYS_ONLY' INCLUDE = 'INCLUDE' class PutItemInputAttributeMap(AttributeMap): pass class Put(BaseModel): """ Represents a request to perform a <code>PutItem</code> operation. """ Item: PutItemInputAttributeMap TableName: TableName ConditionExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None ReturnValuesOnConditionCheckFailure: Optional[ ReturnValuesOnConditionCheckFailure ] = None class PutRequest(BaseModel): """ Represents a request to perform a <code>PutItem</code> operation on an item. """ Item: PutItemInputAttributeMap class Select(Enum): ALL_ATTRIBUTES = 'ALL_ATTRIBUTES' ALL_PROJECTED_ATTRIBUTES = 'ALL_PROJECTED_ATTRIBUTES' SPECIFIC_ATTRIBUTES = 'SPECIFIC_ATTRIBUTES' COUNT = 'COUNT' class Replica(BaseModel): """ Represents the properties of a replica. """ RegionName: Optional[RegionName] = None class ReplicaStatus(Enum): CREATING = 'CREATING' CREATION_FAILED = 'CREATION_FAILED' UPDATING = 'UPDATING' DELETING = 'DELETING' ACTIVE = 'ACTIVE' REGION_DISABLED = 'REGION_DISABLED' INACCESSIBLE_ENCRYPTION_CREDENTIALS = 'INACCESSIBLE_ENCRYPTION_CREDENTIALS' class ReplicaStatusDescription(ArchivalReason): pass class ReplicaStatusPercentProgress(ArchivalReason): pass class ReplicaGlobalSecondaryIndex(BaseModel): """ Represents the properties of a replica global secondary index. """ IndexName: IndexName ProvisionedThroughputOverride: Optional[ProvisionedThroughputOverride2] = None class ReplicaGlobalSecondaryIndexDescription(BaseModel): """ Represents the properties of a replica global secondary index. """ IndexName: Optional[IndexName] = None ProvisionedThroughputOverride: Optional[ProvisionedThroughputOverride2] = None class ReplicaUpdate(BaseModel): """ <p>Represents one of the following:</p> <ul> <li> <p>A new replica to be added to an existing global table.</p> </li> <li> <p>New parameters for an existing replica.</p> </li> <li> <p>An existing replica to be removed from an existing global table.</p> </li> </ul> """ Create: Optional[CreateReplicaAction] = None Delete: Optional[DeleteReplicaAction] = None class ReplicaUpdateList(BaseModel): __root__: List[ReplicaUpdate] class RestoreInProgress(NullAttributeValue): pass class RestoreSummary(BaseModel): """ Contains details for the restore. """ SourceBackupArn: Optional[BackupArn] = None SourceTableArn: Optional[TableArn] = None RestoreDateTime: Date RestoreInProgress: RestoreInProgress class SSEStatus(Enum): ENABLING = 'ENABLING' ENABLED = 'ENABLED' DISABLING = 'DISABLING' DISABLED = 'DISABLED' UPDATING = 'UPDATING' class SSEDescription(BaseModel): """ The description of the server-side encryption status on the specified table. """ Status: Optional[SSEStatus] = None SSEType: Optional[S3SseAlgorithm] = None KMSMasterKeyArn: Optional[KMSMasterKeyArn] = None InaccessibleEncryptionDateTime: Optional[Date] = None class SSEEnabled(NullAttributeValue): pass class ScanTotalSegments(BaseModel): __root__: Annotated[int, Field(ge=1.0, le=1000000.0)] class ScanSegment(BaseModel): __root__: Annotated[int, Field(ge=0.0, le=999999.0)] class TableCreationDateTime(Date): pass class StreamEnabled(NullAttributeValue): pass class StreamViewType(Enum): NEW_IMAGE = 'NEW_IMAGE' OLD_IMAGE = 'OLD_IMAGE' NEW_AND_OLD_IMAGES = 'NEW_AND_OLD_IMAGES' KEYS_ONLY = 'KEYS_ONLY' class TableStatus(Enum): CREATING = 'CREATING' UPDATING = 'UPDATING' DELETING = 'DELETING' ACTIVE = 'ACTIVE' INACCESSIBLE_ENCRYPTION_CREDENTIALS = 'INACCESSIBLE_ENCRYPTION_CREDENTIALS' ARCHIVING = 'ARCHIVING' ARCHIVED = 'ARCHIVED' class TagKeyString(BaseModel): __root__: Annotated[str, Field(max_length=128, min_length=1)] class TagValueString(BaseModel): __root__: Annotated[str, Field(max_length=256, min_length=0)] class Tag(BaseModel): """ <p>Describes a tag. A tag is a key-value pair. You can add up to 50 tags to a single DynamoDB table. </p> <p> AWS-assigned tag names and values are automatically assigned the <code>aws:</code> prefix, which the user cannot assign. AWS-assigned tag names do not count towards the tag limit of 50. User-assigned tag names have the prefix <code>user:</code> in the Cost Allocation Report. You cannot backdate the application of a tag. </p> <p>For an overview on tagging DynamoDB resources, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Tagging.html">Tagging for DynamoDB</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p> """ Key: TagKeyString Value: TagValueString class TagKeyList(BaseModel): __root__: List[TagKeyString] class TimeToLiveAttributeName(KeySchemaAttributeName): pass class TimeToLiveStatus(Enum): ENABLING = 'ENABLING' DISABLING = 'DISABLING' ENABLED = 'ENABLED' DISABLED = 'DISABLED' class TimeToLiveEnabled(NullAttributeValue): pass class TimeToLiveSpecification(BaseModel): """ Represents the settings used to enable or disable Time to Live (TTL) for the specified table. """ Enabled: TimeToLiveEnabled AttributeName: TimeToLiveAttributeName class TransactGetItem(BaseModel): """ Specifies an item to be retrieved as part of the transaction. """ Get: Get class TransactGetItemList(BaseModel): __root__: Annotated[List[TransactGetItem], Field(max_items=25, min_items=1)] class UpdateExpression(ArchivalReason): pass class WriteRequest(BaseModel): """ Represents an operation to perform - either <code>DeleteItem</code> or <code>PutItem</code>. You can only request one of these operations, not both, in a single <code>WriteRequest</code>. If you do need to perform both of these operations, you need to provide two separate <code>WriteRequest</code> objects. """ PutRequest: Optional[PutRequest] = None DeleteRequest: Optional[DeleteRequest] = None class BatchGetItemInput(BaseModel): """ Represents the input of a <code>BatchGetItem</code> operation. """ RequestItems: BatchGetRequestMap ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None class BatchWriteItemInput(BaseModel): """ Represents the input of a <code>BatchWriteItem</code> operation. """ RequestItems: BatchWriteItemRequestMap ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ReturnItemCollectionMetrics: Optional[ReturnItemCollectionMetrics] = None class CreateBackupInput(BaseModel): TableName: TableName BackupName: BackupName class DeleteBackupInput(BaseModel): BackupArn: BackupArn class DeleteItemInput(BaseModel): """ Represents the input of a <code>DeleteItem</code> operation. """ TableName: TableName Key: Key Expected: Optional[ExpectedAttributeMap] = None ConditionalOperator: Optional[ConditionalOperator] = None ReturnValues: Optional[ReturnValue] = None ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ReturnItemCollectionMetrics: Optional[ReturnItemCollectionMetrics] = None ConditionExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None class DeleteTableInput(BaseModel): """ Represents the input of a <code>DeleteTable</code> operation. """ TableName: TableName class DescribeBackupInput(BaseModel): BackupArn: BackupArn class DescribeContinuousBackupsInput(BaseModel): TableName: TableName class DescribeContributorInsightsInput(BaseModel): TableName: TableName IndexName: Optional[IndexName] = None class DescribeExportInput(BaseModel): ExportArn: ExportArn class DescribeGlobalTableInput(BaseModel): GlobalTableName: TableName class DescribeGlobalTableSettingsInput(BaseModel): GlobalTableName: TableName class DescribeKinesisStreamingDestinationInput(BaseModel): TableName: TableName class DescribeLimitsOutput(BaseModel): """ Represents the output of a <code>DescribeLimits</code> operation. """ AccountMaxReadCapacityUnits: Optional[PositiveLongObject] = None AccountMaxWriteCapacityUnits: Optional[PositiveLongObject] = None TableMaxReadCapacityUnits: Optional[PositiveLongObject] = None TableMaxWriteCapacityUnits: Optional[PositiveLongObject] = None class DescribeTableInput(BaseModel): """ Represents the input of a <code>DescribeTable</code> operation. """ TableName: TableName class DescribeTableReplicaAutoScalingInput(BaseModel): TableName: TableName class DescribeTimeToLiveInput(BaseModel): TableName: TableName class KinesisStreamingDestinationOutput(BaseModel): TableName: Optional[TableName] = None StreamArn: Optional[StreamArn] = None DestinationStatus: Optional[DestinationStatus] = None class KinesisStreamingDestinationInput(BaseModel): TableName: TableName StreamArn: StreamArn class ExecuteStatementOutput(BaseModel): Items: Optional[ItemList] = None NextToken: Optional[PartiQLNextToken] = None class ExportTableToPointInTimeInput(BaseModel): TableArn: TableArn ExportTime: Optional[ExportTime] = None ClientToken: Optional[ClientToken] = None S3Bucket: S3Bucket S3BucketOwner: Optional[S3BucketOwner] = None S3Prefix: Optional[S3Prefix] = None S3SseAlgorithm: Optional[S3SseAlgorithm] = None S3SseKmsKeyId: Optional[S3SseKmsKeyId] = None ExportFormat: Optional[ExportFormat] = None class GetItemOutput(BaseModel): """ Represents the output of a <code>GetItem</code> operation. """ Item: Optional[AttributeMap] = None ConsumedCapacity: Optional[ConsumedCapacity] = None class GetItemInput(BaseModel): """ Represents the input of a <code>GetItem</code> operation. """ TableName: TableName Key: Key AttributesToGet: Optional[AttributeNameList] = None ConsistentRead: Optional[ConsistentRead] = None ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ProjectionExpression: Optional[ProjectionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None class ListBackupsInput(BaseModel): TableName: Optional[TableName] = None Limit: Optional[BackupsInputLimit] = None TimeRangeLowerBound: Optional[TimeRangeLowerBound] = None TimeRangeUpperBound: Optional[TimeRangeUpperBound] = None ExclusiveStartBackupArn: Optional[BackupArn] = None BackupType: Optional[BackupTypeFilter] = None class ListContributorInsightsInput(BaseModel): TableName: Optional[TableName] = None NextToken: Optional[NextTokenString] = None MaxResults: Optional[ListContributorInsightsLimit] = None class ListExportsOutput(BaseModel): ExportSummaries: Optional[ExportSummaries] = None NextToken: Optional[ExportNextToken] = None class ListExportsInput(BaseModel): TableArn: Optional[TableArn] = None MaxResults: Optional[ListExportsMaxLimit] = None NextToken: Optional[ExportNextToken] = None class ListGlobalTablesInput(BaseModel): ExclusiveStartGlobalTableName: Optional[TableName] = None Limit: Optional[PositiveIntegerObject] = None RegionName: Optional[RegionName] = None class ListTablesOutput(BaseModel): """ Represents the output of a <code>ListTables</code> operation. """ TableNames: Optional[TableNameList] = None LastEvaluatedTableName: Optional[TableName] = None class ListTablesInput(BaseModel): """ Represents the input of a <code>ListTables</code> operation. """ ExclusiveStartTableName: Optional[TableName] = None Limit: Optional[ListTablesInputLimit] = None class ListTagsOfResourceInput(BaseModel): ResourceArn: ResourceArnString NextToken: Optional[NextTokenString] = None class PutItemInput(BaseModel): """ Represents the input of a <code>PutItem</code> operation. """ TableName: TableName Item: PutItemInputAttributeMap Expected: Optional[ExpectedAttributeMap] = None ReturnValues: Optional[ReturnValue] = None ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ReturnItemCollectionMetrics: Optional[ReturnItemCollectionMetrics] = None ConditionalOperator: Optional[ConditionalOperator] = None ConditionExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None class QueryOutput(BaseModel): """ Represents the output of a <code>Query</code> operation. """ Items: Optional[ItemList] = None Count: Optional[Integer] = None ScannedCount: Optional[Integer] = None LastEvaluatedKey: Optional[Key] = None ConsumedCapacity: Optional[ConsumedCapacity] = None class QueryInput(BaseModel): """ Represents the input of a <code>Query</code> operation. """ TableName: TableName IndexName: Optional[IndexName] = None Select: Optional[Select] = None AttributesToGet: Optional[AttributeNameList] = None Limit: Optional[PositiveIntegerObject] = None ConsistentRead: Optional[ConsistentRead] = None KeyConditions: Optional[KeyConditions] = None QueryFilter: Optional[FilterConditionMap] = None ConditionalOperator: Optional[ConditionalOperator] = None ScanIndexForward: Optional[BooleanObject] = None ExclusiveStartKey: Optional[Key] = None ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ProjectionExpression: Optional[ProjectionExpression] = None FilterExpression: Optional[ConditionExpression] = None KeyConditionExpression: Optional[KeyExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None class ScanOutput(QueryOutput): """ Represents the output of a <code>Scan</code> operation. """ pass class ScanInput(BaseModel): """ Represents the input of a <code>Scan</code> operation. """ TableName: TableName IndexName: Optional[IndexName] = None AttributesToGet: Optional[AttributeNameList] = None Limit: Optional[PositiveIntegerObject] = None Select: Optional[Select] = None ScanFilter: Optional[FilterConditionMap] = None ConditionalOperator: Optional[ConditionalOperator] = None ExclusiveStartKey: Optional[Key] = None ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None TotalSegments: Optional[ScanTotalSegments] = None Segment: Optional[ScanSegment] = None ProjectionExpression: Optional[ProjectionExpression] = None FilterExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None ConsistentRead: Optional[ConsistentRead] = None class TransactGetItemsInput(BaseModel): TransactItems: TransactGetItemList ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None class UntagResourceInput(BaseModel): ResourceArn: ResourceArnString TagKeys: TagKeyList class UpdateContinuousBackupsInput(BaseModel): TableName: TableName PointInTimeRecoverySpecification: PointInTimeRecoverySpecification class UpdateContributorInsightsOutput(BaseModel): TableName: Optional[TableName] = None IndexName: Optional[IndexName] = None ContributorInsightsStatus: Optional[ContributorInsightsStatus] = None class UpdateContributorInsightsInput(BaseModel): TableName: TableName IndexName: Optional[IndexName] = None ContributorInsightsAction: ContributorInsightsAction class UpdateGlobalTableInput(BaseModel): GlobalTableName: TableName ReplicaUpdates: ReplicaUpdateList class UpdateItemInput(BaseModel): """ Represents the input of an <code>UpdateItem</code> operation. """ TableName: TableName Key: Key AttributeUpdates: Optional[AttributeUpdates] = None Expected: Optional[ExpectedAttributeMap] = None ConditionalOperator: Optional[ConditionalOperator] = None ReturnValues: Optional[ReturnValue] = None ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ReturnItemCollectionMetrics: Optional[ReturnItemCollectionMetrics] = None UpdateExpression: Optional[UpdateExpression] = None ConditionExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None class UpdateTimeToLiveOutput(BaseModel): TimeToLiveSpecification: Optional[TimeToLiveSpecification] = None class UpdateTimeToLiveInput(BaseModel): """ Represents the input of an <code>UpdateTimeToLive</code> operation. """ TableName: TableName TimeToLiveSpecification: TimeToLiveSpecification class AutoScalingTargetTrackingScalingPolicyConfigurationDescription(BaseModel): """ Represents the properties of a target tracking scaling policy. """ DisableScaleIn: Optional[BooleanObject] = None ScaleInCooldown: Optional[IntegerObject] = None ScaleOutCooldown: Optional[IntegerObject] = None TargetValue: Double class AutoScalingPolicyDescription(BaseModel): """ Represents the properties of the scaling policy. """ PolicyName: Optional[AutoScalingPolicyName] = None TargetTrackingScalingPolicyConfiguration: Optional[ AutoScalingTargetTrackingScalingPolicyConfigurationDescription ] = None class AutoScalingPolicyDescriptionList(BaseModel): __root__: List[AutoScalingPolicyDescription] class AutoScalingTargetTrackingScalingPolicyConfigurationUpdate( AutoScalingTargetTrackingScalingPolicyConfigurationDescription ): """ Represents the settings of a target tracking scaling policy that will be modified. """ pass class AutoScalingPolicyUpdate(BaseModel): """ Represents the auto scaling policy to be modified. """ PolicyName: Optional[AutoScalingPolicyName] = None TargetTrackingScalingPolicyConfiguration: AutoScalingTargetTrackingScalingPolicyConfigurationUpdate class AutoScalingSettingsDescription(BaseModel): """ Represents the auto scaling settings for a global table or global secondary index. """ MinimumUnits: Optional[PositiveLongObject] = None MaximumUnits: Optional[PositiveLongObject] = None AutoScalingDisabled: Optional[BooleanObject] = None AutoScalingRoleArn: Optional[String] = None ScalingPolicies: Optional[AutoScalingPolicyDescriptionList] = None class AutoScalingSettingsUpdate(BaseModel): """ Represents the auto scaling settings to be modified for a global table or global secondary index. """ MinimumUnits: Optional[PositiveLongObject] = None MaximumUnits: Optional[PositiveLongObject] = None AutoScalingDisabled: Optional[BooleanObject] = None AutoScalingRoleArn: Optional[AutoScalingRoleArn] = None ScalingPolicyUpdate: Optional[AutoScalingPolicyUpdate] = None class BackupDetails(BaseModel): """ Contains the details of the backup created for the table. """ BackupArn: BackupArn BackupName: BackupName BackupSizeBytes: Optional[BackupSizeBytes] = None BackupStatus: BackupStatus BackupType: BackupType BackupCreationDateTime: BackupCreationDateTime BackupExpiryDateTime: Optional[Date] = None class BackupSummary(BaseModel): """ Contains details for the backup. """ TableName: Optional[TableName] = None TableId: Optional[TableId] = None TableArn: Optional[TableArn] = None BackupArn: Optional[BackupArn] = None BackupName: Optional[BackupName] = None BackupCreationDateTime: Optional[BackupCreationDateTime] = None BackupExpiryDateTime: Optional[Date] = None BackupStatus: Optional[BackupStatus] = None BackupType: Optional[BackupType] = None BackupSizeBytes: Optional[BackupSizeBytes] = None class BackupSummaries(BaseModel): __root__: List[BackupSummary] class PartiQLBatchResponse(BaseModel): __root__: List[BatchStatementResponse] class ConsumedCapacityMultiple(BaseModel): __root__: List[ConsumedCapacity] class KeysAndAttributes(BaseModel): """ <p>Represents a set of primary keys and, for each key, the attributes to retrieve from the table.</p> <p>For each primary key, you must provide <i>all</i> of the key attributes. For example, with a simple primary key, you only need to provide the partition key. For a composite primary key, you must provide <i>both</i> the partition key and the sort key.</p> """ Keys: KeyList AttributesToGet: Optional[AttributeNameList] = None ConsistentRead: Optional[ConsistentRead] = None ProjectionExpression: Optional[ProjectionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None class WriteRequests(BaseModel): __root__: Annotated[List[WriteRequest], Field(max_items=25, min_items=1)] class PointInTimeRecoveryDescription(BaseModel): """ The description of the point in time settings applied to the table. """ PointInTimeRecoveryStatus: Optional[ContinuousBackupsStatus] = None EarliestRestorableDateTime: Optional[Date] = None LatestRestorableDateTime: Optional[Date] = None class ContinuousBackupsDescription(BaseModel): """ Represents the continuous backups and point in time recovery settings on the table. """ ContinuousBackupsStatus: ContinuousBackupsStatus PointInTimeRecoveryDescription: Optional[PointInTimeRecoveryDescription] = None class ContributorInsightsSummary(UpdateContributorInsightsOutput): """ Represents a Contributor Insights summary entry. """ pass class ContributorInsightsSummaries(BaseModel): __root__: List[ContributorInsightsSummary] class Projection(BaseModel): """ Represents attributes that are copied (projected) from the table into an index. These are in addition to the primary key attributes and index key attributes, which are automatically projected. """ ProjectionType: Optional[ProjectionType] = None NonKeyAttributes: Optional[NonKeyAttributeNameList] = None class ReplicaList(BaseModel): __root__: List[Replica] class ReplicaGlobalSecondaryIndexList(BaseModel): __root__: Annotated[List[ReplicaGlobalSecondaryIndex], Field(min_items=1)] class CreateReplicationGroupMemberAction(BaseModel): """ Represents a replica to be created. """ RegionName: RegionName KMSMasterKeyId: Optional[KMSMasterKeyId] = None ProvisionedThroughputOverride: Optional[ProvisionedThroughputOverride2] = None GlobalSecondaryIndexes: Optional[ReplicaGlobalSecondaryIndexList] = None class StreamSpecification(BaseModel): """ Represents the DynamoDB Streams configuration for a table in DynamoDB. """ StreamEnabled: StreamEnabled StreamViewType: Optional[StreamViewType] = None class SSESpecification(BaseModel): """ Represents the settings used to enable server-side encryption. """ Enabled: Optional[SSEEnabled] = None SSEType: Optional[S3SseAlgorithm] = None KMSMasterKeyId: Optional[KMSMasterKeyId] = None class TagList(BaseModel): __root__: List[Tag] class FailureException(BaseModel): """ Represents a failure a contributor insights operation. """ ExceptionName: Optional[ExceptionName] = None ExceptionDescription: Optional[ExceptionDescription] = None class Endpoints(BaseModel): __root__: List[Endpoint] class ExportDescription(BaseModel): """ Represents the properties of the exported table. """ ExportArn: Optional[ExportArn] = None ExportStatus: Optional[ExportStatus] = None StartTime: Optional[ExportStartTime] = None EndTime: Optional[ExportEndTime] = None ExportManifest: Optional[ExportManifest] = None TableArn: Optional[TableArn] = None TableId: Optional[TableId] = None ExportTime: Optional[ExportTime] = None ClientToken: Optional[ClientToken] = None S3Bucket: Optional[S3Bucket] = None S3BucketOwner: Optional[S3BucketOwner] = None S3Prefix: Optional[S3Prefix] = None S3SseAlgorithm: Optional[S3SseAlgorithm] = None S3SseKmsKeyId: Optional[S3SseKmsKeyId] = None FailureCode: Optional[FailureCode] = None FailureMessage: Optional[FailureMessage] = None ExportFormat: Optional[ExportFormat] = None BilledSizeBytes: Optional[BilledSizeBytes] = None ItemCount: Optional[ItemCount] = None class KinesisDataStreamDestinations(BaseModel): __root__: List[KinesisDataStreamDestination] class TimeToLiveDescription(BaseModel): """ The description of the Time to Live (TTL) status on the specified table. """ TimeToLiveStatus: Optional[TimeToLiveStatus] = None AttributeName: Optional[TimeToLiveAttributeName] = None class ItemResponseList(BaseModel): __root__: Annotated[List[ItemResponse], Field(max_items=25, min_items=1)] class GlobalSecondaryIndexAutoScalingUpdate(BaseModel): """ Represents the auto scaling settings of a global secondary index for a global table that will be modified. """ IndexName: Optional[IndexName] = None ProvisionedWriteCapacityAutoScalingUpdate: Optional[ AutoScalingSettingsUpdate ] = None class GlobalSecondaryIndexAutoScalingUpdateList(BaseModel): __root__: Annotated[List[GlobalSecondaryIndexAutoScalingUpdate], Field(min_items=1)] class ProvisionedThroughputDescription(BaseModel): """ Represents the provisioned throughput settings for the table, consisting of read and write capacity units, along with data about increases and decreases. """ LastIncreaseDateTime: Optional[Date] = None LastDecreaseDateTime: Optional[Date] = None NumberOfDecreasesToday: Optional[PositiveLongObject] = None ReadCapacityUnits: Optional[NonNegativeLongObject] = None WriteCapacityUnits: Optional[NonNegativeLongObject] = None class GlobalTable(BaseModel): """ Represents the properties of a global table. """ GlobalTableName: Optional[TableName] = None ReplicationGroup: Optional[ReplicaList] = None class GlobalTableGlobalSecondaryIndexSettingsUpdate1(BaseModel): """ Represents the settings of a global secondary index for a global table that will be modified. """ IndexName: IndexName ProvisionedWriteCapacityUnits: Optional[PositiveLongObject] = None ProvisionedWriteCapacityAutoScalingSettingsUpdate: Optional[ AutoScalingSettingsUpdate ] = None class GlobalTableGlobalSecondaryIndexSettingsUpdateList(BaseModel): __root__: Annotated[ List[GlobalTableGlobalSecondaryIndexSettingsUpdate1], Field(max_items=20, min_items=1), ] class GlobalTableList(BaseModel): __root__: List[GlobalTable] class ItemCollectionSizeEstimateRange(BaseModel): __root__: List[ItemCollectionSizeEstimateBound] class KeySchemaElement(BaseModel): """ <p>Represents <i>a single element</i> of a key schema. A key schema specifies the attributes that make up the primary key of a table, or the key attributes of an index.</p> <p>A <code>KeySchemaElement</code> represents exactly one attribute of the primary key. For example, a simple primary key would be represented by one <code>KeySchemaElement</code> (for the partition key). A composite primary key would require one <code>KeySchemaElement</code> for the partition key, and another <code>KeySchemaElement</code> for the sort key.</p> <p>A <code>KeySchemaElement</code> must be a scalar, top-level attribute (not a nested attribute). The data type must be one of String, Number, or Binary. The attribute cannot be nested within a List or a Map.</p> """ AttributeName: KeySchemaAttributeName KeyType: KeyType class ReplicaGlobalSecondaryIndexDescriptionList(BaseModel): __root__: List[ReplicaGlobalSecondaryIndexDescription] class ReplicaDescription(BaseModel): """ Contains the details of the replica. """ RegionName: Optional[RegionName] = None ReplicaStatus: Optional[ReplicaStatus] = None ReplicaStatusDescription: Optional[ReplicaStatusDescription] = None ReplicaStatusPercentProgress: Optional[ReplicaStatusPercentProgress] = None KMSMasterKeyId: Optional[KMSMasterKeyId] = None ProvisionedThroughputOverride: Optional[ProvisionedThroughputOverride2] = None GlobalSecondaryIndexes: Optional[ReplicaGlobalSecondaryIndexDescriptionList] = None ReplicaInaccessibleDateTime: Optional[Date] = None class ReplicaGlobalSecondaryIndexAutoScalingDescription(BaseModel): """ Represents the auto scaling configuration for a replica global secondary index. """ IndexName: Optional[IndexName] = None IndexStatus: Optional[IndexStatus] = None ProvisionedReadCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None ProvisionedWriteCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None class ReplicaGlobalSecondaryIndexAutoScalingUpdate(BaseModel): """ Represents the auto scaling settings of a global secondary index for a replica that will be modified. """ IndexName: Optional[IndexName] = None ProvisionedReadCapacityAutoScalingUpdate: Optional[AutoScalingSettingsUpdate] = None class ReplicaGlobalSecondaryIndexSettingsDescription(BaseModel): """ Represents the properties of a global secondary index. """ IndexName: IndexName IndexStatus: Optional[IndexStatus] = None ProvisionedReadCapacityUnits: Optional[PositiveLongObject] = None ProvisionedReadCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None ProvisionedWriteCapacityUnits: Optional[PositiveLongObject] = None ProvisionedWriteCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None class ReplicaGlobalSecondaryIndexSettingsDescriptionList(BaseModel): __root__: List[ReplicaGlobalSecondaryIndexSettingsDescription] class ReplicaGlobalSecondaryIndexSettingsUpdate(BaseModel): """ Represents the settings of a global secondary index for a global table that will be modified. """ IndexName: IndexName ProvisionedReadCapacityUnits: Optional[PositiveLongObject] = None ProvisionedReadCapacityAutoScalingSettingsUpdate: Optional[ AutoScalingSettingsUpdate ] = None class ReplicaGlobalSecondaryIndexSettingsUpdateList(BaseModel): __root__: Annotated[ List[ReplicaGlobalSecondaryIndexSettingsUpdate], Field(max_items=20, min_items=1), ] class ReplicaSettingsDescription(BaseModel): """ Represents the properties of a replica. """ RegionName: RegionName ReplicaStatus: Optional[ReplicaStatus] = None ReplicaBillingModeSummary: Optional[BillingModeSummary] = None ReplicaProvisionedReadCapacityUnits: Optional[NonNegativeLongObject] = None ReplicaProvisionedReadCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None ReplicaProvisionedWriteCapacityUnits: Optional[NonNegativeLongObject] = None ReplicaProvisionedWriteCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None ReplicaGlobalSecondaryIndexSettings: Optional[ ReplicaGlobalSecondaryIndexSettingsDescriptionList ] = None class ReplicaSettingsUpdate1(BaseModel): """ Represents the settings for a global table in a Region that will be modified. """ RegionName: RegionName ReplicaProvisionedReadCapacityUnits: Optional[PositiveLongObject] = None ReplicaProvisionedReadCapacityAutoScalingSettingsUpdate: Optional[ AutoScalingSettingsUpdate ] = None ReplicaGlobalSecondaryIndexSettingsUpdate: Optional[ ReplicaGlobalSecondaryIndexSettingsUpdateList ] = None class ReplicaSettingsUpdateList(BaseModel): __root__: Annotated[List[ReplicaSettingsUpdate1], Field(max_items=50, min_items=1)] class UpdateReplicationGroupMemberAction(CreateReplicationGroupMemberAction): """ Represents a replica to be modified. """ pass class ReplicationGroupUpdate(BaseModel): """ <p>Represents one of the following:</p> <ul> <li> <p>A new replica to be added to an existing regional table or global table. This request invokes the <code>CreateTableReplica</code> action in the destination Region.</p> </li> <li> <p>New parameters for an existing replica. This request invokes the <code>UpdateTable</code> action in the destination Region.</p> </li> <li> <p>An existing replica to be deleted. The request invokes the <code>DeleteTableReplica</code> action in the destination Region, deleting the replica and all if its items in the destination Region.</p> </li> </ul> """ Create: Optional[CreateReplicationGroupMemberAction] = None Update: Optional[UpdateReplicationGroupMemberAction] = None Delete: Optional[DeleteReplicationGroupMemberAction] = None class ReplicationGroupUpdateList(BaseModel): __root__: Annotated[List[ReplicationGroupUpdate], Field(min_items=1)] class Update2(BaseModel): """ Represents a request to perform an <code>UpdateItem</code> operation. """ Key: Key UpdateExpression: UpdateExpression TableName: TableName ConditionExpression: Optional[ConditionExpression] = None ExpressionAttributeNames: Optional[ExpressionAttributeNameMap] = None ExpressionAttributeValues: Optional[ExpressionAttributeValueMap] = None ReturnValuesOnConditionCheckFailure: Optional[ ReturnValuesOnConditionCheckFailure ] = None class TransactWriteItem(BaseModel): """ A list of requests that can perform update, put, delete, or check operations on multiple items in one or more tables atomically. """ ConditionCheck: Optional[ConditionCheck] = None Put: Optional[Put] = None Delete: Optional[Delete] = None Update: Optional[Update2] = None class TransactWriteItemList(BaseModel): __root__: Annotated[List[TransactWriteItem], Field(max_items=25, min_items=1)] class BatchExecuteStatementOutput(BaseModel): Responses: Optional[PartiQLBatchResponse] = None class BatchGetItemOutput(BaseModel): """ Represents the output of a <code>BatchGetItem</code> operation. """ Responses: Optional[BatchGetResponseMap] = None UnprocessedKeys: Optional[BatchGetRequestMap] = None ConsumedCapacity: Optional[ConsumedCapacityMultiple] = None class BatchWriteItemOutput(BaseModel): """ Represents the output of a <code>BatchWriteItem</code> operation. """ UnprocessedItems: Optional[BatchWriteItemRequestMap] = None ItemCollectionMetrics: Optional[ItemCollectionMetricsPerTable] = None ConsumedCapacity: Optional[ConsumedCapacityMultiple] = None class CreateBackupOutput(BaseModel): BackupDetails: Optional[BackupDetails] = None class CreateGlobalTableInput(BaseModel): GlobalTableName: TableName ReplicationGroup: ReplicaList class DescribeContinuousBackupsOutput(BaseModel): ContinuousBackupsDescription: Optional[ContinuousBackupsDescription] = None class DescribeContributorInsightsOutput(BaseModel): TableName: Optional[TableName] = None IndexName: Optional[IndexName] = None ContributorInsightsRuleList: Optional[ContributorInsightsRuleList] = None ContributorInsightsStatus: Optional[ContributorInsightsStatus] = None LastUpdateDateTime: Optional[LastUpdateDateTime] = None FailureException: Optional[FailureException] = None class DescribeEndpointsResponse(BaseModel): Endpoints: Endpoints class DescribeExportOutput(BaseModel): ExportDescription: Optional[ExportDescription] = None class DescribeKinesisStreamingDestinationOutput(BaseModel): TableName: Optional[TableName] = None KinesisDataStreamDestinations: Optional[KinesisDataStreamDestinations] = None class DescribeTimeToLiveOutput(BaseModel): TimeToLiveDescription: Optional[TimeToLiveDescription] = None class ExecuteTransactionOutput(BaseModel): Responses: Optional[ItemResponseList] = None class ExportTableToPointInTimeOutput(DescribeExportOutput): pass class ListBackupsOutput(BaseModel): BackupSummaries: Optional[BackupSummaries] = None LastEvaluatedBackupArn: Optional[BackupArn] = None class ListContributorInsightsOutput(BaseModel): ContributorInsightsSummaries: Optional[ContributorInsightsSummaries] = None NextToken: Optional[NextTokenString] = None class ListGlobalTablesOutput(BaseModel): GlobalTables: Optional[GlobalTableList] = None LastEvaluatedGlobalTableName: Optional[TableName] = None class ListTagsOfResourceOutput(BaseModel): Tags: Optional[TagList] = None NextToken: Optional[NextTokenString] = None class TagResourceInput(BaseModel): ResourceArn: ResourceArnString Tags: TagList class TransactGetItemsOutput(BaseModel): ConsumedCapacity: Optional[ConsumedCapacityMultiple] = None Responses: Optional[ItemResponseList] = None class TransactWriteItemsOutput(BaseModel): ConsumedCapacity: Optional[ConsumedCapacityMultiple] = None ItemCollectionMetrics: Optional[ItemCollectionMetricsPerTable] = None class TransactWriteItemsInput(BaseModel): TransactItems: TransactWriteItemList ReturnConsumedCapacity: Optional[ReturnConsumedCapacity] = None ReturnItemCollectionMetrics: Optional[ReturnItemCollectionMetrics] = None ClientRequestToken: Optional[ClientRequestToken] = None class UpdateContinuousBackupsOutput(DescribeContinuousBackupsOutput): pass class UpdateGlobalTableSettingsInput(BaseModel): GlobalTableName: TableName GlobalTableBillingMode: Optional[BillingMode] = None GlobalTableProvisionedWriteCapacityUnits: Optional[PositiveLongObject] = None GlobalTableProvisionedWriteCapacityAutoScalingSettingsUpdate: Optional[ AutoScalingSettingsUpdate ] = None GlobalTableGlobalSecondaryIndexSettingsUpdate: Optional[ GlobalTableGlobalSecondaryIndexSettingsUpdateList ] = None ReplicaSettingsUpdate: Optional[ReplicaSettingsUpdateList] = None class KeySchema(BaseModel): __root__: Annotated[List[KeySchemaElement], Field(max_items=2, min_items=1)] class CreateGlobalSecondaryIndexAction(BaseModel): """ Represents a new global secondary index to be added to an existing table. """ IndexName: IndexName KeySchema: KeySchema Projection: Projection ProvisionedThroughput: Optional[ProvisionedThroughput] = None class ItemCollectionMetrics(BaseModel): """ Information about item collections, if any, that were affected by the operation. <code>ItemCollectionMetrics</code> is only returned if the request asked for it. If the table does not have any local secondary indexes, this information is not returned in the response. """ ItemCollectionKey: Optional[ItemCollectionKeyAttributeMap] = None SizeEstimateRangeGB: Optional[ItemCollectionSizeEstimateRange] = None class ReplicaSettingsDescriptionList(BaseModel): __root__: List[ReplicaSettingsDescription] class GlobalSecondaryIndex(CreateGlobalSecondaryIndexAction): """ Represents the properties of a global secondary index. """ pass class GlobalSecondaryIndexDescription(BaseModel): """ Represents the properties of a global secondary index. """ IndexName: Optional[IndexName] = None KeySchema: Optional[KeySchema] = None Projection: Optional[Projection] = None IndexStatus: Optional[IndexStatus] = None Backfilling: Optional[Backfilling] = None ProvisionedThroughput: Optional[ProvisionedThroughputDescription] = None IndexSizeBytes: Optional[Long] = None ItemCount: Optional[Long] = None IndexArn: Optional[String] = None class GlobalSecondaryIndexDescriptionList(BaseModel): __root__: List[GlobalSecondaryIndexDescription] class GlobalSecondaryIndexInfo(BaseModel): """ Represents the properties of a global secondary index for the table when the backup was created. """ IndexName: Optional[IndexName] = None KeySchema: Optional[KeySchema] = None Projection: Optional[Projection] = None ProvisionedThroughput: Optional[ProvisionedThroughput] = None class GlobalSecondaryIndexUpdate(BaseModel): """ <p>Represents one of the following:</p> <ul> <li> <p>A new global secondary index to be added to an existing table.</p> </li> <li> <p>New provisioned throughput parameters for an existing global secondary index.</p> </li> <li> <p>An existing global secondary index to be removed from an existing table.</p> </li> </ul> """ Update: Optional[UpdateGlobalSecondaryIndexAction] = None Create: Optional[CreateGlobalSecondaryIndexAction] = None Delete: Optional[DeleteGlobalSecondaryIndexAction] = None class GlobalSecondaryIndexUpdateList(BaseModel): __root__: List[GlobalSecondaryIndexUpdate] class GlobalSecondaryIndexes(BaseModel): __root__: List[GlobalSecondaryIndexInfo] class ReplicaDescriptionList(BaseModel): __root__: List[ReplicaDescription] class ItemCollectionMetricsMultiple(BaseModel): __root__: List[ItemCollectionMetrics] class LocalSecondaryIndex(BaseModel): """ Represents the properties of a local secondary index. """ IndexName: IndexName KeySchema: KeySchema Projection: Projection class LocalSecondaryIndexDescription(BaseModel): """ Represents the properties of a local secondary index. """ IndexName: Optional[IndexName] = None KeySchema: Optional[KeySchema] = None Projection: Optional[Projection] = None IndexSizeBytes: Optional[Long] = None ItemCount: Optional[Long] = None IndexArn: Optional[String] = None class LocalSecondaryIndexDescriptionList(BaseModel): __root__: List[LocalSecondaryIndexDescription] class LocalSecondaryIndexInfo(BaseModel): """ Represents the properties of a local secondary index for the table when the backup was created. """ IndexName: Optional[IndexName] = None KeySchema: Optional[KeySchema] = None Projection: Optional[Projection] = None class LocalSecondaryIndexes(BaseModel): __root__: List[LocalSecondaryIndexInfo] class ReplicaGlobalSecondaryIndexAutoScalingDescriptionList(BaseModel): __root__: List[ReplicaGlobalSecondaryIndexAutoScalingDescription] class ReplicaAutoScalingDescription(BaseModel): """ Represents the auto scaling settings of the replica. """ RegionName: Optional[RegionName] = None GlobalSecondaryIndexes: Optional[ ReplicaGlobalSecondaryIndexAutoScalingDescriptionList ] = None ReplicaProvisionedReadCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None ReplicaProvisionedWriteCapacityAutoScalingSettings: Optional[ AutoScalingSettingsDescription ] = None ReplicaStatus: Optional[ReplicaStatus] = None class ReplicaAutoScalingDescriptionList(BaseModel): __root__: List[ReplicaAutoScalingDescription] class ReplicaGlobalSecondaryIndexAutoScalingUpdateList(BaseModel): __root__: List[ReplicaGlobalSecondaryIndexAutoScalingUpdate] class ReplicaAutoScalingUpdate(BaseModel): """ Represents the auto scaling settings of a replica that will be modified. """ RegionName: RegionName ReplicaGlobalSecondaryIndexUpdates: Optional[ ReplicaGlobalSecondaryIndexAutoScalingUpdateList ] = None ReplicaProvisionedReadCapacityAutoScalingUpdate: Optional[ AutoScalingSettingsUpdate ] = None class ReplicaAutoScalingUpdateList(BaseModel): __root__: Annotated[List[ReplicaAutoScalingUpdate], Field(min_items=1)] class DeleteItemOutput(BaseModel): """ Represents the output of a <code>DeleteItem</code> operation. """ Attributes: Optional[AttributeMap] = None ConsumedCapacity: Optional[ConsumedCapacity] = None ItemCollectionMetrics: Optional[ItemCollectionMetrics] = None class DescribeGlobalTableSettingsOutput(BaseModel): GlobalTableName: Optional[TableName] = None ReplicaSettings: Optional[ReplicaSettingsDescriptionList] = None class PutItemOutput(DeleteItemOutput): """ Represents the output of a <code>PutItem</code> operation. """ pass class UpdateGlobalTableSettingsOutput(DescribeGlobalTableSettingsOutput): pass class UpdateItemOutput(DeleteItemOutput): """ Represents the output of an <code>UpdateItem</code> operation. """ pass class UpdateTableInput(BaseModel): """ Represents the input of an <code>UpdateTable</code> operation. """ AttributeDefinitions: Optional[AttributeDefinitions] = None TableName: TableName BillingMode: Optional[BillingMode] = None ProvisionedThroughput: Optional[ProvisionedThroughput] = None GlobalSecondaryIndexUpdates: Optional[GlobalSecondaryIndexUpdateList] = None StreamSpecification: Optional[StreamSpecification] = None SSESpecification: Optional[SSESpecification] = None ReplicaUpdates: Optional[ReplicationGroupUpdateList] = None class UpdateTableReplicaAutoScalingInput(BaseModel): GlobalSecondaryIndexUpdates: Optional[ GlobalSecondaryIndexAutoScalingUpdateList ] = None TableName: TableName ProvisionedWriteCapacityAutoScalingUpdate: Optional[ AutoScalingSettingsUpdate ] = None ReplicaUpdates: Optional[ReplicaAutoScalingUpdateList] = None class SourceTableDetails(BaseModel): """ Contains the details of the table when the backup was created. """ TableName: TableName TableId: TableId TableArn: Optional[TableArn] = None TableSizeBytes: Optional[Long] = None KeySchema: KeySchema TableCreationDateTime: TableCreationDateTime ProvisionedThroughput: ProvisionedThroughput ItemCount: Optional[ItemCount] = None BillingMode: Optional[BillingMode] = None class SourceTableFeatureDetails(BaseModel): """ Contains the details of the features enabled on the table when the backup was created. For example, LSIs, GSIs, streams, TTL. """ LocalSecondaryIndexes: Optional[LocalSecondaryIndexes] = None GlobalSecondaryIndexes: Optional[GlobalSecondaryIndexes] = None StreamDescription: Optional[StreamSpecification] = None TimeToLiveDescription: Optional[TimeToLiveDescription] = None SSEDescription: Optional[SSEDescription] = None class BackupDescription(BaseModel): """ Contains the description of the backup created for the table. """ BackupDetails: Optional[BackupDetails] = None SourceTableDetails: Optional[SourceTableDetails] = None SourceTableFeatureDetails: Optional[SourceTableFeatureDetails] = None class GlobalTableDescription(BaseModel): """ Contains details about the global table. """ ReplicationGroup: Optional[ReplicaDescriptionList] = None GlobalTableArn: Optional[GlobalTableArnString] = None CreationDateTime: Optional[Date] = None GlobalTableStatus: Optional[GlobalTableStatus] = None GlobalTableName: Optional[TableName] = None class LocalSecondaryIndexList(BaseModel): __root__: List[LocalSecondaryIndex] class GlobalSecondaryIndexList(BaseModel): __root__: List[GlobalSecondaryIndex] class TableDescription(BaseModel): """ Represents the properties of a table. """ AttributeDefinitions: Optional[AttributeDefinitions] = None TableName: Optional[TableName] = None KeySchema: Optional[KeySchema] = None TableStatus: Optional[TableStatus] = None CreationDateTime: Optional[Date] = None ProvisionedThroughput: Optional[ProvisionedThroughputDescription] = None TableSizeBytes: Optional[Long] = None ItemCount: Optional[Long] = None TableArn: Optional[String] = None TableId: Optional[TableId] = None BillingModeSummary: Optional[BillingModeSummary] = None LocalSecondaryIndexes: Optional[LocalSecondaryIndexDescriptionList] = None GlobalSecondaryIndexes: Optional[GlobalSecondaryIndexDescriptionList] = None StreamSpecification: Optional[StreamSpecification] = None LatestStreamLabel: Optional[String] = None LatestStreamArn: Optional[StreamArn] = None GlobalTableVersion: Optional[String] = None Replicas: Optional[ReplicaDescriptionList] = None RestoreSummary: Optional[RestoreSummary] = None SSEDescription: Optional[SSEDescription] = None ArchivalSummary: Optional[ArchivalSummary] = None class TableAutoScalingDescription(BaseModel): """ Represents the auto scaling configuration for a global table. """ TableName: Optional[TableName] = None TableStatus: Optional[TableStatus] = None Replicas: Optional[ReplicaAutoScalingDescriptionList] = None class CreateGlobalTableOutput(BaseModel): GlobalTableDescription: Optional[GlobalTableDescription] = None class CreateTableOutput(BaseModel): """ Represents the output of a <code>CreateTable</code> operation. """ TableDescription: Optional[TableDescription] = None class CreateTableInput(BaseModel): """ Represents the input of a <code>CreateTable</code> operation. """ AttributeDefinitions: AttributeDefinitions TableName: TableName KeySchema: KeySchema LocalSecondaryIndexes: Optional[LocalSecondaryIndexList] = None GlobalSecondaryIndexes: Optional[GlobalSecondaryIndexList] = None BillingMode: Optional[BillingMode] = None ProvisionedThroughput: Optional[ProvisionedThroughput] = None StreamSpecification: Optional[StreamSpecification] = None SSESpecification: Optional[SSESpecification] = None Tags: Optional[TagList] = None class DeleteBackupOutput(BaseModel): BackupDescription: Optional[BackupDescription] = None class DeleteTableOutput(CreateTableOutput): """ Represents the output of a <code>DeleteTable</code> operation. """ pass class DescribeBackupOutput(DeleteBackupOutput): pass class DescribeGlobalTableOutput(CreateGlobalTableOutput): pass class DescribeTableOutput(BaseModel): """ Represents the output of a <code>DescribeTable</code> operation. """ Table: Optional[TableDescription] = None class DescribeTableReplicaAutoScalingOutput(BaseModel): TableAutoScalingDescription: Optional[TableAutoScalingDescription] = None class RestoreTableFromBackupOutput(CreateTableOutput): pass class RestoreTableFromBackupInput(BaseModel): TargetTableName: TableName BackupArn: BackupArn BillingModeOverride: Optional[BillingMode] = None GlobalSecondaryIndexOverride: Optional[GlobalSecondaryIndexList] = None LocalSecondaryIndexOverride: Optional[LocalSecondaryIndexList] = None ProvisionedThroughputOverride: Optional[ProvisionedThroughput] = None SSESpecificationOverride: Optional[SSESpecification] = None class RestoreTableToPointInTimeOutput(CreateTableOutput): pass class RestoreTableToPointInTimeInput(BaseModel): SourceTableArn: Optional[TableArn] = None SourceTableName: Optional[TableName] = None TargetTableName: TableName UseLatestRestorableTime: Optional[BooleanObject] = None RestoreDateTime: Optional[Date] = None BillingModeOverride: Optional[BillingMode] = None GlobalSecondaryIndexOverride: Optional[GlobalSecondaryIndexList] = None LocalSecondaryIndexOverride: Optional[LocalSecondaryIndexList] = None ProvisionedThroughputOverride: Optional[ProvisionedThroughput] = None SSESpecificationOverride: Optional[SSESpecification] = None class UpdateGlobalTableOutput(CreateGlobalTableOutput): pass class UpdateTableOutput(CreateTableOutput): """ Represents the output of an <code>UpdateTable</code> operation. """ pass class UpdateTableReplicaAutoScalingOutput(DescribeTableReplicaAutoScalingOutput): pass class BatchExecuteStatementInput(BaseModel): Statements: PartiQLBatchRequest class ExecuteStatementInput(BaseModel): Statement: PartiQLStatement Parameters: Optional[PreparedStatementParameters] = None ConsistentRead: Optional[ConsistentRead] = None NextToken: Optional[PartiQLNextToken] = None class ExecuteTransactionInput(BaseModel): TransactStatements: ParameterizedStatements ClientRequestToken: Optional[ClientRequestToken] = None class AttributeValue(BaseModel): """ <p>Represents the data for an attribute.</p> <p>Each attribute value is described as a name-value pair. The name is the data type, and the value is the data itself.</p> <p>For more information, see <a href="https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.NamingRulesDataTypes.html#HowItWorks.DataTypes">Data Types</a> in the <i>Amazon DynamoDB Developer Guide</i>.</p> """ S: Optional[StringAttributeValue] = None N: Optional[NumberAttributeValue] = None B: Optional[BinaryAttributeValue] = None SS: Optional[StringSetAttributeValue] = None NS: Optional[NumberSetAttributeValue] = None BS: Optional[BinarySetAttributeValue] = None M: Optional[MapAttributeValue] = None L: Optional[ListAttributeValue] = None NULL: Optional[NullAttributeValue] = None BOOL: Optional[BooleanAttributeValue] = None class AttributeValueUpdate(BaseModel): """ <p>For the <code>UpdateItem</code> operation, represents the attributes to be modified, the action to perform on each, and the new value for each.</p> <note> <p>You cannot use <code>UpdateItem</code> to update any primary key attributes. Instead, you will need to delete the item, and then use <code>PutItem</code> to create a new item with new attributes.</p> </note> <p>Attribute values cannot be null; string and binary type attributes must have lengths greater than zero; and set type attributes must not be empty. Requests with empty values will be rejected with a <code>ValidationException</code> exception.</p> """ Value: Optional[AttributeValue] = None Action: Optional[AttributeAction] = None class ListAttributeValue(BaseModel): __root__: List[AttributeValue] class AttributeValueList(ListAttributeValue): pass class PartiQLBatchRequest(BaseModel): __root__: Annotated[List[BatchStatementRequest], Field(max_items=25, min_items=1)] class PreparedStatementParameters(BaseModel): __root__: Annotated[List[AttributeValue], Field(min_items=1)] class BatchStatementRequest(BaseModel): """ A PartiQL batch statement request. """ Statement: PartiQLStatement Parameters: Optional[PreparedStatementParameters] = None ConsistentRead: Optional[ConsistentRead] = None class Condition(BaseModel): """ <p>Represents the selection criteria for a <code>Query</code> or <code>Scan</code> operation:</p> <ul> <li> <p>For a <code>Query</code> operation, <code>Condition</code> is used for specifying the <code>KeyConditions</code> to use when querying a table or an index. For <code>KeyConditions</code>, only the following comparison operators are supported:</p> <p> <code>EQ | LE | LT | GE | GT | BEGINS_WITH | BETWEEN</code> </p> <p> <code>Condition</code> is also used in a <code>QueryFilter</code>, which evaluates the query results and returns only the desired values.</p> </li> <li> <p>For a <code>Scan</code> operation, <code>Condition</code> is used in a <code>ScanFilter</code>, which evaluates the scan results and returns only the desired values.</p> </li> </ul> """ AttributeValueList: Optional[AttributeValueList] = None ComparisonOperator: ComparisonOperator class ParameterizedStatements(BaseModel): __root__: Annotated[List[ParameterizedStatement], Field(max_items=25, min_items=1)] class ExpectedAttributeValue(BaseModel): """ <p>Represents a condition to be compared with an attribute value. This condition can be used with <code>DeleteItem</code>, <code>PutItem</code>, or <code>UpdateItem</code> operations; if the comparison evaluates to true, the operation succeeds; if not, the operation fails. You can use <code>ExpectedAttributeValue</code> in one of two different ways:</p> <ul> <li> <p>Use <code>AttributeValueList</code> to specify one or more values to compare against an attribute. Use <code>ComparisonOperator</code> to specify how you want to perform the comparison. If the comparison evaluates to true, then the conditional operation succeeds.</p> </li> <li> <p>Use <code>Value</code> to specify a value that DynamoDB will compare against an attribute. If the values match, then <code>ExpectedAttributeValue</code> evaluates to true and the conditional operation succeeds. Optionally, you can also set <code>Exists</code> to false, indicating that you <i>do not</i> expect to find the attribute value in the table. In this case, the conditional operation succeeds only if the comparison evaluates to false.</p> </li> </ul> <p> <code>Value</code> and <code>Exists</code> are incompatible with <code>AttributeValueList</code> and <code>ComparisonOperator</code>. Note that if you use both sets of parameters at once, DynamoDB will return a <code>ValidationException</code> exception.</p> """ Value: Optional[AttributeValue] = None Exists: Optional[BooleanObject] = None ComparisonOperator: Optional[ComparisonOperator] = None AttributeValueList: Optional[AttributeValueList] = None class ParameterizedStatement(BaseModel): """ Represents a PartiQL statment that uses parameters. """ Statement: PartiQLStatement Parameters: Optional[PreparedStatementParameters] = None BatchExecuteStatementInput.update_forward_refs() ExecuteStatementInput.update_forward_refs() ExecuteTransactionInput.update_forward_refs() AttributeValue.update_forward_refs() PartiQLBatchRequest.update_forward_refs() ParameterizedStatements.update_forward_refs()
28.318693
1,378
0.755441
6,925
78,018
8.443032
0.145126
0.019857
0.0222
0.008004
0.374786
0.29399
0.24179
0.205001
0.16161
0.128019
0
0.003623
0.165154
78,018
2,754
1,379
28.328976
0.894048
0.201402
0
0.433659
1
0.001397
0.019898
0.004714
0
0
0
0
0
1
0
false
0.087989
0.003492
0
0.854749
0
0
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
1
0
0
0
null
0
0
0
0
0
0
0
1
0
0
1
0
0
4
1690e7b7ca5bc3ba56945d33e300d132844e3bee
68
py
Python
test/input/041.py
EliRibble/pyfmt
e84a5531a7c06703eddd9dbc2072b0c8deae8c57
[ "MIT" ]
null
null
null
test/input/041.py
EliRibble/pyfmt
e84a5531a7c06703eddd9dbc2072b0c8deae8c57
[ "MIT" ]
null
null
null
test/input/041.py
EliRibble/pyfmt
e84a5531a7c06703eddd9dbc2072b0c8deae8c57
[ "MIT" ]
null
null
null
def main(): print(not 1) if __name__ == "__main__": main()
11.333333
26
0.558824
9
68
3.333333
0.777778
0
0
0
0
0
0
0
0
0
0
0.02
0.264706
68
5
27
13.6
0.58
0
0
0
0
0
0.117647
0
0
0
0
0
0
1
0.25
true
0
0
0
0.25
0.25
1
0
0
null
0
0
0
0
0
0
0
0
0
0
0
0
0
1
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
1
0
0
0
0
0
0
4
16937d782e0ca6a30df708f6e665284a7b97b51d
172
py
Python
oldstuff/python/pythonchallenge/3.py
bcherry/bcherry
5d2f1144dbdbf35d6284018fa2c9e24ec5cecec6
[ "MIT" ]
3
2016-11-13T09:06:41.000Z
2021-09-11T23:36:19.000Z
oldstuff/python/pythonchallenge/3.py
bcherry/bcherry
5d2f1144dbdbf35d6284018fa2c9e24ec5cecec6
[ "MIT" ]
null
null
null
oldstuff/python/pythonchallenge/3.py
bcherry/bcherry
5d2f1144dbdbf35d6284018fa2c9e24ec5cecec6
[ "MIT" ]
2
2017-04-04T10:03:18.000Z
2021-09-11T23:36:26.000Z
import re text = open("equality.txt",'r').read() regex = '[a-z][A-Z][A-Z][A-Z]([a-z])[A-Z][A-Z][A-Z][a-z]' p = re.compile(regex) ans = p.findall(text) print ''.join(ans)
19.111111
57
0.563953
38
172
2.552632
0.447368
0.185567
0.247423
0.329897
0.185567
0.185567
0.185567
0.185567
0.185567
0.185567
0
0
0.104651
172
8
58
21.5
0.62987
0
0
0
0
0.166667
0.350877
0.274854
0
0
0
0
0
0
null
null
0
0.166667
null
null
0.166667
0
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
1
0
0
0
0
0
0
0
0
4
169e7e2df045afae658042b8ef2d0792f65a3941
151
py
Python
setup.py
jolnanis/motus
e608827f6e16ff88d2e231d9ce3fea4767969424
[ "MIT" ]
null
null
null
setup.py
jolnanis/motus
e608827f6e16ff88d2e231d9ce3fea4767969424
[ "MIT" ]
null
null
null
setup.py
jolnanis/motus
e608827f6e16ff88d2e231d9ce3fea4767969424
[ "MIT" ]
null
null
null
from setuptools import setup, find_packages setup( name='motus', version='0.0.1', packages=find_packages(exclude=('tests', 'tests.*')), )
18.875
57
0.662252
19
151
5.157895
0.684211
0.244898
0
0
0
0
0
0
0
0
0
0.023622
0.15894
151
7
58
21.571429
0.748032
0
0
0
0
0
0.145695
0
0
0
0
0
0
1
0
true
0
0.166667
0
0.166667
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
0
1
0
0
0
0
0
0
4
16ce88e5740fb6fbe5ca58ac247bb4e347732222
906
py
Python
dcpython/app/views.py
lauralorenz/dcpython-django
0a1c6539d8717f858e6c97a88c639729d034f255
[ "Apache-2.0" ]
null
null
null
dcpython/app/views.py
lauralorenz/dcpython-django
0a1c6539d8717f858e6c97a88c639729d034f255
[ "Apache-2.0" ]
null
null
null
dcpython/app/views.py
lauralorenz/dcpython-django
0a1c6539d8717f858e6c97a88c639729d034f255
[ "Apache-2.0" ]
null
null
null
from django.shortcuts import get_object_or_404, render from dcpython.support.models import Donor from dcpython.events.models import Event from dcpython.blog.models import Post from django.conf import settings def home(request): upcoming = Event.objects.upcoming()[:3] donor = Donor.objects.random() posts = Post.objects.published()[:3] return render(request, 'app/home.html', {"upcoming": upcoming, "posts": posts, "donor": donor, "donor_level": donor.get_level()[1] if donor else None, 'GOOGLE_VERIFICATION_ID': settings.GOOGLE_VERIFICATION_ID}) def about(request): return render(request, 'app/about.html') def deals(request): return render(request, 'app/deals.html') def resources(request): return render(request, 'app/resources.html') def legal(request): return render(request, 'app/legal.html') def contact(request): return render(request, 'app/contact.html')
33.555556
214
0.741722
123
906
5.390244
0.357724
0.108597
0.171946
0.199095
0.218703
0
0
0
0
0
0
0.007595
0.128035
906
26
215
34.846154
0.831646
0
0
0
0
0
0.154525
0.024283
0
0
0
0
0
1
0.3
false
0
0.25
0.25
0.85
0
0
0
0
null
0
0
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
null
0
0
0
0
0
1
0
0
0
1
1
0
0
4
bc4ab3287930155150106601fe152ad248919006
61
py
Python
app/nlpapp.py
chutianwen/deep-siamese-text-similarity
e7f74e703789f923f8642f98949936f7f1eac2ae
[ "MIT" ]
null
null
null
app/nlpapp.py
chutianwen/deep-siamese-text-similarity
e7f74e703789f923f8642f98949936f7f1eac2ae
[ "MIT" ]
null
null
null
app/nlpapp.py
chutianwen/deep-siamese-text-similarity
e7f74e703789f923f8642f98949936f7f1eac2ae
[ "MIT" ]
null
null
null
class NLPApp(object): def run(self): raise NotImplemented
15.25
22
0.754098
8
61
5.75
1
0
0
0
0
0
0
0
0
0
0
0
0.147541
61
4
22
15.25
0.884615
0
0
0
0
0
0
0
0
0
0
0
0
1
0.333333
false
0
0
0
0.666667
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
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
bc4af06d7f9e9c7a507cd8bae65920b4bbbf72fe
81
py
Python
aww/apps.py
JamesMusyoka/AWWARDS
79006b0aa31711a6e599e51ab3a8a542d629078d
[ "MIT" ]
1
2019-05-11T06:54:59.000Z
2019-05-11T06:54:59.000Z
aww/apps.py
JamesMusyoka/AWWARDS
79006b0aa31711a6e599e51ab3a8a542d629078d
[ "MIT" ]
1
2020-02-12T00:12:22.000Z
2020-02-12T00:12:22.000Z
aww/apps.py
JamesMusyoka/AWWARDS
79006b0aa31711a6e599e51ab3a8a542d629078d
[ "MIT" ]
6
2018-02-16T19:09:57.000Z
2021-03-29T03:32:36.000Z
from django.apps import AppConfig class AwwConfig(AppConfig): name = 'aww'
13.5
33
0.728395
10
81
5.9
0.9
0
0
0
0
0
0
0
0
0
0
0
0.185185
81
5
34
16.2
0.893939
0
0
0
0
0
0.037037
0
0
0
0
0
0
1
0
false
0
0.333333
0
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
0
0
0
0
null
0
0
0
0
0
0
0
0
1
0
1
0
0
4
bc4f0bbb650014b44f94b58b38f6d6318bae24b6
154
py
Python
encoders/__init__.py
gicheonkang/DAN-VisDial
3af6efa4b4f6bc884dbb10d7bd81e0cc9d7cc940
[ "MIT" ]
35
2019-08-19T16:12:58.000Z
2021-04-02T14:01:19.000Z
encoders/__init__.py
babymind-project/DAN-VisDial
a40422367f349b185c9f3abf5e99c7504eebdc81
[ "MIT" ]
7
2019-08-26T00:43:08.000Z
2021-04-20T11:51:15.000Z
encoders/__init__.py
babymind-project/DAN-VisDial
a40422367f349b185c9f3abf5e99c7504eebdc81
[ "MIT" ]
12
2019-09-05T02:23:06.000Z
2021-03-17T07:52:32.000Z
from .encoder import DAN def Encoder(model_args): name_enc_map = { 'dan': DAN } return name_enc_map[model_args.encoder](model_args)
17.111111
55
0.668831
22
154
4.363636
0.5
0.28125
0.333333
0
0
0
0
0
0
0
0
0
0.233766
154
8
56
19.25
0.813559
0
0
0
0
0
0.019608
0
0
0
0
0
0
1
0.166667
false
0
0.166667
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
0
0
0
0
0
0
0
0
0
0
4
bc5238d9ef896b0e52dbe2b3edf92ff5128d979e
187
py
Python
private/web/default.py
shimataro/brocadefw
c49e6a448a83d47d3b7046194748a97c19a3e1d7
[ "MIT" ]
1
2015-11-22T06:27:56.000Z
2015-11-22T06:27:56.000Z
private/web/default.py
shimataro/brocadefw
c49e6a448a83d47d3b7046194748a97c19a3e1d7
[ "MIT" ]
null
null
null
private/web/default.py
shimataro/brocadefw
c49e6a448a83d47d3b7046194748a97c19a3e1d7
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ デフォルト画面 """ from private.application import MyBaseHandler class Handler(MyBaseHandler): def on_get(self): """ リクエスト処理 """ return self.status_error(404)
18.7
45
0.684492
22
187
5.727273
0.909091
0
0
0
0
0
0
0
0
0
0
0.025157
0.149733
187
9
46
20.777778
0.767296
0.213904
0
0
0
0
0
0
0
0
0
0
0
1
0.25
false
0
0.25
0
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
0
0
0
0
null
0
0
0
0
0
1
0
0
0
0
1
0
0
4
bc55fde07d90de1d16b8ee8c6f62c58a5b6cde03
243
py
Python
Mundo1/ex019.py
kasemiro/AulasCursoEmVideo
31bc0d86c41e06740b7ea4dbff5ee38661adffb1
[ "MIT" ]
null
null
null
Mundo1/ex019.py
kasemiro/AulasCursoEmVideo
31bc0d86c41e06740b7ea4dbff5ee38661adffb1
[ "MIT" ]
null
null
null
Mundo1/ex019.py
kasemiro/AulasCursoEmVideo
31bc0d86c41e06740b7ea4dbff5ee38661adffb1
[ "MIT" ]
null
null
null
from random import choice a1 = input('Nome do aluno: ') a2 = input('Nome do aluno: ') a3 = input('Nome do aluno: ') a4 = input('Nome do aluno: ') lista = [a1, a2, a3, a4] sorteio = choice(lista) print('O aluno sorteado foi {}'.format(sorteio))
30.375
48
0.658436
39
243
4.102564
0.487179
0.225
0.275
0.4
0
0
0
0
0
0
0
0.039604
0.168724
243
8
48
30.375
0.752475
0
0
0
0
0
0.340164
0
0
0
0
0
0
1
0
false
0
0.125
0
0.125
0.125
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
0
0
0
0
0
0
0
4