How to use to method in storybook-root

Best JavaScript code snippet using storybook-root

test_asfreq.py

Source:test_asfreq.py Github

copy

Full Screen

1import pytest2from pandas._libs.tslibs.frequencies import (3 INVALID_FREQ_ERR_MSG, _period_code_map)4from pandas.errors import OutOfBoundsDatetime5from pandas import Period, offsets6class TestFreqConversion(object):7 """Test frequency conversion of date objects"""8 @pytest.mark.parametrize('freq', ['A', 'Q', 'M', 'W', 'B', 'D'])9 def test_asfreq_near_zero(self, freq):10 # GH#19643, GH#1965011 per = Period('0001-01-01', freq=freq)12 tup1 = (per.year, per.hour, per.day)13 prev = per - 114 assert prev.ordinal == per.ordinal - 115 tup2 = (prev.year, prev.month, prev.day)16 assert tup2 < tup117 def test_asfreq_near_zero_weekly(self):18 # GH#1983419 per1 = Period('0001-01-01', 'D') + 620 per2 = Period('0001-01-01', 'D') - 621 week1 = per1.asfreq('W')22 week2 = per2.asfreq('W')23 assert week1 != week224 assert week1.asfreq('D', 'E') >= per125 assert week2.asfreq('D', 'S') <= per226 @pytest.mark.xfail(reason='GH#19643 period_helper asfreq functions fail '27 'to check for overflows')28 def test_to_timestamp_out_of_bounds(self):29 # GH#19643, currently gives Timestamp('1754-08-30 22:43:41.128654848')30 per = Period('0001-01-01', freq='B')31 with pytest.raises(OutOfBoundsDatetime):32 per.to_timestamp()33 def test_asfreq_corner(self):34 val = Period(freq='A', year=2007)35 result1 = val.asfreq('5t')36 result2 = val.asfreq('t')37 expected = Period('2007-12-31 23:59', freq='t')38 assert result1.ordinal == expected.ordinal39 assert result1.freqstr == '5T'40 assert result2.ordinal == expected.ordinal41 assert result2.freqstr == 'T'42 def test_conv_annual(self):43 # frequency conversion tests: from Annual Frequency44 ival_A = Period(freq='A', year=2007)45 ival_AJAN = Period(freq="A-JAN", year=2007)46 ival_AJUN = Period(freq="A-JUN", year=2007)47 ival_ANOV = Period(freq="A-NOV", year=2007)48 ival_A_to_Q_start = Period(freq='Q', year=2007, quarter=1)49 ival_A_to_Q_end = Period(freq='Q', year=2007, quarter=4)50 ival_A_to_M_start = Period(freq='M', year=2007, month=1)51 ival_A_to_M_end = Period(freq='M', year=2007, month=12)52 ival_A_to_W_start = Period(freq='W', year=2007, month=1, day=1)53 ival_A_to_W_end = Period(freq='W', year=2007, month=12, day=31)54 ival_A_to_B_start = Period(freq='B', year=2007, month=1, day=1)55 ival_A_to_B_end = Period(freq='B', year=2007, month=12, day=31)56 ival_A_to_D_start = Period(freq='D', year=2007, month=1, day=1)57 ival_A_to_D_end = Period(freq='D', year=2007, month=12, day=31)58 ival_A_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)59 ival_A_to_H_end = Period(freq='H', year=2007, month=12, day=31,60 hour=23)61 ival_A_to_T_start = Period(freq='Min', year=2007, month=1, day=1,62 hour=0, minute=0)63 ival_A_to_T_end = Period(freq='Min', year=2007, month=12, day=31,64 hour=23, minute=59)65 ival_A_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,66 minute=0, second=0)67 ival_A_to_S_end = Period(freq='S', year=2007, month=12, day=31,68 hour=23, minute=59, second=59)69 ival_AJAN_to_D_end = Period(freq='D', year=2007, month=1, day=31)70 ival_AJAN_to_D_start = Period(freq='D', year=2006, month=2, day=1)71 ival_AJUN_to_D_end = Period(freq='D', year=2007, month=6, day=30)72 ival_AJUN_to_D_start = Period(freq='D', year=2006, month=7, day=1)73 ival_ANOV_to_D_end = Period(freq='D', year=2007, month=11, day=30)74 ival_ANOV_to_D_start = Period(freq='D', year=2006, month=12, day=1)75 assert ival_A.asfreq('Q', 'S') == ival_A_to_Q_start76 assert ival_A.asfreq('Q', 'e') == ival_A_to_Q_end77 assert ival_A.asfreq('M', 's') == ival_A_to_M_start78 assert ival_A.asfreq('M', 'E') == ival_A_to_M_end79 assert ival_A.asfreq('W', 'S') == ival_A_to_W_start80 assert ival_A.asfreq('W', 'E') == ival_A_to_W_end81 assert ival_A.asfreq('B', 'S') == ival_A_to_B_start82 assert ival_A.asfreq('B', 'E') == ival_A_to_B_end83 assert ival_A.asfreq('D', 'S') == ival_A_to_D_start84 assert ival_A.asfreq('D', 'E') == ival_A_to_D_end85 assert ival_A.asfreq('H', 'S') == ival_A_to_H_start86 assert ival_A.asfreq('H', 'E') == ival_A_to_H_end87 assert ival_A.asfreq('min', 'S') == ival_A_to_T_start88 assert ival_A.asfreq('min', 'E') == ival_A_to_T_end89 assert ival_A.asfreq('T', 'S') == ival_A_to_T_start90 assert ival_A.asfreq('T', 'E') == ival_A_to_T_end91 assert ival_A.asfreq('S', 'S') == ival_A_to_S_start92 assert ival_A.asfreq('S', 'E') == ival_A_to_S_end93 assert ival_AJAN.asfreq('D', 'S') == ival_AJAN_to_D_start94 assert ival_AJAN.asfreq('D', 'E') == ival_AJAN_to_D_end95 assert ival_AJUN.asfreq('D', 'S') == ival_AJUN_to_D_start96 assert ival_AJUN.asfreq('D', 'E') == ival_AJUN_to_D_end97 assert ival_ANOV.asfreq('D', 'S') == ival_ANOV_to_D_start98 assert ival_ANOV.asfreq('D', 'E') == ival_ANOV_to_D_end99 assert ival_A.asfreq('A') == ival_A100 def test_conv_quarterly(self):101 # frequency conversion tests: from Quarterly Frequency102 ival_Q = Period(freq='Q', year=2007, quarter=1)103 ival_Q_end_of_year = Period(freq='Q', year=2007, quarter=4)104 ival_QEJAN = Period(freq="Q-JAN", year=2007, quarter=1)105 ival_QEJUN = Period(freq="Q-JUN", year=2007, quarter=1)106 ival_Q_to_A = Period(freq='A', year=2007)107 ival_Q_to_M_start = Period(freq='M', year=2007, month=1)108 ival_Q_to_M_end = Period(freq='M', year=2007, month=3)109 ival_Q_to_W_start = Period(freq='W', year=2007, month=1, day=1)110 ival_Q_to_W_end = Period(freq='W', year=2007, month=3, day=31)111 ival_Q_to_B_start = Period(freq='B', year=2007, month=1, day=1)112 ival_Q_to_B_end = Period(freq='B', year=2007, month=3, day=30)113 ival_Q_to_D_start = Period(freq='D', year=2007, month=1, day=1)114 ival_Q_to_D_end = Period(freq='D', year=2007, month=3, day=31)115 ival_Q_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)116 ival_Q_to_H_end = Period(freq='H', year=2007, month=3, day=31, hour=23)117 ival_Q_to_T_start = Period(freq='Min', year=2007, month=1, day=1,118 hour=0, minute=0)119 ival_Q_to_T_end = Period(freq='Min', year=2007, month=3, day=31,120 hour=23, minute=59)121 ival_Q_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,122 minute=0, second=0)123 ival_Q_to_S_end = Period(freq='S', year=2007, month=3, day=31, hour=23,124 minute=59, second=59)125 ival_QEJAN_to_D_start = Period(freq='D', year=2006, month=2, day=1)126 ival_QEJAN_to_D_end = Period(freq='D', year=2006, month=4, day=30)127 ival_QEJUN_to_D_start = Period(freq='D', year=2006, month=7, day=1)128 ival_QEJUN_to_D_end = Period(freq='D', year=2006, month=9, day=30)129 assert ival_Q.asfreq('A') == ival_Q_to_A130 assert ival_Q_end_of_year.asfreq('A') == ival_Q_to_A131 assert ival_Q.asfreq('M', 'S') == ival_Q_to_M_start132 assert ival_Q.asfreq('M', 'E') == ival_Q_to_M_end133 assert ival_Q.asfreq('W', 'S') == ival_Q_to_W_start134 assert ival_Q.asfreq('W', 'E') == ival_Q_to_W_end135 assert ival_Q.asfreq('B', 'S') == ival_Q_to_B_start136 assert ival_Q.asfreq('B', 'E') == ival_Q_to_B_end137 assert ival_Q.asfreq('D', 'S') == ival_Q_to_D_start138 assert ival_Q.asfreq('D', 'E') == ival_Q_to_D_end139 assert ival_Q.asfreq('H', 'S') == ival_Q_to_H_start140 assert ival_Q.asfreq('H', 'E') == ival_Q_to_H_end141 assert ival_Q.asfreq('Min', 'S') == ival_Q_to_T_start142 assert ival_Q.asfreq('Min', 'E') == ival_Q_to_T_end143 assert ival_Q.asfreq('S', 'S') == ival_Q_to_S_start144 assert ival_Q.asfreq('S', 'E') == ival_Q_to_S_end145 assert ival_QEJAN.asfreq('D', 'S') == ival_QEJAN_to_D_start146 assert ival_QEJAN.asfreq('D', 'E') == ival_QEJAN_to_D_end147 assert ival_QEJUN.asfreq('D', 'S') == ival_QEJUN_to_D_start148 assert ival_QEJUN.asfreq('D', 'E') == ival_QEJUN_to_D_end149 assert ival_Q.asfreq('Q') == ival_Q150 def test_conv_monthly(self):151 # frequency conversion tests: from Monthly Frequency152 ival_M = Period(freq='M', year=2007, month=1)153 ival_M_end_of_year = Period(freq='M', year=2007, month=12)154 ival_M_end_of_quarter = Period(freq='M', year=2007, month=3)155 ival_M_to_A = Period(freq='A', year=2007)156 ival_M_to_Q = Period(freq='Q', year=2007, quarter=1)157 ival_M_to_W_start = Period(freq='W', year=2007, month=1, day=1)158 ival_M_to_W_end = Period(freq='W', year=2007, month=1, day=31)159 ival_M_to_B_start = Period(freq='B', year=2007, month=1, day=1)160 ival_M_to_B_end = Period(freq='B', year=2007, month=1, day=31)161 ival_M_to_D_start = Period(freq='D', year=2007, month=1, day=1)162 ival_M_to_D_end = Period(freq='D', year=2007, month=1, day=31)163 ival_M_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)164 ival_M_to_H_end = Period(freq='H', year=2007, month=1, day=31, hour=23)165 ival_M_to_T_start = Period(freq='Min', year=2007, month=1, day=1,166 hour=0, minute=0)167 ival_M_to_T_end = Period(freq='Min', year=2007, month=1, day=31,168 hour=23, minute=59)169 ival_M_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,170 minute=0, second=0)171 ival_M_to_S_end = Period(freq='S', year=2007, month=1, day=31, hour=23,172 minute=59, second=59)173 assert ival_M.asfreq('A') == ival_M_to_A174 assert ival_M_end_of_year.asfreq('A') == ival_M_to_A175 assert ival_M.asfreq('Q') == ival_M_to_Q176 assert ival_M_end_of_quarter.asfreq('Q') == ival_M_to_Q177 assert ival_M.asfreq('W', 'S') == ival_M_to_W_start178 assert ival_M.asfreq('W', 'E') == ival_M_to_W_end179 assert ival_M.asfreq('B', 'S') == ival_M_to_B_start180 assert ival_M.asfreq('B', 'E') == ival_M_to_B_end181 assert ival_M.asfreq('D', 'S') == ival_M_to_D_start182 assert ival_M.asfreq('D', 'E') == ival_M_to_D_end183 assert ival_M.asfreq('H', 'S') == ival_M_to_H_start184 assert ival_M.asfreq('H', 'E') == ival_M_to_H_end185 assert ival_M.asfreq('Min', 'S') == ival_M_to_T_start186 assert ival_M.asfreq('Min', 'E') == ival_M_to_T_end187 assert ival_M.asfreq('S', 'S') == ival_M_to_S_start188 assert ival_M.asfreq('S', 'E') == ival_M_to_S_end189 assert ival_M.asfreq('M') == ival_M190 def test_conv_weekly(self):191 # frequency conversion tests: from Weekly Frequency192 ival_W = Period(freq='W', year=2007, month=1, day=1)193 ival_WSUN = Period(freq='W', year=2007, month=1, day=7)194 ival_WSAT = Period(freq='W-SAT', year=2007, month=1, day=6)195 ival_WFRI = Period(freq='W-FRI', year=2007, month=1, day=5)196 ival_WTHU = Period(freq='W-THU', year=2007, month=1, day=4)197 ival_WWED = Period(freq='W-WED', year=2007, month=1, day=3)198 ival_WTUE = Period(freq='W-TUE', year=2007, month=1, day=2)199 ival_WMON = Period(freq='W-MON', year=2007, month=1, day=1)200 ival_WSUN_to_D_start = Period(freq='D', year=2007, month=1, day=1)201 ival_WSUN_to_D_end = Period(freq='D', year=2007, month=1, day=7)202 ival_WSAT_to_D_start = Period(freq='D', year=2006, month=12, day=31)203 ival_WSAT_to_D_end = Period(freq='D', year=2007, month=1, day=6)204 ival_WFRI_to_D_start = Period(freq='D', year=2006, month=12, day=30)205 ival_WFRI_to_D_end = Period(freq='D', year=2007, month=1, day=5)206 ival_WTHU_to_D_start = Period(freq='D', year=2006, month=12, day=29)207 ival_WTHU_to_D_end = Period(freq='D', year=2007, month=1, day=4)208 ival_WWED_to_D_start = Period(freq='D', year=2006, month=12, day=28)209 ival_WWED_to_D_end = Period(freq='D', year=2007, month=1, day=3)210 ival_WTUE_to_D_start = Period(freq='D', year=2006, month=12, day=27)211 ival_WTUE_to_D_end = Period(freq='D', year=2007, month=1, day=2)212 ival_WMON_to_D_start = Period(freq='D', year=2006, month=12, day=26)213 ival_WMON_to_D_end = Period(freq='D', year=2007, month=1, day=1)214 ival_W_end_of_year = Period(freq='W', year=2007, month=12, day=31)215 ival_W_end_of_quarter = Period(freq='W', year=2007, month=3, day=31)216 ival_W_end_of_month = Period(freq='W', year=2007, month=1, day=31)217 ival_W_to_A = Period(freq='A', year=2007)218 ival_W_to_Q = Period(freq='Q', year=2007, quarter=1)219 ival_W_to_M = Period(freq='M', year=2007, month=1)220 if Period(freq='D', year=2007, month=12, day=31).weekday == 6:221 ival_W_to_A_end_of_year = Period(freq='A', year=2007)222 else:223 ival_W_to_A_end_of_year = Period(freq='A', year=2008)224 if Period(freq='D', year=2007, month=3, day=31).weekday == 6:225 ival_W_to_Q_end_of_quarter = Period(freq='Q', year=2007, quarter=1)226 else:227 ival_W_to_Q_end_of_quarter = Period(freq='Q', year=2007, quarter=2)228 if Period(freq='D', year=2007, month=1, day=31).weekday == 6:229 ival_W_to_M_end_of_month = Period(freq='M', year=2007, month=1)230 else:231 ival_W_to_M_end_of_month = Period(freq='M', year=2007, month=2)232 ival_W_to_B_start = Period(freq='B', year=2007, month=1, day=1)233 ival_W_to_B_end = Period(freq='B', year=2007, month=1, day=5)234 ival_W_to_D_start = Period(freq='D', year=2007, month=1, day=1)235 ival_W_to_D_end = Period(freq='D', year=2007, month=1, day=7)236 ival_W_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)237 ival_W_to_H_end = Period(freq='H', year=2007, month=1, day=7, hour=23)238 ival_W_to_T_start = Period(freq='Min', year=2007, month=1, day=1,239 hour=0, minute=0)240 ival_W_to_T_end = Period(freq='Min', year=2007, month=1, day=7,241 hour=23, minute=59)242 ival_W_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,243 minute=0, second=0)244 ival_W_to_S_end = Period(freq='S', year=2007, month=1, day=7, hour=23,245 minute=59, second=59)246 assert ival_W.asfreq('A') == ival_W_to_A247 assert ival_W_end_of_year.asfreq('A') == ival_W_to_A_end_of_year248 assert ival_W.asfreq('Q') == ival_W_to_Q249 assert ival_W_end_of_quarter.asfreq('Q') == ival_W_to_Q_end_of_quarter250 assert ival_W.asfreq('M') == ival_W_to_M251 assert ival_W_end_of_month.asfreq('M') == ival_W_to_M_end_of_month252 assert ival_W.asfreq('B', 'S') == ival_W_to_B_start253 assert ival_W.asfreq('B', 'E') == ival_W_to_B_end254 assert ival_W.asfreq('D', 'S') == ival_W_to_D_start255 assert ival_W.asfreq('D', 'E') == ival_W_to_D_end256 assert ival_WSUN.asfreq('D', 'S') == ival_WSUN_to_D_start257 assert ival_WSUN.asfreq('D', 'E') == ival_WSUN_to_D_end258 assert ival_WSAT.asfreq('D', 'S') == ival_WSAT_to_D_start259 assert ival_WSAT.asfreq('D', 'E') == ival_WSAT_to_D_end260 assert ival_WFRI.asfreq('D', 'S') == ival_WFRI_to_D_start261 assert ival_WFRI.asfreq('D', 'E') == ival_WFRI_to_D_end262 assert ival_WTHU.asfreq('D', 'S') == ival_WTHU_to_D_start263 assert ival_WTHU.asfreq('D', 'E') == ival_WTHU_to_D_end264 assert ival_WWED.asfreq('D', 'S') == ival_WWED_to_D_start265 assert ival_WWED.asfreq('D', 'E') == ival_WWED_to_D_end266 assert ival_WTUE.asfreq('D', 'S') == ival_WTUE_to_D_start267 assert ival_WTUE.asfreq('D', 'E') == ival_WTUE_to_D_end268 assert ival_WMON.asfreq('D', 'S') == ival_WMON_to_D_start269 assert ival_WMON.asfreq('D', 'E') == ival_WMON_to_D_end270 assert ival_W.asfreq('H', 'S') == ival_W_to_H_start271 assert ival_W.asfreq('H', 'E') == ival_W_to_H_end272 assert ival_W.asfreq('Min', 'S') == ival_W_to_T_start273 assert ival_W.asfreq('Min', 'E') == ival_W_to_T_end274 assert ival_W.asfreq('S', 'S') == ival_W_to_S_start275 assert ival_W.asfreq('S', 'E') == ival_W_to_S_end276 assert ival_W.asfreq('W') == ival_W277 msg = INVALID_FREQ_ERR_MSG278 with pytest.raises(ValueError, match=msg):279 ival_W.asfreq('WK')280 def test_conv_weekly_legacy(self):281 # frequency conversion tests: from Weekly Frequency282 msg = INVALID_FREQ_ERR_MSG283 with pytest.raises(ValueError, match=msg):284 Period(freq='WK', year=2007, month=1, day=1)285 with pytest.raises(ValueError, match=msg):286 Period(freq='WK-SAT', year=2007, month=1, day=6)287 with pytest.raises(ValueError, match=msg):288 Period(freq='WK-FRI', year=2007, month=1, day=5)289 with pytest.raises(ValueError, match=msg):290 Period(freq='WK-THU', year=2007, month=1, day=4)291 with pytest.raises(ValueError, match=msg):292 Period(freq='WK-WED', year=2007, month=1, day=3)293 with pytest.raises(ValueError, match=msg):294 Period(freq='WK-TUE', year=2007, month=1, day=2)295 with pytest.raises(ValueError, match=msg):296 Period(freq='WK-MON', year=2007, month=1, day=1)297 def test_conv_business(self):298 # frequency conversion tests: from Business Frequency"299 ival_B = Period(freq='B', year=2007, month=1, day=1)300 ival_B_end_of_year = Period(freq='B', year=2007, month=12, day=31)301 ival_B_end_of_quarter = Period(freq='B', year=2007, month=3, day=30)302 ival_B_end_of_month = Period(freq='B', year=2007, month=1, day=31)303 ival_B_end_of_week = Period(freq='B', year=2007, month=1, day=5)304 ival_B_to_A = Period(freq='A', year=2007)305 ival_B_to_Q = Period(freq='Q', year=2007, quarter=1)306 ival_B_to_M = Period(freq='M', year=2007, month=1)307 ival_B_to_W = Period(freq='W', year=2007, month=1, day=7)308 ival_B_to_D = Period(freq='D', year=2007, month=1, day=1)309 ival_B_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)310 ival_B_to_H_end = Period(freq='H', year=2007, month=1, day=1, hour=23)311 ival_B_to_T_start = Period(freq='Min', year=2007, month=1, day=1,312 hour=0, minute=0)313 ival_B_to_T_end = Period(freq='Min', year=2007, month=1, day=1,314 hour=23, minute=59)315 ival_B_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,316 minute=0, second=0)317 ival_B_to_S_end = Period(freq='S', year=2007, month=1, day=1, hour=23,318 minute=59, second=59)319 assert ival_B.asfreq('A') == ival_B_to_A320 assert ival_B_end_of_year.asfreq('A') == ival_B_to_A321 assert ival_B.asfreq('Q') == ival_B_to_Q322 assert ival_B_end_of_quarter.asfreq('Q') == ival_B_to_Q323 assert ival_B.asfreq('M') == ival_B_to_M324 assert ival_B_end_of_month.asfreq('M') == ival_B_to_M325 assert ival_B.asfreq('W') == ival_B_to_W326 assert ival_B_end_of_week.asfreq('W') == ival_B_to_W327 assert ival_B.asfreq('D') == ival_B_to_D328 assert ival_B.asfreq('H', 'S') == ival_B_to_H_start329 assert ival_B.asfreq('H', 'E') == ival_B_to_H_end330 assert ival_B.asfreq('Min', 'S') == ival_B_to_T_start331 assert ival_B.asfreq('Min', 'E') == ival_B_to_T_end332 assert ival_B.asfreq('S', 'S') == ival_B_to_S_start333 assert ival_B.asfreq('S', 'E') == ival_B_to_S_end334 assert ival_B.asfreq('B') == ival_B335 def test_conv_daily(self):336 # frequency conversion tests: from Business Frequency"337 ival_D = Period(freq='D', year=2007, month=1, day=1)338 ival_D_end_of_year = Period(freq='D', year=2007, month=12, day=31)339 ival_D_end_of_quarter = Period(freq='D', year=2007, month=3, day=31)340 ival_D_end_of_month = Period(freq='D', year=2007, month=1, day=31)341 ival_D_end_of_week = Period(freq='D', year=2007, month=1, day=7)342 ival_D_friday = Period(freq='D', year=2007, month=1, day=5)343 ival_D_saturday = Period(freq='D', year=2007, month=1, day=6)344 ival_D_sunday = Period(freq='D', year=2007, month=1, day=7)345 # TODO: unused?346 # ival_D_monday = Period(freq='D', year=2007, month=1, day=8)347 ival_B_friday = Period(freq='B', year=2007, month=1, day=5)348 ival_B_monday = Period(freq='B', year=2007, month=1, day=8)349 ival_D_to_A = Period(freq='A', year=2007)350 ival_Deoq_to_AJAN = Period(freq='A-JAN', year=2008)351 ival_Deoq_to_AJUN = Period(freq='A-JUN', year=2007)352 ival_Deoq_to_ADEC = Period(freq='A-DEC', year=2007)353 ival_D_to_QEJAN = Period(freq="Q-JAN", year=2007, quarter=4)354 ival_D_to_QEJUN = Period(freq="Q-JUN", year=2007, quarter=3)355 ival_D_to_QEDEC = Period(freq="Q-DEC", year=2007, quarter=1)356 ival_D_to_M = Period(freq='M', year=2007, month=1)357 ival_D_to_W = Period(freq='W', year=2007, month=1, day=7)358 ival_D_to_H_start = Period(freq='H', year=2007, month=1, day=1, hour=0)359 ival_D_to_H_end = Period(freq='H', year=2007, month=1, day=1, hour=23)360 ival_D_to_T_start = Period(freq='Min', year=2007, month=1, day=1,361 hour=0, minute=0)362 ival_D_to_T_end = Period(freq='Min', year=2007, month=1, day=1,363 hour=23, minute=59)364 ival_D_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,365 minute=0, second=0)366 ival_D_to_S_end = Period(freq='S', year=2007, month=1, day=1, hour=23,367 minute=59, second=59)368 assert ival_D.asfreq('A') == ival_D_to_A369 assert ival_D_end_of_quarter.asfreq('A-JAN') == ival_Deoq_to_AJAN370 assert ival_D_end_of_quarter.asfreq('A-JUN') == ival_Deoq_to_AJUN371 assert ival_D_end_of_quarter.asfreq('A-DEC') == ival_Deoq_to_ADEC372 assert ival_D_end_of_year.asfreq('A') == ival_D_to_A373 assert ival_D_end_of_quarter.asfreq('Q') == ival_D_to_QEDEC374 assert ival_D.asfreq("Q-JAN") == ival_D_to_QEJAN375 assert ival_D.asfreq("Q-JUN") == ival_D_to_QEJUN376 assert ival_D.asfreq("Q-DEC") == ival_D_to_QEDEC377 assert ival_D.asfreq('M') == ival_D_to_M378 assert ival_D_end_of_month.asfreq('M') == ival_D_to_M379 assert ival_D.asfreq('W') == ival_D_to_W380 assert ival_D_end_of_week.asfreq('W') == ival_D_to_W381 assert ival_D_friday.asfreq('B') == ival_B_friday382 assert ival_D_saturday.asfreq('B', 'S') == ival_B_friday383 assert ival_D_saturday.asfreq('B', 'E') == ival_B_monday384 assert ival_D_sunday.asfreq('B', 'S') == ival_B_friday385 assert ival_D_sunday.asfreq('B', 'E') == ival_B_monday386 assert ival_D.asfreq('H', 'S') == ival_D_to_H_start387 assert ival_D.asfreq('H', 'E') == ival_D_to_H_end388 assert ival_D.asfreq('Min', 'S') == ival_D_to_T_start389 assert ival_D.asfreq('Min', 'E') == ival_D_to_T_end390 assert ival_D.asfreq('S', 'S') == ival_D_to_S_start391 assert ival_D.asfreq('S', 'E') == ival_D_to_S_end392 assert ival_D.asfreq('D') == ival_D393 def test_conv_hourly(self):394 # frequency conversion tests: from Hourly Frequency"395 ival_H = Period(freq='H', year=2007, month=1, day=1, hour=0)396 ival_H_end_of_year = Period(freq='H', year=2007, month=12, day=31,397 hour=23)398 ival_H_end_of_quarter = Period(freq='H', year=2007, month=3, day=31,399 hour=23)400 ival_H_end_of_month = Period(freq='H', year=2007, month=1, day=31,401 hour=23)402 ival_H_end_of_week = Period(freq='H', year=2007, month=1, day=7,403 hour=23)404 ival_H_end_of_day = Period(freq='H', year=2007, month=1, day=1,405 hour=23)406 ival_H_end_of_bus = Period(freq='H', year=2007, month=1, day=1,407 hour=23)408 ival_H_to_A = Period(freq='A', year=2007)409 ival_H_to_Q = Period(freq='Q', year=2007, quarter=1)410 ival_H_to_M = Period(freq='M', year=2007, month=1)411 ival_H_to_W = Period(freq='W', year=2007, month=1, day=7)412 ival_H_to_D = Period(freq='D', year=2007, month=1, day=1)413 ival_H_to_B = Period(freq='B', year=2007, month=1, day=1)414 ival_H_to_T_start = Period(freq='Min', year=2007, month=1, day=1,415 hour=0, minute=0)416 ival_H_to_T_end = Period(freq='Min', year=2007, month=1, day=1, hour=0,417 minute=59)418 ival_H_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,419 minute=0, second=0)420 ival_H_to_S_end = Period(freq='S', year=2007, month=1, day=1, hour=0,421 minute=59, second=59)422 assert ival_H.asfreq('A') == ival_H_to_A423 assert ival_H_end_of_year.asfreq('A') == ival_H_to_A424 assert ival_H.asfreq('Q') == ival_H_to_Q425 assert ival_H_end_of_quarter.asfreq('Q') == ival_H_to_Q426 assert ival_H.asfreq('M') == ival_H_to_M427 assert ival_H_end_of_month.asfreq('M') == ival_H_to_M428 assert ival_H.asfreq('W') == ival_H_to_W429 assert ival_H_end_of_week.asfreq('W') == ival_H_to_W430 assert ival_H.asfreq('D') == ival_H_to_D431 assert ival_H_end_of_day.asfreq('D') == ival_H_to_D432 assert ival_H.asfreq('B') == ival_H_to_B433 assert ival_H_end_of_bus.asfreq('B') == ival_H_to_B434 assert ival_H.asfreq('Min', 'S') == ival_H_to_T_start435 assert ival_H.asfreq('Min', 'E') == ival_H_to_T_end436 assert ival_H.asfreq('S', 'S') == ival_H_to_S_start437 assert ival_H.asfreq('S', 'E') == ival_H_to_S_end438 assert ival_H.asfreq('H') == ival_H439 def test_conv_minutely(self):440 # frequency conversion tests: from Minutely Frequency"441 ival_T = Period(freq='Min', year=2007, month=1, day=1, hour=0,442 minute=0)443 ival_T_end_of_year = Period(freq='Min', year=2007, month=12, day=31,444 hour=23, minute=59)445 ival_T_end_of_quarter = Period(freq='Min', year=2007, month=3, day=31,446 hour=23, minute=59)447 ival_T_end_of_month = Period(freq='Min', year=2007, month=1, day=31,448 hour=23, minute=59)449 ival_T_end_of_week = Period(freq='Min', year=2007, month=1, day=7,450 hour=23, minute=59)451 ival_T_end_of_day = Period(freq='Min', year=2007, month=1, day=1,452 hour=23, minute=59)453 ival_T_end_of_bus = Period(freq='Min', year=2007, month=1, day=1,454 hour=23, minute=59)455 ival_T_end_of_hour = Period(freq='Min', year=2007, month=1, day=1,456 hour=0, minute=59)457 ival_T_to_A = Period(freq='A', year=2007)458 ival_T_to_Q = Period(freq='Q', year=2007, quarter=1)459 ival_T_to_M = Period(freq='M', year=2007, month=1)460 ival_T_to_W = Period(freq='W', year=2007, month=1, day=7)461 ival_T_to_D = Period(freq='D', year=2007, month=1, day=1)462 ival_T_to_B = Period(freq='B', year=2007, month=1, day=1)463 ival_T_to_H = Period(freq='H', year=2007, month=1, day=1, hour=0)464 ival_T_to_S_start = Period(freq='S', year=2007, month=1, day=1, hour=0,465 minute=0, second=0)466 ival_T_to_S_end = Period(freq='S', year=2007, month=1, day=1, hour=0,467 minute=0, second=59)468 assert ival_T.asfreq('A') == ival_T_to_A469 assert ival_T_end_of_year.asfreq('A') == ival_T_to_A470 assert ival_T.asfreq('Q') == ival_T_to_Q471 assert ival_T_end_of_quarter.asfreq('Q') == ival_T_to_Q472 assert ival_T.asfreq('M') == ival_T_to_M473 assert ival_T_end_of_month.asfreq('M') == ival_T_to_M474 assert ival_T.asfreq('W') == ival_T_to_W475 assert ival_T_end_of_week.asfreq('W') == ival_T_to_W476 assert ival_T.asfreq('D') == ival_T_to_D477 assert ival_T_end_of_day.asfreq('D') == ival_T_to_D478 assert ival_T.asfreq('B') == ival_T_to_B479 assert ival_T_end_of_bus.asfreq('B') == ival_T_to_B480 assert ival_T.asfreq('H') == ival_T_to_H481 assert ival_T_end_of_hour.asfreq('H') == ival_T_to_H482 assert ival_T.asfreq('S', 'S') == ival_T_to_S_start483 assert ival_T.asfreq('S', 'E') == ival_T_to_S_end484 assert ival_T.asfreq('Min') == ival_T485 def test_conv_secondly(self):486 # frequency conversion tests: from Secondly Frequency"487 ival_S = Period(freq='S', year=2007, month=1, day=1, hour=0, minute=0,488 second=0)489 ival_S_end_of_year = Period(freq='S', year=2007, month=12, day=31,490 hour=23, minute=59, second=59)491 ival_S_end_of_quarter = Period(freq='S', year=2007, month=3, day=31,492 hour=23, minute=59, second=59)493 ival_S_end_of_month = Period(freq='S', year=2007, month=1, day=31,494 hour=23, minute=59, second=59)495 ival_S_end_of_week = Period(freq='S', year=2007, month=1, day=7,496 hour=23, minute=59, second=59)497 ival_S_end_of_day = Period(freq='S', year=2007, month=1, day=1,498 hour=23, minute=59, second=59)499 ival_S_end_of_bus = Period(freq='S', year=2007, month=1, day=1,500 hour=23, minute=59, second=59)501 ival_S_end_of_hour = Period(freq='S', year=2007, month=1, day=1,502 hour=0, minute=59, second=59)503 ival_S_end_of_minute = Period(freq='S', year=2007, month=1, day=1,504 hour=0, minute=0, second=59)505 ival_S_to_A = Period(freq='A', year=2007)506 ival_S_to_Q = Period(freq='Q', year=2007, quarter=1)507 ival_S_to_M = Period(freq='M', year=2007, month=1)508 ival_S_to_W = Period(freq='W', year=2007, month=1, day=7)509 ival_S_to_D = Period(freq='D', year=2007, month=1, day=1)510 ival_S_to_B = Period(freq='B', year=2007, month=1, day=1)511 ival_S_to_H = Period(freq='H', year=2007, month=1, day=1, hour=0)512 ival_S_to_T = Period(freq='Min', year=2007, month=1, day=1, hour=0,513 minute=0)514 assert ival_S.asfreq('A') == ival_S_to_A515 assert ival_S_end_of_year.asfreq('A') == ival_S_to_A516 assert ival_S.asfreq('Q') == ival_S_to_Q517 assert ival_S_end_of_quarter.asfreq('Q') == ival_S_to_Q518 assert ival_S.asfreq('M') == ival_S_to_M519 assert ival_S_end_of_month.asfreq('M') == ival_S_to_M520 assert ival_S.asfreq('W') == ival_S_to_W521 assert ival_S_end_of_week.asfreq('W') == ival_S_to_W522 assert ival_S.asfreq('D') == ival_S_to_D523 assert ival_S_end_of_day.asfreq('D') == ival_S_to_D524 assert ival_S.asfreq('B') == ival_S_to_B525 assert ival_S_end_of_bus.asfreq('B') == ival_S_to_B526 assert ival_S.asfreq('H') == ival_S_to_H527 assert ival_S_end_of_hour.asfreq('H') == ival_S_to_H528 assert ival_S.asfreq('Min') == ival_S_to_T529 assert ival_S_end_of_minute.asfreq('Min') == ival_S_to_T530 assert ival_S.asfreq('S') == ival_S531 def test_asfreq_mult(self):532 # normal freq to mult freq533 p = Period(freq='A', year=2007)534 # ordinal will not change535 for freq in ['3A', offsets.YearEnd(3)]:536 result = p.asfreq(freq)537 expected = Period('2007', freq='3A')538 assert result == expected539 assert result.ordinal == expected.ordinal540 assert result.freq == expected.freq541 # ordinal will not change542 for freq in ['3A', offsets.YearEnd(3)]:543 result = p.asfreq(freq, how='S')544 expected = Period('2007', freq='3A')545 assert result == expected546 assert result.ordinal == expected.ordinal547 assert result.freq == expected.freq548 # mult freq to normal freq549 p = Period(freq='3A', year=2007)550 # ordinal will change because how=E is the default551 for freq in ['A', offsets.YearEnd()]:552 result = p.asfreq(freq)553 expected = Period('2009', freq='A')554 assert result == expected555 assert result.ordinal == expected.ordinal556 assert result.freq == expected.freq557 # ordinal will not change558 for freq in ['A', offsets.YearEnd()]:559 result = p.asfreq(freq, how='S')560 expected = Period('2007', freq='A')561 assert result == expected562 assert result.ordinal == expected.ordinal563 assert result.freq == expected.freq564 p = Period(freq='A', year=2007)565 for freq in ['2M', offsets.MonthEnd(2)]:566 result = p.asfreq(freq)567 expected = Period('2007-12', freq='2M')568 assert result == expected569 assert result.ordinal == expected.ordinal570 assert result.freq == expected.freq571 for freq in ['2M', offsets.MonthEnd(2)]:572 result = p.asfreq(freq, how='S')573 expected = Period('2007-01', freq='2M')574 assert result == expected575 assert result.ordinal == expected.ordinal576 assert result.freq == expected.freq577 p = Period(freq='3A', year=2007)578 for freq in ['2M', offsets.MonthEnd(2)]:579 result = p.asfreq(freq)580 expected = Period('2009-12', freq='2M')581 assert result == expected582 assert result.ordinal == expected.ordinal583 assert result.freq == expected.freq584 for freq in ['2M', offsets.MonthEnd(2)]:585 result = p.asfreq(freq, how='S')586 expected = Period('2007-01', freq='2M')587 assert result == expected588 assert result.ordinal == expected.ordinal589 assert result.freq == expected.freq590 def test_asfreq_combined(self):591 # normal freq to combined freq592 p = Period('2007', freq='H')593 # ordinal will not change594 expected = Period('2007', freq='25H')595 for freq, how in zip(['1D1H', '1H1D'], ['E', 'S']):596 result = p.asfreq(freq, how=how)597 assert result == expected598 assert result.ordinal == expected.ordinal599 assert result.freq == expected.freq600 # combined freq to normal freq601 p1 = Period(freq='1D1H', year=2007)602 p2 = Period(freq='1H1D', year=2007)603 # ordinal will change because how=E is the default604 result1 = p1.asfreq('H')605 result2 = p2.asfreq('H')606 expected = Period('2007-01-02', freq='H')607 assert result1 == expected608 assert result1.ordinal == expected.ordinal609 assert result1.freq == expected.freq610 assert result2 == expected611 assert result2.ordinal == expected.ordinal612 assert result2.freq == expected.freq613 # ordinal will not change614 result1 = p1.asfreq('H', how='S')615 result2 = p2.asfreq('H', how='S')616 expected = Period('2007-01-01', freq='H')617 assert result1 == expected618 assert result1.ordinal == expected.ordinal619 assert result1.freq == expected.freq620 assert result2 == expected621 assert result2.ordinal == expected.ordinal622 assert result2.freq == expected.freq623 def test_asfreq_MS(self):624 initial = Period("2013")625 assert initial.asfreq(freq="M", how="S") == Period('2013-01', 'M')626 msg = INVALID_FREQ_ERR_MSG627 with pytest.raises(ValueError, match=msg):628 initial.asfreq(freq="MS", how="S")629 with pytest.raises(ValueError, match=msg):630 Period('2013-01', 'MS')...

