matplotlib-rs 0.0.8__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (352) hide show
  1. docs/releases/0.0.1.md +268 -0
  2. docs/releases/0.0.2.md +69 -0
  3. docs/releases/0.0.3.md +80 -0
  4. docs/releases/0.0.4.md +73 -0
  5. docs/releases/0.0.5.md +24 -0
  6. docs/releases/0.0.6.md +24 -0
  7. docs/releases/0.0.7.md +24 -0
  8. docs/releases/0.0.8.md +16 -0
  9. licenses/LICENSE_CONTOURPY +29 -0
  10. licenses/LICENSE_CYCLER +27 -0
  11. licenses/LICENSE_DATEUTIL +54 -0
  12. licenses/LICENSE_KIWISOLVER +71 -0
  13. licenses/LICENSE_LIBWEBP +56 -0
  14. licenses/LICENSE_MATPLOTLIB +1253 -0
  15. licenses/LICENSE_PYPARSING +20 -0
  16. licenses/LICENSE_QHULL +39 -0
  17. licenses/LICENSE_SIX +18 -0
  18. matplotlib_rs/__init__.py +1683 -0
  19. matplotlib_rs/__main__.py +27 -0
  20. matplotlib_rs/_afm.py +500 -0
  21. matplotlib_rs/_animation_data.py +263 -0
  22. matplotlib_rs/_api/__init__.py +495 -0
  23. matplotlib_rs/_api/deprecation.py +534 -0
  24. matplotlib_rs/_axis_py.py +2991 -0
  25. matplotlib_rs/_blocking_input.py +31 -0
  26. matplotlib_rs/_cm.py +1500 -0
  27. matplotlib_rs/_cm_bivar.py +1289 -0
  28. matplotlib_rs/_cm_listed.py +2848 -0
  29. matplotlib_rs/_cm_multivar.py +167 -0
  30. matplotlib_rs/_color_data.py +1142 -0
  31. matplotlib_rs/_colormap.py +132 -0
  32. matplotlib_rs/_constrained_layout.py +825 -0
  33. matplotlib_rs/_contour.py +108 -0
  34. matplotlib_rs/_doc_cache.py +12214 -0
  35. matplotlib_rs/_docstring.py +142 -0
  36. matplotlib_rs/_enums.py +178 -0
  37. matplotlib_rs/_figure_rs.py +294 -0
  38. matplotlib_rs/_fontconfig_pattern.py +129 -0
  39. matplotlib_rs/_foreign.py +220 -0
  40. matplotlib_rs/_hook.py +94 -0
  41. matplotlib_rs/_image.py +160 -0
  42. matplotlib_rs/_imageio.py +229 -0
  43. matplotlib_rs/_internal_utils.py +65 -0
  44. matplotlib_rs/_kiwi.py +484 -0
  45. matplotlib_rs/_layoutgrid.py +549 -0
  46. matplotlib_rs/_live.py +192 -0
  47. matplotlib_rs/_mathtext.py +3103 -0
  48. matplotlib_rs/_mathtext_data.py +1811 -0
  49. matplotlib_rs/_mplrs.cp313-win_amd64.pyd +0 -0
  50. matplotlib_rs/_path.py +25 -0
  51. matplotlib_rs/_png.py +162 -0
  52. matplotlib_rs/_pylab_helpers.py +137 -0
  53. matplotlib_rs/_qhull.py +66 -0
  54. matplotlib_rs/_rcpush.py +84 -0
  55. matplotlib_rs/_spines_rs.py +108 -0
  56. matplotlib_rs/_style_helpers.py +52 -0
  57. matplotlib_rs/_text_helpers.py +51 -0
  58. matplotlib_rs/_tight_bbox.py +85 -0
  59. matplotlib_rs/_tight_layout.py +302 -0
  60. matplotlib_rs/_tri.py +140 -0
  61. matplotlib_rs/_type1font.py +1228 -0
  62. matplotlib_rs/_vendor/__init__.py +8 -0
  63. matplotlib_rs/_vendor/cycler.py +574 -0
  64. matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
  65. matplotlib_rs/_vendor/dateutil/_common.py +44 -0
  66. matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
  67. matplotlib_rs/_vendor/dateutil/_version.py +5 -0
  68. matplotlib_rs/_vendor/dateutil/easter.py +90 -0
  69. matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
  70. matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
  71. matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
  72. matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
  73. matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
  74. matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
  75. matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
  76. matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
  77. matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
  78. matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
  79. matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
  80. matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
  81. matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
  82. matplotlib_rs/_vendor/dateutil/utils.py +72 -0
  83. matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
  84. matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
  85. matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
  86. matplotlib_rs/_vendor/pyparsing/common.py +571 -0
  87. matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
  88. matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
  89. matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
  90. matplotlib_rs/_vendor/pyparsing/results.py +929 -0
  91. matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
  92. matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
  93. matplotlib_rs/_vendor/pyparsing/util.py +515 -0
  94. matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
  95. matplotlib_rs/_vendor/six.py +1004 -0
  96. matplotlib_rs/animation.py +1843 -0
  97. matplotlib_rs/artist.py +2302 -0
  98. matplotlib_rs/axes/__init__.py +19 -0
  99. matplotlib_rs/axes/_axes.py +9402 -0
  100. matplotlib_rs/axes/_bar.py +185 -0
  101. matplotlib_rs/axes/_base.py +5236 -0
  102. matplotlib_rs/axes/_base_rs.py +727 -0
  103. matplotlib_rs/axes/_boxplot.py +391 -0
  104. matplotlib_rs/axes/_hist.py +99 -0
  105. matplotlib_rs/axes/_secondary_axes.py +357 -0
  106. matplotlib_rs/axis.py +1963 -0
  107. matplotlib_rs/backend_bases.py +3760 -0
  108. matplotlib_rs/backend_managers.py +388 -0
  109. matplotlib_rs/backend_tools.py +1002 -0
  110. matplotlib_rs/backends/__init__.py +6 -0
  111. matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
  112. matplotlib_rs/backends/backend_agg.py +552 -0
  113. matplotlib_rs/backends/backend_mixed.py +123 -0
  114. matplotlib_rs/backends/backend_pdf.py +2711 -0
  115. matplotlib_rs/backends/backend_pgf.py +1031 -0
  116. matplotlib_rs/backends/backend_ps.py +1491 -0
  117. matplotlib_rs/backends/backend_svg.py +1395 -0
  118. matplotlib_rs/backends/backend_template.py +214 -0
  119. matplotlib_rs/backends/registry.py +423 -0
  120. matplotlib_rs/bezier.py +691 -0
  121. matplotlib_rs/category.py +236 -0
  122. matplotlib_rs/cbook.py +2762 -0
  123. matplotlib_rs/cm.py +251 -0
  124. matplotlib_rs/collections.py +2711 -0
  125. matplotlib_rs/colorbar.py +1586 -0
  126. matplotlib_rs/colorizer.py +909 -0
  127. matplotlib_rs/colors.py +4278 -0
  128. matplotlib_rs/container.py +256 -0
  129. matplotlib_rs/contour.py +1756 -0
  130. matplotlib_rs/dates.py +1847 -0
  131. matplotlib_rs/dviread.py +1386 -0
  132. matplotlib_rs/figure.py +3815 -0
  133. matplotlib_rs/font_manager.py +1855 -0
  134. matplotlib_rs/ft2font.py +515 -0
  135. matplotlib_rs/gridspec.py +808 -0
  136. matplotlib_rs/hatch.py +244 -0
  137. matplotlib_rs/image.py +1863 -0
  138. matplotlib_rs/inset.py +291 -0
  139. matplotlib_rs/layout_engine.py +310 -0
  140. matplotlib_rs/legend.py +1480 -0
  141. matplotlib_rs/legend_handler.py +812 -0
  142. matplotlib_rs/lines.py +1886 -0
  143. matplotlib_rs/markers.py +908 -0
  144. matplotlib_rs/mathtext.py +141 -0
  145. matplotlib_rs/mlab.py +959 -0
  146. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
  147. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
  148. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
  149. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
  150. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
  151. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
  152. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
  153. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
  154. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
  155. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
  156. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
  157. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
  158. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
  159. matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
  160. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
  161. matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
  162. matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
  163. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
  164. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
  165. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
  166. matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
  167. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
  168. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
  169. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
  170. matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
  171. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
  172. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
  173. matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
  174. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
  175. matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
  176. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
  177. matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
  178. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
  179. matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
  180. matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
  181. matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
  182. matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
  183. matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
  184. matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
  185. matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
  186. matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
  187. matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
  188. matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
  189. matplotlib_rs/mpl-data/images/back.pdf +0 -0
  190. matplotlib_rs/mpl-data/images/back.png +0 -0
  191. matplotlib_rs/mpl-data/images/back.svg +46 -0
  192. matplotlib_rs/mpl-data/images/back_large.png +0 -0
  193. matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
  194. matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
  195. matplotlib_rs/mpl-data/images/filesave.png +0 -0
  196. matplotlib_rs/mpl-data/images/filesave.svg +68 -0
  197. matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
  198. matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
  199. matplotlib_rs/mpl-data/images/forward.pdf +0 -0
  200. matplotlib_rs/mpl-data/images/forward.png +0 -0
  201. matplotlib_rs/mpl-data/images/forward.svg +46 -0
  202. matplotlib_rs/mpl-data/images/forward_large.png +0 -0
  203. matplotlib_rs/mpl-data/images/hand.pdf +0 -0
  204. matplotlib_rs/mpl-data/images/hand.png +0 -0
  205. matplotlib_rs/mpl-data/images/hand.svg +130 -0
  206. matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
  207. matplotlib_rs/mpl-data/images/help.pdf +71 -0
  208. matplotlib_rs/mpl-data/images/help.png +0 -0
  209. matplotlib_rs/mpl-data/images/help.svg +52 -0
  210. matplotlib_rs/mpl-data/images/help_large.png +0 -0
  211. matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
  212. matplotlib_rs/mpl-data/images/home.pdf +0 -0
  213. matplotlib_rs/mpl-data/images/home.png +0 -0
  214. matplotlib_rs/mpl-data/images/home.svg +59 -0
  215. matplotlib_rs/mpl-data/images/home_large.png +0 -0
  216. matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
  217. matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
  218. matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
  219. matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
  220. matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
  221. matplotlib_rs/mpl-data/images/move.pdf +0 -0
  222. matplotlib_rs/mpl-data/images/move.png +0 -0
  223. matplotlib_rs/mpl-data/images/move.svg +73 -0
  224. matplotlib_rs/mpl-data/images/move_large.png +0 -0
  225. matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
  226. matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
  227. matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
  228. matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
  229. matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
  230. matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
  231. matplotlib_rs/mpl-data/images/subplots.png +0 -0
  232. matplotlib_rs/mpl-data/images/subplots.svg +81 -0
  233. matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
  234. matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
  235. matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
  236. matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
  237. matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
  238. matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
  239. matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
  240. matplotlib_rs/mpl-data/matplotlibrc +849 -0
  241. matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
  242. matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
  243. matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
  244. matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
  245. matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
  246. matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
  247. matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
  248. matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
  249. matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
  250. matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
  251. matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
  252. matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
  253. matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
  254. matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
  255. matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
  256. matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
  257. matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
  258. matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
  259. matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
  260. matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
  261. matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
  262. matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
  263. matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
  264. matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
  265. matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
  266. matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
  267. matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
  268. matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
  269. matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
  270. matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
  271. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
  272. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
  273. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
  274. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
  275. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
  276. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
  277. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
  278. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
  279. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
  280. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
  281. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
  282. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
  283. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
  284. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
  285. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
  286. matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
  287. matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
  288. matplotlib_rs/mpl_toolkits/__init__.py +3 -0
  289. matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
  290. matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
  291. matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
  292. matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
  293. matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
  294. matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
  295. matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
  296. matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
  297. matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
  298. matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
  299. matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
  300. matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
  301. matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
  302. matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
  303. matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
  304. matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
  305. matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
  306. matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
  307. matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
  308. matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
  309. matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
  310. matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
  311. matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
  312. matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
  313. matplotlib_rs/offsetbox.py +1726 -0
  314. matplotlib_rs/patches.py +5049 -0
  315. matplotlib_rs/path.py +1147 -0
  316. matplotlib_rs/patheffects.py +512 -0
  317. matplotlib_rs/projections/__init__.py +126 -0
  318. matplotlib_rs/projections/geo.py +512 -0
  319. matplotlib_rs/projections/polar.py +1518 -0
  320. matplotlib_rs/pylab.py +68 -0
  321. matplotlib_rs/pyplot.py +4834 -0
  322. matplotlib_rs/quiver.py +1236 -0
  323. matplotlib_rs/rcsetup.py +3435 -0
  324. matplotlib_rs/sankey.py +815 -0
  325. matplotlib_rs/scale.py +1002 -0
  326. matplotlib_rs/spines.py +618 -0
  327. matplotlib_rs/stackplot.py +144 -0
  328. matplotlib_rs/streamplot.py +768 -0
  329. matplotlib_rs/style/__init__.py +269 -0
  330. matplotlib_rs/style/core.py +28 -0
  331. matplotlib_rs/table.py +860 -0
  332. matplotlib_rs/texmanager.py +375 -0
  333. matplotlib_rs/text.py +2412 -0
  334. matplotlib_rs/textpath.py +377 -0
  335. matplotlib_rs/ticker.py +3111 -0
  336. matplotlib_rs/transforms.py +3069 -0
  337. matplotlib_rs/tri/__init__.py +24 -0
  338. matplotlib_rs/tri/_triangulation.py +248 -0
  339. matplotlib_rs/tri/_tricontour.py +271 -0
  340. matplotlib_rs/tri/_trifinder.py +97 -0
  341. matplotlib_rs/tri/_triinterpolate.py +1575 -0
  342. matplotlib_rs/tri/_tripcolor.py +170 -0
  343. matplotlib_rs/tri/_triplot.py +87 -0
  344. matplotlib_rs/tri/_trirefine.py +308 -0
  345. matplotlib_rs/tri/_tritools.py +264 -0
  346. matplotlib_rs/typing.py +597 -0
  347. matplotlib_rs/units.py +196 -0
  348. matplotlib_rs/widgets.py +4455 -0
  349. matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
  350. matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
  351. matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
  352. matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