Full Screen

Full Screen

__main__pydevd_gen_debug_adapter_protocol.py

Source:__main__pydevd_gen_debug_adapter_protocol.py Github

copy

Full Screen

1'''2Run this module to regenerate the `pydevd_schema.py` file.34Note that it'll generate it based on the current debugProtocol.json. Erase it and rerun5to download the latest version.6'''789def is_variable_to_translate(cls_name, var_name):10 if var_name in ('variablesReference', 'frameId', 'threadId'):11 return True1213 if cls_name == 'StackFrame' and var_name == 'id':14 # It's frameId everywhere except on StackFrame.15 return True1617 if cls_name == 'Thread' and var_name == 'id':18 # It's threadId everywhere except on Thread.19 return True2021 return False222324def _get_noqa_for_var(prop_name):25 return ' # noqa (assign to builtin)' if prop_name in ('type', 'format', 'id', 'hex', 'breakpoint', 'filter') else ''262728class _OrderedSet(object):29 # Not a good ordered set (just something to be small without adding any deps)3031 def __init__(self, initial_contents=None):32 self._contents = []33 self._contents_as_set = set()34 if initial_contents is not None:35 for x in initial_contents:36 self.add(x)3738 def add(self, x):39 if x not in self._contents_as_set:40 self._contents_as_set.add(x)41 self._contents.append(x)4243 def discard(self, x):44 if x in self._contents_as_set:45 self._contents_as_set.remove(x)46 self._contents.remove(x)4748 def copy(self):49 return _OrderedSet(self._contents)5051 def update(self, contents):52 for x in contents:53 self.add(x)5455 def __iter__(self):56 return iter(self._contents)5758 def __contains__(self, item):59 return item in self._contents_as_set6061 def __len__(self):62 return len(self._contents)6364 def set_repr(self):65 if len(self) == 0:66 return 'set()'6768 lst = [repr(x) for x in self]69 return 'set([' + ', '.join(lst) + '])'707172class Ref(object):7374 def __init__(self, ref, ref_data):75 self.ref = ref76 self.ref_data = ref_data7778 def __str__(self):79 return self.ref808182def load_schema_data():83 import os.path84 import json8586 json_file = os.path.join(os.path.dirname(__file__), 'debugProtocol.json')87 if not os.path.exists(json_file):88 import requests89 req = requests.get('https://raw.githubusercontent.com/microsoft/debug-adapter-protocol/gh-pages/debugAdapterProtocol.json')90 assert req.status_code == 20091 with open(json_file, 'wb') as stream:92 stream.write(req.content)9394 with open(json_file, 'rb') as json_contents:95 json_schema_data = json.loads(json_contents.read())96 return json_schema_data979899def load_custom_schema_data():100 import os.path101 import json102103 json_file = os.path.join(os.path.dirname(__file__), 'debugProtocolCustom.json')104105 with open(json_file, 'rb') as json_contents:106 json_schema_data = json.loads(json_contents.read())107 return json_schema_data108109110def create_classes_to_generate_structure(json_schema_data):111 definitions = json_schema_data['definitions']112113 class_to_generatees = {}114115 for name, definition in definitions.items():116 all_of = definition.get('allOf')117 description = definition.get('description')118 is_enum = definition.get('type') == 'string' and 'enum' in definition119 enum_values = None120 if is_enum:121 enum_values = definition['enum']122 properties = {}123 properties.update(definition.get('properties', {}))124 required = _OrderedSet(definition.get('required', _OrderedSet()))125 base_definitions = []126127 if all_of is not None:128 for definition in all_of:129 ref = definition.get('$ref')130 if ref is not None:131 assert ref.startswith('#/definitions/')132 ref = ref[len('#/definitions/'):]133 base_definitions.append(ref)134 else:135 if not description:136 description = definition.get('description')137 properties.update(definition.get('properties', {}))138 required.update(_OrderedSet(definition.get('required', _OrderedSet())))139140 if isinstance(description, (list, tuple)):141 description = '\n'.join(description)142143 if name == 'ModulesRequest': # Hack to accept modules request without arguments (ptvsd: 2050).144 required.discard('arguments')145 class_to_generatees[name] = dict(146 name=name,147 properties=properties,148 base_definitions=base_definitions,149 description=description,150 required=required,151 is_enum=is_enum,152 enum_values=enum_values153 )154 return class_to_generatees155156157def collect_bases(curr_class, classes_to_generate, memo=None):158 ret = []159 if memo is None:160 memo = {}161162 base_definitions = curr_class['base_definitions']163 for base_definition in base_definitions:164 if base_definition not in memo:165 ret.append(base_definition)166 ret.extend(collect_bases(classes_to_generate[base_definition], classes_to_generate, memo))167168 return ret169170171def fill_properties_and_required_from_base(classes_to_generate):172 # Now, resolve properties based on refs173 for class_to_generate in classes_to_generate.values():174 dct = {}175 s = _OrderedSet()176177 for base_definition in reversed(collect_bases(class_to_generate, classes_to_generate)):178 # Note: go from base to current so that the initial order of the properties has that179 # same order.180 dct.update(classes_to_generate[base_definition].get('properties', {}))181 s.update(classes_to_generate[base_definition].get('required', _OrderedSet()))182183 dct.update(class_to_generate['properties'])184 class_to_generate['properties'] = dct185186 s.update(class_to_generate['required'])187 class_to_generate['required'] = s188189 return class_to_generate190191192def update_class_to_generate_description(class_to_generate):193 import textwrap194 description = class_to_generate['description']195 lines = []196 for line in description.splitlines():197 wrapped = textwrap.wrap(line.strip(), 100)198 lines.extend(wrapped)199 lines.append('')200201 while lines and lines[-1] == '':202 lines = lines[:-1]203204 class_to_generate['description'] = ' ' + ('\n '.join(lines))205206207def update_class_to_generate_type(classes_to_generate, class_to_generate):208 properties = class_to_generate.get('properties')209 for _prop_name, prop_val in properties.items():210 prop_type = prop_val.get('type', '')211 if not prop_type:212 prop_type = prop_val.pop('$ref', '')213 if prop_type:214 assert prop_type.startswith('#/definitions/')215 prop_type = prop_type[len('#/definitions/'):]216 prop_val['type'] = Ref(prop_type, classes_to_generate[prop_type])217218219def update_class_to_generate_register_dec(classes_to_generate, class_to_generate):220 # Default221 class_to_generate['register_request'] = ''222 class_to_generate['register_dec'] = '@register'223224 properties = class_to_generate.get('properties')225 enum_type = properties.get('type', {}).get('enum')226 command = None227 event = None228 if enum_type and len(enum_type) == 1 and next(iter(enum_type)) in ("request", "response", "event"):229 msg_type = next(iter(enum_type))230 if msg_type == 'response':231 # The actual command is typed in the request232 response_name = class_to_generate['name']233 request_name = response_name[:-len('Response')] + 'Request'234 if request_name in classes_to_generate:235 command = classes_to_generate[request_name]['properties'].get('command')236 else:237 if response_name == 'ErrorResponse':238 command = {'enum': ['error']}239 else:240 raise AssertionError('Unhandled: %s' % (response_name,))241242 elif msg_type == 'request':243 command = properties.get('command')244245 elif msg_type == 'event':246 command = properties.get('event')247248 else:249 raise AssertionError('Unexpected condition.')250251 if command:252 enum = command.get('enum')253 if enum and len(enum) == 1:254 class_to_generate['register_request'] = '@register_%s(%r)\n' % (msg_type, enum[0])255256257def extract_prop_name_and_prop(class_to_generate):258 properties = class_to_generate.get('properties')259 required = _OrderedSet(class_to_generate.get('required', _OrderedSet()))260261 # Sort so that required come first262 prop_name_and_prop = list(properties.items())263264 def compute_sort_key(x):265 key = x[0]266 if key in required:267 if key == 'seq':268 return 0.5 # seq when required is after the other required keys (to have a default of -1).269 return 0270 return 1271272 prop_name_and_prop.sort(key=compute_sort_key)273274 return prop_name_and_prop275276277def update_class_to_generate_to_json(class_to_generate):278 required = _OrderedSet(class_to_generate.get('required', _OrderedSet()))279 prop_name_and_prop = extract_prop_name_and_prop(class_to_generate)280281 to_dict_body = ['def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused)']282283 translate_prop_names = []284 for prop_name, prop in prop_name_and_prop:285 if is_variable_to_translate(class_to_generate['name'], prop_name):286 translate_prop_names.append(prop_name)287288 for prop_name, prop in prop_name_and_prop:289 namespace = dict(prop_name=prop_name, noqa=_get_noqa_for_var(prop_name))290 to_dict_body.append(' %(prop_name)s = self.%(prop_name)s%(noqa)s' % namespace)291292 if prop.get('type') == 'array':293 to_dict_body.append(' if %(prop_name)s and hasattr(%(prop_name)s[0], "to_dict"):' % namespace)294 to_dict_body.append(' %(prop_name)s = [x.to_dict() for x in %(prop_name)s]' % namespace)295296 if translate_prop_names:297 to_dict_body.append(' if update_ids_to_dap:')298 for prop_name in translate_prop_names:299 namespace = dict(prop_name=prop_name, noqa=_get_noqa_for_var(prop_name))300 to_dict_body.append(' if %(prop_name)s is not None:' % namespace)301 to_dict_body.append(' %(prop_name)s = self._translate_id_to_dap(%(prop_name)s)%(noqa)s' % namespace)302303 if not translate_prop_names:304 update_dict_ids_from_dap_body = []305 else:306 update_dict_ids_from_dap_body = ['', '', '@classmethod', 'def update_dict_ids_from_dap(cls, dct):']307 for prop_name in translate_prop_names:308 namespace = dict(prop_name=prop_name)309 update_dict_ids_from_dap_body.append(' if %(prop_name)r in dct:' % namespace)310 update_dict_ids_from_dap_body.append(' dct[%(prop_name)r] = cls._translate_id_from_dap(dct[%(prop_name)r])' % namespace)311 update_dict_ids_from_dap_body.append(' return dct')312313 class_to_generate['update_dict_ids_from_dap'] = _indent_lines('\n'.join(update_dict_ids_from_dap_body))314315 to_dict_body.append(' dct = {')316 first_not_required = False317318 for prop_name, prop in prop_name_and_prop:319 use_to_dict = prop['type'].__class__ == Ref and not prop['type'].ref_data.get('is_enum', False)320 is_array = prop['type'] == 'array'321 ref_array_cls_name = ''322 if is_array:323 ref = prop['items'].get('$ref')324 if ref is not None:325 ref_array_cls_name = ref.split('/')[-1]326327 namespace = dict(prop_name=prop_name, ref_array_cls_name=ref_array_cls_name)328 if prop_name in required:329 if use_to_dict:330 to_dict_body.append(' %(prop_name)r: %(prop_name)s.to_dict(update_ids_to_dap=update_ids_to_dap),' % namespace)331 else:332 if ref_array_cls_name:333 to_dict_body.append(' %(prop_name)r: [%(ref_array_cls_name)s.update_dict_ids_to_dap(o) for o in %(prop_name)s] if (update_ids_to_dap and %(prop_name)s) else %(prop_name)s,' % namespace)334 else:335 to_dict_body.append(' %(prop_name)r: %(prop_name)s,' % namespace)336 else:337 if not first_not_required:338 first_not_required = True339 to_dict_body.append(' }')340341 to_dict_body.append(' if %(prop_name)s is not None:' % namespace)342 if use_to_dict:343 to_dict_body.append(' dct[%(prop_name)r] = %(prop_name)s.to_dict(update_ids_to_dap=update_ids_to_dap)' % namespace)344 else:345 if ref_array_cls_name:346 to_dict_body.append(' dct[%(prop_name)r] = [%(ref_array_cls_name)s.update_dict_ids_to_dap(o) for o in %(prop_name)s] if (update_ids_to_dap and %(prop_name)s) else %(prop_name)s' % namespace)347 else:348 to_dict_body.append(' dct[%(prop_name)r] = %(prop_name)s' % namespace)349350 if not first_not_required:351 first_not_required = True352 to_dict_body.append(' }')353354 to_dict_body.append(' dct.update(self.kwargs)')355 to_dict_body.append(' return dct')356357 class_to_generate['to_dict'] = _indent_lines('\n'.join(to_dict_body))358359 if not translate_prop_names:360 update_dict_ids_to_dap_body = []361 else:362 update_dict_ids_to_dap_body = ['', '', '@classmethod', 'def update_dict_ids_to_dap(cls, dct):']363 for prop_name in translate_prop_names:364 namespace = dict(prop_name=prop_name)365 update_dict_ids_to_dap_body.append(' if %(prop_name)r in dct:' % namespace)366 update_dict_ids_to_dap_body.append(' dct[%(prop_name)r] = cls._translate_id_to_dap(dct[%(prop_name)r])' % namespace)367 update_dict_ids_to_dap_body.append(' return dct')368369 class_to_generate['update_dict_ids_to_dap'] = _indent_lines('\n'.join(update_dict_ids_to_dap_body))370371372def update_class_to_generate_init(class_to_generate):373 args = []374 init_body = []375 docstring = []376377 required = _OrderedSet(class_to_generate.get('required', _OrderedSet()))378 prop_name_and_prop = extract_prop_name_and_prop(class_to_generate)379380 translate_prop_names = []381 for prop_name, prop in prop_name_and_prop:382 if is_variable_to_translate(class_to_generate['name'], prop_name):383 translate_prop_names.append(prop_name)384385 enum = prop.get('enum')386 if enum and len(enum) == 1:387 init_body.append(' self.%(prop_name)s = %(enum)r' % dict(prop_name=prop_name, enum=next(iter(enum))))388 else:389 if prop_name in required:390 if prop_name == 'seq':391 args.append(prop_name + '=-1')392 else:393 args.append(prop_name)394 else:395 args.append(prop_name + '=None')396397 if prop['type'].__class__ == Ref:398 ref = prop['type']399 ref_data = ref.ref_data400 if ref_data.get('is_enum', False):401 init_body.append(' if %s is not None:' % (prop_name,))402 init_body.append(' assert %s in %s.VALID_VALUES' % (prop_name, str(ref)))403 init_body.append(' self.%(prop_name)s = %(prop_name)s' % dict(404 prop_name=prop_name))405 else:406 namespace = dict(407 prop_name=prop_name,408 ref_name=str(ref)409 )410 init_body.append(' if %(prop_name)s is None:' % namespace)411 init_body.append(' self.%(prop_name)s = %(ref_name)s()' % namespace)412 init_body.append(' else:')413 init_body.append(' self.%(prop_name)s = %(ref_name)s(update_ids_from_dap=update_ids_from_dap, **%(prop_name)s) if %(prop_name)s.__class__ != %(ref_name)s else %(prop_name)s' % namespace414 )415416 else:417 init_body.append(' self.%(prop_name)s = %(prop_name)s' % dict(prop_name=prop_name))418419 if prop['type'] == 'array':420 ref = prop['items'].get('$ref')421 if ref is not None:422 ref_array_cls_name = ref.split('/')[-1]423 init_body.append(' if update_ids_from_dap and self.%(prop_name)s:' % dict(prop_name=prop_name))424 init_body.append(' for o in self.%(prop_name)s:' % dict(prop_name=prop_name))425 init_body.append(' %(ref_array_cls_name)s.update_dict_ids_from_dap(o)' % dict(ref_array_cls_name=ref_array_cls_name))426427 prop_type = prop['type']428 prop_description = prop.get('description', '')429430 if isinstance(prop_description, (list, tuple)):431 prop_description = '\n '.join(prop_description)432433 docstring.append(':param %(prop_type)s %(prop_name)s: %(prop_description)s' % dict(434 prop_type=prop_type, prop_name=prop_name, prop_description=prop_description))435436 if translate_prop_names:437 init_body.append(' if update_ids_from_dap:')438 for prop_name in translate_prop_names:439 init_body.append(' self.%(prop_name)s = self._translate_id_from_dap(self.%(prop_name)s)' % dict(prop_name=prop_name))440441 docstring = _indent_lines('\n'.join(docstring))442 init_body = '\n'.join(init_body)443444 # Actually bundle the whole __init__ from the parts.445 args = ', '.join(args)446 if args:447 args = ', ' + args448449 # Note: added kwargs because some messages are expected to be extended by the user (so, we'll actually450 # make all extendable so that we don't have to worry about which ones -- we loose a little on typing,451 # but may be better than doing a allow list based on something only pointed out in the documentation).452 class_to_generate['init'] = '''def __init__(self%(args)s, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused)453 """454%(docstring)s455 """456%(init_body)s457 self.kwargs = kwargs458''' % dict(args=args, init_body=init_body, docstring=docstring)459460 class_to_generate['init'] = _indent_lines(class_to_generate['init'])461462463def update_class_to_generate_props(class_to_generate):464 import json465466 def default(o):467 if isinstance(o, Ref):468 return o.ref469 raise AssertionError('Unhandled: %s' % (o,))470471 properties = class_to_generate['properties']472 class_to_generate['props'] = ' __props__ = %s' % _indent_lines(473 json.dumps(properties, indent=4, default=default)).strip()474475476def update_class_to_generate_refs(class_to_generate):477 properties = class_to_generate['properties']478 class_to_generate['refs'] = ' __refs__ = %s' % _OrderedSet(479 key for (key, val) in properties.items() if val['type'].__class__ == Ref).set_repr()480481482def update_class_to_generate_enums(class_to_generate):483 class_to_generate['enums'] = ''484 if class_to_generate.get('is_enum', False):485 enums = ''486 for enum in class_to_generate['enum_values']:487 enums += ' %s = %r\n' % (enum.upper(), enum)488 enums += '\n'489 enums += ' VALID_VALUES = %s\n\n' % _OrderedSet(class_to_generate['enum_values']).set_repr()490 class_to_generate['enums'] = enums491492493def update_class_to_generate_objects(classes_to_generate, class_to_generate):494 properties = class_to_generate['properties']495 for key, val in properties.items():496 if val['type'] == 'object':497 create_new = val.copy()498 create_new.update({499 'name': '%s%s' % (class_to_generate['name'], key.title()),500 'description': ' "%s" of %s' % (key, class_to_generate['name'])501 })502 if 'properties' not in create_new:503 create_new['properties'] = {}504505 assert create_new['name'] not in classes_to_generate506 classes_to_generate[create_new['name']] = create_new507508 update_class_to_generate_type(classes_to_generate, create_new)509 update_class_to_generate_props(create_new)510511 # Update nested object types512 update_class_to_generate_objects(classes_to_generate, create_new)513514 val['type'] = Ref(create_new['name'], classes_to_generate[create_new['name']])515 val.pop('properties', None)516517518def gen_debugger_protocol():519 import os.path520 import sys521522 if sys.version_info[:2] < (3, 6):523 raise AssertionError('Must be run with Python 3.6 onwards (to keep dict order).')524525 classes_to_generate = create_classes_to_generate_structure(load_schema_data())526 classes_to_generate.update(create_classes_to_generate_structure(load_custom_schema_data()))527528 class_to_generate = fill_properties_and_required_from_base(classes_to_generate)529530 for class_to_generate in list(classes_to_generate.values()):531 update_class_to_generate_description(class_to_generate)532 update_class_to_generate_type(classes_to_generate, class_to_generate)533 update_class_to_generate_props(class_to_generate)534 update_class_to_generate_objects(classes_to_generate, class_to_generate)535536 for class_to_generate in classes_to_generate.values():537 update_class_to_generate_refs(class_to_generate)538 update_class_to_generate_init(class_to_generate)539 update_class_to_generate_enums(class_to_generate)540 update_class_to_generate_to_json(class_to_generate)541 update_class_to_generate_register_dec(classes_to_generate, class_to_generate)542543 class_template = '''544%(register_request)s%(register_dec)s545class %(name)s(BaseSchema):546 """547%(description)s548549 Note: automatically generated code. Do not edit manually.550 """551552%(enums)s%(props)s553%(refs)s554555 __slots__ = list(__props__.keys()) + ['kwargs']556557%(init)s%(update_dict_ids_from_dap)s558559%(to_dict)s%(update_dict_ids_to_dap)s560'''561562 contents = []563 contents.append('# coding: utf-8')564 contents.append('# Automatically generated code.')565 contents.append('# Do not edit manually.')566 contents.append('# Generated by running: %s' % os.path.basename(__file__))567 contents.append('from .pydevd_base_schema import BaseSchema, register, register_request, register_response, register_event')568 contents.append('')569 for class_to_generate in classes_to_generate.values():570 contents.append(class_template % class_to_generate)571572 parent_dir = os.path.dirname(__file__)573 schema = os.path.join(parent_dir, 'pydevd_schema.py')574 with open(schema, 'w', encoding='utf-8') as stream:575 stream.write('\n'.join(contents))576577578def _indent_lines(lines, indent=' '):579 out_lines = []580 for line in lines.splitlines(keepends=True):581 out_lines.append(indent + line)582583 return ''.join(out_lines)584585586if __name__ == '__main__':587 ...

Full Screen

Full Screen

number-tostring.js

Source:number-tostring.js Github

copy

Full Screen

1// Copyright 2008 the V8 project authors. All rights reserved.2// Redistribution and use in source and binary forms, with or without3// modification, are permitted provided that the following conditions are4// met:5//6// * Redistributions of source code must retain the above copyright7// notice, this list of conditions and the following disclaimer.8// * Redistributions in binary form must reproduce the above9// copyright notice, this list of conditions and the following10// disclaimer in the documentation and/or other materials provided11// with the distribution.12// * Neither the name of Google Inc. nor the names of its13// contributors may be used to endorse or promote products derived14// from this software without specific prior written permission.15//16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27// ----------------------------------------------------------------------28// toString29assertEquals("NaN", (NaN).toString());30assertEquals("Infinity", (1/0).toString());31assertEquals("-Infinity", (-1/0).toString());32assertEquals("0", (0).toString());33assertEquals("9", (9).toString());34assertEquals("90", (90).toString());35assertEquals("90.12", (90.12).toString());36assertEquals("0.1", (0.1).toString());37assertEquals("0.01", (0.01).toString());38assertEquals("0.0123", (0.0123).toString());39assertEquals("111111111111111110000", (111111111111111111111).toString());40assertEquals("1.1111111111111111e+21", (1111111111111111111111).toString());41assertEquals("1.1111111111111111e+22", (11111111111111111111111).toString());42assertEquals("0.00001", (0.00001).toString());43assertEquals("0.000001", (0.000001).toString());44assertEquals("1e-7", (0.0000001).toString());45assertEquals("1.2e-7", (0.00000012).toString());46assertEquals("1.23e-7", (0.000000123).toString());47assertEquals("1e-8", (0.00000001).toString());48assertEquals("1.2e-8", (0.000000012).toString());49assertEquals("1.23e-8", (0.0000000123).toString());50assertEquals("0", (-0).toString());51assertEquals("-9", (-9).toString());52assertEquals("-90", (-90).toString());53assertEquals("-90.12", (-90.12).toString());54assertEquals("-0.1", (-0.1).toString());55assertEquals("-0.01", (-0.01).toString());56assertEquals("-0.0123", (-0.0123).toString());57assertEquals("-111111111111111110000", (-111111111111111111111).toString());58assertEquals("-1.1111111111111111e+21", (-1111111111111111111111).toString());59assertEquals("-1.1111111111111111e+22", (-11111111111111111111111).toString());60assertEquals("-0.00001", (-0.00001).toString());61assertEquals("-0.000001", (-0.000001).toString());62assertEquals("-1e-7", (-0.0000001).toString());63assertEquals("-1.2e-7", (-0.00000012).toString());64assertEquals("-1.23e-7", (-0.000000123).toString());65assertEquals("-1e-8", (-0.00000001).toString());66assertEquals("-1.2e-8", (-0.000000012).toString());67assertEquals("-1.23e-8", (-0.0000000123).toString());68assertEquals("NaN", (NaN).toString(16));69assertEquals("Infinity", (1/0).toString(16));70assertEquals("-Infinity", (-1/0).toString(16));71assertEquals("0", (0).toString(16));72assertEquals("9", (9).toString(16));73assertEquals("5a", (90).toString(16));74assertEquals("5a.1eb851eb852", (90.12).toString(16));75assertEquals("0.1999999999999a", (0.1).toString(16));76assertEquals("0.028f5c28f5c28f6", (0.01).toString(16));77assertEquals("0.032617c1bda511a", (0.0123).toString(16));78assertEquals("605f9f6dd18bc8000", (111111111111111111111).toString(16));79assertEquals("3c3bc3a4a2f75c0000", (1111111111111111111111).toString(16));80assertEquals("25a55a46e5da9a00000", (11111111111111111111111).toString(16));81assertEquals("0.0000a7c5ac471b4788", (0.00001).toString(16));82assertEquals("0.000010c6f7a0b5ed8d", (0.000001).toString(16));83assertEquals("0.000001ad7f29abcaf48", (0.0000001).toString(16));84assertEquals("0.000002036565348d256", (0.00000012).toString(16));85assertEquals("0.0000021047ee22aa466", (0.000000123).toString(16));86assertEquals("0.0000002af31dc4611874", (0.00000001).toString(16));87assertEquals("0.000000338a23b87483be", (0.000000012).toString(16));88assertEquals("0.00000034d3fe36aaa0a2", (0.0000000123).toString(16));89assertEquals("0", (-0).toString(16));90assertEquals("-9", (-9).toString(16));91assertEquals("-5a", (-90).toString(16));92assertEquals("-5a.1eb851eb852", (-90.12).toString(16));93assertEquals("-0.1999999999999a", (-0.1).toString(16));94assertEquals("-0.028f5c28f5c28f6", (-0.01).toString(16));95assertEquals("-0.032617c1bda511a", (-0.0123).toString(16));96assertEquals("-605f9f6dd18bc8000", (-111111111111111111111).toString(16));97assertEquals("-3c3bc3a4a2f75c0000", (-1111111111111111111111).toString(16));98assertEquals("-25a55a46e5da9a00000", (-11111111111111111111111).toString(16));99assertEquals("-0.0000a7c5ac471b4788", (-0.00001).toString(16));100assertEquals("-0.000010c6f7a0b5ed8d", (-0.000001).toString(16));101assertEquals("-0.000001ad7f29abcaf48", (-0.0000001).toString(16));102assertEquals("-0.000002036565348d256", (-0.00000012).toString(16));103assertEquals("-0.0000021047ee22aa466", (-0.000000123).toString(16));104assertEquals("-0.0000002af31dc4611874", (-0.00000001).toString(16));105assertEquals("-0.000000338a23b87483be", (-0.000000012).toString(16));106assertEquals("-0.00000034d3fe36aaa0a2", (-0.0000000123).toString(16));107assertEquals("4294967296", Math.pow(2,32).toString());108assertEquals("ffffffff", (Math.pow(2,32)-1).toString(16));109assertEquals("11111111111111111111111111111111", (Math.pow(2,32)-1).toString(2));110assertEquals("5yc1z", (10000007).toString(36));111assertEquals("0", (0).toString(36));112assertEquals("0", (0).toString(16));113assertEquals("0", (0).toString(10));114assertEquals("0", (0).toString(8));115assertEquals("0", (0).toString(2));116assertEquals("100000000000000000000000000000000", Math.pow(2,32).toString(2));117assertEquals("100000000000000000000000000000001", (Math.pow(2,32) + 1).toString(2));118assertEquals("100000000000080", (0x100000000000081).toString(16));119assertEquals("1000000000000100", (-(-'0x1000000000000081')).toString(16));120assertEquals("1000000000000000", (-(-'0x1000000000000080')).toString(16));121assertEquals("1000000000000000", (-(-'0x100000000000007F')).toString(16));122assertEquals("100000000000000000000000000000000000000000000000010000000", (0x100000000000081).toString(2));123assertEquals("-11111111111111111111111111111111", (-(Math.pow(2,32)-1)).toString(2));124assertEquals("-5yc1z", (-10000007).toString(36));125assertEquals("-100000000000000000000000000000000", (-Math.pow(2,32)).toString(2));126assertEquals("-100000000000000000000000000000001", (-(Math.pow(2,32) + 1)).toString(2));127assertEquals("-100000000000080", (-0x100000000000081).toString(16));128assertEquals("-100000000000000000000000000000000000000000000000010000000", (-0x100000000000081).toString(2));129assertEquals("1000", (1000).toString());130assertEquals("0.00001", (0.00001).toString());131assertEquals("1000000000000000100", (1000000000000000128).toString());132assertEquals("1e+21", (1000000000000000012800).toString());133assertEquals("-1e+21", (-1000000000000000012800).toString());134assertEquals("1e-7", (0.0000001).toString());135assertEquals("-1e-7", (-0.0000001).toString());136assertEquals("1.0000000000000001e+21", (1000000000000000128000).toString());137assertEquals("0.000001", (0.000001).toString());138assertEquals("1e-7", (0.0000001).toString());139assertEquals("8.8", (8.5).toString(16));140assertEquals("-8.8", (-8.5).toString(16));141// ----------------------------------------------------------------------142// toFixed143assertEquals("NaN", (NaN).toFixed(2));144assertEquals("Infinity", (1/0).toFixed(2));145assertEquals("-Infinity", (-1/0).toFixed(2));146assertEquals("1.1111111111111111e+21", (1111111111111111111111).toFixed(8));147assertEquals("0.1", (0.1).toFixed(1));148assertEquals("0.10", (0.1).toFixed(2));149assertEquals("0.100", (0.1).toFixed(3));150assertEquals("0.01", (0.01).toFixed(2));151assertEquals("0.010", (0.01).toFixed(3));152assertEquals("0.0100", (0.01).toFixed(4));153assertEquals("0.00", (0.001).toFixed(2));154assertEquals("0.001", (0.001).toFixed(3));155assertEquals("0.0010", (0.001).toFixed(4));156assertEquals("1.0000", (1).toFixed(4));157assertEquals("1.0", (1).toFixed(1));158assertEquals("1", (1).toFixed(0));159assertEquals("12", (12).toFixed(0));160assertEquals("1", (1.1).toFixed(0));161assertEquals("12", (12.1).toFixed(0));162assertEquals("1", (1.12).toFixed(0));163assertEquals("12", (12.12).toFixed(0));164assertEquals("0.0000006", (0.0000006).toFixed(7));165assertEquals("0.00000006", (0.00000006).toFixed(8));166assertEquals("0.000000060", (0.00000006).toFixed(9));167assertEquals("0.0000000600", (0.00000006).toFixed(10));168assertEquals("0", (0).toFixed(0));169assertEquals("0.0", (0).toFixed(1));170assertEquals("0.00", (0).toFixed(2));171assertEquals("-1.1111111111111111e+21", (-1111111111111111111111).toFixed(8));172assertEquals("-0.1", (-0.1).toFixed(1));173assertEquals("-0.10", (-0.1).toFixed(2));174assertEquals("-0.100", (-0.1).toFixed(3));175assertEquals("-0.01", (-0.01).toFixed(2));176assertEquals("-0.010", (-0.01).toFixed(3));177assertEquals("-0.0100", (-0.01).toFixed(4));178assertEquals("-0.00", (-0.001).toFixed(2));179assertEquals("-0.001", (-0.001).toFixed(3));180assertEquals("-0.0010", (-0.001).toFixed(4));181assertEquals("-1.0000", (-1).toFixed(4));182assertEquals("-1.0", (-1).toFixed(1));183assertEquals("-1", (-1).toFixed(0));184assertEquals("-1", (-1.1).toFixed(0));185assertEquals("-12", (-12.1).toFixed(0));186assertEquals("-1", (-1.12).toFixed(0));187assertEquals("-12", (-12.12).toFixed(0));188assertEquals("-0.0000006", (-0.0000006).toFixed(7));189assertEquals("-0.00000006", (-0.00000006).toFixed(8));190assertEquals("-0.000000060", (-0.00000006).toFixed(9));191assertEquals("-0.0000000600", (-0.00000006).toFixed(10));192assertEquals("0", (-0).toFixed(0));193assertEquals("0.0", (-0).toFixed(1));194assertEquals("0.00", (-0).toFixed(2));195assertEquals("1000", (1000).toFixed());196assertEquals("0", (0.00001).toFixed());197assertEquals("0.00001", (0.00001).toFixed(5));198assertEquals("0.00000000000000000010", (0.0000000000000000001).toFixed(20));199assertEquals("0.00001000000000000", (0.00001).toFixed(17));200assertEquals("1.00000000000000000", (1).toFixed(17));201assertEquals("1000000000000000128", (1000000000000000128).toFixed());202assertEquals("100000000000000128.0", (100000000000000128).toFixed(1));203assertEquals("10000000000000128.00", (10000000000000128).toFixed(2));204assertEquals("10000000000000128.00000000000000000000", (10000000000000128).toFixed(20));205assertEquals("0", (0).toFixed());206assertEquals("-42.000", ((-42).toFixed(3)));207assertEquals("-1000000000000000128", (-1000000000000000128).toFixed());208assertEquals("-0.00000000000000000010", (-0.0000000000000000001).toFixed(20));209assertEquals("0.12312312312312299889", (0.123123123123123).toFixed(20));210// Test that we round up even when the last digit generated is even.211// dtoa does not do this in its original form.212assertEquals("1", 0.5.toFixed(0), "0.5.toFixed(0)");213assertEquals("-1", (-0.5).toFixed(0), "(-0.5).toFixed(0)");214assertEquals("1.3", 1.25.toFixed(1), "1.25.toFixed(1)");215// This is bizare, but Spidermonkey and KJS behave the same.216assertEquals("234.2040", (234.20405).toFixed(4), "234.2040.toFixed(4)");217assertEquals("234.2041", (234.2040506).toFixed(4));218// ----------------------------------------------------------------------219// toExponential220assertEquals("1e+0", (1).toExponential());221assertEquals("1.1e+1", (11).toExponential());222assertEquals("1.12e+2", (112).toExponential());223assertEquals("1e+0", (1).toExponential(0));224assertEquals("1e+1", (11).toExponential(0));225assertEquals("1e+2", (112).toExponential(0));226assertEquals("1.0e+0", (1).toExponential(1));227assertEquals("1.1e+1", (11).toExponential(1));228assertEquals("1.1e+2", (112).toExponential(1));229assertEquals("1.00e+0", (1).toExponential(2));230assertEquals("1.10e+1", (11).toExponential(2));231assertEquals("1.12e+2", (112).toExponential(2));232assertEquals("1.000e+0", (1).toExponential(3));233assertEquals("1.100e+1", (11).toExponential(3));234assertEquals("1.120e+2", (112).toExponential(3));235assertEquals("1e-1", (0.1).toExponential());236assertEquals("1.1e-1", (0.11).toExponential());237assertEquals("1.12e-1", (0.112).toExponential());238assertEquals("1e-1", (0.1).toExponential(0));239assertEquals("1e-1", (0.11).toExponential(0));240assertEquals("1e-1", (0.112).toExponential(0));241assertEquals("1.0e-1", (0.1).toExponential(1));242assertEquals("1.1e-1", (0.11).toExponential(1));243assertEquals("1.1e-1", (0.112).toExponential(1));244assertEquals("1.00e-1", (0.1).toExponential(2));245assertEquals("1.10e-1", (0.11).toExponential(2));246assertEquals("1.12e-1", (0.112).toExponential(2));247assertEquals("1.000e-1", (0.1).toExponential(3));248assertEquals("1.100e-1", (0.11).toExponential(3));249assertEquals("1.120e-1", (0.112).toExponential(3));250assertEquals("-1e+0", (-1).toExponential());251assertEquals("-1.1e+1", (-11).toExponential());252assertEquals("-1.12e+2", (-112).toExponential());253assertEquals("-1e+0", (-1).toExponential(0));254assertEquals("-1e+1", (-11).toExponential(0));255assertEquals("-1e+2", (-112).toExponential(0));256assertEquals("-1.0e+0", (-1).toExponential(1));257assertEquals("-1.1e+1", (-11).toExponential(1));258assertEquals("-1.1e+2", (-112).toExponential(1));259assertEquals("-1.00e+0", (-1).toExponential(2));260assertEquals("-1.10e+1", (-11).toExponential(2));261assertEquals("-1.12e+2", (-112).toExponential(2));262assertEquals("-1.000e+0", (-1).toExponential(3));263assertEquals("-1.100e+1", (-11).toExponential(3));264assertEquals("-1.120e+2", (-112).toExponential(3));265assertEquals("-1e-1", (-0.1).toExponential());266assertEquals("-1.1e-1", (-0.11).toExponential());267assertEquals("-1.12e-1", (-0.112).toExponential());268assertEquals("-1e-1", (-0.1).toExponential(0));269assertEquals("-1e-1", (-0.11).toExponential(0));270assertEquals("-1e-1", (-0.112).toExponential(0));271assertEquals("-1.0e-1", (-0.1).toExponential(1));272assertEquals("-1.1e-1", (-0.11).toExponential(1));273assertEquals("-1.1e-1", (-0.112).toExponential(1));274assertEquals("-1.00e-1", (-0.1).toExponential(2));275assertEquals("-1.10e-1", (-0.11).toExponential(2));276assertEquals("-1.12e-1", (-0.112).toExponential(2));277assertEquals("-1.000e-1", (-0.1).toExponential(3));278assertEquals("-1.100e-1", (-0.11).toExponential(3));279assertEquals("-1.120e-1", (-0.112).toExponential(3));280assertEquals("NaN", (NaN).toExponential(2));281assertEquals("Infinity", (Infinity).toExponential(2));282assertEquals("-Infinity", (-Infinity).toExponential(2));283assertEquals("1e+0", (1).toExponential(0));284assertEquals("0e+0", (0).toExponential());285assertEquals("0.00e+0", (0).toExponential(2));286assertEquals("1e+1", (11.2356).toExponential(0));287assertEquals("1.1236e+1", (11.2356).toExponential(4));288assertEquals("1.1236e-4", (0.000112356).toExponential(4));289assertEquals("-1.1236e-4", (-0.000112356).toExponential(4));290assertEquals("1.12356e-4", (0.000112356).toExponential());291assertEquals("-1.12356e-4", (-0.000112356).toExponential());292// ----------------------------------------------------------------------293// toPrecision294assertEquals("NaN", (NaN).toPrecision(1));295assertEquals("Infinity", (Infinity).toPrecision(2));296assertEquals("-Infinity", (-Infinity).toPrecision(2));297assertEquals("0.000555000000000000", (0.000555).toPrecision(15));298assertEquals("5.55000000000000e-7", (0.000000555).toPrecision(15));299assertEquals("-5.55000000000000e-7", (-0.000000555).toPrecision(15));300assertEquals("1e+8", (123456789).toPrecision(1));301assertEquals("123456789", (123456789).toPrecision(9));302assertEquals("1.2345679e+8", (123456789).toPrecision(8));303assertEquals("1.234568e+8", (123456789).toPrecision(7));304assertEquals("-1.234568e+8", (-123456789).toPrecision(7));305assertEquals("-1.2e-9", Number(-.0000000012345).toPrecision(2));306assertEquals("-1.2e-8", Number(-.000000012345).toPrecision(2));307assertEquals("-1.2e-7", Number(-.00000012345).toPrecision(2));308assertEquals("-0.0000012", Number(-.0000012345).toPrecision(2));309assertEquals("-0.000012", Number(-.000012345).toPrecision(2));310assertEquals("-0.00012", Number(-.00012345).toPrecision(2));311assertEquals("-0.0012", Number(-.0012345).toPrecision(2));312assertEquals("-0.012", Number(-.012345).toPrecision(2));313assertEquals("-0.12", Number(-.12345).toPrecision(2));314assertEquals("-1.2", Number(-1.2345).toPrecision(2));315assertEquals("-12", Number(-12.345).toPrecision(2));316assertEquals("-1.2e+2", Number(-123.45).toPrecision(2));317assertEquals("-1.2e+3", Number(-1234.5).toPrecision(2));318assertEquals("-1.2e+4", Number(-12345).toPrecision(2));319assertEquals("-1.235e+4", Number(-12345.67).toPrecision(4));320assertEquals("-1.234e+4", Number(-12344.67).toPrecision(4));321// Test that we round up even when the last digit generated is even.322// dtoa does not do this in its original form.323assertEquals("1.3", 1.25.toPrecision(2), "1.25.toPrecision(2)");...