@@ -0,0 +1,1429 @@
1
+ # Vendored by tools/vendor_deps.py from python-dateutil 3.0.0 (see licenses/LICENSE_DATEUTIL).
2
+ # -*- coding: utf-8 -*-
3
+ import bisect
4
+ import calendar
5
+ import functools
6
+ import io
7
+ import os
8
+ import re
9
+ import stat
10
+ import struct
11
+ import sys
12
+ from datetime import MAXYEAR, MINYEAR, datetime, timedelta
13
+
14
+ from matplotlib_rs._vendor import six
15
+
16
+ from ._common import _tzinfo, enfold, tzname_in_python2
17
+
18
+ EPOCH = datetime(1970, 1, 1)
19
+ EPOCHORDINAL = EPOCH.toordinal()
20
+
21
+ # TODO: Move this to _common.py
22
+ try:
23
+ # Python 3.7 feature
24
+ from contextlib import nullcontext as _nullcontext
25
+ except ImportError:
26
+ import contextlib
27
+
28
+ @contextlib.contextmanager
29
+ def _nullcontext(context):
30
+ yield context
31
+
32
+
33
+ # It is relatively expensive to construct new timedelta objects, and in most
34
+ # cases we're looking at the same deltas, like integer numbers of hours, etc.
35
+ # To improve speed and memory use, we'll keep a dictionary with references
36
+ # to the ones we've already used so far.
37
+ #
38
+ # Loading every time zone in the 2020a version of the time zone database
39
+ # requires 447 timedeltas, which requires approximately the amount of space
40
+ # that ZoneInfo("America/New_York") with 236 transitions takes up, so we will
41
+ # set the cache size to 512 so that in the common case we always get cache
42
+ # hits, but specifically crafted ZoneInfo objects don't leak arbitrary amounts
43
+ # of memory.
44
+ _TIMEDELTA_CACHE_SIZE = 512
45
+ if six.PY2:
46
+
47
+ def _cache_load_timedelta(f):
48
+ from collections import OrderedDict
49
+
50
+ from matplotlib_rs._vendor.six.moves import _thread
51
+
52
+ CACHE_LOCK = _thread.allocate_lock()
53
+ TIMEDELTA_CACHE = OrderedDict()
54
+
55
+ @functools.wraps(f)
56
+ def cached_load_timedelta(seconds):
57
+ # OrderedDict is implemented in Python on Python 2, so every
58
+ # access has to hold the lock to keep its linked list intact.
59
+ with CACHE_LOCK:
60
+ rv = TIMEDELTA_CACHE.pop(seconds, None)
61
+ if rv is None:
62
+ rv = f(seconds)
63
+
64
+ TIMEDELTA_CACHE[seconds] = rv
65
+
66
+ if len(TIMEDELTA_CACHE) > _TIMEDELTA_CACHE_SIZE:
67
+ TIMEDELTA_CACHE.popitem(last=False)
68
+
69
+ return rv
70
+
71
+ return cached_load_timedelta
72
+
73
+ else:
74
+ _cache_load_timedelta = functools.lru_cache(maxsize=512)
75
+
76
+
77
+ @_cache_load_timedelta
78
+ def _load_timedelta(seconds):
79
+ return timedelta(seconds=seconds)
80
+
81
+
82
+ def _unpickle(cls, key, filename, data):
83
+ obj = cls.__new__(cls)
84
+ obj._key = key
85
+ obj._filename = filename
86
+
87
+ obj._load_from_data(data)
88
+
89
+ return obj
90
+
91
+
92
+ class tzfile(_tzinfo):
93
+ """
94
+ This is a ``tzinfo`` subclass that allows one to use the ``tzfile(5)``
95
+ format timezone files to extract current and historical zone information.
96
+
97
+ :param fileobj:
98
+ This can be an opened file stream or a file name that the time zone
99
+ information can be read from.
100
+
101
+ :param filename:
102
+ This is an optional parameter specifying the source of the time zone
103
+ information in the event that ``fileobj`` is a file object. If omitted
104
+ and ``fileobj`` is a file stream, this parameter will be set either to
105
+ ``fileobj``'s ``name`` attribute or to ``repr(fileobj)``.
106
+
107
+ This class is intended to be mostly equivalent to the standard library
108
+ :py:class:`zoneinfo.ZoneInfo` class. The primary differences are:
109
+
110
+ * All caching in ``tzfile`` is handled by :func:`tz.gettz` level (you
111
+ should generally not attempt to construct a ``tzfile`` directly).
112
+ * ``tzfile`` objects are pickled by value rather than by reference to
113
+ the IANA key.
114
+ * ``tzfile`` has equality-by-value semantics, whereas
115
+ :py:class:`~zoneinfo.ZoneInfo` has equality-by-identity semantics.
116
+
117
+ See `Sources for Time Zone and Daylight Saving Time Data
118
+ <https://data.iana.org/time-zones/tz-link.html>`_ for more information.
119
+ Time zone files can be compiled from the `IANA Time Zone database files
120
+ <https://www.iana.org/time-zones>`_ with the `zic time zone compiler
121
+ <https://www.freebsd.org/cgi/man.cgi?query=zic&sektion=8>`_
122
+
123
+ .. note::
124
+
125
+ Only construct a ``tzfile`` directly if you have a specific timezone
126
+ file on disk that you want to read into a Python ``tzinfo`` object.
127
+ If you want to get a ``tzfile`` representing a specific IANA zone,
128
+ (e.g. ``'America/New_York'``), you should call
129
+ :func:`dateutil.tz.gettz` with the zone identifier.
130
+
131
+ .. versionchanged:: 3.0.0
132
+ ``tzfile`` is now a partial backport of :py:class:`zoneinfo.ZoneInfo`,
133
+ which brings with it support for Version 2 and 3 ``tzfile(5)`` binaries.
134
+
135
+ **Examples:**
136
+
137
+ Using the US Eastern time zone as an example, we can see that a ``tzfile``
138
+ provides time zone information for the standard Daylight Saving offsets:
139
+
140
+ .. testsetup:: tzfile
141
+
142
+ from matplotlib_rs._vendor.dateutil.tz import gettz
143
+ from datetime import datetime
144
+
145
+ .. doctest:: tzfile
146
+
147
+ >>> NYC = gettz('America/New_York')
148
+ >>> NYC
149
+ tzfile('/usr/share/zoneinfo/America/New_York')
150
+
151
+ >>> print(datetime(2016, 1, 3, tzinfo=NYC)) # EST
152
+ 2016-01-03 00:00:00-05:00
153
+
154
+ >>> print(datetime(2016, 7, 7, tzinfo=NYC)) # EDT
155
+ 2016-07-07 00:00:00-04:00
156
+
157
+
158
+ The ``tzfile`` structure contains a fully history of the time zone,
159
+ so historical dates will also have the right offsets. For example, before
160
+ the adoption of standard time on November 18, 1883, New York used local
161
+ mean time:
162
+
163
+ .. doctest:: tzfile
164
+
165
+ >>> print(datetime(1883, 11, 18, tzinfo=NYC)) # LMT
166
+ 1883-11-18 00:00:00-04:56:02
167
+
168
+ Python versions before 3.6 do not support sub-minute offsets, so there the
169
+ offset is rounded to ``-04:56``.
170
+
171
+ And during World War II, New York was on "Eastern War Time", which was a
172
+ state of permanent daylight saving time:
173
+
174
+ .. doctest:: tzfile
175
+
176
+ >>> print(datetime(1944, 2, 7, tzinfo=NYC)) # EWT
177
+ 1944-02-07 00:00:00-04:00
178
+
179
+ """
180
+
181
+ def __init__(self, fileobj, filename=None, key=None):
182
+ super(tzfile, self).__init__()
183
+
184
+ file_opened_here = False
185
+ if isinstance(fileobj, six.string_types):
186
+ self._filename = fileobj
187
+ fileobj = open(fileobj, "rb")
188
+ file_opened_here = True
189
+ elif filename is not None:
190
+ self._filename = filename
191
+ elif hasattr(fileobj, "name"):
192
+ self._filename = fileobj.name
193
+ elif key is not None:
194
+ self._filename = key
195
+ else:
196
+ self._filename = repr(fileobj)
197
+
198
+ if fileobj is not None:
199
+ if not file_opened_here:
200
+ fileobj = _nullcontext(fileobj)
201
+
202
+ with fileobj as file_stream:
203
+ self._load_file(file_stream)
204
+
205
+ self._key = key
206
+
207
+ @property
208
+ def key(self):
209
+ """
210
+ Read-only attribute returning the ``key`` constructor argument.
211
+
212
+ For zones generated from :func:`gettz`, this will be the IANA key
213
+ passed to ``gettz`` — no normalization is done, so although in most
214
+ distributions of the time zone database "US/Eastern" is a link to
215
+ "America/New_York", ``tz.gettz("US/Eastern").key`` should always return
216
+ ``"US/Eastern"``.
217
+
218
+ For zones constructed via another mechanism without specifying ``key``,
219
+ this returns :obj:`None`.
220
+ """
221
+ return self._key
222
+
223
+ def is_ambiguous(self, dt):
224
+ """
225
+ Whether or not the "wall time" of a given datetime is ambiguous in this
226
+ zone.
227
+
228
+ :param dt:
229
+ A :py:class:`datetime.datetime`, naive or time zone aware.
230
+
231
+
232
+ :return:
233
+ Returns ``True`` if ambiguous, ``False`` otherwise.
234
+
235
+ .. versionadded:: 2.6.0
236
+ """
237
+ return self._is_ambiguous_or_imaginary(dt) == 1
238
+
239
+ def _is_ambiguous_or_imaginary(self, dt):
240
+ if dt is None or self._fixed_offset:
241
+ return 0
242
+
243
+ timestamp = self._get_local_timestamp(dt)
244
+ tti_0 = self._find_trans(dt, fold=0, timestamp=timestamp)
245
+ tti_1 = self._find_trans(dt, fold=1, timestamp=timestamp)
246
+
247
+ # Returns 1 if ambiguous, -1 if imaginary and 0 otherwise.
248
+ return int(tti_0.utcoff > tti_1.utcoff) - int(
249
+ tti_1.utcoff > tti_0.utcoff
250
+ )
251
+
252
+ def utcoffset(self, dt):
253
+ return self._find_trans(dt).utcoff
254
+
255
+ def dst(self, dt):
256
+ return self._find_trans(dt).dstoff
257
+
258
+ @tzname_in_python2
259
+ def tzname(self, dt):
260
+ return self._find_trans(dt).tzname
261
+
262
+ def fromutc(self, dt):
263
+ """
264
+ The ``tzfile`` implementation of :py:func:`datetime.tzinfo.fromutc`.
265
+
266
+ :param dt:
267
+ A :py:class:`datetime.datetime` object.
268
+
269
+ :raises TypeError:
270
+ Raised if ``dt`` is not a :py:class:`datetime.datetime` object.
271
+
272
+ :raises ValueError:
273
+ Raised if this is called with a ``dt`` which does not have this
274
+ ``tzinfo`` attached.
275
+
276
+ :return:
277
+ Returns a :py:class:`datetime.datetime` object representing the
278
+ wall time in ``self``'s time zone.
279
+ """
280
+
281
+ if not isinstance(dt, datetime):
282
+ raise TypeError("fromutc() requires a datetime argument")
283
+ if dt.tzinfo is not self:
284
+ raise ValueError("dt.tzinfo is not self")
285
+
286
+ timestamp = self._get_local_timestamp(dt)
287
+ num_trans = len(self._trans_utc)
288
+
289
+ if num_trans >= 1 and timestamp < self._trans_utc[0]:
290
+ tti = self._tti_before
291
+ fold = 0
292
+ elif (
293
+ num_trans == 0 or timestamp > self._trans_utc[-1]
294
+ ) and not isinstance(self._tz_after, _ttinfo):
295
+ tti, fold = self._tz_after.get_trans_info_fromutc(
296
+ timestamp, dt.year
297
+ )
298
+
299
+ # The TZ string only knows about its own transitions, so check
300
+ # whether we are in a fold created by the last explicit one.
301
+ if num_trans and not fold:
302
+ if num_trans > 1:
303
+ tti_prev = self._ttinfos[-2]
304
+ else:
305
+ tti_prev = self._tti_before
306
+
307
+ shift = tti_prev.utcoff - tti.utcoff
308
+ fold = shift.total_seconds() > timestamp - self._trans_utc[-1]
309
+ elif num_trans == 0:
310
+ tti = self._tz_after
311
+ fold = 0
312
+ else:
313
+ idx = bisect.bisect_right(self._trans_utc, timestamp)
314
+
315
+ if num_trans > 1 and timestamp >= self._trans_utc[1]:
316
+ tti_prev, tti = self._ttinfos[idx - 2 : idx]
317
+ elif timestamp > self._trans_utc[-1]:
318
+ # Only reachable with exactly one transition, so the
319
+ # offset before it is _tti_before, not _ttinfos[-1].
320
+ tti_prev = self._tti_before
321
+ tti = self._tz_after
322
+ else:
323
+ tti_prev = self._tti_before
324
+ tti = self._ttinfos[0]
325
+
326
+ # Detect fold
327
+ shift = tti_prev.utcoff - tti.utcoff
328
+ fold = shift.total_seconds() > timestamp - self._trans_utc[idx - 1]
329
+ dt += tti.utcoff
330
+ if fold:
331
+ return enfold(dt, fold=1)
332
+ else:
333
+ return dt
334
+
335
+ def _find_trans(self, dt, fold=None, timestamp=None):
336
+ if dt is None:
337
+ if self._fixed_offset:
338
+ return self._tz_after
339
+ else:
340
+ return _NO_TTINFO
341
+
342
+ if timestamp is None:
343
+ ts = self._get_local_timestamp(dt)
344
+ else:
345
+ ts = timestamp
346
+
347
+ if fold is None:
348
+ fold = getattr(dt, "fold", 0)
349
+
350
+ lt = self._trans_local[fold]
351
+
352
+ num_trans = len(lt)
353
+
354
+ if num_trans and ts < lt[0]:
355
+ return self._tti_before
356
+ elif not num_trans or ts > lt[-1]:
357
+ if isinstance(self._tz_after, _TZStr):
358
+ tti = self._tz_after.get_trans_info(ts, dt.year, fold)
359
+
360
+ # The TZ string only describes times after the last explicit
361
+ # transition. If its answer for this local time is a different
362
+ # offset from the last transition's, and corresponds to a time
363
+ # before that transition (e.g. when the TZ string's own DST
364
+ # period for that year ends after the transition), the offset
365
+ # from the last explicit transition applies instead.
366
+ last_tti = self._ttinfos[-1] if num_trans else None
367
+ if (
368
+ last_tti is not None
369
+ and tti.utcoff != last_tti.utcoff
370
+ and ts - tti.utcoff.total_seconds() < self._trans_utc[-1]
371
+ ):
372
+ return last_tti
373
+
374
+ return tti
375
+ else:
376
+ return self._tz_after
377
+ else:
378
+ # idx is the transition that occurs after this timestamp, so we
379
+ # subtract off 1 to get the current ttinfo
380
+ idx = bisect.bisect_right(lt, ts) - 1
381
+ assert idx >= 0
382
+ return self._ttinfos[idx]
383
+
384
+ def _get_local_timestamp(self, dt):
385
+ return (
386
+ (dt.toordinal() - EPOCHORDINAL) * 86400
387
+ + dt.hour * 3600
388
+ + dt.minute * 60
389
+ + dt.second
390
+ )
391
+
392
+ # The attributes set by _unpickle and _load_from_data
393
+ _UNPICKLE_ATTRS = frozenset(
394
+ [
395
+ "_filename",
396
+ "_fixed_offset",
397
+ "_isdst",
398
+ "_key",
399
+ "_trans_idx",
400
+ "_trans_local",
401
+ "_trans_utc",
402
+ "_tti_before",
403
+ "_ttinfo_list",
404
+ "_ttinfos",
405
+ "_tz_after",
406
+ "_tz_str",
407
+ "_utcoff_raw",
408
+ ]
409
+ )
410
+
411
+ def __reduce__(self):
412
+ return self.__reduce_ex__(None)
413
+
414
+ def __reduce_ex__(self, protocol):
415
+ utcoff = [
416
+ int(ttinfo.utcoff.total_seconds()) for ttinfo in self._ttinfo_list
417
+ ]
418
+ utcoff = getattr(self, "_utcoff_raw", utcoff)
419
+ abbr = [ttinfo.tzname for ttinfo in self._ttinfo_list]
420
+
421
+ # dst() is inferred per transition, so the transitions don't map back
422
+ # to the local time types, and these are kept as they were in the file
423
+ trans_idx = self._trans_idx
424
+ isdst = self._isdst
425
+
426
+ trans_utc = self._trans_utc
427
+ tz_str = self._tz_str
428
+
429
+ data = (trans_idx, trans_utc, utcoff, isdst, abbr, tz_str)
430
+ args = (self.__class__, self._key, self._filename, data)
431
+
432
+ # Preserve any other instance state, such as attributes added by a
433
+ # subclass, but not the attributes that _unpickle rebuilds from data
434
+ state = {
435
+ k: v for k, v in vars(self).items() if k not in self._UNPICKLE_ATTRS
436
+ }
437
+ if state:
438
+ return (_unpickle, args, state)
439
+
440
+ return (_unpickle, args)
441
+
442
+ def _load_file(self, fobj):
443
+ # Reading the file requires seeking past the parts we don't use and
444
+ # reading the footer a line at a time, so read anything that doesn't
445
+ # support that (e.g. a pipe) into memory first; TZif files are small.
446
+ if not _is_seekable(fobj) or not hasattr(fobj, "readline"):
447
+ fobj = io.BytesIO(fobj.read())
448
+
449
+ # Retrieve all the data as it exists in the zoneinfo file
450
+ data = load_data(fobj)
451
+ self._load_from_data(data)
452
+
453
+ def _load_from_data(self, data):
454
+ trans_idx, trans_utc, utcoff, isdst, abbr, tz_str = data
455
+
456
+ # Infer the DST offsets (needed for .dst()) from the data, for each
457
+ # transition and for each local time type
458
+ trans_dstoff = self._utcoff_to_dstoff(
459
+ trans_idx, trans_utc, utcoff, isdst
460
+ )
461
+ dstoff = [3600 if dst else 0 for dst in isdst]
462
+ for idx, trans_off in zip(trans_idx, trans_dstoff):
463
+ dstoff[idx] = trans_off
464
+
465
+ if sys.version_info < (3, 6):
466
+ # For python pre-3.6, round to full-minutes if that's not the case.
467
+ # Python's datetime doesn't accept sub-minute timezones. Check
468
+ # http://python.org/sf/1447945 or https://bugs.python.org/issue5288
469
+ # for some information.
470
+ utcoff_adjusted = [60 * ((s + 30) // 60) for s in utcoff]
471
+ dstoff = [60 * ((s + 30) // 60) for s in dstoff]
472
+ trans_dstoff = [60 * ((s + 30) // 60) for s in trans_dstoff]
473
+ self._utcoff_raw = utcoff
474
+ else:
475
+ utcoff_adjusted = utcoff
476
+
477
+ # Convert all the transition times (UTC) into "seconds since 1970-01-01 local time"
478
+ trans_local = self._ts_to_local(trans_idx, trans_utc, utcoff_adjusted)
479
+
480
+ # Construct `_ttinfo` objects for each transition in the file
481
+ _ttinfo_list = [
482
+ _ttinfo(
483
+ _load_timedelta(utcoffset), _load_timedelta(dstoffset), tzname
484
+ )
485
+ for utcoffset, dstoffset, tzname in zip(
486
+ utcoff_adjusted, dstoff, abbr
487
+ )
488
+ ]
489
+
490
+ self._ttinfo_list = _ttinfo_list
491
+
492
+ self._trans_idx = trans_idx
493
+ self._isdst = isdst
494
+ self._trans_utc = trans_utc
495
+ self._trans_local = trans_local
496
+
497
+ # Transitions to the same local time type usually have the same DST
498
+ # offset, so share the _ttinfo objects between them where possible.
499
+ ttinfos = {}
500
+ self._ttinfos = []
501
+ for idx, trans_off in zip(trans_idx, trans_dstoff):
502
+ tti = _ttinfo_list[idx]
503
+ if tti.dstoff.total_seconds() != trans_off:
504
+ key = (idx, trans_off)
505
+ if key not in ttinfos:
506
+ ttinfos[key] = _ttinfo(
507
+ tti.utcoff, _load_timedelta(trans_off), tti.tzname
508
+ )
509
+ tti = ttinfos[key]
510
+ self._ttinfos.append(tti)
511
+
512
+ # Find the first non-DST transition
513
+ for i in range(len(isdst)):
514
+ if not isdst[i]:
515
+ self._tti_before = _ttinfo_list[i]
516
+ break
517
+ else:
518
+ if self._ttinfos:
519
+ self._tti_before = self._ttinfos[0]
520
+ else:
521
+ self._tti_before = None
522
+
523
+ # Set the "fallback" time zone
524
+ self._tz_str = tz_str
525
+ if tz_str is not None and tz_str != b"":
526
+ self._tz_after = _parse_tz_str(tz_str.decode())
527
+ else:
528
+ if not self._ttinfos and not _ttinfo_list:
529
+ raise ValueError("No time zone information found.")
530
+
531
+ if self._ttinfos:
532
+ self._tz_after = self._ttinfos[-1]
533
+ else:
534
+ # With no transitions and no TZ string, RFC 9636 Section 3.2
535
+ # says that local time is specified by time type 0
536
+ self._tz_after = _ttinfo_list[0]
537
+
538
+ # Determine if this is a "fixed offset" zone, meaning that the output
539
+ # of the utcoffset, dst and tzname functions does not depend on the
540
+ # specific datetime passed.
541
+ #
542
+ # We make three simplifying assumptions here:
543
+ #
544
+ # 1. If _tz_after is not a _ttinfo, it has transitions that might
545
+ # actually occur (it is possible to construct TZ strings that
546
+ # specify STD and DST but no transitions ever occur, such as
547
+ # AAA0BBB,0/0,J365/25).
548
+ # 2. If _ttinfo_list contains more than one _ttinfo object, the objects
549
+ # represent different offsets.
550
+ # 3. _ttinfo_list contains no unused _ttinfos (in which case an
551
+ # otherwise fixed-offset zone with extra _ttinfos defined may
552
+ # appear to *not* be a fixed offset zone).
553
+ #
554
+ # Violations to these assumptions would be fairly exotic, and exotic
555
+ # zones should almost certainly not be used with datetime.time (the
556
+ # only thing that would be affected by this).
557
+ if len(_ttinfo_list) > 1 or not isinstance(self._tz_after, _ttinfo):
558
+ self._fixed_offset = False
559
+ elif not _ttinfo_list:
560
+ self._fixed_offset = True
561
+ else:
562
+ self._fixed_offset = _ttinfo_list[0] == self._tz_after
563
+
564
+ @staticmethod
565
+ def _utcoff_to_dstoff(trans_idx, trans_utc, utcoffsets, isdsts):
566
+ """Infer the DST offset (the value of dst()) for each transition.
567
+
568
+ TZif files give the total UTC offset of each local time type and
569
+ whether it is DST, but not how much of the offset is DST, so this has
570
+ to be worked out from the standard time on either side of each DST
571
+ period. That is done for each transition rather than for each local
572
+ time type, because zic reuses a local time type for periods with
573
+ different standard offsets (e.g. UTC+0 DST in the Azores was double
574
+ summer time in the 1940s and summer time later).
575
+ """
576
+ n = len(trans_idx)
577
+
578
+ # The DST offset implied by the last standard time before and the
579
+ # first standard time after each transition. Before the first
580
+ # transition, it's the first standard time type, as for _tti_before.
581
+ first_std_utcoff = next(
582
+ (utcoff for utcoff, dst in zip(utcoffsets, isdsts) if not dst),
583
+ None,
584
+ )
585
+ before = [None] * n
586
+ after = [None] * n
587
+ for indices, implied, std_utcoff in (
588
+ (range(n), before, first_std_utcoff),
589
+ (range(n - 1, -1, -1), after, None),
590
+ ):
591
+ for i in indices:
592
+ idx = trans_idx[i]
593
+ if not isdsts[idx]:
594
+ std_utcoff = utcoffsets[idx]
595
+ elif std_utcoff is not None:
596
+ implied[i] = utcoffsets[idx] - std_utcoff
597
+
598
+ # DST offsets where the standard time is the same on both sides
599
+ clear_cut = [
600
+ (trans_utc[i], before[i])
601
+ for i in range(n)
602
+ if before[i] and before[i] == after[i]
603
+ ]
604
+
605
+ dstoffs = [0] * n
606
+ for i in range(n):
607
+ if not isdsts[trans_idx[i]]:
608
+ continue
609
+
610
+ candidates = {c for c in (before[i], after[i]) if c}
611
+ if len(candidates) > 1:
612
+ # The standard offset changed during the DST period. A change
613
+ # from local mean time can give something like 0:34:39, which
614
+ # is not a plausible amount of DST.
615
+ plausible = {c for c in candidates if c % 300 == 0}
616
+ candidates = plausible or candidates
617
+
618
+ if len(candidates) > 1:
619
+ # Prefer the amount of DST the zone used around the same
620
+ # time, e.g. Tehran used 1:00 and Rarotonga 0:30, though the
621
+ # TZif data for Tehran in 1977 and for Rarotonga in 1978 look
622
+ # the same. This has to be local in time, because some zones
623
+ # used different amounts in different eras (e.g. Montevideo
624
+ # used 0:30 in the 1920s and 1:00 later).
625
+ nearby = {
626
+ dstoff
627
+ for ts, dstoff in clear_cut
628
+ if abs(ts - trans_utc[i]) <= _DST_CONSENSUS_WINDOW
629
+ }
630
+ consensus = candidates & nearby
631
+ if len(consensus) == 1:
632
+ candidates = consensus
633
+
634
+ if candidates:
635
+ # Otherwise, prefer positive DST, then the smaller amount. In
636
+ # the 1942 occupation zones, e.g. Europe/Kyiv, the standard
637
+ # time before gives -1:00 and the one after +1:00.
638
+ dstoffs[i] = min(candidates, key=lambda c: (c < 0, abs(c)))
639
+ else:
640
+ # Without any standard time to compare to, one hour is a much
641
+ # better guess than 0
642
+ dstoffs[i] = 3600
643
+
644
+ return dstoffs
645
+
646
+ @staticmethod
647
+ def _ts_to_local(trans_idx, trans_list_utc, utcoffsets):
648
+ """Generate number of seconds since 1970 *in the local time*.
649
+
650
+ This is necessary to easily find the transition times in local time"""
651
+ if not trans_list_utc:
652
+ return [[], []]
653
+
654
+ # Start with the timestamps and modify in-place
655
+ trans_list_wall = [list(trans_list_utc), list(trans_list_utc)]
656
+
657
+ if len(utcoffsets) > 1:
658
+ offset_0 = utcoffsets[0]
659
+ offset_1 = utcoffsets[trans_idx[0]]
660
+ if offset_1 > offset_0:
661
+ offset_1, offset_0 = offset_0, offset_1
662
+ else:
663
+ offset_0 = offset_1 = utcoffsets[0]
664
+
665
+ trans_list_wall[0][0] += offset_0
666
+ trans_list_wall[1][0] += offset_1
667
+
668
+ for i in range(1, len(trans_idx)):
669
+ offset_0 = utcoffsets[trans_idx[i - 1]]
670
+ offset_1 = utcoffsets[trans_idx[i]]
671
+
672
+ if offset_1 > offset_0:
673
+ offset_1, offset_0 = offset_0, offset_1
674
+
675
+ trans_list_wall[0][i] += offset_0
676
+ trans_list_wall[1][i] += offset_1
677
+
678
+ return trans_list_wall
679
+
680
+ def __eq__(self, other):
681
+ if not isinstance(other, tzfile):
682
+ return NotImplemented
683
+
684
+ return (
685
+ self._trans_utc == other._trans_utc
686
+ and self._trans_local == other._trans_local
687
+ and self._ttinfos == other._ttinfos
688
+ and self._tti_before == other._tti_before
689
+ and self._fallback_key() == other._fallback_key()
690
+ )
691
+
692
+ def _fallback_key(self):
693
+ # The behavior after the last transition is determined either by the
694
+ # TZ string or, in its absence, by a single _ttinfo; _TZStr objects
695
+ # do not define equality, so compare the string they came from.
696
+ if isinstance(self._tz_after, _ttinfo):
697
+ return self._tz_after
698
+ return self._tz_str
699
+
700
+ __hash__ = None
701
+
702
+ def __ne__(self, other):
703
+ return not (self == other)
704
+
705
+ def __repr__(self):
706
+ return "%s(%s)" % (self.__class__.__name__, repr(self._filename))
707
+
708
+
709
+ # Before Python 3.16, pipes on Windows claim to be seekable, but seeking on
710
+ # them silently does nothing. See https://github.com/python/cpython/issues/86768
711
+ _SEEKABLE_PIPES_BUG = sys.platform == "win32" and sys.version_info < (3, 16)
712
+
713
+
714
+ def _is_seekable(fobj):
715
+ if not hasattr(fobj, "seek"):
716
+ return False
717
+
718
+ seekable = getattr(fobj, "seekable", None)
719
+ # Python 2 file objects can seek but have no seekable() method
720
+ if seekable is not None and not seekable():
721
+ return False
722
+
723
+ if not _SEEKABLE_PIPES_BUG:
724
+ return True
725
+
726
+ # For anything backed by a file descriptor, only trust regular files.
727
+ try:
728
+ fd = fobj.fileno()
729
+ except (AttributeError, OSError, ValueError):
730
+ # io.UnsupportedOperation (e.g. from BytesIO) is both of the latter
731
+ return True
732
+
733
+ try:
734
+ return stat.S_ISREG(os.fstat(fd).st_mode)
735
+ except OSError:
736
+ return True
737
+
738
+
739
+ def load_data(fobj):
740
+ try:
741
+ return _load_data(fobj)
742
+ except struct.error as e:
743
+ # struct.unpack fails when a read comes up short
744
+ six.raise_from(
745
+ ValueError("Invalid TZif file: unexpected end of file"), e
746
+ )
747
+
748
+
749
+ def _load_data(fobj):
750
+ header = _TZifHeader.from_file(fobj)
751
+
752
+ if header.version == 1:
753
+ time_size = 4
754
+ time_type = "l"
755
+ else:
756
+ # Version 2+ has 64-bit integer transition times
757
+ time_size = 8
758
+ time_type = "q"
759
+
760
+ # Version 2+ also starts with a Version 1 header and data, which
761
+ # we need to skip now
762
+ skip_bytes = (
763
+ header.timecnt * 5 # Transition times and types
764
+ + header.typecnt * 6 # Local time type records
765
+ + header.charcnt # Time zone designations
766
+ + header.leapcnt * 8 # Leap second records
767
+ + header.isstdcnt # Standard/wall indicators
768
+ + header.isutcnt # UT/local indicators
769
+ )
770
+
771
+ fobj.seek(skip_bytes, 1)
772
+
773
+ # Now we need to read the second header, which is not the same
774
+ # as the first
775
+ header = _TZifHeader.from_file(fobj)
776
+
777
+ typecnt = header.typecnt
778
+ timecnt = header.timecnt
779
+ charcnt = header.charcnt
780
+
781
+ # The data portion starts with timecnt transitions and indices
782
+ if timecnt:
783
+ trans_list_utc = struct.unpack(
784
+ ">%s%s" % (timecnt, time_type), fobj.read(timecnt * time_size)
785
+ )
786
+ trans_idx = struct.unpack(">%sB" % timecnt, fobj.read(timecnt))
787
+
788
+ if max(trans_idx) >= typecnt:
789
+ raise ValueError(
790
+ "Invalid transition index found while reading TZif: %s"
791
+ % max(trans_idx)
792
+ )
793
+ else:
794
+ trans_list_utc = ()
795
+ trans_idx = ()
796
+
797
+ # Read the ttinfo struct, (utoff, isdst, abbrind)
798
+ if typecnt:
799
+ utcoff, isdst, abbrind = zip(
800
+ *(struct.unpack(">lbb", fobj.read(6)) for i in range(typecnt))
801
+ )
802
+ else:
803
+ utcoff = ()
804
+ isdst = ()
805
+ abbrind = ()
806
+
807
+ # Now read the abbreviations. They are null-terminated strings, indexed
808
+ # not by position in the array but by position in the unsplit
809
+ # abbreviation string. I suppose this makes more sense in C, which uses
810
+ # null to terminate the strings, but it's inconvenient here...
811
+ abbr_vals = {}
812
+ abbr_chars = fobj.read(charcnt)
813
+
814
+ def get_abbr(idx):
815
+ # Gets a string starting at idx and running until the next \x00
816
+ #
817
+ # We cannot pre-populate abbr_vals by splitting on \x00 because there
818
+ # are some zones that use subsets of longer abbreviations, like so:
819
+ #
820
+ # LMT\x00AHST\x00HDT\x00
821
+ #
822
+ # Where the idx to abbr mapping should be:
823
+ #
824
+ # {0: "LMT", 4: "AHST", 5: "HST", 9: "HDT"}
825
+ if idx not in abbr_vals:
826
+ span_end = abbr_chars.find(b"\x00", idx)
827
+ abbr_vals[idx] = abbr_chars[idx:span_end].decode()
828
+
829
+ return abbr_vals[idx]
830
+
831
+ abbr = tuple(get_abbr(idx) for idx in abbrind)
832
+
833
+ # The remainder of the file consists of leap seconds (currently unused) and
834
+ # the standard/wall and ut/local indicators, which are metadata we don't need.
835
+ # In version 2 files, we need to skip the unnecessary data to get at the TZ string,
836
+ # and in version 1 files we'll just hopefully consume the rest of the file.
837
+
838
+ # Each leap second record has size (time_size + 4)
839
+ skip_bytes = (
840
+ header.isutcnt + header.isstdcnt + header.leapcnt * (time_size + 4)
841
+ )
842
+ fobj.seek(skip_bytes, 1)
843
+ if header.version >= 2:
844
+ c = fobj.read(1) # Should be \n
845
+ if c != b"\n":
846
+ raise ValueError("Invalid TZif file: expected newline, got %r" % c)
847
+
848
+ line = fobj.readline()
849
+ if not line.endswith(b"\n"):
850
+ raise ValueError("Invalid TZif file: unexpected end of file")
851
+ tz_str = line.rstrip(b"\n")
852
+ else:
853
+ tz_str = None
854
+
855
+ return trans_idx, trans_list_utc, utcoff, isdst, abbr, tz_str
856
+
857
+
858
+ # How close in time (in seconds) the DST periods that _utcoff_to_dstoff uses
859
+ # to choose between two possible DST offsets have to be
860
+ _DST_CONSENSUS_WINDOW = 10 * 365 * 86400
861
+
862
+
863
+ class _TZifHeader(object):
864
+ __slots__ = [
865
+ "version",
866
+ "isutcnt",
867
+ "isstdcnt",
868
+ "leapcnt",
869
+ "timecnt",
870
+ "typecnt",
871
+ "charcnt",
872
+ ]
873
+
874
+ def __init__(self, *args):
875
+ assert len(self.__slots__) == len(args)
876
+ for attr, val in zip(self.__slots__, args):
877
+ setattr(self, attr, val)
878
+
879
+ @classmethod
880
+ def from_file(cls, stream):
881
+ # The header starts with a 4-byte "magic" value
882
+ if stream.read(4) != b"TZif":
883
+ raise ValueError("Invalid TZif file: magic not found")
884
+
885
+ _version = stream.read(1)
886
+ if _version == b"\x00":
887
+ version = 1
888
+ else:
889
+ version = int(_version)
890
+ stream.read(15)
891
+
892
+ args = (version,)
893
+
894
+ # Slots are defined in the order that the bytes are arranged
895
+ args = args + struct.unpack(">6l", stream.read(24))
896
+
897
+ return cls(*args)
898
+
899
+
900
+ class _ttinfo(object):
901
+ __slots__ = ["utcoff", "dstoff", "tzname"]
902
+
903
+ def __init__(self, utcoff, dstoff, tzname):
904
+ self.utcoff = utcoff
905
+ self.dstoff = dstoff
906
+ self.tzname = tzname
907
+
908
+ def __eq__(self, other):
909
+ if not isinstance(other, _ttinfo):
910
+ return NotImplemented
911
+
912
+ return (
913
+ self.utcoff == other.utcoff
914
+ and self.dstoff == other.dstoff
915
+ and self.tzname == other.tzname
916
+ )
917
+
918
+ def __ne__(self, other):
919
+ # Python 2 does not derive __ne__ from __eq__
920
+ eq = self.__eq__(other)
921
+ if eq is NotImplemented:
922
+ return eq
923
+ return not eq
924
+
925
+ def __repr__(self): # pragma: nocover
926
+ return "%s(%s, %s, %s)" % (
927
+ self.__class__.__name__,
928
+ self.utcoff,
929
+ self.dstoff,
930
+ self.tzname,
931
+ )
932
+
933
+
934
+ _NO_TTINFO = _ttinfo(None, None, None)
935
+
936
+
937
+ def _unpack(t):
938
+ # Python 2-specific backport for x, *y = t
939
+ return t[0], t[1:]
940
+
941
+
942
+ # re.ASCII does not exist on Python 2, where str patterns are ASCII-only
943
+ # anyway (and unicode patterns are too unless re.UNICODE is passed).
944
+ _RE_ASCII = getattr(re, "ASCII", 0)
945
+
946
+
947
+ def _fullmatch(pattern, string, flags=0):
948
+ # Python 2-specific backport of re.fullmatch
949
+ return re.match(r"(?:%s)\Z" % pattern, string, flags)
950
+
951
+
952
+ def _round_offset(seconds):
953
+ # Python < 3.6 does not support sub-minute offsets, see the comment in
954
+ # tzfile._load_from_data.
955
+ if sys.version_info < (3, 6):
956
+ return 60 * ((seconds + 30) // 60)
957
+ return seconds
958
+
959
+
960
+ def _parse_tz_str(tz_str):
961
+ # The tz string has the format:
962
+ #
963
+ # std[offset[dst[offset],start[/time],end[/time]]]
964
+ #
965
+ # std and dst must be 3 or more characters long and must not contain
966
+ # a leading colon, embedded digits, commas, nor a plus or minus signs;
967
+ # The spaces between "std" and "offset" are only for display and are
968
+ # not actually present in the string.
969
+ #
970
+ # The format of the offset is ``[+|-]hh[:mm[:ss]]``
971
+
972
+ # TODO: When we drop Python 2, this should be offset_str, *start_end_str = ...
973
+ offset_str, start_end_str = _unpack(tz_str.split(",", 1))
974
+
975
+ parser_re = (
976
+ r"(?P<std>[a-zA-Z]+|<[a-zA-Z0-9+-]+>)"
977
+ r"(?:"
978
+ r"(?P<stdoff>[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)"
979
+ r"(?:"
980
+ r"(?P<dst>[a-zA-Z]+|<[a-zA-Z0-9+-]+>)"
981
+ r"(?P<dstoff>[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)?"
982
+ r")?" # dst
983
+ r")?" # stdoff
984
+ )
985
+
986
+ m = _fullmatch(parser_re, offset_str, _RE_ASCII)
987
+
988
+ if m is None:
989
+ raise ValueError("%s is not a valid TZ string" % tz_str)
990
+
991
+ std_abbr = m.group("std")
992
+ dst_abbr = m.group("dst")
993
+ dst_offset = None
994
+
995
+ std_abbr = std_abbr.strip("<>")
996
+
997
+ if dst_abbr:
998
+ dst_abbr = dst_abbr.strip("<>")
999
+
1000
+ std_offset = m.group("stdoff")
1001
+ if std_offset:
1002
+ try:
1003
+ std_offset = _round_offset(_parse_tz_delta(std_offset))
1004
+ except ValueError as e:
1005
+ raise ValueError("Invalid STD offset in %s" % tz_str)
1006
+ else:
1007
+ # The STD offset is required
1008
+ raise ValueError("Invalid STD offset in %s" % tz_str)
1009
+
1010
+ if dst_abbr is not None:
1011
+ dst_offset = m.group("dstoff")
1012
+ if dst_offset:
1013
+ try:
1014
+ dst_offset = _round_offset(_parse_tz_delta(dst_offset))
1015
+ except ValueError as e:
1016
+ raise ValueError("Invalid DST offset in %s" % tz_str)
1017
+ else:
1018
+ dst_offset = std_offset + 3600
1019
+
1020
+ if not start_end_str:
1021
+ raise ValueError("Missing transition rules: %s" % tz_str)
1022
+
1023
+ start_end_strs = start_end_str[0].split(",", 1)
1024
+ try:
1025
+ start, end = (_parse_dst_start_end(x) for x in start_end_strs)
1026
+ except ValueError as e:
1027
+ raise ValueError("Invalid TZ string: %s" % tz_str)
1028
+
1029
+ return _TZStr(std_abbr, std_offset, dst_abbr, dst_offset, start, end)
1030
+ elif start_end_str:
1031
+ raise ValueError("Transition rule present without DST: %s" % tz_str)
1032
+ else:
1033
+ # This is a static ttinfo, don't return _TZStr
1034
+ return _ttinfo(
1035
+ _load_timedelta(std_offset), _load_timedelta(0), std_abbr
1036
+ )
1037
+
1038
+
1039
+ def _parse_dst_start_end(dststr):
1040
+ date, time = _unpack(dststr.split("/", 1))
1041
+ date_type = date[:1]
1042
+ if date_type == "M":
1043
+ n_is_julian = False
1044
+ m = _fullmatch(r"M(\d{1,2})\.(\d)\.(\d)", date, _RE_ASCII)
1045
+ if m is None:
1046
+ raise ValueError("Invalid dst start/end date: %s" % dststr)
1047
+ date_offset = tuple(map(int, m.groups()))
1048
+ offset = _CalendarOffset(*date_offset)
1049
+ else:
1050
+ if date_type == "J":
1051
+ n_is_julian = True
1052
+ date = date[1:]
1053
+ else:
1054
+ n_is_julian = False
1055
+
1056
+ if _fullmatch(r"\d{1,3}", date, _RE_ASCII) is None:
1057
+ raise ValueError("Invalid dst start/end date: %s" % dststr)
1058
+ doy = int(date)
1059
+ offset = _DayOffset(doy, n_is_julian)
1060
+
1061
+ if time:
1062
+ offset.hour, offset.minute, offset.second = _parse_transition_time(
1063
+ time[0]
1064
+ )
1065
+
1066
+ return offset
1067
+
1068
+
1069
+ def _parse_transition_time(time_str):
1070
+ match = _fullmatch(
1071
+ r"(?P<sign>[+-])?(?P<h>\d{1,3})(:(?P<m>\d{2})(:(?P<s>\d{2}))?)?",
1072
+ time_str,
1073
+ _RE_ASCII,
1074
+ )
1075
+ if match is None:
1076
+ raise ValueError("Invalid time: %s" % time_str)
1077
+
1078
+ h, m, s = (int(v or 0) for v in map(match.group, ("h", "m", "s")))
1079
+
1080
+ if h > 167:
1081
+ raise ValueError("Hour must be in [0, 167]: %s" % time_str)
1082
+
1083
+ if match.group("sign") == "-":
1084
+ h, m, s = -h, -m, -s
1085
+
1086
+ return h, m, s
1087
+
1088
+
1089
+ def _parse_tz_delta(tz_delta):
1090
+ match = _fullmatch(
1091
+ r"(?P<sign>[+-])?(?P<h>\d{1,3})(:(?P<m>\d{2})(:(?P<s>\d{2}))?)?",
1092
+ tz_delta,
1093
+ _RE_ASCII,
1094
+ )
1095
+ # Anything passed to this function should already have hit an equivalent
1096
+ # regular expression to find the section to parse.
1097
+ assert match is not None, tz_delta
1098
+
1099
+ h, m, s = (int(v or 0) for v in map(match.group, ("h", "m", "s")))
1100
+
1101
+ total = h * 3600 + m * 60 + s
1102
+
1103
+ if h > 24:
1104
+ raise ValueError("Offset hours must be in [0, 24]: %s" % tz_delta)
1105
+
1106
+ # Yes, +5 maps to an offset of -5h
1107
+ if match.group("sign") != "-":
1108
+ total *= -1
1109
+
1110
+ return total
1111
+
1112
+
1113
+ class _TZStr(object):
1114
+ __slots__ = (
1115
+ "std",
1116
+ "dst",
1117
+ "start",
1118
+ "end",
1119
+ "get_trans_info",
1120
+ "get_trans_info_fromutc",
1121
+ "dst_diff",
1122
+ )
1123
+
1124
+ def __init__(
1125
+ self, std_abbr, std_offset, dst_abbr, dst_offset, start=None, end=None
1126
+ ):
1127
+ self.dst_diff = dst_offset - std_offset
1128
+ std_offset = _load_timedelta(std_offset)
1129
+ self.std = _ttinfo(
1130
+ utcoff=std_offset, dstoff=_load_timedelta(0), tzname=std_abbr
1131
+ )
1132
+
1133
+ self.start = start
1134
+ self.end = end
1135
+
1136
+ dst_offset = _load_timedelta(dst_offset)
1137
+ delta = _load_timedelta(self.dst_diff)
1138
+ self.dst = _ttinfo(utcoff=dst_offset, dstoff=delta, tzname=dst_abbr)
1139
+
1140
+ # These are assertions because the constructor should only be called
1141
+ # by functions that would fail before passing start or end
1142
+ assert start is not None, "No transition start specified"
1143
+ assert end is not None, "No transition end specified"
1144
+
1145
+ self.get_trans_info = self._get_trans_info
1146
+ self.get_trans_info_fromutc = self._get_trans_info_fromutc
1147
+
1148
+ def transitions(self, year):
1149
+ start = self.start.year_to_epoch(year)
1150
+ end = self.end.year_to_epoch(year)
1151
+ return start, end
1152
+
1153
+ def _near_new_year(self, ts, year):
1154
+ """Whether ts is close enough to the new year that the rules for the
1155
+ previous or next year might matter."""
1156
+ year_start = _post_epoch_days_before_year(year) * 86400
1157
+ year_end = _post_epoch_days_before_year(year + 1) * 86400
1158
+ return (
1159
+ ts < year_start + _NEW_YEAR_MARGIN
1160
+ or ts >= year_end - _NEW_YEAR_MARGIN
1161
+ )
1162
+
1163
+ def _get_trans_info(self, ts, year, fold):
1164
+ """Get the information about the current transition - tti"""
1165
+ if self._near_new_year(ts, year):
1166
+ return self._get_trans_info_near_new_year(ts, fold)
1167
+
1168
+ start, end = self.transitions(year)
1169
+
1170
+ # With fold = 0, the period (denominated in local time) with the
1171
+ # smaller offset starts at the end of the gap and ends at the end of
1172
+ # the fold; with fold = 1, it runs from the start of the gap to the
1173
+ # beginning of the fold.
1174
+ #
1175
+ # So in order to determine the DST boundaries we need to know both
1176
+ # the fold and whether DST is positive or negative (rare), and it
1177
+ # turns out that this boils down to fold XOR is_positive.
1178
+ if fold == (self.dst_diff >= 0):
1179
+ end -= self.dst_diff
1180
+ else:
1181
+ start += self.dst_diff
1182
+
1183
+ if start < end:
1184
+ isdst = start <= ts < end
1185
+ else:
1186
+ isdst = not (end <= ts < start)
1187
+
1188
+ return self.dst if isdst else self.std
1189
+
1190
+ def _get_trans_info_near_new_year(self, ts, fold):
1191
+ # Answer the question in terms of UTC, where the transitions from the
1192
+ # adjacent years are taken into account: a local time is valid for
1193
+ # an offset if the rules give that offset at the corresponding UTC
1194
+ # time.
1195
+ valid = []
1196
+ for tti in (self.std, self.dst):
1197
+ utc_ts = ts - tti.utcoff.total_seconds()
1198
+ try:
1199
+ utc_year = (EPOCH + timedelta(seconds=utc_ts)).year
1200
+ except OverflowError:
1201
+ # Before year 1 or after year 9999
1202
+ utc_year = MINYEAR if utc_ts < 0 else MAXYEAR
1203
+ actual, _ = self._get_trans_info_fromutc_near_new_year(
1204
+ utc_ts, utc_year
1205
+ )
1206
+ if actual is tti:
1207
+ valid.append(tti)
1208
+
1209
+ if len(valid) == 1:
1210
+ return valid[0]
1211
+
1212
+ smaller, larger = sorted((self.std, self.dst), key=lambda t: t.utcoff)
1213
+ if valid:
1214
+ # Ambiguous: fold=0 is the first occurrence, with the larger offset
1215
+ return larger if fold == 0 else smaller
1216
+ else:
1217
+ # Imaginary: fold=0 uses the offset from before the transition
1218
+ return smaller if fold == 0 else larger
1219
+
1220
+ def _get_trans_info_fromutc_near_new_year(self, ts, year):
1221
+ # The rules are in terms of the local year, which near the new year
1222
+ # is not always the UTC year, and a rule can put a transition up to a
1223
+ # week into the previous or next year (e.g. "J365/25"), so look at the
1224
+ # transitions for the years on either side as well and use the last
1225
+ # one before ts.
1226
+ std_utcoff = self.std.utcoff.total_seconds()
1227
+ dst_utcoff = self.dst.utcoff.total_seconds()
1228
+
1229
+ transitions = []
1230
+ for y in (year - 1, year, year + 1):
1231
+ start, end = self.transitions(y)
1232
+ transitions.append((start - std_utcoff, True))
1233
+ transitions.append((end - dst_utcoff, False))
1234
+
1235
+ # When one DST period ends at the same instant as the next one starts,
1236
+ # as with "DST all year" rules like "0/0,J365/25", sorting puts the
1237
+ # end first, so these stay in DST without a transition in between.
1238
+ transitions.sort()
1239
+
1240
+ isdst = not transitions[0][1]
1241
+ last_change = None
1242
+ i = 0
1243
+ while i < len(transitions) and transitions[i][0] <= ts:
1244
+ trans_ts = transitions[i][0]
1245
+ new_isdst = isdst
1246
+ while i < len(transitions) and transitions[i][0] == trans_ts:
1247
+ new_isdst = transitions[i][1]
1248
+ i += 1
1249
+
1250
+ if new_isdst != isdst:
1251
+ isdst = new_isdst
1252
+ last_change = trans_ts
1253
+
1254
+ if isdst:
1255
+ tti, tti_prev = self.dst, self.std
1256
+ else:
1257
+ tti, tti_prev = self.std, self.dst
1258
+
1259
+ # A transition to a smaller offset creates a fold just after it.
1260
+ fold = False
1261
+ if last_change is not None:
1262
+ shift = (tti_prev.utcoff - tti.utcoff).total_seconds()
1263
+ fold = shift > ts - last_change
1264
+
1265
+ return (tti, fold)
1266
+
1267
+ def _get_trans_info_fromutc(self, ts, year):
1268
+ if self._near_new_year(ts, year):
1269
+ return self._get_trans_info_fromutc_near_new_year(ts, year)
1270
+
1271
+ start, end = self.transitions(year)
1272
+ start -= self.std.utcoff.total_seconds()
1273
+ end -= self.dst.utcoff.total_seconds()
1274
+
1275
+ if start < end:
1276
+ isdst = start <= ts < end
1277
+ else:
1278
+ isdst = not (end <= ts < start)
1279
+
1280
+ # For positive DST, the ambiguous period is one dst_diff after the end
1281
+ # of DST; for negative DST, the ambiguous period is one dst_diff before
1282
+ # the start of DST.
1283
+ if self.dst_diff > 0:
1284
+ ambig_start = end
1285
+ ambig_end = end + self.dst_diff
1286
+ else:
1287
+ ambig_start = start
1288
+ ambig_end = start - self.dst_diff
1289
+
1290
+ fold = ambig_start <= ts < ambig_end
1291
+
1292
+ return (self.dst if isdst else self.std, fold)
1293
+
1294
+
1295
+ # A rule can put a transition up to 167 hours (just under a week) away from
1296
+ # the day it names, and local time is at most a day or so away from UTC, so
1297
+ # only times within this distance of the new year can be affected by the
1298
+ # rules for the previous or next year.
1299
+ _NEW_YEAR_MARGIN = 10 * 86400
1300
+
1301
+
1302
+ def _post_epoch_days_before_year(year):
1303
+ """Get the number of days between 1970-01-01 and YEAR-01-01"""
1304
+ y = year - 1
1305
+ return y * 365 + y // 4 - y // 100 + y // 400 + 1 - EPOCHORDINAL
1306
+
1307
+
1308
+ class _DayOffset(object):
1309
+ __slots__ = ["d", "julian", "hour", "minute", "second"]
1310
+
1311
+ def __init__(self, d, julian, hour=2, minute=0, second=0):
1312
+ min_day = 0 + julian # convert bool to int
1313
+ if not min_day <= d <= 365:
1314
+ raise ValueError("d must be in [%s, 365], not: %s" % (min_day, d))
1315
+
1316
+ self.d = d
1317
+ self.julian = julian
1318
+ self.hour = hour
1319
+ self.minute = minute
1320
+ self.second = second
1321
+
1322
+ def year_to_epoch(self, year):
1323
+ days_before_year = _post_epoch_days_before_year(year)
1324
+
1325
+ # "n" counts days from 0 and includes February 29; "Jn" counts days
1326
+ # from 1 and never counts February 29, so in leap years, J60 (March 1)
1327
+ # and every day after it is one day later than its number suggests.
1328
+ d = self.d
1329
+ if self.julian:
1330
+ d -= 1
1331
+ if d >= 59 and calendar.isleap(year):
1332
+ d += 1
1333
+
1334
+ epoch = (days_before_year + d) * 86400
1335
+ epoch += self.hour * 3600 + self.minute * 60 + self.second
1336
+
1337
+ return epoch
1338
+
1339
+
1340
+ class _CalendarOffset(object):
1341
+ __slots__ = ["m", "w", "d", "hour", "minute", "second"]
1342
+
1343
+ _DAYS_BEFORE_MONTH = (
1344
+ -1,
1345
+ 0,
1346
+ 31,
1347
+ 59,
1348
+ 90,
1349
+ 120,
1350
+ 151,
1351
+ 181,
1352
+ 212,
1353
+ 243,
1354
+ 273,
1355
+ 304,
1356
+ 334,
1357
+ )
1358
+
1359
+ def __init__(self, m, w, d, hour=2, minute=0, second=0):
1360
+ if not 1 <= m <= 12:
1361
+ raise ValueError("m must be in [1, 12]")
1362
+
1363
+ if not 1 <= w <= 5:
1364
+ raise ValueError("w must be in [1, 5]")
1365
+
1366
+ if not 0 <= d <= 6:
1367
+ raise ValueError("d must be in [0, 6]")
1368
+
1369
+ self.m = m
1370
+ self.w = w
1371
+ self.d = d
1372
+ self.hour = hour
1373
+ self.minute = minute
1374
+ self.second = second
1375
+
1376
+ @classmethod
1377
+ def _ymd2ord(cls, year, month, day):
1378
+ return (
1379
+ _post_epoch_days_before_year(year)
1380
+ + cls._DAYS_BEFORE_MONTH[month]
1381
+ + (month > 2 and calendar.isleap(year))
1382
+ + day
1383
+ - 1
1384
+ )
1385
+
1386
+ # TODO: These are not actually epoch dates as they are expressed in local time
1387
+ def year_to_epoch(self, year):
1388
+ """Calculates the datetime of the occurrence from the year"""
1389
+ # We know year and month, we need to convert w, d into day of month
1390
+ #
1391
+ # Week 1 is the first week in which day `d` (where 0 = Sunday) appears.
1392
+ # Week 5 represents the last occurrence of day `d`, so we need to know
1393
+ # the range of the month.
1394
+ #
1395
+ # This doesn't use calendar.monthrange because the rules for years 0
1396
+ # and 10000 can affect times that datetime can represent, and
1397
+ # calendar.monthrange constructs a datetime.date. Instead, get the
1398
+ # weekday (0 = Monday) from the ordinal: 1970-01-01 was a Thursday.
1399
+ first_ordinal = self._ymd2ord(year, self.m, 1)
1400
+ first_day = (first_ordinal + 3) % 7
1401
+ if self.m == 12:
1402
+ next_ordinal = self._ymd2ord(year + 1, 1, 1)
1403
+ else:
1404
+ next_ordinal = self._ymd2ord(year, self.m + 1, 1)
1405
+ days_in_month = next_ordinal - first_ordinal
1406
+
1407
+ # This equation seems magical, so I'll break it down:
1408
+ # 1. calendar says 0 = Monday, POSIX says 0 = Sunday
1409
+ # so we need first_day + 1 to get 1 = Monday -> 7 = Sunday,
1410
+ # which is still equivalent because this math is mod 7
1411
+ # 2. Get first day - desired day mod 7: -1 % 7 = 6, so we don't need
1412
+ # to do anything to adjust negative numbers.
1413
+ # 3. Add 1 because month days are a 1-based index.
1414
+ month_day = (self.d - (first_day + 1)) % 7 + 1
1415
+
1416
+ # Now use a 0-based index version of `w` to calculate the w-th
1417
+ # occurrence of `d`
1418
+ month_day += (self.w - 1) * 7
1419
+
1420
+ # month_day will only be > days_in_month if w was 5, and `w` means
1421
+ # "last occurrence of `d`", so now we just check if we over-shot the
1422
+ # end of the month and if so knock off 1 week.
1423
+ if month_day > days_in_month:
1424
+ month_day -= 7
1425
+
1426
+ ordinal = self._ymd2ord(year, self.m, month_day)
1427
+ epoch = ordinal * 86400
1428
+ epoch += self.hour * 3600 + self.minute * 60 + self.second
1429
+ return epoch