Full Screen

Full Screen

number-tostring-small.js

Source:number-tostring-small.js Github

copy

Full Screen

1// Copyright 2008 the V8 project authors. All rights reserved.2// Redistribution and use in source and binary forms, with or without3// modification, are permitted provided that the following conditions are4// met:5//6// * Redistributions of source code must retain the above copyright7// notice, this list of conditions and the following disclaimer.8// * Redistributions in binary form must reproduce the above9// copyright notice, this list of conditions and the following10// disclaimer in the documentation and/or other materials provided11// with the distribution.12// * Neither the name of Google Inc. nor the names of its13// contributors may be used to endorse or promote products derived14// from this software without specific prior written permission.15//16// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS17// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT18// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR19// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT20// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,21// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT22// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,23// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY24// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT25// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE26// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.27// This file is a concatenation of the number-tostring and28// to-precision mjsunit tests where the mjsunit assert code has been29// removed.30// ----------------------------------------------------------------------31// toString32(NaN).toString();33(1/0).toString();34(-1/0).toString();35(0).toString();36(9).toString();37(90).toString();38(90.12).toString();39(0.1).toString();40(0.01).toString();41(0.0123).toString();42(111111111111111111111).toString();43(1111111111111111111111).toString();44(11111111111111111111111).toString();45(0.00001).toString();46(0.000001).toString();47(0.0000001).toString();48(0.00000012).toString();49(0.000000123).toString();50(0.00000001).toString();51(0.000000012).toString();52(0.0000000123).toString();53(-0).toString();54(-9).toString();55(-90).toString();56(-90.12).toString();57(-0.1).toString();58(-0.01).toString();59(-0.0123).toString();60(-111111111111111111111).toString();61(-1111111111111111111111).toString();62(-11111111111111111111111).toString();63(-0.00001).toString();64(-0.000001).toString();65(-0.0000001).toString();66(-0.00000012).toString();67(-0.000000123).toString();68(-0.00000001).toString();69(-0.000000012).toString();70(-0.0000000123).toString();71(NaN).toString(16);72(1/0).toString(16);73(-1/0).toString(16);74(0).toString(16);75(9).toString(16);76(90).toString(16);77(90.12).toString(16);78(0.1).toString(16);79(0.01).toString(16);80(0.0123).toString(16);81(111111111111111111111).toString(16);82(1111111111111111111111).toString(16);83(11111111111111111111111).toString(16);84(0.00001).toString(16);85(0.000001).toString(16);86(0.0000001).toString(16);87(0.00000012).toString(16);88(0.000000123).toString(16);89(0.00000001).toString(16);90(0.000000012).toString(16);91(0.0000000123).toString(16);92(-0).toString(16);93(-9).toString(16);94(-90).toString(16);95(-90.12).toString(16);96(-0.1).toString(16);97(-0.01).toString(16);98(-0.0123).toString(16);99(-111111111111111111111).toString(16);100(-1111111111111111111111).toString(16);101(-11111111111111111111111).toString(16);102(-0.00001).toString(16);103(-0.000001).toString(16);104(-0.0000001).toString(16);105(-0.00000012).toString(16);106(-0.000000123).toString(16);107(-0.00000001).toString(16);108(-0.000000012).toString(16);109(-0.0000000123).toString(16);110(2,32).toString();111(Math.pow(2,32)-1).toString(16);112(Math.pow(2,32)-1).toString(2);113(10000007).toString(36);114(0).toString(36);115(0).toString(16);116(0).toString(10);117(0).toString(8);118(0).toString(2);119(2,32).toString(2);120(Math.pow(2,32) + 1).toString(2);121(0x100000000000081).toString(16);122(-(-'0x1000000000000081')).toString(16);123(0x100000000000081).toString(2);124(-(Math.pow(2,32)-1)).toString(2);125(-10000007).toString(36);126(-Math.pow(2,32)).toString(2);127(-(Math.pow(2,32) + 1)).toString(2);128(-0x100000000000081).toString(16);129(-0x100000000000081).toString(2);130(1000).toString();131(0.00001).toString();132(1000000000000000128).toString();133(1000000000000000012800).toString();134(-1000000000000000012800).toString();135(0.0000001).toString();136(-0.0000001).toString();137(1000000000000000128000).toString();138(0.000001).toString();139(0.0000001).toString();140(8.5).toString(16);141(-8.5).toString(16);142// ----------------------------------------------------------------------143// toFixed144(NaN).toFixed(2);145(1/0).toFixed(2);146(-1/0).toFixed(2);147(1111111111111111111111).toFixed(8);148(0.1).toFixed(1);149(0.1).toFixed(2);150(0.1).toFixed(3);151(0.01).toFixed(2);152(0.01).toFixed(3);153(0.01).toFixed(4);154(0.001).toFixed(2);155(0.001).toFixed(3);156(0.001).toFixed(4);157(1).toFixed(4);158(1).toFixed(1);159(1).toFixed(0);160(12).toFixed(0);161(1.1).toFixed(0);162(12.1).toFixed(0);163(1.12).toFixed(0);164(12.12).toFixed(0);165(0.0000006).toFixed(7);166(0.00000006).toFixed(8);167(0.00000006).toFixed(9);168(0.00000006).toFixed(10);169(0).toFixed(0);170(0).toFixed(1);171(0).toFixed(2);172(-1111111111111111111111).toFixed(8);173(-0.1).toFixed(1);174(-0.1).toFixed(2);175(-0.1).toFixed(3);176(-0.01).toFixed(2);177(-0.01).toFixed(3);178(-0.01).toFixed(4);179(-0.001).toFixed(2);180(-0.001).toFixed(3);181(-0.001).toFixed(4);182(-1).toFixed(4);183(-1).toFixed(1);184(-1).toFixed(0);185(-1.1).toFixed(0);186(-12.1).toFixed(0);187(-1.12).toFixed(0);188(-12.12).toFixed(0);189(-0.0000006).toFixed(7);190(-0.00000006).toFixed(8);191(-0.00000006).toFixed(9);192(-0.00000006).toFixed(10);193(-0).toFixed(0);194(-0).toFixed(1);195(-0).toFixed(2);196(1000).toFixed();197(0.00001).toFixed();198(0.00001).toFixed(5);199(0.0000000000000000001).toFixed(20);200(0.00001).toFixed(17);201(1).toFixed(17);202(1000000000000000128).toFixed();203(100000000000000128).toFixed(1);204(10000000000000128).toFixed(2);205(10000000000000128).toFixed(20);206(0).toFixed();207((-42).toFixed(3));208(-1000000000000000128).toFixed();209(-0.0000000000000000001).toFixed(20);210(0.123123123123123).toFixed(20);211// Test that we round up even when the last digit generated is even.212// dtoa does not do this in its original form.213(0.5).toFixed(0);214(-0.5).toFixed(0);215(1.25).toFixed(1);216// This is bizare, but Spidermonkey and KJS behave the same.217(234.20405).toFixed(4);218(234.2040506).toFixed(4);219// ----------------------------------------------------------------------220// toExponential221(1).toExponential();222(11).toExponential();223(112).toExponential();224(1).toExponential(0);225(11).toExponential(0);226(112).toExponential(0);227(1).toExponential(1);228(11).toExponential(1);229(112).toExponential(1);230(1).toExponential(2);231(11).toExponential(2);232(112).toExponential(2);233(1).toExponential(3);234(11).toExponential(3);235(112).toExponential(3);236(0.1).toExponential();237(0.11).toExponential();238(0.112).toExponential();239(0.1).toExponential(0);240(0.11).toExponential(0);241(0.112).toExponential(0);242(0.1).toExponential(1);243(0.11).toExponential(1);244(0.112).toExponential(1);245(0.1).toExponential(2);246(0.11).toExponential(2);247(0.112).toExponential(2);248(0.1).toExponential(3);249(0.11).toExponential(3);250(0.112).toExponential(3);251(-1).toExponential();252(-11).toExponential();253(-112).toExponential();254(-1).toExponential(0);255(-11).toExponential(0);256(-112).toExponential(0);257(-1).toExponential(1);258(-11).toExponential(1);259(-112).toExponential(1);260(-1).toExponential(2);261(-11).toExponential(2);262(-112).toExponential(2);263(-1).toExponential(3);264(-11).toExponential(3);265(-112).toExponential(3);266(-0.1).toExponential();267(-0.11).toExponential();268(-0.112).toExponential();269(-0.1).toExponential(0);270(-0.11).toExponential(0);271(-0.112).toExponential(0);272(-0.1).toExponential(1);273(-0.11).toExponential(1);274(-0.112).toExponential(1);275(-0.1).toExponential(2);276(-0.11).toExponential(2);277(-0.112).toExponential(2);278(-0.1).toExponential(3);279(-0.11).toExponential(3);280(-0.112).toExponential(3);281(NaN).toExponential(2);282(Infinity).toExponential(2);283(-Infinity).toExponential(2);284(1).toExponential(0);285(0).toExponential();286(0).toExponential(2);287(11.2356).toExponential(0);288(11.2356).toExponential(4);289(0.000112356).toExponential(4);290(-0.000112356).toExponential(4);291(0.000112356).toExponential();292(-0.000112356).toExponential();293// ----------------------------------------------------------------------294// toPrecision295(NaN).toPrecision(1);296(Infinity).toPrecision(2);297(-Infinity).toPrecision(2);298(0.000555).toPrecision(15);299(0.000000555).toPrecision(15);300(-0.000000555).toPrecision(15);301(123456789).toPrecision(1);302(123456789).toPrecision(9);303(123456789).toPrecision(8);304(123456789).toPrecision(7);305(-123456789).toPrecision(7);306(-.0000000012345).toPrecision(2);307(-.000000012345).toPrecision(2);308(-.00000012345).toPrecision(2);309(-.0000012345).toPrecision(2);310(-.000012345).toPrecision(2);311(-.00012345).toPrecision(2);312(-.0012345).toPrecision(2);313(-.012345).toPrecision(2);314(-.12345).toPrecision(2);315(-1.2345).toPrecision(2);316(-12.345).toPrecision(2);317(-123.45).toPrecision(2);318(-1234.5).toPrecision(2);319(-12345).toPrecision(2);320(-12345.67).toPrecision(4);321Number(-12344.67).toPrecision(4);322// Test that we round up even when the last digit generated is even.323// dtoa does not do this in its original form.324(1.25).toPrecision(2);325(1.35).toPrecision(2);326// Test the exponential notation output.327(1.2345e+27).toPrecision(1);328(1.2345e+27).toPrecision(2);329(1.2345e+27).toPrecision(3);330(1.2345e+27).toPrecision(4);331(1.2345e+27).toPrecision(5);332(1.2345e+27).toPrecision(6);333(1.2345e+27).toPrecision(7);334(-1.2345e+27).toPrecision(1);335(-1.2345e+27).toPrecision(2);336(-1.2345e+27).toPrecision(3);337(-1.2345e+27).toPrecision(4);338(-1.2345e+27).toPrecision(5);339(-1.2345e+27).toPrecision(6);340(-1.2345e+27).toPrecision(7);341// Test the fixed notation output.342(7).toPrecision(1);343(7).toPrecision(2);344(7).toPrecision(3);345(-7).toPrecision(1);346(-7).toPrecision(2);347(-7).toPrecision(3);348(91).toPrecision(1);349(91).toPrecision(2);350(91).toPrecision(3);351(91).toPrecision(4);352(-91).toPrecision(1);353(-91).toPrecision(2);354(-91).toPrecision(3);355(-91).toPrecision(4);356(91.1234).toPrecision(1);357(91.1234).toPrecision(2);358(91.1234).toPrecision(3);359(91.1234).toPrecision(4);360(91.1234).toPrecision(5);361(91.1234).toPrecision(6);362(91.1234).toPrecision(7);363(91.1234).toPrecision(8);364(-91.1234).toPrecision(1);365(-91.1234).toPrecision(2);366(-91.1234).toPrecision(3);367(-91.1234).toPrecision(4);368(-91.1234).toPrecision(5);369(-91.1234).toPrecision(6);370(-91.1234).toPrecision(7);...

Full Screen

Full Screen

temperature_conversions.py

Source:temperature_conversions.py Github

copy

Full Screen

1""" Convert between different units of temperature """2def celsius_to_fahrenheit(celsius: float, ndigits: int = 2) -> float:3 """4 Convert a given value from Celsius to Fahrenheit and round it to 2 decimal places.5 Wikipedia reference: https://en.wikipedia.org/wiki/Celsius6 Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit7 >>> celsius_to_fahrenheit(273.354, 3)8 524.0379 >>> celsius_to_fahrenheit(273.354, 0)10 524.011 >>> celsius_to_fahrenheit(-40.0)12 -40.013 >>> celsius_to_fahrenheit(-20.0)14 -4.015 >>> celsius_to_fahrenheit(0)16 32.017 >>> celsius_to_fahrenheit(20)18 68.019 >>> celsius_to_fahrenheit("40")20 104.021 >>> celsius_to_fahrenheit("celsius")22 Traceback (most recent call last):23 ...24 ValueError: could not convert string to float: 'celsius'25 """26 return round((float(celsius) * 9 / 5) + 32, ndigits)27def celsius_to_kelvin(celsius: float, ndigits: int = 2) -> float:28 """29 Convert a given value from Celsius to Kelvin and round it to 2 decimal places.30 Wikipedia reference: https://en.wikipedia.org/wiki/Celsius31 Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin32 >>> celsius_to_kelvin(273.354, 3)33 546.50434 >>> celsius_to_kelvin(273.354, 0)35 547.036 >>> celsius_to_kelvin(0)37 273.1538 >>> celsius_to_kelvin(20.0)39 293.1540 >>> celsius_to_kelvin("40")41 313.1542 >>> celsius_to_kelvin("celsius")43 Traceback (most recent call last):44 ...45 ValueError: could not convert string to float: 'celsius'46 """47 return round(float(celsius) + 273.15, ndigits)48def celsius_to_rankine(celsius: float, ndigits: int = 2) -> float:49 """50 Convert a given value from Celsius to Rankine and round it to 2 decimal places.51 Wikipedia reference: https://en.wikipedia.org/wiki/Celsius52 Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale53 >>> celsius_to_rankine(273.354, 3)54 983.70755 >>> celsius_to_rankine(273.354, 0)56 984.057 >>> celsius_to_rankine(0)58 491.6759 >>> celsius_to_rankine(20.0)60 527.6761 >>> celsius_to_rankine("40")62 563.6763 >>> celsius_to_rankine("celsius")64 Traceback (most recent call last):65 ...66 ValueError: could not convert string to float: 'celsius'67 """68 return round((float(celsius) * 9 / 5) + 491.67, ndigits)69def fahrenheit_to_celsius(fahrenheit: float, ndigits: int = 2) -> float:70 """71 Convert a given value from Fahrenheit to Celsius and round it to 2 decimal places.72 Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit73 Wikipedia reference: https://en.wikipedia.org/wiki/Celsius74 >>> fahrenheit_to_celsius(273.354, 3)75 134.08676 >>> fahrenheit_to_celsius(273.354, 0)77 134.078 >>> fahrenheit_to_celsius(0)79 -17.7880 >>> fahrenheit_to_celsius(20.0)81 -6.6782 >>> fahrenheit_to_celsius(40.0)83 4.4484 >>> fahrenheit_to_celsius(60)85 15.5686 >>> fahrenheit_to_celsius(80)87 26.6788 >>> fahrenheit_to_celsius("100")89 37.7890 >>> fahrenheit_to_celsius("fahrenheit")91 Traceback (most recent call last):92 ...93 ValueError: could not convert string to float: 'fahrenheit'94 """95 return round((float(fahrenheit) - 32) * 5 / 9, ndigits)96def fahrenheit_to_kelvin(fahrenheit: float, ndigits: int = 2) -> float:97 """98 Convert a given value from Fahrenheit to Kelvin and round it to 2 decimal places.99 Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit100 Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin101 >>> fahrenheit_to_kelvin(273.354, 3)102 407.236103 >>> fahrenheit_to_kelvin(273.354, 0)104 407.0105 >>> fahrenheit_to_kelvin(0)106 255.37107 >>> fahrenheit_to_kelvin(20.0)108 266.48109 >>> fahrenheit_to_kelvin(40.0)110 277.59111 >>> fahrenheit_to_kelvin(60)112 288.71113 >>> fahrenheit_to_kelvin(80)114 299.82115 >>> fahrenheit_to_kelvin("100")116 310.93117 >>> fahrenheit_to_kelvin("fahrenheit")118 Traceback (most recent call last):119 ...120 ValueError: could not convert string to float: 'fahrenheit'121 """122 return round(((float(fahrenheit) - 32) * 5 / 9) + 273.15, ndigits)123def fahrenheit_to_rankine(fahrenheit: float, ndigits: int = 2) -> float:124 """125 Convert a given value from Fahrenheit to Rankine and round it to 2 decimal places.126 Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit127 Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale128 >>> fahrenheit_to_rankine(273.354, 3)129 733.024130 >>> fahrenheit_to_rankine(273.354, 0)131 733.0132 >>> fahrenheit_to_rankine(0)133 459.67134 >>> fahrenheit_to_rankine(20.0)135 479.67136 >>> fahrenheit_to_rankine(40.0)137 499.67138 >>> fahrenheit_to_rankine(60)139 519.67140 >>> fahrenheit_to_rankine(80)141 539.67142 >>> fahrenheit_to_rankine("100")143 559.67144 >>> fahrenheit_to_rankine("fahrenheit")145 Traceback (most recent call last):146 ...147 ValueError: could not convert string to float: 'fahrenheit'148 """149 return round(float(fahrenheit) + 459.67, ndigits)150def kelvin_to_celsius(kelvin: float, ndigits: int = 2) -> float:151 """152 Convert a given value from Kelvin to Celsius and round it to 2 decimal places.153 Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin154 Wikipedia reference: https://en.wikipedia.org/wiki/Celsius155 >>> kelvin_to_celsius(273.354, 3)156 0.204157 >>> kelvin_to_celsius(273.354, 0)158 0.0159 >>> kelvin_to_celsius(273.15)160 0.0161 >>> kelvin_to_celsius(300)162 26.85163 >>> kelvin_to_celsius("315.5")164 42.35165 >>> kelvin_to_celsius("kelvin")166 Traceback (most recent call last):167 ...168 ValueError: could not convert string to float: 'kelvin'169 """170 return round(float(kelvin) - 273.15, ndigits)171def kelvin_to_fahrenheit(kelvin: float, ndigits: int = 2) -> float:172 """173 Convert a given value from Kelvin to Fahrenheit and round it to 2 decimal places.174 Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin175 Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit176 >>> kelvin_to_fahrenheit(273.354, 3)177 32.367178 >>> kelvin_to_fahrenheit(273.354, 0)179 32.0180 >>> kelvin_to_fahrenheit(273.15)181 32.0182 >>> kelvin_to_fahrenheit(300)183 80.33184 >>> kelvin_to_fahrenheit("315.5")185 108.23186 >>> kelvin_to_fahrenheit("kelvin")187 Traceback (most recent call last):188 ...189 ValueError: could not convert string to float: 'kelvin'190 """191 return round(((float(kelvin) - 273.15) * 9 / 5) + 32, ndigits)192def kelvin_to_rankine(kelvin: float, ndigits: int = 2) -> float:193 """194 Convert a given value from Kelvin to Rankine and round it to 2 decimal places.195 Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin196 Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale197 >>> kelvin_to_rankine(273.354, 3)198 492.037199 >>> kelvin_to_rankine(273.354, 0)200 492.0201 >>> kelvin_to_rankine(0)202 0.0203 >>> kelvin_to_rankine(20.0)204 36.0205 >>> kelvin_to_rankine("40")206 72.0207 >>> kelvin_to_rankine("kelvin")208 Traceback (most recent call last):209 ...210 ValueError: could not convert string to float: 'kelvin'211 """212 return round((float(kelvin) * 9 / 5), ndigits)213def rankine_to_celsius(rankine: float, ndigits: int = 2) -> float:214 """215 Convert a given value from Rankine to Celsius and round it to 2 decimal places.216 Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale217 Wikipedia reference: https://en.wikipedia.org/wiki/Celsius218 >>> rankine_to_celsius(273.354, 3)219 -121.287220 >>> rankine_to_celsius(273.354, 0)221 -121.0222 >>> rankine_to_celsius(273.15)223 -121.4224 >>> rankine_to_celsius(300)225 -106.48226 >>> rankine_to_celsius("315.5")227 -97.87228 >>> rankine_to_celsius("rankine")229 Traceback (most recent call last):230 ...231 ValueError: could not convert string to float: 'rankine'232 """233 return round((float(rankine) - 491.67) * 5 / 9, ndigits)234def rankine_to_fahrenheit(rankine: float, ndigits: int = 2) -> float:235 """236 Convert a given value from Rankine to Fahrenheit and round it to 2 decimal places.237 Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale238 Wikipedia reference: https://en.wikipedia.org/wiki/Fahrenheit239 >>> rankine_to_fahrenheit(273.15)240 -186.52241 >>> rankine_to_fahrenheit(300)242 -159.67243 >>> rankine_to_fahrenheit("315.5")244 -144.17245 >>> rankine_to_fahrenheit("rankine")246 Traceback (most recent call last):247 ...248 ValueError: could not convert string to float: 'rankine'249 """250 return round(float(rankine) - 459.67, ndigits)251def rankine_to_kelvin(rankine: float, ndigits: int = 2) -> float:252 """253 Convert a given value from Rankine to Kelvin and round it to 2 decimal places.254 Wikipedia reference: https://en.wikipedia.org/wiki/Rankine_scale255 Wikipedia reference: https://en.wikipedia.org/wiki/Kelvin256 >>> rankine_to_kelvin(0)257 0.0258 >>> rankine_to_kelvin(20.0)259 11.11260 >>> rankine_to_kelvin("40")261 22.22262 >>> rankine_to_kelvin("rankine")263 Traceback (most recent call last):264 ...265 ValueError: could not convert string to float: 'rankine'266 """267 return round((float(rankine) * 5 / 9), ndigits)268if __name__ == "__main__":269 import doctest...

Full Screen

Full Screen

colorConversion.test.ts

Source:colorConversion.test.ts Github

copy

Full Screen

1import { RgbColor } from "../Color";2const colorConversionTables = {3 black: { hex: "#000000", r: 0, g: 0, b: 0, h: 0, s: 0, l: 0 },4 white: { hex: "#FFFFFF", r: 255, g: 255, b: 255, h: 0, s: 0, l: 100 },5 red: { hex: "#FF0000", r: 255, g: 0, b: 0, h: 0, s: 100, l: 50 },6 lime: { hex: "#00FF00", r: 0, g: 255, b: 0, h: 120, s: 100, l: 50 },7 blue: { hex: "#0000FF", r: 0, g: 0, b: 255, h: 240, s: 100, l: 50 },8 yellow: { hex: "#FFFF00", r: 255, g: 255, b: 0, h: 60, s: 100, l: 50 },9 cyan: { hex: "#00FFFF", r: 0, g: 255, b: 255, h: 180, s: 100, l: 50 },10 magenta: { hex: "#FF00FF", r: 255, g: 0, b: 255, h: 300, s: 100, l: 50 },11 silver: { hex: "#BFBFBF", r: 191, g: 191, b: 191, h: 0, s: 0, l: 75 },12 gray: { hex: "#808080", r: 128, g: 128, b: 128, h: 0, s: 0, l: 50 },13 maroon: { hex: "#800000", r: 128, g: 0, b: 0, h: 0, s: 100, l: 25 },14 olive: { hex: "#808000", r: 128, g: 128, b: 0, h: 60, s: 100, l: 25 },15 green: { hex: "#008000", r: 0, g: 128, b: 0, h: 120, s: 100, l: 25 },16 purple: { hex: "#800080", r: 128, g: 0, b: 128, h: 300, s: 100, l: 25 },17 teal: { hex: "#008080", r: 0, g: 128, b: 128, h: 180, s: 100, l: 25 },18 navy: { hex: "#000080", r: 0, g: 0, b: 128, h: 240, s: 100, l: 25 },19} as const;20describe("colorConversion", () => {21 it("converts black", () => {22 const C = colorConversionTables.black;23 const color = new RgbColor(C.r, C.g, C.b);24 const hsl = color.toHsl();25 const rgb = hsl.toRgb();26 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());27 expect(hsl.h).toBeCloseTo(C.h, 0);28 expect(hsl.s).toBeCloseTo(C.s, 0);29 expect(hsl.l).toBeCloseTo(C.l, 0);30 expect(rgb.r).toBeCloseTo(C.r, 0);31 expect(rgb.g).toBeCloseTo(C.g, 0);32 expect(rgb.b).toBeCloseTo(C.b, 0);33 });34 it("converts white", () => {35 const C = colorConversionTables.white;36 const color = new RgbColor(C.r, C.g, C.b);37 const hsl = color.toHsl();38 const rgb = hsl.toRgb();39 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());40 expect(hsl.h).toBeCloseTo(C.h, 0);41 expect(hsl.s).toBeCloseTo(C.s, 0);42 expect(hsl.l).toBeCloseTo(C.l, 0);43 expect(rgb.r).toBeCloseTo(C.r, 0);44 expect(rgb.g).toBeCloseTo(C.g, 0);45 expect(rgb.b).toBeCloseTo(C.b, 0);46 });47 it("converts red", () => {48 const C = colorConversionTables.red;49 const color = new RgbColor(C.r, C.g, C.b);50 const hsl = color.toHsl();51 const rgb = hsl.toRgb();52 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());53 expect(hsl.h).toBeCloseTo(C.h, 0);54 expect(hsl.s).toBeCloseTo(C.s, 0);55 expect(hsl.l).toBeCloseTo(C.l, 0);56 expect(rgb.r).toBeCloseTo(C.r, 0);57 expect(rgb.g).toBeCloseTo(C.g, 0);58 expect(rgb.b).toBeCloseTo(C.b, 0);59 });60 it("converts lime", () => {61 const C = colorConversionTables.lime;62 const color = new RgbColor(C.r, C.g, C.b);63 const hsl = color.toHsl();64 const rgb = hsl.toRgb();65 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());66 expect(hsl.h).toBeCloseTo(C.h, 0);67 expect(hsl.s).toBeCloseTo(C.s, 0);68 expect(hsl.l).toBeCloseTo(C.l, 0);69 expect(rgb.r).toBeCloseTo(C.r, 0);70 expect(rgb.g).toBeCloseTo(C.g, 0);71 expect(rgb.b).toBeCloseTo(C.b, 0);72 });73 it("converts blue", () => {74 const C = colorConversionTables.blue;75 const color = new RgbColor(C.r, C.g, C.b);76 const hsl = color.toHsl();77 const rgb = hsl.toRgb();78 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());79 expect(hsl.h).toBeCloseTo(C.h, 0);80 expect(hsl.s).toBeCloseTo(C.s, 0);81 expect(hsl.l).toBeCloseTo(C.l, 0);82 expect(rgb.r).toBeCloseTo(C.r, 0);83 expect(rgb.g).toBeCloseTo(C.g, 0);84 expect(rgb.b).toBeCloseTo(C.b, 0);85 });86 it("converts yellow", () => {87 const C = colorConversionTables.yellow;88 const color = new RgbColor(C.r, C.g, C.b);89 const hsl = color.toHsl();90 const rgb = hsl.toRgb();91 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());92 expect(hsl.h).toBeCloseTo(C.h, 0);93 expect(hsl.s).toBeCloseTo(C.s, 0);94 expect(hsl.l).toBeCloseTo(C.l, 0);95 expect(rgb.r).toBeCloseTo(C.r, 0);96 expect(rgb.g).toBeCloseTo(C.g, 0);97 expect(rgb.b).toBeCloseTo(C.b, 0);98 });99 it("converts cyan", () => {100 const C = colorConversionTables.cyan;101 const color = new RgbColor(C.r, C.g, C.b);102 const hsl = color.toHsl();103 const rgb = hsl.toRgb();104 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());105 expect(hsl.h).toBeCloseTo(C.h, 0);106 expect(hsl.s).toBeCloseTo(C.s, 0);107 expect(hsl.l).toBeCloseTo(C.l, 0);108 expect(rgb.r).toBeCloseTo(C.r, 0);109 expect(rgb.g).toBeCloseTo(C.g, 0);110 expect(rgb.b).toBeCloseTo(C.b, 0);111 });112 it("converts magenta", () => {113 const C = colorConversionTables.magenta;114 const color = new RgbColor(C.r, C.g, C.b);115 const hsl = color.toHsl();116 const rgb = hsl.toRgb();117 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());118 expect(hsl.h).toBeCloseTo(C.h, 0);119 expect(hsl.s).toBeCloseTo(C.s, 0);120 expect(hsl.l).toBeCloseTo(C.l, 0);121 expect(rgb.r).toBeCloseTo(C.r, 0);122 expect(rgb.g).toBeCloseTo(C.g, 0);123 expect(rgb.b).toBeCloseTo(C.b, 0);124 });125 it("converts silver", () => {126 const C = colorConversionTables.silver;127 const color = new RgbColor(C.r, C.g, C.b);128 const hsl = color.toHsl();129 const rgb = hsl.toRgb();130 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());131 expect(hsl.h).toBeCloseTo(C.h, 0);132 expect(hsl.s).toBeCloseTo(C.s, 0);133 expect(hsl.l).toBeCloseTo(C.l, 0);134 expect(rgb.r).toBeCloseTo(C.r, 0);135 expect(rgb.g).toBeCloseTo(C.g, 0);136 expect(rgb.b).toBeCloseTo(C.b, 0);137 });138 it("converts gray", () => {139 const C = colorConversionTables.gray;140 const color = new RgbColor(C.r, C.g, C.b);141 const hsl = color.toHsl();142 const rgb = hsl.toRgb();143 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());144 expect(hsl.h).toBeCloseTo(C.h, 0);145 expect(hsl.s).toBeCloseTo(C.s, 0);146 expect(hsl.l).toBeCloseTo(C.l, 0);147 expect(rgb.r).toBeCloseTo(C.r, 0);148 expect(rgb.g).toBeCloseTo(C.g, 0);149 expect(rgb.b).toBeCloseTo(C.b, 0);150 });151 it("converts maroon", () => {152 const C = colorConversionTables.maroon;153 const color = new RgbColor(C.r, C.g, C.b);154 const hsl = color.toHsl();155 const rgb = hsl.toRgb();156 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());157 expect(hsl.h).toBeCloseTo(C.h, 0);158 expect(hsl.s).toBeCloseTo(C.s, 0);159 expect(hsl.l).toBeCloseTo(C.l, 0);160 expect(rgb.r).toBeCloseTo(C.r, 0);161 expect(rgb.g).toBeCloseTo(C.g, 0);162 expect(rgb.b).toBeCloseTo(C.b, 0);163 });164 it("converts olive", () => {165 const C = colorConversionTables.olive;166 const color = new RgbColor(C.r, C.g, C.b);167 const hsl = color.toHsl();168 const rgb = hsl.toRgb();169 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());170 expect(hsl.h).toBeCloseTo(C.h, 0);171 expect(hsl.s).toBeCloseTo(C.s, 0);172 expect(hsl.l).toBeCloseTo(C.l, 0);173 expect(rgb.r).toBeCloseTo(C.r, 0);174 expect(rgb.g).toBeCloseTo(C.g, 0);175 expect(rgb.b).toBeCloseTo(C.b, 0);176 });177 it("converts green", () => {178 const C = colorConversionTables.green;179 const color = new RgbColor(C.r, C.g, C.b);180 const hsl = color.toHsl();181 const rgb = hsl.toRgb();182 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());183 expect(hsl.h).toBeCloseTo(C.h, 0);184 expect(hsl.s).toBeCloseTo(C.s, 0);185 expect(hsl.l).toBeCloseTo(C.l, 0);186 expect(rgb.r).toBeCloseTo(C.r, 0);187 expect(rgb.g).toBeCloseTo(C.g, 0);188 expect(rgb.b).toBeCloseTo(C.b, 0);189 });190 it("converts purple", () => {191 const C = colorConversionTables.purple;192 const color = new RgbColor(C.r, C.g, C.b);193 const hsl = color.toHsl();194 const rgb = hsl.toRgb();195 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());196 expect(hsl.h).toBeCloseTo(C.h, 0);197 expect(hsl.s).toBeCloseTo(C.s, 0);198 expect(hsl.l).toBeCloseTo(C.l, 0);199 expect(rgb.r).toBeCloseTo(C.r, 0);200 expect(rgb.g).toBeCloseTo(C.g, 0);201 expect(rgb.b).toBeCloseTo(C.b, 0);202 });203 it("converts teal", () => {204 const C = colorConversionTables.teal;205 const color = new RgbColor(C.r, C.g, C.b);206 const hsl = color.toHsl();207 const rgb = hsl.toRgb();208 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());209 expect(hsl.h).toBeCloseTo(C.h, 0);210 expect(hsl.s).toBeCloseTo(C.s, 0);211 expect(hsl.l).toBeCloseTo(C.l, 0);212 expect(rgb.r).toBeCloseTo(C.r, 0);213 expect(rgb.g).toBeCloseTo(C.g, 0);214 expect(rgb.b).toBeCloseTo(C.b, 0);215 });216 it("converts navy", () => {217 const C = colorConversionTables.navy;218 const color = new RgbColor(C.r, C.g, C.b);219 const hsl = color.toHsl();220 const rgb = hsl.toRgb();221 expect(color.toHexString().toLowerCase()).toBe(C.hex.toLowerCase());222 expect(hsl.h).toBeCloseTo(C.h, 0);223 expect(hsl.s).toBeCloseTo(C.s, 0);224 expect(hsl.l).toBeCloseTo(C.l, 0);225 expect(rgb.r).toBeCloseTo(C.r, 0);226 expect(rgb.g).toBeCloseTo(C.g, 0);227 expect(rgb.b).toBeCloseTo(C.b, 0);228 });...

Full Screen

Full Screen

test_warp.py

Source:test_warp.py Github

copy

Full Screen

1import numpy as np2import pytest3import drjit as dr4from drjit.scalar import ArrayXf as Float5import mitsuba as mi6def check_warp_vectorization(func_str, wrapper = (lambda f: lambda x: f(x)), atol=1e-6):7 """8 Helper routine which compares evaluations of the vectorized and9 non-vectorized version of a warping routine.10 """11 def kernel(u : float, v : float):12 func_vec = wrapper(getattr(mi.warp, func_str))13 pdf_func_vec = wrapper(getattr(mi.warp, func_str + "_pdf"))14 result = func_vec([u, v])15 pdf = pdf_func_vec(result)16 return result17 from mitsuba.test.util import check_vectorization18 check_vectorization(kernel, atol=atol)19def check_inverse(func, inverse):20 for x in dr.linspace(Float, 1e-6, 1-1e-6, 10):21 for y in dr.linspace(Float, 1e-6, 1-1e-6, 10):22 p1 = dr.scalar.Array2f(x, y)23 p2 = func(p1)24 p3 = inverse(p2)25 assert(dr.allclose(p1, p3, atol=1e-5))26def test_square_to_uniform_disk(variant_scalar_rgb):27 assert(dr.allclose(mi.warp.square_to_uniform_disk([0.5, 0]), [0, 0]))28 assert(dr.allclose(mi.warp.square_to_uniform_disk([0, 1]), [1, 0]))29 assert(dr.allclose(mi.warp.square_to_uniform_disk([0.5, 1]), [-1, 0], atol=1e-7))30 assert(dr.allclose(mi.warp.square_to_uniform_disk([1, 1]), [1, 0], atol=1e-6))31 check_inverse(mi.warp.square_to_uniform_disk, mi.warp.uniform_disk_to_square)32 check_warp_vectorization("square_to_uniform_disk")33def test_square_to_uniform_disk_concentric(variant_scalar_rgb):34 from math import sqrt35 assert(dr.allclose(mi.warp.square_to_uniform_disk_concentric([0, 0]), ([-1 / sqrt(2), -1 / sqrt(2)])))36 assert(dr.allclose(mi.warp.square_to_uniform_disk_concentric([0.5, .5]), [0, 0]))37 check_inverse(mi.warp.square_to_uniform_disk_concentric, mi.warp.uniform_disk_to_square_concentric)38 check_warp_vectorization("square_to_uniform_disk_concentric")39def test_square_to_uniform_triangle(variant_scalar_rgb):40 assert(dr.allclose(mi.warp.square_to_uniform_triangle([0, 0]), [0, 0]))41 assert(dr.allclose(mi.warp.square_to_uniform_triangle([0, 0.1]), [0, 0.1]))42 assert(dr.allclose(mi.warp.square_to_uniform_triangle([0, 1]), [0, 1]))43 assert(dr.allclose(mi.warp.square_to_uniform_triangle([1, 0]), [1, 0]))44 assert(dr.allclose(mi.warp.square_to_uniform_triangle([1, 0.5]), [1, 0]))45 assert(dr.allclose(mi.warp.square_to_uniform_triangle([1, 1]), [1, 0]))46 check_inverse(mi.warp.square_to_uniform_triangle, mi.warp.uniform_triangle_to_square)47 check_warp_vectorization("square_to_uniform_triangle")48def test_interval_to_tent(variant_scalar_rgb):49 assert(dr.allclose(mi.warp.interval_to_tent(0.5), 0))50 assert(dr.allclose(mi.warp.interval_to_tent(0), -1))51 assert(dr.allclose(mi.warp.interval_to_tent(1), 1))52def test_interval_to_nonuniform_tent(variant_scalar_rgb):53 assert(dr.allclose(mi.warp.interval_to_nonuniform_tent(0, 0.5, 1, 0.499), 0.499, atol=1e-3))54 assert(dr.allclose(mi.warp.interval_to_nonuniform_tent(0, 0.5, 1, 0), 0))55 assert(dr.allclose(mi.warp.interval_to_nonuniform_tent(0, 0.5, 1, 0.5), 1))56def test_square_to_tent(variant_scalar_rgb):57 assert(dr.allclose(mi.warp.square_to_tent([0.5, 0.5]), [0, 0]))58 assert(dr.allclose(mi.warp.square_to_tent([0, 0.5]), [-1, 0]))59 assert(dr.allclose(mi.warp.square_to_tent([1, 0]), [1, -1]))60 check_inverse(mi.warp.square_to_tent, mi.warp.tent_to_square)61 check_warp_vectorization("square_to_tent")62def test_square_to_uniform_sphere_vec(variant_scalar_rgb):63 assert(dr.allclose(mi.warp.square_to_uniform_sphere([0, 0]), [0, 0, 1]))64 assert(dr.allclose(mi.warp.square_to_uniform_sphere([0, 1]), [0, 0, -1]))65 assert(dr.allclose(mi.warp.square_to_uniform_sphere([0.5, 0.5]), [-1, 0, 0], atol=1e-7))66 check_inverse(mi.warp.square_to_uniform_sphere, mi.warp.uniform_sphere_to_square)67 check_warp_vectorization("square_to_uniform_sphere")68def test_square_to_uniform_hemisphere(variant_scalar_rgb):69 assert(dr.allclose(mi.warp.square_to_uniform_hemisphere([0.5, 0.5]), [0, 0, 1]))70 assert(dr.allclose(mi.warp.square_to_uniform_hemisphere([0, 0.5]), [-1, 0, 0]))71 check_inverse(mi.warp.square_to_uniform_hemisphere, mi.warp.uniform_hemisphere_to_square)72 check_warp_vectorization("square_to_uniform_hemisphere")73def test_square_to_cosine_hemisphere(variant_scalar_rgb):74 assert(dr.allclose(mi.warp.square_to_cosine_hemisphere([0.5, 0.5]), [0, 0, 1]))75 assert(dr.allclose(mi.warp.square_to_cosine_hemisphere([0.5, 0]), [0, -1, 0], atol=1e-7))76 check_inverse(mi.warp.square_to_cosine_hemisphere, mi.warp.cosine_hemisphere_to_square)77 check_warp_vectorization("square_to_cosine_hemisphere", atol=1e-5)78def test_square_to_uniform_cone(variant_scalar_rgb):79 assert(dr.allclose(mi.warp.square_to_uniform_cone([0.5, 0.5], 1), [0, 0, 1]))80 assert(dr.allclose(mi.warp.square_to_uniform_cone([0.5, 0], 1), [0, 0, 1], atol=1e-7))81 assert(dr.allclose(mi.warp.square_to_uniform_cone([0.5, 0], 0), [0, -1, 0], atol=1e-7))82 fwd = lambda v: mi.warp.square_to_uniform_cone(v, 0.3)83 inv = lambda v: mi.warp.uniform_cone_to_square(v, 0.3)84 check_inverse(fwd, inv)85 wrapper = lambda f: lambda x: f(x, 0.3)86 check_warp_vectorization("square_to_uniform_cone", wrapper)87def test_square_to_beckmann(variant_scalar_rgb):88 fwd = lambda v: mi.warp.square_to_beckmann(v, 0.3)89 pdf = lambda v: mi.warp.square_to_beckmann_pdf(v, 0.3)90 inv = lambda v: mi.warp.beckmann_to_square(v, 0.3)91 check_inverse(fwd, inv)92 wrapper = lambda f: lambda x: f(x, 0.3)93 check_warp_vectorization("square_to_beckmann", wrapper, atol=1e-5)94def test_square_to_von_mises_fisher(variant_scalar_rgb):95 fwd = lambda v: mi.warp.square_to_von_mises_fisher(v, 10)96 pdf = lambda v: mi.warp.square_to_von_mises_fisher_pdf(v, 10)97 inv = lambda v: mi.warp.von_mises_fisher_to_square(v, 10)98 check_inverse(fwd, inv)99 wrapper = lambda f: lambda x: f(x, 10)100 check_warp_vectorization("square_to_von_mises_fisher", wrapper)101def test_square_to_std_normal_pdf(variant_scalar_rgb):102 assert(dr.allclose(mi.warp.square_to_std_normal_pdf([0, 0]), 0.16, atol=1e-2))103 assert(dr.allclose(mi.warp.square_to_std_normal_pdf([0, 0.8]), 0.12, atol=1e-2))104 assert(dr.allclose(mi.warp.square_to_std_normal_pdf([0.8, 0]), 0.12, atol=1e-2))105def test_square_to_std_normal(variant_scalar_rgb):106 assert(dr.allclose(mi.warp.square_to_std_normal([0, 0]), [0, 0]))107 assert(dr.allclose(mi.warp.square_to_std_normal([0, 1]), [0, 0]))108 assert(dr.allclose(mi.warp.square_to_std_normal([0.39346, 0]), [1, 0], atol=1e-3))109def test_interval_to_linear(variant_scalar_rgb):110 x = mi.warp.interval_to_linear(3, 5., .3)111 assert dr.allclose(mi.warp.linear_to_interval(3, 5, x), .3)112def test_square_to_bilinear(variant_scalar_rgb):113 # Reference values generated by Mathematica114 values = [1, 3, 5, 7]115 p, pdf = mi.warp.square_to_bilinear(*values, [0.3, 0.2])116 assert dr.allclose(p.y, 0.306226)117 assert dr.allclose(p.x, 0.372479)118 assert dr.allclose(pdf, 2.96986)119 p2, pdf2 = mi.warp.bilinear_to_square(*values, p)120 assert dr.allclose(p2.y, 0.2)121 assert dr.allclose(p2.x, 0.3)122 assert dr.allclose(pdf2, pdf)123 pdf3 = mi.warp.square_to_bilinear_pdf(*values, p),...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { getStorybookUI, configure } from '@storybook/react-native';2import { loadStories } from './storyLoader';3configure(() => {4 loadStories();5}, module);6const StorybookUIRoot = getStorybookUI({ port: 7007, host: 'localhost' });7export default StorybookUIRoot;8import { loadStories } from './index';9export { loadStories };10import { configure } from '@storybook/react-native';11function loadStories() {12 require('./stories');13}14configure(loadStories, module);15import { storiesOf } from '@storybook/react-native';16import React from 'react';17import { Text } from 'react-native';18storiesOf('Welcome', module).add('to Storybook', () => (19));20import { configure } from '@storybook/react';21configure(require.context('../src', true, /\.stories\.js$/), module);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { getStorybookUI, configure } from '@storybook/react-native';2import { loadStories } from './storyLoader';3import './rn-addons';4configure(() => {5 loadStories();6}, module);7const StorybookUIRoot = getStorybookUI({ port: 7007, onDeviceUI: true });8export default StorybookUIRoot;9import { configure } from '@storybook/react-native';10import { addDecorator } from '@storybook/react';11import { withKnobs } from '@storybook/addon-knobs';12import { withA11y } from '@storybook/addon-a11y';13addDecorator(withKnobs);14addDecorator(withA11y);15configure(() => {16 require('../src/stories');17}, module);18import { setOptions } from '@storybook/addon-options';19setOptions({

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { withInfo } from '@storybook/addon-info';4import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';5import { Text } from '../src/components/Text';6storiesOf('Text', module)7 .addDecorator(withKnobs)8 .add(9 withInfo('Text')(() => (10 size={number('size', 14)}11 color={text('color', 'black')}12 bold={boolean('bold', false)}13 {text('text', 'Hello World')}14 );15{16 "dependencies": {17 },18 "devDependencies": {19 },20 "scripts": {21 }22}23import { configure } from '@storybook/react';24const req = require.context('../src/components', true, /.stories.js$/);25function loadStories() {26 req.keys().forEach(filename => req(filename));27}28configure(loadStories, module);29module.exports = async ({ config, mode }) => {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from '@storybook/react';2import { withInfo } from '@storybook/addon-info';3import { withKnobs } from '@storybook/addon-knobs';4import { withA11y } from '@storybook/addon-a11y';5import { withConsole } from '@storybook/addon-console';6import { withTests } from '@storybook/addon-jest';7import { withOptions } from '@storybook/addon-options';8import { withViewport } from '@storybook/addon-viewport';9addDecorator(withInfo);10addDecorator(withKnobs);11addDecorator(withA11y);12addDecorator(withConsole);13addDecorator(withTests);14addDecorator(withOptions);15addDecorator(withViewport);16import { configure, addDecorator } from '@storybook/react';17import { withInfo } from '@storybook/addon-info';18import { withKnobs } from '@storybook/addon-knobs';19import { withA11y } from '@storybook/addon-a11y';20import { withConsole } from '@storybook/addon-console';21import { withTests } from '@storybook/addon-jest';22import { withOptions } from '@storybook/addon-options';23import { withViewport } from '@storybook/addon-viewport';24addDecorator(withInfo);25addDecorator(withKnobs);26addDecorator(withA11y);27addDecorator(withConsole);28addDecorator(withTests);29addDecorator(withOptions);30addDecorator(withViewport);31import 'storybook-addon-jsx/register';32const req = require.context('../stories', true, /\.stories\.js$/);33function loadStories() {34 req.keys().forEach(filename => req(filename));35}36configure(loadStories, module);37import { addDecorator } from '@storybook/react';38import { withInfo } from '@storybook/addon-info';39import { withKnobs } from '@storybook/addon-knobs';40import { withA11y } from '@storybook/addon-a11y';41import { withConsole } from '@storybook/addon-console';42import { withTests } from '@storybook/addon-jest';43import { withOptions } from '@storybook/addon-options';44import { withViewport } from '@storybook/addon-viewport';45addDecorator(withInfo);46addDecorator(with

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';2storiesOf('Button', module)3 .addDecorator(withKnobs)4 .add('with text', () => (5 <Button disabled={boolean('Disabled', false)}>6 {text('Label', 'Hello Storybook')}7 .add('with some emoji', () => (8 <Button disabled={boolean('Disabled', false)}>9 ));10import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';11storiesOf('Button', module)12 .addDecorator(withKnobs)13 .add('with text', () => (14 <Button disabled={boolean('Disabled', false)}>15 {text('Label', 'Hello Storybook')}16 .add('with some emoji', () => (17 <Button disabled={boolean('Disabled', false)}>18 ));19import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';20storiesOf('Button', module)21 .addDecorator(withKnobs)22 .add('with text', () => (23 <Button disabled={boolean('Disabled', false)}>24 {text('Label', 'Hello Storybook')}25 .add('with some emoji', () => (26 <Button disabled={boolean('Disabled', false)}>27 ));28import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';29storiesOf('Button', module)30 .addDecorator(withKnobs)31 .add('with text', () => (32 <Button disabled={boolean('Disabled', false)}>33 {text('Label', 'Hello Storybook')}34 .add('with some emoji',

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { withKnobs, text, boolean, number } from '@storybook/addon-knobs/react';3import { action } from '@storybook/addon-actions';4import { withInfo } from '@storybook/addon-info';5storiesOf('Test', module)6 .addDecorator(withKnobs)7 .addDecorator(withInfo)8 .add('test', () => (9 ));10import '@storybook/addon-knobs/register';11import '@storybook/addon-actions/register';12import '@storybook/addon-info/register';13import { configure } from '@storybook/react';14import { setOptions } from '@storybook/addon-options';15setOptions({16});17function loadStories() {18 require('../test.js');19}20configure(loadStories, module);21{22 "scripts": {23 },24 "devDependencies": {25 }26}

Full Screen

Using AI Code Generation

copy

Full Screen

1import { addDecorator } from '@storybook/react';2import { withRoot } from './storybook-root-decorator';3addDecorator(withRoot);4import { withRoot } from './storybook-addon-decorator';5export default {6};7import { withRoot } from './storybook-addon-decorator';8storiesOf('Example/Example', module).addDecorator(withRoot).add('Example', () => <Example />);9import { withRoot } from './storybook-addon-decorator';10storiesOf('Example/Example', module).add('Example', () => <Example />, { decorators: [withRoot] });11import { withRoot } from './storybook-addon-decorator';12storiesOf('Example/Example', module)13 .addDecorator(withRoot)14 .addDecorator(withRoot)15 .add('Example', () => <Example />);16import { withRoot } from './storybook-addon-decorator';17storiesOf('Example/Example', module)18 .add('Example', () => <Example />, { decorators: [withRoot] })19 .add('Example', () => <Example />, { decorators: [withRoot] });20import { withRoot } from './storybook-addon-decorator';21storiesOf('Example/Example', module)22 .addDecorator(withRoot)23 .addDecorator(withRoot)24 .add('Example', () => <Example />, { decorators: [withRoot] })25 .add('Example', () => <Example />, { decorators: [withRoot] });26import { withRoot } from './storybook-addon-decorator';27storiesOf('Example/Example', module)28 .addDecorator(withRoot)29 .addDecorator(withRoot)30 .addDecorator(withRoot)31 .addDecorator(withRoot)32 .add('Example', () => <Example />, { decorators: [withRoot] })33 .add('Example', () => <Example />,

Full Screen

Using AI Code Generation

copy

Full Screen

1import { withKnobs, text } from '@storybook/addon-knobs';2import { storiesOf } from '@storybook/vue';3import Vue from 'vue';4import MyComponent from './MyComponent.vue';5Vue.component('my-component', MyComponent);6storiesOf('MyComponent', module)7 .addDecorator(withKnobs)8 .add('simple', () => ({9 props: {10 title: {11 default: text('Title', 'Hello World'),12 },13 },14 }));15 <h1>{{ title }}</h1>16export default {17 props: {18 title: {19 },20 },21};22{23 "scripts": {24 },25 "devDependencies": {26 },27}28module.exports = {29};30import { addDecorator } from '@storybook/vue';31import { withKnobs } from '@storybook/addon-knobs';32addDecorator(withKnobs);33module.exports = ({ config }) => {34 config.module.rules.push({35 });36 return config;37};38{39 "compilerOptions": {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storybookRoot } from 'storybook-root';2import { storiesOf } from '@storybook/react';3storiesOf('Test', module)4 .add('test', () => {5 return (6 <button onClick={storybookRoot.open}>Open Storybook</button>7 );8 });9import { configure } from '@storybook/react';10const storybookRoot = {11 open: () => {12 const storybookRoot = document.getElementById('storybook-root');13 storybookRoot.style.display = 'block';14 configure(() => {15 const req = require.context('../src', true, /.stories.js$/);16 req.keys().forEach(filename => req(filename));17 }, module);18 },19};20export { storybookRoot };

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful