diff --git a/python_embeded/Lib/site-packages/pymatting-1.1.14.dist-info/licenses/LICENSE.md b/python_embeded/Lib/site-packages/pymatting-1.1.14.dist-info/licenses/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..2b3e8b593a8976319002e66b17b5934ab4cb9d5a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting-1.1.14.dist-info/licenses/LICENSE.md
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 PyMatting
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/__init__.py b/python_embeded/Lib/site-packages/pymatting/alpha/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2245a44a0ffbb6bdce076ad49b8ca93aa4ff9f3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/__init__.py
@@ -0,0 +1,7 @@
+from pymatting.alpha.estimate_alpha_lkm import estimate_alpha_lkm
+from pymatting.alpha.estimate_alpha_lbdm import estimate_alpha_lbdm
+from pymatting.alpha.estimate_alpha_rw import estimate_alpha_rw
+from pymatting.alpha.estimate_alpha_knn import estimate_alpha_knn
+from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf
+from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf as estimate_alpha
+from pymatting.alpha.estimate_alpha_sm import estimate_alpha_sm
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_cf.py b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_cf.py
new file mode 100644
index 0000000000000000000000000000000000000000..57d50098055f2d36110afb4b5c73789faccdddf6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_cf.py
@@ -0,0 +1,78 @@
+from pymatting.util.util import sanity_check_image, trimap_split
+from pymatting.laplacian.cf_laplacian import cf_laplacian
+from pymatting.preconditioner.ichol import ichol
+from pymatting.solver.cg import cg
+import numpy as np
+
+
+def estimate_alpha_cf(
+ image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
+):
+ """
+ Estimate alpha from an input image and an input trimap using Closed-Form Alpha Matting as proposed by :cite:`levin2007closed`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h \\times w` of the image
+ preconditioner: function or scipy.sparse.linalg.LinearOperator
+ Function or sparse matrix that applies the preconditioner to a vector (default: ichol)
+ laplacian_kwargs: dictionary
+ Arguments passed to the :code:`cf_laplacian` function
+ cg_kwargs: dictionary
+ Arguments passed to the :code:`cg` solver
+ is_known: numpy.ndarray
+ Binary mask of pixels for which to compute the laplacian matrix.
+ Providing this parameter might improve performance if few pixels are unknown.
+
+ Returns
+ -------
+ alpha: numpy.ndarray
+ Estimated alpha matte
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
+ >>> alpha = estimate_alpha_cf(
+ ... image,
+ ... trimap,
+ ... laplacian_kwargs={"epsilon": 1e-6},
+ ... cg_kwargs={"maxiter":2000})
+ """
+ if preconditioner is None:
+ preconditioner = ichol
+
+ sanity_check_image(image)
+
+ h, w = trimap.shape[:2]
+
+ is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
+
+ L = cf_laplacian(image, **laplacian_kwargs, is_known=is_known)
+
+ # Split Laplacian matrix L into
+ #
+ # [L_U R ]
+ # [R^T L_K]
+ #
+ # and then solve L_U x_U = -R is_fg_K for x where K (is_known) corresponds to
+ # fixed pixels and U (is_unknown) corresponds to unknown pixels. For reference, see
+ # Grady, Leo, et al. "Random walks for interactive alpha-matting." Proceedings of VIIP. Vol. 2005. 2005.
+
+ L_U = L[is_unknown, :][:, is_unknown]
+
+ R = L[is_unknown, :][:, is_known]
+
+ m = is_fg[is_known]
+
+ x = trimap.copy().ravel()
+
+ x[is_unknown] = cg(L_U, -R.dot(m), M=preconditioner(L_U), **cg_kwargs)
+
+ alpha = np.clip(x, 0, 1).reshape(trimap.shape)
+
+ return alpha
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_knn.py b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_knn.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e0275d1909fe9138f31792cfb47facc16aeecd7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_knn.py
@@ -0,0 +1,56 @@
+from pymatting.util.util import sanity_check_image
+from pymatting.laplacian.laplacian import make_linear_system
+from pymatting.laplacian.knn_laplacian import knn_laplacian
+from pymatting.preconditioner.jacobi import jacobi
+from pymatting.solver.cg import cg
+import numpy as np
+
+
+def estimate_alpha_knn(
+ image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
+):
+ """
+ Estimate alpha from an input image and an input trimap using KNN Matting similar to :cite:`chen2013knn`.
+ See `knn_laplacian` for more details.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h \\times w` of the image
+ preconditioner: function or scipy.sparse.linalg.LinearOperator
+ Function or sparse matrix that applies the preconditioner to a vector (default: jacobi)
+ laplacian_kwargs: dictionary
+ Arguments passed to the :code:`knn_laplacian` function
+ cg_kwargs: dictionary
+ Arguments passed to the :code:`cg` solver
+
+ Returns
+ -------
+ alpha: numpy.ndarray
+ Estimated alpha matte
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
+ >>> alpha = estimate_alpha_knn(
+ ... image,
+ ... trimap,
+ ... laplacian_kwargs={"n_neighbors": [15, 10]},
+ ... cg_kwargs={"maxiter":2000})
+ """
+ if preconditioner is None:
+ preconditioner = jacobi
+
+ sanity_check_image(image)
+
+ A, b = make_linear_system(knn_laplacian(image, **laplacian_kwargs), trimap)
+
+ x = cg(A, b, M=preconditioner(A), **cg_kwargs)
+
+ alpha = np.clip(x, 0, 1).reshape(trimap.shape)
+
+ return alpha
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lbdm.py b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lbdm.py
new file mode 100644
index 0000000000000000000000000000000000000000..079d100a6bd7cb4ada06cae38aa53aa217e67470
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lbdm.py
@@ -0,0 +1,56 @@
+from pymatting.util.util import sanity_check_image
+from pymatting.laplacian.laplacian import make_linear_system
+from pymatting.laplacian.lbdm_laplacian import lbdm_laplacian
+from pymatting.preconditioner.ichol import ichol
+from pymatting.solver.cg import cg
+import numpy as np
+
+
+def estimate_alpha_lbdm(
+ image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
+):
+ """
+ Estimate alpha from an input image and an input trimap using Learning Based Digital Matting as proposed by :cite:`zheng2009learning`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h \\times w` of the image
+ preconditioner: function or scipy.sparse.linalg.LinearOperator
+ Function or sparse matrix that applies the preconditioner to a vector (default: ichol)
+ laplacian_kwargs: dictionary
+ Arguments passed to the :code:`lbdm_laplacian` function
+ cg_kwargs: dictionary
+ Arguments passed to the :code:`cg` solver
+
+ Returns
+ -------
+ alpha: numpy.ndarray
+ Estimated alpha matte
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
+ >>> alpha = estimate_alpha_lbdm(
+ ... image,
+ ... trimap,
+ ... laplacian_kwargs={"epsilon": 1e-6},
+ ... cg_kwargs={"maxiter":2000})
+
+ """
+ if preconditioner is None:
+ preconditioner = ichol
+
+ sanity_check_image(image)
+
+ A, b = make_linear_system(lbdm_laplacian(image, **laplacian_kwargs), trimap)
+
+ x = cg(A, b, M=preconditioner(A), **cg_kwargs)
+
+ alpha = np.clip(x, 0, 1).reshape(trimap.shape)
+
+ return alpha
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lkm.py b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lkm.py
new file mode 100644
index 0000000000000000000000000000000000000000..6503f79beaf9b47d34a215f8f0a5ac1e3e801ba7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_lkm.py
@@ -0,0 +1,64 @@
+from pymatting.util.util import sanity_check_image
+from pymatting.laplacian.lkm_laplacian import lkm_laplacian
+from pymatting.util.util import trimap_split
+from pymatting.solver.cg import cg
+import numpy as np
+
+
+def estimate_alpha_lkm(image, trimap, laplacian_kwargs={}, cg_kwargs={}):
+ """
+ Estimate alpha from an input image and an input trimap as described in Fast Matting Using Large Kernel Matting Laplacian Matrices by :cite:`he2010fast`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h \\times w` of the image
+ laplacian_kwargs: dictionary
+ Arguments passed to the :code:`lkm_laplacian` function
+ cg_kwargs: dictionary
+ Arguments passed to the :code:`cg` solver
+
+ Returns
+ -------
+ alpha: numpy.ndarray
+ Estimated alpha matte
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
+ >>> alpha = estimate_alpha_lkm(
+ ... image,
+ ... trimap,
+ ... laplacian_kwargs={"epsilon": 1e-6, "radius": 15},
+ ... cg_kwargs={"maxiter":2000})
+
+ """
+
+ sanity_check_image(image)
+
+ L_matvec, diag_L = lkm_laplacian(image, **laplacian_kwargs)
+
+ is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
+
+ lambda_value = 100.0
+
+ c = lambda_value * is_known
+ b = lambda_value * is_fg
+
+ inv_diag_A = 1.0 / (diag_L + c)
+
+ def A_matvec(x):
+ return L_matvec(x) + c * x
+
+ def jacobi(x):
+ return inv_diag_A * x
+
+ x = cg(A_matvec, b, M=jacobi, **cg_kwargs)
+
+ alpha = np.clip(x, 0, 1).reshape(trimap.shape)
+
+ return alpha
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_rw.py b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_rw.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b3eebba5bd1b804fd4c4a111e4e6f26c06753aa
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_rw.py
@@ -0,0 +1,56 @@
+from pymatting.util.util import sanity_check_image
+from pymatting.laplacian.laplacian import make_linear_system
+from pymatting.laplacian.rw_laplacian import rw_laplacian
+from pymatting.preconditioner.jacobi import jacobi
+from pymatting.solver.cg import cg
+import numpy as np
+
+
+def estimate_alpha_rw(
+ image, trimap, preconditioner=None, laplacian_kwargs={}, cg_kwargs={}
+):
+ """
+ Estimate alpha from an input image and an input trimap using Learning Based Digital Matting as proposed by :cite:`grady2005random`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h \\times w` of the image
+ preconditioner: function or scipy.sparse.linalg.LinearOperator
+ Function or sparse matrix that applies the preconditioner to a vector (default: jacobi)
+ laplacian_kwargs: dictionary
+ Arguments passed to the :code:`rw_laplacian` function
+ cg_kwargs: dictionary
+ Arguments passed to the :code:`cg` solver
+
+ Returns
+ -------
+ alpha: numpy.ndarray
+ Estimated alpha matte
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
+ >>> alpha = estimate_alpha_rw(
+ .... image,
+ ... trimap,
+ ... laplacian_kwargs={"sigma": 0.03},
+ ... cg_kwargs={"maxiter":2000})
+
+ """
+ if preconditioner is None:
+ preconditioner = jacobi
+
+ sanity_check_image(image)
+
+ A, b = make_linear_system(rw_laplacian(image, **laplacian_kwargs), trimap)
+
+ x = cg(A, b, M=preconditioner(A), **cg_kwargs)
+
+ alpha = np.clip(x, 0, 1).reshape(trimap.shape)
+
+ return alpha
diff --git a/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_sm.py b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_sm.py
new file mode 100644
index 0000000000000000000000000000000000000000..926c6e488f4ed9482689629f8bc87dd09502ff8c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/alpha/estimate_alpha_sm.py
@@ -0,0 +1,613 @@
+from numba import njit, pndindex
+import numpy as np
+
+def estimate_alpha_sm(
+ image,
+ trimap,
+ return_foreground_background=False,
+ trimap_expansion_radius=10,
+ trimap_expansion_threshold=0.02,
+ sample_gathering_angles=4,
+ sample_gathering_weights=(3.0, 2.0, 1.0, 4.0),
+ sample_gathering_Np_radius=1,
+ sample_refinement_radius=5,
+ local_smoothing_radius1=5,
+ local_smoothing_radius2=5,
+ local_smoothing_radius3=5,
+ local_smoothing_sigma_sq1=None,
+ local_smoothing_sigma_sq2=0.1,
+ local_smoothing_sigma_sq3=None,
+
+):
+ """
+ Estimate alpha from an input image and an input trimap using Shared Matting as proposed by :cite:`GastalOliveira2010SharedMatting`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h \\times w \\times d` for which the alpha matte should be estimated
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h \\times w` of the image
+ return_foreground_background: numpy.ndarray
+ Whether to return foreground and background estimate. They will be computed either way
+ trimap_expansion_radius: int
+ How much to expand trimap.
+ trimap_expansion_threshold: float
+ Which pixel colors are similar enough to expand trimap into
+ sample_gathering_angles: int
+ In how many directions to search for new samples.
+ sample_gathering_weights: Tuple[float, float, float, float]
+ Weights for various cost functions
+ sample_gathering_Np_radius: int
+ Radius of Np function
+ sample_refinement_radius: int
+ Search region for better neighboring samples
+ local_smoothing_radius1: int
+ Radius for foreground/background smoothing
+ local_smoothing_radius2: int
+ Radius for confidence computation
+ local_smoothing_radius3: int
+ Radius for low frequency alpha computation
+ local_smoothing_sigma_sq1: float
+ Squared sigma value for foreground/background smoothing
+ Defaults to :code:`(2 * local_smoothing_radius1 + 1)**2 / (9 * pi)` if not given
+ local_smoothing_sigma_sq2: float
+ Squared sigma value for confidence computation
+ local_smoothing_sigma_sq3: float
+ Squared sigma value for low frequency alpha computation
+ Defaults to :code:`(2 * local_smoothing_radius3 + 1)**2 / (9 * pi)` if not given
+
+ Returns
+ -------
+ alpha: numpy.ndarray
+ Estimated alpha matte
+ foreground: numpy.ndarray
+ Estimated foreground
+ background: numpy.ndarray
+ Estimated background
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> trimap = load_image("data/lemur/lemur_trimap.png", "GRAY")
+ >>> alpha, foreground, background = estimate_alpha_sm(
+ ... image,
+ ... trimap,
+ ... return_foreground_background=True,
+ ... sample_gathering_angles=4)
+ """
+ assert image.dtype in [np.float32, np.float64], f"image.dtype should be float32 or float64, but is {image.dtype}"
+ assert trimap.dtype in [np.float32, np.float64], f"trimap.dtype should be float32 or float64, but is {trimap.dtype}"
+ assert trimap.shape == image.shape[:2], f"image height and width should match trimap height and width, but image shape is {image.shape} and trimap shape is {trimap.shape}"
+ assert len(image.shape) == 3 and image.shape[2] == 3, f"image should be RGB, but shape is {image.shape}"
+
+ if local_smoothing_sigma_sq1 is None:
+ local_smoothing_sigma_sq1 = (2 * local_smoothing_radius1 + 1)**2 / (9.0 * np.pi)
+
+ if local_smoothing_sigma_sq3 is None:
+ local_smoothing_sigma_sq3 = (2 * local_smoothing_radius1 + 1)**2 / (9.0 * np.pi)
+
+ # Convert to float32 if float64. Precision should be sufficient.
+ image = image.astype(np.float32)
+ trimap = trimap.astype(np.float32)
+
+ expanded_trimap = trimap.copy()
+
+ if trimap_expansion_radius > 0 and trimap_expansion_threshold > 0.0:
+ expand_trimap(
+ expanded_trimap,
+ trimap,
+ image,
+ k_i=trimap_expansion_radius,
+ k_c=trimap_expansion_threshold)
+
+ avg_F = image[expanded_trimap == 1.0].mean(axis=0)
+ avg_B = image[expanded_trimap == 0.0].mean(axis=0)
+
+ gathering_F = np.zeros_like(image) + avg_F
+ gathering_B = np.zeros_like(image) + avg_B
+
+ gathering_alpha = np.zeros_like(trimap)
+
+ eN, eA, ef, eb = sample_gathering_weights
+
+ sample_gathering(
+ gathering_F,
+ gathering_B,
+ gathering_alpha,
+ image,
+ expanded_trimap,
+ num_angles=sample_gathering_angles,
+ eN=eN,
+ eA=eA,
+ ef=ef,
+ eb=eb,
+ Np_radius=sample_gathering_Np_radius)
+
+ refined_F = np.zeros_like(image)
+ refined_B = np.zeros_like(image)
+ refined_alpha = np.zeros_like(trimap)
+
+ sample_refinement(
+ refined_F,
+ refined_B,
+ refined_alpha,
+ gathering_F,
+ gathering_B,
+ image,
+ expanded_trimap,
+ radius=sample_refinement_radius)
+
+ final_F = np.zeros_like(image)
+ final_B = np.zeros_like(image)
+ final_alpha = np.zeros_like(trimap)
+
+ local_smoothing(
+ final_F,
+ final_B,
+ final_alpha,
+ refined_F,
+ refined_B,
+ refined_alpha,
+ image,
+ expanded_trimap,
+ radius1=local_smoothing_radius1,
+ radius2=local_smoothing_radius2,
+ radius3=local_smoothing_radius3,
+ sigma_sq1=local_smoothing_sigma_sq1,
+ sigma_sq2=local_smoothing_sigma_sq2,
+ sigma_sq3=local_smoothing_sigma_sq3)
+
+ if return_foreground_background:
+ return final_alpha, final_F, final_B
+ else:
+ return final_alpha
+
+@njit("f4(f4[::1], f4[::1], f4[::1])", cache=True, nogil=True)
+def estimate_alpha(I, F, B):
+ fb0 = F[0] - B[0]
+ fb1 = F[1] - B[1]
+ fb2 = F[2] - B[2]
+
+ ib0 = I[0] - B[0]
+ ib1 = I[1] - B[1]
+ ib2 = I[2] - B[2]
+
+ denom = fb0 * fb0 + fb1 * fb1 + fb2 * fb2 + 1e-5
+
+ alpha = (ib0 * fb0 + ib1 * fb1 + ib2 * fb2) / denom
+
+ alpha = max(0.0, min(1.0, alpha))
+
+ return alpha
+
+@njit("f4(f4[::1], f4[::1])", cache=True, nogil=True)
+def inner(a, b):
+ s = 0.0
+ for i in range(len(a)):
+ s += a[i] * b[i]
+ return s
+
+@njit("f4(f4[::1], f4[::1], f4[::1])", cache=True, nogil=True)
+def Mp2(I, F, B):
+ a = estimate_alpha(I, F, B)
+
+ d0 = a * F[0] + (1.0 - a) * B[0] - I[0]
+ d1 = a * F[1] + (1.0 - a) * B[1] - I[1]
+ d2 = a * F[2] + (1.0 - a) * B[2] - I[2]
+
+ return d0 * d0 + d1 * d1 + d2 * d2
+
+@njit("f4(f4[:, :, ::1], i8, i8, f4[::1], f4[::1], i8)", cache=True, nogil=True)
+def Np(image, x, y, F, B, r):
+ h, w = image.shape[:2]
+ result = 0.0
+ for y2 in range(y - r, y + r + 1):
+ y2 = max(0, min(h - 1, y2))
+ for x2 in range(x - r, x + r + 1):
+ x2 = max(0, min(w - 1, x2))
+ result += Mp2(image[y2, x2], F, B)
+ return result
+
+@njit("f4(f4[:, :, ::1], i8, i8, i8, i8)", cache=True, nogil=True)
+def Ep(image, px, py, sx, sy):
+ result = 0.0
+
+ spx = sx - px
+ spy = sy - py
+
+ d = np.hypot(spx, spy)
+
+ if d == 0.0: return 0.0
+
+ num_steps = int(np.ceil(d))
+ num_steps = max(1, min(10, num_steps))
+
+ step_x = spx / num_steps
+ step_y = spy / num_steps
+
+ h, w = image.shape[:2]
+
+ for i in range(num_steps + 1):
+ qx = int(px + float(i) * step_x)
+ qy = int(py + float(i) * step_x)
+
+ q_l = max(0, min(w - 1, qx - 1))
+ q_r = max(0, min(w - 1, qx + 1))
+ q_u = max(0, min(h - 1, qy + 1))
+ q_d = max(0, min(h - 1, qy - 1))
+ qx = max(0, min(w - 1, qx))
+ qy = max(0, min(h - 1, qy))
+
+ Ix0 = 0.5 * (image[qy, q_r, 0] - image[qy, q_l, 0])
+ Ix1 = 0.5 * (image[qy, q_r, 1] - image[qy, q_l, 1])
+ Ix2 = 0.5 * (image[qy, q_r, 2] - image[qy, q_l, 2])
+
+ Iy0 = 0.5 * (image[q_u, qx, 0] - image[q_d, qx, 0])
+ Iy1 = 0.5 * (image[q_u, qx, 1] - image[q_d, qx, 1])
+ Iy2 = 0.5 * (image[q_u, qx, 2] - image[q_d, qx, 2])
+
+ v0 = step_x * Ix0 + step_y * Iy0
+ v1 = step_x * Ix1 + step_y * Iy1
+ v2 = step_x * Ix2 + step_y * Iy2
+
+ result += np.sqrt(v0 * v0 + v1 * v1 + v2 * v2)
+
+ return result
+
+@njit("f4(f4[::1], f4[::1])", cache=True, nogil=True)
+def dist(a, b):
+ d2 = 0.0
+ for i in range(a.shape[0]):
+ d2 += (a[i] - b[i]) ** 2
+ return np.sqrt(d2)
+
+@njit("f4(f4[::1])", cache=True, nogil=True)
+def length(a):
+ return np.sqrt(inner(a, a))
+
+@njit("void(f4[:, ::1], f4[:, ::1], f4[:, :, ::1], i8, f4)", cache=True, parallel=True, nogil=True)
+def expand_trimap(expanded_trimap, trimap, image, k_i, k_c):
+ # NB: Description in paper does not match published test images.
+ # The radius appears to be larger and expanded trimap is sparser.
+ h, w = trimap.shape
+
+ for y, x in pndindex((h, w)):
+ if trimap[y, x] == 0 or trimap[y, x] == 1: continue
+
+ closest = np.inf
+
+ for y2 in range(y - k_i, y + k_i + 1):
+ for x2 in range(x - k_i, x + k_i + 1):
+ if x2 < 0 or x2 >= w or y2 < 0 or y2 >= h: continue
+ if trimap[y2, x2] != 0 and trimap[y2, x2] != 1: continue
+
+ dr = image[y, x, 0] - image[y2, x2, 0]
+ dg = image[y, x, 1] - image[y2, x2, 1]
+ db = image[y, x, 2] - image[y2, x2, 2]
+
+ color_distance = np.sqrt(dr * dr + dg * dg + db * db)
+
+ spatial_distance = np.hypot(x - x2, y - y2)
+
+ if color_distance > k_c: continue
+ if spatial_distance > k_i: continue
+
+ if spatial_distance < closest:
+ closest = spatial_distance
+ expanded_trimap[y, x] = trimap[y2, x2]
+
+@njit("void(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, ::1], i8, f4, f4, f4, f4, i8)", cache=True, parallel=True, nogil=True)
+def sample_gathering(
+ gathering_F,
+ gathering_B,
+ gathering_alpha,
+ image,
+ trimap,
+ num_angles,
+ eN,
+ eA,
+ ef,
+ eb,
+ Np_radius,
+):
+ h, w = trimap.shape
+
+ max_steps = 2 * max(w, h)
+
+ for y, x in pndindex((h, w)):
+ fg_samples = np.zeros((num_angles, 3), dtype=np.float32)
+ fg_samples_xy = np.zeros((num_angles, 2), dtype=np.int32)
+ bg_samples = np.zeros((num_angles, 3), dtype=np.float32)
+ bg_samples_xy = np.zeros((num_angles, 2), dtype=np.int32)
+
+ C_p = image[y, x]
+
+ gathering_alpha[y, x] = trimap[y, x]
+
+ if trimap[y, x] == 0:
+ gathering_B[y, x] = C_p
+ continue
+
+ if trimap[y, x] == 1:
+ gathering_F[y, x] = C_p
+ continue
+
+ # Fixed start angles in 8-by-8 grid for reproducible tests
+ n = 8
+ i = (x % n) + (y % n) * n
+ # Shuffle (99991 is a prime number)
+ i = (i * 99991) % (n * n)
+ start_angle = 2.0 * np.pi / (n * n) * i
+
+ num_fg_samples = 0
+ num_bg_samples = 0
+
+ for i in range(num_angles):
+ angle = 2.0 * np.pi / num_angles * i + start_angle
+
+ c = np.cos(angle)
+ s = np.sin(angle)
+
+ has_fg = False
+ has_bg = False
+
+ for step in range(max_steps):
+ if has_fg and has_bg: break
+
+ x2 = int(x + step * c)
+ y2 = int(y + step * s)
+
+ if x2 < 0 or y2 < 0 or x2 >= w or y2 >= h: break
+
+ if not has_fg and trimap[y2, x2] == 1:
+ fg_samples[num_fg_samples] = image[y2, x2]
+ fg_samples_xy[num_fg_samples, 0] = x2
+ fg_samples_xy[num_fg_samples, 1] = y2
+ num_fg_samples += 1
+ has_fg = True
+
+ if not has_bg and trimap[y2, x2] == 0:
+ bg_samples[num_bg_samples] = image[y2, x2]
+ bg_samples_xy[num_bg_samples, 0] = x2
+ bg_samples_xy[num_bg_samples, 1] = y2
+ num_bg_samples += 1
+ has_bg = True
+
+ if num_fg_samples == 0:
+ fg_samples[num_fg_samples] = gathering_F[y, x]
+ fg_samples_xy[num_fg_samples, 0] = x
+ fg_samples_xy[num_fg_samples, 1] = y
+ num_fg_samples += 1
+
+ if num_bg_samples == 0:
+ bg_samples[num_bg_samples] = gathering_B[y, x]
+ bg_samples_xy[num_bg_samples, 0] = x
+ bg_samples_xy[num_bg_samples, 1] = y
+ num_bg_samples += 1
+
+ min_Ep_f = np.inf
+ min_Ep_b = np.inf
+
+ for i in range(num_fg_samples):
+ Ep_f = Ep(image, x, y, fg_samples_xy[i, 0], fg_samples_xy[i, 1])
+
+ min_Ep_f = min(min_Ep_f, Ep_f)
+
+ for j in range(num_bg_samples):
+ Ep_b = Ep(image, x, y, bg_samples_xy[j, 0], bg_samples_xy[j, 1])
+
+ min_Ep_b = min(min_Ep_b, Ep_b)
+
+ PF_p = min_Ep_b / (min_Ep_f + min_Ep_b + 1e-5)
+
+ min_cost = np.inf
+
+ # Find best foreground/background pair
+ for i in range(num_fg_samples):
+ for j in range(num_bg_samples):
+ F = fg_samples[i]
+ B = bg_samples[j]
+
+ alpha_p = estimate_alpha(C_p, F, B)
+
+ Ap = PF_p + (1.0 - 2.0 * PF_p) * alpha_p
+
+ Dp_f = np.hypot(x - fg_samples_xy[i, 0], y - fg_samples_xy[i, 1])
+ Dp_b = np.hypot(x - bg_samples_xy[j, 0], y - bg_samples_xy[j, 1])
+
+ g_p = (
+ Np(image, x, y, F, B, Np_radius)**eN *
+ Ap**eA *
+ Dp_f**ef *
+ Dp_b**eb)
+
+ if min_cost > g_p:
+ min_cost = g_p
+ gathering_alpha[y, x] = alpha_p
+ gathering_F[y, x] = F
+ gathering_B[y, x] = B
+
+@njit("void(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], i8)", cache=True, parallel=False, nogil=True)
+def sample_refinement(
+ refined_F,
+ refined_B,
+ refined_alpha,
+ gathering_F,
+ gathering_B,
+ image,
+ trimap,
+ radius,
+):
+ h, w = trimap.shape
+
+ refined_F[:] = gathering_F
+ refined_B[:] = gathering_B
+ refined_alpha[:] = trimap
+
+ for y, x in pndindex((h, w)):
+ C_p = image[y, x]
+
+ if trimap[y, x] == 0 or trimap[y, x] == 1:
+ continue
+
+ max_samples = 3
+ sample_F = np.zeros((max_samples, 3), dtype=np.float32)
+ sample_B = np.zeros((max_samples, 3), dtype=np.float32)
+ sample_cost = np.zeros(max_samples, dtype=np.float32)
+ sample_cost[:] = np.inf
+
+ for dy in range(-radius, radius + 1):
+ for dx in range(-radius, radius + 1):
+ x2 = x + dx
+ y2 = y + dy
+
+ if 0 <= x2 < w and 0 <= y2 < h:
+ F_q = gathering_F[y2, x2]
+ B_q = gathering_B[y2, x2]
+
+ cost = Mp2(C_p, F_q, B_q)
+
+ i = np.argmax(sample_cost)
+
+ if cost < sample_cost[i]:
+ sample_cost[i] = cost
+ sample_F[i] = F_q
+ sample_B[i] = B_q
+
+ F_mean = sample_F.sum(axis=0) / max_samples
+ B_mean = sample_B.sum(axis=0) / max_samples
+
+ refined_F[y, x] = F_mean
+ refined_B[y, x] = B_mean
+
+ refined_alpha[y, x] = estimate_alpha(C_p, F_mean, B_mean)
+
+@njit("void(f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, :, ::1], f4[:, ::1], f4[:, :, ::1], f4[:, ::1], i8, i8, i8, f4, f4, f4)", cache=True, parallel=True, nogil=True)
+def local_smoothing(
+ final_F,
+ final_B,
+ final_alpha,
+ refined_F,
+ refined_B,
+ refined_alpha,
+ image,
+ trimap,
+ radius1,
+ radius2,
+ radius3,
+ sigma_sq1,
+ sigma_sq2,
+ sigma_sq3,
+):
+ h, w = trimap.shape
+
+ final_confidence = np.zeros((h, w), dtype=np.float32)
+ W_FB = np.zeros((h, w), dtype=np.float32)
+ low_frequency_alpha = np.zeros((h, w), dtype=np.float32)
+
+ final_F[:] = refined_F
+ final_B[:] = refined_B
+
+ for y, x in pndindex((h, w)):
+ C_p = image[y, x]
+
+ if trimap[y, x] == 0 or trimap[y, x] == 1:
+ continue
+
+ F_p = np.zeros(3, dtype=np.float32)
+ B_p = np.zeros(3, dtype=np.float32)
+
+ sum_F = 0.0
+ sum_B = 0.0
+
+ alpha_p = refined_alpha[y, x]
+
+ for dy in range(-radius1, radius1 + 1):
+ for dx in range(-radius1, radius1 + 1):
+ x2 = x + dx
+ y2 = y + dy
+
+ if 0 <= x2 < w and 0 <= y2 < h:
+ # NB: Gaussian not normalized, not using confidence
+ Wc_pq = np.exp(-1.0 / sigma_sq1 * (dx * dx + dy * dy))
+
+ if x != x2 or y != y2:
+ Wc_pq *= abs(refined_alpha[y, x] - refined_alpha[y2, x2])
+
+ alpha_q = refined_alpha[y2, x2]
+
+ W_F = Wc_pq * alpha_q
+ W_B = Wc_pq * (1.0 - alpha_q)
+
+ W_F = max(W_F, 1e-5)
+ W_B = max(W_B, 1e-5)
+
+ sum_F += W_F
+ sum_B += W_B
+
+ for c in range(3):
+ F_p[c] += W_F * refined_F[y2, x2, c]
+ B_p[c] += W_B * refined_B[y2, x2, c]
+
+ F_p /= sum_F
+ B_p /= sum_B
+
+ final_F[y, x] = F_p
+ final_B[y, x] = B_p
+
+ final_alpha[y, x] = estimate_alpha(C_p, F_p, B_p)
+
+ # NB: Not using confidence
+ W_FB[y, x] = alpha_p * (1.0 - alpha_p)
+
+ for y, x in pndindex((h, w)):
+ C_p = image[y, x]
+
+ if trimap[y, x] == 0 or trimap[y, x] == 1:
+ final_confidence[y, x] = trimap[y, x]
+ continue
+
+ D_FB = 0.0
+ weight_sum = 0.0
+ for dy in range(-radius2, radius2 + 1):
+ for dx in range(-radius2, radius2 + 1):
+ x2 = x + dx
+ y2 = y + dy
+ if 0 <= x2 < w and 0 <= y2 < h:
+ weight_sum += W_FB[y2, x2]
+ D_FB += W_FB[y2, x2] * dist(final_F[y2, x2], final_B[y2, x2])
+
+ D_FB /= weight_sum + 1e-5
+ D_FB += 1e-5
+
+ FB_dist = dist(final_F[y, x], final_B[y, x])
+
+ F_p = final_F[y, x]
+ B_p = final_B[y, x]
+
+ final_confidence[y, x] = min(1.0, FB_dist / D_FB) * np.exp(-1.0 / sigma_sq2 * np.sqrt(Mp2(C_p, F_p, B_p)))
+
+ for y, x in pndindex((h, w)):
+ if trimap[y, x] == 0 or trimap[y, x] == 1:
+ final_alpha[y, x] = trimap[y, x]
+ continue
+
+ alpha_sum = 0.0
+ weight_sum = 0.0
+ for dy in range(-radius3, radius3 + 1):
+ for dx in range(-radius3, radius3 + 1):
+ x2 = x + dx
+ y2 = y + dy
+ if 0 <= x2 < w and 0 <= y2 < h:
+ # NB: Gaussian not normalized, not using final_confidence(x2, y2)
+ D_image_squared = dx * dx + dy * dy
+ is_known = trimap[y2, x2] == 0 or trimap[y2, x2] == 1
+ W_alpha = np.exp(-1.0 / sigma_sq3 * (dx * dx + dy * dy)) + is_known
+ alpha_sum += W_alpha * refined_alpha[y2, x2]
+ weight_sum += W_alpha
+
+ low_frequency_alpha[y, x] = alpha_sum / weight_sum
+
+ final_alpha[y, x] = final_confidence[y, x] * final_alpha[y, x] + (1.0 - final_confidence[y, x]) * low_frequency_alpha[y, x]
diff --git a/python_embeded/Lib/site-packages/pymatting/config/__init__.py b/python_embeded/Lib/site-packages/pymatting/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/config/__init__.py
@@ -0,0 +1 @@
+
diff --git a/python_embeded/Lib/site-packages/pymatting/cutout/__init__.py b/python_embeded/Lib/site-packages/pymatting/cutout/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ff5863a5674d7d453aa2455d1d8075714a0b247
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/cutout/__init__.py
@@ -0,0 +1 @@
+from pymatting.cutout.cutout import cutout
diff --git a/python_embeded/Lib/site-packages/pymatting/cutout/cutout.py b/python_embeded/Lib/site-packages/pymatting/cutout/cutout.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cd45e426486eb67bb09fd8cc2276e8bb6438cf4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/cutout/cutout.py
@@ -0,0 +1,36 @@
+from pymatting.util.util import load_image, save_image, stack_images
+from pymatting.alpha.estimate_alpha_cf import estimate_alpha_cf
+from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
+
+
+def cutout(image_path, trimap_path, cutout_path):
+ """
+ Generate a cutout image from an input image and an input trimap.
+ This method is using closed-form alpha matting as proposed by :cite:`levin2007closed` and multi-level foreground extraction :cite:`germer2020multilevel`.
+
+ Parameters
+ ----------
+ image_path: str
+ Path of input image
+ trimap_path: str
+ Path of input trimap
+ cutout_path: str
+ Path of output cutout image
+
+ Example
+ -------
+ >>> cutout("../data/lemur.png", "../data/lemur_trimap.png", "lemur_cutout.png")
+ """
+ image = load_image(image_path, "RGB")
+ trimap = load_image(trimap_path, "GRAY")
+
+ if image.shape[:2] != trimap.shape[:2]:
+ raise ValueError("Input image and trimap must have same size")
+
+ alpha = estimate_alpha_cf(image, trimap)
+
+ foreground = estimate_foreground_ml(image, alpha)
+
+ cutout = stack_images(foreground, alpha)
+
+ save_image(cutout_path, cutout)
diff --git a/python_embeded/Lib/site-packages/pymatting/foreground/__init__.py b/python_embeded/Lib/site-packages/pymatting/foreground/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1eaf8e8d264aa920e17f2419ca9246f1315c3ac
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/foreground/__init__.py
@@ -0,0 +1,5 @@
+from pymatting.foreground.estimate_foreground_cf import estimate_foreground_cf
+from pymatting.foreground.estimate_foreground_ml import estimate_foreground_ml
+from pymatting.foreground.estimate_foreground_ml import (
+ estimate_foreground_ml as estimate_foreground,
+)
diff --git a/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_cf.py b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_cf.py
new file mode 100644
index 0000000000000000000000000000000000000000..167854eee7b10603ad73deef7b645a364c2754a8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_cf.py
@@ -0,0 +1,130 @@
+from pymatting.preconditioner.ichol import ichol
+from pymatting.util.util import sparse_conv_matrix_with_offsets
+from pymatting.solver.cg import cg
+import scipy.sparse
+import numpy as np
+
+
+def estimate_foreground_cf(
+ image,
+ alpha,
+ regularization=1e-5,
+ rtol=1e-5,
+ neighbors=[(-1, 0), (1, 0), (0, -1), (0, 1)],
+ return_background=False,
+ foreground_guess=None,
+ background_guess=None,
+ ichol_kwargs={},
+ cg_kwargs={},
+):
+ """Estimates the foreground of an image given alpha matte and image.
+
+ This method is based on the publication :cite:`levin2007closed`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Input image with shape :math:`h \\times w \\times d`
+ alpha: numpy.ndarray
+ Input alpha matte with shape :math:`h \\times w`
+ regularization: float
+ Regularization strength :math:`\\epsilon`, defaults to :math:`10^{-5}`
+ neighbors: list of tuples of ints
+ List of relative positions that define the neighborhood of a pixel
+ return_background: bool
+ Whether to return the estimated background in addition to the foreground
+ foreground_guess: numpy.ndarray
+ An initial guess for the foreground image in order to accelerate convergence.
+ Using input image by default.
+ background_guess: numpy.ndarray
+ An initial guess for the background image.
+ Using input image by default.
+ ichol_kwargs: dictionary
+ Keyword arguments for the incomplete Cholesky preconditioner
+ cg_kwargs: dictionary
+ Keyword arguments for the conjugate gradient descent solver
+
+ Returns
+ -------
+ F: numpy.ndarray
+ Extracted foreground
+ B: numpy.ndarray
+ Extracted background (not returned by default)
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> alpha = load_image("data/lemur/lemur_alpha.png", "GRAY")
+ >>> F = estimate_foreground_cf(image, alpha, return_background=False)
+ >>> F, B = estimate_foreground_cf(image, alpha, return_background=True)
+
+
+ See Also
+ --------
+ stack_images: This function can be used to place the foreground on a new background.
+ """
+ h, w, d = image.shape
+
+ assert alpha.shape == (h, w)
+
+ n = w * h
+
+ a = alpha.flatten()
+
+ S = None
+ for dx, dy in neighbors:
+ # directional derivative
+ D = sparse_conv_matrix_with_offsets(w, h, [1.0, -1.0], [0, dx], [0, dy])
+
+ S2 = D.T.dot(scipy.sparse.diags(regularization + np.abs(D.dot(a)))).dot(D)
+
+ S = S2 if S is None else S + S2
+
+ del D, S2
+
+ V = scipy.sparse.bmat([[S, None], [None, S]])
+
+ del S
+
+ U = scipy.sparse.bmat([[scipy.sparse.diags(a), scipy.sparse.diags(1 - a)]])
+
+ A = U.T.dot(U) + V
+
+ A.sum_duplicates()
+
+ del V
+
+ # Compute preconditioner for faster convergence
+ precondition = ichol(A, **ichol_kwargs)
+
+ # By default use input image as initialization
+ foreground = (image if foreground_guess is None else foreground_guess).copy()
+ background = (image if background_guess is None else background_guess).copy()
+
+ # For each image color channel
+ for channel in range(d):
+ image_channel = image[:, :, channel].flatten()
+
+ b = U.T.dot(image_channel)
+
+ # Initialization vector for conjugate gradient descent
+ f0 = foreground[:, :, channel].flatten()
+ b0 = background[:, :, channel].flatten()
+ fb = np.concatenate([f0, b0])
+
+ # Solve linear system
+ # A fb = b
+ # for fb using conjugate gradient descent
+ fb = cg(A, b, x0=fb, M=precondition, rtol=rtol, **cg_kwargs)
+
+ foreground[:, :, channel] = fb[:n].reshape(h, w)
+ background[:, :, channel] = fb[n:].reshape(h, w)
+
+ foreground = np.clip(foreground, 0, 1)
+ background = np.clip(background, 0, 1)
+
+ if return_background:
+ return foreground, background
+
+ return foreground
diff --git a/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml.py b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml.py
new file mode 100644
index 0000000000000000000000000000000000000000..c117f291779fcf2c8b01997dbc84c2a0c5f5b699
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml.py
@@ -0,0 +1,253 @@
+import numpy as np
+from numba import njit, prange
+
+
+@njit("void(f4[:, :, :], f4[:, :, :])", cache=True, nogil=True, parallel=True)
+def _resize_nearest_multichannel(dst, src):
+ """
+ Internal method.
+
+ Resize image src to dst using nearest neighbors filtering.
+ Images must have multiple color channels, i.e. :code:`len(shape) == 3`.
+
+ Parameters
+ ----------
+ dst: numpy.ndarray of type np.float32
+ output image
+ src: numpy.ndarray of type np.float32
+ input image
+ """
+ h_src, w_src, depth = src.shape
+ h_dst, w_dst, depth = dst.shape
+
+ for y_dst in prange(h_dst):
+ for x_dst in range(w_dst):
+ x_src = max(0, min(w_src - 1, x_dst * w_src // w_dst))
+ y_src = max(0, min(h_src - 1, y_dst * h_src // h_dst))
+
+ for c in range(depth):
+ dst[y_dst, x_dst, c] = src[y_src, x_src, c]
+
+
+@njit("void(f4[:, :], f4[:, :])", cache=True, nogil=True, parallel=True)
+def _resize_nearest(dst, src):
+ """
+ Internal method.
+
+ Resize image src to dst using nearest neighbors filtering.
+ Images must be grayscale, i.e. :code:`len(shape) == 3`.
+
+ Parameters
+ ----------
+ dst: numpy.ndarray of type np.float32
+ output image
+ src: numpy.ndarray of type np.float32
+ input image
+ """
+ h_src, w_src = src.shape
+ h_dst, w_dst = dst.shape
+
+ for y_dst in prange(h_dst):
+ for x_dst in range(w_dst):
+ x_src = max(0, min(w_src - 1, x_dst * w_src // w_dst))
+ y_src = max(0, min(h_src - 1, y_dst * h_src // h_dst))
+
+ dst[y_dst, x_dst] = src[y_src, x_src]
+
+# TODO
+# There should be an option to switch @njit(parallel=True) on or off.
+# parallel=True would be faster, but might cause race conditions.
+# User should have the option to turn it on or off.
+@njit("Tuple((f4[:, :, :], f4[:, :, :]))(f4[:, :, :], f4[:, :], f4, i4, i4, i4, f4)", cache=True, nogil=True)
+def _estimate_fb_ml(
+ input_image,
+ input_alpha,
+ regularization,
+ n_small_iterations,
+ n_big_iterations,
+ small_size,
+ gradient_weight,
+):
+ h0, w0, depth = input_image.shape
+
+ dtype = np.float32
+
+ w_prev = 1
+ h_prev = 1
+
+ # Compute average foreground and background color
+ F_mean_color = np.zeros(depth, dtype=dtype)
+ B_mean_color = np.zeros(depth, dtype=dtype)
+ F_count = 0
+ B_count = 0
+ for y in range(h0):
+ for x in range(w0):
+ if input_alpha[y, x] > 0.9:
+ for c in range(depth):
+ F_mean_color[c] += input_image[y, x, c]
+ F_count += 1
+ if input_alpha[y, x] < 0.1:
+ for c in range(depth):
+ B_mean_color[c] += input_image[y, x, c]
+ B_count += 1
+
+ F_mean_color /= F_count + 1e-5
+ B_mean_color /= B_count + 1e-5
+
+ # Initialize initial foreground and background with average color
+ F_prev = np.zeros((h_prev, w_prev, depth), dtype=dtype) + F_mean_color
+ B_prev = np.zeros((h_prev, w_prev, depth), dtype=dtype) + B_mean_color
+
+ n_levels = int(np.ceil(np.log2(max(w0, h0))))
+
+ for i_level in range(n_levels + 1):
+ w = round(w0 ** (i_level / n_levels))
+ h = round(h0 ** (i_level / n_levels))
+
+ image = np.empty((h, w, depth), dtype=dtype)
+ alpha = np.empty((h, w), dtype=dtype)
+
+ _resize_nearest_multichannel(image, input_image)
+ _resize_nearest(alpha, input_alpha)
+
+ F = np.empty((h, w, depth), dtype=dtype)
+ B = np.empty((h, w, depth), dtype=dtype)
+
+ _resize_nearest_multichannel(F, F_prev)
+ _resize_nearest_multichannel(B, B_prev)
+
+ if w <= small_size and h <= small_size:
+ n_iter = n_small_iterations
+ else:
+ n_iter = n_big_iterations
+
+ b = np.zeros((2, depth), dtype=dtype)
+
+ dx = [-1, 1, 0, 0]
+ dy = [0, 0, -1, 1]
+
+ for i_iter in range(n_iter):
+ for y in prange(h):
+ for x in range(w):
+ a0 = alpha[y, x]
+ a1 = 1.0 - a0
+
+ a00 = a0 * a0
+ a01 = a0 * a1
+ # a10 = a01 can be omitted due to symmetry of matrix
+ a11 = a1 * a1
+
+ for c in range(depth):
+ b[0, c] = a0 * image[y, x, c]
+ b[1, c] = a1 * image[y, x, c]
+
+ for d in range(4):
+ x2 = max(0, min(w - 1, x + dx[d]))
+ y2 = max(0, min(h - 1, y + dy[d]))
+
+ gradient = abs(a0 - alpha[y2, x2])
+
+ da = regularization + gradient_weight * gradient
+
+ a00 += da
+ a11 += da
+
+ for c in range(depth):
+ b[0, c] += da * F[y2, x2, c]
+ b[1, c] += da * B[y2, x2, c]
+
+ determinant = a00 * a11 - a01 * a01
+
+ inv_det = 1.0 / determinant
+
+ b00 = inv_det * a11
+ b01 = inv_det * -a01
+ b11 = inv_det * a00
+
+ for c in range(depth):
+ F_c = b00 * b[0, c] + b01 * b[1, c]
+ B_c = b01 * b[0, c] + b11 * b[1, c]
+
+ F_c = max(0.0, min(1.0, F_c))
+ B_c = max(0.0, min(1.0, B_c))
+
+ F[y, x, c] = F_c
+ B[y, x, c] = B_c
+
+ F_prev = F
+ B_prev = B
+
+ w_prev = w
+ h_prev = h
+
+ return F, B
+
+
+def estimate_foreground_ml(
+ image,
+ alpha,
+ regularization=1e-5,
+ n_small_iterations=10,
+ n_big_iterations=2,
+ small_size=32,
+ return_background=False,
+ gradient_weight=1.0,
+):
+ """Estimates the foreground of an image given its alpha matte.
+
+ See :cite:`germer2020multilevel` for reference.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Input image with shape :math:`h \\times w \\times d`
+ alpha: numpy.ndarray
+ Input alpha matte shape :math:`h \\times w`
+ regularization: float
+ Regularization strength :math:`\\epsilon`, defaults to :math:`10^{-5}`.
+ Higher regularization results in smoother colors.
+ n_small_iterations: int
+ Number of iterations performed on small scale, defaults to :math:`10`
+ n_big_iterations: int
+ Number of iterations performed on large scale, defaults to :math:`2`
+ small_size: int
+ Threshold that determines at which size `n_small_iterations` should be used
+ return_background: bool
+ Whether to return the estimated background in addition to the foreground
+ gradient_weight: float
+ Larger values enforce smoother foregrounds, defaults to :math:`1`
+
+ Returns
+ -------
+ F: numpy.ndarray
+ Extracted foreground
+ B: numpy.ndarray
+ Extracted background
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> image = load_image("data/lemur/lemur.png", "RGB")
+ >>> alpha = load_image("data/lemur/lemur_alpha.png", "GRAY")
+ >>> F = estimate_foreground_ml(image, alpha, return_background=False)
+ >>> F, B = estimate_foreground_ml(image, alpha, return_background=True)
+
+ See Also
+ --------
+ stack_images: This function can be used to place the foreground on a new background.
+ """
+
+ foreground, background = _estimate_fb_ml(
+ image.astype(np.float32),
+ alpha.astype(np.float32),
+ regularization,
+ n_small_iterations,
+ n_big_iterations,
+ small_size,
+ gradient_weight,
+ )
+
+ if return_background:
+ return foreground, background
+
+ return foreground
diff --git a/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_cupy.py b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_cupy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1bea88b8215f54fb5e3f460e0c93d7177bf44d1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_cupy.py
@@ -0,0 +1,230 @@
+import numpy as np
+import cupy as cp
+from pymatting.util.util import div_round_up
+
+_resize_nearest = cp.RawKernel(
+ r"""
+extern "C" __global__
+void resize_nearest(
+ float *dst,
+ const float *src,
+ int w_src, int h_src,
+ int w_dst, int h_dst,
+ int depth
+){
+ int x_dst = blockDim.x * blockIdx.x + threadIdx.x;
+ int y_dst = blockDim.y * blockIdx.y + threadIdx.y;
+
+ if (x_dst >= w_dst || y_dst >= h_dst) return;
+
+ int x_src = min(x_dst * w_src / w_dst, w_src - 1);
+ int y_src = min(y_dst * h_src / h_dst, h_src - 1);
+
+ float *ptr_dst = dst + (x_dst + y_dst * w_dst) * depth;
+ const float *ptr_src = src + (x_src + y_src * w_src) * depth;
+
+ for (int channel = 0; channel < depth; channel++){
+ ptr_dst[channel] = ptr_src[channel];
+ }
+}
+""",
+ "resize_nearest",
+)
+
+ml_iteration = cp.RawKernel(
+ r"""
+extern "C" __global__
+void ml_iteration(
+ float *F,
+ float *B,
+ const float *F_prev,
+ const float *B_prev,
+ const float *image,
+ const float *alpha,
+ int w,
+ int h,
+ float regularization
+){
+ int x = blockDim.x * blockIdx.x + threadIdx.x;
+ int y = blockDim.y * blockIdx.y + threadIdx.y;
+
+ int i = x + y * w;
+
+ if (x >= w || y >= h) return;
+
+ float a0 = alpha[i];
+ float a1 = 1.0f - a0;
+
+ float b00 = a0 * image[i * 3 + 0];
+ float b01 = a0 * image[i * 3 + 1];
+ float b02 = a0 * image[i * 3 + 2];
+
+ float b10 = a1 * image[i * 3 + 0];
+ float b11 = a1 * image[i * 3 + 1];
+ float b12 = a1 * image[i * 3 + 2];
+
+ int js[4] = {
+ max( 0, x - 1) + y * w,
+ min(w - 1, x + 1) + y * w,
+ x + max( 0, y - 1) * w,
+ x + min(h - 1, y + 1) * w,
+ };
+
+ float a_sum = 0.0f;
+
+ for (int d = 0; d < 4; d++){
+ int j = js[d];
+
+ float da = regularization + fabsf(a0 - alpha[j]);
+
+ a_sum += da;
+
+ b00 += da * F_prev[j * 3 + 0];
+ b01 += da * F_prev[j * 3 + 1];
+ b02 += da * F_prev[j * 3 + 2];
+
+ b10 += da * B_prev[j * 3 + 0];
+ b11 += da * B_prev[j * 3 + 1];
+ b12 += da * B_prev[j * 3 + 2];
+ }
+
+ float a00 = a0 * a0 + a_sum;
+ float a11 = a1 * a1 + a_sum;
+ float a01 = a0 * a1;
+
+ float inv_det = 1.0f / (a00 * a11 - a01 * a01);
+
+ F[i * 3 + 0] = fmaxf(0.0f, fminf(1.0f, inv_det * (a11 * b00 - a01 * b10)));
+ F[i * 3 + 1] = fmaxf(0.0f, fminf(1.0f, inv_det * (a11 * b01 - a01 * b11)));
+ F[i * 3 + 2] = fmaxf(0.0f, fminf(1.0f, inv_det * (a11 * b02 - a01 * b12)));
+
+ B[i * 3 + 0] = fmaxf(0.0f, fminf(1.0f, inv_det * (a00 * b10 - a01 * b00)));
+ B[i * 3 + 1] = fmaxf(0.0f, fminf(1.0f, inv_det * (a00 * b11 - a01 * b01)));
+ B[i * 3 + 2] = fmaxf(0.0f, fminf(1.0f, inv_det * (a00 * b12 - a01 * b02)));
+}
+""",
+ "ml_iteration",
+)
+
+
+def estimate_foreground_ml_cupy(
+ input_image,
+ input_alpha,
+ regularization=1e-5,
+ n_small_iterations=10,
+ n_big_iterations=2,
+ small_size=32,
+ block_size=(32, 32),
+ return_background=False,
+ to_numpy=True,
+):
+ """See the :code:`estimate_foreground` method for documentation."""
+ h0, w0, depth = input_image.shape
+
+ assert depth == 3
+
+ n = h0 * w0 * depth
+
+ if isinstance(input_image, cp.ndarray):
+ input_image = input_image.astype(cp.float32).ravel()
+ else:
+ input_image = cp.asarray(input_image.astype(np.float32).flatten())
+
+ if isinstance(input_alpha, cp.ndarray):
+ input_alpha = input_alpha.astype(cp.float32).ravel()
+ else:
+ input_alpha = cp.asarray(input_alpha.astype(np.float32).flatten())
+
+ F_prev = cp.zeros(n, dtype=cp.float32)
+ B_prev = cp.zeros(n, dtype=cp.float32)
+
+ F = cp.zeros(n, dtype=cp.float32)
+ B = cp.zeros(n, dtype=cp.float32)
+
+ image_level = cp.zeros(n, dtype=cp.float32)
+ alpha_level = cp.zeros(h0 * w0, dtype=cp.float32)
+
+ n_levels = (max(w0, h0) - 1).bit_length()
+
+ w_prev = 1
+ h_prev = 1
+
+ def resize_nearest(dst, src, w_src, h_src, w_dst, h_dst, depth):
+ grid_size = (
+ div_round_up(w_dst, block_size[0]),
+ div_round_up(h_dst, block_size[1]),
+ )
+
+ _resize_nearest(
+ grid_size,
+ block_size,
+ (
+ dst,
+ src,
+ w_src,
+ h_src,
+ w_dst,
+ h_dst,
+ depth,
+ ),
+ )
+
+ resize_nearest(F, input_image, w0, h0, w_prev, h_prev, depth)
+ resize_nearest(B, input_image, w0, h0, w_prev, h_prev, depth)
+
+ for i_level in range(n_levels + 1):
+ w = round(w0 ** (i_level / n_levels))
+ h = round(h0 ** (i_level / n_levels))
+
+ resize_nearest(image_level, input_image, w0, h0, w, h, depth)
+ resize_nearest(alpha_level, input_alpha, w0, h0, w, h, 1)
+
+ resize_nearest(F_prev, F, w_prev, h_prev, w, h, depth)
+ resize_nearest(B_prev, B, w_prev, h_prev, w, h, depth)
+
+ # Do more iterations for low resolution.
+ n_iter = n_big_iterations
+ if min(w, h) <= small_size:
+ n_iter = n_small_iterations
+
+ grid_size = (div_round_up(w, block_size[0]), div_round_up(h, block_size[1]))
+
+ for i_iter in range(n_iter):
+ ml_iteration(
+ grid_size,
+ block_size,
+ (
+ F,
+ B,
+ F_prev,
+ B_prev,
+ image_level,
+ alpha_level,
+ w,
+ h,
+ np.float32(regularization),
+ ),
+ )
+
+ F_prev, F = F, F_prev
+ B_prev, B = B, B_prev
+
+ w_prev = w
+ h_prev = h
+
+ # Reshape back to original shape.
+ F = F.reshape(h0, w0, depth)
+ B = B.reshape(h0, w0, depth)
+
+ # Convert to NumPy if requested
+ if to_numpy:
+ F_out = cp.asnumpy(F)
+ B_out = cp.asnumpy(B)
+ else:
+ F_out = F
+ B_out = B
+
+ if return_background:
+ return F_out, B_out
+
+ return F_out
diff --git a/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_pyopencl.py b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_pyopencl.py
new file mode 100644
index 0000000000000000000000000000000000000000..715946a44dbd10c226f29ba637e4754cd99d9ba1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/foreground/estimate_foreground_ml_pyopencl.py
@@ -0,0 +1,229 @@
+import math
+import numpy as np
+import pyopencl as cl
+
+source = """
+__kernel void resize_nearest(
+ __global float *dst,
+ __global const float *src,
+ int w_src, int h_src,
+ int w_dst, int h_dst,
+ int depth
+){
+ int x_dst = get_global_id(0);
+ int y_dst = get_global_id(1);
+
+ if (x_dst >= w_dst || y_dst >= h_dst) return;
+
+ int x_src = min(x_dst * w_src / w_dst, w_src - 1);
+ int y_src = min(y_dst * h_src / h_dst, h_src - 1);
+
+ __global float *ptr_dst = dst + (x_dst + y_dst * w_dst) * depth;
+ __global const float *ptr_src = src + (x_src + y_src * w_src) * depth;
+
+ for (int channel = 0; channel < depth; channel++){
+ ptr_dst[channel] = ptr_src[channel];
+ }
+}
+
+__kernel void ml_iteration(
+ __global float *F,
+ __global float *B,
+ __global const float *F_prev,
+ __global const float *B_prev,
+ __global const float *image,
+ __global const float *alpha,
+ int w,
+ int h,
+ float regularization
+){
+ int x = get_global_id(0);
+ int y = get_global_id(1);
+
+ int i = x + y * w;
+
+ if (x >= w || y >= h) return;
+
+ float a0 = alpha[i];
+ float a1 = 1.0f - a0;
+
+ float b00 = a0 * image[i * 3 + 0];
+ float b01 = a0 * image[i * 3 + 1];
+ float b02 = a0 * image[i * 3 + 2];
+
+ float b10 = a1 * image[i * 3 + 0];
+ float b11 = a1 * image[i * 3 + 1];
+ float b12 = a1 * image[i * 3 + 2];
+
+ int js[4] = {
+ max( 0, x - 1) + y * w,
+ min(w - 1, x + 1) + y * w,
+ x + max( 0, y - 1) * w,
+ x + min(h - 1, y + 1) * w,
+ };
+
+ float a_sum = 0.0f;
+
+ for (int d = 0; d < 4; d++){
+ int j = js[d];
+
+ float da = regularization + fabs(a0 - alpha[j]);
+
+ a_sum += da;
+
+ b00 += da * F_prev[j * 3 + 0];
+ b01 += da * F_prev[j * 3 + 1];
+ b02 += da * F_prev[j * 3 + 2];
+
+ b10 += da * B_prev[j * 3 + 0];
+ b11 += da * B_prev[j * 3 + 1];
+ b12 += da * B_prev[j * 3 + 2];
+ }
+
+ float a00 = a0 * a0 + a_sum;
+ float a11 = a1 * a1 + a_sum;
+ float a01 = a0 * a1;
+
+ float inv_det = 1.0f / (a00 * a11 - a01 * a01);
+
+ F[i * 3 + 0] = fmax(0.0f, fmin(1.0f, inv_det * (a11 * b00 - a01 * b10)));
+ F[i * 3 + 1] = fmax(0.0f, fmin(1.0f, inv_det * (a11 * b01 - a01 * b11)));
+ F[i * 3 + 2] = fmax(0.0f, fmin(1.0f, inv_det * (a11 * b02 - a01 * b12)));
+ B[i * 3 + 0] = fmax(0.0f, fmin(1.0f, inv_det * (a00 * b10 - a01 * b00)));
+ B[i * 3 + 1] = fmax(0.0f, fmin(1.0f, inv_det * (a00 * b11 - a01 * b01)));
+ B[i * 3 + 2] = fmax(0.0f, fmin(1.0f, inv_det * (a00 * b12 - a01 * b02)));
+}
+"""
+
+platform = cl.get_platforms()[0]
+device = platform.get_devices(cl.device_type.GPU)[0]
+context = cl.Context([device])
+queue = cl.CommandQueue(context)
+program = cl.Program(context, source).build()
+
+
+def estimate_foreground_ml_pyopencl(
+ input_image,
+ input_alpha,
+ regularization=1e-5,
+ n_small_iterations=10,
+ n_big_iterations=2,
+ small_size=32,
+ return_background=False,
+):
+ """See the :code:`estimate_foreground` method for documentation."""
+
+ def upload(array):
+ hostbuf = array.astype(np.float32).flatten()
+ return cl.Buffer(
+ context,
+ cl.mem_flags.READ_ONLY | cl.mem_flags.COPY_HOST_PTR,
+ hostbuf=hostbuf,
+ )
+
+ def alloc(*shape):
+ n = math.prod(shape)
+ buffer = cl.Buffer(context, cl.mem_flags.READ_WRITE, n * 4)
+ zero = np.uint32(0)
+ cl.enqueue_fill_buffer(queue, buffer, zero, 0, n*4)
+ return buffer
+
+ def download(device_buf, shape):
+ host_buf = np.empty(shape, dtype=np.float32)
+
+ cl.enqueue_copy(queue, host_buf, device_buf)
+
+ return host_buf.reshape(shape)
+
+ h0, w0, depth = input_image.shape
+
+ assert depth == 3
+
+ n = h0 * w0 * depth
+
+ input_image = upload(input_image)
+ input_alpha = upload(input_alpha)
+
+ F_prev = alloc(n)
+ B_prev = alloc(n)
+
+ F = alloc(n)
+ B = alloc(n)
+
+ image_level = alloc(n)
+ alpha_level = alloc(h0 * w0)
+
+ n_levels = (max(w0, h0) - 1).bit_length()
+
+ def resize_nearest(dst, src, w_src, h_src, w_dst, h_dst, depth):
+ program.resize_nearest(
+ queue,
+ (w_dst, h_dst),
+ None,
+ dst,
+ src,
+ *np.int32([w_src, h_src, w_dst, h_dst, depth])
+ )
+
+ w_prev = 1
+ h_prev = 1
+
+ resize_nearest(F, input_image, w0, h0, w_prev, h_prev, depth)
+ resize_nearest(B, input_image, w0, h0, w_prev, h_prev, depth)
+
+ for i_level in range(n_levels + 1):
+ w = round(w0 ** (i_level / n_levels))
+ h = round(h0 ** (i_level / n_levels))
+
+ resize_nearest(image_level, input_image, w0, h0, w, h, depth)
+ resize_nearest(alpha_level, input_alpha, w0, h0, w, h, 1)
+
+ resize_nearest(F_prev, F, w_prev, h_prev, w, h, depth)
+ resize_nearest(B_prev, B, w_prev, h_prev, w, h, depth)
+
+ # Do more iterations for low resolution.
+ n_iter = n_big_iterations
+ if min(w, h) <= small_size:
+ n_iter = n_small_iterations
+
+ for i_iter in range(n_iter):
+ program.ml_iteration(
+ queue,
+ (w, h),
+ None,
+ F,
+ B,
+ F_prev,
+ B_prev,
+ image_level,
+ alpha_level,
+ np.int32(w),
+ np.int32(h),
+ np.float32(regularization),
+ )
+
+ F_prev, F = F, F_prev
+ B_prev, B = B, B_prev
+
+ w_prev = w
+ h_prev = h
+
+ F_host = download(F, (h0, w0, depth))
+ B_host = download(B, (h0, w0, depth))
+
+ for buf in [
+ F,
+ B,
+ F_prev,
+ B_prev,
+ input_image,
+ input_alpha,
+ image_level,
+ alpha_level,
+ ]:
+ buf.release()
+
+ if return_background:
+ return F_host, B_host
+
+ return F_host
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/__init__.py b/python_embeded/Lib/site-packages/pymatting/laplacian/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f08a84187bf3ff6cd9d172dc00a0c61e8eae4136
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/__init__.py
@@ -0,0 +1,19 @@
+from pymatting.laplacian.cf_laplacian import cf_laplacian
+from pymatting.laplacian.knn_laplacian import knn_laplacian
+from pymatting.laplacian.lkm_laplacian import lkm_laplacian
+from pymatting.laplacian.rw_laplacian import rw_laplacian
+from pymatting.laplacian.lbdm_laplacian import lbdm_laplacian
+from pymatting.laplacian.uniform_laplacian import uniform_laplacian
+from pymatting.laplacian.laplacian import make_linear_system
+
+LAPLACIANS = [
+ cf_laplacian,
+ knn_laplacian,
+ lbdm_laplacian,
+ rw_laplacian,
+ uniform_laplacian,
+]
+
+LAPLACIAN_OPERATORS = [
+ lkm_laplacian,
+]
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/cf_laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/cf_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b324c760a8980b891a5e95dcc04d9d415a02b8c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/cf_laplacian.py
@@ -0,0 +1,177 @@
+import numpy as np
+import scipy.sparse
+from numba import njit
+
+@njit("void(f8[:, :, :], f8, i8, f8[:, :, :], i8[:], i8[:], b1[:, :])", cache=True, nogil=True)
+def _cf_laplacian(image, epsilon, r, values, indices, indptr, is_known):
+ h, w, d = image.shape
+ assert d == 3
+ size = 2 * r + 1
+ window_area = size * size
+
+ for yi in range(h):
+ for xi in range(w):
+ i = xi + yi * w
+ k = i * (4 * r + 1) ** 2
+ for yj in range(yi - 2 * r, yi + 2 * r + 1):
+ for xj in range(xi - 2 * r, xi + 2 * r + 1):
+ j = xj + yj * w
+
+ if 0 <= xj < w and 0 <= yj < h:
+ indices[k] = j
+
+ k += 1
+
+ indptr[i + 1] = k
+
+ # Centered and normalized window colors
+ c = np.zeros((2 * r + 1, 2 * r + 1, 3))
+
+ # For each pixel of image
+ for y in range(r, h - r):
+ for x in range(r, w - r):
+
+ if np.all(is_known[y - r : y + r + 1, x - r : x + r + 1]):
+ continue
+
+ # For each color channel
+ for dc in range(3):
+ # Calculate sum of color channel in window
+ s = 0.0
+ for dy in range(size):
+ for dx in range(size):
+ s += image[y + dy - r, x + dx - r, dc]
+
+ # Calculate centered window color
+ for dy in range(2 * r + 1):
+ for dx in range(2 * r + 1):
+ c[dy, dx, dc] = (
+ image[y + dy - r, x + dx - r, dc] - s / window_area
+ )
+
+ # Calculate covariance matrix over color channels with epsilon regularization
+ a00 = epsilon
+ a01 = 0.0
+ a02 = 0.0
+ a11 = epsilon
+ a12 = 0.0
+ a22 = epsilon
+
+ for dy in range(size):
+ for dx in range(size):
+ a00 += c[dy, dx, 0] * c[dy, dx, 0]
+ a01 += c[dy, dx, 0] * c[dy, dx, 1]
+ a02 += c[dy, dx, 0] * c[dy, dx, 2]
+ a11 += c[dy, dx, 1] * c[dy, dx, 1]
+ a12 += c[dy, dx, 1] * c[dy, dx, 2]
+ a22 += c[dy, dx, 2] * c[dy, dx, 2]
+
+ a00 /= window_area
+ a01 /= window_area
+ a02 /= window_area
+ a11 /= window_area
+ a12 /= window_area
+ a22 /= window_area
+
+ det = (
+ a00 * a12 * a12
+ + a01 * a01 * a22
+ + a02 * a02 * a11
+ - a00 * a11 * a22
+ - 2 * a01 * a02 * a12
+ )
+
+ inv_det = 1.0 / det
+
+ # Calculate inverse covariance matrix
+ m00 = (a12 * a12 - a11 * a22) * inv_det
+ m01 = (a01 * a22 - a02 * a12) * inv_det
+ m02 = (a02 * a11 - a01 * a12) * inv_det
+ m11 = (a02 * a02 - a00 * a22) * inv_det
+ m12 = (a00 * a12 - a01 * a02) * inv_det
+ m22 = (a01 * a01 - a00 * a11) * inv_det
+
+ # For each pair ((xi, yi), (xj, yj)) in a (2 r + 1)x(2 r + 1) window
+ for dyi in range(2 * r + 1):
+ for dxi in range(2 * r + 1):
+ s = c[dyi, dxi, 0]
+ t = c[dyi, dxi, 1]
+ u = c[dyi, dxi, 2]
+
+ c0 = m00 * s + m01 * t + m02 * u
+ c1 = m01 * s + m11 * t + m12 * u
+ c2 = m02 * s + m12 * t + m22 * u
+
+ for dyj in range(2 * r + 1):
+ for dxj in range(2 * r + 1):
+ xi = x + dxi - r
+ yi = y + dyi - r
+ xj = x + dxj - r
+ yj = y + dyj - r
+
+ i = xi + yi * w
+ j = xj + yj * w
+
+ # Calculate contribution of pixel pair to L_ij
+ temp = (
+ c0 * c[dyj, dxj, 0]
+ + c1 * c[dyj, dxj, 1]
+ + c2 * c[dyj, dxj, 2]
+ )
+
+ value = (1.0 if (i == j) else 0.0) - (
+ 1 + temp
+ ) / window_area
+
+ dx = xj - xi + 2 * r
+ dy = yj - yi + 2 * r
+
+ values[i, dy, dx] += value
+
+
+def cf_laplacian(image, epsilon=1e-7, radius=1, is_known=None):
+ """
+ This function implements the alpha estimator for closed-form alpha matting
+ as proposed by :cite:`levin2007closed`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h\\times w \\times 3`
+ epsilon: float
+ Regularization strength, defaults to :math:`10^{-7}`. Strong
+ regularization improves convergence but results in smoother alpha mattes.
+ radius: int
+ Radius of local window size, defaults to :math:`1`, i.e. only adjacent
+ pixels are considered.
+ The size of the local window is given as :math:`(2 r + 1)^2`, where
+ :math:`r` denotes the radius. A larger radius might lead to
+ violated color line constraints, but also
+ favors further propagation of information within the image.
+ is_known: numpy.ndarray
+ Binary mask of pixels for which to compute the laplacian matrix.
+ Laplacian entries for known pixels will have undefined values.
+
+ Returns
+ -------
+ L: scipy.sparse.spmatrix
+ Matting Laplacian
+ """
+ h, w, d = image.shape
+ n = h * w
+
+ if is_known is None:
+ is_known = np.zeros((h, w), dtype=np.bool_)
+
+ is_known = is_known.reshape(h, w)
+
+ # Data for matting laplacian in csr format
+ indptr = np.zeros(n + 1, dtype=np.int64)
+ indices = np.zeros(n * (4 * radius + 1) ** 2, dtype=np.int64)
+ values = np.zeros((n, 4 * radius + 1, 4 * radius + 1), dtype=np.float64)
+
+ _cf_laplacian(image, epsilon, radius, values, indices, indptr, is_known)
+
+ L = scipy.sparse.csr_matrix((values.ravel(), indices, indptr), (n, n))
+
+ return L
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/knn_laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/knn_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf997adbb2fc29184041a0439beac6fe16e42be9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/knn_laplacian.py
@@ -0,0 +1,92 @@
+import numpy as np
+import scipy.sparse
+from pymatting.util.kdtree import knn
+from pymatting.util.util import normalize_rows
+
+
+def knn_laplacian(
+ image,
+ n_neighbors=[20, 10],
+ distance_weights=[2.0, 0.1],
+ kernel="binary",
+):
+ """
+ This function calculates the KNN matting Laplacian matrix similar to
+ :cite:`chen2013knn`.
+ We use a kernel of 1 instead of a soft kernel by default since the former is
+ faster to compute and both produce almost identical results in all our
+ experiments, which is to be expected as the soft kernel is very close to 1
+ in most cases.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h\\times w \\times 3`
+ n_neighbors: list of ints
+ Number of neighbors to consider. If :code:`len(n_neighbors)>1` multiple
+ nearest neighbor calculations are done and merged, defaults to
+ `[20, 10]`, i.e. first 20 neighbors are considered and in the second run
+ :math:`10` neighbors. The pixel distances are then weighted by the
+ :code:`distance_weights`.
+ distance_weights: list of floats
+ Weight of distance in feature vector, defaults to `[2.0, 0.1]`.
+ kernel: str
+ Must be either "binary" or "soft". Default is "binary".
+
+ Returns
+ -------
+ L: scipy.sparse.spmatrix
+ Matting Laplacian matrix
+ """
+ h, w = image.shape[:2]
+ r, g, b = image.reshape(-1, 3).T
+ n = w * h
+
+ if kernel not in ["binary", "soft"]:
+ raise ValueError("kernel must be binary/soft, but not " + kernel + ".")
+
+ x = np.tile(np.linspace(0, 1, w), h)
+ y = np.repeat(np.linspace(0, 1, h), w)
+
+ # Store weight matrix indices and values in sparse coordinate form.
+ i, j, coo_data = [], [], []
+
+ for k, distance_weight in zip(n_neighbors, distance_weights):
+ # Features consist of RGB color values and weighted spatial coordinates.
+ f = np.stack(
+ [r, g, b, distance_weight * x, distance_weight * y],
+ axis=1,
+ out=np.zeros((n, 5), dtype=np.float32),
+ )
+
+ # Find indices of nearest neighbors in feature space.
+ _, neighbor_indices = knn(f, f, k=k)
+
+ # [0 0 0 0 0 (k times) 1 1 1 1 1 2 2 2 2 2 ...]
+ i.append(np.repeat(np.arange(n), k))
+ j.append(neighbor_indices.ravel())
+
+ W_ij = np.ones(k * n)
+
+ if kernel == "soft":
+ W_ij -= np.abs(f[i[-1]] - f[j[-1]]).sum(axis=1) / f.shape[1]
+
+ coo_data.append(W_ij)
+
+ # Add matrix to itself to get a symmetric matrix.
+ # The '+' here is list concatenation and not addition.
+ # The csr_matrix constructor will do the addition later.
+ ij = np.concatenate(i + j)
+ ji = np.concatenate(j + i)
+ coo_data = np.concatenate(coo_data + coo_data)
+
+ # Assemble weights from coordinate sparse matrix format.
+ W = scipy.sparse.csr_matrix((coo_data, (ij, ji)), (n, n))
+
+ W = normalize_rows(W)
+
+ I = scipy.sparse.identity(n)
+
+ L = I - W
+
+ return L
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..9c1c7af4f6c0d9cc99a6c77402bec467fa6b0480
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/laplacian.py
@@ -0,0 +1,60 @@
+from pymatting.util.util import trimap_split
+import scipy.sparse
+
+
+def make_linear_system(L, trimap, lambda_value=100.0, return_c=False):
+ """This function constructs a linear system from a matting Laplacian by
+ constraining the foreground and background pixels with a diagonal matrix
+ `C` to values in the right-hand-side vector `b`. The constraints are
+ weighted by a factor :math:`\\lambda`. The linear system is given as
+
+ .. math::
+
+ A = L + \\lambda C,
+
+ where :math:`C=\\mathop{Diag}(c)` having :math:`c_i = 1` if pixel i is known
+ and :math:`c_i = 0` otherwise.
+ The right-hand-side :math:`b` is a vector with entries :math:`b_i = 1` is
+ pixel is is a foreground pixel and :math:`b_i = 0` otherwise.
+
+
+ Parameters
+ ----------
+ L: scipy.sparse.spmatrix
+ Laplacian matrix, e.g. calculated with :code:`lbdm_laplacian` function
+ trimap: numpy.ndarray
+ Trimap with shape :math:`h\\times w`
+ lambda_value: float
+ Constraint penalty, defaults to 100
+ return_c: bool
+ Whether to return the constraint matrix `C`, defaults to False
+
+ Returns
+ -------
+ A: scipy.sparse.spmatrix
+ Matrix describing the system of linear equations
+ b: numpy.ndarray
+ Vector describing the right-hand side of the system
+ C: numpy.ndarray
+ Vector describing the diagonal entries of the matrix `C`, only returned
+ if `return_c` is set to True
+ """
+ h, w = trimap.shape[:2]
+
+ is_fg, is_bg, is_known, is_unknown = trimap_split(trimap)
+
+ c = lambda_value * is_known
+ b = lambda_value * is_fg
+
+ C = scipy.sparse.diags(c)
+
+ A = L + C
+
+ A = A.tocsr()
+
+ A.sum_duplicates()
+
+ if return_c:
+ return A, b, c
+
+ return A, b
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/lbdm_laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/lbdm_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..48517817c2ee1e18261dc2dd0b5903f59295fc80
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/lbdm_laplacian.py
@@ -0,0 +1,94 @@
+import numpy as np
+import scipy.sparse
+from numba import njit
+
+@njit("f8[:, :](f8[:, :], f8)", cache=True, nogil=True)
+def calculate_kernel_matrix(X, v):
+ n, m = X.shape
+ K = np.zeros((n, n))
+ for i in range(n):
+ for j in range(n):
+ K[i, j] = np.exp(-np.sqrt(v) * np.sum(np.square(X[i] - X[j])))
+ return K
+
+
+@njit("Tuple((f8[:], i4[:], i4[:]))(f8[:, :, :], f8, i4)", cache=True, nogil=True)
+def _lbdm_laplacian(image, epsilon, r):
+ h, w = image.shape[:2]
+ n = h * w
+
+ area = (2 * r + 1) ** 2
+
+ indices = np.arange(n).reshape(h, w)
+
+ values = np.zeros((n, area ** 2))
+ i_inds = np.zeros((n, area ** 2), dtype=np.int32)
+ j_inds = np.zeros((n, area ** 2), dtype=np.int32)
+
+ # gray = (image[:, :, 0] + image[:, :, 1] + image[:, :, 2]) / 3.0
+ # v = np.std(gray)
+
+ for y in range(r, h - r):
+ for x in range(r, w - r):
+ i = x + y * w
+
+ X = np.ones((area, 3 + 1))
+
+ k = 0
+ for y2 in range(y - r, y + r + 1):
+ for x2 in range(x - r, x + r + 1):
+ for c in range(3):
+ X[k, c] = image[y2, x2, c]
+ k += 1
+
+ window_indices = indices[y - r : y + r + 1, x - r : x + r + 1].flatten()
+
+ # does not produce better results than no kernel
+ # K = calculate_kernel_matrix(X, v)
+
+ K = np.dot(X, X.T)
+
+ f = np.linalg.solve(K + epsilon * np.eye(area), K)
+
+ tmp2 = np.eye(f.shape[0]) - f
+ tmp3 = tmp2.dot(tmp2.T)
+
+ for k in range(area):
+ i_inds[i, k::area] = window_indices
+ j_inds[i, k * area : k * area + area] = window_indices
+ values[i] = tmp3.ravel()
+
+ return values.ravel(), i_inds.ravel(), j_inds.ravel()
+
+
+def lbdm_laplacian(image, epsilon=1e-7, radius=1):
+ """
+ Calculate a Laplacian matrix based on :cite:`zheng2009learning`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h\\times w \\times 3`
+ epsilon: float
+ Regularization strength, defaults to :math:`10^{-7}`. Strong
+ regularization improves convergence but results in smoother alpha mattes.
+ radius: int
+ Radius of local window size, defaults to :math:`1`, i.e. only adjacent
+ pixels are considered. The size of the local window is given as
+ :math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius
+ might lead to violated color line constraints, but also favors further
+ propagation of information within the image.
+
+ Returns
+ -------
+ L: scipy.sparse.csr_matrix
+ Matting Laplacian
+ """
+ h, w = image.shape[:2]
+ n = h * w
+
+ values, i_inds, j_inds = _lbdm_laplacian(image, epsilon, radius)
+
+ L = scipy.sparse.csr_matrix((values, (i_inds, j_inds)), shape=(n, n))
+
+ return L
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/lkm_laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/lkm_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..fac3695a21f81709188e32cac71869c8f89c958a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/lkm_laplacian.py
@@ -0,0 +1,76 @@
+import numpy as np
+from pymatting.util.util import vec_vec_dot, mat_vec_dot, vec_vec_outer
+from pymatting.util.boxfilter import boxfilter
+
+
+def lkm_laplacian(image, epsilon=1e-7, radius=10, return_diagonal=True):
+ """Calculates the Laplacian for large kernel matting :cite:`he2010fast`
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image of shape :math:`h\\times w \\times 3`
+ epsilons: float
+ Regularization strength, defaults to :math:`10^{-7}`
+ radius: int
+ Radius of local window size, defaults to :math:`10`, i.e. only adjacent
+ pixels are considered. The size of the local window is given as
+ :math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius
+ might lead to violated color line constraints, but also favors further
+ propagation of information within the image.
+ return_diagonal: bool
+ Whether to also return the diagonal of the laplacian, defaults to True
+
+ Returns
+ -------
+ L_matvec: function
+ Function that applies the Laplacian matrix to a vector
+ diag_L: numpy.ndarray
+ Diagonal entries of the matting Laplacian, only returns if
+ `return_diagonal` is True
+ """
+ image = image.astype(np.float64)
+
+ window_size = 2 * radius + 1
+ window_area = window_size * window_size
+ h, w, depth = image.shape
+
+ # means over neighboring pixels
+ means = boxfilter(image, radius, mode="valid") / window_area
+
+ # color covariance over neighboring pixels
+ covs = boxfilter(vec_vec_outer(image, image), radius, mode="valid") / window_area
+ covs -= vec_vec_outer(means, means)
+
+ # precompute values which do not depend on p
+ V = np.linalg.inv(covs + epsilon / window_area * np.eye(depth)) / window_area
+ Vm = mat_vec_dot(V, means)
+ mVm = 1 / window_area + vec_vec_dot(means, Vm)
+ c = boxfilter(np.ones((h - 2 * radius, w - 2 * radius)), radius, mode="full")
+
+ def L_matvec(p):
+ p = p.reshape(h, w)
+
+ p_sums = boxfilter(p, radius, mode="valid")
+ pI_sums = boxfilter(p[:, :, np.newaxis] * image, radius, mode="valid")
+
+ p_L = c * p
+
+ temp = p_sums[:, :, np.newaxis] * Vm - mat_vec_dot(V, pI_sums)
+ p_L += vec_vec_dot(image, boxfilter(temp, radius, mode="full"))
+
+ temp = p_sums * mVm - vec_vec_dot(pI_sums, Vm)
+ p_L -= boxfilter(temp, radius, mode="full")
+
+ return p_L.flatten()
+
+ if return_diagonal:
+ # compute diagonal of L
+ diag_L = boxfilter(1.0 - mVm, radius, mode="full")
+ temp = 2 * boxfilter(Vm, radius, mode="full")
+ temp -= mat_vec_dot(boxfilter(V, radius, mode="full"), image)
+ diag_L += vec_vec_dot(image, temp)
+
+ return L_matvec, diag_L.flatten()
+
+ return L_matvec
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/rw_laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/rw_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..14b9361658751e0fac7c202e56ca65bd5af5985c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/rw_laplacian.py
@@ -0,0 +1,81 @@
+import numpy as np
+import scipy.sparse
+from pymatting.util.util import weights_to_laplacian
+from numba import njit
+
+@njit("Tuple((f8[:], i4[:], i4[:]))(f8[:,:,:], f8, i4)", cache=True, nogil=True)
+def _rw_laplacian(image, sigma, r):
+ h, w = image.shape[:2]
+ n = h * w
+
+ m = n * (2 * r + 1) ** 2
+
+ i_inds = np.empty(m, dtype=np.int32)
+ j_inds = np.empty(m, dtype=np.int32)
+ values = np.empty(m)
+
+ k = 0
+
+ for y in range(h):
+ for x in range(w):
+ for dy in range(-r, r + 1):
+ for dx in range(-r, r + 1):
+ x2 = x + dx
+ y2 = y + dy
+
+ x2 = max(0, min(w - 1, x2))
+ y2 = max(0, min(h - 1, y2))
+
+ i = x + y * w
+ j = x2 + y2 * w
+
+ zi = image[y, x]
+ zj = image[y2, x2]
+
+ wij = np.exp(-900 * np.linalg.norm(zi - zj) ** 2)
+
+ i_inds[k] = i
+ j_inds[k] = j
+
+ values[k] = wij
+
+ k += 1
+
+ return values, i_inds, j_inds
+
+
+def rw_laplacian(image, sigma=0.033, radius=1, regularization=1e-8):
+ """
+ This function implements the alpha estimator for random walk alpha matting
+ as described in :cite:`grady2005random`.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h\\times w \\times 3`
+ sigma: float
+ Sigma used to calculate the weights (see Equation 4 in
+ :cite:`grady2005random`), defaults to :math:`0.033`
+ radius: int
+ Radius of local window size, defaults to :math:`1`, i.e. only adjacent
+ pixels are considered. The size of the local window is given as
+ :math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius
+ might lead to violated color line constraints, but also favors further
+ propagation of information within the image.
+ regularization: float
+ Regularization strength, defaults to :math:`10^{-8}`. Strong
+ regularization improves convergence but results in smoother alpha matte.
+
+ Returns
+ -------
+ L: scipy.sparse.spmatrix
+ Matting Laplacian
+ """
+ h, w = image.shape[:2]
+ n = h * w
+
+ values, i_inds, j_inds = _rw_laplacian(image, sigma, radius)
+
+ W = scipy.sparse.csr_matrix((values, (i_inds, j_inds)), shape=(n, n))
+
+ return weights_to_laplacian(W, regularization=regularization)
diff --git a/python_embeded/Lib/site-packages/pymatting/laplacian/uniform_laplacian.py b/python_embeded/Lib/site-packages/pymatting/laplacian/uniform_laplacian.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0f5f159dbb6121e002c3711f0a00446e6b17420
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/laplacian/uniform_laplacian.py
@@ -0,0 +1,31 @@
+from pymatting.util.util import (
+ grid_coordinates,
+ sparse_conv_matrix,
+ weights_to_laplacian,
+)
+import numpy as np
+
+
+def uniform_laplacian(image, radius=1):
+ """This function returns a Laplacian matrix with all weights equal to one.
+
+ Parameters
+ ----------
+ image: numpy.ndarray
+ Image with shape :math:`h\\times w \\times 3`
+ radius: int
+ Radius of local window size, defaults to 1, i.e. only adjacent pixels are considered.
+ The size of the local window is given as :math:`(2 r + 1)^2`, where :math:`r` denotes the radius. A larger radius might lead to violated color line constraints, but also
+ favors further propagation of information within the image.
+
+ Returns
+ -------
+ L: scipy.sparse.spmatrix
+ Matting Laplacian
+ """
+ height, width = image.shape[:2]
+ window_size = 2 * radius + 1
+
+ W = sparse_conv_matrix(width, height, np.ones((window_size, window_size)))
+
+ return weights_to_laplacian(W)
diff --git a/python_embeded/Lib/site-packages/pymatting/preconditioner/__init__.py b/python_embeded/Lib/site-packages/pymatting/preconditioner/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9831a19bcccad6b42185e566cb3b729fdeacbc8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/preconditioner/__init__.py
@@ -0,0 +1,3 @@
+from pymatting.preconditioner.ichol import ichol
+from pymatting.preconditioner.jacobi import jacobi
+from pymatting.preconditioner.vcycle import vcycle
diff --git a/python_embeded/Lib/site-packages/pymatting/preconditioner/ichol.py b/python_embeded/Lib/site-packages/pymatting/preconditioner/ichol.py
new file mode 100644
index 0000000000000000000000000000000000000000..23fc80be2dac253cd54eb67a44ba3e679fdead2d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/preconditioner/ichol.py
@@ -0,0 +1,301 @@
+import numpy as np
+import scipy.sparse
+from numba import njit
+
+
+@njit(
+ "i8(i8, f8[:], i8[:], i8[:], f8[:], i8[:], i8[:], f8, f8, i8, f8, b1)",
+ cache=True,
+ nogil=True,
+)
+def _ichol(
+ n,
+ Av,
+ Ar,
+ Ap,
+ Lv,
+ Lr,
+ Lp,
+ discard_threshold,
+ shift,
+ max_nnz,
+ relative_discard_threshold,
+ diag_keep_discarded,
+):
+ """
+ :cite:`jones1995improved` might be slightly interesting for the general idea
+ to use linked list to keep track of the sparse matrix values. But instead of
+ pointers, we have to use indices here, since this is Python and not C.
+ """
+ nnz = 0
+ c_n = 0
+ s = np.zeros(n, np.int64) # Next non-zero row index i in column j of L
+ t = np.zeros(n, np.int64) # First subdiagonal index i in column j of A
+ l = np.zeros(n, np.int64) - 1 # Linked list of non-zero columns in row k of L
+ a = np.zeros(n, np.float64) # Values of column j
+ r = np.zeros(n, np.float64) # r[j] = sum(abs(A[j:, j])) for relative threshold
+ b = np.zeros(n, np.bool_) # b[i] indicates if the i-th element of column j is non-zero
+ c = np.empty(n, np.int64) # Row indices of non-zero elements in column j
+ d = np.full(n, shift, np.float64) # Diagonal elements of A
+ for j in range(n):
+ for idx in range(Ap[j], Ap[j + 1]):
+ i = Ar[idx]
+ if i == j:
+ d[j] += Av[idx]
+ t[j] = idx + 1
+ if i >= j:
+ r[j] += abs(Av[idx])
+ for j in range(n): # For each column j
+ for idx in range(t[j], Ap[j + 1]): # For each L_ij
+ i = Ar[idx]
+ L_ij = Av[idx]
+ if L_ij != 0.0 and i > j:
+ a[i] += L_ij # Assign non-zero value to L_ij in sparse column
+ if not b[i]:
+ b[i] = True # Mark it as non-zero
+ c[c_n] = i # Remember index for later deletion
+ c_n += 1
+ k = l[j] # Find index k of column with non-zero element in row j
+ while k != -1: # For each column of that type
+ k0 = s[k] # Start index of non-zero elements in column k
+ k1 = Lp[k + 1] # End index
+ k2 = l[k] # Remember next column index before it is overwritten
+ L_jk = Lv[k0] # Value of non-zero element at start of column
+ k0 += 1 # Advance to next non-zero element in column
+ if k0 < k1: # If there is a next non-zero element
+ s[k] = k0 # Advance start index in column k to next non-zero element
+ i = Lr[k0] # Row index of next non-zero element in column k
+ l[k] = l[i] # Remember old list i index in list k
+ l[i] = k # Insert index of non-zero element into list i
+ for idx in range(k0, k1): # For each non-zero L_ik in column k
+ i = Lr[idx]
+ L_ik = Lv[idx]
+ a[i] -= L_ik * L_jk # Update element L_ij in sparse column
+ if not b[i]: # Check if sparse column element was zero
+ b[i] = True # Mark as non-zero in sparse column
+ c[c_n] = i # Remember index for later deletion
+ c_n += 1
+ k = k2 # Advance to next column k
+ if d[j] <= 0.0:
+ return -1
+ if nnz + 1 + c_n > max_nnz:
+ return -2
+ d[j] = np.sqrt(d[j]) # Update diagonal element L_ii
+ Lv[nnz] = d[j] # Add diagonal element L_ii to L
+ Lr[nnz] = j # Add row index of L_ii to L
+ nnz += 1
+ s[j] = nnz # Set first non-zero index of column j
+ for i in np.sort(
+ c[:c_n]
+ ): # Sort row indices of column j for correct insertion order into L
+ L_ij = a[i] / d[j] # Get non-zero element from sparse column j
+ if diag_keep_discarded:
+ d[i] -= L_ij * L_ij # Update diagonal element L_ii
+ rel = (
+ relative_discard_threshold * r[j]
+ ) # Relative discard threshold (before div)
+ if (
+ abs(L_ij) > discard_threshold and abs(a[i]) > rel
+ ): # If element is sufficiently non-zero
+ if not diag_keep_discarded:
+ d[i] -= L_ij * L_ij # Update diagonal element L_ii
+ Lv[nnz] = L_ij # Add element L_ij to L
+ Lr[nnz] = i # Add row index of L_ij
+ nnz += 1
+ a[i] = 0.0 # Set element i in column j to zero
+ b[i] = False # Mark element as zero
+ c_n = 0 # Discard row indices of non-zero elements in column j.
+ Lp[j + 1] = nnz # Update count of non-zero elements up to column j
+ if Lp[j] + 1 < Lp[j + 1]: # If column j has a non-zero element below diagonal
+ i = Lr[Lp[j] + 1] # Row index of first off-diagonal non-zero element
+ l[j] = l[i] # Remember old list i index in list j
+ l[i] = j # Insert index of non-zero element into list i
+ return nnz
+
+
+@njit("void(f8[:], i8[:], i8[:], f8[:], i8)", cache=True, nogil=True)
+def _backsub_L_csc_inplace(data, indices, indptr, x, n):
+ for j in range(n):
+ k = indptr[j]
+ L_jj = data[k]
+ temp = x[j] / L_jj
+
+ x[j] = temp
+
+ for k in range(indptr[j] + 1, indptr[j + 1]):
+ i = indices[k]
+ L_ij = data[k]
+
+ x[i] -= L_ij * temp
+
+
+@njit("void(f8[:], i8[:], i8[:], f8[:], i8)", cache=True, nogil=True)
+def _backsub_LT_csc_inplace(data, indices, indptr, x, n):
+ for i in range(n - 1, -1, -1):
+ s = x[i]
+
+ for k in range(indptr[i] + 1, indptr[i + 1]):
+ j = indices[k]
+ L_ji = data[k]
+ s -= L_ji * x[j]
+
+ k = indptr[i]
+ L_ii = data[k]
+
+ x[i] = s / L_ii
+
+
+class CholeskyDecomposition(object):
+ """Cholesky Decomposition
+
+ Calling this object applies the preconditioner to a vector by forward and back substitution.
+
+ Parameters
+ ----------
+ Ltuple: tuple of numpy.ndarrays
+ Tuple of array describing values, row indices and row pointers for Cholesky factor in the compressed sparse column format (csc)
+ """
+
+ def __init__(self, Ltuple):
+ self.Ltuple = Ltuple
+
+ @property
+ def L(self):
+ """Returns the Cholesky factor
+
+ Returns
+ -------
+ L: scipy.sparse.csc_matrix
+ Cholesky factor
+ """
+ Lv, Lr, Lp = self.Ltuple
+ n = len(Lp) - 1
+ return scipy.sparse.csc_matrix(self.Ltuple, (n, n))
+
+ def __call__(self, b):
+ Lv, Lr, Lp = self.Ltuple
+ n = len(b)
+ x = b.copy()
+ _backsub_L_csc_inplace(Lv, Lr, Lp, x, n)
+ _backsub_LT_csc_inplace(Lv, Lr, Lp, x, n)
+ return x
+
+
+def ichol(
+ A,
+ discard_threshold=1e-4,
+ shifts=[0.0, 1e-4, 1e-3, 1e-2, 0.1, 0.5, 1.0, 10.0, 100, 1e3, 1e4, 1e5],
+ max_nnz=int(4e9 / 16),
+ relative_discard_threshold=0.0,
+ diag_keep_discarded=True,
+):
+ """Implements the thresholded incomplete Cholesky decomposition.
+ For reference, a dense ichol implementation with relative threshold would look like this:
+
+ L = np.tril(A)
+ for j in range(n):
+ col = L[j:, j]
+ col -= np.sum(L[j, :j] * L[j:, :j], axis=1)
+ discard_mask = abs(col[1:]) < relative_discard_threshold * np.sum(np.abs(A[j:, j]))
+ col[1:][discard_mask] = 0
+ col[0] **= 0.5
+ col[1:] /= col[0]
+
+ Parameters
+ ----------
+ A: scipy.sparse.csc_matrix
+ Matrix for which the preconditioner should be calculated
+ discard_threshold: float
+ Values having an absolute value smaller than this threshold will be discarded while calculating the Cholesky decompositions
+ shifts: array of floats
+ Values to try for regularizing the matrix of interest in case it is not positive definite after discarding the small values
+ max_nnz: int
+ Maximum number of non-zero entries in the Cholesky decomposition. Defaults to 250 million, which should usually be around 4 GB.
+ relative_discard_threshold: float
+ Values with an absolute value of less than :code:`relative_discard_threshold * sum(abs(A[j:, j]))` will be discarded.
+ diag_keep_discarded: bool
+ Whether to update the diagonal with the discarded values. Usually better if :code:`True`.
+
+ Returns
+ -------
+ chol: CholeskyDecomposition
+ Preconditioner or solver object.
+
+ Raises
+ ------
+ ValueError:
+ If inappropriate parameter values were passed
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> import numpy as np
+ >>> from scipy.sparse import csc_matrix
+ >>> A = np.array([[2.0, 3.0], [3.0, 5.0]])
+ >>> cholesky_decomposition = ichol(csc_matrix(A))
+ >>> cholesky_decomposition(np.array([1.0, 2.0]))
+ array([-1., 1.])
+ """
+
+ if isinstance(A, scipy.sparse.csr_matrix):
+ A = A.T
+
+ if not isinstance(A, scipy.sparse.csc_matrix):
+ raise ValueError("Matrix A must be a scipy.sparse.csc_matrix")
+
+ if not A.has_canonical_format:
+ A.sum_duplicates()
+
+ m, n = A.shape
+
+ assert m == n
+
+ Lv = np.empty(max_nnz, dtype=np.float64) # Values of non-zero elements of L
+ Lr = np.empty(max_nnz, dtype=np.int64) # Row indices of non-zero elements of L
+ Lp = np.zeros(
+ n + 1, dtype=np.int64
+ ) # Start(Lp[i]) and end(Lp[i+1]) index of L[:, i] in Lv
+
+ for shift in shifts:
+ nnz = _ichol(
+ n,
+ A.data,
+ A.indices.astype(np.int64),
+ A.indptr.astype(np.int64),
+ Lv,
+ Lr,
+ Lp,
+ discard_threshold,
+ shift,
+ max_nnz,
+ relative_discard_threshold,
+ diag_keep_discarded,
+ )
+
+ if nnz >= 0:
+ break
+
+ if nnz == -1:
+ print("PERFORMANCE WARNING:")
+ print(
+ "Thresholded incomplete Cholesky decomposition failed due to insufficient positive-definiteness of matrix A with parameters:"
+ )
+ print(" discard_threshold = %e" % discard_threshold)
+ print(" shift = %e" % shift)
+ print("Try decreasing discard_threshold or start with a larger shift")
+ print("")
+
+ if nnz == -2:
+ raise ValueError(
+ "Thresholded incomplete Cholesky decomposition failed because more than max_nnz non-zero elements were created. Try increasing max_nnz or discard_threshold."
+ )
+
+ if nnz < 0:
+ raise ValueError(
+ "Thresholded incomplete Cholesky decomposition failed due to insufficient positive-definiteness of matrix A and diagonal shifts did not help."
+ )
+
+ Lv = Lv[:nnz]
+ Lr = Lr[:nnz]
+
+ return CholeskyDecomposition((Lv, Lr, Lp))
diff --git a/python_embeded/Lib/site-packages/pymatting/preconditioner/jacobi.py b/python_embeded/Lib/site-packages/pymatting/preconditioner/jacobi.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fe5e0e07634bf5c4caa29a09919cff3d224e5d3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/preconditioner/jacobi.py
@@ -0,0 +1,31 @@
+def jacobi(A):
+ """
+ Compute the Jacobi preconditioner function for the matrix A.
+
+ Parameters
+ ----------
+ A: np.array
+ Input matrix to compute the Jacobi preconditioner for.
+
+ Returns
+ -------
+ precondition_matvec: function
+ Function which applies the Jacobi preconditioner to a vector
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> import numpy as np
+ >>> A = np.array([[2, 3], [3, 5]])
+ >>> preconditioner = jacobi(A)
+ >>> preconditioner(np.array([1, 2]))
+ array([0.5, 0.4])
+ """
+ diagonal = A.diagonal()
+
+ inverse_diagonal = 1.0 / diagonal
+
+ def precondition_matvec(x):
+ return x * inverse_diagonal
+
+ return precondition_matvec
diff --git a/python_embeded/Lib/site-packages/pymatting/preconditioner/vcycle.py b/python_embeded/Lib/site-packages/pymatting/preconditioner/vcycle.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb24c9ad742c9e0656bae46d9588276a0015941c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/preconditioner/vcycle.py
@@ -0,0 +1,153 @@
+import numpy as np
+import scipy.sparse
+import scipy.sparse.linalg
+
+
+def make_P(shape):
+ h, w = shape
+ n = h * w
+ h2 = h // 2
+ w2 = w // 2
+ n2 = w2 * h2
+ weights = np.float64([1, 2, 1, 2, 4, 2, 1, 2, 1]) / 16
+
+ x2 = np.repeat(np.tile(np.arange(w2), h2), 9)
+ y2 = np.repeat(np.repeat(np.arange(h2), w2), 9)
+
+ x = x2 * 2 + np.tile([-1, 0, 1, -1, 0, 1, -1, 0, 1], n2)
+ y = y2 * 2 + np.tile([-1, -1, -1, 0, 0, 0, 1, 1, 1], n2)
+
+ mask = (0 <= x) & (x < w) & (0 <= y) & (y <= h)
+
+ i_inds = (x2 + y2 * w2)[mask]
+ j_inds = (x + y * w)[mask]
+ values = np.tile(weights, n2)[mask]
+
+ downsample = scipy.sparse.csr_matrix((values, (i_inds, j_inds)), (n2, n))
+ upsample = downsample.T
+
+ return upsample, downsample
+
+
+def jacobi_step(A, A_diag, b, x, num_iter, omega):
+ if x is None:
+ if num_iter > 0:
+ x = omega * b / A_diag
+ num_iter -= 1
+ else:
+ x = np.zeros_like(b)
+
+ for _ in range(num_iter):
+ x = x + omega * (b - A.dot(x)) / A_diag
+
+ return x
+
+
+def _vcycle_step(
+ A,
+ b,
+ shape,
+ cache,
+ num_pre_iter,
+ num_post_iter,
+ omega,
+ direct_solve_size,
+):
+ h, w = shape
+ n = h * w
+
+ if n <= direct_solve_size:
+ return scipy.sparse.linalg.spsolve(A, b)
+
+ if shape not in cache:
+ upsample, downsample = make_P(shape)
+
+ coarse_A = downsample.dot(A).dot(upsample)
+
+ A_diag = A.diagonal()
+
+ cache[shape] = (upsample, downsample, coarse_A, A_diag)
+ else:
+ upsample, downsample, coarse_A, A_diag = cache[shape]
+
+ # smooth error
+ x = jacobi_step(A, A_diag, b, None, num_pre_iter, omega)
+
+ # calculate residual error to perfect solution
+ residual = b - A.dot(x)
+
+ # downsample residual error
+ coarse_residual = downsample.dot(residual)
+
+ # calculate coarse solution for residual
+ coarse_x = _vcycle_step(
+ coarse_A,
+ coarse_residual,
+ (h // 2, w // 2),
+ cache,
+ num_pre_iter,
+ num_post_iter,
+ omega,
+ direct_solve_size,
+ )
+
+ # apply coarse correction
+ x += upsample.dot(coarse_x)
+
+ # smooth error
+ x = jacobi_step(A, A_diag, b, x, num_post_iter, omega)
+
+ return x
+
+
+def vcycle(
+ A,
+ shape,
+ num_pre_iter=1,
+ num_post_iter=1,
+ omega=0.8,
+ direct_solve_size=64,
+ cache=None,
+):
+ """
+ Implements the V-Cycle preconditioner.
+ The V-Cycle solver was recommended by :cite:`lee2014scalable` to solve the alpha matting problem.
+
+ Parameters
+ ----------
+ A: numpy.ndarray
+ Input matrix
+ shape: tuple of ints
+ Describing the height and width of the image
+ num_pre_iter: int
+ Number of Jacobi iterations before each V-Cycle, defaults to 1
+ num_post_iter: int
+ Number of Jacobi iterations after each V-Cycle, defaults to 1
+ omega: float
+ Weight parameter for the Jacobi method. If method fails to converge, try different values.
+
+ Returns
+ -------
+ precondition: function
+ Function which applies the V-Cycle preconditioner to a vector
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> import numpy as np
+ >>> from scipy.sparse import csc_matrix
+ >>> A = np.array([[2, 3], [3, 5]])
+ >>> preconditioner = vcycle(A, (2, 2))
+ >>> preconditioner(np.array([1, 2]))
+ array([-1., 1.])
+ """
+
+ if cache is None:
+ cache = {}
+
+ def precondition(r):
+ return _vcycle_step(
+ A, r, shape, cache, num_pre_iter, num_post_iter, omega, direct_solve_size
+ )
+
+ return precondition
diff --git a/python_embeded/Lib/site-packages/pymatting/solver/__init__.py b/python_embeded/Lib/site-packages/pymatting/solver/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..121679e5b7e7f44ac0d1df0c47dcf1f1a49f2443
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/solver/__init__.py
@@ -0,0 +1,2 @@
+from pymatting.solver.cg import cg
+from pymatting.solver.callback import CounterCallback, ProgressCallback
diff --git a/python_embeded/Lib/site-packages/pymatting/solver/callback.py b/python_embeded/Lib/site-packages/pymatting/solver/callback.py
new file mode 100644
index 0000000000000000000000000000000000000000..45b8522f1eb9f97c13bafda519c9e70e657da9fc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/solver/callback.py
@@ -0,0 +1,23 @@
+class CounterCallback(object):
+ """Callback to count number of iterations of iterative solvers."""
+
+ def __init__(self):
+ self.n = 0
+
+ def __call__(self, A, x, b, norm_b, r, norm_r):
+ self.n += 1
+
+
+class ProgressCallback(object):
+ """
+ Callback to count number of iterations of iterative solvers.
+ Also prints residual error.
+ """
+
+ def __init__(self):
+ self.n = 0
+
+ def __call__(self, A, x, b, norm_b, r, norm_r):
+ self.n += 1
+
+ print("iteration %7d - %e (%.20f)" % (self.n, norm_r, norm_r))
diff --git a/python_embeded/Lib/site-packages/pymatting/solver/cg.py b/python_embeded/Lib/site-packages/pymatting/solver/cg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a99a34f41c4fccd7c0668e41afaf1b7d7462d979
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pymatting/solver/cg.py
@@ -0,0 +1,117 @@
+import numpy as np
+
+
+def cg(
+ A,
+ b,
+ x0=None,
+ atol=0.0,
+ rtol=1e-7,
+ maxiter=10000,
+ callback=None,
+ M=None,
+ reorthogonalize=False,
+):
+ """Solves a system of linear equations :math:`Ax=b` using conjugate gradient descent :cite:`hestenes1952methods`
+
+ Parameters
+ ----------
+ A: scipy.sparse.csr_matrix
+ Square matrix
+ b: numpy.ndarray
+ Vector describing the right-hand side of the system
+ x0: numpy.ndarray
+ Initialization, if `None` then :code:`x=np.zeros_like(b)`
+ atol: float
+ Absolute tolerance. The loop terminates if the :math:`||r||` is smaller than `atol`, where :math:`r` denotes the residual of the current iterate.
+ rtol: float
+ Relative tolerance. The loop terminates if :math:`{||r||}/{||b||}` is smaller than `rtol`, where :math:`r` denotes the residual of the current iterate.
+ callback: function
+ Function :code:`callback(A, x, b, norm_b, r, norm_r)` called after each iteration, defaults to `None`
+ M: function or scipy.sparse.csr_matrix
+ Function that applies the preconditioner to a vector. Alternatively, `M` can be a matrix describing the precondioner.
+ reorthogonalize: boolean
+ Whether to apply reorthogonalization of the residuals after each update, defaults to `False`
+
+
+ Returns
+ -------
+ x: numpy.ndarray
+ Solution of the system
+
+ Example
+ -------
+ >>> from pymatting import *
+ >>> import numpy as np
+ >>> A = np.array([[3.0, 1.0], [1.0, 2.0]])
+ >>> M = jacobi(A)
+ >>> b = np.array([4.0, 3.0])
+ >>> cg(A, b, M=M)
+ array([1., 1.])
+ """
+ if M is None:
+
+ def precondition(x):
+ return x
+
+ elif callable(M):
+ precondition = M
+ else:
+
+ def precondition(x):
+ return M.dot(x)
+
+ x = np.zeros_like(b) if x0 is None else x0.copy()
+
+ norm_b = np.linalg.norm(b)
+
+ if callable(A):
+ r = b - A(x)
+ else:
+ r = b - A.dot(x)
+
+ norm_r = np.linalg.norm(r)
+
+ if norm_r < atol or norm_r < rtol * norm_b:
+ return x
+
+ z = precondition(r)
+ p = z.copy()
+ rz = np.inner(r, z)
+
+ for iteration in range(maxiter):
+ r_old = r.copy()
+
+ if callable(A):
+ Ap = A(p)
+ else:
+ Ap = A.dot(p)
+
+ alpha = rz / np.inner(p, Ap)
+ x += alpha * p
+ r -= alpha * Ap
+
+ norm_r = np.linalg.norm(r)
+
+ if callback is not None:
+ callback(A, x, b, norm_b, r, norm_r)
+
+ if norm_r < atol or norm_r < rtol * norm_b:
+ return x
+
+ z = precondition(r)
+
+ if reorthogonalize:
+ beta = np.inner(r - r_old, z) / rz
+ rz = np.inner(r, z)
+ else:
+ beta = 1.0 / rz
+ rz = np.inner(r, z)
+ beta *= rz
+
+ p *= beta
+ p += z
+
+ raise ValueError(
+ "Conjugate gradient descent did not converge within %d iterations" % maxiter
+ )
diff --git a/python_embeded/Lib/site-packages/pyparsing/diagram/__init__.py b/python_embeded/Lib/site-packages/pyparsing/diagram/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..526cf3862a471a2073dbc559cca533404a10671e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyparsing/diagram/__init__.py
@@ -0,0 +1,754 @@
+# mypy: ignore-errors
+from __future__ import annotations
+
+import itertools
+import railroad
+import pyparsing
+import dataclasses
+import typing
+from typing import (
+ Generic,
+ TypeVar,
+ Callable,
+ Iterable,
+)
+from jinja2 import Template
+from io import StringIO
+import inspect
+import re
+
+
+jinja2_template_source = """\
+{% if not embed %}
+
+
+
+{% endif %}
+ {% if not head %}
+
+ {% else %}
+ {{ head | safe }}
+ {% endif %}
+{% if not embed %}
+
+
+{% endif %}
+
+{{ body | safe }}
+{% for diagram in diagrams %}
+
+
{{ diagram.title }}
+
{{ diagram.text }}
+
+ {{ diagram.svg }}
+
+
+{% endfor %}
+{% if not embed %}
+
+
+{% endif %}
+"""
+
+template = Template(jinja2_template_source)
+
+
+_bookmark_lookup = {}
+_bookmark_ids = itertools.count(start=1)
+
+def _make_bookmark(s: str) -> str:
+ """
+ Converts a string into a valid HTML bookmark (ID or anchor name).
+ """
+ if s in _bookmark_lookup:
+ return _bookmark_lookup[s]
+
+ # Replace invalid characters with hyphens and ensure only valid characters
+ bookmark = re.sub(r'[^a-zA-Z0-9-]+', '-', s)
+
+ # Ensure it starts with a letter by adding 'z' if necessary
+ if not bookmark[:1].isalpha():
+ bookmark = f"z{bookmark}"
+
+ # Convert to lowercase and strip hyphens
+ bookmark = bookmark.lower().strip('-')
+
+ _bookmark_lookup[s] = bookmark = f"{bookmark}-{next(_bookmark_ids):04d}"
+
+ return bookmark
+
+
+def _collapse_verbose_regex(regex_str: str) -> str:
+ if "\n" not in regex_str:
+ return regex_str
+ collapsed = pyparsing.Regex(r"#.*$").suppress().transform_string(regex_str)
+ collapsed = re.sub(r"\s*\n\s*", "", collapsed)
+ return collapsed
+
+
+@dataclasses.dataclass
+class NamedDiagram:
+ """
+ A simple structure for associating a name with a railroad diagram
+ """
+
+ name: str
+ index: int
+ diagram: railroad.DiagramItem = None
+
+ @property
+ def bookmark(self):
+ bookmark = _make_bookmark(self.name)
+ return bookmark
+
+
+T = TypeVar("T")
+
+
+class EachItem(railroad.Group):
+ """
+ Custom railroad item to compose a:
+ - Group containing a
+ - OneOrMore containing a
+ - Choice of the elements in the Each
+ with the group label indicating that all must be matched
+ """
+
+ all_label = "[ALL]"
+
+ def __init__(self, *items) -> None:
+ choice_item = railroad.Choice(len(items) - 1, *items)
+ one_or_more_item = railroad.OneOrMore(item=choice_item)
+ super().__init__(one_or_more_item, label=self.all_label)
+
+
+class AnnotatedItem(railroad.Group):
+ """
+ Simple subclass of Group that creates an annotation label
+ """
+
+ def __init__(self, label: str, item) -> None:
+ super().__init__(item=item, label=f"[{label}]" if label else "")
+
+
+class EditablePartial(Generic[T]):
+ """
+ Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been
+ constructed.
+ """
+
+ # We need this here because the railroad constructors actually transform the data, so can't be called until the
+ # entire tree is assembled
+
+ def __init__(self, func: Callable[..., T], args: list, kwargs: dict) -> None:
+ self.func = func
+ self.args = args
+ self.kwargs = kwargs
+
+ @classmethod
+ def from_call(cls, func: Callable[..., T], *args, **kwargs) -> EditablePartial[T]:
+ """
+ If you call this function in the same way that you would call the constructor, it will store the arguments
+ as you expect. For example EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)
+ """
+ return EditablePartial(func=func, args=list(args), kwargs=kwargs)
+
+ @property
+ def name(self):
+ return self.kwargs["name"]
+
+ def __call__(self) -> T:
+ """
+ Evaluate the partial and return the result
+ """
+ args = self.args.copy()
+ kwargs = self.kwargs.copy()
+
+ # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g.
+ # args=['list', 'of', 'things'])
+ arg_spec = inspect.getfullargspec(self.func)
+ if arg_spec.varargs in self.kwargs:
+ args += kwargs.pop(arg_spec.varargs)
+
+ return self.func(*args, **kwargs)
+
+
+def railroad_to_html(diagrams: list[NamedDiagram], embed=False, **kwargs) -> str:
+ """
+ Given a list of NamedDiagram, produce a single HTML string that visualises those diagrams
+ :params kwargs: kwargs to be passed in to the template
+ """
+ data = []
+ for diagram in diagrams:
+ if diagram.diagram is None:
+ continue
+ io = StringIO()
+ try:
+ css = kwargs.get("css")
+ diagram.diagram.writeStandalone(io.write, css=css)
+ except AttributeError:
+ diagram.diagram.writeSvg(io.write)
+ title = diagram.name
+ if diagram.index == 0:
+ title += " (root)"
+ data.append(
+ {
+ "title": title, "text": "", "svg": io.getvalue(), "bookmark": diagram.bookmark
+ }
+ )
+
+ return template.render(diagrams=data, embed=embed, **kwargs)
+
+
+def resolve_partial(partial: EditablePartial[T]) -> T:
+ """
+ Recursively resolves a collection of Partials into whatever type they are
+ """
+ if isinstance(partial, EditablePartial):
+ partial.args = resolve_partial(partial.args)
+ partial.kwargs = resolve_partial(partial.kwargs)
+ return partial()
+ elif isinstance(partial, list):
+ return [resolve_partial(x) for x in partial]
+ elif isinstance(partial, dict):
+ return {key: resolve_partial(x) for key, x in partial.items()}
+ else:
+ return partial
+
+
+def to_railroad(
+ element: pyparsing.ParserElement,
+ diagram_kwargs: typing.Optional[dict] = None,
+ vertical: int = 3,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+ show_hidden: bool = False,
+) -> list[NamedDiagram]:
+ """
+ Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram
+ creation if you want to access the Railroad tree before it is converted to HTML
+ :param element: base element of the parser being diagrammed
+ :param diagram_kwargs: kwargs to pass to the Diagram() constructor
+ :param vertical: (optional) - int - limit at which number of alternatives should be
+ shown vertically instead of horizontally
+ :param show_results_names - bool to indicate whether results name annotations should be
+ included in the diagram
+ :param show_groups - bool to indicate whether groups should be highlighted with an unlabeled
+ surrounding box
+ :param show_hidden - bool to indicate whether internal elements that are typically hidden
+ should be shown
+ """
+ # Convert the whole tree underneath the root
+ lookup = ConverterState(diagram_kwargs=diagram_kwargs or {})
+ _to_diagram_element(
+ element,
+ lookup=lookup,
+ parent=None,
+ vertical=vertical,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ show_hidden=show_hidden,
+ )
+
+ root_id = id(element)
+ # Convert the root if it hasn't been already
+ if root_id in lookup:
+ if not element.customName:
+ lookup[root_id].name = ""
+ lookup[root_id].mark_for_extraction(root_id, lookup, force=True)
+
+ # Now that we're finished, we can convert from intermediate structures into Railroad elements
+ diags = list(lookup.diagrams.values())
+ if len(diags) > 1:
+ # collapse out duplicate diags with the same name
+ seen = set()
+ deduped_diags = []
+ for d in diags:
+ # don't extract SkipTo elements, they are uninformative as subdiagrams
+ if d.name == "...":
+ continue
+ if d.name is not None and d.name not in seen:
+ seen.add(d.name)
+ deduped_diags.append(d)
+ resolved = [resolve_partial(partial) for partial in deduped_diags]
+ else:
+ # special case - if just one diagram, always display it, even if
+ # it has no name
+ resolved = [resolve_partial(partial) for partial in diags]
+ return sorted(resolved, key=lambda diag: diag.index)
+
+
+def _should_vertical(
+ specification: int, exprs: Iterable[pyparsing.ParserElement]
+) -> bool:
+ """
+ Returns true if we should return a vertical list of elements
+ """
+ if specification is None:
+ return False
+ else:
+ return len(_visible_exprs(exprs)) >= specification
+
+
+@dataclasses.dataclass
+class ElementState:
+ """
+ State recorded for an individual pyparsing Element
+ """
+
+ #: The pyparsing element that this represents
+ element: pyparsing.ParserElement
+ #: The output Railroad element in an unconverted state
+ converted: EditablePartial
+ #: The parent Railroad element, which we store so that we can extract this if it's duplicated
+ parent: EditablePartial
+ #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram
+ number: int
+ #: The name of the element
+ name: str = None
+ #: The index of this inside its parent
+ parent_index: typing.Optional[int] = None
+ #: If true, we should extract this out into a subdiagram
+ extract: bool = False
+ #: If true, all of this element's children have been filled out
+ complete: bool = False
+
+ def mark_for_extraction(
+ self, el_id: int, state: ConverterState, name: str = None, force: bool = False
+ ):
+ """
+ Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram
+ :param el_id: id of the element
+ :param state: element/diagram state tracker
+ :param name: name to use for this element's text
+ :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the
+ root element when we know we're finished
+ """
+ self.extract = True
+
+ # Set the name
+ if not self.name:
+ if name:
+ # Allow forcing a custom name
+ self.name = name
+ elif self.element.customName:
+ self.name = self.element.customName
+ else:
+ self.name = ""
+
+ # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children
+ # to be added
+ # Also, if this is just a string literal etc, don't bother extracting it
+ if force or (self.complete and _worth_extracting(self.element)):
+ state.extract_into_diagram(el_id)
+
+
+class ConverterState:
+ """
+ Stores some state that persists between recursions into the element tree
+ """
+
+ def __init__(self, diagram_kwargs: typing.Optional[dict] = None) -> None:
+ #: A dictionary mapping ParserElements to state relating to them
+ self._element_diagram_states: dict[int, ElementState] = {}
+ #: A dictionary mapping ParserElement IDs to subdiagrams generated from them
+ self.diagrams: dict[int, EditablePartial[NamedDiagram]] = {}
+ #: The index of the next unnamed element
+ self.unnamed_index: int = 1
+ #: The index of the next element. This is used for sorting
+ self.index: int = 0
+ #: Shared kwargs that are used to customize the construction of diagrams
+ self.diagram_kwargs: dict = diagram_kwargs or {}
+ self.extracted_diagram_names: set[str] = set()
+
+ def __setitem__(self, key: int, value: ElementState):
+ self._element_diagram_states[key] = value
+
+ def __getitem__(self, key: int) -> ElementState:
+ return self._element_diagram_states[key]
+
+ def __delitem__(self, key: int):
+ del self._element_diagram_states[key]
+
+ def __contains__(self, key: int):
+ return key in self._element_diagram_states
+
+ def get(self, key, default=None):
+ try:
+ return self[key]
+ except KeyError:
+ return default
+
+ def generate_unnamed(self) -> int:
+ """
+ Generate a number used in the name of an otherwise unnamed diagram
+ """
+ self.unnamed_index += 1
+ return self.unnamed_index
+
+ def generate_index(self) -> int:
+ """
+ Generate a number used to index a diagram
+ """
+ self.index += 1
+ return self.index
+
+ def extract_into_diagram(self, el_id: int):
+ """
+ Used when we encounter the same token twice in the same tree. When this
+ happens, we replace all instances of that token with a terminal, and
+ create a new subdiagram for the token
+ """
+ position = self[el_id]
+
+ # Replace the original definition of this element with a regular block
+ if position.parent:
+ href = f"#{_make_bookmark(position.name)}"
+ ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name, href=href)
+ if "item" in position.parent.kwargs:
+ position.parent.kwargs["item"] = ret
+ elif "items" in position.parent.kwargs:
+ position.parent.kwargs["items"][position.parent_index] = ret
+
+ # If the element we're extracting is a group, skip to its content but keep the title
+ if position.converted.func == railroad.Group:
+ content = position.converted.kwargs["item"]
+ else:
+ content = position.converted
+
+ self.diagrams[el_id] = EditablePartial.from_call(
+ NamedDiagram,
+ name=position.name,
+ diagram=EditablePartial.from_call(
+ railroad.Diagram, content, **self.diagram_kwargs
+ ),
+ index=position.number,
+ )
+
+ del self[el_id]
+
+
+def _worth_extracting(element: pyparsing.ParserElement) -> bool:
+ """
+ Returns true if this element is worth having its own sub-diagram. Simply, if any of its children
+ themselves have children, then its complex enough to extract
+ """
+ children = element.recurse()
+ return any(child.recurse() for child in children)
+
+
+def _apply_diagram_item_enhancements(fn):
+ """
+ decorator to ensure enhancements to a diagram item (such as results name annotations)
+ get applied on return from _to_diagram_element (we do this since there are several
+ returns in _to_diagram_element)
+ """
+
+ def _inner(
+ element: pyparsing.ParserElement,
+ parent: typing.Optional[EditablePartial],
+ lookup: ConverterState = None,
+ vertical: int = None,
+ index: int = 0,
+ name_hint: str = None,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+ show_hidden: bool = False,
+ ) -> typing.Optional[EditablePartial]:
+ ret = fn(
+ element,
+ parent,
+ lookup,
+ vertical,
+ index,
+ name_hint,
+ show_results_names,
+ show_groups,
+ show_hidden,
+ )
+
+ # apply annotation for results name, if present
+ if show_results_names and ret is not None:
+ element_results_name = element.resultsName
+ if element_results_name:
+ # add "*" to indicate if this is a "list all results" name
+ modal_tag = "" if element.modalResults else "*"
+ ret = EditablePartial.from_call(
+ railroad.Group,
+ item=ret,
+ label=f"{repr(element_results_name)}{modal_tag}",
+ )
+
+ return ret
+
+ return _inner
+
+
+def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]):
+ non_diagramming_exprs = (
+ pyparsing.ParseElementEnhance,
+ pyparsing.PositionToken,
+ pyparsing.And._ErrorStop,
+ )
+ return [
+ e
+ for e in exprs
+ if not isinstance(e, non_diagramming_exprs)
+ ]
+
+
+@_apply_diagram_item_enhancements
+def _to_diagram_element(
+ element: pyparsing.ParserElement,
+ parent: typing.Optional[EditablePartial],
+ lookup: ConverterState = None,
+ vertical: int = None,
+ index: int = 0,
+ name_hint: str = None,
+ show_results_names: bool = False,
+ show_groups: bool = False,
+ show_hidden: bool = False,
+) -> typing.Optional[EditablePartial]:
+ """
+ Recursively converts a PyParsing Element to a railroad Element
+ :param lookup: The shared converter state that keeps track of useful things
+ :param index: The index of this element within the parent
+ :param parent: The parent of this element in the output tree
+ :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default),
+ it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never
+ do so
+ :param name_hint: If provided, this will override the generated name
+ :param show_results_names: bool flag indicating whether to add annotations for results names
+ :param show_groups: bool flag indicating whether to show groups using bounding box
+ :param show_hidden: bool flag indicating whether to show elements that are typically hidden
+ :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed
+ """
+ exprs = element.recurse()
+ name = name_hint or element.customName or type(element).__name__
+
+ # Python's id() is used to provide a unique identifier for elements
+ el_id = id(element)
+
+ element_results_name = element.resultsName
+
+ # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram
+ if not element.customName:
+ if isinstance(
+ element,
+ (
+ # pyparsing.TokenConverter,
+ pyparsing.Forward,
+ pyparsing.Located,
+ ),
+ ):
+ # However, if this element has a useful custom name, and its child does not, we can pass it on to the child
+ if exprs:
+ if not exprs[0].customName:
+ propagated_name = name
+ else:
+ propagated_name = None
+
+ return _to_diagram_element(
+ element.expr,
+ parent=parent,
+ lookup=lookup,
+ vertical=vertical,
+ index=index,
+ name_hint=propagated_name,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ show_hidden=show_hidden,
+ )
+
+ # If the element isn't worth extracting, we always treat it as the first time we say it
+ if _worth_extracting(element):
+ looked_up = lookup.get(el_id)
+ if looked_up and looked_up.name is not None:
+ # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate,
+ # so we have to extract it into a new diagram.
+ looked_up.mark_for_extraction(el_id, lookup, name=name_hint)
+ href = f"#{_make_bookmark(looked_up.name)}"
+ ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name, href=href)
+ return ret
+
+ elif el_id in lookup.diagrams:
+ # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we
+ # just put in a marker element that refers to the sub-diagram
+ text = lookup.diagrams[el_id].kwargs["name"]
+ ret = EditablePartial.from_call(
+ railroad.NonTerminal, text=text, href=f"#{_make_bookmark(text)}"
+ )
+ return ret
+
+ # Recursively convert child elements
+ # Here we find the most relevant Railroad element for matching pyparsing Element
+ # We use ``items=[]`` here to hold the place for where the child elements will go once created
+
+ # see if this element is normally hidden, and whether hidden elements are desired
+ # if not, just return None
+ if not element.show_in_diagram and not show_hidden:
+ return None
+
+ if isinstance(element, pyparsing.And):
+ # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat
+ # (all will have the same name, and resultsName)
+ if not exprs:
+ return None
+ if len(set((e.name, e.resultsName) for e in exprs)) == 1 and len(exprs) > 2:
+ ret = EditablePartial.from_call(
+ railroad.OneOrMore, item="", repeat=str(len(exprs))
+ )
+ elif _should_vertical(vertical, exprs):
+ ret = EditablePartial.from_call(railroad.Stack, items=[])
+ else:
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
+ elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)):
+ if not exprs:
+ return None
+ if _should_vertical(vertical, exprs):
+ ret = EditablePartial.from_call(railroad.Choice, 0, items=[])
+ else:
+ ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[])
+ elif isinstance(element, pyparsing.Each):
+ if not exprs:
+ return None
+ ret = EditablePartial.from_call(EachItem, items=[])
+ elif isinstance(element, pyparsing.NotAny):
+ ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="")
+ elif isinstance(element, pyparsing.FollowedBy):
+ ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="")
+ elif isinstance(element, pyparsing.PrecededBy):
+ ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="")
+ elif isinstance(element, pyparsing.Group):
+ if show_groups:
+ ret = EditablePartial.from_call(AnnotatedItem, label="", item="")
+ else:
+ ret = EditablePartial.from_call(
+ railroad.Group, item=None, label=element_results_name
+ )
+ elif isinstance(element, pyparsing.TokenConverter):
+ label = type(element).__name__.lower()
+ if label == "tokenconverter":
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
+ else:
+ ret = EditablePartial.from_call(AnnotatedItem, label=label, item="")
+ elif isinstance(element, pyparsing.Opt):
+ ret = EditablePartial.from_call(railroad.Optional, item="")
+ elif isinstance(element, pyparsing.OneOrMore):
+ if element.not_ender is not None:
+ args = [
+ parent,
+ lookup,
+ vertical,
+ index,
+ name_hint,
+ show_results_names,
+ show_groups,
+ show_hidden,
+ ]
+ return _to_diagram_element(
+ (~element.not_ender.expr + element.expr)[1, ...].set_name(element.name),
+ *args,
+ )
+ ret = EditablePartial.from_call(railroad.OneOrMore, item=None)
+ elif isinstance(element, pyparsing.ZeroOrMore):
+ if element.not_ender is not None:
+ args = [
+ parent,
+ lookup,
+ vertical,
+ index,
+ name_hint,
+ show_results_names,
+ show_groups,
+ show_hidden,
+ ]
+ return _to_diagram_element(
+ (~element.not_ender.expr + element.expr)[...].set_name(element.name),
+ *args,
+ )
+ ret = EditablePartial.from_call(railroad.ZeroOrMore, item="")
+ elif isinstance(element, pyparsing.Empty) and not element.customName:
+ # Skip unnamed "Empty" elements
+ ret = None
+ elif isinstance(element, pyparsing.ParseElementEnhance):
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
+ elif len(exprs) > 0 and not element_results_name:
+ ret = EditablePartial.from_call(railroad.Group, item="", label=name)
+ elif isinstance(element, pyparsing.Regex):
+ collapsed_patt = _collapse_verbose_regex(element.pattern)
+ ret = EditablePartial.from_call(railroad.Terminal, collapsed_patt)
+ elif len(exprs) > 0:
+ ret = EditablePartial.from_call(railroad.Sequence, items=[])
+ else:
+ terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName)
+ ret = terminal
+
+ if ret is None:
+ return
+
+ # Indicate this element's position in the tree so we can extract it if necessary
+ lookup[el_id] = ElementState(
+ element=element,
+ converted=ret,
+ parent=parent,
+ parent_index=index,
+ number=lookup.generate_index(),
+ )
+ if element.customName:
+ lookup[el_id].mark_for_extraction(el_id, lookup, element.customName)
+
+ i = 0
+ for expr in exprs:
+ # Add a placeholder index in case we have to extract the child before we even add it to the parent
+ if "items" in ret.kwargs:
+ ret.kwargs["items"].insert(i, None)
+
+ item = _to_diagram_element(
+ expr,
+ parent=ret,
+ lookup=lookup,
+ vertical=vertical,
+ index=i,
+ show_results_names=show_results_names,
+ show_groups=show_groups,
+ show_hidden=show_hidden,
+ )
+
+ # Some elements don't need to be shown in the diagram
+ if item is not None:
+ if "item" in ret.kwargs:
+ ret.kwargs["item"] = item
+ elif "items" in ret.kwargs:
+ # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal
+ ret.kwargs["items"][i] = item
+ i += 1
+ elif "items" in ret.kwargs:
+ # If we're supposed to skip this element, remove it from the parent
+ del ret.kwargs["items"][i]
+
+ # If all this items children are none, skip this item
+ if ret and (
+ ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0)
+ or ("item" in ret.kwargs and ret.kwargs["item"] is None)
+ ):
+ ret = EditablePartial.from_call(railroad.Terminal, name)
+
+ # Mark this element as "complete", ie it has all of its children
+ if el_id in lookup:
+ lookup[el_id].complete = True
+
+ if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete:
+ lookup.extract_into_diagram(el_id)
+ if ret is not None:
+ text = lookup.diagrams[el_id].kwargs["name"]
+ href = f"#{_make_bookmark(text)}"
+ ret = EditablePartial.from_call(
+ railroad.NonTerminal, text=text, href=href
+ )
+
+ return ret
diff --git a/python_embeded/Lib/site-packages/pyparsing/tools/__init__.py b/python_embeded/Lib/site-packages/pyparsing/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py b/python_embeded/Lib/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4a8bd9f516994ce6b9734ca07c5895bb8276fd4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py
@@ -0,0 +1,116 @@
+from functools import lru_cache
+import pyparsing as pp
+
+
+@lru_cache(maxsize=None)
+def camel_to_snake(s: str) -> str:
+ """
+ Convert CamelCase to snake_case.
+ """
+ return "".join("_" + c.lower() if c.isupper() else c for c in s).lstrip("_")
+
+
+pre_pep8_method_names = """
+addCondition addParseAction anyCloseTag anyOpenTag asDict asList cStyleComment canParseNext conditionAsParseAction
+convertToDate convertToDatetime convertToFloat convertToInteger countedArray cppStyleComment dblQuotedString
+dblSlashComment defaultName dictOf disableMemoization downcaseTokens enableLeftRecursion enablePackrat getName
+htmlComment ignoreWhitespace indentedBlock infixNotation inlineLiteralsUsing javaStyleComment leaveWhitespace
+lineEnd lineStart locatedExpr matchOnlyAtCol matchPreviousExpr matchPreviousLiteral nestedExpr nullDebugAction oneOf
+originalTextFor parseFile parseString parseWithTabs pythonStyleComment quotedString removeQuotes replaceWith
+resetCache restOfLine runTests scanString searchString setBreak setDebug setDebugActions setDefaultWhitespaceChars
+setFailAction setName setParseAction setResultsName setWhitespaceChars sglQuotedString stringEnd stringStart tokenMap
+traceParseAction transformString tryParse unicodeString upcaseTokens withAttribute withClass
+""".split()
+
+special_changes = {
+ "opAssoc": "OpAssoc",
+ "delimitedList": "DelimitedList",
+ "delimited_list": "DelimitedList",
+ "replaceHTMLEntity": "replace_html_entity",
+ "makeHTMLTags": "make_html_tags",
+ "makeXMLTags": "make_xml_tags",
+ "commonHTMLEntity": "common_html_entity",
+ "stripHTMLTags": "strip_html_tags",
+}
+
+pre_pep8_arg_names = """parseAll maxMatches listAllMatches callDuringTry includeSeparators fullDump printResults
+failureTests postParse matchString identChars maxMismatches initChars bodyChars asKeyword excludeChars asGroupList
+asMatch quoteChar escChar escQuote unquoteResults endQuoteChar convertWhitespaceEscapes notChars wordChars stopOn
+failOn joinString markerString intExpr useRegex asString ignoreExpr""".split()
+
+pre_pep8_method_name = pp.one_of(pre_pep8_method_names, as_keyword=True)
+pre_pep8_method_name.set_parse_action(lambda t: camel_to_snake(t[0]))
+special_pre_pep8_name = pp.one_of(special_changes, as_keyword=True)
+special_pre_pep8_name.set_parse_action(lambda t: special_changes[t[0]])
+# only replace arg names if part of an arg list
+pre_pep8_arg_name = pp.Regex(
+ rf"{pp.util.make_compressed_re(pre_pep8_arg_names)}\s*="
+)
+pre_pep8_arg_name.set_parse_action(lambda t: camel_to_snake(t[0]))
+
+pep8_converter = pre_pep8_method_name | special_pre_pep8_name | pre_pep8_arg_name
+
+if __name__ == "__main__":
+ import argparse
+ from pathlib import Path
+ import sys
+
+ argparser = argparse.ArgumentParser(
+ description = (
+ "Utility to convert Python pyparsing scripts using legacy"
+ " camelCase names to use PEP8 snake_case names."
+ "\nBy default, this script will only show whether this script would make any changes."
+ )
+ )
+ argparser.add_argument("--verbose", "-v", action="store_true", help="Show unified diff for each source file")
+ argparser.add_argument("-vv", action="store_true", dest="verbose2", help="Show unified diff for each source file, plus names of scanned files with no changes")
+ argparser.add_argument("--update", "-u", action="store_true", help="Update source files in-place")
+ argparser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of source files (default: utf-8)")
+ argparser.add_argument("--exit-zero-even-if-changed", "-exit0", action="store_true", help="Exit with status code 0 even if changes were made")
+ argparser.add_argument("source_filename", nargs="+", help="Source filenames or filename patterns of Python files to be converted")
+ args = argparser.parse_args()
+
+
+ def show_diffs(original, modified):
+ import difflib
+
+ diff = difflib.unified_diff(
+ original.splitlines(), modified.splitlines(), lineterm=""
+ )
+ sys.stdout.writelines(f"{diff_line}\n" for diff_line in diff)
+
+ exit_status = 0
+
+ for filename_pattern in args.source_filename:
+
+ for filename in Path().glob(filename_pattern):
+ if not Path(filename).is_file():
+ continue
+
+ try:
+ original_contents = Path(filename).read_text(encoding=args.encoding)
+ modified_contents = pep8_converter.transform_string(
+ original_contents
+ )
+
+ if modified_contents != original_contents:
+ if args.update:
+ Path(filename).write_text(modified_contents, encoding=args.encoding)
+ print(f"Converted {filename}")
+ else:
+ print(f"Found required changes in {filename}")
+
+ if args.verbose:
+ show_diffs(original_contents, modified_contents)
+ print()
+
+ exit_status = 1
+
+ else:
+ if args.verbose2:
+ print(f"No required changes in {filename}")
+
+ except Exception as e:
+ print(f"Failed to convert {filename}: {type(e).__name__}: {e}")
+
+ sys.exit(exit_status if not args.exit_zero_even_if_changed else 0)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/__init__.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..776b917732a0683c99ae2b5af5d4433f45c709a0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/__init__.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from .api import set_clipboard_text
+from .get_clipboard_text_and_convert import get_clipboard_text_and_convert
+
+__all__ = [
+ "set_clipboard_text",
+ "get_clipboard_text_and_convert",
+]
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/api.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/api.py
new file mode 100644
index 0000000000000000000000000000000000000000..d31a5782f3c78dbc5481b7103089533bae82d978
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/api.py
@@ -0,0 +1,27 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from pyreadline3.py3k_compat import is_ironpython
+
+if is_ironpython:
+ try:
+ from .ironpython_clipboard import get_clipboard_text, set_clipboard_text
+ except ImportError:
+ from .no_clipboard import get_clipboard_text, set_clipboard_text
+
+else:
+ try:
+ from .win32_clipboard import get_clipboard_text, set_clipboard_text
+ except ImportError:
+ from .no_clipboard import get_clipboard_text, set_clipboard_text
+
+__all__ = [
+ "get_clipboard_text",
+ "set_clipboard_text",
+]
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/get_clipboard_text_and_convert.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/get_clipboard_text_and_convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5cde9cd845a4878428e8753a8f40d82afc84934
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/get_clipboard_text_and_convert.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from typing import Any, List, Tuple
+
+from .api import get_clipboard_text
+
+
+def _make_num(x: Any) -> Any:
+ try:
+ return int(x)
+ except ValueError:
+ try:
+ return float(x)
+ except ValueError:
+ try:
+ return complex(x)
+ except ValueError:
+ return x
+
+
+def _make_list_of_list(txt: str) -> Tuple[
+ List[List[Any]],
+ bool,
+]:
+
+ ut = []
+ flag = False
+
+ for line in [x for x in txt.split("\r\n") if x != ""]:
+ words = [_make_num(x) for x in line.split("\t")]
+
+ if str in list(map(type, words)):
+ flag = True
+
+ ut.append(words)
+
+ return (
+ ut,
+ flag,
+ )
+
+
+def get_clipboard_text_and_convert(paste_list: bool = False) -> str:
+ """Get txt from clipboard. if paste_list==True the convert tab separated
+ data to list of lists. Enclose list of list in array() if all elements are
+ numeric"""
+
+ txt = get_clipboard_text()
+
+ if not txt:
+ return ""
+
+ if not paste_list:
+ return txt
+
+ if "\t" not in txt:
+ return txt
+
+ array, flag = _make_list_of_list(txt)
+
+ if flag:
+ txt = repr(array)
+ else:
+ txt = "array(%s)" % repr(array)
+
+ txt = "".join([c for c in txt if c not in " \t\r\n"])
+
+ return txt
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/ironpython_clipboard.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/ironpython_clipboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4a377a822b5d81796c94c381d5a2b156da6e1a2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/ironpython_clipboard.py
@@ -0,0 +1,31 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import clr
+import System.Windows.Forms.Clipboard as cb
+
+clr.AddReferenceByPartialName("System.Windows.Forms")
+
+
+def get_clipboard_text() -> str:
+ text = ""
+ if cb.ContainsText():
+ text = cb.GetText()
+
+ return text
+
+
+def set_clipboard_text(text: str) -> None:
+ cb.SetText(text)
+
+
+if __name__ == "__main__":
+ txt = get_clipboard_text() # display last text clipped
+ print(txt)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/no_clipboard.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/no_clipboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ecc58fa9b6959ec0ee128f19ed5f80e0d3667a7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/no_clipboard.py
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+GLOBAL_CLIPBOARD_BUFFER = ""
+
+
+def get_clipboard_text() -> str:
+ return GLOBAL_CLIPBOARD_BUFFER
+
+
+def set_clipboard_text(text: str) -> None:
+ global GLOBAL_CLIPBOARD_BUFFER
+ GLOBAL_CLIPBOARD_BUFFER = text
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/obsolete.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/obsolete.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa3605ee1a271f2736e1c3e0da53870ea9242d94
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/obsolete.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from typing import Any, List
+
+from .api import set_clipboard_text
+
+
+def _make_tab(lists: List[Any]) -> str:
+ if hasattr(lists, "tolist"):
+ lists = lists.tolist()
+
+ ut = []
+ for rad in lists:
+ if type(rad) in [list, tuple]:
+ ut.append("\t".join(["%s" % x for x in rad]))
+ else:
+ ut.append("%s" % rad)
+
+ return "\n".join(ut)
+
+
+def _send_data(lists: List[Any]) -> None:
+ set_clipboard_text(_make_tab(lists))
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/py.typed b/python_embeded/Lib/site-packages/pyreadline3/clipboard/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pyreadline3/clipboard/win32_clipboard.py b/python_embeded/Lib/site-packages/pyreadline3/clipboard/win32_clipboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ccf82e490b7133e126bcdfda6fc28a537c4442e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/clipboard/win32_clipboard.py
@@ -0,0 +1,157 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Jack Trainor.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+###################################
+#
+# Based on recipe posted to ctypes-users
+# see archive
+# http://aspn.activestate.com/ASPN/Mail/Message/ctypes-users/1771866
+#
+#
+
+##########################################################################
+#
+# The Python win32clipboard lib functions work well enough ... except that they
+# can only cut and paste items from within one application, not across
+# applications or processes.
+#
+# I've written a number of Python text filters I like to run on the contents of
+# the clipboard so I need to call the Windows clipboard API with global memory
+# for my filters to work properly.
+#
+# Here's some sample code solving this problem using ctypes.
+#
+# This is my first work with ctypes. It's powerful stuff, but passing
+# arguments in and out of functions is tricky. More sample code would have
+# been helpful, hence this contribution.
+#
+##########################################################################
+
+import ctypes
+import ctypes.wintypes as wintypes
+from ctypes import (
+ addressof,
+ c_buffer,
+ c_char_p,
+ c_int,
+ c_size_t,
+ c_void_p,
+ c_wchar_p,
+ cast,
+ create_unicode_buffer,
+ sizeof,
+ windll,
+ wstring_at,
+)
+from typing import Union
+
+from pyreadline3.keysyms.winconstants import CF_UNICODETEXT, GHND
+from pyreadline3.unicode_helper import ensure_unicode
+
+OpenClipboard = windll.user32.OpenClipboard
+OpenClipboard.argtypes = [wintypes.HWND]
+OpenClipboard.restype = wintypes.BOOL
+
+EmptyClipboard = windll.user32.EmptyClipboard
+
+GetClipboardData = windll.user32.GetClipboardData
+GetClipboardData.argtypes = [wintypes.UINT]
+GetClipboardData.restype = wintypes.HANDLE
+
+GetClipboardFormatName = windll.user32.GetClipboardFormatNameA
+GetClipboardFormatName.argtypes = [wintypes.UINT, c_char_p, c_int]
+
+SetClipboardData = windll.user32.SetClipboardData
+SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE]
+SetClipboardData.restype = wintypes.HANDLE
+
+EnumClipboardFormats = windll.user32.EnumClipboardFormats
+EnumClipboardFormats.argtypes = [c_int]
+
+CloseClipboard = windll.user32.CloseClipboard
+CloseClipboard.argtypes = []
+
+
+GlobalAlloc = windll.kernel32.GlobalAlloc
+GlobalAlloc.argtypes = [wintypes.UINT, c_size_t]
+GlobalAlloc.restype = wintypes.HGLOBAL
+GlobalLock = windll.kernel32.GlobalLock
+GlobalLock.argtypes = [wintypes.HGLOBAL]
+GlobalLock.restype = c_void_p
+GlobalUnlock = windll.kernel32.GlobalUnlock
+GlobalUnlock.argtypes = [c_int]
+
+_strncpy = ctypes.windll.kernel32.lstrcpynW
+_strncpy.restype = c_wchar_p
+_strncpy.argtypes = [c_wchar_p, c_wchar_p, c_size_t]
+
+
+def _enum() -> None:
+ OpenClipboard(0)
+
+ q = EnumClipboardFormats(0)
+ while q:
+ q = EnumClipboardFormats(q)
+
+ CloseClipboard()
+
+
+def _get_format_name(format_str: str) -> bytes:
+ buffer = c_buffer(100)
+ bufferSize = sizeof(buffer)
+
+ OpenClipboard(0)
+
+ GetClipboardFormatName(format_str, buffer, bufferSize)
+
+ CloseClipboard()
+
+ return buffer.value
+
+
+def get_clipboard_text() -> str:
+ text = ""
+
+ if OpenClipboard(0):
+ h_clip_mem = GetClipboardData(CF_UNICODETEXT)
+
+ if h_clip_mem:
+ text = wstring_at(GlobalLock(h_clip_mem))
+ GlobalUnlock(h_clip_mem)
+
+ CloseClipboard()
+
+ return text
+
+
+def set_clipboard_text(text: Union[str, bytes]) -> None:
+ buffer = create_unicode_buffer(ensure_unicode(text))
+ buffer_size = sizeof(buffer)
+
+ h_global_mem = GlobalAlloc(GHND, c_size_t(buffer_size))
+ GlobalLock.restype = c_void_p
+ lp_global_mem = GlobalLock(h_global_mem)
+
+ _strncpy(
+ cast(lp_global_mem, c_wchar_p),
+ cast(addressof(buffer), c_wchar_p),
+ c_size_t(buffer_size),
+ )
+
+ GlobalUnlock(c_int(h_global_mem))
+
+ if OpenClipboard(0):
+ EmptyClipboard()
+ SetClipboardData(CF_UNICODETEXT, h_global_mem)
+ CloseClipboard()
+
+
+if __name__ == "__main__":
+ txt = get_clipboard_text() # display last text clipped
+ print(txt)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/configuration/pyreadlineconfig.ini b/python_embeded/Lib/site-packages/pyreadline3/configuration/pyreadlineconfig.ini
new file mode 100644
index 0000000000000000000000000000000000000000..ebce948b73b2ea9bac073ad7e75c137859bd4945
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/configuration/pyreadlineconfig.ini
@@ -0,0 +1,89 @@
+#Bind keys for exit (keys only work on empty lines
+#disable_readline(True) #Disable pyreadline3 completely.
+from __future__ import absolute_import
+debug_output("off") #"on" saves log info to./pyreadline_debug_log.txt
+ #"on_nologfile" only enables print warning messages
+bind_exit_key("Control-d")
+bind_exit_key("Control-z")
+
+#Commands for moving
+bind_key("Home", "beginning_of_line")
+bind_key("End", "end_of_line")
+bind_key("Left", "backward_char")
+bind_key("Control-b", "backward_char")
+bind_key("Right", "forward_char")
+bind_key("Control-f", "forward_char")
+bind_key("Alt-f", "forward_word")
+bind_key("Alt-b", "backward_word")
+bind_key("Clear", "clear_screen")
+bind_key("Control-l", "clear_screen")
+bind_key("Control-a", "beginning_of_line")
+bind_key("Control-e", "end_of_line")
+#bind_key("Control-l", "redraw_current_line")
+
+#Commands for Manipulating the History
+bind_key("Return", "accept_line")
+bind_key("Control-p", "previous_history")
+bind_key("Control-n", "next_history")
+bind_key("Up", "history_search_backward")
+bind_key("Down", "history_search_forward")
+bind_key("Alt-<", "beginning_of_history")
+bind_key("Alt->", "end_of_history")
+bind_key("Control-r", "reverse_search_history")
+bind_key("Control-s", "forward_search_history")
+bind_key("Alt-p", "non_incremental_reverse_search_history")
+bind_key("Alt-n", "non_incremental_forward_search_history")
+
+bind_key("Control-z", "undo")
+bind_key("Control-_", "undo")
+
+#Commands for Changing Text
+bind_key("Delete", "delete_char")
+bind_key("Control-d", "delete_char")
+bind_key("BackSpace", "backward_delete_char")
+#bind_key("Control-Shift-v", "quoted_insert")
+bind_key("Control-space", "self_insert")
+bind_key("Control-BackSpace", "backward_delete_word")
+
+#Killing and Yanking
+bind_key("Control-k", "kill_line")
+bind_key("Control-shift-k", "kill_whole_line")
+bind_key("Escape", "kill_whole_line")
+bind_key("Meta-d", "kill_word")
+bind_key("Control-w", "unix_word_rubout")
+#bind_key("Control-Delete", "forward_kill_word")
+
+#Copy paste
+bind_key("Shift-Right", "forward_char_extend_selection")
+bind_key("Shift-Left", "backward_char_extend_selection")
+bind_key("Shift-Control-Right", "forward_word_extend_selection")
+bind_key("Shift-Control-Left", "backward_word_extend_selection")
+bind_key("Control-m", "set_mark")
+
+bind_key("Control-Shift-x", "copy_selection_to_clipboard")
+#bind_key("Control-c", "copy_selection_to_clipboard") #Needs allow_ctrl_c(True) below to be uncommented
+bind_key("Control-q", "copy_region_to_clipboard")
+bind_key('Control-Shift-v', "paste_mulitline_code")
+bind_key("Control-x", "cut_selection_to_clipboard")
+
+bind_key("Control-v", "paste")
+bind_key("Control-y", "yank")
+bind_key("Alt-v", "ipython_paste")
+
+#Unbinding keys:
+#un_bind_key("Home")
+
+#Other
+bell_style("none") #modes: none, audible, visible(not implemented)
+show_all_if_ambiguous("on")
+mark_directories("on")
+completer_delims(" \t\n\"\\'`@$><=;|&{(?")
+complete_filesystem("off")
+debug_output("off")
+#allow_ctrl_c(True) #(Allows use of ctrl-c as copy key, still propagate keyboardinterrupt when not waiting for input)
+
+history_filename("~/.pythonhistory")
+history_length(200) #value of -1 means no limit
+
+#set_mode("vi") #will cause following bind_keys to bind to vi mode as well as activate vi mode
+#ctrl_c_tap_time_interval(0.3)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/configuration/startup.py b/python_embeded/Lib/site-packages/pyreadline3/configuration/startup.py
new file mode 100644
index 0000000000000000000000000000000000000000..3652e5170a776a4659388a1deb326709861409a6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/configuration/startup.py
@@ -0,0 +1,38 @@
+# -*- coding: UTF-8 -*-
+# Example snippet to use in a PYTHONSTARTUP file
+
+
+try:
+ import atexit
+
+ # pyreadline3.rlmain.config_path=r"c:\xxx\pyreadlineconfig.ini"
+ import readline
+
+ import pyreadline3.rlmain
+ import pyreadline3.unicode_helper
+
+ #
+ #
+ # Normally the codepage for pyreadline3 is set to be sys.stdout.encoding
+ # if you need to change this uncomment the following line
+ # pyreadline3.unicode_helper.pyreadline_codepage="utf8"
+except ImportError:
+ print("Module readline not available.")
+else:
+ # import tab completion functionality
+ import rlcompleter
+
+ # Override completer from rlcompleter to disable automatic ( on callable
+ completer_obj = rlcompleter.Completer()
+
+ def nop(val, word):
+ return word
+
+ completer_obj._callable_postfix = nop
+ readline.set_completer(completer_obj.complete)
+
+ # activate tab completion
+ readline.parse_and_bind("tab: complete")
+ readline.read_history_file()
+ atexit.register(readline.write_history_file)
+ del readline, rlcompleter, atexit
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/__init__.py b/python_embeded/Lib/site-packages/pyreadline3/console/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2414aa9e3c3e6ee8ee03988c094d6797e21da6b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/__init__.py
@@ -0,0 +1,16 @@
+from pyreadline3.py3k_compat import is_ironpython
+
+if is_ironpython:
+ try:
+ from .ironpython_console import *
+ except ImportError as x:
+ raise ImportError(
+ "Could not find a console implementation for local " "ironpython version"
+ ) from x
+else:
+ try:
+ from .console import *
+ except ImportError as x:
+ raise ImportError(
+ "Could not find a console implementation for local " "python version"
+ ) from x
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/ansi.py b/python_embeded/Lib/site-packages/pyreadline3/console/ansi.py
new file mode 100644
index 0000000000000000000000000000000000000000..e025eb2a6d7dae6451aaa8d0b19e5b111e7f9f82
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/ansi.py
@@ -0,0 +1,253 @@
+# -*- coding: ISO-8859-1 -*-
+
+
+import os
+import re
+import sys
+
+terminal_escape = re.compile("(\001?\033\\[[0-9;]*m\002?)")
+escape_parts = re.compile("\001?\033\\[([0-9;]*)m\002?")
+
+
+class AnsiState(object):
+ def __init__(
+ self,
+ bold=False,
+ inverse=False,
+ color="white",
+ background="black",
+ backgroundbold=False,
+ ):
+ self.bold = bold
+ self.inverse = inverse
+ self.color = color
+ self.background = background
+ self.backgroundbold = backgroundbold
+
+ trtable = {
+ "black": 0,
+ "red": 4,
+ "green": 2,
+ "yellow": 6,
+ "blue": 1,
+ "magenta": 5,
+ "cyan": 3,
+ "white": 7,
+ }
+ revtable = dict(zip(trtable.values(), trtable.keys()))
+
+ def get_winattr(self):
+ attr = 0
+ if self.bold:
+ attr |= 0x0008
+ if self.backgroundbold:
+ attr |= 0x0080
+ if self.inverse:
+ attr |= 0x4000
+ attr |= self.trtable[self.color]
+ attr |= self.trtable[self.background] << 4
+ return attr
+
+ def set_winattr(self, attr):
+ self.bold = bool(attr & 0x0008)
+ self.backgroundbold = bool(attr & 0x0080)
+ self.inverse = bool(attr & 0x4000)
+ self.color = self.revtable[attr & 0x0007]
+ self.background = self.revtable[(attr & 0x0070) >> 4]
+
+ winattr = property(get_winattr, set_winattr)
+
+ def __repr__(self):
+ return (
+ "AnsiState(bold=%s,inverse=%s,color=%9s,"
+ "background=%9s,backgroundbold=%s)# 0x%x"
+ % (
+ self.bold,
+ self.inverse,
+ '"%s"' % self.color,
+ '"%s"' % self.background,
+ self.backgroundbold,
+ self.winattr,
+ )
+ )
+
+ def copy(self):
+ x = AnsiState()
+ x.bold = self.bold
+ x.inverse = self.inverse
+ x.color = self.color
+ x.background = self.background
+ x.backgroundbold = self.backgroundbold
+ return x
+
+
+defaultstate = AnsiState(False, False, "white")
+
+trtable = {
+ 0: "black",
+ 1: "red",
+ 2: "green",
+ 3: "yellow",
+ 4: "blue",
+ 5: "magenta",
+ 6: "cyan",
+ 7: "white",
+}
+
+
+class AnsiWriter(object):
+ def __init__(self, default=defaultstate):
+ if isinstance(defaultstate, AnsiState):
+ self.defaultstate = default
+ else:
+ self.defaultstate = AnsiState()
+ self.defaultstate.winattr = defaultstate
+
+ def write_color(self, text, attr=None):
+ """write text at current cursor position and interpret color escapes.
+
+ return the number of characters written.
+ """
+ if isinstance(attr, AnsiState):
+ defaultstate = attr
+ elif attr is None: # use attribute form initial console
+ attr = self.defaultstate.copy()
+ else:
+ defaultstate = AnsiState()
+ defaultstate.winattr = attr
+ attr = defaultstate
+ chunks = terminal_escape.split(text)
+ n = 0 # count the characters we actually write, omitting the escapes
+ res = []
+ for chunk in chunks:
+ m = escape_parts.match(chunk)
+ if m:
+ parts = m.group(1).split(";")
+ if len(parts) == 1 and parts[0] == "0":
+ attr = self.defaultstate.copy()
+ continue
+ for part in parts:
+ if part == "0": # No text attribute
+ attr = self.defaultstate.copy()
+ attr.bold = False
+ elif part == "7": # switch on reverse
+ attr.inverse = True
+ # switch on bold (i.e. intensify foreground color)
+ elif part == "1":
+ attr.bold = True
+ elif len(part) == 2:
+ if part == "22": # Normal foreground color
+ attr.bold = False
+ elif "30" <= part <= "37": # set foreground color
+ attr.color = trtable[int(part) - 30]
+ elif part == "39": # Default foreground color
+ attr.color = self.defaultstate.color
+ elif "40" <= part <= "47": # set background color
+ attr.background = trtable[int(part) - 40]
+ elif part == "49": # Default background color
+ attr.background = self.defaultstate.background
+ continue
+ n += len(chunk)
+
+ res.append((attr.copy(), chunk))
+
+ return n, res
+
+ def parse_color(self, text, attr=None):
+ n, res = self.write_color(text, attr)
+ return n, [attr.winattr for attr, text in res]
+
+
+def write_color(text, attr=None):
+ a = AnsiWriter(defaultstate)
+ return a.write_color(text, attr)
+
+
+def write_color_old(text, attr=None):
+ """write text at current cursor position and interpret color escapes.
+
+ return the number of characters written.
+ """
+ res = []
+ chunks = terminal_escape.split(text)
+ n = 0 # count the characters we actually write, omitting the escapes
+ if attr is None: # use attribute from initial console
+ attr = 15
+ for chunk in chunks:
+ m = escape_parts.match(chunk)
+ if m:
+ for part in m.group(1).split(";"):
+ if part == "0": # No text attribute
+ attr = 0
+ elif part == "7": # switch on reverse
+ attr |= 0x4000
+ # switch on bold (i.e. intensify foreground color)
+ if part == "1":
+ attr |= 0x08
+ elif len(part) == 2 and "30" <= part <= "37": # set foreground color
+ part = int(part) - 30
+ # we have to mirror bits
+ attr = (
+ (attr & ~0x07)
+ | ((part & 0x1) << 2)
+ | (part & 0x2)
+ | ((part & 0x4) >> 2)
+ )
+ elif len(part) == 2 and "40" <= part <= "47": # set background color
+ part = int(part) - 40
+ # we have to mirror bits
+ attr = (
+ (attr & ~0x70)
+ | ((part & 0x1) << 6)
+ | ((part & 0x2) << 4)
+ | ((part & 0x4) << 2)
+ )
+ # ignore blink, underline and anything we don't understand
+ continue
+ n += len(chunk)
+ if chunk:
+ res.append(("0x%x" % attr, chunk))
+ return res
+
+
+# trtable={0:"black",1:"red",2:"green",3:"yellow",4:"blue",5:"magenta",6:"cyan",7:"white"}
+
+if __name__ == "__main__x":
+ import pprint
+
+ pprint = pprint.pprint
+
+ s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
+ pprint(write_color(s))
+ pprint(write_color_old(s))
+ s = "\033[1;31mred\033[1;32mgreen\033[1;33myellow\033[1;34mblue\033[1;35mmagenta\033[1;36mcyan\033[1;37mwhite\033[0m"
+ pprint(write_color(s))
+ pprint(write_color_old(s))
+
+ s = "\033[0;7;31mred\033[0;7;32mgreen\033[0;7;33myellow\033[0;7;34mblue\033[0;7;35mmagenta\033[0;7;36mcyan\033[0;7;37mwhite\033[0m"
+ pprint(write_color(s))
+ pprint(write_color_old(s))
+ s = "\033[1;7;31mred\033[1;7;32mgreen\033[1;7;33myellow\033[1;7;34mblue\033[1;7;35mmagenta\033[1;7;36mcyan\033[1;7;37mwhite\033[0m"
+ pprint(write_color(s))
+ pprint(write_color_old(s))
+
+
+if __name__ == "__main__":
+ import pprint
+
+ import console
+
+ pprint = pprint.pprint
+
+ c = console.Console()
+ c.write_color("dhsjdhs")
+ c.write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:")
+ print
+ pprint(write_color("\033[0;32mIn [\033[1;32m1\033[0;32m]:"))
+
+if __name__ == "__main__x":
+ import pprint
+
+ pprint = pprint.pprint
+ s = "\033[0;31mred\033[0;32mgreen\033[0;33myellow\033[0;34mblue\033[0;35mmagenta\033[0;36mcyan\033[0;37mwhite\033[0m"
+ pprint(write_color(s))
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/console.py b/python_embeded/Lib/site-packages/pyreadline3/console/console.py
new file mode 100644
index 0000000000000000000000000000000000000000..7133207071dfbaf67e9f82793b5ae971a83d5ffa
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/console.py
@@ -0,0 +1,901 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+from .event import Event
+
+"""Cursor control and color for the Windows console.
+
+This was modeled after the C extension of the same name by Fredrik Lundh.
+"""
+
+# primitive debug printing that won't interfere with the screen
+
+import os
+import re
+import sys
+import traceback
+
+import pyreadline3.unicode_helper as unicode_helper
+from pyreadline3.console.ansi import AnsiState, AnsiWriter
+from pyreadline3.keysyms import KeyPress, make_KeyPress
+from pyreadline3.logger import log
+from pyreadline3.unicode_helper import ensure_str, ensure_unicode
+
+try:
+ import ctypes.util
+ from ctypes import *
+ from ctypes.wintypes import *
+
+ from _ctypes import call_function
+except ImportError:
+ raise ImportError("You need ctypes to run this code")
+
+
+def nolog(string):
+ pass
+
+
+log = nolog
+
+
+# some constants we need
+STD_INPUT_HANDLE = -10
+STD_OUTPUT_HANDLE = -11
+ENABLE_WINDOW_INPUT = 0x0008
+ENABLE_MOUSE_INPUT = 0x0010
+ENABLE_PROCESSED_INPUT = 0x0001
+WHITE = 0x7
+BLACK = 0
+MENU_EVENT = 0x0008
+KEY_EVENT = 0x0001
+MOUSE_MOVED = 0x0001
+MOUSE_EVENT = 0x0002
+WINDOW_BUFFER_SIZE_EVENT = 0x0004
+FOCUS_EVENT = 0x0010
+MENU_EVENT = 0x0008
+VK_SHIFT = 0x10
+VK_CONTROL = 0x11
+VK_MENU = 0x12
+GENERIC_READ = int(0x80000000)
+GENERIC_WRITE = 0x40000000
+
+# Windows structures we'll need later
+
+
+class COORD(Structure):
+ _fields_ = [("X", c_short), ("Y", c_short)]
+
+
+class SMALL_RECT(Structure):
+ _fields_ = [
+ ("Left", c_short),
+ ("Top", c_short),
+ ("Right", c_short),
+ ("Bottom", c_short),
+ ]
+
+
+class CONSOLE_SCREEN_BUFFER_INFO(Structure):
+ _fields_ = [
+ ("dwSize", COORD),
+ ("dwCursorPosition", COORD),
+ ("wAttributes", c_short),
+ ("srWindow", SMALL_RECT),
+ ("dwMaximumWindowSize", COORD),
+ ]
+
+
+class CHAR_UNION(Union):
+ _fields_ = [("UnicodeChar", c_wchar), ("AsciiChar", c_char)]
+
+
+class CHAR_INFO(Structure):
+ _fields_ = [("Char", CHAR_UNION), ("Attributes", c_short)]
+
+
+class KEY_EVENT_RECORD(Structure):
+ _fields_ = [
+ ("bKeyDown", c_byte),
+ ("pad2", c_byte),
+ ("pad1", c_short),
+ ("wRepeatCount", c_short),
+ ("wVirtualKeyCode", c_short),
+ ("wVirtualScanCode", c_short),
+ ("uChar", CHAR_UNION),
+ ("dwControlKeyState", c_int),
+ ]
+
+
+class MOUSE_EVENT_RECORD(Structure):
+ _fields_ = [
+ ("dwMousePosition", COORD),
+ ("dwButtonState", c_int),
+ ("dwControlKeyState", c_int),
+ ("dwEventFlags", c_int),
+ ]
+
+
+class WINDOW_BUFFER_SIZE_RECORD(Structure):
+ _fields_ = [("dwSize", COORD)]
+
+
+class MENU_EVENT_RECORD(Structure):
+ _fields_ = [("dwCommandId", c_uint)]
+
+
+class FOCUS_EVENT_RECORD(Structure):
+ _fields_ = [("bSetFocus", c_byte)]
+
+
+class INPUT_UNION(Union):
+ _fields_ = [
+ ("KeyEvent", KEY_EVENT_RECORD),
+ ("MouseEvent", MOUSE_EVENT_RECORD),
+ ("WindowBufferSizeEvent", WINDOW_BUFFER_SIZE_RECORD),
+ ("MenuEvent", MENU_EVENT_RECORD),
+ ("FocusEvent", FOCUS_EVENT_RECORD),
+ ]
+
+
+class INPUT_RECORD(Structure):
+ _fields_ = [("EventType", c_short), ("Event", INPUT_UNION)]
+
+
+class CONSOLE_CURSOR_INFO(Structure):
+ _fields_ = [("dwSize", c_int), ("bVisible", c_byte)]
+
+
+# I didn't want to have to individually import these so I made a list, they are
+# added to the Console class later in this file.
+
+funcs = [
+ "AllocConsole",
+ "CreateConsoleScreenBuffer",
+ "FillConsoleOutputAttribute",
+ "FillConsoleOutputCharacterW",
+ "FreeConsole",
+ "GetConsoleCursorInfo",
+ "GetConsoleMode",
+ "GetConsoleScreenBufferInfo",
+ "GetConsoleTitleW",
+ "GetProcAddress",
+ "GetStdHandle",
+ "PeekConsoleInputW",
+ "ReadConsoleInputW",
+ "ScrollConsoleScreenBufferW",
+ "SetConsoleActiveScreenBuffer",
+ "SetConsoleCursorInfo",
+ "SetConsoleCursorPosition",
+ "SetConsoleMode",
+ "SetConsoleScreenBufferSize",
+ "SetConsoleTextAttribute",
+ "SetConsoleTitleW",
+ "SetConsoleWindowInfo",
+ "WriteConsoleW",
+ "WriteConsoleOutputCharacterW",
+ "WriteFile",
+]
+
+# I don't want events for these keys, they are just a bother for my application
+key_modifiers = {
+ VK_SHIFT: 1,
+ VK_CONTROL: 1,
+ VK_MENU: 1, # alt key
+ 0x5B: 1, # windows key
+}
+
+
+def split_block(text, size=1000):
+ return [text[start : start + size] for start in range(0, len(text), size)]
+
+
+class Console(object):
+ """Console driver for Windows."""
+
+ def __init__(self, newbuffer=0):
+ """Initialize the Console object.
+
+ newbuffer=1 will allocate a new buffer so the old content will be restored
+ on exit.
+ """
+ # Do I need the following line? It causes a console to be created whenever
+ # readline is imported into a pythonw application which seems wrong. Things
+ # seem to work without it...
+ # self.AllocConsole()
+
+ if newbuffer:
+ self.hout = self.CreateConsoleScreenBuffer(
+ GENERIC_READ | GENERIC_WRITE, 0, None, 1, None
+ )
+ self.SetConsoleActiveScreenBuffer(self.hout)
+ else:
+ self.hout = self.GetStdHandle(STD_OUTPUT_HANDLE)
+
+ self.hin = self.GetStdHandle(STD_INPUT_HANDLE)
+ self.inmode = DWORD(0)
+ self.GetConsoleMode(self.hin, byref(self.inmode))
+ self.SetConsoleMode(self.hin, 0xF)
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ self.attr = info.wAttributes
+ self.saveattr = info.wAttributes # remember the initial colors
+ self.defaultstate = AnsiState()
+ self.defaultstate.winattr = info.wAttributes
+ self.ansiwriter = AnsiWriter(self.defaultstate)
+
+ background = self.attr & 0xF0
+ for escape in self.escape_to_color:
+ if self.escape_to_color[escape] is not None:
+ self.escape_to_color[escape] |= background
+ log("initial attr=%x" % self.attr)
+ self.softspace = 0 # this is for using it as a file-like object
+ self.serial = 0
+
+ self.pythondll = ctypes.pythonapi
+ self.inputHookPtr = c_void_p.from_address(
+ addressof(self.pythondll.PyOS_InputHook)
+ ).value
+
+ self.pythondll.PyMem_RawMalloc.restype = c_size_t
+ self.pythondll.PyMem_RawMalloc.argtypes = [c_size_t]
+ setattr(Console, "PyMem_Malloc", self.pythondll.PyMem_RawMalloc)
+
+ def __del__(self):
+ """Cleanup the console when finished."""
+ # I don't think this ever gets called
+ self.SetConsoleTextAttribute(self.hout, self.saveattr)
+ self.SetConsoleMode(self.hin, self.inmode)
+ self.FreeConsole()
+
+ def _get_top_bot(self):
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ rect = info.srWindow
+ top = rect.Top
+ bot = rect.Bottom
+ return top, bot
+
+ def fixcoord(self, x, y):
+ """Return a long with x and y packed inside,
+ also handle negative x and y."""
+ if x < 0 or y < 0:
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ if x < 0:
+ x = info.srWindow.Right - x
+ y = info.srWindow.Bottom + y
+
+ # this is a hack! ctypes won't pass structures but COORD is
+ # just like a long, so this works.
+ return c_int(y << 16 | x)
+
+ def pos(self, x=None, y=None):
+ """Move or query the window cursor."""
+ if x is None:
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ return (info.dwCursorPosition.X, info.dwCursorPosition.Y)
+ else:
+ return self.SetConsoleCursorPosition(self.hout, self.fixcoord(x, y))
+
+ def home(self):
+ """Move to home."""
+ self.pos(0, 0)
+
+ # Map ANSI color escape sequences into Windows Console Attributes
+
+ terminal_escape = re.compile("(\001?\033\\[[0-9;]+m\002?)")
+ escape_parts = re.compile("\001?\033\\[([0-9;]+)m\002?")
+ escape_to_color = {
+ "0;30": 0x0, # black
+ "0;31": 0x4, # red
+ "0;32": 0x2, # green
+ "0;33": 0x4 + 0x2, # brown?
+ "0;34": 0x1, # blue
+ "0;35": 0x1 + 0x4, # purple
+ "0;36": 0x2 + 0x4, # cyan
+ "0;37": 0x1 + 0x2 + 0x4, # grey
+ "1;30": 0x1 + 0x2 + 0x4, # dark gray
+ "1;31": 0x4 + 0x8, # red
+ "1;32": 0x2 + 0x8, # light green
+ "1;33": 0x4 + 0x2 + 0x8, # yellow
+ "1;34": 0x1 + 0x8, # light blue
+ "1;35": 0x1 + 0x4 + 0x8, # light purple
+ "1;36": 0x1 + 0x2 + 0x8, # light cyan
+ "1;37": 0x1 + 0x2 + 0x4 + 0x8, # white
+ "0": None,
+ }
+
+ # This pattern should match all characters that change the cursor position differently
+ # than a normal character.
+ motion_char_re = re.compile("([\n\r\t\010\007])")
+
+ def write_scrolling(self, text, attr=None):
+ """write text at current cursor position while watching for scrolling.
+
+ If the window scrolls because you are at the bottom of the screen
+ buffer, all positions that you are storing will be shifted by the
+ scroll amount. For example, I remember the cursor position of the
+ prompt so that I can redraw the line but if the window scrolls,
+ the remembered position is off.
+
+ This variant of write tries to keep track of the cursor position
+ so that it will know when the screen buffer is scrolled. It
+ returns the number of lines that the buffer scrolled.
+
+ """
+ text = ensure_unicode(text)
+ x, y = self.pos()
+ w, h = self.size()
+ scroll = 0 # the result
+ # split the string into ordinary characters and funny characters
+ chunks = self.motion_char_re.split(text)
+ for chunk in chunks:
+ n = self.write_color(chunk, attr)
+ if len(chunk) == 1: # the funny characters will be alone
+ if chunk[0] == "\n": # newline
+ x = 0
+ y += 1
+ elif chunk[0] == "\r": # carriage return
+ x = 0
+ elif chunk[0] == "\t": # tab
+ x = 8 * (int(x / 8) + 1)
+ if x > w: # newline
+ x -= w
+ y += 1
+ elif chunk[0] == "\007": # bell
+ pass
+ elif chunk[0] == "\010":
+ x -= 1
+ if x < 0:
+ y -= 1 # backed up 1 line
+ else: # ordinary character
+ x += 1
+ if x == w: # wrap
+ x = 0
+ y += 1
+ if y == h: # scroll
+ scroll += 1
+ y = h - 1
+ else: # chunk of ordinary characters
+ x += n
+ l = int(x / w) # lines we advanced
+ x = x % w # new x value
+ y += l
+ if y >= h: # scroll
+ scroll += y - h + 1
+ y = h - 1
+ return scroll
+
+ def write_color(self, text, attr=None):
+ text = ensure_unicode(text)
+ n, res = self.ansiwriter.write_color(text, attr)
+ junk = DWORD(0)
+ for attr, chunk in res:
+ log("console.attr:%s" % (attr))
+ log("console.chunk:%s" % (chunk))
+ self.SetConsoleTextAttribute(self.hout, attr.winattr)
+ for short_chunk in split_block(chunk):
+ self.WriteConsoleW(
+ self.hout, short_chunk, len(short_chunk), byref(junk), None
+ )
+ return n
+
+ def write_plain(self, text, attr=None):
+ """write text at current cursor position."""
+ text = ensure_unicode(text)
+ log('write("%s", %s)' % (text, attr))
+ if attr is None:
+ attr = self.attr
+ junk = DWORD(0)
+ self.SetConsoleTextAttribute(self.hout, attr)
+ for short_chunk in split_block(chunk):
+ self.WriteConsoleW(
+ self.hout,
+ ensure_unicode(short_chunk),
+ len(short_chunk),
+ byref(junk),
+ None,
+ )
+ return len(text)
+
+ # This function must be used to ensure functioning with EMACS
+ # Emacs sets the EMACS environment variable
+ if "EMACS" in os.environ:
+
+ def write_color(self, text, attr=None):
+ text = ensure_str(text)
+ junk = DWORD(0)
+ self.WriteFile(self.hout, text, len(text), byref(junk), None)
+ return len(text)
+
+ write_plain = write_color
+
+ # make this class look like a file object
+ def write(self, text):
+ text = ensure_unicode(text)
+ log('write("%s")' % text)
+ return self.write_color(text)
+
+ # write = write_scrolling
+
+ def isatty(self):
+ return True
+
+ def flush(self):
+ pass
+
+ def page(self, attr=None, fill=" "):
+ """Fill the entire screen."""
+ if attr is None:
+ attr = self.attr
+ if len(fill) != 1:
+ raise ValueError
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ if info.dwCursorPosition.X != 0 or info.dwCursorPosition.Y != 0:
+ self.SetConsoleCursorPosition(self.hout, self.fixcoord(0, 0))
+
+ w = info.dwSize.X
+ n = DWORD(0)
+ for y in range(info.dwSize.Y):
+ self.FillConsoleOutputAttribute(
+ self.hout, attr, w, self.fixcoord(0, y), byref(n)
+ )
+ self.FillConsoleOutputCharacterW(
+ self.hout, ord(fill[0]), w, self.fixcoord(0, y), byref(n)
+ )
+
+ self.attr = attr
+
+ def text(self, x, y, text, attr=None):
+ """Write text at the given position."""
+ if attr is None:
+ attr = self.attr
+
+ pos = self.fixcoord(x, y)
+ n = DWORD(0)
+ self.WriteConsoleOutputCharacterW(self.hout, text, len(text), pos, byref(n))
+ self.FillConsoleOutputAttribute(self.hout, attr, n, pos, byref(n))
+
+ def clear_to_end_of_window(self):
+ top, bot = self._get_top_bot()
+ pos = self.pos()
+ w, h = self.size()
+ self.rectangle((pos[0], pos[1], w, pos[1] + 1))
+ if pos[1] < bot:
+ self.rectangle((0, pos[1] + 1, w, bot + 1))
+
+ def rectangle(self, rect, attr=None, fill=" "):
+ """Fill Rectangle."""
+ x0, y0, x1, y1 = rect
+ n = DWORD(0)
+ if attr is None:
+ attr = self.attr
+ for y in range(y0, y1):
+ pos = self.fixcoord(x0, y)
+ self.FillConsoleOutputAttribute(self.hout, attr, x1 - x0, pos, byref(n))
+ self.FillConsoleOutputCharacterW(
+ self.hout, ord(fill[0]), x1 - x0, pos, byref(n)
+ )
+
+ def scroll(self, rect, dx, dy, attr=None, fill=" "):
+ """Scroll a rectangle."""
+ if attr is None:
+ attr = self.attr
+ x0, y0, x1, y1 = rect
+ source = SMALL_RECT(x0, y0, x1 - 1, y1 - 1)
+ dest = self.fixcoord(x0 + dx, y0 + dy)
+ style = CHAR_INFO()
+ style.Char.AsciiChar = ensure_str(fill[0])
+ style.Attributes = attr
+
+ return self.ScrollConsoleScreenBufferW(
+ self.hout, byref(source), byref(source), dest, byref(style)
+ )
+
+ def scroll_window(self, lines):
+ """Scroll the window by the indicated number of lines."""
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ rect = info.srWindow
+ log("sw: rtop=%d rbot=%d" % (rect.Top, rect.Bottom))
+ top = rect.Top + lines
+ bot = rect.Bottom + lines
+ h = bot - top
+ maxbot = info.dwSize.Y - 1
+ if top < 0:
+ top = 0
+ bot = h
+ if bot > maxbot:
+ bot = maxbot
+ top = bot - h
+
+ nrect = SMALL_RECT()
+ nrect.Top = top
+ nrect.Bottom = bot
+ nrect.Left = rect.Left
+ nrect.Right = rect.Right
+ log("sn: top=%d bot=%d" % (top, bot))
+ r = self.SetConsoleWindowInfo(self.hout, True, byref(nrect))
+ log("r=%d" % r)
+
+ def get(self):
+ """Get next event from queue."""
+ inputHookFunc = c_void_p.from_address(self.inputHookPtr).value
+
+ Cevent = INPUT_RECORD()
+ count = DWORD(0)
+ while True:
+ if inputHookFunc:
+ call_function(inputHookFunc, ())
+ status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count))
+ if status and count.value == 1:
+ e = event(self, Cevent)
+ return e
+
+ def getkeypress(self):
+ """Return next key press event from the queue, ignoring others."""
+ while True:
+ e = self.get()
+ if e.type == "KeyPress" and e.keycode not in key_modifiers:
+ log("console.getkeypress %s" % e)
+ if e.keyinfo.keyname == "next":
+ self.scroll_window(12)
+ elif e.keyinfo.keyname == "prior":
+ self.scroll_window(-12)
+ else:
+ return e
+ elif (e.type == "KeyRelease") and (
+ e.keyinfo == KeyPress("S", False, True, False, "S")
+ or e.keyinfo == KeyPress("C", False, True, False, "C")
+ ):
+ log("getKeypress:%s,%s,%s" % (e.keyinfo, e.keycode, e.type))
+ return e
+
+ def getchar(self):
+ """Get next character from queue."""
+
+ Cevent = INPUT_RECORD()
+ count = DWORD(0)
+ while True:
+ status = self.ReadConsoleInputW(self.hin, byref(Cevent), 1, byref(count))
+ if (
+ status
+ and (count.value == 1)
+ and (Cevent.EventType == 1)
+ and Cevent.Event.KeyEvent.bKeyDown
+ ):
+ sym = keysym(Cevent.Event.KeyEvent.wVirtualKeyCode)
+ if len(sym) == 0:
+ sym = Cevent.Event.KeyEvent.uChar.AsciiChar
+ return sym
+
+ def peek(self):
+ """Check event queue."""
+ Cevent = INPUT_RECORD()
+ count = DWORD(0)
+ status = self.PeekConsoleInputW(self.hin, byref(Cevent), 1, byref(count))
+ if status and count == 1:
+ return event(self, Cevent)
+
+ def title(self, txt=None):
+ """Set/get title."""
+ if txt:
+ self.SetConsoleTitleW(txt)
+ else:
+ buffer = create_unicode_buffer(200)
+ n = self.GetConsoleTitleW(buffer, 200)
+ if n > 0:
+ return buffer.value[:n]
+
+ def size(self, width=None, height=None):
+ """Set/get window size."""
+ info = CONSOLE_SCREEN_BUFFER_INFO()
+ status = self.GetConsoleScreenBufferInfo(self.hout, byref(info))
+ if not status:
+ return None
+ if width is not None and height is not None:
+ wmin = info.srWindow.Right - info.srWindow.Left + 1
+ hmin = info.srWindow.Bottom - info.srWindow.Top + 1
+ # print wmin, hmin
+ width = max(width, wmin)
+ height = max(height, hmin)
+ # print width, height
+ self.SetConsoleScreenBufferSize(self.hout, self.fixcoord(width, height))
+ else:
+ return (info.dwSize.X, info.dwSize.Y)
+
+ def cursor(self, visible=None, size=None):
+ """Set cursor on or off."""
+ info = CONSOLE_CURSOR_INFO()
+ if self.GetConsoleCursorInfo(self.hout, byref(info)):
+ if visible is not None:
+ info.bVisible = visible
+ if size is not None:
+ info.dwSize = size
+ self.SetConsoleCursorInfo(self.hout, byref(info))
+
+ def bell(self):
+ self.write("\007")
+
+ def next_serial(self):
+ """Get next event serial number."""
+ self.serial += 1
+ return self.serial
+
+
+# add the functions from the dll to the class
+for func in funcs:
+ setattr(Console, func, getattr(windll.kernel32, func))
+
+
+_strncpy = ctypes.windll.kernel32.lstrcpynA
+_strncpy.restype = c_char_p
+_strncpy.argtypes = [c_char_p, c_char_p, c_size_t]
+
+
+LPVOID = c_void_p
+LPCVOID = c_void_p
+FARPROC = c_void_p
+LPDWORD = POINTER(DWORD)
+
+Console.AllocConsole.restype = BOOL
+Console.AllocConsole.argtypes = [] # void
+Console.CreateConsoleScreenBuffer.restype = HANDLE
+Console.CreateConsoleScreenBuffer.argtypes = [
+ DWORD,
+ DWORD,
+ c_void_p,
+ DWORD,
+ LPVOID,
+] # DWORD, DWORD, SECURITY_ATTRIBUTES*, DWORD, LPVOID
+Console.FillConsoleOutputAttribute.restype = BOOL
+Console.FillConsoleOutputAttribute.argtypes = [
+ HANDLE,
+ WORD,
+ DWORD,
+ c_int,
+ LPDWORD,
+] # HANDLE, WORD, DWORD, COORD, LPDWORD
+Console.FillConsoleOutputCharacterW.restype = BOOL
+Console.FillConsoleOutputCharacterW.argtypes = [
+ HANDLE,
+ c_ushort,
+ DWORD,
+ c_int,
+ LPDWORD,
+] # HANDLE, TCHAR, DWORD, COORD, LPDWORD
+Console.FreeConsole.restype = BOOL
+Console.FreeConsole.argtypes = [] # void
+Console.GetConsoleCursorInfo.restype = BOOL
+Console.GetConsoleCursorInfo.argtypes = [
+ HANDLE,
+ c_void_p,
+] # HANDLE, PCONSOLE_CURSOR_INFO
+Console.GetConsoleMode.restype = BOOL
+Console.GetConsoleMode.argtypes = [HANDLE, LPDWORD] # HANDLE, LPDWORD
+Console.GetConsoleScreenBufferInfo.restype = BOOL
+Console.GetConsoleScreenBufferInfo.argtypes = [
+ HANDLE,
+ c_void_p,
+] # HANDLE, PCONSOLE_SCREEN_BUFFER_INFO
+Console.GetConsoleTitleW.restype = DWORD
+Console.GetConsoleTitleW.argtypes = [c_wchar_p, DWORD] # LPTSTR , DWORD
+Console.GetProcAddress.restype = FARPROC
+Console.GetProcAddress.argtypes = [HMODULE, c_char_p] # HMODULE , LPCSTR
+Console.GetStdHandle.restype = HANDLE
+Console.GetStdHandle.argtypes = [DWORD]
+Console.PeekConsoleInputW.restype = BOOL
+# HANDLE, PINPUT_RECORD, DWORD, LPDWORD
+Console.PeekConsoleInputW.argtypes = [HANDLE, c_void_p, DWORD, LPDWORD]
+Console.ReadConsoleInputW.restype = BOOL
+# HANDLE, PINPUT_RECORD, DWORD, LPDWORD
+Console.ReadConsoleInputW.argtypes = [HANDLE, c_void_p, DWORD, LPDWORD]
+Console.ScrollConsoleScreenBufferW.restype = BOOL
+Console.ScrollConsoleScreenBufferW.argtypes = [
+ HANDLE,
+ c_void_p,
+ c_void_p,
+ c_int,
+ c_void_p,
+] # HANDLE, SMALL_RECT*, SMALL_RECT*, COORD, LPDWORD
+Console.SetConsoleActiveScreenBuffer.restype = BOOL
+Console.SetConsoleActiveScreenBuffer.argtypes = [HANDLE] # HANDLE
+Console.SetConsoleCursorInfo.restype = BOOL
+Console.SetConsoleCursorInfo.argtypes = [
+ HANDLE,
+ c_void_p,
+] # HANDLE, CONSOLE_CURSOR_INFO*
+Console.SetConsoleCursorPosition.restype = BOOL
+Console.SetConsoleCursorPosition.argtypes = [HANDLE, c_int] # HANDLE, COORD
+Console.SetConsoleMode.restype = BOOL
+Console.SetConsoleMode.argtypes = [HANDLE, DWORD] # HANDLE, DWORD
+Console.SetConsoleScreenBufferSize.restype = BOOL
+Console.SetConsoleScreenBufferSize.argtypes = [HANDLE, c_int] # HANDLE, COORD
+Console.SetConsoleTextAttribute.restype = BOOL
+Console.SetConsoleTextAttribute.argtypes = [HANDLE, WORD] # HANDLE, WORD
+Console.SetConsoleTitleW.restype = BOOL
+Console.SetConsoleTitleW.argtypes = [c_wchar_p] # LPCTSTR
+Console.SetConsoleWindowInfo.restype = BOOL
+Console.SetConsoleWindowInfo.argtypes = [
+ HANDLE,
+ BOOL,
+ c_void_p,
+] # HANDLE, BOOL, SMALL_RECT*
+Console.WriteConsoleW.restype = BOOL
+# HANDLE, VOID*, DWORD, LPDWORD, LPVOID
+Console.WriteConsoleW.argtypes = [HANDLE, c_void_p, DWORD, LPDWORD, LPVOID]
+Console.WriteConsoleOutputCharacterW.restype = BOOL
+Console.WriteConsoleOutputCharacterW.argtypes = [
+ HANDLE,
+ c_wchar_p,
+ DWORD,
+ c_int,
+ LPDWORD,
+] # HANDLE, LPCTSTR, DWORD, COORD, LPDWORD
+Console.WriteFile.restype = BOOL
+# HANDLE, LPCVOID , DWORD, LPDWORD , LPOVERLAPPED
+Console.WriteFile.argtypes = [HANDLE, LPCVOID, DWORD, LPDWORD, c_void_p]
+
+
+VkKeyScan = windll.user32.VkKeyScanA
+
+
+class event(Event):
+ """Represent events from the console."""
+
+ def __init__(self, console, input):
+ """Initialize an event from the Windows input structure."""
+ self.type = "??"
+ self.serial = console.next_serial()
+ self.width = 0
+ self.height = 0
+ self.x = 0
+ self.y = 0
+ self.char = ""
+ self.keycode = 0
+ self.keysym = "??"
+ # a tuple with (control, meta, shift, keycode) for dispatch
+ self.keyinfo = None
+ self.width = None
+
+ if input.EventType == KEY_EVENT:
+ if input.Event.KeyEvent.bKeyDown:
+ self.type = "KeyPress"
+ else:
+ self.type = "KeyRelease"
+ self.char = input.Event.KeyEvent.uChar.UnicodeChar
+ self.keycode = input.Event.KeyEvent.wVirtualKeyCode
+ self.state = input.Event.KeyEvent.dwControlKeyState
+ self.keyinfo = make_KeyPress(self.char, self.state, self.keycode)
+
+ elif input.EventType == MOUSE_EVENT:
+ if input.Event.MouseEvent.dwEventFlags & MOUSE_MOVED:
+ self.type = "Motion"
+ else:
+ self.type = "Button"
+ self.x = input.Event.MouseEvent.dwMousePosition.X
+ self.y = input.Event.MouseEvent.dwMousePosition.Y
+ self.state = input.Event.MouseEvent.dwButtonState
+ elif input.EventType == WINDOW_BUFFER_SIZE_EVENT:
+ self.type = "Configure"
+ self.width = input.Event.WindowBufferSizeEvent.dwSize.X
+ self.height = input.Event.WindowBufferSizeEvent.dwSize.Y
+ elif input.EventType == FOCUS_EVENT:
+ if input.Event.FocusEvent.bSetFocus:
+ self.type = "FocusIn"
+ else:
+ self.type = "FocusOut"
+ elif input.EventType == MENU_EVENT:
+ self.type = "Menu"
+ self.state = input.Event.MenuEvent.dwCommandId
+
+
+def getconsole(buffer=1):
+ """Get a console handle.
+
+ If buffer is non-zero, a new console buffer is allocated and
+ installed. Otherwise, this returns a handle to the current
+ console buffer"""
+
+ c = Console(buffer)
+
+ return c
+
+
+# The following code uses ctypes to allow a Python callable to
+# substitute for GNU readline within the Python interpreter. Calling
+# raw_input or other functions that do input, inside your callable
+# might be a bad idea, then again, it might work.
+
+# The Python callable can raise EOFError or KeyboardInterrupt and
+# these will be translated into the appropriate outputs from readline
+# so that they will then be translated back!
+
+# If the Python callable raises any other exception, a traceback will
+# be printed and readline will appear to return an empty line.
+
+# I use ctypes to create a C-callable from a Python wrapper that
+# handles the exceptions and gets the result into the right form.
+
+
+# the type for our C-callable wrapper
+HOOKFUNC23 = CFUNCTYPE(c_char_p, c_void_p, c_void_p, c_char_p)
+
+readline_hook = None # the python hook goes here
+readline_ref = None # reference to the c-callable to keep it alive
+
+
+def hook_wrapper_23(stdin, stdout, prompt):
+ """Wrap a Python readline so it behaves like GNU readline."""
+ try:
+ # call the Python hook
+ res = ensure_str(readline_hook(prompt))
+ # make sure it returned the right sort of thing
+ if res and not isinstance(res, bytes):
+ raise TypeError("readline must return a string.")
+ except KeyboardInterrupt:
+ # GNU readline returns 0 on keyboard interrupt
+ return 0
+ except EOFError:
+ # It returns an empty string on EOF
+ res = ensure_str("")
+ except BaseException:
+ print("Readline internal error", file=sys.stderr)
+ traceback.print_exc()
+ res = ensure_str("\n")
+ # we have to make a copy because the caller expects to free the result
+ n = len(res)
+ p = Console.PyMem_Malloc(n + 1)
+ _strncpy(cast(p, c_char_p), res, n + 1)
+ return p
+
+
+def install_readline(hook):
+ """Set up things for the interpreter to call
+ our function like GNU readline."""
+ global readline_hook, readline_ref
+ # save the hook so the wrapper can call it
+ readline_hook = hook
+ # get the address of PyOS_ReadlineFunctionPointer so we can update it
+ PyOS_RFP = c_void_p.from_address(
+ Console.GetProcAddress(
+ sys.dllhandle, "PyOS_ReadlineFunctionPointer".encode("ascii")
+ )
+ )
+ # save a reference to the generated C-callable so it doesn't go away
+ readline_ref = HOOKFUNC23(hook_wrapper_23)
+ # get the address of the function
+ func_start = c_void_p.from_address(addressof(readline_ref)).value
+ # write the function address into PyOS_ReadlineFunctionPointer
+ PyOS_RFP.value = func_start
+
+
+if __name__ == "__main__":
+ import sys
+ import time
+
+ def p(char):
+ return chr(VkKeyScan(ord(char)) & 0xFF)
+
+ c = Console(0)
+ sys.stdout = c
+ sys.stderr = c
+ c.page()
+ print(p("d"), p("D"))
+ c.pos(5, 10)
+ c.write("hi there")
+ print("some printed output")
+ for i in range(10):
+ q = c.getkeypress()
+ print(q)
+ del c
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/console_attributes.py b/python_embeded/Lib/site-packages/pyreadline3/console/console_attributes.py
new file mode 100644
index 0000000000000000000000000000000000000000..611fea652f19c32dfa737b2295963f6ed6820a4e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/console_attributes.py
@@ -0,0 +1,15 @@
+FOREGROUND_BLUE = 0x0001
+FOREGROUND_GREEN = 0x0002
+FOREGROUND_RED = 0x0004
+FOREGROUND_INTENSITY = 0x0008
+BACKGROUND_BLUE = 0x0010
+BACKGROUND_GREEN = 0x0020
+BACKGROUND_RED = 0x0040
+BACKGROUND_INTENSITY = 0x0080
+COMMON_LVB_LEADING_BYTE = 0x0100
+COMMON_LVB_TRAILING_BYTE = 0x0200
+COMMON_LVB_GRID_HORIZONTAL = 0x0400
+COMMON_LVB_GRID_LVERTICAL = 0x0800
+COMMON_LVB_GRID_RVERTICAL = 0x1000
+COMMON_LVB_REVERSE_VIDEO = 0x2000
+COMMON_LVB_UNDERSCORE = 0x4000
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/consolebase.py b/python_embeded/Lib/site-packages/pyreadline3/console/consolebase.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b36fedb2d648d9c41f7f2aef4a7d38d8661f315
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/consolebase.py
@@ -0,0 +1,50 @@
+class baseconsole(object):
+ def __init__(self):
+ pass
+
+ def bell(self):
+ raise NotImplementedError
+
+ def pos(self, x=None, y=None):
+ """Move or query the window cursor."""
+ raise NotImplementedError
+
+ def size(self):
+ raise NotImplementedError
+
+ def rectangle(self, rect, attr=None, fill=" "):
+ """Fill Rectangle."""
+ raise NotImplementedError
+
+ def write_scrolling(self, text, attr=None):
+ """write text at current cursor position while watching for scrolling.
+
+ If the window scrolls because you are at the bottom of the screen
+ buffer, all positions that you are storing will be shifted by the
+ scroll amount. For example, I remember the cursor position of the
+ prompt so that I can redraw the line but if the window scrolls,
+ the remembered position is off.
+
+ This variant of write tries to keep track of the cursor position
+ so that it will know when the screen buffer is scrolled. It
+ returns the number of lines that the buffer scrolled.
+
+ """
+ raise NotImplementedError
+
+ def getkeypress(self):
+ """Return next key press event from the queue, ignoring others."""
+ raise NotImplementedError
+
+ def write(self, text):
+ raise NotImplementedError
+
+ def page(self, attr=None, fill=" "):
+ """Fill the entire screen."""
+ raise NotImplementedError
+
+ def isatty(self):
+ return True
+
+ def flush(self):
+ pass
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/event.py b/python_embeded/Lib/site-packages/pyreadline3/console/event.py
new file mode 100644
index 0000000000000000000000000000000000000000..21c764b2ba789f3f222ecd77a74c45e8ce6c9d88
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/event.py
@@ -0,0 +1,37 @@
+class Event(object):
+ """Represent events from the console."""
+
+ def __init__(self, console, input):
+ pass
+
+ def __repr__(self):
+ """Display an event for debugging."""
+ if self.type in ["KeyPress", "KeyRelease"]:
+ chr = self.char
+ if ord(chr) < ord("A"):
+ chr = "?"
+ s = "%s char='%s'%d keysym='%s' keycode=%d:%x state=%x keyinfo=%s" % (
+ self.type,
+ chr,
+ ord(self.char),
+ self.keysym,
+ self.keycode,
+ self.keycode,
+ self.state,
+ self.keyinfo,
+ )
+ elif self.type in ["Motion", "Button"]:
+ s = "%s x=%d y=%d state=%x" % (self.type, self.x, self.y, self.state)
+ elif self.type == "Configure":
+ s = "%s w=%d h=%d" % (self.type, self.width, self.height)
+ elif self.type in ["FocusIn", "FocusOut"]:
+ s = self.type
+ elif self.type == "Menu":
+ s = "%s state=%x" % (self.type, self.state)
+ else:
+ s = "unknown event type"
+ return s
+
+
+# def __str__(self):
+# return "('%s',%s,%s,%s)"%(self.char,self.key,self.state,self.keyinfo)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/console/ironpython_console.py b/python_embeded/Lib/site-packages/pyreadline3/console/ironpython_console.py
new file mode 100644
index 0000000000000000000000000000000000000000..9489e7280abc0087af563f706c3e50fb1befcc37
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/console/ironpython_console.py
@@ -0,0 +1,469 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import os
+import re
+
+import IronPythonConsole
+import System
+from pyreadline3.console.ansi import AnsiState
+from pyreadline3.keysyms import (
+ make_keyinfo,
+ make_KeyPress,
+ make_KeyPress_from_keydescr,
+ make_keysym,
+)
+from pyreadline3.logger import log
+
+from .event import Event
+
+"""Cursor control and color for the .NET console.
+"""
+
+#
+# Ironpython requires a patch to work do:
+#
+# In file PythonCommandLine.cs patch line:
+# class PythonCommandLine
+# {
+
+# to:
+# public class PythonCommandLine
+# {
+#
+#
+#
+# primitive debug printing that won't interfere with the screen
+
+import sys
+
+import clr
+
+clr.AddReferenceToFileAndPath(sys.executable)
+
+
+color = System.ConsoleColor
+
+ansicolor = {
+ "0;30": color.Black,
+ "0;31": color.DarkRed,
+ "0;32": color.DarkGreen,
+ "0;33": color.DarkYellow,
+ "0;34": color.DarkBlue,
+ "0;35": color.DarkMagenta,
+ "0;36": color.DarkCyan,
+ "0;37": color.DarkGray,
+ "1;30": color.Gray,
+ "1;31": color.Red,
+ "1;32": color.Green,
+ "1;33": color.Yellow,
+ "1;34": color.Blue,
+ "1;35": color.Magenta,
+ "1;36": color.Cyan,
+ "1;37": color.White,
+}
+
+winattr = {
+ "black": 0,
+ "darkgray": 0 + 8,
+ "darkred": 4,
+ "red": 4 + 8,
+ "darkgreen": 2,
+ "green": 2 + 8,
+ "darkyellow": 6,
+ "yellow": 6 + 8,
+ "darkblue": 1,
+ "blue": 1 + 8,
+ "darkmagenta": 5,
+ "magenta": 5 + 8,
+ "darkcyan": 3,
+ "cyan": 3 + 8,
+ "gray": 7,
+ "white": 7 + 8,
+}
+
+
+class Console(object):
+ """Console driver for Windows."""
+
+ def __init__(self, newbuffer=0):
+ """Initialize the Console object.
+
+ newbuffer=1 will allocate a new buffer so the old content will be restored
+ on exit.
+ """
+ self.serial = 0
+ self.attr = System.Console.ForegroundColor
+ self.saveattr = winattr[str(System.Console.ForegroundColor).lower()]
+ self.savebg = System.Console.BackgroundColor
+ log("initial attr=%s" % self.attr)
+
+ def _get(self):
+ top = System.Console.WindowTop
+ log("WindowTop:%s" % top)
+ return top
+
+ def _set(self, value):
+ top = System.Console.WindowTop
+ log("Set WindowTop:old:%s,new:%s" % (top, value))
+
+ WindowTop = property(_get, _set)
+ del _get, _set
+
+ def __del__(self):
+ """Cleanup the console when finished."""
+ # I don't think this ever gets called
+ pass
+
+ def pos(self, x=None, y=None):
+ """Move or query the window cursor."""
+ if x is not None:
+ System.Console.CursorLeft = x
+ else:
+ x = System.Console.CursorLeft
+ if y is not None:
+ System.Console.CursorTop = y
+ else:
+ y = System.Console.CursorTop
+ return x, y
+
+ def home(self):
+ """Move to home."""
+ self.pos(0, 0)
+
+ # Map ANSI color escape sequences into Windows Console Attributes
+
+ terminal_escape = re.compile("(\001?\033\\[[0-9;]*m\002?)")
+ escape_parts = re.compile("\001?\033\\[([0-9;]*)m\002?")
+
+ # This pattern should match all characters that change the cursor position differently
+ # than a normal character.
+ motion_char_re = re.compile("([\n\r\t\010\007])")
+
+ def write_scrolling(self, text, attr=None):
+ """write text at current cursor position while watching for scrolling.
+
+ If the window scrolls because you are at the bottom of the screen
+ buffer, all positions that you are storing will be shifted by the
+ scroll amount. For example, I remember the cursor position of the
+ prompt so that I can redraw the line but if the window scrolls,
+ the remembered position is off.
+
+ This variant of write tries to keep track of the cursor position
+ so that it will know when the screen buffer is scrolled. It
+ returns the number of lines that the buffer scrolled.
+
+ """
+ x, y = self.pos()
+ w, h = self.size()
+ scroll = 0 # the result
+
+ # split the string into ordinary characters and funny characters
+ chunks = self.motion_char_re.split(text)
+ for chunk in chunks:
+ n = self.write_color(chunk, attr)
+ if len(chunk) == 1: # the funny characters will be alone
+ if chunk[0] == "\n": # newline
+ x = 0
+ y += 1
+ elif chunk[0] == "\r": # carriage return
+ x = 0
+ elif chunk[0] == "\t": # tab
+ x = 8 * (int(x / 8) + 1)
+ if x > w: # newline
+ x -= w
+ y += 1
+ elif chunk[0] == "\007": # bell
+ pass
+ elif chunk[0] == "\010":
+ x -= 1
+ if x < 0:
+ y -= 1 # backed up 1 line
+ else: # ordinary character
+ x += 1
+ if x == w: # wrap
+ x = 0
+ y += 1
+ if y == h: # scroll
+ scroll += 1
+ y = h - 1
+ else: # chunk of ordinary characters
+ x += n
+ l = int(x / w) # lines we advanced
+ x = x % w # new x value
+ y += l
+ if y >= h: # scroll
+ scroll += y - h + 1
+ y = h - 1
+ return scroll
+
+ trtable = {
+ 0: color.Black,
+ 4: color.DarkRed,
+ 2: color.DarkGreen,
+ 6: color.DarkYellow,
+ 1: color.DarkBlue,
+ 5: color.DarkMagenta,
+ 3: color.DarkCyan,
+ 7: color.Gray,
+ 8: color.DarkGray,
+ 4 + 8: color.Red,
+ 2 + 8: color.Green,
+ 6 + 8: color.Yellow,
+ 1 + 8: color.Blue,
+ 5 + 8: color.Magenta,
+ 3 + 8: color.Cyan,
+ 7 + 8: color.White,
+ }
+
+ def write_color(self, text, attr=None):
+ """write text at current cursor position and interpret color escapes.
+
+ return the number of characters written.
+ """
+ log('write_color("%s", %s)' % (text, attr))
+ chunks = self.terminal_escape.split(text)
+ log("chunks=%s" % repr(chunks))
+ bg = self.savebg
+ n = 0 # count the characters we actually write, omitting the escapes
+ if attr is None: # use attribute from initial console
+ attr = self.attr
+ try:
+ fg = self.trtable[(0x000F & attr)]
+ bg = self.trtable[(0x00F0 & attr) >> 4]
+ except TypeError:
+ fg = attr
+
+ for chunk in chunks:
+ m = self.escape_parts.match(chunk)
+ if m:
+ log(m.group(1))
+ attr = ansicolor.get(m.group(1), self.attr)
+ n += len(chunk)
+ System.Console.ForegroundColor = fg
+ System.Console.BackgroundColor = bg
+ System.Console.Write(chunk)
+ return n
+
+ def write_plain(self, text, attr=None):
+ """write text at current cursor position."""
+ log('write("%s", %s)' % (text, attr))
+ if attr is None:
+ attr = self.attr
+ n = c_int(0)
+ self.SetConsoleTextAttribute(self.hout, attr)
+ self.WriteConsoleA(self.hout, text, len(text), byref(n), None)
+ return len(text)
+
+ if "EMACS" in os.environ:
+
+ def write_color(self, text, attr=None):
+ junk = c_int(0)
+ self.WriteFile(self.hout, text, len(text), byref(junk), None)
+ return len(text)
+
+ write_plain = write_color
+
+ # make this class look like a file object
+ def write(self, text):
+ log('write("%s")' % text)
+ return self.write_color(text)
+
+ # write = write_scrolling
+
+ def isatty(self):
+ return True
+
+ def flush(self):
+ pass
+
+ def page(self, attr=None, fill=" "):
+ """Fill the entire screen."""
+ System.Console.Clear()
+
+ def text(self, x, y, text, attr=None):
+ """Write text at the given position."""
+ self.pos(x, y)
+ self.write_color(text, attr)
+
+ def clear_to_end_of_window(self):
+ oldtop = self.WindowTop
+ lastline = self.WindowTop + System.Console.WindowHeight
+ pos = self.pos()
+ w, h = self.size()
+ length = w - pos[0] + min((lastline - pos[1] - 1), 5) * w - 1
+ self.write_color(length * " ")
+ self.pos(*pos)
+ self.WindowTop = oldtop
+
+ def rectangle(self, rect, attr=None, fill=" "):
+ """Fill Rectangle."""
+ oldtop = self.WindowTop
+ oldpos = self.pos()
+ # raise NotImplementedError
+ x0, y0, x1, y1 = rect
+ if attr is None:
+ attr = self.attr
+ if fill:
+ rowfill = fill[:1] * abs(x1 - x0)
+ else:
+ rowfill = " " * abs(x1 - x0)
+ for y in range(y0, y1):
+ System.Console.SetCursorPosition(x0, y)
+ self.write_color(rowfill, attr)
+ self.pos(*oldpos)
+
+ def scroll(self, rect, dx, dy, attr=None, fill=" "):
+ """Scroll a rectangle."""
+ raise NotImplementedError
+
+ def scroll_window(self, lines):
+ """Scroll the window by the indicated number of lines."""
+ top = self.WindowTop + lines
+ if top < 0:
+ top = 0
+ if top + System.Console.WindowHeight > System.Console.BufferHeight:
+ top = System.Console.BufferHeight
+ self.WindowTop = top
+
+ def getkeypress(self):
+ """Return next key press event from the queue, ignoring others."""
+ ck = System.ConsoleKey
+ while True:
+ e = System.Console.ReadKey(True)
+ if e.Key == System.ConsoleKey.PageDown: # PageDown
+ self.scroll_window(12)
+ elif e.Key == System.ConsoleKey.PageUp: # PageUp
+ self.scroll_window(-12)
+ elif str(e.KeyChar) == "\000": # Drop deadkeys
+ log("Deadkey: %s" % e)
+ return event(self, e)
+ else:
+ return event(self, e)
+
+ def title(self, txt=None):
+ """Set/get title."""
+ if txt:
+ System.Console.Title = txt
+ else:
+ return System.Console.Title
+
+ def size(self, width=None, height=None):
+ """Set/get window size."""
+ sc = System.Console
+ if width is not None and height is not None:
+ sc.BufferWidth, sc.BufferHeight = width, height
+ else:
+ return sc.BufferWidth, sc.BufferHeight
+
+ if width is not None and height is not None:
+ sc.WindowWidth, sc.WindowHeight = width, height
+ else:
+ return sc.WindowWidth - 1, sc.WindowHeight - 1
+
+ def cursor(self, visible=True, size=None):
+ """Set cursor on or off."""
+ System.Console.CursorVisible = visible
+
+ def bell(self):
+ System.Console.Beep()
+
+ def next_serial(self):
+ """Get next event serial number."""
+ self.serial += 1
+ return self.serial
+
+
+class event(Event):
+ """Represent events from the console."""
+
+ def __init__(self, console, input):
+ """Initialize an event from the Windows input structure."""
+ self.type = "??"
+ self.serial = console.next_serial()
+ self.width = 0
+ self.height = 0
+ self.x = 0
+ self.y = 0
+ self.char = str(input.KeyChar)
+ self.keycode = input.Key
+ self.state = input.Modifiers
+ log("%s,%s,%s" % (input.Modifiers, input.Key, input.KeyChar))
+ self.type = "KeyRelease"
+ self.keysym = make_keysym(self.keycode)
+ self.keyinfo = make_KeyPress(self.char, self.state, self.keycode)
+
+
+def make_event_from_keydescr(keydescr):
+ def input():
+ return 1
+
+ input.KeyChar = "a"
+ input.Key = System.ConsoleKey.A
+ input.Modifiers = System.ConsoleModifiers.Shift
+ input.next_serial = input
+ e = event(input, input)
+ del input.next_serial
+ keyinfo = make_KeyPress_from_keydescr(keydescr)
+ e.keyinfo = keyinfo
+ return e
+
+
+CTRL_C_EVENT = make_event_from_keydescr("Control-c")
+
+
+def install_readline(hook):
+ def hook_wrap():
+ try:
+ res = hook()
+ except KeyboardInterrupt as x: # this exception does not seem to be caught
+ res = ""
+ except EOFError:
+ return None
+ if res[-1:] == "\n":
+ return res[:-1]
+ else:
+ return res
+
+ class IronPythonWrapper(IronPythonConsole.IConsole):
+ def ReadLine(self, autoIndentSize):
+ return hook_wrap()
+
+ def Write(self, text, style):
+ System.Console.Write(text)
+
+ def WriteLine(self, text, style):
+ System.Console.WriteLine(text)
+
+ IronPythonConsole.PythonCommandLine.MyConsole = IronPythonWrapper()
+
+
+if __name__ == "__main__":
+ import sys
+ import time
+
+ c = Console(0)
+ sys.stdout = c
+ sys.stderr = c
+ c.page()
+ c.pos(5, 10)
+ c.write("hi there")
+ c.title("Testing console")
+ # c.bell()
+ print()
+ print("size", c.size())
+ print(" some printed output")
+ for i in range(10):
+ e = c.getkeypress()
+ print(e.Key, chr(e.KeyChar), ord(e.KeyChar), e.Modifiers)
+ del c
+
+ System.Console.Clear()
diff --git a/python_embeded/Lib/site-packages/pyreadline3/keysyms/__init__.py b/python_embeded/Lib/site-packages/pyreadline3/keysyms/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..77a7a2fbe2842c552e22ea4b5c52e1b3f165b99a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/keysyms/__init__.py
@@ -0,0 +1,14 @@
+from pyreadline3.py3k_compat import is_ironpython
+
+from . import winconstants
+
+if is_ironpython:
+ try:
+ from .ironpython_keysyms import *
+ except ImportError as x:
+ raise ImportError("Could not import keysym for local ironpython version") from x
+else:
+ try:
+ from .keysyms import *
+ except ImportError as x:
+ raise ImportError("Could not import keysym for local python version") from x
diff --git a/python_embeded/Lib/site-packages/pyreadline3/keysyms/common.py b/python_embeded/Lib/site-packages/pyreadline3/keysyms/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..f721bdf78ae0cd8d89408d127c0b6050b54f5393
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/keysyms/common.py
@@ -0,0 +1,198 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+# table for translating virtual keys to X windows key symbols
+
+
+try:
+ set
+except NameError:
+ from sets import Set as set
+
+from pyreadline3.unicode_helper import ensure_unicode
+
+validkey = set(
+ [
+ "cancel",
+ "backspace",
+ "tab",
+ "clear",
+ "return",
+ "shift_l",
+ "control_l",
+ "alt_l",
+ "pause",
+ "caps_lock",
+ "escape",
+ "space",
+ "prior",
+ "next",
+ "end",
+ "home",
+ "left",
+ "up",
+ "right",
+ "down",
+ "select",
+ "print",
+ "execute",
+ "snapshot",
+ "insert",
+ "delete",
+ "help",
+ "f1",
+ "f2",
+ "f3",
+ "f4",
+ "f5",
+ "f6",
+ "f7",
+ "f8",
+ "f9",
+ "f10",
+ "f11",
+ "f12",
+ "f13",
+ "f14",
+ "f15",
+ "f16",
+ "f17",
+ "f18",
+ "f19",
+ "f20",
+ "f21",
+ "f22",
+ "f23",
+ "f24",
+ "num_lock",
+ "scroll_lock",
+ "vk_apps",
+ "vk_processkey",
+ "vk_attn",
+ "vk_crsel",
+ "vk_exsel",
+ "vk_ereof",
+ "vk_play",
+ "vk_zoom",
+ "vk_noname",
+ "vk_pa1",
+ "vk_oem_clear",
+ "numpad0",
+ "numpad1",
+ "numpad2",
+ "numpad3",
+ "numpad4",
+ "numpad5",
+ "numpad6",
+ "numpad7",
+ "numpad8",
+ "numpad9",
+ "divide",
+ "multiply",
+ "add",
+ "subtract",
+ "vk_decimal",
+ ]
+)
+
+escape_sequence_to_special_key = {
+ "\\e[a": "up",
+ "\\e[b": "down",
+ "del": "delete",
+}
+
+
+class KeyPress(object):
+ def __init__(self, char="", shift=False, control=False, meta=False, keyname=""):
+ if control or meta or shift:
+ char = char.upper()
+ self.info = dict(
+ char=char, shift=shift, control=control, meta=meta, keyname=keyname
+ )
+
+ def create(name):
+ def get(self):
+ return self.info[name]
+
+ def set(self, value):
+ self.info[name] = value
+
+ return property(get, set)
+
+ char = create("char")
+ shift = create("shift")
+ control = create("control")
+ meta = create("meta")
+ keyname = create("keyname")
+
+ def __repr__(self):
+ return "(%s,%s,%s,%s)" % tuple(map(ensure_unicode, self.tuple()))
+
+ def tuple(self):
+ if self.keyname:
+ return (self.control, self.meta, self.shift, self.keyname)
+ else:
+ if self.control or self.meta or self.shift:
+ return (self.control, self.meta, self.shift, self.char.upper())
+ else:
+ return (self.control, self.meta, self.shift, self.char)
+
+ def __eq__(self, other):
+ if isinstance(other, KeyPress):
+ s = self.tuple()
+ o = other.tuple()
+ return s == o
+ else:
+ return False
+
+
+def make_KeyPress_from_keydescr(keydescr):
+ keyinfo = KeyPress()
+ if len(keydescr) > 2 and keydescr[:1] == '"' and keydescr[-1:] == '"':
+ keydescr = keydescr[1:-1]
+
+ while True:
+ lkeyname = keydescr.lower()
+ if lkeyname.startswith("control-"):
+ keyinfo.control = True
+ keydescr = keydescr[8:]
+ elif lkeyname.startswith("ctrl-"):
+ keyinfo.control = True
+ keydescr = keydescr[5:]
+ elif keydescr.lower().startswith("\\c-"):
+ keyinfo.control = True
+ keydescr = keydescr[3:]
+ elif keydescr.lower().startswith("\\m-"):
+ keyinfo.meta = True
+ keydescr = keydescr[3:]
+ elif keydescr in escape_sequence_to_special_key:
+ keydescr = escape_sequence_to_special_key[keydescr]
+ elif lkeyname.startswith("meta-"):
+ keyinfo.meta = True
+ keydescr = keydescr[5:]
+ elif lkeyname.startswith("alt-"):
+ keyinfo.meta = True
+ keydescr = keydescr[4:]
+ elif lkeyname.startswith("shift-"):
+ keyinfo.shift = True
+ keydescr = keydescr[6:]
+ else:
+ if len(keydescr) > 1:
+ if keydescr.strip().lower() in validkey:
+ keyinfo.keyname = keydescr.strip().lower()
+ keyinfo.char = ""
+ else:
+ raise IndexError("Not a valid key: '%s'" % keydescr)
+ else:
+ keyinfo.char = keydescr
+ return keyinfo
+
+
+if __name__ == "__main__":
+ import startup
diff --git a/python_embeded/Lib/site-packages/pyreadline3/keysyms/ironpython_keysyms.py b/python_embeded/Lib/site-packages/pyreadline3/keysyms/ironpython_keysyms.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ae55070d27eddbb86eb13e1776c54268ac2f4af
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/keysyms/ironpython_keysyms.py
@@ -0,0 +1,213 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import System
+
+from .common import KeyPress, make_KeyPress_from_keydescr, validkey
+
+c32 = System.ConsoleKey
+Shift = System.ConsoleModifiers.Shift
+Control = System.ConsoleModifiers.Control
+Alt = System.ConsoleModifiers.Alt
+# table for translating virtual keys to X windows key symbols
+code2sym_map = {
+ # c32.CANCEL: 'Cancel',
+ c32.Backspace: "BackSpace",
+ c32.Tab: "Tab",
+ c32.Clear: "Clear",
+ c32.Enter: "Return",
+ # c32.Shift: 'Shift_L',
+ # c32.Control: 'Control_L',
+ # c32.Menu: 'Alt_L',
+ c32.Pause: "Pause",
+ # c32.Capital: 'Caps_Lock',
+ c32.Escape: "Escape",
+ # c32.Space: 'space',
+ c32.PageUp: "Prior",
+ c32.PageDown: "Next",
+ c32.End: "End",
+ c32.Home: "Home",
+ c32.LeftArrow: "Left",
+ c32.UpArrow: "Up",
+ c32.RightArrow: "Right",
+ c32.DownArrow: "Down",
+ c32.Select: "Select",
+ c32.Print: "Print",
+ c32.Execute: "Execute",
+ # c32.Snapshot: 'Snapshot',
+ c32.Insert: "Insert",
+ c32.Delete: "Delete",
+ c32.Help: "Help",
+ c32.F1: "F1",
+ c32.F2: "F2",
+ c32.F3: "F3",
+ c32.F4: "F4",
+ c32.F5: "F5",
+ c32.F6: "F6",
+ c32.F7: "F7",
+ c32.F8: "F8",
+ c32.F9: "F9",
+ c32.F10: "F10",
+ c32.F11: "F11",
+ c32.F12: "F12",
+ c32.F13: "F13",
+ c32.F14: "F14",
+ c32.F15: "F15",
+ c32.F16: "F16",
+ c32.F17: "F17",
+ c32.F18: "F18",
+ c32.F19: "F19",
+ c32.F20: "F20",
+ c32.F21: "F21",
+ c32.F22: "F22",
+ c32.F23: "F23",
+ c32.F24: "F24",
+ # c32.Numlock: 'Num_Lock,',
+ # c32.Scroll: 'Scroll_Lock',
+ # c32.Apps: 'VK_APPS',
+ # c32.ProcesskeY: 'VK_PROCESSKEY',
+ # c32.Attn: 'VK_ATTN',
+ # c32.Crsel: 'VK_CRSEL',
+ # c32.Exsel: 'VK_EXSEL',
+ # c32.Ereof: 'VK_EREOF',
+ # c32.Play: 'VK_PLAY',
+ # c32.Zoom: 'VK_ZOOM',
+ # c32.Noname: 'VK_NONAME',
+ # c32.Pa1: 'VK_PA1',
+ c32.OemClear: "VK_OEM_CLEAR",
+ c32.NumPad0: "NUMPAD0",
+ c32.NumPad1: "NUMPAD1",
+ c32.NumPad2: "NUMPAD2",
+ c32.NumPad3: "NUMPAD3",
+ c32.NumPad4: "NUMPAD4",
+ c32.NumPad5: "NUMPAD5",
+ c32.NumPad6: "NUMPAD6",
+ c32.NumPad7: "NUMPAD7",
+ c32.NumPad8: "NUMPAD8",
+ c32.NumPad9: "NUMPAD9",
+ c32.Divide: "Divide",
+ c32.Multiply: "Multiply",
+ c32.Add: "Add",
+ c32.Subtract: "Subtract",
+ c32.Decimal: "VK_DECIMAL",
+}
+
+# function to handle the mapping
+
+
+def make_keysym(keycode):
+ try:
+ sym = code2sym_map[keycode]
+ except KeyError:
+ sym = ""
+ return sym
+
+
+sym2code_map = {}
+for code, sym in code2sym_map.items():
+ sym2code_map[sym.lower()] = code
+
+
+def key_text_to_keyinfo(keytext):
+ """Convert a GNU readline style textual description of a key to keycode with modifiers"""
+ if keytext.startswith('"'): # "
+ return keyseq_to_keyinfo(keytext[1:-1])
+ else:
+ return keyname_to_keyinfo(keytext)
+
+
+def char_to_keyinfo(char, control=False, meta=False, shift=False):
+ vk = ord(char)
+ if vk & 0xFFFF == 0xFFFF:
+ print('VkKeyScan("%s") = %x' % (char, vk))
+ raise ValueError("bad key")
+ if vk & 0x100:
+ shift = True
+ if vk & 0x200:
+ control = True
+ if vk & 0x400:
+ meta = True
+ return (control, meta, shift, vk & 0xFF)
+
+
+def keyname_to_keyinfo(keyname):
+ control = False
+ meta = False
+ shift = False
+
+ while True:
+ lkeyname = keyname.lower()
+ if lkeyname.startswith("control-"):
+ control = True
+ keyname = keyname[8:]
+ elif lkeyname.startswith("ctrl-"):
+ control = True
+ keyname = keyname[5:]
+ elif lkeyname.startswith("meta-"):
+ meta = True
+ keyname = keyname[5:]
+ elif lkeyname.startswith("alt-"):
+ meta = True
+ keyname = keyname[4:]
+ elif lkeyname.startswith("shift-"):
+ shift = True
+ keyname = keyname[6:]
+ else:
+ if len(keyname) > 1:
+ return (control, meta, shift, sym2code_map.get(keyname.lower(), " "))
+ else:
+ return char_to_keyinfo(keyname, control, meta, shift)
+
+
+def keyseq_to_keyinfo(keyseq):
+ res = []
+ control = False
+ meta = False
+ shift = False
+
+ while True:
+ if keyseq.startswith("\\C-"):
+ control = True
+ keyseq = keyseq[3:]
+ elif keyseq.startswith("\\M-"):
+ meta = True
+ keyseq = keyseq[3:]
+ elif keyseq.startswith("\\e"):
+ res.append(char_to_keyinfo("\033", control, meta, shift))
+ control = meta = shift = False
+ keyseq = keyseq[2:]
+ elif len(keyseq) >= 1:
+ res.append(char_to_keyinfo(keyseq[0], control, meta, shift))
+ control = meta = shift = False
+ keyseq = keyseq[1:]
+ else:
+ return res[0]
+
+
+def make_keyinfo(keycode, state):
+ control = False
+ meta = False
+ shift = False
+ return (control, meta, shift, keycode)
+
+
+def make_KeyPress(char, state, keycode):
+
+ shift = bool(int(state) & int(Shift))
+ control = bool(int(state) & int(Control))
+ meta = bool(int(state) & int(Alt))
+ keyname = code2sym_map.get(keycode, "").lower()
+ if control and meta: # equivalent to altgr so clear flags
+ control = False
+ meta = False
+ elif control:
+ char = str(keycode)
+ return KeyPress(char, shift, control, meta, keyname)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/keysyms/keysyms.py b/python_embeded/Lib/site-packages/pyreadline3/keysyms/keysyms.py
new file mode 100644
index 0000000000000000000000000000000000000000..a3caab18daa902aa30a976767a4341bc1608ce71
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/keysyms/keysyms.py
@@ -0,0 +1,138 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+from ctypes import windll
+
+from . import winconstants as c32
+from .common import KeyPress
+
+# table for translating virtual keys to X windows key symbols
+
+code2sym_map = {
+ c32.VK_CANCEL: "cancel",
+ c32.VK_BACK: "backspace",
+ c32.VK_TAB: "tab",
+ c32.VK_CLEAR: "clear",
+ c32.VK_RETURN: "return",
+ c32.VK_SHIFT: "shift_l",
+ c32.VK_CONTROL: "control_l",
+ c32.VK_MENU: "alt_l",
+ c32.VK_PAUSE: "pause",
+ c32.VK_CAPITAL: "caps_lock",
+ c32.VK_ESCAPE: "escape",
+ c32.VK_SPACE: "space",
+ c32.VK_PRIOR: "prior",
+ c32.VK_NEXT: "next",
+ c32.VK_END: "end",
+ c32.VK_HOME: "home",
+ c32.VK_LEFT: "left",
+ c32.VK_UP: "up",
+ c32.VK_RIGHT: "right",
+ c32.VK_DOWN: "down",
+ c32.VK_SELECT: "select",
+ c32.VK_PRINT: "print",
+ c32.VK_EXECUTE: "execute",
+ c32.VK_SNAPSHOT: "snapshot",
+ c32.VK_INSERT: "insert",
+ c32.VK_DELETE: "delete",
+ c32.VK_HELP: "help",
+ c32.VK_F1: "f1",
+ c32.VK_F2: "f2",
+ c32.VK_F3: "f3",
+ c32.VK_F4: "f4",
+ c32.VK_F5: "f5",
+ c32.VK_F6: "f6",
+ c32.VK_F7: "f7",
+ c32.VK_F8: "f8",
+ c32.VK_F9: "f9",
+ c32.VK_F10: "f10",
+ c32.VK_F11: "f11",
+ c32.VK_F12: "f12",
+ c32.VK_F13: "f13",
+ c32.VK_F14: "f14",
+ c32.VK_F15: "f15",
+ c32.VK_F16: "f16",
+ c32.VK_F17: "f17",
+ c32.VK_F18: "f18",
+ c32.VK_F19: "f19",
+ c32.VK_F20: "f20",
+ c32.VK_F21: "f21",
+ c32.VK_F22: "f22",
+ c32.VK_F23: "f23",
+ c32.VK_F24: "f24",
+ c32.VK_NUMLOCK: "num_lock,",
+ c32.VK_SCROLL: "scroll_lock",
+ c32.VK_APPS: "vk_apps",
+ c32.VK_PROCESSKEY: "vk_processkey",
+ c32.VK_ATTN: "vk_attn",
+ c32.VK_CRSEL: "vk_crsel",
+ c32.VK_EXSEL: "vk_exsel",
+ c32.VK_EREOF: "vk_ereof",
+ c32.VK_PLAY: "vk_play",
+ c32.VK_ZOOM: "vk_zoom",
+ c32.VK_NONAME: "vk_noname",
+ c32.VK_PA1: "vk_pa1",
+ c32.VK_OEM_CLEAR: "vk_oem_clear",
+ c32.VK_NUMPAD0: "numpad0",
+ c32.VK_NUMPAD1: "numpad1",
+ c32.VK_NUMPAD2: "numpad2",
+ c32.VK_NUMPAD3: "numpad3",
+ c32.VK_NUMPAD4: "numpad4",
+ c32.VK_NUMPAD5: "numpad5",
+ c32.VK_NUMPAD6: "numpad6",
+ c32.VK_NUMPAD7: "numpad7",
+ c32.VK_NUMPAD8: "numpad8",
+ c32.VK_NUMPAD9: "numpad9",
+ c32.VK_DIVIDE: "divide",
+ c32.VK_MULTIPLY: "multiply",
+ c32.VK_ADD: "add",
+ c32.VK_SUBTRACT: "subtract",
+ c32.VK_DECIMAL: "vk_decimal",
+}
+
+VkKeyScan = windll.user32.VkKeyScanA
+
+
+def char_to_keyinfo(char, control=False, meta=False, shift=False):
+ k = KeyPress()
+ vk = VkKeyScan(ord(char))
+ if vk & 0xFFFF == 0xFFFF:
+ print('VkKeyScan("%s") = %x' % (char, vk))
+ raise ValueError("bad key")
+ if vk & 0x100:
+ k.shift = True
+ if vk & 0x200:
+ k.control = True
+ if vk & 0x400:
+ k.meta = True
+ k.char = chr(vk & 0xFF)
+ return k
+
+
+def make_KeyPress(char, state, keycode):
+ control = (state & (4 + 8)) != 0
+ meta = (state & (1 + 2)) != 0
+ shift = (state & 0x10) != 0
+ if control and not meta: # Matches ctrl- chords should pass keycode as char
+ char = chr(keycode)
+ elif control and meta: # Matches alt gr and should just pass on char
+ control = False
+ meta = False
+ try:
+ keyname = code2sym_map[keycode]
+ except KeyError:
+ keyname = ""
+ out = KeyPress(char, shift, control, meta, keyname)
+ return out
+
+
+if __name__ == "__main__":
+ import startup
diff --git a/python_embeded/Lib/site-packages/pyreadline3/keysyms/winconstants.py b/python_embeded/Lib/site-packages/pyreadline3/keysyms/winconstants.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f3e5a9df9dd74bee3460f505bdf106fc7870fe0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/keysyms/winconstants.py
@@ -0,0 +1,172 @@
+# This file contains constants that are normally found in win32all
+# But included here to avoid the dependency
+
+
+VK_LBUTTON = 1
+VK_RBUTTON = 2
+VK_CANCEL = 3
+VK_MBUTTON = 4
+VK_XBUTTON1 = 5
+VK_XBUTTON2 = 6
+VK_BACK = 8
+VK_TAB = 9
+VK_CLEAR = 12
+VK_RETURN = 13
+VK_SHIFT = 16
+VK_CONTROL = 17
+VK_MENU = 18
+VK_PAUSE = 19
+VK_CAPITAL = 20
+VK_KANA = 0x15
+VK_HANGEUL = 0x15
+VK_HANGUL = 0x15
+VK_JUNJA = 0x17
+VK_FINAL = 0x18
+VK_HANJA = 0x19
+VK_KANJI = 0x19
+VK_ESCAPE = 0x1B
+VK_CONVERT = 0x1C
+VK_NONCONVERT = 0x1D
+VK_ACCEPT = 0x1E
+VK_MODECHANGE = 0x1F
+VK_SPACE = 32
+VK_PRIOR = 33
+VK_NEXT = 34
+VK_END = 35
+VK_HOME = 36
+VK_LEFT = 37
+VK_UP = 38
+VK_RIGHT = 39
+VK_DOWN = 40
+VK_SELECT = 41
+VK_PRINT = 42
+VK_EXECUTE = 43
+VK_SNAPSHOT = 44
+VK_INSERT = 45
+VK_DELETE = 46
+VK_HELP = 47
+VK_LWIN = 0x5B
+VK_RWIN = 0x5C
+VK_APPS = 0x5D
+VK_SLEEP = 0x5F
+VK_NUMPAD0 = 0x60
+VK_NUMPAD1 = 0x61
+VK_NUMPAD2 = 0x62
+VK_NUMPAD3 = 0x63
+VK_NUMPAD4 = 0x64
+VK_NUMPAD5 = 0x65
+VK_NUMPAD6 = 0x66
+VK_NUMPAD7 = 0x67
+VK_NUMPAD8 = 0x68
+VK_NUMPAD9 = 0x69
+VK_MULTIPLY = 0x6A
+VK_ADD = 0x6B
+VK_SEPARATOR = 0x6C
+VK_SUBTRACT = 0x6D
+VK_DECIMAL = 0x6E
+VK_DIVIDE = 0x6F
+VK_F1 = 0x70
+VK_F2 = 0x71
+VK_F3 = 0x72
+VK_F4 = 0x73
+VK_F5 = 0x74
+VK_F6 = 0x75
+VK_F7 = 0x76
+VK_F8 = 0x77
+VK_F9 = 0x78
+VK_F10 = 0x79
+VK_F11 = 0x7A
+VK_F12 = 0x7B
+VK_F13 = 0x7C
+VK_F14 = 0x7D
+VK_F15 = 0x7E
+VK_F16 = 0x7F
+VK_F17 = 0x80
+VK_F18 = 0x81
+VK_F19 = 0x82
+VK_F20 = 0x83
+VK_F21 = 0x84
+VK_F22 = 0x85
+VK_F23 = 0x86
+VK_F24 = 0x87
+VK_NUMLOCK = 0x90
+VK_SCROLL = 0x91
+VK_LSHIFT = 0xA0
+VK_RSHIFT = 0xA1
+VK_LCONTROL = 0xA2
+VK_RCONTROL = 0xA3
+VK_LMENU = 0xA4
+VK_RMENU = 0xA5
+VK_BROWSER_BACK = 0xA6
+VK_BROWSER_FORWARD = 0xA7
+VK_BROWSER_REFRESH = 0xA8
+VK_BROWSER_STOP = 0xA9
+VK_BROWSER_SEARCH = 0xAA
+VK_BROWSER_FAVORITES = 0xAB
+VK_BROWSER_HOME = 0xAC
+VK_VOLUME_MUTE = 0xAD
+VK_VOLUME_DOWN = 0xAE
+VK_VOLUME_UP = 0xAF
+VK_MEDIA_NEXT_TRACK = 0xB0
+VK_MEDIA_PREV_TRACK = 0xB1
+VK_MEDIA_STOP = 0xB2
+VK_MEDIA_PLAY_PAUSE = 0xB3
+VK_LAUNCH_MAIL = 0xB4
+VK_LAUNCH_MEDIA_SELECT = 0xB5
+VK_LAUNCH_APP1 = 0xB6
+VK_LAUNCH_APP2 = 0xB7
+VK_OEM_1 = 0xBA
+VK_OEM_PLUS = 0xBB
+VK_OEM_COMMA = 0xBC
+VK_OEM_MINUS = 0xBD
+VK_OEM_PERIOD = 0xBE
+VK_OEM_2 = 0xBF
+VK_OEM_3 = 0xC0
+VK_OEM_4 = 0xDB
+VK_OEM_5 = 0xDC
+VK_OEM_6 = 0xDD
+VK_OEM_7 = 0xDE
+VK_OEM_8 = 0xDF
+VK_OEM_102 = 0xE2
+VK_PROCESSKEY = 0xE5
+VK_PACKET = 0xE7
+VK_ATTN = 0xF6
+VK_CRSEL = 0xF7
+VK_EXSEL = 0xF8
+VK_EREOF = 0xF9
+VK_PLAY = 0xFA
+VK_ZOOM = 0xFB
+VK_NONAME = 0xFC
+VK_PA1 = 0xFD
+VK_OEM_CLEAR = 0xFE
+
+CF_TEXT = 1
+CF_BITMAP = 2
+CF_METAFILEPICT = 3
+CF_SYLK = 4
+CF_DIF = 5
+CF_TIFF = 6
+CF_OEMTEXT = 7
+CF_DIB = 8
+CF_PALETTE = 9
+CF_PENDATA = 10
+CF_RIFF = 11
+CF_WAVE = 12
+CF_UNICODETEXT = 13
+CF_ENHMETAFILE = 14
+CF_HDROP = 15
+CF_LOCALE = 16
+CF_MAX = 17
+CF_OWNERDISPLAY = 128
+CF_DSPTEXT = 129
+CF_DSPBITMAP = 130
+CF_DSPMETAFILEPICT = 131
+CF_DSPENHMETAFILE = 142
+CF_PRIVATEFIRST = 512
+CF_PRIVATELAST = 767
+CF_GDIOBJFIRST = 768
+CF_GDIOBJLAST = 1023
+
+
+GPTR = 64
+GHND = 66
diff --git a/python_embeded/Lib/site-packages/pyreadline3/lineeditor/__init__.py b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pyreadline3/lineeditor/history.py b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/history.py
new file mode 100644
index 0000000000000000000000000000000000000000..87e4d866ee639e9d76d8d0683b2b465febe73c32
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/history.py
@@ -0,0 +1,284 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+import re, operator, string, sys, os, io
+
+from pyreadline3.logger import log
+from pyreadline3.unicode_helper import ensure_str, ensure_unicode
+
+from . import lineobj
+
+
+class EscapeHistory(Exception):
+ pass
+
+
+class LineHistory(object):
+ def __init__(self):
+ self.history = []
+ self._history_length = 100
+ self._history_cursor = 0
+ # Cannot expand unicode strings correctly on python2.4
+ self.history_filename = os.path.expanduser(ensure_str("~/.history"))
+ self.lastcommand = None
+ self.query = ""
+ self.last_search_for = ""
+
+ def get_current_history_length(self):
+ """Return the number of lines currently in the history.
+ (This is different from get_history_length(), which returns
+ the maximum number of lines that will be written to a history file.)"""
+ value = len(self.history)
+ log("get_current_history_length:%d" % value)
+ return value
+
+ def get_history_length(self):
+ """Return the desired length of the history file. Negative values imply
+ unlimited history file size."""
+ value = self._history_length
+ log("get_history_length:%d" % value)
+ return value
+
+ def get_history_item(self, index):
+ """Return the current contents of history item at index (starts with index 1)."""
+ item = self.history[index - 1]
+ log("get_history_item: index:%d item:%r" % (index, item))
+ return item.get_line_text()
+
+ def set_history_length(self, value):
+ log("set_history_length: old:%d new:%d" % (self._history_length, value))
+ self._history_length = value
+
+ def get_history_cursor(self):
+ value = self._history_cursor
+ log("get_history_cursor:%d" % value)
+ return value
+
+ def set_history_cursor(self, value):
+ log("set_history_cursor: old:%d new:%d" % (self._history_cursor, value))
+ self._history_cursor = value
+
+ history_length = property(get_history_length, set_history_length)
+ history_cursor = property(get_history_cursor, set_history_cursor)
+
+ def clear_history(self):
+ """Clear readline history."""
+ self.history[:] = []
+ self.history_cursor = 0
+
+ def read_history_file(self, filename=None):
+ """Load a readline history file."""
+ if filename is None:
+ filename = self.history_filename
+ try:
+ with io.open(filename, "rt", errors="replace") as fd:
+ for line in fd:
+ self.add_history(lineobj.ReadLineTextBuffer(line.rstrip()))
+ except IOError:
+ self.history = []
+ self.history_cursor = 0
+
+ def write_history_file(self, filename=None):
+ """Save a readline history file."""
+ if filename is None:
+ filename = self.history_filename
+ with io.open(filename, "wt", errors="replace") as fp:
+ fp.writelines(
+ tuple(
+ line.get_line_text()+"\n"
+ for line in self.history[-self.history_length :]
+ )
+ )
+
+ def add_history(self, line):
+ """Append a line to the history buffer, as if it was the last line typed."""
+ line = ensure_unicode(line)
+ if not hasattr(line, "get_line_text"):
+ line = lineobj.ReadLineTextBuffer(line)
+ if not line.get_line_text():
+ pass
+ elif (
+ len(self.history) > 0
+ and self.history[-1].get_line_text() == line.get_line_text()
+ ):
+ pass
+ else:
+ self.history.append(line)
+ self.history_cursor = len(self.history)
+
+ def previous_history(self, current): # (C-p)
+ """Move back through the history list, fetching the previous command."""
+ if self.history_cursor == len(self.history):
+ # do not use add_history since we do not want to increment cursor
+ self.history.append(current.copy())
+
+ if self.history_cursor > 0:
+ self.history_cursor -= 1
+ current.set_line(self.history[self.history_cursor].get_line_text())
+ current.point = lineobj.EndOfLine
+
+ def next_history(self, current): # (C-n)
+ """Move forward through the history list, fetching the next command."""
+ if self.history_cursor < len(self.history) - 1:
+ self.history_cursor += 1
+ current.set_line(self.history[self.history_cursor].get_line_text())
+
+ def beginning_of_history(self): # (M-<)
+ """Move to the first line in the history."""
+ self.history_cursor = 0
+ if len(self.history) > 0:
+ self.l_buffer = self.history[0]
+
+ def end_of_history(self, current): # (M->)
+ """Move to the end of the input history, i.e., the line currently
+ being entered."""
+ self.history_cursor = len(self.history)
+ current.set_line(self.history[-1].get_line_text())
+
+ def reverse_search_history(self, searchfor, startpos=None):
+ if startpos is None:
+ startpos = self.history_cursor
+ origpos = startpos
+
+ result = lineobj.ReadLineTextBuffer("")
+
+ for idx, line in list(enumerate(self.history))[startpos:0:-1]:
+ if searchfor in line:
+ startpos = idx
+ break
+
+ # If we get a new search without change in search term it means
+ # someone pushed ctrl-r and we should find the next match
+ if self.last_search_for == searchfor and startpos > 0:
+ startpos -= 1
+ for idx, line in list(enumerate(self.history))[startpos:0:-1]:
+ if searchfor in line:
+ startpos = idx
+ break
+
+ if self.history:
+ result = self.history[startpos].get_line_text()
+ else:
+ result = ""
+ self.history_cursor = startpos
+ self.last_search_for = searchfor
+ log(
+ "reverse_search_history: old:%d new:%d result:%r"
+ % (origpos, self.history_cursor, result)
+ )
+ return result
+
+ def forward_search_history(self, searchfor, startpos=None):
+ if startpos is None:
+ startpos = min(
+ self.history_cursor, max(0, self.get_current_history_length() - 1)
+ )
+ # origpos = startpos
+
+ result = lineobj.ReadLineTextBuffer("")
+
+ for idx, line in list(enumerate(self.history))[startpos:]:
+ if searchfor in line:
+ startpos = idx
+ break
+
+ # If we get a new search without change in search term it means
+ # someone pushed ctrl-r and we should find the next match
+ if (
+ self.last_search_for == searchfor
+ and startpos < self.get_current_history_length() - 1
+ ):
+ startpos += 1
+ for idx, line in list(enumerate(self.history))[startpos:]:
+ if searchfor in line:
+ startpos = idx
+ break
+
+ if self.history:
+ result = self.history[startpos].get_line_text()
+ else:
+ result = ""
+ self.history_cursor = startpos
+ self.last_search_for = searchfor
+ return result
+
+ def _search(self, direction, partial):
+ try:
+ if (
+ self.lastcommand != self.history_search_forward
+ and self.lastcommand != self.history_search_backward
+ ):
+ self.query = "".join(partial[0 : partial.point].get_line_text())
+ hcstart = max(self.history_cursor, 0)
+ hc = self.history_cursor + direction
+ while (direction < 0 and hc >= 0) or (
+ direction > 0 and hc < len(self.history)
+ ):
+ h = self.history[hc]
+ if not self.query:
+ self.history_cursor = hc
+ result = lineobj.ReadLineTextBuffer(h, point=len(h.get_line_text()))
+ return result
+ elif h.get_line_text().startswith(self.query) and (
+ h != partial.get_line_text()
+ ):
+ self.history_cursor = hc
+ result = lineobj.ReadLineTextBuffer(h, point=partial.point)
+ return result
+ hc += direction
+ else:
+ if len(self.history) == 0:
+ pass
+ elif hc >= len(self.history) and not self.query:
+ self.history_cursor = len(self.history)
+ return lineobj.ReadLineTextBuffer("", point=0)
+ elif (
+ self.history[max(min(hcstart, len(self.history) - 1), 0)]
+ .get_line_text()
+ .startswith(self.query)
+ and self.query
+ ):
+ return lineobj.ReadLineTextBuffer(
+ self.history[max(min(hcstart, len(self.history) - 1), 0)],
+ point=partial.point,
+ )
+ else:
+ return lineobj.ReadLineTextBuffer(partial, point=partial.point)
+ return lineobj.ReadLineTextBuffer(
+ self.query, point=min(len(self.query), partial.point)
+ )
+ except IndexError:
+ raise
+
+ def history_search_forward(self, partial): # ()
+ """Search forward through the history for the string of characters
+ between the start of the current line and the point. This is a
+ non-incremental search. By default, this command is unbound."""
+ return self._search(1, partial)
+
+ def history_search_backward(self, partial): # ()
+ """Search backward through the history for the string of characters
+ between the start of the current line and the point. This is a
+ non-incremental search. By default, this command is unbound."""
+
+ return self._search(-1, partial)
+
+
+if __name__ == "__main__":
+ q = LineHistory()
+ r = LineHistory()
+ s = LineHistory()
+ RL = lineobj.ReadLineTextBuffer
+ q.add_history(RL("aaaa"))
+ q.add_history(RL("aaba"))
+ q.add_history(RL("aaca"))
+ q.add_history(RL("akca"))
+ q.add_history(RL("bbb"))
+ q.add_history(RL("ako"))
+ r.add_history(RL("ako"))
diff --git a/python_embeded/Lib/site-packages/pyreadline3/lineeditor/lineobj.py b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/lineobj.py
new file mode 100644
index 0000000000000000000000000000000000000000..65157c3e86cddc7daa2df28b7254b1109aae0413
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/lineobj.py
@@ -0,0 +1,866 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import pyreadline3.clipboard as clipboard
+from pyreadline3.unicode_helper import biter, ensure_unicode
+
+from . import wordmatcher
+
+# set to true to copy every addition to kill ring to clipboard
+kill_ring_to_clipboard = False
+
+
+class NotAWordError(IndexError):
+ pass
+
+
+def quote_char(c):
+ if ord(c) > 0:
+ return c
+
+
+# ############# Line positioner ########################
+
+
+class LinePositioner(object):
+ def __call__(self, line):
+ NotImplementedError("Base class !!!")
+
+
+class NextChar(LinePositioner):
+ def __call__(self, line):
+ if line.point < len(line.line_buffer):
+ return line.point + 1
+ else:
+ return line.point
+
+
+NextChar = NextChar()
+
+
+class PrevChar(LinePositioner):
+ def __call__(self, line):
+ if line.point > 0:
+ return line.point - 1
+ else:
+ return line.point
+
+
+PrevChar = PrevChar()
+
+
+class NextWordStart(LinePositioner):
+ def __call__(self, line):
+ return line.next_start_segment(line.line_buffer, line.is_word_token)[line.point]
+
+
+NextWordStart = NextWordStart()
+
+
+class NextWordEnd(LinePositioner):
+ def __call__(self, line):
+ return line.next_end_segment(line.line_buffer, line.is_word_token)[line.point]
+
+
+NextWordEnd = NextWordEnd()
+
+
+class PrevWordStart(LinePositioner):
+ def __call__(self, line):
+ return line.prev_start_segment(line.line_buffer, line.is_word_token)[line.point]
+
+
+PrevWordStart = PrevWordStart()
+
+
+class WordStart(LinePositioner):
+ def __call__(self, line):
+ if line.is_word_token(line.get_line_text()[Point(line) : Point(line) + 1]):
+ if Point(line) > 0 and line.is_word_token(
+ line.get_line_text()[Point(line) - 1 : Point(line)]
+ ):
+ return PrevWordStart(line)
+ else:
+ return line.point
+ else:
+ raise NotAWordError("Point is not in a word")
+
+
+WordStart = WordStart()
+
+
+class WordEnd(LinePositioner):
+ def __call__(self, line):
+ if line.is_word_token(line.get_line_text()[Point(line) : Point(line) + 1]):
+ if line.is_word_token(
+ line.get_line_text()[Point(line) + 1 : Point(line) + 2]
+ ):
+ return NextWordEnd(line)
+ else:
+ return line.point
+ else:
+ raise NotAWordError("Point is not in a word")
+
+
+WordEnd = WordEnd()
+
+
+class PrevWordEnd(LinePositioner):
+ def __call__(self, line):
+ return line.prev_end_segment(line.line_buffer, line.is_word_token)[line.point]
+
+
+PrevWordEnd = PrevWordEnd()
+
+
+class PrevSpace(LinePositioner):
+ def __call__(self, line):
+ point = line.point
+ if line[point - 1 : point].get_line_text() == " ":
+ while point > 0 and line[point - 1 : point].get_line_text() == " ":
+ point -= 1
+ while point > 0 and line[point - 1 : point].get_line_text() != " ":
+ point -= 1
+ return point
+
+
+PrevSpace = PrevSpace()
+
+
+class StartOfLine(LinePositioner):
+ def __call__(self, line):
+ return 0
+
+
+StartOfLine = StartOfLine()
+
+
+class EndOfLine(LinePositioner):
+ def __call__(self, line):
+ return len(line.line_buffer)
+
+
+EndOfLine = EndOfLine()
+
+
+class Point(LinePositioner):
+ def __call__(self, line):
+ return line.point
+
+
+Point = Point()
+
+
+class Mark(LinePositioner):
+ def __call__(self, line):
+ return line.mark
+
+
+k = Mark()
+
+all_positioners = sorted(
+ [
+ (value.__class__.__name__, value)
+ for key, value in globals().items()
+ if isinstance(value, LinePositioner)
+ ]
+)
+
+# ############## LineSlice #################
+
+
+class LineSlice(object):
+ def __call__(self, line):
+ NotImplementedError("Base class !!!")
+
+
+class CurrentWord(LineSlice):
+ def __call__(self, line):
+ return slice(WordStart(line), WordEnd(line), None)
+
+
+CurrentWord = CurrentWord()
+
+
+class NextWord(LineSlice):
+ def __call__(self, line):
+ work = TextLine(line)
+ work.point = NextWordStart
+ start = work.point
+ stop = NextWordEnd(work)
+ return slice(start, stop)
+
+
+NextWord = NextWord()
+
+
+class PrevWord(LineSlice):
+ def __call__(self, line):
+ work = TextLine(line)
+ work.point = PrevWordEnd
+ stop = work.point
+ start = PrevWordStart(work)
+ return slice(start, stop)
+
+
+PrevWord = PrevWord()
+
+
+class PointSlice(LineSlice):
+ def __call__(self, line):
+ return slice(Point(line), Point(line) + 1, None)
+
+
+PointSlice = PointSlice()
+
+
+# ############## TextLine ######################
+
+
+class TextLine(object):
+ def __init__(self, txtstr, point=None, mark=None):
+ self.line_buffer = []
+ self._point = 0
+ self.mark = -1
+ self.undo_stack = []
+ self.overwrite = False
+ if isinstance(txtstr, TextLine): # copy
+ self.line_buffer = txtstr.line_buffer[:]
+ if point is None:
+ self.point = txtstr.point
+ else:
+ self.point = point
+ if mark is None:
+ self.mark = txtstr.mark
+ else:
+ self.mark = mark
+ else:
+ self._insert_text(txtstr)
+ if point is None:
+ self.point = 0
+ else:
+ self.point = point
+ if mark is None:
+ self.mark = -1
+ else:
+ self.mark = mark
+
+ self.is_word_token = wordmatcher.is_word_token
+ self.next_start_segment = wordmatcher.next_start_segment
+ self.next_end_segment = wordmatcher.next_end_segment
+ self.prev_start_segment = wordmatcher.prev_start_segment
+ self.prev_end_segment = wordmatcher.prev_end_segment
+
+ def push_undo(self):
+ l_text = self.get_line_text()
+ if self.undo_stack and l_text == self.undo_stack[-1].get_line_text():
+ self.undo_stack[-1].point = self.point
+ else:
+ self.undo_stack.append(self.copy())
+
+ def pop_undo(self):
+ if len(self.undo_stack) >= 2:
+ self.undo_stack.pop()
+ self.set_top_undo()
+ self.undo_stack.pop()
+ else:
+ self.reset_line()
+ self.undo_stack = []
+
+ def set_top_undo(self):
+ if self.undo_stack:
+ undo = self.undo_stack[-1]
+ self.line_buffer = undo.line_buffer
+ self.point = undo.point
+ self.mark = undo.mark
+ else:
+ pass
+
+ def __repr__(self):
+ return 'TextLine("%s",point=%s,mark=%s)' % (
+ self.line_buffer,
+ self.point,
+ self.mark,
+ )
+
+ def copy(self):
+ return self.__class__(self)
+
+ def set_point(self, value):
+ if isinstance(value, LinePositioner):
+ value = value(self)
+ assert value <= len(self.line_buffer)
+ if value > len(self.line_buffer):
+ value = len(self.line_buffer)
+ self._point = value
+
+ def get_point(self):
+ return self._point
+
+ point = property(get_point, set_point)
+
+ def visible_line_width(self, position=Point):
+ """Return the visible width of the text up to position."""
+ extra_char_width = len(
+ [None for c in self[:position].line_buffer if 0x2013 <= ord(c) <= 0xFFFD]
+ )
+ return (
+ len(self[:position].quoted_text())
+ + self[:position].line_buffer.count("\t") * 7
+ + extra_char_width
+ )
+
+ def quoted_text(self):
+ quoted = [quote_char(c) for c in self.line_buffer]
+ return "".join(map(ensure_unicode, quoted))
+
+ def get_line_text(self):
+ buf = self.line_buffer
+ buf = list(map(ensure_unicode, buf))
+ return "".join(buf)
+
+ def set_line(self, text, cursor=None):
+ self.line_buffer = [c for c in str(text)]
+ if cursor is None:
+ self.point = len(self.line_buffer)
+ else:
+ self.point = cursor
+
+ def reset_line(self):
+ self.line_buffer = []
+ self.point = 0
+
+ def end_of_line(self):
+ self.point = len(self.line_buffer)
+
+ def _insert_text(self, text, argument=1):
+ text = text * argument
+ if self.overwrite:
+ for c in biter(text):
+ # if self.point:
+ self.line_buffer[self.point] = c
+ self.point += 1
+ else:
+ for c in biter(text):
+ self.line_buffer.insert(self.point, c)
+ self.point += 1
+
+ def __getitem__(self, key):
+ # Check if key is LineSlice, convert to regular slice
+ # and continue processing
+ if isinstance(key, LineSlice):
+ key = key(self)
+ if isinstance(key, slice):
+ if key.step is None:
+ pass
+ else:
+ raise RuntimeError('step is not "None"')
+ if key.start is None:
+ start = StartOfLine(self)
+ elif isinstance(key.start, LinePositioner):
+ start = key.start(self)
+ else:
+ start = key.start
+ if key.stop is None:
+ stop = EndOfLine(self)
+ elif isinstance(key.stop, LinePositioner):
+ stop = key.stop(self)
+ else:
+ stop = key.stop
+ return self.__class__(self.line_buffer[start:stop], point=0)
+ elif isinstance(key, LinePositioner):
+ return self.line_buffer[key(self)]
+ elif isinstance(key, tuple):
+ # Multiple slice not allowed
+ raise IndexError("Cannot use step in line buffer indexing")
+ else:
+ # return TextLine(self.line_buffer[key])
+ return self.line_buffer[key]
+
+ def __delitem__(self, key):
+ point = self.point
+ if isinstance(key, LineSlice):
+ key = key(self)
+ if isinstance(key, slice):
+ start = key.start
+ stop = key.stop
+ if isinstance(start, LinePositioner):
+ start = start(self)
+ elif start is None:
+ start = 0
+ if isinstance(stop, LinePositioner):
+ stop = stop(self)
+ elif stop is None:
+ stop = EndOfLine(self)
+ elif isinstance(key, LinePositioner):
+ start = key(self)
+ stop = start + 1
+ else:
+ start = key
+ stop = key + 1
+ prev = self.line_buffer[:start]
+ rest = self.line_buffer[stop:]
+ self.line_buffer = prev + rest
+ if point > stop:
+ self.point = point - (stop - start)
+ elif point >= start and point <= stop:
+ self.point = start
+
+ def __setitem__(self, key, value):
+ if isinstance(key, LineSlice):
+ key = key(self)
+ if isinstance(key, slice):
+ start = key.start
+ stop = key.stop
+ elif isinstance(key, LinePositioner):
+ start = key(self)
+ stop = start + 1
+ else:
+ start = key
+ stop = key + 1
+ prev = self.line_buffer[:start]
+ value = self.__class__(value).line_buffer
+ rest = self.line_buffer[stop:]
+ out = prev + value + rest
+ if len(out) >= len(self):
+ self.point = len(self)
+ self.line_buffer = out
+
+ def __len__(self):
+ return len(self.line_buffer)
+
+ def upper(self):
+ self.line_buffer = [x.upper() for x in self.line_buffer]
+ return self
+
+ def lower(self):
+ self.line_buffer = [x.lower() for x in self.line_buffer]
+ return self
+
+ def capitalize(self):
+ self.set_line(self.get_line_text().capitalize(), self.point)
+ return self
+
+ def startswith(self, txt):
+ return self.get_line_text().startswith(txt)
+
+ def endswith(self, txt):
+ return self.get_line_text().endswith(txt)
+
+ def __contains__(self, txt):
+ return txt in self.get_line_text()
+
+
+class ReadLineTextBuffer(TextLine):
+ def __init__(self, txtstr, point=None, mark=None):
+ super().__init__(txtstr, point, mark)
+
+ self.enable_win32_clipboard = True
+ self.selection_mark = -1
+ self.enable_selection = True
+ self.kill_ring = []
+
+ def __repr__(self):
+ return "ReadLineTextBuffer" '("%s",point=%s,mark=%s,selection_mark=%s)' % (
+ self.line_buffer,
+ self.point,
+ self.mark,
+ self.selection_mark,
+ )
+
+ def insert_text(self, char, argument=1):
+ self.delete_selection()
+ self.selection_mark = -1
+ self._insert_text(char, argument)
+
+ def to_clipboard(self):
+ if self.enable_win32_clipboard:
+ clipboard.set_clipboard_text(self.get_line_text())
+
+ # Movement
+
+ def beginning_of_line(self):
+ self.selection_mark = -1
+ self.point = StartOfLine
+
+ def end_of_line(self):
+ self.selection_mark = -1
+ self.point = EndOfLine
+
+ def forward_char(self, argument=1):
+ if argument < 0:
+ self.backward_char(-argument)
+ self.selection_mark = -1
+ for _ in range(argument):
+ self.point = NextChar
+
+ def backward_char(self, argument=1):
+ if argument < 0:
+ self.forward_char(-argument)
+ self.selection_mark = -1
+ for _ in range(argument):
+ self.point = PrevChar
+
+ def forward_word(self, argument=1):
+ if argument < 0:
+ self.backward_word(-argument)
+ self.selection_mark = -1
+ for _ in range(argument):
+ self.point = NextWordStart
+
+ def backward_word(self, argument=1):
+ if argument < 0:
+ self.forward_word(-argument)
+ self.selection_mark = -1
+ for _ in range(argument):
+ self.point = PrevWordStart
+
+ def forward_word_end(self, argument=1):
+ if argument < 0:
+ self.backward_word_end(-argument)
+ self.selection_mark = -1
+ for _ in range(argument):
+ self.point = NextWordEnd
+
+ def backward_word_end(self, argument=1):
+ if argument < 0:
+ self.forward_word_end(-argument)
+ self.selection_mark = -1
+ for _ in range(argument):
+ self.point = NextWordEnd
+
+ # Movement select
+ def beginning_of_line_extend_selection(self):
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ self.point = StartOfLine
+
+ def end_of_line_extend_selection(self):
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ self.point = EndOfLine
+
+ def forward_char_extend_selection(self, argument=1):
+ if argument < 0:
+ self.backward_char_extend_selection(-argument)
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ for _ in range(argument):
+ self.point = NextChar
+
+ def backward_char_extend_selection(self, argument=1):
+ if argument < 0:
+ self.forward_char_extend_selection(-argument)
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ for _ in range(argument):
+ self.point = PrevChar
+
+ def forward_word_extend_selection(self, argument=1):
+ if argument < 0:
+ self.backward_word_extend_selection(-argument)
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ for _ in range(argument):
+ self.point = NextWordStart
+
+ def backward_word_extend_selection(self, argument=1):
+ if argument < 0:
+ self.forward_word_extend_selection(-argument)
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ for _ in range(argument):
+ self.point = PrevWordStart
+
+ def forward_word_end_extend_selection(self, argument=1):
+ if argument < 0:
+ self.backward_word_end_extend_selection(-argument)
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ for _ in range(argument):
+ self.point = NextWordEnd
+
+ def backward_word_end_extend_selection(self, argument=1):
+ if argument < 0:
+ self.forward_word_end_extend_selection(-argument)
+ if self.enable_selection and self.selection_mark < 0:
+ self.selection_mark = self.point
+ for _ in range(argument):
+ self.point = PrevWordEnd
+
+ # delete
+
+ def delete_selection(self):
+ if self.enable_selection and self.selection_mark >= 0:
+ if self.selection_mark < self.point:
+ del self[self.selection_mark : self.point]
+ self.selection_mark = -1
+ else:
+ del self[self.point : self.selection_mark]
+ self.selection_mark = -1
+ return True
+ else:
+ self.selection_mark = -1
+ return False
+
+ def delete_char(self, argument=1):
+ if argument < 0:
+ self.backward_delete_char(-argument)
+ if self.delete_selection():
+ argument -= 1
+ for _ in range(argument):
+ del self[Point]
+
+ def backward_delete_char(self, argument=1):
+ if argument < 0:
+ self.delete_char(-argument)
+ if self.delete_selection():
+ argument -= 1
+ for _ in range(argument):
+ if self.point > 0:
+ self.backward_char()
+ self.delete_char()
+
+ def forward_delete_word(self, argument=1):
+ if argument < 0:
+ self.backward_delete_word(-argument)
+ if self.delete_selection():
+ argument -= 1
+ for _ in range(argument):
+ del self[Point:NextWordStart]
+
+ def backward_delete_word(self, argument=1):
+ if argument < 0:
+ self.forward_delete_word(-argument)
+ if self.delete_selection():
+ argument -= 1
+ for _ in range(argument):
+ del self[PrevWordStart:Point]
+
+ def delete_current_word(self):
+ if not self.delete_selection():
+ del self[CurrentWord]
+ self.selection_mark = -1
+
+ def delete_horizontal_space(self):
+ if self[Point] in " \t":
+ del self[PrevWordEnd:NextWordStart]
+ self.selection_mark = -1
+
+ # Case
+
+ def upcase_word(self):
+ p = self.point
+ try:
+ self[CurrentWord] = self[CurrentWord].upper()
+ self.point = p
+ except NotAWordError:
+ pass
+
+ def downcase_word(self):
+ p = self.point
+ try:
+ self[CurrentWord] = self[CurrentWord].lower()
+ self.point = p
+ except NotAWordError:
+ pass
+
+ def capitalize_word(self):
+ p = self.point
+ try:
+ self[CurrentWord] = self[CurrentWord].capitalize()
+ self.point = p
+ except NotAWordError:
+ pass
+
+ # Transpose
+
+ def transpose_chars(self):
+ p2 = Point(self)
+ if p2 == 0:
+ return
+ elif p2 == len(self):
+ p2 = p2 - 1
+ p1 = p2 - 1
+ self[p2], self[p1] = self[p1], self[p2]
+ self.point = p2 + 1
+
+ def transpose_words(self):
+ word1 = TextLine(self)
+ word2 = TextLine(self)
+ if self.point == len(self):
+ word2.point = PrevWordStart
+ word1.point = PrevWordStart(word2)
+ else:
+ word1.point = PrevWordStart
+ word2.point = NextWordStart
+ stop1 = NextWordEnd(word1)
+ stop2 = NextWordEnd(word2)
+ start1 = word1.point
+ start2 = word2.point
+ self[start2:stop2] = word1[Point:NextWordEnd]
+ self[start1:stop1] = word2[Point:NextWordEnd]
+ self.point = stop2
+
+ # Kill
+
+ def kill_line(self):
+ self.add_to_kill_ring(self[self.point :])
+ del self.line_buffer[self.point :]
+
+ def kill_whole_line(self):
+ self.add_to_kill_ring(self[:])
+ del self[:]
+
+ def backward_kill_line(self):
+ del self[StartOfLine:Point]
+
+ def unix_line_discard(self):
+ del self[StartOfLine:Point]
+
+ def kill_word(self):
+ """Kills to next word ending"""
+ del self[Point:NextWordEnd]
+
+ def backward_kill_word(self):
+ """Kills to next word ending"""
+ if not self.delete_selection():
+ del self[PrevWordStart:Point]
+ self.selection_mark = -1
+
+ def forward_kill_word(self):
+ """Kills to next word ending"""
+ if not self.delete_selection():
+ del self[Point:NextWordEnd]
+ self.selection_mark = -1
+
+ def unix_word_rubout(self):
+ if not self.delete_selection():
+ del self[PrevSpace:Point]
+ self.selection_mark = -1
+
+ def kill_region(self):
+ pass
+
+ def copy_region_as_kill(self):
+ pass
+
+ def copy_backward_word(self):
+ pass
+
+ def copy_forward_word(self):
+ pass
+
+ def yank(self):
+ self.paste_from_kill_ring()
+
+ def yank_pop(self):
+ pass
+
+ # Mark
+
+ def set_mark(self):
+ self.mark = self.point
+
+ def exchange_point_and_mark(self):
+ pass
+
+ def copy_region_to_clipboard(self): # ()
+ """Copy the text in the region to the windows clipboard."""
+ if self.enable_win32_clipboard:
+ mark = min(self.mark, len(self.line_buffer))
+ cursor = min(self.point, len(self.line_buffer))
+ if self.mark == -1:
+ return
+ begin = min(cursor, mark)
+ end = max(cursor, mark)
+ toclipboard = "".join(self.line_buffer[begin:end])
+ clipboard.set_clipboard_text(toclipboard)
+
+ def copy_selection_to_clipboard(self): # ()
+ """Copy the text in the region to the windows clipboard."""
+ if (
+ self.enable_win32_clipboard
+ and self.enable_selection
+ and self.selection_mark >= 0
+ ):
+ selection_mark = min(self.selection_mark, len(self.line_buffer))
+ cursor = min(self.point, len(self.line_buffer))
+ if self.selection_mark == -1:
+ return
+ begin = min(cursor, selection_mark)
+ end = max(cursor, selection_mark)
+ toclipboard = "".join(self.line_buffer[begin:end])
+ clipboard.set_clipboard_text(toclipboard)
+
+ def cut_selection_to_clipboard(self): # ()
+ self.copy_selection_to_clipboard()
+ self.delete_selection()
+
+ # Paste
+
+ # Kill ring
+
+ def add_to_kill_ring(self, txt):
+ self.kill_ring = [txt]
+ if kill_ring_to_clipboard:
+ clipboard.set_clipboard_text(txt.get_line_text())
+
+ def paste_from_kill_ring(self):
+ if self.kill_ring:
+ self.insert_text(self.kill_ring[0])
+
+
+##################################################################
+q = ReadLineTextBuffer("asff asFArw ewrWErhg", point=8)
+q = TextLine("asff asFArw ewrWErhg", point=8)
+
+
+def show_pos(buff, pos, chr="."):
+ l_n = len(buff.line_buffer)
+
+ def choice(is_bool):
+ if is_bool:
+ return chr
+ else:
+ return " "
+
+ return "".join([choice(pos == idx) for idx in range(l_n + 1)])
+
+
+def test_positioner(buff, points, positioner):
+ print((" %s " % positioner.__class__.__name__).center(40, "-"))
+ buffstr = buff.line_buffer
+
+ print('"%s"' % (buffstr))
+ for point in points:
+ b = TextLine(buff, point=point)
+ out = [" "] * (len(buffstr) + 1)
+ pos = positioner(b)
+ if pos == point:
+ out[pos] = "&"
+ else:
+ out[point] = "."
+ out[pos] = "^"
+ print('"%s"' % ("".join(out)))
+
+
+if __name__ == "__main__":
+
+ print('%-15s "%s"' % ("Position", q.get_line_text()))
+ print('%-15s "%s"' % ("Point", show_pos(q, q.point)))
+
+ for name, positioner_q in all_positioners:
+ pos_q = positioner_q(q)
+
+ print('%-15s "%s"' % (name, show_pos(q, pos_q, "^")))
+
+ l_t = ReadLineTextBuffer("kjjk asads asad")
+ l_t.point = EndOfLine
diff --git a/python_embeded/Lib/site-packages/pyreadline3/lineeditor/wordmatcher.py b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/wordmatcher.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2a514fdd10883659db316d911bc3cbebecff8c9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/lineeditor/wordmatcher.py
@@ -0,0 +1,124 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import re
+
+
+def str_find_all(in_str, ch):
+ result = []
+ index = 0
+ while index >= 0:
+ index = in_str.find(ch, index)
+ if index >= 0:
+ result.append(index)
+ index += 1
+ return result
+
+
+word_pattern = re.compile("(x*)")
+
+
+def markwords(in_str, is_wordfun):
+ markers = {True: "x", False: "o"}
+ return "".join([markers[is_wordfun(ch)] for ch in in_str])
+
+
+def split_words(in_str, is_wordfun):
+ return [x for x in word_pattern.split(markwords(in_str, is_wordfun)) if x != ""]
+
+
+def mark_start_segment(in_str, is_segment):
+ def mark_start(s):
+ if s[0:1] == "x":
+ return "s" + s[1:]
+ else:
+ return s
+
+ return "".join(map(mark_start, split_words(in_str, is_segment)))
+
+
+def mark_end_segment(in_str, is_segment):
+ def mark_start(s):
+ if s[0:1] == "x":
+ return s[:-1] + "s"
+ else:
+ return s
+
+ return "".join(map(mark_start, split_words(in_str, is_segment)))
+
+
+def mark_start_segment_index(in_str, is_segment):
+ return str_find_all(mark_start_segment(in_str, is_segment), "s")
+
+
+def mark_end_segment_index(in_str, is_segment):
+ return [x + 1 for x in str_find_all(mark_end_segment(in_str, is_segment), "s")]
+
+
+# ############### Following are used in lineobj ###########################
+
+
+def is_word_token(in_str):
+ return not is_non_word_token(in_str)
+
+
+def is_non_word_token(in_str):
+ if len(in_str) != 1 or in_str in " \t\n":
+ return True
+ else:
+ return False
+
+
+def next_start_segment(in_str, is_segment):
+ in_str = "".join(in_str)
+ result = []
+ for start in mark_start_segment_index(in_str, is_segment):
+ result[len(result) : start] = [start for x in range(start - len(result))]
+ result[len(result) : len(in_str)] = [
+ len(in_str) for x in range(len(in_str) - len(result) + 1)
+ ]
+ return result
+
+
+def next_end_segment(in_str, is_segment):
+ in_str = "".join(in_str)
+ result = []
+ for start in mark_end_segment_index(in_str, is_segment):
+ result[len(result) : start] = [start for x in range(start - len(result))]
+ result[len(result) : len(in_str)] = [
+ len(in_str) for x in range(len(in_str) - len(result) + 1)
+ ]
+ return result
+
+
+def prev_start_segment(in_str, is_segment):
+ in_str = "".join(in_str)
+ result = []
+ prev = 0
+ for start in mark_start_segment_index(in_str, is_segment):
+ result[len(result) : start + 1] = [prev for x in range(start - len(result) + 1)]
+ prev = start
+ result[len(result) : len(in_str)] = [
+ prev for x in range(len(in_str) - len(result) + 1)
+ ]
+ return result
+
+
+def prev_end_segment(in_str, is_segment):
+ in_str = "".join(in_str)
+ result = []
+ prev = 0
+ for start in mark_end_segment_index(in_str, is_segment):
+ result[len(result) : start + 1] = [prev for x in range(start - len(result) + 1)]
+ prev = start
+ result[len(result) : len(in_str)] = [
+ len(in_str) for x in range(len(in_str) - len(result) + 1)
+ ]
+ return result
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/__init__.py b/python_embeded/Lib/site-packages/pyreadline3/logger/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..65e943b847c436bfa076faad17098f2c8d3825ac
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/logger/__init__.py
@@ -0,0 +1,26 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from .control import (
+ start_file_log,
+ start_socket_log,
+ stop_file_log,
+ stop_logging,
+ stop_socket_log,
+)
+from .log import log
+
+__all__ = [
+ "start_file_log",
+ "start_socket_log",
+ "stop_file_log",
+ "stop_logging",
+ "stop_socket_log",
+ "log",
+]
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/control.py b/python_embeded/Lib/site-packages/pyreadline3/logger/control.py
new file mode 100644
index 0000000000000000000000000000000000000000..8de961b14382ae0165f17e40bef81fc2d9341b99
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/logger/control.py
@@ -0,0 +1,75 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+import os
+from logging import FileHandler, Formatter, StreamHandler
+from logging.handlers import DEFAULT_TCP_LOGGING_PORT
+from typing import Optional
+
+from .logger import LOGGER
+from .socket_stream import SocketStream
+
+_default_formatter_str = os.environ.get("PYREADLINE_FORMATTER", "%(message)s")
+
+SOCKET_HANDLER: Optional["StreamHandler[SocketStream]"] = None
+FILE_HANDLER: Optional[FileHandler] = None
+
+
+def start_socket_log(
+ host: str = "localhost",
+ port: int = DEFAULT_TCP_LOGGING_PORT,
+ formatter_str: str = _default_formatter_str,
+) -> None:
+ global SOCKET_HANDLER
+
+ if SOCKET_HANDLER is not None:
+ return
+
+ SOCKET_HANDLER = StreamHandler(SocketStream(host, port))
+ SOCKET_HANDLER.setFormatter(Formatter(formatter_str))
+
+ LOGGER.addHandler(SOCKET_HANDLER)
+
+
+def stop_socket_log() -> None:
+ global SOCKET_HANDLER
+
+ if SOCKET_HANDLER is None:
+ return
+
+ LOGGER.removeHandler(SOCKET_HANDLER)
+
+ SOCKET_HANDLER = None
+
+
+def start_file_log(filename: str) -> None:
+ global FILE_HANDLER
+
+ if FILE_HANDLER is not None:
+ return
+
+ FILE_HANDLER = FileHandler(filename, "w")
+ LOGGER.addHandler(FILE_HANDLER)
+
+
+def stop_file_log() -> None:
+ global FILE_HANDLER
+
+ if FILE_HANDLER is None:
+ return
+
+ LOGGER.removeHandler(FILE_HANDLER)
+
+ FILE_HANDLER.close()
+ FILE_HANDLER = None
+
+
+def stop_logging() -> None:
+ stop_file_log()
+ stop_socket_log()
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/log.py b/python_embeded/Lib/site-packages/pyreadline3/logger/log.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a29fb86dc9eeb23664b99fc7adf5dd2f9d06017
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/logger/log.py
@@ -0,0 +1,18 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from pyreadline3.unicode_helper import ensure_str
+
+from .logger import LOGGER
+
+
+def log(record: str) -> None:
+ s = ensure_str(record)
+
+ LOGGER.debug(s)
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/logger.py b/python_embeded/Lib/site-packages/pyreadline3/logger/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..7db31ac563f6f5fb221f097401550684845a008a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/logger/logger.py
@@ -0,0 +1,20 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+import logging
+import os
+
+from .null_handler import NULLHandler
+
+_default_log_level = os.environ.get("PYREADLINE_LOG", "DEBUG")
+
+LOGGER = logging.getLogger("PYREADLINE")
+LOGGER.setLevel(_default_log_level)
+LOGGER.propagate = False
+LOGGER.addHandler(NULLHandler())
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/null_handler.py b/python_embeded/Lib/site-packages/pyreadline3/logger/null_handler.py
new file mode 100644
index 0000000000000000000000000000000000000000..4211f881da25928bc29f5bd1877b6369871cf541
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/logger/null_handler.py
@@ -0,0 +1,16 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from logging import Handler, LogRecord
+
+
+class NULLHandler(Handler):
+
+ def emit(self, record: LogRecord) -> None:
+ pass
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/py.typed b/python_embeded/Lib/site-packages/pyreadline3/logger/py.typed
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pyreadline3/logger/socket_stream.py b/python_embeded/Lib/site-packages/pyreadline3/logger/socket_stream.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b7bd9e97121fbec524d3f983b58b5f9fc703a79
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/logger/socket_stream.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+from socket import AF_INET, SOCK_DGRAM, socket
+
+from pyreadline3.unicode_helper import ensure_str
+
+
+class SocketStream:
+ def __init__(
+ self,
+ host: str,
+ port: int,
+ ) -> None:
+ self.__host = host
+ self.__port = port
+ self.__socket = socket(AF_INET, SOCK_DGRAM)
+
+ def write(self, record: str) -> None:
+ self.__socket.sendto(
+ ensure_str(record),
+ (self.__host, self.__port),
+ )
+
+ def flush(self) -> None:
+ pass
+
+ def close(self) -> None:
+ pass
diff --git a/python_embeded/Lib/site-packages/pyreadline3/modes/__init__.py b/python_embeded/Lib/site-packages/pyreadline3/modes/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..792ac9e72b211f74cf321965f8bc79bac1d114ff
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/modes/__init__.py
@@ -0,0 +1,7 @@
+from . import emacs, notemacs, vi
+
+__all__ = ["emacs", "notemacs", "vi"]
+
+editingmodes = [emacs.EmacsMode, notemacs.NotEmacsMode, vi.ViMode]
+
+# add check to ensure all modes have unique mode names
diff --git a/python_embeded/Lib/site-packages/pyreadline3/modes/basemode.py b/python_embeded/Lib/site-packages/pyreadline3/modes/basemode.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5bb4ea0a6e2a9273fd98c43f64bf6d7a114f435
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/modes/basemode.py
@@ -0,0 +1,582 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import glob
+import math
+import os
+import re
+import sys
+
+import pyreadline3.clipboard as clipboard
+import pyreadline3.lineeditor.history as history
+import pyreadline3.lineeditor.lineobj as lineobj
+from pyreadline3.error import ReadlineError
+from pyreadline3.keysyms.common import make_KeyPress_from_keydescr
+from pyreadline3.logger import log
+from pyreadline3.py3k_compat import is_callable, is_ironpython
+from pyreadline3.unicode_helper import ensure_str, ensure_unicode
+
+
+class BaseMode(object):
+ mode = "base"
+
+ def __init__(self, rlobj):
+ self.argument = 0
+ self.rlobj = rlobj
+ self.exit_dispatch = {}
+ self.key_dispatch = {}
+ self.argument = 1
+ self.prevargument = None
+ self.l_buffer = lineobj.ReadLineTextBuffer("")
+ self._history = history.LineHistory()
+ self.completer_delims = " \t\n\"\\'`@$><=;|&{("
+ self.show_all_if_ambiguous = "on"
+ self.mark_directories = "on"
+ self.complete_filesystem = "off"
+ self.completer = None
+ self.begidx = 0
+ self.endidx = 0
+ self.tabstop = 4
+ self.startup_hook = None
+ self.pre_input_hook = None
+ self.first_prompt = True
+ self.cursor_size = 25
+
+ self.prompt = ">>> "
+
+ # Paste settings
+ # assumes data on clipboard is path if shorter than 300 characters and doesn't contain \t or \n
+ # and replace \ with / for easier use in ipython
+ self.enable_ipython_paste_for_paths = True
+
+ # automatically convert tabseparated data to list of lists or array
+ # constructors
+ self.enable_ipython_paste_list_of_lists = True
+ self.enable_win32_clipboard = True
+
+ self.paste_line_buffer = []
+
+ self._sub_modes = []
+
+ def __repr__(self):
+ return ""
+
+ def _gs(x):
+ def g(self):
+ return getattr(self.rlobj, x)
+
+ def s(self, q):
+ setattr(self.rlobj, x, q)
+
+ return g, s
+
+ def _g(x):
+ def g(self):
+ return getattr(self.rlobj, x)
+
+ return g
+
+ def _argreset(self):
+ val = self.argument
+ self.argument = 0
+ if val == 0:
+ val = 1
+ return val
+
+ argument_reset = property(_argreset)
+
+ # used in readline
+ ctrl_c_tap_time_interval = property(*_gs("ctrl_c_tap_time_interval"))
+ allow_ctrl_c = property(*_gs("allow_ctrl_c"))
+ _print_prompt = property(_g("_print_prompt"))
+ _update_line = property(_g("_update_line"))
+ console = property(_g("console"))
+ prompt_begin_pos = property(_g("prompt_begin_pos"))
+ prompt_end_pos = property(_g("prompt_end_pos"))
+
+ # used in completer _completions
+ # completer_delims=property(*_gs("completer_delims"))
+ _bell = property(_g("_bell"))
+ bell_style = property(_g("bell_style"))
+
+ # used in emacs
+ _clear_after = property(_g("_clear_after"))
+ _update_prompt_pos = property(_g("_update_prompt_pos"))
+
+ # not used in basemode or emacs
+
+ def process_keyevent(self, keyinfo):
+ raise NotImplementedError
+
+ def readline_setup(self, prompt=""):
+ self.l_buffer.selection_mark = -1
+ if self.first_prompt:
+ self.first_prompt = False
+ if self.startup_hook:
+ try:
+ self.startup_hook()
+ except BaseException:
+ print("startup hook failed")
+ traceback.print_exc()
+
+ self.l_buffer.reset_line()
+ self.prompt = prompt
+
+ if self.pre_input_hook:
+ try:
+ self.pre_input_hook()
+ except BaseException:
+ print("pre_input_hook failed")
+ traceback.print_exc()
+ self.pre_input_hook = None
+
+ # ###################################
+
+ def finalize(self):
+ """Every bindable command should call this function for cleanup.
+ Except those that want to set argument to a non-zero value.
+ """
+ self.argument = 0
+
+ def add_history(self, text):
+ self._history.add_history(lineobj.ReadLineTextBuffer(text))
+
+ # Create key bindings:
+
+ def rl_settings_to_string(self):
+ out = ["%-20s: %s" % ("show all if ambigous", self.show_all_if_ambiguous)]
+ out.append("%-20s: %s" % ("mark_directories", self.mark_directories))
+ out.append("%-20s: %s" % ("bell_style", self.bell_style))
+ out.append("------------- key bindings ------------")
+ tablepat = "%-7s %-7s %-7s %-15s %-15s "
+ out.append(tablepat % ("Control", "Meta", "Shift", "Keycode/char", "Function"))
+ bindings = sorted(
+ [(k[0], k[1], k[2], k[3], v.__name__) for k, v in self.key_dispatch.items()]
+ )
+ for key in bindings:
+ out.append(tablepat % (key))
+ return out
+
+ def _bind_key(self, key, func):
+ """setup the mapping from key to call the function."""
+ if not is_callable(func):
+ print("Trying to bind non method to keystroke:%s,%s" % (key, func))
+ raise ReadlineError(
+ "Trying to bind non method to keystroke:%s,%s,%s,%s"
+ % (key, func, type(func), type(self._bind_key))
+ )
+ keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple()
+ log(">>>%s -> %s<<<" % (keyinfo, func.__name__))
+ self.key_dispatch[keyinfo] = func
+
+ def _bind_exit_key(self, key):
+ """setup the mapping from key to call the function."""
+ keyinfo = make_KeyPress_from_keydescr(key.lower()).tuple()
+ self.exit_dispatch[keyinfo] = None
+
+ def init_editing_mode(self, e): # (C-e)
+ """When in vi command mode, this causes a switch to emacs editing
+ mode."""
+
+ raise NotImplementedError
+
+ # completion commands
+
+ def _get_completions(self):
+ """Return a list of possible completions for the string ending at the point.
+ Also set begidx and endidx in the process."""
+ completions = []
+ self.begidx = self.l_buffer.point
+ self.endidx = self.l_buffer.point
+ buf = self.l_buffer.line_buffer
+ if self.completer:
+ # get the string to complete
+ while self.begidx > 0:
+ self.begidx -= 1
+ if buf[self.begidx] in self.completer_delims:
+ self.begidx += 1
+ break
+ text = ensure_str("".join(buf[self.begidx : self.endidx]))
+ log('complete text="%s"' % ensure_unicode(text))
+ i = 0
+ while True:
+ try:
+ r = self.completer(ensure_unicode(text), i)
+ except IndexError:
+ break
+ i += 1
+ if r is None:
+ break
+ elif r and r not in completions:
+ completions.append(r)
+ else:
+ pass
+ log("text completions=<%s>" % list(map(ensure_unicode, completions)))
+ if (self.complete_filesystem == "on") and not completions:
+ # get the filename to complete
+ while self.begidx > 0:
+ self.begidx -= 1
+ if buf[self.begidx] in " \t\n":
+ self.begidx += 1
+ break
+ text = ensure_str("".join(buf[self.begidx : self.endidx]))
+ log('file complete text="%s"' % ensure_unicode(text))
+ completions = list(
+ map(
+ ensure_unicode,
+ glob.glob(os.path.expanduser(text) + "*".encode("ascii")),
+ )
+ )
+ if self.mark_directories == "on":
+ mc = []
+ for f in completions:
+ if os.path.isdir(f):
+ mc.append(f + os.sep)
+ else:
+ mc.append(f)
+ completions = mc
+ log("fnames=<%s>" % list(map(ensure_unicode, completions)))
+ return completions
+
+ def _display_completions(self, completions):
+ if not completions:
+ return
+ self.console.write("\n")
+ wmax = max(map(len, completions))
+ w, h = self.console.size()
+ cols = max(1, int((w - 1) / (wmax + 1)))
+ rows = int(math.ceil(float(len(completions)) / cols))
+ for row in range(rows):
+ s = ""
+ for col in range(cols):
+ i = col * rows + row
+ if i < len(completions):
+ self.console.write(completions[i].ljust(wmax + 1))
+ self.console.write("\n")
+ if is_ironpython:
+ self.prompt = sys.ps1
+ self._print_prompt()
+
+ def complete(self, e): # (TAB)
+ """Attempt to perform completion on the text before point. The
+ actual completion performed is application-specific. The default is
+ filename completion."""
+ completions = self._get_completions()
+ if completions:
+ cprefix = commonprefix(completions)
+ if len(cprefix) > 0:
+ rep = [c for c in cprefix]
+ point = self.l_buffer.point
+ self.l_buffer[self.begidx : self.endidx] = rep
+ self.l_buffer.point = point + len(rep) - (self.endidx - self.begidx)
+ if len(completions) > 1:
+ if self.show_all_if_ambiguous == "on":
+ self._display_completions(completions)
+ else:
+ self._bell()
+ else:
+ self._bell()
+ self.finalize()
+
+ def possible_completions(self, e): # (M-?)
+ """List the possible completions of the text before point."""
+ completions = self._get_completions()
+ self._display_completions(completions)
+ self.finalize()
+
+ def insert_completions(self, e): # (M-*)
+ """Insert all completions of the text before point that would have
+ been generated by possible-completions."""
+ completions = self._get_completions()
+ b = self.begidx
+ e = self.endidx
+ for comp in completions:
+ rep = [c for c in comp]
+ rep.append(" ")
+ self.l_buffer[b:e] = rep
+ b += len(rep)
+ e = b
+ self.line_cursor = b
+ self.finalize()
+
+ def menu_complete(self, e): # ()
+ """Similar to complete, but replaces the word to be completed with a
+ single match from the list of possible completions. Repeated
+ execution of menu-complete steps through the list of possible
+ completions, inserting each match in turn. At the end of the list of
+ completions, the bell is rung (subject to the setting of bell-style)
+ and the original text is restored. An argument of n moves n
+ positions forward in the list of matches; a negative argument may be
+ used to move backward through the list. This command is intended to
+ be bound to TAB, but is unbound by default."""
+ self.finalize()
+
+ # Methods below here are bindable emacs functions
+
+ def insert_text(self, string):
+ """Insert text into the command line."""
+ self.l_buffer.insert_text(string, self.argument_reset)
+ self.finalize()
+
+ def beginning_of_line(self, e): # (C-a)
+ """Move to the start of the current line."""
+ self.l_buffer.beginning_of_line()
+ self.finalize()
+
+ def end_of_line(self, e): # (C-e)
+ """Move to the end of the line."""
+ self.l_buffer.end_of_line()
+ self.finalize()
+
+ def forward_char(self, e): # (C-f)
+ """Move forward a character."""
+ self.l_buffer.forward_char(self.argument_reset)
+ self.finalize()
+
+ def backward_char(self, e): # (C-b)
+ """Move back a character."""
+ self.l_buffer.backward_char(self.argument_reset)
+ self.finalize()
+
+ def forward_word(self, e): # (M-f)
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.forward_word(self.argument_reset)
+ self.finalize()
+
+ def backward_word(self, e): # (M-b)
+ """Move back to the start of the current or previous word. Words are
+ composed of letters and digits."""
+ self.l_buffer.backward_word(self.argument_reset)
+ self.finalize()
+
+ def forward_word_end(self, e): # ()
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.forward_word_end(self.argument_reset)
+ self.finalize()
+
+ def backward_word_end(self, e): # ()
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.backward_word_end(self.argument_reset)
+ self.finalize()
+
+ # Movement with extend selection
+ def beginning_of_line_extend_selection(self, e):
+ """Move to the start of the current line."""
+ self.l_buffer.beginning_of_line_extend_selection()
+ self.finalize()
+
+ def end_of_line_extend_selection(self, e):
+ """Move to the end of the line."""
+ self.l_buffer.end_of_line_extend_selection()
+ self.finalize()
+
+ def forward_char_extend_selection(self, e):
+ """Move forward a character."""
+ self.l_buffer.forward_char_extend_selection(self.argument_reset)
+ self.finalize()
+
+ def backward_char_extend_selection(self, e):
+ """Move back a character."""
+ self.l_buffer.backward_char_extend_selection(self.argument_reset)
+ self.finalize()
+
+ def forward_word_extend_selection(self, e):
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.forward_word_extend_selection(self.argument_reset)
+ self.finalize()
+
+ def backward_word_extend_selection(self, e):
+ """Move back to the start of the current or previous word. Words are
+ composed of letters and digits."""
+ self.l_buffer.backward_word_extend_selection(self.argument_reset)
+ self.finalize()
+
+ def forward_word_end_extend_selection(self, e):
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
+ self.finalize()
+
+ def backward_word_end_extend_selection(self, e):
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.forward_word_end_extend_selection(self.argument_reset)
+ self.finalize()
+
+ # Change case
+
+ def upcase_word(self, e): # (M-u)
+ """Uppercase the current (or following) word. With a negative
+ argument, uppercase the previous word, but do not move the cursor."""
+ self.l_buffer.upcase_word()
+ self.finalize()
+
+ def downcase_word(self, e): # (M-l)
+ """Lowercase the current (or following) word. With a negative
+ argument, lowercase the previous word, but do not move the cursor."""
+ self.l_buffer.downcase_word()
+ self.finalize()
+
+ def capitalize_word(self, e): # (M-c)
+ """Capitalize the current (or following) word. With a negative
+ argument, capitalize the previous word, but do not move the cursor."""
+ self.l_buffer.capitalize_word()
+ self.finalize()
+
+ # #######
+
+ def clear_screen(self, e): # (C-l)
+ """Clear the screen and redraw the current line, leaving the current
+ line at the top of the screen."""
+ self.console.page()
+ self.finalize()
+
+ def redraw_current_line(self, e): # ()
+ """Refresh the current line. By default, this is unbound."""
+ self.finalize()
+
+ def accept_line(self, e): # (Newline or Return)
+ """Accept the line regardless of where the cursor is. If this line
+ is non-empty, it may be added to the history list for future recall
+ with add_history(). If this line is a modified history line, the
+ history line is restored to its original state."""
+ self.finalize()
+ return True
+
+ def delete_char(self, e): # (C-d)
+ """Delete the character at point. If point is at the beginning of
+ the line, there are no characters in the line, and the last
+ character typed was not bound to delete-char, then return EOF."""
+ self.l_buffer.delete_char(self.argument_reset)
+ self.finalize()
+
+ def backward_delete_char(self, e): # (Rubout)
+ """Delete the character behind the cursor. A numeric argument means
+ to kill the characters instead of deleting them."""
+ self.l_buffer.backward_delete_char(self.argument_reset)
+ self.finalize()
+
+ def backward_delete_word(self, e): # (Control-Rubout)
+ """Delete the character behind the cursor. A numeric argument means
+ to kill the characters instead of deleting them."""
+ self.l_buffer.backward_delete_word(self.argument_reset)
+ self.finalize()
+
+ def forward_delete_word(self, e): # (Control-Delete)
+ """Delete the character behind the cursor. A numeric argument means
+ to kill the characters instead of deleting them."""
+ self.l_buffer.forward_delete_word(self.argument_reset)
+ self.finalize()
+
+ def delete_horizontal_space(self, e): # ()
+ """Delete all spaces and tabs around point. By default, this is unbound."""
+ self.l_buffer.delete_horizontal_space()
+ self.finalize()
+
+ def self_insert(self, e): # (a, b, A, 1, !, ...)
+ """Insert yourself."""
+ if (
+ e.char and ord(e.char) != 0
+ ): # don't insert null character in buffer, can happen with dead keys.
+ self.insert_text(e.char)
+ self.finalize()
+
+ # Paste from clipboard
+
+ def paste(self, e):
+ """Paste windows clipboard.
+ Assume single line strip other lines and end of line markers and trailing spaces
+ """ # (Control-v)
+ if self.enable_win32_clipboard:
+ txt = clipboard.get_clipboard_text_and_convert(False)
+ txt = txt.split("\n")[0].strip("\r").strip("\n")
+ log("paste: >%s<" % list(map(ord, txt)))
+ self.insert_text(txt)
+ self.finalize()
+
+ def paste_mulitline_code(self, e):
+ """Paste windows clipboard as multiline code.
+ Removes any empty lines in the code"""
+ reg = re.compile("\r?\n")
+ if self.enable_win32_clipboard:
+ txt = clipboard.get_clipboard_text_and_convert(False)
+ t = reg.split(txt)
+ t = [row for row in t if row.strip() != ""] # remove empty lines
+ if t != [""]:
+ self.insert_text(t[0])
+ self.add_history(self.l_buffer.copy())
+ self.paste_line_buffer = t[1:]
+ log("multi: >%s<" % self.paste_line_buffer)
+ return True
+ else:
+ return False
+ self.finalize()
+
+ def ipython_paste(self, e):
+ """Paste windows clipboard. If enable_ipython_paste_list_of_lists is
+ True then try to convert tabseparated data to repr of list of lists or
+ repr of array.
+ If enable_ipython_paste_for_paths==True then change \\ to / and spaces
+ to \\space"""
+ if self.enable_win32_clipboard:
+ txt = clipboard.get_clipboard_text_and_convert(
+ self.enable_ipython_paste_list_of_lists
+ )
+ if self.enable_ipython_paste_for_paths:
+ if len(txt) < 300 and ("\t" not in txt) and ("\n" not in txt):
+ txt = txt.replace("\\", "/").replace(" ", r"\ ")
+ self.insert_text(txt)
+ self.finalize()
+
+ def copy_region_to_clipboard(self, e): # ()
+ """Copy the text in the region to the windows clipboard."""
+ self.l_buffer.copy_region_to_clipboard()
+ self.finalize()
+
+ def copy_selection_to_clipboard(self, e): # ()
+ """Copy the text in the region to the windows clipboard."""
+ self.l_buffer.copy_selection_to_clipboard()
+ self.finalize()
+
+ def cut_selection_to_clipboard(self, e): # ()
+ """Copy the text in the region to the windows clipboard."""
+ self.l_buffer.cut_selection_to_clipboard()
+ self.finalize()
+
+ def dump_functions(self, e): # ()
+ """Print all of the functions and their key bindings to the Readline
+ output stream. If a numeric argument is supplied, the output is
+ formatted in such a way that it can be made part of an inputrc
+ file. This command is unbound by default."""
+ print()
+ txt = "\n".join(self.rl_settings_to_string())
+ print(txt)
+ self._print_prompt()
+ self.finalize()
+
+
+def commonprefix(m):
+ "Given a list of pathnames, returns the longest common leading component"
+ if not m:
+ return ""
+ prefix = m[0]
+ for item in m:
+ for i in range(len(prefix)):
+ if prefix[: i + 1].lower() != item[: i + 1].lower():
+ prefix = prefix[:i]
+ if i == 0:
+ return ""
+ break
+ return prefix
diff --git a/python_embeded/Lib/site-packages/pyreadline3/modes/emacs.py b/python_embeded/Lib/site-packages/pyreadline3/modes/emacs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9036f5714b238352f819d501dc5595855226f28
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/modes/emacs.py
@@ -0,0 +1,716 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import pyreadline3.lineeditor.lineobj as lineobj
+from pyreadline3.lineeditor.lineobj import Point
+from pyreadline3.logger import log
+
+from . import basemode
+
+
+class IncrementalSearchPromptMode(object):
+ def __init__(self, rlobj):
+ pass
+
+ def _process_incremental_search_keyevent(self, keyinfo):
+ log("_process_incremental_search_keyevent")
+ keytuple = keyinfo.tuple()
+ # dispatch_func = self.key_dispatch.get(keytuple, default)
+ revtuples = []
+ fwdtuples = []
+ for ktuple, func in self.key_dispatch.items():
+ if func == self.reverse_search_history:
+ revtuples.append(ktuple)
+ elif func == self.forward_search_history:
+ fwdtuples.append(ktuple)
+
+ log("IncrementalSearchPromptMode %s %s" % (keyinfo, keytuple))
+ if keyinfo.keyname == "backspace":
+ self.subsearch_query = self.subsearch_query[:-1]
+ if len(self.subsearch_query) > 0:
+ self.line = self.subsearch_fun(self.subsearch_query)
+ else:
+ self._bell()
+ self.line = "" # empty query means no search result
+ elif keyinfo.keyname in ["return", "escape"]:
+ self._bell()
+ self.prompt = self.subsearch_oldprompt
+ self.process_keyevent_queue = self.process_keyevent_queue[:-1]
+ self._history.history_cursor = len(self._history.history)
+ if keyinfo.keyname == "escape":
+ self.l_buffer.set_line(self.subsearch_old_line)
+ return True
+ elif keyinfo.keyname:
+ pass
+ elif keytuple in revtuples:
+ self.subsearch_fun = self._history.reverse_search_history
+ self.subsearch_prompt = "reverse-i-search%d`%s': "
+ self.line = self.subsearch_fun(self.subsearch_query)
+ elif keytuple in fwdtuples:
+ self.subsearch_fun = self._history.forward_search_history
+ self.subsearch_prompt = "forward-i-search%d`%s': "
+ self.line = self.subsearch_fun(self.subsearch_query)
+ elif keyinfo.control == False and keyinfo.meta == False:
+ self.subsearch_query += keyinfo.char
+ self.line = self.subsearch_fun(self.subsearch_query)
+ else:
+ pass
+ self.prompt = self.subsearch_prompt % (
+ self._history.history_cursor,
+ self.subsearch_query,
+ )
+ self.l_buffer.set_line(self.line)
+
+ def _init_incremental_search(self, searchfun, init_event):
+ """Initialize search prompt"""
+ log("init_incremental_search")
+ self.subsearch_query = ""
+ self.subsearch_fun = searchfun
+ self.subsearch_old_line = self.l_buffer.get_line_text()
+
+ queue = self.process_keyevent_queue
+ queue.append(self._process_incremental_search_keyevent)
+
+ self.subsearch_oldprompt = self.prompt
+
+ if (
+ self.previous_func != self.reverse_search_history
+ and self.previous_func != self.forward_search_history
+ ):
+ self.subsearch_query = self.l_buffer[0:Point].get_line_text()
+
+ if self.subsearch_fun == self.reverse_search_history:
+ self.subsearch_prompt = "reverse-i-search%d`%s': "
+ else:
+ self.subsearch_prompt = "forward-i-search%d`%s': "
+
+ self.prompt = self.subsearch_prompt % (self._history.history_cursor, "")
+
+ if self.subsearch_query:
+ self.line = self._process_incremental_search_keyevent(init_event)
+ else:
+ self.line = ""
+
+
+class SearchPromptMode(object):
+ def __init__(self, rlobj):
+ pass
+
+ def _process_non_incremental_search_keyevent(self, keyinfo):
+ keytuple = keyinfo.tuple()
+ log("SearchPromptMode %s %s" % (keyinfo, keytuple))
+ history = self._history
+
+ if keyinfo.keyname == "backspace":
+ self.non_inc_query = self.non_inc_query[:-1]
+ elif keyinfo.keyname in ["return", "escape"]:
+ if self.non_inc_query:
+ if self.non_inc_direction == -1:
+ res = history.reverse_search_history(self.non_inc_query)
+ else:
+ res = history.forward_search_history(self.non_inc_query)
+
+ self._bell()
+ self.prompt = self.non_inc_oldprompt
+ self.process_keyevent_queue = self.process_keyevent_queue[:-1]
+ self._history.history_cursor = len(self._history.history)
+ if keyinfo.keyname == "escape":
+ self.l_buffer = self.non_inc_oldline
+ else:
+ self.l_buffer.set_line(res)
+ return False
+ elif keyinfo.keyname:
+ pass
+ elif keyinfo.control == False and keyinfo.meta == False:
+ self.non_inc_query += keyinfo.char
+ else:
+ pass
+ self.prompt = self.non_inc_oldprompt + ":" + self.non_inc_query
+
+ def _init_non_i_search(self, direction):
+ self.non_inc_direction = direction
+ self.non_inc_query = ""
+ self.non_inc_oldprompt = self.prompt
+ self.non_inc_oldline = self.l_buffer.copy()
+ self.l_buffer.reset_line()
+ self.prompt = self.non_inc_oldprompt + ":"
+ queue = self.process_keyevent_queue
+ queue.append(self._process_non_incremental_search_keyevent)
+
+ def non_incremental_reverse_search_history(self, e): # (M-p)
+ """Search backward starting at the current line and moving up
+ through the history as necessary using a non-incremental search for
+ a string supplied by the user."""
+ return self._init_non_i_search(-1)
+
+ def non_incremental_forward_search_history(self, e): # (M-n)
+ """Search forward starting at the current line and moving down
+ through the the history as necessary using a non-incremental search
+ for a string supplied by the user."""
+ return self._init_non_i_search(1)
+
+
+class LeaveModeTryNext(Exception):
+ pass
+
+
+class DigitArgumentMode(object):
+ def __init__(self, rlobj):
+ pass
+
+ def _process_digit_argument_keyevent(self, keyinfo):
+ log("DigitArgumentMode.keyinfo %s" % keyinfo)
+ keytuple = keyinfo.tuple()
+ log("DigitArgumentMode.keytuple %s %s" % (keyinfo, keytuple))
+ if keyinfo.keyname in ["return"]:
+ self.prompt = self._digit_argument_oldprompt
+ self.process_keyevent_queue = self.process_keyevent_queue[:-1]
+ return True
+ elif keyinfo.keyname:
+ pass
+ elif (
+ keyinfo.char in "0123456789"
+ and keyinfo.control == False
+ and keyinfo.meta == False
+ ):
+ log("arg %s %s" % (self.argument, keyinfo.char))
+ self.argument = self.argument * 10 + int(keyinfo.char)
+ else:
+ self.prompt = self._digit_argument_oldprompt
+ raise LeaveModeTryNext
+ self.prompt = "(arg: %s) " % self.argument
+
+ def _init_digit_argument(self, keyinfo):
+ """Initialize search prompt"""
+ c = self.console
+ line = self.l_buffer.get_line_text()
+ self._digit_argument_oldprompt = self.prompt
+ queue = self.process_keyevent_queue
+ queue = self.process_keyevent_queue
+ queue.append(self._process_digit_argument_keyevent)
+
+ if keyinfo.char == "-":
+ self.argument = -1
+ elif keyinfo.char in "0123456789":
+ self.argument = int(keyinfo.char)
+ log("<%s> %s" % (self.argument, type(self.argument)))
+ self.prompt = "(arg: %s) " % self.argument
+ log("arg-init %s %s" % (self.argument, keyinfo.char))
+
+
+class EmacsMode(
+ DigitArgumentMode, IncrementalSearchPromptMode, SearchPromptMode, basemode.BaseMode
+):
+ mode = "emacs"
+
+ def __init__(self, rlobj):
+ basemode.BaseMode.__init__(self, rlobj)
+ IncrementalSearchPromptMode.__init__(self, rlobj)
+ SearchPromptMode.__init__(self, rlobj)
+ DigitArgumentMode.__init__(self, rlobj)
+ self._keylog = lambda x, y: None
+ self.previous_func = None
+ self.prompt = ">>> "
+ self._insert_verbatim = False
+ self.next_meta = False # True to force meta on next character
+
+ self.process_keyevent_queue = [self._process_keyevent]
+
+ def __repr__(self):
+ return ""
+
+ def add_key_logger(self, logfun):
+ """logfun should be function that takes disp_fun and line_""" """buffer object """
+ self._keylog = logfun
+
+ def process_keyevent(self, keyinfo):
+ try:
+ r = self.process_keyevent_queue[-1](keyinfo)
+ except LeaveModeTryNext:
+ self.process_keyevent_queue = self.process_keyevent_queue[:-1]
+ r = self.process_keyevent(keyinfo)
+ if r:
+ self.add_history(self.l_buffer.copy())
+ return True
+ return False
+
+ def _process_keyevent(self, keyinfo):
+ """return True when line is final"""
+ # Process exit keys. Only exit on empty line
+ log("_process_keyevent <%s>" % keyinfo)
+
+ def nop(e):
+ pass
+
+ if self.next_meta:
+ self.next_meta = False
+ keyinfo.meta = True
+ keytuple = keyinfo.tuple()
+
+ if self._insert_verbatim:
+ self.insert_text(keyinfo)
+ self._insert_verbatim = False
+ self.argument = 0
+ return False
+
+ if keytuple in self.exit_dispatch:
+ pars = (self.l_buffer, lineobj.EndOfLine(self.l_buffer))
+ log("exit_dispatch:<%s, %s>" % pars)
+ if lineobj.EndOfLine(self.l_buffer) == 0:
+ raise EOFError
+ if keyinfo.keyname or keyinfo.control or keyinfo.meta:
+ default = nop
+ else:
+ default = self.self_insert
+ dispatch_func = self.key_dispatch.get(keytuple, default)
+
+ log("readline from keyboard:<%s,%s>" % (keytuple, dispatch_func))
+
+ r = None
+ if dispatch_func:
+ r = dispatch_func(keyinfo)
+ self._keylog(dispatch_func, self.l_buffer)
+ self.l_buffer.push_undo()
+
+ self.previous_func = dispatch_func
+ return r
+
+ # History commands
+ def previous_history(self, e): # (C-p)
+ """Move back through the history list, fetching the previous
+ command."""
+ self._history.previous_history(self.l_buffer)
+ self.l_buffer.point = lineobj.EndOfLine
+ self.finalize()
+
+ def next_history(self, e): # (C-n)
+ """Move forward through the history list, fetching the next
+ command."""
+ self._history.next_history(self.l_buffer)
+ self.finalize()
+
+ def beginning_of_history(self, e): # (M-<)
+ """Move to the first line in the history."""
+ self._history.beginning_of_history()
+ self.finalize()
+
+ def end_of_history(self, e): # (M->)
+ """Move to the end of the input history, i.e., the line currently
+ being entered."""
+ self._history.end_of_history(self.l_buffer)
+ self.finalize()
+
+ def reverse_search_history(self, e): # (C-r)
+ """Search backward starting at the current line and moving up
+ through the history as necessary. This is an incremental search."""
+ log("rev_search_history")
+ self._init_incremental_search(self._history.reverse_search_history, e)
+ self.finalize()
+
+ def forward_search_history(self, e): # (C-s)
+ """Search forward starting at the current line and moving down
+ through the the history as necessary. This is an incremental
+ search."""
+ log("fwd_search_history")
+ self._init_incremental_search(self._history.forward_search_history, e)
+ self.finalize()
+
+ def history_search_forward(self, e): # ()
+ """Search forward through the history for the string of characters
+ between the start of the current line and the point. This is a
+ non-incremental search. By default, this command is unbound."""
+ if self.previous_func and hasattr(self._history, self.previous_func.__name__):
+ self._history.lastcommand = getattr(
+ self._history, self.previous_func.__name__
+ )
+ else:
+ self._history.lastcommand = None
+ q = self._history.history_search_forward(self.l_buffer)
+ self.l_buffer = q
+ self.l_buffer.point = q.point
+ self.finalize()
+
+ def history_search_backward(self, e): # ()
+ """Search backward through the history for the string of characters
+ between the start of the current line and the point. This is a
+ non-incremental search. By default, this command is unbound."""
+ if self.previous_func and hasattr(self._history, self.previous_func.__name__):
+ self._history.lastcommand = getattr(
+ self._history, self.previous_func.__name__
+ )
+ else:
+ self._history.lastcommand = None
+ q = self._history.history_search_backward(self.l_buffer)
+ self.l_buffer = q
+ self.l_buffer.point = q.point
+ self.finalize()
+
+ def yank_nth_arg(self, e): # (M-C-y)
+ """Insert the first argument to the previous command (usually the
+ second word on the previous line) at point. With an argument n,
+ insert the nth word from the previous command (the words in the
+ previous command begin with word 0). A negative argument inserts the
+ nth word from the end of the previous command."""
+ self.finalize()
+
+ def yank_last_arg(self, e): # (M-. or M-_)
+ """Insert last argument to the previous command (the last word of
+ the previous history entry). With an argument, behave exactly like
+ yank-nth-arg. Successive calls to yank-last-arg move back through
+ the history list, inserting the last argument of each line in turn."""
+ self.finalize()
+
+ def forward_backward_delete_char(self, e): # ()
+ """Delete the character under the cursor, unless the cursor is at
+ the end of the line, in which case the character behind the cursor
+ is deleted. By default, this is not bound to a key."""
+ self.finalize()
+
+ def quoted_insert(self, e): # (C-q or C-v)
+ """Add the next character typed to the line verbatim. This is how to
+ insert key sequences like C-q, for example."""
+ self._insert_verbatim = True
+ self.finalize()
+
+ def tab_insert(self, e): # (M-TAB)
+ """Insert a tab character."""
+ cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
+ ws = " " * (self.tabstop - (cursor % self.tabstop))
+ self.insert_text(ws)
+ self.finalize()
+
+ def transpose_chars(self, e): # (C-t)
+ """Drag the character before the cursor forward over the character
+ at the cursor, moving the cursor forward as well. If the insertion
+ point is at the end of the line, then this transposes the last two
+ characters of the line. Negative arguments have no effect."""
+ self.l_buffer.transpose_chars()
+ self.finalize()
+
+ def transpose_words(self, e): # (M-t)
+ """Drag the word before point past the word after point, moving
+ point past that word as well. If the insertion point is at the end
+ of the line, this transposes the last two words on the line."""
+ self.l_buffer.transpose_words()
+ self.finalize()
+
+ def overwrite_mode(self, e): # ()
+ """Toggle overwrite mode. With an explicit positive numeric
+ argument, switches to overwrite mode. With an explicit non-positive
+ numeric argument, switches to insert mode. This command affects only
+ emacs mode; vi mode does overwrite differently. Each call to
+ readline() starts in insert mode. In overwrite mode, characters
+ bound to self-insert replace the text at point rather than pushing
+ the text to the right. Characters bound to backward-delete-char
+ replace the character before point with a space."""
+ self.finalize()
+
+ def kill_line(self, e): # (C-k)
+ """Kill the text from point to the end of the line."""
+ self.l_buffer.kill_line()
+ self.finalize()
+
+ def backward_kill_line(self, e): # (C-x Rubout)
+ """Kill backward to the beginning of the line."""
+ self.l_buffer.backward_kill_line()
+ self.finalize()
+
+ def unix_line_discard(self, e): # (C-u)
+ """Kill backward from the cursor to the beginning of the current
+ line."""
+ # how is this different from backward_kill_line?
+ self.l_buffer.unix_line_discard()
+ self.finalize()
+
+ def kill_whole_line(self, e): # ()
+ """Kill all characters on the current line, no matter where point
+ is. By default, this is unbound."""
+ self.l_buffer.kill_whole_line()
+ self.finalize()
+
+ def kill_word(self, e): # (M-d)
+ """Kill from point to the end of the current word, or if between
+ words, to the end of the next word. Word boundaries are the same as
+ forward-word."""
+ self.l_buffer.kill_word()
+ self.finalize()
+
+ forward_kill_word = kill_word
+
+ def backward_kill_word(self, e): # (M-DEL)
+ """Kill the word behind point. Word boundaries are the same as
+ backward-word."""
+ self.l_buffer.backward_kill_word()
+ self.finalize()
+
+ def unix_word_rubout(self, e): # (C-w)
+ """Kill the word behind point, using white space as a word
+ boundary. The killed text is saved on the kill-ring."""
+ self.l_buffer.unix_word_rubout()
+ self.finalize()
+
+ def kill_region(self, e): # ()
+ """Kill the text in the current region. By default, this command is
+ unbound."""
+ self.finalize()
+
+ def copy_region_as_kill(self, e): # ()
+ """Copy the text in the region to the kill buffer, so it can be
+ yanked right away. By default, this command is unbound."""
+ self.finalize()
+
+ def copy_backward_word(self, e): # ()
+ """Copy the word before point to the kill buffer. The word
+ boundaries are the same as backward-word. By default, this command
+ is unbound."""
+ self.finalize()
+
+ def copy_forward_word(self, e): # ()
+ """Copy the word following point to the kill buffer. The word
+ boundaries are the same as forward-word. By default, this command is
+ unbound."""
+ self.finalize()
+
+ def yank(self, e): # (C-y)
+ """Yank the top of the kill ring into the buffer at point."""
+ self.l_buffer.yank()
+ self.finalize()
+
+ def yank_pop(self, e): # (M-y)
+ """Rotate the kill-ring, and yank the new top. You can only do this
+ if the prior command is yank or yank-pop."""
+ self.l_buffer.yank_pop()
+ self.finalize()
+
+ def delete_char_or_list(self, e): # ()
+ """Deletes the character under the cursor if not at the beginning or
+ end of the line (like delete-char). If at the end of the line,
+ behaves identically to possible-completions. This command is unbound
+ by default."""
+ self.finalize()
+
+ def start_kbd_macro(self, e): # (C-x ()
+ """Begin saving the characters typed into the current keyboard
+ macro."""
+ self.finalize()
+
+ def end_kbd_macro(self, e): # (C-x ))
+ """Stop saving the characters typed into the current keyboard macro
+ and save the definition."""
+ self.finalize()
+
+ def call_last_kbd_macro(self, e): # (C-x e)
+ """Re-execute the last keyboard macro defined, by making the
+ characters in the macro appear as if typed at the keyboard."""
+ self.finalize()
+
+ def re_read_init_file(self, e): # (C-x C-r)
+ """Read in the contents of the inputrc file, and incorporate any
+ bindings or variable assignments found there."""
+ self.finalize()
+
+ def abort(self, e): # (C-g)
+ """Abort the current editing command and ring the terminals bell
+ (subject to the setting of bell-style)."""
+ self._bell()
+ self.finalize()
+
+ def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...)
+ """If the metafied character x is lowercase, run the command that is
+ bound to the corresponding uppercase character."""
+ self.finalize()
+
+ def prefix_meta(self, e): # (ESC)
+ """Metafy the next character typed. This is for keyboards without a
+ meta key. Typing ESC f is equivalent to typing M-f."""
+ self.next_meta = True
+ self.finalize()
+
+ def undo(self, e): # (C-_ or C-x C-u)
+ """Incremental undo, separately remembered for each line."""
+ self.l_buffer.pop_undo()
+ self.finalize()
+
+ def revert_line(self, e): # (M-r)
+ """Undo all changes made to this line. This is like executing the
+ undo command enough times to get back to the beginning."""
+ self.finalize()
+
+ def tilde_expand(self, e): # (M-~)
+ """Perform tilde expansion on the current word."""
+ self.finalize()
+
+ def set_mark(self, e): # (C-@)
+ """Set the mark to the point. If a numeric argument is supplied, the
+ mark is set to that position."""
+ self.l_buffer.set_mark()
+ self.finalize()
+
+ def exchange_point_and_mark(self, e): # (C-x C-x)
+ """Swap the point with the mark. The current cursor position is set
+ to the saved position, and the old cursor position is saved as the
+ mark."""
+ self.finalize()
+
+ def character_search(self, e): # (C-])
+ """A character is read and point is moved to the next occurrence of
+ that character. A negative count searches for previous occurrences."""
+ self.finalize()
+
+ def character_search_backward(self, e): # (M-C-])
+ """A character is read and point is moved to the previous occurrence
+ of that character. A negative count searches for subsequent
+ occurrences."""
+ self.finalize()
+
+ def insert_comment(self, e): # (M-#)
+ """Without a numeric argument, the value of the comment-begin
+ variable is inserted at the beginning of the current line. If a
+ numeric argument is supplied, this command acts as a toggle: if the
+ characters at the beginning of the line do not match the value of
+ comment-begin, the value is inserted, otherwise the characters in
+ comment-begin are deleted from the beginning of the line. In either
+ case, the line is accepted as if a newline had been typed."""
+ self.finalize()
+
+ def dump_variables(self, e): # ()
+ """Print all of the settable variables and their values to the
+ Readline output stream. If a numeric argument is supplied, the
+ output is formatted in such a way that it can be made part of an
+ inputrc file. This command is unbound by default."""
+ self.finalize()
+
+ def dump_macros(self, e): # ()
+ """Print all of the Readline key sequences bound to macros and the
+ strings they output. If a numeric argument is supplied, the output
+ is formatted in such a way that it can be made part of an inputrc
+ file. This command is unbound by default."""
+ self.finalize()
+
+ def digit_argument(self, e): # (M-0, M-1, ... M--)
+ """Add this digit to the argument already accumulating, or start a
+ new argument. M-- starts a negative argument."""
+ self._init_digit_argument(e)
+ # Should not finalize
+
+ def universal_argument(self, e): # ()
+ """This is another way to specify an argument. If this command is
+ followed by one or more digits, optionally with a leading minus
+ sign, those digits define the argument. If the command is followed
+ by digits, executing universal-argument again ends the numeric
+ argument, but is otherwise ignored. As a special case, if this
+ command is immediately followed by a character that is neither a
+ digit or minus sign, the argument count for the next command is
+ multiplied by four. The argument count is initially one, so
+ executing this function the first time makes the argument count
+ four, a second time makes the argument count sixteen, and so on. By
+ default, this is not bound to a key."""
+ # Should not finalize
+
+ # Create key bindings:
+ def init_editing_mode(self, e): # (C-e)
+ """When in vi command mode, this causes a switch to emacs editing
+ mode."""
+ self._bind_exit_key("Control-d")
+ self._bind_exit_key("Control-z")
+
+ # I often accidentally hold the shift or control while typing space
+ self._bind_key("space", self.self_insert)
+ self._bind_key("Shift-space", self.self_insert)
+ self._bind_key("Control-space", self.self_insert)
+ self._bind_key("Return", self.accept_line)
+ self._bind_key("Left", self.backward_char)
+ self._bind_key("Control-b", self.backward_char)
+ self._bind_key("Right", self.forward_char)
+ self._bind_key("Control-f", self.forward_char)
+ self._bind_key("Control-h", self.backward_delete_char)
+ self._bind_key("BackSpace", self.backward_delete_char)
+ self._bind_key("Control-BackSpace", self.backward_delete_word)
+
+ self._bind_key("Home", self.beginning_of_line)
+ self._bind_key("End", self.end_of_line)
+ self._bind_key("Delete", self.delete_char)
+ self._bind_key("Control-d", self.delete_char)
+ self._bind_key("Clear", self.clear_screen)
+ self._bind_key("Alt-f", self.forward_word)
+ self._bind_key("Alt-b", self.backward_word)
+ self._bind_key("Control-l", self.clear_screen)
+ self._bind_key("Control-p", self.previous_history)
+ self._bind_key("Up", self.history_search_backward)
+ self._bind_key("Control-n", self.next_history)
+ self._bind_key("Down", self.history_search_forward)
+ self._bind_key("Control-a", self.beginning_of_line)
+ self._bind_key("Control-e", self.end_of_line)
+ self._bind_key("Alt-<", self.beginning_of_history)
+ self._bind_key("Alt->", self.end_of_history)
+ self._bind_key("Control-r", self.reverse_search_history)
+ self._bind_key("Control-s", self.forward_search_history)
+ self._bind_key("Control-Shift-r", self.forward_search_history)
+ self._bind_key("Alt-p", self.non_incremental_reverse_search_history)
+ self._bind_key("Alt-n", self.non_incremental_forward_search_history)
+ self._bind_key("Control-z", self.undo)
+ self._bind_key("Control-_", self.undo)
+ self._bind_key("Escape", self.kill_whole_line)
+ self._bind_key("Meta-d", self.kill_word)
+ self._bind_key("Control-Delete", self.forward_delete_word)
+ self._bind_key("Control-w", self.unix_word_rubout)
+ # self._bind_key('Control-Shift-v', self.quoted_insert)
+ self._bind_key("Control-v", self.paste)
+ self._bind_key("Alt-v", self.ipython_paste)
+ self._bind_key("Control-y", self.yank)
+ self._bind_key("Control-k", self.kill_line)
+ self._bind_key("Control-m", self.set_mark)
+ self._bind_key("Control-q", self.copy_region_to_clipboard)
+ # self._bind_key('Control-shift-k', self.kill_whole_line)
+ self._bind_key("Control-Shift-v", self.paste_mulitline_code)
+ self._bind_key("Control-Right", self.forward_word_end)
+ self._bind_key("Control-Left", self.backward_word)
+ self._bind_key("Shift-Right", self.forward_char_extend_selection)
+ self._bind_key("Shift-Left", self.backward_char_extend_selection)
+ self._bind_key("Shift-Control-Right", self.forward_word_end_extend_selection)
+ self._bind_key("Shift-Control-Left", self.backward_word_extend_selection)
+ self._bind_key("Shift-Home", self.beginning_of_line_extend_selection)
+ self._bind_key("Shift-End", self.end_of_line_extend_selection)
+ self._bind_key("numpad0", self.self_insert)
+ self._bind_key("numpad1", self.self_insert)
+ self._bind_key("numpad2", self.self_insert)
+ self._bind_key("numpad3", self.self_insert)
+ self._bind_key("numpad4", self.self_insert)
+ self._bind_key("numpad5", self.self_insert)
+ self._bind_key("numpad6", self.self_insert)
+ self._bind_key("numpad7", self.self_insert)
+ self._bind_key("numpad8", self.self_insert)
+ self._bind_key("numpad9", self.self_insert)
+ self._bind_key("add", self.self_insert)
+ self._bind_key("subtract", self.self_insert)
+ self._bind_key("multiply", self.self_insert)
+ self._bind_key("divide", self.self_insert)
+ self._bind_key("vk_decimal", self.self_insert)
+ log("RUNNING INIT EMACS")
+ for i in range(0, 10):
+ self._bind_key("alt-%d" % i, self.digit_argument)
+ self._bind_key("alt--", self.digit_argument)
+
+
+# make it case insensitive
+def commonprefix(m):
+ "Given a list of pathnames, returns the longest common leading component"
+ if not m:
+ return ""
+ prefix = m[0]
+ for item in m:
+ for i in range(len(prefix)):
+ if prefix[: i + 1].lower() != item[: i + 1].lower():
+ prefix = prefix[:i]
+ if i == 0:
+ return ""
+ break
+ return prefix
diff --git a/python_embeded/Lib/site-packages/pyreadline3/modes/notemacs.py b/python_embeded/Lib/site-packages/pyreadline3/modes/notemacs.py
new file mode 100644
index 0000000000000000000000000000000000000000..df6a1108d39dc927a16b4564622286d938b57bc4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/modes/notemacs.py
@@ -0,0 +1,612 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import os
+
+import pyreadline3.lineeditor.history as history
+import pyreadline3.lineeditor.lineobj as lineobj
+import pyreadline3.logger as logger
+from pyreadline3.logger import log
+
+from . import basemode
+
+
+class NotEmacsMode(basemode.BaseMode):
+ mode = "notemacs"
+
+ def __init__(self, rlobj):
+ super().__init__(rlobj)
+
+ def __repr__(self):
+ return ""
+
+ def _readline_from_keyboard(self):
+ c = self.console
+ while True:
+ self._update_line()
+ event = c.getkeypress()
+ if self.next_meta:
+ self.next_meta = False
+ control, meta, shift, code = event.keyinfo
+ event.keyinfo = (control, True, shift, code)
+
+ # Process exit keys. Only exit on empty line
+ if event.keyinfo in self.exit_dispatch:
+ if lineobj.EndOfLine(self.l_buffer) == 0:
+ raise EOFError
+
+ dispatch_func = self.key_dispatch.get(event.keyinfo, self.self_insert)
+ log("readline from keyboard:%s" % (event.keyinfo,))
+ r = None
+ if dispatch_func:
+ r = dispatch_func(event)
+ self.l_buffer.push_undo()
+
+ self.previous_func = dispatch_func
+ if r:
+ self._update_line()
+ break
+
+ def readline(self, prompt=""):
+ """Try to act like GNU readline."""
+ # handle startup_hook
+ if self.first_prompt:
+ self.first_prompt = False
+ if self.startup_hook:
+ try:
+ self.startup_hook()
+ except BaseException:
+ print("startup hook failed")
+ traceback.print_exc()
+
+ c = self.console
+ self.l_buffer.reset_line()
+ self.prompt = prompt
+ self._print_prompt()
+
+ if self.pre_input_hook:
+ try:
+ self.pre_input_hook()
+ except BaseException:
+ print("pre_input_hook failed")
+ traceback.print_exc()
+ self.pre_input_hook = None
+
+ log("in readline: %s" % self.paste_line_buffer)
+ if len(self.paste_line_buffer) > 0:
+ self.l_buffer = lineobj.ReadlineTextBuffer(self.paste_line_buffer[0])
+ self._update_line()
+ self.paste_line_buffer = self.paste_line_buffer[1:]
+ c.write("\r\n")
+ else:
+ self._readline_from_keyboard()
+ c.write("\r\n")
+
+ self.add_history(self.l_buffer.copy())
+
+ log("returning(%s)" % self.l_buffer.get_line_text())
+ return self.l_buffer.get_line_text() + "\n"
+
+ # Methods below here are bindable emacs functions
+
+ def beginning_of_line(self, e): # (C-a)
+ """Move to the start of the current line."""
+ self.l_buffer.beginning_of_line()
+
+ def end_of_line(self, e): # (C-e)
+ """Move to the end of the line."""
+ self.l_buffer.end_of_line()
+
+ def forward_char(self, e): # (C-f)
+ """Move forward a character."""
+ self.l_buffer.forward_char()
+
+ def backward_char(self, e): # (C-b)
+ """Move back a character."""
+ self.l_buffer.backward_char()
+
+ def forward_word(self, e): # (M-f)
+ """Move forward to the end of the next word. Words are composed of
+ letters and digits."""
+ self.l_buffer.forward_word()
+
+ def backward_word(self, e): # (M-b)
+ """Move back to the start of the current or previous word. Words are
+ composed of letters and digits."""
+ self.l_buffer.backward_word()
+
+ def clear_screen(self, e): # (C-l)
+ """Clear the screen and redraw the current line, leaving the current
+ line at the top of the screen."""
+ self.console.page()
+
+ def redraw_current_line(self, e): # ()
+ """Refresh the current line. By default, this is unbound."""
+ pass
+
+ def accept_line(self, e): # (Newline or Return)
+ """Accept the line regardless of where the cursor is. If this line
+ is non-empty, it may be added to the history list for future recall
+ with add_history(). If this line is a modified history line, the
+ history line is restored to its original state."""
+ return True
+
+ # History commands
+ def previous_history(self, e): # (C-p)
+ """Move back through the history list, fetching the previous command."""
+ self._history.previous_history(self.l_buffer)
+
+ def next_history(self, e): # (C-n)
+ """Move forward through the history list, fetching the next command."""
+ self._history.next_history(self.l_buffer)
+
+ def beginning_of_history(self, e): # (M-<)
+ """Move to the first line in the history."""
+ self._history.beginning_of_history()
+
+ def end_of_history(self, e): # (M->)
+ """Move to the end of the input history, i.e., the line currently
+ being entered."""
+ self._history.end_of_history(self.l_buffer)
+
+ def _i_search(self, searchfun, direction, init_event):
+ c = self.console
+ line = self.get_line_buffer()
+ query = ""
+ hc_start = self._history.history_cursor # + direction
+ while True:
+ x, y = self.prompt_end_pos
+ c.pos(0, y)
+ if direction < 0:
+ prompt = "reverse-i-search"
+ else:
+ prompt = "forward-i-search"
+
+ scroll = c.write_scrolling("%s`%s': %s" % (prompt, query, line))
+ self._update_prompt_pos(scroll)
+ self._clear_after()
+
+ event = c.getkeypress()
+ if event.keysym == "BackSpace":
+ if len(query) > 0:
+ query = query[:-1]
+ self._history.history_cursor = hc_start
+ else:
+ self._bell()
+ elif (
+ event.char in string.letters + string.digits + string.punctuation + " "
+ ):
+ self._history.history_cursor = hc_start
+ query += event.char
+ elif event.keyinfo == init_event.keyinfo:
+ self._history.history_cursor += direction
+ line = searchfun(query)
+ pass
+ else:
+ if event.keysym != "Return":
+ self._bell()
+ break
+ line = searchfun(query)
+
+ px, py = self.prompt_begin_pos
+ c.pos(0, py)
+ self.l_buffer.set_line(line)
+ self._print_prompt()
+ self._history.history_cursor = len(self._history.history)
+
+ def reverse_search_history(self, e): # (C-r)
+ """Search backward starting at the current line and moving up
+ through the history as necessary. This is an incremental search."""
+ # print("HEJ")
+ # self.console.bell()
+ self._i_search(self._history.reverse_search_history, -1, e)
+
+ def forward_search_history(self, e): # (C-s)
+ """Search forward starting at the current line and moving down
+ through the the history as necessary. This is an incremental search."""
+ # print("HEJ")
+ # self.console.bell()
+ self._i_search(self._history.forward_search_history, 1, e)
+
+ def non_incremental_reverse_search_history(self, e): # (M-p)
+ """Search backward starting at the current line and moving up
+ through the history as necessary using a non-incremental search for
+ a string supplied by the user."""
+ self._history.non_incremental_reverse_search_history(self.l_buffer)
+
+ def non_incremental_forward_search_history(self, e): # (M-n)
+ """Search forward starting at the current line and moving down
+ through the the history as necessary using a non-incremental search
+ for a string supplied by the user."""
+ self._history.non_incremental_reverse_search_history(self.l_buffer)
+
+ def history_search_forward(self, e): # ()
+ """Search forward through the history for the string of characters
+ between the start of the current line and the point. This is a
+ non-incremental search. By default, this command is unbound."""
+ self.l_buffer = self._history.history_search_forward(self.l_buffer)
+
+ def history_search_backward(self, e): # ()
+ """Search backward through the history for the string of characters
+ between the start of the current line and the point. This is a
+ non-incremental search. By default, this command is unbound."""
+ self.l_buffer = self._history.history_search_backward(self.l_buffer)
+
+ def yank_nth_arg(self, e): # (M-C-y)
+ """Insert the first argument to the previous command (usually the
+ second word on the previous line) at point. With an argument n,
+ insert the nth word from the previous command (the words in the
+ previous command begin with word 0). A negative argument inserts the
+ nth word from the end of the previous command."""
+ pass
+
+ def yank_last_arg(self, e): # (M-. or M-_)
+ """Insert last argument to the previous command (the last word of
+ the previous history entry). With an argument, behave exactly like
+ yank-nth-arg. Successive calls to yank-last-arg move back through
+ the history list, inserting the last argument of each line in turn."""
+ pass
+
+ def delete_char(self, e): # (C-d)
+ """Delete the character at point. If point is at the beginning of
+ the line, there are no characters in the line, and the last
+ character typed was not bound to delete-char, then return EOF."""
+ self.l_buffer.delete_char()
+
+ def backward_delete_char(self, e): # (Rubout)
+ """Delete the character behind the cursor. A numeric argument means
+ to kill the characters instead of deleting them."""
+ self.l_buffer.backward_delete_char()
+
+ def forward_backward_delete_char(self, e): # ()
+ """Delete the character under the cursor, unless the cursor is at
+ the end of the line, in which case the character behind the cursor
+ is deleted. By default, this is not bound to a key."""
+ pass
+
+ def quoted_insert(self, e): # (C-q or C-v)
+ """Add the next character typed to the line verbatim. This is how to
+ insert key sequences like C-q, for example."""
+ e = self.console.getkeypress()
+ self.insert_text(e.char)
+
+ def tab_insert(self, e): # (M-TAB)
+ """Insert a tab character."""
+ cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
+ ws = " " * (self.tabstop - (cursor % self.tabstop))
+ self.insert_text(ws)
+
+ def self_insert(self, e): # (a, b, A, 1, !, ...)
+ """Insert yourself."""
+ if (
+ ord(e.char) != 0
+ ): # don't insert null character in buffer, can happen with dead keys.
+ self.insert_text(e.char)
+
+ def transpose_chars(self, e): # (C-t)
+ """Drag the character before the cursor forward over the character
+ at the cursor, moving the cursor forward as well. If the insertion
+ point is at the end of the line, then this transposes the last two
+ characters of the line. Negative arguments have no effect."""
+ self.l_buffer.transpose_chars()
+
+ def transpose_words(self, e): # (M-t)
+ """Drag the word before point past the word after point, moving
+ point past that word as well. If the insertion point is at the end
+ of the line, this transposes the last two words on the line."""
+ self.l_buffer.transpose_words()
+
+ def upcase_word(self, e): # (M-u)
+ """Uppercase the current (or following) word. With a negative
+ argument, uppercase the previous word, but do not move the cursor."""
+ self.l_buffer.upcase_word()
+
+ def downcase_word(self, e): # (M-l)
+ """Lowercase the current (or following) word. With a negative
+ argument, lowercase the previous word, but do not move the cursor."""
+ self.l_buffer.downcase_word()
+
+ def capitalize_word(self, e): # (M-c)
+ """Capitalize the current (or following) word. With a negative
+ argument, capitalize the previous word, but do not move the cursor."""
+ self.l_buffer.capitalize_word()
+
+ def overwrite_mode(self, e): # ()
+ """Toggle overwrite mode. With an explicit positive numeric
+ argument, switches to overwrite mode. With an explicit non-positive
+ numeric argument, switches to insert mode. This command affects only
+ emacs mode; vi mode does overwrite differently. Each call to
+ readline() starts in insert mode. In overwrite mode, characters
+ bound to self-insert replace the text at point rather than pushing
+ the text to the right. Characters bound to backward-delete-char
+ replace the character before point with a space."""
+ pass
+
+ def kill_line(self, e): # (C-k)
+ """Kill the text from point to the end of the line."""
+ self.l_buffer.kill_line()
+
+ def backward_kill_line(self, e): # (C-x Rubout)
+ """Kill backward to the beginning of the line."""
+ self.l_buffer.backward_kill_line()
+
+ def unix_line_discard(self, e): # (C-u)
+ """Kill backward from the cursor to the beginning of the current line."""
+ # how is this different from backward_kill_line?
+ self.l_buffer.unix_line_discard()
+
+ def kill_whole_line(self, e): # ()
+ """Kill all characters on the current line, no matter where point
+ is. By default, this is unbound."""
+ self.l_buffer.kill_whole_line()
+
+ def kill_word(self, e): # (M-d)
+ """Kill from point to the end of the current word, or if between
+ words, to the end of the next word. Word boundaries are the same as
+ forward-word."""
+ self.l_buffer.kill_word()
+
+ def backward_kill_word(self, e): # (M-DEL)
+ """Kill the word behind point. Word boundaries are the same as
+ backward-word."""
+ self.l_buffer.backward_kill_word()
+
+ def unix_word_rubout(self, e): # (C-w)
+ """Kill the word behind point, using white space as a word
+ boundary. The killed text is saved on the kill-ring."""
+ self.l_buffer.unix_word_rubout()
+
+ def delete_horizontal_space(self, e): # ()
+ """Delete all spaces and tabs around point. By default, this is unbound."""
+ pass
+
+ def kill_region(self, e): # ()
+ """Kill the text in the current region. By default, this command is unbound."""
+ pass
+
+ def copy_region_as_kill(self, e): # ()
+ """Copy the text in the region to the kill buffer, so it can be
+ yanked right away. By default, this command is unbound."""
+ pass
+
+ def copy_region_to_clipboard(self, e): # ()
+ """Copy the text in the region to the windows clipboard."""
+ if self.enable_win32_clipboard:
+ mark = min(self.l_buffer.mark, len(self.l_buffer.line_buffer))
+ cursor = min(self.l_buffer.point, len(self.l_buffer.line_buffer))
+ if self.l_buffer.mark == -1:
+ return
+ begin = min(cursor, mark)
+ end = max(cursor, mark)
+ toclipboard = "".join(self.l_buffer.line_buffer[begin:end])
+ clipboard.set_clipboard_text(str(toclipboard))
+
+ def copy_backward_word(self, e): # ()
+ """Copy the word before point to the kill buffer. The word
+ boundaries are the same as backward-word. By default, this command
+ is unbound."""
+ pass
+
+ def copy_forward_word(self, e): # ()
+ """Copy the word following point to the kill buffer. The word
+ boundaries are the same as forward-word. By default, this command is
+ unbound."""
+ pass
+
+ def paste(self, e):
+ """Paste windows clipboard"""
+ if self.enable_win32_clipboard:
+ txt = clipboard.get_clipboard_text_and_convert(False)
+ self.insert_text(txt)
+
+ def paste_mulitline_code(self, e):
+ """Paste windows clipboard"""
+ reg = re.compile("\r?\n")
+ if self.enable_win32_clipboard:
+ txt = clipboard.get_clipboard_text_and_convert(False)
+ t = reg.split(txt)
+ t = [row for row in t if row.strip() != ""] # remove empty lines
+ if t != [""]:
+ self.insert_text(t[0])
+ self.add_history(self.l_buffer.copy())
+ self.paste_line_buffer = t[1:]
+ log("multi: %s" % self.paste_line_buffer)
+ return True
+ else:
+ return False
+
+ def ipython_paste(self, e):
+ """Paste windows clipboard. If enable_ipython_paste_list_of_lists is
+ True then try to convert tabseparated data to repr of list of lists or
+ repr of array"""
+ if self.enable_win32_clipboard:
+ txt = clipboard.get_clipboard_text_and_convert(
+ self.enable_ipython_paste_list_of_lists
+ )
+ if self.enable_ipython_paste_for_paths:
+ if len(txt) < 300 and ("\t" not in txt) and ("\n" not in txt):
+ txt = txt.replace("\\", "/").replace(" ", r"\ ")
+ self.insert_text(txt)
+
+ def yank(self, e): # (C-y)
+ """Yank the top of the kill ring into the buffer at point."""
+ pass
+
+ def yank_pop(self, e): # (M-y)
+ """Rotate the kill-ring, and yank the new top. You can only do this
+ if the prior command is yank or yank-pop."""
+ pass
+
+ def digit_argument(self, e): # (M-0, M-1, ... M--)
+ """Add this digit to the argument already accumulating, or start a
+ new argument. M-- starts a negative argument."""
+ pass
+
+ def universal_argument(self, e): # ()
+ """This is another way to specify an argument. If this command is
+ followed by one or more digits, optionally with a leading minus
+ sign, those digits define the argument. If the command is followed
+ by digits, executing universal-argument again ends the numeric
+ argument, but is otherwise ignored. As a special case, if this
+ command is immediately followed by a character that is neither a
+ digit or minus sign, the argument count for the next command is
+ multiplied by four. The argument count is initially one, so
+ executing this function the first time makes the argument count
+ four, a second time makes the argument count sixteen, and so on. By
+ default, this is not bound to a key."""
+ pass
+
+ def delete_char_or_list(self, e): # ()
+ """Deletes the character under the cursor if not at the beginning or
+ end of the line (like delete-char). If at the end of the line,
+ behaves identically to possible-completions. This command is unbound
+ by default."""
+ pass
+
+ def start_kbd_macro(self, e): # (C-x ()
+ """Begin saving the characters typed into the current keyboard macro."""
+ pass
+
+ def end_kbd_macro(self, e): # (C-x ))
+ """Stop saving the characters typed into the current keyboard macro
+ and save the definition."""
+ pass
+
+ def call_last_kbd_macro(self, e): # (C-x e)
+ """Re-execute the last keyboard macro defined, by making the
+ characters in the macro appear as if typed at the keyboard."""
+ pass
+
+ def re_read_init_file(self, e): # (C-x C-r)
+ """Read in the contents of the inputrc file, and incorporate any
+ bindings or variable assignments found there."""
+ pass
+
+ def abort(self, e): # (C-g)
+ """Abort the current editing command and ring the terminals bell
+ (subject to the setting of bell-style)."""
+ self._bell()
+
+ def do_uppercase_version(self, e): # (M-a, M-b, M-x, ...)
+ """If the metafied character x is lowercase, run the command that is
+ bound to the corresponding uppercase character."""
+ pass
+
+ def prefix_meta(self, e): # (ESC)
+ """Metafy the next character typed. This is for keyboards without a
+ meta key. Typing ESC f is equivalent to typing M-f."""
+ self.next_meta = True
+
+ def undo(self, e): # (C-_ or C-x C-u)
+ """Incremental undo, separately remembered for each line."""
+ self.l_buffer.pop_undo()
+
+ def revert_line(self, e): # (M-r)
+ """Undo all changes made to this line. This is like executing the
+ undo command enough times to get back to the beginning."""
+ pass
+
+ def tilde_expand(self, e): # (M-~)
+ """Perform tilde expansion on the current word."""
+ pass
+
+ def set_mark(self, e): # (C-@)
+ """Set the mark to the point. If a numeric argument is supplied, the
+ mark is set to that position."""
+ self.l_buffer.set_mark()
+
+ def exchange_point_and_mark(self, e): # (C-x C-x)
+ """Swap the point with the mark. The current cursor position is set
+ to the saved position, and the old cursor position is saved as the
+ mark."""
+ pass
+
+ def character_search(self, e): # (C-])
+ """A character is read and point is moved to the next occurrence of
+ that character. A negative count searches for previous occurrences."""
+ pass
+
+ def character_search_backward(self, e): # (M-C-])
+ """A character is read and point is moved to the previous occurrence
+ of that character. A negative count searches for subsequent
+ occurrences."""
+ pass
+
+ def insert_comment(self, e): # (M-#)
+ """Without a numeric argument, the value of the comment-begin
+ variable is inserted at the beginning of the current line. If a
+ numeric argument is supplied, this command acts as a toggle: if the
+ characters at the beginning of the line do not match the value of
+ comment-begin, the value is inserted, otherwise the characters in
+ comment-begin are deleted from the beginning of the line. In either
+ case, the line is accepted as if a newline had been typed."""
+ pass
+
+ def dump_functions(self, e): # ()
+ """Print all of the functions and their key bindings to the Readline
+ output stream. If a numeric argument is supplied, the output is
+ formatted in such a way that it can be made part of an inputrc
+ file. This command is unbound by default."""
+ pass
+
+ def dump_variables(self, e): # ()
+ """Print all of the settable variables and their values to the
+ Readline output stream. If a numeric argument is supplied, the
+ output is formatted in such a way that it can be made part of an
+ inputrc file. This command is unbound by default."""
+ pass
+
+ def dump_macros(self, e): # ()
+ """Print all of the Readline key sequences bound to macros and the
+ strings they output. If a numeric argument is supplied, the output
+ is formatted in such a way that it can be made part of an inputrc
+ file. This command is unbound by default."""
+ pass
+
+ # Create key bindings:
+
+ def init_editing_mode(self, e): # (C-e)
+ """When in vi command mode, this causes a switch to emacs editing
+ mode."""
+
+ self._bind_exit_key("Control-d")
+ self._bind_exit_key("Control-z")
+
+ # I often accidentally hold the shift or control while typing space
+ self._bind_key("Shift-space", self.self_insert)
+ self._bind_key("Control-space", self.self_insert)
+ self._bind_key("Return", self.accept_line)
+ self._bind_key("Left", self.backward_char)
+ self._bind_key("Control-b", self.backward_char)
+ self._bind_key("Right", self.forward_char)
+ self._bind_key("Control-f", self.forward_char)
+ self._bind_key("BackSpace", self.backward_delete_char)
+ self._bind_key("Home", self.beginning_of_line)
+ self._bind_key("End", self.end_of_line)
+ self._bind_key("Delete", self.delete_char)
+ self._bind_key("Control-d", self.delete_char)
+ self._bind_key("Clear", self.clear_screen)
+
+
+# make it case insensitive
+def commonprefix(m):
+ "Given a list of pathnames, returns the longest common leading component"
+ if not m:
+ return ""
+ prefix = m[0]
+ for item in m:
+ for i in range(len(prefix)):
+ if prefix[: i + 1].lower() != item[: i + 1].lower():
+ prefix = prefix[:i]
+ if i == 0:
+ return ""
+ break
+ return prefix
diff --git a/python_embeded/Lib/site-packages/pyreadline3/modes/vi.py b/python_embeded/Lib/site-packages/pyreadline3/modes/vi.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea40af473ba33d1dd2174cfddf69797c1d6e35c2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyreadline3/modes/vi.py
@@ -0,0 +1,1279 @@
+# -*- coding: utf-8 -*-
+# *****************************************************************************
+# Copyright (C) 2003-2006 Gary Bishop.
+# Copyright (C) 2006-2020 Michael Graz.
+# Copyright (C) 2006-2020 Jorgen Stenarson.
+# Copyright (C) 2020 Bassem Girgis.
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+# *****************************************************************************
+
+
+import os
+
+import pyreadline3.lineeditor.lineobj as lineobj
+from pyreadline3.logger import log
+
+from . import basemode
+
+
+class ViMode(basemode.BaseMode):
+ mode = "vi"
+
+ def __init__(self, rlobj):
+ super().__init__(rlobj)
+
+ self.__vi_insert_mode = None
+
+ def __repr__(self):
+ return ""
+
+ def process_keyevent(self, keyinfo):
+ def nop(e):
+ pass
+
+ keytuple = keyinfo.tuple()
+
+ # Process exit keys. Only exit on empty line
+ if keytuple in self.exit_dispatch:
+ if lineobj.EndOfLine(self.l_buffer) == 0:
+ raise EOFError
+
+ dispatch_func = self.key_dispatch.get(keytuple, self.vi_key)
+ log("readline from keyboard:%s->%s" % (keytuple, dispatch_func))
+ r = None
+ if dispatch_func:
+ r = dispatch_func(keyinfo)
+ self.l_buffer.push_undo()
+
+ self.previous_func = dispatch_func
+ if r:
+ self._update_line()
+ return True
+ return False
+
+ # Methods below here are bindable emacs functions
+
+ def init_editing_mode(self, e): # (M-C-j)
+ """Initialize vi editingmode"""
+ self.show_all_if_ambiguous = "on"
+ self.key_dispatch = {}
+ self.__vi_insert_mode = None
+ self._vi_command = None
+ self._vi_command_edit = None
+ self._vi_key_find_char = None
+ self._vi_key_find_direction = True
+ self._vi_yank_buffer = None
+ self._vi_multiplier1 = ""
+ self._vi_multiplier2 = ""
+ self._vi_undo_stack = []
+ self._vi_undo_cursor = -1
+ self._vi_current = None
+ self._vi_search_text = ""
+ self._vi_search_position = 0
+ self.vi_save_line()
+ self.vi_set_insert_mode(True)
+ # make ' ' to ~ self insert
+ for c in range(ord(" "), 127):
+ self._bind_key("%s" % chr(c), self.vi_key)
+ self._bind_key("BackSpace", self.vi_backspace)
+ self._bind_key("Escape", self.vi_escape)
+ self._bind_key("Return", self.vi_accept_line)
+
+ self._bind_key("Left", self.backward_char)
+ self._bind_key("Right", self.forward_char)
+ self._bind_key("Home", self.beginning_of_line)
+ self._bind_key("End", self.end_of_line)
+ self._bind_key("Delete", self.delete_char)
+
+ self._bind_key("Control-d", self.vi_eof)
+ self._bind_key("Control-z", self.vi_eof)
+ self._bind_key("Control-r", self.vi_redo)
+ self._bind_key("Up", self.vi_arrow_up)
+ self._bind_key("Control-p", self.vi_up)
+ self._bind_key("Down", self.vi_arrow_down)
+ self._bind_key("Control-n", self.vi_down)
+ self._bind_key("Tab", self.vi_complete)
+
+ # self._bind_key('Control-e', self.emacs)
+
+ def vi_key(self, e):
+ if not self._vi_command:
+ self._vi_command = ViCommand(self)
+ elif self._vi_command.is_end:
+ if self._vi_command.is_edit:
+ self._vi_command_edit = self._vi_command
+ self._vi_command = ViCommand(self)
+ self._vi_command.add_char(e.char)
+
+ def vi_error(self):
+ self._bell()
+
+ def vi_get_is_insert_mode(self):
+ return self.__vi_insert_mode
+
+ vi_is_insert_mode = property(vi_get_is_insert_mode)
+
+ def vi_escape(self, e):
+ if self.vi_is_insert_mode:
+ if self._vi_command:
+ self._vi_command.add_char(e.char)
+ else:
+ self._vi_command = ViCommand(self)
+ self.vi_set_insert_mode(False)
+ self.l_buffer.point = lineobj.PrevChar
+ elif self._vi_command and self._vi_command.is_replace_one:
+ self._vi_command.add_char(e.char)
+ else:
+ self.vi_error()
+
+ def vi_backspace(self, e):
+ if self._vi_command:
+ self._vi_command.add_char(e.char)
+ else:
+ self._vi_do_backspace(self._vi_command)
+
+ def _vi_do_backspace(self, vi_cmd):
+ if self.vi_is_insert_mode or (self._vi_command and self._vi_command.is_search):
+ if self.l_buffer.point > 0:
+ self.l_buffer.point -= 1
+ if self.l_buffer.overwrite:
+ try:
+ prev = self._vi_undo_stack[self._vi_undo_cursor][1][
+ self.l_buffer.point
+ ]
+ self.l_buffer.line_buffer[self.l_buffer.point] = prev
+ except IndexError:
+ del self.l_buffer.line_buffer[self.l_buffer.point]
+ else:
+ self.vi_save_line()
+ del self.l_buffer.line_buffer[self.l_buffer.point]
+
+ def vi_accept_line(self, e):
+ if self._vi_command and self._vi_command.is_search:
+ self._vi_command.do_search()
+ return False
+ self._vi_command = None
+ self.vi_set_insert_mode(True)
+ self._vi_undo_stack = []
+ self._vi_undo_cursor = -1
+ self._vi_current = None
+ if self.l_buffer.line_buffer:
+ self.add_history(self.l_buffer.copy())
+ return self.accept_line(e)
+
+ def vi_eof(self, e):
+ raise EOFError
+
+ def vi_set_insert_mode(self, value):
+ if self.__vi_insert_mode == value:
+ return
+ self.__vi_insert_mode = value
+ if value:
+ self.vi_save_line()
+ self.cursor_size = 25
+ else:
+ self.cursor_size = 100
+
+ def vi_undo_restart(self):
+ tpl_undo = (
+ self.l_buffer.point,
+ self.l_buffer.line_buffer[:],
+ )
+ self._vi_undo_stack = [tpl_undo]
+ self._vi_undo_cursor = 0
+
+ def vi_save_line(self):
+ if self._vi_undo_stack and self._vi_undo_cursor >= 0:
+ del self._vi_undo_stack[self._vi_undo_cursor + 1 :]
+ # tpl_undo = (self.l_buffer.point, self.l_buffer[:], )
+ tpl_undo = (
+ self.l_buffer.point,
+ self.l_buffer.line_buffer[:],
+ )
+ if (
+ not self._vi_undo_stack
+ or self._vi_undo_stack[self._vi_undo_cursor][1] != tpl_undo[1]
+ ):
+ self._vi_undo_stack.append(tpl_undo)
+ self._vi_undo_cursor += 1
+
+ def vi_undo_prepare(self):
+ if self._vi_undo_cursor == len(self._vi_undo_stack) - 1:
+ self.vi_save_line()
+
+ def vi_undo(self, do_pop=True):
+ self.vi_undo_prepare()
+ if not self._vi_undo_stack or self._vi_undo_cursor <= 0:
+ self.vi_error()
+ return
+ self._vi_undo_cursor -= 1
+ self.vi_undo_assign()
+
+ def vi_undo_all(self):
+ self.vi_undo_prepare()
+ if self._vi_undo_cursor > 0:
+ self._vi_undo_cursor = 0
+ self.vi_undo_assign()
+ else:
+ self.vi_error()
+
+ def vi_undo_assign(self):
+ tpl_undo = self._vi_undo_stack[self._vi_undo_cursor]
+ self.l_buffer.line_buffer = tpl_undo[1][:]
+ self.l_buffer.point = tpl_undo[0]
+
+ def vi_redo(self, e):
+ if self._vi_undo_cursor >= len(self._vi_undo_stack) - 1:
+ self.vi_error()
+ return
+ self._vi_undo_cursor += 1
+ self.vi_undo_assign()
+
+ def vi_search(self, rng):
+ for i in rng:
+ line_history = self._history.history[i]
+ pos = line_history.get_line_text().find(self._vi_search_text)
+ if pos >= 0:
+ self._vi_search_position = i
+ self._history.history_cursor = i
+ self.l_buffer.line_buffer = list(line_history.line_buffer)
+ self.l_buffer.point = pos
+ self.vi_undo_restart()
+ return True
+ self._bell()
+ return False
+
+ def vi_search_first(self):
+ text = "".join(self.l_buffer.line_buffer[1:])
+ if text:
+ self._vi_search_text = text
+ self._vi_search_position = len(self._history.history) - 1
+ elif self._vi_search_text:
+ self._vi_search_position -= 1
+ else:
+ self.vi_error()
+ self.vi_undo()
+ return
+ if not self.vi_search(list(range(self._vi_search_position, -1, -1))):
+ # Here: search text not found
+ self.vi_undo()
+
+ def vi_search_again_backward(self):
+ self.vi_search(list(range(self._vi_search_position - 1, -1, -1)))
+
+ def vi_search_again_forward(self):
+ self.vi_search(
+ list(range(self._vi_search_position + 1, len(self._history.history)))
+ )
+
+ def vi_up(self, e):
+ if self._history.history_cursor == len(self._history.history):
+ self._vi_current = self.l_buffer.line_buffer[:]
+ # self._history.previous_history (e)
+ self._history.previous_history(self.l_buffer)
+ if self.vi_is_insert_mode:
+ self.end_of_line(e)
+ else:
+ self.beginning_of_line(e)
+ self.vi_undo_restart()
+
+ def vi_down(self, e):
+ if self._history.history_cursor >= len(self._history.history):
+ self.vi_error()
+ return
+ if self._history.history_cursor < len(self._history.history) - 1:
+ # self._history.next_history (e)
+ self._history.next_history(self.l_buffer)
+ if self.vi_is_insert_mode:
+ self.end_of_line(e)
+ else:
+ self.beginning_of_line(e)
+ self.vi_undo_restart()
+ elif self._vi_current is not None:
+ self._history.history_cursor = len(self._history.history)
+ self.l_buffer.line_buffer = self._vi_current
+ self.end_of_line(e)
+ if not self.vi_is_insert_mode and self.l_buffer.point > 0:
+ self.l_buffer.point -= 1
+ self._vi_current = None
+ else:
+ self.vi_error()
+ return
+
+ def vi_arrow_up(self, e):
+ self.vi_set_insert_mode(True)
+ self.vi_up(e)
+ self.vi_save_line()
+
+ def vi_arrow_down(self, e):
+ self.vi_set_insert_mode(True)
+ self.vi_down(e)
+ self.vi_save_line()
+
+ def vi_complete(self, e):
+ text = self.l_buffer.get_line_text()
+ if text and not text.isspace():
+ return self.complete(e)
+ else:
+ return self.vi_key(e)
+
+
+# vi input states
+# sequence of possible states are in the order below
+_VI_BEGIN = "vi_begin"
+_VI_MULTI1 = "vi_multi1"
+_VI_ACTION = "vi_action"
+_VI_MULTI2 = "vi_multi2"
+_VI_MOTION = "vi_motion"
+_VI_MOTION_ARGUMENT = "vi_motion_argument"
+_VI_REPLACE_ONE = "vi_replace_one"
+_VI_TEXT = "vi_text"
+_VI_SEARCH = "vi_search"
+_VI_END = "vi_end"
+
+# vi helper class
+
+
+class ViCommand:
+ def __init__(self, readline):
+ self.readline = readline
+ self.lst_char = []
+ self.state = _VI_BEGIN
+ self.action = self.movement
+ self.motion = None
+ self.motion_argument = None
+ self.text = None
+ self.pos_motion = None
+ self.is_edit = False
+ self.is_overwrite = False
+ self.is_error = False
+ self.is_star = False
+ self.delete_left = 0
+ self.delete_right = 0
+ self.readline._vi_multiplier1 = ""
+ self.readline._vi_multiplier2 = ""
+ self.set_override_multiplier(0)
+ self.skip_multipler = False
+ self.tabstop = 4
+ self.dct_fcn = {
+ ord("$"): self.key_dollar,
+ ord("^"): self.key_hat,
+ ord(";"): self.key_semicolon,
+ ord(","): self.key_comma,
+ ord("%"): self.key_percent,
+ ord("."): self.key_dot,
+ ord("/"): self.key_slash,
+ ord("*"): self.key_star,
+ ord("|"): self.key_bar,
+ ord("~"): self.key_tilde,
+ 8: self.key_backspace,
+ }
+
+ def add_char(self, char):
+ self.lst_char.append(char)
+ if self.state == _VI_BEGIN and self.readline.vi_is_insert_mode:
+ self.readline.vi_save_line()
+ self.state = _VI_TEXT
+ if self.state == _VI_SEARCH:
+ if char == "\x08": # backspace
+ self.key_backspace(char)
+ else:
+ self.set_text(char)
+ return
+ if self.state == _VI_TEXT:
+ if char == "\x1b": # escape
+ self.escape(char)
+ elif char == "\x09": # tab
+ ts = self.tabstop
+ ws = " " * (ts - (self.readline.l_buffer.point % ts))
+ self.set_text(ws)
+ elif char == "\x08": # backspace
+ self.key_backspace(char)
+ else:
+ self.set_text(char)
+ return
+ if self.state == _VI_MOTION_ARGUMENT:
+ self.set_motion_argument(char)
+ return
+ if self.state == _VI_REPLACE_ONE:
+ self.replace_one(char)
+ return
+ try:
+ fcn_instance = self.dct_fcn[ord(char)]
+ except BaseException:
+ fcn_instance = getattr(self, "key_%s" % char, None)
+ if fcn_instance:
+ fcn_instance(char)
+ return
+ if char.isdigit():
+ self.key_digit(char)
+ return
+ # Here: could not process key
+ self.error()
+
+ def set_text(self, text):
+ if self.text is None:
+ self.text = text
+ else:
+ self.text += text
+ self.set_buffer(text)
+
+ def set_buffer(self, text):
+ for char in text:
+ if not self.char_isprint(char):
+ continue
+ # self.readline.l_buffer.insert_text(char)
+ # continue
+ # #overwrite in l_buffer obj
+ if self.is_overwrite:
+ if self.readline.l_buffer.point < len(
+ self.readline.l_buffer.line_buffer
+ ):
+ # self.readline.l_buffer[self.l_buffer.point]=char
+ self.readline.l_buffer.line_buffer[self.readline.l_buffer.point] = (
+ char
+ )
+ else:
+ # self.readline.l_buffer.insert_text(char)
+ self.readline.l_buffer.line_buffer.append(char)
+ else:
+ # self.readline.l_buffer.insert_text(char)
+ self.readline.l_buffer.line_buffer.insert(
+ self.readline.l_buffer.point, char
+ )
+ self.readline.l_buffer.point += 1
+
+ def replace_one(self, char):
+ if char == "\x1b": # escape
+ self.end()
+ return
+ self.is_edit = True
+ self.readline.vi_save_line()
+ times = self.get_multiplier()
+ cursor = self.readline.l_buffer.point
+ self.readline.l_buffer.line_buffer[cursor : cursor + times] = char * times
+ if times > 1:
+ self.readline.l_buffer.point += times - 1
+ self.end()
+
+ def char_isprint(self, char):
+ return ord(char) >= ord(" ") and ord(char) <= ord("~")
+
+ def key_dollar(self, char):
+ self.motion = self.motion_end_in_line
+ self.delete_right = 1
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_hat(self, char):
+ self.motion = self.motion_beginning_of_line
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_0(self, char):
+ if self.state in [_VI_BEGIN, _VI_ACTION]:
+ self.key_hat(char)
+ else:
+ self.key_digit(char)
+
+ def key_digit(self, char):
+ if self.state in [_VI_BEGIN, _VI_MULTI1]:
+ self.readline._vi_multiplier1 += char
+ self.readline._vi_multiplier2 = ""
+ self.state = _VI_MULTI1
+ elif self.state in [_VI_ACTION, _VI_MULTI2]:
+ self.readline._vi_multiplier2 += char
+ self.state = _VI_MULTI2
+
+ def key_w(self, char):
+ if self.action == self.change:
+ self.key_e(char)
+ return
+ self.motion = self.motion_word_short
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_W(self, char):
+ if self.action == self.change:
+ self.key_E(char)
+ return
+ self.motion = self.motion_word_long
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_e(self, char):
+ self.motion = self.motion_end_short
+ self.state = _VI_MOTION
+ self.delete_right = 1
+ self.apply()
+
+ def key_E(self, char):
+ self.motion = self.motion_end_long
+ self.state = _VI_MOTION
+ self.delete_right = 1
+ self.apply()
+
+ def key_b(self, char):
+ self.motion = self.motion_back_short
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_B(self, char):
+ self.motion = self.motion_back_long
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_f(self, char):
+ self.readline._vi_key_find_direction = True
+ self.motion = self.motion_find_char_forward
+ self.delete_right = 1
+ self.state = _VI_MOTION_ARGUMENT
+
+ def key_F(self, char):
+ self.readline._vi_key_find_direction = False
+ self.motion = self.motion_find_char_backward
+ self.delete_left = 1
+ self.state = _VI_MOTION_ARGUMENT
+
+ def key_t(self, char):
+ self.motion = self.motion_to_char_forward
+ self.delete_right = 1
+ self.state = _VI_MOTION_ARGUMENT
+
+ def key_T(self, char):
+ self.motion = self.motion_to_char_backward
+ self.state = _VI_MOTION_ARGUMENT
+
+ def key_j(self, char):
+ self.readline.vi_down(ViEvent(char))
+ self.state = _VI_END
+
+ def key_k(self, char):
+ self.readline.vi_up(ViEvent(char))
+ self.state = _VI_END
+
+ def key_semicolon(self, char):
+ if self.readline._vi_key_find_char is None:
+ self.error()
+ return
+ if self.readline._vi_key_find_direction:
+ self.motion = self.motion_find_char_forward
+ else:
+ self.motion = self.motion_find_char_backward
+ self.set_motion_argument(self.readline._vi_key_find_char)
+
+ def key_comma(self, char):
+ if self.readline._vi_key_find_char is None:
+ self.error()
+ return
+ if self.readline._vi_key_find_direction:
+ self.motion = self.motion_find_char_backward
+ else:
+ self.motion = self.motion_find_char_forward
+ self.set_motion_argument(self.readline._vi_key_find_char)
+
+ def key_percent(self, char):
+ """find matching <([{}])>"""
+ self.motion = self.motion_matching
+ self.delete_right = 1
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_dot(self, char):
+ vi_cmd_edit = self.readline._vi_command_edit
+ if not vi_cmd_edit:
+ return
+ if vi_cmd_edit.is_star:
+ self.key_star(char)
+ return
+ if self.has_multiplier():
+ count = self.get_multiplier()
+ else:
+ count = 0
+ # Create the ViCommand object after getting multiplier from self
+ # Side effect of the ViCommand creation is resetting of global
+ # multipliers
+ vi_cmd = ViCommand(self.readline)
+ if count >= 1:
+ vi_cmd.set_override_multiplier(count)
+ vi_cmd_edit.set_override_multiplier(count)
+ elif vi_cmd_edit.override_multiplier:
+ vi_cmd.set_override_multiplier(vi_cmd_edit.override_multiplier)
+ for char in vi_cmd_edit.lst_char:
+ vi_cmd.add_char(char)
+ if vi_cmd_edit.is_overwrite and self.readline.l_buffer.point > 0:
+ self.readline.l_buffer.point -= 1
+ self.readline.vi_set_insert_mode(False)
+ self.end()
+
+ def key_slash(self, char):
+ self.readline.vi_save_line()
+ self.readline.l_buffer.line_buffer = ["/"]
+ self.readline.l_buffer.point = 1
+ self.state = _VI_SEARCH
+
+ def key_star(self, char):
+ self.is_star = True
+ self.is_edit = True
+ self.readline.vi_save_line()
+ completions = self.readline._get_completions()
+ if completions:
+ text = " ".join(completions) + " "
+ self.readline.l_buffer.line_buffer[
+ self.readline.begidx : self.readline.endidx + 1
+ ] = list(text)
+ prefix_len = self.readline.endidx - self.readline.begidx
+ self.readline.l_buffer.point += len(text) - prefix_len
+ self.readline.vi_set_insert_mode(True)
+ else:
+ self.error()
+ self.state = _VI_TEXT
+
+ def key_bar(self, char):
+ self.motion = self.motion_column
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_tilde(self, char):
+ self.is_edit = True
+ self.readline.vi_save_line()
+ for i in range(self.get_multiplier()):
+ try:
+ c = self.readline.l_buffer.line_buffer[self.readline.l_buffer.point]
+ if c.isupper():
+ self.readline.l_buffer.line_buffer[self.readline.l_buffer.point] = (
+ c.lower()
+ )
+ elif c.islower():
+ self.readline.l_buffer.line_buffer[self.readline.l_buffer.point] = (
+ c.upper()
+ )
+ self.readline.l_buffer.point += 1
+ except IndexError:
+ break
+ self.end()
+
+ def key_h(self, char):
+ self.motion = self.motion_left
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_backspace(self, char):
+ if self.state in [_VI_TEXT, _VI_SEARCH]:
+ if self.text and len(self.text):
+ self.text = self.text[:-1]
+ try:
+ # Remove backspaces for potential dot command
+ self.lst_char.pop()
+ self.lst_char.pop()
+ except IndexError:
+ pass
+ else:
+ self.key_h(char)
+ self.readline._vi_do_backspace(self)
+ if self.state == _VI_SEARCH and not (self.readline.l_buffer.line_buffer):
+ self.state = _VI_BEGIN
+
+ def key_l(self, char):
+ self.motion = self.motion_right
+ self.state = _VI_MOTION
+ self.apply()
+
+ def key_i(self, char):
+ self.is_edit = True
+ self.state = _VI_TEXT
+ self.readline.vi_set_insert_mode(True)
+
+ def key_I(self, char):
+ self.is_edit = True
+ self.state = _VI_TEXT
+ self.readline.vi_set_insert_mode(True)
+ self.readline.l_buffer.point = 0
+
+ def key_a(self, char):
+ self.is_edit = True
+ self.state = _VI_TEXT
+ self.readline.vi_set_insert_mode(True)
+ if len(self.readline.l_buffer.line_buffer):
+ self.readline.l_buffer.point += 1
+
+ def key_A(self, char):
+ self.is_edit = True
+ self.state = _VI_TEXT
+ self.readline.vi_set_insert_mode(True)
+ self.readline.l_buffer.point = len(self.readline.l_buffer.line_buffer)
+
+ def key_d(self, char):
+ self.is_edit = True
+ self.state = _VI_ACTION
+ self.action = self.delete
+
+ def key_D(self, char):
+ self.is_edit = True
+ self.state = _VI_ACTION
+ self.action = self.delete_end_of_line
+ self.apply()
+
+ def key_x(self, char):
+ self.is_edit = True
+ self.state = _VI_ACTION
+ self.action = self.delete_char
+ self.apply()
+
+ def key_X(self, char):
+ self.is_edit = True
+ self.state = _VI_ACTION
+ self.action = self.delete_prev_char
+ self.apply()
+
+ def key_s(self, char):
+ self.is_edit = True
+ i1 = self.readline.l_buffer.point
+ i2 = self.readline.l_buffer.point + self.get_multiplier()
+ self.skip_multipler = True
+ self.readline.vi_set_insert_mode(True)
+ del self.readline.l_buffer.line_buffer[i1:i2]
+ self.state = _VI_TEXT
+
+ def key_S(self, char):
+ self.is_edit = True
+ self.readline.vi_set_insert_mode(True)
+ self.readline.l_buffer.line_buffer = []
+ self.readline.l_buffer.point = 0
+ self.state = _VI_TEXT
+
+ def key_c(self, char):
+ self.is_edit = True
+ self.state = _VI_ACTION
+ self.action = self.change
+
+ def key_C(self, char):
+ self.is_edit = True
+ self.readline.vi_set_insert_mode(True)
+ del self.readline.l_buffer.line_buffer[self.readline.l_buffer.point :]
+ self.state = _VI_TEXT
+
+ def key_r(self, char):
+ self.state = _VI_REPLACE_ONE
+
+ def key_R(self, char):
+ self.is_edit = True
+ self.is_overwrite = True
+ self.readline.l_buffer.overwrite = True
+ self.readline.vi_set_insert_mode(True)
+ self.state = _VI_TEXT
+
+ def key_y(self, char):
+ self._state = _VI_ACTION
+ self.action = self.yank
+
+ def key_Y(self, char):
+ self.readline._vi_yank_buffer = self.readline.l_buffer.get_line_text()
+ self.end()
+
+ def key_p(self, char):
+ if not self.readline._vi_yank_buffer:
+ return
+ self.is_edit = True
+ self.readline.vi_save_line()
+ self.readline.l_buffer.point += 1
+ self.readline.l_buffer.insert_text(
+ self.readline._vi_yank_buffer * self.get_multiplier()
+ )
+ self.readline.l_buffer.point -= 1
+ self.state = _VI_END
+
+ def key_P(self, char):
+ if not self.readline._vi_yank_buffer:
+ return
+ self.is_edit = True
+ self.readline.vi_save_line()
+ self.readline.l_buffer.insert_text(
+ self.readline._vi_yank_buffer * self.get_multiplier()
+ )
+ self.readline.l_buffer.point -= 1
+ self.state = _VI_END
+
+ def key_u(self, char):
+ self.readline.vi_undo()
+ self.state = _VI_END
+
+ def key_U(self, char):
+ self.readline.vi_undo_all()
+ self.state = _VI_END
+
+ def key_v(self, char):
+ editor = ViExternalEditor(self.readline.l_buffer.line_buffer)
+ self.readline.l_buffer.line_buffer = list(editor.result)
+ self.readline.l_buffer.point = 0
+ self.is_edit = True
+ self.state = _VI_END
+
+ def error(self):
+ self.readline._bell()
+ self.is_error = True
+
+ def state_is_end(self):
+ return self.state == _VI_END
+
+ is_end = property(state_is_end)
+
+ def state_is_search(self):
+ return self.state == _VI_SEARCH
+
+ is_search = property(state_is_search)
+
+ def state_is_replace_one(self):
+ return self.state == _VI_REPLACE_ONE
+
+ is_replace_one = property(state_is_replace_one)
+
+ def do_search(self):
+ self.readline.vi_search_first()
+ self.state = _VI_END
+
+ def key_n(self, char):
+ self.readline.vi_search_again_backward()
+ self.state = _VI_END
+
+ def key_N(self, char):
+ self.readline.vi_search_again_forward()
+ self.state = _VI_END
+
+ def motion_beginning_of_line(self, line, index=0, count=1, **kw):
+ return 0
+
+ def motion_end_in_line(self, line, index=0, count=1, **kw):
+ return max(0, len(self.readline.l_buffer.line_buffer) - 1)
+
+ def motion_word_short(self, line, index=0, count=1, **kw):
+ return vi_pos_word_short(line, index, count)
+
+ def motion_word_long(self, line, index=0, count=1, **kw):
+ return vi_pos_word_long(line, index, count)
+
+ def motion_end_short(self, line, index=0, count=1, **kw):
+ return vi_pos_end_short(line, index, count)
+
+ def motion_end_long(self, line, index=0, count=1, **kw):
+ return vi_pos_end_long(line, index, count)
+
+ def motion_back_short(self, line, index=0, count=1, **kw):
+ return vi_pos_back_short(line, index, count)
+
+ def motion_back_long(self, line, index=0, count=1, **kw):
+ return vi_pos_back_long(line, index, count)
+
+ def motion_find_char_forward(self, line, index=0, count=1, char=None):
+ self.readline._vi_key_find_char = char
+ return vi_pos_find_char_forward(line, char, index, count)
+
+ def motion_find_char_backward(self, line, index=0, count=1, char=None):
+ self.readline._vi_key_find_char = char
+ return vi_pos_find_char_backward(line, char, index, count)
+
+ def motion_to_char_forward(self, line, index=0, count=1, char=None):
+ return vi_pos_to_char_forward(line, char, index, count)
+
+ def motion_to_char_backward(self, line, index=0, count=1, char=None):
+ return vi_pos_to_char_backward(line, char, index, count)
+
+ def motion_left(self, line, index=0, count=1, char=None):
+ return max(0, index - count)
+
+ def motion_right(self, line, index=0, count=1, char=None):
+ return min(len(line), index + count)
+
+ def motion_matching(self, line, index=0, count=1, char=None):
+ return vi_pos_matching(line, index)
+
+ def motion_column(self, line, index=0, count=1, char=None):
+ return max(0, count - 1)
+
+ def has_multiplier(self):
+ return (
+ self.override_multiplier
+ or self.readline._vi_multiplier1
+ or self.readline._vi_multiplier2
+ )
+
+ def get_multiplier(self):
+ if self.override_multiplier:
+ return int(self.override_multiplier)
+ if self.readline._vi_multiplier1 == "":
+ m1 = 1
+ else:
+ m1 = int(self.readline._vi_multiplier1)
+ if self.readline._vi_multiplier2 == "":
+ m2 = 1
+ else:
+ m2 = int(self.readline._vi_multiplier2)
+ return m1 * m2
+
+ def set_override_multiplier(self, count):
+ self.override_multiplier = count
+
+ def apply(self):
+ if self.motion:
+ self.pos_motion = self.motion(
+ self.readline.l_buffer.line_buffer,
+ self.readline.l_buffer.point,
+ self.get_multiplier(),
+ char=self.motion_argument,
+ )
+ if self.pos_motion < 0:
+ self.error()
+ return
+ self.action()
+ if self.state != _VI_TEXT:
+ self.end()
+
+ def movement(self):
+ if self.pos_motion <= len(self.readline.l_buffer.line_buffer):
+ self.readline.l_buffer.point = self.pos_motion
+ else:
+ self.readline.l_buffer.point = len(self.readline.l_buffer.line_buffer) - 1
+
+ def yank(self):
+ if self.pos_motion > self.readline.l_buffer.point:
+ s = self.readline.l_buffer.line_buffer[
+ self.readline.l_buffer.point : self.pos_motion + self.delete_right
+ ]
+ else:
+ index = max(0, self.pos_motion - self.delete_left)
+ s = self.readline.l_buffer.line_buffer[
+ index : self.readline.l_buffer.point + self.delete_right
+ ]
+ self.readline._vi_yank_buffer = s
+
+ def delete(self):
+ self.readline.vi_save_line()
+ self.yank()
+ # point=lineobj.Point(self.readline.l_buffer)
+ # pm=self.pos_motion
+ # del self.readline.l_buffer[point:pm]
+ # return
+ if self.pos_motion > self.readline.l_buffer.point:
+ del self.readline.l_buffer.line_buffer[
+ self.readline.l_buffer.point : self.pos_motion + self.delete_right
+ ]
+ if self.readline.l_buffer.point > len(self.readline.l_buffer.line_buffer):
+ self.readline.l_buffer.point = len(self.readline.l_buffer.line_buffer)
+ else:
+ index = max(0, self.pos_motion - self.delete_left)
+ del self.readline.l_buffer.line_buffer[
+ index : self.readline.l_buffer.point + self.delete_right
+ ]
+ self.readline.l_buffer.point = index
+
+ def delete_end_of_line(self):
+ self.readline.vi_save_line()
+ # del self.readline.l_buffer [self.readline.l_buffer.point : ]
+ line_text = self.readline.l_buffer.get_line_text()
+ line_text = line_text[: self.readline.l_buffer.point]
+ self.readline.l_buffer.set_line(line_text)
+ if self.readline.l_buffer.point > 0:
+ self.readline.l_buffer.point -= 1
+
+ def delete_char(self):
+ # point=lineobj.Point(self.readline.l_buffer)
+ # del self.readline.l_buffer[point:point+self.get_multiplier ()]
+ # return
+ self.pos_motion = self.readline.l_buffer.point + self.get_multiplier()
+ self.delete()
+ end = max(0, len(self.readline.l_buffer) - 1)
+ if self.readline.l_buffer.point > end:
+ self.readline.l_buffer.point = end
+
+ def delete_prev_char(self):
+ self.pos_motion = self.readline.l_buffer.point - self.get_multiplier()
+ self.delete()
+
+ def change(self):
+ self.readline.vi_set_insert_mode(True)
+ self.delete()
+ self.skip_multipler = True
+ self.state = _VI_TEXT
+
+ def escape(self, char):
+ if self.state == _VI_TEXT:
+ if not self.skip_multipler:
+ times = self.get_multiplier()
+ if times > 1 and self.text:
+ extra = self.text * (times - 1)
+ self.set_buffer(extra)
+ self.state = _VI_END
+
+ def set_motion_argument(self, char):
+ self.motion_argument = char
+ self.apply()
+
+ def end(self):
+ self.state = _VI_END
+ if self.readline.l_buffer.point >= len(self.readline.l_buffer.line_buffer):
+ self.readline.l_buffer.point = max(
+ 0, len(self.readline.l_buffer.line_buffer) - 1
+ )
+
+
+class ViExternalEditor:
+ def __init__(self, line):
+ if isinstance(line, type([])):
+ line = "".join(line)
+ file_tmp = self.get_tempfile()
+ fp_tmp = self.file_open(file_tmp, "w")
+ fp_tmp.write(line)
+ fp_tmp.close()
+ self.run_editor(file_tmp)
+ fp_tmp = self.file_open(file_tmp, "r")
+ self.result = fp_tmp.read()
+ fp_tmp.close()
+ self.file_remove(file_tmp)
+
+ def get_tempfile(self):
+ import tempfile
+
+ return tempfile.mktemp(prefix="readline-", suffix=".py")
+
+ def file_open(self, filename, mode):
+ return open(filename, mode)
+
+ def file_remove(self, filename):
+ os.remove(filename)
+
+ def get_editor(self):
+ try:
+ return os.environ["EDITOR"]
+ except KeyError:
+ return "notepad" # ouch
+
+ def run_editor(self, filename):
+ cmd = "%s %s" % (
+ self.get_editor(),
+ filename,
+ )
+ self.run_command(cmd)
+
+ def run_command(self, command):
+ os.system(command)
+
+
+class ViEvent:
+ def __init__(self, char):
+ self.char = char
+
+
+# vi standalone functions
+
+
+def vi_is_word(char):
+ log(
+ "xx vi_is_word: type(%s), %s"
+ % (
+ type(char),
+ char,
+ )
+ )
+ return char.isalpha() or char.isdigit() or char == "_"
+
+
+def vi_is_space(char):
+ return char.isspace()
+
+
+def vi_is_word_or_space(char):
+ return vi_is_word(char) or vi_is_space(char)
+
+
+def vi_pos_word_short(line, index=0, count=1):
+ try:
+ for i in range(count):
+ in_word = vi_is_word(line[index])
+ if not in_word:
+ while not vi_is_word(line[index]):
+ index += 1
+ else:
+ while vi_is_word(line[index]):
+ index += 1
+ while vi_is_space(line[index]):
+ index += 1
+ return index
+ except IndexError:
+ return len(line)
+
+
+def vi_pos_word_long(line, index=0, count=1):
+ try:
+ for i in range(count):
+ in_space = vi_is_space(line[index])
+ if not in_space:
+ while not vi_is_space(line[index]):
+ index += 1
+ while vi_is_space(line[index]):
+ index += 1
+ return index
+ except IndexError:
+ return len(line)
+
+
+def vi_pos_end_short(line, index=0, count=1):
+ try:
+ for i in range(count):
+ index += 1
+ while vi_is_space(line[index]):
+ index += 1
+ in_word = vi_is_word(line[index])
+ if not in_word:
+ while not vi_is_word_or_space(line[index]):
+ index += 1
+ else:
+ while vi_is_word(line[index]):
+ index += 1
+ return index - 1
+ except IndexError:
+ return max(0, len(line) - 1)
+
+
+def vi_pos_end_long(line, index=0, count=1):
+ try:
+ for i in range(count):
+ index += 1
+ while vi_is_space(line[index]):
+ index += 1
+ while not vi_is_space(line[index]):
+ index += 1
+ return index - 1
+ except IndexError:
+ return max(0, len(line) - 1)
+
+
+class vi_list(list):
+ """This is a list that cannot have a negative index"""
+
+ def __getitem__(self, key):
+ try:
+ if int(key) < 0:
+ raise IndexError
+ except ValueError:
+ pass
+ return list.__getitem__(self, key)
+
+
+def vi_pos_back_short(line, index=0, count=1):
+ line = vi_list(line)
+ try:
+ for i in range(count):
+ index -= 1
+ while vi_is_space(line[index]):
+ index -= 1
+ in_word = vi_is_word(line[index])
+ if in_word:
+ while vi_is_word(line[index]):
+ index -= 1
+ else:
+ while not vi_is_word_or_space(line[index]):
+ index -= 1
+ return index + 1
+ except IndexError:
+ return 0
+
+
+def vi_pos_back_long(line, index=0, count=1):
+ line = vi_list(line)
+ try:
+ for i in range(count):
+ index -= 1
+ while vi_is_space(line[index]):
+ index -= 1
+ while not vi_is_space(line[index]):
+ index -= 1
+ return index + 1
+ except IndexError:
+ return 0
+
+
+def vi_pos_find_char_forward(line, char, index=0, count=1):
+ try:
+ for i in range(count):
+ index += 1
+ while line[index] != char:
+ index += 1
+ return index
+ except IndexError:
+ return -1
+
+
+def vi_pos_find_char_backward(line, char, index=0, count=1):
+ try:
+ for i in range(count):
+ index -= 1
+ while True:
+ if index < 0:
+ return -1
+ if line[index] == char:
+ break
+ index -= 1
+ return index
+ except IndexError:
+ return -1
+
+
+def vi_pos_to_char_forward(line, char, index=0, count=1):
+ index = vi_pos_find_char_forward(line, char, index, count)
+ if index > 0:
+ return index - 1
+ return index
+
+
+def vi_pos_to_char_backward(line, char, index=0, count=1):
+ index = vi_pos_find_char_backward(line, char, index, count)
+ if index >= 0:
+ return index + 1
+ return index
+
+
+_vi_dct_matching = {
+ "<": (">", +1),
+ ">": ("<", -1),
+ "(": (")", +1),
+ ")": ("(", -1),
+ "[": ("]", +1),
+ "]": ("[", -1),
+ "{": ("}", +1),
+ "}": ("{", -1),
+}
+
+
+def vi_pos_matching(line, index=0):
+ """find matching <([{}])>"""
+ anchor = None
+ target = None
+ delta = 1
+ count = 0
+ try:
+ while True:
+ if anchor is None:
+ # first find anchor
+ try:
+ target, delta = _vi_dct_matching[line[index]]
+ anchor = line[index]
+ count = 1
+ except KeyError:
+ index += 1
+ continue
+ else:
+ # Here the anchor has been found
+ # Need to get corresponding target
+ if index < 0:
+ return -1
+ if line[index] == anchor:
+ count += 1
+ elif line[index] == target:
+ count -= 1
+ if count == 0:
+ return index
+ index += delta
+ except IndexError:
+ return -1
diff --git a/python_embeded/Lib/site-packages/python_dotenv-1.1.0.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/python_dotenv-1.1.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..3a97119010ac82e15e917a69b7b8f9f59b5a4601
--- /dev/null
+++ b/python_embeded/Lib/site-packages/python_dotenv-1.1.0.dist-info/licenses/LICENSE
@@ -0,0 +1,27 @@
+Copyright (c) 2014, Saurabh Kumar (python-dotenv), 2013, Ted Tieken (django-dotenv-rw), 2013, Jacob Kaplan-Moss (django-dotenv)
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+- Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+
+- Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+- Neither the name of django-dotenv nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
+CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/basictimerapp.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/basictimerapp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2025eac2f6e2025ea736d5867c73cd16b75817bb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/basictimerapp.py
@@ -0,0 +1,258 @@
+# basictimerapp - a really simple timer application.
+# This should be run using the command line:
+# pythonwin /app demos\basictimerapp.py
+import sys
+import time
+
+import timer
+import win32api
+import win32con
+import win32ui
+from pywin.framework import dlgappcore
+
+
+class TimerAppDialog(dlgappcore.AppDialog):
+ softspace = 1
+
+ def __init__(self, appName=""):
+ dlgappcore.AppDialog.__init__(self, win32ui.IDD_GENERAL_STATUS)
+ self.timerAppName = appName
+ self.argOff = 0
+ if len(self.timerAppName) == 0:
+ if len(sys.argv) > 1 and sys.argv[1][0] != "/":
+ self.timerAppName = sys.argv[1]
+ self.argOff = 1
+
+ def PreDoModal(self):
+ # sys.stderr = sys.stdout
+ pass
+
+ def ProcessArgs(self, args):
+ for arg in args:
+ if arg == "/now":
+ self.OnOK()
+
+ def OnInitDialog(self):
+ win32ui.SetProfileFileName("pytimer.ini")
+ self.title = win32ui.GetProfileVal(
+ self.timerAppName, "Title", "Remote System Timer"
+ )
+ self.buildTimer = win32ui.GetProfileVal(
+ self.timerAppName, "Timer", "EachMinuteIntervaler()"
+ )
+ self.doWork = win32ui.GetProfileVal(self.timerAppName, "Work", "DoDemoWork()")
+ # replace "\n" with real \n.
+ self.doWork = self.doWork.replace("\\n", "\n")
+ dlgappcore.AppDialog.OnInitDialog(self)
+
+ self.SetWindowText(self.title)
+ self.prompt1 = self.GetDlgItem(win32ui.IDC_PROMPT1)
+ self.prompt2 = self.GetDlgItem(win32ui.IDC_PROMPT2)
+ self.prompt3 = self.GetDlgItem(win32ui.IDC_PROMPT3)
+ self.butOK = self.GetDlgItem(win32con.IDOK)
+ self.butCancel = self.GetDlgItem(win32con.IDCANCEL)
+ self.prompt1.SetWindowText("Python Timer App")
+ self.prompt2.SetWindowText("")
+ self.prompt3.SetWindowText("")
+ self.butOK.SetWindowText("Do it now")
+ self.butCancel.SetWindowText("Close")
+
+ self.timerManager = TimerManager(self)
+ self.ProcessArgs(sys.argv[self.argOff :])
+ self.timerManager.go()
+ return 1
+
+ def OnDestroy(self, msg):
+ dlgappcore.AppDialog.OnDestroy(self, msg)
+ self.timerManager.stop()
+
+ def OnOK(self):
+ # stop the timer, then restart after setting special boolean
+ self.timerManager.stop()
+ self.timerManager.bConnectNow = 1
+ self.timerManager.go()
+ return
+
+
+# def OnCancel(self): default behaviour - cancel == close.
+# return
+
+
+class TimerManager:
+ def __init__(self, dlg):
+ self.dlg = dlg
+ self.timerId = None
+ self.intervaler = eval(self.dlg.buildTimer)
+ self.bConnectNow = 0
+ self.bHaveSetPrompt1 = 0
+
+ def CaptureOutput(self):
+ self.oldOut = sys.stdout
+ self.oldErr = sys.stderr
+ sys.stdout = sys.stderr = self
+ self.bHaveSetPrompt1 = 0
+
+ def ReleaseOutput(self):
+ sys.stdout = self.oldOut
+ sys.stderr = self.oldErr
+
+ def write(self, str):
+ s = str.strip()
+ if len(s):
+ if self.bHaveSetPrompt1:
+ dest = self.dlg.prompt3
+ else:
+ dest = self.dlg.prompt1
+ self.bHaveSetPrompt1 = 1
+ dest.SetWindowText(s)
+
+ def go(self):
+ self.OnTimer(None, None)
+
+ def stop(self):
+ if self.timerId:
+ timer.kill_timer(self.timerId)
+ self.timerId = None
+
+ def OnTimer(self, id, timeVal):
+ if id:
+ timer.kill_timer(id)
+ if self.intervaler.IsTime() or self.bConnectNow:
+ # do the work.
+ try:
+ self.dlg.SetWindowText(self.dlg.title + " - Working...")
+ self.dlg.butOK.EnableWindow(0)
+ self.dlg.butCancel.EnableWindow(0)
+ self.CaptureOutput()
+ try:
+ exec(self.dlg.doWork)
+ print("The last operation completed successfully.")
+ except:
+ t, v, tb = sys.exc_info()
+ str = f"Failed: {t}: {v!r}"
+ print(str)
+ self.oldErr.write(str)
+ tb = None # Prevent cycle
+ finally:
+ self.ReleaseOutput()
+ self.dlg.butOK.EnableWindow()
+ self.dlg.butCancel.EnableWindow()
+ self.dlg.SetWindowText(self.dlg.title)
+ else:
+ now = time.time()
+ nextTime = self.intervaler.GetNextTime()
+ if nextTime:
+ timeDiffSeconds = nextTime - now
+ timeDiffMinutes = int(timeDiffSeconds / 60)
+ timeDiffSeconds %= 60
+ timeDiffHours = int(timeDiffMinutes / 60)
+ timeDiffMinutes %= 60
+ self.dlg.prompt1.SetWindowText(
+ "Next connection due in %02d:%02d:%02d"
+ % (timeDiffHours, timeDiffMinutes, timeDiffSeconds)
+ )
+ self.timerId = timer.set_timer(
+ self.intervaler.GetWakeupInterval(), self.OnTimer
+ )
+ self.bConnectNow = 0
+
+
+class TimerIntervaler:
+ def __init__(self):
+ self.nextTime = None
+ self.wakeUpInterval = 2000
+
+ def GetWakeupInterval(self):
+ return self.wakeUpInterval
+
+ def GetNextTime(self):
+ return self.nextTime
+
+ def IsTime(self):
+ now = time.time()
+ if self.nextTime is None:
+ self.nextTime = self.SetFirstTime(now)
+ ret = 0
+ if now >= self.nextTime:
+ ret = 1
+ self.nextTime = self.SetNextTime(self.nextTime, now)
+ # do the work.
+ return ret
+
+
+class EachAnyIntervaler(TimerIntervaler):
+ def __init__(self, timeAt, timePos, timeAdd, wakeUpInterval=None):
+ TimerIntervaler.__init__(self)
+ self.timeAt = timeAt
+ self.timePos = timePos
+ self.timeAdd = timeAdd
+ if wakeUpInterval:
+ self.wakeUpInterval = wakeUpInterval
+
+ def SetFirstTime(self, now):
+ timeTup = time.localtime(now)
+ lst = []
+ for item in timeTup:
+ lst.append(item)
+ bAdd = timeTup[self.timePos] > self.timeAt
+ lst[self.timePos] = self.timeAt
+ for pos in range(self.timePos + 1, 6):
+ lst[pos] = 0
+ ret = time.mktime(tuple(lst))
+ if bAdd:
+ ret += self.timeAdd
+ return ret
+
+ def SetNextTime(self, lastTime, now):
+ return lastTime + self.timeAdd
+
+
+class EachMinuteIntervaler(EachAnyIntervaler):
+ def __init__(self, at=0):
+ EachAnyIntervaler.__init__(self, at, 5, 60, 2000)
+
+
+class EachHourIntervaler(EachAnyIntervaler):
+ def __init__(self, at=0):
+ EachAnyIntervaler.__init__(self, at, 4, 3600, 10000)
+
+
+class EachDayIntervaler(EachAnyIntervaler):
+ def __init__(self, at=0):
+ EachAnyIntervaler.__init__(self, at, 3, 86400, 10000)
+
+
+class TimerDialogApp(dlgappcore.DialogApp):
+ def CreateDialog(self):
+ return TimerAppDialog()
+
+
+def DoDemoWork():
+ print("Doing the work...")
+ print("About to connect")
+ win32api.MessageBeep(win32con.MB_ICONASTERISK)
+ win32api.Sleep(2000)
+ print("Doing something else...")
+ win32api.MessageBeep(win32con.MB_ICONEXCLAMATION)
+ win32api.Sleep(2000)
+ print("More work.")
+ win32api.MessageBeep(win32con.MB_ICONHAND)
+ win32api.Sleep(2000)
+ print("The last bit.")
+ win32api.MessageBeep(win32con.MB_OK)
+ win32api.Sleep(2000)
+
+
+app = TimerDialogApp()
+
+
+def t():
+ t = TimerAppDialog("Test Dialog")
+ t.DoModal()
+ return t
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ demoutils.NeedApp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/customprint.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/customprint.py
new file mode 100644
index 0000000000000000000000000000000000000000..421c0148737f4892f45563cba20e47ac2c5838f4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/customprint.py
@@ -0,0 +1,183 @@
+# A demo of an Application object that has some custom print functionality.
+
+# If you desire, you can also run this from inside Pythonwin, in which
+# case it will do the demo inside the Pythonwin environment.
+
+# This sample was contributed by Roger Burnham.
+
+import win32con
+import win32ui
+from pywin.framework import app
+from pywin.mfc import afxres, dialog, docview
+
+PRINTDLGORD = 1538
+IDC_PRINT_MAG_EDIT = 1010
+
+
+class PrintDemoTemplate(docview.DocTemplate):
+ def _SetupSharedMenu_(self):
+ pass
+
+
+class PrintDemoView(docview.ScrollView):
+ def OnInitialUpdate(self):
+ ret = self._obj_.OnInitialUpdate()
+ self.colors = {
+ "Black": (0x00 << 0) + (0x00 << 8) + (0x00 << 16),
+ "Red": (0xFF << 0) + (0x00 << 8) + (0x00 << 16),
+ "Green": (0x00 << 0) + (0xFF << 8) + (0x00 << 16),
+ "Blue": (0x00 << 0) + (0x00 << 8) + (0xFF << 16),
+ "Cyan": (0x00 << 0) + (0xFF << 8) + (0xFF << 16),
+ "Magenta": (0xFF << 0) + (0x00 << 8) + (0xFF << 16),
+ "Yellow": (0xFF << 0) + (0xFF << 8) + (0x00 << 16),
+ }
+ self.pens = {}
+ for name, color in self.colors.items():
+ self.pens[name] = win32ui.CreatePen(win32con.PS_SOLID, 5, color)
+ self.pen = None
+ self.size = (128, 128)
+ self.SetScaleToFitSize(self.size)
+ self.HookCommand(self.OnFilePrint, afxres.ID_FILE_PRINT)
+ self.HookCommand(self.OnFilePrintPreview, win32ui.ID_FILE_PRINT_PREVIEW)
+ return ret
+
+ def OnDraw(self, dc):
+ oldPen = None
+ x, y = self.size
+ delta = 2
+ colors = sorted(self.colors) * 2
+ for color in colors:
+ if oldPen is None:
+ oldPen = dc.SelectObject(self.pens[color])
+ else:
+ dc.SelectObject(self.pens[color])
+ dc.MoveTo((delta, delta))
+ dc.LineTo((x - delta, delta))
+ dc.LineTo((x - delta, y - delta))
+ dc.LineTo((delta, y - delta))
+ dc.LineTo((delta, delta))
+ delta += 4
+ if x - delta <= 0 or y - delta <= 0:
+ break
+ dc.SelectObject(oldPen)
+
+ def OnPrepareDC(self, dc, pInfo):
+ if dc.IsPrinting():
+ mag = self.prtDlg["mag"]
+ dc.SetMapMode(win32con.MM_ANISOTROPIC)
+ dc.SetWindowOrg((0, 0))
+ dc.SetWindowExt((1, 1))
+ dc.SetViewportOrg((0, 0))
+ dc.SetViewportExt((mag, mag))
+
+ def OnPreparePrinting(self, pInfo):
+ flags = (
+ win32ui.PD_USEDEVMODECOPIES
+ | win32ui.PD_PAGENUMS
+ | win32ui.PD_NOPAGENUMS
+ | win32ui.PD_NOSELECTION
+ )
+ self.prtDlg = ImagePrintDialog(pInfo, PRINTDLGORD, flags)
+ pInfo.SetPrintDialog(self.prtDlg)
+ pInfo.SetMinPage(1)
+ pInfo.SetMaxPage(1)
+ pInfo.SetFromPage(1)
+ pInfo.SetToPage(1)
+ ret = self.DoPreparePrinting(pInfo)
+ return ret
+
+ def OnBeginPrinting(self, dc, pInfo):
+ return self._obj_.OnBeginPrinting(dc, pInfo)
+
+ def OnEndPrinting(self, dc, pInfo):
+ del self.prtDlg
+ return self._obj_.OnEndPrinting(dc, pInfo)
+
+ def OnFilePrintPreview(self, *arg):
+ self._obj_.OnFilePrintPreview()
+
+ def OnFilePrint(self, *arg):
+ self._obj_.OnFilePrint()
+
+ def OnPrint(self, dc, pInfo):
+ doc = self.GetDocument()
+ metrics = dc.GetTextMetrics()
+ cxChar = metrics["tmAveCharWidth"]
+ cyChar = metrics["tmHeight"]
+ left, top, right, bottom = pInfo.GetDraw()
+ dc.TextOut(0, 2 * cyChar, doc.GetTitle())
+ top += 7 * cyChar / 2
+ dc.MoveTo(left, top)
+ dc.LineTo(right, top)
+ top += cyChar
+ # this seems to have not effect...
+ # get what I want with the dc.SetWindowOrg calls
+ pInfo.SetDraw((left, top, right, bottom))
+ dc.SetWindowOrg((0, -top))
+
+ self.OnDraw(dc)
+ dc.SetTextAlign(win32con.TA_LEFT | win32con.TA_BOTTOM)
+
+ rect = self.GetWindowRect()
+ rect = self.ScreenToClient(rect)
+ height = rect[3] - rect[1]
+ dc.SetWindowOrg((0, -(top + height + cyChar)))
+ dc.MoveTo(left, 0)
+ dc.LineTo(right, 0)
+
+ x = 0
+ y = (3 * cyChar) / 2
+
+ dc.TextOut(x, y, doc.GetTitle())
+ y += cyChar
+
+
+class PrintDemoApp(app.CApp):
+ def __init__(self):
+ app.CApp.__init__(self)
+
+ def InitInstance(self):
+ template = PrintDemoTemplate(None, None, None, PrintDemoView)
+ self.AddDocTemplate(template)
+ self._obj_.InitMDIInstance()
+ self.LoadMainFrame()
+ doc = template.OpenDocumentFile(None)
+ doc.SetTitle("Custom Print Document")
+
+
+class ImagePrintDialog(dialog.PrintDialog):
+ sectionPos = "Image Print Demo"
+
+ def __init__(self, pInfo, dlgID, flags=win32ui.PD_USEDEVMODECOPIES):
+ dialog.PrintDialog.__init__(self, pInfo, dlgID, flags=flags)
+ mag = win32ui.GetProfileVal(self.sectionPos, "Document Magnification", 0)
+ if mag <= 0:
+ mag = 2
+ win32ui.WriteProfileVal(self.sectionPos, "Document Magnification", mag)
+
+ self["mag"] = mag
+
+ def OnInitDialog(self):
+ self.magCtl = self.GetDlgItem(IDC_PRINT_MAG_EDIT)
+ self.magCtl.SetWindowText(repr(self["mag"]))
+ return dialog.PrintDialog.OnInitDialog(self)
+
+ def OnOK(self):
+ dialog.PrintDialog.OnOK(self)
+ strMag = self.magCtl.GetWindowText()
+ try:
+ self["mag"] = int(strMag)
+ except:
+ pass
+ win32ui.WriteProfileVal(self.sectionPos, "Document Magnification", self["mag"])
+
+
+if __name__ == "__main__":
+ # Running under Pythonwin
+ def test():
+ template = PrintDemoTemplate(None, None, None, PrintDemoView)
+ template.OpenDocumentFile(None)
+
+ test()
+else:
+ app = PrintDemoApp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/demoutils.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/demoutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b17ff4aebdd5ae838db201c883e24aafdc163ce6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/demoutils.py
@@ -0,0 +1,63 @@
+# Utilities for the demos
+
+import sys
+
+import win32api
+import win32con
+import win32ui
+
+NotScriptMsg = """\
+This demo program is not designed to be run as a Script, but is
+probably used by some other test program. Please try another demo.
+"""
+
+NeedGUIMsg = """\
+This demo program can only be run from inside of Pythonwin
+
+You must start Pythonwin, and select 'Run' from the toolbar or File menu
+"""
+
+
+NeedAppMsg = """\
+This demo program is a 'Pythonwin Application'.
+
+It is more demo code than an example of Pythonwin's capabilities.
+
+To run it, you must execute the command:
+pythonwin.exe /app "%s"
+
+Would you like to execute it now?
+"""
+
+
+def NotAScript():
+ import win32ui
+
+ win32ui.MessageBox(NotScriptMsg, "Demos")
+
+
+def NeedGoodGUI():
+ from pywin.framework.app import HaveGoodGUI
+
+ rc = HaveGoodGUI()
+ if not rc:
+ win32ui.MessageBox(NeedGUIMsg, "Demos")
+ return rc
+
+
+def NeedApp():
+ import win32ui
+
+ rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO)
+ if rc == win32con.IDYES:
+ try:
+ parent = win32ui.GetMainFrame().GetSafeHwnd()
+ win32api.ShellExecute(
+ parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
+ )
+ except win32api.error as details:
+ win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
+
+
+if __name__ == "__main__":
+ NotAScript()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/dlgappdemo.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/dlgappdemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..e998d08a09417fa447e91369403fa7541bf2f724
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/dlgappdemo.py
@@ -0,0 +1,51 @@
+# dlgappdemo - a demo of a dialog application.
+# This is a demonstration of both a custom "application" module,
+# and a Python program in a dialog box.
+#
+# NOTE: You CAN NOT import this module from either PythonWin or Python.
+# This module must be specified on the commandline to PythonWin only.
+# eg, PythonWin /app dlgappdemo.py
+
+import sys
+
+import win32ui
+from pywin.framework import dlgappcore
+
+
+class TestDialogApp(dlgappcore.DialogApp):
+ def CreateDialog(self):
+ return TestAppDialog()
+
+
+class TestAppDialog(dlgappcore.AppDialog):
+ def __init__(self):
+ self.edit = None
+ dlgappcore.AppDialog.__init__(self, win32ui.IDD_LARGE_EDIT)
+
+ def OnInitDialog(self):
+ self.SetWindowText("Test dialog application")
+ self.edit = self.GetDlgItem(win32ui.IDC_EDIT1)
+ print("Hello from Python")
+ print("args are:", end=" ")
+ for arg in sys.argv:
+ print(arg)
+ return 1
+
+ def PreDoModal(self):
+ sys.stdout = sys.stderr = self
+
+ def write(self, str):
+ if self.edit:
+ self.edit.SetSel(-2)
+ # translate \n to \n\r
+ self.edit.ReplaceSel(str.replace("\n", "\r\n"))
+ else:
+ win32ui.OutputDebug("dlgapp - no edit control! >>\n%s\n<<\n" % str)
+
+
+app = TestDialogApp()
+
+if __name__ == "__main__":
+ import demoutils
+
+ demoutils.NeedApp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/dojobapp.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/dojobapp.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc8b4106694ce25cfea576a9d093cd3b74a6851b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/dojobapp.py
@@ -0,0 +1,71 @@
+# dojobapp - do a job, show the result in a dialog, and exit.
+#
+# Very simple - faily minimal dialog based app.
+#
+# This should be run using the command line:
+# pythonwin /app demos\dojobapp.py
+
+
+import win32con
+import win32ui
+from pywin.framework import dlgappcore
+
+
+class DoJobAppDialog(dlgappcore.AppDialog):
+ softspace = 1
+
+ def __init__(self, appName=""):
+ self.appName = appName
+ dlgappcore.AppDialog.__init__(self, win32ui.IDD_GENERAL_STATUS)
+
+ def PreDoModal(self):
+ pass
+
+ def ProcessArgs(self, args):
+ pass
+
+ def OnInitDialog(self):
+ self.SetWindowText(self.appName)
+ butCancel = self.GetDlgItem(win32con.IDCANCEL)
+ butCancel.ShowWindow(win32con.SW_HIDE)
+ p1 = self.GetDlgItem(win32ui.IDC_PROMPT1)
+ p2 = self.GetDlgItem(win32ui.IDC_PROMPT2)
+
+ # Do something here!
+
+ p1.SetWindowText("Hello there")
+ p2.SetWindowText("from the demo")
+
+ def OnDestroy(self, msg):
+ pass
+
+
+# def OnOK(self):
+# pass
+# def OnCancel(self): default behaviour - cancel == close.
+# return
+
+
+class DoJobDialogApp(dlgappcore.DialogApp):
+ def CreateDialog(self):
+ return DoJobAppDialog("Do Something")
+
+
+class CopyToDialogApp(DoJobDialogApp):
+ def __init__(self):
+ DoJobDialogApp.__init__(self)
+
+
+app = DoJobDialogApp()
+
+
+def t():
+ t = DoJobAppDialog("Copy To")
+ t.DoModal()
+ return t
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ demoutils.NeedApp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/helloapp.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/helloapp.py
new file mode 100644
index 0000000000000000000000000000000000000000..289016fbd8ce666929d0e12a781787322910c15e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/app/helloapp.py
@@ -0,0 +1,53 @@
+##
+## helloapp.py
+##
+##
+## A nice, small 'hello world' Pythonwin application.
+## NOT an MDI application - just a single, normal, top-level window.
+##
+## MUST be run with the command line "pythonwin.exe /app helloapp.py"
+## (or if you are really keen, rename "pythonwin.exe" to something else, then
+## using MSVC or similar, edit the string section in the .EXE to name this file)
+##
+## Originally by Willy Heineman
+
+
+import win32con
+import win32ui
+from pywin.mfc import window
+from pywin.mfc.thread import WinApp
+
+
+# The main frame.
+# Does almost nothing at all - doesn't even create a child window!
+class HelloWindow(window.Wnd):
+ def __init__(self):
+ # The window.Wnd ctor creates a Window object, and places it in
+ # self._obj_. Note the window object exists, but the window itself
+ # does not!
+ window.Wnd.__init__(self, win32ui.CreateWnd())
+
+ # Now we ask the window object to create the window itself.
+ self._obj_.CreateWindowEx(
+ win32con.WS_EX_CLIENTEDGE,
+ win32ui.RegisterWndClass(0, 0, win32con.COLOR_WINDOW + 1),
+ "Hello World!",
+ win32con.WS_OVERLAPPEDWINDOW,
+ (100, 100, 400, 300),
+ None,
+ 0,
+ None,
+ )
+
+
+# The application object itself.
+class HelloApp(WinApp):
+ def InitInstance(self):
+ self.frame = HelloWindow()
+ self.frame.ShowWindow(win32con.SW_SHOWNORMAL)
+ # We need to tell MFC what our main frame is.
+ self.SetMainFrame(self.frame)
+
+
+# Now create the application object itself!
+app = HelloApp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/cmdserver.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/cmdserver.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a20ee4735fb70e1a9752fd09105e8553b7c5319
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/cmdserver.py
@@ -0,0 +1,113 @@
+# cmdserver.py
+
+# Demo code that is not Pythonwin related, but too good to throw away...
+
+import _thread
+import sys
+import traceback
+
+import win32api
+from pywin.framework import winout
+
+
+class ThreadWriter:
+ "Assign an instance to sys.stdout for per-thread printing objects - Courtesy Guido!"
+
+ def __init__(self):
+ "Constructor -- initialize the table of writers"
+ self.writers = {}
+ self.origStdOut = None
+
+ def register(self, writer):
+ "Register the writer for the current thread"
+ self.writers[_thread.get_ident()] = writer
+ if self.origStdOut is None:
+ self.origStdOut = sys.stdout
+ sys.stdout = self
+
+ def unregister(self):
+ "Remove the writer for the current thread, if any"
+ try:
+ del self.writers[_thread.get_ident()]
+ except KeyError:
+ pass
+ if len(self.writers) == 0:
+ sys.stdout = self.origStdOut
+ self.origStdOut = None
+
+ def getwriter(self):
+ "Return the current thread's writer, default sys.stdout"
+ self.writers.get(_thread.get_ident(), self.origStdOut)
+
+ def write(self, str):
+ "Write to the current thread's writer, default sys.stdout"
+ self.getwriter().write(str)
+
+
+def Test():
+ num = 1
+ while num < 1000:
+ print("Hello there no", num)
+ win32api.Sleep(50)
+ num += 1
+
+
+class flags:
+ SERVER_BEST = 0
+ SERVER_IMMEDIATE = 1
+ SERVER_THREAD = 2
+ SERVER_PROCESS = 3
+
+
+def StartServer(cmd, title=None, bCloseOnEnd=0, serverFlags=flags.SERVER_BEST):
+ out = winout.WindowOutput(title, None, winout.flags.WQ_IDLE)
+ if not title:
+ title = cmd
+ out.Create(title)
+ # ServerThread((out, cmd, title, bCloseOnEnd))
+ # out = sys.stdout
+ _thread.start_new_thread(ServerThread, (out, cmd, title, bCloseOnEnd))
+
+
+def ServerThread(myout, cmd, title, bCloseOnEnd):
+ try:
+ writer.register(myout)
+ print('Executing "%s"\n' % cmd)
+ bOK = 1
+ try:
+ import __main__
+
+ exec(cmd + "\n", __main__.__dict__)
+ except:
+ bOK = 0
+ if bOK:
+ print("Command terminated without errors.")
+ else:
+ t, v, tb = sys.exc_info()
+ print(t, ": ", v)
+ traceback.print_tb(tb)
+ tb = None # prevent a cycle
+ print("Command terminated with an unhandled exception")
+ writer.unregister()
+ if bOK and bCloseOnEnd:
+ myout.frame.DestroyWindow()
+
+ # Unhandled exception of any kind in a thread kills the gui!
+ except:
+ t, v, tb = sys.exc_info()
+ print(t, ": ", v)
+ traceback.print_tb(tb)
+ tb = None
+ print("Thread failed")
+
+
+# assist for reloading (when debugging) - use only 1 tracer object,
+# else a large chain of tracer objects will exist.
+try:
+ writer
+except NameError:
+ writer = ThreadWriter()
+if __name__ == "__main__":
+ import demoutils
+
+ demoutils.NotAScript()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/createwin.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/createwin.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e42886a82504408db8428e3e00f6bb870880206
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/createwin.py
@@ -0,0 +1,114 @@
+#
+# Window creation example
+#
+# This example creates a minimal "control" that just fills in its
+# window with red. To make your own control, subclass Control and
+# write your own OnPaint() method. See PyCWnd.HookMessage for what
+# the parameters to OnPaint are.
+#
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog, window
+
+
+class Control(window.Wnd):
+ """Generic control class"""
+
+ def __init__(self):
+ window.Wnd.__init__(self, win32ui.CreateWnd())
+
+ def OnPaint(self):
+ dc, paintStruct = self.BeginPaint()
+ self.DoPaint(dc)
+ self.EndPaint(paintStruct)
+
+ def DoPaint(self, dc): # Override this!
+ pass
+
+
+class RedBox(Control):
+ def DoPaint(self, dc):
+ dc.FillSolidRect(self.GetClientRect(), win32api.RGB(255, 0, 0))
+
+
+class RedBoxWithPie(RedBox):
+ def DoPaint(self, dc):
+ RedBox.DoPaint(self, dc)
+ r = self.GetClientRect()
+ dc.Pie(r[0], r[1], r[2], r[3], 0, 0, r[2], r[3] // 2)
+
+
+def MakeDlgTemplate():
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+
+ w = 64
+ h = 64
+
+ dlg = [
+ ["Red box", (0, 0, w, h), style, None, (8, "MS Sans Serif")],
+ ]
+
+ s = win32con.WS_TABSTOP | cs
+
+ dlg.append(
+ [
+ 128,
+ "Cancel",
+ win32con.IDCANCEL,
+ (7, h - 18, 50, 14),
+ s | win32con.BS_PUSHBUTTON,
+ ]
+ )
+
+ return dlg
+
+
+class TestDialog(dialog.Dialog):
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.redbox = RedBox()
+ self.redbox.CreateWindow(
+ None,
+ "RedBox",
+ win32con.WS_CHILD | win32con.WS_VISIBLE,
+ (5, 5, 90, 68),
+ self,
+ 1003,
+ )
+ return rc
+
+
+class TestPieDialog(dialog.Dialog):
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.control = RedBoxWithPie()
+ self.control.CreateWindow(
+ None,
+ "RedBox with Pie",
+ win32con.WS_CHILD | win32con.WS_VISIBLE,
+ (5, 5, 90, 68),
+ self,
+ 1003,
+ )
+
+
+def demo(modal=0):
+ d = TestPieDialog(MakeDlgTemplate())
+ if modal:
+ d.DoModal()
+ else:
+ d.CreateWindow()
+
+
+if __name__ == "__main__":
+ demo(1)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/demoutils.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/demoutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..d87a01c4c0aec677199e7b992e258ca177856aa9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/demoutils.py
@@ -0,0 +1,65 @@
+# Utilities for the demos
+
+import sys
+
+import win32api
+import win32con
+import win32ui
+
+NotScriptMsg = """\
+This demo program is not designed to be run as a Script, but is
+probably used by some other test program. Please try another demo.
+"""
+
+NeedGUIMsg = """\
+This demo program can only be run from inside of Pythonwin
+
+You must start Pythonwin, and select 'Run' from the toolbar or File menu
+"""
+
+
+NeedAppMsg = """\
+This demo program is a 'Pythonwin Application'.
+
+It is more demo code than an example of Pythonwin's capabilities.
+
+To run it, you must execute the command:
+pythonwin.exe /app "%s"
+
+Would you like to execute it now?
+"""
+
+
+def NotAScript():
+ import win32ui
+
+ win32ui.MessageBox(NotScriptMsg, "Demos")
+
+
+def NeedGoodGUI():
+ from pywin.framework.app import HaveGoodGUI
+
+ rc = HaveGoodGUI()
+ if not rc:
+ win32ui.MessageBox(NeedGUIMsg, "Demos")
+ return rc
+
+
+def NeedApp():
+ import win32ui
+
+ rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO)
+ if rc == win32con.IDYES:
+ try:
+ parent = win32ui.GetMainFrame().GetSafeHwnd()
+ win32api.ShellExecute(
+ parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
+ )
+ except win32api.error as details:
+ win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ demoutils.NotAScript()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dibdemo.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dibdemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7943a3a64bc840b052486bf54b3728279150801
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dibdemo.py
@@ -0,0 +1,73 @@
+# A demo which creates a view and a frame which displays a PPM format bitmap
+#
+# This hasnnt been run in a while, as I don't have many of that format around!
+
+import win32api
+import win32con
+import win32ui
+
+
+class DIBView:
+ def __init__(self, doc, dib):
+ self.dib = dib
+ self.view = win32ui.CreateView(doc)
+ self.width = self.height = 0
+ # set up message handlers
+ # self.view.OnPrepareDC = self.OnPrepareDC
+ self.view.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ def OnSize(self, params):
+ lParam = params[3]
+ self.width = win32api.LOWORD(lParam)
+ self.height = win32api.HIWORD(lParam)
+
+ def OnDraw(self, ob, dc):
+ # set sizes used for "non strecth" mode.
+ self.view.SetScrollSizes(win32con.MM_TEXT, self.dib.GetSize())
+ dibSize = self.dib.GetSize()
+ dibRect = (0, 0, dibSize[0], dibSize[1])
+ # stretch BMP.
+ # self.dib.Paint(dc, (0,0,self.width, self.height),dibRect)
+ # non stretch.
+ self.dib.Paint(dc)
+
+
+class DIBDemo:
+ def __init__(self, filename, *bPBM):
+ # init data members
+ f = open(filename, "rb")
+ dib = win32ui.CreateDIBitmap()
+ if len(bPBM) > 0:
+ magic = f.readline()
+ if magic != "P6\n":
+ print("The file is not a PBM format file")
+ raise ValueError("Failed - The file is not a PBM format file")
+ # check magic?
+ rowcollist = f.readline().split()
+ cols = int(rowcollist[0])
+ rows = int(rowcollist[1])
+ f.readline() # what's this one?
+ dib.LoadPBMData(f, (cols, rows))
+ else:
+ dib.LoadWindowsFormatFile(f)
+ f.close()
+ # create doc/view
+ self.doc = win32ui.CreateDoc()
+ self.dibView = DIBView(self.doc, dib)
+ self.frame = win32ui.CreateMDIFrame()
+ self.frame.LoadFrame() # this will force OnCreateClient
+ self.doc.SetTitle("DIB Demo")
+ self.frame.ShowWindow()
+
+ # display the sucka
+ self.frame.ActivateFrame()
+
+ def OnCreateClient(self, createparams, context):
+ self.dibView.view.CreateWindow(self.frame)
+ return 1
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ demoutils.NotAScript()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dlgtest.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dlgtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4d5a9e30a6a4314a7c446c87e3e465108dd6d91
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dlgtest.py
@@ -0,0 +1,145 @@
+# A Demo of Pythonwin's Dialog and Property Page support.
+
+###################
+#
+# First demo - use the built-in to Pythonwin "Tab Stop" dialog, but
+# customise it heavily.
+#
+# ID's for the tabstop dialog - out test.
+#
+import win32con
+import win32ui
+from pywin.mfc import dialog
+from win32con import IDCANCEL
+from win32ui import IDC_EDIT_TABS, IDC_PROMPT_TABS, IDD_SET_TABSTOPS
+
+
+class TestDialog(dialog.Dialog):
+ def __init__(self, modal=1):
+ dialog.Dialog.__init__(self, IDD_SET_TABSTOPS)
+ self.counter = 0
+ if modal:
+ self.DoModal()
+ else:
+ self.CreateWindow()
+
+ def OnInitDialog(self):
+ # Set the caption of the dialog itself.
+ self.SetWindowText("Used to be Tab Stops!")
+ # Get a child control, remember it, and change its text.
+ self.edit = self.GetDlgItem(IDC_EDIT_TABS) # the text box.
+ self.edit.SetWindowText("Test")
+ # Hook a Windows message for the dialog.
+ self.edit.HookMessage(self.KillFocus, win32con.WM_KILLFOCUS)
+ # Get the prompt control, and change its next.
+ prompt = self.GetDlgItem(IDC_PROMPT_TABS) # the prompt box.
+ prompt.SetWindowText("Prompt")
+ # And the same for the button..
+ cancel = self.GetDlgItem(IDCANCEL) # the cancel button
+ cancel.SetWindowText("&Kill me")
+
+ # And just for demonstration purposes, we hook the notify message for the dialog.
+ # This allows us to be notified when the Edit Control text changes.
+ self.HookCommand(self.OnNotify, IDC_EDIT_TABS)
+
+ def OnNotify(self, controlid, code):
+ if code == win32con.EN_CHANGE:
+ print("Edit text changed!")
+ return 1 # I handled this, so no need to call defaults!
+
+ # kill focus for the edit box.
+ # Simply increment the value in the text box.
+ def KillFocus(self, msg):
+ self.counter += 1
+ if self.edit is not None:
+ self.edit.SetWindowText(str(self.counter))
+
+ # Called when the dialog box is terminating...
+ def OnDestroy(self, msg):
+ del self.edit
+ del self.counter
+
+
+# A very simply Property Sheet.
+# We only make a new class for demonstration purposes.
+class TestSheet(dialog.PropertySheet):
+ def __init__(self, title):
+ dialog.PropertySheet.__init__(self, title)
+ self.HookMessage(self.OnActivate, win32con.WM_ACTIVATE)
+
+ def OnActivate(self, msg):
+ pass
+
+
+# A very simply Property Page, which will be "owned" by the above
+# Property Sheet.
+# We create a new class, just so we can hook a control notification.
+class TestPage(dialog.PropertyPage):
+ def OnInitDialog(self):
+ # We use the HookNotify function to allow Python to respond to
+ # Windows WM_NOTIFY messages.
+ # In this case, we are interested in BN_CLICKED messages.
+ self.HookNotify(self.OnNotify, win32con.BN_CLICKED)
+
+ def OnNotify(self, std, extra):
+ print("OnNotify", std, extra)
+
+
+# Some code that actually uses these objects.
+def demo(modal=0):
+ TestDialog(modal)
+
+ # property sheet/page demo
+ ps = win32ui.CreatePropertySheet("Property Sheet/Page Demo")
+ # Create a completely standard PropertyPage.
+ page1 = win32ui.CreatePropertyPage(win32ui.IDD_PROPDEMO1)
+ # Create our custom property page.
+ page2 = TestPage(win32ui.IDD_PROPDEMO2)
+ ps.AddPage(page1)
+ ps.AddPage(page2)
+ if modal:
+ ps.DoModal()
+ else:
+ style = (
+ win32con.WS_SYSMENU
+ | win32con.WS_POPUP
+ | win32con.WS_CAPTION
+ | win32con.DS_MODALFRAME
+ | win32con.WS_VISIBLE
+ )
+ styleex = win32con.WS_EX_DLGMODALFRAME | win32con.WS_EX_PALETTEWINDOW
+ ps.CreateWindow(win32ui.GetMainFrame(), style, styleex)
+
+
+def test(modal=1):
+ # dlg=dialog.Dialog(1010)
+ # dlg.CreateWindow()
+ # dlg.EndDialog(0)
+ # del dlg
+ # return
+ # property sheet/page demo
+ ps = TestSheet("Property Sheet/Page Demo")
+ page1 = win32ui.CreatePropertyPage(win32ui.IDD_PROPDEMO1)
+ page2 = win32ui.CreatePropertyPage(win32ui.IDD_PROPDEMO2)
+ ps.AddPage(page1)
+ ps.AddPage(page2)
+ del page1
+ del page2
+ if modal:
+ ps.DoModal()
+ else:
+ ps.CreateWindow(win32ui.GetMainFrame())
+ return ps
+
+
+def d():
+ dlg = win32ui.CreateDialog(win32ui.IDD_DEBUGGER)
+ dlg.datalist.append((win32ui.IDC_DBG_RADIOSTACK, "radio"))
+ print("data list is ", dlg.datalist)
+ dlg.data["radio"] = 1
+ dlg.DoModal()
+ print(dlg.data["radio"])
+
+
+if __name__ == "__main__":
+ demo(1)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dyndlg.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dyndlg.py
new file mode 100644
index 0000000000000000000000000000000000000000..6660435bb76d71589bc1cf2c12fc3196778d09e3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/dyndlg.py
@@ -0,0 +1,104 @@
+# dyndlg.py
+# contributed by Curt Hagenlocher
+
+# Dialog Template params:
+# Parameter 0 - Window caption
+# Parameter 1 - Bounds (rect tuple)
+# Parameter 2 - Window style
+# Parameter 3 - Extended style
+# Parameter 4 - Font tuple
+# Parameter 5 - Menu name
+# Parameter 6 - Window class
+# Dialog item params:
+# Parameter 0 - Window class
+# Parameter 1 - Text
+# Parameter 2 - ID
+# Parameter 3 - Bounds
+# Parameter 4 - Style
+# Parameter 5 - Extended style
+# Parameter 6 - Extra data
+
+
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+
+def MakeDlgTemplate():
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+ dlg = [
+ ["Select Warehouse", (0, 0, 177, 93), style, None, (8, "MS Sans Serif")],
+ ]
+ dlg.append([130, "Current Warehouse:", -1, (7, 7, 69, 9), cs | win32con.SS_LEFT])
+ dlg.append([130, "ASTORIA", 128, (16, 17, 99, 7), cs | win32con.SS_LEFT])
+ dlg.append([130, "New &Warehouse:", -1, (7, 29, 69, 9), cs | win32con.SS_LEFT])
+ s = win32con.WS_TABSTOP | cs
+ # dlg.append([131, None, 130, (5, 40, 110, 48),
+ # s | win32con.LBS_NOTIFY | win32con.LBS_SORT | win32con.LBS_NOINTEGRALHEIGHT | win32con.WS_VSCROLL | win32con.WS_BORDER])
+ dlg.append(
+ [
+ "{8E27C92B-1264-101C-8A2F-040224009C02}",
+ None,
+ 131,
+ (5, 40, 110, 48),
+ win32con.WS_TABSTOP,
+ ]
+ )
+
+ dlg.append(
+ [128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]
+ )
+ s = win32con.BS_PUSHBUTTON | s
+ dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 22, 50, 14), s])
+ dlg.append([128, "&Help", 100, (124, 74, 50, 14), s])
+
+ return dlg
+
+
+def test1():
+ win32ui.CreateDialogIndirect(MakeDlgTemplate()).DoModal()
+
+
+def test2():
+ dialog.Dialog(MakeDlgTemplate()).DoModal()
+
+
+def test3():
+ dlg = win32ui.LoadDialogResource(win32ui.IDD_SET_TABSTOPS)
+ dlg[0][0] = "New Dialog Title"
+ dlg[0][1] = (80, 20, 161, 60)
+ dlg[1][1] = "&Confusion:"
+ cs = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | win32con.WS_TABSTOP
+ | win32con.BS_PUSHBUTTON
+ )
+ dlg.append([128, "&Help", 100, (111, 41, 40, 14), cs])
+ dialog.Dialog(dlg).DoModal()
+
+
+def test4():
+ page1 = dialog.PropertyPage(win32ui.LoadDialogResource(win32ui.IDD_PROPDEMO1))
+ page2 = dialog.PropertyPage(win32ui.LoadDialogResource(win32ui.IDD_PROPDEMO2))
+ ps = dialog.PropertySheet("Property Sheet/Page Demo", None, [page1, page2])
+ ps.DoModal()
+
+
+def testall():
+ test1()
+ test2()
+ test3()
+ test4()
+
+
+if __name__ == "__main__":
+ testall()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/fontdemo.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/fontdemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..31304ef9d6a3738235f219b206ec7476abe3eac4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/fontdemo.py
@@ -0,0 +1,85 @@
+# Demo of Generic document windows, DC, and Font usage
+# by Dave Brennan (brennan@hal.com)
+
+# usage examples:
+
+# >>> from fontdemo import *
+# >>> d = FontDemo('Hello, Python')
+# >>> f1 = { 'name':'Arial', 'height':36, 'weight':win32con.FW_BOLD}
+# >>> d.SetFont(f1)
+# >>> f2 = {'name':'Courier New', 'height':24, 'italic':1}
+# >>> d.SetFont (f2)
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import docview
+
+# font is a dictionary in which the following elements matter:
+# (the best matching font to supplied parameters is returned)
+# name string name of the font as known by Windows
+# size point size of font in logical units
+# weight weight of font (win32con.FW_NORMAL, win32con.FW_BOLD)
+# italic boolean; true if set to anything but None
+# underline boolean; true if set to anything but None
+
+
+class FontView(docview.ScrollView):
+ def __init__(
+ self, doc, text="Python Rules!", font_spec={"name": "Arial", "height": 42}
+ ):
+ docview.ScrollView.__init__(self, doc)
+ self.font = win32ui.CreateFont(font_spec)
+ self.text = text
+ self.width = self.height = 0
+ # set up message handlers
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ def OnAttachedObjectDeath(self):
+ docview.ScrollView.OnAttachedObjectDeath(self)
+ del self.font
+
+ def SetFont(self, new_font):
+ # Change font on the fly
+ self.font = win32ui.CreateFont(new_font)
+ # redraw the entire client window
+ self.InvalidateRect(None)
+
+ def OnSize(self, params):
+ lParam = params[3]
+ self.width = win32api.LOWORD(lParam)
+ self.height = win32api.HIWORD(lParam)
+
+ def OnPrepareDC(self, dc, printinfo):
+ # Set up the DC for forthcoming OnDraw call
+ self.SetScrollSizes(win32con.MM_TEXT, (100, 100))
+ dc.SetTextColor(win32api.RGB(0, 0, 255))
+ dc.SetBkColor(win32api.GetSysColor(win32con.COLOR_WINDOW))
+ dc.SelectObject(self.font)
+ dc.SetTextAlign(win32con.TA_CENTER | win32con.TA_BASELINE)
+
+ def OnDraw(self, dc):
+ if self.width == 0 and self.height == 0:
+ left, top, right, bottom = self.GetClientRect()
+ self.width = right - left
+ self.height = bottom - top
+ x, y = self.width // 2, self.height // 2
+ dc.TextOut(x, y, self.text)
+
+
+def FontDemo():
+ # create doc/view
+ template = docview.DocTemplate(win32ui.IDR_PYTHONTYPE, None, None, FontView)
+ doc = template.OpenDocumentFile(None)
+ doc.SetTitle("Font Demo")
+ # print("template is ", template, "obj is", template._obj_)
+ template.close()
+ # print("closed")
+ # del template
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ FontDemo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/guidemo.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/guidemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..29489b501b6cc22aa69e8fd5096c134ffc28eb71
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/guidemo.py
@@ -0,0 +1,53 @@
+# GUI Demo - just a worker script to invoke all the other demo/test scripts.
+import sys
+
+import __main__
+import pywin.dialogs.list
+
+demos = [
+ ("Font", "import fontdemo;fontdemo.FontDemo()"),
+ ("Open GL Demo", "import openGLDemo;openGLDemo.test()"),
+ ("Threaded GUI", "import threadedgui;threadedgui.ThreadedDemo()"),
+ ("Tree View Demo", "import hiertest;hiertest.demoboth()"),
+ ("3-Way Splitter Window", "import splittst;splittst.demo()"),
+ ("Custom Toolbars and Tooltips", "import toolbar;toolbar.test()"),
+ ("Progress Bar", "import progressbar;progressbar.demo()"),
+ ("Slider Control", "import sliderdemo;sliderdemo.demo()"),
+ ("Dynamic window creation", "import createwin;createwin.demo()"),
+ ("Various Dialog demos", "import dlgtest;dlgtest.demo()"),
+ ("OCX Control Demo", "from ocx import ocxtest;ocxtest.demo()"),
+ ("OCX Serial Port Demo", "from ocx import ocxserialtest; ocxserialtest.test()"),
+ (
+ "Internet Explorer Control Demo",
+ 'from ocx import webbrowser; webbrowser.Demo("https://www.python.org")',
+ ),
+]
+
+
+def _exec_demo(cmd):
+ try:
+ exec(cmd)
+ except Exception as error:
+ print(f"Demo of {cmd} failed - {type(error)}:{error}")
+
+
+def demo():
+ if "/go" in sys.argv:
+ for name, cmd in demos:
+ _exec_demo(cmd)
+ return
+
+ # Otherwise allow the user to select the demo to run
+ while True:
+ rc = pywin.dialogs.list.SelectFromLists("Select a Demo", demos, ["Demo Title"])
+ if rc is None:
+ break
+ title, cmd = demos[rc]
+ _exec_demo(cmd)
+
+
+if __name__ == __main__.__name__:
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/hiertest.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/hiertest.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebced0ca9f8f1247fd7ddcfc479ee4e33717549e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/hiertest.py
@@ -0,0 +1,138 @@
+import os
+
+import commctrl
+import win32ui
+from pywin.mfc import docview, window
+from pywin.tools import hierlist
+
+
+# directory listbox
+# This has obvious limitations - doesn't track subdirs, etc. Demonstrates
+# simple use of Python code for querying the tree as needed.
+# Only use strings, and lists of strings (from curdir())
+class DirHierList(hierlist.HierList):
+ def __init__(self, root, listBoxID=win32ui.IDC_LIST1):
+ hierlist.HierList.__init__(self, root, win32ui.IDB_HIERFOLDERS, listBoxID)
+
+ def GetText(self, item):
+ return os.path.basename(item)
+
+ def GetSubList(self, item):
+ if os.path.isdir(item):
+ ret = [os.path.join(item, fname) for fname in os.listdir(item)]
+ else:
+ ret = None
+ return ret
+
+ # if the item is a dir, it is expandable.
+ def IsExpandable(self, item):
+ return os.path.isdir(item)
+
+ def GetSelectedBitmapColumn(self, item):
+ return self.GetBitmapColumn(item) + 6 # Use different color for selection
+
+
+class TestDocument(docview.Document):
+ def __init__(self, template):
+ docview.Document.__init__(self, template)
+ self.hierlist = hierlist.HierListWithItems(
+ HLIFileDir("\\"), win32ui.IDB_HIERFOLDERS, win32ui.AFX_IDW_PANE_FIRST
+ )
+
+
+class HierListView(docview.TreeView):
+ def OnInitialUpdate(self):
+ rc = self._obj_.OnInitialUpdate()
+ self.hierList = self.GetDocument().hierlist
+ self.hierList.HierInit(self.GetParent())
+ self.hierList.SetStyle(
+ commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS
+ )
+ return rc
+
+
+class HierListFrame(window.MDIChildWnd):
+ pass
+
+
+def GetTestRoot():
+ tree1 = ("Tree 1", [("Item 1", "Item 1 data"), "Item 2", 3])
+ tree2 = ("Tree 2", [("Item 2.1", "Item 2 data"), "Item 2.2", 2.3])
+ return ("Root", [tree1, tree2, "Item 3"])
+
+
+def demoboth():
+ template = docview.DocTemplate(
+ win32ui.IDR_PYTHONTYPE, TestDocument, HierListFrame, HierListView
+ )
+ template.OpenDocumentFile(None).SetTitle("Hierlist demo")
+
+ demomodeless()
+
+
+def demomodeless():
+ testList2 = DirHierList("\\")
+ dlg = hierlist.HierDialog("hier list test", testList2)
+ dlg.CreateWindow()
+
+
+def demodlg():
+ testList2 = DirHierList("\\")
+ dlg = hierlist.HierDialog("hier list test", testList2)
+ dlg.DoModal()
+
+
+def demo():
+ template = docview.DocTemplate(
+ win32ui.IDR_PYTHONTYPE, TestDocument, HierListFrame, HierListView
+ )
+ template.OpenDocumentFile(None).SetTitle("Hierlist demo")
+
+
+#
+# Demo/Test for HierList items.
+#
+# Easy to make a better directory program.
+#
+class HLIFileDir(hierlist.HierListItem):
+ def __init__(self, filename):
+ self.filename = filename
+ hierlist.HierListItem.__init__(self)
+
+ def GetText(self):
+ try:
+ return "%-20s %d bytes" % (
+ os.path.basename(self.filename),
+ os.stat(self.filename)[6],
+ )
+ except OSError as details:
+ return "%-20s - %s" % (self.filename, details[1])
+
+ def IsExpandable(self):
+ return os.path.isdir(self.filename)
+
+ def GetSubList(self):
+ ret = []
+ for newname in os.listdir(self.filename):
+ if newname not in (".", ".."):
+ ret.append(HLIFileDir(os.path.join(self.filename, newname)))
+ return ret
+
+
+def demohli():
+ template = docview.DocTemplate(
+ win32ui.IDR_PYTHONTYPE,
+ TestDocument,
+ hierlist.HierListFrame,
+ hierlist.HierListView,
+ )
+ template.OpenDocumentFile(None).SetTitle("Hierlist demo")
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.HaveGoodGUI():
+ demoboth()
+ else:
+ demodlg()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/menutest.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/menutest.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e3236fb7a32aa8084c757d1fa3172a4eeb6c815
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/menutest.py
@@ -0,0 +1,13 @@
+# Run this as a python script, to gray "close" off the edit window system menu.
+import win32con
+from pywin.framework import interact
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ win = interact.edit.currentView.GetParent()
+ menu = win.GetSystemMenu()
+ id = menu.GetMenuItemID(6)
+ menu.EnableMenuItem(id, win32con.MF_BYCOMMAND | win32con.MF_GRAYED)
+ print("The interactive window's 'Close' menu item is now disabled.")
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/objdoc.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/objdoc.py
new file mode 100644
index 0000000000000000000000000000000000000000..220b33b2df162f89a11a9e3037300f6cabfcabaf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/objdoc.py
@@ -0,0 +1,57 @@
+# This is a sample file, and shows the basic framework for using an "Object" based
+# document, rather than a "filename" based document.
+# This is referenced by the Pythonwin .html documentation.
+
+# In the example below, the OpenObject() method is used instead of OpenDocumentFile,
+# and all the core MFC document open functionality is retained.
+
+import win32ui
+from pywin.mfc import docview
+
+
+class object_template(docview.DocTemplate):
+ def __init__(self):
+ docview.DocTemplate.__init__(self, None, None, None, object_view)
+
+ def OpenObject(self, object): # Use this instead of OpenDocumentFile.
+ # Look for existing open document
+ for doc in self.GetDocumentList():
+ print("document is ", doc)
+ if doc.object is object:
+ doc.GetFirstView().ActivateFrame()
+ return doc
+ # not found - new one.
+ doc = object_document(self, object)
+ frame = self.CreateNewFrame(doc)
+ doc.OnNewDocument()
+ doc.SetTitle(str(object))
+ self.InitialUpdateFrame(frame, doc)
+ return doc
+
+
+class object_document(docview.Document):
+ def __init__(self, template, object):
+ docview.Document.__init__(self, template)
+ self.object = object
+
+ def OnOpenDocument(self, name):
+ raise RuntimeError("Should not be called if template strings set up correctly")
+ return 0
+
+
+class object_view(docview.EditView):
+ def OnInitialUpdate(self):
+ self.ReplaceSel(f"Object is {self.GetDocument().object!r}")
+
+
+def demo():
+ t = object_template()
+ d = t.OpenObject(win32ui)
+ return (t, d)
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/demoutils.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/demoutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b17ff4aebdd5ae838db201c883e24aafdc163ce6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/demoutils.py
@@ -0,0 +1,63 @@
+# Utilities for the demos
+
+import sys
+
+import win32api
+import win32con
+import win32ui
+
+NotScriptMsg = """\
+This demo program is not designed to be run as a Script, but is
+probably used by some other test program. Please try another demo.
+"""
+
+NeedGUIMsg = """\
+This demo program can only be run from inside of Pythonwin
+
+You must start Pythonwin, and select 'Run' from the toolbar or File menu
+"""
+
+
+NeedAppMsg = """\
+This demo program is a 'Pythonwin Application'.
+
+It is more demo code than an example of Pythonwin's capabilities.
+
+To run it, you must execute the command:
+pythonwin.exe /app "%s"
+
+Would you like to execute it now?
+"""
+
+
+def NotAScript():
+ import win32ui
+
+ win32ui.MessageBox(NotScriptMsg, "Demos")
+
+
+def NeedGoodGUI():
+ from pywin.framework.app import HaveGoodGUI
+
+ rc = HaveGoodGUI()
+ if not rc:
+ win32ui.MessageBox(NeedGUIMsg, "Demos")
+ return rc
+
+
+def NeedApp():
+ import win32ui
+
+ rc = win32ui.MessageBox(NeedAppMsg % sys.argv[0], "Demos", win32con.MB_YESNO)
+ if rc == win32con.IDYES:
+ try:
+ parent = win32ui.GetMainFrame().GetSafeHwnd()
+ win32api.ShellExecute(
+ parent, None, "pythonwin.exe", '/app "%s"' % sys.argv[0], None, 1
+ )
+ except win32api.error as details:
+ win32ui.MessageBox("Error executing command - %s" % (details), "Demos")
+
+
+if __name__ == "__main__":
+ NotAScript()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/flash.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/flash.py
new file mode 100644
index 0000000000000000000000000000000000000000..37ad73ded1ed5ff1f1f1587e284eb5d7dc7be1cf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/flash.py
@@ -0,0 +1,95 @@
+# By Bradley Schatz
+# simple flash/python application demonstrating bidirectional
+# communicaion between flash and python. Click the sphere to see
+# behavior. Uses Bounce.swf from FlashBounce.zip, available from
+# https://cspages.ucalgary.ca/~saul/vb_examples/tutorial12/
+
+# Update to the path of the .swf file (note it could be a true URL)
+flash_url = "c:\\bounce.swf"
+
+import sys
+
+import regutil
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import activex, window
+from win32com.client import gencache
+
+FlashModule = gencache.EnsureModule("{D27CDB6B-AE6D-11CF-96B8-444553540000}", 0, 1, 0)
+
+if FlashModule is None:
+ raise ImportError("Flash does not appear to be installed.")
+
+
+class MyFlashComponent(activex.Control, FlashModule.ShockwaveFlash):
+ def __init__(self):
+ activex.Control.__init__(self)
+ FlashModule.ShockwaveFlash.__init__(self)
+ self.x = 50
+ self.y = 50
+ self.angle = 30
+ self.started = 0
+
+ def OnFSCommand(self, command, args):
+ print("FSCommend", command, args)
+ self.x += 20
+ self.y += 20
+ self.angle += 20
+ if self.x > 200 or self.y > 200:
+ self.x = 0
+ self.y = 0
+ if self.angle > 360:
+ self.angle = 0
+ self.SetVariable("xVal", self.x)
+ self.SetVariable("yVal", self.y)
+ self.SetVariable("angle", self.angle)
+ self.TPlay("_root.mikeBall")
+
+ def OnProgress(self, percentDone):
+ print("PercentDone", percentDone)
+
+ def OnReadyStateChange(self, newState):
+ # 0=Loading, 1=Uninitialized, 2=Loaded, 3=Interactive, 4=Complete
+ print("State", newState)
+
+
+class BrowserFrame(window.MDIChildWnd):
+ def __init__(self, url=None):
+ if url is None:
+ self.url = regutil.GetRegisteredHelpFile("Main Python Documentation")
+ else:
+ self.url = url
+ pass # Don't call base class doc/view version...
+
+ def Create(self, title, rect=None, parent=None):
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
+ self._obj_ = win32ui.CreateMDIChild()
+ self._obj_.AttachObject(self)
+ self._obj_.CreateWindow(None, title, style, rect, parent)
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.ocx = MyFlashComponent()
+ self.ocx.CreateControl(
+ "Flash Player", win32con.WS_VISIBLE | win32con.WS_CHILD, rect, self, 1000
+ )
+ self.ocx.LoadMovie(0, flash_url)
+ self.ocx.Play()
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ def OnSize(self, params):
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.ocx.SetWindowPos(0, rect, 0)
+
+
+def Demo():
+ url = None
+ if len(sys.argv) > 1:
+ url = win32api.GetFullPathName(sys.argv[1])
+ f = BrowserFrame(url)
+ f.Create("Flash Player")
+
+
+if __name__ == "__main__":
+ Demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/msoffice.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/msoffice.py
new file mode 100644
index 0000000000000000000000000000000000000000..3de155bdd3342b147715d691acea46fadba75df1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/msoffice.py
@@ -0,0 +1,159 @@
+# This demo uses some of the Microsoft Office components.
+#
+# It was taken from an MSDN article showing how to embed excel.
+# It is not comlpete yet, but it _does_ show an Excel spreadsheet in a frame!
+#
+
+import win32con
+import win32ui
+import win32uiole
+from pywin.mfc import activex, docview, object, window
+from win32com.client import gencache
+
+
+class OleClientItem(object.CmdTarget):
+ def __init__(self, doc):
+ object.CmdTarget.__init__(self, win32uiole.CreateOleClientItem(doc))
+
+ def OnGetItemPosition(self):
+ # For now return a hard-coded rect.
+ return (10, 10, 210, 210)
+
+ def OnActivate(self):
+ # Allow only one inplace activate item per frame
+ view = self.GetActiveView()
+ item = self.GetDocument().GetInPlaceActiveItem(view)
+ if item is not None and item._obj_ != self._obj_:
+ item.Close()
+ self._obj_.OnActivate()
+
+ def OnChange(self, oleNotification, dwParam):
+ self._obj_.OnChange(oleNotification, dwParam)
+ self.GetDocument().UpdateAllViews(None)
+
+ def OnChangeItemPosition(self, rect):
+ # During in-place activation CEmbed_ExcelCntrItem::OnChangeItemPosition
+ # is called by the server to change the position of the in-place
+ # window. Usually, this is a result of the data in the server
+ # document changing such that the extent has changed or as a result
+ # of in-place resizing.
+ #
+ # The default here is to call the base class, which will call
+ # COleClientItem::SetItemRects to move the item
+ # to the new position.
+ if not self._obj_.OnChangeItemPosition(self, rect):
+ return 0
+
+ # TODO: update any cache you may have of the item's rectangle/extent
+ return 1
+
+
+class OleDocument(object.CmdTarget):
+ def __init__(self, template):
+ object.CmdTarget.__init__(self, win32uiole.CreateOleDocument(template))
+ self.EnableCompoundFile()
+
+
+class ExcelView(docview.ScrollView):
+ def OnInitialUpdate(self):
+ self.HookMessage(self.OnSetFocus, win32con.WM_SETFOCUS)
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ self.SetScrollSizes(win32con.MM_TEXT, (100, 100))
+ rc = self._obj_.OnInitialUpdate()
+ self.EmbedExcel()
+ return rc
+
+ def EmbedExcel(self):
+ doc = self.GetDocument()
+ self.clientItem = OleClientItem(doc)
+ self.clientItem.CreateNewItem("Excel.Sheet")
+ self.clientItem.DoVerb(-1, self)
+ doc.UpdateAllViews(None)
+
+ def OnDraw(self, dc):
+ doc = self.GetDocument()
+ pos = doc.GetStartPosition()
+ clientItem, pos = doc.GetNextItem(pos)
+ clientItem.Draw(dc, (10, 10, 210, 210))
+
+ # Special handling of OnSetFocus and OnSize are required for a container
+ # when an object is being edited in-place.
+ def OnSetFocus(self, msg):
+ item = self.GetDocument().GetInPlaceActiveItem(self)
+ if (
+ item is not None
+ and item.GetItemState() == win32uiole.COleClientItem_activeUIState
+ ):
+ wnd = item.GetInPlaceWindow()
+ if wnd is not None:
+ wnd.SetFocus()
+ return 0 # Don't get the base version called.
+ return 1 # Call the base version.
+
+ def OnSize(self, params):
+ item = self.GetDocument().GetInPlaceActiveItem(self)
+ if item is not None:
+ item.SetItemRects()
+ return 1 # do call the base!
+
+
+class OleTemplate(docview.DocTemplate):
+ def __init__(
+ self, resourceId=None, MakeDocument=None, MakeFrame=None, MakeView=None
+ ):
+ if MakeDocument is None:
+ MakeDocument = OleDocument
+ if MakeView is None:
+ MakeView = ExcelView
+ docview.DocTemplate.__init__(
+ self, resourceId, MakeDocument, MakeFrame, MakeView
+ )
+
+
+class WordFrame(window.MDIChildWnd):
+ def __init__(self, doc=None):
+ self._obj_ = win32ui.CreateMDIChild()
+ self._obj_.AttachObject(self)
+ # Don't call base class doc/view version...
+
+ def Create(self, title, rect=None, parent=None):
+ WordModule = gencache.EnsureModule(
+ "{00020905-0000-0000-C000-000000000046}", 1033, 8, 0
+ )
+ if WordModule is None:
+ raise ImportError(
+ "Microsoft Word version 8 does not appear to be installed."
+ )
+
+ # WordModule.Word doesn't exist in WordModule, WordModule.Words does, but CreateControl still fails
+ class MyWordControl(activex.Control, WordModule.Word): ...
+
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
+ self._obj_.CreateWindow(None, title, style, rect, parent)
+
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.ocx = MyWordControl()
+ self.ocx.CreateControl(
+ "Microsoft Word", win32con.WS_VISIBLE | win32con.WS_CHILD, rect, self, 20000
+ )
+
+
+def Demo():
+ import sys
+
+ import win32api
+
+ docName = None
+ if len(sys.argv) > 1:
+ docName = win32api.GetFullPathName(sys.argv[1])
+ OleTemplate().OpenDocumentFile(docName)
+
+ # ActiveX not currently working
+ # f = WordFrame(docName)
+ # f.Create("Microsoft Office")
+
+
+if __name__ == "__main__":
+ Demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/ocxserialtest.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/ocxserialtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..316a418f9b8b2b0fbf728247a50611b40e12a4b0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/ocxserialtest.py
@@ -0,0 +1,132 @@
+# ocxserialtest.py
+#
+# Sample that uses the mscomm OCX to talk to a serial
+# device.
+
+# Very simple - queries a modem for ATI responses
+
+import pythoncom
+import win32con
+import win32ui
+from pywin.mfc import activex, dialog
+from win32com.client import gencache
+
+SERIAL_SETTINGS = "19200,n,8,1"
+SERIAL_PORT = 2
+
+win32ui.DoWaitCursor(1)
+serialModule = gencache.EnsureModule("{648A5603-2C6E-101B-82B6-000000000014}", 0, 1, 1)
+win32ui.DoWaitCursor(0)
+if serialModule is None:
+ raise ImportError("MS COMM Control does not appear to be installed on the PC")
+
+
+def MakeDlgTemplate():
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+ dlg = [
+ ["Very Basic Terminal", (0, 0, 350, 180), style, None, (8, "MS Sans Serif")],
+ ]
+ s = win32con.WS_TABSTOP | cs
+ dlg.append(
+ [
+ "RICHEDIT",
+ None,
+ 132,
+ (5, 5, 340, 170),
+ s
+ | win32con.ES_WANTRETURN
+ | win32con.ES_MULTILINE
+ | win32con.ES_AUTOVSCROLL
+ | win32con.WS_VSCROLL,
+ ]
+ )
+ return dlg
+
+
+####################################
+#
+# Serial Control
+#
+class MySerialControl(activex.Control, serialModule.MSComm):
+ def __init__(self, parent):
+ activex.Control.__init__(self)
+ serialModule.MSComm.__init__(self)
+ self.parent = parent
+
+ def OnComm(self):
+ self.parent.OnComm()
+
+
+class TestSerDialog(dialog.Dialog):
+ def __init__(self, *args):
+ dialog.Dialog.__init__(*(self,) + args)
+ self.olectl = None
+
+ def OnComm(self):
+ event = self.olectl.CommEvent
+ if event == serialModule.OnCommConstants.comEvReceive:
+ self.editwindow.ReplaceSel(self.olectl.Input)
+
+ def OnKey(self, key):
+ if self.olectl:
+ self.olectl.Output = chr(key)
+
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.editwindow = self.GetDlgItem(132)
+ self.editwindow.HookAllKeyStrokes(self.OnKey)
+
+ self.olectl = MySerialControl(self)
+ try:
+ self.olectl.CreateControl(
+ "OCX",
+ win32con.WS_TABSTOP | win32con.WS_VISIBLE,
+ (7, 43, 500, 300),
+ self._obj_,
+ 131,
+ )
+ except win32ui.error:
+ self.MessageBox("The Serial Control could not be created")
+ self.olectl = None
+ self.EndDialog(win32con.IDCANCEL)
+ if self.olectl:
+ self.olectl.Settings = SERIAL_SETTINGS
+ self.olectl.CommPort = SERIAL_PORT
+ self.olectl.RThreshold = 1
+ try:
+ self.olectl.PortOpen = 1
+ except pythoncom.com_error as details:
+ print(
+ "Could not open the specified serial port - %s"
+ % (details.excepinfo[2])
+ )
+ self.EndDialog(win32con.IDCANCEL)
+ return rc
+
+ def OnDestroy(self, msg):
+ if self.olectl:
+ try:
+ self.olectl.PortOpen = 0
+ except pythoncom.com_error as details:
+ print("Error closing port - %s" % (details.excepinfo[2]))
+ return dialog.Dialog.OnDestroy(self, msg)
+
+
+def test():
+ d = TestSerDialog(MakeDlgTemplate())
+ d.DoModal()
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/ocxtest.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/ocxtest.py
new file mode 100644
index 0000000000000000000000000000000000000000..5136d8d15b212407a962a5fb846d5834ec87ad3e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/ocxtest.py
@@ -0,0 +1,243 @@
+# OCX Tester for Pythonwin
+#
+# This file _is_ ready to run. All that is required is that the OCXs being tested
+# are installed on your machine.
+#
+# The .py files behind the OCXs will be automatically generated and imported.
+
+import glob
+import os
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import activex, dialog, window
+from win32com.client import gencache
+
+
+def MakeDlgTemplate():
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+ dlg = [
+ ["OCX Demos", (0, 0, 350, 350), style, None, (8, "MS Sans Serif")],
+ ]
+ s = win32con.WS_TABSTOP | cs
+ # dlg.append([131, None, 130, (5, 40, 110, 48),
+ # s | win32con.LBS_NOTIFY | win32con.LBS_SORT | win32con.LBS_NOINTEGRALHEIGHT | win32con.WS_VSCROLL | win32con.WS_BORDER])
+ # dlg.append(["{8E27C92B-1264-101C-8A2F-040224009C02}", None, 131, (5, 40, 110, 48),win32con.WS_TABSTOP])
+
+ dlg.append(
+ [128, "About", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]
+ )
+ s = win32con.BS_PUSHBUTTON | s
+ dlg.append([128, "Close", win32con.IDCANCEL, (124, 22, 50, 14), s])
+
+ return dlg
+
+
+####################################
+#
+# Calendar test code
+#
+
+
+def GetTestCalendarClass():
+ global calendarParentModule
+ win32ui.DoWaitCursor(1)
+ calendarParentModule = gencache.EnsureModule(
+ "{8E27C92E-1264-101C-8A2F-040224009C02}", 0, 7, 0
+ )
+ win32ui.DoWaitCursor(0)
+ if calendarParentModule is None:
+ return None
+
+ class TestCalDialog(dialog.Dialog):
+ def OnInitDialog(self):
+ class MyCal(activex.Control, calendarParentModule.Calendar):
+ def OnAfterUpdate(self):
+ print("OnAfterUpdate")
+
+ def OnClick(self):
+ print("OnClick")
+
+ def OnDblClick(self):
+ print("OnDblClick")
+
+ def OnKeyDown(self, KeyCode, Shift):
+ print("OnKeyDown", KeyCode, Shift)
+
+ def OnKeyPress(self, KeyAscii):
+ print("OnKeyPress", KeyAscii)
+
+ def OnKeyUp(self, KeyCode, Shift):
+ print("OnKeyUp", KeyCode, Shift)
+
+ def OnBeforeUpdate(self, Cancel):
+ print("OnBeforeUpdate", Cancel)
+
+ def OnNewMonth(self):
+ print("OnNewMonth")
+
+ def OnNewYear(self):
+ print("OnNewYear")
+
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.olectl = MyCal()
+ try:
+ self.olectl.CreateControl(
+ "OCX",
+ win32con.WS_TABSTOP | win32con.WS_VISIBLE,
+ (7, 43, 500, 300),
+ self._obj_,
+ 131,
+ )
+ except win32ui.error:
+ self.MessageBox("The Calendar Control could not be created")
+ self.olectl = None
+ self.EndDialog(win32con.IDCANCEL)
+
+ return rc
+
+ def OnOK(self):
+ self.olectl.AboutBox()
+
+ return TestCalDialog
+
+
+####################################
+#
+# Video Control
+#
+def GetTestVideoModule():
+ global videoControlModule, videoControlFileName
+ win32ui.DoWaitCursor(1)
+ videoControlModule = gencache.EnsureModule(
+ "{05589FA0-C356-11CE-BF01-00AA0055595A}", 0, 2, 0
+ )
+ win32ui.DoWaitCursor(0)
+ if videoControlModule is None:
+ return None
+ fnames = glob.glob(os.path.join(win32api.GetWindowsDirectory(), "*.avi"))
+ if not fnames:
+ print("No AVI files available in system directory")
+ return None
+ videoControlFileName = fnames[0]
+ return videoControlModule
+
+
+def GetTestVideoDialogClass():
+ if GetTestVideoModule() is None:
+ return None
+
+ class TestVideoDialog(dialog.Dialog):
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ try:
+ self.olectl = activex.MakeControlInstance(
+ videoControlModule.ActiveMovie
+ )
+ self.olectl.CreateControl(
+ "",
+ win32con.WS_TABSTOP | win32con.WS_VISIBLE,
+ (7, 43, 500, 300),
+ self._obj_,
+ 131,
+ )
+ except win32ui.error:
+ self.MessageBox("The Video Control could not be created")
+ self.olectl = None
+ self.EndDialog(win32con.IDCANCEL)
+ return
+
+ self.olectl.FileName = videoControlFileName
+ # self.olectl.Run()
+ return rc
+
+ def OnOK(self):
+ self.olectl.AboutBox()
+
+ return TestVideoDialog
+
+
+###############
+#
+# An OCX in an MDI Frame
+#
+class OCXFrame(window.MDIChildWnd):
+ def __init__(self):
+ pass # Don't call base class doc/view version...
+
+ def Create(self, controlClass, title, rect=None, parent=None):
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
+ self._obj_ = win32ui.CreateMDIChild()
+ self._obj_.AttachObject(self)
+ self._obj_.CreateWindow(None, title, style, rect, parent)
+
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.ocx = controlClass()
+ self.ocx.CreateControl(
+ "", win32con.WS_VISIBLE | win32con.WS_CHILD, rect, self, 1000
+ )
+
+
+def MDITest():
+ calendarParentModule = gencache.EnsureModule(
+ "{8E27C92E-1264-101C-8A2F-040224009C02}", 0, 7, 0
+ )
+
+ class MyCal(activex.Control, calendarParentModule.Calendar):
+ def OnAfterUpdate(self):
+ print("OnAfterUpdate")
+
+ def OnClick(self):
+ print("OnClick")
+
+ f = OCXFrame()
+ f.Create(MyCal, "Calendar Test")
+
+
+def test1():
+ klass = GetTestCalendarClass()
+ if klass is None:
+ print(
+ "Can not test the MSAccess Calendar control - it does not appear to be installed"
+ )
+ return
+
+ d = klass(MakeDlgTemplate())
+ d.DoModal()
+
+
+def test2():
+ klass = GetTestVideoDialogClass()
+ if klass is None:
+ print("Can not test the Video OCX - it does not appear to be installed,")
+ print("or no AVI files can be found.")
+ return
+ d = klass(MakeDlgTemplate())
+ d.DoModal()
+ d = None
+
+
+def testall():
+ test1()
+ test2()
+
+
+def demo():
+ testall()
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ testall()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/webbrowser.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/webbrowser.py
new file mode 100644
index 0000000000000000000000000000000000000000..13f54422b8ae2f860dc6e23c6f5948de8b8e7ec6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/ocx/webbrowser.py
@@ -0,0 +1,72 @@
+# This demo uses the Internet Explorer Web Browser control.
+
+# It catches an "OnNavigate" event, and updates the frame title.
+# (event stuff by Neil Hodgson)
+
+import sys
+
+import regutil
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import activex, window
+from win32com.client import gencache
+
+WebBrowserModule = gencache.EnsureModule(
+ "{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1
+)
+if WebBrowserModule is None:
+ raise ImportError("Internet Explorer does not appear to be installed.")
+
+
+class MyWebBrowser(activex.Control, WebBrowserModule.WebBrowser):
+ def OnBeforeNavigate2(
+ self, pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel
+ ):
+ self.GetParent().OnNavigate(URL)
+ # print("BeforeNavigate2", pDisp, URL, Flags, TargetFrameName, PostData, Headers, Cancel)
+
+
+class BrowserFrame(window.MDIChildWnd):
+ def __init__(self, url=None):
+ if url is None:
+ self.url = regutil.GetRegisteredHelpFile("Main Python Documentation")
+ if self.url is None:
+ self.url = "https://www.python.org"
+ else:
+ self.url = url
+ pass # Don't call base class doc/view version...
+
+ def Create(self, title, rect=None, parent=None):
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
+ self._obj_ = win32ui.CreateMDIChild()
+ self._obj_.AttachObject(self)
+ self._obj_.CreateWindow(None, title, style, rect, parent)
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.ocx = MyWebBrowser()
+ self.ocx.CreateControl(
+ "Web Browser", win32con.WS_VISIBLE | win32con.WS_CHILD, rect, self, 1000
+ )
+ self.ocx.Navigate(self.url)
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ def OnSize(self, params):
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.ocx.SetWindowPos(0, rect, 0)
+
+ def OnNavigate(self, url):
+ title = f"Web Browser - {url}"
+ self.SetWindowText(title)
+
+
+def Demo(url=None):
+ if url is None and len(sys.argv) > 1:
+ url = win32api.GetFullPathName(sys.argv[1])
+ f = BrowserFrame(url)
+ f.Create("Web Browser")
+
+
+if __name__ == "__main__":
+ Demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/openGLDemo.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/openGLDemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a28b0b025286012fb6953bbd3227e11c080cbd4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/openGLDemo.py
@@ -0,0 +1,415 @@
+# Ported from the win32 and MFC OpenGL Samples.
+
+import sys
+
+try:
+ from OpenGL.GL import (
+ GL_COLOR_BUFFER_BIT,
+ GL_DEPTH_BUFFER_BIT,
+ GL_DEPTH_TEST,
+ GL_MODELVIEW,
+ GL_PROJECTION,
+ GL_QUAD_STRIP,
+ GL_QUADS,
+ GL_TRIANGLE_FAN,
+ glBegin,
+ glClear,
+ glClearColor,
+ glClearDepth,
+ glColor3f,
+ glEnable,
+ glEnd,
+ glFinish,
+ glLoadIdentity,
+ glMatrixMode,
+ glPopMatrix,
+ glPushMatrix,
+ glRotatef,
+ glTranslatef,
+ glVertex3f,
+ glViewport,
+ )
+ from OpenGL.GLU import (
+ GLU_FILL,
+ GLU_SMOOTH,
+ gluCylinder,
+ gluNewQuadric,
+ gluPerspective,
+ gluQuadricDrawStyle,
+ gluQuadricNormals,
+ )
+ from OpenGL.WGL import (
+ PIXELFORMATDESCRIPTOR,
+ ChoosePixelFormat,
+ DescribePixelFormat,
+ GetPixelFormat,
+ SetPixelFormat,
+ SwapBuffers,
+ wglCreateContext,
+ wglDeleteContext,
+ wglGetCurrentContext,
+ wglGetCurrentDC,
+ wglMakeCurrent,
+ )
+except ImportError:
+ print("The OpenGL extensions do not appear to be installed.")
+ print("This Pythonwin demo can not run")
+ sys.exit(1)
+
+import timer
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import docview
+
+PFD_TYPE_RGBA = 0
+PFD_TYPE_COLORINDEX = 1
+PFD_MAIN_PLANE = 0
+PFD_OVERLAY_PLANE = 1
+PFD_UNDERLAY_PLANE = -1
+PFD_DOUBLEBUFFER = 0x00000001
+PFD_STEREO = 0x00000002
+PFD_DRAW_TO_WINDOW = 0x00000004
+PFD_DRAW_TO_BITMAP = 0x00000008
+PFD_SUPPORT_GDI = 0x00000010
+PFD_SUPPORT_OPENGL = 0x00000020
+PFD_GENERIC_FORMAT = 0x00000040
+PFD_NEED_PALETTE = 0x00000080
+PFD_NEED_SYSTEM_PALETTE = 0x00000100
+PFD_SWAP_EXCHANGE = 0x00000200
+PFD_SWAP_COPY = 0x00000400
+PFD_SWAP_LAYER_BUFFERS = 0x00000800
+PFD_GENERIC_ACCELERATED = 0x00001000
+PFD_DEPTH_DONTCARE = 0x20000000
+PFD_DOUBLEBUFFER_DONTCARE = 0x40000000
+PFD_STEREO_DONTCARE = 0x80000000
+
+
+# threeto8 = [0, 0o111>>1, 0o222>>1, 0o333>>1, 0o444>>1, 0o555>>1, 0o666>>1, 0o377]
+threeto8 = [0, 73 >> 1, 146 >> 1, 219 >> 1, 292 >> 1, 365 >> 1, 438 >> 1, 255]
+twoto8 = [0, 0x55, 0xAA, 0xFF]
+oneto8 = [0, 255]
+
+
+def ComponentFromIndex(i, nbits, shift):
+ # val = (unsigned char) (i >> shift);
+ val = (i >> shift) & 0xF
+ if nbits == 1:
+ val &= 0x1
+ return oneto8[val]
+ elif nbits == 2:
+ val &= 0x3
+ return twoto8[val]
+ elif nbits == 3:
+ val &= 0x7
+ return threeto8[val]
+ else:
+ return 0
+
+
+OpenGLViewParent = docview.ScrollView
+
+
+class OpenGLView(OpenGLViewParent):
+ def PreCreateWindow(self, cc):
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+ # An OpenGL window must be created with the following flags and must not
+ # include CS_PARENTDC for the class style. Refer to SetPixelFormat
+ # documentation in the "Comments" section for further information.
+ style = cc[5]
+ style |= win32con.WS_CLIPSIBLINGS | win32con.WS_CLIPCHILDREN
+ cc = cc[0], cc[1], cc[2], cc[3], cc[4], style, cc[6], cc[7], cc[8]
+ cc = self._obj_.PreCreateWindow(cc)
+ return cc
+
+ def OnSize(self, params):
+ lParam = params[3]
+ cx = win32api.LOWORD(lParam)
+ cy = win32api.HIWORD(lParam)
+ glViewport(0, 0, cx, cy)
+
+ if self.oldrect[2] > cx or self.oldrect[3] > cy:
+ self.RedrawWindow()
+
+ self.OnSizeChange(cx, cy)
+
+ self.oldrect = self.oldrect[0], self.oldrect[1], cx, cy
+
+ def OnInitialUpdate(self):
+ self.SetScaleToFitSize(
+ (100, 100)
+ ) # or SetScrollSizes() - A Pythonwin requirement
+ return self._obj_.OnInitialUpdate()
+
+ # return rc
+
+ def OnCreate(self, cs):
+ self.oldrect = self.GetClientRect()
+ self._InitContexts()
+ self.Init()
+
+ def OnDestroy(self, msg):
+ self.Term()
+ self._DestroyContexts()
+ return OpenGLViewParent.OnDestroy(self, msg)
+
+ def OnDraw(self, dc):
+ self.DrawScene()
+
+ def OnEraseBkgnd(self, dc):
+ return 1
+
+ # The OpenGL helpers
+ def _SetupPixelFormat(self):
+ dc = self.dc.GetSafeHdc()
+ pfd = PIXELFORMATDESCRIPTOR()
+ pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER
+ pfd.iPixelType = PFD_TYPE_RGBA
+ pfd.cColorBits = 24
+ pfd.cDepthBits = 32
+ pfd.iLayerType = PFD_MAIN_PLANE
+ pixelformat = ChoosePixelFormat(dc, pfd)
+ SetPixelFormat(dc, pixelformat, pfd)
+ self._CreateRGBPalette(pfd)
+
+ def _CreateRGBPalette(self, pfd):
+ hdc = self.dc.GetSafeHdc()
+ iPixelFormat = GetPixelFormat(hdc)
+ DescribePixelFormat(hdc, iPixelFormat, pfd.nSize, pfd)
+ if pfd.dwFlags & PFD_NEED_PALETTE:
+ iPixelFormat = 1 << pfd.cColorBits
+ pal = []
+ for i in range(iPixelFormat):
+ this = (
+ ComponentFromIndex(i, pfd.cRedBits, pfd.cRedShift),
+ ComponentFromIndex(i, pfd.cGreenBits, pfd.cGreenShift),
+ ComponentFromIndex(i, pfd.cBlueBits, pfd.cBlueShift),
+ 0,
+ )
+ pal.append(this)
+ hpal = win32ui.CreatePalette(pal)
+ self.dc.SelectPalette(hpal, 0)
+ self.dc.RealizePalette()
+
+ def _InitContexts(self):
+ self.dc = self.GetDC()
+ self._SetupPixelFormat()
+ hrc = wglCreateContext(self.dc.GetSafeHdc())
+ wglMakeCurrent(self.dc.GetSafeHdc(), hrc)
+
+ def _DestroyContexts(self):
+ hrc = wglGetCurrentContext()
+ wglMakeCurrent(0, 0)
+ if hrc:
+ wglDeleteContext(hrc)
+
+ # The methods to support OpenGL
+ def DrawScene(self):
+ raise NotImplementedError("You must override this method")
+
+ def Init(self):
+ raise NotImplementedError("You must override this method")
+
+ def OnSizeChange(self, cx, cy):
+ pass
+
+ def Term(self):
+ pass
+
+
+class TestView(OpenGLView):
+ def OnSizeChange(self, right, bottom):
+ glClearColor(0.0, 0.0, 0.0, 1.0)
+ glClearDepth(1.0)
+ glEnable(GL_DEPTH_TEST)
+
+ glMatrixMode(GL_PROJECTION)
+ if bottom:
+ aspect = right / bottom
+ else:
+ aspect = 0 # When window created!
+ glLoadIdentity()
+ gluPerspective(45.0, aspect, 3.0, 7.0)
+ glMatrixMode(GL_MODELVIEW)
+
+ near_plane = 3.0
+ far_plane = 7.0
+ maxObjectSize = 3.0
+ self.radius = near_plane + maxObjectSize / 2.0
+
+ def Init(self):
+ pass
+
+ def DrawScene(self):
+ glClearColor(0.0, 0.0, 0.0, 1.0)
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
+
+ glPushMatrix()
+ glTranslatef(0.0, 0.0, -self.radius)
+
+ self._DrawCone()
+
+ self._DrawPyramid()
+
+ glPopMatrix()
+ glFinish()
+
+ SwapBuffers(wglGetCurrentDC())
+
+ def _DrawCone(self):
+ glColor3f(0.0, 1.0, 0.0)
+
+ glPushMatrix()
+ glTranslatef(-1.0, 0.0, 0.0)
+ quadObj = gluNewQuadric()
+ gluQuadricDrawStyle(quadObj, GLU_FILL)
+ gluQuadricNormals(quadObj, GLU_SMOOTH)
+ gluCylinder(quadObj, 1.0, 0.0, 1.0, 20, 10)
+ # gluDeleteQuadric(quadObj);
+ glPopMatrix()
+
+ def _DrawPyramid(self):
+ glPushMatrix()
+ glTranslatef(1.0, 0.0, 0.0)
+ glBegin(GL_TRIANGLE_FAN)
+ glColor3f(1.0, 0.0, 0.0)
+ glVertex3f(0.0, 1.0, 0.0)
+ glColor3f(0.0, 1.0, 0.0)
+ glVertex3f(-1.0, 0.0, 0.0)
+ glColor3f(0.0, 0.0, 1.0)
+ glVertex3f(0.0, 0.0, 1.0)
+ glColor3f(0.0, 1.0, 0.0)
+ glVertex3f(1.0, 0.0, 0.0)
+ glEnd()
+ glPopMatrix()
+
+
+class CubeView(OpenGLView):
+ def OnSizeChange(self, right, bottom):
+ glClearColor(0.0, 0.0, 0.0, 1.0)
+ glClearDepth(1.0)
+ glEnable(GL_DEPTH_TEST)
+
+ glMatrixMode(GL_PROJECTION)
+ if bottom:
+ aspect = right / bottom
+ else:
+ aspect = 0 # When window created!
+ glLoadIdentity()
+ gluPerspective(45.0, aspect, 3.0, 7.0)
+ glMatrixMode(GL_MODELVIEW)
+
+ near_plane = 3.0
+ far_plane = 7.0
+ maxObjectSize = 3.0
+ self.radius = near_plane + maxObjectSize / 2.0
+
+ def Init(self):
+ self.busy = 0
+ self.wAngleY = 10.0
+ self.wAngleX = 1.0
+ self.wAngleZ = 5.0
+ self.timerid = timer.set_timer(150, self.OnTimer)
+
+ def OnTimer(self, id, timeVal):
+ self.DrawScene()
+
+ def Term(self):
+ timer.kill_timer(self.timerid)
+
+ def DrawScene(self):
+ if self.busy:
+ return
+ self.busy = 1
+
+ glClearColor(0.0, 0.0, 0.0, 1.0)
+ glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
+
+ glPushMatrix()
+
+ glTranslatef(0.0, 0.0, -self.radius)
+ glRotatef(self.wAngleX, 1.0, 0.0, 0.0)
+ glRotatef(self.wAngleY, 0.0, 1.0, 0.0)
+ glRotatef(self.wAngleZ, 0.0, 0.0, 1.0)
+
+ self.wAngleX += 1.0
+ self.wAngleY += 10.0
+ self.wAngleZ += 5.0
+
+ glBegin(GL_QUAD_STRIP)
+ glColor3f(1.0, 0.0, 1.0)
+ glVertex3f(-0.5, 0.5, 0.5)
+
+ glColor3f(1.0, 0.0, 0.0)
+ glVertex3f(-0.5, -0.5, 0.5)
+
+ glColor3f(1.0, 1.0, 1.0)
+ glVertex3f(0.5, 0.5, 0.5)
+
+ glColor3f(1.0, 1.0, 0.0)
+ glVertex3f(0.5, -0.5, 0.5)
+
+ glColor3f(0.0, 1.0, 1.0)
+ glVertex3f(0.5, 0.5, -0.5)
+
+ glColor3f(0.0, 1.0, 0.0)
+ glVertex3f(0.5, -0.5, -0.5)
+
+ glColor3f(0.0, 0.0, 1.0)
+ glVertex3f(-0.5, 0.5, -0.5)
+
+ glColor3f(0.0, 0.0, 0.0)
+ glVertex3f(-0.5, -0.5, -0.5)
+
+ glColor3f(1.0, 0.0, 1.0)
+ glVertex3f(-0.5, 0.5, 0.5)
+
+ glColor3f(1.0, 0.0, 0.0)
+ glVertex3f(-0.5, -0.5, 0.5)
+
+ glEnd()
+
+ glBegin(GL_QUADS)
+ glColor3f(1.0, 0.0, 1.0)
+ glVertex3f(-0.5, 0.5, 0.5)
+
+ glColor3f(1.0, 1.0, 1.0)
+ glVertex3f(0.5, 0.5, 0.5)
+
+ glColor3f(0.0, 1.0, 1.0)
+ glVertex3f(0.5, 0.5, -0.5)
+
+ glColor3f(0.0, 0.0, 1.0)
+ glVertex3f(-0.5, 0.5, -0.5)
+ glEnd()
+
+ glBegin(GL_QUADS)
+ glColor3f(1.0, 0.0, 0.0)
+ glVertex3f(-0.5, -0.5, 0.5)
+
+ glColor3f(1.0, 1.0, 0.0)
+ glVertex3f(0.5, -0.5, 0.5)
+
+ glColor3f(0.0, 1.0, 0.0)
+ glVertex3f(0.5, -0.5, -0.5)
+
+ glColor3f(0.0, 0.0, 0.0)
+ glVertex3f(-0.5, -0.5, -0.5)
+ glEnd()
+
+ glPopMatrix()
+
+ glFinish()
+ SwapBuffers(wglGetCurrentDC())
+
+ self.busy = 0
+
+
+def test():
+ template = docview.DocTemplate(None, None, None, CubeView)
+ # template = docview.DocTemplate(None, None, None, TestView )
+ template.OpenDocumentFile(None)
+
+
+if __name__ == "__main__":
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/progressbar.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/progressbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..a461ab959a310709f8aa73de3d288fb13160f20f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/progressbar.py
@@ -0,0 +1,105 @@
+#
+# Progress bar control example
+#
+# PyCProgressCtrl encapsulates the MFC CProgressCtrl class. To use it,
+# you:
+#
+# - Create the control with win32ui.CreateProgressCtrl()
+# - Create the control window with PyCProgressCtrl.CreateWindow()
+# - Initialize the range if you want it to be other than (0, 100) using
+# PyCProgressCtrl.SetRange()
+# - Either:
+# - Set the step size with PyCProgressCtrl.SetStep(), and
+# - Increment using PyCProgressCtrl.StepIt()
+# or:
+# - Set the amount completed using PyCProgressCtrl.SetPos()
+#
+# Example and progress bar code courtesy of KDL Technologies, Ltd., Hong Kong SAR, China.
+#
+
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+
+def MakeDlgTemplate():
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+
+ w = 215
+ h = 36
+
+ dlg = [
+ [
+ "Progress bar control example",
+ (0, 0, w, h),
+ style,
+ None,
+ (8, "MS Sans Serif"),
+ ],
+ ]
+
+ s = win32con.WS_TABSTOP | cs
+
+ dlg.append(
+ [
+ 128,
+ "Tick",
+ win32con.IDOK,
+ (10, h - 18, 50, 14),
+ s | win32con.BS_DEFPUSHBUTTON,
+ ]
+ )
+
+ dlg.append(
+ [
+ 128,
+ "Cancel",
+ win32con.IDCANCEL,
+ (w - 60, h - 18, 50, 14),
+ s | win32con.BS_PUSHBUTTON,
+ ]
+ )
+
+ return dlg
+
+
+class TestDialog(dialog.Dialog):
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.pbar = win32ui.CreateProgressCtrl()
+ self.pbar.CreateWindow(
+ win32con.WS_CHILD | win32con.WS_VISIBLE, (10, 10, 310, 24), self, 1001
+ )
+ # self.pbar.SetStep (5)
+ self.progress = 0
+ self.pincr = 5
+ return rc
+
+ def OnOK(self):
+ # NB: StepIt wraps at the end if you increment past the upper limit!
+ # self.pbar.StepIt()
+ self.progress += self.pincr
+ if self.progress > 100:
+ self.progress = 100
+ if self.progress <= 100:
+ self.pbar.SetPos(self.progress)
+
+
+def demo(modal=0):
+ d = TestDialog(MakeDlgTemplate())
+ if modal:
+ d.DoModal()
+ else:
+ d.CreateWindow()
+
+
+if __name__ == "__main__":
+ demo(1)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/sliderdemo.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/sliderdemo.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c58224d0bd790bd01a8c68bf2b965b235323af5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/sliderdemo.py
@@ -0,0 +1,76 @@
+# sliderdemo.py
+# Demo of the slider control courtesy of Mike Fletcher.
+
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+
+class MyDialog(dialog.Dialog):
+ """
+ Example using simple controls
+ """
+
+ _dialogstyle = (
+ win32con.WS_MINIMIZEBOX
+ | win32con.WS_DLGFRAME
+ | win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ _buttonstyle = (
+ win32con.BS_PUSHBUTTON
+ | win32con.WS_TABSTOP
+ | win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ )
+ ### The static template, contains all "normal" dialog items
+ DIALOGTEMPLATE = [
+ # the dialog itself is the first element in the template
+ ["Example slider", (0, 0, 50, 43), _dialogstyle, None, (8, "MS SansSerif")],
+ # rest of elements are the controls within the dialog
+ # standard "Close" button
+ [128, "Close", win32con.IDCANCEL, (0, 30, 50, 13), _buttonstyle],
+ ]
+ ### ID of the control to be created during dialog initialisation
+ IDC_SLIDER = 9500
+
+ def __init__(self):
+ dialog.Dialog.__init__(self, self.DIALOGTEMPLATE)
+
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ # now initialise your controls that you want to create
+ # programmatically, including those which are OLE controls
+ # those created directly by win32ui.Create*
+ # and your "custom controls" which are subclasses/whatever
+ win32ui.EnableControlContainer()
+ self.slider = win32ui.CreateSliderCtrl()
+ self.slider.CreateWindow(
+ win32con.WS_TABSTOP | win32con.WS_VISIBLE,
+ (0, 0, 100, 30),
+ self._obj_,
+ self.IDC_SLIDER,
+ )
+ self.HookMessage(self.OnSliderMove, win32con.WM_HSCROLL)
+ return rc
+
+ def OnSliderMove(self, params):
+ print("Slider moved")
+
+ def OnCancel(self):
+ print("The slider control is at position", self.slider.GetPos())
+ self._obj_.OnCancel()
+
+
+###
+def demo():
+ dia = MyDialog()
+ dia.DoModal()
+
+
+if __name__ == "__main__":
+ demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/splittst.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/splittst.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f9ccb751ba4411d121ad53725a59c2af448c7ce
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/splittst.py
@@ -0,0 +1,79 @@
+import commctrl
+import fontdemo
+import win32ui
+from pywin.mfc import docview, window
+
+# derive from CMDIChild. This does much work for us.
+
+
+class SplitterFrame(window.MDIChildWnd):
+ def __init__(self):
+ # call base CreateFrame
+ self.images = None
+ window.MDIChildWnd.__init__(self)
+
+ def OnCreateClient(self, cp, context):
+ splitter = win32ui.CreateSplitter()
+ doc = context.doc
+ frame_rect = self.GetWindowRect()
+ size = ((frame_rect[2] - frame_rect[0]), (frame_rect[3] - frame_rect[1]) // 2)
+ sub_size = (size[0] // 2, size[1])
+ splitter.CreateStatic(self, 2, 1)
+ self.v1 = win32ui.CreateEditView(doc)
+ self.v2 = fontdemo.FontView(doc)
+ # CListControl view
+ self.v3 = win32ui.CreateListView(doc)
+ sub_splitter = win32ui.CreateSplitter()
+ # pass "splitter" so each view knows how to get to the others
+ sub_splitter.CreateStatic(splitter, 1, 2)
+ sub_splitter.CreateView(self.v1, 0, 0, (sub_size))
+ sub_splitter.CreateView(self.v2, 0, 1, (0, 0)) # size ignored.
+ splitter.SetRowInfo(0, size[1], 0)
+ splitter.CreateView(self.v3, 1, 0, (0, 0)) # size ignored.
+ # Setup items in the imagelist
+ self.images = win32ui.CreateImageList(32, 32, 1, 5, 5)
+ self.images.Add(win32ui.GetApp().LoadIcon(win32ui.IDR_MAINFRAME))
+ self.images.Add(win32ui.GetApp().LoadIcon(win32ui.IDR_PYTHONCONTYPE))
+ self.images.Add(win32ui.GetApp().LoadIcon(win32ui.IDR_TEXTTYPE))
+ self.v3.SetImageList(self.images, commctrl.LVSIL_NORMAL)
+ self.v3.InsertItem(0, "Icon 1", 0)
+ self.v3.InsertItem(0, "Icon 2", 1)
+ self.v3.InsertItem(0, "Icon 3", 2)
+ # self.v3.Arrange(commctrl.LVA_DEFAULT) Hmmm - win95 aligns left always???
+ return 1
+
+ def OnDestroy(self, msg):
+ window.MDIChildWnd.OnDestroy(self, msg)
+ if self.images:
+ self.images.DeleteImageList()
+ self.images = None
+
+ def InitialUpdateFrame(self, doc, makeVisible):
+ self.v1.ReplaceSel("Hello from Edit Window 1")
+ self.v1.SetModifiedFlag(0)
+
+
+class SampleTemplate(docview.DocTemplate):
+ def __init__(self):
+ docview.DocTemplate.__init__(
+ self, win32ui.IDR_PYTHONTYPE, None, SplitterFrame, None
+ )
+
+ def InitialUpdateFrame(self, frame, doc, makeVisible):
+ # print("frame is ", frame, frame._obj_)
+ # print("doc is ", doc, doc._obj_)
+ self._obj_.InitialUpdateFrame(frame, doc, makeVisible) # call default handler.
+ frame.InitialUpdateFrame(doc, makeVisible)
+
+
+def demo():
+ template = SampleTemplate()
+ doc = template.OpenDocumentFile(None)
+ doc.SetTitle("Splitter Demo")
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/threadedgui.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/threadedgui.py
new file mode 100644
index 0000000000000000000000000000000000000000..6195e5511f5109cdb4ceb3763ed54555d236acc1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/threadedgui.py
@@ -0,0 +1,189 @@
+# Demo of using just windows, without documents and views.
+
+# Also demo of a GUI thread, pretty much direct from the MFC C++ sample MTMDI.
+
+import timer
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import window
+from pywin.mfc.thread import WinThread
+
+WM_USER_PREPARE_TO_CLOSE = win32con.WM_USER + 32
+
+# font is a dictionary in which the following elements matter:
+# (the best matching font to supplied parameters is returned)
+# name string name of the font as known by Windows
+# size point size of font in logical units
+# weight weight of font (win32con.FW_NORMAL, win32con.FW_BOLD)
+# italic boolean; true if set to anything but None
+# underline boolean; true if set to anything but None
+
+
+# This window is a child window of a frame. It is not the frame window itself.
+class FontWindow(window.Wnd):
+ def __init__(self, text="Python Rules!"):
+ window.Wnd.__init__(self)
+ self.text = text
+ self.index = 0
+ self.incr = 1
+ self.width = self.height = 0
+ self.ChangeAttributes()
+ # set up message handlers
+
+ def Create(self, title, style, rect, parent):
+ classStyle = win32con.CS_HREDRAW | win32con.CS_VREDRAW
+ className = win32ui.RegisterWndClass(
+ classStyle, 0, win32con.COLOR_WINDOW + 1, 0
+ )
+ self._obj_ = win32ui.CreateWnd()
+ self._obj_.AttachObject(self)
+ self._obj_.CreateWindow(
+ className, title, style, rect, parent, win32ui.AFX_IDW_PANE_FIRST
+ )
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+ self.HookMessage(self.OnPrepareToClose, WM_USER_PREPARE_TO_CLOSE)
+ self.HookMessage(self.OnDestroy, win32con.WM_DESTROY)
+ self.timerid = timer.set_timer(100, self.OnTimer)
+ self.InvalidateRect()
+
+ def OnDestroy(self, msg):
+ timer.kill_timer(self.timerid)
+
+ def OnTimer(self, id, timeVal):
+ self.index += self.incr
+ if self.index > len(self.text):
+ self.incr = -1
+ self.index = len(self.text)
+ elif self.index < 0:
+ self.incr = 1
+ self.index = 0
+ self.InvalidateRect()
+
+ def OnPaint(self):
+ # print("Paint message from thread", win32api.GetCurrentThreadId())
+ dc, paintStruct = self.BeginPaint()
+ self.OnPrepareDC(dc, None)
+
+ if self.width == 0 and self.height == 0:
+ left, top, right, bottom = self.GetClientRect()
+ self.width = right - left
+ self.height = bottom - top
+ x, y = self.width // 2, self.height // 2
+ dc.TextOut(x, y, self.text[: self.index])
+ self.EndPaint(paintStruct)
+
+ def ChangeAttributes(self):
+ font_spec = {"name": "Arial", "height": 42}
+ self.font = win32ui.CreateFont(font_spec)
+
+ def OnPrepareToClose(self, params):
+ self.DestroyWindow()
+
+ def OnSize(self, params):
+ lParam = params[3]
+ self.width = win32api.LOWORD(lParam)
+ self.height = win32api.HIWORD(lParam)
+
+ def OnPrepareDC(self, dc, printinfo):
+ # Set up the DC for forthcoming OnDraw call
+ dc.SetTextColor(win32api.RGB(0, 0, 255))
+ dc.SetBkColor(win32api.GetSysColor(win32con.COLOR_WINDOW))
+ dc.SelectObject(self.font)
+ dc.SetTextAlign(win32con.TA_CENTER | win32con.TA_BASELINE)
+
+
+class FontFrame(window.MDIChildWnd):
+ def __init__(self):
+ pass # Don't call base class doc/view version...
+
+ def Create(self, title, rect=None, parent=None):
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
+ self._obj_ = win32ui.CreateMDIChild()
+ self._obj_.AttachObject(self)
+
+ self._obj_.CreateWindow(None, title, style, rect, parent)
+ rect = self.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+ self.child = FontWindow("Not threaded")
+ self.child.Create(
+ "FontDemo", win32con.WS_CHILD | win32con.WS_VISIBLE, rect, self
+ )
+
+
+class TestThread(WinThread):
+ def __init__(self, parentWindow):
+ self.parentWindow = parentWindow
+ self.child = None
+ WinThread.__init__(self)
+
+ def InitInstance(self):
+ rect = self.parentWindow.GetClientRect()
+ rect = (0, 0, rect[2] - rect[0], rect[3] - rect[1])
+
+ self.child = FontWindow()
+ self.child.Create(
+ "FontDemo", win32con.WS_CHILD | win32con.WS_VISIBLE, rect, self.parentWindow
+ )
+ self.SetMainFrame(self.child)
+ return WinThread.InitInstance(self)
+
+ def ExitInstance(self):
+ return 0
+
+
+class ThreadedFontFrame(window.MDIChildWnd):
+ def __init__(self):
+ pass # Don't call base class doc/view version...
+ self.thread = None
+
+ def Create(self, title, rect=None, parent=None):
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_OVERLAPPEDWINDOW
+ self._obj_ = win32ui.CreateMDIChild()
+ self._obj_.CreateWindow(None, title, style, rect, parent)
+ self._obj_.HookMessage(self.OnDestroy, win32con.WM_DESTROY)
+ self._obj_.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ self.thread = TestThread(self)
+ self.thread.CreateThread()
+
+ def OnSize(self, msg):
+ pass
+
+ def OnDestroy(self, msg):
+ win32ui.OutputDebugString("OnDestroy\n")
+ if self.thread and self.thread.child:
+ child = self.thread.child
+ child.SendMessage(WM_USER_PREPARE_TO_CLOSE, 0, 0)
+ win32ui.OutputDebugString("Destroyed\n")
+
+
+def Demo():
+ f = FontFrame()
+ f.Create("Font Demo")
+
+
+def ThreadedDemo():
+ rect = win32ui.GetMainFrame().GetMDIClient().GetClientRect()
+ rect = rect[0], int(rect[3] * 3 / 4), int(rect[2] / 4), rect[3]
+ incr = rect[2]
+ for i in range(4):
+ if i == 0:
+ f = FontFrame()
+ title = "Not threaded"
+ else:
+ f = ThreadedFontFrame()
+ title = "Threaded GUI Demo"
+ f.Create(title, rect)
+ rect = rect[0] + incr, rect[1], rect[2] + incr, rect[3]
+ # Givem a chance to start
+ win32api.Sleep(100)
+ win32ui.PumpWaitingMessages()
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ ThreadedDemo()
+# Demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/toolbar.py b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/toolbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..39fd86442fc5b3267d247cba4f14a0a279031a3a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/Demos/toolbar.py
@@ -0,0 +1,105 @@
+# Demo of ToolBars
+
+# Shows the toolbar control.
+# Demos how to make custom tooltips, etc.
+
+import commctrl
+import win32con
+import win32ui
+from pywin.mfc import afxres, docview, window
+
+
+class GenericFrame(window.MDIChildWnd):
+ def OnCreateClient(self, cp, context):
+ # handlers for toolbar buttons
+ self.HookCommand(self.OnPrevious, 401)
+ self.HookCommand(self.OnNext, 402)
+ # It's not necessary for us to hook both of these - the
+ # common controls should fall-back all by themselves.
+ # Indeed, given we hook TTN_NEEDTEXTW, commctrl.TTN_NEEDTEXTA
+ # will not be called.
+ self.HookNotify(self.GetTTText, commctrl.TTN_NEEDTEXT)
+ self.HookNotify(self.GetTTText, commctrl.TTN_NEEDTEXTW)
+
+ # parent = win32ui.GetMainFrame()
+ parent = self
+ style = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | afxres.CBRS_SIZE_DYNAMIC
+ | afxres.CBRS_TOP
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ )
+
+ buttons = (win32ui.ID_APP_ABOUT, win32ui.ID_VIEW_INTERACTIVE)
+ bitmap = win32ui.IDB_BROWSER_HIER
+ tbid = 0xE840
+ self.toolbar = tb = win32ui.CreateToolBar(parent, style, tbid)
+ tb.LoadBitmap(bitmap)
+ tb.SetButtons(buttons)
+
+ tb.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ tb.SetWindowText("Test")
+ parent.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ parent.DockControlBar(tb)
+ parent.LoadBarState("ToolbarTest")
+ window.MDIChildWnd.OnCreateClient(self, cp, context)
+ return 1
+
+ def OnDestroy(self, msg):
+ self.SaveBarState("ToolbarTest")
+
+ def GetTTText(self, std, extra):
+ (hwndFrom, idFrom, code) = std
+ text, hinst, flags = extra
+ if flags & commctrl.TTF_IDISHWND:
+ return # Not handled
+ if idFrom == win32ui.ID_APP_ABOUT:
+ # our 'extra' return value needs to be the following
+ # entries from a NMTTDISPINFO[W] struct:
+ # (szText, hinst, uFlags). None means 'don't change
+ # the value'
+ return 0, ("It works!", None, None)
+ return None # not handled.
+
+ def GetMessageString(self, id):
+ if id == win32ui.ID_APP_ABOUT:
+ return "Dialog Test\nTest"
+ else:
+ return self._obj_.GetMessageString(id)
+
+ def OnSize(self, params):
+ print("OnSize called with ", params)
+
+ def OnNext(self, id, cmd):
+ print("OnNext called")
+
+ def OnPrevious(self, id, cmd):
+ print("OnPrevious called")
+
+
+msg = """\
+This toolbar was dynamically created.\r
+\r
+The first item's tooltips is provided by Python code.\r
+\r
+(Don't close the window with the toolbar in a floating state - it may not re-appear!)\r
+"""
+
+
+def test():
+ template = docview.DocTemplate(
+ win32ui.IDR_PYTHONTYPE, None, GenericFrame, docview.EditView
+ )
+ doc = template.OpenDocumentFile(None)
+ doc.SetTitle("Toolbar Test")
+ view = doc.GetFirstView()
+ view.SetWindowText(msg)
+
+
+if __name__ == "__main__":
+ import demoutils
+
+ if demoutils.NeedGoodGUI():
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/IDLE.cfg b/python_embeded/Lib/site-packages/pythonwin/pywin/IDLE.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..f2491e4c8e3531e9a5a1d3f23cf446e02f0c99d7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/IDLE.cfg
@@ -0,0 +1,28 @@
+[General]
+# We base this configuration on the default config.
+# You can list "Based On" as many times as you like
+Based On = default
+
+[Keys]
+# Only list keys different to default.
+# Note you may wish to rebind some of the default
+# Pythonwin keys to "Beep" or "DoNothing"
+
+Alt+L = LocateSelectedFile
+Ctrl+Q = AppExit
+
+# Other non-default Pythonwin keys
+Alt+A = EditSelectAll
+Alt+M = LocateModule
+
+# Movement
+Ctrl+D = GotoEndOfFile
+
+# Tabs and other indent features
+Alt+T = <>
+Ctrl+[ = <>
+Ctrl+] = <>
+
+[Keys:Interactive]
+Alt+P = <>
+Alt+N = <>
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..23f3bdbb554a1d76220ccdd9d6963f68c20c123d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/__init__.py
@@ -0,0 +1,3 @@
+# Referenced and used variable - but in practice can't be changed.
+# Scintilla _only_ supports "utf-8" ATM
+default_scintilla_encoding = "utf-8"
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3dc6ab5799c233990e65c134150abbf7b846c9f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/__init__.py
@@ -0,0 +1,133 @@
+import sys
+
+isInprocApp = -1
+
+
+def _CheckNeedGUI():
+ global isInprocApp
+ if isInprocApp == -1:
+ import win32ui
+
+ isInprocApp = win32ui.GetApp().IsInproc()
+ if isInprocApp:
+ # MAY Need it - may already have one
+ need = "pywin.framework.app" not in sys.modules
+ else:
+ need = 0
+ if need:
+ import pywin.framework.app
+
+ from . import dbgpyapp
+
+ pywin.framework.app.CreateDefaultGUI(dbgpyapp.DebuggerPythonApp)
+
+ else:
+ # Check we have the appropriate editor
+ # No longer necessary!
+ pass
+ return need
+
+
+# Inject some methods in the top level name-space.
+currentDebugger = None # Wipe out any old one on reload.
+
+
+def _GetCurrentDebugger():
+ global currentDebugger
+ if currentDebugger is None:
+ _CheckNeedGUI()
+ from . import debugger
+
+ currentDebugger = debugger.Debugger()
+ return currentDebugger
+
+
+def GetDebugger():
+ # An error here is not nice - as we are probably trying to
+ # break into the debugger on a Python error, any
+ # error raised by this is usually silent, and causes
+ # big problems later!
+ try:
+ rc = _GetCurrentDebugger()
+ rc.GUICheckInit()
+ return rc
+ except:
+ print("Could not create the debugger!")
+ import traceback
+
+ traceback.print_exc()
+ return None
+
+
+def close():
+ if currentDebugger is not None:
+ currentDebugger.close()
+
+
+def run(cmd, globals=None, locals=None, start_stepping=1):
+ _GetCurrentDebugger().run(cmd, globals, locals, start_stepping)
+
+
+def runeval(expression, globals=None, locals=None):
+ return _GetCurrentDebugger().runeval(expression, globals, locals)
+
+
+def runcall(*args):
+ return _GetCurrentDebugger().runcall(*args)
+
+
+def set_trace():
+ import sys
+
+ d = _GetCurrentDebugger()
+
+ if d.frameShutdown:
+ return # App closing
+
+ if d.stopframe != d.botframe:
+ # If I'm not "running"
+ return
+
+ sys.settrace(None) # May be hooked
+ d.reset()
+ d.set_trace()
+
+
+# "brk" is an alias for "set_trace" ("break" is a reserved word :-(
+brk = set_trace
+
+# Post-Mortem interface
+
+
+def post_mortem(t=None):
+ if t is None:
+ t = sys.exc_info()[2] # Will be valid if we are called from an except handler.
+ if t is None:
+ try:
+ t = sys.last_traceback
+ except AttributeError:
+ print(
+ "No traceback can be found from which to perform post-mortem debugging!"
+ )
+ print("No debugging can continue")
+ return
+ p = _GetCurrentDebugger()
+ if p.frameShutdown:
+ return # App closing
+ # No idea why I need to settrace to None - it should have been reset by now?
+ sys.settrace(None)
+ p.reset()
+ while t.tb_next is not None:
+ t = t.tb_next
+ p.bAtPostMortem = 1
+ p.prep_run(None)
+ try:
+ p.interaction(t.tb_frame, t)
+ finally:
+ t = None
+ p.bAtPostMortem = 0
+ p.done_run()
+
+
+def pm(t=None):
+ post_mortem(t)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/configui.py b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/configui.py
new file mode 100644
index 0000000000000000000000000000000000000000..be8e5b6246663cb31f68bbfd733823cdf5676e43
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/configui.py
@@ -0,0 +1,34 @@
+import win32ui
+from pywin.mfc import dialog
+
+from . import dbgcon
+
+
+class DebuggerOptionsPropPage(dialog.PropertyPage):
+ def __init__(self):
+ dialog.PropertyPage.__init__(self, win32ui.IDD_PP_DEBUGGER)
+
+ def OnInitDialog(self):
+ options = self.options = dbgcon.LoadDebuggerOptions()
+ self.AddDDX(win32ui.IDC_CHECK1, dbgcon.OPT_HIDE)
+ self[dbgcon.OPT_STOP_EXCEPTIONS] = options[dbgcon.OPT_STOP_EXCEPTIONS]
+ self.AddDDX(win32ui.IDC_CHECK2, dbgcon.OPT_STOP_EXCEPTIONS)
+ self[dbgcon.OPT_HIDE] = options[dbgcon.OPT_HIDE]
+ return dialog.PropertyPage.OnInitDialog(self)
+
+ def OnOK(self):
+ self.UpdateData()
+ dirty = 0
+ for key, val in self.items():
+ if key in self.options:
+ if self.options[key] != val:
+ self.options[key] = val
+ dirty = 1
+ if dirty:
+ dbgcon.SaveDebuggerOptions(self.options)
+ # If there is a debugger open, then set its options.
+ import pywin.debugger
+
+ if pywin.debugger.currentDebugger is not None:
+ pywin.debugger.currentDebugger.options = self.options
+ return 1
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/dbgcon.py b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/dbgcon.py
new file mode 100644
index 0000000000000000000000000000000000000000..fd2a174460c9c5834ed8bd84f573fd6aa6ccc0c8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/dbgcon.py
@@ -0,0 +1,31 @@
+# General constants for the debugger
+
+DBGSTATE_NOT_DEBUGGING = 0
+DBGSTATE_RUNNING = 1
+DBGSTATE_BREAK = 2
+DBGSTATE_QUITTING = 3 # Attempting to back out of the debug session.
+
+LINESTATE_CURRENT = 0x1 # This line is where we are stopped
+LINESTATE_BREAKPOINT = 0x2 # This line is a breakpoint
+LINESTATE_CALLSTACK = 0x4 # This line is in the callstack.
+
+OPT_HIDE = "hide"
+OPT_STOP_EXCEPTIONS = "stopatexceptions"
+
+import win32ui
+
+
+def DoGetOption(optsDict, optName, default):
+ optsDict[optName] = win32ui.GetProfileVal("Debugger Options", optName, default)
+
+
+def LoadDebuggerOptions():
+ opts = {}
+ DoGetOption(opts, OPT_HIDE, 0)
+ DoGetOption(opts, OPT_STOP_EXCEPTIONS, 1)
+ return opts
+
+
+def SaveDebuggerOptions(opts):
+ for key, val in opts.items():
+ win32ui.WriteProfileVal("Debugger Options", key, val)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/dbgpyapp.py b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/dbgpyapp.py
new file mode 100644
index 0000000000000000000000000000000000000000..881897ee1ebe6d05d2f50371a8ecfe54199d2bb0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/dbgpyapp.py
@@ -0,0 +1,48 @@
+# dbgpyapp.py - Debugger Python application class
+#
+import sys
+
+import win32con
+import win32ui
+from pywin.framework import intpyapp
+
+version = "0.3.0"
+
+
+class DebuggerPythonApp(intpyapp.InteractivePythonApp):
+ def LoadMainFrame(self):
+ "Create the main applications frame"
+ self.frame = self.CreateMainFrame()
+ self.SetMainFrame(self.frame)
+ self.frame.LoadFrame(win32ui.IDR_DEBUGGER, win32con.WS_OVERLAPPEDWINDOW)
+ self.frame.DragAcceptFiles() # we can accept these.
+ self.frame.ShowWindow(win32con.SW_HIDE)
+ self.frame.UpdateWindow()
+
+ # but we do rehook, hooking the new code objects.
+ self.HookCommands()
+
+ def InitInstance(self):
+ # Use a registry path of "Python\Pythonwin Debugger
+ win32ui.SetAppName(win32ui.LoadString(win32ui.IDR_DEBUGGER))
+ win32ui.SetRegistryKey(f"Python {sys.winver}")
+ # We _need_ the Scintilla color editor.
+ # (and we _always_ get it now :-)
+
+ numMRU = win32ui.GetProfileVal("Settings", "Recent File List Size", 10)
+ win32ui.LoadStdProfileSettings(numMRU)
+
+ self.LoadMainFrame()
+
+ # Display the interactive window if the user wants it.
+ from pywin.framework import interact
+
+ interact.CreateInteractiveWindowUserPreference()
+
+ # Load the modules we use internally.
+ self.LoadSystemModules()
+ # Load additional module the user may want.
+ self.LoadUserModules()
+
+ # win32ui.CreateDebuggerThread()
+ win32ui.EnableControlContainer()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/debugger.py b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/debugger.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cd64743384ea16ea81ea68c249d3bd018cc3af1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/debugger.py
@@ -0,0 +1,1097 @@
+# debugger.py
+
+# A debugger for Pythonwin. Built from pdb.
+
+# Mark Hammond (MHammond@skippinet.com.au) - Dec 94.
+
+# usage:
+# >>> import pywin.debugger
+# >>> pywin.debugger.GetDebugger().run("command")
+
+import bdb
+import os
+import pdb
+import string
+import sys
+import traceback
+import types
+
+import commctrl
+import pywin.docking.DockingBar
+import win32api
+import win32con
+import win32ui
+from pywin.framework import app, editor, interact, scriptutils
+from pywin.framework.editor.color.coloreditor import MARKER_BREAKPOINT, MARKER_CURRENT
+from pywin.mfc import afxres, window
+from pywin.tools import browser, hierlist
+
+from .dbgcon import *
+
+LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW
+
+
+def SetInteractiveContext(globs, locs):
+ if interact.edit is not None and interact.edit.currentView is not None:
+ interact.edit.currentView.SetContext(globs, locs)
+
+
+def _LineStateToMarker(ls):
+ if ls == LINESTATE_CURRENT:
+ return MARKER_CURRENT
+ # elif ls == LINESTATE_CALLSTACK:
+ # return MARKER_CALLSTACK
+ return MARKER_BREAKPOINT
+
+
+class HierListItem(browser.HLIPythonObject):
+ pass
+
+
+class HierFrameItem(HierListItem):
+ def __init__(self, frame, debugger):
+ HierListItem.__init__(self, frame, repr(frame))
+ self.debugger = debugger
+
+ def GetText(self):
+ name = self.myobject.f_code.co_name
+ if not name or name == "?":
+ # See if locals has a '__name__' (ie, a module)
+ if "__name__" in self.myobject.f_locals:
+ name = str(self.myobject.f_locals["__name__"]) + " module"
+ else:
+ name = ""
+
+ return "%s (%s:%d)" % (
+ name,
+ os.path.split(self.myobject.f_code.co_filename)[1],
+ self.myobject.f_lineno,
+ )
+
+ def GetBitmapColumn(self):
+ if self.debugger.curframe is self.myobject:
+ return 7
+ else:
+ return 8
+
+ def GetSubList(self):
+ ret = []
+ ret.append(HierFrameDict(self.myobject.f_locals, "Locals", 2))
+ ret.append(HierFrameDict(self.myobject.f_globals, "Globals", 1))
+ return ret
+
+ def IsExpandable(self):
+ return 1
+
+ def TakeDefaultAction(self):
+ # Set the default frame to be this frame.
+ self.debugger.set_cur_frame(self.myobject)
+ return 1
+
+
+class HierFrameDict(browser.HLIDict):
+ def __init__(self, dict, name, bitmapColumn):
+ self.bitmapColumn = bitmapColumn
+ browser.HLIDict.__init__(self, dict, name)
+
+ def GetBitmapColumn(self):
+ return self.bitmapColumn
+
+
+class NoStackAvailableItem(HierListItem):
+ def __init__(self, why):
+ HierListItem.__init__(self, None, why)
+
+ def IsExpandable(self):
+ return 0
+
+ def GetText(self):
+ return self.name
+
+ def GetBitmapColumn(self):
+ return 8
+
+
+class HierStackRoot(HierListItem):
+ def __init__(self, debugger):
+ HierListItem.__init__(self, debugger, None)
+ self.last_stack = []
+
+ # def __del__(self):
+ # print("HierStackRoot dieing")
+ def GetSubList(self):
+ debugger = self.myobject
+ # print(self.debugger.stack, self.debugger.curframe)
+ ret = []
+ if debugger.debuggerState == DBGSTATE_BREAK:
+ stackUse = debugger.stack[:]
+ stackUse.reverse()
+ self.last_stack = []
+ for frame, lineno in stackUse:
+ self.last_stack.append((frame, lineno))
+ if (
+ frame is debugger.userbotframe
+ ): # Don't bother showing frames below our bottom frame.
+ break
+ for frame, lineno in self.last_stack:
+ ret.append(HierFrameItem(frame, debugger))
+ ## elif debugger.debuggerState==DBGSTATE_NOT_DEBUGGING:
+ ## ret.append(NoStackAvailableItem(''))
+ ## else:
+ ## ret.append(NoStackAvailableItem(''))
+ return ret
+
+ def GetText(self):
+ return "root item"
+
+ def IsExpandable(self):
+ return 1
+
+
+class HierListDebugger(hierlist.HierListWithItems):
+ """Hier List of stack frames, breakpoints, whatever"""
+
+ def __init__(self):
+ hierlist.HierListWithItems.__init__(
+ self, None, win32ui.IDB_DEBUGGER_HIER, None, win32api.RGB(255, 0, 0)
+ )
+
+ def Setup(self, debugger):
+ root = HierStackRoot(debugger)
+ self.AcceptRoot(root)
+
+
+# def Refresh(self):
+# self.Setup()
+
+
+class DebuggerWindow(window.Wnd):
+ def __init__(self, ob):
+ window.Wnd.__init__(self, ob)
+ self.debugger = None
+
+ def Init(self, debugger):
+ self.debugger = debugger
+
+ def GetDefRect(self):
+ defRect = app.LoadWindowSize("Debugger Windows\\" + self.title)
+ if defRect[2] - defRect[0] == 0:
+ defRect = 0, 0, 150, 150
+ return defRect
+
+ def OnDestroy(self, msg):
+ newSize = self.GetWindowPlacement()[4]
+ pywin.framework.app.SaveWindowSize("Debugger Windows\\" + self.title, newSize)
+ return window.Wnd.OnDestroy(self, msg)
+
+ def OnKeyDown(self, msg):
+ key = msg[2]
+ if key in (13, 27, 32):
+ return 1
+ if key in (46, 8): # delete/BS key
+ self.DeleteSelected()
+ return 0
+ view = scriptutils.GetActiveView()
+ try:
+ firer = view.bindings.fire_key_event
+ except AttributeError:
+ firer = None
+ if firer is not None:
+ return firer(msg)
+ else:
+ return 1
+
+ def DeleteSelected(self):
+ win32api.MessageBeep()
+
+ def EditSelected(self):
+ win32api.MessageBeep()
+
+
+class DebuggerStackWindow(DebuggerWindow):
+ title = "Stack"
+
+ def __init__(self):
+ DebuggerWindow.__init__(self, win32ui.CreateTreeCtrl())
+ self.list = HierListDebugger()
+ self.listOK = 0
+
+ def SaveState(self):
+ self.list.DeleteAllItems()
+ self.listOK = 0
+ win32ui.WriteProfileVal(
+ "Debugger Windows\\" + self.title, "Visible", self.IsWindowVisible()
+ )
+
+ def CreateWindow(self, parent):
+ style = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | win32con.WS_BORDER
+ | commctrl.TVS_HASLINES
+ | commctrl.TVS_LINESATROOT
+ | commctrl.TVS_HASBUTTONS
+ )
+ self._obj_.CreateWindow(style, self.GetDefRect(), parent, win32ui.IDC_LIST1)
+ self.HookMessage(self.OnKeyDown, win32con.WM_KEYDOWN)
+ self.HookMessage(self.OnKeyDown, win32con.WM_SYSKEYDOWN)
+ self.list.HierInit(parent, self)
+ self.listOK = 0 # delayed setup
+ # self.list.Setup()
+
+ def RespondDebuggerState(self, state):
+ assert self.debugger is not None, "Init not called"
+ if not self.listOK:
+ self.listOK = 1
+ self.list.Setup(self.debugger)
+ else:
+ self.list.Refresh()
+
+ def RespondDebuggerData(self):
+ try:
+ handle = self.GetChildItem(0)
+ except win32ui.error:
+ return # No items
+ while 1:
+ item = self.list.ItemFromHandle(handle)
+ col = self.list.GetBitmapColumn(item)
+ selCol = self.list.GetSelectedBitmapColumn(item)
+ if selCol is None:
+ selCol = col
+ if self.list.GetItemImage(handle) != (col, selCol):
+ self.list.SetItemImage(handle, col, selCol)
+ try:
+ handle = self.GetNextSiblingItem(handle)
+ except win32ui.error:
+ break
+
+
+class DebuggerListViewWindow(DebuggerWindow):
+ def __init__(self):
+ DebuggerWindow.__init__(self, win32ui.CreateListCtrl())
+
+ def CreateWindow(self, parent):
+ list = self
+ style = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | win32con.WS_BORDER
+ | commctrl.LVS_EDITLABELS
+ | commctrl.LVS_REPORT
+ )
+ self._obj_.CreateWindow(style, self.GetDefRect(), parent, win32ui.IDC_LIST1)
+ self.HookMessage(self.OnKeyDown, win32con.WM_KEYDOWN)
+ self.HookMessage(self.OnKeyDown, win32con.WM_SYSKEYDOWN)
+ list = self
+ title, width = self.columns[0]
+ itemDetails = (commctrl.LVCFMT_LEFT, width, title, 0)
+ list.InsertColumn(0, itemDetails)
+ col = 1
+ for title, width in self.columns[1:]:
+ col += 1
+ itemDetails = (commctrl.LVCFMT_LEFT, width, title, 0)
+ list.InsertColumn(col, itemDetails)
+ parent.HookNotify(self.OnListEndLabelEdit, LVN_ENDLABELEDIT)
+ parent.HookNotify(self.OnItemRightClick, commctrl.NM_RCLICK)
+ parent.HookNotify(self.OnItemDoubleClick, commctrl.NM_DBLCLK)
+
+ def RespondDebuggerData(self):
+ pass
+
+ def RespondDebuggerState(self, state):
+ pass
+
+ def EditSelected(self):
+ try:
+ sel = self.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ except win32ui.error:
+ return
+ self.EditLabel(sel)
+
+ def OnKeyDown(self, msg):
+ key = msg[2]
+ # If someone starts typing, they probably are trying to edit the text!
+ if chr(key) in string.ascii_uppercase:
+ self.EditSelected()
+ return 0
+ return DebuggerWindow.OnKeyDown(self, msg)
+
+ def OnItemDoubleClick(self, notify_data, extra):
+ self.EditSelected()
+
+ def OnItemRightClick(self, notify_data, extra):
+ # First select the item we right-clicked on.
+ pt = self.ScreenToClient(win32api.GetCursorPos())
+ flags, hItem, subitem = self.HitTest(pt)
+ if hItem == -1 or commctrl.TVHT_ONITEM & flags == 0:
+ return None
+ self.SetItemState(hItem, commctrl.LVIS_SELECTED, commctrl.LVIS_SELECTED)
+
+ menu = win32ui.CreatePopupMenu()
+ menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1000, "Edit item")
+ menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1001, "Delete item")
+ dockbar = self.GetParent()
+ if dockbar.IsFloating():
+ hook_parent = win32ui.GetMainFrame()
+ else:
+ hook_parent = self.GetParentFrame()
+ hook_parent.HookCommand(self.OnEditItem, 1000)
+ hook_parent.HookCommand(self.OnDeleteItem, 1001)
+ menu.TrackPopupMenu(win32api.GetCursorPos()) # track at mouse position.
+ return None
+
+ def OnDeleteItem(self, command, code):
+ self.DeleteSelected()
+
+ def OnEditItem(self, command, code):
+ self.EditSelected()
+
+
+class DebuggerBreakpointsWindow(DebuggerListViewWindow):
+ title = "Breakpoints"
+ columns = [("Condition", 70), ("Location", 1024)]
+
+ def SaveState(self):
+ items = []
+ for i in range(self.GetItemCount()):
+ items.append(self.GetItemText(i, 0))
+ items.append(self.GetItemText(i, 1))
+ win32ui.WriteProfileVal(
+ "Debugger Windows\\" + self.title, "BreakpointList", "\t".join(items)
+ )
+ win32ui.WriteProfileVal(
+ "Debugger Windows\\" + self.title, "Visible", self.IsWindowVisible()
+ )
+ return 1
+
+ def OnListEndLabelEdit(self, std, extra):
+ item = extra[0]
+ text = item[4]
+ if text is None:
+ return
+
+ item_id = self.GetItem(item[0])[6]
+
+ from bdb import Breakpoint
+
+ for bplist in Breakpoint.bplist.values():
+ for bp in bplist:
+ if id(bp) == item_id:
+ if text.strip().lower() == "none":
+ text = None
+ bp.cond = text
+ break
+ self.RespondDebuggerData()
+
+ def DeleteSelected(self):
+ try:
+ num = self.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ item_id = self.GetItem(num)[6]
+ from bdb import Breakpoint
+
+ for bplist in Breakpoint.bplist.values():
+ for bp in bplist:
+ if id(bp) == item_id:
+ self.debugger.clear_break(bp.file, bp.line)
+ break
+ except win32ui.error:
+ win32api.MessageBeep()
+ self.RespondDebuggerData()
+
+ def RespondDebuggerData(self):
+ l = self
+ l.DeleteAllItems()
+ index = -1
+ from bdb import Breakpoint
+
+ for bplist in Breakpoint.bplist.values():
+ for bp in bplist:
+ baseName = os.path.split(bp.file)[1]
+ cond = bp.cond
+ item = index + 1, 0, 0, 0, str(cond), 0, id(bp)
+ index = l.InsertItem(item)
+ l.SetItemText(index, 1, f"{baseName}: {bp.line}")
+
+
+class DebuggerWatchWindow(DebuggerListViewWindow):
+ title = "Watch"
+ columns = [("Expression", 70), ("Value", 1024)]
+
+ def CreateWindow(self, parent):
+ DebuggerListViewWindow.CreateWindow(self, parent)
+ items = win32ui.GetProfileVal(
+ "Debugger Windows\\" + self.title, "Items", ""
+ ).split("\t")
+ index = -1
+ for item in items:
+ if item:
+ index = self.InsertItem(index + 1, item)
+ self.InsertItem(index + 1, "")
+
+ def SaveState(self):
+ items = []
+ for i in range(self.GetItemCount() - 1):
+ items.append(self.GetItemText(i, 0))
+ win32ui.WriteProfileVal(
+ "Debugger Windows\\" + self.title, "Items", "\t".join(items)
+ )
+ win32ui.WriteProfileVal(
+ "Debugger Windows\\" + self.title, "Visible", self.IsWindowVisible()
+ )
+ return 1
+
+ def OnListEndLabelEdit(self, std, extra):
+ item = extra[0]
+ itemno = item[0]
+ text = item[4]
+ if text is None:
+ return
+ self.SetItemText(itemno, 0, text)
+ if itemno == self.GetItemCount() - 1:
+ self.InsertItem(itemno + 1, "")
+ self.RespondDebuggerState(self.debugger.debuggerState)
+
+ def DeleteSelected(self):
+ try:
+ num = self.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ if num < self.GetItemCount() - 1: # We can't delete the last
+ self.DeleteItem(num)
+ except win32ui.error:
+ win32api.MessageBeep()
+
+ def RespondDebuggerState(self, state):
+ globs = locs = None
+ if state == DBGSTATE_BREAK:
+ if self.debugger.curframe:
+ globs = self.debugger.curframe.f_globals
+ locs = self.debugger.curframe.f_locals
+ elif state == DBGSTATE_NOT_DEBUGGING:
+ import __main__
+
+ globs = locs = __main__.__dict__
+ for i in range(self.GetItemCount() - 1):
+ text = self.GetItemText(i, 0)
+ if globs is None:
+ val = ""
+ else:
+ try:
+ val = repr(eval(text, globs, locs))
+ except SyntaxError:
+ val = "Syntax Error"
+ except:
+ t, v, tb = sys.exc_info()
+ val = traceback.format_exception_only(t, v)[0].strip()
+ tb = None # prevent a cycle.
+ self.SetItemText(i, 1, val)
+
+
+def CreateDebuggerDialog(parent, klass):
+ control = klass()
+ control.CreateWindow(parent)
+ return control
+
+
+DebuggerDialogInfos = (
+ (0xE810, DebuggerStackWindow, None),
+ (0xE811, DebuggerBreakpointsWindow, (10, 10)),
+ (0xE812, DebuggerWatchWindow, None),
+)
+
+
+# Prepare all the "control bars" for this package.
+# If control bars are not all loaded when the toolbar-state functions are
+# called, things go horribly wrong.
+def PrepareControlBars(frame):
+ style = (
+ win32con.WS_CHILD
+ | afxres.CBRS_SIZE_DYNAMIC
+ | afxres.CBRS_TOP
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ )
+ tbd = win32ui.CreateToolBar(frame, style, win32ui.ID_VIEW_TOOLBAR_DBG)
+ tbd.ModifyStyle(0, commctrl.TBSTYLE_FLAT)
+ tbd.LoadToolBar(win32ui.IDR_DEBUGGER)
+ tbd.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ tbd.SetWindowText("Debugger")
+ frame.DockControlBar(tbd)
+
+ # and the other windows.
+ for id, klass, float in DebuggerDialogInfos:
+ try:
+ frame.GetControlBar(id)
+ exists = 1
+ except win32ui.error:
+ exists = 0
+ if exists:
+ continue
+ bar = pywin.docking.DockingBar.DockingBar()
+ style = win32con.WS_CHILD | afxres.CBRS_LEFT # don't create visible.
+ bar.CreateWindow(
+ frame,
+ CreateDebuggerDialog,
+ klass.title,
+ id,
+ style,
+ childCreatorArgs=(klass,),
+ )
+ bar.SetBarStyle(
+ bar.GetBarStyle()
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ | afxres.CBRS_SIZE_DYNAMIC
+ )
+ bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ if float is None:
+ frame.DockControlBar(bar)
+ else:
+ frame.FloatControlBar(bar, float, afxres.CBRS_ALIGN_ANY)
+
+ ## frame.ShowControlBar(bar, 0, 1)
+
+
+SKIP_NONE = 0
+SKIP_STEP = 1
+SKIP_RUN = 2
+
+debugger_parent = pdb.Pdb
+
+
+class Debugger(debugger_parent):
+ def __init__(self):
+ self.inited = 0
+ self.skipBotFrame = SKIP_NONE
+ self.userbotframe = None
+ self.frameShutdown = 0
+ self.pumping = 0
+ self.debuggerState = DBGSTATE_NOT_DEBUGGING # Assume so, anyway.
+ self.shownLineCurrent = None # The last filename I highlighted.
+ self.shownLineCallstack = None # The last filename I highlighted.
+ self.last_cmd_debugged = ""
+ self.abortClosed = 0
+ self.isInitialBreakpoint = 0
+ debugger_parent.__init__(self)
+
+ # See if any break-points have been set in the editor
+ for doc in editor.editorTemplate.GetDocumentList():
+ lineNo = -1
+ while 1:
+ lineNo = doc.MarkerGetNext(lineNo + 1, MARKER_BREAKPOINT)
+ if lineNo <= 0:
+ break
+ self.set_break(doc.GetPathName(), lineNo)
+
+ self.reset()
+ self.inForcedGUI = win32ui.GetApp().IsInproc()
+ self.options = LoadDebuggerOptions()
+ self.bAtException = self.bAtPostMortem = 0
+
+ def __del__(self):
+ self.close()
+
+ def close(self, frameShutdown=0):
+ # abortClose indicates if we have total shutdown
+ # (ie, main window is dieing)
+ if self.pumping:
+ # Can stop pump here, as it only posts a message, and
+ # returns immediately.
+ if not self.StopDebuggerPump(): # User cancelled close.
+ return 0
+ # NOTE - from this point on the close can not be
+ # stopped - the WM_QUIT message is already in the queue.
+ self.frameShutdown = frameShutdown
+ if not self.inited:
+ return 1
+ self.inited = 0
+
+ SetInteractiveContext(None, None)
+
+ frame = win32ui.GetMainFrame()
+ # Hide the debuger toolbars (as they won't normally form part of the main toolbar state.
+ for id, klass, float in DebuggerDialogInfos:
+ try:
+ tb = frame.GetControlBar(id)
+ if tb.dialog is not None: # We may never have actually been shown.
+ tb.dialog.SaveState()
+ frame.ShowControlBar(tb, 0, 1)
+ except win32ui.error:
+ pass
+
+ self._UnshowCurrentLine()
+ self.set_quit()
+ return 1
+
+ def StopDebuggerPump(self):
+ assert self.pumping, "Can't stop the debugger pump if I'm not pumping!"
+ # After stopping a pump, I may never return.
+ if self.GUIAboutToFinishInteract():
+ self.pumping = 0
+ win32ui.StopDebuggerPump() # Posts a message, so we do return.
+ return 1
+ return 0
+
+ def get_option(self, option):
+ """Public interface into debugger options"""
+ try:
+ return self.options[option]
+ except KeyError as error:
+ raise KeyError(f"Option {option} is not a valid option") from error
+
+ def prep_run(self, cmd):
+ pass
+
+ def done_run(self, cmd=None):
+ self.RespondDebuggerState(DBGSTATE_NOT_DEBUGGING)
+ self.close()
+
+ def canonic(self, fname):
+ return os.path.abspath(fname).lower()
+
+ def reset(self):
+ debugger_parent.reset(self)
+ self.userbotframe = None
+ self.UpdateAllLineStates()
+ self._UnshowCurrentLine()
+
+ def setup(self, f, t):
+ debugger_parent.setup(self, f, t)
+ self.bAtException = t is not None
+
+ def set_break(self, filename, lineno, temporary=0, cond=None):
+ filename = self.canonic(filename)
+ self.SetLineState(filename, lineno, LINESTATE_BREAKPOINT)
+ return debugger_parent.set_break(self, filename, lineno, temporary, cond)
+
+ def clear_break(self, filename, lineno):
+ filename = self.canonic(filename)
+ self.ResetLineState(filename, lineno, LINESTATE_BREAKPOINT)
+ return debugger_parent.clear_break(self, filename, lineno)
+
+ def cmdloop(self):
+ if self.frameShutdown:
+ return # App in the process of closing - never break in!
+ self.GUIAboutToBreak()
+
+ def print_stack_entry(self, frame):
+ # We don't want a stack printed - our GUI is better :-)
+ pass
+
+ def user_return(self, frame, return_value):
+ # Same as parent, just no "print"
+ # This function is called when a return trap is set here
+ frame.f_locals["__return__"] = return_value
+ self.interaction(frame, None)
+
+ def user_call(self, frame, args):
+ # base class has an annoying 'print' that adds no value to us...
+ if self.stop_here(frame):
+ self.interaction(frame, None)
+
+ def user_exception(self, frame, exc_info):
+ # This function is called if an exception occurs,
+ # but only if we are to stop at or just below this level
+ (exc_type, exc_value, exc_traceback) = exc_info
+ if self.get_option(OPT_STOP_EXCEPTIONS):
+ frame.f_locals["__exception__"] = exc_type, exc_value
+ print("Unhandled exception while debugging...")
+ # We may be called with exc_value
+ # being the args to the exception, or it may already be
+ # instantiated (IOW, PyErr_Normalize() hasn't been
+ # called on the args). traceback.print_exception fails.
+ # So we instantiate an exception instance to print.
+ if not isinstance(exc_value, BaseException):
+ # they are args - may be a single item or already a tuple
+ if not isinstance(exc_value, tuple):
+ exc_value = (exc_value,)
+ exc_value = exc_type(*exc_value)
+
+ traceback.print_exception(exc_type, exc_value, exc_traceback)
+ self.interaction(frame, exc_traceback)
+
+ def user_line(self, frame):
+ if frame.f_lineno == 0:
+ return
+ debugger_parent.user_line(self, frame)
+
+ def stop_here(self, frame):
+ if self.isInitialBreakpoint:
+ self.isInitialBreakpoint = 0
+ self.set_continue()
+ return 0
+ if frame is self.botframe and self.skipBotFrame == SKIP_RUN:
+ self.set_continue()
+ return 0
+ if frame is self.botframe and self.skipBotFrame == SKIP_STEP:
+ self.set_step()
+ return 0
+ return debugger_parent.stop_here(self, frame)
+
+ def run(self, cmd, globals=None, locals=None, start_stepping=1):
+ if not isinstance(cmd, (str, types.CodeType)):
+ raise TypeError("Only strings can be run")
+ self.last_cmd_debugged = cmd
+ if start_stepping:
+ self.isInitialBreakpoint = 0
+ else:
+ self.isInitialBreakpoint = 1
+ try:
+ if globals is None:
+ import __main__
+
+ globals = __main__.__dict__
+ if locals is None:
+ locals = globals
+ self.reset()
+ self.prep_run(cmd)
+ sys.settrace(self.trace_dispatch)
+ if not isinstance(cmd, types.CodeType):
+ cmd += "\n"
+ try:
+ try:
+ if start_stepping:
+ self.skipBotFrame = SKIP_STEP
+ else:
+ self.skipBotFrame = SKIP_RUN
+ exec(cmd, globals, locals)
+ except bdb.BdbQuit:
+ pass
+ finally:
+ self.skipBotFrame = SKIP_NONE
+ self.quitting = 1
+ sys.settrace(None)
+
+ finally:
+ self.done_run(cmd)
+
+ def runeval(self, expr, globals=None, locals=None):
+ self.prep_run(expr)
+ try:
+ debugger_parent.runeval(self, expr, globals, locals)
+ finally:
+ self.done_run(expr)
+
+ def runexec(self, what, globs=None, locs=None):
+ self.reset()
+ sys.settrace(self.trace_dispatch)
+ try:
+ try:
+ exec(what, globs, locs)
+ except bdb.BdbQuit:
+ pass
+ finally:
+ self.quitting = 1
+ sys.settrace(None)
+
+ def do_set_step(self):
+ if self.GUIAboutToRun():
+ self.set_step()
+
+ def do_set_next(self):
+ if self.GUIAboutToRun():
+ self.set_next(self.curframe)
+
+ def do_set_return(self):
+ if self.GUIAboutToRun():
+ self.set_return(self.curframe)
+
+ def do_set_continue(self):
+ if self.GUIAboutToRun():
+ self.set_continue()
+
+ def set_quit(self):
+ ok = 1
+ if self.pumping:
+ ok = self.StopDebuggerPump()
+ if ok:
+ debugger_parent.set_quit(self)
+
+ def _dump_frame_(self, frame, name=None):
+ if name is None:
+ name = ""
+ if frame:
+ if frame.f_code and frame.f_code.co_filename:
+ fname = os.path.split(frame.f_code.co_filename)[1]
+ else:
+ fname = "??"
+ print(repr(name), fname, frame.f_lineno, frame)
+ else:
+ print(repr(name), "None")
+
+ def set_trace(self):
+ # Start debugging from _2_ levels up!
+ try:
+ 1 + ""
+ except:
+ frame = sys.exc_info()[2].tb_frame.f_back.f_back
+ self.reset()
+ self.userbotframe = None
+ while frame:
+ # scriptutils.py creates a local variable with name
+ # '_debugger_stop_frame_', and we don't go past it
+ # (everything above this is Pythonwin framework code)
+ if "_debugger_stop_frame_" in frame.f_locals:
+ self.userbotframe = frame
+ break
+
+ frame.f_trace = self.trace_dispatch
+ self.botframe = frame
+ frame = frame.f_back
+ self.set_step()
+ sys.settrace(self.trace_dispatch)
+
+ def set_cur_frame(self, frame):
+ # Sets the "current" frame - ie, the frame with focus. This is the
+ # frame on which "step out" etc actions are taken.
+ # This may or may not be the top of the stack.
+ assert frame is not None, "You must pass a valid frame"
+ self.curframe = frame
+ for f, index in self.stack:
+ if f is frame:
+ self.curindex = index
+ break
+ else:
+ assert False, "Can't find the frame in the stack."
+ SetInteractiveContext(frame.f_globals, frame.f_locals)
+ self.GUIRespondDebuggerData()
+ self.ShowCurrentLine()
+
+ def IsBreak(self):
+ return self.debuggerState == DBGSTATE_BREAK
+
+ def IsDebugging(self):
+ return self.debuggerState != DBGSTATE_NOT_DEBUGGING
+
+ def RespondDebuggerState(self, state):
+ if state == self.debuggerState:
+ return
+ if state == DBGSTATE_NOT_DEBUGGING: # Debugger exists, but not doing anything
+ title = ""
+ elif state == DBGSTATE_RUNNING: # Code is running under the debugger.
+ title = " - running"
+ elif state == DBGSTATE_BREAK: # We are at a breakpoint or stepping or whatever.
+ if not self.bAtException:
+ title = " - break"
+ elif self.bAtPostMortem:
+ title = " - post mortem exception"
+ else:
+ title = " - exception"
+ else:
+ raise ValueError("Invalid debugger state passed!")
+ win32ui.GetMainFrame().SetWindowText(
+ win32ui.LoadString(win32ui.IDR_MAINFRAME) + title
+ )
+ if self.debuggerState == DBGSTATE_QUITTING and state != DBGSTATE_NOT_DEBUGGING:
+ print("Ignoring state change cos I'm trying to stop!", state)
+ return
+ self.debuggerState = state
+ try:
+ frame = win32ui.GetMainFrame()
+ except win32ui.error:
+ frame = None
+ if frame is not None:
+ for id, klass, float in DebuggerDialogInfos:
+ cb = win32ui.GetMainFrame().GetControlBar(id).dialog
+ cb.RespondDebuggerState(state)
+ # Tell each open editor window about the state transition
+ for doc in editor.editorTemplate.GetDocumentList():
+ doc.OnDebuggerStateChange(state)
+ self.ShowCurrentLine()
+
+ #
+ # GUI debugger interface.
+ #
+ def GUICheckInit(self):
+ if self.inited:
+ return
+ self.inited = 1
+ frame = win32ui.GetMainFrame()
+
+ # Ensure the debugger windows are attached to the debugger.
+ for id, klass, float in DebuggerDialogInfos:
+ w = frame.GetControlBar(id)
+ w.dialog.Init(self)
+ # Show toolbar if it was visible during last debug session
+ # This would be better done using a CDockState, but that class is not wrapped yet
+ if win32ui.GetProfileVal(
+ "Debugger Windows\\" + w.dialog.title, "Visible", 0
+ ):
+ frame.ShowControlBar(w, 1, 1)
+
+ # ALWAYS show debugging toolbar, regardless of saved state
+ tb = frame.GetControlBar(win32ui.ID_VIEW_TOOLBAR_DBG)
+ frame.ShowControlBar(tb, 1, 1)
+ self.GUIRespondDebuggerData()
+
+ # frame.RecalcLayout()
+
+ def GetDebuggerBar(self, barName):
+ frame = win32ui.GetMainFrame()
+ for id, klass, float in DebuggerDialogInfos:
+ if klass.title == barName:
+ return frame.GetControlBar(id)
+ assert False, "Can't find a bar of that name!"
+
+ def GUIRespondDebuggerData(self):
+ if not self.inited: # GUI not inited - no toolbars etc.
+ return
+
+ for id, klass, float in DebuggerDialogInfos:
+ cb = win32ui.GetMainFrame().GetControlBar(id).dialog
+ cb.RespondDebuggerData()
+
+ def GUIAboutToRun(self):
+ if not self.StopDebuggerPump():
+ return 0
+ self._UnshowCurrentLine()
+ self.RespondDebuggerState(DBGSTATE_RUNNING)
+ SetInteractiveContext(None, None)
+ return 1
+
+ def GUIAboutToBreak(self):
+ "Called as the GUI debugger is about to get context, and take control of the running program."
+ self.GUICheckInit()
+ self.RespondDebuggerState(DBGSTATE_BREAK)
+ self.GUIAboutToInteract()
+ if self.pumping:
+ print("!!! Already pumping - outa here")
+ return
+ self.pumping = 1
+ win32ui.StartDebuggerPump() # NOTE - This will NOT return until the user is finished interacting
+ assert not self.pumping, "Should not be pumping once the pump has finished"
+ if self.frameShutdown: # User shut down app while debugging
+ win32ui.GetMainFrame().PostMessage(win32con.WM_CLOSE)
+
+ def GUIAboutToInteract(self):
+ "Called as the GUI is about to perform any interaction with the user"
+ frame = win32ui.GetMainFrame()
+ # Remember the enabled state of our main frame
+ # may be disabled primarily if a modal dialog is displayed.
+ # Only get at enabled via GetWindowLong.
+ self.bFrameEnabled = frame.IsWindowEnabled()
+ self.oldForeground = None
+ fw = win32ui.GetForegroundWindow()
+ if fw is not frame:
+ self.oldForeground = fw
+ # fw.EnableWindow(0) Leave enabled for now?
+ self.oldFrameEnableState = frame.IsWindowEnabled()
+ frame.EnableWindow(1)
+ if self.inForcedGUI and not frame.IsWindowVisible():
+ frame.ShowWindow(win32con.SW_SHOW)
+ frame.UpdateWindow()
+ if self.curframe:
+ SetInteractiveContext(self.curframe.f_globals, self.curframe.f_locals)
+ else:
+ SetInteractiveContext(None, None)
+ self.GUIRespondDebuggerData()
+
+ def GUIAboutToFinishInteract(self):
+ """Called as the GUI is about to finish any interaction with the user
+ Returns non zero if we are allowed to stop interacting"""
+ if self.oldForeground is not None:
+ try:
+ win32ui.GetMainFrame().EnableWindow(self.oldFrameEnableState)
+ self.oldForeground.EnableWindow(1)
+ except win32ui.error:
+ # old window may be dead.
+ pass
+ # self.oldForeground.SetForegroundWindow() - fails??
+ if not self.inForcedGUI:
+ return 1 # Never a problem, and nothing else to do.
+ # If we are running a forced GUI, we may never get an opportunity
+ # to interact again. Therefore we perform a "SaveAll", to makesure that
+ # any documents are saved before leaving.
+ for template in win32ui.GetApp().GetDocTemplateList():
+ for doc in template.GetDocumentList():
+ if not doc.SaveModified():
+ return 0
+ # All documents saved - now hide the app and debugger.
+ if self.get_option(OPT_HIDE):
+ frame = win32ui.GetMainFrame()
+ frame.ShowWindow(win32con.SW_HIDE)
+ return 1
+
+ #
+ # Pythonwin interface - all stuff to do with showing source files,
+ # changing line states etc.
+ #
+ def ShowLineState(self, fileName, lineNo, lineState):
+ # Set the state of a line, open if not already
+ self.ShowLineNo(fileName, lineNo)
+ self.SetLineState(fileName, lineNo, lineState)
+
+ def SetLineState(self, fileName, lineNo, lineState):
+ # Set the state of a line if the document is open.
+ doc = editor.editorTemplate.FindOpenDocument(fileName)
+ if doc is not None:
+ marker = _LineStateToMarker(lineState)
+ if not doc.MarkerCheck(lineNo, marker):
+ doc.MarkerAdd(lineNo, marker)
+
+ def ResetLineState(self, fileName, lineNo, lineState):
+ # Set the state of a line if the document is open.
+ doc = editor.editorTemplate.FindOpenDocument(fileName)
+ if doc is not None:
+ marker = _LineStateToMarker(lineState)
+ doc.MarkerDelete(lineNo, marker)
+
+ def UpdateDocumentLineStates(self, doc):
+ # Show all lines in their special status color. If the doc is open
+ # all line states are reset.
+ doc.MarkerDeleteAll(MARKER_BREAKPOINT)
+ doc.MarkerDeleteAll(MARKER_CURRENT)
+ fname = self.canonic(doc.GetPathName())
+ # Now loop over all break-points
+ for line in self.breaks.get(fname, []):
+ doc.MarkerAdd(line, MARKER_BREAKPOINT)
+ # And the current line if in this document.
+ if self.shownLineCurrent and fname == self.shownLineCurrent[0]:
+ lineNo = self.shownLineCurrent[1]
+ if not doc.MarkerCheck(lineNo, MARKER_CURRENT):
+ doc.MarkerAdd(lineNo, MARKER_CURRENT)
+
+ # if self.shownLineCallstack and fname == self.shownLineCallstack[0]:
+ # doc.MarkerAdd(self.shownLineCallstack[1], MARKER_CURRENT)
+
+ def UpdateAllLineStates(self):
+ for doc in editor.editorTemplate.GetDocumentList():
+ self.UpdateDocumentLineStates(doc)
+
+ def ShowCurrentLine(self):
+ # Show the current line. Only ever 1 current line - undoes last current
+ # The "Current Line" is self.curframe.
+ # The "Callstack Line" is the top of the stack.
+ # If current == callstack, only show as current.
+ self._UnshowCurrentLine() # un-highlight the old one.
+ if self.curframe:
+ fileName = self.canonic(self.curframe.f_code.co_filename)
+ lineNo = self.curframe.f_lineno
+ self.shownLineCurrent = fileName, lineNo
+ self.ShowLineState(fileName, lineNo, LINESTATE_CURRENT)
+
+ def _UnshowCurrentLine(self):
+ "Unshow the current line, and forget it"
+ if self.shownLineCurrent is not None:
+ fname, lineno = self.shownLineCurrent
+ self.ResetLineState(fname, lineno, LINESTATE_CURRENT)
+ self.shownLineCurrent = None
+
+ def ShowLineNo(self, filename, lineno):
+ wasOpen = editor.editorTemplate.FindOpenDocument(filename) is not None
+ if os.path.isfile(filename) and scriptutils.JumpToDocument(filename, lineno):
+ if not wasOpen:
+ doc = editor.editorTemplate.FindOpenDocument(filename)
+ if doc is not None:
+ self.UpdateDocumentLineStates(doc)
+ return 1
+ return 0
+ return 1
+ else:
+ # Can't find the source file - linecache may have it?
+ import linecache
+
+ line = linecache.getline(filename, lineno)
+ print(
+ "%s(%d): %s"
+ % (os.path.basename(filename), lineno, line[:-1].expandtabs(4))
+ )
+ return 0
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/fail.py b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/fail.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc1e93f55aaf42b9426000432c3628a560a7d214
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/debugger/fail.py
@@ -0,0 +1,54 @@
+# NOTE NOTE - This module is designed to fail!
+#
+# The ONLY purpose for this script is testing/demoing the
+# Pythonwin debugger package.
+
+# It does nothing useful, and it even doesn't do that!
+
+import sys
+import time
+
+import pywin.debugger
+
+
+def a():
+ a = 1
+ try:
+ b()
+ except:
+ # Break into the debugger with the exception information.
+ pywin.debugger.post_mortem(sys.exc_info()[2])
+ a = 1
+ a = 2
+ a = 3
+ a = 4
+
+
+def b():
+ b = 1
+ pywin.debugger.set_trace()
+ # After importing or running this module, you are likely to be
+ # sitting at the next line. This is because we explicitly
+ # broke into the debugger using the "set_trace() function
+ # "pywin.debugger.brk()" is a shorter alias for this.
+ c()
+
+
+def c():
+ c = 1
+ d()
+
+
+def d():
+ d = 1
+ e(d)
+ raise ValueError("Hi")
+
+
+def e(arg):
+ e = 1
+ time.sleep(1)
+ return e
+
+
+a()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/default.cfg b/python_embeded/Lib/site-packages/pythonwin/pywin/default.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..517c5a3d90bbec07613754d07a4806d65ad3d954
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/default.cfg
@@ -0,0 +1,214 @@
+# The default keyboard etc configuration file for Pythonwin.
+#
+# The format of this file is very similar to a Windows INI file.
+# Sections are identified with [Section] lines, but comments
+# use the standatd Python # character. Depending on the section,
+# lines may not be in the standard "key=value" format.
+
+# NOTE: You should not need to modify this file.
+# Simply create a new .CFG file, and add an entry:
+# [General]
+# BasedOn = Default
+#
+# and add your customisations. Then select your new configuration
+# from the Pythonwin View/Options/Editor dialog.
+# This way you get to add your own customisations,
+# but still take advantage of changes to the default
+# configuration in new releases.
+
+# See IDLE.cfg for an example extension configuration.
+#
+##########################################################################
+
+[IDLE Extensions]
+
+# The list of IDLE extensions to load. The extensions
+# AutoIndent, AutoFormat and possibly others are
+# "built-in", so do not need specifying.
+
+FormatParagraph
+CallTips
+
+
+[Keys]
+
+# The list of _default_ key definitions.
+# See [Keys:Interactive] and [Keys:Editor] below for further defs.
+
+#Events of the format <>
+# are events defined in IDLE extensions.
+
+Alt+Q = <>
+
+Ctrl+W = ViewWhitespace
+Ctrl+Shift+8 = ViewWhitespace # The MSVC default key def.
+
+Ctrl+Shift+F = ViewFixedFont
+
+# Auto-complete, call-tips, etc.
+Alt+/ = <>
+Ctrl+Space = <>
+( = <>
+) = <>
+Up = <>
+Down = <>
+Left = <>
+Right = <>
+. = KeyDot
+
+# Debugger - These are the MSVC default keys, for want of a better choice.
+F9 = DbgBreakpointToggle
+F5 = DbgGo
+Shift+F5 = DbgClose
+F11 = DbgStep
+F10 = DbgStepOver
+Shift+F11 = DbgStepOut
+
+Ctrl+F3 = AutoFindNext
+
+
+[Keys:Editor]
+# Key bindings specific to the editor
+F2 = GotoNextBookmark
+Ctrl+F2 = ToggleBookmark
+Ctrl+G = GotoLine
+
+Alt+I = ShowInteractiveWindow
+Alt-B = AddBanner # A sample Event defined in this file.
+
+# Block operations
+Alt+3 = <>
+Shift+Alt+3 = <>
+Alt+4 = <> # IDLE default.
+Alt+5 = <>
+Alt+6 = <>
+
+# Tabs and other indent features
+Back = <>
+Ctrl+T = <>
+Alt+U = <>
+Enter = EnterKey
+Tab = TabKey
+Shift-Tab = <>
+
+# Folding
+Add = FoldExpand
+Alt+Add = FoldExpandAll
+Shift+Add = FoldExpandSecondLevel
+Subtract = FoldCollapse
+Alt+Subtract = FoldCollapseAll
+Shift+Subtract = FoldCollapseSecondLevel
+Multiply = FoldTopLevel
+
+[Keys:Interactive]
+# Key bindings specific to the interactive window.
+# History for the interactive window
+Ctrl+Up = <>
+Ctrl+Down = <>
+Enter = ProcessEnter
+Ctrl+Enter = ProcessEnter
+Shift+Enter = ProcessEnter
+Esc = ProcessEsc
+Alt+I = WindowBack # Toggle back to previous window.
+Home = InteractiveHome # A sample Event defined in this file.
+Shift+Home = InteractiveHomeExtend # A sample Event defined in this file.
+
+# When docked, the Ctrl+Tab and Shift+Ctrl+Tab keys don't work as expected.
+Ctrl+Tab = MDINext
+Ctrl+Shift+Tab = MDIPrev
+
+[Extensions]
+# Python event handlers specific to this config file.
+# All functions not starting with an "_" are assumed
+# to be events, and take 2 params:
+# * editor_window is the same object passed to IDLE
+# extensions. editor_window.text is a text widget
+# that conforms to the Tk text widget interface.
+# * event is the event being fired. Will always be None
+# in the current implementation.
+
+# Simply by defining these functions, they are available as
+# events.
+# Note that we bind keystrokes to these events in the various
+# [Keys] sections.
+
+# Add a simple file/class/function simple banner
+def AddBanner(editor_window, event):
+
+ text = editor_window.text
+ big_line = "#" * 70
+ banner = "%s\n## \n## \n## \n%s\n" % (big_line, big_line)
+
+ # Insert at the start of the current line.
+ pos = text.index("insert linestart")
+
+ text.undo_block_start() # Allow action to be undone as a single unit.
+ text.insert(pos, banner)
+ text.undo_block_stop()
+
+ # Now set the insert point to the middle of the banner.
+ line, col = [int(s) for s in pos.split(".")]
+ text.mark_set("insert", "%d.1 lineend" % (line+2, ) )
+
+
+# Here is a sample event bound to the "Home" key in the
+# interactive window
+def InteractiveHome(editor_window, event):
+ return _DoInteractiveHome(editor_window.text, 0)
+
+def InteractiveHomeExtend(editor_window, event):
+ return _DoInteractiveHome(editor_window.text, 1)
+
+def _DoInteractiveHome(text, extend):
+ import sys
+ # If Scintilla has an autocomplete window open, then let Scintilla handle it.
+ if text.edit.SCIAutoCActive():
+ return 1
+ of_interest = "insert linestart + %d c" % len(sys.ps1)
+ if not text.compare("insert", "==", of_interest) and \
+ text.get("insert linestart", of_interest) in [sys.ps1, sys.ps2]: # Not sys.ps? line
+ end = of_interest
+ else:
+ end = "insert linestart"
+
+ if extend: start = "insert"
+ else: start = end
+ text.tag_add("sel", start, end)
+
+# From Niki Spahie
+def AutoFindNext(editor_window, event):
+ "find selected text or word under cursor"
+
+ from pywin.scintilla import find
+ from pywin.scintilla import scintillacon
+
+ try:
+ sci = editor_window.edit
+ word = sci.GetSelText()
+ if word:
+ find.lastSearch.findText = word
+ find.lastSearch.sel = sci.GetSel()
+ else:
+ pos = sci.SendScintilla( scintillacon.SCI_GETCURRENTPOS )
+ start = sci.SendScintilla( scintillacon.SCI_WORDSTARTPOSITION, pos, 1 )
+ end = sci.SendScintilla( scintillacon.SCI_WORDENDPOSITION, pos, 1 )
+ word = sci.GetTextRange( start, end )
+ if word:
+ find.lastSearch.findText = word
+ find.lastSearch.sel = (start,end)
+ except Exception:
+ import traceback
+ traceback.print_exc()
+ find.FindNext()
+
+
+# A couple of generic events.
+def Beep(editor_window, event):
+ editor_window.text.beep()
+
+def DoNothing(editor_window, event):
+ pass
+
+def ContinueEvent(editor_window, event):
+ # Almost an "unbind" - allows Pythonwin/MFC to handle the keystroke
+ return 1
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/ideoptions.py b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/ideoptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..f94eef046470755ec7908db77500d2c5ecddda11
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/ideoptions.py
@@ -0,0 +1,136 @@
+# The property page to define generic IDE options for Pythonwin
+
+import win32con
+import win32ui
+from pywin.framework import interact
+from pywin.mfc import dialog
+
+buttonControlMap = {
+ win32ui.IDC_BUTTON1: win32ui.IDC_EDIT1,
+ win32ui.IDC_BUTTON2: win32ui.IDC_EDIT2,
+ win32ui.IDC_BUTTON3: win32ui.IDC_EDIT3,
+}
+
+
+class OptionsPropPage(dialog.PropertyPage):
+ def __init__(self):
+ dialog.PropertyPage.__init__(self, win32ui.IDD_PP_IDE)
+ self.AddDDX(win32ui.IDC_CHECK1, "bShowAtStartup")
+ self.AddDDX(win32ui.IDC_CHECK2, "bDocking")
+ self.AddDDX(win32ui.IDC_EDIT4, "MRUSize", "i")
+
+ def OnInitDialog(self):
+ edit = self.GetDlgItem(win32ui.IDC_EDIT1)
+ format = eval(
+ win32ui.GetProfileVal(
+ interact.sectionProfile,
+ interact.STYLE_INTERACTIVE_PROMPT,
+ str(interact.formatInput),
+ )
+ )
+ edit.SetDefaultCharFormat(format)
+ edit.SetWindowText("Input Text")
+
+ edit = self.GetDlgItem(win32ui.IDC_EDIT2)
+ format = eval(
+ win32ui.GetProfileVal(
+ interact.sectionProfile,
+ interact.STYLE_INTERACTIVE_OUTPUT,
+ str(interact.formatOutput),
+ )
+ )
+ edit.SetDefaultCharFormat(format)
+ edit.SetWindowText("Output Text")
+
+ edit = self.GetDlgItem(win32ui.IDC_EDIT3)
+ format = eval(
+ win32ui.GetProfileVal(
+ interact.sectionProfile,
+ interact.STYLE_INTERACTIVE_ERROR,
+ str(interact.formatOutputError),
+ )
+ )
+ edit.SetDefaultCharFormat(format)
+ edit.SetWindowText("Error Text")
+
+ self["bShowAtStartup"] = interact.LoadPreference("Show at startup", 1)
+ self["bDocking"] = interact.LoadPreference("Docking", 0)
+ self["MRUSize"] = win32ui.GetProfileVal("Settings", "Recent File List Size", 10)
+
+ # Hook the button clicks.
+ self.HookCommand(self.HandleCharFormatChange, win32ui.IDC_BUTTON1)
+ self.HookCommand(self.HandleCharFormatChange, win32ui.IDC_BUTTON2)
+ self.HookCommand(self.HandleCharFormatChange, win32ui.IDC_BUTTON3)
+
+ # Ensure the spin control remains in range.
+ spinner = self.GetDlgItem(win32ui.IDC_SPIN1)
+ spinner.SetRange(1, 16)
+
+ return dialog.PropertyPage.OnInitDialog(self)
+
+ # Called to save away the new format tuple for the specified item.
+ def HandleCharFormatChange(self, id, code):
+ if code == win32con.BN_CLICKED:
+ editId = buttonControlMap.get(id)
+ assert editId is not None, "Format button has no associated edit control"
+ editControl = self.GetDlgItem(editId)
+ existingFormat = editControl.GetDefaultCharFormat()
+ flags = win32con.CF_SCREENFONTS
+ d = win32ui.CreateFontDialog(existingFormat, flags, None, self)
+ if d.DoModal() == win32con.IDOK:
+ cf = d.GetCharFormat()
+ editControl.SetDefaultCharFormat(cf)
+ self.SetModified(1)
+ return 0 # We handled this fully!
+
+ def OnOK(self):
+ # Handle the edit controls - get all the fonts, put them back into interact, then
+ # get interact to save its stuff!
+ controlAttrs = [
+ (win32ui.IDC_EDIT1, interact.STYLE_INTERACTIVE_PROMPT),
+ (win32ui.IDC_EDIT2, interact.STYLE_INTERACTIVE_OUTPUT),
+ (win32ui.IDC_EDIT3, interact.STYLE_INTERACTIVE_ERROR),
+ ]
+ for id, key in controlAttrs:
+ control = self.GetDlgItem(id)
+ fmt = control.GetDefaultCharFormat()
+ win32ui.WriteProfileVal(interact.sectionProfile, key, str(fmt))
+
+ # Save the other interactive window options.
+ interact.SavePreference("Show at startup", self["bShowAtStartup"])
+ interact.SavePreference("Docking", self["bDocking"])
+
+ # And the other options.
+ win32ui.WriteProfileVal("Settings", "Recent File List Size", self["MRUSize"])
+
+ return 1
+
+ def ChangeFormat(self, fmtAttribute, fmt):
+ dlg = win32ui.CreateFontDialog(fmt)
+ if dlg.DoModal() != win32con.IDOK:
+ return None
+ return dlg.GetCharFormat()
+
+ def OnFormatTitle(self, command, code):
+ fmt = self.GetFormat(interact.formatTitle)
+ if fmt:
+ interact.formatTitle = fmt
+ interact.SaveFontPreferences()
+
+ def OnFormatInput(self, command, code):
+ fmt = self.GetFormat(interact.formatInput)
+ if fmt:
+ interact.formatInput = fmt
+ interact.SaveFontPreferences()
+
+ def OnFormatOutput(self, command, code):
+ fmt = self.GetFormat(interact.formatOutput)
+ if fmt:
+ interact.formatOutput = fmt
+ interact.SaveFontPreferences()
+
+ def OnFormatError(self, command, code):
+ fmt = self.GetFormat(interact.formatOutputError)
+ if fmt:
+ interact.formatOutputError = fmt
+ interact.SaveFontPreferences()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/list.py b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/list.py
new file mode 100644
index 0000000000000000000000000000000000000000..5abca8ff00930ff61b0d3b7bc652dce363cd2156
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/list.py
@@ -0,0 +1,146 @@
+import commctrl
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+
+class ListDialog(dialog.Dialog):
+ def __init__(self, title, list):
+ dialog.Dialog.__init__(self, self._maketemplate(title))
+ self.HookMessage(self.on_size, win32con.WM_SIZE)
+ self.HookNotify(self.OnListItemChange, commctrl.LVN_ITEMCHANGED)
+ self.HookCommand(self.OnListClick, win32ui.IDC_LIST1)
+ self.items = list
+
+ def _maketemplate(self, title):
+ style = win32con.WS_DLGFRAME | win32con.WS_SYSMENU | win32con.WS_VISIBLE
+ ls = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | commctrl.LVS_ALIGNLEFT
+ | commctrl.LVS_REPORT
+ )
+ bs = win32con.WS_CHILD | win32con.WS_VISIBLE
+ return [
+ [title, (0, 0, 200, 200), style, None, (8, "MS Sans Serif")],
+ ["SysListView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), ls],
+ [128, "OK", win32con.IDOK, (10, 0, 50, 14), bs | win32con.BS_DEFPUSHBUTTON],
+ [128, "Cancel", win32con.IDCANCEL, (0, 0, 50, 14), bs],
+ ]
+
+ def FillList(self):
+ size = self.GetWindowRect()
+ width = size[2] - size[0] - (10)
+ itemDetails = (commctrl.LVCFMT_LEFT, width, "Item", 0)
+ self.itemsControl.InsertColumn(0, itemDetails)
+ index = 0
+ for item in self.items:
+ index = self.itemsControl.InsertItem(index + 1, str(item), 0)
+
+ def OnListClick(self, id, code):
+ if code == commctrl.NM_DBLCLK:
+ self.EndDialog(win32con.IDOK)
+ return 1
+
+ def OnListItemChange(self, std, extra):
+ (
+ (hwndFrom, idFrom, code),
+ (
+ itemNotify,
+ sub,
+ newState,
+ oldState,
+ change,
+ point,
+ lparam,
+ ),
+ ) = (std, extra)
+ oldSel = (oldState & commctrl.LVIS_SELECTED) != 0
+ newSel = (newState & commctrl.LVIS_SELECTED) != 0
+ if oldSel != newSel:
+ try:
+ self.selecteditem = itemNotify
+ self.butOK.EnableWindow(1)
+ except win32ui.error:
+ self.selecteditem = None
+
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.itemsControl = self.GetDlgItem(win32ui.IDC_LIST1)
+ self.butOK = self.GetDlgItem(win32con.IDOK)
+ self.butCancel = self.GetDlgItem(win32con.IDCANCEL)
+
+ self.FillList()
+
+ size = self.GetWindowRect()
+ self.LayoutControls(size[2] - size[0], size[3] - size[1])
+ self.butOK.EnableWindow(0) # wait for first selection
+ return rc
+
+ def LayoutControls(self, w, h):
+ self.itemsControl.MoveWindow((0, 0, w, h - 30))
+ self.butCancel.MoveWindow((10, h - 24, 60, h - 4))
+ self.butOK.MoveWindow((w - 60, h - 24, w - 10, h - 4))
+
+ def on_size(self, params):
+ lparam = params[3]
+ w = win32api.LOWORD(lparam)
+ h = win32api.HIWORD(lparam)
+ self.LayoutControls(w, h)
+
+
+class ListsDialog(ListDialog):
+ def __init__(self, title, list, colHeadings=["Item"]):
+ ListDialog.__init__(self, title, list)
+ self.colHeadings = colHeadings
+
+ def FillList(self):
+ index = 0
+ size = self.GetWindowRect()
+ width = (
+ size[2] - size[0] - (10) - win32api.GetSystemMetrics(win32con.SM_CXVSCROLL)
+ )
+ numCols = len(self.colHeadings)
+
+ for col in self.colHeadings:
+ itemDetails = (commctrl.LVCFMT_LEFT, int(width / numCols), col, 0)
+ self.itemsControl.InsertColumn(index, itemDetails)
+ index += 1
+ index = 0
+ for items in self.items:
+ index = self.itemsControl.InsertItem(index + 1, str(items[0]), 0)
+ for itemno in range(1, numCols):
+ item = items[itemno]
+ self.itemsControl.SetItemText(index, itemno, str(item))
+
+
+def SelectFromList(title, lst):
+ dlg = ListDialog(title, lst)
+ if dlg.DoModal() == win32con.IDOK:
+ return dlg.selecteditem
+ else:
+ return None
+
+
+def SelectFromLists(title, lists, headings):
+ dlg = ListsDialog(title, lists, headings)
+ if dlg.DoModal() == win32con.IDOK:
+ return dlg.selecteditem
+ else:
+ return None
+
+
+def test():
+ # print SelectFromList('Single list', [1,2,3])
+ print(
+ SelectFromLists(
+ "Multi-List",
+ [("1", 1, "a"), ("2", 2, "b"), ("3", 3, "c")],
+ ["Col 1", "Col 2"],
+ )
+ )
+
+
+if __name__ == "__main__":
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/login.py b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/login.py
new file mode 100644
index 0000000000000000000000000000000000000000..836a08af0756f2dc004e7a68d0c637b554a7430c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/login.py
@@ -0,0 +1,155 @@
+"""login -- PythonWin user ID and password dialog box
+
+(Adapted from originally distributed with Mark Hammond's PythonWin -
+this now replaces it!)
+
+login.GetLogin() displays a modal "OK/Cancel" dialog box with input
+fields for a user ID and password. The password field input is masked
+with *'s. GetLogin takes two optional parameters, a window title, and a
+default user ID. If these parameters are omitted, the title defaults to
+"Login", and the user ID is left blank. GetLogin returns a (userid, password)
+tuple. GetLogin can be called from scripts running on the console - i.e. you
+don't need to write a full-blown GUI app to use it.
+
+login.GetPassword() is similar, except there is no username field.
+
+Example:
+import pywin.dialogs.login
+title = "FTP Login"
+def_user = "fred"
+userid, password = pywin.dialogs.login.GetLogin(title, def_user)
+
+Jim Eggleston, 28 August 1996
+Merged with dlgpass and moved to pywin.dialogs by Mark Hammond Jan 1998.
+"""
+
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+
+def MakeLoginDlgTemplate(title):
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+
+ # Window frame and title
+ dlg = [
+ [title, (0, 0, 184, 40), style, None, (8, "MS Sans Serif")],
+ ]
+
+ # ID label and text box
+ dlg.append([130, "User ID:", -1, (7, 9, 69, 9), cs | win32con.SS_LEFT])
+ s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
+ dlg.append(["EDIT", None, win32ui.IDC_EDIT1, (50, 7, 60, 12), s])
+
+ # Password label and text box
+ dlg.append([130, "Password:", -1, (7, 22, 69, 9), cs | win32con.SS_LEFT])
+ s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
+ dlg.append(
+ ["EDIT", None, win32ui.IDC_EDIT2, (50, 20, 60, 12), s | win32con.ES_PASSWORD]
+ )
+
+ # OK/Cancel Buttons
+ s = cs | win32con.WS_TABSTOP
+ dlg.append(
+ [128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]
+ )
+ s = win32con.BS_PUSHBUTTON | s
+ dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 20, 50, 14), s])
+ return dlg
+
+
+def MakePasswordDlgTemplate(title):
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+ # Window frame and title
+ dlg = [
+ [title, (0, 0, 177, 45), style, None, (8, "MS Sans Serif")],
+ ]
+
+ # Password label and text box
+ dlg.append([130, "Password:", -1, (7, 7, 69, 9), cs | win32con.SS_LEFT])
+ s = cs | win32con.WS_TABSTOP | win32con.WS_BORDER
+ dlg.append(
+ ["EDIT", None, win32ui.IDC_EDIT1, (50, 7, 60, 12), s | win32con.ES_PASSWORD]
+ )
+
+ # OK/Cancel Buttons
+ s = cs | win32con.WS_TABSTOP | win32con.BS_PUSHBUTTON
+ dlg.append(
+ [128, "OK", win32con.IDOK, (124, 5, 50, 14), s | win32con.BS_DEFPUSHBUTTON]
+ )
+ dlg.append([128, "Cancel", win32con.IDCANCEL, (124, 22, 50, 14), s])
+ return dlg
+
+
+class LoginDlg(dialog.Dialog):
+ Cancel = 0
+
+ def __init__(self, title):
+ dialog.Dialog.__init__(self, MakeLoginDlgTemplate(title))
+ self.AddDDX(win32ui.IDC_EDIT1, "userid")
+ self.AddDDX(win32ui.IDC_EDIT2, "password")
+
+
+def GetLogin(title="Login", userid="", password=""):
+ d = LoginDlg(title)
+ d["userid"] = userid
+ d["password"] = password
+ if d.DoModal() != win32con.IDOK:
+ return (None, None)
+ else:
+ return (d["userid"], d["password"])
+
+
+class PasswordDlg(dialog.Dialog):
+ def __init__(self, title):
+ dialog.Dialog.__init__(self, MakePasswordDlgTemplate(title))
+ self.AddDDX(win32ui.IDC_EDIT1, "password")
+
+
+def GetPassword(title="Password", password=""):
+ d = PasswordDlg(title)
+ d["password"] = password
+ if d.DoModal() != win32con.IDOK:
+ return None
+ return d["password"]
+
+
+if __name__ == "__main__":
+ import sys
+
+ title = "Login"
+ def_user = ""
+ if len(sys.argv) > 1:
+ title = sys.argv[1]
+ if len(sys.argv) > 2:
+ def_userid = sys.argv[2]
+ userid, password = GetLogin(title, def_user)
+ if userid == password is None:
+ print("User pressed Cancel")
+ else:
+ print("User ID: ", userid)
+ print("Password:", password)
+ newpassword = GetPassword("Reenter just for fun", password)
+ if newpassword is None:
+ print("User cancelled")
+ else:
+ what = ""
+ if newpassword != password:
+ what = "not "
+ print("The passwords did %smatch" % (what))
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/status.py b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/status.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f5b832513c44796dd4d10b8a2b18fa241f10f3b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/dialogs/status.py
@@ -0,0 +1,242 @@
+# No cancel button.
+
+import threading
+import time
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog
+from pywin.mfc.thread import WinThread
+
+
+def MakeProgressDlgTemplate(caption, staticText=""):
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ cs = win32con.WS_CHILD | win32con.WS_VISIBLE
+
+ w = 215
+ h = 36 # With button
+ h = 40
+
+ dlg = [
+ [caption, (0, 0, w, h), style, None, (8, "MS Sans Serif")],
+ ]
+
+ s = win32con.WS_TABSTOP | cs
+
+ dlg.append([130, staticText, 1000, (7, 7, w - 7, h - 32), cs | win32con.SS_LEFT])
+
+ # dlg.append([128,
+ # "Cancel",
+ # win32con.IDCANCEL,
+ # (w - 60, h - 18, 50, 14), s | win32con.BS_PUSHBUTTON])
+
+ return dlg
+
+
+class CStatusProgressDialog(dialog.Dialog):
+ def __init__(self, title, msg="", maxticks=100, tickincr=1):
+ self.initMsg = msg
+ templ = MakeProgressDlgTemplate(title, msg)
+ dialog.Dialog.__init__(self, templ)
+ self.maxticks = maxticks
+ self.tickincr = tickincr
+ self.pbar = None
+
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ self.static = self.GetDlgItem(1000)
+ self.pbar = win32ui.CreateProgressCtrl()
+ self.pbar.CreateWindow(
+ win32con.WS_CHILD | win32con.WS_VISIBLE, (10, 30, 310, 44), self, 1001
+ )
+ self.pbar.SetRange(0, self.maxticks)
+ self.pbar.SetStep(self.tickincr)
+ self.progress = 0
+ self.pincr = 5
+ return rc
+
+ def Close(self):
+ self.EndDialog(0)
+
+ def SetMaxTicks(self, maxticks):
+ if self.pbar is not None:
+ self.pbar.SetRange(0, maxticks)
+
+ def Tick(self):
+ if self.pbar is not None:
+ self.pbar.StepIt()
+
+ def SetTitle(self, text):
+ self.SetWindowText(text)
+
+ def SetText(self, text):
+ self.SetDlgItemText(1000, text)
+
+ def Set(self, pos, max=None):
+ if self.pbar is not None:
+ self.pbar.SetPos(pos)
+ if max is not None:
+ self.pbar.SetRange(0, max)
+
+
+# a progress dialog created in a new thread - especially suitable for
+# console apps with no message loop.
+MYWM_SETTITLE = win32con.WM_USER + 10
+MYWM_SETMSG = win32con.WM_USER + 11
+MYWM_TICK = win32con.WM_USER + 12
+MYWM_SETMAXTICKS = win32con.WM_USER + 13
+MYWM_SET = win32con.WM_USER + 14
+
+
+class CThreadedStatusProcessDialog(CStatusProgressDialog):
+ def __init__(self, title, msg="", maxticks=100, tickincr=1):
+ self.title = title
+ self.msg = msg
+ self.threadid = win32api.GetCurrentThreadId()
+ CStatusProgressDialog.__init__(self, title, msg, maxticks, tickincr)
+
+ def OnInitDialog(self):
+ rc = CStatusProgressDialog.OnInitDialog(self)
+ self.HookMessage(self.OnTitle, MYWM_SETTITLE)
+ self.HookMessage(self.OnMsg, MYWM_SETMSG)
+ self.HookMessage(self.OnTick, MYWM_TICK)
+ self.HookMessage(self.OnMaxTicks, MYWM_SETMAXTICKS)
+ self.HookMessage(self.OnSet, MYWM_SET)
+ return rc
+
+ def _Send(self, msg):
+ try:
+ self.PostMessage(msg)
+ except win32ui.error:
+ # the user closed the window - but this does not cancel the
+ # process - so just ignore it.
+ pass
+
+ def OnTitle(self, msg):
+ CStatusProgressDialog.SetTitle(self, self.title)
+
+ def OnMsg(self, msg):
+ CStatusProgressDialog.SetText(self, self.msg)
+
+ def OnTick(self, msg):
+ CStatusProgressDialog.Tick(self)
+
+ def OnMaxTicks(self, msg):
+ CStatusProgressDialog.SetMaxTicks(self, self.maxticks)
+
+ def OnSet(self, msg):
+ CStatusProgressDialog.Set(self, self.pos, self.max)
+
+ def Close(self):
+ assert self.threadid, "No thread!"
+ win32api.PostThreadMessage(self.threadid, win32con.WM_QUIT, 0, 0)
+
+ def SetMaxTicks(self, maxticks):
+ self.maxticks = maxticks
+ self._Send(MYWM_SETMAXTICKS)
+
+ def SetTitle(self, title):
+ self.title = title
+ self._Send(MYWM_SETTITLE)
+
+ def SetText(self, text):
+ self.msg = text
+ self._Send(MYWM_SETMSG)
+
+ def Tick(self):
+ self._Send(MYWM_TICK)
+
+ def Set(self, pos, max=None):
+ self.pos = pos
+ self.max = max
+ self._Send(MYWM_SET)
+
+
+class ProgressThread(WinThread):
+ def __init__(self, title, msg="", maxticks=100, tickincr=1):
+ self.title = title
+ self.msg = msg
+ self.maxticks = maxticks
+ self.tickincr = tickincr
+ self.dialog = None
+ WinThread.__init__(self)
+ self.createdEvent = threading.Event()
+
+ def InitInstance(self):
+ self.dialog = CThreadedStatusProcessDialog(
+ self.title, self.msg, self.maxticks, self.tickincr
+ )
+ self.dialog.CreateWindow()
+ try:
+ self.dialog.SetForegroundWindow()
+ except win32ui.error:
+ pass
+ self.createdEvent.set()
+ return WinThread.InitInstance(self)
+
+ def ExitInstance(self):
+ return 0
+
+
+def StatusProgressDialog(title, msg="", maxticks=100, parent=None):
+ d = CStatusProgressDialog(title, msg, maxticks)
+ d.CreateWindow(parent)
+ return d
+
+
+def ThreadedStatusProgressDialog(title, msg="", maxticks=100):
+ t = ProgressThread(title, msg, maxticks)
+ t.CreateThread()
+ # Need to run a basic "PumpWaitingMessages" loop just incase we are
+ # running inside Pythonwin.
+ # Basic timeout incase things go terribly wrong. Ideally we should use
+ # win32event.MsgWaitForMultipleObjects(), but we use a threading module
+ # event - so use a dumb strategy
+ end_time = time.time() + 10
+ while time.time() < end_time:
+ if t.createdEvent.isSet():
+ break
+ win32ui.PumpWaitingMessages()
+ time.sleep(0.1)
+ return t.dialog
+
+
+def demo():
+ d = StatusProgressDialog("A Demo", "Doing something...")
+ import win32api
+
+ for i in range(100):
+ if i == 50:
+ d.SetText("Getting there...")
+ if i == 90:
+ d.SetText("Nearly done...")
+ win32api.Sleep(20)
+ d.Tick()
+ d.Close()
+
+
+def thread_demo():
+ d = ThreadedStatusProgressDialog("A threaded demo", "Doing something")
+ import win32api
+
+ for i in range(100):
+ if i == 50:
+ d.SetText("Getting there...")
+ if i == 90:
+ d.SetText("Nearly done...")
+ win32api.Sleep(20)
+ d.Tick()
+ d.Close()
+
+
+if __name__ == "__main__":
+ thread_demo()
+ # demo()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/docking/DockingBar.py b/python_embeded/Lib/site-packages/pythonwin/pywin/docking/DockingBar.py
new file mode 100644
index 0000000000000000000000000000000000000000..7011003372e7bc180174ed1b466f8984590400cb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/docking/DockingBar.py
@@ -0,0 +1,676 @@
+# DockingBar.py
+
+# Ported directly (comments and all) from the samples at www.codeguru.com
+
+# WARNING: Use at your own risk, as this interface is highly likely to change.
+# Currently we support only one child per DockingBar. Later we need to add
+# support for multiple children.
+
+import struct
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import afxres, window
+
+clrBtnHilight = win32api.GetSysColor(win32con.COLOR_BTNHILIGHT)
+clrBtnShadow = win32api.GetSysColor(win32con.COLOR_BTNSHADOW)
+
+
+def CenterPoint(rect):
+ width = rect[2] - rect[0]
+ height = rect[3] - rect[1]
+ return rect[0] + width // 2, rect[1] + height // 2
+
+
+def OffsetRect(rect, point):
+ (x, y) = point
+ return rect[0] + x, rect[1] + y, rect[2] + x, rect[3] + y
+
+
+def DeflateRect(rect, point):
+ (x, y) = point
+ return rect[0] + x, rect[1] + y, rect[2] - x, rect[3] - y
+
+
+def PtInRect(rect, pt):
+ return rect[0] <= pt[0] < rect[2] and rect[1] <= pt[1] < rect[3]
+
+
+class DockingBar(window.Wnd):
+ def __init__(self, obj=None):
+ if obj is None:
+ obj = win32ui.CreateControlBar()
+ window.Wnd.__init__(self, obj)
+ self.dialog = None
+ self.nDockBarID = 0
+ self.sizeMin = 32, 32
+ self.sizeHorz = 200, 200
+ self.sizeVert = 200, 200
+ self.sizeFloat = 200, 200
+ self.bTracking = 0
+ self.bInRecalcNC = 0
+ self.cxEdge = 6
+ self.cxBorder = 3
+ self.cxGripper = 20
+ self.brushBkgd = win32ui.CreateBrush()
+ self.brushBkgd.CreateSolidBrush(win32api.GetSysColor(win32con.COLOR_BTNFACE))
+
+ # Support for diagonal resizing
+ self.cyBorder = 3
+ self.cCaptionSize = win32api.GetSystemMetrics(win32con.SM_CYSMCAPTION)
+ self.cMinWidth = win32api.GetSystemMetrics(win32con.SM_CXMIN)
+ self.cMinHeight = win32api.GetSystemMetrics(win32con.SM_CYMIN)
+ self.rectUndock = (0, 0, 0, 0)
+
+ def OnUpdateCmdUI(self, target, bDisableIfNoHndler):
+ return self.UpdateDialogControls(target, bDisableIfNoHndler)
+
+ def CreateWindow(
+ self,
+ parent,
+ childCreator,
+ title,
+ id,
+ style=win32con.WS_CHILD | win32con.WS_VISIBLE | afxres.CBRS_LEFT,
+ childCreatorArgs=(),
+ ):
+ assert not (
+ (style & afxres.CBRS_SIZE_FIXED) and (style & afxres.CBRS_SIZE_DYNAMIC)
+ ), "Invalid style"
+ self.rectClose = self.rectBorder = self.rectGripper = self.rectTracker = (
+ 0,
+ 0,
+ 0,
+ 0,
+ )
+
+ # save the style
+ self._obj_.dwStyle = style & afxres.CBRS_ALL
+
+ cursor = win32api.LoadCursor(0, win32con.IDC_ARROW)
+ wndClass = win32ui.RegisterWndClass(
+ win32con.CS_DBLCLKS, cursor, self.brushBkgd.GetSafeHandle(), 0
+ )
+
+ self._obj_.CreateWindow(wndClass, title, style, (0, 0, 0, 0), parent, id)
+
+ # Create the child dialog
+ self.dialog = childCreator(*(self,) + childCreatorArgs)
+
+ # use the dialog dimensions as default base dimensions
+ assert self.dialog.IsWindow(), (
+ "The childCreator function %s did not create a window!" % childCreator
+ )
+ rect = self.dialog.GetWindowRect()
+ self.sizeHorz = self.sizeVert = self.sizeFloat = (
+ rect[2] - rect[0],
+ rect[3] - rect[1],
+ )
+
+ self.sizeHorz = self.sizeHorz[0], self.sizeHorz[1] + self.cxEdge + self.cxBorder
+ self.sizeVert = self.sizeVert[0] + self.cxEdge + self.cxBorder, self.sizeVert[1]
+ self.HookMessages()
+
+ def CalcFixedLayout(self, bStretch, bHorz):
+ rectTop = self.dockSite.GetControlBar(
+ afxres.AFX_IDW_DOCKBAR_TOP
+ ).GetWindowRect()
+ rectLeft = self.dockSite.GetControlBar(
+ afxres.AFX_IDW_DOCKBAR_LEFT
+ ).GetWindowRect()
+ if bStretch:
+ nHorzDockBarWidth = 32767
+ nVertDockBarHeight = 32767
+ else:
+ nHorzDockBarWidth = rectTop[2] - rectTop[0] + 4
+ nVertDockBarHeight = rectLeft[3] - rectLeft[1] + 4
+
+ if self.IsFloating():
+ return self.sizeFloat
+ if bHorz:
+ return nHorzDockBarWidth, self.sizeHorz[1]
+ return self.sizeVert[0], nVertDockBarHeight
+
+ def CalcDynamicLayout(self, length, mode):
+ # Support for diagonal sizing.
+ if self.IsFloating():
+ self.GetParent().GetParent().ModifyStyle(win32ui.MFS_4THICKFRAME, 0)
+ if mode & (win32ui.LM_HORZDOCK | win32ui.LM_VERTDOCK):
+ flags = (
+ win32con.SWP_NOSIZE
+ | win32con.SWP_NOMOVE
+ | win32con.SWP_NOZORDER
+ | win32con.SWP_NOACTIVATE
+ | win32con.SWP_FRAMECHANGED
+ )
+ self.SetWindowPos(
+ 0,
+ (
+ 0,
+ 0,
+ 0,
+ 0,
+ ),
+ flags,
+ )
+ self.dockSite.RecalcLayout()
+ return self._obj_.CalcDynamicLayout(length, mode)
+
+ if mode & win32ui.LM_MRUWIDTH:
+ return self.sizeFloat
+ if mode & win32ui.LM_COMMIT:
+ self.sizeFloat = length, self.sizeFloat[1]
+ return self.sizeFloat
+ # More diagonal sizing.
+ if self.IsFloating():
+ dc = self.dockContext
+ pt = win32api.GetCursorPos()
+ windowRect = self.GetParent().GetParent().GetWindowRect()
+
+ hittest = dc.nHitTest
+ if hittest == win32con.HTTOPLEFT:
+ cx = max(windowRect[2] - pt[0], self.cMinWidth) - self.cxBorder
+ cy = max(windowRect[3] - self.cCaptionSize - pt[1], self.cMinHeight) - 1
+ self.sizeFloat = cx, cy
+
+ top = (
+ min(pt[1], windowRect[3] - self.cCaptionSize - self.cMinHeight)
+ - self.cyBorder
+ )
+ left = min(pt[0], windowRect[2] - self.cMinWidth) - 1
+ dc.rectFrameDragHorz = (
+ left,
+ top,
+ dc.rectFrameDragHorz[2],
+ dc.rectFrameDragHorz[3],
+ )
+ return self.sizeFloat
+ if hittest == win32con.HTTOPRIGHT:
+ cx = max(pt[0] - windowRect[0], self.cMinWidth)
+ cy = max(windowRect[3] - self.cCaptionSize - pt[1], self.cMinHeight) - 1
+ self.sizeFloat = cx, cy
+
+ top = (
+ min(pt[1], windowRect[3] - self.cCaptionSize - self.cMinHeight)
+ - self.cyBorder
+ )
+ dc.rectFrameDragHorz = (
+ dc.rectFrameDragHorz[0],
+ top,
+ dc.rectFrameDragHorz[2],
+ dc.rectFrameDragHorz[3],
+ )
+ return self.sizeFloat
+
+ if hittest == win32con.HTBOTTOMLEFT:
+ cx = max(windowRect[2] - pt[0], self.cMinWidth) - self.cxBorder
+ cy = max(pt[1] - windowRect[1] - self.cCaptionSize, self.cMinHeight)
+ self.sizeFloat = cx, cy
+
+ left = min(pt[0], windowRect[2] - self.cMinWidth) - 1
+ dc.rectFrameDragHorz = (
+ left,
+ dc.rectFrameDragHorz[1],
+ dc.rectFrameDragHorz[2],
+ dc.rectFrameDragHorz[3],
+ )
+ return self.sizeFloat
+
+ if hittest == win32con.HTBOTTOMRIGHT:
+ cx = max(pt[0] - windowRect[0], self.cMinWidth)
+ cy = max(pt[1] - windowRect[1] - self.cCaptionSize, self.cMinHeight)
+ self.sizeFloat = cx, cy
+ return self.sizeFloat
+
+ if mode & win32ui.LM_LENGTHY:
+ self.sizeFloat = self.sizeFloat[0], max(self.sizeMin[1], length)
+ return self.sizeFloat
+ else:
+ return max(self.sizeMin[0], length), self.sizeFloat[1]
+
+ def OnWindowPosChanged(self, msg):
+ if self.GetSafeHwnd() == 0 or self.dialog is None:
+ return 0
+ lparam = msg[3]
+ """ LPARAM used with WM_WINDOWPOSCHANGED:
+ typedef struct {
+ HWND hwnd;
+ HWND hwndInsertAfter;
+ int x;
+ int y;
+ int cx;
+ int cy;
+ UINT flags;} WINDOWPOS;
+ """
+ format = "PPiiiii"
+ bytes = win32ui.GetBytes(lparam, struct.calcsize(format))
+ hwnd, hwndAfter, x, y, cx, cy, flags = struct.unpack(format, bytes)
+
+ if self.bInRecalcNC:
+ rc = self.GetClientRect()
+ self.dialog.MoveWindow(rc)
+ return 0
+ # Find on which side are we docked
+ nDockBarID = self.GetParent().GetDlgCtrlID()
+ # Return if dropped at same location
+ # no docking side change and no size change
+ if (
+ (nDockBarID == self.nDockBarID)
+ and (flags & win32con.SWP_NOSIZE)
+ and (
+ (self._obj_.dwStyle & afxres.CBRS_BORDER_ANY) != afxres.CBRS_BORDER_ANY
+ )
+ ):
+ return
+ self.nDockBarID = nDockBarID
+
+ # Force recalc the non-client area
+ self.bInRecalcNC = 1
+ try:
+ swpflags = (
+ win32con.SWP_NOSIZE
+ | win32con.SWP_NOMOVE
+ | win32con.SWP_NOZORDER
+ | win32con.SWP_FRAMECHANGED
+ )
+ self.SetWindowPos(0, (0, 0, 0, 0), swpflags)
+ finally:
+ self.bInRecalcNC = 0
+ return 0
+
+ # This is a virtual and not a message hook.
+ def OnSetCursor(self, window, nHitTest, wMouseMsg):
+ if nHitTest != win32con.HTSIZE or self.bTracking:
+ return self._obj_.OnSetCursor(window, nHitTest, wMouseMsg)
+
+ if self.IsHorz():
+ win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZENS))
+ else:
+ win32api.SetCursor(win32api.LoadCursor(0, win32con.IDC_SIZEWE))
+ return 1
+
+ # Mouse Handling
+ def OnLButtonUp(self, msg):
+ if not self.bTracking:
+ return 1 # pass it on.
+ self.StopTracking(1)
+ return 0 # Don't pass on
+
+ def OnLButtonDown(self, msg):
+ # UINT nFlags, CPoint point)
+ # only start dragging if clicked in "void" space
+ if self.dockBar is not None:
+ # start the drag
+ pt = msg[5]
+ pt = self.ClientToScreen(pt)
+ self.dockContext.StartDrag(pt)
+ return 0
+ return 1
+
+ def OnNcLButtonDown(self, msg):
+ if self.bTracking:
+ return 0
+ nHitTest = wparam = msg[2]
+ pt = msg[5]
+
+ if nHitTest == win32con.HTSYSMENU and not self.IsFloating():
+ self.GetDockingFrame().ShowControlBar(self, 0, 0)
+ elif nHitTest == win32con.HTMINBUTTON and not self.IsFloating():
+ self.dockContext.ToggleDocking()
+ elif (
+ nHitTest == win32con.HTCAPTION
+ and not self.IsFloating()
+ and self.dockBar is not None
+ ):
+ self.dockContext.StartDrag(pt)
+ elif nHitTest == win32con.HTSIZE and not self.IsFloating():
+ self.StartTracking()
+ else:
+ return 1
+ return 0
+
+ def OnLButtonDblClk(self, msg):
+ # only toggle docking if clicked in "void" space
+ if self.dockBar is not None:
+ # toggle docking
+ self.dockContext.ToggleDocking()
+ return 0
+ return 1
+
+ def OnNcLButtonDblClk(self, msg):
+ nHitTest = wparam = msg[2]
+ # UINT nHitTest, CPoint point)
+ if self.dockBar is not None and nHitTest == win32con.HTCAPTION:
+ # toggle docking
+ self.dockContext.ToggleDocking()
+ return 0
+ return 1
+
+ def OnMouseMove(self, msg):
+ flags = wparam = msg[2]
+ lparam = msg[3]
+ if self.IsFloating() or not self.bTracking:
+ return 1
+
+ # Convert unsigned 16 bit to signed 32 bit.
+ x = win32api.LOWORD(lparam)
+ if x & 32768:
+ x |= -65536
+ y = win32api.HIWORD(lparam)
+ if y & 32768:
+ y |= -65536
+ pt = x, y
+ cpt = CenterPoint(self.rectTracker)
+ pt = self.ClientToWnd(pt)
+ if self.IsHorz():
+ if cpt[1] != pt[1]:
+ self.OnInvertTracker(self.rectTracker)
+ self.rectTracker = OffsetRect(self.rectTracker, (0, pt[1] - cpt[1]))
+ self.OnInvertTracker(self.rectTracker)
+ else:
+ if cpt[0] != pt[0]:
+ self.OnInvertTracker(self.rectTracker)
+ self.rectTracker = OffsetRect(self.rectTracker, (pt[0] - cpt[0], 0))
+ self.OnInvertTracker(self.rectTracker)
+
+ return 0 # Don't pass it on.
+
+ # def OnBarStyleChange(self, old, new):
+
+ def OnNcCalcSize(self, bCalcValid, size_info):
+ (rc0, rc1, rc2, pos) = size_info
+ self.rectBorder = self.GetWindowRect()
+ self.rectBorder = OffsetRect(
+ self.rectBorder, (-self.rectBorder[0], -self.rectBorder[1])
+ )
+
+ dwBorderStyle = self._obj_.dwStyle | afxres.CBRS_BORDER_ANY
+
+ if self.nDockBarID == afxres.AFX_IDW_DOCKBAR_TOP:
+ dwBorderStyle &= ~afxres.CBRS_BORDER_BOTTOM
+ rc0.left += self.cxGripper
+ rc0.bottom -= self.cxEdge
+ rc0.top += self.cxBorder
+ rc0.right -= self.cxBorder
+ self.rectBorder = (
+ self.rectBorder[0],
+ self.rectBorder[3] - self.cxEdge,
+ self.rectBorder[2],
+ self.rectBorder[3],
+ )
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM:
+ dwBorderStyle &= ~afxres.CBRS_BORDER_TOP
+ rc0.left += self.cxGripper
+ rc0.top += self.cxEdge
+ rc0.bottom -= self.cxBorder
+ rc0.right -= self.cxBorder
+ self.rectBorder = (
+ self.rectBorder[0],
+ self.rectBorder[1],
+ self.rectBorder[2],
+ self.rectBorder[1] + self.cxEdge,
+ )
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_LEFT:
+ dwBorderStyle &= ~afxres.CBRS_BORDER_RIGHT
+ rc0.right -= self.cxEdge
+ rc0.left += self.cxBorder
+ rc0.bottom -= self.cxBorder
+ rc0.top += self.cxGripper
+ self.rectBorder = (
+ self.rectBorder[2] - self.cxEdge,
+ self.rectBorder[1],
+ self.rectBorder[2],
+ self.rectBorder[3],
+ )
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_RIGHT:
+ dwBorderStyle &= ~afxres.CBRS_BORDER_LEFT
+ rc0.left += self.cxEdge
+ rc0.right -= self.cxBorder
+ rc0.bottom -= self.cxBorder
+ rc0.top += self.cxGripper
+ self.rectBorder = (
+ self.rectBorder[0],
+ self.rectBorder[1],
+ self.rectBorder[0] + self.cxEdge,
+ self.rectBorder[3],
+ )
+ else:
+ self.rectBorder = 0, 0, 0, 0
+
+ self.SetBarStyle(dwBorderStyle)
+ return 0
+
+ def OnNcPaint(self, msg):
+ self.EraseNonClient()
+ dc = self.GetWindowDC()
+ ctl = win32api.GetSysColor(win32con.COLOR_BTNHIGHLIGHT)
+ cbr = win32api.GetSysColor(win32con.COLOR_BTNSHADOW)
+ dc.Draw3dRect(self.rectBorder, ctl, cbr)
+
+ self.DrawGripper(dc)
+
+ rect = self.GetClientRect()
+ self.InvalidateRect(rect, 1)
+ return 0
+
+ def OnNcHitTest(self, pt): # A virtual, not a hooked message.
+ if self.IsFloating():
+ return 1
+
+ ptOrig = pt
+ rect = self.GetWindowRect()
+ pt = pt[0] - rect[0], pt[1] - rect[1]
+
+ if PtInRect(self.rectClose, pt):
+ return win32con.HTSYSMENU
+ elif PtInRect(self.rectUndock, pt):
+ return win32con.HTMINBUTTON
+ elif PtInRect(self.rectGripper, pt):
+ return win32con.HTCAPTION
+ elif PtInRect(self.rectBorder, pt):
+ return win32con.HTSIZE
+ else:
+ return self._obj_.OnNcHitTest(ptOrig)
+
+ def StartTracking(self):
+ self.SetCapture()
+
+ # make sure no updates are pending
+ self.RedrawWindow(None, None, win32con.RDW_ALLCHILDREN | win32con.RDW_UPDATENOW)
+ self.dockSite.LockWindowUpdate()
+
+ self.ptOld = CenterPoint(self.rectBorder)
+ self.bTracking = 1
+
+ self.rectTracker = self.rectBorder
+ if not self.IsHorz():
+ l, t, r, b = self.rectTracker
+ b -= 4
+ self.rectTracker = l, t, r, b
+
+ self.OnInvertTracker(self.rectTracker)
+
+ def OnCaptureChanged(self, msg):
+ hwnd = lparam = msg[3]
+ if self.bTracking and hwnd != self.GetSafeHwnd():
+ self.StopTracking(0) # cancel tracking
+ return 1
+
+ def StopTracking(self, bAccept):
+ self.OnInvertTracker(self.rectTracker)
+ self.dockSite.UnlockWindowUpdate()
+ self.bTracking = 0
+ self.ReleaseCapture()
+ if not bAccept:
+ return
+
+ rcc = self.dockSite.GetWindowRect()
+ if self.IsHorz():
+ newsize = self.sizeHorz[1]
+ maxsize = newsize + (rcc[3] - rcc[1])
+ minsize = self.sizeMin[1]
+ else:
+ newsize = self.sizeVert[0]
+ maxsize = newsize + (rcc[2] - rcc[0])
+ minsize = self.sizeMin[0]
+
+ pt = CenterPoint(self.rectTracker)
+ if self.nDockBarID == afxres.AFX_IDW_DOCKBAR_TOP:
+ newsize += pt[1] - self.ptOld[1]
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM:
+ newsize += -pt[1] + self.ptOld[1]
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_LEFT:
+ newsize += pt[0] - self.ptOld[0]
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_RIGHT:
+ newsize += -pt[0] + self.ptOld[0]
+ newsize = max(minsize, min(maxsize, newsize))
+ if self.IsHorz():
+ self.sizeHorz = self.sizeHorz[0], newsize
+ else:
+ self.sizeVert = newsize, self.sizeVert[1]
+ self.dockSite.RecalcLayout()
+ return 0
+
+ def OnInvertTracker(self, rect):
+ assert rect[2] - rect[0] > 0 and rect[3] - rect[1] > 0, "rect is empty"
+ assert self.bTracking
+ rcc = self.GetWindowRect()
+ rcf = self.dockSite.GetWindowRect()
+
+ rect = OffsetRect(rect, (rcc[0] - rcf[0], rcc[1] - rcf[1]))
+ rect = DeflateRect(rect, (1, 1))
+
+ flags = win32con.DCX_WINDOW | win32con.DCX_CACHE | win32con.DCX_LOCKWINDOWUPDATE
+ dc = self.dockSite.GetDCEx(None, flags)
+ try:
+ brush = win32ui.GetHalftoneBrush()
+ oldBrush = dc.SelectObject(brush)
+
+ dc.PatBlt(
+ (rect[0], rect[1]),
+ (rect[2] - rect[0], rect[3] - rect[1]),
+ win32con.PATINVERT,
+ )
+ dc.SelectObject(oldBrush)
+ finally:
+ self.dockSite.ReleaseDC(dc)
+
+ def IsHorz(self):
+ return (
+ self.nDockBarID == afxres.AFX_IDW_DOCKBAR_TOP
+ or self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM
+ )
+
+ def ClientToWnd(self, pt):
+ x, y = pt
+ if self.nDockBarID == afxres.AFX_IDW_DOCKBAR_BOTTOM:
+ y += self.cxEdge
+ elif self.nDockBarID == afxres.AFX_IDW_DOCKBAR_RIGHT:
+ x += self.cxEdge
+ return x, y
+
+ def DrawGripper(self, dc):
+ # no gripper if floating
+ if self._obj_.dwStyle & afxres.CBRS_FLOATING:
+ return
+
+ # -==HACK==-
+ # in order to calculate the client area properly after docking,
+ # the client area must be recalculated twice (I have no idea why)
+ self.dockSite.RecalcLayout()
+ # -==END HACK==-
+
+ gripper = self.GetWindowRect()
+ gripper = self.ScreenToClient(gripper)
+ gripper = OffsetRect(gripper, (-gripper[0], -gripper[1]))
+ gl, gt, gr, gb = gripper
+
+ if self._obj_.dwStyle & afxres.CBRS_ORIENT_HORZ:
+ # gripper at left
+ self.rectGripper = gl, gt + 40, gl + 20, gb
+ # draw close box
+ self.rectClose = gl + 7, gt + 10, gl + 19, gt + 22
+ dc.DrawFrameControl(
+ self.rectClose, win32con.DFC_CAPTION, win32con.DFCS_CAPTIONCLOSE
+ )
+ # draw docking toggle box
+ self.rectUndock = OffsetRect(self.rectClose, (0, 13))
+ dc.DrawFrameControl(
+ self.rectUndock, win32con.DFC_CAPTION, win32con.DFCS_CAPTIONMAX
+ )
+
+ gt += 38
+ gb -= 10
+ gl += 10
+ gr = gl + 3
+ gripper = gl, gt, gr, gb
+ dc.Draw3dRect(gripper, clrBtnHilight, clrBtnShadow)
+ dc.Draw3dRect(OffsetRect(gripper, (4, 0)), clrBtnHilight, clrBtnShadow)
+ else:
+ # gripper at top
+ self.rectGripper = gl, gt, gr - 40, gt + 20
+ # draw close box
+ self.rectClose = gr - 21, gt + 7, gr - 10, gt + 18
+ dc.DrawFrameControl(
+ self.rectClose, win32con.DFC_CAPTION, win32con.DFCS_CAPTIONCLOSE
+ )
+ # draw docking toggle box
+ self.rectUndock = OffsetRect(self.rectClose, (-13, 0))
+ dc.DrawFrameControl(
+ self.rectUndock, win32con.DFC_CAPTION, win32con.DFCS_CAPTIONMAX
+ )
+ gr -= 38
+ gl += 10
+ gt += 10
+ gb = gt + 3
+
+ gripper = gl, gt, gr, gb
+ dc.Draw3dRect(gripper, clrBtnHilight, clrBtnShadow)
+ dc.Draw3dRect(OffsetRect(gripper, (0, 4)), clrBtnHilight, clrBtnShadow)
+
+ def HookMessages(self):
+ self.HookMessage(self.OnLButtonUp, win32con.WM_LBUTTONUP)
+ self.HookMessage(self.OnLButtonDown, win32con.WM_LBUTTONDOWN)
+ self.HookMessage(self.OnLButtonDblClk, win32con.WM_LBUTTONDBLCLK)
+ self.HookMessage(self.OnNcLButtonDown, win32con.WM_NCLBUTTONDOWN)
+ self.HookMessage(self.OnNcLButtonDblClk, win32con.WM_NCLBUTTONDBLCLK)
+ self.HookMessage(self.OnMouseMove, win32con.WM_MOUSEMOVE)
+ self.HookMessage(self.OnNcPaint, win32con.WM_NCPAINT)
+ self.HookMessage(self.OnCaptureChanged, win32con.WM_CAPTURECHANGED)
+ self.HookMessage(self.OnWindowPosChanged, win32con.WM_WINDOWPOSCHANGED)
+
+
+# self.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+
+def EditCreator(parent):
+ d = win32ui.CreateEdit()
+ es = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | win32con.WS_BORDER
+ | win32con.ES_MULTILINE
+ | win32con.ES_WANTRETURN
+ )
+ d.CreateWindow(es, (0, 0, 150, 150), parent, 1000)
+ return d
+
+
+def test():
+ bar = DockingBar()
+ creator = EditCreator
+ bar.CreateWindow(win32ui.GetMainFrame(), creator, "Coolbar Demo", 0xFFFFF)
+ # win32ui.GetMainFrame().ShowControlBar(bar, 1, 0)
+ bar.SetBarStyle(
+ bar.GetBarStyle()
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ | afxres.CBRS_SIZE_DYNAMIC
+ )
+ bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ win32ui.GetMainFrame().DockControlBar(bar, afxres.AFX_IDW_DOCKBAR_BOTTOM)
+
+
+if __name__ == "__main__":
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/docking/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/docking/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/app.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/app.py
new file mode 100644
index 0000000000000000000000000000000000000000..07f076f88e44c00a9af82131ec26860ad40b87e0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/app.py
@@ -0,0 +1,411 @@
+# Application stuff.
+# The application is responsible for managing the main frame window.
+#
+# We also grab the FileOpen command, to invoke our Python editor
+"The PythonWin application code. Manages most aspects of MDI, etc"
+
+from __future__ import annotations
+
+import builtins
+import os
+import sys
+import traceback
+import warnings
+from typing import TYPE_CHECKING
+
+import regutil
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import afxres, dialog, window
+from pywin.mfc.thread import WinApp
+
+from . import scriptutils
+
+if TYPE_CHECKING:
+ from typing_extensions import Literal
+
+
+# Helper for writing a Window position by name, and later loading it.
+def SaveWindowSize(section, rect, state=""):
+ """Writes a rectangle to an INI file
+ Args: section = section name in the applications INI file
+ rect = a rectangle in a (cy, cx, y, x) tuple
+ (same format as CREATESTRUCT position tuples)."""
+ left, top, right, bottom = rect
+ if state:
+ state += " "
+ win32ui.WriteProfileVal(section, state + "left", left)
+ win32ui.WriteProfileVal(section, state + "top", top)
+ win32ui.WriteProfileVal(section, state + "right", right)
+ win32ui.WriteProfileVal(section, state + "bottom", bottom)
+
+
+def LoadWindowSize(section, state=""):
+ """Loads a section from an INI file, and returns a rect in a tuple (see SaveWindowSize)"""
+ if state:
+ state += " "
+ left = win32ui.GetProfileVal(section, state + "left", 0)
+ top = win32ui.GetProfileVal(section, state + "top", 0)
+ right = win32ui.GetProfileVal(section, state + "right", 0)
+ bottom = win32ui.GetProfileVal(section, state + "bottom", 0)
+ return (left, top, right, bottom)
+
+
+def RectToCreateStructRect(rect):
+ return (rect[3] - rect[1], rect[2] - rect[0], rect[1], rect[0])
+
+
+# Define FrameWindow and Application objects
+#
+# The Main Frame of the application.
+class MainFrame(window.MDIFrameWnd):
+ sectionPos = "Main Window"
+ statusBarIndicators = (
+ afxres.ID_SEPARATOR, # // status line indicator
+ afxres.ID_INDICATOR_CAPS,
+ afxres.ID_INDICATOR_NUM,
+ afxres.ID_INDICATOR_SCRL,
+ win32ui.ID_INDICATOR_LINENUM,
+ win32ui.ID_INDICATOR_COLNUM,
+ )
+
+ def OnCreate(self, cs) -> Literal[-1, 0, 1]:
+ self._CreateStatusBar()
+ return 0
+
+ def _CreateStatusBar(self):
+ self.statusBar = win32ui.CreateStatusBar(self)
+ self.statusBar.SetIndicators(self.statusBarIndicators)
+ self.HookCommandUpdate(self.OnUpdatePosIndicator, win32ui.ID_INDICATOR_LINENUM)
+ self.HookCommandUpdate(self.OnUpdatePosIndicator, win32ui.ID_INDICATOR_COLNUM)
+
+ def OnUpdatePosIndicator(self, cmdui):
+ editControl = scriptutils.GetActiveEditControl()
+ value = " " * 5
+ if editControl is not None:
+ try:
+ startChar, endChar = editControl.GetSel()
+ lineNo = editControl.LineFromChar(startChar)
+ colNo = endChar - editControl.LineIndex(lineNo)
+
+ if cmdui.m_nID == win32ui.ID_INDICATOR_LINENUM:
+ value = "%0*d" % (5, lineNo + 1)
+ else:
+ value = "%0*d" % (3, colNo + 1)
+ except win32ui.error:
+ pass
+ cmdui.SetText(value)
+ cmdui.Enable()
+
+ def PreCreateWindow(self, cc):
+ cc = self._obj_.PreCreateWindow(cc)
+ pos = LoadWindowSize(self.sectionPos)
+ self.startRect = pos
+ if pos[2] - pos[0]:
+ rect = RectToCreateStructRect(pos)
+ cc = cc[0], cc[1], cc[2], cc[3], rect, cc[5], cc[6], cc[7], cc[8]
+ return cc
+
+ def OnDestroy(self, msg):
+ # use GetWindowPlacement(), as it works even when min'd or max'd
+ rectNow = self.GetWindowPlacement()[4]
+ if rectNow != self.startRect:
+ SaveWindowSize(self.sectionPos, rectNow)
+ return 0
+
+
+class CApp(WinApp):
+ "A class for the application"
+
+ def __init__(self):
+ self.oldCallbackCaller = None
+ WinApp.__init__(self, win32ui.GetApp())
+ self.idleHandlers = []
+
+ def InitInstance(self):
+ "Called to crank up the app"
+ HookInput()
+ numMRU = win32ui.GetProfileVal("Settings", "Recent File List Size", 10)
+ win32ui.LoadStdProfileSettings(numMRU)
+ # self._obj_.InitMDIInstance()
+ if win32api.GetVersionEx()[0] < 4:
+ win32ui.SetDialogBkColor()
+ win32ui.Enable3dControls()
+
+ # install a "callback caller" - a manager for the callbacks
+ # self.oldCallbackCaller = win32ui.InstallCallbackCaller(self.CallbackManager)
+ self.LoadMainFrame()
+ self.SetApplicationPaths()
+
+ def ExitInstance(self):
+ "Called as the app dies - too late to prevent it here!"
+ win32ui.OutputDebug("Application shutdown\n")
+ # Restore the callback manager, if any.
+ try:
+ win32ui.InstallCallbackCaller(self.oldCallbackCaller)
+ except AttributeError:
+ pass
+ if self.oldCallbackCaller:
+ del self.oldCallbackCaller
+ self.frame = None # clean Python references to the now destroyed window object.
+ self.idleHandlers = []
+ # Attempt cleanup if not already done!
+ if self._obj_:
+ self._obj_.AttachObject(None)
+ self._obj_ = None
+ return 0
+
+ def HaveIdleHandler(self, handler):
+ return handler in self.idleHandlers
+
+ def AddIdleHandler(self, handler):
+ self.idleHandlers.append(handler)
+
+ def DeleteIdleHandler(self, handler):
+ self.idleHandlers.remove(handler)
+
+ def OnIdle(self, count):
+ try:
+ ret = 0
+ handlers = self.idleHandlers[:] # copy list, as may be modified during loop
+ for handler in handlers:
+ try:
+ thisRet = handler(handler, count)
+ except:
+ print(f"Idle handler {handler!r} failed")
+ traceback.print_exc()
+ print("Idle handler removed from list")
+ try:
+ self.DeleteIdleHandler(handler)
+ except ValueError: # Item not in list.
+ pass
+ thisRet = 0
+ ret = ret or thisRet
+ return ret
+ except KeyboardInterrupt:
+ pass
+
+ def CreateMainFrame(self):
+ return MainFrame()
+
+ def LoadMainFrame(self):
+ "Create the main applications frame"
+ self.frame = self.CreateMainFrame()
+ self.SetMainFrame(self.frame)
+ self.frame.LoadFrame(win32ui.IDR_MAINFRAME, win32con.WS_OVERLAPPEDWINDOW)
+ self.frame.DragAcceptFiles() # we can accept these.
+ self.frame.ShowWindow(win32ui.GetInitialStateRequest())
+ self.frame.UpdateWindow()
+ self.HookCommands()
+
+ def OnHelp(self, id, code):
+ try:
+ if id == win32ui.ID_HELP_GUI_REF:
+ helpFile = regutil.GetRegisteredHelpFile("Pythonwin Reference")
+ helpCmd = win32con.HELP_CONTENTS
+ else:
+ helpFile = regutil.GetRegisteredHelpFile("Main Python Documentation")
+ helpCmd = win32con.HELP_FINDER
+ if helpFile is None:
+ win32ui.MessageBox("The help file is not registered!")
+ else:
+ from . import help
+
+ help.OpenHelpFile(helpFile, helpCmd)
+ except:
+ t, v, tb = sys.exc_info()
+ win32ui.MessageBox(f"Internal error in help file processing\r\n{t}: {v}")
+ tb = None # Prevent a cycle
+
+ def DoLoadModules(self, modules):
+ # XXX - this should go, but the debugger uses it :-(
+ # don't do much checking!
+ for module in modules:
+ __import__(module)
+
+ def HookCommands(self):
+ self.frame.HookMessage(self.OnDropFiles, win32con.WM_DROPFILES)
+ self.HookCommand(self.HandleOnFileOpen, win32ui.ID_FILE_OPEN)
+ self.HookCommand(self.HandleOnFileNew, win32ui.ID_FILE_NEW)
+ self.HookCommand(self.OnFileMRU, win32ui.ID_FILE_MRU_FILE1)
+ self.HookCommand(self.OnHelpAbout, win32ui.ID_APP_ABOUT)
+ self.HookCommand(self.OnHelp, win32ui.ID_HELP_PYTHON)
+ self.HookCommand(self.OnHelp, win32ui.ID_HELP_GUI_REF)
+ # Hook for the right-click menu.
+ self.frame.GetWindow(win32con.GW_CHILD).HookMessage(
+ self.OnRClick, win32con.WM_RBUTTONDOWN
+ )
+
+ def SetApplicationPaths(self):
+ # Load the users/application paths
+ new_path = []
+ apppath = win32ui.GetProfileVal("Python", "Application Path", "").split(";")
+ for path in apppath:
+ if len(path) > 0:
+ new_path.append(win32ui.FullPath(path))
+ for extra_num in range(1, 11):
+ apppath = win32ui.GetProfileVal(
+ "Python", "Application Path %d" % extra_num, ""
+ ).split(";")
+ if len(apppath) == 0:
+ break
+ for path in apppath:
+ if len(path) > 0:
+ new_path.append(win32ui.FullPath(path))
+ sys.path = new_path + sys.path
+
+ def OnRClick(self, params):
+ "Handle right click message"
+ # put up the entire FILE menu!
+ menu = win32ui.LoadMenu(win32ui.IDR_TEXTTYPE).GetSubMenu(0)
+ menu.TrackPopupMenu(params[5]) # track at mouse position.
+ return 0
+
+ def OnDropFiles(self, msg):
+ "Handle a file being dropped from file manager"
+ hDropInfo = msg[2]
+ self.frame.SetActiveWindow() # active us
+ nFiles = win32api.DragQueryFile(hDropInfo)
+ try:
+ for iFile in range(0, nFiles):
+ fileName = win32api.DragQueryFile(hDropInfo, iFile)
+ win32ui.GetApp().OpenDocumentFile(fileName)
+ finally:
+ win32api.DragFinish(hDropInfo)
+
+ return 0
+
+ # No longer used by Pythonwin, as the C++ code has this same basic functionality
+ # but handles errors slightly better.
+ # It all still works, tho, so if you need similar functionality, you can use it.
+ # Therefore I haven't deleted this code completely!
+ # def CallbackManager( self, ob, args = () ):
+ # """Manage win32 callbacks. Trap exceptions, report on them, then return 'All OK'
+ # to the frame-work. """
+ # import traceback
+ # try:
+ # ret = apply(ob, args)
+ # return ret
+ # except:
+ # # take copies of the exception values, else other (handled) exceptions may get
+ # # copied over by the other fns called.
+ # win32ui.SetStatusText('An exception occured in a windows command handler.')
+ # t, v, tb = sys.exc_info()
+ # traceback.print_exception(t, v, tb.tb_next)
+ # try:
+ # sys.stdout.flush()
+ # except (NameError, AttributeError):
+ # pass
+
+ # Command handlers.
+ def OnFileMRU(self, id, code):
+ "Called when a File 1-n message is recieved"
+ fileName = win32ui.GetRecentFileList()[id - win32ui.ID_FILE_MRU_FILE1]
+ win32ui.GetApp().OpenDocumentFile(fileName)
+
+ def HandleOnFileOpen(self, id, code):
+ "Called when FileOpen message is received"
+ win32ui.GetApp().OnFileOpen()
+
+ def HandleOnFileNew(self, id, code):
+ "Called when FileNew message is received"
+ win32ui.GetApp().OnFileNew()
+
+ def OnHelpAbout(self, id, code):
+ "Called when HelpAbout message is received. Displays the About dialog."
+ win32ui.InitRichEdit()
+ dlg = AboutBox()
+ dlg.DoModal()
+
+
+def _GetRegistryValue(key, val, default=None):
+ # val is registry value - None for default val.
+ try:
+ hkey = win32api.RegOpenKey(win32con.HKEY_CURRENT_USER, key)
+ return win32api.RegQueryValueEx(hkey, val)[0]
+ except win32api.error:
+ try:
+ hkey = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, key)
+ return win32api.RegQueryValueEx(hkey, val)[0]
+ except win32api.error:
+ return default
+
+
+scintilla = "Scintilla is Copyright 1998-2020 Neil Hodgson (https://www.scintilla.org)"
+idle = "This program uses IDLE extensions by Guido van Rossum, Tim Peters and others."
+contributors = "Thanks to the following people for making significant contributions: Roger Upole, Sidnei da Silva, Sam Rushing, Curt Hagenlocher, Dave Brennan, Roger Burnham, Gordon McMillan, Neil Hodgson, Laramie Leavitt. (let me know if I have forgotten you!)"
+
+
+# The About Box
+class AboutBox(dialog.Dialog):
+ def __init__(self, idd=win32ui.IDD_ABOUTBOX):
+ dialog.Dialog.__init__(self, idd)
+
+ def OnInitDialog(self):
+ text = "Pythonwin - Python IDE and GUI Framework for Windows.\n\n{}\n\nPython is {}\n\n{}\n\n{}\n\n{}".format(
+ win32ui.copyright, sys.copyright, scintilla, idle, contributors
+ )
+ self.SetDlgItemText(win32ui.IDC_EDIT1, text)
+ import sysconfig
+
+ site_packages = sysconfig.get_paths()["platlib"]
+ version_path = os.path.join(site_packages, "pywin32.version.txt")
+ try:
+ with open(version_path) as f:
+ ver = "pywin32 build %s" % f.read().strip()
+ except OSError:
+ ver = None
+ if not ver:
+ warnings.warn(f"Could not read pywin32's version from '{version_path}'")
+ self.SetDlgItemText(win32ui.IDC_ABOUT_VERSION, ver)
+ self.HookCommand(self.OnButHomePage, win32ui.IDC_BUTTON1)
+
+ def OnButHomePage(self, id, code):
+ if code == win32con.BN_CLICKED:
+ win32api.ShellExecute(
+ 0, "open", "https://github.com/mhammond/pywin32", None, "", 1
+ )
+
+
+def Win32Input(prompt=None):
+ "Provide input() for gui apps"
+ # flush stderr/out first.
+ try:
+ sys.stdout.flush()
+ sys.stderr.flush()
+ except:
+ pass
+ if prompt is None:
+ prompt = ""
+ ret = dialog.GetSimpleInput(prompt)
+ if ret is None:
+ raise KeyboardInterrupt("operation cancelled")
+ return ret
+
+
+def HookInput():
+ builtins.input = Win32Input
+
+
+def HaveGoodGUI():
+ """Returns true if we currently have a good gui available."""
+ return "pywin.framework.startup" in sys.modules
+
+
+def CreateDefaultGUI(appClass=None):
+ """Creates a default GUI environment"""
+ if appClass is None:
+ from . import intpyapp # Bring in the default app - could be param'd later.
+
+ appClass = intpyapp.InteractivePythonApp
+ # Create and init the app.
+ appClass().InitInstance()
+
+
+def CheckCreateDefaultGUI():
+ """Checks and creates if necessary a default GUI environment."""
+ rc = HaveGoodGUI()
+ if not rc:
+ CreateDefaultGUI()
+ return rc
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/bitmap.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/bitmap.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1b0b5e9cb20802db56d0f626bc5472e3df8ff8d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/bitmap.py
@@ -0,0 +1,168 @@
+import os
+import sys
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import docview, window
+
+bStretch = 1
+
+
+class BitmapDocument(docview.Document):
+ "A bitmap document. Holds the bitmap data itself."
+
+ def __init__(self, template):
+ docview.Document.__init__(self, template)
+ self.bitmap = None
+
+ def OnNewDocument(self):
+ # I can not create new bitmaps.
+ win32ui.MessageBox("Bitmaps can not be created.")
+
+ def OnOpenDocument(self, filename):
+ self.bitmap = win32ui.CreateBitmap()
+ # init data members
+ f = open(filename, "rb")
+ try:
+ try:
+ self.bitmap.LoadBitmapFile(f)
+ except OSError:
+ win32ui.MessageBox("Could not load the bitmap from %s" % filename)
+ return 0
+ finally:
+ f.close()
+ self.size = self.bitmap.GetSize()
+ return 1
+
+ def DeleteContents(self):
+ self.bitmap = None
+
+
+class BitmapView(docview.ScrollView):
+ "A view of a bitmap. Obtains data from document."
+
+ def __init__(self, doc):
+ docview.ScrollView.__init__(self, doc)
+ self.width = self.height = 0
+ # set up message handlers
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+
+ def OnInitialUpdate(self):
+ doc = self.GetDocument()
+ if doc.bitmap:
+ bitmapSize = doc.bitmap.GetSize()
+ self.SetScrollSizes(win32con.MM_TEXT, bitmapSize)
+
+ def OnSize(self, params):
+ lParam = params[3]
+ self.width = win32api.LOWORD(lParam)
+ self.height = win32api.HIWORD(lParam)
+
+ def OnDraw(self, dc):
+ # set sizes used for "non stretch" mode.
+ doc = self.GetDocument()
+ if doc.bitmap is None:
+ return
+ bitmapSize = doc.bitmap.GetSize()
+ if bStretch:
+ # stretch BMP.
+ viewRect = (0, 0, self.width, self.height)
+ bitmapRect = (0, 0, bitmapSize[0], bitmapSize[1])
+ doc.bitmap.Paint(dc, viewRect, bitmapRect)
+ else:
+ # non stretch.
+ doc.bitmap.Paint(dc)
+
+
+class BitmapFrame(window.MDIChildWnd):
+ def OnCreateClient(self, createparams, context):
+ borderX = win32api.GetSystemMetrics(win32con.SM_CXFRAME)
+ borderY = win32api.GetSystemMetrics(win32con.SM_CYFRAME)
+ titleY = win32api.GetSystemMetrics(win32con.SM_CYCAPTION) # includes border
+ # try and maintain default window pos, else adjust if can't fit
+ # get the main client window dimensions.
+ mdiClient = win32ui.GetMainFrame().GetWindow(win32con.GW_CHILD)
+ clientWindowRect = mdiClient.ScreenToClient(mdiClient.GetWindowRect())
+ clientWindowSize = (
+ clientWindowRect[2] - clientWindowRect[0],
+ clientWindowRect[3] - clientWindowRect[1],
+ )
+ left, top, right, bottom = mdiClient.ScreenToClient(self.GetWindowRect())
+ # width, height=context.doc.size[0], context.doc.size[1]
+ # width = width+borderX*2
+ # height= height+titleY+borderY*2-1
+ # if (left+width)>clientWindowSize[0]:
+ # left = clientWindowSize[0] - width
+ # if left<0:
+ # left = 0
+ # width = clientWindowSize[0]
+ # if (top+height)>clientWindowSize[1]:
+ # top = clientWindowSize[1] - height
+ # if top<0:
+ # top = 0
+ # height = clientWindowSize[1]
+ # self.frame.MoveWindow((left, top, left+width, top+height),0)
+ window.MDIChildWnd.OnCreateClient(self, createparams, context)
+ return 1
+
+
+class BitmapTemplate(docview.DocTemplate):
+ def __init__(self):
+ docview.DocTemplate.__init__(
+ self, win32ui.IDR_PYTHONTYPE, BitmapDocument, BitmapFrame, BitmapView
+ )
+
+ def MatchDocType(self, fileName, fileType):
+ doc = self.FindOpenDocument(fileName)
+ if doc:
+ return doc
+ ext = os.path.splitext(fileName)[1].lower()
+ if ext == ".bmp": # removed due to PIL! or ext=='.ppm':
+ return win32ui.CDocTemplate_Confidence_yesAttemptNative
+ return win32ui.CDocTemplate_Confidence_maybeAttemptForeign
+
+
+# return win32ui.CDocTemplate_Confidence_noAttempt
+
+# For debugging purposes, when this module may be reloaded many times.
+try:
+ win32ui.GetApp().RemoveDocTemplate(bitmapTemplate) # type: ignore[has-type, used-before-def]
+except NameError:
+ pass
+
+bitmapTemplate = BitmapTemplate()
+bitmapTemplate.SetDocStrings(
+ "\nBitmap\nBitmap\nBitmap (*.bmp)\n.bmp\nPythonBitmapFileType\nPython Bitmap File"
+)
+win32ui.GetApp().AddDocTemplate(bitmapTemplate)
+
+# This works, but just didn't make it through the code reorg.
+# class PPMBitmap(Bitmap):
+# def LoadBitmapFile(self, file ):
+# magic=file.readline()
+# if magic <> "P6\n":
+# raise TypeError, "The file is not a PPM format file"
+# rowcollist=file.readline().split()
+# cols=int(rowcollist[0])
+# rows=int(rowcollist[1])
+# file.readline() # what's this one?
+# self.bitmap.LoadPPMFile(file,(cols,rows))
+
+
+def t():
+ bitmapTemplate.OpenDocumentFile("d:\\winnt\\arcade.bmp")
+ # OpenBMPFile( 'd:\\winnt\\arcade.bmp')
+
+
+def demo():
+ import glob
+
+ winDir = win32api.GetWindowsDirectory()
+ if sys.version_info >= (3, 10):
+ fileNames = glob.glob("*.bmp", root_dir=winDir)[:2]
+ else:
+ fileNames = glob.glob1(winDir, "*.bmp")[:2]
+
+ for fileName in fileNames:
+ bitmapTemplate.OpenDocumentFile(os.path.join(winDir, fileName))
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/cmdline.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/cmdline.py
new file mode 100644
index 0000000000000000000000000000000000000000..412181ecf86a171c89b6f4627366b726f15e387d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/cmdline.py
@@ -0,0 +1,54 @@
+# cmdline - command line utilities.
+import string
+import sys
+
+import win32ui
+
+
+def ParseArgs(str):
+ ret = []
+ pos = 0
+ length = len(str)
+ while pos < length:
+ try:
+ while str[pos] in string.whitespace:
+ pos += 1
+ except IndexError:
+ break
+ if pos >= length:
+ break
+ if str[pos] == '"':
+ pos += 1
+ try:
+ endPos = str.index('"', pos) - 1
+ nextPos = endPos + 2
+ except ValueError:
+ endPos = length
+ nextPos = endPos + 1
+ else:
+ endPos = pos
+ while endPos < length and not str[endPos] in string.whitespace:
+ endPos += 1
+ nextPos = endPos + 1
+ ret.append(str[pos : endPos + 1].strip())
+ pos = nextPos
+ return ret
+
+
+def FixArgFileName(fileName):
+ """Convert a filename on the commandline to something useful.
+ Given an automatic filename on the commandline, turn it a python module name,
+ with the path added to sys.path."""
+ import os
+
+ path, fname = os.path.split(fileName)
+ if len(path) == 0:
+ path = os.curdir
+ path = os.path.abspath(path)
+ # must check that the command line arg's path is in sys.path
+ for syspath in sys.path:
+ if os.path.abspath(syspath) == path:
+ break
+ else:
+ sys.path.append(path)
+ return os.path.splitext(fname)[0]
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/dbgcommands.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/dbgcommands.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdc53830c83954fa56d4fe4214fc39dc1e818732
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/dbgcommands.py
@@ -0,0 +1,188 @@
+# Command Handlers for the debugger.
+
+# Not in the debugger package, as I always want these interfaces to be
+# available, even if the debugger has not yet been (or can not be)
+# imported
+import warnings
+
+import win32ui
+from pywin.scintilla.control import CScintillaEditInterface
+
+from . import scriptutils
+
+IdToBarNames = {
+ win32ui.IDC_DBG_STACK: ("Stack", 0),
+ win32ui.IDC_DBG_BREAKPOINTS: ("Breakpoints", 0),
+ win32ui.IDC_DBG_WATCH: ("Watch", 1),
+}
+
+
+class DebuggerCommandHandler:
+ def HookCommands(self):
+ commands = (
+ (self.OnStep, None, win32ui.IDC_DBG_STEP),
+ (self.OnStepOut, self.OnUpdateOnlyBreak, win32ui.IDC_DBG_STEPOUT),
+ (self.OnStepOver, None, win32ui.IDC_DBG_STEPOVER),
+ (self.OnGo, None, win32ui.IDC_DBG_GO),
+ (self.OnClose, self.OnUpdateClose, win32ui.IDC_DBG_CLOSE),
+ (self.OnAdd, self.OnUpdateAddBreakpoints, win32ui.IDC_DBG_ADD),
+ (self.OnClearAll, self.OnUpdateClearAllBreakpoints, win32ui.IDC_DBG_CLEAR),
+ # (self.OnDebuggerToolbar, self.OnUpdateDebuggerToolbar, win32ui.ID_DEBUGGER_TOOLBAR),
+ )
+
+ frame = win32ui.GetMainFrame()
+
+ for methHandler, methUpdate, id in commands:
+ frame.HookCommand(methHandler, id)
+ if not methUpdate is None:
+ frame.HookCommandUpdate(methUpdate, id)
+
+ for id in IdToBarNames:
+ frame.HookCommand(self.OnDebuggerBar, id)
+ frame.HookCommandUpdate(self.OnUpdateDebuggerBar, id)
+
+ def OnDebuggerToolbar(self, id, code):
+ if code == 0:
+ return not win32ui.GetMainFrame().OnBarCheck(id)
+
+ def OnUpdateDebuggerToolbar(self, cmdui):
+ win32ui.GetMainFrame().OnUpdateControlBarMenu(cmdui)
+ cmdui.Enable(1)
+
+ def _GetDebugger(self):
+ try:
+ import pywin.debugger
+
+ return pywin.debugger.currentDebugger
+ except ImportError:
+ return None
+
+ def _DoOrStart(self, doMethod, startFlag):
+ d = self._GetDebugger()
+ if d is not None and d.IsDebugging():
+ method = getattr(d, doMethod)
+ method()
+ else:
+ scriptutils.RunScript(
+ defName=None, defArgs=None, bShowDialog=0, debuggingType=startFlag
+ )
+
+ def OnStep(self, msg, code):
+ self._DoOrStart("do_set_step", scriptutils.RS_DEBUGGER_STEP)
+
+ def OnStepOver(self, msg, code):
+ self._DoOrStart("do_set_next", scriptutils.RS_DEBUGGER_STEP)
+
+ def OnStepOut(self, msg, code):
+ d = self._GetDebugger()
+ if d is not None and d.IsDebugging():
+ d.do_set_return()
+
+ def OnGo(self, msg, code):
+ self._DoOrStart("do_set_continue", scriptutils.RS_DEBUGGER_GO)
+
+ def OnClose(self, msg, code):
+ d = self._GetDebugger()
+ if d is not None:
+ if d.IsDebugging():
+ d.set_quit()
+ else:
+ d.close()
+
+ def OnUpdateClose(self, cmdui):
+ d = self._GetDebugger()
+ if d is not None and d.inited:
+ cmdui.Enable(1)
+ else:
+ cmdui.Enable(0)
+
+ def OnAdd(self, msg, code):
+ doc, view = scriptutils.GetActiveEditorDocument()
+ if doc is None:
+ ## Don't do a messagebox, as this could be triggered from the app's
+ ## idle loop whenever the debug toolbar is visible, giving a never-ending
+ ## series of dialogs. This can happen when the OnUpdate handler
+ ## for the toolbar button IDC_DBG_ADD fails, since MFC falls back to
+ ## sending a normal command if the UI update command fails.
+ ## win32ui.MessageBox('There is no active window - no breakpoint can be added')
+ warnings.warn("There is no active window - no breakpoint can be added")
+ return None
+ pathName = doc.GetPathName()
+ lineNo = view.LineFromChar(view.GetSel()[0]) + 1
+ # If I have a debugger, then tell it, otherwise just add a marker
+ d = self._GetDebugger()
+ if d is None:
+ import pywin.framework.editor.color.coloreditor
+
+ doc.MarkerToggle(
+ lineNo, pywin.framework.editor.color.coloreditor.MARKER_BREAKPOINT
+ )
+ else:
+ if d.get_break(pathName, lineNo):
+ win32ui.SetStatusText("Clearing breakpoint", 1)
+ rc = d.clear_break(pathName, lineNo)
+ else:
+ win32ui.SetStatusText("Setting breakpoint", 1)
+ rc = d.set_break(pathName, lineNo)
+ if rc:
+ win32ui.MessageBox(rc)
+ d.GUIRespondDebuggerData()
+
+ def OnClearAll(self, msg, code):
+ win32ui.SetStatusText("Clearing all breakpoints")
+ d = self._GetDebugger()
+ if d is None:
+ import pywin.framework.editor
+ import pywin.framework.editor.color.coloreditor
+
+ for doc in pywin.framework.editor.editorTemplate.GetDocumentList():
+ doc.MarkerDeleteAll(
+ pywin.framework.editor.color.coloreditor.MARKER_BREAKPOINT
+ )
+ else:
+ d.clear_all_breaks()
+ d.UpdateAllLineStates()
+ d.GUIRespondDebuggerData()
+
+ def OnUpdateOnlyBreak(self, cmdui):
+ d = self._GetDebugger()
+ ok = d is not None and d.IsBreak()
+ cmdui.Enable(ok)
+
+ def OnUpdateAddBreakpoints(self, cmdui):
+ doc, view = scriptutils.GetActiveEditorDocument()
+ if doc is None or not isinstance(view, CScintillaEditInterface):
+ enabled = 0
+ else:
+ enabled = 1
+ lineNo = view.LineFromChar(view.GetSel()[0]) + 1
+ import pywin.framework.editor.color.coloreditor
+
+ cmdui.SetCheck(
+ doc.MarkerAtLine(
+ lineNo, pywin.framework.editor.color.coloreditor.MARKER_BREAKPOINT
+ )
+ != 0
+ )
+ cmdui.Enable(enabled)
+
+ def OnUpdateClearAllBreakpoints(self, cmdui):
+ d = self._GetDebugger()
+ cmdui.Enable(d is None or len(d.breaks) != 0)
+
+ def OnUpdateDebuggerBar(self, cmdui):
+ name, enabled = IdToBarNames.get(cmdui.m_nID, (None, 0))
+ d = self._GetDebugger()
+ if d is not None and d.IsDebugging() and name is not None:
+ enabled = 1
+ bar = d.GetDebuggerBar(name)
+ cmdui.SetCheck(bar.IsWindowVisible())
+ cmdui.Enable(enabled)
+
+ def OnDebuggerBar(self, id, code):
+ name = IdToBarNames.get(id)[0]
+ d = self._GetDebugger()
+ if d is not None and name is not None:
+ bar = d.GetDebuggerBar(name)
+ newState = not bar.IsWindowVisible()
+ win32ui.GetMainFrame().ShowControlBar(bar, newState, 1)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/dlgappcore.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/dlgappcore.py
new file mode 100644
index 0000000000000000000000000000000000000000..30fe1007fe2b78ed1691ef7c6991cab79399f15d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/dlgappcore.py
@@ -0,0 +1,76 @@
+# dlgappcore.
+#
+# base classes for dialog based apps.
+
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+from . import app
+
+
+class AppDialog(dialog.Dialog):
+ "The dialog box for the application"
+
+ def __init__(self, id, dll=None):
+ self.iconId = win32ui.IDR_MAINFRAME
+ dialog.Dialog.__init__(self, id, dll)
+
+ def OnInitDialog(self):
+ return dialog.Dialog.OnInitDialog(self)
+
+ # Provide support for a dlg app using an icon
+ def OnPaint(self):
+ if not self.IsIconic():
+ return self._obj_.OnPaint()
+ dc, paintStruct = self.BeginPaint()
+ self.DefWindowProc(win32con.WM_ICONERASEBKGND, dc.GetHandleOutput(), 0)
+ left, top, right, bottom = self.GetClientRect()
+ left = (right - win32api.GetSystemMetrics(win32con.SM_CXICON)) >> 1
+ top = (bottom - win32api.GetSystemMetrics(win32con.SM_CYICON)) >> 1
+ hIcon = win32ui.GetApp().LoadIcon(self.iconId)
+ dc.DrawIcon((left, top), hIcon)
+ self.EndPaint(paintStruct)
+
+ # Only needed to provide a minimized icon (and this seems
+ # less important under win95/NT4
+ def OnEraseBkgnd(self, dc):
+ if self.IsIconic():
+ return 1
+ else:
+ return self._obj_.OnEraseBkgnd(dc)
+
+ def OnQueryDragIcon(self):
+ return win32ui.GetApp().LoadIcon(self.iconId)
+
+ def PreDoModal(self):
+ pass
+
+
+class DialogApp(app.CApp):
+ "An application class, for an app with main dialog box"
+
+ def InitInstance(self):
+ # win32ui.SetProfileFileName('dlgapp.ini')
+ win32ui.LoadStdProfileSettings()
+ win32ui.EnableControlContainer()
+ win32ui.Enable3dControls()
+ self.dlg = self.frame = self.CreateDialog()
+
+ if self.frame is None:
+ raise NotImplementedError(
+ "No dialog was created by CreateDialog(). Subclasses need to implement CreateDialog."
+ )
+
+ self._obj_.InitDlgInstance(self.dlg)
+ self.PreDoModal()
+ self.dlg.PreDoModal()
+ self.dlg.DoModal()
+
+ def CreateDialog(self):
+ pass
+
+ def PreDoModal(self):
+ pass
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/ModuleBrowser.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/ModuleBrowser.py
new file mode 100644
index 0000000000000000000000000000000000000000..410568e1b7f7fb54a088e37d7b17614f8e5b0c9c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/ModuleBrowser.py
@@ -0,0 +1,235 @@
+# ModuleBrowser.py - A view that provides a module browser for an editor document.
+import pyclbr
+
+import commctrl
+import pywin.framework.scriptutils
+import pywin.mfc.docview
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import afxres
+from pywin.tools import hierlist
+
+
+class HierListCLBRModule(hierlist.HierListItem):
+ def __init__(self, modName, clbrdata):
+ self.modName = modName
+ self.clbrdata = clbrdata
+
+ def GetText(self):
+ return self.modName
+
+ def GetSubList(self):
+ ret = []
+ for item in self.clbrdata.values():
+ if (
+ item.__class__ != pyclbr.Class
+ ): # ie, it is a pyclbr Function instance (only introduced post 1.5.2)
+ ret.append(HierListCLBRFunction(item))
+ else:
+ ret.append(HierListCLBRClass(item))
+ ret.sort()
+ return ret
+
+ def IsExpandable(self):
+ return 1
+
+
+class HierListCLBRItem(hierlist.HierListItem):
+ def __init__(self, name, file, lineno, suffix=""):
+ self.name = str(name)
+ self.file = file
+ self.lineno = lineno
+ self.suffix = suffix
+
+ def __lt__(self, other):
+ return self.name < other.name
+
+ def __eq__(self, other):
+ return self.name == other.name
+
+ def GetText(self):
+ return self.name + self.suffix
+
+ def TakeDefaultAction(self):
+ if self.file:
+ pywin.framework.scriptutils.JumpToDocument(
+ self.file, self.lineno, bScrollToTop=1
+ )
+ else:
+ win32ui.SetStatusText("Can not locate the source code for this object.")
+
+ def PerformItemSelected(self):
+ if self.file is None:
+ msg = f"{self.name} - source can not be located."
+ else:
+ msg = "%s defined at line %d of %s" % (self.name, self.lineno, self.file)
+ win32ui.SetStatusText(msg)
+
+
+class HierListCLBRClass(HierListCLBRItem):
+ def __init__(self, clbrclass, suffix=""):
+ try:
+ name = clbrclass.name
+ file = clbrclass.file
+ lineno = clbrclass.lineno
+ self.super = clbrclass.super
+ self.methods = clbrclass.methods
+ except AttributeError:
+ name = clbrclass
+ file = lineno = None
+ self.super = []
+ self.methods = {}
+ HierListCLBRItem.__init__(self, name, file, lineno, suffix)
+
+ def GetSubList(self):
+ r1 = []
+ for c in self.super:
+ r1.append(HierListCLBRClass(c, " (Parent class)"))
+ r1.sort()
+ r2 = []
+ for meth, lineno in self.methods.items():
+ r2.append(HierListCLBRMethod(meth, self.file, lineno))
+ r2.sort()
+ return r1 + r2
+
+ def IsExpandable(self):
+ return len(self.methods) + len(self.super)
+
+ def GetBitmapColumn(self):
+ return 21
+
+
+class HierListCLBRFunction(HierListCLBRItem):
+ def __init__(self, clbrfunc, suffix=""):
+ name = clbrfunc.name
+ file = clbrfunc.file
+ lineno = clbrfunc.lineno
+ HierListCLBRItem.__init__(self, name, file, lineno, suffix)
+
+ def GetBitmapColumn(self):
+ return 22
+
+
+class HierListCLBRMethod(HierListCLBRItem):
+ def GetBitmapColumn(self):
+ return 22
+
+
+class HierListCLBRErrorItem(hierlist.HierListItem):
+ def __init__(self, text):
+ self.text = text
+
+ def GetText(self):
+ return self.text
+
+ def GetSubList(self):
+ return [HierListCLBRErrorItem(self.text)]
+
+ def IsExpandable(self):
+ return 0
+
+
+class HierListCLBRErrorRoot(HierListCLBRErrorItem):
+ def IsExpandable(self):
+ return 1
+
+
+class BrowserView(pywin.mfc.docview.TreeView):
+ def OnInitialUpdate(self):
+ self.list = None
+ rc = self._obj_.OnInitialUpdate()
+ self.HookMessage(self.OnSize, win32con.WM_SIZE)
+ self.bDirty = 0
+ self.destroying = 0
+ return rc
+
+ def DestroyBrowser(self):
+ self.DestroyList()
+
+ def OnActivateView(self, activate, av, dv):
+ # print("AV", self.bDirty, activate)
+ if activate:
+ self.CheckRefreshList()
+ return self._obj_.OnActivateView(activate, av, dv)
+
+ def _MakeRoot(self):
+ path = self.GetDocument().GetPathName()
+ if not path:
+ return HierListCLBRErrorRoot(
+ "Error: Can not browse a file until it is saved"
+ )
+ else:
+ mod, path = pywin.framework.scriptutils.GetPackageModuleName(path)
+ if self.bDirty:
+ what = "Refreshing"
+ # Hack for pyclbr being too smart
+ try:
+ del pyclbr._modules[mod]
+ except (KeyError, AttributeError):
+ pass
+ else:
+ what = "Building"
+ win32ui.SetStatusText(f"{what} class list - please wait...", 1)
+ win32ui.DoWaitCursor(1)
+ try:
+ reader = pyclbr.readmodule_ex # new version post 1.5.2
+ except AttributeError:
+ reader = pyclbr.readmodule
+ try:
+ data = reader(mod, [path])
+ if data:
+ return HierListCLBRModule(mod, data)
+ else:
+ return HierListCLBRErrorRoot("No Python classes in module.")
+
+ finally:
+ win32ui.DoWaitCursor(0)
+ win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
+
+ def DestroyList(self):
+ self.destroying = 1
+ list = getattr(
+ self, "list", None
+ ) # If the document was not successfully opened, we may not have a list.
+ self.list = None
+ if list is not None:
+ list.HierTerm()
+ self.destroying = 0
+
+ def CheckMadeList(self):
+ if self.list is not None or self.destroying:
+ return
+ self.rootitem = root = self._MakeRoot()
+ self.list = list = hierlist.HierListWithItems(root, win32ui.IDB_BROWSER_HIER)
+ list.HierInit(self.GetParentFrame(), self)
+ list.SetStyle(
+ commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS
+ )
+
+ def CheckRefreshList(self):
+ if self.bDirty:
+ if self.list is None:
+ self.CheckMadeList()
+ else:
+ new_root = self._MakeRoot()
+ if self.rootitem.__class__ == new_root.__class__ == HierListCLBRModule:
+ self.rootitem.modName = new_root.modName
+ self.rootitem.clbrdata = new_root.clbrdata
+ self.list.Refresh()
+ else:
+ self.list.AcceptRoot(self._MakeRoot())
+ self.bDirty = 0
+
+ def OnSize(self, params):
+ lparam = params[3]
+ w = win32api.LOWORD(lparam)
+ h = win32api.HIWORD(lparam)
+ if w != 0:
+ self.CheckMadeList()
+ elif w == 0:
+ self.DestroyList()
+ return 1
+
+ def _UpdateUIForState(self):
+ self.bDirty = 1
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dcaa480d14769272d41ba3306563e1786284698e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/__init__.py
@@ -0,0 +1,105 @@
+# __init__ for the Pythonwin editor package.
+#
+# We used to support optional editors - eg, color or non-color.
+#
+# This really isn't necessary with Scintilla, and scintilla
+# is getting so deeply embedded that it was too much work.
+
+import win32ui
+
+defaultCharacterFormat = (-402653169, 0, 200, 0, 0, 0, 49, "Courier New")
+
+##def GetDefaultEditorModuleName():
+## import pywin
+## # If someone has set pywin.editormodulename, then this is what we use
+## try:
+## prefModule = pywin.editormodulename
+## except AttributeError:
+## prefModule = win32ui.GetProfileVal("Editor","Module", "")
+## return prefModule
+##
+##def WriteDefaultEditorModule(module):
+## try:
+## module = module.__name__
+## except:
+## pass
+## win32ui.WriteProfileVal("Editor", "Module", module)
+
+
+def LoadDefaultEditor():
+ pass
+
+
+## prefModule = GetDefaultEditorModuleName()
+## restorePrefModule = None
+## mod = None
+## if prefModule:
+## try:
+## mod = __import__(prefModule)
+## except 'xx':
+## msg = "Importing your preferred editor ('%s') failed.\n\nError %s: %s\n\nAn attempt will be made to load the default editor.\n\nWould you like this editor disabled in the future?" % (prefModule, sys.exc_info()[0], sys.exc_info()[1])
+## rc = win32ui.MessageBox(msg, "Error importing editor", win32con.MB_YESNO)
+## if rc == win32con.IDNO:
+## restorePrefModule = prefModule
+## WriteDefaultEditorModule("")
+## del rc
+##
+## try:
+## # Try and load the default one - don't catch errors here.
+## if mod is None:
+## prefModule = "pywin.framework.editor.color.coloreditor"
+## mod = __import__(prefModule)
+##
+## # Get at the real module.
+## mod = sys.modules[prefModule]
+##
+## # Do a "from mod import *"
+## globals().update(mod.__dict__)
+##
+## finally:
+## # Restore the users default editor if it failed and they requested not to disable it.
+## if restorePrefModule:
+## WriteDefaultEditorModule(restorePrefModule)
+
+
+def GetEditorOption(option, defaultValue, min=None, max=None):
+ rc = win32ui.GetProfileVal("Editor", option, defaultValue)
+ if min is not None and rc < min:
+ rc = defaultValue
+ if max is not None and rc > max:
+ rc = defaultValue
+ return rc
+
+
+def SetEditorOption(option, newValue):
+ win32ui.WriteProfileVal("Editor", option, newValue)
+
+
+def DeleteEditorOption(option):
+ try:
+ win32ui.WriteProfileVal("Editor", option, None)
+ except win32ui.error:
+ pass
+
+
+# Load and save font tuples
+def GetEditorFontOption(option, default=None):
+ if default is None:
+ default = defaultCharacterFormat
+ fmt = GetEditorOption(option, "")
+ if fmt == "":
+ return default
+ try:
+ return eval(fmt)
+ except:
+ print("WARNING: Invalid font setting in registry - setting ignored")
+ return default
+
+
+def SetEditorFontOption(option, newValue):
+ SetEditorOption(option, str(newValue))
+
+
+from pywin.framework.editor.color.coloreditor import ( # nopycln: import
+ editorTemplate as editorTemplate, # Adds doc template & Re-export
+)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/color/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/color/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/color/coloreditor.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/color/coloreditor.py
new file mode 100644
index 0000000000000000000000000000000000000000..7cb2f5e71609272e4dda7a5cdfe2bfc1b3091733
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/color/coloreditor.py
@@ -0,0 +1,646 @@
+# Color Editor originally by Neil Hodgson, but restructured by mh to integrate
+# even tighter into Pythonwin.
+
+import pywin.scintilla.keycodes
+import pywin.scintilla.view
+import win32api
+import win32con
+import win32ui
+from pywin.debugger import dbgcon
+from pywin.framework.editor import GetEditorOption
+from pywin.framework.editor.document import EditorDocumentBase
+from pywin.framework.editor.frame import EditorFrame
+from pywin.framework.editor.template import EditorTemplateBase
+from pywin.scintilla import bindings, scintillacon
+from pywin.scintilla.view import CScintillaView as SyntEditViewParent
+
+# WARNING: Duplicated in document.py and editor.py
+MSG_CHECK_EXTERNAL_FILE = win32con.WM_USER + 1999
+
+# Define a few common markers
+MARKER_BOOKMARK = 0
+MARKER_BREAKPOINT = 1
+MARKER_CURRENT = 2
+
+
+class SyntEditDocument(EditorDocumentBase):
+ "A SyntEdit document."
+
+ def OnDebuggerStateChange(self, state):
+ self._ApplyOptionalToViews("OnDebuggerStateChange", state)
+
+ def HookViewNotifications(self, view):
+ EditorDocumentBase.HookViewNotifications(self, view)
+ view.SCISetUndoCollection(1)
+
+ def FinalizeViewCreation(self, view):
+ EditorDocumentBase.FinalizeViewCreation(self, view)
+ if view == self.GetFirstView():
+ self.GetDocTemplate().CheckIDLEMenus(view.idle)
+
+
+class SyntEditView(SyntEditViewParent):
+ "A view of a SyntEdit. Obtains data from document."
+
+ def __init__(self, doc):
+ SyntEditViewParent.__init__(self, doc)
+ self.bCheckingFile = 0
+
+ def OnInitialUpdate(self):
+ SyntEditViewParent.OnInitialUpdate(self)
+
+ self.HookMessage(self.OnRClick, win32con.WM_RBUTTONDOWN)
+
+ for id in (
+ win32ui.ID_VIEW_FOLD_COLLAPSE,
+ win32ui.ID_VIEW_FOLD_COLLAPSE_ALL,
+ win32ui.ID_VIEW_FOLD_EXPAND,
+ win32ui.ID_VIEW_FOLD_EXPAND_ALL,
+ ):
+ self.HookCommand(self.OnCmdViewFold, id)
+ self.HookCommandUpdate(self.OnUpdateViewFold, id)
+ self.HookCommand(self.OnCmdViewFoldTopLevel, win32ui.ID_VIEW_FOLD_TOPLEVEL)
+
+ # Define the markers
+ # self.SCIMarkerDeleteAll()
+ self.SCIMarkerDefineAll(
+ MARKER_BOOKMARK,
+ scintillacon.SC_MARK_ROUNDRECT,
+ win32api.RGB(0x0, 0x0, 0x0),
+ win32api.RGB(0, 0xFF, 0xFF),
+ )
+
+ self.SCIMarkerDefine(MARKER_CURRENT, scintillacon.SC_MARK_ARROW)
+ self.SCIMarkerSetBack(MARKER_CURRENT, win32api.RGB(0xFF, 0xFF, 0x00))
+
+ # Define the folding markers
+ if 1: # traditional markers
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDEROPEN,
+ scintillacon.SC_MARK_MINUS,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDER,
+ scintillacon.SC_MARK_PLUS,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDERSUB,
+ scintillacon.SC_MARK_EMPTY,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDERTAIL,
+ scintillacon.SC_MARK_EMPTY,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDEREND,
+ scintillacon.SC_MARK_EMPTY,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDEROPENMID,
+ scintillacon.SC_MARK_EMPTY,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDERMIDTAIL,
+ scintillacon.SC_MARK_EMPTY,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ else: # curved markers
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDEROPEN,
+ scintillacon.SC_MARK_CIRCLEMINUS,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDER,
+ scintillacon.SC_MARK_CIRCLEPLUS,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDERSUB,
+ scintillacon.SC_MARK_VLINE,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDERTAIL,
+ scintillacon.SC_MARK_LCORNERCURVE,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDEREND,
+ scintillacon.SC_MARK_CIRCLEPLUSCONNECTED,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDEROPENMID,
+ scintillacon.SC_MARK_CIRCLEMINUSCONNECTED,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+ self.SCIMarkerDefineAll(
+ scintillacon.SC_MARKNUM_FOLDERMIDTAIL,
+ scintillacon.SC_MARK_TCORNERCURVE,
+ win32api.RGB(0xFF, 0xFF, 0xFF),
+ win32api.RGB(0, 0, 0),
+ )
+
+ self.SCIMarkerDefine(MARKER_BREAKPOINT, scintillacon.SC_MARK_CIRCLE)
+ # Marker background depends on debugger state
+ self.SCIMarkerSetFore(MARKER_BREAKPOINT, win32api.RGB(0x0, 0, 0))
+ # Get the current debugger state.
+ try:
+ import pywin.debugger
+
+ if pywin.debugger.currentDebugger is None:
+ state = dbgcon.DBGSTATE_NOT_DEBUGGING
+ else:
+ state = pywin.debugger.currentDebugger.debuggerState
+ except ImportError:
+ state = dbgcon.DBGSTATE_NOT_DEBUGGING
+ self.OnDebuggerStateChange(state)
+
+ def _GetSubConfigNames(self):
+ return ["editor"] # Allow [Keys:Editor] sections to be specific to us
+
+ def DoConfigChange(self):
+ SyntEditViewParent.DoConfigChange(self)
+ tabSize = GetEditorOption("Tab Size", 4, 2)
+ indentSize = GetEditorOption("Indent Size", 4, 2)
+ bUseTabs = GetEditorOption("Use Tabs", 0)
+ bSmartTabs = GetEditorOption("Smart Tabs", 1)
+ ext = self.idle.IDLEExtension("AutoIndent") # Required extension.
+
+ self.SCISetViewWS(GetEditorOption("View Whitespace", 0))
+ self.SCISetViewEOL(GetEditorOption("View EOL", 0))
+ self.SCISetIndentationGuides(GetEditorOption("View Indentation Guides", 0))
+
+ if GetEditorOption("Right Edge Enabled", 0):
+ mode = scintillacon.EDGE_BACKGROUND
+ else:
+ mode = scintillacon.EDGE_NONE
+ self.SCISetEdgeMode(mode)
+ self.SCISetEdgeColumn(GetEditorOption("Right Edge Column", 75))
+ self.SCISetEdgeColor(
+ GetEditorOption("Right Edge Color", win32api.RGB(0xEF, 0xEF, 0xEF))
+ )
+
+ width = GetEditorOption("Marker Margin Width", 16)
+ self.SCISetMarginWidthN(1, width)
+ width = GetEditorOption("Fold Margin Width", 12)
+ self.SCISetMarginWidthN(2, width)
+ width = GetEditorOption("Line Number Margin Width", 0)
+ self.SCISetMarginWidthN(0, width)
+ self.bFolding = GetEditorOption("Enable Folding", 1)
+ fold_flags = 0
+ self.SendScintilla(
+ scintillacon.SCI_SETMODEVENTMASK, scintillacon.SC_MOD_CHANGEFOLD
+ )
+ if self.bFolding:
+ if GetEditorOption("Fold Lines", 1):
+ fold_flags = 16
+
+ self.SCISetProperty("fold", self.bFolding)
+ self.SCISetFoldFlags(fold_flags)
+
+ tt_color = GetEditorOption("Tab Timmy Color", win32api.RGB(0xFF, 0, 0))
+ self.SendScintilla(scintillacon.SCI_INDICSETFORE, 1, tt_color)
+
+ tt_use = GetEditorOption("Use Tab Timmy", 1)
+ if tt_use:
+ self.SCISetProperty("tab.timmy.whinge.level", "1")
+
+ # Auto-indent has very complicated behaviour. In a nutshell, the only
+ # way to get sensible behaviour from it is to ensure tabwidth != indentsize.
+ # Further, usetabs will only ever go from 1->0, never 0->1.
+ # This is _not_ the behaviour Pythonwin wants:
+ # * Tab width is arbitary, so should have no impact on smarts.
+ # * bUseTabs setting should reflect how new files are created, and
+ # if Smart Tabs disabled, existing files are edited
+ # * If "Smart Tabs" is enabled, bUseTabs should have no bearing
+ # for existing files (unless of course no context can be determined)
+ #
+ # So for smart tabs we configure the widget with completely dummy
+ # values (ensuring tabwidth != indentwidth), ask it to guess, then
+ # look at the values it has guessed, and re-configure
+ if bSmartTabs:
+ ext.config(usetabs=1, tabwidth=5, indentwidth=4)
+ ext.set_indentation_params(1)
+ if ext.indentwidth == 5:
+ # Either 5 literal spaces, or a single tab character. Assume a tab
+ usetabs = 1
+ indentwidth = tabSize
+ else:
+ # Either Indented with spaces, and indent size has been guessed or
+ # an empty file (or no context found - tough!)
+ if self.GetTextLength() == 0: # emtpy
+ usetabs = bUseTabs
+ indentwidth = indentSize
+ else: # guessed.
+ indentwidth = ext.indentwidth
+ usetabs = 0
+ # Tab size can never be guessed - set at user preference.
+ ext.config(usetabs=usetabs, indentwidth=indentwidth, tabwidth=tabSize)
+ else:
+ # Don't want smart-tabs - just set the options!
+ ext.config(usetabs=bUseTabs, tabwidth=tabSize, indentwidth=indentSize)
+ self.SCISetIndent(indentSize)
+ self.SCISetTabWidth(tabSize)
+
+ def OnDebuggerStateChange(self, state):
+ if state == dbgcon.DBGSTATE_NOT_DEBUGGING:
+ # Indicate breakpoints aren't really usable.
+ # Not quite white - useful when no marker margin, so set as background color.
+ self.SCIMarkerSetBack(MARKER_BREAKPOINT, win32api.RGB(0xEF, 0xEF, 0xEF))
+ else:
+ # A light-red, so still readable when no marker margin.
+ self.SCIMarkerSetBack(MARKER_BREAKPOINT, win32api.RGB(0xFF, 0x80, 0x80))
+
+ def HookDocumentHandlers(self):
+ SyntEditViewParent.HookDocumentHandlers(self)
+ self.HookMessage(self.OnCheckExternalDocumentUpdated, MSG_CHECK_EXTERNAL_FILE)
+
+ def HookHandlers(self):
+ SyntEditViewParent.HookHandlers(self)
+ self.HookMessage(self.OnSetFocus, win32con.WM_SETFOCUS)
+
+ def _PrepareUserStateChange(self):
+ return self.GetSel(), self.GetFirstVisibleLine()
+
+ def _EndUserStateChange(self, info):
+ scrollOff = info[1] - self.GetFirstVisibleLine()
+ if scrollOff:
+ self.LineScroll(scrollOff)
+ # Make sure we don't reset the cursor beyond the buffer.
+ max = self.GetTextLength()
+ newPos = min(info[0][0], max), min(info[0][1], max)
+ self.SetSel(newPos)
+
+ #######################################
+ # The Windows Message or Notify handlers.
+ #######################################
+ def OnMarginClick(self, std, extra):
+ notify = self.SCIUnpackNotifyMessage(extra)
+ if notify.margin == 2: # Our fold margin
+ line_click = self.LineFromChar(notify.position)
+ # max_line = self.GetLineCount()
+ if self.SCIGetFoldLevel(line_click) & scintillacon.SC_FOLDLEVELHEADERFLAG:
+ # If a fold point.
+ self.SCIToggleFold(line_click)
+ return 1
+
+ def OnSetFocus(self, msg):
+ # Even though we use file change notifications, we should be very sure about it here.
+ self.OnCheckExternalDocumentUpdated(msg)
+ return 1
+
+ def OnCheckExternalDocumentUpdated(self, msg):
+ if self.bCheckingFile:
+ return
+ self.bCheckingFile = 1
+ self.GetDocument().CheckExternalDocumentUpdated()
+ self.bCheckingFile = 0
+
+ def OnRClick(self, params):
+ menu = win32ui.CreatePopupMenu()
+ self.AppendMenu(menu, "&Locate module", "LocateModule")
+ self.AppendMenu(menu, flags=win32con.MF_SEPARATOR)
+ self.AppendMenu(menu, "&Undo", "EditUndo")
+ self.AppendMenu(menu, "&Redo", "EditRedo")
+ self.AppendMenu(menu, flags=win32con.MF_SEPARATOR)
+ self.AppendMenu(menu, "Cu&t", "EditCut")
+ self.AppendMenu(menu, "&Copy", "EditCopy")
+ self.AppendMenu(menu, "&Paste", "EditPaste")
+ self.AppendMenu(menu, flags=win32con.MF_SEPARATOR)
+ self.AppendMenu(menu, "&Select all", "EditSelectAll")
+ self.AppendMenu(
+ menu, "View &Whitespace", "ViewWhitespace", checked=self.SCIGetViewWS()
+ )
+ self.AppendMenu(
+ menu, "&Fixed Font", "ViewFixedFont", checked=self._GetColorizer().bUseFixed
+ )
+ self.AppendMenu(menu, flags=win32con.MF_SEPARATOR)
+ self.AppendMenu(menu, "&Goto line...", "GotoLine")
+
+ submenu = win32ui.CreatePopupMenu()
+ newitems = self.idle.GetMenuItems("edit")
+ for text, event in newitems:
+ self.AppendMenu(submenu, text, event)
+
+ flags = win32con.MF_STRING | win32con.MF_ENABLED | win32con.MF_POPUP
+ menu.AppendMenu(flags, submenu.GetHandle(), "&Source code")
+
+ flags = (
+ win32con.TPM_LEFTALIGN | win32con.TPM_LEFTBUTTON | win32con.TPM_RIGHTBUTTON
+ )
+ menu.TrackPopupMenu(params[5], flags, self)
+ return 0
+
+ def OnCmdViewFold(self, cid, code): # Handle the menu command
+ if cid == win32ui.ID_VIEW_FOLD_EXPAND_ALL:
+ self.FoldExpandAllEvent(None)
+ elif cid == win32ui.ID_VIEW_FOLD_EXPAND:
+ self.FoldExpandEvent(None)
+ elif cid == win32ui.ID_VIEW_FOLD_COLLAPSE_ALL:
+ self.FoldCollapseAllEvent(None)
+ elif cid == win32ui.ID_VIEW_FOLD_COLLAPSE:
+ self.FoldCollapseEvent(None)
+ else:
+ print("Unknown collapse/expand ID")
+
+ def OnUpdateViewFold(self, cmdui): # Update the tick on the UI.
+ if not self.bFolding:
+ cmdui.Enable(0)
+ return
+ id = cmdui.m_nID
+ if id in (win32ui.ID_VIEW_FOLD_EXPAND_ALL, win32ui.ID_VIEW_FOLD_COLLAPSE_ALL):
+ cmdui.Enable()
+ else:
+ enable = 0
+ lineno = self.LineFromChar(self.GetSel()[0])
+ foldable = (
+ self.SCIGetFoldLevel(lineno) & scintillacon.SC_FOLDLEVELHEADERFLAG
+ )
+ is_expanded = self.SCIGetFoldExpanded(lineno)
+ if id == win32ui.ID_VIEW_FOLD_EXPAND:
+ if foldable and not is_expanded:
+ enable = 1
+ elif id == win32ui.ID_VIEW_FOLD_COLLAPSE:
+ if foldable and is_expanded:
+ enable = 1
+ cmdui.Enable(enable)
+
+ def OnCmdViewFoldTopLevel(self, cid, code): # Handle the menu command
+ self.FoldTopLevelEvent(None)
+
+ #######################################
+ # The Events
+ #######################################
+ def ToggleBookmarkEvent(self, event, pos=-1):
+ """Toggle a bookmark at the specified or current position"""
+ if pos == -1:
+ pos, end = self.GetSel()
+ startLine = self.LineFromChar(pos)
+ self.GetDocument().MarkerToggle(startLine + 1, MARKER_BOOKMARK)
+ return 0
+
+ def GotoNextBookmarkEvent(self, event, fromPos=-1):
+ """Move to the next bookmark"""
+ if fromPos == -1:
+ fromPos, end = self.GetSel()
+ startLine = self.LineFromChar(fromPos) + 1 # Zero based line to start
+ nextLine = self.GetDocument().MarkerGetNext(startLine + 1, MARKER_BOOKMARK) - 1
+ if nextLine < 0:
+ nextLine = self.GetDocument().MarkerGetNext(0, MARKER_BOOKMARK) - 1
+ if nextLine < 0 or nextLine == startLine - 1:
+ win32api.MessageBeep()
+ else:
+ self.SCIEnsureVisible(nextLine)
+ self.SCIGotoLine(nextLine)
+ return 0
+
+ def TabKeyEvent(self, event):
+ """Insert an indent. If no selection, a single indent, otherwise a block indent"""
+ # Handle auto-complete first.
+ if self.SCIAutoCActive():
+ self.SCIAutoCComplete()
+ return 0
+ # Call the IDLE event.
+ return self.bindings.fire("<>", event)
+
+ def EnterKeyEvent(self, event):
+ """Handle the enter key with special handling for auto-complete"""
+ # Handle auto-complete first.
+ if self.SCIAutoCActive():
+ self.SCIAutoCComplete()
+ self.SCIAutoCCancel()
+ # Call the IDLE event.
+ return self.bindings.fire("<>", event)
+
+ def ShowInteractiveWindowEvent(self, event):
+ import pywin.framework.interact
+
+ pywin.framework.interact.ShowInteractiveWindow()
+
+ def FoldTopLevelEvent(self, event=None):
+ if not self.bFolding:
+ return 1
+
+ win32ui.DoWaitCursor(1)
+ try:
+ self.Colorize()
+ maxLine = self.GetLineCount()
+ # Find the first line, and check out its state.
+ for lineSeek in range(maxLine):
+ if self.SCIGetFoldLevel(lineSeek) & scintillacon.SC_FOLDLEVELHEADERFLAG:
+ expanding = not self.SCIGetFoldExpanded(lineSeek)
+ break
+ else:
+ # no folds here!
+ return
+ for lineSeek in range(lineSeek, maxLine):
+ level = self.SCIGetFoldLevel(lineSeek)
+ level_no = (
+ level
+ & scintillacon.SC_FOLDLEVELNUMBERMASK
+ - scintillacon.SC_FOLDLEVELBASE
+ )
+ is_header = level & scintillacon.SC_FOLDLEVELHEADERFLAG
+ # print(lineSeek, level_no, is_header)
+ if level_no == 0 and is_header:
+ if (expanding and not self.SCIGetFoldExpanded(lineSeek)) or (
+ not expanding and self.SCIGetFoldExpanded(lineSeek)
+ ):
+ self.SCIToggleFold(lineSeek)
+ finally:
+ win32ui.DoWaitCursor(-1)
+
+ def FoldExpandSecondLevelEvent(self, event):
+ if not self.bFolding:
+ return 1
+ win32ui.DoWaitCursor(1)
+ ## I think this is needed since Scintilla may not have
+ ## already formatted parts of file outside visible window.
+ self.Colorize()
+ levels = [scintillacon.SC_FOLDLEVELBASE]
+ ## Scintilla's level number is based on amount of whitespace indentation
+ for lineno in range(self.GetLineCount()):
+ level = self.SCIGetFoldLevel(lineno)
+ if not level & scintillacon.SC_FOLDLEVELHEADERFLAG:
+ continue
+ curr_level = level & scintillacon.SC_FOLDLEVELNUMBERMASK
+ if curr_level > levels[-1]:
+ levels.append(curr_level)
+ try:
+ level_ind = levels.index(curr_level)
+ except ValueError:
+ ## probably syntax error in source file, bail
+ break
+ levels = levels[: level_ind + 1]
+ if level_ind == 1 and not self.SCIGetFoldExpanded(lineno):
+ self.SCIToggleFold(lineno)
+ win32ui.DoWaitCursor(-1)
+
+ def FoldCollapseSecondLevelEvent(self, event):
+ if not self.bFolding:
+ return 1
+ win32ui.DoWaitCursor(1)
+ ## I think this is needed since Scintilla may not have
+ ## already formatted parts of file outside visible window.
+ self.Colorize()
+ levels = [scintillacon.SC_FOLDLEVELBASE]
+ ## Scintilla's level number is based on amount of whitespace indentation
+ for lineno in range(self.GetLineCount()):
+ level = self.SCIGetFoldLevel(lineno)
+ if not level & scintillacon.SC_FOLDLEVELHEADERFLAG:
+ continue
+ curr_level = level & scintillacon.SC_FOLDLEVELNUMBERMASK
+ if curr_level > levels[-1]:
+ levels.append(curr_level)
+ try:
+ level_ind = levels.index(curr_level)
+ except ValueError:
+ ## probably syntax error in source file, bail
+ break
+ levels = levels[: level_ind + 1]
+ if level_ind == 1 and self.SCIGetFoldExpanded(lineno):
+ self.SCIToggleFold(lineno)
+ win32ui.DoWaitCursor(-1)
+
+ def FoldExpandEvent(self, event):
+ if not self.bFolding:
+ return 1
+ win32ui.DoWaitCursor(1)
+ lineno = self.LineFromChar(self.GetSel()[0])
+ if self.SCIGetFoldLevel(
+ lineno
+ ) & scintillacon.SC_FOLDLEVELHEADERFLAG and not self.SCIGetFoldExpanded(lineno):
+ self.SCIToggleFold(lineno)
+ win32ui.DoWaitCursor(-1)
+
+ def FoldExpandAllEvent(self, event):
+ if not self.bFolding:
+ return 1
+ win32ui.DoWaitCursor(1)
+ for lineno in range(0, self.GetLineCount()):
+ if self.SCIGetFoldLevel(
+ lineno
+ ) & scintillacon.SC_FOLDLEVELHEADERFLAG and not self.SCIGetFoldExpanded(
+ lineno
+ ):
+ self.SCIToggleFold(lineno)
+ win32ui.DoWaitCursor(-1)
+
+ def FoldCollapseEvent(self, event):
+ if not self.bFolding:
+ return 1
+ win32ui.DoWaitCursor(1)
+ lineno = self.LineFromChar(self.GetSel()[0])
+ if self.SCIGetFoldLevel(
+ lineno
+ ) & scintillacon.SC_FOLDLEVELHEADERFLAG and self.SCIGetFoldExpanded(lineno):
+ self.SCIToggleFold(lineno)
+ win32ui.DoWaitCursor(-1)
+
+ def FoldCollapseAllEvent(self, event):
+ if not self.bFolding:
+ return 1
+ win32ui.DoWaitCursor(1)
+ self.Colorize()
+ for lineno in range(0, self.GetLineCount()):
+ if self.SCIGetFoldLevel(
+ lineno
+ ) & scintillacon.SC_FOLDLEVELHEADERFLAG and self.SCIGetFoldExpanded(lineno):
+ self.SCIToggleFold(lineno)
+ win32ui.DoWaitCursor(-1)
+
+
+class SplitterFrame(EditorFrame):
+ def OnCreate(self, cs):
+ self.HookCommand(self.OnWindowSplit, win32ui.ID_WINDOW_SPLIT)
+ return 1
+
+ def OnWindowSplit(self, id, code):
+ self.GetDlgItem(win32ui.AFX_IDW_PANE_FIRST).DoKeyboardSplit()
+ return 1
+
+
+class SyntEditTemplate(EditorTemplateBase):
+ def __init__(
+ self, res=win32ui.IDR_TEXTTYPE, makeDoc=None, makeFrame=None, makeView=None
+ ):
+ if makeDoc is None:
+ makeDoc = SyntEditDocument
+ if makeView is None:
+ makeView = SyntEditView
+ if makeFrame is None:
+ makeFrame = SplitterFrame
+ self.bSetMenus = 0
+ EditorTemplateBase.__init__(self, res, makeDoc, makeFrame, makeView)
+
+ def CheckIDLEMenus(self, idle):
+ if self.bSetMenus:
+ return
+ self.bSetMenus = 1
+
+ submenu = win32ui.CreatePopupMenu()
+ newitems = idle.GetMenuItems("edit")
+ flags = win32con.MF_STRING | win32con.MF_ENABLED
+ for text, event in newitems:
+ id = bindings.event_to_commands.get(event)
+ if id is not None:
+ keyname = pywin.scintilla.view.configManager.get_key_binding(
+ event, ["editor"]
+ )
+ if keyname is not None:
+ text += "\t" + keyname
+ submenu.AppendMenu(flags, id, text)
+
+ mainMenu = self.GetSharedMenu()
+ editMenu = mainMenu.GetSubMenu(1)
+ editMenu.AppendMenu(win32con.MF_SEPARATOR, 0, "")
+ editMenu.AppendMenu(
+ win32con.MF_STRING | win32con.MF_POPUP | win32con.MF_ENABLED,
+ submenu.GetHandle(),
+ "&Source Code",
+ )
+
+ def _CreateDocTemplate(self, resourceId):
+ return win32ui.CreateDocTemplate(resourceId)
+
+ def CreateWin32uiDocument(self):
+ return self.DoCreateDoc()
+
+ def GetPythonPropertyPages(self):
+ """Returns a list of property pages"""
+ from pywin.scintilla import configui
+
+ return EditorTemplateBase.GetPythonPropertyPages(self) + [
+ configui.ScintillaFormatPropertyPage()
+ ]
+
+
+# For debugging purposes, when this module may be reloaded many times.
+try:
+ win32ui.GetApp().RemoveDocTemplate(editorTemplate) # type: ignore[has-type, used-before-def]
+except NameError:
+ pass
+
+editorTemplate = SyntEditTemplate()
+win32ui.GetApp().AddDocTemplate(editorTemplate)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/configui.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/configui.py
new file mode 100644
index 0000000000000000000000000000000000000000..9250e7dd1fa4cac16c69ef4d6d531b00652f3074
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/configui.py
@@ -0,0 +1,299 @@
+import pywin.scintilla.config
+import win32api
+import win32con
+import win32ui
+from pywin.framework.editor import DeleteEditorOption, GetEditorOption, SetEditorOption
+from pywin.mfc import dialog
+
+from . import document
+
+# The standard 16 color VGA palette should always be possible
+paletteVGA = (
+ ("Black", 0, 0, 0),
+ ("Navy", 0, 0, 128),
+ ("Green", 0, 128, 0),
+ ("Cyan", 0, 128, 128),
+ ("Maroon", 128, 0, 0),
+ ("Purple", 128, 0, 128),
+ ("Olive", 128, 128, 0),
+ ("Gray", 128, 128, 128),
+ ("Silver", 192, 192, 192),
+ ("Blue", 0, 0, 255),
+ ("Lime", 0, 255, 0),
+ ("Aqua", 0, 255, 255),
+ ("Red", 255, 0, 0),
+ ("Fuchsia", 255, 0, 255),
+ ("Yellow", 255, 255, 0),
+ ("White", 255, 255, 255),
+)
+
+
+######################################################
+#
+# Property Page for editor options
+#
+class EditorPropertyPage(dialog.PropertyPage):
+ def __init__(self):
+ dialog.PropertyPage.__init__(self, win32ui.IDD_PP_EDITOR)
+ self.autooptions = []
+ self._AddEditorOption(win32ui.IDC_AUTO_RELOAD, "i", "Auto Reload", 1)
+ self._AddEditorOption(
+ win32ui.IDC_COMBO1, "i", "Backup Type", document.BAK_DOT_BAK_BAK_DIR
+ )
+ self._AddEditorOption(
+ win32ui.IDC_AUTOCOMPLETE, "i", "Autocomplete Attributes", 1
+ )
+ self._AddEditorOption(win32ui.IDC_CALLTIPS, "i", "Show Call Tips", 1)
+ self._AddEditorOption(
+ win32ui.IDC_MARGIN_LINENUMBER, "i", "Line Number Margin Width", 0
+ )
+ self._AddEditorOption(win32ui.IDC_RADIO1, "i", "MarkersInMargin", None)
+ self._AddEditorOption(
+ win32ui.IDC_MARGIN_MARKER, "i", "Marker Margin Width", None
+ )
+ self["Marker Margin Width"] = GetEditorOption("Marker Margin Width", 16)
+
+ # Folding
+ self._AddEditorOption(win32ui.IDC_MARGIN_FOLD, "i", "Fold Margin Width", 12)
+ self._AddEditorOption(win32ui.IDC_FOLD_ENABLE, "i", "Enable Folding", 1)
+ self._AddEditorOption(win32ui.IDC_FOLD_ON_OPEN, "i", "Fold On Open", 0)
+ self._AddEditorOption(win32ui.IDC_FOLD_SHOW_LINES, "i", "Fold Lines", 1)
+
+ # Right edge.
+ self._AddEditorOption(
+ win32ui.IDC_RIGHTEDGE_ENABLE, "i", "Right Edge Enabled", 0
+ )
+ self._AddEditorOption(
+ win32ui.IDC_RIGHTEDGE_COLUMN, "i", "Right Edge Column", 75
+ )
+
+ # Source control, etc
+ self.AddDDX(win32ui.IDC_VSS_INTEGRATE, "bVSS")
+ self.AddDDX(win32ui.IDC_KEYBOARD_CONFIG, "Configs", "l")
+ self["Configs"] = pywin.scintilla.config.find_config_files()
+
+ def _AddEditorOption(self, idd, typ, optionName, defaultVal):
+ self.AddDDX(idd, optionName, typ)
+ # some options are "derived" - ie, can be implied from others
+ # (eg, "view markers in background" is implied from "markerMarginWidth==0"
+ # So we don't actually store these values, but they do still get DDX support.
+ if defaultVal is not None:
+ self[optionName] = GetEditorOption(optionName, defaultVal)
+ self.autooptions.append((optionName, defaultVal))
+
+ def OnInitDialog(self):
+ for name, val in self.autooptions:
+ self[name] = GetEditorOption(name, val)
+
+ # Note that these MUST be in the same order as the BAK constants.
+ cbo = self.GetDlgItem(win32ui.IDC_COMBO1)
+ cbo.AddString("None")
+ cbo.AddString(".BAK File")
+ cbo.AddString("TEMP dir")
+ cbo.AddString("Own dir")
+
+ # Source Safe
+ bVSS = (
+ GetEditorOption("Source Control Module", "") == "pywin.framework.editor.vss"
+ )
+ self["bVSS"] = bVSS
+
+ edit = self.GetDlgItem(win32ui.IDC_RIGHTEDGE_SAMPLE)
+ edit.SetWindowText("Sample Color")
+
+ rc = dialog.PropertyPage.OnInitDialog(self)
+
+ try:
+ self.GetDlgItem(win32ui.IDC_KEYBOARD_CONFIG).SelectString(
+ -1, GetEditorOption("Keyboard Config", "default")
+ )
+ except win32ui.error:
+ import traceback
+
+ traceback.print_exc()
+
+ self.HookCommand(self.OnButSimple, win32ui.IDC_FOLD_ENABLE)
+ self.HookCommand(self.OnButSimple, win32ui.IDC_RADIO1)
+ self.HookCommand(self.OnButSimple, win32ui.IDC_RADIO2)
+ self.HookCommand(self.OnButSimple, win32ui.IDC_RIGHTEDGE_ENABLE)
+ self.HookCommand(self.OnButEdgeColor, win32ui.IDC_RIGHTEDGE_DEFINE)
+
+ butMarginEnabled = self["Marker Margin Width"] > 0
+ self.GetDlgItem(win32ui.IDC_RADIO1).SetCheck(butMarginEnabled)
+ self.GetDlgItem(win32ui.IDC_RADIO2).SetCheck(not butMarginEnabled)
+
+ self.edgeColor = self.initialEdgeColor = GetEditorOption(
+ "Right Edge Color", win32api.RGB(0xEF, 0xEF, 0xEF)
+ )
+ for spinner_id in (win32ui.IDC_SPIN1, win32ui.IDC_SPIN2, win32ui.IDC_SPIN3):
+ spinner = self.GetDlgItem(spinner_id)
+ spinner.SetRange(0, 100)
+ self.UpdateUIForState()
+
+ return rc
+
+ def OnButSimple(self, id, code):
+ if code == win32con.BN_CLICKED:
+ self.UpdateUIForState()
+
+ def OnButEdgeColor(self, id, code):
+ if code == win32con.BN_CLICKED:
+ d = win32ui.CreateColorDialog(self.edgeColor, 0, self)
+ # Ensure the current color is a custom color (as it may not be in the swatch)
+ # plus some other nice gray scales.
+ ccs = [self.edgeColor]
+ for c in range(0xEF, 0x4F, -0x10):
+ ccs.append(win32api.RGB(c, c, c))
+ d.SetCustomColors(ccs)
+ if d.DoModal() == win32con.IDOK:
+ self.edgeColor = d.GetColor()
+ self.UpdateUIForState()
+
+ def UpdateUIForState(self):
+ folding = self.GetDlgItem(win32ui.IDC_FOLD_ENABLE).GetCheck()
+ self.GetDlgItem(win32ui.IDC_FOLD_ON_OPEN).EnableWindow(folding)
+ self.GetDlgItem(win32ui.IDC_FOLD_SHOW_LINES).EnableWindow(folding)
+
+ widthEnabled = self.GetDlgItem(win32ui.IDC_RADIO1).GetCheck()
+ self.GetDlgItem(win32ui.IDC_MARGIN_MARKER).EnableWindow(widthEnabled)
+ self.UpdateData() # Ensure self[] is up to date with the control data.
+ if widthEnabled and self["Marker Margin Width"] == 0:
+ self["Marker Margin Width"] = 16
+ self.UpdateData(0) # Ensure control up to date with self[]
+
+ # Right edge
+ edgeEnabled = self.GetDlgItem(win32ui.IDC_RIGHTEDGE_ENABLE).GetCheck()
+ self.GetDlgItem(win32ui.IDC_RIGHTEDGE_COLUMN).EnableWindow(edgeEnabled)
+ self.GetDlgItem(win32ui.IDC_RIGHTEDGE_SAMPLE).EnableWindow(edgeEnabled)
+ self.GetDlgItem(win32ui.IDC_RIGHTEDGE_DEFINE).EnableWindow(edgeEnabled)
+
+ edit = self.GetDlgItem(win32ui.IDC_RIGHTEDGE_SAMPLE)
+ edit.SetBackgroundColor(0, self.edgeColor)
+
+ def OnOK(self):
+ for name, defVal in self.autooptions:
+ SetEditorOption(name, self[name])
+ # Margin width gets handled differently.
+ if self["MarkersInMargin"] == 0:
+ SetEditorOption("Marker Margin Width", self["Marker Margin Width"])
+ else:
+ SetEditorOption("Marker Margin Width", 0)
+ if self.edgeColor != self.initialEdgeColor:
+ SetEditorOption("Right Edge Color", self.edgeColor)
+ if self["bVSS"]:
+ SetEditorOption("Source Control Module", "pywin.framework.editor.vss")
+ else:
+ if (
+ GetEditorOption("Source Control Module", "")
+ == "pywin.framework.editor.vss"
+ ):
+ SetEditorOption("Source Control Module", "")
+ # Keyboard config
+ configname = self.GetDlgItem(win32ui.IDC_KEYBOARD_CONFIG).GetWindowText()
+ if configname:
+ if configname == "default":
+ DeleteEditorOption("Keyboard Config")
+ else:
+ SetEditorOption("Keyboard Config", configname)
+
+ import pywin.scintilla.view
+
+ pywin.scintilla.view.LoadConfiguration()
+
+ # Now tell all views we have changed.
+ ## for doc in editorTemplate.GetDocumentList():
+ ## for view in doc.GetAllViews():
+ ## try:
+ ## fn = view.OnConfigChange
+ ## except AttributeError:
+ ## continue
+ ## fn()
+ return 1
+
+
+class EditorWhitespacePropertyPage(dialog.PropertyPage):
+ def __init__(self):
+ dialog.PropertyPage.__init__(self, win32ui.IDD_PP_TABS)
+ self.autooptions = []
+ self._AddEditorOption(win32ui.IDC_TAB_SIZE, "i", "Tab Size", 4)
+ self._AddEditorOption(win32ui.IDC_INDENT_SIZE, "i", "Indent Size", 4)
+ self._AddEditorOption(win32ui.IDC_USE_SMART_TABS, "i", "Smart Tabs", 1)
+ self._AddEditorOption(win32ui.IDC_VIEW_WHITESPACE, "i", "View Whitespace", 0)
+ self._AddEditorOption(win32ui.IDC_VIEW_EOL, "i", "View EOL", 0)
+ self._AddEditorOption(
+ win32ui.IDC_VIEW_INDENTATIONGUIDES, "i", "View Indentation Guides", 0
+ )
+
+ def _AddEditorOption(self, idd, typ, optionName, defaultVal):
+ self.AddDDX(idd, optionName, typ)
+ self[optionName] = GetEditorOption(optionName, defaultVal)
+ self.autooptions.append((optionName, defaultVal))
+
+ def OnInitDialog(self):
+ for name, val in self.autooptions:
+ self[name] = GetEditorOption(name, val)
+
+ rc = dialog.PropertyPage.OnInitDialog(self)
+
+ idc = win32ui.IDC_TABTIMMY_NONE
+ if GetEditorOption("Use Tab Timmy", 1):
+ idc = win32ui.IDC_TABTIMMY_IND
+ self.GetDlgItem(idc).SetCheck(1)
+
+ idc = win32ui.IDC_RADIO1
+ if GetEditorOption("Use Tabs", 0):
+ idc = win32ui.IDC_USE_TABS
+ self.GetDlgItem(idc).SetCheck(1)
+
+ tt_color = GetEditorOption("Tab Timmy Color", win32api.RGB(0xFF, 0, 0))
+ self.cbo = self.GetDlgItem(win32ui.IDC_COMBO1)
+ for c in paletteVGA:
+ self.cbo.AddString(c[0])
+ sel = 0
+ for c in paletteVGA:
+ if tt_color == win32api.RGB(c[1], c[2], c[3]):
+ break
+ sel += 1
+ else:
+ sel = -1
+ self.cbo.SetCurSel(sel)
+ self.HookCommand(self.OnButSimple, win32ui.IDC_TABTIMMY_NONE)
+ self.HookCommand(self.OnButSimple, win32ui.IDC_TABTIMMY_IND)
+ self.HookCommand(self.OnButSimple, win32ui.IDC_TABTIMMY_BG)
+ # Set ranges for the spinners.
+ for spinner_id in [win32ui.IDC_SPIN1, win32ui.IDC_SPIN2]:
+ spinner = self.GetDlgItem(spinner_id)
+ spinner.SetRange(1, 16)
+ return rc
+
+ def OnButSimple(self, id, code):
+ if code == win32con.BN_CLICKED:
+ self.UpdateUIForState()
+
+ def UpdateUIForState(self):
+ timmy = self.GetDlgItem(win32ui.IDC_TABTIMMY_NONE).GetCheck()
+ self.GetDlgItem(win32ui.IDC_COMBO1).EnableWindow(not timmy)
+
+ def OnOK(self):
+ for name, defVal in self.autooptions:
+ SetEditorOption(name, self[name])
+
+ SetEditorOption("Use Tabs", self.GetDlgItem(win32ui.IDC_USE_TABS).GetCheck())
+
+ SetEditorOption(
+ "Use Tab Timmy", self.GetDlgItem(win32ui.IDC_TABTIMMY_IND).GetCheck()
+ )
+ c = paletteVGA[self.cbo.GetCurSel()]
+ SetEditorOption("Tab Timmy Color", win32api.RGB(c[1], c[2], c[3]))
+
+ return 1
+
+
+def testpp():
+ ps = dialog.PropertySheet("Editor Options")
+ ps.AddPage(EditorWhitespacePropertyPage())
+ ps.DoModal()
+
+
+if __name__ == "__main__":
+ testpp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/document.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/document.py
new file mode 100644
index 0000000000000000000000000000000000000000..6ad3c35e467adb67b54bce3b7035f5bf754a38c6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/document.py
@@ -0,0 +1,379 @@
+# We no longer support the old, non-colour editor!
+
+import os
+import shutil
+import traceback
+
+import win32api
+import win32con
+import win32ui
+from pywin.framework.editor import GetEditorOption
+
+BAK_NONE = 0
+BAK_DOT_BAK = 1
+BAK_DOT_BAK_TEMP_DIR = 2
+BAK_DOT_BAK_BAK_DIR = 3
+
+MSG_CHECK_EXTERNAL_FILE = (
+ win32con.WM_USER + 1999
+) ## WARNING: Duplicated in editor.py and coloreditor.py
+
+import pywin.scintilla.document
+
+ParentEditorDocument = pywin.scintilla.document.CScintillaDocument
+
+
+class EditorDocumentBase(ParentEditorDocument):
+ def __init__(self, template):
+ self.bAutoReload = GetEditorOption("Auto Reload", 1)
+ self.bDeclinedReload = 0 # Has the user declined to reload.
+ self.fileStat = None
+ self.bReportedFileNotFound = 0
+
+ # what sort of bak file should I create.
+ # default to write to %temp%/bak/filename.ext
+ self.bakFileType = GetEditorOption("Backup Type", BAK_DOT_BAK_BAK_DIR)
+
+ self.watcherThread = FileWatchingThread(self)
+ self.watcherThread.CreateThread()
+ # Should I try and use VSS integration?
+ self.scModuleName = GetEditorOption("Source Control Module", "")
+ self.scModule = None # Loaded when first used.
+ ParentEditorDocument.__init__(self, template, template.CreateWin32uiDocument())
+
+ def OnCloseDocument(self):
+ self.watcherThread.SignalStop()
+ return self._obj_.OnCloseDocument()
+
+ # def OnOpenDocument(self, name):
+ # rc = ParentEditorDocument.OnOpenDocument(self, name)
+ # self.GetFirstView()._SetLoadedText(self.text)
+ # self._DocumentStateChanged()
+ # return rc
+
+ def OnSaveDocument(self, fileName):
+ win32ui.SetStatusText("Saving file...", 1)
+ # rename to bak if required.
+ dir, basename = os.path.split(fileName)
+ if self.bakFileType == BAK_DOT_BAK:
+ bakFileName = dir + "\\" + os.path.splitext(basename)[0] + ".bak"
+ elif self.bakFileType == BAK_DOT_BAK_TEMP_DIR:
+ bakFileName = (
+ win32api.GetTempPath() + "\\" + os.path.splitext(basename)[0] + ".bak"
+ )
+ elif self.bakFileType == BAK_DOT_BAK_BAK_DIR:
+ tempPath = os.path.join(win32api.GetTempPath(), "bak")
+ try:
+ os.mkdir(tempPath, 0)
+ except OSError:
+ pass
+ bakFileName = os.path.join(tempPath, basename)
+ try:
+ os.unlink(bakFileName) # raise NameError if no bakups wanted.
+ except (OSError, NameError):
+ pass
+ try:
+ # Do a copy as it might be on different volumes,
+ # and the file may be a hard-link, causing the link
+ # to follow the backup.
+ shutil.copy2(fileName, bakFileName)
+ except (OSError, NameError):
+ pass
+ try:
+ self.SaveFile(fileName)
+ except OSError as details:
+ win32ui.MessageBox("Error - could not save file\r\n\r\n%s" % details)
+ return 0
+ except (UnicodeEncodeError, LookupError) as details:
+ rc = win32ui.MessageBox(
+ "Encoding failed: \r\n%s" % details
+ + "\r\nPlease add desired source encoding as first line of file, eg \r\n"
+ + "# -*- coding: mbcs -*-\r\n\r\n"
+ + "If you continue, the file will be saved as binary and will\r\n"
+ + "not be valid in the declared encoding.\r\n\r\n"
+ + "Save the file as binary with an invalid encoding?",
+ "File save failed",
+ win32con.MB_YESNO | win32con.MB_DEFBUTTON2,
+ )
+ if rc == win32con.IDYES:
+ try:
+ self.SaveFile(fileName, encoding="latin-1")
+ except OSError as details:
+ win32ui.MessageBox(
+ "Error - could not save file\r\n\r\n%s" % details
+ )
+ return 0
+ else:
+ return 0
+ self.SetModifiedFlag(0) # No longer dirty
+ self.bDeclinedReload = 0 # They probably want to know if it changes again!
+ win32ui.AddToRecentFileList(fileName)
+ self.SetPathName(fileName)
+ win32ui.SetStatusText("Ready")
+ self._DocumentStateChanged()
+ return 1
+
+ def FinalizeViewCreation(self, view):
+ ParentEditorDocument.FinalizeViewCreation(self, view)
+ if view == self.GetFirstView():
+ self._DocumentStateChanged()
+ if view.bFolding and GetEditorOption("Fold On Open", 0):
+ view.FoldTopLevelEvent()
+
+ def HookViewNotifications(self, view):
+ ParentEditorDocument.HookViewNotifications(self, view)
+
+ # Support for reloading the document from disk - presumably after some
+ # external application has modified it (or possibly source control has
+ # checked it out.
+ def ReloadDocument(self):
+ """Reloads the document from disk. Assumes the file has
+ been saved and user has been asked if necessary - it just does it!
+ """
+ win32ui.SetStatusText("Reloading document. Please wait...", 1)
+ self.SetModifiedFlag(0)
+ # Loop over all views, saving their state, then reload the document
+ views = self.GetAllViews()
+ states = []
+ for view in views:
+ try:
+ info = view._PrepareUserStateChange()
+ except AttributeError: # Not our editor view?
+ info = None
+ states.append(info)
+ self.OnOpenDocument(self.GetPathName())
+ for view, info in zip(views, states):
+ if info is not None:
+ view._EndUserStateChange(info)
+ self._DocumentStateChanged()
+ win32ui.SetStatusText("Document reloaded.")
+
+ # Reloading the file
+ def CheckExternalDocumentUpdated(self):
+ if self.bDeclinedReload or not self.GetPathName():
+ return
+ try:
+ newstat = os.stat(self.GetPathName())
+ except OSError as exc:
+ if not self.bReportedFileNotFound:
+ print(
+ "The file '{}' is open for editing, but\nchecking it for changes caused the error: {}".format(
+ self.GetPathName(), exc.strerror
+ )
+ )
+ self.bReportedFileNotFound = 1
+ return
+ if self.bReportedFileNotFound:
+ print(
+ "The file '{}' has re-appeared - continuing to watch for changes...".format(
+ self.GetPathName()
+ )
+ )
+ self.bReportedFileNotFound = (
+ 0 # Once found again we want to start complaining.
+ )
+ changed = (
+ (self.fileStat is None)
+ or self.fileStat[0] != newstat[0]
+ or self.fileStat[6] != newstat[6]
+ or self.fileStat[8] != newstat[8]
+ or self.fileStat[9] != newstat[9]
+ )
+ if changed:
+ question = None
+ if self.IsModified():
+ question = (
+ "%s\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it and LOSE THE CHANGES in the source editor?"
+ % self.GetPathName()
+ )
+ mbStyle = win32con.MB_YESNO | win32con.MB_DEFBUTTON2 # Default to "No"
+ else:
+ if not self.bAutoReload:
+ question = (
+ "%s\r\n\r\nThis file has been modified outside of the source editor.\r\nDo you want to reload it?"
+ % self.GetPathName()
+ )
+ mbStyle = win32con.MB_YESNO # Default to "Yes"
+ if question:
+ rc = win32ui.MessageBox(question, None, mbStyle)
+ if rc != win32con.IDYES:
+ self.bDeclinedReload = 1
+ return
+ self.ReloadDocument()
+
+ def _DocumentStateChanged(self):
+ """Called whenever the documents state (on disk etc) has been changed
+ by the editor (eg, as the result of a save operation)
+ """
+ if self.GetPathName():
+ try:
+ self.fileStat = os.stat(self.GetPathName())
+ except OSError:
+ self.fileStat = None
+ else:
+ self.fileStat = None
+ self.watcherThread._DocumentStateChanged()
+ self._UpdateUIForState()
+ self._ApplyOptionalToViews("_UpdateUIForState")
+ self._ApplyOptionalToViews("SetReadOnly", self._IsReadOnly())
+ self._ApplyOptionalToViews("SCISetSavePoint")
+ # Allow the debugger to reset us too.
+ import pywin.debugger
+
+ if pywin.debugger.currentDebugger is not None:
+ pywin.debugger.currentDebugger.UpdateDocumentLineStates(self)
+
+ # Read-only document support - make it obvious to the user
+ # that the file is read-only.
+ def _IsReadOnly(self):
+ return self.fileStat is not None and (self.fileStat[0] & 128) == 0
+
+ def _UpdateUIForState(self):
+ """Change the title to reflect the state of the document -
+ eg ReadOnly, Dirty, etc
+ """
+ filename = self.GetPathName()
+ if not filename:
+ return # New file - nothing to do
+ try:
+ # This seems necessary so the internal state of the window becomes
+ # "visible". without it, it is still shown, but certain functions
+ # (such as updating the title) don't immediately work?
+ self.GetFirstView().ShowWindow(win32con.SW_SHOW)
+ title = win32ui.GetFileTitle(filename)
+ except win32ui.error:
+ title = filename
+ if self._IsReadOnly():
+ title += " (read-only)"
+ self.SetTitle(title)
+
+ def MakeDocumentWritable(self):
+ pretend_ss = 0 # Set to 1 to test this without source safe :-)
+ if not self.scModuleName and not pretend_ss: # No Source Control support.
+ win32ui.SetStatusText(
+ "Document is read-only, and no source-control system is configured"
+ )
+ win32api.MessageBeep()
+ return 0
+
+ # We have source control support - check if the user wants to use it.
+ msg = "Would you like to check this file out?"
+ defButton = win32con.MB_YESNO
+ if self.IsModified():
+ msg += "\r\n\r\nALL CHANGES IN THE EDITOR WILL BE LOST"
+ defButton = win32con.MB_YESNO
+ if win32ui.MessageBox(msg, None, defButton) != win32con.IDYES:
+ return 0
+
+ if pretend_ss:
+ print("We are only pretending to check it out!")
+ win32api.SetFileAttributes(
+ self.GetPathName(), win32con.FILE_ATTRIBUTE_NORMAL
+ )
+ self.ReloadDocument()
+ return 1
+
+ # Now call on the module to do it.
+ if self.scModule is None:
+ try:
+ self.scModule = __import__(self.scModuleName)
+ for part in self.scModuleName.split(".")[1:]:
+ self.scModule = getattr(self.scModule, part)
+ except:
+ traceback.print_exc()
+ print("Error loading source control module.")
+ return 0
+
+ if self.scModule.CheckoutFile(self.GetPathName()):
+ self.ReloadDocument()
+ return 1
+ return 0
+
+ def CheckMakeDocumentWritable(self):
+ if self._IsReadOnly():
+ return self.MakeDocumentWritable()
+ return 1
+
+ def SaveModified(self):
+ # Called as the document is closed. If we are about
+ # to prompt for a save, bring the document to the foreground.
+ if self.IsModified():
+ frame = self.GetFirstView().GetParentFrame()
+ try:
+ frame.MDIActivate()
+ frame.AutoRestore()
+ except:
+ print("Could not bring document to foreground")
+ return self._obj_.SaveModified()
+
+
+# NOTE - I DONT use the standard threading module,
+# as this waits for all threads to terminate at shutdown.
+# When using the debugger, it is possible shutdown will
+# occur without Pythonwin getting a complete shutdown,
+# so we deadlock at the end - threading is waiting for
+import pywin.mfc.thread
+import win32event
+
+
+class FileWatchingThread(pywin.mfc.thread.WinThread):
+ def __init__(self, doc):
+ self.doc = doc
+ self.adminEvent = win32event.CreateEvent(None, 0, 0, None)
+ self.stopEvent = win32event.CreateEvent(None, 0, 0, None)
+ self.watchEvent = None
+ pywin.mfc.thread.WinThread.__init__(self)
+
+ def _DocumentStateChanged(self):
+ win32event.SetEvent(self.adminEvent)
+
+ def RefreshEvent(self):
+ self.hwnd = self.doc.GetFirstView().GetSafeHwnd()
+ if self.watchEvent is not None:
+ win32api.FindCloseChangeNotification(self.watchEvent)
+ self.watchEvent = None
+ path = self.doc.GetPathName()
+ if path:
+ path = os.path.dirname(path)
+ if path:
+ filter = (
+ win32con.FILE_NOTIFY_CHANGE_FILE_NAME
+ | win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES
+ | win32con.FILE_NOTIFY_CHANGE_LAST_WRITE
+ )
+ try:
+ self.watchEvent = win32api.FindFirstChangeNotification(path, 0, filter)
+ except win32api.error as exc:
+ print("Can not watch file", path, "for changes -", exc.strerror)
+
+ def SignalStop(self):
+ win32event.SetEvent(self.stopEvent)
+
+ def Run(self):
+ while 1:
+ handles = [self.stopEvent, self.adminEvent]
+ if self.watchEvent is not None:
+ handles.append(self.watchEvent)
+ rc = win32event.WaitForMultipleObjects(handles, 0, win32event.INFINITE)
+ if rc == win32event.WAIT_OBJECT_0:
+ break
+ elif rc == win32event.WAIT_OBJECT_0 + 1:
+ self.RefreshEvent()
+ else:
+ win32api.PostMessage(self.hwnd, MSG_CHECK_EXTERNAL_FILE, 0, 0)
+ try:
+ # If the directory has been removed underneath us, we get this error.
+ win32api.FindNextChangeNotification(self.watchEvent)
+ except win32api.error as exc:
+ print(
+ "Can not watch file",
+ self.doc.GetPathName(),
+ "for changes -",
+ exc.strerror,
+ )
+ break
+
+ # close a circular reference
+ self.doc = None
+ if self.watchEvent:
+ win32api.FindCloseChangeNotification(self.watchEvent)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/editor.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/editor.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdc7e9ad28bfa26d43a3988f3ed72bc21db94188
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/editor.py
@@ -0,0 +1,511 @@
+#####################################################################
+#
+# editor.py
+#
+# A general purpose text editor, built on top of the win32ui edit
+# type, which is built on an MFC CEditView
+#
+#
+# We now support reloading of externally modified documented
+# (eg, presumably by some other process, such as source control or
+# another editor.
+# We also support auto-loading of externally modified files.
+# - if the current document has not been modified in this
+# editor, but has been modified on disk, then the file
+# can be automatically reloaded.
+#
+# Note that it will _always_ prompt you if the file in the editor has been modified.
+
+
+import re
+
+import win32api
+import win32con
+import win32ui
+from pywin.framework.editor import (
+ GetEditorFontOption,
+ GetEditorOption,
+ defaultCharacterFormat,
+)
+from pywin.mfc import afxres
+from pywin.mfc.docview import RichEditView as ParentEditorView
+
+from .document import EditorDocumentBase as ParentEditorDocument
+
+# from pywin.mfc.docview import EditView as ParentEditorView
+# from pywin.mfc.docview import Document as ParentEditorDocument
+
+patImport = re.compile(r"import (?P.*)")
+patIndent = re.compile(r"^([ \t]*[~ \t])")
+
+ID_LOCATE_FILE = 0xE200
+ID_GOTO_LINE = 0xE2001
+# WARNING: Duplicated in document.py and coloreditor.py
+MSG_CHECK_EXTERNAL_FILE = win32con.WM_USER + 1999
+
+# Key Codes that modify the bufffer when Ctrl or Alt are NOT pressed.
+MODIFYING_VK_KEYS = [
+ win32con.VK_BACK,
+ win32con.VK_TAB,
+ win32con.VK_RETURN,
+ win32con.VK_SPACE,
+ win32con.VK_DELETE,
+]
+for k in range(48, 91):
+ MODIFYING_VK_KEYS.append(k)
+
+# Key Codes that modify the bufffer when Ctrl is pressed.
+MODIFYING_VK_KEYS_CTRL = [
+ win32con.VK_BACK,
+ win32con.VK_RETURN,
+ win32con.VK_SPACE,
+ win32con.VK_DELETE,
+]
+
+# Key Codes that modify the bufffer when Alt is pressed.
+MODIFYING_VK_KEYS_ALT = [
+ win32con.VK_BACK,
+ win32con.VK_RETURN,
+ win32con.VK_SPACE,
+ win32con.VK_DELETE,
+]
+
+
+# The editor itself starts here.
+# Using the MFC Document/View model, we have an EditorDocument, which is responsible for
+# managing the contents of the file, and a view which is responsible for rendering it.
+#
+# Due to a limitation in the Windows edit controls, we are limited to one view
+# per document, although nothing in this code assumes this (I hope!)
+
+isRichText = 1 # We are using the Rich Text control. This has not been tested with value "0" for quite some time!
+
+
+class EditorDocument(ParentEditorDocument):
+ #
+ # File loading and saving operations
+ #
+ def OnOpenDocument(self, filename):
+ #
+ # handle Unix and PC text file format.
+ #
+
+ # Get the "long name" of the file name, as it may have been translated
+ # to short names by the shell.
+ self.SetPathName(filename) # Must set this early!
+ # Now do the work!
+ self.BeginWaitCursor()
+ win32ui.SetStatusText("Loading file...", 1)
+ try:
+ f = open(filename, "rb")
+ except OSError:
+ win32ui.MessageBox(
+ filename
+ + "\nCan not find this file\nPlease verify that the correct path and file name are given"
+ )
+ self.EndWaitCursor()
+ return 0
+ raw = f.read()
+ f.close()
+ contents = self.TranslateLoadedData(raw)
+ rc = 0
+ try:
+ self.GetFirstView().SetWindowText(contents)
+ rc = 1
+ except TypeError: # Null byte in file.
+ win32ui.MessageBox("This file contains NULL bytes, and can not be edited")
+ rc = 0
+
+ self.EndWaitCursor()
+ self.SetModifiedFlag(0) # No longer dirty
+ self._DocumentStateChanged()
+ return rc
+
+ def TranslateLoadedData(self, data):
+ """Given raw data read from a file, massage it suitable for the edit window"""
+ # if a CR in the first 250 chars, then perform the expensive translate
+ if data[:250].find("\r") == -1:
+ win32ui.SetStatusText(
+ "Translating from Unix file format - please wait...", 1
+ )
+ return re.sub(r"\r*\n", "\r\n", data)
+ else:
+ return data
+
+ def SaveFile(self, fileName, encoding=None):
+ if isRichText:
+ view = self.GetFirstView()
+ view.SaveTextFile(fileName, encoding=encoding)
+ else: # Old style edit view window.
+ self.GetFirstView().SaveFile(fileName)
+ try:
+ # Make sure line cache has updated info about me!
+ import linecache
+
+ linecache.checkcache()
+ except:
+ pass
+
+ #
+ # Color state stuff
+ #
+ def SetAllLineColors(self, color=None):
+ for view in self.GetAllViews():
+ view.SetAllLineColors(color)
+
+ def SetLineColor(self, lineNo, color):
+ "Color a line of all views"
+ for view in self.GetAllViews():
+ view.SetLineColor(lineNo, color)
+
+
+# def StreamTextOut(self, data): ### This seems unreliable???
+# self.saveFileHandle.write(data)
+# return 1 # keep em coming!
+
+
+class EditorView(ParentEditorView):
+ def __init__(self, doc):
+ ParentEditorView.__init__(self, doc)
+ if isRichText:
+ self.SetWordWrap(win32ui.CRichEditView_WrapNone)
+
+ self.addToMRU = 1
+ self.HookHandlers()
+ self.bCheckingFile = 0
+
+ self.defCharFormat = GetEditorFontOption("Default Font", defaultCharacterFormat)
+
+ # Smart tabs override everything else if context can be worked out.
+ self.bSmartTabs = GetEditorOption("Smart Tabs", 1)
+
+ self.tabSize = GetEditorOption("Tab Size", 8)
+ self.indentSize = GetEditorOption("Indent Size", 8)
+ # If next indent is at a tab position, and useTabs is set, a tab will be inserted.
+ self.bUseTabs = GetEditorOption("Use Tabs", 1)
+
+ def OnInitialUpdate(self):
+ rc = self._obj_.OnInitialUpdate()
+ self.SetDefaultCharFormat(self.defCharFormat)
+ return rc
+
+ def CutCurLine(self):
+ curLine = self._obj_.LineFromChar()
+ nextLine = curLine + 1
+ start = self._obj_.LineIndex(curLine)
+ end = self._obj_.LineIndex(nextLine)
+ if end == 0: # must be last line.
+ end = start + self.end.GetLineLength(curLine)
+ self._obj_.SetSel(start, end)
+ self._obj_.Cut()
+
+ def _PrepareUserStateChange(self):
+ "Return selection, lineindex, etc info, so it can be restored"
+ self.SetRedraw(0)
+ return self.GetModify(), self.GetSel(), self.GetFirstVisibleLine()
+
+ def _EndUserStateChange(self, info):
+ scrollOff = info[2] - self.GetFirstVisibleLine()
+ if scrollOff:
+ self.LineScroll(scrollOff)
+ self.SetSel(info[1])
+ self.SetModify(info[0])
+ self.SetRedraw(1)
+ self.InvalidateRect()
+ self.UpdateWindow()
+
+ def _UpdateUIForState(self):
+ self.SetReadOnly(self.GetDocument()._IsReadOnly())
+
+ def SetAllLineColors(self, color=None):
+ if isRichText:
+ info = self._PrepareUserStateChange()
+ try:
+ if color is None:
+ color = self.defCharFormat[4]
+ self.SetSel(0, -1)
+ self.SetSelectionCharFormat((win32con.CFM_COLOR, 0, 0, 0, color))
+ finally:
+ self._EndUserStateChange(info)
+
+ def SetLineColor(self, lineNo, color):
+ "lineNo is the 1 based line number to set. If color is None, default color is used."
+ if isRichText:
+ info = self._PrepareUserStateChange()
+ try:
+ if color is None:
+ color = self.defCharFormat[4]
+ lineNo -= 1
+ startIndex = self.LineIndex(lineNo)
+ if startIndex != -1:
+ self.SetSel(startIndex, self.LineIndex(lineNo + 1))
+ self.SetSelectionCharFormat((win32con.CFM_COLOR, 0, 0, 0, color))
+ finally:
+ self._EndUserStateChange(info)
+
+ def Indent(self):
+ """Insert an indent to move the cursor to the next tab position.
+
+ Honors the tab size and 'use tabs' settings. Assumes the cursor is already at the
+ position to be indented, and the selection is a single character (ie, not a block)
+ """
+ start, end = self._obj_.GetSel()
+ startLine = self._obj_.LineFromChar(start)
+ line = self._obj_.GetLine(startLine)
+ realCol = start - self._obj_.LineIndex(startLine)
+ # Calulate the next tab stop.
+ # Expand existing tabs.
+ curCol = 0
+ for ch in line[:realCol]:
+ if ch == "\t":
+ curCol = ((curCol / self.tabSize) + 1) * self.tabSize
+ else:
+ curCol += 1
+ nextColumn = ((curCol / self.indentSize) + 1) * self.indentSize
+ # print("curCol is", curCol, "nextColumn is", nextColumn)
+ ins = None
+ if self.bSmartTabs:
+ # Look for some context.
+ if realCol == 0: # Start of the line - see if the line above can tell us
+ lookLine = startLine - 1
+ while lookLine >= 0:
+ check = self._obj_.GetLine(lookLine)[0:1]
+ if check in ("\t", " "):
+ ins = check
+ break
+ lookLine -= 1
+ else: # See if the previous char can tell us
+ check = line[realCol - 1]
+ if check in ("\t", " "):
+ ins = check
+
+ # Either smart tabs off, or not smart enough!
+ # Use the "old style" settings.
+ if ins is None:
+ if self.bUseTabs and nextColumn % self.tabSize == 0:
+ ins = "\t"
+ else:
+ ins = " "
+
+ if ins == " ":
+ # Calc the number of spaces to take us to the next stop
+ ins *= nextColumn - curCol
+
+ self._obj_.ReplaceSel(ins)
+
+ def BlockDent(self, isIndent, startLine, endLine):
+ "Indent/Undent all lines specified"
+ if not self.GetDocument().CheckMakeDocumentWritable():
+ return 0
+ tabSize = self.tabSize # hard-code for now!
+ info = self._PrepareUserStateChange()
+ try:
+ for lineNo in range(startLine, endLine):
+ pos = self._obj_.LineIndex(lineNo)
+ self._obj_.SetSel(pos, pos)
+ if isIndent:
+ self.Indent()
+ else:
+ line = self._obj_.GetLine(lineNo)
+ try:
+ noToDel = 0
+ if line[0] == "\t":
+ noToDel = 1
+ elif line[0] == " ":
+ for noToDel in range(0, tabSize):
+ if line[noToDel] != " ":
+ break
+ else:
+ noToDel = tabSize
+ if noToDel:
+ self._obj_.SetSel(pos, pos + noToDel)
+ self._obj_.Clear()
+ except IndexError:
+ pass
+ finally:
+ self._EndUserStateChange(info)
+ self.GetDocument().SetModifiedFlag(1) # Now dirty
+ self._obj_.SetSel(self.LineIndex(startLine), self.LineIndex(endLine))
+
+ def GotoLine(self, lineNo=None):
+ try:
+ if lineNo is None:
+ lineNo = int(input("Enter Line Number"))
+ except (ValueError, KeyboardInterrupt):
+ return 0
+ self.GetLineCount() # Seems to be needed when file first opened???
+ charNo = self.LineIndex(lineNo - 1)
+ self.SetSel(charNo)
+
+ def HookHandlers(self): # children can override, but should still call me!
+ # self.HookAllKeyStrokes(self.OnKey)
+ self.HookMessage(self.OnCheckExternalDocumentUpdated, MSG_CHECK_EXTERNAL_FILE)
+ self.HookMessage(self.OnRClick, win32con.WM_RBUTTONDOWN)
+ self.HookMessage(self.OnSetFocus, win32con.WM_SETFOCUS)
+ self.HookMessage(self.OnKeyDown, win32con.WM_KEYDOWN)
+ self.HookKeyStroke(self.OnKeyCtrlY, 25) # ^Y
+ self.HookKeyStroke(self.OnKeyCtrlG, 7) # ^G
+ self.HookKeyStroke(self.OnKeyTab, 9) # TAB
+ self.HookKeyStroke(self.OnKeyEnter, 13) # Enter
+ self.HookCommand(self.OnCmdLocateFile, ID_LOCATE_FILE)
+ self.HookCommand(self.OnCmdGotoLine, ID_GOTO_LINE)
+ self.HookCommand(self.OnEditPaste, afxres.ID_EDIT_PASTE)
+ self.HookCommand(self.OnEditCut, afxres.ID_EDIT_CUT)
+
+ # Hook Handlers
+ def OnSetFocus(self, msg):
+ # Even though we use file change notifications, we should be very sure about it here.
+ self.OnCheckExternalDocumentUpdated(msg)
+
+ def OnRClick(self, params):
+ menu = win32ui.CreatePopupMenu()
+
+ # look for a module name
+ line = self._obj_.GetLine().strip()
+ flags = win32con.MF_STRING | win32con.MF_ENABLED
+ matchResult = patImport.match(line)
+ if matchResult and matchResult[0] == line:
+ menu.AppendMenu(
+ flags, ID_LOCATE_FILE, "&Locate %s.py" % matchResult.group("name")
+ )
+ menu.AppendMenu(win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, win32ui.ID_EDIT_UNDO, "&Undo")
+ menu.AppendMenu(win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, win32ui.ID_EDIT_CUT, "Cu&t")
+ menu.AppendMenu(flags, win32ui.ID_EDIT_COPY, "&Copy")
+ menu.AppendMenu(flags, win32ui.ID_EDIT_PASTE, "&Paste")
+ menu.AppendMenu(flags, win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, win32ui.ID_EDIT_SELECT_ALL, "&Select all")
+ menu.AppendMenu(flags, win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, ID_GOTO_LINE, "&Goto line...")
+ menu.TrackPopupMenu(params[5])
+ return 0
+
+ def OnCmdGotoLine(self, cmd, code):
+ self.GotoLine()
+ return 0
+
+ def OnCmdLocateFile(self, cmd, code):
+ modName = patImport.group("name")
+ if not modName:
+ return 0
+ import pywin.framework.scriptutils
+
+ fileName = pywin.framework.scriptutils.LocatePythonFile(modName)
+ if fileName is None:
+ win32ui.SetStatusText("Can't locate module %s" % modName)
+ else:
+ win32ui.GetApp().OpenDocumentFile(fileName)
+ return 0
+
+ # Key handlers
+ def OnKeyEnter(self, key):
+ if not self.GetDocument().CheckMakeDocumentWritable():
+ return 0
+ curLine = self._obj_.GetLine()
+ self._obj_.ReplaceSel("\r\n") # insert the newline
+ # If the current line indicates the next should be indented,
+ # then copy the current indentation to this line.
+ res = patIndent.match(curLine, 0)
+ if res > 0 and curLine.strip():
+ curIndent = patIndent.group(1)
+ self._obj_.ReplaceSel(curIndent)
+ return 0 # don't pass on
+
+ def OnKeyCtrlY(self, key):
+ if not self.GetDocument().CheckMakeDocumentWritable():
+ return 0
+ self.CutCurLine()
+ return 0 # don't let him have it!
+
+ def OnKeyCtrlG(self, key):
+ self.GotoLine()
+ return 0 # don't let him have it!
+
+ def OnKeyTab(self, key):
+ if not self.GetDocument().CheckMakeDocumentWritable():
+ return 0
+ start, end = self._obj_.GetSel()
+ if start == end: # normal TAB key
+ self.Indent()
+ return 0 # we handled this.
+
+ # Otherwise it is a block indent/dedent.
+ if start > end:
+ start, end = end, start # swap them.
+ startLine = self._obj_.LineFromChar(start)
+ endLine = self._obj_.LineFromChar(end)
+
+ self.BlockDent(win32api.GetKeyState(win32con.VK_SHIFT) >= 0, startLine, endLine)
+ return 0
+
+ def OnEditPaste(self, id, code):
+ # Return 1 if we can make the file editable.(or it already is!)
+ return self.GetDocument().CheckMakeDocumentWritable()
+
+ def OnEditCut(self, id, code):
+ # Return 1 if we can make the file editable.(or it already is!)
+ return self.GetDocument().CheckMakeDocumentWritable()
+
+ def OnKeyDown(self, msg):
+ key = msg[2]
+ if win32api.GetKeyState(win32con.VK_CONTROL) & 0x8000:
+ modList = MODIFYING_VK_KEYS_CTRL
+ elif win32api.GetKeyState(win32con.VK_MENU) & 0x8000:
+ modList = MODIFYING_VK_KEYS_ALT
+ else:
+ modList = MODIFYING_VK_KEYS
+
+ if key in modList:
+ # Return 1 if we can make the file editable.(or it already is!)
+ return self.GetDocument().CheckMakeDocumentWritable()
+ return 1 # Pass it on OK
+
+ # def OnKey(self, key):
+ # return self.GetDocument().CheckMakeDocumentWritable()
+
+ def OnCheckExternalDocumentUpdated(self, msg):
+ if self._obj_ is None or self.bCheckingFile:
+ return
+ self.bCheckingFile = 1
+ self.GetDocument().CheckExternalDocumentUpdated()
+ self.bCheckingFile = 0
+
+
+from .template import EditorTemplateBase
+
+
+class EditorTemplate(EditorTemplateBase):
+ def __init__(
+ self, res=win32ui.IDR_TEXTTYPE, makeDoc=None, makeFrame=None, makeView=None
+ ):
+ if makeDoc is None:
+ makeDoc = EditorDocument
+ if makeView is None:
+ makeView = EditorView
+ EditorTemplateBase.__init__(self, res, makeDoc, makeFrame, makeView)
+
+ def _CreateDocTemplate(self, resourceId):
+ return win32ui.CreateRichEditDocTemplate(resourceId)
+
+ def CreateWin32uiDocument(self):
+ return self.DoCreateRichEditDoc()
+
+
+def Create(fileName=None, title=None, template=None):
+ return editorTemplate.OpenDocumentFile(fileName)
+
+
+from pywin.framework.editor import GetDefaultEditorModuleName
+
+prefModule = GetDefaultEditorModuleName()
+# Initialize only if this is the "default" editor.
+if __name__ == prefModule:
+ # For debugging purposes, when this module may be reloaded many times.
+ try:
+ win32ui.GetApp().RemoveDocTemplate(editorTemplate) # type: ignore[has-type, used-before-def]
+ except (NameError, win32ui.error):
+ pass
+
+ editorTemplate = EditorTemplate()
+ win32ui.GetApp().AddDocTemplate(editorTemplate)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/frame.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/frame.py
new file mode 100644
index 0000000000000000000000000000000000000000..79ce66d8a37b764cbb18dbe5274eee4ac9e32385
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/frame.py
@@ -0,0 +1,74 @@
+# frame.py - The MDI frame window for an editor.
+import pywin.framework.window
+import win32con
+import win32ui
+
+from . import ModuleBrowser
+
+
+class EditorFrame(pywin.framework.window.MDIChildWnd):
+ def OnCreateClient(self, cp, context):
+ # Create the default view as specified by the template (ie, the editor view)
+ view = context.template.MakeView(context.doc)
+ # Create the browser view.
+ browserView = ModuleBrowser.BrowserView(context.doc)
+ view2 = context.template.MakeView(context.doc)
+
+ splitter = win32ui.CreateSplitter()
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE
+ splitter.CreateStatic(self, 1, 2, style, win32ui.AFX_IDW_PANE_FIRST)
+ sub_splitter = self.sub_splitter = win32ui.CreateSplitter()
+ sub_splitter.CreateStatic(splitter, 2, 1, style, win32ui.AFX_IDW_PANE_FIRST + 1)
+
+ # Note we must add the default view first, so that doc.GetFirstView() returns the editor view.
+ sub_splitter.CreateView(view, 1, 0, (0, 0))
+ splitter.CreateView(browserView, 0, 0, (0, 0))
+ sub_splitter.CreateView(view2, 0, 0, (0, 0))
+
+ # print("First view is", context.doc.GetFirstView())
+ # print("Views are", view, view2, browserView)
+ # print("Parents are", view.GetParent(), view2.GetParent(), browserView.GetParent())
+ # print("Splitter is", splitter)
+ # print("sub splitter is", sub_splitter)
+ # Old
+ # splitter.CreateStatic (self, 1, 2)
+ # splitter.CreateView(view, 0, 1, (0,0)) # size ignored.
+ # splitter.CreateView (browserView, 0, 0, (0, 0))
+
+ # Restrict the size of the browser splitter (and we can avoid filling
+ # it until it is shown)
+ splitter.SetColumnInfo(0, 10, 20)
+ # And the active view is our default view (so it gets initial focus)
+ self.SetActiveView(view)
+
+ def GetEditorView(self):
+ # In a multi-view (eg, splitter) environment, get
+ # an editor (ie, scintilla) view
+ # Look for the splitter opened the most!
+ if self.sub_splitter is None:
+ return self.GetDlgItem(win32ui.AFX_IDW_PANE_FIRST)
+ v1 = self.sub_splitter.GetPane(0, 0)
+ v2 = self.sub_splitter.GetPane(1, 0)
+ r1 = v1.GetWindowRect()
+ r2 = v2.GetWindowRect()
+ if r1[3] - r1[1] > r2[3] - r2[1]:
+ return v1
+ return v2
+
+ def GetBrowserView(self):
+ # XXX - should fix this :-)
+ return self.GetActiveDocument().GetAllViews()[1]
+
+ def OnClose(self):
+ doc = self.GetActiveDocument()
+ if not doc.SaveModified():
+ # Cancel button selected from Save dialog, do not actually close
+ # print("close cancelled")
+ return 0
+ ## So the 'Save' dialog doesn't come up twice
+ doc._obj_.SetModifiedFlag(False)
+
+ # Must force the module browser to close itself here (OnDestroy for the view itself is too late!)
+ self.sub_splitter = None # ensure no circles!
+ self.GetBrowserView().DestroyBrowser()
+ return self._obj_.OnClose()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/template.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/template.py
new file mode 100644
index 0000000000000000000000000000000000000000..5307caa6b539575bff2a1f2957a544ce4acacbc7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/template.py
@@ -0,0 +1,59 @@
+import os
+
+import win32api
+import win32ui
+from pywin.mfc import docview
+
+from . import frame
+
+ParentEditorTemplate = docview.DocTemplate
+
+
+class EditorTemplateBase(ParentEditorTemplate):
+ def __init__(
+ self, res=win32ui.IDR_TEXTTYPE, makeDoc=None, makeFrame=None, makeView=None
+ ):
+ if makeFrame is None:
+ makeFrame = frame.EditorFrame
+ ParentEditorTemplate.__init__(self, res, makeDoc, makeFrame, makeView)
+
+ def _CreateDocTemplate(self, resourceId):
+ raise NotImplementedError("You must override this")
+
+ def CreateWin32uiDocument(self):
+ raise NotImplementedError("You must override this")
+
+ def GetFileExtensions(self):
+ return ".txt", ".py"
+
+ def MatchDocType(self, fileName, fileType):
+ doc = self.FindOpenDocument(fileName)
+ if doc:
+ return doc
+ ext = os.path.splitext(fileName)[1].lower()
+ if ext in self.GetFileExtensions():
+ return win32ui.CDocTemplate_Confidence_yesAttemptNative
+ return win32ui.CDocTemplate_Confidence_maybeAttemptForeign
+
+ def InitialUpdateFrame(self, frame, doc, makeVisible=1):
+ self._obj_.InitialUpdateFrame(frame, doc, makeVisible) # call default handler.
+ doc._UpdateUIForState()
+
+ def GetPythonPropertyPages(self):
+ """Returns a list of property pages"""
+ from . import configui
+
+ return [configui.EditorPropertyPage(), configui.EditorWhitespacePropertyPage()]
+
+ def OpenDocumentFile(self, filename, bMakeVisible=1):
+ if filename is not None:
+ try:
+ path = os.path.split(filename)[0]
+ # print("The editor is translating", "filename", "to")
+ filename = win32api.FindFiles(filename)[0][8]
+ filename = os.path.join(path, filename)
+ # print("filename")
+ except (win32api.error, IndexError) as details:
+ # print("Couldn't get the full filename!", details)
+ pass
+ return self._obj_.OpenDocumentFile(filename, bMakeVisible)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/vss.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/vss.py
new file mode 100644
index 0000000000000000000000000000000000000000..726f546e5b95c91fe74d9649b559a8b68830c134
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/editor/vss.py
@@ -0,0 +1,104 @@
+# vss.py -- Source Control using Microsoft VSS.
+
+# Provides routines for checking files out of VSS.
+#
+# Uses an INI file very similar to how VB integrates with VSS - even
+# as far as using the same name.
+
+# The file must be named "Mssccprj.scc", and be in the format of
+# an INI file. This file may be in a parent directory, in which
+# case the project name will be built from what is specified in the
+# ini file, plus the path from the INI file to the file itself.
+#
+# The INI file should have a [Python] section, and a
+# Project=Project Name
+# and optionally
+# Database=??
+
+
+import os
+import sys
+import traceback
+
+import win32api
+import win32ui
+
+g_iniName = "Mssccprj.scc" # Use the same INI name as VB!
+
+g_sourceSafe = None
+
+
+def FindVssProjectInfo(fullfname):
+ """Looks up the file system for an INI file describing the project.
+
+ Looking up the tree is for ni style packages.
+
+ Returns (projectName, pathToFileName) where pathToFileName contains
+ the path from the ini file to the actual file.
+ """
+ path, fnameonly = os.path.split(fullfname)
+ origPath = path
+ project = ""
+ retPaths = [fnameonly]
+ while not project:
+ iniName = os.path.join(path, g_iniName)
+ database = win32api.GetProfileVal("Python", "Database", "", iniName)
+ project = win32api.GetProfileVal("Python", "Project", "", iniName)
+ if project:
+ break
+ # No valid INI file in this directory - look up a level.
+ path, addpath = os.path.split(path)
+ if not addpath: # Root?
+ break
+ retPaths.insert(0, addpath)
+ if not project:
+ win32ui.MessageBox(
+ "%s\r\n\r\nThis directory is not configured for Python/VSS" % origPath
+ )
+ return
+ return project, "/".join(retPaths), database
+
+
+def CheckoutFile(fileName):
+ global g_sourceSafe
+ import pythoncom
+
+ ok = 0
+ # Assumes the fileName has a complete path,
+ # and that the INI file can be found in that path
+ # (or a parent path if a ni style package)
+ try:
+ import win32com.client
+ import win32com.client.gencache
+
+ mod = win32com.client.gencache.EnsureModule(
+ "{783CD4E0-9D54-11CF-B8EE-00608CC9A71F}", 0, 5, 0
+ )
+ if mod is None:
+ win32ui.MessageBox(
+ "VSS does not appear to be installed. The TypeInfo can not be created"
+ )
+ return ok
+
+ rc = FindVssProjectInfo(fileName)
+ if rc is None:
+ return
+ project, vssFname, database = rc
+ if g_sourceSafe is None:
+ g_sourceSafe = win32com.client.Dispatch("SourceSafe")
+ # SS seems a bit weird. It defaults the arguments as empty strings, but
+ # then complains when they are used - so we pass "Missing"
+ if not database:
+ database = pythoncom.Missing
+ g_sourceSafe.Open(database, pythoncom.Missing, pythoncom.Missing)
+ item = g_sourceSafe.VSSItem(f"$/{project}/{vssFname}")
+ item.Checkout(None, fileName)
+ ok = 1
+ except pythoncom.com_error as exc:
+ win32ui.MessageBox(exc.strerror, "Error checking out file")
+ except:
+ typ, val, tb = sys.exc_info()
+ traceback.print_exc()
+ win32ui.MessageBox(f"{typ} - {val}", "Error checking out file")
+ tb = None # Cleanup a cycle
+ return ok
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/help.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/help.py
new file mode 100644
index 0000000000000000000000000000000000000000..e97eef3ddd529b7737db751b140eb3f98ac0cc09
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/help.py
@@ -0,0 +1,173 @@
+# help.py - help utilities for PythonWin.
+import os
+
+import regutil
+import win32api
+import win32con
+import win32ui
+
+htmlhelp_handle = None
+
+html_help_command_translators = {
+ win32con.HELP_CONTENTS: 1, # HH_DISPLAY_TOC
+ win32con.HELP_CONTEXT: 15, # HH_HELP_CONTEXT
+ win32con.HELP_FINDER: 1, # HH_DISPLAY_TOC
+}
+
+
+def FinalizeHelp():
+ global htmlhelp_handle
+ if htmlhelp_handle is not None:
+ import win32help
+
+ try:
+ # frame = win32ui.GetMainFrame().GetSafeHwnd()
+ frame = 0
+ win32help.HtmlHelp(frame, None, win32help.HH_UNINITIALIZE, htmlhelp_handle)
+ except win32help.error:
+ print("Failed to finalize htmlhelp!")
+ htmlhelp_handle = None
+
+
+def OpenHelpFile(fileName, helpCmd=None, helpArg=None):
+ "Open a help file, given a full path"
+ # default help arg.
+ win32ui.DoWaitCursor(1)
+ try:
+ if helpCmd is None:
+ helpCmd = win32con.HELP_CONTENTS
+ ext = os.path.splitext(fileName)[1].lower()
+ if ext == ".hlp":
+ win32api.WinHelp(
+ win32ui.GetMainFrame().GetSafeHwnd(), fileName, helpCmd, helpArg
+ )
+ # XXX - using the htmlhelp API wreaks havoc with keyboard shortcuts
+ # so we disable it, forcing ShellExecute, which works fine (but
+ # doesn't close the help file when Pythonwin is closed.
+ # Tom Heller also points out
+ # https://web.archive.org/web/20070519165457/http://www.microsoft.com:80/mind/0499/faq/faq0499.asp ,
+ # which may or may not be related.
+ elif 0 and ext == ".chm":
+ import win32help
+
+ global htmlhelp_handle
+ helpCmd = html_help_command_translators.get(helpCmd, helpCmd)
+ # frame = win32ui.GetMainFrame().GetSafeHwnd()
+ frame = 0 # Don't want it overlapping ours!
+ if htmlhelp_handle is None:
+ htmlhelp_hwnd, htmlhelp_handle = win32help.HtmlHelp(
+ frame, None, win32help.HH_INITIALIZE
+ )
+ win32help.HtmlHelp(frame, fileName, helpCmd, helpArg)
+ else:
+ # Hope that the extension is registered, and we know what to do!
+ win32api.ShellExecute(0, "open", fileName, None, "", win32con.SW_SHOW)
+ return fileName
+ finally:
+ win32ui.DoWaitCursor(-1)
+
+
+def ListAllHelpFiles():
+ ret = []
+ ret = _ListAllHelpFilesInRoot(win32con.HKEY_LOCAL_MACHINE)
+ # Ensure we don't get dups.
+ for item in _ListAllHelpFilesInRoot(win32con.HKEY_CURRENT_USER):
+ if item not in ret:
+ ret.append(item)
+ return ret
+
+
+def _ListAllHelpFilesInRoot(root):
+ """Returns a list of (helpDesc, helpFname) for all registered help files"""
+
+ retList = []
+ try:
+ key = win32api.RegOpenKey(
+ root, regutil.BuildDefaultPythonKey() + "\\Help", 0, win32con.KEY_READ
+ )
+ except win32api.error as exc:
+ import winerror
+
+ if exc.winerror != winerror.ERROR_FILE_NOT_FOUND:
+ raise
+ return retList
+ try:
+ keyNo = 0
+ while 1:
+ try:
+ helpDesc = win32api.RegEnumKey(key, keyNo)
+ helpFile = win32api.RegQueryValue(key, helpDesc)
+ retList.append((helpDesc, helpFile))
+ keyNo += 1
+ except win32api.error as exc:
+ import winerror
+
+ if exc.winerror != winerror.ERROR_NO_MORE_ITEMS:
+ raise
+ break
+ finally:
+ win32api.RegCloseKey(key)
+ return retList
+
+
+def SelectAndRunHelpFile():
+ from pywin.dialogs import list
+
+ helpFiles = ListAllHelpFiles()
+ if len(helpFiles) == 1:
+ # only 1 help file registered - probably ours - no point asking
+ index = 0
+ else:
+ index = list.SelectFromLists("Select Help file", helpFiles, ["Title"])
+ if index is not None:
+ OpenHelpFile(helpFiles[index][1])
+
+
+helpIDMap = None
+
+
+def SetHelpMenuOtherHelp(mainMenu):
+ """Modifies the main Help Menu to handle all registered help files.
+ mainMenu -- The main menu to modify - usually from docTemplate.GetSharedMenu()
+ """
+
+ # Load all help files from the registry.
+ global helpIDMap
+ if helpIDMap is None:
+ helpIDMap = {}
+ cmdID = win32ui.ID_HELP_OTHER
+ excludeList = ["Main Python Documentation", "Pythonwin Reference"]
+ firstList = ListAllHelpFiles()
+ # We actually want to not only exclude these entries, but
+ # their help file names (as many entries may share the same name)
+ excludeFnames = []
+ for desc, fname in firstList:
+ if desc in excludeList:
+ excludeFnames.append(fname)
+
+ helpDescs = []
+ for desc, fname in firstList:
+ if fname not in excludeFnames:
+ helpIDMap[cmdID] = (desc, fname)
+ win32ui.GetMainFrame().HookCommand(HandleHelpOtherCommand, cmdID)
+ cmdID += 1
+
+ helpMenu = mainMenu.GetSubMenu(
+ mainMenu.GetMenuItemCount() - 1
+ ) # Help menu always last.
+ otherHelpMenuPos = 2 # can't search for ID, as sub-menu has no ID.
+ otherMenu = helpMenu.GetSubMenu(otherHelpMenuPos)
+ while otherMenu.GetMenuItemCount():
+ otherMenu.DeleteMenu(0, win32con.MF_BYPOSITION)
+
+ if helpIDMap:
+ for id, (desc, fname) in helpIDMap.items():
+ otherMenu.AppendMenu(win32con.MF_ENABLED | win32con.MF_STRING, id, desc)
+ else:
+ helpMenu.EnableMenuItem(
+ otherHelpMenuPos, win32con.MF_BYPOSITION | win32con.MF_GRAYED
+ )
+
+
+def HandleHelpOtherCommand(cmd, code):
+ OpenHelpFile(helpIDMap[cmd][1])
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/interact.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/interact.py
new file mode 100644
index 0000000000000000000000000000000000000000..c536b47f0564ace752ace38eddac4648f70131bf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/interact.py
@@ -0,0 +1,995 @@
+##################################################################
+##
+## Interactive Shell Window
+##
+
+import array
+import code
+import os
+import string
+import sys
+import traceback
+
+import __main__
+import pywin.framework.app
+import pywin.scintilla.control
+import pywin.scintilla.formatter
+import pywin.scintilla.IDLEenvironment # nopycln: import # Injects fast_readline into the IDLE auto-indent extension
+import win32api
+import win32clipboard
+import win32con
+import win32ui
+from pywin.mfc import afxres
+
+## sequential after ID_GOTO_LINE defined in editor.py
+ID_EDIT_COPY_CODE = 0xE2002
+ID_EDIT_EXEC_CLIPBOARD = 0x2003
+
+trace = pywin.scintilla.formatter.trace
+
+import re
+
+from . import winout
+
+# from IDLE.
+_is_block_opener = re.compile(r":\s*(#.*)?$").search
+_is_block_closer = re.compile(
+ r"""
+ \s*
+ ( return
+ | break
+ | continue
+ | raise
+ | pass
+ )
+ \b
+""",
+ re.VERBOSE,
+).match
+
+tracebackHeader = b"Traceback ("
+
+sectionProfile = "Interactive Window"
+valueFormatTitle = "FormatTitle"
+valueFormatInput = "FormatInput"
+valueFormatOutput = "FormatOutput"
+valueFormatOutputError = "FormatOutputError"
+
+# These are defaults only. Values are read from the registry.
+formatTitle = (-536870897, 0, 220, 0, 16711680, 184, 34, "Arial")
+formatInput = (-402653169, 0, 200, 0, 0, 0, 49, "Courier New")
+formatOutput = (-402653169, 0, 200, 0, 8421376, 0, 49, "Courier New")
+formatOutputError = (-402653169, 0, 200, 0, 255, 0, 49, "Courier New")
+
+try:
+ sys.ps1
+except AttributeError:
+ sys.ps1 = ">>> "
+ sys.ps2 = "... "
+
+
+def LoadPreference(preference, default=""):
+ return win32ui.GetProfileVal(sectionProfile, preference, default)
+
+
+def SavePreference(prefName, prefValue):
+ win32ui.WriteProfileVal(sectionProfile, prefName, prefValue)
+
+
+def SaveFontPreferences():
+ win32ui.WriteProfileVal(sectionProfile, valueFormatTitle, str(formatTitle))
+ win32ui.WriteProfileVal(sectionProfile, valueFormatInput, str(formatInput))
+ win32ui.WriteProfileVal(sectionProfile, valueFormatOutput, str(formatOutput))
+ win32ui.WriteProfileVal(
+ sectionProfile, valueFormatOutputError, str(formatOutputError)
+ )
+
+
+def GetPromptPrefix(line):
+ ps1 = sys.ps1
+ if line[: len(ps1)] == ps1:
+ return ps1
+ ps2 = sys.ps2
+ if line[: len(ps2)] == ps2:
+ return ps2
+
+
+#############################################################
+#
+# Colorizer related code.
+#
+#############################################################
+STYLE_INTERACTIVE_EOL = "Interactive EOL"
+STYLE_INTERACTIVE_OUTPUT = "Interactive Output"
+STYLE_INTERACTIVE_PROMPT = "Interactive Prompt"
+STYLE_INTERACTIVE_BANNER = "Interactive Banner"
+STYLE_INTERACTIVE_ERROR = "Interactive Error"
+STYLE_INTERACTIVE_ERROR_FINALLINE = "Interactive Error (final line)"
+
+INTERACTIVE_STYLES = [
+ STYLE_INTERACTIVE_EOL,
+ STYLE_INTERACTIVE_OUTPUT,
+ STYLE_INTERACTIVE_PROMPT,
+ STYLE_INTERACTIVE_BANNER,
+ STYLE_INTERACTIVE_ERROR,
+ STYLE_INTERACTIVE_ERROR_FINALLINE,
+]
+
+FormatterParent = pywin.scintilla.formatter.PythonSourceFormatter
+
+
+class InteractiveFormatter(FormatterParent):
+ def __init__(self, scintilla):
+ FormatterParent.__init__(self, scintilla)
+ self.bannerDisplayed = False
+
+ def SetStyles(self):
+ FormatterParent.SetStyles(self)
+ Style = pywin.scintilla.formatter.Style
+ self.RegisterStyle(Style(STYLE_INTERACTIVE_EOL, STYLE_INTERACTIVE_PROMPT))
+ self.RegisterStyle(Style(STYLE_INTERACTIVE_PROMPT, formatInput))
+ self.RegisterStyle(Style(STYLE_INTERACTIVE_OUTPUT, formatOutput))
+ self.RegisterStyle(Style(STYLE_INTERACTIVE_BANNER, formatTitle))
+ self.RegisterStyle(Style(STYLE_INTERACTIVE_ERROR, formatOutputError))
+ self.RegisterStyle(
+ Style(STYLE_INTERACTIVE_ERROR_FINALLINE, STYLE_INTERACTIVE_ERROR)
+ )
+
+ def LoadPreference(self, name, default):
+ rc = win32ui.GetProfileVal("Format", name, default)
+ if rc == default:
+ rc = win32ui.GetProfileVal(sectionProfile, name, default)
+ return rc
+
+ def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart):
+ lengthDoc = len(cdoc)
+ if lengthDoc == 0:
+ return
+ state = styleStart
+ # As per comments in Colorize(), we work with the raw utf8
+ # bytes. To avoid too much pain, we treat each utf8 byte
+ # as a latin-1 unicode character - we only use it to compare
+ # against ascii chars anyway...
+ chNext = cdoc[0:1].decode("latin-1")
+ startSeg = 0
+ i = 0
+ lastState = state # debug only
+ while i < lengthDoc:
+ ch = chNext
+ chNext = cdoc[i + 1 : i + 2].decode("latin-1")
+
+ # trace("ch=%r, i=%d, next=%r, state=%s" % (ch, i, chNext, state))
+ if state == STYLE_INTERACTIVE_EOL:
+ if ch not in "\r\n":
+ self.ColorSeg(startSeg, i - 1, state)
+ startSeg = i
+ if ch in (str(sys.ps1)[0], str(sys.ps2)[0]):
+ state = STYLE_INTERACTIVE_PROMPT
+ elif cdoc[i : i + len(tracebackHeader)] == tracebackHeader:
+ state = STYLE_INTERACTIVE_ERROR
+ else:
+ state = STYLE_INTERACTIVE_OUTPUT
+ elif state == STYLE_INTERACTIVE_PROMPT:
+ if ch not in sys.ps1 + sys.ps2 + " ":
+ self.ColorSeg(startSeg, i - 1, state)
+ startSeg = i
+ if ch in "\r\n":
+ state = STYLE_INTERACTIVE_EOL
+ else:
+ state = stylePyStart # Start coloring Python code.
+ elif state in (STYLE_INTERACTIVE_OUTPUT,):
+ if ch in "\r\n":
+ self.ColorSeg(startSeg, i - 1, state)
+ startSeg = i
+ state = STYLE_INTERACTIVE_EOL
+ elif state == STYLE_INTERACTIVE_ERROR:
+ if ch in "\r\n" and chNext and chNext not in string.whitespace:
+ # Everything including me
+ self.ColorSeg(startSeg, i, state)
+ startSeg = i + 1
+ state = STYLE_INTERACTIVE_ERROR_FINALLINE
+ elif i == 0 and ch not in string.whitespace:
+ # If we are coloring from the start of a line,
+ # we need this better check for the last line
+ # Color up to not including me
+ self.ColorSeg(startSeg, i - 1, state)
+ startSeg = i
+ state = STYLE_INTERACTIVE_ERROR_FINALLINE
+ elif state == STYLE_INTERACTIVE_ERROR_FINALLINE:
+ if ch in "\r\n":
+ self.ColorSeg(startSeg, i - 1, state)
+ startSeg = i
+ state = STYLE_INTERACTIVE_EOL
+ elif state == STYLE_INTERACTIVE_BANNER:
+ if ch in "\r\n" and (chNext == "" or chNext in ">["):
+ # Everything including me
+ self.ColorSeg(startSeg, i - 1, state)
+ startSeg = i
+ state = STYLE_INTERACTIVE_EOL
+ else:
+ # It is a PythonColorizer state - seek past the end of the line
+ # and ask the Python colorizer to color that.
+ end = startSeg
+ while end < lengthDoc and cdoc[end] not in b"\r\n":
+ end += 1
+ self.ColorizePythonCode(cdoc[:end], startSeg, state)
+ stylePyStart = self.GetStringStyle(end - 1)
+ if stylePyStart is None:
+ stylePyStart = pywin.scintilla.formatter.STYLE_DEFAULT
+ else:
+ stylePyStart = stylePyStart.name
+ startSeg = end
+ i = end - 1 # ready for increment.
+ chNext = cdoc[end : end + 1].decode("latin-1")
+ state = STYLE_INTERACTIVE_EOL
+ if lastState != state:
+ lastState = state
+ i += 1
+ # and the rest
+ if startSeg < i:
+ self.ColorSeg(startSeg, i - 1, state)
+
+ def Colorize(self, start=0, end=-1):
+ # scintilla's formatting is all done in terms of utf, so
+ # we work with utf8 bytes instead of unicode. This magically
+ # works as any extended chars found in the utf8 don't change
+ # the semantics.
+ stringVal = self.scintilla.GetTextRange(start, end, decode=False)
+ styleStart = None
+ stylePyStart = None
+ if start > 1:
+ # Likely we are being asked to color from the start of the line.
+ # We find the last formatted character on the previous line.
+ # If TQString, we continue it. Otherwise, we reset.
+ look = start - 1
+ while look and self.scintilla.SCIGetCharAt(look) in "\n\r":
+ look -= 1
+ if look and look < start - 1: # Did we find a char before the \n\r sets?
+ strstyle = self.GetStringStyle(look)
+ quote_char = None
+ if strstyle is not None:
+ if strstyle.name == pywin.scintilla.formatter.STYLE_TQSSTRING:
+ quote_char = "'"
+ elif strstyle.name == pywin.scintilla.formatter.STYLE_TQDSTRING:
+ quote_char = '"'
+ if quote_char is not None:
+ # It is a TQS. If the TQS is not terminated, we
+ # carry the style through.
+ if look > 2:
+ look_str = (
+ self.scintilla.SCIGetCharAt(look - 2)
+ + self.scintilla.SCIGetCharAt(look - 1)
+ + self.scintilla.SCIGetCharAt(look)
+ )
+ if look_str != quote_char * 3:
+ stylePyStart = strstyle.name
+ if stylePyStart is None:
+ stylePyStart = pywin.scintilla.formatter.STYLE_DEFAULT
+
+ if start > 0:
+ stylenum = self.scintilla.SCIGetStyleAt(start - 1)
+ styleStart = self.GetStyleByNum(stylenum).name
+ elif self.bannerDisplayed:
+ styleStart = STYLE_INTERACTIVE_EOL
+ else:
+ styleStart = STYLE_INTERACTIVE_BANNER
+ self.bannerDisplayed = True
+ self.scintilla.SCIStartStyling(start, 31)
+ self.style_buffer = array.array("b", (0,) * len(stringVal))
+ self.ColorizeInteractiveCode(stringVal, styleStart, stylePyStart)
+ self.scintilla.SCISetStylingEx(self.style_buffer)
+ self.style_buffer = None
+
+
+###############################################################
+#
+# This class handles the Python interactive interpreter.
+#
+# It uses a basic EditWindow, and does all the magic.
+# This is triggered by the enter key hander attached by the
+# start-up code. It determines if a command is to be executed
+# or continued (ie, emit "... ") by snooping around the current
+# line, looking for the prompts
+#
+class PythonwinInteractiveInterpreter(code.InteractiveInterpreter):
+ def __init__(self, locals=None, globals=None):
+ if locals is None:
+ locals = __main__.__dict__
+ if globals is None:
+ globals = locals
+ self.globals = globals
+ code.InteractiveInterpreter.__init__(self, locals)
+
+ def showsyntaxerror(self, filename=None, **kwargs):
+ sys.stderr.write(
+ tracebackHeader.decode("ascii")
+ ) # So the color syntaxer recognises it.
+ code.InteractiveInterpreter.showsyntaxerror(self, filename)
+
+ def runcode(self, code):
+ try:
+ exec(code, self.globals, self.locals)
+ except SystemExit:
+ raise
+ except:
+ self.showtraceback()
+
+
+class InteractiveCore:
+ def __init__(self, banner=None):
+ self.banner = banner
+
+ # LoadFontPreferences()
+ def Init(self):
+ self.oldStdOut = self.oldStdErr = None
+
+ # self.SetWordWrap(win32ui.CRichEditView_WrapNone)
+ self.interp = PythonwinInteractiveInterpreter()
+
+ self.OutputGrab() # Release at cleanup.
+
+ if self.GetTextLength() == 0:
+ if self.banner is None:
+ suffix = ""
+ if win32ui.debug:
+ suffix = ", debug build"
+ sys.stderr.write(
+ f"PythonWin {sys.version} on {sys.platform}{suffix}.\n"
+ )
+ sys.stderr.write(
+ "Portions {} - see 'Help/About PythonWin' for further copyright information.\n".format(
+ win32ui.copyright
+ )
+ )
+ else:
+ sys.stderr.write(self.banner)
+ rcfile = os.environ.get("PYTHONSTARTUP")
+ if rcfile:
+ import __main__
+
+ try:
+ exec(
+ compile(
+ open(rcfile, "rb").read(), rcfile, "exec", dont_inherit=True
+ ),
+ __main__.__dict__,
+ __main__.__dict__,
+ )
+ except:
+ sys.stderr.write(
+ ">>> \nError executing PYTHONSTARTUP script %r\n" % (rcfile)
+ )
+ traceback.print_exc(file=sys.stderr)
+ self.AppendToPrompt([])
+
+ def SetContext(self, globals, locals, name="Dbg"):
+ oldPrompt = sys.ps1
+ if globals is None:
+ # Reset
+ sys.ps1 = ">>> "
+ sys.ps2 = "... "
+ locals = globals = __main__.__dict__
+ else:
+ sys.ps1 = "[%s]>>> " % name
+ sys.ps2 = "[%s]... " % name
+ self.interp.locals = locals
+ self.interp.globals = globals
+ self.AppendToPrompt([], oldPrompt)
+
+ def GetContext(self):
+ return self.interp.globals, self.interp.locals
+
+ def DoGetLine(self, line=-1):
+ if line == -1:
+ line = self.LineFromChar()
+ line = self.GetLine(line)
+ while line and line[-1] in ("\r", "\n"):
+ line = line[:-1]
+ return line
+
+ def AppendToPrompt(self, bufLines, oldPrompt=None):
+ "Take a command and stick it at the end of the buffer (with python prompts inserted if required)."
+ self.flush()
+ lastLineNo = self.GetLineCount() - 1
+ line = self.DoGetLine(lastLineNo)
+ if oldPrompt and line == oldPrompt:
+ self.SetSel(self.GetTextLength() - len(oldPrompt), self.GetTextLength())
+ self.ReplaceSel(sys.ps1)
+ elif line != str(sys.ps1):
+ if len(line) != 0:
+ self.write("\n")
+ self.write(sys.ps1)
+ self.flush()
+ self.idle.text.mark_set("iomark", "end-1c")
+ if not bufLines:
+ return
+ terms = (["\n" + sys.ps2] * (len(bufLines) - 1)) + [""]
+ for bufLine, term in zip(bufLines, terms):
+ if bufLine.strip():
+ self.write(bufLine + term)
+ self.flush()
+
+ def EnsureNoPrompt(self):
+ # Get ready to write some text NOT at a Python prompt.
+ self.flush()
+ lastLineNo = self.GetLineCount() - 1
+ line = self.DoGetLine(lastLineNo)
+ if not line or line in (sys.ps1, sys.ps2):
+ self.SetSel(self.GetTextLength() - len(line), self.GetTextLength())
+ self.ReplaceSel("")
+ else:
+ # Just add a new line.
+ self.write("\n")
+
+ def _GetSubConfigNames(self):
+ return ["interactive"] # Allow [Keys:Interactive] sections to be specific
+
+ def HookHandlers(self):
+ # Hook menu command (executed when a menu item with that ID is selected from a menu/toolbar
+ self.HookCommand(self.OnSelectBlock, win32ui.ID_EDIT_SELECT_BLOCK)
+ self.HookCommand(self.OnEditCopyCode, ID_EDIT_COPY_CODE)
+ self.HookCommand(self.OnEditExecClipboard, ID_EDIT_EXEC_CLIPBOARD)
+ mod = pywin.scintilla.IDLEenvironment.GetIDLEModule("IdleHistory")
+ if mod is not None:
+ self.history = mod.History(self.idle.text, "\n" + sys.ps2)
+ else:
+ self.history = None
+ # hack for now for event handling.
+
+ # GetBlockBoundary takes a line number, and will return the
+ # start and and line numbers of the block, and a flag indicating if the
+ # block is a Python code block.
+ # If the line specified has a Python prompt, then the lines are parsed
+ # backwards and forwards, and the flag is true.
+ # If the line does not start with a prompt, the block is searched forward
+ # and backward until a prompt _is_ found, and all lines in between without
+ # prompts are returned, and the flag is false.
+ def GetBlockBoundary(self, lineNo):
+ line = self.DoGetLine(lineNo)
+ maxLineNo = self.GetLineCount() - 1
+ prefix = GetPromptPrefix(line)
+ if prefix is None: # Non code block
+ flag = 0
+ startLineNo = lineNo
+ while startLineNo > 0:
+ if GetPromptPrefix(self.DoGetLine(startLineNo - 1)) is not None:
+ break # there _is_ a prompt
+ startLineNo -= 1
+ endLineNo = lineNo
+ while endLineNo < maxLineNo:
+ if GetPromptPrefix(self.DoGetLine(endLineNo + 1)) is not None:
+ break # there _is_ a prompt
+ endLineNo += 1
+ else: # Code block
+ flag = 1
+ startLineNo = lineNo
+ while startLineNo > 0 and prefix != str(sys.ps1):
+ prefix = GetPromptPrefix(self.DoGetLine(startLineNo - 1))
+ if prefix is None:
+ break
+ # there is no prompt.
+ startLineNo -= 1
+ endLineNo = lineNo
+ while endLineNo < maxLineNo:
+ prefix = GetPromptPrefix(self.DoGetLine(endLineNo + 1))
+ if prefix is None:
+ break # there is no prompt
+ if prefix == str(sys.ps1):
+ break # this is another command
+ endLineNo += 1
+ # continue until end of buffer, or no prompt
+ return (startLineNo, endLineNo, flag)
+
+ def ExtractCommand(self, lines):
+ start, end = lines
+ retList = []
+ while end >= start:
+ thisLine = self.DoGetLine(end)
+ promptLen = len(GetPromptPrefix(thisLine))
+ retList = [thisLine[promptLen:]] + retList
+ end -= 1
+ return retList
+
+ def OutputGrab(self):
+ # import win32traceutil; return
+ self.oldStdOut = sys.stdout
+ self.oldStdErr = sys.stderr
+ sys.stdout = self
+ sys.stderr = self
+ self.flush()
+
+ def OutputRelease(self):
+ # a command may have overwritten these - only restore if not.
+ if self.oldStdOut is not None:
+ if sys.stdout == self:
+ sys.stdout = self.oldStdOut
+ if self.oldStdErr is not None:
+ if sys.stderr == self:
+ sys.stderr = self.oldStdErr
+ self.oldStdOut = None
+ self.oldStdErr = None
+ self.flush()
+
+ ###################################
+ #
+ # Message/Command/Key Hooks.
+ #
+ # Enter key handler
+ #
+ def ProcessEnterEvent(self, event):
+ # If autocompletion has been triggered, complete and do not process event
+ if self.SCIAutoCActive():
+ self.SCIAutoCComplete()
+ self.SCICancel()
+ return
+
+ self.SCICancel()
+ # First, check for an error message
+ haveGrabbedOutput = 0
+ if self.HandleSpecialLine():
+ return 0
+
+ lineNo = self.LineFromChar()
+ start, end, isCode = self.GetBlockBoundary(lineNo)
+ # If we are not in a code block just go to the prompt (or create a new one)
+ if not isCode:
+ self.AppendToPrompt([])
+ win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
+ return
+
+ lines = self.ExtractCommand((start, end))
+
+ # If we are in a code-block, but it isn't at the end of the buffer
+ # then copy it to the end ready for editing and subsequent execution
+ if end != self.GetLineCount() - 1:
+ win32ui.SetStatusText("Press ENTER to execute command")
+ self.AppendToPrompt(lines)
+ self.SetSel(-2)
+ return
+
+ # If SHIFT held down, we want new code here and now!
+ bNeedIndent = (
+ win32api.GetKeyState(win32con.VK_SHIFT) < 0
+ or win32api.GetKeyState(win32con.VK_CONTROL) < 0
+ )
+ if bNeedIndent:
+ self.ReplaceSel("\n")
+ else:
+ self.SetSel(-2)
+ self.ReplaceSel("\n")
+ source = "\n".join(lines)
+ while source and source[-1] in "\t ":
+ source = source[:-1]
+ self.OutputGrab() # grab the output for the command exec.
+ try:
+ if self.interp.runsource(
+ source, ""
+ ): # Need more input!
+ bNeedIndent = 1
+ else:
+ # If the last line isn't empty, append a newline
+ if self.history is not None:
+ self.history.history_store(source)
+ self.AppendToPrompt([])
+ win32ui.SetStatusText(
+ win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)
+ )
+ # win32ui.SetStatusText('Successfully executed statement')
+ finally:
+ self.OutputRelease()
+ if bNeedIndent:
+ win32ui.SetStatusText("Ready to continue the command")
+ # Now attempt correct indentation (should use IDLE?)
+ curLine = self.DoGetLine(lineNo)[len(sys.ps2) :]
+ pos = 0
+ indent = ""
+ while len(curLine) > pos and curLine[pos] in string.whitespace:
+ indent += curLine[pos]
+ pos += 1
+ if _is_block_opener(curLine):
+ indent += "\t"
+ elif _is_block_closer(curLine):
+ indent = indent[:-1]
+ # use ReplaceSel to ensure it goes at the cursor rather than end of buffer.
+ self.ReplaceSel(sys.ps2 + indent)
+ return 0
+
+ # ESC key handler
+ def ProcessEscEvent(self, event):
+ # Implement a cancel.
+ if self.SCIAutoCActive() or self.SCICallTipActive():
+ self.SCICancel()
+ else:
+ win32ui.SetStatusText("Cancelled.")
+ self.AppendToPrompt(("",))
+ return 0
+
+ def OnSelectBlock(self, command, code):
+ lineNo = self.LineFromChar()
+ start, end, isCode = self.GetBlockBoundary(lineNo)
+ startIndex = self.LineIndex(start)
+ endIndex = self.LineIndex(end + 1) - 2 # skip \r + \n
+ if endIndex < 0: # must be beyond end of buffer
+ endIndex = -2 # self.Length()
+ self.SetSel(startIndex, endIndex)
+
+ def OnEditCopyCode(self, command, code):
+ """Sanitizes code from interactive window, removing prompts and output,
+ and inserts it in the clipboard."""
+ code = self.GetSelText()
+ lines = code.splitlines()
+ out_lines = []
+ for line in lines:
+ if line.startswith(sys.ps1):
+ line = line[len(sys.ps1) :]
+ out_lines.append(line)
+ elif line.startswith(sys.ps2):
+ line = line[len(sys.ps2) :]
+ out_lines.append(line)
+ out_code = os.linesep.join(out_lines)
+ win32clipboard.OpenClipboard()
+ try:
+ win32clipboard.SetClipboardData(
+ win32clipboard.CF_UNICODETEXT, str(out_code)
+ )
+ finally:
+ win32clipboard.CloseClipboard()
+
+ def OnEditExecClipboard(self, command, code):
+ """Executes python code directly from the clipboard."""
+ win32clipboard.OpenClipboard()
+ try:
+ code = win32clipboard.GetClipboardData(win32clipboard.CF_UNICODETEXT)
+ finally:
+ win32clipboard.CloseClipboard()
+
+ code = code.replace("\r\n", "\n") + "\n"
+ try:
+ o = compile(code, "", "exec")
+ exec(o, __main__.__dict__)
+ except:
+ traceback.print_exc()
+
+ def GetRightMenuItems(self):
+ # Just override parents
+ ret = []
+ flags = 0
+ ret.append((flags, win32ui.ID_EDIT_UNDO, "&Undo"))
+ ret.append(win32con.MF_SEPARATOR)
+ ret.append((flags, win32ui.ID_EDIT_CUT, "Cu&t"))
+ ret.append((flags, win32ui.ID_EDIT_COPY, "&Copy"))
+
+ start, end = self.GetSel()
+ if start != end:
+ ret.append((flags, ID_EDIT_COPY_CODE, "Copy code without prompts"))
+ if win32clipboard.IsClipboardFormatAvailable(win32clipboard.CF_UNICODETEXT):
+ ret.append(
+ (flags, ID_EDIT_EXEC_CLIPBOARD, "Execute python code from clipboard")
+ )
+
+ ret.append((flags, win32ui.ID_EDIT_PASTE, "&Paste"))
+ ret.append(win32con.MF_SEPARATOR)
+ ret.append((flags, win32ui.ID_EDIT_SELECT_ALL, "&Select all"))
+ ret.append((flags, win32ui.ID_EDIT_SELECT_BLOCK, "Select &block"))
+ ret.append((flags, win32ui.ID_VIEW_WHITESPACE, "View &Whitespace"))
+ return ret
+
+ def MDINextEvent(self, event):
+ win32ui.GetMainFrame().MDINext(0)
+
+ def MDIPrevEvent(self, event):
+ win32ui.GetMainFrame().MDINext(0)
+
+ def WindowBackEvent(self, event):
+ parent = self.GetParentFrame()
+ if parent == win32ui.GetMainFrame():
+ # It is docked.
+ try:
+ wnd, isactive = parent.MDIGetActive()
+ wnd.SetFocus()
+ except win32ui.error:
+ # No MDI window active!
+ pass
+ else:
+ # Normal Window
+ try:
+ lastActive = self.GetParentFrame().lastActive
+ # If the window is invalid, reset it.
+ if lastActive is not None and (
+ lastActive._obj_ is None or lastActive.GetSafeHwnd() == 0
+ ):
+ lastActive = self.GetParentFrame().lastActive = None
+ win32ui.SetStatusText("The last active Window has been closed.")
+ except AttributeError:
+ print("Can't find the last active window!")
+ lastActive = None
+ if lastActive is not None:
+ lastActive.MDIActivate()
+
+
+class InteractiveView(InteractiveCore, winout.WindowOutputView):
+ def __init__(self, doc):
+ InteractiveCore.__init__(self)
+ winout.WindowOutputView.__init__(self, doc)
+ self.encoding = pywin.default_scintilla_encoding
+
+ def _MakeColorizer(self):
+ return InteractiveFormatter(self)
+
+ def OnInitialUpdate(self):
+ winout.WindowOutputView.OnInitialUpdate(self)
+ self.SetWordWrap()
+ self.Init()
+
+ def HookHandlers(self):
+ winout.WindowOutputView.HookHandlers(self)
+ InteractiveCore.HookHandlers(self)
+
+
+class CInteractivePython(winout.WindowOutput):
+ def __init__(self, makeDoc=None, makeFrame=None):
+ self.IsFinalDestroy = 0
+ winout.WindowOutput.__init__(
+ self,
+ sectionProfile,
+ sectionProfile,
+ winout.flags.WQ_LINE,
+ 1,
+ None,
+ makeDoc,
+ makeFrame,
+ InteractiveView,
+ )
+ self.Create()
+
+ def OnViewDestroy(self, view):
+ if self.IsFinalDestroy:
+ view.OutputRelease()
+ winout.WindowOutput.OnViewDestroy(self, view)
+
+ def Close(self):
+ self.IsFinalDestroy = 1
+ winout.WindowOutput.Close(self)
+
+
+class InteractiveFrame(winout.WindowOutputFrame):
+ def __init__(self):
+ self.lastActive = None
+ winout.WindowOutputFrame.__init__(self)
+
+ def OnMDIActivate(self, bActive, wndActive, wndDeactive):
+ if bActive:
+ self.lastActive = wndDeactive
+
+
+######################################################################
+##
+## Dockable Window Support
+##
+######################################################################
+ID_DOCKED_INTERACTIVE_CONTROLBAR = 0xE802
+
+DockedInteractiveViewParent = InteractiveView
+
+
+class DockedInteractiveView(DockedInteractiveViewParent):
+ def HookHandlers(self):
+ DockedInteractiveViewParent.HookHandlers(self)
+ self.HookMessage(self.OnSetFocus, win32con.WM_SETFOCUS)
+ self.HookMessage(self.OnKillFocus, win32con.WM_KILLFOCUS)
+
+ def OnSetFocus(self, msg):
+ self.GetParentFrame().SetActiveView(self)
+ return 1
+
+ def OnKillFocus(self, msg):
+ # If we are losing focus to another in this app, reset the main frame's active view.
+ hwnd = wparam = msg[2]
+ try:
+ wnd = win32ui.CreateWindowFromHandle(hwnd)
+ reset = wnd.GetTopLevelFrame() == self.GetTopLevelFrame()
+ except win32ui.error:
+ reset = 0 # Not my window
+ if reset:
+ self.GetParentFrame().SetActiveView(None)
+ return 1
+
+ def OnDestroy(self, msg):
+ newSize = self.GetWindowPlacement()[4]
+ pywin.framework.app.SaveWindowSize("Interactive Window", newSize, "docked")
+ try:
+ if self.GetParentFrame().GetActiveView == self:
+ self.GetParentFrame().SetActiveView(None)
+ except win32ui.error:
+ pass
+ try:
+ if win32ui.GetMainFrame().GetActiveView() == self:
+ win32ui.GetMainFrame().SetActiveView(None)
+ except win32ui.error:
+ pass
+ return DockedInteractiveViewParent.OnDestroy(self, msg)
+
+
+class CDockedInteractivePython(CInteractivePython):
+ def __init__(self, dockbar):
+ self.bFirstCreated = 0
+ self.dockbar = dockbar
+ CInteractivePython.__init__(self)
+
+ def NeedRecreateWindow(self):
+ if self.bCreating:
+ return 0
+ try:
+ frame = win32ui.GetMainFrame()
+ if frame.closing:
+ return 0 # Dieing!
+ except (win32ui.error, AttributeError):
+ return 0 # The app is dieing!
+ try:
+ cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
+ return not cb.IsWindowVisible()
+ except win32ui.error:
+ return 1 # Control bar does not exist!
+
+ def RecreateWindow(self):
+ try:
+ dockbar = win32ui.GetMainFrame().GetControlBar(
+ ID_DOCKED_INTERACTIVE_CONTROLBAR
+ )
+ win32ui.GetMainFrame().ShowControlBar(dockbar, 1, 1)
+ except win32ui.error:
+ CreateDockedInteractiveWindow()
+
+ def Create(self):
+ self.bCreating = 1
+ doc = InteractiveDocument(None, self.DoCreateDoc())
+ view = DockedInteractiveView(doc)
+ defRect = pywin.framework.app.LoadWindowSize("Interactive Window", "docked")
+ if defRect[2] - defRect[0] == 0:
+ defRect = 0, 0, 500, 200
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.WS_BORDER
+ id = 1050 # win32ui.AFX_IDW_PANE_FIRST
+ view.CreateWindow(self.dockbar, id, style, defRect)
+ view.OnInitialUpdate()
+ self.bFirstCreated = 1
+
+ self.currentView = doc.GetFirstView()
+ self.bCreating = 0
+ if self.title:
+ doc.SetTitle(self.title)
+
+
+# The factory we pass to the dockable window support.
+def InteractiveViewCreator(parent):
+ global edit
+ edit = CDockedInteractivePython(parent)
+ return edit.currentView
+
+
+def CreateDockedInteractiveWindow():
+ # Later, the DockingBar should be capable of hosting multiple
+ # children.
+ from pywin.docking.DockingBar import DockingBar
+
+ bar = DockingBar()
+ creator = InteractiveViewCreator
+ bar.CreateWindow(
+ win32ui.GetMainFrame(),
+ creator,
+ "Interactive Window",
+ ID_DOCKED_INTERACTIVE_CONTROLBAR,
+ )
+ bar.SetBarStyle(
+ bar.GetBarStyle()
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ | afxres.CBRS_SIZE_DYNAMIC
+ )
+ bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ win32ui.GetMainFrame().DockControlBar(bar, afxres.AFX_IDW_DOCKBAR_BOTTOM)
+
+
+######################################################################
+#
+# The public interface to this module.
+#
+######################################################################
+# No extra functionality now, but maybe later, so
+# publicize these names.
+InteractiveDocument = winout.WindowOutputDocument
+
+# We remember our one and only interactive window in the "edit" variable.
+edit = None
+
+
+def CreateInteractiveWindowUserPreference(makeDoc=None, makeFrame=None):
+ """Create some sort of interactive window if the user's preference say we should."""
+ bCreate = LoadPreference("Show at startup", 1)
+ if bCreate:
+ CreateInteractiveWindow(makeDoc, makeFrame)
+
+
+def CreateInteractiveWindow(makeDoc=None, makeFrame=None):
+ """Create a standard or docked interactive window unconditionally"""
+ assert edit is None, "Creating second interactive window!"
+ bDocking = LoadPreference("Docking", 0)
+ if bDocking:
+ CreateDockedInteractiveWindow()
+ else:
+ CreateMDIInteractiveWindow(makeDoc, makeFrame)
+ assert edit is not None, "Created interactive window, but did not set the global!"
+ edit.currentView.SetFocus()
+
+
+def CreateMDIInteractiveWindow(makeDoc=None, makeFrame=None):
+ """Create a standard (non-docked) interactive window unconditionally"""
+ global edit
+ if makeDoc is None:
+ makeDoc = InteractiveDocument
+ if makeFrame is None:
+ makeFrame = InteractiveFrame
+ edit = CInteractivePython(makeDoc=makeDoc, makeFrame=makeFrame)
+
+
+def DestroyInteractiveWindow():
+ """Destroy the interactive window.
+ This is different to Closing the window,
+ which may automatically re-appear. Once destroyed, it can never be recreated,
+ and a complete new instance must be created (which the various other helper
+ functions will then do after making this call
+ """
+ global edit
+ if edit is not None and edit.currentView is not None:
+ if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
+ # It is docked - do nothing now (this is only called at shutdown!)
+ pass
+ else:
+ # It is a standard window - call Close on the container.
+ edit.Close()
+ edit = None
+
+
+def CloseInteractiveWindow():
+ """Close the interactive window, allowing it to be re-created on demand."""
+ global edit
+ if edit is not None and edit.currentView is not None:
+ if edit.currentView.GetParentFrame() == win32ui.GetMainFrame():
+ # It is docked, just hide the dock bar.
+ frame = win32ui.GetMainFrame()
+ cb = frame.GetControlBar(ID_DOCKED_INTERACTIVE_CONTROLBAR)
+ frame.ShowControlBar(cb, 0, 1)
+ else:
+ # It is a standard window - destroy the frame/view, allowing the object itself to remain.
+ edit.currentView.GetParentFrame().DestroyWindow()
+
+
+def ToggleInteractiveWindow():
+ """If the interactive window is visible, hide it, otherwise show it."""
+ if edit is None:
+ CreateInteractiveWindow()
+ else:
+ if edit.NeedRecreateWindow():
+ edit.RecreateWindow()
+ else:
+ # Close it, allowing a reopen.
+ CloseInteractiveWindow()
+
+
+def ShowInteractiveWindow():
+ """Shows (or creates if necessary) an interactive window"""
+ if edit is None:
+ CreateInteractiveWindow()
+ else:
+ if edit.NeedRecreateWindow():
+ edit.RecreateWindow()
+ else:
+ parent = edit.currentView.GetParentFrame()
+ if parent == win32ui.GetMainFrame(): # It is docked.
+ edit.currentView.SetFocus()
+ else: # It is a "normal" window
+ edit.currentView.GetParentFrame().AutoRestore()
+ win32ui.GetMainFrame().MDIActivate(edit.currentView.GetParentFrame())
+
+
+def IsInteractiveWindowVisible():
+ return edit is not None and not edit.NeedRecreateWindow()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/intpyapp.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/intpyapp.py
new file mode 100644
index 0000000000000000000000000000000000000000..4f304b800222cf979e1f13138facdc19b55c9642
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/intpyapp.py
@@ -0,0 +1,552 @@
+# intpyapp.py - Interactive Python application class
+#
+import os
+import sys
+import traceback
+
+import __main__
+import commctrl
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import afxres, dialog, docview
+
+from . import app, dbgcommands
+
+lastLocateFileName = ".py" # used in the "File/Locate" dialog...
+
+
+# todo - _SetupSharedMenu should be moved to a framework class.
+def _SetupSharedMenu_(self):
+ sharedMenu = self.GetSharedMenu()
+ from pywin.framework import toolmenu
+
+ toolmenu.SetToolsMenu(sharedMenu)
+ from pywin.framework import help
+
+ help.SetHelpMenuOtherHelp(sharedMenu)
+
+
+docview.DocTemplate._SetupSharedMenu_ = _SetupSharedMenu_ # type: ignore[method-assign]
+
+
+class MainFrame(app.MainFrame):
+ def OnCreate(self, createStruct):
+ self.closing = 0
+ if app.MainFrame.OnCreate(self, createStruct) == -1:
+ return -1
+ style = (
+ win32con.WS_CHILD
+ | afxres.CBRS_SIZE_DYNAMIC
+ | afxres.CBRS_TOP
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ )
+
+ self.EnableDocking(afxres.CBRS_ALIGN_ANY)
+
+ tb = win32ui.CreateToolBar(self, style | win32con.WS_VISIBLE)
+ tb.ModifyStyle(0, commctrl.TBSTYLE_FLAT)
+ tb.LoadToolBar(win32ui.IDR_MAINFRAME)
+ tb.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ tb.SetWindowText("Standard")
+ self.DockControlBar(tb)
+ # Any other packages which use toolbars
+ from pywin.debugger.debugger import PrepareControlBars
+
+ PrepareControlBars(self)
+ # Note "interact" also uses dockable windows, but they already happen
+
+ # And a "Tools" menu on the main frame.
+ menu = self.GetMenu()
+ from . import toolmenu
+
+ toolmenu.SetToolsMenu(menu, 2)
+ # And fix the "Help" menu on the main frame
+ from pywin.framework import help
+
+ help.SetHelpMenuOtherHelp(menu)
+
+ def OnClose(self):
+ try:
+ import pywin.debugger
+
+ if (
+ pywin.debugger.currentDebugger is not None
+ and pywin.debugger.currentDebugger.pumping
+ ):
+ try:
+ pywin.debugger.currentDebugger.close(1)
+ except:
+ traceback.print_exc()
+ return
+ except win32ui.error:
+ pass
+ self.closing = 1
+ self.SaveBarState("ToolbarDefault")
+ self.SetActiveView(None) # Otherwise MFC's OnClose may _not_ prompt for save.
+
+ from pywin.framework import help
+
+ help.FinalizeHelp()
+
+ self.DestroyControlBar(afxres.AFX_IDW_TOOLBAR)
+ self.DestroyControlBar(win32ui.ID_VIEW_TOOLBAR_DBG)
+
+ return self._obj_.OnClose()
+
+ def DestroyControlBar(self, id):
+ try:
+ bar = self.GetControlBar(id)
+ except win32ui.error:
+ return
+ bar.DestroyWindow()
+
+ def OnCommand(self, wparam, lparam):
+ # By default, the current MDI child frame will process WM_COMMAND
+ # messages before any docked control bars - even if the control bar
+ # has focus. This is a problem for the interactive window when docked.
+ # Therefore, we detect the situation of a view having the main frame
+ # as its parent, and assume it must be a docked view (which it will in an MDI app)
+ try:
+ v = (
+ self.GetActiveView()
+ ) # Raise an exception if none - good - then we want default handling
+ # Main frame _does_ have a current view (ie, a docking view) - see if it wants it.
+ if v.OnCommand(wparam, lparam):
+ return 1
+ except (win32ui.error, AttributeError):
+ pass
+ return self._obj_.OnCommand(wparam, lparam)
+
+
+class InteractivePythonApp(app.CApp):
+ # This works if necessary - just we don't need to override the Run method.
+ # def Run(self):
+ # return self._obj_.Run()
+
+ def HookCommands(self):
+ app.CApp.HookCommands(self)
+ dbgcommands.DebuggerCommandHandler().HookCommands()
+ self.HookCommand(self.OnViewBrowse, win32ui.ID_VIEW_BROWSE)
+ self.HookCommand(self.OnFileImport, win32ui.ID_FILE_IMPORT)
+ self.HookCommand(self.OnFileCheck, win32ui.ID_FILE_CHECK)
+ self.HookCommandUpdate(self.OnUpdateFileCheck, win32ui.ID_FILE_CHECK)
+ self.HookCommand(self.OnFileRun, win32ui.ID_FILE_RUN)
+ self.HookCommand(self.OnFileLocate, win32ui.ID_FILE_LOCATE)
+ self.HookCommand(self.OnInteractiveWindow, win32ui.ID_VIEW_INTERACTIVE)
+ self.HookCommandUpdate(
+ self.OnUpdateInteractiveWindow, win32ui.ID_VIEW_INTERACTIVE
+ )
+ self.HookCommand(self.OnViewOptions, win32ui.ID_VIEW_OPTIONS)
+ self.HookCommand(self.OnHelpIndex, afxres.ID_HELP_INDEX)
+ self.HookCommand(self.OnFileSaveAll, win32ui.ID_FILE_SAVE_ALL)
+ self.HookCommand(self.OnViewToolbarDbg, win32ui.ID_VIEW_TOOLBAR_DBG)
+ self.HookCommandUpdate(self.OnUpdateViewToolbarDbg, win32ui.ID_VIEW_TOOLBAR_DBG)
+
+ def CreateMainFrame(self):
+ return MainFrame()
+
+ def MakeExistingDDEConnection(self):
+ # Use DDE to connect to an existing instance
+ # Return None if no existing instance
+ try:
+ from . import intpydde
+ except ImportError:
+ # No dde support!
+ return None
+ conv = intpydde.CreateConversation(self.ddeServer)
+ try:
+ conv.ConnectTo("Pythonwin", "System")
+ return conv
+ except intpydde.error:
+ return None
+
+ def InitDDE(self):
+ # Do all the magic DDE handling.
+ # Returns TRUE if we have pumped the arguments to our
+ # remote DDE app, and we should terminate.
+ try:
+ from . import intpydde
+ except ImportError:
+ self.ddeServer = None
+ intpydde = None
+ if intpydde is not None:
+ self.ddeServer = intpydde.DDEServer(self)
+ self.ddeServer.Create("Pythonwin", intpydde.CBF_FAIL_SELFCONNECTIONS)
+ try:
+ # If there is an existing instance, pump the arguments to it.
+ connection = self.MakeExistingDDEConnection()
+ if connection is not None:
+ connection.Exec("self.Activate()")
+ if self.ProcessArgs(sys.argv, connection) is None:
+ return 1
+ except:
+ # It is too early to 'print' an exception - we
+ # don't have stdout setup yet!
+ win32ui.DisplayTraceback(
+ sys.exc_info(), " - error in DDE conversation with Pythonwin"
+ )
+ return 1
+
+ def InitInstance(self):
+ # Allow "/nodde" and "/new" to optimize this!
+ if (
+ "/nodde" not in sys.argv
+ and "/new" not in sys.argv
+ and "-nodde" not in sys.argv
+ and "-new" not in sys.argv
+ ):
+ if self.InitDDE():
+ return 1 # A remote DDE client is doing it for us!
+ else:
+ self.ddeServer = None
+
+ win32ui.SetRegistryKey(
+ f"Python {sys.winver}"
+ ) # MFC automatically puts the main frame caption on!
+ app.CApp.InitInstance(self)
+
+ # Create the taskbar icon
+ win32ui.CreateDebuggerThread()
+
+ # Allow Pythonwin to host OCX controls.
+ win32ui.EnableControlContainer()
+
+ # Display the interactive window if the user wants it.
+ from . import interact
+
+ interact.CreateInteractiveWindowUserPreference()
+
+ # Load the modules we use internally.
+ self.LoadSystemModules()
+
+ # Load additional module the user may want.
+ self.LoadUserModules()
+
+ # Load the ToolBar state near the end of the init process, as
+ # there may be Toolbar IDs created by the user or other modules.
+ # By now all these modules should be loaded, so all the toolbar IDs loaded.
+ try:
+ self.frame.LoadBarState("ToolbarDefault")
+ except win32ui.error:
+ # MFC sucks. It does essentially "GetDlgItem(x)->Something", so if the
+ # toolbar with ID x does not exist, MFC crashes! Pythonwin has a trap for this
+ # but I need to investigate more how to prevent it (AFAIK, ensuring all the
+ # toolbars are created by now _should_ stop it!)
+ pass
+
+ # Finally process the command line arguments.
+ try:
+ self.ProcessArgs(sys.argv)
+ except:
+ # too early for printing anything.
+ win32ui.DisplayTraceback(
+ sys.exc_info(), " - error processing command line args"
+ )
+
+ def ExitInstance(self):
+ win32ui.DestroyDebuggerThread()
+ try:
+ from . import interact
+
+ interact.DestroyInteractiveWindow()
+ except:
+ pass
+ if self.ddeServer is not None:
+ self.ddeServer.Shutdown()
+ self.ddeServer = None
+ return app.CApp.ExitInstance(self)
+
+ def Activate(self):
+ # Bring to the foreground. Mainly used when another app starts up, it asks
+ # this one to activate itself, then it terminates.
+ frame = win32ui.GetMainFrame()
+ frame.SetForegroundWindow()
+ if frame.GetWindowPlacement()[1] == win32con.SW_SHOWMINIMIZED:
+ frame.ShowWindow(win32con.SW_RESTORE)
+
+ def ProcessArgs(self, args, dde=None):
+ # If we are going to talk to a remote app via DDE, then
+ # activate it!
+ if (
+ len(args) < 1 or not args[0]
+ ): # argv[0]=='' when started without args, just like Python.exe!
+ return
+
+ i = 0
+ while i < len(args):
+ argType = args[i]
+ i += 1
+ if argType.startswith("-"):
+ # Support dash options. Slash options are misinterpreted by python init
+ # as path and not finding usually 'C:\\' ends up in sys.path[0]
+ argType = "/" + argType[1:]
+ if not argType.startswith("/"):
+ argType = win32ui.GetProfileVal(
+ "Python", "Default Arg Type", "/edit"
+ ).lower()
+ i -= 1 # arg is /edit's parameter
+ par = i < len(args) and args[i] or "MISSING"
+ if argType in ("/nodde", "/new", "-nodde", "-new"):
+ # Already handled
+ pass
+ elif argType.startswith("/goto:"):
+ gotoline = int(argType[len("/goto:") :])
+ if dde:
+ dde.Exec(
+ "from pywin.framework import scriptutils\n"
+ "ed = scriptutils.GetActiveEditControl()\n"
+ "if ed: ed.SetSel(ed.LineIndex(%s - 1))" % gotoline
+ )
+ else:
+ from . import scriptutils
+
+ ed = scriptutils.GetActiveEditControl()
+ if ed:
+ ed.SetSel(ed.LineIndex(gotoline - 1))
+ elif argType == "/edit":
+ # Load up the default application.
+ i += 1
+ fname = win32api.GetFullPathName(par)
+ if not os.path.isfile(fname):
+ # if we don't catch this, OpenDocumentFile() (actually
+ # PyCDocument.SetPathName() in
+ # pywin.scintilla.document.CScintillaDocument.OnOpenDocument)
+ # segfaults Pythonwin on recent PY3 builds (b228)
+ win32ui.MessageBox(
+ "No such file: {}\n\nCommand Line: {}".format(
+ fname, win32api.GetCommandLine()
+ ),
+ "Open file for edit",
+ win32con.MB_ICONERROR,
+ )
+ continue
+ if dde:
+ dde.Exec(f"win32ui.GetApp().OpenDocumentFile({fname!r})")
+ else:
+ win32ui.GetApp().OpenDocumentFile(par)
+ elif argType == "/rundlg":
+ if dde:
+ dde.Exec(
+ "from pywin.framework import scriptutils;scriptutils.RunScript({!r}, {!r}, 1)".format(
+ par, " ".join(args[i + 1 :])
+ )
+ )
+ else:
+ from . import scriptutils
+
+ scriptutils.RunScript(par, " ".join(args[i + 1 :]))
+ return
+ elif argType == "/run":
+ if dde:
+ dde.Exec(
+ "from pywin.framework import scriptutils;scriptutils.RunScript({!r}, {!r}, 0)".format(
+ par, " ".join(args[i + 1 :])
+ )
+ )
+ else:
+ from . import scriptutils
+
+ scriptutils.RunScript(par, " ".join(args[i + 1 :]), 0)
+ return
+ elif argType == "/app":
+ raise RuntimeError(
+ "/app only supported for new instances of Pythonwin.exe"
+ )
+ elif argType == "/dde": # Send arbitary command
+ if dde is not None:
+ dde.Exec(par)
+ else:
+ win32ui.MessageBox(
+ "The /dde command can only be used\r\nwhen Pythonwin is already running"
+ )
+ i += 1
+ else:
+ raise ValueError("Command line argument not recognised: %s" % argType)
+
+ def LoadSystemModules(self):
+ self.DoLoadModules("pywin.framework.editor,pywin.framework.stdin")
+
+ def LoadUserModules(self, moduleNames=None):
+ # Load the users modules.
+ if moduleNames is None:
+ default = "pywin.framework.sgrepmdi"
+ moduleNames = win32ui.GetProfileVal("Python", "Startup Modules", default)
+ self.DoLoadModules(moduleNames)
+
+ def DoLoadModules(self, moduleNames): # ", sep string of module names.
+ if not moduleNames:
+ return
+ modules = moduleNames.split(",")
+ for module in modules:
+ try:
+ __import__(module)
+ except: # Catch em all, else the app itself dies! 'ImportError:
+ traceback.print_exc()
+ msg = 'Startup import of user module "%s" failed' % module
+ print(msg)
+ win32ui.MessageBox(msg)
+
+ #
+ # DDE Callback
+ #
+ def OnDDECommand(self, command):
+ try:
+ exec(command + "\n")
+ except:
+ print("ERROR executing DDE command: ", command)
+ traceback.print_exc()
+ raise
+
+ #
+ # General handlers
+ #
+ def OnViewBrowse(self, id, code):
+ "Called when ViewBrowse message is received"
+ from pywin.tools import browser
+
+ obName = dialog.GetSimpleInput("Object", "__builtins__", "Browse Python Object")
+ if obName is None:
+ return
+ try:
+ browser.Browse(eval(obName, __main__.__dict__, __main__.__dict__))
+ except NameError:
+ win32ui.MessageBox("This is no object with this name")
+ except AttributeError:
+ win32ui.MessageBox("The object has no attribute of that name")
+ except:
+ traceback.print_exc()
+ win32ui.MessageBox("This object can not be browsed")
+
+ def OnFileImport(self, id, code):
+ "Called when a FileImport message is received. Import the current or specified file"
+ from . import scriptutils
+
+ scriptutils.ImportFile()
+
+ def OnFileCheck(self, id, code):
+ "Called when a FileCheck message is received. Check the current file."
+ from . import scriptutils
+
+ scriptutils.CheckFile()
+
+ def OnUpdateFileCheck(self, cmdui):
+ from . import scriptutils
+
+ cmdui.Enable(scriptutils.GetActiveFileName(0) is not None)
+
+ def OnFileRun(self, id, code):
+ "Called when a FileRun message is received."
+ from . import scriptutils
+
+ showDlg = win32api.GetKeyState(win32con.VK_SHIFT) >= 0
+ scriptutils.RunScript(None, None, showDlg)
+
+ def OnFileLocate(self, id, code):
+ from . import scriptutils
+
+ global lastLocateFileName # save the new version away for next time...
+
+ name = dialog.GetSimpleInput(
+ "File name", lastLocateFileName, "Locate Python File"
+ )
+ if name is None: # Cancelled.
+ return
+ lastLocateFileName = name
+ # if ".py" supplied, rip it off!
+ # should also check for .pys and .pyw
+ if lastLocateFileName[-3:].lower() == ".py":
+ lastLocateFileName = lastLocateFileName[:-3]
+ lastLocateFileName = lastLocateFileName.replace(".", "\\")
+ newName = scriptutils.LocatePythonFile(lastLocateFileName)
+ if newName is None:
+ win32ui.MessageBox("The file '%s' can not be located" % lastLocateFileName)
+ else:
+ win32ui.GetApp().OpenDocumentFile(newName)
+
+ # Display all the "options" property pages we can find
+ def OnViewOptions(self, id, code):
+ win32ui.InitRichEdit()
+ sheet = dialog.PropertySheet("Pythonwin Options")
+ # Add property pages we know about that need manual work.
+ from pywin.dialogs import ideoptions
+
+ sheet.AddPage(ideoptions.OptionsPropPage())
+
+ from . import toolmenu
+
+ sheet.AddPage(toolmenu.ToolMenuPropPage())
+
+ # Get other dynamic pages from templates.
+ pages = []
+ for template in self.GetDocTemplateList():
+ try:
+ # Don't actually call the function with the exception handler.
+ getter = template.GetPythonPropertyPages
+ except AttributeError:
+ # Template does not provide property pages!
+ continue
+ pages.extend(getter())
+
+ # Debugger template goes at the end
+ try:
+ from pywin.debugger import configui
+ except ImportError:
+ configui = None
+ if configui is not None:
+ pages.append(configui.DebuggerOptionsPropPage())
+ # Now simply add the pages, and display the dialog.
+ for page in pages:
+ sheet.AddPage(page)
+
+ if sheet.DoModal() == win32con.IDOK:
+ win32ui.SetStatusText("Applying configuration changes...", 1)
+ win32ui.DoWaitCursor(1)
+ # Tell every Window in our app that win.ini has changed!
+ win32ui.GetMainFrame().SendMessageToDescendants(
+ win32con.WM_WININICHANGE, 0, 0
+ )
+ win32ui.DoWaitCursor(0)
+
+ def OnInteractiveWindow(self, id, code):
+ # toggle the existing state.
+ from . import interact
+
+ interact.ToggleInteractiveWindow()
+
+ def OnUpdateInteractiveWindow(self, cmdui):
+ try:
+ interact = sys.modules["pywin.framework.interact"]
+ state = interact.IsInteractiveWindowVisible()
+ except KeyError: # Interactive module hasn't ever been imported.
+ state = 0
+ cmdui.Enable()
+ cmdui.SetCheck(state)
+
+ def OnFileSaveAll(self, id, code):
+ # Only attempt to save editor documents.
+ from pywin.framework.editor import editorTemplate
+
+ num = 0
+ for doc in editorTemplate.GetDocumentList():
+ if doc.IsModified() and doc.GetPathName():
+ num = num = 1
+ doc.OnSaveDocument(doc.GetPathName())
+ win32ui.SetStatusText("%d documents saved" % num, 1)
+
+ def OnViewToolbarDbg(self, id, code):
+ if code == 0:
+ return not win32ui.GetMainFrame().OnBarCheck(id)
+
+ def OnUpdateViewToolbarDbg(self, cmdui):
+ win32ui.GetMainFrame().OnUpdateControlBarMenu(cmdui)
+ cmdui.Enable(1)
+
+ def OnHelpIndex(self, id, code):
+ from . import help
+
+ help.SelectAndRunHelpFile()
+
+
+thisApp = InteractivePythonApp()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/intpydde.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/intpydde.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b4eb0c86dbd3c5fb385abc3056f08c8b64de048
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/intpydde.py
@@ -0,0 +1,65 @@
+# DDE support for Pythonwin
+#
+# Seems to work fine (in the context that IE4 seems to have broken
+# DDE on _all_ NT4 machines I have tried, but only when a "Command Prompt" window
+# is open. Strange, but true. If you have problems with this, close all Command Prompts!
+
+
+import sys
+import traceback
+
+import win32ui
+from dde import ( # nopycln: import # Re-exported for intpyapp.py
+ CBF_FAIL_SELFCONNECTIONS as CBF_FAIL_SELFCONNECTIONS, # noqa: PLC0414
+ CreateConversation as CreateConversation, # noqa: PLC0414
+ CreateServer,
+ CreateServerSystemTopic,
+ error as error, # noqa: PLC0414
+)
+from pywin.mfc import object
+
+
+class DDESystemTopic(object.Object):
+ def __init__(self, app):
+ self.app = app
+ object.Object.__init__(self, CreateServerSystemTopic())
+
+ def Exec(self, data):
+ try:
+ # print("Executing", cmd)
+ self.app.OnDDECommand(data)
+ except:
+ t, v, tb = sys.exc_info()
+ # The DDE Execution failed.
+ print("Error executing DDE command.")
+ traceback.print_exception(t, v, tb)
+ return 0
+
+
+class DDEServer(object.Object):
+ def __init__(self, app):
+ self.app = app
+ object.Object.__init__(self, CreateServer())
+ self.topic = self.item = None
+
+ def CreateSystemTopic(self):
+ return DDESystemTopic(self.app)
+
+ def Shutdown(self):
+ self._obj_.Shutdown()
+ self._obj_.Destroy()
+ if self.topic is not None:
+ self.topic.Destroy()
+ self.topic = None
+ if self.item is not None:
+ self.item.Destroy()
+ self.item = None
+
+ def OnCreate(self):
+ return 1
+
+ def Status(self, msg):
+ try:
+ win32ui.SetStatusText(msg)
+ except win32ui.error:
+ pass
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..efb46ace62c128fec13021d665f23e5e8ffaccb8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/scriptutils.py
@@ -0,0 +1,684 @@
+"""
+Various utilities for running/importing a script
+"""
+
+import bdb
+import linecache
+import os
+import sys
+import traceback
+
+import __main__
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog
+from pywin.mfc.docview import TreeView
+
+from .cmdline import ParseArgs
+
+RS_DEBUGGER_NONE = 0 # Don't run under the debugger.
+RS_DEBUGGER_STEP = 1 # Start stepping under the debugger
+RS_DEBUGGER_GO = 2 # Just run under the debugger, stopping only at break-points.
+RS_DEBUGGER_PM = (
+ 3 # Don't run under debugger, but do post-mortem analysis on exception.
+)
+
+debugging_options = """No debugging
+Step-through in the debugger
+Run in the debugger
+Post-Mortem of unhandled exceptions""".split("\n")
+
+byte_cr = b"\r"
+byte_lf = b"\n"
+byte_crlf = b"\r\n"
+
+
+# A dialog box for the "Run Script" command.
+class DlgRunScript(dialog.Dialog):
+ "A class for the 'run script' dialog"
+
+ def __init__(self, bHaveDebugger):
+ dialog.Dialog.__init__(self, win32ui.IDD_RUN_SCRIPT)
+ self.AddDDX(win32ui.IDC_EDIT1, "script")
+ self.AddDDX(win32ui.IDC_EDIT2, "args")
+ self.AddDDX(win32ui.IDC_COMBO1, "debuggingType", "i")
+ self.HookCommand(self.OnBrowse, win32ui.IDC_BUTTON2)
+ self.bHaveDebugger = bHaveDebugger
+
+ def OnInitDialog(self):
+ rc = dialog.Dialog.OnInitDialog(self)
+ cbo = self.GetDlgItem(win32ui.IDC_COMBO1)
+ for o in debugging_options:
+ cbo.AddString(o)
+ cbo.SetCurSel(self["debuggingType"])
+ if not self.bHaveDebugger:
+ cbo.EnableWindow(0)
+
+ def OnBrowse(self, id, code):
+ if code != 0: # BN_CLICKED
+ return 1
+ openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
+ dlg = win32ui.CreateFileDialog(
+ 1, None, None, openFlags, "Python Scripts (*.py)|*.py||", self
+ )
+ dlg.SetOFNTitle("Run Script")
+ if dlg.DoModal() != win32con.IDOK:
+ return 0
+ self["script"] = dlg.GetPathName()
+ self.UpdateData(0)
+ return 0
+
+
+def GetDebugger():
+ """Get the default Python debugger. Returns the debugger, or None.
+
+ It is assumed the debugger has a standard "pdb" defined interface.
+ Currently always returns the 'pywin.debugger' debugger, or None
+ (pdb is _not_ returned as it is not effective in this GUI environment)
+ """
+ try:
+ import pywin.debugger
+
+ return pywin.debugger
+ except ImportError:
+ return None
+
+
+def IsOnPythonPath(path):
+ "Given a path only, see if it is on the Pythonpath. Assumes path is a full path spec."
+ # must check that the command line arg's path is in sys.path
+ for syspath in sys.path:
+ try:
+ # sys.path can have an empty entry.
+ if syspath and win32ui.FullPath(syspath) == path:
+ return 1
+ except win32ui.error as details:
+ print(f"Warning: The sys.path entry '{syspath}' is invalid\n{details}")
+ return 0
+
+
+def GetPackageModuleName(fileName):
+ r"""Given a filename, return (module name, new path).
+ eg - given "c:\a\b\c\my.py", return ("b.c.my",None) if "c:\a" is on sys.path.
+ If no package found, will return ("my", "c:\a\b\c")
+ """
+ path, fname = os.path.split(fileName)
+ path = origPath = win32ui.FullPath(path)
+ fname = os.path.splitext(fname)[0]
+ modBits = []
+ newPathReturn = None
+ if not IsOnPythonPath(path):
+ # Module not directly on the search path - see if under a package.
+ while len(path) > 3: # ie 'C:\'
+ path, modBit = os.path.split(path)
+ modBits.append(modBit)
+ # If on path, _and_ existing package of that name loaded.
+ if (
+ IsOnPythonPath(path)
+ and modBit in sys.modules
+ and (
+ os.path.exists(os.path.join(path, modBit, "__init__.py"))
+ or os.path.exists(os.path.join(path, modBit, "__init__.pyc"))
+ or os.path.exists(os.path.join(path, modBit, "__init__.pyo"))
+ )
+ ):
+ modBits.reverse()
+ return ".".join(modBits) + "." + fname, newPathReturn
+ # Not found - look a level higher
+ else:
+ newPathReturn = origPath
+
+ return fname, newPathReturn
+
+
+def GetActiveView():
+ """Gets the edit control (eg, EditView) with the focus, or None"""
+ try:
+ childFrame, bIsMaximised = win32ui.GetMainFrame().MDIGetActive()
+ return childFrame.GetActiveView()
+ except win32ui.error:
+ return None
+
+
+def GetActiveEditControl():
+ view = GetActiveView()
+ if view is None:
+ return None
+ if hasattr(view, "SCIAddText"): # Is it a scintilla control?
+ return view
+ try:
+ return view.GetRichEditCtrl()
+ except AttributeError:
+ pass
+ try:
+ return view.GetEditCtrl()
+ except AttributeError:
+ pass
+
+
+def GetActiveEditorDocument():
+ """Returns the active editor document and view, or (None,None) if no
+ active document or it's not an editor document.
+ """
+ view = GetActiveView()
+ if view is None or isinstance(view, TreeView):
+ return (None, None)
+ doc = view.GetDocument()
+ if hasattr(doc, "MarkerAdd"): # Is it an Editor document?
+ return doc, view
+ return (None, None)
+
+
+def GetActiveFileName(bAutoSave=1):
+ """Gets the file name for the active frame, saving it if necessary.
+
+ Returns None if it can't be found, or raises KeyboardInterrupt.
+ """
+ pathName = None
+ active = GetActiveView()
+ if active is None:
+ return None
+ try:
+ doc = active.GetDocument()
+ pathName = doc.GetPathName()
+
+ if bAutoSave and (
+ len(pathName) > 0
+ or doc.GetTitle()[:8] == "Untitled"
+ or doc.GetTitle()[:6] == "Script"
+ ): # if not a special purpose window
+ if doc.IsModified():
+ try:
+ doc.OnSaveDocument(pathName)
+ pathName = doc.GetPathName()
+
+ # clear the linecache buffer
+ linecache.clearcache()
+
+ except win32ui.error:
+ raise KeyboardInterrupt
+
+ except (win32ui.error, AttributeError):
+ pass
+ if not pathName:
+ return None
+ return pathName
+
+
+lastScript = ""
+lastArgs = ""
+lastDebuggingType = RS_DEBUGGER_NONE
+
+
+def RunScript(defName=None, defArgs=None, bShowDialog=1, debuggingType=None):
+ global lastScript, lastArgs, lastDebuggingType
+ _debugger_stop_frame_ = 1 # Magic variable so the debugger will hide me!
+
+ # Get the debugger - may be None!
+ debugger = GetDebugger()
+
+ if defName is None:
+ try:
+ pathName = GetActiveFileName()
+ except KeyboardInterrupt:
+ return # User cancelled save.
+ else:
+ pathName = defName
+ if not pathName:
+ pathName = lastScript
+ if defArgs is None:
+ args = ""
+ if pathName == lastScript:
+ args = lastArgs
+ else:
+ args = defArgs
+ if debuggingType is None:
+ debuggingType = lastDebuggingType
+
+ if not pathName or bShowDialog:
+ dlg = DlgRunScript(debugger is not None)
+ dlg["script"] = pathName
+ dlg["args"] = args
+ dlg["debuggingType"] = debuggingType
+ if dlg.DoModal() != win32con.IDOK:
+ return
+ script = dlg["script"]
+ args = dlg["args"]
+ debuggingType = dlg["debuggingType"]
+ if not script:
+ return
+ if debuggingType == RS_DEBUGGER_GO and debugger is not None:
+ # This may surprise users - they select "Run under debugger", but
+ # it appears not to! Only warn when they pick from the dialog!
+ # First - ensure the debugger is activated to pickup any break-points
+ # set in the editor.
+ try:
+ # Create the debugger, but _dont_ init the debugger GUI.
+ rd = debugger._GetCurrentDebugger()
+ except AttributeError:
+ rd = None
+ if rd is not None and len(rd.breaks) == 0:
+ msg = "There are no active break-points.\r\n\r\nSelecting this debug option without any\r\nbreak-points is unlikely to have the desired effect\r\nas the debugger is unlikely to be invoked..\r\n\r\nWould you like to step-through in the debugger instead?"
+ rc = win32ui.MessageBox(
+ msg,
+ win32ui.LoadString(win32ui.IDR_DEBUGGER),
+ win32con.MB_YESNOCANCEL | win32con.MB_ICONINFORMATION,
+ )
+ if rc == win32con.IDCANCEL:
+ return
+ if rc == win32con.IDYES:
+ debuggingType = RS_DEBUGGER_STEP
+
+ lastDebuggingType = debuggingType
+ lastScript = script
+ lastArgs = args
+ else:
+ script = pathName
+
+ # try and open the script.
+ if (
+ len(os.path.splitext(script)[1]) == 0
+ ): # check if no extension supplied, and give one.
+ script += ".py"
+ # If no path specified, try and locate the file
+ path, fnameonly = os.path.split(script)
+ if len(path) == 0:
+ try:
+ os.stat(fnameonly) # See if it is OK as is...
+ script = fnameonly
+ except OSError:
+ fullScript = LocatePythonFile(script)
+ if fullScript is None:
+ win32ui.MessageBox("The file '%s' can not be located" % script)
+ return
+ script = fullScript
+ else:
+ path = win32ui.FullPath(path)
+ if not IsOnPythonPath(path):
+ sys.path.append(path)
+
+ # py3k fun: If we use text mode to open the file, we get \r\n
+ # translated so Python allows the syntax (good!), but we get back
+ # text already decoded from the default encoding (bad!) and Python
+ # ignores any encoding decls (bad!). If we use binary mode we get
+ # the raw bytes and Python looks at the encoding (good!) but \r\n
+ # chars stay in place so Python throws a syntax error (bad!).
+ # So: do the binary thing and manually normalize \r\n.
+ try:
+ f = open(script, "rb")
+ except OSError as exc:
+ win32ui.MessageBox(
+ "The file could not be opened - %s (%d)" % (exc.strerror, exc.errno)
+ )
+ return
+
+ # Get the source-code - as above, normalize \r\n
+ code = f.read().replace(byte_crlf, byte_lf).replace(byte_cr, byte_lf) + byte_lf
+
+ # Remember and hack sys.argv for the script.
+ oldArgv = sys.argv
+ sys.argv = ParseArgs(args)
+ sys.argv.insert(0, script)
+ # sys.path[0] is the path of the script
+ oldPath0 = sys.path[0]
+ newPath0 = os.path.split(script)[0]
+ if not oldPath0: # if sys.path[0] is empty
+ sys.path[0] = newPath0
+ insertedPath0 = 0
+ else:
+ sys.path.insert(0, newPath0)
+ insertedPath0 = 1
+ bWorked = 0
+ win32ui.DoWaitCursor(1)
+ base = os.path.split(script)[1]
+ # Allow windows to repaint before starting.
+ win32ui.PumpWaitingMessages()
+ win32ui.SetStatusText("Running script %s..." % base, 1)
+ exitCode = 0
+ from pywin.framework import interact
+
+ # Check the debugger flags
+ if debugger is None and (debuggingType != RS_DEBUGGER_NONE):
+ win32ui.MessageBox(
+ "No debugger is installed. Debugging options have been ignored!"
+ )
+ debuggingType = RS_DEBUGGER_NONE
+
+ # Get a code object - ignore the debugger for this, as it is probably a syntax error
+ # at this point
+ try:
+ codeObject = compile(code, script, "exec")
+ except:
+ # Almost certainly a syntax error!
+ _HandlePythonFailure("run script", script)
+ # No code object which to run/debug.
+ return
+ __main__.__file__ = script
+ try:
+ if debuggingType == RS_DEBUGGER_STEP:
+ debugger.run(codeObject, __main__.__dict__, start_stepping=1)
+ elif debuggingType == RS_DEBUGGER_GO:
+ debugger.run(codeObject, __main__.__dict__, start_stepping=0)
+ else:
+ # Post mortem or no debugging
+ exec(codeObject, __main__.__dict__)
+ bWorked = 1
+ except bdb.BdbQuit:
+ # Don't print tracebacks when the debugger quit, but do print a message.
+ print("Debugging session cancelled.")
+ exitCode = 1
+ bWorked = 1
+ except SystemExit as code:
+ exitCode = code
+ bWorked = 1
+ except KeyboardInterrupt:
+ # Consider this successful, as we don't want the debugger.
+ # (but we do want a traceback!)
+ if interact.edit and interact.edit.currentView:
+ interact.edit.currentView.EnsureNoPrompt()
+ traceback.print_exc()
+ if interact.edit and interact.edit.currentView:
+ interact.edit.currentView.AppendToPrompt([])
+ bWorked = 1
+ except:
+ if interact.edit and interact.edit.currentView:
+ interact.edit.currentView.EnsureNoPrompt()
+ traceback.print_exc()
+ if interact.edit and interact.edit.currentView:
+ interact.edit.currentView.AppendToPrompt([])
+ if debuggingType == RS_DEBUGGER_PM:
+ debugger.pm()
+ del __main__.__file__
+ sys.argv = oldArgv
+ if insertedPath0:
+ del sys.path[0]
+ else:
+ sys.path[0] = oldPath0
+ f.close()
+ if bWorked:
+ win32ui.SetStatusText(f"Script '{script}' returned exit code {exitCode}")
+ else:
+ win32ui.SetStatusText("Exception raised while running script %s" % base)
+ try:
+ sys.stdout.flush()
+ except AttributeError:
+ pass
+
+ win32ui.DoWaitCursor(0)
+
+
+def ImportFile():
+ """This code looks for the current window, and determines if it can be imported. If not,
+ it will prompt for a file name, and allow it to be imported."""
+ try:
+ pathName = GetActiveFileName()
+ except KeyboardInterrupt:
+ pathName = None
+
+ if pathName is not None:
+ if os.path.splitext(pathName)[1].lower() not in (".py", ".pyw", ".pyx"):
+ pathName = None
+
+ if pathName is None:
+ openFlags = win32con.OFN_OVERWRITEPROMPT | win32con.OFN_FILEMUSTEXIST
+ dlg = win32ui.CreateFileDialog(
+ 1, None, None, openFlags, "Python Scripts (*.py;*.pyw)|*.py;*.pyw;*.pyx||"
+ )
+ dlg.SetOFNTitle("Import Script")
+ if dlg.DoModal() != win32con.IDOK:
+ return 0
+
+ pathName = dlg.GetPathName()
+
+ # If already imported, don't look for package
+ path, modName = os.path.split(pathName)
+ modName, modExt = os.path.splitext(modName)
+ newPath = None
+ # note that some packages (*cough* email *cough*) use "lazy importers"
+ # meaning sys.modules can change as a side-effect of looking at
+ # module.__file__ - so we must take a copy (ie, list(items()))
+ for key, mod in sys.modules.items():
+ if getattr(mod, "__file__", None):
+ fname = mod.__file__
+ base, ext = os.path.splitext(fname)
+ if ext.lower() in (".pyo", ".pyc"):
+ ext = ".py"
+ fname = base + ext
+ if win32ui.ComparePath(fname, pathName):
+ modName = key
+ break
+ else: # for not broken
+ modName, newPath = GetPackageModuleName(pathName)
+ if newPath:
+ sys.path.append(newPath)
+
+ if modName in sys.modules:
+ bNeedReload = 1
+ what = "reload"
+ else:
+ what = "import"
+ bNeedReload = 0
+
+ win32ui.SetStatusText(what.capitalize() + "ing module...", 1)
+ win32ui.DoWaitCursor(1)
+ # win32ui.GetMainFrame().BeginWaitCursor()
+
+ try:
+ # always do an import, as it is cheap if it's already loaded. This ensures
+ # it is in our name space.
+ codeObj = compile("import " + modName, "", "exec")
+ except SyntaxError:
+ win32ui.SetStatusText('Invalid filename for import: "' + modName + '"')
+ return
+ try:
+ exec(codeObj, __main__.__dict__)
+ mod = sys.modules.get(modName)
+ if bNeedReload:
+ from importlib import reload
+
+ mod = reload(sys.modules[modName])
+ win32ui.SetStatusText(
+ "Successfully "
+ + what
+ + "ed module '"
+ + modName
+ + "': %s" % getattr(mod, "__file__", "")
+ )
+ except:
+ _HandlePythonFailure(what)
+ win32ui.DoWaitCursor(0)
+
+
+def CheckFile():
+ """This code looks for the current window, and gets Python to check it
+ without actually executing any code (ie, by compiling only)
+ """
+ try:
+ pathName = GetActiveFileName()
+ except KeyboardInterrupt:
+ return
+
+ what = "check"
+ win32ui.SetStatusText(what.capitalize() + "ing module...", 1)
+ win32ui.DoWaitCursor(1)
+ try:
+ f = open(pathName)
+ except OSError as details:
+ print(f"Can't open file '{pathName}' - {details}")
+ return
+ try:
+ code = f.read() + "\n"
+ finally:
+ f.close()
+ try:
+ codeObj = compile(code, pathName, "exec")
+ if RunTabNanny(pathName):
+ win32ui.SetStatusText(
+ "Python and the TabNanny successfully checked the file '"
+ + os.path.basename(pathName)
+ + "'"
+ )
+ except SyntaxError:
+ _HandlePythonFailure(what, pathName)
+ except:
+ traceback.print_exc()
+ _HandlePythonFailure(what)
+ win32ui.DoWaitCursor(0)
+
+
+def RunTabNanny(filename):
+ import io
+
+ tabnanny = FindTabNanny()
+ if tabnanny is None:
+ win32ui.MessageBox("The TabNanny is not around, so the children can run amok!")
+ return
+
+ # Capture the tab-nanny output
+ newout = io.StringIO()
+ old_out = sys.stderr, sys.stdout
+ sys.stderr = sys.stdout = newout
+ try:
+ tabnanny.check(filename)
+ finally:
+ # Restore output
+ sys.stderr, sys.stdout = old_out
+ data = newout.getvalue()
+ if data:
+ try:
+ lineno = data.split()[1]
+ lineno = int(lineno)
+ _JumpToPosition(filename, lineno)
+ try: # Try and display whitespace
+ GetActiveEditControl().SCISetViewWS(1)
+ except:
+ pass
+ win32ui.SetStatusText("The TabNanny found trouble at line %d" % lineno)
+ except (IndexError, TypeError, ValueError):
+ print("The tab nanny complained, but I can't see where!")
+ print(data)
+ return 0
+ return 1
+
+
+def _JumpToPosition(fileName, lineno, col=1):
+ JumpToDocument(fileName, lineno, col)
+
+
+def JumpToDocument(fileName, lineno=0, col=1, nChars=0, bScrollToTop=0):
+ # Jump to the position in a file.
+ # If lineno is <= 0, don't move the position - just open/restore.
+ # if nChars > 0, select that many characters.
+ # if bScrollToTop, the specified line will be moved to the top of the window
+ # (eg, bScrollToTop should be false when jumping to an error line to retain the
+ # context, but true when jumping to a method defn, where we want the full body.
+ # Return the view which is editing the file, or None on error.
+ doc = win32ui.GetApp().OpenDocumentFile(fileName)
+ if doc is None:
+ return None
+ frame = doc.GetFirstView().GetParentFrame()
+ try:
+ view = frame.GetEditorView()
+ if frame.GetActiveView() != view:
+ frame.SetActiveView(view)
+ frame.AutoRestore()
+ except AttributeError: # Not an editor frame??
+ view = doc.GetFirstView()
+ if lineno > 0:
+ charNo = view.LineIndex(lineno - 1)
+ start = charNo + col - 1
+ size = view.GetTextLength()
+ try:
+ view.EnsureCharsVisible(charNo)
+ except AttributeError:
+ print("Doesn't appear to be one of our views?")
+ view.SetSel(min(start, size), min(start + nChars, size))
+ if bScrollToTop:
+ curTop = view.GetFirstVisibleLine()
+ nScroll = (lineno - 1) - curTop
+ view.LineScroll(nScroll, 0)
+ view.SetFocus()
+ return view
+
+
+def _HandlePythonFailure(what, syntaxErrorPathName=None):
+ typ, details, tb = sys.exc_info()
+ if isinstance(details, SyntaxError):
+ try:
+ msg, (fileName, line, col, text) = details
+ if (not fileName or fileName == "") and syntaxErrorPathName:
+ fileName = syntaxErrorPathName
+ _JumpToPosition(fileName, line, col)
+ except (TypeError, ValueError):
+ msg = str(details)
+ win32ui.SetStatusText(f"Failed to {what} - syntax error - {msg}")
+ else:
+ traceback.print_exc()
+ win32ui.SetStatusText(f"Failed to {what} - {details}")
+ tb = None # Clean up a cycle.
+
+
+# Find the Python TabNanny in either the standard library or the Python Tools/Scripts directory.
+def FindTabNanny():
+ try:
+ return __import__("tabnanny")
+ except ImportError:
+ pass
+ # OK - not in the standard library - go looking.
+ filename = "tabnanny.py"
+ try:
+ path = win32api.RegQueryValue(
+ win32con.HKEY_LOCAL_MACHINE,
+ "SOFTWARE\\Python\\PythonCore\\%s\\InstallPath" % (sys.winver),
+ )
+ except win32api.error:
+ print("WARNING - The Python registry does not have an 'InstallPath' setting")
+ print(" The file '%s' can not be located" % (filename))
+ return None
+ fname = os.path.join(path, "Tools\\Scripts\\%s" % filename)
+ try:
+ os.stat(fname)
+ except OSError:
+ print(f"WARNING - The file '{filename}' can not be located in path '{path}'")
+ return None
+
+ tabnannyhome, tabnannybase = os.path.split(fname)
+ tabnannybase = os.path.splitext(tabnannybase)[0]
+ # Put tab nanny at the top of the path.
+ sys.path.insert(0, tabnannyhome)
+ try:
+ return __import__(tabnannybase)
+ finally:
+ # remove the tab-nanny from the path
+ del sys.path[0]
+
+
+def LocatePythonFile(fileName, bBrowseIfDir=1):
+ "Given a file name, return a fully qualified file name, or None"
+ # first look for the exact file as specified
+ if not os.path.isfile(fileName):
+ # Go looking!
+ baseName = fileName
+ for path in sys.path:
+ fileName = os.path.abspath(os.path.join(path, baseName))
+ if os.path.isdir(fileName):
+ if bBrowseIfDir:
+ d = win32ui.CreateFileDialog(
+ 1, "*.py", None, 0, "Python Files (*.py)|*.py|All files|*.*"
+ )
+ d.SetOFNInitialDir(fileName)
+ rc = d.DoModal()
+ if rc == win32con.IDOK:
+ fileName = d.GetPathName()
+ break
+ else:
+ return None
+ else:
+ fileName += ".py"
+ if os.path.isfile(fileName):
+ break # Found it!
+
+ else: # for not broken out of
+ return None
+ return win32ui.FullPath(fileName)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/sgrepmdi.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/sgrepmdi.py
new file mode 100644
index 0000000000000000000000000000000000000000..02c80fd2da7e668c56829ffd461cd3d21036d804
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/sgrepmdi.py
@@ -0,0 +1,749 @@
+# SGrepMDI is by Gordon McMillan (gmcm@hypernet.com)
+# It does basically what Find In Files does in MSVC with a couple enhancements.
+# - It saves any directories in the app's ini file (if you want to get rid
+# of them you'll have to edit the file)
+# - "Directories" can be directories,
+# - semicolon separated lists of "directories",
+# - environment variables that evaluate to "directories",
+# - registry path names that evaluate to "directories",
+# - all of which is recursive, so you can mix them all up.
+# - It is MDI, so you can 'nest' greps and return to earlier ones,
+# (ie, have multiple results open at the same time)
+# - Like FIF, double clicking a line opens an editor and takes you to the line.
+# - You can highlight text, right click and start a new grep with the selected
+# text as search pattern and same directories etc as before.
+# - You can save grep parameters (so you don't lose your hardearned pattern)
+# from File|Save
+# - You can save grep results by right clicking in the result window.
+# Hats off to Mark Hammond for providing an environment where I could cobble
+# something like this together in a couple evenings!
+
+import glob
+import os
+import re
+
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog, docview, window
+
+from . import scriptutils
+
+
+def getsubdirs(d):
+ dlist = []
+ flist = glob.glob(d + "\\*")
+ for f in flist:
+ if os.path.isdir(f):
+ dlist.append(f)
+ dlist += getsubdirs(f)
+ return dlist
+
+
+class dirpath:
+ def __init__(self, str, recurse=0):
+ dp = str.split(";")
+ dirs = {}
+ for d in dp:
+ if os.path.isdir(d):
+ d = d.lower()
+ if d not in dirs:
+ dirs[d] = None
+ if recurse:
+ subdirs = getsubdirs(d)
+ for sd in subdirs:
+ sd = sd.lower()
+ if sd not in dirs:
+ dirs[sd] = None
+ elif os.path.isfile(d):
+ pass
+ else:
+ x = None
+ if d in os.environ:
+ x = dirpath(os.environ[d])
+ elif d[:5] == "HKEY_":
+ keystr = d.split("\\")
+ try:
+ root = eval("win32con." + keystr[0])
+ except:
+ win32ui.MessageBox(
+ "Can't interpret registry key name '%s'" % keystr[0]
+ )
+ try:
+ subkey = "\\".join(keystr[1:])
+ val = win32api.RegQueryValue(root, subkey)
+ if val:
+ x = dirpath(val)
+ else:
+ win32ui.MessageBox(
+ "Registry path '%s' did not return a path entry" % d
+ )
+ except:
+ win32ui.MessageBox(
+ "Can't interpret registry key value: %s" % keystr[1:]
+ )
+ else:
+ win32ui.MessageBox("Directory '%s' not found" % d)
+ if x:
+ for xd in x:
+ if xd not in dirs:
+ dirs[xd] = None
+ if recurse:
+ subdirs = getsubdirs(xd)
+ for sd in subdirs:
+ sd = sd.lower()
+ if sd not in dirs:
+ dirs[sd] = None
+ self.dirs = list(dirs)
+
+ def __getitem__(self, key):
+ return self.dirs[key]
+
+ def __len__(self):
+ return len(self.dirs)
+
+ def __setitem__(self, key, value):
+ self.dirs[key] = value
+
+ def __delitem__(self, key):
+ del self.dirs[key]
+
+ def __getslice__(self, lo, hi):
+ return self.dirs[lo:hi]
+
+ def __setslice__(self, lo, hi, seq):
+ self.dirs[lo:hi] = seq
+
+ def __delslice__(self, lo, hi):
+ del self.dirs[lo:hi]
+
+ def __add__(self, other):
+ if isinstance(other, (dirpath, list)):
+ return self.dirs + other.dirs
+
+ def __radd__(self, other):
+ if isinstance(other, (dirpath, list)):
+ return other.dirs + self.dirs
+
+
+# Group(1) is the filename, group(2) is the lineno.
+regexGrep = re.compile(r"^([a-zA-Z]:[^(]*)\(([0-9]+)\)")
+
+# these are the atom numbers defined by Windows for basic dialog controls
+
+BUTTON = 0x80
+EDIT = 0x81
+STATIC = 0x82
+LISTBOX = 0x83
+SCROLLBAR = 0x84
+COMBOBOX = 0x85
+
+
+class GrepTemplate(docview.RichEditDocTemplate):
+ def __init__(self):
+ docview.RichEditDocTemplate.__init__(
+ self, win32ui.IDR_TEXTTYPE, GrepDocument, GrepFrame, GrepView
+ )
+ self.SetDocStrings("\nGrep\nGrep\nGrep params (*.grep)\n.grep\n\n\n")
+ win32ui.GetApp().AddDocTemplate(self)
+ self.docparams = None
+
+ def MatchDocType(self, fileName, fileType):
+ doc = self.FindOpenDocument(fileName)
+ if doc:
+ return doc
+ ext = os.path.splitext(fileName)[1].lower()
+ if ext == ".grep":
+ return win32ui.CDocTemplate_Confidence_yesAttemptNative
+ return win32ui.CDocTemplate_Confidence_noAttempt
+
+ def setParams(self, params):
+ self.docparams = params
+
+ def readParams(self):
+ tmp = self.docparams
+ self.docparams = None
+ return tmp
+
+
+class GrepFrame(window.MDIChildWnd):
+ # The template and doc params will one day be removed.
+ def __init__(self, wnd=None):
+ window.MDIChildWnd.__init__(self, wnd)
+
+
+class GrepDocument(docview.RichEditDoc):
+ def __init__(self, template):
+ docview.RichEditDoc.__init__(self, template)
+ self.dirpattern = ""
+ self.filpattern = ""
+ self.greppattern = ""
+ self.casesensitive = 1
+ self.recurse = 1
+ self.verbose = 0
+
+ def OnOpenDocument(self, fnm):
+ # this bizarre stuff with params is so right clicking in a result window
+ # and starting a new grep can communicate the default parameters to the
+ # new grep.
+ try:
+ params = open(fnm, "r").read()
+ except:
+ params = None
+ self.setInitParams(params)
+ return self.OnNewDocument()
+
+ def OnCloseDocument(self):
+ try:
+ win32ui.GetApp().DeleteIdleHandler(self.SearchFile)
+ except:
+ pass
+ return self._obj_.OnCloseDocument()
+
+ def saveInitParams(self):
+ # Only save the flags, not the text boxes.
+ paramstr = "\t%s\t\t%d\t%d" % (
+ self.filpattern,
+ self.casesensitive,
+ self.recurse,
+ )
+ win32ui.WriteProfileVal("Grep", "Params", paramstr)
+
+ def setInitParams(self, paramstr):
+ if paramstr is None:
+ paramstr = win32ui.GetProfileVal("Grep", "Params", "\t\t\t1\t0\t0")
+ params = paramstr.split("\t")
+ if len(params) < 3:
+ params.extend([""] * (3 - len(params)))
+ if len(params) < 6:
+ params.extend([0] * (6 - len(params)))
+ self.dirpattern = params[0]
+ self.filpattern = params[1]
+ self.greppattern = params[2]
+ self.casesensitive = int(params[3])
+ self.recurse = int(params[4])
+ self.verbose = int(params[5])
+ # setup some reasonable defaults.
+ if not self.dirpattern:
+ try:
+ editor = win32ui.GetMainFrame().MDIGetActive()[0].GetEditorView()
+ self.dirpattern = os.path.abspath(
+ os.path.dirname(editor.GetDocument().GetPathName())
+ )
+ except (AttributeError, win32ui.error):
+ self.dirpattern = os.getcwd()
+ if not self.filpattern:
+ self.filpattern = "*.py"
+
+ def OnNewDocument(self):
+ if self.dirpattern == "":
+ self.setInitParams(greptemplate.readParams())
+ d = GrepDialog(
+ self.dirpattern,
+ self.filpattern,
+ self.greppattern,
+ self.casesensitive,
+ self.recurse,
+ self.verbose,
+ )
+ if d.DoModal() == win32con.IDOK:
+ self.dirpattern = d["dirpattern"]
+ self.filpattern = d["filpattern"]
+ self.greppattern = d["greppattern"]
+ self.casesensitive = d["casesensitive"]
+ self.recurse = d["recursive"]
+ self.verbose = d["verbose"]
+ self.doSearch()
+ self.saveInitParams()
+ return 1
+ return 0 # cancelled - return zero to stop frame creation.
+
+ def doSearch(self):
+ self.dp = dirpath(self.dirpattern, self.recurse)
+ self.SetTitle(f"Grep for {self.greppattern} in {self.filpattern}")
+ # self.text = []
+ self.GetFirstView().Append(f"#Search {self.dirpattern}\n")
+ if self.verbose:
+ self.GetFirstView().Append(f"# ={self.dp.dirs!r}\n")
+ self.GetFirstView().Append(f"# Files {self.filpattern}\n")
+ self.GetFirstView().Append(f"# For {self.greppattern}\n")
+ self.fplist = self.filpattern.split(";")
+ if self.casesensitive:
+ self.pat = re.compile(self.greppattern)
+ else:
+ self.pat = re.compile(self.greppattern, re.IGNORECASE)
+ win32ui.SetStatusText("Searching. Please wait...", 0)
+ self.dpndx = self.fpndx = 0
+ self.fndx = -1
+ if not self.dp:
+ self.GetFirstView().Append(
+ "# ERROR: '%s' does not resolve to any search locations"
+ % self.dirpattern
+ )
+ self.SetModifiedFlag(0)
+ else:
+ self.flist = glob.glob(self.dp[0] + "\\" + self.fplist[0])
+ win32ui.GetApp().AddIdleHandler(self.SearchFile)
+
+ def SearchFile(self, handler, count):
+ self.fndx += 1
+ if self.fndx < len(self.flist):
+ f = self.flist[self.fndx]
+ if self.verbose:
+ self.GetFirstView().Append("# .." + f + "\n")
+ # Directories may match the file type pattern, and files may be removed
+ # while grep is running
+ if os.path.isfile(f):
+ win32ui.SetStatusText("Searching " + f, 0)
+ lines = open(f, "r").readlines()
+ for i in range(len(lines)):
+ line = lines[i]
+ if self.pat.search(line) is not None:
+ self.GetFirstView().Append(f"{f} ({i + 1!r}) {line}")
+ else:
+ self.fndx = -1
+ self.fpndx += 1
+ if self.fpndx < len(self.fplist):
+ self.flist = glob.glob(
+ self.dp[self.dpndx] + "\\" + self.fplist[self.fpndx]
+ )
+ else:
+ self.fpndx = 0
+ self.dpndx += 1
+ if self.dpndx < len(self.dp):
+ self.flist = glob.glob(
+ self.dp[self.dpndx] + "\\" + self.fplist[self.fpndx]
+ )
+ else:
+ win32ui.SetStatusText("Search complete.", 0)
+ self.SetModifiedFlag(0) # default to not modified.
+ try:
+ win32ui.GetApp().DeleteIdleHandler(self.SearchFile)
+ except:
+ pass
+ return 0
+ return 1
+
+ def GetParams(self):
+ return "{}\t{}\t{}\t{!r}\t{!r}\t{!r}".format(
+ self.dirpattern,
+ self.filpattern,
+ self.greppattern,
+ self.casesensitive,
+ self.recurse,
+ self.verbose,
+ )
+
+ def OnSaveDocument(self, filename):
+ # print("OnSaveDocument() filename=", filename)
+ savefile = open(filename, "wb")
+ txt = self.GetParams() + "\n"
+ # print("writing", txt)
+ savefile.write(txt)
+ savefile.close()
+ self.SetModifiedFlag(0)
+ return 1
+
+
+ID_OPEN_FILE = 0xE400
+ID_GREP = 0xE401
+ID_SAVERESULTS = 0x402
+ID_TRYAGAIN = 0x403
+
+
+class GrepView(docview.RichEditView):
+ def __init__(self, doc):
+ docview.RichEditView.__init__(self, doc)
+ self.SetWordWrap(win32ui.CRichEditView_WrapNone)
+ self.HookHandlers()
+
+ def OnInitialUpdate(self):
+ rc = self._obj_.OnInitialUpdate()
+ format = (-402653169, 0, 200, 0, 0, 0, 49, "Courier New")
+ self.SetDefaultCharFormat(format)
+ return rc
+
+ def HookHandlers(self):
+ self.HookMessage(self.OnRClick, win32con.WM_RBUTTONDOWN)
+ self.HookCommand(self.OnCmdOpenFile, ID_OPEN_FILE)
+ self.HookCommand(self.OnCmdGrep, ID_GREP)
+ self.HookCommand(self.OnCmdSave, ID_SAVERESULTS)
+ self.HookCommand(self.OnTryAgain, ID_TRYAGAIN)
+ self.HookMessage(self.OnLDblClick, win32con.WM_LBUTTONDBLCLK)
+
+ def OnLDblClick(self, params):
+ line = self.GetLine()
+ regexGrepResult = regexGrep.match(line)
+ if regexGrepResult:
+ fname = regexGrepResult.group(1)
+ line = int(regexGrepResult.group(2))
+ scriptutils.JumpToDocument(fname, line)
+ return 0 # don't pass on
+ return 1 # pass it on by default.
+
+ def OnRClick(self, params):
+ menu = win32ui.CreatePopupMenu()
+ flags = win32con.MF_STRING | win32con.MF_ENABLED
+ lineno = self._obj_.LineFromChar(-1) # selection or current line
+ line = self._obj_.GetLine(lineno)
+ regexGrepResult = regexGrep.match(line)
+ if regexGrepResult:
+ self.fnm = regexGrepResult.group(1)
+ self.lnnum = int(regexGrepResult.group(2))
+ menu.AppendMenu(flags, ID_OPEN_FILE, "&Open " + self.fnm)
+ menu.AppendMenu(win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, ID_TRYAGAIN, "&Try Again")
+ charstart, charend = self._obj_.GetSel()
+ if charstart != charend:
+ linestart = self._obj_.LineIndex(lineno)
+ self.sel = line[charstart - linestart : charend - linestart]
+ menu.AppendMenu(flags, ID_GREP, "&Grep for " + self.sel)
+ menu.AppendMenu(win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, win32ui.ID_EDIT_CUT, "Cu&t")
+ menu.AppendMenu(flags, win32ui.ID_EDIT_COPY, "&Copy")
+ menu.AppendMenu(flags, win32ui.ID_EDIT_PASTE, "&Paste")
+ menu.AppendMenu(flags, win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, win32ui.ID_EDIT_SELECT_ALL, "&Select all")
+ menu.AppendMenu(flags, win32con.MF_SEPARATOR)
+ menu.AppendMenu(flags, ID_SAVERESULTS, "Sa&ve results")
+ menu.TrackPopupMenu(params[5])
+ return 0
+
+ def OnCmdOpenFile(self, cmd, code):
+ doc = win32ui.GetApp().OpenDocumentFile(self.fnm)
+ if doc:
+ vw = doc.GetFirstView()
+ # hope you have an editor that implements GotoLine()!
+ try:
+ vw.GotoLine(int(self.lnnum))
+ except:
+ pass
+ return 0
+
+ def OnCmdGrep(self, cmd, code):
+ if code != 0:
+ return 1
+ curparamsstr = self.GetDocument().GetParams()
+ params = curparamsstr.split("\t")
+ params[2] = self.sel
+ greptemplate.setParams("\t".join(params))
+ greptemplate.OpenDocumentFile()
+ return 0
+
+ def OnTryAgain(self, cmd, code):
+ if code != 0:
+ return 1
+ greptemplate.setParams(self.GetDocument().GetParams())
+ greptemplate.OpenDocumentFile()
+ return 0
+
+ def OnCmdSave(self, cmd, code):
+ if code != 0:
+ return 1
+ flags = win32con.OFN_OVERWRITEPROMPT
+ dlg = win32ui.CreateFileDialog(
+ 0, None, None, flags, "Text Files (*.txt)|*.txt||", self
+ )
+ dlg.SetOFNTitle("Save Results As")
+ if dlg.DoModal() == win32con.IDOK:
+ pn = dlg.GetPathName()
+ self._obj_.SaveTextFile(pn)
+ return 0
+
+ def Append(self, strng):
+ numlines = self.GetLineCount()
+ endpos = self.LineIndex(numlines - 1) + len(self.GetLine(numlines - 1))
+ self.SetSel(endpos, endpos)
+ self.ReplaceSel(strng)
+
+
+class GrepDialog(dialog.Dialog):
+ def __init__(self, dp, fp, gp, cs, r, v):
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ CS = win32con.WS_CHILD | win32con.WS_VISIBLE
+ tmp = [
+ ["Grep", (0, 0, 210, 90), style, None, (8, "MS Sans Serif")],
+ ]
+ tmp.append([STATIC, "Grep For:", -1, (7, 7, 50, 9), CS])
+ tmp.append(
+ [
+ EDIT,
+ gp,
+ 101,
+ (52, 7, 144, 11),
+ CS | win32con.WS_TABSTOP | win32con.ES_AUTOHSCROLL | win32con.WS_BORDER,
+ ]
+ )
+ tmp.append([STATIC, "Directories:", -1, (7, 20, 50, 9), CS])
+ tmp.append(
+ [
+ EDIT,
+ dp,
+ 102,
+ (52, 20, 128, 11),
+ CS | win32con.WS_TABSTOP | win32con.ES_AUTOHSCROLL | win32con.WS_BORDER,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "...",
+ 110,
+ (182, 20, 16, 11),
+ CS | win32con.BS_PUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append([STATIC, "File types:", -1, (7, 33, 50, 9), CS])
+ tmp.append(
+ [
+ EDIT,
+ fp,
+ 103,
+ (52, 33, 128, 11),
+ CS | win32con.WS_TABSTOP | win32con.ES_AUTOHSCROLL | win32con.WS_BORDER,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "...",
+ 111,
+ (182, 33, 16, 11),
+ CS | win32con.BS_PUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "Case sensitive",
+ 104,
+ (7, 45, 72, 9),
+ CS
+ | win32con.BS_AUTOCHECKBOX
+ | win32con.BS_LEFTTEXT
+ | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "Subdirectories",
+ 105,
+ (7, 56, 72, 9),
+ CS
+ | win32con.BS_AUTOCHECKBOX
+ | win32con.BS_LEFTTEXT
+ | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "Verbose",
+ 106,
+ (7, 67, 72, 9),
+ CS
+ | win32con.BS_AUTOCHECKBOX
+ | win32con.BS_LEFTTEXT
+ | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "OK",
+ win32con.IDOK,
+ (166, 53, 32, 12),
+ CS | win32con.BS_DEFPUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "Cancel",
+ win32con.IDCANCEL,
+ (166, 67, 32, 12),
+ CS | win32con.BS_PUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ dialog.Dialog.__init__(self, tmp)
+ self.AddDDX(101, "greppattern")
+ self.AddDDX(102, "dirpattern")
+ self.AddDDX(103, "filpattern")
+ self.AddDDX(104, "casesensitive")
+ self.AddDDX(105, "recursive")
+ self.AddDDX(106, "verbose")
+ self._obj_.data["greppattern"] = gp
+ self._obj_.data["dirpattern"] = dp
+ self._obj_.data["filpattern"] = fp
+ self._obj_.data["casesensitive"] = cs
+ self._obj_.data["recursive"] = r
+ self._obj_.data["verbose"] = v
+ self.HookCommand(self.OnMoreDirectories, 110)
+ self.HookCommand(self.OnMoreFiles, 111)
+
+ def OnMoreDirectories(self, cmd, code):
+ if code != 0:
+ return 1
+ self.getMore("Grep\\Directories", "dirpattern")
+
+ def OnMoreFiles(self, cmd, code):
+ if code != 0:
+ return 1
+ self.getMore("Grep\\File Types", "filpattern")
+
+ def getMore(self, section, key):
+ self.UpdateData(1)
+ # get the items out of the ini file
+ ini = win32ui.GetProfileFileName()
+ secitems = win32api.GetProfileSection(section, ini)
+ items = []
+ for secitem in secitems:
+ items.append(secitem.split("=")[1])
+ dlg = GrepParamsDialog(items)
+ if dlg.DoModal() == win32con.IDOK:
+ itemstr = ";".join(dlg.getItems())
+ self._obj_.data[key] = itemstr
+ # update the ini file with dlg.getNew()
+ i = 0
+ newitems = dlg.getNew()
+ if newitems:
+ items.extend(newitems)
+ for item in items:
+ win32api.WriteProfileVal(section, repr(i), item, ini)
+ i += 1
+ self.UpdateData(0)
+
+ def OnOK(self):
+ self.UpdateData(1)
+ for id, name in (
+ (101, "greppattern"),
+ (102, "dirpattern"),
+ (103, "filpattern"),
+ ):
+ if not self[name]:
+ self.GetDlgItem(id).SetFocus()
+ win32api.MessageBeep()
+ win32ui.SetStatusText("Please enter a value")
+ return
+ self._obj_.OnOK()
+
+
+class GrepParamsDialog(dialog.Dialog):
+ def __init__(self, items):
+ self.items = items
+ self.newitems = []
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ CS = win32con.WS_CHILD | win32con.WS_VISIBLE
+ tmp = [
+ ["Grep Parameters", (0, 0, 205, 100), style, None, (8, "MS Sans Serif")],
+ ]
+ tmp.append(
+ [
+ LISTBOX,
+ "",
+ 107,
+ (7, 7, 150, 72),
+ CS
+ | win32con.LBS_MULTIPLESEL
+ | win32con.LBS_STANDARD
+ | win32con.LBS_HASSTRINGS
+ | win32con.WS_TABSTOP
+ | win32con.LBS_NOTIFY,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "OK",
+ win32con.IDOK,
+ (167, 7, 32, 12),
+ CS | win32con.BS_DEFPUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "Cancel",
+ win32con.IDCANCEL,
+ (167, 23, 32, 12),
+ CS | win32con.BS_PUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ tmp.append([STATIC, "New:", -1, (2, 83, 15, 12), CS])
+ tmp.append(
+ [
+ EDIT,
+ "",
+ 108,
+ (18, 83, 139, 12),
+ CS | win32con.WS_TABSTOP | win32con.ES_AUTOHSCROLL | win32con.WS_BORDER,
+ ]
+ )
+ tmp.append(
+ [
+ BUTTON,
+ "Add",
+ 109,
+ (167, 83, 32, 12),
+ CS | win32con.BS_PUSHBUTTON | win32con.WS_TABSTOP,
+ ]
+ )
+ dialog.Dialog.__init__(self, tmp)
+ self.HookCommand(self.OnAddItem, 109)
+ self.HookCommand(self.OnListDoubleClick, 107)
+
+ def OnInitDialog(self):
+ lb = self.GetDlgItem(107)
+ for item in self.items:
+ lb.AddString(item)
+ return self._obj_.OnInitDialog()
+
+ def OnAddItem(self, cmd, code):
+ if code != 0:
+ return 1
+ eb = self.GetDlgItem(108)
+ item = eb.GetLine(0)
+ self.newitems.append(item)
+ lb = self.GetDlgItem(107)
+ i = lb.AddString(item)
+ lb.SetSel(i, 1)
+ return 1
+
+ def OnListDoubleClick(self, cmd, code):
+ if code == win32con.LBN_DBLCLK:
+ self.OnOK()
+ return 1
+
+ def OnOK(self):
+ lb = self.GetDlgItem(107)
+ self.selections = lb.GetSelTextItems()
+ self._obj_.OnOK()
+
+ def getItems(self):
+ return self.selections
+
+ def getNew(self):
+ return self.newitems
+
+
+try:
+ win32ui.GetApp().RemoveDocTemplate(greptemplate) # type: ignore[has-type, used-before-def]
+except NameError:
+ pass
+
+greptemplate = GrepTemplate()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/startup.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/startup.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dc7d556748c2a548c66fe2414b495cdebb5a33c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/startup.py
@@ -0,0 +1,70 @@
+# startup.py
+#
+"The main application startup code for PythonWin."
+
+#
+# This does the basic command line handling.
+
+# Keep this as short as possible, cos error output is only redirected if
+# this runs OK. Errors in imported modules are much better - the messages go somewhere (not any more :-)
+
+import os
+import sys
+
+import win32api
+import win32ui
+
+if not sys.argv:
+ # Initialize sys.argv from commandline. When sys.argv is empty list (
+ # different from [''] meaning "no cmd line arguments" ), then C
+ # bootstrapping or another method of invocation failed to initialize
+ # sys.argv and it will be done here. ( This was a workaround for a bug in
+ # win32ui but is retained for other situations. )
+ argv = win32api.CommandLineToArgv(win32api.GetCommandLine())
+ sys.argv = argv[1:]
+ if os.getcwd() not in sys.path and "." not in sys.path:
+ sys.path.insert(0, os.getcwd())
+
+# You may wish to redirect error output somewhere useful if you have startup errors.
+# eg, 'import win32traceutil' will do this for you.
+# import win32traceutil # Just uncomment this line to see error output!
+
+# An old class I used to use - generally only useful if Pythonwin is running under MSVC
+# class DebugOutput:
+# softspace=1
+# def write(self,message):
+# win32ui.OutputDebug(message)
+# sys.stderr=sys.stdout=DebugOutput()
+
+# To fix a problem with Pythonwin when started from the Pythonwin directory,
+# we update the pywin path to ensure it is absolute.
+# If it is indeed relative, it will be relative to our current directory.
+# If it's already absolute, then this will have no affect.
+import pywin
+import pywin.framework
+
+# Ensure we're working on __path__ as list, not Iterable
+pywin.__path__ = list(pywin.__path__)
+pywin.framework.__path__ = list(pywin.framework.__path__)
+
+pywin.__path__[0] = win32ui.FullPath(pywin.__path__[0])
+pywin.framework.__path__[0] = win32ui.FullPath(pywin.framework.__path__[0])
+
+# make a few weird sys values. This is so later we can clobber sys.argv to trick
+# scripts when running under a GUI environment.
+
+moduleName = "pywin.framework.intpyapp"
+sys.appargvoffset = 0
+sys.appargv = sys.argv[:]
+# Must check for /app param here.
+if len(sys.argv) >= 2 and sys.argv[0].lower() in ("/app", "-app"):
+ from . import cmdline
+
+ moduleName = cmdline.FixArgFileName(sys.argv[1])
+ sys.appargvoffset = 2
+ newargv = sys.argv[sys.appargvoffset :]
+ # newargv.insert(0, sys.argv[0])
+ sys.argv = newargv
+
+# Import the application module.
+__import__(moduleName)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/stdin.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/stdin.py
new file mode 100644
index 0000000000000000000000000000000000000000..19cd2286a2621687ef4c818a31a98bbbcbbc47ed
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/stdin.py
@@ -0,0 +1,172 @@
+# Copyright (c) 2000 David Abrahams. Permission to copy, use, modify, sell
+# and distribute this software is granted provided this copyright
+# notice appears in all copies. This software is provided "as is" without
+# express or implied warranty, and with no claim as to its suitability for
+# any purpose.
+"""Provides a class Stdin which can be used to emulate the regular old
+sys.stdin for the PythonWin interactive window. Right now it just pops
+up a input() dialog. With luck, someone will integrate it into the
+actual PythonWin interactive window someday.
+
+WARNING: Importing this file automatically replaces sys.stdin with an
+instance of Stdin (below). This is useful because you can just open
+Stdin.py in PythonWin and hit the import button to get it set up right
+if you don't feel like changing PythonWin's source. To put things back
+the way they were, simply use this magic incantation:
+ import sys
+ sys.stdin = sys.stdin.real_file
+"""
+
+import sys
+
+get_input_line = input
+
+
+class Stdin:
+ def __init__(self):
+ self.real_file = sys.stdin # NOTE: Likely to be None
+ self.buffer = ""
+ self.closed = False
+
+ def __getattr__(self, name):
+ """Forward most functions to the real sys.stdin for absolute realism."""
+ if self.real_file is None:
+ raise AttributeError(name)
+ return getattr(self.real_file, name)
+
+ def isatty(self):
+ """Return 1 if the file is connected to a tty(-like) device, else 0."""
+ return 1
+
+ def read(self, size=-1):
+ """Read at most size bytes from the file (less if the read
+ hits EOF or no more data is immediately available on a pipe,
+ tty or similar device). If the size argument is negative or
+ omitted, read all data until EOF is reached. The bytes are
+ returned as a string object. An empty string is returned when
+ EOF is encountered immediately. (For certain files, like ttys,
+ it makes sense to continue reading after an EOF is hit.)"""
+ result_size = self.__get_lines(size)
+ return self.__extract_from_buffer(result_size)
+
+ def readline(self, size=-1):
+ """Read one entire line from the file. A trailing newline
+ character is kept in the string2.6 (but may be absent when a file ends
+ with an incomplete line). If the size argument is present and
+ non-negative, it is a maximum byte count (including the trailing
+ newline) and an incomplete line may be returned. An empty string is
+ returned when EOF is hit immediately. Note: unlike stdio's fgets(),
+ the returned string contains null characters ('\0') if they occurred
+ in the input.
+ """
+ maximum_result_size = self.__get_lines(size, lambda buffer: "\n" in buffer)
+
+ if "\n" in self.buffer[:maximum_result_size]:
+ result_size = self.buffer.find("\n", 0, maximum_result_size) + 1
+ assert result_size > 0
+ else:
+ result_size = maximum_result_size
+
+ return self.__extract_from_buffer(result_size)
+
+ def __extract_from_buffer(self, character_count):
+ """Remove the first character_count characters from the internal buffer and
+ return them.
+ """
+ result = self.buffer[:character_count]
+ self.buffer = self.buffer[character_count:]
+ return result
+
+ def __get_lines(self, desired_size, done_reading=lambda buffer: False):
+ """Keep adding lines to our internal buffer until done_reading(self.buffer)
+ is true or EOF has been reached or we have desired_size bytes in the buffer.
+ If desired_size < 0, we are never satisfied until we reach EOF. If done_reading
+ is not supplied, it is not consulted.
+
+ If desired_size < 0, returns the length of the internal buffer. Otherwise,
+ returns desired_size.
+ """
+ while not done_reading(self.buffer) and (
+ desired_size < 0 or len(self.buffer) < desired_size
+ ):
+ try:
+ self.__get_line()
+ except (
+ EOFError,
+ KeyboardInterrupt,
+ ): # deal with cancellation of get_input_line dialog
+ desired_size = len(self.buffer) # Be satisfied!
+
+ if desired_size < 0:
+ return len(self.buffer)
+ else:
+ return desired_size
+
+ def __get_line(self):
+ """Grab one line from get_input_line() and append it to the buffer."""
+ line = get_input_line()
+ print(">>>", line) # echo input to console
+ self.buffer = self.buffer + line + "\n"
+
+ def readlines(self, *sizehint):
+ """Read until EOF using readline() and return a list containing the lines
+ thus read. If the optional sizehint argument is present, instead of
+ reading up to EOF, whole lines totalling approximately sizehint bytes
+ (possibly after rounding up to an internal buffer size) are read.
+ """
+ result = []
+ total_read = 0
+ while sizehint == () or total_read < sizehint[0]:
+ line = self.readline()
+ if line == "":
+ break
+ total_read += len(line)
+ result.append(line)
+ return result
+
+
+if __name__ == "__main__":
+ test_input = r"""this is some test
+input that I am hoping
+~
+will be very instructive
+and when I am done
+I will have tested everything.
+Twelve and twenty blackbirds
+baked in a pie. Patty cake
+patty cake so am I.
+~
+Thirty-five niggling idiots!
+Sell you soul to the devil, baby
+"""
+
+ def fake_input(prompt=None):
+ """Replacement for input() which pulls lines out of global test_input.
+ For testing only!
+ """
+ global test_input
+ if "\n" not in test_input:
+ end_of_line_pos = len(test_input)
+ else:
+ end_of_line_pos = test_input.find("\n")
+ result = test_input[:end_of_line_pos]
+ test_input = test_input[end_of_line_pos + 1 :]
+ if len(result) == 0 or result[0] == "~":
+ raise EOFError
+ return result
+
+ get_input_line = fake_input
+
+ # Some completely inadequate tests, just to make sure the code's not totally broken
+ try:
+ x = Stdin()
+ print(x.read())
+ print(x.readline())
+ print(x.read(12))
+ print(x.readline(47))
+ print(x.readline(3))
+ print(x.readlines())
+ finally:
+ get_input_line = input
+else:
+ sys.stdin = Stdin()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/toolmenu.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/toolmenu.py
new file mode 100644
index 0000000000000000000000000000000000000000..89c17e7618e500ab9f43e84e26039f5e70334d03
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/toolmenu.py
@@ -0,0 +1,279 @@
+# toolmenu.py
+
+import sys
+
+import win32api
+import win32con
+import win32ui
+
+tools = {}
+idPos = 100
+
+# The default items should no tools menu exist in the INI file.
+defaultToolMenuItems = [
+ ("Browser", "win32ui.GetApp().OnViewBrowse(0,0)"),
+ (
+ "Browse PythonPath",
+ "from pywin.tools import browseProjects;browseProjects.Browse()",
+ ),
+ ("Edit Python Path", "from pywin.tools import regedit;regedit.EditRegistry()"),
+ ("COM Makepy utility", "from win32com.client import makepy;makepy.main()"),
+ (
+ "COM Browser",
+ "from win32com.client import combrowse;combrowse.main(modal=False)",
+ ),
+ (
+ "Trace Collector Debugging tool",
+ "from pywin.tools import TraceCollector;TraceCollector.MakeOutputWindow()",
+ ),
+]
+
+
+def LoadToolMenuItems():
+ # Load from the registry.
+ items = []
+ lookNo = 1
+ while 1:
+ menu = win32ui.GetProfileVal("Tools Menu\\%s" % lookNo, "", "")
+ if menu == "":
+ break
+ cmd = win32ui.GetProfileVal("Tools Menu\\%s" % lookNo, "Command", "")
+ items.append((menu, cmd))
+ lookNo += 1
+
+ if len(items) == 0:
+ items = defaultToolMenuItems
+ return items
+
+
+def WriteToolMenuItems(items):
+ # Items is a list of (menu, command)
+ # Delete the entire registry tree.
+ try:
+ mainKey = win32ui.GetAppRegistryKey()
+ toolKey = win32api.RegOpenKey(mainKey, "Tools Menu")
+ except win32ui.error:
+ toolKey = None
+ if toolKey is not None:
+ while 1:
+ try:
+ subkey = win32api.RegEnumKey(toolKey, 0)
+ except win32api.error:
+ break
+ win32api.RegDeleteKey(toolKey, subkey)
+ # Keys are now removed - write the new ones.
+ # But first check if we have the defaults - and if so, don't write anything!
+ if items == defaultToolMenuItems:
+ return
+ itemNo = 1
+ for menu, cmd in items:
+ win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "", menu)
+ win32ui.WriteProfileVal("Tools Menu\\%s" % itemNo, "Command", cmd)
+ itemNo += 1
+
+
+def SetToolsMenu(menu, menuPos=None):
+ global tools
+ global idPos
+
+ # todo - check the menu does not already exist.
+ # Create the new menu
+ toolsMenu = win32ui.CreatePopupMenu()
+
+ # Load from the ini file.
+ items = LoadToolMenuItems()
+ for menuString, cmd in items:
+ tools[idPos] = (menuString, cmd, menuString)
+ toolsMenu.AppendMenu(
+ win32con.MF_ENABLED | win32con.MF_STRING, idPos, menuString
+ )
+ win32ui.GetMainFrame().HookCommand(HandleToolCommand, idPos)
+ idPos += 1
+
+ # Find the correct spot to insert the new tools menu.
+ if menuPos is None:
+ menuPos = menu.GetMenuItemCount() - 2
+ if menuPos < 0:
+ menuPos = 0
+
+ menu.InsertMenu(
+ menuPos,
+ win32con.MF_BYPOSITION
+ | win32con.MF_ENABLED
+ | win32con.MF_STRING
+ | win32con.MF_POPUP,
+ toolsMenu.GetHandle(),
+ "&Tools",
+ )
+
+
+def HandleToolCommand(cmd, code):
+ import re
+ import traceback
+
+ global tools
+ (menuString, pyCmd, desc) = tools[cmd]
+ win32ui.SetStatusText("Executing tool %s" % desc, 1)
+ pyCmd = re.sub(r"\\n", "\n", pyCmd)
+ win32ui.DoWaitCursor(1)
+ oldFlag = None
+ try:
+ oldFlag = sys.stdout.template.writeQueueing
+ sys.stdout.template.writeQueueing = 0
+ except (NameError, AttributeError):
+ pass
+
+ try:
+ exec("%s\n" % pyCmd)
+ worked = 1
+ except SystemExit:
+ # The program raised a SystemExit - ignore it.
+ worked = 1
+ except:
+ print("Failed to execute command:\n%s" % pyCmd)
+ traceback.print_exc()
+ worked = 0
+ if oldFlag is not None:
+ sys.stdout.template.writeQueueing = oldFlag
+ win32ui.DoWaitCursor(0)
+ if worked:
+ text = "Completed successfully."
+ else:
+ text = "Error executing %s." % desc
+ win32ui.SetStatusText(text, 1)
+
+
+# The property page for maintaing the items on the Tools menu.
+import commctrl
+from pywin.mfc import dialog
+
+LVN_ENDLABELEDIT = commctrl.LVN_ENDLABELEDITW
+
+
+class ToolMenuPropPage(dialog.PropertyPage):
+ def __init__(self):
+ self.bImChangingEditControls = 0 # Am I programatically changing the controls?
+ dialog.PropertyPage.__init__(self, win32ui.IDD_PP_TOOLMENU)
+
+ def OnInitDialog(self):
+ self.editMenuCommand = self.GetDlgItem(win32ui.IDC_EDIT2)
+ self.butNew = self.GetDlgItem(win32ui.IDC_BUTTON3)
+
+ # Now hook the change notification messages for the edit controls.
+ self.HookCommand(self.OnCommandEditControls, win32ui.IDC_EDIT1)
+ self.HookCommand(self.OnCommandEditControls, win32ui.IDC_EDIT2)
+
+ self.HookNotify(self.OnNotifyListControl, commctrl.LVN_ITEMCHANGED)
+ self.HookNotify(self.OnNotifyListControlEndLabelEdit, commctrl.LVN_ENDLABELEDIT)
+
+ # Hook the button clicks.
+ self.HookCommand(self.OnButtonNew, win32ui.IDC_BUTTON3) # New Item
+ self.HookCommand(self.OnButtonDelete, win32ui.IDC_BUTTON4) # Delete item
+ self.HookCommand(self.OnButtonMove, win32ui.IDC_BUTTON1) # Move up
+ self.HookCommand(self.OnButtonMove, win32ui.IDC_BUTTON2) # Move down
+
+ # Setup the columns in the list control
+ lc = self.GetDlgItem(win32ui.IDC_LIST1)
+ rect = lc.GetWindowRect()
+ cx = rect[2] - rect[0]
+ colSize = cx / 2 - win32api.GetSystemMetrics(win32con.SM_CXBORDER) - 1
+
+ item = commctrl.LVCFMT_LEFT, colSize, "Menu Text"
+ lc.InsertColumn(0, item)
+
+ item = commctrl.LVCFMT_LEFT, colSize, "Python Command"
+ lc.InsertColumn(1, item)
+
+ # Insert the existing tools menu
+ itemNo = 0
+ for desc, cmd in LoadToolMenuItems():
+ lc.InsertItem(itemNo, desc)
+ lc.SetItemText(itemNo, 1, cmd)
+ itemNo += 1
+
+ self.listControl = lc
+ return dialog.PropertyPage.OnInitDialog(self)
+
+ def OnOK(self):
+ # Write the menu back to the registry.
+ items = []
+ itemLook = 0
+ while 1:
+ try:
+ text = self.listControl.GetItemText(itemLook, 0)
+ if not text:
+ break
+ items.append((text, self.listControl.GetItemText(itemLook, 1)))
+ except win32ui.error:
+ # no more items!
+ break
+ itemLook += 1
+ WriteToolMenuItems(items)
+ return self._obj_.OnOK()
+
+ def OnCommandEditControls(self, id, cmd):
+ # print("OnEditControls", id, cmd)
+ if cmd == win32con.EN_CHANGE and not self.bImChangingEditControls:
+ itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ newText = self.editMenuCommand.GetWindowText()
+ self.listControl.SetItemText(itemNo, 1, newText)
+
+ return 0
+
+ def OnNotifyListControlEndLabelEdit(self, id, cmd):
+ newText = self.listControl.GetEditControl().GetWindowText()
+ itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ self.listControl.SetItemText(itemNo, 0, newText)
+
+ def OnNotifyListControl(self, id, cmd):
+ # print(id, cmd)
+ try:
+ itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ except win32ui.error: # No selection!
+ return
+
+ self.bImChangingEditControls = 1
+ try:
+ item = self.listControl.GetItem(itemNo, 1)
+ self.editMenuCommand.SetWindowText(item[4])
+ finally:
+ self.bImChangingEditControls = 0
+
+ return 0 # we have handled this!
+
+ def OnButtonNew(self, id, cmd):
+ if cmd == win32con.BN_CLICKED:
+ newIndex = self.listControl.GetItemCount()
+ self.listControl.InsertItem(newIndex, "Click to edit the text")
+ self.listControl.EnsureVisible(newIndex, 0)
+
+ def OnButtonMove(self, id, cmd):
+ if cmd == win32con.BN_CLICKED:
+ try:
+ itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ except win32ui.error:
+ return
+ menu = self.listControl.GetItemText(itemNo, 0)
+ cmd = self.listControl.GetItemText(itemNo, 1)
+ if id == win32ui.IDC_BUTTON1:
+ # Move up
+ if itemNo > 0:
+ self.listControl.DeleteItem(itemNo)
+ # reinsert it.
+ self.listControl.InsertItem(itemNo - 1, menu)
+ self.listControl.SetItemText(itemNo - 1, 1, cmd)
+ else:
+ # Move down.
+ if itemNo < self.listControl.GetItemCount() - 1:
+ self.listControl.DeleteItem(itemNo)
+ # reinsert it.
+ self.listControl.InsertItem(itemNo + 1, menu)
+ self.listControl.SetItemText(itemNo + 1, 1, cmd)
+
+ def OnButtonDelete(self, id, cmd):
+ if cmd == win32con.BN_CLICKED:
+ try:
+ itemNo = self.listControl.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ except win32ui.error: # No selection!
+ return
+ self.listControl.DeleteItem(itemNo)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/window.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/window.py
new file mode 100644
index 0000000000000000000000000000000000000000..0652cb5da1fdbc7578e75fd5fe6e353732220c6c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/window.py
@@ -0,0 +1,14 @@
+# Framework Window classes.
+
+# Most Pythonwin windows should use these classes rather than
+# the raw MFC ones if they want Pythonwin specific functionality.
+import pywin.mfc.window
+import win32con
+
+
+class MDIChildWnd(pywin.mfc.window.MDIChildWnd):
+ def AutoRestore(self):
+ "If the window is minimised or maximised, restore it."
+ p = self.GetWindowPlacement()
+ if p[1] == win32con.SW_MINIMIZE or p[1] == win32con.SW_SHOWMINIMIZED:
+ self.SetWindowPlacement(p[0], win32con.SW_RESTORE, p[2], p[3], p[4])
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/framework/winout.py b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/winout.py
new file mode 100644
index 0000000000000000000000000000000000000000..3c36b9fc4cc2bc71c4a824551c0445f39bcb1f18
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/framework/winout.py
@@ -0,0 +1,589 @@
+# winout.py
+#
+# generic "output window"
+#
+# This Window will detect itself closing, and recreate next time output is
+# written to it.
+
+# This has the option of writing output at idle time (by hooking the
+# idle message, and queueing output) or writing as each
+# write is executed.
+# Updating the window directly gives a jerky appearance as many writes
+# take place between commands, and the windows scrolls, and updates etc
+# Updating at idle-time may defer all output of a long process, giving the
+# appearence nothing is happening.
+# There is a compromise "line" mode, which will output whenever
+# a complete line is available.
+
+# behaviour depends on self.writeQueueing
+
+# This module is thread safe - output can originate from any thread. If any thread
+# other than the main thread attempts to print, it is always queued until next idle time
+
+import queue
+import re
+
+import pywin.scintilla.document
+import win32api
+import win32con
+import win32ui
+from pywin.framework import app, window
+from pywin.mfc import docview
+from pywin.scintilla import scintillacon
+
+debug = lambda msg: None
+# debug=win32ui.OutputDebugString
+# import win32trace;win32trace.InitWrite() # for debugging - delete me!
+# debug = win32trace.write
+# WindowOutputDocumentParent=docview.RichEditDoc
+# WindowOutputDocumentParent=docview.Document
+WindowOutputDocumentParent = pywin.scintilla.document.CScintillaDocument
+
+
+class flags:
+ # queueing of output.
+ WQ_NONE = 0
+ WQ_LINE = 1
+ WQ_IDLE = 2
+
+
+class WindowOutputDocument(WindowOutputDocumentParent):
+ def SaveModified(self):
+ return 1 # say it is OK to destroy my document
+
+ def OnSaveDocument(self, fileName):
+ win32ui.SetStatusText("Saving file...", 1)
+ try:
+ self.SaveFile(fileName)
+ except OSError as details:
+ win32ui.MessageBox("Error - could not save file\r\n\r\n%s" % details)
+ return 0
+ win32ui.SetStatusText("Ready")
+ return 1
+
+
+class WindowOutputFrame(window.MDIChildWnd):
+ def __init__(self, wnd=None):
+ window.MDIChildWnd.__init__(self, wnd)
+ self.HookMessage(self.OnSizeMove, win32con.WM_SIZE)
+ self.HookMessage(self.OnSizeMove, win32con.WM_MOVE)
+
+ def LoadFrame(self, idResource, style, wndParent, context):
+ self.template = context.template
+ return self._obj_.LoadFrame(idResource, style, wndParent, context)
+
+ def PreCreateWindow(self, cc):
+ cc = self._obj_.PreCreateWindow(cc)
+ if (
+ self.template.defSize
+ and self.template.defSize[0] != self.template.defSize[1]
+ ):
+ rect = app.RectToCreateStructRect(self.template.defSize)
+ cc = cc[0], cc[1], cc[2], cc[3], rect, cc[5], cc[6], cc[7], cc[8]
+ return cc
+
+ def OnSizeMove(self, msg):
+ # so recreate maintains position.
+ # Need to map coordinates from the
+ # frame windows first child.
+ mdiClient = self.GetParent()
+ self.template.defSize = mdiClient.ScreenToClient(self.GetWindowRect())
+
+ def OnDestroy(self, message):
+ self.template.OnFrameDestroy(self)
+ return 1
+
+
+class WindowOutputViewImpl:
+ def __init__(self):
+ self.patErrorMessage = re.compile(r'\W*File "(.*)", line ([0-9]+)')
+ self.template = self.GetDocument().GetDocTemplate()
+
+ def HookHandlers(self):
+ # Hook for the right-click menu.
+ self.HookMessage(self.OnRClick, win32con.WM_RBUTTONDOWN)
+
+ def OnDestroy(self, msg):
+ self.template.OnViewDestroy(self)
+
+ def OnInitialUpdate(self):
+ self.RestoreKillBuffer()
+ self.SetSel(-2) # end of buffer
+
+ def GetRightMenuItems(self):
+ ret = []
+ flags = win32con.MF_STRING | win32con.MF_ENABLED
+ ret.append((flags, win32ui.ID_EDIT_COPY, "&Copy"))
+ ret.append((flags, win32ui.ID_EDIT_SELECT_ALL, "&Select all"))
+ return ret
+
+ #
+ # Windows command handlers, virtuals, etc.
+ #
+ def OnRClick(self, params):
+ paramsList = self.GetRightMenuItems()
+ menu = win32ui.CreatePopupMenu()
+ for appendParams in paramsList:
+ if not isinstance(appendParams, tuple):
+ appendParams = (appendParams,)
+ menu.AppendMenu(*appendParams)
+ menu.TrackPopupMenu(params[5]) # track at mouse position.
+ return 0
+
+ # as this is often used as an output window, exeptions will often
+ # be printed. Therefore, we support this functionality at this level.
+ # Returns TRUE if the current line is an error message line, and will
+ # jump to it. FALSE if no error (and no action taken)
+ def HandleSpecialLine(self):
+ from . import scriptutils
+
+ line = self.GetLine()
+ if line[:11] == "com_error: ":
+ # An OLE Exception - pull apart the exception
+ # and try and locate a help file.
+ try:
+ import win32api
+ import win32con
+
+ det = eval(line[line.find(":") + 1 :].strip())
+ win32ui.SetStatusText("Opening help file on OLE error...")
+ from . import help
+
+ help.OpenHelpFile(det[2][3], win32con.HELP_CONTEXT, det[2][4])
+ return 1
+ except win32api.error as details:
+ win32ui.SetStatusText(
+ "The help file could not be opened - %s" % details.strerror
+ )
+ return 1
+ except:
+ win32ui.SetStatusText(
+ "Line is a COM error, but no WinHelp details can be parsed"
+ )
+ # Look for a Python traceback.
+ matchResult = self.patErrorMessage.match(line)
+ if matchResult is None:
+ # No match - try the previous line
+ lineNo = self.LineFromChar()
+ if lineNo > 0:
+ line = self.GetLine(lineNo - 1)
+ matchResult = self.patErrorMessage.match(line)
+ if matchResult is not None:
+ # we have an error line.
+ fileName = matchResult.group(1)
+ if fileName[0] == "<":
+ win32ui.SetStatusText("Can not load this file")
+ return 1 # still was an error message.
+ else:
+ lineNoString = matchResult.group(2)
+ # Attempt to locate the file (in case it is a relative spec)
+ fileNameSpec = fileName
+ fileName = scriptutils.LocatePythonFile(fileName)
+ if fileName is None:
+ # Don't force update, so it replaces the idle prompt.
+ win32ui.SetStatusText(
+ "Can't locate the file '%s'" % (fileNameSpec), 0
+ )
+ return 1
+
+ win32ui.SetStatusText(
+ "Jumping to line " + lineNoString + " of file " + fileName, 1
+ )
+ if not scriptutils.JumpToDocument(fileName, int(lineNoString)):
+ win32ui.SetStatusText("Could not open %s" % fileName)
+ return 1 # still was an error message.
+ return 1
+ return 0 # not an error line
+
+ def write(self, msg):
+ return self.template.write(msg)
+
+ def writelines(self, lines):
+ for line in lines:
+ self.write(line)
+
+ def flush(self):
+ self.template.flush()
+
+
+class WindowOutputViewRTF(docview.RichEditView, WindowOutputViewImpl):
+ def __init__(self, doc):
+ docview.RichEditView.__init__(self, doc)
+ WindowOutputViewImpl.__init__(self)
+
+ def OnInitialUpdate(self):
+ WindowOutputViewImpl.OnInitialUpdate(self)
+ return docview.RichEditView.OnInitialUpdate(self)
+
+ def OnDestroy(self, msg):
+ WindowOutputViewImpl.OnDestroy(self, msg)
+ docview.RichEditView.OnDestroy(self, msg)
+
+ def HookHandlers(self):
+ WindowOutputViewImpl.HookHandlers(self)
+ # Hook for finding and locating error messages
+ self.HookMessage(self.OnLDoubleClick, win32con.WM_LBUTTONDBLCLK)
+
+ # docview.RichEditView.HookHandlers(self)
+
+ def OnLDoubleClick(self, params):
+ if self.HandleSpecialLine():
+ return 0 # don't pass on
+ return 1 # pass it on by default.
+
+ def RestoreKillBuffer(self):
+ if len(self.template.killBuffer):
+ self.StreamIn(win32con.SF_RTF, self._StreamRTFIn)
+ self.template.killBuffer = []
+
+ def SaveKillBuffer(self):
+ self.StreamOut(win32con.SF_RTFNOOBJS, self._StreamRTFOut)
+
+ def _StreamRTFOut(self, data):
+ self.template.killBuffer.append(data)
+ return 1 # keep em coming!
+
+ def _StreamRTFIn(self, bytes):
+ try:
+ item = self.template.killBuffer[0]
+ self.template.killBuffer.remove(item)
+ if bytes < len(item):
+ print("Warning - output buffer not big enough!")
+ return item
+ except IndexError:
+ return None
+
+ def dowrite(self, str):
+ self.SetSel(-2)
+ self.ReplaceSel(str)
+
+
+import pywin.scintilla.view
+
+
+class WindowOutputViewScintilla(
+ pywin.scintilla.view.CScintillaView, WindowOutputViewImpl
+):
+ def __init__(self, doc):
+ pywin.scintilla.view.CScintillaView.__init__(self, doc)
+ WindowOutputViewImpl.__init__(self)
+
+ def OnInitialUpdate(self):
+ pywin.scintilla.view.CScintillaView.OnInitialUpdate(self)
+ self.SCISetMarginWidth(3)
+ WindowOutputViewImpl.OnInitialUpdate(self)
+
+ def OnDestroy(self, msg):
+ WindowOutputViewImpl.OnDestroy(self, msg)
+ pywin.scintilla.view.CScintillaView.OnDestroy(self, msg)
+
+ def HookHandlers(self):
+ WindowOutputViewImpl.HookHandlers(self)
+ pywin.scintilla.view.CScintillaView.HookHandlers(self)
+ self.GetParent().HookNotify(
+ self.OnScintillaDoubleClick, scintillacon.SCN_DOUBLECLICK
+ )
+
+ ## self.HookMessage(self.OnLDoubleClick,win32con.WM_LBUTTONDBLCLK)
+
+ def OnScintillaDoubleClick(self, std, extra):
+ self.HandleSpecialLine()
+
+ ## def OnLDoubleClick(self,params):
+ ## return 0 # never don't pass on
+
+ def RestoreKillBuffer(self):
+ assert len(self.template.killBuffer) in (0, 1), "Unexpected killbuffer contents"
+ if self.template.killBuffer:
+ self.SCIAddText(self.template.killBuffer[0])
+ self.template.killBuffer = []
+
+ def SaveKillBuffer(self):
+ self.template.killBuffer = [self.GetTextRange(0, -1)]
+
+ def dowrite(self, str):
+ end = self.GetTextLength()
+ atEnd = end == self.GetSel()[0]
+ self.SCIInsertText(str, end)
+ if atEnd:
+ self.SetSel(self.GetTextLength())
+
+ def SetWordWrap(self, bWrapOn=1):
+ if bWrapOn:
+ wrap_mode = scintillacon.SC_WRAP_WORD
+ else:
+ wrap_mode = scintillacon.SC_WRAP_NONE
+ self.SCISetWrapMode(wrap_mode)
+
+ def _MakeColorizer(self):
+ return None # No colorizer for me!
+
+
+WindowOutputView = WindowOutputViewScintilla
+
+
+# The WindowOutput class is actually an MFC template. This is a conventient way of
+# making sure that my state can exist beyond the life of the windows themselves.
+# This is primarily to support the functionality of a WindowOutput window automatically
+# being recreated if necessary when written to.
+class WindowOutput(docview.DocTemplate):
+ """Looks like a general Output Window - text can be written by the 'write' method.
+ Will auto-create itself on first write, and also on next write after being closed"""
+
+ softspace = 1
+
+ def __init__(
+ self,
+ title=None,
+ defSize=None,
+ queueing=flags.WQ_LINE,
+ bAutoRestore=1,
+ style=None,
+ makeDoc=None,
+ makeFrame=None,
+ makeView=None,
+ ):
+ """init the output window -
+ Params
+ title=None -- What is the title of the window
+ defSize=None -- What is the default size for the window - if this
+ is a string, the size will be loaded from the ini file.
+ queueing = flags.WQ_LINE -- When should output be written
+ bAutoRestore=1 -- Should a minimized window be restored.
+ style -- Style for Window, or None for default.
+ makeDoc, makeFrame, makeView -- Classes for frame, view and window respectively.
+ """
+ if makeDoc is None:
+ makeDoc = WindowOutputDocument
+ if makeFrame is None:
+ makeFrame = WindowOutputFrame
+ if makeView is None:
+ makeView = WindowOutputViewScintilla
+ docview.DocTemplate.__init__(
+ self, win32ui.IDR_PYTHONTYPE, makeDoc, makeFrame, makeView
+ )
+ self.SetDocStrings("\nOutput\n\nText Documents (*.txt)\n.txt\n\n\n")
+ win32ui.GetApp().AddDocTemplate(self)
+ self.writeQueueing = queueing
+ self.errorCantRecreate = 0
+ self.killBuffer = []
+ self.style = style
+ self.bAutoRestore = bAutoRestore
+ self.title = title
+ self.bCreating = 0
+ self.interruptCount = 0
+ if isinstance(defSize, str): # maintain size pos from ini file.
+ self.iniSizeSection = defSize
+ self.defSize = app.LoadWindowSize(defSize)
+ self.loadedSize = self.defSize
+ else:
+ self.iniSizeSection = None
+ self.defSize = defSize
+ self.currentView = None
+ self.outputQueue = queue.Queue(-1)
+ self.mainThreadId = win32api.GetCurrentThreadId()
+ self.idleHandlerSet = 0
+ self.SetIdleHandler()
+
+ def __del__(self):
+ self.Close()
+
+ def Create(self, title=None, style=None):
+ self.bCreating = 1
+ if title:
+ self.title = title
+ if style:
+ self.style = style
+ doc = self.OpenDocumentFile()
+ if doc is None:
+ return
+ self.currentView = doc.GetFirstView()
+ self.bCreating = 0
+ if self.title:
+ doc.SetTitle(self.title)
+
+ def Close(self):
+ self.RemoveIdleHandler()
+ try:
+ parent = self.currentView.GetParent()
+ except (AttributeError, win32ui.error): # Already closed
+ return
+ parent.DestroyWindow()
+
+ def SetTitle(self, title):
+ self.title = title
+ if self.currentView:
+ self.currentView.GetDocument().SetTitle(self.title)
+
+ def OnViewDestroy(self, view):
+ self.currentView.SaveKillBuffer()
+ self.currentView = None
+
+ def OnFrameDestroy(self, frame):
+ if self.iniSizeSection:
+ # use GetWindowPlacement(), as it works even when min'd or max'd
+ newSize = frame.GetWindowPlacement()[4]
+ if self.loadedSize != newSize:
+ app.SaveWindowSize(self.iniSizeSection, newSize)
+
+ def SetIdleHandler(self):
+ if not self.idleHandlerSet:
+ debug("Idle handler set\n")
+ win32ui.GetApp().AddIdleHandler(self.QueueIdleHandler)
+ self.idleHandlerSet = 1
+
+ def RemoveIdleHandler(self):
+ if self.idleHandlerSet:
+ debug("Idle handler reset\n")
+ if win32ui.GetApp().DeleteIdleHandler(self.QueueIdleHandler) == 0:
+ debug("Error deleting idle handler\n")
+ self.idleHandlerSet = 0
+
+ def RecreateWindow(self):
+ if self.errorCantRecreate:
+ debug("Error = not trying again")
+ return 0
+ try:
+ # This will fail if app shutting down
+ win32ui.GetMainFrame().GetSafeHwnd()
+ self.Create()
+ return 1
+ except (win32ui.error, AttributeError):
+ self.errorCantRecreate = 1
+ debug("Winout can not recreate the Window!\n")
+ return 0
+
+ # this handles the idle message, and does the printing.
+ def QueueIdleHandler(self, handler, count):
+ try:
+ bEmpty = self.QueueFlush(20)
+ # If the queue is empty, then we are back to idle and restart interrupt logic.
+ if bEmpty:
+ self.interruptCount = 0
+ except KeyboardInterrupt:
+ # First interrupt since idle we just pass on.
+ # later ones we dump the queue and give up.
+ self.interruptCount += 1
+ if self.interruptCount > 1:
+ # Drop the queue quickly as the user is already annoyed :-)
+ self.outputQueue = queue.Queue(-1)
+ print("Interrupted.")
+ bEmpty = 1
+ else:
+ raise # re-raise the error so the users exception filters up.
+ return not bEmpty # More to do if not empty.
+
+ # Returns true if the Window needs to be recreated.
+ def NeedRecreateWindow(self):
+ try:
+ if self.currentView is not None and self.currentView.IsWindow():
+ return 0
+ except (
+ win32ui.error,
+ AttributeError,
+ ): # Attribute error if the win32ui object has died.
+ pass
+ return 1
+
+ # Returns true if the Window is OK (either cos it was, or because it was recreated
+ def CheckRecreateWindow(self):
+ if self.bCreating:
+ return 1
+ if not self.NeedRecreateWindow():
+ return 1
+ if self.bAutoRestore:
+ if self.RecreateWindow():
+ return 1
+ return 0
+
+ def QueueFlush(self, max=None):
+ # Returns true if the queue is empty after the flush
+ # debug("Queueflush - %d, %d\n" % (max, self.outputQueue.qsize()))
+ if self.bCreating:
+ return 1
+ items = []
+ rc = 0
+ while max is None or max > 0:
+ try:
+ item = self.outputQueue.get_nowait()
+ items.append(item)
+ except queue.Empty:
+ rc = 1
+ break
+ if max is not None:
+ max -= 1
+ if len(items) != 0:
+ if not self.CheckRecreateWindow():
+ debug(":Recreate failed!\n")
+ return 1 # In trouble - so say we have nothing to do.
+ win32ui.PumpWaitingMessages() # Pump paint messages
+ self.currentView.dowrite("".join(items))
+ return rc
+
+ def HandleOutput(self, message):
+ # debug("QueueOutput on thread %d, flags %d with '%s'...\n" % (win32api.GetCurrentThreadId(), self.writeQueueing, message ))
+ self.outputQueue.put(message)
+ if win32api.GetCurrentThreadId() != self.mainThreadId:
+ pass
+ # debug("not my thread - ignoring queue options!\n")
+ elif self.writeQueueing == flags.WQ_LINE:
+ pos = message.rfind("\n")
+ if pos >= 0:
+ # debug("Line queueing - forcing flush\n")
+ self.QueueFlush()
+ return
+ elif self.writeQueueing == flags.WQ_NONE:
+ # debug("WQ_NONE - flushing!\n")
+ self.QueueFlush()
+ return
+ # Let our idle handler get it - wake it up
+ try:
+ win32ui.GetMainFrame().PostMessage(
+ win32con.WM_USER
+ ) # Kick main thread off.
+ except win32ui.error:
+ # This can happen as the app is shutting down, so we send it to the C++ debugger
+ win32api.OutputDebugString(message)
+
+ # delegate certain fns to my view.
+ def writelines(self, lines):
+ for line in lines:
+ self.write(line)
+
+ def write(self, message):
+ self.HandleOutput(message)
+
+ def flush(self):
+ self.QueueFlush()
+
+ def HandleSpecialLine(self):
+ self.currentView.HandleSpecialLine()
+
+
+def RTFWindowOutput(*args, **kw):
+ kw["makeView"] = WindowOutputViewRTF
+ return WindowOutput(*args, **kw)
+
+
+def thread_test(o):
+ for i in range(5):
+ o.write("Hi from thread %d\n" % (win32api.GetCurrentThreadId()))
+ win32api.Sleep(100)
+
+
+def test():
+ w = WindowOutput(queueing=flags.WQ_IDLE)
+ w.write("First bit of text\n")
+ import _thread
+
+ for i in range(5):
+ w.write("Hello from the main thread\n")
+ _thread.start_new(thread_test, (w,))
+ for i in range(2):
+ w.write("Hello from the main thread\n")
+ win32api.Sleep(50)
+ return w
+
+
+if __name__ == "__main__":
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/AutoExpand.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/AutoExpand.py
new file mode 100644
index 0000000000000000000000000000000000000000..7543eed3dd5521673788d8c7d5768eb055e95c82
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/AutoExpand.py
@@ -0,0 +1,95 @@
+import re
+import string
+
+###$ event <>
+###$ win
+###$ unix
+
+
+class AutoExpand:
+ keydefs = {
+ "<>": [""],
+ }
+
+ unix_keydefs = {
+ "<>": [""],
+ }
+
+ menudefs = [
+ (
+ "edit",
+ [
+ ("E_xpand word", "<>"),
+ ],
+ ),
+ ]
+
+ wordchars = string.ascii_letters + string.digits + "_"
+
+ def __init__(self, editwin):
+ self.text = editwin.text
+ self.text.wordlist = None # XXX what is this?
+ self.state = None
+
+ def expand_word_event(self, event):
+ curinsert = self.text.index("insert")
+ curline = self.text.get("insert linestart", "insert lineend")
+ if not self.state:
+ words = self.getwords()
+ index = 0
+ else:
+ words, index, insert, line = self.state
+ if insert != curinsert or line != curline:
+ words = self.getwords()
+ index = 0
+ if not words:
+ self.text.bell()
+ return "break"
+ word = self.getprevword()
+ self.text.delete("insert - %d chars" % len(word), "insert")
+ newword = words[index]
+ index = (index + 1) % len(words)
+ if index == 0:
+ self.text.bell() # Warn we cycled around
+ self.text.insert("insert", newword)
+ curinsert = self.text.index("insert")
+ curline = self.text.get("insert linestart", "insert lineend")
+ self.state = words, index, curinsert, curline
+ return "break"
+
+ def getwords(self):
+ word = self.getprevword()
+ if not word:
+ return []
+ before = self.text.get("1.0", "insert wordstart")
+ wbefore = re.findall(r"\b" + word + r"\w+\b", before)
+ del before
+ after = self.text.get("insert wordend", "end")
+ wafter = re.findall(r"\b" + word + r"\w+\b", after)
+ del after
+ if not wbefore and not wafter:
+ return []
+ words = []
+ dict = {}
+ # search backwards through words before
+ wbefore.reverse()
+ for w in wbefore:
+ if dict.get(w):
+ continue
+ words.append(w)
+ dict[w] = w
+ # search onwards through words after
+ for w in wafter:
+ if dict.get(w):
+ continue
+ words.append(w)
+ dict[w] = w
+ words.append(word)
+ return words
+
+ def getprevword(self):
+ line = self.text.get("insert linestart", "insert")
+ i = len(line)
+ while i > 0 and line[i - 1] in self.wordchars:
+ i -= 1
+ return line[i:]
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/AutoIndent.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/AutoIndent.py
new file mode 100644
index 0000000000000000000000000000000000000000..069c5198e1271e050d3db1813a38ff3a199fb7ae
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/AutoIndent.py
@@ -0,0 +1,536 @@
+import tokenize
+
+from pywin import default_scintilla_encoding
+
+from . import PyParse
+
+
+class AutoIndent:
+ menudefs = [
+ (
+ "edit",
+ [
+ None,
+ ("_Indent region", "<>"),
+ ("_Dedent region", "<>"),
+ ("Comment _out region", "<>"),
+ ("U_ncomment region", "<>"),
+ ("Tabify region", "<>"),
+ ("Untabify region", "<>"),
+ ("Toggle tabs", "<>"),
+ ("New indent width", "<>"),
+ ],
+ ),
+ ]
+
+ keydefs = {
+ "<>": [""],
+ "<>": ["", ""],
+ "<>": [""],
+ }
+
+ windows_keydefs = {
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ }
+
+ unix_keydefs = {
+ "<>": [
+ "",
+ "",
+ "",
+ ],
+ "<>": [
+ "",
+ "",
+ "",
+ ],
+ "<>": ["", ""],
+ "<>": ["", ""],
+ "<>": ["", ""],
+ "<>": ["", ""],
+ "<>": [""],
+ "<>": [""],
+ }
+
+ # usetabs true -> literal tab characters are used by indent and
+ # dedent cmds, possibly mixed with spaces if
+ # indentwidth is not a multiple of tabwidth
+ # false -> tab characters are converted to spaces by indent
+ # and dedent cmds, and ditto TAB keystrokes
+ # indentwidth is the number of characters per logical indent level.
+ # tabwidth is the display width of a literal tab character.
+ # CAUTION: telling Tk to use anything other than its default
+ # tab setting causes it to use an entirely different tabbing algorithm,
+ # treating tab stops as fixed distances from the left margin.
+ # Nobody expects this, so for now tabwidth should never be changed.
+ usetabs = 1
+ indentwidth = 4
+ tabwidth = 8 # for IDLE use, must remain 8 until Tk is fixed
+
+ # If context_use_ps1 is true, parsing searches back for a ps1 line;
+ # else searches for a popular (if, def, ...) Python stmt.
+ context_use_ps1 = 0
+
+ # When searching backwards for a reliable place to begin parsing,
+ # first start num_context_lines[0] lines back, then
+ # num_context_lines[1] lines back if that didn't work, and so on.
+ # The last value should be huge (larger than the # of lines in a
+ # conceivable file).
+ # Making the initial values larger slows things down more often.
+ num_context_lines = 50, 500, 5000000
+
+ def __init__(self, editwin):
+ self.editwin = editwin
+ self.text = editwin.text
+
+ def config(self, **options):
+ for key, value in options.items():
+ if key == "usetabs":
+ self.usetabs = value
+ elif key == "indentwidth":
+ self.indentwidth = value
+ elif key == "tabwidth":
+ self.tabwidth = value
+ elif key == "context_use_ps1":
+ self.context_use_ps1 = value
+ else:
+ raise KeyError(f"bad option name: {key!r}")
+
+ # If ispythonsource and guess are true, guess a good value for
+ # indentwidth based on file content (if possible), and if
+ # indentwidth != tabwidth set usetabs false.
+ # In any case, adjust the Text widget's view of what a tab
+ # character means.
+
+ def set_indentation_params(self, ispythonsource, guess=1):
+ if guess and ispythonsource:
+ i = self.guess_indent()
+ if 2 <= i <= 8:
+ self.indentwidth = i
+ if self.indentwidth != self.tabwidth:
+ self.usetabs = 0
+
+ self.editwin.set_tabwidth(self.tabwidth)
+
+ def smart_backspace_event(self, event):
+ text = self.text
+ first, last = self.editwin.get_selection_indices()
+ if first and last:
+ text.delete(first, last)
+ text.mark_set("insert", first)
+ return "break"
+ # Delete whitespace left, until hitting a real char or closest
+ # preceding virtual tab stop.
+ chars = text.get("insert linestart", "insert")
+ if chars == "":
+ if text.compare("insert", ">", "1.0"):
+ # easy: delete preceding newline
+ text.delete("insert-1c")
+ else:
+ text.bell() # at start of buffer
+ return "break"
+ if chars[-1] not in " \t":
+ # easy: delete preceding real char
+ text.delete("insert-1c")
+ return "break"
+ # Ick. It may require *inserting* spaces if we back up over a
+ # tab character! This is written to be clear, not fast.
+ have = len(chars.expandtabs(self.tabwidth))
+ assert have > 0
+ want = int((have - 1) / self.indentwidth) * self.indentwidth
+ ncharsdeleted = 0
+ while 1:
+ chars = chars[:-1]
+ ncharsdeleted += 1
+ have = len(chars.expandtabs(self.tabwidth))
+ if have <= want or chars[-1] not in " \t":
+ break
+ text.undo_block_start()
+ text.delete("insert-%dc" % ncharsdeleted, "insert")
+ if have < want:
+ text.insert("insert", " " * (want - have))
+ text.undo_block_stop()
+ return "break"
+
+ def smart_indent_event(self, event):
+ # if intraline selection:
+ # delete it
+ # elif multiline selection:
+ # do indent-region & return
+ # indent one level
+ text = self.text
+ first, last = self.editwin.get_selection_indices()
+ text.undo_block_start()
+ try:
+ if first and last:
+ if index2line(first) != index2line(last):
+ return self.indent_region_event(event)
+ text.delete(first, last)
+ text.mark_set("insert", first)
+ prefix = text.get("insert linestart", "insert")
+ raw, effective = classifyws(prefix, self.tabwidth)
+ if raw == len(prefix):
+ # only whitespace to the left
+ self.reindent_to(effective + self.indentwidth)
+ else:
+ if self.usetabs:
+ pad = "\t"
+ else:
+ effective = len(prefix.expandtabs(self.tabwidth))
+ n = self.indentwidth
+ pad = " " * (n - effective % n)
+ text.insert("insert", pad)
+ text.see("insert")
+ return "break"
+ finally:
+ text.undo_block_stop()
+
+ def newline_and_indent_event(self, event):
+ text = self.text
+ first, last = self.editwin.get_selection_indices()
+ text.undo_block_start()
+ try:
+ if first and last:
+ text.delete(first, last)
+ text.mark_set("insert", first)
+ line = text.get("insert linestart", "insert")
+ i, n = 0, len(line)
+ while i < n and line[i] in " \t":
+ i += 1
+ if i == n:
+ # the cursor is in or at leading indentation; just inject
+ # an empty line at the start and strip space from current line
+ text.delete("insert - %d chars" % i, "insert")
+ text.insert("insert linestart", "\n")
+ return "break"
+ indent = line[:i]
+ # strip whitespace before insert point
+ i = 0
+ while line and line[-1] in " \t":
+ line = line[:-1]
+ i += 1
+ if i:
+ text.delete("insert - %d chars" % i, "insert")
+ # strip whitespace after insert point
+ while text.get("insert") in " \t":
+ text.delete("insert")
+ # start new line
+ text.insert("insert", "\n")
+
+ # adjust indentation for continuations and block
+ # open/close first need to find the last stmt
+ lno = index2line(text.index("insert"))
+ y = PyParse.Parser(self.indentwidth, self.tabwidth)
+ for context in self.num_context_lines:
+ startat = max(lno - context, 1)
+ startatindex = f"{startat!r}.0"
+ rawtext = text.get(startatindex, "insert")
+ y.set_str(rawtext)
+ bod = y.find_good_parse_start(
+ self.context_use_ps1, self._build_char_in_string_func(startatindex)
+ )
+ if bod is not None or startat == 1:
+ break
+ y.set_lo(bod or 0)
+ c = y.get_continuation_type()
+ if c != PyParse.C_NONE:
+ # The current stmt hasn't ended yet.
+ if c == PyParse.C_STRING:
+ # inside a string; just mimic the current indent
+ text.insert("insert", indent)
+ elif c == PyParse.C_BRACKET:
+ # line up with the first (if any) element of the
+ # last open bracket structure; else indent one
+ # level beyond the indent of the line with the
+ # last open bracket
+ self.reindent_to(y.compute_bracket_indent())
+ elif c == PyParse.C_BACKSLASH:
+ # if more than one line in this stmt already, just
+ # mimic the current indent; else if initial line
+ # has a start on an assignment stmt, indent to
+ # beyond leftmost =; else to beyond first chunk of
+ # non-whitespace on initial line
+ if y.get_num_lines_in_stmt() > 1:
+ text.insert("insert", indent)
+ else:
+ self.reindent_to(y.compute_backslash_indent())
+ else:
+ raise ValueError(f"bogus continuation type {c!r}")
+ return "break"
+
+ # This line starts a brand new stmt; indent relative to
+ # indentation of initial line of closest preceding
+ # interesting stmt.
+ indent = y.get_base_indent_string()
+ text.insert("insert", indent)
+ if y.is_block_opener():
+ self.smart_indent_event(event)
+ elif indent and y.is_block_closer():
+ self.smart_backspace_event(event)
+ return "break"
+ finally:
+ text.see("insert")
+ text.undo_block_stop()
+
+ auto_indent = newline_and_indent_event
+
+ # Our editwin provides a is_char_in_string function that works
+ # with a Tk text index, but PyParse only knows about offsets into
+ # a string. This builds a function for PyParse that accepts an
+ # offset.
+
+ def _build_char_in_string_func(self, startindex):
+ def inner(offset, _startindex=startindex, _icis=self.editwin.is_char_in_string):
+ return _icis(_startindex + "+%dc" % offset)
+
+ return inner
+
+ def indent_region_event(self, event):
+ head, tail, chars, lines = self.get_region()
+ for pos in range(len(lines)):
+ line = lines[pos]
+ if line:
+ raw, effective = classifyws(line, self.tabwidth)
+ effective += self.indentwidth
+ lines[pos] = self._make_blanks(effective) + line[raw:]
+ self.set_region(head, tail, chars, lines)
+ return "break"
+
+ def dedent_region_event(self, event):
+ head, tail, chars, lines = self.get_region()
+ for pos in range(len(lines)):
+ line = lines[pos]
+ if line:
+ raw, effective = classifyws(line, self.tabwidth)
+ effective = max(effective - self.indentwidth, 0)
+ lines[pos] = self._make_blanks(effective) + line[raw:]
+ self.set_region(head, tail, chars, lines)
+ return "break"
+
+ def comment_region_event(self, event):
+ head, tail, chars, lines = self.get_region()
+ for pos in range(len(lines) - 1):
+ line = lines[pos]
+ lines[pos] = "##" + line
+ self.set_region(head, tail, chars, lines)
+
+ def uncomment_region_event(self, event):
+ head, tail, chars, lines = self.get_region()
+ for pos in range(len(lines)):
+ line = lines[pos]
+ if not line:
+ continue
+ if line[:2] == "##":
+ line = line[2:]
+ elif line[:1] == "#":
+ line = line[1:]
+ lines[pos] = line
+ self.set_region(head, tail, chars, lines)
+
+ def tabify_region_event(self, event):
+ head, tail, chars, lines = self.get_region()
+ tabwidth = self._asktabwidth()
+ for pos in range(len(lines)):
+ line = lines[pos]
+ if line:
+ raw, effective = classifyws(line, tabwidth)
+ ntabs, nspaces = divmod(effective, tabwidth)
+ lines[pos] = "\t" * ntabs + " " * nspaces + line[raw:]
+ self.set_region(head, tail, chars, lines)
+
+ def untabify_region_event(self, event):
+ head, tail, chars, lines = self.get_region()
+ tabwidth = self._asktabwidth()
+ for pos in range(len(lines)):
+ lines[pos] = lines[pos].expandtabs(tabwidth)
+ self.set_region(head, tail, chars, lines)
+
+ def toggle_tabs_event(self, event):
+ if self.editwin.askyesno(
+ "Toggle tabs",
+ "Turn tabs " + ("on", "off")[self.usetabs] + "?",
+ parent=self.text,
+ ):
+ self.usetabs = not self.usetabs
+ return "break"
+
+ # XXX this isn't bound to anything -- see class tabwidth comments
+ def change_tabwidth_event(self, event):
+ new = self._asktabwidth()
+ if new != self.tabwidth:
+ self.tabwidth = new
+ self.set_indentation_params(0, guess=0)
+ return "break"
+
+ def change_indentwidth_event(self, event):
+ new = self.editwin.askinteger(
+ "Indent width",
+ "New indent width (1-16)",
+ parent=self.text,
+ initialvalue=self.indentwidth,
+ minvalue=1,
+ maxvalue=16,
+ )
+ if new and new != self.indentwidth:
+ self.indentwidth = new
+ return "break"
+
+ def get_region(self):
+ text = self.text
+ first, last = self.editwin.get_selection_indices()
+ if first and last:
+ head = text.index(first + " linestart")
+ tail = text.index(last + "-1c lineend +1c")
+ else:
+ head = text.index("insert linestart")
+ tail = text.index("insert lineend +1c")
+ chars = text.get(head, tail)
+ lines = chars.split("\n")
+ return head, tail, chars, lines
+
+ def set_region(self, head, tail, chars, lines):
+ text = self.text
+ newchars = "\n".join(lines)
+ if newchars == chars:
+ text.bell()
+ return
+ text.tag_remove("sel", "1.0", "end")
+ text.mark_set("insert", head)
+ text.undo_block_start()
+ text.delete(head, tail)
+ text.insert(head, newchars)
+ text.undo_block_stop()
+ text.tag_add("sel", head, "insert")
+
+ # Make string that displays as n leading blanks.
+
+ def _make_blanks(self, n):
+ if self.usetabs:
+ ntabs, nspaces = divmod(n, self.tabwidth)
+ return "\t" * ntabs + " " * nspaces
+ else:
+ return " " * n
+
+ # Delete from beginning of line to insert point, then reinsert
+ # column logical (meaning use tabs if appropriate) spaces.
+
+ def reindent_to(self, column):
+ text = self.text
+ text.undo_block_start()
+ if text.compare("insert linestart", "!=", "insert"):
+ text.delete("insert linestart", "insert")
+ if column:
+ text.insert("insert", self._make_blanks(column))
+ text.undo_block_stop()
+
+ def _asktabwidth(self):
+ return (
+ self.editwin.askinteger(
+ "Tab width",
+ "Spaces per tab?",
+ parent=self.text,
+ initialvalue=self.tabwidth,
+ minvalue=1,
+ maxvalue=16,
+ )
+ or self.tabwidth
+ )
+
+ # Guess indentwidth from text content.
+ # Return guessed indentwidth. This should not be believed unless
+ # it's in a reasonable range (e.g., it will be 0 if no indented
+ # blocks are found).
+
+ def guess_indent(self):
+ opener, indented = IndentSearcher(self.text, self.tabwidth).run()
+ if opener and indented:
+ raw, indentsmall = classifyws(opener, self.tabwidth)
+ raw, indentlarge = classifyws(indented, self.tabwidth)
+ else:
+ indentsmall = indentlarge = 0
+ return indentlarge - indentsmall
+
+
+# "line.col" -> line, as an int
+def index2line(index):
+ return int(float(index))
+
+
+# Look at the leading whitespace in s.
+# Return pair (# of leading ws characters,
+# effective # of leading blanks after expanding
+# tabs to width tabwidth)
+
+
+def classifyws(s, tabwidth):
+ raw = effective = 0
+ for ch in s:
+ if ch == " ":
+ raw += 1
+ effective += 1
+ elif ch == "\t":
+ raw += 1
+ effective = (effective // tabwidth + 1) * tabwidth
+ else:
+ break
+ return raw, effective
+
+
+class IndentSearcher:
+ # .run() chews over the Text widget, looking for a block opener
+ # and the stmt following it. Returns a pair,
+ # (line containing block opener, line containing stmt)
+ # Either or both may be None.
+
+ def __init__(self, text, tabwidth):
+ self.text = text
+ self.tabwidth = tabwidth
+ self.i = self.finished = 0
+ self.blkopenline = self.indentedline = None
+
+ def readline(self):
+ if self.finished:
+ val = ""
+ else:
+ i = self.i = self.i + 1
+ mark = f"{i!r}.0"
+ if self.text.compare(mark, ">=", "end"):
+ val = ""
+ else:
+ val = self.text.get(mark, mark + " lineend+1c")
+ # hrm - not sure this is correct - the source code may have
+ # an encoding declared, but the data will *always* be in
+ # default_scintilla_encoding - so if anyone looks at the encoding decl
+ # in the source they will be wrong. I think. Maybe. Or something...
+ return val.encode(default_scintilla_encoding)
+
+ def run(self):
+ OPENERS = ("class", "def", "for", "if", "try", "while")
+ INDENT = tokenize.INDENT
+ NAME = tokenize.NAME
+
+ save_tabsize = tokenize.tabsize
+ tokenize.tabsize = self.tabwidth
+ try:
+ try:
+ for typ, token, start, end, line in tokenize.tokenize(self.readline):
+ if typ == NAME and token in OPENERS:
+ self.blkopenline = line
+ elif typ == INDENT and self.blkopenline:
+ self.indentedline = line
+ break
+
+ except (tokenize.TokenError, IndentationError):
+ # since we cut off the tokenizer early, we can trigger
+ # spurious errors
+ pass
+ finally:
+ tokenize.tabsize = save_tabsize
+ return self.blkopenline, self.indentedline
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/CallTips.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/CallTips.py
new file mode 100644
index 0000000000000000000000000000000000000000..a87d7af2beccf165e6533c61421cba30267c6afc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/CallTips.py
@@ -0,0 +1,216 @@
+# CallTips.py - An IDLE extension that provides "Call Tips" - ie, a floating window that
+# displays parameter information as you open parens.
+
+import inspect
+import string
+import sys
+import traceback
+
+
+class CallTips:
+ menudefs = []
+
+ keydefs = {
+ "<>": [""],
+ "<>": [""],
+ "<>": [""],
+ "<>": ["", ""],
+ }
+
+ windows_keydefs = {}
+
+ unix_keydefs = {}
+
+ def __init__(self, editwin):
+ self.editwin = editwin
+ self.text = editwin.text
+ self.calltip = None
+ if hasattr(self.text, "make_calltip_window"):
+ self._make_calltip_window = self.text.make_calltip_window
+ else:
+ self._make_calltip_window = self._make_tk_calltip_window
+
+ def close(self):
+ self._make_calltip_window = None
+
+ # Makes a Tk based calltip window. Used by IDLE, but not Pythonwin.
+ # See __init__ above for how this is used.
+ def _make_tk_calltip_window(self):
+ import CallTipWindow
+
+ return CallTipWindow.CallTip(self.text)
+
+ def _remove_calltip_window(self):
+ if self.calltip:
+ self.calltip.hidetip()
+ self.calltip = None
+
+ def paren_open_event(self, event):
+ self._remove_calltip_window()
+ arg_text = get_arg_text(self.get_object_at_cursor())
+ if arg_text:
+ self.calltip_start = self.text.index("insert")
+ self.calltip = self._make_calltip_window()
+ self.calltip.showtip(arg_text)
+ return "" # so the event is handled normally.
+
+ def paren_close_event(self, event):
+ # Now just hides, but later we should check if other
+ # paren'd expressions remain open.
+ self._remove_calltip_window()
+ return "" # so the event is handled normally.
+
+ def check_calltip_cancel_event(self, event):
+ if self.calltip:
+ # If we have moved before the start of the calltip,
+ # or off the calltip line, then cancel the tip.
+ # (Later need to be smarter about multi-line, etc)
+ if self.text.compare(
+ "insert", "<=", self.calltip_start
+ ) or self.text.compare("insert", ">", self.calltip_start + " lineend"):
+ self._remove_calltip_window()
+ return "" # so the event is handled normally.
+
+ def calltip_cancel_event(self, event):
+ self._remove_calltip_window()
+ return "" # so the event is handled normally.
+
+ def get_object_at_cursor(
+ self,
+ wordchars="._"
+ + string.ascii_uppercase
+ + string.ascii_lowercase
+ + string.digits,
+ ):
+ # XXX - This needs to be moved to a better place
+ # so the "." attribute lookup code can also use it.
+ text = self.text
+ chars = text.get("insert linestart", "insert")
+ i = len(chars)
+ while i and chars[i - 1] in wordchars:
+ i -= 1
+ word = chars[i:]
+ if word:
+ # How is this for a hack!
+ import __main__
+
+ namespace = sys.modules.copy()
+ namespace.update(__main__.__dict__)
+ try:
+ return eval(word, namespace)
+ except:
+ pass
+ return None # Can't find an object.
+
+
+def _find_constructor(class_ob):
+ # Given a class object, return a function object used for the
+ # constructor (ie, __init__() ) or None if we can't find one.
+ try:
+ return class_ob.__init__
+ except AttributeError:
+ for base in class_ob.__bases__:
+ rc = _find_constructor(base)
+ if rc is not None:
+ return rc
+ return None
+
+
+def get_arg_text(ob):
+ # Get a string describing the arguments for the given object.
+ argText = ""
+ if ob is not None:
+ if inspect.isclass(ob):
+ # Look for the highest __init__ in the class chain.
+ fob = _find_constructor(ob)
+ if fob is None:
+ fob = lambda: None
+ else:
+ fob = ob
+ if inspect.isfunction(fob) or inspect.ismethod(fob):
+ try:
+ argText = str(inspect.signature(fob))
+ except:
+ print("Failed to format the args")
+ traceback.print_exc()
+ # See if we can use the docstring
+ if hasattr(ob, "__doc__"):
+ doc = ob.__doc__
+ try:
+ doc = doc.strip()
+ pos = doc.find("\n")
+ except AttributeError:
+ ## New style classes may have __doc__ slot without actually
+ ## having a string assigned to it
+ pass
+ else:
+ if pos < 0 or pos > 70:
+ pos = 70
+ if argText:
+ argText += "\n"
+ argText += doc[:pos]
+
+ return argText
+
+
+#################################################
+#
+# Test code
+#
+if __name__ == "__main__":
+
+ def t1():
+ "()"
+
+ def t2(a, b=None):
+ "(a, b=None)"
+
+ def t3(a, *args):
+ "(a, *args)"
+
+ def t4(*args):
+ "(*args)"
+
+ def t5(a, *args):
+ "(a, *args)"
+
+ def t6(a, b=None, *args, **kw):
+ "(a, b=None, *args, **kw)"
+
+ class TC:
+ "(self, a=None, *b)"
+
+ def __init__(self, a=None, *b):
+ "(self, a=None, *b)"
+
+ def t1(self):
+ "(self)"
+
+ def t2(self, a, b=None):
+ "(self, a, b=None)"
+
+ def t3(self, a, *args):
+ "(self, a, *args)"
+
+ def t4(self, *args):
+ "(self, *args)"
+
+ def t5(self, a, *args):
+ "(self, a, *args)"
+
+ def t6(self, a, b=None, *args, **kw):
+ "(self, a, b=None, *args, **kw)"
+
+ def test(tests):
+ failed = []
+ for t in tests:
+ expected = t.__doc__ + "\n" + t.__doc__
+ if get_arg_text(t) != expected:
+ failed.append(t)
+ print(f"{t} - expected {expected!r}, but got {get_arg_text(t)!r}")
+ print("%d of %d tests failed" % (len(failed), len(tests)))
+
+ tc = TC()
+ tests = t1, t2, t3, t4, t5, t6, TC, tc.t1, tc.t2, tc.t3, tc.t4, tc.t5, tc.t6
+
+ test(tests)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/FormatParagraph.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/FormatParagraph.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9ba5e2f656f4aec9a7158ca6f959a674f0b1266
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/FormatParagraph.py
@@ -0,0 +1,166 @@
+# Extension to format a paragraph
+
+# Does basic, standard text formatting, and also understands Python
+# comment blocks. Thus, for editing Python source code, this
+# extension is really only suitable for reformatting these comment
+# blocks or triple-quoted strings.
+
+# Known problems with comment reformatting:
+# * If there is a selection marked, and the first line of the
+# selection is not complete, the block will probably not be detected
+# as comments, and will have the normal "text formatting" rules
+# applied.
+# * If a comment block has leading whitespace that mixes tabs and
+# spaces, they will not be considered part of the same block.
+# * Fancy comments, like this bulleted list, aren't handled :-)
+
+import re
+
+
+class FormatParagraph:
+ menudefs = [
+ (
+ "edit",
+ [
+ ("Format Paragraph", "<>"),
+ ],
+ )
+ ]
+
+ keydefs = {
+ "<>": [""],
+ }
+
+ unix_keydefs = {
+ "<>": [""],
+ }
+
+ def __init__(self, editwin):
+ self.editwin = editwin
+
+ def close(self):
+ self.editwin = None
+
+ def format_paragraph_event(self, event):
+ text = self.editwin.text
+ first, last = self.editwin.get_selection_indices()
+ if first and last:
+ data = text.get(first, last)
+ comment_header = ""
+ else:
+ first, last, comment_header, data = find_paragraph(
+ text, text.index("insert")
+ )
+ if comment_header:
+ # Reformat the comment lines - convert to text sans header.
+ lines = data.split("\n")
+ lines = map(lambda st, l=len(comment_header): st[l:], lines)
+ data = "\n".join(lines)
+ # Reformat to 70 chars or a 20 char width, whichever is greater.
+ format_width = max(70 - len(comment_header), 20)
+ newdata = reformat_paragraph(data, format_width)
+ # re-split and re-insert the comment header.
+ newdata = newdata.split("\n")
+ # If the block ends in a \n, we don't want the comment
+ # prefix inserted after it. (I'm not sure it makes sense to
+ # reformat a comment block that isn't made of complete
+ # lines, but whatever!) Can't think of a clean soltution,
+ # so we hack away
+ block_suffix = ""
+ if not newdata[-1]:
+ block_suffix = "\n"
+ newdata = newdata[:-1]
+ builder = lambda item, prefix=comment_header: prefix + item
+ newdata = "\n".join([builder(d) for d in newdata]) + block_suffix
+ else:
+ # Just a normal text format
+ newdata = reformat_paragraph(data)
+ text.tag_remove("sel", "1.0", "end")
+ if newdata != data:
+ text.mark_set("insert", first)
+ text.undo_block_start()
+ text.delete(first, last)
+ text.insert(first, newdata)
+ text.undo_block_stop()
+ else:
+ text.mark_set("insert", last)
+ text.see("insert")
+
+
+def find_paragraph(text, mark):
+ lineno, col = list(map(int, mark.split(".")))
+ line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
+ while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line):
+ lineno += 1
+ line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
+ first_lineno = lineno
+ comment_header = get_comment_header(line)
+ comment_header_len = len(comment_header)
+ while get_comment_header(line) == comment_header and not is_all_white(
+ line[comment_header_len:]
+ ):
+ lineno += 1
+ line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
+ last = "%d.0" % lineno
+ # Search back to beginning of paragraph
+ lineno = first_lineno - 1
+ line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
+ while (
+ lineno > 0
+ and get_comment_header(line) == comment_header
+ and not is_all_white(line[comment_header_len:])
+ ):
+ lineno -= 1
+ line = text.get("%d.0" % lineno, "%d.0 lineend" % lineno)
+ first = "%d.0" % (lineno + 1)
+ return first, last, comment_header, text.get(first, last)
+
+
+def reformat_paragraph(data, limit=70):
+ lines = data.split("\n")
+ i = 0
+ n = len(lines)
+ while i < n and is_all_white(lines[i]):
+ i += 1
+ if i >= n:
+ return data
+ indent1 = get_indent(lines[i])
+ if i + 1 < n and not is_all_white(lines[i + 1]):
+ indent2 = get_indent(lines[i + 1])
+ else:
+ indent2 = indent1
+ new = lines[:i]
+ partial = indent1
+ while i < n and not is_all_white(lines[i]):
+ # XXX Should take double space after period (etc.) into account
+ words = re.split(r"(\s+)", lines[i])
+ for j in range(0, len(words), 2):
+ word = words[j]
+ if not word:
+ continue # Can happen when line ends in whitespace
+ if len((partial + word).expandtabs()) > limit and partial != indent1:
+ new.append(partial.rstrip())
+ partial = indent2
+ partial += word + " "
+ if j + 1 < len(words) and words[j + 1] != " ":
+ partial += " "
+ i += 1
+ new.append(partial.rstrip())
+ # XXX Should reformat remaining paragraphs as well
+ new.extend(lines[i:])
+ return "\n".join(new)
+
+
+def is_all_white(line):
+ return re.match(r"^\s*$", line) is not None
+
+
+def get_indent(line):
+ return re.match(r"^(\s*)", line).group()
+
+
+def get_comment_header(line):
+ m = re.match(r"^(\s*#*)", line)
+ if m is None:
+ return ""
+ return m.group(1)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/IdleHistory.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/IdleHistory.py
new file mode 100644
index 0000000000000000000000000000000000000000..34a8f9842646dd285da237423dff836edd9985b1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/IdleHistory.py
@@ -0,0 +1,87 @@
+class History:
+ def __init__(self, text, output_sep="\n"):
+ self.text = text
+ self.history = []
+ self.history_prefix = None
+ self.history_pointer = None
+ self.output_sep = output_sep
+ text.bind("<>", self.history_prev)
+ text.bind("<>", self.history_next)
+
+ def history_next(self, event):
+ self.history_do(0)
+ return "break"
+
+ def history_prev(self, event):
+ self.history_do(1)
+ return "break"
+
+ def _get_source(self, start, end):
+ # Get source code from start index to end index. Lines in the
+ # text control may be separated by sys.ps2 .
+ lines = self.text.get(start, end).split(self.output_sep)
+ return "\n".join(lines)
+
+ def _put_source(self, where, source):
+ output = self.output_sep.join(source.split("\n"))
+ self.text.insert(where, output)
+
+ def history_do(self, reverse):
+ nhist = len(self.history)
+ pointer = self.history_pointer
+ prefix = self.history_prefix
+ if pointer is not None and prefix is not None:
+ if (
+ self.text.compare("insert", "!=", "end-1c")
+ or self._get_source("iomark", "end-1c") != self.history[pointer]
+ ):
+ pointer = prefix = None
+ if pointer is None or prefix is None:
+ prefix = self._get_source("iomark", "end-1c")
+ if reverse:
+ pointer = nhist
+ else:
+ pointer = -1
+ nprefix = len(prefix)
+ while 1:
+ if reverse:
+ pointer -= 1
+ else:
+ pointer += 1
+ if pointer < 0 or pointer >= nhist:
+ self.text.bell()
+ if self._get_source("iomark", "end-1c") != prefix:
+ self.text.delete("iomark", "end-1c")
+ self._put_source("iomark", prefix)
+ pointer = prefix = None
+ break
+ item = self.history[pointer]
+ if item[:nprefix] == prefix and len(item) > nprefix:
+ self.text.delete("iomark", "end-1c")
+ self._put_source("iomark", item)
+ break
+ self.text.mark_set("insert", "end-1c")
+ self.text.see("insert")
+ self.text.tag_remove("sel", "1.0", "end")
+ self.history_pointer = pointer
+ self.history_prefix = prefix
+
+ def history_store(self, source):
+ source = source.strip()
+ if len(source) > 2:
+ # avoid duplicates
+ try:
+ self.history.remove(source)
+ except ValueError:
+ pass
+ self.history.append(source)
+ self.history_pointer = None
+ self.history_prefix = None
+
+ def recall(self, s):
+ s = s.strip()
+ self.text.tag_remove("sel", "1.0", "end")
+ self.text.delete("iomark", "end-1c")
+ self.text.mark_set("insert", "end-1c")
+ self.text.insert("insert", s)
+ self.text.see("insert")
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/PyParse.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/PyParse.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ae256821b5d39af53245d3e50edf9727e2f720a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/PyParse.py
@@ -0,0 +1,585 @@
+import re
+import sys
+
+# Reason last stmt is continued (or C_NONE if it's not).
+C_NONE, C_BACKSLASH, C_STRING, C_BRACKET = list(range(4))
+
+if 0: # for throwaway debugging output
+
+ def dump(*stuff):
+ sys.__stdout__.write(" ".join(map(str, stuff)) + "\n")
+
+
+# Find what looks like the start of a popular stmt.
+
+_synchre = re.compile(
+ r"""
+ ^
+ [ \t]*
+ (?: if
+ | for
+ | while
+ | else
+ | def
+ | return
+ | assert
+ | break
+ | class
+ | continue
+ | elif
+ | try
+ | except
+ | raise
+ | import
+ )
+ \b
+""",
+ re.VERBOSE | re.MULTILINE,
+).search
+
+# Match blank line or non-indenting comment line.
+
+_junkre = re.compile(
+ r"""
+ [ \t]*
+ (?: \# \S .* )?
+ \n
+""",
+ re.VERBOSE,
+).match
+
+# Match any flavor of string; the terminating quote is optional
+# so that we're robust in the face of incomplete program text.
+
+_match_stringre = re.compile(
+ r"""
+ \""" [^"\\]* (?:
+ (?: \\. | "(?!"") )
+ [^"\\]*
+ )*
+ (?: \""" )?
+
+| " [^"\\\n]* (?: \\. [^"\\\n]* )* "?
+
+| ''' [^'\\]* (?:
+ (?: \\. | '(?!'') )
+ [^'\\]*
+ )*
+ (?: ''' )?
+
+| ' [^'\\\n]* (?: \\. [^'\\\n]* )* '?
+""",
+ re.VERBOSE | re.DOTALL,
+).match
+
+# Match a line that starts with something interesting;
+# used to find the first item of a bracket structure.
+
+_itemre = re.compile(
+ r"""
+ [ \t]*
+ [^\s#\\] # if we match, m.end()-1 is the interesting char
+""",
+ re.VERBOSE,
+).match
+
+# Match start of stmts that should be followed by a dedent.
+
+_closere = re.compile(
+ r"""
+ \s*
+ (?: return
+ | break
+ | continue
+ | raise
+ | pass
+ )
+ \b
+""",
+ re.VERBOSE,
+).match
+
+# Chew up non-special chars as quickly as possible. If match is
+# successful, m.end() less 1 is the index of the last boring char
+# matched. If match is unsuccessful, the string starts with an
+# interesting char.
+
+_chew_ordinaryre = re.compile(
+ r"""
+ [^[\](){}#'"\\]+
+""",
+ re.VERBOSE,
+).match
+
+# Build translation table to map uninteresting chars to "x", open
+# brackets to "(", and close brackets to ")".
+
+_tran = ["x"] * 256
+for ch in "({[":
+ _tran[ord(ch)] = "("
+for ch in ")}]":
+ _tran[ord(ch)] = ")"
+for ch in "\"'\\\n#":
+ _tran[ord(ch)] = ch
+del ch
+
+
+class Parser:
+ def __init__(self, indentwidth, tabwidth):
+ self.indentwidth = indentwidth
+ self.tabwidth = tabwidth
+
+ def set_str(self, str):
+ assert len(str) == 0 or str[-1] == "\n", f"Oops - have str {str!r}"
+ self.str = str
+ self.study_level = 0
+
+ # Return index of a good place to begin parsing, as close to the
+ # end of the string as possible. This will be the start of some
+ # popular stmt like "if" or "def". Return None if none found:
+ # the caller should pass more prior context then, if possible, or
+ # if not (the entire program text up until the point of interest
+ # has already been tried) pass 0 to set_lo.
+ #
+ # This will be reliable iff given a reliable is_char_in_string
+ # function, meaning that when it says "no", it's absolutely
+ # guaranteed that the char is not in a string.
+ #
+ # Ack, hack: in the shell window this kills us, because there's
+ # no way to tell the differences between output, >>> etc and
+ # user input. Indeed, IDLE's first output line makes the rest
+ # look like it's in an unclosed paren!:
+ # Python X.X.X (#0, Apr 13 1999, ...
+
+ def find_good_parse_start(self, use_ps1, is_char_in_string=None):
+ str, pos = self.str, None
+ if use_ps1:
+ # shell window
+ ps1 = "\n" + sys.ps1
+ i = str.rfind(ps1)
+ if i >= 0:
+ pos = i + len(ps1)
+ # make it look like there's a newline instead
+ # of ps1 at the start -- hacking here once avoids
+ # repeated hackery later
+ self.str = str[: pos - 1] + "\n" + str[pos:]
+ return pos
+
+ # File window -- real work.
+ if not is_char_in_string:
+ # no clue -- make the caller pass everything
+ return None
+
+ # Peek back from the end for a good place to start,
+ # but don't try too often; pos will be left None, or
+ # bumped to a legitimate synch point.
+ limit = len(str)
+ for tries in range(5):
+ i = str.rfind(":\n", 0, limit)
+ if i < 0:
+ break
+ i = str.rfind("\n", 0, i) + 1 # start of colon line
+ m = _synchre(str, i, limit)
+ if m and not is_char_in_string(m.start()):
+ pos = m.start()
+ break
+ limit = i
+ if pos is None:
+ # Nothing looks like a block-opener, or stuff does
+ # but is_char_in_string keeps returning true; most likely
+ # we're in or near a giant string, the colorizer hasn't
+ # caught up enough to be helpful, or there simply *aren't*
+ # any interesting stmts. In any of these cases we're
+ # going to have to parse the whole thing to be sure, so
+ # give it one last try from the start, but stop wasting
+ # time here regardless of the outcome.
+ m = _synchre(str)
+ if m and not is_char_in_string(m.start()):
+ pos = m.start()
+ return pos
+
+ # Peeking back worked; look forward until _synchre no longer
+ # matches.
+ i = pos + 1
+ while 1:
+ m = _synchre(str, i)
+ if m:
+ s, i = m.span()
+ if not is_char_in_string(s):
+ pos = s
+ else:
+ break
+ return pos
+
+ # Throw away the start of the string. Intended to be called with
+ # find_good_parse_start's result.
+
+ def set_lo(self, lo):
+ assert lo == 0 or self.str[lo - 1] == "\n"
+ if lo > 0:
+ self.str = self.str[lo:]
+
+ # As quickly as humanly possible , find the line numbers (0-
+ # based) of the non-continuation lines.
+ # Creates self.{goodlines, continuation}.
+
+ def _study1(self):
+ if self.study_level >= 1:
+ return
+ self.study_level = 1
+
+ # Map all uninteresting characters to "x", all open brackets
+ # to "(", all close brackets to ")", then collapse runs of
+ # uninteresting characters. This can cut the number of chars
+ # by a factor of 10-40, and so greatly speed the following loop.
+ str = self.str
+ str = str.translate(_tran)
+ str = str.replace("xxxxxxxx", "x")
+ str = str.replace("xxxx", "x")
+ str = str.replace("xx", "x")
+ str = str.replace("xx", "x")
+ str = str.replace("\nx", "\n")
+ # note that replacing x\n with \n would be incorrect, because
+ # x may be preceded by a backslash
+
+ # March over the squashed version of the program, accumulating
+ # the line numbers of non-continued stmts, and determining
+ # whether & why the last stmt is a continuation.
+ continuation = C_NONE
+ level = lno = 0 # level is nesting level; lno is line number
+ self.goodlines = goodlines = [0]
+ push_good = goodlines.append
+ i, n = 0, len(str)
+ while i < n:
+ ch = str[i]
+ i += 1
+
+ # cases are checked in decreasing order of frequency
+ if ch == "x":
+ continue
+
+ if ch == "\n":
+ lno += 1
+ if level == 0:
+ push_good(lno)
+ # else we're in an unclosed bracket structure
+ continue
+
+ if ch == "(":
+ level += 1
+ continue
+
+ if ch == ")":
+ if level:
+ level -= 1
+ # else the program is invalid, but we can't complain
+ continue
+
+ if ch == '"' or ch == "'":
+ # consume the string
+ quote = ch
+ if str[i - 1 : i + 2] == quote * 3:
+ quote *= 3
+ w = len(quote) - 1
+ i += w
+ while i < n:
+ ch = str[i]
+ i += 1
+
+ if ch == "x":
+ continue
+
+ if str[i - 1 : i + w] == quote:
+ i += w
+ break
+
+ if ch == "\n":
+ lno += 1
+ if w == 0:
+ # unterminated single-quoted string
+ if level == 0:
+ push_good(lno)
+ break
+ continue
+
+ if ch == "\\":
+ assert i < n
+ if str[i] == "\n":
+ lno += 1
+ i += 1
+ continue
+
+ # else comment char or paren inside string
+
+ else:
+ # didn't break out of the loop, so we're still
+ # inside a string
+ continuation = C_STRING
+ continue # with outer loop
+
+ if ch == "#":
+ # consume the comment
+ i = str.find("\n", i)
+ assert i >= 0
+ continue
+
+ assert ch == "\\"
+ assert i < n
+ if str[i] == "\n":
+ lno += 1
+ if i + 1 == n:
+ continuation = C_BACKSLASH
+ i += 1
+
+ # The last stmt may be continued for all 3 reasons.
+ # String continuation takes precedence over bracket
+ # continuation, which beats backslash continuation.
+ if continuation != C_STRING and level > 0:
+ continuation = C_BRACKET
+ self.continuation = continuation
+
+ # Push the final line number as a sentinel value, regardless of
+ # whether it's continued.
+ assert (continuation == C_NONE) == (goodlines[-1] == lno)
+ if goodlines[-1] != lno:
+ push_good(lno)
+
+ def get_continuation_type(self):
+ self._study1()
+ return self.continuation
+
+ # study1 was sufficient to determine the continuation status,
+ # but doing more requires looking at every character. study2
+ # does this for the last interesting statement in the block.
+ # Creates:
+ # self.stmt_start, stmt_end
+ # slice indices of last interesting stmt
+ # self.lastch
+ # last non-whitespace character before optional trailing
+ # comment
+ # self.lastopenbracketpos
+ # if continuation is C_BRACKET, index of last open bracket
+
+ def _study2(self):
+ if self.study_level >= 2:
+ return
+ self._study1()
+ self.study_level = 2
+
+ # Set p and q to slice indices of last interesting stmt.
+ str, goodlines = self.str, self.goodlines
+ i = len(goodlines) - 1
+ p = len(str) # index of newest line
+ while i:
+ assert p
+ # p is the index of the stmt at line number goodlines[i].
+ # Move p back to the stmt at line number goodlines[i-1].
+ q = p
+ for nothing in range(goodlines[i - 1], goodlines[i]):
+ # tricky: sets p to 0 if no preceding newline
+ p = str.rfind("\n", 0, p - 1) + 1
+ # The stmt str[p:q] isn't a continuation, but may be blank
+ # or a non-indenting comment line.
+ if _junkre(str, p):
+ i -= 1
+ else:
+ break
+ if i == 0:
+ # nothing but junk!
+ assert p == 0
+ q = p
+ self.stmt_start, self.stmt_end = p, q
+
+ # Analyze this stmt, to find the last open bracket (if any)
+ # and last interesting character (if any).
+ lastch = ""
+ stack = [] # stack of open bracket indices
+ push_stack = stack.append
+ while p < q:
+ # suck up all except ()[]{}'"#\\
+ m = _chew_ordinaryre(str, p, q)
+ if m:
+ # we skipped at least one boring char
+ newp = m.end()
+ # back up over totally boring whitespace
+ i = newp - 1 # index of last boring char
+ while i >= p and str[i] in " \t\n":
+ i -= 1
+ if i >= p:
+ lastch = str[i]
+ p = newp
+ if p >= q:
+ break
+
+ ch = str[p]
+
+ if ch in "([{":
+ push_stack(p)
+ lastch = ch
+ p += 1
+ continue
+
+ if ch in ")]}":
+ if stack:
+ del stack[-1]
+ lastch = ch
+ p += 1
+ continue
+
+ if ch == '"' or ch == "'":
+ # consume string
+ # Note that study1 did this with a Python loop, but
+ # we use a regexp here; the reason is speed in both
+ # cases; the string may be huge, but study1 pre-squashed
+ # strings to a couple of characters per line. study1
+ # also needed to keep track of newlines, and we don't
+ # have to.
+ lastch = ch
+ p = _match_stringre(str, p, q).end()
+ continue
+
+ if ch == "#":
+ # consume comment and trailing newline
+ p = str.find("\n", p, q) + 1
+ assert p > 0
+ continue
+
+ assert ch == "\\"
+ p += 1 # beyond backslash
+ assert p < q
+ if str[p] != "\n":
+ # the program is invalid, but can't complain
+ lastch = ch + str[p]
+ p += 1 # beyond escaped char
+
+ # end while p < q:
+
+ self.lastch = lastch
+ if stack:
+ self.lastopenbracketpos = stack[-1]
+
+ # Assuming continuation is C_BRACKET, return the number
+ # of spaces the next line should be indented.
+
+ def compute_bracket_indent(self):
+ self._study2()
+ assert self.continuation == C_BRACKET
+ j = self.lastopenbracketpos
+ str = self.str
+ n = len(str)
+ origi = i = str.rfind("\n", 0, j) + 1
+ j += 1 # one beyond open bracket
+ # find first list item; set i to start of its line
+ while j < n:
+ m = _itemre(str, j)
+ if m:
+ j = m.end() - 1 # index of first interesting char
+ extra = 0
+ break
+ else:
+ # this line is junk; advance to next line
+ i = j = str.find("\n", j) + 1
+ else:
+ # nothing interesting follows the bracket;
+ # reproduce the bracket line's indentation + a level
+ j = i = origi
+ while str[j] in " \t":
+ j += 1
+ extra = self.indentwidth
+ return len(str[i:j].expandtabs(self.tabwidth)) + extra
+
+ # Return number of physical lines in last stmt (whether or not
+ # it's an interesting stmt! this is intended to be called when
+ # continuation is C_BACKSLASH).
+
+ def get_num_lines_in_stmt(self):
+ self._study1()
+ goodlines = self.goodlines
+ return goodlines[-1] - goodlines[-2]
+
+ # Assuming continuation is C_BACKSLASH, return the number of spaces
+ # the next line should be indented. Also assuming the new line is
+ # the first one following the initial line of the stmt.
+
+ def compute_backslash_indent(self):
+ self._study2()
+ assert self.continuation == C_BACKSLASH
+ str = self.str
+ i = self.stmt_start
+ while str[i] in " \t":
+ i += 1
+ startpos = i
+
+ # See whether the initial line starts an assignment stmt; i.e.,
+ # look for an = operator
+ endpos = str.find("\n", startpos) + 1
+ found = level = 0
+ while i < endpos:
+ ch = str[i]
+ if ch in "([{":
+ level += 1
+ i += 1
+ elif ch in ")]}":
+ if level:
+ level -= 1
+ i += 1
+ elif ch == '"' or ch == "'":
+ i = _match_stringre(str, i, endpos).end()
+ elif ch == "#":
+ break
+ elif (
+ level == 0
+ and ch == "="
+ and (i == 0 or str[i - 1] not in "=<>!")
+ and str[i + 1] != "="
+ ):
+ found = 1
+ break
+ else:
+ i += 1
+
+ if found:
+ # found a legit =, but it may be the last interesting
+ # thing on the line
+ i += 1 # move beyond the =
+ found = re.match(r"\s*\\", str[i:endpos]) is None
+
+ if not found:
+ # oh well ... settle for moving beyond the first chunk
+ # of non-whitespace chars
+ i = startpos
+ while str[i] not in " \t\n":
+ i += 1
+
+ return len(str[self.stmt_start : i].expandtabs(self.tabwidth)) + 1
+
+ # Return the leading whitespace on the initial line of the last
+ # interesting stmt.
+
+ def get_base_indent_string(self):
+ self._study2()
+ i, n = self.stmt_start, self.stmt_end
+ j = i
+ str = self.str
+ while j < n and str[j] in " \t":
+ j += 1
+ return str[i:j]
+
+ # Did the last interesting stmt open a block?
+
+ def is_block_opener(self):
+ self._study2()
+ return self.lastch == ":"
+
+ # Did the last interesting stmt close a block?
+
+ def is_block_closer(self):
+ self._study2()
+ return _closere(self.str, self.stmt_start) is not None
+
+ # index of last open bracket ({[, or None if none
+ lastopenbracketpos = None
+
+ def get_last_open_bracket_pos(self):
+ self._study2()
+ return self.lastopenbracketpos
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/idle/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d734bc01c3aa7e4183ca9763f0759a1109d1ca6d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/idle/__init__.py
@@ -0,0 +1 @@
+# This file denotes the directory as a Python package.
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/activex.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/activex.py
new file mode 100644
index 0000000000000000000000000000000000000000..8322a8b6d0c1f6d37b506398bc6f051ad24f1bcf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/activex.py
@@ -0,0 +1,79 @@
+"""Support for ActiveX control hosting in Pythonwin."""
+
+import win32ui
+import win32uiole
+
+from . import window
+
+
+class Control(window.Wnd):
+ """An ActiveX control base class. A new class must be derived from both
+ this class and the Events class. See the demos for more details.
+ """
+
+ def __init__(self):
+ self.__dict__["_dispobj_"] = None
+ window.Wnd.__init__(self)
+
+ def _GetControlCLSID(self):
+ return self.CLSID
+
+ def _GetDispatchClass(self):
+ return self.default_interface
+
+ def _GetEventMap(self):
+ return self.default_source._dispid_to_func_
+
+ def CreateControl(self, windowTitle, style, rect, parent, id, lic_string=None):
+ clsid = str(self._GetControlCLSID())
+ self.__dict__["_obj_"] = win32ui.CreateControl(
+ clsid, windowTitle, style, rect, parent, id, None, False, lic_string
+ )
+ klass = self._GetDispatchClass()
+ dispobj = klass(win32uiole.GetIDispatchForWindow(self._obj_))
+ self.HookOleEvents()
+ self.__dict__["_dispobj_"] = dispobj
+
+ def HookOleEvents(self):
+ dict = self._GetEventMap()
+ for dispid, methodName in dict.items():
+ if hasattr(self, methodName):
+ self._obj_.HookOleEvent(getattr(self, methodName), dispid)
+
+ def __getattr__(self, attr):
+ # Delegate attributes to the windows and the Dispatch object for this class
+ try:
+ return window.Wnd.__getattr__(self, attr)
+ except AttributeError:
+ pass
+ return getattr(self._dispobj_, attr)
+
+ def __setattr__(self, attr, value):
+ if hasattr(self.__dict__, attr):
+ self.__dict__[attr] = value
+ return
+ try:
+ if self._dispobj_:
+ self._dispobj_.__setattr__(attr, value)
+ return
+ except AttributeError:
+ pass
+ self.__dict__[attr] = value
+
+
+def MakeControlClass(controlClass, name=None):
+ """Given a CoClass in a generated .py file, this function will return a Class
+ object which can be used as an OCX control.
+
+ This function is used when you do not want to handle any events from the OCX
+ control. If you need events, then you should derive a class from both the
+ activex.Control class and the CoClass
+ """
+ if name is None:
+ name = controlClass.__name__
+ return type("OCX" + name, (Control, controlClass), {})
+
+
+def MakeControlInstance(controlClass, name=None):
+ """As for MakeControlClass(), but returns an instance of the class."""
+ return MakeControlClass(controlClass, name)()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/afxres.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/afxres.py
new file mode 100644
index 0000000000000000000000000000000000000000..f909612ce0897051d016c102f9cd3079d1bc83d1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/afxres.py
@@ -0,0 +1,501 @@
+# Generated by h2py from stdin
+TCS_MULTILINE = 0x0200
+CBRS_ALIGN_LEFT = 0x1000
+CBRS_ALIGN_TOP = 0x2000
+CBRS_ALIGN_RIGHT = 0x4000
+CBRS_ALIGN_BOTTOM = 0x8000
+CBRS_ALIGN_ANY = 0xF000
+CBRS_BORDER_LEFT = 0x0100
+CBRS_BORDER_TOP = 0x0200
+CBRS_BORDER_RIGHT = 0x0400
+CBRS_BORDER_BOTTOM = 0x0800
+CBRS_BORDER_ANY = 0x0F00
+CBRS_TOOLTIPS = 0x0010
+CBRS_FLYBY = 0x0020
+CBRS_FLOAT_MULTI = 0x0040
+CBRS_BORDER_3D = 0x0080
+CBRS_HIDE_INPLACE = 0x0008
+CBRS_SIZE_DYNAMIC = 0x0004
+CBRS_SIZE_FIXED = 0x0002
+CBRS_FLOATING = 0x0001
+CBRS_GRIPPER = 0x00400000
+CBRS_ORIENT_HORZ = CBRS_ALIGN_TOP | CBRS_ALIGN_BOTTOM
+CBRS_ORIENT_VERT = CBRS_ALIGN_LEFT | CBRS_ALIGN_RIGHT
+CBRS_ORIENT_ANY = CBRS_ORIENT_HORZ | CBRS_ORIENT_VERT
+CBRS_ALL = 0xFFFF
+CBRS_NOALIGN = 0x00000000
+CBRS_LEFT = CBRS_ALIGN_LEFT | CBRS_BORDER_RIGHT
+CBRS_TOP = CBRS_ALIGN_TOP | CBRS_BORDER_BOTTOM
+CBRS_RIGHT = CBRS_ALIGN_RIGHT | CBRS_BORDER_LEFT
+CBRS_BOTTOM = CBRS_ALIGN_BOTTOM | CBRS_BORDER_TOP
+SBPS_NORMAL = 0x0000
+SBPS_NOBORDERS = 0x0100
+SBPS_POPOUT = 0x0200
+SBPS_OWNERDRAW = 0x1000
+SBPS_DISABLED = 0x04000000
+SBPS_STRETCH = 0x08000000
+ID_INDICATOR_EXT = 0xE700
+ID_INDICATOR_CAPS = 0xE701
+ID_INDICATOR_NUM = 0xE702
+ID_INDICATOR_SCRL = 0xE703
+ID_INDICATOR_OVR = 0xE704
+ID_INDICATOR_REC = 0xE705
+ID_INDICATOR_KANA = 0xE706
+ID_SEPARATOR = 0
+AFX_IDW_CONTROLBAR_FIRST = 0xE800
+AFX_IDW_CONTROLBAR_LAST = 0xE8FF
+AFX_IDW_TOOLBAR = 0xE800
+AFX_IDW_STATUS_BAR = 0xE801
+AFX_IDW_PREVIEW_BAR = 0xE802
+AFX_IDW_RESIZE_BAR = 0xE803
+AFX_IDW_DOCKBAR_TOP = 0xE81B
+AFX_IDW_DOCKBAR_LEFT = 0xE81C
+AFX_IDW_DOCKBAR_RIGHT = 0xE81D
+AFX_IDW_DOCKBAR_BOTTOM = 0xE81E
+AFX_IDW_DOCKBAR_FLOAT = 0xE81F
+
+
+def AFX_CONTROLBAR_MASK(nIDC):
+ return 1 << (nIDC - AFX_IDW_CONTROLBAR_FIRST)
+
+
+AFX_IDW_PANE_FIRST = 0xE900
+AFX_IDW_PANE_LAST = 0xE9FF
+AFX_IDW_HSCROLL_FIRST = 0xEA00
+AFX_IDW_VSCROLL_FIRST = 0xEA10
+AFX_IDW_SIZE_BOX = 0xEA20
+AFX_IDW_PANE_SAVE = 0xEA21
+AFX_IDS_APP_TITLE = 0xE000
+AFX_IDS_IDLEMESSAGE = 0xE001
+AFX_IDS_HELPMODEMESSAGE = 0xE002
+AFX_IDS_APP_TITLE_EMBEDDING = 0xE003
+AFX_IDS_COMPANY_NAME = 0xE004
+AFX_IDS_OBJ_TITLE_INPLACE = 0xE005
+ID_FILE_NEW = 0xE100
+ID_FILE_OPEN = 0xE101
+ID_FILE_CLOSE = 0xE102
+ID_FILE_SAVE = 0xE103
+ID_FILE_SAVE_AS = 0xE104
+ID_FILE_PAGE_SETUP = 0xE105
+ID_FILE_PRINT_SETUP = 0xE106
+ID_FILE_PRINT = 0xE107
+ID_FILE_PRINT_DIRECT = 0xE108
+ID_FILE_PRINT_PREVIEW = 0xE109
+ID_FILE_UPDATE = 0xE10A
+ID_FILE_SAVE_COPY_AS = 0xE10B
+ID_FILE_SEND_MAIL = 0xE10C
+ID_FILE_MRU_FIRST = 0xE110
+ID_FILE_MRU_FILE1 = 0xE110
+ID_FILE_MRU_FILE2 = 0xE111
+ID_FILE_MRU_FILE3 = 0xE112
+ID_FILE_MRU_FILE4 = 0xE113
+ID_FILE_MRU_FILE5 = 0xE114
+ID_FILE_MRU_FILE6 = 0xE115
+ID_FILE_MRU_FILE7 = 0xE116
+ID_FILE_MRU_FILE8 = 0xE117
+ID_FILE_MRU_FILE9 = 0xE118
+ID_FILE_MRU_FILE10 = 0xE119
+ID_FILE_MRU_FILE11 = 0xE11A
+ID_FILE_MRU_FILE12 = 0xE11B
+ID_FILE_MRU_FILE13 = 0xE11C
+ID_FILE_MRU_FILE14 = 0xE11D
+ID_FILE_MRU_FILE15 = 0xE11E
+ID_FILE_MRU_FILE16 = 0xE11F
+ID_FILE_MRU_LAST = 0xE11F
+ID_EDIT_CLEAR = 0xE120
+ID_EDIT_CLEAR_ALL = 0xE121
+ID_EDIT_COPY = 0xE122
+ID_EDIT_CUT = 0xE123
+ID_EDIT_FIND = 0xE124
+ID_EDIT_PASTE = 0xE125
+ID_EDIT_PASTE_LINK = 0xE126
+ID_EDIT_PASTE_SPECIAL = 0xE127
+ID_EDIT_REPEAT = 0xE128
+ID_EDIT_REPLACE = 0xE129
+ID_EDIT_SELECT_ALL = 0xE12A
+ID_EDIT_UNDO = 0xE12B
+ID_EDIT_REDO = 0xE12C
+ID_WINDOW_NEW = 0xE130
+ID_WINDOW_ARRANGE = 0xE131
+ID_WINDOW_CASCADE = 0xE132
+ID_WINDOW_TILE_HORZ = 0xE133
+ID_WINDOW_TILE_VERT = 0xE134
+ID_WINDOW_SPLIT = 0xE135
+AFX_IDM_WINDOW_FIRST = 0xE130
+AFX_IDM_WINDOW_LAST = 0xE13F
+AFX_IDM_FIRST_MDICHILD = 0xFF00
+ID_APP_ABOUT = 0xE140
+ID_APP_EXIT = 0xE141
+ID_HELP_INDEX = 0xE142
+ID_HELP_FINDER = 0xE143
+ID_HELP_USING = 0xE144
+ID_CONTEXT_HELP = 0xE145
+ID_HELP = 0xE146
+ID_DEFAULT_HELP = 0xE147
+ID_NEXT_PANE = 0xE150
+ID_PREV_PANE = 0xE151
+ID_FORMAT_FONT = 0xE160
+ID_OLE_INSERT_NEW = 0xE200
+ID_OLE_EDIT_LINKS = 0xE201
+ID_OLE_EDIT_CONVERT = 0xE202
+ID_OLE_EDIT_CHANGE_ICON = 0xE203
+ID_OLE_EDIT_PROPERTIES = 0xE204
+ID_OLE_VERB_FIRST = 0xE210
+ID_OLE_VERB_LAST = 0xE21F
+AFX_ID_PREVIEW_CLOSE = 0xE300
+AFX_ID_PREVIEW_NUMPAGE = 0xE301
+AFX_ID_PREVIEW_NEXT = 0xE302
+AFX_ID_PREVIEW_PREV = 0xE303
+AFX_ID_PREVIEW_PRINT = 0xE304
+AFX_ID_PREVIEW_ZOOMIN = 0xE305
+AFX_ID_PREVIEW_ZOOMOUT = 0xE306
+ID_VIEW_TOOLBAR = 0xE800
+ID_VIEW_STATUS_BAR = 0xE801
+ID_RECORD_FIRST = 0xE900
+ID_RECORD_LAST = 0xE901
+ID_RECORD_NEXT = 0xE902
+ID_RECORD_PREV = 0xE903
+IDC_STATIC = -1
+AFX_IDS_SCFIRST = 0xEF00
+AFX_IDS_SCSIZE = 0xEF00
+AFX_IDS_SCMOVE = 0xEF01
+AFX_IDS_SCMINIMIZE = 0xEF02
+AFX_IDS_SCMAXIMIZE = 0xEF03
+AFX_IDS_SCNEXTWINDOW = 0xEF04
+AFX_IDS_SCPREVWINDOW = 0xEF05
+AFX_IDS_SCCLOSE = 0xEF06
+AFX_IDS_SCRESTORE = 0xEF12
+AFX_IDS_SCTASKLIST = 0xEF13
+AFX_IDS_MDICHILD = 0xEF1F
+AFX_IDS_DESKACCESSORY = 0xEFDA
+AFX_IDS_OPENFILE = 0xF000
+AFX_IDS_SAVEFILE = 0xF001
+AFX_IDS_ALLFILTER = 0xF002
+AFX_IDS_UNTITLED = 0xF003
+AFX_IDS_SAVEFILECOPY = 0xF004
+AFX_IDS_PREVIEW_CLOSE = 0xF005
+AFX_IDS_UNNAMED_FILE = 0xF006
+AFX_IDS_ABOUT = 0xF010
+AFX_IDS_HIDE = 0xF011
+AFX_IDP_NO_ERROR_AVAILABLE = 0xF020
+AFX_IDS_NOT_SUPPORTED_EXCEPTION = 0xF021
+AFX_IDS_RESOURCE_EXCEPTION = 0xF022
+AFX_IDS_MEMORY_EXCEPTION = 0xF023
+AFX_IDS_USER_EXCEPTION = 0xF024
+AFX_IDS_PRINTONPORT = 0xF040
+AFX_IDS_ONEPAGE = 0xF041
+AFX_IDS_TWOPAGE = 0xF042
+AFX_IDS_PRINTPAGENUM = 0xF043
+AFX_IDS_PREVIEWPAGEDESC = 0xF044
+AFX_IDS_PRINTDEFAULTEXT = 0xF045
+AFX_IDS_PRINTDEFAULT = 0xF046
+AFX_IDS_PRINTFILTER = 0xF047
+AFX_IDS_PRINTCAPTION = 0xF048
+AFX_IDS_PRINTTOFILE = 0xF049
+AFX_IDS_OBJECT_MENUITEM = 0xF080
+AFX_IDS_EDIT_VERB = 0xF081
+AFX_IDS_ACTIVATE_VERB = 0xF082
+AFX_IDS_CHANGE_LINK = 0xF083
+AFX_IDS_AUTO = 0xF084
+AFX_IDS_MANUAL = 0xF085
+AFX_IDS_FROZEN = 0xF086
+AFX_IDS_ALL_FILES = 0xF087
+AFX_IDS_SAVE_MENU = 0xF088
+AFX_IDS_UPDATE_MENU = 0xF089
+AFX_IDS_SAVE_AS_MENU = 0xF08A
+AFX_IDS_SAVE_COPY_AS_MENU = 0xF08B
+AFX_IDS_EXIT_MENU = 0xF08C
+AFX_IDS_UPDATING_ITEMS = 0xF08D
+AFX_IDS_METAFILE_FORMAT = 0xF08E
+AFX_IDS_DIB_FORMAT = 0xF08F
+AFX_IDS_BITMAP_FORMAT = 0xF090
+AFX_IDS_LINKSOURCE_FORMAT = 0xF091
+AFX_IDS_EMBED_FORMAT = 0xF092
+AFX_IDS_PASTELINKEDTYPE = 0xF094
+AFX_IDS_UNKNOWNTYPE = 0xF095
+AFX_IDS_RTF_FORMAT = 0xF096
+AFX_IDS_TEXT_FORMAT = 0xF097
+AFX_IDS_INVALID_CURRENCY = 0xF098
+AFX_IDS_INVALID_DATETIME = 0xF099
+AFX_IDS_INVALID_DATETIMESPAN = 0xF09A
+AFX_IDP_INVALID_FILENAME = 0xF100
+AFX_IDP_FAILED_TO_OPEN_DOC = 0xF101
+AFX_IDP_FAILED_TO_SAVE_DOC = 0xF102
+AFX_IDP_ASK_TO_SAVE = 0xF103
+AFX_IDP_FAILED_TO_CREATE_DOC = 0xF104
+AFX_IDP_FILE_TOO_LARGE = 0xF105
+AFX_IDP_FAILED_TO_START_PRINT = 0xF106
+AFX_IDP_FAILED_TO_LAUNCH_HELP = 0xF107
+AFX_IDP_INTERNAL_FAILURE = 0xF108
+AFX_IDP_COMMAND_FAILURE = 0xF109
+AFX_IDP_FAILED_MEMORY_ALLOC = 0xF10A
+AFX_IDP_PARSE_INT = 0xF110
+AFX_IDP_PARSE_REAL = 0xF111
+AFX_IDP_PARSE_INT_RANGE = 0xF112
+AFX_IDP_PARSE_REAL_RANGE = 0xF113
+AFX_IDP_PARSE_STRING_SIZE = 0xF114
+AFX_IDP_PARSE_RADIO_BUTTON = 0xF115
+AFX_IDP_PARSE_BYTE = 0xF116
+AFX_IDP_PARSE_UINT = 0xF117
+AFX_IDP_PARSE_DATETIME = 0xF118
+AFX_IDP_PARSE_CURRENCY = 0xF119
+AFX_IDP_FAILED_INVALID_FORMAT = 0xF120
+AFX_IDP_FAILED_INVALID_PATH = 0xF121
+AFX_IDP_FAILED_DISK_FULL = 0xF122
+AFX_IDP_FAILED_ACCESS_READ = 0xF123
+AFX_IDP_FAILED_ACCESS_WRITE = 0xF124
+AFX_IDP_FAILED_IO_ERROR_READ = 0xF125
+AFX_IDP_FAILED_IO_ERROR_WRITE = 0xF126
+AFX_IDP_STATIC_OBJECT = 0xF180
+AFX_IDP_FAILED_TO_CONNECT = 0xF181
+AFX_IDP_SERVER_BUSY = 0xF182
+AFX_IDP_BAD_VERB = 0xF183
+AFX_IDP_FAILED_TO_NOTIFY = 0xF185
+AFX_IDP_FAILED_TO_LAUNCH = 0xF186
+AFX_IDP_ASK_TO_UPDATE = 0xF187
+AFX_IDP_FAILED_TO_UPDATE = 0xF188
+AFX_IDP_FAILED_TO_REGISTER = 0xF189
+AFX_IDP_FAILED_TO_AUTO_REGISTER = 0xF18A
+AFX_IDP_FAILED_TO_CONVERT = 0xF18B
+AFX_IDP_GET_NOT_SUPPORTED = 0xF18C
+AFX_IDP_SET_NOT_SUPPORTED = 0xF18D
+AFX_IDP_ASK_TO_DISCARD = 0xF18E
+AFX_IDP_FAILED_TO_CREATE = 0xF18F
+AFX_IDP_FAILED_MAPI_LOAD = 0xF190
+AFX_IDP_INVALID_MAPI_DLL = 0xF191
+AFX_IDP_FAILED_MAPI_SEND = 0xF192
+AFX_IDP_FILE_NONE = 0xF1A0
+AFX_IDP_FILE_GENERIC = 0xF1A1
+AFX_IDP_FILE_NOT_FOUND = 0xF1A2
+AFX_IDP_FILE_BAD_PATH = 0xF1A3
+AFX_IDP_FILE_TOO_MANY_OPEN = 0xF1A4
+AFX_IDP_FILE_ACCESS_DENIED = 0xF1A5
+AFX_IDP_FILE_INVALID_FILE = 0xF1A6
+AFX_IDP_FILE_REMOVE_CURRENT = 0xF1A7
+AFX_IDP_FILE_DIR_FULL = 0xF1A8
+AFX_IDP_FILE_BAD_SEEK = 0xF1A9
+AFX_IDP_FILE_HARD_IO = 0xF1AA
+AFX_IDP_FILE_SHARING = 0xF1AB
+AFX_IDP_FILE_LOCKING = 0xF1AC
+AFX_IDP_FILE_DISKFULL = 0xF1AD
+AFX_IDP_FILE_EOF = 0xF1AE
+AFX_IDP_ARCH_NONE = 0xF1B0
+AFX_IDP_ARCH_GENERIC = 0xF1B1
+AFX_IDP_ARCH_READONLY = 0xF1B2
+AFX_IDP_ARCH_ENDOFFILE = 0xF1B3
+AFX_IDP_ARCH_WRITEONLY = 0xF1B4
+AFX_IDP_ARCH_BADINDEX = 0xF1B5
+AFX_IDP_ARCH_BADCLASS = 0xF1B6
+AFX_IDP_ARCH_BADSCHEMA = 0xF1B7
+AFX_IDS_OCC_SCALEUNITS_PIXELS = 0xF1C0
+AFX_IDS_STATUS_FONT = 0xF230
+AFX_IDS_TOOLTIP_FONT = 0xF231
+AFX_IDS_UNICODE_FONT = 0xF232
+AFX_IDS_MINI_FONT = 0xF233
+AFX_IDP_SQL_FIRST = 0xF280
+AFX_IDP_SQL_CONNECT_FAIL = 0xF281
+AFX_IDP_SQL_RECORDSET_FORWARD_ONLY = 0xF282
+AFX_IDP_SQL_EMPTY_COLUMN_LIST = 0xF283
+AFX_IDP_SQL_FIELD_SCHEMA_MISMATCH = 0xF284
+AFX_IDP_SQL_ILLEGAL_MODE = 0xF285
+AFX_IDP_SQL_MULTIPLE_ROWS_AFFECTED = 0xF286
+AFX_IDP_SQL_NO_CURRENT_RECORD = 0xF287
+AFX_IDP_SQL_NO_ROWS_AFFECTED = 0xF288
+AFX_IDP_SQL_RECORDSET_READONLY = 0xF289
+AFX_IDP_SQL_SQL_NO_TOTAL = 0xF28A
+AFX_IDP_SQL_ODBC_LOAD_FAILED = 0xF28B
+AFX_IDP_SQL_DYNASET_NOT_SUPPORTED = 0xF28C
+AFX_IDP_SQL_SNAPSHOT_NOT_SUPPORTED = 0xF28D
+AFX_IDP_SQL_API_CONFORMANCE = 0xF28E
+AFX_IDP_SQL_SQL_CONFORMANCE = 0xF28F
+AFX_IDP_SQL_NO_DATA_FOUND = 0xF290
+AFX_IDP_SQL_ROW_UPDATE_NOT_SUPPORTED = 0xF291
+AFX_IDP_SQL_ODBC_V2_REQUIRED = 0xF292
+AFX_IDP_SQL_NO_POSITIONED_UPDATES = 0xF293
+AFX_IDP_SQL_LOCK_MODE_NOT_SUPPORTED = 0xF294
+AFX_IDP_SQL_DATA_TRUNCATED = 0xF295
+AFX_IDP_SQL_ROW_FETCH = 0xF296
+AFX_IDP_SQL_INCORRECT_ODBC = 0xF297
+AFX_IDP_SQL_UPDATE_DELETE_FAILED = 0xF298
+AFX_IDP_SQL_DYNAMIC_CURSOR_NOT_SUPPORTED = 0xF299
+AFX_IDP_DAO_FIRST = 0xF2A0
+AFX_IDP_DAO_ENGINE_INITIALIZATION = 0xF2A0
+AFX_IDP_DAO_DFX_BIND = 0xF2A1
+AFX_IDP_DAO_OBJECT_NOT_OPEN = 0xF2A2
+AFX_IDP_DAO_ROWTOOSHORT = 0xF2A3
+AFX_IDP_DAO_BADBINDINFO = 0xF2A4
+AFX_IDP_DAO_COLUMNUNAVAILABLE = 0xF2A5
+AFX_IDC_LISTBOX = 100
+AFX_IDC_CHANGE = 101
+AFX_IDC_PRINT_DOCNAME = 201
+AFX_IDC_PRINT_PRINTERNAME = 202
+AFX_IDC_PRINT_PORTNAME = 203
+AFX_IDC_PRINT_PAGENUM = 204
+ID_APPLY_NOW = 0x3021
+ID_WIZBACK = 0x3023
+ID_WIZNEXT = 0x3024
+ID_WIZFINISH = 0x3025
+AFX_IDC_TAB_CONTROL = 0x3020
+AFX_IDD_FILEOPEN = 28676
+AFX_IDD_FILESAVE = 28677
+AFX_IDD_FONT = 28678
+AFX_IDD_COLOR = 28679
+AFX_IDD_PRINT = 28680
+AFX_IDD_PRINTSETUP = 28681
+AFX_IDD_FIND = 28682
+AFX_IDD_REPLACE = 28683
+AFX_IDD_NEWTYPEDLG = 30721
+AFX_IDD_PRINTDLG = 30722
+AFX_IDD_PREVIEW_TOOLBAR = 30723
+AFX_IDD_PREVIEW_SHORTTOOLBAR = 30731
+AFX_IDD_INSERTOBJECT = 30724
+AFX_IDD_CHANGEICON = 30725
+AFX_IDD_CONVERT = 30726
+AFX_IDD_PASTESPECIAL = 30727
+AFX_IDD_EDITLINKS = 30728
+AFX_IDD_FILEBROWSE = 30729
+AFX_IDD_BUSY = 30730
+AFX_IDD_OBJECTPROPERTIES = 30732
+AFX_IDD_CHANGESOURCE = 30733
+AFX_IDC_CONTEXTHELP = 30977
+AFX_IDC_MAGNIFY = 30978
+AFX_IDC_SMALLARROWS = 30979
+AFX_IDC_HSPLITBAR = 30980
+AFX_IDC_VSPLITBAR = 30981
+AFX_IDC_NODROPCRSR = 30982
+AFX_IDC_TRACKNWSE = 30983
+AFX_IDC_TRACKNESW = 30984
+AFX_IDC_TRACKNS = 30985
+AFX_IDC_TRACKWE = 30986
+AFX_IDC_TRACK4WAY = 30987
+AFX_IDC_MOVE4WAY = 30988
+AFX_IDB_MINIFRAME_MENU = 30994
+AFX_IDB_CHECKLISTBOX_NT = 30995
+AFX_IDB_CHECKLISTBOX_95 = 30996
+AFX_IDR_PREVIEW_ACCEL = 30997
+AFX_IDI_STD_MDIFRAME = 31233
+AFX_IDI_STD_FRAME = 31234
+AFX_IDC_FONTPROP = 1000
+AFX_IDC_FONTNAMES = 1001
+AFX_IDC_FONTSTYLES = 1002
+AFX_IDC_FONTSIZES = 1003
+AFX_IDC_STRIKEOUT = 1004
+AFX_IDC_UNDERLINE = 1005
+AFX_IDC_SAMPLEBOX = 1006
+AFX_IDC_COLOR_BLACK = 1100
+AFX_IDC_COLOR_WHITE = 1101
+AFX_IDC_COLOR_RED = 1102
+AFX_IDC_COLOR_GREEN = 1103
+AFX_IDC_COLOR_BLUE = 1104
+AFX_IDC_COLOR_YELLOW = 1105
+AFX_IDC_COLOR_MAGENTA = 1106
+AFX_IDC_COLOR_CYAN = 1107
+AFX_IDC_COLOR_GRAY = 1108
+AFX_IDC_COLOR_LIGHTGRAY = 1109
+AFX_IDC_COLOR_DARKRED = 1110
+AFX_IDC_COLOR_DARKGREEN = 1111
+AFX_IDC_COLOR_DARKBLUE = 1112
+AFX_IDC_COLOR_LIGHTBROWN = 1113
+AFX_IDC_COLOR_DARKMAGENTA = 1114
+AFX_IDC_COLOR_DARKCYAN = 1115
+AFX_IDC_COLORPROP = 1116
+AFX_IDC_SYSTEMCOLORS = 1117
+AFX_IDC_PROPNAME = 1201
+AFX_IDC_PICTURE = 1202
+AFX_IDC_BROWSE = 1203
+AFX_IDC_CLEAR = 1204
+AFX_IDD_PROPPAGE_COLOR = 32257
+AFX_IDD_PROPPAGE_FONT = 32258
+AFX_IDD_PROPPAGE_PICTURE = 32259
+AFX_IDB_TRUETYPE = 32384
+AFX_IDS_PROPPAGE_UNKNOWN = 0xFE01
+AFX_IDS_COLOR_DESKTOP = 0xFE04
+AFX_IDS_COLOR_APPWORKSPACE = 0xFE05
+AFX_IDS_COLOR_WNDBACKGND = 0xFE06
+AFX_IDS_COLOR_WNDTEXT = 0xFE07
+AFX_IDS_COLOR_MENUBAR = 0xFE08
+AFX_IDS_COLOR_MENUTEXT = 0xFE09
+AFX_IDS_COLOR_ACTIVEBAR = 0xFE0A
+AFX_IDS_COLOR_INACTIVEBAR = 0xFE0B
+AFX_IDS_COLOR_ACTIVETEXT = 0xFE0C
+AFX_IDS_COLOR_INACTIVETEXT = 0xFE0D
+AFX_IDS_COLOR_ACTIVEBORDER = 0xFE0E
+AFX_IDS_COLOR_INACTIVEBORDER = 0xFE0F
+AFX_IDS_COLOR_WNDFRAME = 0xFE10
+AFX_IDS_COLOR_SCROLLBARS = 0xFE11
+AFX_IDS_COLOR_BTNFACE = 0xFE12
+AFX_IDS_COLOR_BTNSHADOW = 0xFE13
+AFX_IDS_COLOR_BTNTEXT = 0xFE14
+AFX_IDS_COLOR_BTNHIGHLIGHT = 0xFE15
+AFX_IDS_COLOR_DISABLEDTEXT = 0xFE16
+AFX_IDS_COLOR_HIGHLIGHT = 0xFE17
+AFX_IDS_COLOR_HIGHLIGHTTEXT = 0xFE18
+AFX_IDS_REGULAR = 0xFE19
+AFX_IDS_BOLD = 0xFE1A
+AFX_IDS_ITALIC = 0xFE1B
+AFX_IDS_BOLDITALIC = 0xFE1C
+AFX_IDS_SAMPLETEXT = 0xFE1D
+AFX_IDS_DISPLAYSTRING_FONT = 0xFE1E
+AFX_IDS_DISPLAYSTRING_COLOR = 0xFE1F
+AFX_IDS_DISPLAYSTRING_PICTURE = 0xFE20
+AFX_IDS_PICTUREFILTER = 0xFE21
+AFX_IDS_PICTYPE_UNKNOWN = 0xFE22
+AFX_IDS_PICTYPE_NONE = 0xFE23
+AFX_IDS_PICTYPE_BITMAP = 0xFE24
+AFX_IDS_PICTYPE_METAFILE = 0xFE25
+AFX_IDS_PICTYPE_ICON = 0xFE26
+AFX_IDS_COLOR_PPG = 0xFE28
+AFX_IDS_COLOR_PPG_CAPTION = 0xFE29
+AFX_IDS_FONT_PPG = 0xFE2A
+AFX_IDS_FONT_PPG_CAPTION = 0xFE2B
+AFX_IDS_PICTURE_PPG = 0xFE2C
+AFX_IDS_PICTURE_PPG_CAPTION = 0xFE2D
+AFX_IDS_PICTUREBROWSETITLE = 0xFE30
+AFX_IDS_BORDERSTYLE_0 = 0xFE31
+AFX_IDS_BORDERSTYLE_1 = 0xFE32
+AFX_IDS_VERB_EDIT = 0xFE40
+AFX_IDS_VERB_PROPERTIES = 0xFE41
+AFX_IDP_PICTURECANTOPEN = 0xFE83
+AFX_IDP_PICTURECANTLOAD = 0xFE84
+AFX_IDP_PICTURETOOLARGE = 0xFE85
+AFX_IDP_PICTUREREADFAILED = 0xFE86
+AFX_IDP_E_ILLEGALFUNCTIONCALL = 0xFEA0
+AFX_IDP_E_OVERFLOW = 0xFEA1
+AFX_IDP_E_OUTOFMEMORY = 0xFEA2
+AFX_IDP_E_DIVISIONBYZERO = 0xFEA3
+AFX_IDP_E_OUTOFSTRINGSPACE = 0xFEA4
+AFX_IDP_E_OUTOFSTACKSPACE = 0xFEA5
+AFX_IDP_E_BADFILENAMEORNUMBER = 0xFEA6
+AFX_IDP_E_FILENOTFOUND = 0xFEA7
+AFX_IDP_E_BADFILEMODE = 0xFEA8
+AFX_IDP_E_FILEALREADYOPEN = 0xFEA9
+AFX_IDP_E_DEVICEIOERROR = 0xFEAA
+AFX_IDP_E_FILEALREADYEXISTS = 0xFEAB
+AFX_IDP_E_BADRECORDLENGTH = 0xFEAC
+AFX_IDP_E_DISKFULL = 0xFEAD
+AFX_IDP_E_BADRECORDNUMBER = 0xFEAE
+AFX_IDP_E_BADFILENAME = 0xFEAF
+AFX_IDP_E_TOOMANYFILES = 0xFEB0
+AFX_IDP_E_DEVICEUNAVAILABLE = 0xFEB1
+AFX_IDP_E_PERMISSIONDENIED = 0xFEB2
+AFX_IDP_E_DISKNOTREADY = 0xFEB3
+AFX_IDP_E_PATHFILEACCESSERROR = 0xFEB4
+AFX_IDP_E_PATHNOTFOUND = 0xFEB5
+AFX_IDP_E_INVALIDPATTERNSTRING = 0xFEB6
+AFX_IDP_E_INVALIDUSEOFNULL = 0xFEB7
+AFX_IDP_E_INVALIDFILEFORMAT = 0xFEB8
+AFX_IDP_E_INVALIDPROPERTYVALUE = 0xFEB9
+AFX_IDP_E_INVALIDPROPERTYARRAYINDEX = 0xFEBA
+AFX_IDP_E_SETNOTSUPPORTEDATRUNTIME = 0xFEBB
+AFX_IDP_E_SETNOTSUPPORTED = 0xFEBC
+AFX_IDP_E_NEEDPROPERTYARRAYINDEX = 0xFEBD
+AFX_IDP_E_SETNOTPERMITTED = 0xFEBE
+AFX_IDP_E_GETNOTSUPPORTEDATRUNTIME = 0xFEBF
+AFX_IDP_E_GETNOTSUPPORTED = 0xFEC0
+AFX_IDP_E_PROPERTYNOTFOUND = 0xFEC1
+AFX_IDP_E_INVALIDCLIPBOARDFORMAT = 0xFEC2
+AFX_IDP_E_INVALIDPICTURE = 0xFEC3
+AFX_IDP_E_PRINTERERROR = 0xFEC4
+AFX_IDP_E_CANTSAVEFILETOTEMP = 0xFEC5
+AFX_IDP_E_SEARCHTEXTNOTFOUND = 0xFEC6
+AFX_IDP_E_REPLACEMENTSTOOLONG = 0xFEC7
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/dialog.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/dialog.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dbb98a7200eb809a2d83d048a1d351b2e526846
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/dialog.py
@@ -0,0 +1,277 @@
+""" \
+Base class for Dialogs. Also contains a few useful utility functions
+"""
+
+# dialog.py
+# Python class for Dialog Boxes in PythonWin.
+
+import win32con
+import win32ui
+
+from . import window
+
+
+def dllFromDll(dllid):
+ "given a 'dll' (maybe a dll, filename, etc), return a DLL object"
+ if dllid is None:
+ return None
+ elif isinstance(dllid, str):
+ return win32ui.LoadLibrary(dllid)
+ else:
+ try:
+ dllid.GetFileName()
+ except AttributeError:
+ raise TypeError("DLL parameter must be None, a filename or a dll object")
+ return dllid
+
+
+class Dialog(window.Wnd):
+ "Base class for a dialog"
+
+ def __init__(self, id, dllid=None):
+ """id is the resource ID, or a template
+ dllid may be None, a dll object, or a string with a dll name"""
+ # must take a reference to the DLL until InitDialog.
+ self.dll = dllFromDll(dllid)
+ if isinstance(id, list): # a template
+ dlg = win32ui.CreateDialogIndirect(id)
+ else:
+ dlg = win32ui.CreateDialog(id, self.dll)
+ window.Wnd.__init__(self, dlg)
+ self.HookCommands()
+ self.bHaveInit = None
+
+ def HookCommands(self):
+ pass
+
+ def OnAttachedObjectDeath(self):
+ self.data = self._obj_.data
+ window.Wnd.OnAttachedObjectDeath(self)
+
+ # provide virtuals.
+ def OnOK(self):
+ self._obj_.OnOK()
+
+ def OnCancel(self):
+ self._obj_.OnCancel()
+
+ def OnInitDialog(self):
+ self.bHaveInit = 1
+ if self._obj_.data:
+ self._obj_.UpdateData(0)
+ return 1 # I did NOT set focus to a child window.
+
+ def OnDestroy(self, msg):
+ self.dll = None # theoretically not needed if object destructs normally.
+
+ # DDX support
+ def AddDDX(self, *args):
+ self._obj_.datalist.append(args)
+
+ # Make a dialog object look like a dictionary for the DDX support
+ def __bool__(self):
+ return True
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, key):
+ return self.data[key]
+
+ def __setitem__(self, key, item):
+ self._obj_.data[key] = item # self.UpdateData(0)
+
+ def keys(self):
+ return self.data.keys()
+
+ def items(self):
+ return self.data.items()
+
+ def values(self):
+ return self.data.values()
+
+ def __contains__(self, key):
+ return key in self.data
+
+ has_key = __contains__
+
+
+class PrintDialog(Dialog):
+ "Base class for a print dialog"
+
+ def __init__(
+ self,
+ pInfo,
+ dlgID,
+ printSetupOnly=0,
+ flags=(
+ win32ui.PD_ALLPAGES
+ | win32ui.PD_USEDEVMODECOPIES
+ | win32ui.PD_NOPAGENUMS
+ | win32ui.PD_HIDEPRINTTOFILE
+ | win32ui.PD_NOSELECTION
+ ),
+ parent=None,
+ dllid=None,
+ ):
+ self.dll = dllFromDll(dllid)
+ if isinstance(dlgID, list): # a template
+ raise TypeError("dlgID parameter must be an integer resource ID")
+ dlg = win32ui.CreatePrintDialog(dlgID, printSetupOnly, flags, parent, self.dll)
+ window.Wnd.__init__(self, dlg)
+ self.HookCommands()
+ self.bHaveInit = None
+ self.pInfo = pInfo
+ # init values (if PrintSetup is called, values still available)
+ flags = pInfo.GetFlags()
+ self["toFile"] = flags & win32ui.PD_PRINTTOFILE != 0
+ self["direct"] = pInfo.GetDirect()
+ self["preview"] = pInfo.GetPreview()
+ self["continuePrinting"] = pInfo.GetContinuePrinting()
+ self["curPage"] = pInfo.GetCurPage()
+ self["numPreviewPages"] = pInfo.GetNumPreviewPages()
+ self["userData"] = pInfo.GetUserData()
+ self["draw"] = pInfo.GetDraw()
+ self["pageDesc"] = pInfo.GetPageDesc()
+ self["minPage"] = pInfo.GetMinPage()
+ self["maxPage"] = pInfo.GetMaxPage()
+ self["offsetPage"] = pInfo.GetOffsetPage()
+ self["fromPage"] = pInfo.GetFromPage()
+ self["toPage"] = pInfo.GetToPage()
+ # these values updated after OnOK
+ self["copies"] = 0
+ self["deviceName"] = ""
+ self["driverName"] = ""
+ self["printAll"] = 0
+ self["printCollate"] = 0
+ self["printRange"] = 0
+ self["printSelection"] = 0
+
+ def OnInitDialog(self):
+ self.pInfo.CreatePrinterDC() # This also sets the hDC of the pInfo structure.
+ return self._obj_.OnInitDialog()
+
+ def OnCancel(self):
+ del self.pInfo
+
+ def OnOK(self):
+ """DoModal has finished. Can now access the users choices"""
+ self._obj_.OnOK()
+ pInfo = self.pInfo
+ # user values
+ flags = pInfo.GetFlags()
+ self["toFile"] = flags & win32ui.PD_PRINTTOFILE != 0
+ self["direct"] = pInfo.GetDirect()
+ self["preview"] = pInfo.GetPreview()
+ self["continuePrinting"] = pInfo.GetContinuePrinting()
+ self["curPage"] = pInfo.GetCurPage()
+ self["numPreviewPages"] = pInfo.GetNumPreviewPages()
+ self["userData"] = pInfo.GetUserData()
+ self["draw"] = pInfo.GetDraw()
+ self["pageDesc"] = pInfo.GetPageDesc()
+ self["minPage"] = pInfo.GetMinPage()
+ self["maxPage"] = pInfo.GetMaxPage()
+ self["offsetPage"] = pInfo.GetOffsetPage()
+ self["fromPage"] = pInfo.GetFromPage()
+ self["toPage"] = pInfo.GetToPage()
+ self["copies"] = pInfo.GetCopies()
+ self["deviceName"] = pInfo.GetDeviceName()
+ self["driverName"] = pInfo.GetDriverName()
+ self["printAll"] = pInfo.PrintAll()
+ self["printCollate"] = pInfo.PrintCollate()
+ self["printRange"] = pInfo.PrintRange()
+ self["printSelection"] = pInfo.PrintSelection()
+ del self.pInfo
+
+
+class PropertyPage(Dialog):
+ "Base class for a Property Page"
+
+ def __init__(self, id, dllid=None, caption=0):
+ """id is the resource ID
+ dllid may be None, a dll object, or a string with a dll name"""
+
+ self.dll = dllFromDll(dllid)
+ if self.dll:
+ oldRes = win32ui.SetResource(self.dll)
+ if isinstance(id, list):
+ dlg = win32ui.CreatePropertyPageIndirect(id)
+ else:
+ dlg = win32ui.CreatePropertyPage(id, caption)
+ if self.dll:
+ win32ui.SetResource(oldRes)
+ # don't call dialog init!
+ window.Wnd.__init__(self, dlg)
+ self.HookCommands()
+
+
+class PropertySheet(window.Wnd):
+ def __init__(self, caption, dll=None, pageList=None): # parent=None, style,etc):
+ "Initialize a property sheet. pageList is a list of ID's"
+ # must take a reference to the DLL until InitDialog.
+ self.dll = dllFromDll(dll)
+ self.sheet = win32ui.CreatePropertySheet(caption)
+ window.Wnd.__init__(self, self.sheet)
+ if not pageList is None:
+ self.AddPage(pageList)
+
+ def OnInitDialog(self):
+ return self._obj_.OnInitDialog()
+
+ def DoModal(self):
+ if self.dll:
+ oldRes = win32ui.SetResource(self.dll)
+ rc = self.sheet.DoModal()
+ if self.dll:
+ win32ui.SetResource(oldRes)
+ return rc
+
+ def AddPage(self, pages):
+ if self.dll:
+ oldRes = win32ui.SetResource(self.dll)
+ try: # try list style access
+ pages[0]
+ isSeq = 1
+ except (TypeError, KeyError):
+ isSeq = 0
+ if isSeq:
+ for page in pages:
+ self.DoAddSinglePage(page)
+ else:
+ self.DoAddSinglePage(pages)
+ if self.dll:
+ win32ui.SetResource(oldRes)
+
+ def DoAddSinglePage(self, page):
+ "Page may be page, or int ID. Assumes DLL setup"
+ if isinstance(page, int):
+ self.sheet.AddPage(win32ui.CreatePropertyPage(page))
+ else:
+ self.sheet.AddPage(page)
+
+
+# define some app utility functions.
+def GetSimpleInput(prompt, defValue="", title=None):
+ """displays a dialog, and returns a string, or None if cancelled.
+ args prompt, defValue='', title=main frames title"""
+ # uses a simple dialog to return a string object.
+ if title is None:
+ title = win32ui.GetMainFrame().GetWindowText()
+
+ class DlgSimpleInput(Dialog):
+ def __init__(self, prompt, defValue, title):
+ self.title = title
+ Dialog.__init__(self, win32ui.IDD_SIMPLE_INPUT)
+ self.AddDDX(win32ui.IDC_EDIT1, "result")
+ self.AddDDX(win32ui.IDC_PROMPT1, "prompt")
+ self._obj_.data["result"] = defValue
+ self._obj_.data["prompt"] = prompt
+
+ def OnInitDialog(self):
+ self.SetWindowText(self.title)
+ return Dialog.OnInitDialog(self)
+
+ dlg = DlgSimpleInput(prompt, defValue, title)
+ if dlg.DoModal() != win32con.IDOK:
+ return None
+ return dlg["result"]
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/docview.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/docview.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5c7f99ac4de7c03220425d602ed13df8ff19d22
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/docview.py
@@ -0,0 +1,151 @@
+# document and view classes for MFC.
+import win32ui
+
+from . import object, window
+
+
+class View(window.Wnd):
+ def __init__(self, initobj):
+ window.Wnd.__init__(self, initobj)
+
+ def OnInitialUpdate(self):
+ pass
+
+
+# Simple control based views.
+class CtrlView(View):
+ def __init__(self, doc, wndclass, style=0):
+ View.__init__(self, win32ui.CreateCtrlView(doc, wndclass, style))
+
+
+class EditView(CtrlView):
+ def __init__(self, doc):
+ View.__init__(self, win32ui.CreateEditView(doc))
+
+
+class RichEditView(CtrlView):
+ def __init__(self, doc):
+ View.__init__(self, win32ui.CreateRichEditView(doc))
+
+
+class ListView(CtrlView):
+ def __init__(self, doc):
+ View.__init__(self, win32ui.CreateListView(doc))
+
+
+class TreeView(CtrlView):
+ def __init__(self, doc):
+ View.__init__(self, win32ui.CreateTreeView(doc))
+
+
+# Other more advanced views.
+class ScrollView(View):
+ def __init__(self, doc):
+ View.__init__(self, win32ui.CreateView(doc))
+
+
+class FormView(View):
+ def __init__(self, doc, id):
+ View.__init__(self, win32ui.CreateFormView(doc, id))
+
+
+class Document(object.CmdTarget):
+ def __init__(self, template, docobj=None):
+ if docobj is None:
+ docobj = template.DoCreateDoc()
+ object.CmdTarget.__init__(self, docobj)
+
+
+class RichEditDoc(object.CmdTarget):
+ def __init__(self, template):
+ object.CmdTarget.__init__(self, template.DoCreateRichEditDoc())
+
+
+class CreateContext:
+ "A transient base class used as a CreateContext"
+
+ def __init__(self, template, doc=None):
+ self.template = template
+ self.doc = doc
+
+ def __del__(self):
+ self.close()
+
+ def close(self):
+ self.doc = None
+ self.template = None
+
+
+class DocTemplate(object.CmdTarget):
+ def __init__(
+ self, resourceId=None, MakeDocument=None, MakeFrame=None, MakeView=None
+ ):
+ if resourceId is None:
+ resourceId = win32ui.IDR_PYTHONTYPE
+ object.CmdTarget.__init__(self, self._CreateDocTemplate(resourceId))
+ self.MakeDocument = MakeDocument
+ self.MakeFrame = MakeFrame
+ self.MakeView = MakeView
+ self._SetupSharedMenu_()
+
+ def _SetupSharedMenu_(self):
+ pass # to be overridden by each "app"
+
+ def _CreateDocTemplate(self, resourceId):
+ return win32ui.CreateDocTemplate(resourceId)
+
+ def __del__(self):
+ object.CmdTarget.__del__(self)
+
+ def CreateCreateContext(self, doc=None):
+ return CreateContext(self, doc)
+
+ def CreateNewFrame(self, doc):
+ makeFrame = self.MakeFrame
+ if makeFrame is None:
+ makeFrame = window.MDIChildWnd
+ wnd = makeFrame()
+ context = self.CreateCreateContext(doc)
+ wnd.LoadFrame(
+ self.GetResourceID(), -1, None, context
+ ) # triggers OnCreateClient...
+ return wnd
+
+ def CreateNewDocument(self):
+ makeDocument = self.MakeDocument
+ if makeDocument is None:
+ makeDocument = Document
+ return makeDocument(self)
+
+ def CreateView(self, frame, context):
+ makeView = self.MakeView
+ if makeView is None:
+ makeView = EditView
+ view = makeView(context.doc)
+ view.CreateWindow(frame)
+
+
+class RichEditDocTemplate(DocTemplate):
+ def __init__(
+ self, resourceId=None, MakeDocument=None, MakeFrame=None, MakeView=None
+ ):
+ if MakeView is None:
+ MakeView = RichEditView
+ if MakeDocument is None:
+ MakeDocument = RichEditDoc
+ DocTemplate.__init__(self, resourceId, MakeDocument, MakeFrame, MakeView)
+
+ def _CreateDocTemplate(self, resourceId):
+ return win32ui.CreateRichEditDocTemplate(resourceId)
+
+
+def t():
+ class FormTemplate(DocTemplate):
+ def CreateView(self, frame, context):
+ makeView = self.MakeView
+ # view = FormView(context.doc, win32ui.IDD_PROPDEMO1)
+ view = ListView(context.doc)
+ view.CreateWindow(frame)
+
+ t = FormTemplate()
+ return t.OpenDocumentFile(None)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/object.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/object.py
new file mode 100644
index 0000000000000000000000000000000000000000..64ed66037ec3f688f9cdace745f812fc3b497c03
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/object.py
@@ -0,0 +1,66 @@
+# MFC base classes.
+
+import win32ui
+
+
+class Object:
+ def __init__(self, initObj=None):
+ self.__dict__["_obj_"] = initObj
+ # self._obj_ = initObj
+ if initObj is not None:
+ initObj.AttachObject(self)
+
+ def __del__(self):
+ self.close()
+
+ def __getattr__(
+ self, attr
+ ): # Make this object look like the underlying win32ui one.
+ # During cleanup __dict__ is not available, causing recursive death.
+ if not attr.startswith("__"):
+ try:
+ o = self.__dict__["_obj_"]
+ if o is not None:
+ return getattr(o, attr)
+ # Only raise this error for non "internal" names -
+ # Python may be calling __len__, __bool__, etc, so
+ # we don't want this exception
+ if attr[0] != "_" and attr[-1] != "_":
+ raise win32ui.error("The MFC object has died.")
+ except KeyError:
+ # No _obj_ at all - don't report MFC object died when there isn't one!
+ pass
+ raise AttributeError(attr)
+
+ def OnAttachedObjectDeath(self):
+ # print("object", self.__class__.__name__, "dieing")
+ self._obj_ = None
+
+ def close(self):
+ if "_obj_" in self.__dict__:
+ if self._obj_ is not None:
+ self._obj_.AttachObject(None)
+ self._obj_ = None
+
+
+class CmdTarget(Object):
+ def __init__(self, initObj):
+ Object.__init__(self, initObj)
+
+ def HookNotifyRange(self, handler, firstID, lastID):
+ oldhandlers = []
+ for i in range(firstID, lastID + 1):
+ oldhandlers.append(self.HookNotify(handler, i))
+ return oldhandlers
+
+ def HookCommandRange(self, handler, firstID, lastID):
+ oldhandlers = []
+ for i in range(firstID, lastID + 1):
+ oldhandlers.append(self.HookCommand(handler, i))
+ return oldhandlers
+
+ def HookCommandUpdateRange(self, handler, firstID, lastID):
+ oldhandlers = []
+ for i in range(firstID, lastID + 1):
+ oldhandlers.append(self.HookCommandUpdate(handler, i))
+ return oldhandlers
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/thread.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/thread.py
new file mode 100644
index 0000000000000000000000000000000000000000..7bce1ab82e6c71eb2ea27ec4b85abc578425ab4d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/thread.py
@@ -0,0 +1,25 @@
+# Thread and application objects
+
+import win32ui
+
+from . import object
+
+
+class WinThread(object.CmdTarget):
+ def __init__(self, initObj=None):
+ if initObj is None:
+ initObj = win32ui.CreateThread()
+ object.CmdTarget.__init__(self, initObj)
+
+ def InitInstance(self):
+ pass # Default None/0 return indicates success for InitInstance()
+
+ def ExitInstance(self):
+ pass
+
+
+class WinApp(WinThread):
+ def __init__(self, initApp=None):
+ if initApp is None:
+ initApp = win32ui.GetApp()
+ WinThread.__init__(self, initApp)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/window.py b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/window.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb4721369b98fe55124dcffd940429dbe2b50a53
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/mfc/window.py
@@ -0,0 +1,50 @@
+# The MFCish window classes.
+import win32con
+import win32ui
+
+from . import object
+
+
+class Wnd(object.CmdTarget):
+ def __init__(self, initobj=None):
+ object.CmdTarget.__init__(self, initobj)
+ if self._obj_:
+ self._obj_.HookMessage(self.OnDestroy, win32con.WM_DESTROY)
+
+ def OnDestroy(self, msg):
+ pass
+
+
+# NOTE NOTE - This facility is currently disabled in Pythonwin!!!!!
+# Note - to process all messages for your window, add the following method
+# to a derived class. This code provides default message handling (ie, is
+# identical, except presumably in speed, as if the method did not exist at
+# all, so presumably will be modified to test for specific messages to be
+# useful!
+# def WindowProc(self, msg, wParam, lParam):
+# rc, lResult = self._obj_.OnWndMsg(msg, wParam, lParam)
+# if not rc: lResult = self._obj_.DefWindowProc(msg, wParam, lParam)
+# return lResult
+
+
+class FrameWnd(Wnd):
+ def __init__(self, wnd):
+ Wnd.__init__(self, wnd)
+
+
+class MDIChildWnd(FrameWnd):
+ def __init__(self, wnd=None):
+ if wnd is None:
+ wnd = win32ui.CreateMDIChild()
+ FrameWnd.__init__(self, wnd)
+
+ def OnCreateClient(self, cp, context):
+ if context is not None and context.template is not None:
+ context.template.CreateView(self, context)
+
+
+class MDIFrameWnd(FrameWnd):
+ def __init__(self, wnd=None):
+ if wnd is None:
+ wnd = win32ui.CreateMDIFrame()
+ FrameWnd.__init__(self, wnd)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/IDLEenvironment.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/IDLEenvironment.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8b5a058ff5e548ad58c939a5a63d83f86664178
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/IDLEenvironment.py
@@ -0,0 +1,593 @@
+# Code that allows Pythonwin to pretend it is IDLE
+# (at least as far as most IDLE extensions are concerned)
+
+import string
+import sys
+
+import win32api
+import win32con
+import win32ui
+from pywin import default_scintilla_encoding
+from pywin.mfc.dialog import GetSimpleInput
+
+wordchars = string.ascii_uppercase + string.ascii_lowercase + string.digits
+
+
+class TextError(Exception): # When a TclError would normally be raised.
+ pass
+
+
+class EmptyRange(Exception): # Internally raised.
+ pass
+
+
+def GetIDLEModule(module):
+ try:
+ # First get it from Pythonwin it is exists.
+ modname = "pywin.idle." + module
+ __import__(modname)
+ except ImportError as details:
+ msg = (
+ f"The IDLE extension '{module}' can not be located.\r\n\r\n"
+ "Please correct the installation and restart the"
+ f" application.\r\n\r\n{details}"
+ )
+ win32ui.MessageBox(msg)
+ return None
+ mod = sys.modules[modname]
+ mod.TclError = TextError # A hack that can go soon!
+ return mod
+
+
+# A class that is injected into the IDLE auto-indent extension.
+# It allows for decent performance when opening a new file,
+# as auto-indent uses the tokenizer module to determine indents.
+# The default AutoIndent readline method works OK, but it goes through
+# this layer of Tk index indirection for every single line. For large files
+# without indents (and even small files with indents :-) it was pretty slow!
+def fast_readline(self):
+ if self.finished:
+ val = ""
+ else:
+ if "_scint_lines" not in self.__dict__:
+ # XXX - note - assumes this is only called once the file is loaded!
+ self._scint_lines = self.text.edit.GetTextRange().split("\n")
+ sl = self._scint_lines
+ i = self.i = self.i + 1
+ if i >= len(sl):
+ val = ""
+ else:
+ val = sl[i] + "\n"
+ return val.encode(default_scintilla_encoding)
+
+
+try:
+ GetIDLEModule("AutoIndent").IndentSearcher.readline = fast_readline
+except AttributeError: # GetIDLEModule may return None
+ pass
+
+
+# A class that attempts to emulate an IDLE editor window.
+# Construct with a Pythonwin view.
+class IDLEEditorWindow:
+ def __init__(self, edit):
+ self.edit = edit
+ self.text = TkText(edit)
+ self.extensions = {}
+ self.extension_menus = {}
+
+ def close(self):
+ self.edit = self.text = None
+ self.extension_menus = None
+ try:
+ for ext in self.extensions.values():
+ closer = getattr(ext, "close", None)
+ if closer is not None:
+ closer()
+ finally:
+ self.extensions = {}
+
+ def IDLEExtension(self, extension):
+ ext = self.extensions.get(extension)
+ if ext is not None:
+ return ext
+ mod = GetIDLEModule(extension)
+ if mod is None:
+ return None
+ klass = getattr(mod, extension)
+ ext = self.extensions[extension] = klass(self)
+ # Find and bind all the events defined in the extension.
+ events = [item for item in dir(klass) if item[-6:] == "_event"]
+ for event in events:
+ name = "<<{}>>".format(event[:-6].replace("_", "-"))
+ self.edit.bindings.bind(name, getattr(ext, event))
+ return ext
+
+ def GetMenuItems(self, menu_name):
+ # Get all menu items for the menu name (eg, "edit")
+ bindings = self.edit.bindings
+ ret = []
+ for ext in self.extensions.values():
+ menudefs = getattr(ext, "menudefs", [])
+ for name, items in menudefs:
+ if name == menu_name:
+ for text, event in [item for item in items if item is not None]:
+ text = text.replace("&", "&&")
+ text = text.replace("_", "&")
+ ret.append((text, event))
+ return ret
+
+ ######################################################################
+ # The IDLE "Virtual UI" methods that are exposed to the IDLE extensions.
+ #
+ def askinteger(
+ self, caption, prompt, parent=None, initialvalue=0, minvalue=None, maxvalue=None
+ ):
+ while 1:
+ rc = GetSimpleInput(prompt, str(initialvalue), caption)
+ if rc is None:
+ return 0 # Correct "cancel" semantics?
+ err = None
+ try:
+ rc = int(rc)
+ except ValueError:
+ err = "Please enter an integer"
+ if not err and minvalue is not None and rc < minvalue:
+ err = f"Please enter an integer greater then or equal to {minvalue}"
+ if not err and maxvalue is not None and rc > maxvalue:
+ err = f"Please enter an integer less then or equal to {maxvalue}"
+ if err:
+ win32ui.MessageBox(err, caption, win32con.MB_OK)
+ continue
+ return rc
+
+ def askyesno(self, caption, prompt, parent=None):
+ return win32ui.MessageBox(prompt, caption, win32con.MB_YESNO) == win32con.IDYES
+
+ ######################################################################
+ # The IDLE "Virtual Text Widget" methods that are exposed to the IDLE extensions.
+ #
+
+ # Is character at text_index in a Python string? Return 0 for
+ # "guaranteed no", true for anything else.
+ def is_char_in_string(self, text_index):
+ # A helper for the code analyser - we need internal knowledge of
+ # the colorizer to get this information
+ # This assumes the colorizer has got to this point!
+ text_index = self.text._getoffset(text_index)
+ c = self.text.edit._GetColorizer()
+ if c and c.GetStringStyle(text_index) is None:
+ return 0
+ return 1
+
+ # If a selection is defined in the text widget, return
+ # (start, end) as Tkinter text indices, otherwise return
+ # (None, None)
+ def get_selection_indices(self):
+ try:
+ first = self.text.index("sel.first")
+ last = self.text.index("sel.last")
+ return first, last
+ except TextError:
+ return None, None
+
+ def set_tabwidth(self, width):
+ self.edit.SCISetTabWidth(width)
+
+ def get_tabwidth(self):
+ return self.edit.GetTabWidth()
+
+
+# A class providing the generic "Call Tips" interface
+class CallTips:
+ def __init__(self, edit):
+ self.edit = edit
+
+ def showtip(self, tip_text):
+ self.edit.SCICallTipShow(tip_text)
+
+ def hidetip(self):
+ self.edit.SCICallTipCancel()
+
+
+########################################
+#
+# Helpers for the TkText emulation.
+def TkOffsetToIndex(offset, edit):
+ lineoff = 0
+ # May be 1 > actual end if we pretended there was a trailing '\n'
+ offset = min(offset, edit.GetTextLength())
+ line = edit.LineFromChar(offset)
+ lineIndex = edit.LineIndex(line)
+ return "%d.%d" % (line + 1, offset - lineIndex)
+
+
+def _NextTok(str, pos):
+ # Returns (token, endPos)
+ end = len(str)
+ if pos >= end:
+ return None, 0
+ while pos < end and str[pos] in string.whitespace:
+ pos += 1
+ # Special case for +-
+ if str[pos] in "+-":
+ return str[pos], pos + 1
+ # Digits also a special case.
+ endPos = pos
+ while endPos < end and str[endPos] in string.digits + ".":
+ endPos += 1
+ if pos != endPos:
+ return str[pos:endPos], endPos
+ endPos = pos
+ while endPos < end and str[endPos] not in string.whitespace + string.digits + "+-":
+ endPos += 1
+ if pos != endPos:
+ return str[pos:endPos], endPos
+ return None, 0
+
+
+def TkIndexToOffset(bm, edit, marks):
+ base, nextTokPos = _NextTok(bm, 0)
+ if base is None:
+ raise ValueError("Empty bookmark ID!")
+ if base.find(".") > 0:
+ try:
+ line, col = base.split(".", 2)
+ if col == "first" or col == "last":
+ # Tag name
+ if line != "sel":
+ raise ValueError("Tags aren't here!")
+ sel = edit.GetSel()
+ if sel[0] == sel[1]:
+ raise EmptyRange
+ if col == "first":
+ pos = sel[0]
+ else:
+ pos = sel[1]
+ else:
+ # Lines are 1 based for tkinter
+ line = int(line) - 1
+ if line > edit.GetLineCount():
+ pos = edit.GetTextLength() + 1
+ else:
+ pos = edit.LineIndex(line)
+ if pos == -1:
+ pos = edit.GetTextLength()
+ pos += int(col)
+ except (ValueError, IndexError):
+ raise ValueError("Unexpected literal in '%s'" % base)
+ elif base == "insert":
+ pos = edit.GetSel()[0]
+ elif base == "end":
+ pos = edit.GetTextLength()
+ # Pretend there is a trailing '\n' if necessary
+ if pos and edit.SCIGetCharAt(pos - 1) != "\n":
+ pos += 1
+ else:
+ try:
+ pos = marks[base]
+ except KeyError:
+ raise ValueError("Unsupported base offset or undefined mark '%s'" % base)
+
+ while 1:
+ word, nextTokPos = _NextTok(bm, nextTokPos)
+ if word is None:
+ break
+ if word in ("+", "-"):
+ num, nextTokPos = _NextTok(bm, nextTokPos)
+ if num is None:
+ raise ValueError("+/- operator needs 2 args")
+ what, nextTokPos = _NextTok(bm, nextTokPos)
+ if what is None:
+ raise ValueError("+/- operator needs 2 args")
+ if what[0] != "c":
+ raise ValueError("+/- only supports chars")
+ if word == "+":
+ pos += int(num)
+ else:
+ pos -= int(num)
+ elif word == "wordstart":
+ while pos > 0 and edit.SCIGetCharAt(pos - 1) in wordchars:
+ pos -= 1
+ elif word == "wordend":
+ end = edit.GetTextLength()
+ while pos < end and edit.SCIGetCharAt(pos) in wordchars:
+ pos += 1
+ elif word == "linestart":
+ while pos > 0 and edit.SCIGetCharAt(pos - 1) not in "\n\r":
+ pos -= 1
+ elif word == "lineend":
+ end = edit.GetTextLength()
+ while pos < end and edit.SCIGetCharAt(pos) not in "\n\r":
+ pos += 1
+ else:
+ raise ValueError("Unsupported relative offset '%s'" % word)
+ return max(pos, 0) # Tkinter is tollerant of -ve indexes - we aren't
+
+
+# A class that resembles an IDLE (ie, a Tk) text widget.
+# Construct with an edit object (eg, an editor view)
+class TkText:
+ def __init__(self, edit):
+ self.calltips = None
+ self.edit = edit
+ self.marks = {}
+
+ ## def __getattr__(self, attr):
+ ## if attr=="tk": return self # So text.tk.call works.
+ ## if attr=="master": return None # ditto!
+ ## raise AttributeError, attr
+ ## def __getitem__(self, item):
+ ## if item=="tabs":
+ ## size = self.edit.GetTabWidth()
+ ## if size==8: return "" # Tk default
+ ## return size # correct semantics?
+ ## elif item=="font": # Used for measurements we don't need to do!
+ ## return "Don't know the font"
+ ## raise IndexError, "Invalid index '%s'" % item
+ def make_calltip_window(self):
+ if self.calltips is None:
+ self.calltips = CallTips(self.edit)
+ return self.calltips
+
+ def _getoffset(self, index):
+ return TkIndexToOffset(index, self.edit, self.marks)
+
+ def _getindex(self, off):
+ return TkOffsetToIndex(off, self.edit)
+
+ def _fix_indexes(self, start, end):
+ # first some magic to handle skipping over utf8 extended chars.
+ while start > 0 and ord(self.edit.SCIGetCharAt(start)) & 0xC0 == 0x80:
+ start -= 1
+ while (
+ end < self.edit.GetTextLength()
+ and ord(self.edit.SCIGetCharAt(end)) & 0xC0 == 0x80
+ ):
+ end += 1
+ # now handling fixing \r\n->\n disparities...
+ if (
+ start > 0
+ and self.edit.SCIGetCharAt(start) == "\n"
+ and self.edit.SCIGetCharAt(start - 1) == "\r"
+ ):
+ start -= 1
+ if (
+ end < self.edit.GetTextLength()
+ and self.edit.SCIGetCharAt(end - 1) == "\r"
+ and self.edit.SCIGetCharAt(end) == "\n"
+ ):
+ end += 1
+ return start, end
+
+ ## def get_tab_width(self):
+ ## return self.edit.GetTabWidth()
+ ## def call(self, *rest):
+ ## # Crap to support Tk measurement hacks for tab widths
+ ## if rest[0] != "font" or rest[1] != "measure":
+ ## raise ValueError, "Unsupport call type"
+ ## return len(rest[5])
+ ## def configure(self, **kw):
+ ## for name, val in kw.items():
+ ## if name=="tabs":
+ ## self.edit.SCISetTabWidth(int(val))
+ ## else:
+ ## raise ValueError, "Unsupported configuration item %s" % kw
+ def bind(self, binding, handler):
+ self.edit.bindings.bind(binding, handler)
+
+ def get(self, start, end=None):
+ try:
+ start = self._getoffset(start)
+ if end is None:
+ end = start + 1
+ else:
+ end = self._getoffset(end)
+ except EmptyRange:
+ return ""
+ # Simple semantic checks to conform to the Tk text interface
+ if end <= start:
+ return ""
+ max = self.edit.GetTextLength()
+ checkEnd = 0
+ if end > max:
+ end = max
+ checkEnd = 1
+ start, end = self._fix_indexes(start, end)
+ ret = self.edit.GetTextRange(start, end)
+ # pretend a trailing '\n' exists if necessary.
+ if checkEnd and (not ret or ret[-1] != "\n"):
+ ret += "\n"
+ return ret.replace("\r", "")
+
+ def index(self, spec):
+ try:
+ return self._getindex(self._getoffset(spec))
+ except EmptyRange:
+ return ""
+
+ def insert(self, pos, text):
+ try:
+ pos = self._getoffset(pos)
+ except EmptyRange:
+ raise TextError("Empty range")
+ self.edit.SetSel((pos, pos))
+ # IDLE only deals with "\n" - we will be nicer
+
+ bits = text.split("\n")
+ self.edit.SCIAddText(bits[0])
+ for bit in bits[1:]:
+ self.edit.SCINewline()
+ self.edit.SCIAddText(bit)
+
+ def delete(self, start, end=None):
+ try:
+ start = self._getoffset(start)
+ if end is not None:
+ end = self._getoffset(end)
+ except EmptyRange:
+ raise TextError("Empty range")
+ # If end is specified and == start, then we must delete nothing.
+ if start == end:
+ return
+ # If end is not specified, delete one char
+ if end is None:
+ end = start + 1
+ else:
+ # Tk says not to delete in this case, but our control would.
+ if end < start:
+ return
+ if start == self.edit.GetTextLength():
+ return # Nothing to delete.
+ old = self.edit.GetSel()[0] # Lose a selection
+ # Hack for partial '\r\n' and UTF-8 char removal
+ start, end = self._fix_indexes(start, end)
+ self.edit.SetSel((start, end))
+ self.edit.Clear()
+ if old >= start and old < end:
+ old = start
+ elif old >= end:
+ old -= end - start
+ self.edit.SetSel(old)
+
+ def bell(self):
+ win32api.MessageBeep()
+
+ def see(self, pos):
+ # Most commands we use in Scintilla actually force the selection
+ # to be seen, making this unnecessary.
+ pass
+
+ def mark_set(self, name, pos):
+ try:
+ pos = self._getoffset(pos)
+ except EmptyRange:
+ raise TextError("Empty range '%s'" % pos)
+ if name == "insert":
+ self.edit.SetSel(pos)
+ else:
+ self.marks[name] = pos
+
+ def tag_add(self, name, start, end):
+ if name != "sel":
+ raise ValueError("Only sel tag is supported")
+ try:
+ start = self._getoffset(start)
+ end = self._getoffset(end)
+ except EmptyRange:
+ raise TextError("Empty range")
+ self.edit.SetSel(start, end)
+
+ def tag_remove(self, name, start, end):
+ if name != "sel" or start != "1.0" or end != "end":
+ raise ValueError("Can't remove this tag")
+ # Turn the sel into a cursor
+ self.edit.SetSel(self.edit.GetSel()[0])
+
+ def compare(self, i1, op, i2):
+ try:
+ i1 = self._getoffset(i1)
+ except EmptyRange:
+ i1 = ""
+ try:
+ i2 = self._getoffset(i2)
+ except EmptyRange:
+ i2 = ""
+ return eval("%d%s%d" % (i1, op, i2))
+
+ def undo_block_start(self):
+ self.edit.SCIBeginUndoAction()
+
+ def undo_block_stop(self):
+ self.edit.SCIEndUndoAction()
+
+
+######################################################################
+#
+# Test related code.
+#
+######################################################################
+def TestCheck(index, edit, expected=None):
+ rc = TkIndexToOffset(index, edit, {})
+ if rc != expected:
+ print("ERROR: Index", index, ", expected", expected, "but got", rc)
+
+
+def TestGet(fr, to, t, expected):
+ got = t.get(fr, to)
+ if got != expected:
+ print(f"ERROR: get({fr!r}, {to!r}) expected {expected!r}, but got {got!r}")
+
+
+def test():
+ import pywin.framework.editor
+
+ d = pywin.framework.editor.editorTemplate.OpenDocumentFile(None)
+ e = d.GetFirstView()
+ t = TkText(e)
+ e.SCIAddText("hi there how\nare you today\r\nI hope you are well")
+ e.SetSel((4, 4))
+
+ skip = """
+ TestCheck("insert", e, 4)
+ TestCheck("insert wordstart", e, 3)
+ TestCheck("insert wordend", e, 8)
+ TestCheck("insert linestart", e, 0)
+ TestCheck("insert lineend", e, 12)
+ TestCheck("insert + 4 chars", e, 8)
+ TestCheck("insert +4c", e, 8)
+ TestCheck("insert - 2 chars", e, 2)
+ TestCheck("insert -2c", e, 2)
+ TestCheck("insert-2c", e, 2)
+ TestCheck("insert-2 c", e, 2)
+ TestCheck("insert- 2c", e, 2)
+ TestCheck("1.1", e, 1)
+ TestCheck("1.0", e, 0)
+ TestCheck("2.0", e, 13)
+ try:
+ TestCheck("sel.first", e, 0)
+ print("*** sel.first worked with an empty selection")
+ except TextError:
+ pass
+ e.SetSel((4,5))
+ TestCheck("sel.first- 2c", e, 2)
+ TestCheck("sel.last- 2c", e, 3)
+ """
+ # Check EOL semantics
+ e.SetSel((4, 4))
+ TestGet("insert lineend", "insert lineend +1c", t, "\n")
+ e.SetSel((20, 20))
+ TestGet("insert lineend", "insert lineend +1c", t, "\n")
+ e.SetSel((35, 35))
+ TestGet("insert lineend", "insert lineend +1c", t, "\n")
+
+
+class IDLEWrapper:
+ def __init__(self, control):
+ self.text = control
+
+
+def IDLETest(extension):
+ import os
+ import sys
+
+ modname = "pywin.idle." + extension
+ __import__(modname)
+ mod = sys.modules[modname]
+ mod.TclError = TextError
+ klass = getattr(mod, extension)
+
+ # Create a new Scintilla Window.
+ import pywin.framework.editor
+
+ d = pywin.framework.editor.editorTemplate.OpenDocumentFile(None)
+ v = d.GetFirstView()
+ fname = os.path.splitext(__file__)[0] + ".py"
+ v.SCIAddText(open(fname).read())
+ d.SetModifiedFlag(0)
+ r = klass(IDLEWrapper(TkText(v)))
+ return r
+
+
+if __name__ == "__main__":
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..46175df8b9e4be646aa0f9f2fe8c593bdc9a1625
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/__init__.py
@@ -0,0 +1 @@
+# package init.
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/bindings.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/bindings.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e510d3698ae473fe79ab3f16b3e443b993f853e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/bindings.py
@@ -0,0 +1,180 @@
+from __future__ import annotations
+
+import traceback
+
+import win32api
+import win32con
+import win32ui
+
+from . import ( # nopycln: import # Injects fast_readline into the IDLE auto-indent extension
+ IDLEenvironment,
+)
+
+HANDLER_ARGS_GUESS = 0
+HANDLER_ARGS_NATIVE = 1
+HANDLER_ARGS_IDLE = 2
+HANDLER_ARGS_EXTENSION = 3
+
+next_id = 5000
+
+event_to_commands: dict[str, int] = {} # dict of event names to IDs
+command_to_events: dict[int, str] = {} # dict of IDs to event names
+
+
+def assign_command_id(event, id=0):
+ global next_id
+ if id == 0:
+ id = event_to_commands.get(event, 0)
+ if id == 0:
+ id = next_id
+ next_id += 1
+ # Only map the ones we allocated - specified ones are assumed to have a handler
+ command_to_events[id] = event
+ event_to_commands[event] = id
+ return id
+
+
+class SendCommandHandler:
+ def __init__(self, cmd):
+ self.cmd = cmd
+
+ def __call__(self, *args):
+ win32ui.GetMainFrame().SendMessage(win32con.WM_COMMAND, self.cmd)
+
+
+class Binding:
+ def __init__(self, handler, handler_args_type):
+ self.handler = handler
+ self.handler_args_type = handler_args_type
+
+
+class BindingsManager:
+ def __init__(self, parent_view):
+ self.parent_view = parent_view
+ self.bindings = {} # dict of Binding instances.
+ self.keymap = {}
+
+ def prepare_configure(self):
+ self.keymap = {}
+
+ def complete_configure(self):
+ for id in command_to_events:
+ self.parent_view.HookCommand(self._OnCommand, id)
+
+ def close(self):
+ self.parent_view = self.bindings = self.keymap = None
+
+ def report_error(self, problem):
+ try:
+ win32ui.SetStatusText(problem, 1)
+ except win32ui.error:
+ # No status bar!
+ print(problem)
+
+ def update_keymap(self, keymap):
+ self.keymap.update(keymap)
+
+ def bind(self, event, handler, handler_args_type=HANDLER_ARGS_GUESS, cid=0):
+ if handler is None:
+ handler = SendCommandHandler(cid)
+ self.bindings[event] = self._new_binding(handler, handler_args_type)
+ self.bind_command(event, cid)
+
+ def bind_command(self, event, id=0):
+ "Binds an event to a Windows control/command ID"
+ id = assign_command_id(event, id)
+ return id
+
+ def get_command_id(self, event):
+ id = event_to_commands.get(event)
+ if id is None:
+ # See if we even have an event of that name!?
+ if event not in self.bindings:
+ return None
+ id = self.bind_command(event)
+ return id
+
+ def _OnCommand(self, id, code):
+ event = command_to_events.get(id)
+ if event is None:
+ self.report_error("No event associated with event ID %d" % id)
+ return 1
+ return self.fire(event)
+
+ def _new_binding(self, event, handler_args_type):
+ return Binding(event, handler_args_type)
+
+ def _get_IDLE_handler(self, ext, handler):
+ try:
+ instance = self.parent_view.idle.IDLEExtension(ext)
+ name = handler.replace("-", "_") + "_event"
+ return getattr(instance, name)
+ except (ImportError, AttributeError):
+ msg = f"Can not find event '{handler}' in IDLE extension '{ext}'"
+ self.report_error(msg)
+ return None
+
+ def fire(self, event, event_param=None):
+ # Fire the specified event. Result is native Pythonwin result
+ # (ie, 1==pass one, 0 or None==handled)
+
+ # First look up the event directly - if there, we are set.
+ binding = self.bindings.get(event)
+ if binding is None:
+ # If possible, find it!
+ # A native method name
+ handler = getattr(self.parent_view, event + "Event", None)
+ if handler is None:
+ # Can't decide if I should report an error??
+ self.report_error("The event name '%s' can not be found." % event)
+ # Either way, just let the default handlers grab it.
+ return 1
+ binding = self._new_binding(handler, HANDLER_ARGS_NATIVE)
+ # Cache it.
+ self.bindings[event] = binding
+
+ handler_args_type = binding.handler_args_type
+ # Now actually fire it.
+ if handler_args_type == HANDLER_ARGS_GUESS:
+ # Can't be native, as natives are never added with "guess".
+ # Must be extension or IDLE.
+ if event[0] == "<":
+ handler_args_type = HANDLER_ARGS_IDLE
+ else:
+ handler_args_type = HANDLER_ARGS_EXTENSION
+ try:
+ if handler_args_type == HANDLER_ARGS_EXTENSION:
+ args = self.parent_view.idle, event_param
+ else:
+ args = (event_param,)
+ rc = binding.handler(*args)
+ if handler_args_type == HANDLER_ARGS_IDLE:
+ # Convert to our return code.
+ if rc in (None, "break"):
+ rc = 0
+ else:
+ rc = 1
+ except:
+ message = "Firing event '%s' failed." % event
+ print(message)
+ traceback.print_exc()
+ self.report_error(message)
+ rc = 1 # Let any default handlers have a go!
+ return rc
+
+ def fire_key_event(self, msg):
+ key = msg[2]
+ keyState = 0
+ if win32api.GetKeyState(win32con.VK_CONTROL) & 0x8000:
+ keyState |= win32con.RIGHT_CTRL_PRESSED | win32con.LEFT_CTRL_PRESSED
+ if win32api.GetKeyState(win32con.VK_SHIFT) & 0x8000:
+ keyState |= win32con.SHIFT_PRESSED
+ if win32api.GetKeyState(win32con.VK_MENU) & 0x8000:
+ keyState |= win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED
+ keyinfo = key, keyState
+ # Special hacks for the dead-char key on non-US keyboards.
+ # (XXX - which do not work :-(
+ event = self.keymap.get(keyinfo)
+ if event is None:
+ return 1
+ return self.fire(event, None)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/config.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..d601402bb96088fcc60a6a2baf50a19fd2c015a9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/config.py
@@ -0,0 +1,363 @@
+# config.py - deals with loading configuration information.
+
+# Loads config data from a .cfg file. Also caches the compiled
+# data back into a .cfc file.
+
+# If you are wondering how to avoid needing .cfg files (eg,
+# if you are freezing Pythonwin etc) I suggest you create a
+# .py file, and put the config info in a docstring. Then
+# pass a CStringIO file (rather than a filename) to the
+# config manager.
+import glob
+import importlib.util
+import marshal
+import os
+import stat
+import sys
+import traceback
+import types
+
+import pywin
+import win32api
+
+from . import keycodes
+
+debugging = 0
+if debugging:
+ import win32traceutil # Some trace statements fire before the interactive window is open.
+
+ def trace(*args):
+ sys.stderr.write(" ".join(map(str, args)) + "\n")
+
+else:
+ trace = lambda *args: None
+
+compiled_config_version = 3
+
+
+def split_line(line, lineno):
+ comment_pos = line.find("#")
+ if comment_pos >= 0:
+ line = line[:comment_pos]
+ sep_pos = line.rfind("=")
+ if sep_pos == -1:
+ if line.strip():
+ print(f"Warning: Line {lineno}: {line!r} is an invalid entry")
+ return None, None
+ return "", ""
+ return line[:sep_pos].strip(), line[sep_pos + 1 :].strip()
+
+
+def get_section_header(line):
+ # Returns the section if the line is a section header, else None
+ if line[0] == "[":
+ end = line.find("]")
+ if end == -1:
+ end = len(line)
+ rc = line[1:end].lower()
+ try:
+ i = rc.index(":")
+ return rc[:i], rc[i + 1 :]
+ except ValueError:
+ return rc, ""
+ return None, None
+
+
+def find_config_file(f):
+ return os.path.join(next(iter(pywin.__path__)), f + ".cfg")
+
+
+def find_config_files():
+ return [
+ os.path.split(x)[1]
+ for x in [
+ os.path.splitext(x)[0]
+ for x in glob.glob(os.path.join(next(iter(pywin.__path__)), "*.cfg"))
+ ]
+ ]
+
+
+class ConfigManager:
+ def __init__(self, f):
+ self.filename = "unknown"
+ self.last_error = None
+ self.key_to_events = {}
+ b_close = False
+ if hasattr(f, "readline"):
+ fp = f
+ self.filename = ""
+ compiled_name = None
+ else:
+ try:
+ f = find_config_file(f)
+ src_stat = os.stat(f)
+ except OSError:
+ self.report_error("Config file '%s' not found" % f)
+ return
+ self.filename = f
+ self.basename = os.path.basename(f)
+ trace("Loading configuration", self.basename)
+ compiled_name = os.path.splitext(f)[0] + ".cfc"
+ try:
+ cf = open(compiled_name, "rb")
+ try:
+ ver = marshal.load(cf)
+ ok = compiled_config_version == ver
+ if ok:
+ kblayoutname = marshal.load(cf)
+ magic = marshal.load(cf)
+ size = marshal.load(cf)
+ mtime = marshal.load(cf)
+ if (
+ magic == importlib.util.MAGIC_NUMBER
+ and win32api.GetKeyboardLayoutName() == kblayoutname
+ and src_stat[stat.ST_MTIME] == mtime
+ and src_stat[stat.ST_SIZE] == size
+ ):
+ self.cache = marshal.load(cf)
+ trace("Configuration loaded cached", compiled_name)
+ return # We are ready to roll!
+ finally:
+ cf.close()
+ except (OSError, EOFError):
+ pass
+ fp = open(f)
+ b_close = True
+ self.cache = {}
+ lineno = 1
+ line = fp.readline()
+ while line:
+ # Skip to the next section (maybe already there!)
+ section, subsection = get_section_header(line)
+ while line and section is None:
+ line = fp.readline()
+ if not line:
+ break
+ lineno += 1
+ section, subsection = get_section_header(line)
+ if not line:
+ break
+
+ if section == "keys":
+ line, lineno = self._load_keys(subsection, fp, lineno)
+ elif section == "extensions":
+ line, lineno = self._load_extensions(subsection, fp, lineno)
+ elif section == "idle extensions":
+ line, lineno = self._load_idle_extensions(subsection, fp, lineno)
+ elif section == "general":
+ line, lineno = self._load_general(subsection, fp, lineno)
+ else:
+ self.report_error(
+ f"Unrecognised section header '{section}:{subsection}'"
+ )
+ line = fp.readline()
+ lineno += 1
+ if b_close:
+ fp.close()
+ # Check critical data.
+ if not self.cache.get("keys"):
+ self.report_error("No keyboard definitions were loaded")
+ if not self.last_error and compiled_name:
+ try:
+ cf = open(compiled_name, "wb")
+ marshal.dump(compiled_config_version, cf)
+ marshal.dump(win32api.GetKeyboardLayoutName(), cf)
+ marshal.dump(importlib.util.MAGIC_NUMBER, cf)
+ marshal.dump(src_stat[stat.ST_SIZE], cf)
+ marshal.dump(src_stat[stat.ST_MTIME], cf)
+ marshal.dump(self.cache, cf)
+ cf.close()
+ except (OSError, EOFError):
+ pass # Ignore errors - may be read only.
+
+ def configure(self, editor, subsections=None):
+ # Execute the extension code, and find any events.
+ # First, we "recursively" connect any we are based on.
+ if subsections is None:
+ subsections = []
+ subsections = [""] + subsections
+ general = self.get_data("general")
+ if general:
+ parents = general.get("based on", [])
+ for parent in parents:
+ trace("Configuration based on", parent, "- loading.")
+ parent = self.__class__(parent)
+ parent.configure(editor, subsections)
+ if parent.last_error:
+ self.report_error(parent.last_error)
+
+ bindings = editor.bindings
+ codeob = self.get_data("extension code")
+ if codeob is not None:
+ ns = {}
+ try:
+ exec(codeob, ns)
+ except:
+ traceback.print_exc()
+ self.report_error("Executing extension code failed")
+ ns = None
+ if ns:
+ num = 0
+ for name, func in ns.items():
+ if isinstance(func, types.FunctionType) and name[:1] != "_":
+ bindings.bind(name, func)
+ num += 1
+ trace("Configuration Extension code loaded", num, "events")
+ # Load the idle extensions
+ for subsection in subsections:
+ for ext in self.get_data("idle extensions", {}).get(subsection, []):
+ try:
+ editor.idle.IDLEExtension(ext)
+ trace("Loaded IDLE extension", ext)
+ except:
+ self.report_error("Can not load the IDLE extension '%s'" % ext)
+
+ # Now bind up the key-map (remembering a reverse map
+ subsection_keymap = self.get_data("keys")
+ num_bound = 0
+ for subsection in subsections:
+ keymap = subsection_keymap.get(subsection, {})
+ bindings.update_keymap(keymap)
+ num_bound += len(keymap)
+ trace("Configuration bound", num_bound, "keys")
+
+ def get_key_binding(self, event, subsections=None):
+ if subsections is None:
+ subsections = []
+ subsections = [""] + subsections
+
+ subsection_keymap = self.get_data("keys")
+ for subsection in subsections:
+ map = self.key_to_events.get(subsection)
+ if map is None: # Build it
+ keymap = subsection_keymap.get(subsection, {})
+ map = {map_event: key_info for key_info, map_event in keymap.items()}
+ self.key_to_events[subsection] = map
+
+ info = map.get(event)
+ if info is not None:
+ return keycodes.make_key_name(info[0], info[1])
+ return None
+
+ def report_error(self, msg):
+ self.last_error = msg
+ print(f"Error in {self.filename}: {msg}")
+
+ def report_warning(self, msg):
+ print(f"Warning in {self.filename}: {msg}")
+
+ def _readline(self, fp, lineno, bStripComments=1):
+ line = fp.readline()
+ lineno += 1
+ if line:
+ bBreak = (
+ get_section_header(line)[0] is not None
+ ) # A new section is starting
+ if bStripComments and not bBreak:
+ pos = line.find("#")
+ if pos >= 0:
+ line = line[:pos] + "\n"
+ else:
+ bBreak = 1
+ return line, lineno, bBreak
+
+ def get_data(self, name, default=None):
+ return self.cache.get(name, default)
+
+ def _save_data(self, name, data):
+ self.cache[name] = data
+ return data
+
+ def _load_general(self, sub_section, fp, lineno):
+ map = {}
+ while 1:
+ line, lineno, bBreak = self._readline(fp, lineno)
+ if bBreak:
+ break
+
+ key, val = split_line(line, lineno)
+ if not key:
+ continue
+ key = key.lower()
+ l = map.get(key, [])
+ l.append(val)
+ map[key] = l
+ self._save_data("general", map)
+ return line, lineno
+
+ def _load_keys(self, sub_section, fp, lineno):
+ # Builds a nested dictionary of
+ # (scancode, flags) = event_name
+ main_map = self.get_data("keys", {})
+ map = main_map.get(sub_section, {})
+ while 1:
+ line, lineno, bBreak = self._readline(fp, lineno)
+ if bBreak:
+ break
+
+ key, event = split_line(line, lineno)
+ if not event:
+ continue
+ sc, flag = keycodes.parse_key_name(key)
+ if sc is None:
+ self.report_warning("Line %d: Invalid key name '%s'" % (lineno, key))
+ else:
+ map[sc, flag] = event
+ main_map[sub_section] = map
+ self._save_data("keys", main_map)
+ return line, lineno
+
+ def _load_extensions(self, sub_section, fp, lineno):
+ start_lineno = lineno
+ lines = []
+ while 1:
+ line, lineno, bBreak = self._readline(fp, lineno, 0)
+ if bBreak:
+ break
+ lines.append(line)
+ try:
+ c = compile(
+ "\n" * start_lineno + "".join(lines), # produces correct tracebacks
+ self.filename,
+ "exec",
+ )
+ self._save_data("extension code", c)
+ except SyntaxError as details:
+ errlineno = details.lineno + start_lineno
+ # Should handle syntax errors better here, and offset the lineno.
+ self.report_error(
+ "Compiling extension code failed:\r\nFile: %s\r\nLine %d\r\n%s"
+ % (details.filename, errlineno, details.msg)
+ )
+ return line, lineno
+
+ def _load_idle_extensions(self, sub_section, fp, lineno):
+ extension_map = self.get_data("idle extensions")
+ if extension_map is None:
+ extension_map = {}
+ extensions = []
+ while 1:
+ line, lineno, bBreak = self._readline(fp, lineno)
+ if bBreak:
+ break
+ line = line.strip()
+ if line:
+ extensions.append(line)
+ extension_map[sub_section] = extensions
+ self._save_data("idle extensions", extension_map)
+ return line, lineno
+
+
+def test():
+ import time
+
+ start = time.clock()
+ f = "default"
+ cm = ConfigManager(f)
+ map = cm.get_data("keys")
+ took = time.clock() - start
+ print(f"Loaded {len(map)} items in {took:.4f} secs")
+
+
+if __name__ == "__main__":
+ test()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/configui.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/configui.py
new file mode 100644
index 0000000000000000000000000000000000000000..455d5d8d5d3a9c75440ce9a52d6e408479aa4b6d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/configui.py
@@ -0,0 +1,291 @@
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog
+
+# Used to indicate that style should use default color
+from win32con import CLR_INVALID
+
+from . import scintillacon
+
+######################################################
+# Property Page for syntax formatting options
+
+# The standard 16 color VGA palette should always be possible
+paletteVGA = (
+ ("Black", win32api.RGB(0, 0, 0)),
+ ("Navy", win32api.RGB(0, 0, 128)),
+ ("Green", win32api.RGB(0, 128, 0)),
+ ("Cyan", win32api.RGB(0, 128, 128)),
+ ("Maroon", win32api.RGB(128, 0, 0)),
+ ("Purple", win32api.RGB(128, 0, 128)),
+ ("Olive", win32api.RGB(128, 128, 0)),
+ ("Gray", win32api.RGB(128, 128, 128)),
+ ("Silver", win32api.RGB(192, 192, 192)),
+ ("Blue", win32api.RGB(0, 0, 255)),
+ ("Lime", win32api.RGB(0, 255, 0)),
+ ("Aqua", win32api.RGB(0, 255, 255)),
+ ("Red", win32api.RGB(255, 0, 0)),
+ ("Fuchsia", win32api.RGB(255, 0, 255)),
+ ("Yellow", win32api.RGB(255, 255, 0)),
+ ("White", win32api.RGB(255, 255, 255)),
+ # and a few others will generally be possible.
+ ("DarkGrey", win32api.RGB(64, 64, 64)),
+ ("PurpleBlue", win32api.RGB(64, 64, 192)),
+ ("DarkGreen", win32api.RGB(0, 96, 0)),
+ ("DarkOlive", win32api.RGB(128, 128, 64)),
+ ("MediumBlue", win32api.RGB(0, 0, 192)),
+ ("DarkNavy", win32api.RGB(0, 0, 96)),
+ ("Magenta", win32api.RGB(96, 0, 96)),
+ ("OffWhite", win32api.RGB(255, 255, 220)),
+ ("LightPurple", win32api.RGB(220, 220, 255)),
+ ("", win32con.CLR_INVALID),
+)
+
+
+class ScintillaFormatPropertyPage(dialog.PropertyPage):
+ def __init__(self, scintillaClass=None, caption=0):
+ self.scintillaClass = scintillaClass
+ dialog.PropertyPage.__init__(self, win32ui.IDD_PP_FORMAT, caption=caption)
+
+ def OnInitDialog(self):
+ try:
+ if self.scintillaClass is None:
+ from . import control
+
+ sc = control.CScintillaEdit
+ else:
+ sc = self.scintillaClass
+
+ self.scintilla = sc()
+ style = win32con.WS_CHILD | win32con.WS_VISIBLE | win32con.ES_MULTILINE
+ # Convert the rect size
+ rect = self.MapDialogRect((5, 5, 120, 75))
+ self.scintilla.CreateWindow(style, rect, self, 111)
+ self.HookNotify(self.OnBraceMatch, scintillacon.SCN_UPDATEUI)
+ self.scintilla.HookKeyStroke(self.OnEsc, 27)
+ self.scintilla.SCISetViewWS(1)
+ self.pos_bstart = self.pos_bend = self.pos_bbad = 0
+
+ colorizer = self.scintilla._GetColorizer()
+ text = colorizer.GetSampleText()
+ items = text.split("|", 2)
+ pos = len(items[0])
+ self.scintilla.SCIAddText("".join(items))
+ self.scintilla.SetSel(pos, pos)
+ self.scintilla.ApplyFormattingStyles()
+ self.styles = self.scintilla._GetColorizer().styles
+
+ self.cbo = self.GetDlgItem(win32ui.IDC_COMBO1)
+ for c in paletteVGA:
+ self.cbo.AddString(c[0])
+
+ self.cboBoldItalic = self.GetDlgItem(win32ui.IDC_COMBO2)
+ for item in ("Bold Italic", "Bold", "Italic", "Regular"):
+ self.cboBoldItalic.InsertString(0, item)
+
+ self.butIsDefault = self.GetDlgItem(win32ui.IDC_CHECK1)
+ self.butIsDefaultBackground = self.GetDlgItem(win32ui.IDC_CHECK2)
+ self.listbox = self.GetDlgItem(win32ui.IDC_LIST1)
+ self.HookCommand(self.OnListCommand, win32ui.IDC_LIST1)
+ names = sorted(self.styles)
+ for name in names:
+ if self.styles[name].aliased is None:
+ self.listbox.AddString(name)
+ self.listbox.SetCurSel(0)
+
+ idc = win32ui.IDC_RADIO1
+ if not self.scintilla._GetColorizer().bUseFixed:
+ idc = win32ui.IDC_RADIO2
+ self.GetDlgItem(idc).SetCheck(1)
+ self.UpdateUIForStyle(self.styles[names[0]])
+
+ self.scintilla.HookFormatter(self)
+ self.HookCommand(self.OnButDefaultFixedFont, win32ui.IDC_BUTTON1)
+ self.HookCommand(self.OnButDefaultPropFont, win32ui.IDC_BUTTON2)
+ self.HookCommand(self.OnButThisFont, win32ui.IDC_BUTTON3)
+ self.HookCommand(self.OnButUseDefaultFont, win32ui.IDC_CHECK1)
+ self.HookCommand(self.OnButThisBackground, win32ui.IDC_BUTTON4)
+ self.HookCommand(self.OnButUseDefaultBackground, win32ui.IDC_CHECK2)
+ self.HookCommand(self.OnStyleUIChanged, win32ui.IDC_COMBO1)
+ self.HookCommand(self.OnStyleUIChanged, win32ui.IDC_COMBO2)
+ self.HookCommand(self.OnButFixedOrDefault, win32ui.IDC_RADIO1)
+ self.HookCommand(self.OnButFixedOrDefault, win32ui.IDC_RADIO2)
+ except:
+ import traceback
+
+ traceback.print_exc()
+
+ def OnEsc(self, ch):
+ self.GetParent().EndDialog(win32con.IDCANCEL)
+
+ def OnBraceMatch(self, std, extra):
+ import pywin.scintilla.view
+
+ pywin.scintilla.view.DoBraceMatch(self.scintilla)
+
+ def GetSelectedStyle(self):
+ return self.styles[self.listbox.GetText(self.listbox.GetCurSel())]
+
+ def _DoButDefaultFont(self, extra_flags, attr):
+ baseFormat = getattr(self.scintilla._GetColorizer(), attr)
+ flags = (
+ extra_flags
+ | win32con.CF_SCREENFONTS
+ | win32con.CF_EFFECTS
+ | win32con.CF_FORCEFONTEXIST
+ )
+ d = win32ui.CreateFontDialog(baseFormat, flags, None, self)
+ if d.DoModal() == win32con.IDOK:
+ setattr(self.scintilla._GetColorizer(), attr, d.GetCharFormat())
+ self.OnStyleUIChanged(0, win32con.BN_CLICKED)
+
+ def OnButDefaultFixedFont(self, id, code):
+ if code == win32con.BN_CLICKED:
+ self._DoButDefaultFont(win32con.CF_FIXEDPITCHONLY, "baseFormatFixed")
+ return 1
+
+ def OnButDefaultPropFont(self, id, code):
+ if code == win32con.BN_CLICKED:
+ self._DoButDefaultFont(win32con.CF_SCALABLEONLY, "baseFormatProp")
+ return 1
+
+ def OnButFixedOrDefault(self, id, code):
+ if code == win32con.BN_CLICKED:
+ bUseFixed = id == win32ui.IDC_RADIO1
+ self.GetDlgItem(win32ui.IDC_RADIO1).GetCheck() != 0
+ self.scintilla._GetColorizer().bUseFixed = bUseFixed
+ self.scintilla.ApplyFormattingStyles(0)
+ return 1
+
+ def OnButThisFont(self, id, code):
+ if code == win32con.BN_CLICKED:
+ flags = (
+ win32con.CF_SCREENFONTS
+ | win32con.CF_EFFECTS
+ | win32con.CF_FORCEFONTEXIST
+ )
+ style = self.GetSelectedStyle()
+ # If the selected style is based on the default, we need to apply
+ # the default to it.
+ def_format = self.scintilla._GetColorizer().GetDefaultFormat()
+ format = style.GetCompleteFormat(def_format)
+ d = win32ui.CreateFontDialog(format, flags, None, self)
+ if d.DoModal() == win32con.IDOK:
+ style.format = d.GetCharFormat()
+ self.scintilla.ApplyFormattingStyles(0)
+ return 1
+
+ def OnButUseDefaultFont(self, id, code):
+ if code == win32con.BN_CLICKED:
+ isDef = self.butIsDefault.GetCheck()
+ self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not isDef)
+ if isDef: # Being reset to the default font.
+ style = self.GetSelectedStyle()
+ style.ForceAgainstDefault()
+ self.UpdateUIForStyle(style)
+ self.scintilla.ApplyFormattingStyles(0)
+ else:
+ # User wants to override default -
+ # do nothing!
+ pass
+
+ def OnButThisBackground(self, id, code):
+ if code == win32con.BN_CLICKED:
+ style = self.GetSelectedStyle()
+ bg = win32api.RGB(0xFF, 0xFF, 0xFF)
+ if style.background != CLR_INVALID:
+ bg = style.background
+ d = win32ui.CreateColorDialog(bg, 0, self)
+ if d.DoModal() == win32con.IDOK:
+ style.background = d.GetColor()
+ self.scintilla.ApplyFormattingStyles(0)
+ return 1
+
+ def OnButUseDefaultBackground(self, id, code):
+ if code == win32con.BN_CLICKED:
+ isDef = self.butIsDefaultBackground.GetCheck()
+ self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(not isDef)
+ if isDef: # Being reset to the default color
+ style = self.GetSelectedStyle()
+ style.background = style.default_background
+ self.UpdateUIForStyle(style)
+ self.scintilla.ApplyFormattingStyles(0)
+ else:
+ # User wants to override default -
+ # do nothing!
+ pass
+
+ def OnListCommand(self, id, code):
+ if code == win32con.LBN_SELCHANGE:
+ style = self.GetSelectedStyle()
+ self.UpdateUIForStyle(style)
+ return 1
+
+ def UpdateUIForStyle(self, style):
+ format = style.format
+ sel = 0
+ for c in paletteVGA:
+ if format[4] == c[1]:
+ # print("Style", style.name, "is", c[0])
+ break
+ sel += 1
+ else:
+ sel = -1
+ self.cbo.SetCurSel(sel)
+ self.butIsDefault.SetCheck(style.IsBasedOnDefault())
+ self.GetDlgItem(win32ui.IDC_BUTTON3).EnableWindow(not style.IsBasedOnDefault())
+
+ self.butIsDefaultBackground.SetCheck(
+ style.background == style.default_background
+ )
+ self.GetDlgItem(win32ui.IDC_BUTTON4).EnableWindow(
+ style.background != style.default_background
+ )
+
+ bold = format[1] & win32con.CFE_BOLD != 0
+ italic = format[1] & win32con.CFE_ITALIC != 0
+ self.cboBoldItalic.SetCurSel(bold * 2 + italic)
+
+ def OnStyleUIChanged(self, id, code):
+ if code in [win32con.BN_CLICKED, win32con.CBN_SELCHANGE]:
+ style = self.GetSelectedStyle()
+ self.ApplyUIFormatToStyle(style)
+ self.scintilla.ApplyFormattingStyles(0)
+ return 0
+ return 1
+
+ def ApplyUIFormatToStyle(self, style):
+ format = style.format
+ color = paletteVGA[self.cbo.GetCurSel()]
+ effect = 0
+ sel = self.cboBoldItalic.GetCurSel()
+ if sel == 0:
+ effect = 0
+ elif sel == 1:
+ effect = win32con.CFE_ITALIC
+ elif sel == 2:
+ effect = win32con.CFE_BOLD
+ else:
+ effect = win32con.CFE_BOLD | win32con.CFE_ITALIC
+ maskFlags = (
+ format[0] | win32con.CFM_COLOR | win32con.CFM_BOLD | win32con.CFM_ITALIC
+ )
+ style.format = (
+ maskFlags,
+ effect,
+ style.format[2],
+ style.format[3],
+ color[1],
+ ) + style.format[5:]
+
+ def OnOK(self):
+ self.scintilla._GetColorizer().SavePreferences()
+ return 1
+
+
+def test():
+ page = ScintillaFormatPropertyPage()
+ sheet = dialog.PropertySheet("Test")
+ sheet.AddPage(page)
+ sheet.CreateWindow()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/control.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/control.py
new file mode 100644
index 0000000000000000000000000000000000000000..d033ae0ce7517a155aa48410768cf89257c6d080
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/control.py
@@ -0,0 +1,565 @@
+# An Python interface to the Scintilla control.
+#
+# Exposes Python classes that allow you to use Scintilla as
+# a "standard" MFC edit control (eg, control.GetTextLength(), control.GetSel()
+# plus many Scintilla specific features (eg control.SCIAddStyledText())
+
+import array
+import os
+import struct
+
+import win32api
+import win32con
+import win32ui
+from pywin import default_scintilla_encoding
+from pywin.mfc import window
+
+from . import scintillacon
+
+# Load Scintilla.dll to get access to the control.
+# We expect to find this in the same directory as win32ui.pyd
+dllid = None
+if win32ui.debug: # If running _d version of Pythonwin...
+ try:
+ dllid = win32api.LoadLibrary(
+ os.path.join(os.path.split(win32ui.__file__)[0], "Scintilla_d.DLL")
+ )
+ except (
+ win32api.error
+ ): # Not there - we don't _need_ a debug ver, so ignore this error.
+ pass
+if dllid is None:
+ try:
+ dllid = win32api.LoadLibrary(
+ os.path.join(os.path.split(win32ui.__file__)[0], "Scintilla.DLL")
+ )
+ except win32api.error:
+ pass
+if dllid is None:
+ # Still not there - let's see if Windows can find it by searching?
+ dllid = win32api.LoadLibrary("Scintilla.DLL")
+
+null_byte = b"\0"
+
+## These are from Richedit.h - need to add to win32con or commctrl
+EM_GETTEXTRANGE = 1099
+EM_EXLINEFROMCHAR = 1078
+EM_FINDTEXTEX = 1103
+EM_GETSELTEXT = 1086
+EM_EXSETSEL = win32con.WM_USER + 55
+
+
+class ScintillaNotification:
+ def __init__(self, **args):
+ self.__dict__.update(args)
+
+
+class ScintillaControlInterface:
+ def SCIUnpackNotifyMessage(self, msg):
+ format = "iiiiPiiiPPiiii"
+ bytes = win32ui.GetBytes(msg, struct.calcsize(format))
+ (
+ position,
+ ch,
+ modifiers,
+ modificationType,
+ text_ptr,
+ length,
+ linesAdded,
+ msg,
+ wParam,
+ lParam,
+ line,
+ foldLevelNow,
+ foldLevelPrev,
+ margin,
+ ) = struct.unpack(format, bytes)
+ return ScintillaNotification(
+ position=position,
+ ch=ch,
+ modifiers=modifiers,
+ modificationType=modificationType,
+ text_ptr=text_ptr,
+ length=length,
+ linesAdded=linesAdded,
+ msg=msg,
+ wParam=wParam,
+ lParam=lParam,
+ line=line,
+ foldLevelNow=foldLevelNow,
+ foldLevelPrev=foldLevelPrev,
+ margin=margin,
+ )
+
+ def SCIAddText(self, text):
+ self.SendMessage(
+ scintillacon.SCI_ADDTEXT, text.encode(default_scintilla_encoding)
+ )
+
+ def SCIAddStyledText(self, text, style=None):
+ # If style is None, text is assumed to be a "native" Scintilla buffer.
+ # If style is specified, text is a normal string, and the style is
+ # assumed to apply to the entire string.
+ if style is not None:
+ text = list(map(lambda char, style=style: char + chr(style), text))
+ text = "".join(text)
+ self.SendMessage(
+ scintillacon.SCI_ADDSTYLEDTEXT, text.encode(default_scintilla_encoding)
+ )
+
+ def SCIInsertText(self, text, pos=-1):
+ # SCIInsertText allows unicode or bytes - but if they are bytes,
+ # the caller must ensure it is encoded correctly.
+ if isinstance(text, str):
+ text = text.encode(default_scintilla_encoding)
+ self.SendScintilla(scintillacon.SCI_INSERTTEXT, pos, text + null_byte)
+
+ def SCISetSavePoint(self):
+ self.SendScintilla(scintillacon.SCI_SETSAVEPOINT)
+
+ def SCISetUndoCollection(self, collectFlag):
+ self.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, collectFlag)
+
+ def SCIBeginUndoAction(self):
+ self.SendScintilla(scintillacon.SCI_BEGINUNDOACTION)
+
+ def SCIEndUndoAction(self):
+ self.SendScintilla(scintillacon.SCI_ENDUNDOACTION)
+
+ def SCIGetCurrentPos(self):
+ return self.SendScintilla(scintillacon.SCI_GETCURRENTPOS)
+
+ def SCIGetCharAt(self, pos):
+ # Must ensure char is unsigned!
+ return chr(self.SendScintilla(scintillacon.SCI_GETCHARAT, pos) & 0xFF)
+
+ def SCIGotoLine(self, line):
+ self.SendScintilla(scintillacon.SCI_GOTOLINE, line)
+
+ def SCIBraceMatch(self, pos, maxReStyle):
+ return self.SendScintilla(scintillacon.SCI_BRACEMATCH, pos, maxReStyle)
+
+ def SCIBraceHighlight(self, pos, posOpposite):
+ return self.SendScintilla(scintillacon.SCI_BRACEHIGHLIGHT, pos, posOpposite)
+
+ def SCIBraceBadHighlight(self, pos):
+ return self.SendScintilla(scintillacon.SCI_BRACEBADLIGHT, pos)
+
+ ####################################
+ # Styling
+ # def SCIColourise(self, start=0, end=-1):
+ # NOTE - dependent on of we use builtin lexer, so handled below.
+ def SCIGetEndStyled(self):
+ return self.SendScintilla(scintillacon.SCI_GETENDSTYLED)
+
+ def SCIStyleSetFore(self, num, v):
+ return self.SendScintilla(scintillacon.SCI_STYLESETFORE, num, v)
+
+ def SCIStyleSetBack(self, num, v):
+ return self.SendScintilla(scintillacon.SCI_STYLESETBACK, num, v)
+
+ def SCIStyleSetEOLFilled(self, num, v):
+ return self.SendScintilla(scintillacon.SCI_STYLESETEOLFILLED, num, v)
+
+ def SCIStyleSetFont(self, num, name, characterset=0):
+ buff = (name + "\0").encode(default_scintilla_encoding)
+ self.SendScintilla(scintillacon.SCI_STYLESETFONT, num, buff)
+ self.SendScintilla(scintillacon.SCI_STYLESETCHARACTERSET, num, characterset)
+
+ def SCIStyleSetBold(self, num, bBold):
+ self.SendScintilla(scintillacon.SCI_STYLESETBOLD, num, bBold)
+
+ def SCIStyleSetItalic(self, num, bItalic):
+ self.SendScintilla(scintillacon.SCI_STYLESETITALIC, num, bItalic)
+
+ def SCIStyleSetSize(self, num, size):
+ self.SendScintilla(scintillacon.SCI_STYLESETSIZE, num, size)
+
+ def SCIGetViewWS(self):
+ return self.SendScintilla(scintillacon.SCI_GETVIEWWS)
+
+ def SCISetViewWS(self, val):
+ self.SendScintilla(scintillacon.SCI_SETVIEWWS, not (val == 0))
+ self.InvalidateRect()
+
+ def SCISetIndentationGuides(self, val):
+ self.SendScintilla(scintillacon.SCI_SETINDENTATIONGUIDES, val)
+
+ def SCIGetIndentationGuides(self):
+ return self.SendScintilla(scintillacon.SCI_GETINDENTATIONGUIDES)
+
+ def SCISetIndent(self, val):
+ self.SendScintilla(scintillacon.SCI_SETINDENT, val)
+
+ def SCIGetIndent(self, val):
+ return self.SendScintilla(scintillacon.SCI_GETINDENT)
+
+ def SCIGetViewEOL(self):
+ return self.SendScintilla(scintillacon.SCI_GETVIEWEOL)
+
+ def SCISetViewEOL(self, val):
+ self.SendScintilla(scintillacon.SCI_SETVIEWEOL, not (val == 0))
+ self.InvalidateRect()
+
+ def SCISetTabWidth(self, width):
+ self.SendScintilla(scintillacon.SCI_SETTABWIDTH, width, 0)
+
+ def SCIStartStyling(self, pos, mask):
+ self.SendScintilla(scintillacon.SCI_STARTSTYLING, pos, mask)
+
+ def SCISetStyling(self, pos, attr):
+ self.SendScintilla(scintillacon.SCI_SETSTYLING, pos, attr)
+
+ def SCISetStylingEx(self, ray): # ray is an array.
+ address, length = ray.buffer_info()
+ self.SendScintilla(scintillacon.SCI_SETSTYLINGEX, length, address)
+
+ def SCIGetStyleAt(self, pos):
+ return self.SendScintilla(scintillacon.SCI_GETSTYLEAT, pos)
+
+ def SCISetMarginWidth(self, width):
+ self.SendScintilla(scintillacon.SCI_SETMARGINWIDTHN, 1, width)
+
+ def SCISetMarginWidthN(self, n, width):
+ self.SendScintilla(scintillacon.SCI_SETMARGINWIDTHN, n, width)
+
+ def SCISetFoldFlags(self, flags):
+ self.SendScintilla(scintillacon.SCI_SETFOLDFLAGS, flags)
+
+ # Markers
+ def SCIMarkerDefineAll(self, markerNum, markerType, fore, back):
+ self.SCIMarkerDefine(markerNum, markerType)
+ self.SCIMarkerSetFore(markerNum, fore)
+ self.SCIMarkerSetBack(markerNum, back)
+
+ def SCIMarkerDefine(self, markerNum, markerType):
+ self.SendScintilla(scintillacon.SCI_MARKERDEFINE, markerNum, markerType)
+
+ def SCIMarkerSetFore(self, markerNum, fore):
+ self.SendScintilla(scintillacon.SCI_MARKERSETFORE, markerNum, fore)
+
+ def SCIMarkerSetBack(self, markerNum, back):
+ self.SendScintilla(scintillacon.SCI_MARKERSETBACK, markerNum, back)
+
+ def SCIMarkerAdd(self, lineNo, markerNum):
+ self.SendScintilla(scintillacon.SCI_MARKERADD, lineNo, markerNum)
+
+ def SCIMarkerDelete(self, lineNo, markerNum):
+ self.SendScintilla(scintillacon.SCI_MARKERDELETE, lineNo, markerNum)
+
+ def SCIMarkerDeleteAll(self, markerNum=-1):
+ self.SendScintilla(scintillacon.SCI_MARKERDELETEALL, markerNum)
+
+ def SCIMarkerGet(self, lineNo):
+ return self.SendScintilla(scintillacon.SCI_MARKERGET, lineNo)
+
+ def SCIMarkerNext(self, lineNo, markerNum):
+ return self.SendScintilla(scintillacon.SCI_MARKERNEXT, lineNo, markerNum)
+
+ def SCICancel(self):
+ self.SendScintilla(scintillacon.SCI_CANCEL)
+
+ # AutoComplete
+ def SCIAutoCShow(self, text):
+ if isinstance(text, (list, tuple)):
+ text = " ".join(text)
+ buff = (text + "\0").encode(default_scintilla_encoding)
+ return self.SendScintilla(scintillacon.SCI_AUTOCSHOW, 0, buff)
+
+ def SCIAutoCCancel(self):
+ self.SendScintilla(scintillacon.SCI_AUTOCCANCEL)
+
+ def SCIAutoCActive(self):
+ return self.SendScintilla(scintillacon.SCI_AUTOCACTIVE)
+
+ def SCIAutoCComplete(self):
+ return self.SendScintilla(scintillacon.SCI_AUTOCCOMPLETE)
+
+ def SCIAutoCStops(self, stops):
+ buff = (stops + "\0").encode(default_scintilla_encoding)
+ self.SendScintilla(scintillacon.SCI_AUTOCSTOPS, 0, buff)
+
+ def SCIAutoCSetAutoHide(self, hide):
+ self.SendScintilla(scintillacon.SCI_AUTOCSETAUTOHIDE, hide)
+
+ def SCIAutoCSetFillups(self, fillups):
+ self.SendScintilla(scintillacon.SCI_AUTOCSETFILLUPS, fillups)
+
+ # Call tips
+ def SCICallTipShow(self, text, pos=-1):
+ if pos == -1:
+ pos = self.GetSel()[0]
+ buff = (text + "\0").encode(default_scintilla_encoding)
+ self.SendScintilla(scintillacon.SCI_CALLTIPSHOW, pos, buff)
+
+ def SCICallTipCancel(self):
+ self.SendScintilla(scintillacon.SCI_CALLTIPCANCEL)
+
+ def SCICallTipActive(self):
+ return self.SendScintilla(scintillacon.SCI_CALLTIPACTIVE)
+
+ def SCICallTipPosStart(self):
+ return self.SendScintilla(scintillacon.SCI_CALLTIPPOSSTART)
+
+ def SCINewline(self):
+ self.SendScintilla(scintillacon.SCI_NEWLINE)
+
+ # Lexer etc
+ def SCISetKeywords(self, keywords, kw_list_no=0):
+ buff = (keywords + "\0").encode(default_scintilla_encoding)
+ self.SendScintilla(scintillacon.SCI_SETKEYWORDS, kw_list_no, buff)
+
+ def SCISetProperty(self, name, value):
+ name_buff = array.array("b", (name + "\0").encode(default_scintilla_encoding))
+ val_buff = array.array(
+ "b", (str(value) + "\0").encode(default_scintilla_encoding)
+ )
+ address_name_buffer = name_buff.buffer_info()[0]
+ address_val_buffer = val_buff.buffer_info()[0]
+ self.SendScintilla(
+ scintillacon.SCI_SETPROPERTY, address_name_buffer, address_val_buffer
+ )
+
+ def SCISetStyleBits(self, nbits):
+ self.SendScintilla(scintillacon.SCI_SETSTYLEBITS, nbits)
+
+ # Folding
+ def SCIGetFoldLevel(self, lineno):
+ return self.SendScintilla(scintillacon.SCI_GETFOLDLEVEL, lineno)
+
+ def SCIToggleFold(self, lineno):
+ return self.SendScintilla(scintillacon.SCI_TOGGLEFOLD, lineno)
+
+ def SCIEnsureVisible(self, lineno):
+ self.SendScintilla(scintillacon.SCI_ENSUREVISIBLE, lineno)
+
+ def SCIGetFoldExpanded(self, lineno):
+ return self.SendScintilla(scintillacon.SCI_GETFOLDEXPANDED, lineno)
+
+ # right edge
+ def SCISetEdgeColumn(self, edge):
+ self.SendScintilla(scintillacon.SCI_SETEDGECOLUMN, edge)
+
+ def SCIGetEdgeColumn(self):
+ return self.SendScintilla(scintillacon.SCI_GETEDGECOLUMN)
+
+ def SCISetEdgeMode(self, mode):
+ self.SendScintilla(scintillacon.SCI_SETEDGEMODE, mode)
+
+ def SCIGetEdgeMode(self):
+ return self.SendScintilla(scintillacon.SCI_GETEDGEMODE)
+
+ def SCISetEdgeColor(self, color):
+ self.SendScintilla(scintillacon.SCI_SETEDGECOLOUR, color)
+
+ def SCIGetEdgeColor(self):
+ return self.SendScintilla(scintillacon.SCI_GETEDGECOLOR)
+
+ # Multi-doc
+ def SCIGetDocPointer(self):
+ return self.SendScintilla(scintillacon.SCI_GETDOCPOINTER)
+
+ def SCISetDocPointer(self, p):
+ return self.SendScintilla(scintillacon.SCI_SETDOCPOINTER, 0, p)
+
+ def SCISetWrapMode(self, mode):
+ return self.SendScintilla(scintillacon.SCI_SETWRAPMODE, mode)
+
+ def SCIGetWrapMode(self):
+ return self.SendScintilla(scintillacon.SCI_GETWRAPMODE)
+
+
+class CScintillaEditInterface(ScintillaControlInterface):
+ def close(self):
+ self.colorizer = None
+
+ def Clear(self):
+ self.SendScintilla(win32con.WM_CLEAR)
+
+ def FindText(self, flags, range, findText):
+ """LPARAM for EM_FINDTEXTEX:
+ typedef struct _findtextex {
+ CHARRANGE chrg;
+ LPCTSTR lpstrText;
+ CHARRANGE chrgText;} FINDTEXTEX;
+ typedef struct _charrange {
+ LONG cpMin;
+ LONG cpMax;} CHARRANGE;
+ """
+ findtextex_fmt = "llPll"
+ ## Scintilla does not handle unicode in EM_FINDTEXT msg (FINDTEXTEX struct)
+ txt_buff = (findText + "\0").encode(default_scintilla_encoding)
+ txt_array = array.array("b", txt_buff)
+ ft_buff = struct.pack(
+ findtextex_fmt, range[0], range[1], txt_array.buffer_info()[0], 0, 0
+ )
+ ft_array = array.array("b", ft_buff)
+ rc = self.SendScintilla(EM_FINDTEXTEX, flags, ft_array.buffer_info()[0])
+ ftUnpacked = struct.unpack(findtextex_fmt, ft_array)
+ return rc, (ftUnpacked[3], ftUnpacked[4])
+
+ def GetSel(self):
+ currentPos = self.SendScintilla(scintillacon.SCI_GETCURRENTPOS)
+ anchorPos = self.SendScintilla(scintillacon.SCI_GETANCHOR)
+ if currentPos < anchorPos:
+ return (currentPos, anchorPos)
+ else:
+ return (anchorPos, currentPos)
+ return currentPos
+
+ def GetSelText(self):
+ start, end = self.GetSel()
+ txtBuf = array.array("b", null_byte * (end - start + 1))
+ addressTxtBuf = txtBuf.buffer_info()[0]
+ # EM_GETSELTEXT is documented as returning the number of chars
+ # not including the NULL, but scintilla includes the NULL. A
+ # quick glance at the scintilla impl doesn't make this
+ # obvious - the NULL is included in the 'selection' object
+ # and reflected in the length of that 'selection' object.
+ # I expect that is a bug in scintilla and may be fixed by now,
+ # but we just blindly assume that the last char is \0 and
+ # strip it.
+ self.SendScintilla(EM_GETSELTEXT, 0, addressTxtBuf)
+ return txtBuf.tobytes()[:-1].decode(default_scintilla_encoding)
+
+ def SetSel(self, start=0, end=None):
+ if isinstance(start, tuple):
+ assert (
+ end is None
+ ), "If you pass a point in the first param, the second must be None"
+ start, end = start
+ elif end is None:
+ end = start
+ if start < 0:
+ start = self.GetTextLength()
+ if end < 0:
+ end = self.GetTextLength()
+ assert start <= self.GetTextLength(), "The start postion is invalid (%d/%d)" % (
+ start,
+ self.GetTextLength(),
+ )
+ assert end <= self.GetTextLength(), "The end postion is invalid (%d/%d)" % (
+ end,
+ self.GetTextLength(),
+ )
+ cr = struct.pack("ll", start, end)
+ crBuff = array.array("b", cr)
+ addressCrBuff = crBuff.buffer_info()[0]
+ rc = self.SendScintilla(EM_EXSETSEL, 0, addressCrBuff)
+
+ def GetLineCount(self):
+ return self.SendScintilla(win32con.EM_GETLINECOUNT)
+
+ def LineFromChar(self, charPos=-1):
+ if charPos == -1:
+ charPos = self.GetSel()[0]
+ assert (
+ charPos >= 0 and charPos <= self.GetTextLength()
+ ), f"The charPos postion ({charPos}) is invalid (max={self.GetTextLength()})"
+ # return self.SendScintilla(EM_EXLINEFROMCHAR, charPos)
+ # EM_EXLINEFROMCHAR puts charPos in lParam, not wParam
+ return self.SendScintilla(EM_EXLINEFROMCHAR, 0, charPos)
+
+ def LineIndex(self, line):
+ return self.SendScintilla(win32con.EM_LINEINDEX, line)
+
+ def ScrollCaret(self):
+ return self.SendScintilla(win32con.EM_SCROLLCARET)
+
+ def GetCurLineNumber(self):
+ return self.LineFromChar(self.SCIGetCurrentPos())
+
+ def GetTextLength(self):
+ return self.SendScintilla(scintillacon.SCI_GETTEXTLENGTH)
+
+ def GetTextRange(self, start=0, end=-1, decode=True):
+ if end == -1:
+ end = self.SendScintilla(scintillacon.SCI_GETTEXTLENGTH)
+ assert end >= start, "Negative index requested (%d/%d)" % (start, end)
+ assert (
+ start >= 0 and start <= self.GetTextLength()
+ ), "The start postion is invalid"
+ assert end >= 0 and end <= self.GetTextLength(), "The end postion is invalid"
+ initer = null_byte * (end - start + 1)
+ buff = array.array("b", initer)
+ addressBuffer = buff.buffer_info()[0]
+ tr = struct.pack("llP", start, end, addressBuffer)
+ trBuff = array.array("b", tr)
+ addressTrBuff = trBuff.buffer_info()[0]
+ num_bytes = self.SendScintilla(EM_GETTEXTRANGE, 0, addressTrBuff)
+ ret = buff.tobytes()[:num_bytes]
+ if decode:
+ ret = ret.decode(default_scintilla_encoding)
+ return ret
+
+ def ReplaceSel(self, str):
+ buff = (str + "\0").encode(default_scintilla_encoding)
+ self.SendScintilla(scintillacon.SCI_REPLACESEL, 0, buff)
+
+ def GetLine(self, line=-1):
+ if line == -1:
+ line = self.GetCurLineNumber()
+ start = self.LineIndex(line)
+ end = self.LineIndex(line + 1)
+ return self.GetTextRange(start, end)
+
+ def SetReadOnly(self, flag=1):
+ return self.SendScintilla(win32con.EM_SETREADONLY, flag)
+
+ def LineScroll(self, lines, cols=0):
+ return self.SendScintilla(win32con.EM_LINESCROLL, cols, lines)
+
+ def GetFirstVisibleLine(self):
+ return self.SendScintilla(win32con.EM_GETFIRSTVISIBLELINE)
+
+ def SetWordWrap(self, mode):
+ if mode != win32ui.CRichEditView_WrapNone:
+ raise ValueError("We don't support word-wrap (I don't think :-)")
+
+
+class CScintillaColorEditInterface(CScintillaEditInterface):
+ ################################
+ # Plug-in colorizer support
+ def _GetColorizer(self):
+ if not hasattr(self, "colorizer"):
+ self.colorizer = self._MakeColorizer()
+ return self.colorizer
+
+ def _MakeColorizer(self):
+ # Give parent a chance to hook.
+ parent_func = getattr(self.GetParentFrame(), "_MakeColorizer", None)
+ if parent_func is not None:
+ return parent_func()
+ from . import formatter
+
+ ## return formatter.PythonSourceFormatter(self)
+ return formatter.BuiltinPythonSourceFormatter(self)
+
+ def Colorize(self, start=0, end=-1):
+ c = self._GetColorizer()
+ if c is not None:
+ c.Colorize(start, end)
+
+ def ApplyFormattingStyles(self, bReload=1):
+ c = self._GetColorizer()
+ if c is not None:
+ c.ApplyFormattingStyles(bReload)
+
+ # The Parent window will normally hook
+ def HookFormatter(self, parent=None):
+ c = self._GetColorizer()
+ if c is not None: # No need if we have no color!
+ c.HookFormatter(parent)
+
+
+class CScintillaEdit(window.Wnd, CScintillaColorEditInterface):
+ def __init__(self, wnd=None):
+ if wnd is None:
+ wnd = win32ui.CreateWnd()
+ window.Wnd.__init__(self, wnd)
+
+ def SendScintilla(self, msg, w=0, l=0):
+ return self.SendMessage(msg, w, l)
+
+ def CreateWindow(self, style, rect, parent, id):
+ self._obj_.CreateWindow("Scintilla", "Scintilla", style, rect, parent, id, None)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/document.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/document.py
new file mode 100644
index 0000000000000000000000000000000000000000..38d37f719e4dca3a4542d57e7f573aa96538753c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/document.py
@@ -0,0 +1,312 @@
+import codecs
+import re
+import string
+
+import win32con
+import win32ui
+from pywin import default_scintilla_encoding
+from pywin.mfc import docview
+
+from . import scintillacon
+
+crlf_bytes = b"\r\n"
+lf_bytes = b"\n"
+
+# re from pep263 - but we use it both on bytes and strings.
+re_encoding_bytes = re.compile(rb"coding[:=]\s*([-\w.]+)")
+re_encoding_text = re.compile(r"coding[:=]\s*([-\w.]+)")
+
+ParentScintillaDocument = docview.Document
+
+
+class CScintillaDocument(ParentScintillaDocument):
+ "A SyntEdit document."
+
+ def __init__(self, *args):
+ self.bom = None # the BOM, if any, read from the file.
+ # the encoding we detected from the source. Might have
+ # detected via the BOM or an encoding decl. Note that in
+ # the latter case (ie, while self.bom is None), it can't be
+ # trusted - the user may have edited the encoding decl between
+ # open and save.
+ self.source_encoding = None
+ ParentScintillaDocument.__init__(self, *args)
+
+ def DeleteContents(self):
+ pass
+
+ def OnOpenDocument(self, filename):
+ # init data members
+ # print("Opening", filename)
+ self.SetPathName(filename) # Must set this early!
+ try:
+ # load the text as binary we can get smart
+ # about detecting any existing EOL conventions.
+ f = open(filename, "rb")
+ try:
+ self._LoadTextFromFile(f)
+ finally:
+ f.close()
+ except OSError:
+ rc = win32ui.MessageBox(
+ "Could not load the file from %s\n\nDo you want to create a new file?"
+ % filename,
+ "Pythonwin",
+ win32con.MB_YESNO | win32con.MB_ICONWARNING,
+ )
+ if rc == win32con.IDNO:
+ return 0
+ assert rc == win32con.IDYES, rc
+ try:
+ f = open(filename, "wb+")
+ try:
+ self._LoadTextFromFile(f)
+ finally:
+ f.close()
+ except OSError as e:
+ rc = win32ui.MessageBox("Cannot create the file %s" % filename)
+ return 1
+
+ def SaveFile(self, fileName, encoding=None):
+ view = self.GetFirstView()
+ ok = view.SaveTextFile(fileName, encoding=encoding)
+ if ok:
+ view.SCISetSavePoint()
+ return ok
+
+ def ApplyFormattingStyles(self):
+ self._ApplyOptionalToViews("ApplyFormattingStyles")
+
+ # #####################
+ # File related functions
+ # Helper to transfer text from the MFC document to the control.
+ def _LoadTextFromFile(self, f):
+ # detect EOL mode - we don't support \r only - so find the
+ # first '\n' and guess based on the char before.
+ l = f.readline()
+ l2 = f.readline()
+ # If line ends with \r\n or has no line ending, use CRLF.
+ if l.endswith(crlf_bytes) or not l.endswith(lf_bytes):
+ eol_mode = scintillacon.SC_EOL_CRLF
+ else:
+ eol_mode = scintillacon.SC_EOL_LF
+
+ # Detect the encoding - first look for a BOM, and if not found,
+ # look for a pep263 encoding declaration.
+ for bom, encoding in (
+ (codecs.BOM_UTF8, "utf8"),
+ (codecs.BOM_UTF16_LE, "utf_16_le"),
+ (codecs.BOM_UTF16_BE, "utf_16_be"),
+ ):
+ if l.startswith(bom):
+ self.bom = bom
+ self.source_encoding = encoding
+ l = l[len(bom) :] # remove it.
+ break
+ else:
+ # no bom detected - look for pep263 encoding decl.
+ for look in (l, l2):
+ # Note we are looking at raw bytes here: so
+ # both the re itself uses bytes and the result
+ # is bytes - but we need the result as a string.
+ match = re_encoding_bytes.search(look)
+ if match is not None:
+ self.source_encoding = match.group(1).decode("ascii")
+ break
+
+ # reading by lines would be too slow? Maybe we can use the
+ # incremental encoders? For now just stick with loading the
+ # entire file in memory.
+ text = l + l2 + f.read()
+
+ # Translate from source encoding to UTF-8 bytes for Scintilla
+ source_encoding = self.source_encoding
+ # If we don't know an encoding, try utf-8 - if that fails we will
+ # fallback to latin-1 to treat it as bytes...
+ if source_encoding is None:
+ source_encoding = "utf-8"
+ # we could optimize this by avoiding utf8 to-ing and from-ing,
+ # but then we would lose the ability to handle invalid utf8
+ # (and even then, the use of encoding aliases makes this tricky)
+ # To create an invalid utf8 file:
+ # >>> open(filename, "wb").write(codecs.BOM_UTF8+"bad \xa9har\r\n")
+ try:
+ dec = text.decode(source_encoding)
+ except UnicodeError:
+ print(
+ "WARNING: Failed to decode bytes from '%s' encoding - treating as latin1"
+ % source_encoding
+ )
+ dec = text.decode("latin1")
+ except LookupError:
+ print(
+ "WARNING: Invalid encoding '%s' specified - treating as latin1"
+ % source_encoding
+ )
+ dec = text.decode("latin1")
+ # and put it back as utf8 - this shouldn't fail.
+ text = dec.encode(default_scintilla_encoding)
+
+ view = self.GetFirstView()
+ if view.IsWindow():
+ # Turn off undo collection while loading
+ view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 0, 0)
+ # Make sure the control isn't read-only
+ view.SetReadOnly(0)
+ view.SendScintilla(scintillacon.SCI_CLEARALL)
+ view.SendMessage(scintillacon.SCI_ADDTEXT, text)
+ view.SendScintilla(scintillacon.SCI_SETUNDOCOLLECTION, 1, 0)
+ view.SendScintilla(win32con.EM_EMPTYUNDOBUFFER, 0, 0)
+ # set EOL mode
+ view.SendScintilla(scintillacon.SCI_SETEOLMODE, eol_mode)
+
+ def _SaveTextToFile(self, view, filename, encoding=None):
+ s = view.GetTextRange() # already decoded from scintilla's encoding
+ source_encoding = encoding
+ if source_encoding is None:
+ if self.bom:
+ source_encoding = self.source_encoding
+ else:
+ # no BOM - look for an encoding.
+ bits = re.split(r"[\r\n]+", s, 3)
+ for look in bits[:-1]:
+ match = re_encoding_text.search(look)
+ if match is not None:
+ source_encoding = match.group(1)
+ self.source_encoding = source_encoding
+ break
+
+ if source_encoding is None:
+ source_encoding = "utf-8"
+
+ ## encode data before opening file so script is not lost if encoding fails
+ file_contents = s.encode(source_encoding)
+ # Open in binary mode as scintilla itself ensures the
+ # line endings are already appropriate
+ f = open(filename, "wb")
+ try:
+ if self.bom:
+ f.write(self.bom)
+ f.write(file_contents)
+ finally:
+ f.close()
+ self.SetModifiedFlag(0)
+
+ def FinalizeViewCreation(self, view):
+ pass
+
+ def HookViewNotifications(self, view):
+ parent = view.GetParentFrame()
+ parent.HookNotify(
+ ViewNotifyDelegate(self, "OnBraceMatch"), scintillacon.SCN_UPDATEUI
+ )
+ parent.HookNotify(
+ ViewNotifyDelegate(self, "OnMarginClick"), scintillacon.SCN_MARGINCLICK
+ )
+ parent.HookNotify(
+ ViewNotifyDelegate(self, "OnNeedShown"), scintillacon.SCN_NEEDSHOWN
+ )
+
+ parent.HookNotify(
+ DocumentNotifyDelegate(self, "OnSavePointReached"),
+ scintillacon.SCN_SAVEPOINTREACHED,
+ )
+ parent.HookNotify(
+ DocumentNotifyDelegate(self, "OnSavePointLeft"),
+ scintillacon.SCN_SAVEPOINTLEFT,
+ )
+ parent.HookNotify(
+ DocumentNotifyDelegate(self, "OnModifyAttemptRO"),
+ scintillacon.SCN_MODIFYATTEMPTRO,
+ )
+ # Tell scintilla what characters should abort auto-complete.
+ view.SCIAutoCStops(string.whitespace + "()[]:;+-/*=\\?'!#@$%^&,<>\"'|")
+
+ if view != self.GetFirstView():
+ view.SCISetDocPointer(self.GetFirstView().SCIGetDocPointer())
+
+ def OnSavePointReached(self, std, extra):
+ self.SetModifiedFlag(0)
+
+ def OnSavePointLeft(self, std, extra):
+ self.SetModifiedFlag(1)
+
+ def OnModifyAttemptRO(self, std, extra):
+ self.MakeDocumentWritable()
+
+ # All Marker functions are 1 based.
+ def MarkerAdd(self, lineNo, marker):
+ self.GetEditorView().SCIMarkerAdd(lineNo - 1, marker)
+
+ def MarkerCheck(self, lineNo, marker):
+ v = self.GetEditorView()
+ lineNo -= 1 # Make 0 based
+ markerState = v.SCIMarkerGet(lineNo)
+ return markerState & (1 << marker) != 0
+
+ def MarkerToggle(self, lineNo, marker):
+ v = self.GetEditorView()
+ if self.MarkerCheck(lineNo, marker):
+ v.SCIMarkerDelete(lineNo - 1, marker)
+ else:
+ v.SCIMarkerAdd(lineNo - 1, marker)
+
+ def MarkerDelete(self, lineNo, marker):
+ self.GetEditorView().SCIMarkerDelete(lineNo - 1, marker)
+
+ def MarkerDeleteAll(self, marker):
+ self.GetEditorView().SCIMarkerDeleteAll(marker)
+
+ def MarkerGetNext(self, lineNo, marker):
+ return self.GetEditorView().SCIMarkerNext(lineNo - 1, 1 << marker) + 1
+
+ def MarkerAtLine(self, lineNo, marker):
+ markerState = self.GetEditorView().SCIMarkerGet(lineNo - 1)
+ return markerState & (1 << marker)
+
+ # Helper for reflecting functions to views.
+ def _ApplyToViews(self, funcName, *args):
+ for view in self.GetAllViews():
+ func = getattr(view, funcName)
+ func(*args)
+
+ def _ApplyOptionalToViews(self, funcName, *args):
+ for view in self.GetAllViews():
+ func = getattr(view, funcName, None)
+ if func is not None:
+ func(*args)
+
+ def GetEditorView(self):
+ # Find the first frame with a view,
+ # then ask it to give the editor view
+ # as it knows which one is "active"
+ try:
+ frame_gev = self.GetFirstView().GetParentFrame().GetEditorView
+ except AttributeError:
+ return self.GetFirstView()
+ return frame_gev()
+
+
+# Delegate to the correct view, based on the control that sent it.
+class ViewNotifyDelegate:
+ def __init__(self, doc, name):
+ self.doc = doc
+ self.name = name
+
+ def __call__(self, std, extra):
+ (hwndFrom, idFrom, code) = std
+ for v in self.doc.GetAllViews():
+ if v.GetSafeHwnd() == hwndFrom:
+ return getattr(v, self.name)(*(std, extra))
+
+
+# Delegate to the document, but only from a single view (as each view sends it seperately)
+class DocumentNotifyDelegate:
+ def __init__(self, doc, name):
+ self.doc = doc
+ self.delegate = getattr(doc, name)
+
+ def __call__(self, std, extra):
+ (hwndFrom, idFrom, code) = std
+ if hwndFrom == self.doc.GetEditorView().GetSafeHwnd():
+ self.delegate(*(std, extra))
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/find.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/find.py
new file mode 100644
index 0000000000000000000000000000000000000000..551f8d2ab529ebd3fda26ae4b19896c10b56e28d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/find.py
@@ -0,0 +1,511 @@
+# find.py - Find and Replace
+from __future__ import annotations
+
+import win32api
+import win32con
+import win32ui
+from pywin.framework import scriptutils
+from pywin.mfc import afxres, dialog
+
+FOUND_NOTHING = 0
+FOUND_NORMAL = 1
+FOUND_LOOPED_BACK = 2
+FOUND_NEXT_FILE = 3
+
+
+class SearchParams:
+ def __init__(self, other=None):
+ if other is None:
+ self.__dict__["findText"] = ""
+ self.__dict__["replaceText"] = ""
+ self.__dict__["matchCase"] = 0
+ self.__dict__["matchWords"] = 0
+ self.__dict__["acrossFiles"] = 0
+ self.__dict__["remember"] = 1
+ self.__dict__["sel"] = (-1, -1)
+ self.__dict__["keepDialogOpen"] = 0
+ else:
+ self.__dict__.update(other.__dict__)
+
+ # Helper so we can't misspell attributes :-)
+ def __setattr__(self, attr, val):
+ if not hasattr(self, attr):
+ raise AttributeError(attr)
+ self.__dict__[attr] = val
+
+
+curDialog = None
+lastSearch = defaultSearch = SearchParams()
+searchHistory: list[str] = []
+
+
+def ShowFindDialog():
+ _ShowDialog(FindDialog)
+
+
+def ShowReplaceDialog():
+ _ShowDialog(ReplaceDialog)
+
+
+def _ShowDialog(dlgClass):
+ global curDialog
+ if curDialog is not None:
+ if curDialog.__class__ != dlgClass:
+ curDialog.DestroyWindow()
+ curDialog = None
+ else:
+ curDialog.SetFocus()
+ if curDialog is None:
+ curDialog = dlgClass()
+ curDialog.CreateWindow()
+
+
+def FindNext():
+ params = SearchParams(lastSearch)
+ params.sel = (-1, -1)
+ if not params.findText:
+ ShowFindDialog()
+ else:
+ return _FindIt(None, params)
+
+
+def _GetControl(control=None):
+ if control is None:
+ control = scriptutils.GetActiveEditControl()
+ return control
+
+
+def _FindIt(control, searchParams):
+ global lastSearch, defaultSearch
+ control = _GetControl(control)
+ if control is None:
+ return FOUND_NOTHING
+
+ # Move to the next char, so we find the next one.
+ flags = 0
+ if searchParams.matchWords:
+ flags |= win32con.FR_WHOLEWORD
+ if searchParams.matchCase:
+ flags |= win32con.FR_MATCHCASE
+ if searchParams.sel == (-1, -1):
+ sel = control.GetSel()
+ # If the position is the same as we found last time,
+ # then we assume it is a "FindNext"
+ if sel == lastSearch.sel:
+ sel = sel[0] + 1, sel[0] + 1
+ else:
+ sel = searchParams.sel
+
+ if sel[0] == sel[1]:
+ sel = sel[0], control.GetTextLength()
+
+ rc = FOUND_NOTHING
+ # (Old edit control will fail here!)
+ posFind, foundSel = control.FindText(flags, sel, searchParams.findText)
+ lastSearch = SearchParams(searchParams)
+ if posFind >= 0:
+ rc = FOUND_NORMAL
+ lineno = control.LineFromChar(posFind)
+ control.SCIEnsureVisible(lineno)
+ control.SetSel(foundSel)
+ control.SetFocus()
+ win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
+ if rc == FOUND_NOTHING and lastSearch.acrossFiles:
+ # Loop around all documents. First find this document.
+ try:
+ try:
+ doc = control.GetDocument()
+ except AttributeError:
+ try:
+ doc = control.GetParent().GetDocument()
+ except AttributeError:
+ print("Can't find a document for the control!")
+ doc = None
+ if doc is not None:
+ template = doc.GetDocTemplate()
+ alldocs = template.GetDocumentList()
+ mypos = lookpos = alldocs.index(doc)
+ while 1:
+ lookpos = (lookpos + 1) % len(alldocs)
+ if lookpos == mypos:
+ break
+ view = alldocs[lookpos].GetFirstView()
+ posFind, foundSel = view.FindText(
+ flags, (0, view.GetTextLength()), searchParams.findText
+ )
+ if posFind >= 0:
+ nChars = foundSel[1] - foundSel[0]
+ lineNo = view.LineFromChar(posFind) # zero based.
+ lineStart = view.LineIndex(lineNo)
+ colNo = posFind - lineStart # zero based.
+ scriptutils.JumpToDocument(
+ alldocs[lookpos].GetPathName(),
+ lineNo + 1,
+ colNo + 1,
+ nChars,
+ )
+ rc = FOUND_NEXT_FILE
+ break
+ except win32ui.error:
+ pass
+ if rc == FOUND_NOTHING:
+ # Loop around this control - attempt to find from the start of the control.
+ posFind, foundSel = control.FindText(
+ flags, (0, sel[0] - 1), searchParams.findText
+ )
+ if posFind >= 0:
+ control.SCIEnsureVisible(control.LineFromChar(foundSel[0]))
+ control.SetSel(foundSel)
+ control.SetFocus()
+ win32ui.SetStatusText("Not found! Searching from the top of the file.")
+ rc = FOUND_LOOPED_BACK
+ else:
+ lastSearch.sel = -1, -1
+ win32ui.SetStatusText("Can not find '%s'" % searchParams.findText)
+
+ if rc != FOUND_NOTHING:
+ lastSearch.sel = foundSel
+
+ if lastSearch.remember:
+ defaultSearch = lastSearch
+
+ # track search history
+ try:
+ ix = searchHistory.index(searchParams.findText)
+ except ValueError:
+ if len(searchHistory) > 50:
+ searchHistory[50:] = []
+ else:
+ del searchHistory[ix]
+ searchHistory.insert(0, searchParams.findText)
+
+ return rc
+
+
+def _ReplaceIt(control):
+ control = _GetControl(control)
+ statusText = "Can not find '%s'." % lastSearch.findText
+ rc = FOUND_NOTHING
+ if control is not None and lastSearch.sel != (-1, -1):
+ control.ReplaceSel(lastSearch.replaceText)
+ rc = FindNext()
+ if rc != FOUND_NOTHING:
+ statusText = win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE)
+ win32ui.SetStatusText(statusText)
+ return rc
+
+
+class FindReplaceDialog(dialog.Dialog):
+ def __init__(self):
+ dialog.Dialog.__init__(self, self._GetDialogTemplate())
+ self.HookCommand(self.OnFindNext, 109)
+
+ def OnInitDialog(self):
+ self.editFindText = self.GetDlgItem(102)
+ self.butMatchWords = self.GetDlgItem(105)
+ self.butMatchCase = self.GetDlgItem(107)
+ self.butKeepDialogOpen = self.GetDlgItem(115)
+ self.butAcrossFiles = self.GetDlgItem(116)
+ self.butRemember = self.GetDlgItem(117)
+
+ self.editFindText.SetWindowText(defaultSearch.findText)
+ control = _GetControl()
+ # _GetControl only gets normal MDI windows; if the interactive
+ # window is docked and no document open, we get None.
+ if control:
+ # If we have a selection, default to that.
+ sel = control.GetSelText()
+ if len(sel) != 0:
+ self.editFindText.SetWindowText(sel)
+ if defaultSearch.remember:
+ defaultSearch.findText = sel
+ for hist in searchHistory:
+ self.editFindText.AddString(hist)
+
+ if hasattr(self.editFindText, "SetEditSel"):
+ self.editFindText.SetEditSel(0, -1)
+ else:
+ self.editFindText.SetSel(0, -1)
+ self.butMatchWords.SetCheck(defaultSearch.matchWords)
+ self.butMatchCase.SetCheck(defaultSearch.matchCase)
+ self.butKeepDialogOpen.SetCheck(defaultSearch.keepDialogOpen)
+ self.butAcrossFiles.SetCheck(defaultSearch.acrossFiles)
+ self.butRemember.SetCheck(defaultSearch.remember)
+ return dialog.Dialog.OnInitDialog(self)
+
+ def OnDestroy(self, msg):
+ global curDialog
+ curDialog = None
+ return dialog.Dialog.OnDestroy(self, msg)
+
+ def DoFindNext(self):
+ params = SearchParams()
+ params.findText = self.editFindText.GetWindowText()
+ params.matchCase = self.butMatchCase.GetCheck()
+ params.matchWords = self.butMatchWords.GetCheck()
+ params.acrossFiles = self.butAcrossFiles.GetCheck()
+ params.remember = self.butRemember.GetCheck()
+ return _FindIt(None, params)
+
+ def OnFindNext(self, id, code):
+ if code != 0: # BN_CLICKED
+ # 3d controls (python.exe + start_pythonwin.pyw) send
+ # other notification codes
+ return 1 #
+ if not self.editFindText.GetWindowText():
+ win32api.MessageBeep()
+ return 1
+ if self.DoFindNext() != FOUND_NOTHING:
+ if not self.butKeepDialogOpen.GetCheck():
+ self.DestroyWindow()
+
+
+class FindDialog(FindReplaceDialog):
+ def _GetDialogTemplate(self):
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ visible = win32con.WS_CHILD | win32con.WS_VISIBLE
+ dt = [
+ ["Find", (0, 2, 240, 75), style, None, (8, "MS Sans Serif")],
+ ["Static", "Fi&nd What:", 101, (5, 8, 40, 10), visible],
+ [
+ "ComboBox",
+ "",
+ 102,
+ (50, 7, 120, 120),
+ visible
+ | win32con.WS_BORDER
+ | win32con.WS_TABSTOP
+ | win32con.WS_VSCROLL
+ | win32con.CBS_DROPDOWN
+ | win32con.CBS_AUTOHSCROLL,
+ ],
+ [
+ "Button",
+ "Match &whole word only",
+ 105,
+ (5, 23, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Match &case",
+ 107,
+ (5, 33, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Keep &dialog open",
+ 115,
+ (5, 43, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Across &open files",
+ 116,
+ (5, 52, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "&Remember as default search",
+ 117,
+ (5, 61, 150, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "&Find Next",
+ 109,
+ (185, 5, 50, 14),
+ visible | win32con.BS_DEFPUSHBUTTON | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Cancel",
+ win32con.IDCANCEL,
+ (185, 23, 50, 14),
+ visible | win32con.WS_TABSTOP,
+ ],
+ ]
+ return dt
+
+
+class ReplaceDialog(FindReplaceDialog):
+ def _GetDialogTemplate(self):
+ style = (
+ win32con.DS_MODALFRAME
+ | win32con.WS_POPUP
+ | win32con.WS_VISIBLE
+ | win32con.WS_CAPTION
+ | win32con.WS_SYSMENU
+ | win32con.DS_SETFONT
+ )
+ visible = win32con.WS_CHILD | win32con.WS_VISIBLE
+ dt = [
+ ["Replace", (0, 2, 240, 95), style, 0, (8, "MS Sans Serif")],
+ ["Static", "Fi&nd What:", 101, (5, 8, 40, 10), visible],
+ [
+ "ComboBox",
+ "",
+ 102,
+ (60, 7, 110, 120),
+ visible
+ | win32con.WS_BORDER
+ | win32con.WS_TABSTOP
+ | win32con.WS_VSCROLL
+ | win32con.CBS_DROPDOWN
+ | win32con.CBS_AUTOHSCROLL,
+ ],
+ ["Static", "Re&place with:", 103, (5, 25, 50, 10), visible],
+ [
+ "ComboBox",
+ "",
+ 104,
+ (60, 24, 110, 120),
+ visible
+ | win32con.WS_BORDER
+ | win32con.WS_TABSTOP
+ | win32con.WS_VSCROLL
+ | win32con.CBS_DROPDOWN
+ | win32con.CBS_AUTOHSCROLL,
+ ],
+ [
+ "Button",
+ "Match &whole word only",
+ 105,
+ (5, 42, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Match &case",
+ 107,
+ (5, 52, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Keep &dialog open",
+ 115,
+ (5, 62, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Across &open files",
+ 116,
+ (5, 72, 100, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "&Remember as default search",
+ 117,
+ (5, 81, 150, 10),
+ visible | win32con.BS_AUTOCHECKBOX | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "&Find Next",
+ 109,
+ (185, 5, 50, 14),
+ visible | win32con.BS_DEFPUSHBUTTON | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "&Replace",
+ 110,
+ (185, 23, 50, 14),
+ visible | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Replace &All",
+ 111,
+ (185, 41, 50, 14),
+ visible | win32con.WS_TABSTOP,
+ ],
+ [
+ "Button",
+ "Cancel",
+ win32con.IDCANCEL,
+ (185, 59, 50, 14),
+ visible | win32con.WS_TABSTOP,
+ ],
+ ]
+ return dt
+
+ def OnInitDialog(self):
+ rc = FindReplaceDialog.OnInitDialog(self)
+ self.HookCommand(self.OnReplace, 110)
+ self.HookCommand(self.OnReplaceAll, 111)
+ self.HookMessage(self.OnActivate, win32con.WM_ACTIVATE)
+ self.editReplaceText = self.GetDlgItem(104)
+ self.editReplaceText.SetWindowText(lastSearch.replaceText)
+ if hasattr(self.editReplaceText, "SetEditSel"):
+ self.editReplaceText.SetEditSel(0, -1)
+ else:
+ self.editReplaceText.SetSel(0, -1)
+ self.butReplace = self.GetDlgItem(110)
+ self.butReplaceAll = self.GetDlgItem(111)
+ self.CheckButtonStates()
+ return rc # 0 when focus set
+
+ def CheckButtonStates(self):
+ # We can do a "Replace" or "Replace All" if the current selection
+ # is the same as the search text.
+ ft = self.editFindText.GetWindowText()
+ control = _GetControl()
+ # bCanReplace = len(ft)>0 and control.GetSelText() == ft
+ bCanReplace = control is not None and lastSearch.sel == control.GetSel()
+ self.butReplace.EnableWindow(bCanReplace)
+
+ # self.butReplaceAll.EnableWindow(bCanReplace)
+
+ def OnActivate(self, msg):
+ wparam = msg[2]
+ fActive = win32api.LOWORD(wparam)
+ if fActive != win32con.WA_INACTIVE:
+ self.CheckButtonStates()
+
+ def OnFindNext(self, id, code):
+ if code != 0:
+ return 1
+ self.DoFindNext()
+ self.CheckButtonStates()
+
+ def OnReplace(self, id, code):
+ if code != 0:
+ return 1
+ lastSearch.replaceText = self.editReplaceText.GetWindowText()
+ _ReplaceIt(None)
+
+ def OnReplaceAll(self, id, code):
+ if code != 0:
+ return 1
+ control = _GetControl(None)
+ if control is not None:
+ control.SetSel(0)
+ num = 0
+ if self.DoFindNext() == FOUND_NORMAL:
+ num = 1
+ lastSearch.replaceText = self.editReplaceText.GetWindowText()
+ while _ReplaceIt(control) == FOUND_NORMAL:
+ num += 1
+
+ win32ui.SetStatusText("Replaced %d occurrences" % num)
+ if num > 0 and not self.butKeepDialogOpen.GetCheck():
+ self.DestroyWindow()
+
+
+if __name__ == "__main__":
+ ShowFindDialog()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/formatter.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/formatter.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fc42fbcb1f9e7c94d10357284f42ae6b98bd812
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/formatter.py
@@ -0,0 +1,704 @@
+# Does Python source formatting for Scintilla controls.
+import array
+import string
+
+import win32api
+import win32con
+import win32ui
+
+from . import scintillacon
+
+WM_KICKIDLE = 0x036A
+
+# Used to indicate that style should use default color
+from win32con import CLR_INVALID
+
+debugging = 0
+if debugging:
+ # Output must go to another process else the result of
+ # the printing itself will trigger again trigger a trace.
+
+ import win32trace
+ import win32traceutil
+
+ def trace(*args):
+ win32trace.write(" ".join(map(str, args)) + "\n")
+
+else:
+ trace = lambda *args: None
+
+
+class Style:
+ """Represents a single format"""
+
+ def __init__(self, name, format, background=CLR_INVALID):
+ self.name = name # Name the format representes eg, "String", "Class"
+ # Default background for each style is only used when there are no
+ # saved settings (generally on first startup)
+ self.background = self.default_background = background
+ if isinstance(format, str):
+ self.aliased = format
+ self.format = None
+ else:
+ self.format = format
+ self.aliased = None
+ self.stylenum = None # Not yet registered.
+
+ def IsBasedOnDefault(self):
+ return len(self.format) == 5
+
+ # If the currently extended font defintion matches the
+ # default format, restore the format to the "simple" format.
+ def NormalizeAgainstDefault(self, defaultFormat):
+ if self.IsBasedOnDefault():
+ return 0 # No more to do, and not changed.
+ bIsDefault = (
+ self.format[7] == defaultFormat[7] and self.format[2] == defaultFormat[2]
+ )
+ if bIsDefault:
+ self.ForceAgainstDefault()
+ return bIsDefault
+
+ def ForceAgainstDefault(self):
+ self.format = self.format[:5]
+
+ def GetCompleteFormat(self, defaultFormat):
+ # Get the complete style after applying any relevant defaults.
+ if len(self.format) == 5: # It is a default one
+ fmt = self.format + defaultFormat[5:]
+ else:
+ fmt = self.format
+ flags = (
+ win32con.CFM_BOLD
+ | win32con.CFM_CHARSET
+ | win32con.CFM_COLOR
+ | win32con.CFM_FACE
+ | win32con.CFM_ITALIC
+ | win32con.CFM_SIZE
+ )
+ return (flags,) + fmt[1:]
+
+
+# The Formatter interface
+# used primarily when the actual formatting is done by Scintilla!
+class FormatterBase:
+ def __init__(self, scintilla):
+ self.scintilla = scintilla
+ self.baseFormatFixed = (-402653169, 0, 200, 0, 0, 0, 49, "Courier New")
+ self.baseFormatProp = (-402653169, 0, 200, 0, 0, 0, 49, "Arial")
+ self.bUseFixed = 1
+ self.styles = {} # Indexed by name
+ self.styles_by_id = {} # Indexed by allocated ID.
+ self.SetStyles()
+
+ def HookFormatter(self, parent=None):
+ raise NotImplementedError
+
+ # Used by the IDLE extensions to quickly determine if a character is a string.
+ def GetStringStyle(self, pos):
+ try:
+ style = self.styles_by_id[self.scintilla.SCIGetStyleAt(pos)]
+ except KeyError:
+ # A style we don't know about - probably not even a .py file - can't be a string
+ return None
+ if style.name in self.string_style_names:
+ return style
+ return None
+
+ def RegisterStyle(self, style, stylenum):
+ assert stylenum is not None, "We must have a style number"
+ assert style.stylenum is None, "Style has already been registered"
+ assert stylenum not in self.styles, "We are reusing a style number!"
+ style.stylenum = stylenum
+ self.styles[style.name] = style
+ self.styles_by_id[stylenum] = style
+
+ def SetStyles(self):
+ raise NotImplementedError
+
+ def GetSampleText(self):
+ return "Sample Text for the Format Dialog"
+
+ def GetDefaultFormat(self):
+ if self.bUseFixed:
+ return self.baseFormatFixed
+ return self.baseFormatProp
+
+ # Update the control with the new style format.
+ def _ReformatStyle(self, style):
+ ## Selection (background only for now)
+ ## Passing False for WPARAM to SCI_SETSELBACK is documented as resetting to scintilla default,
+ ## but does not work - selection background is not visible at all.
+ ## Default value in SPECIAL_STYLES taken from scintilla source.
+ if style.name == STYLE_SELECTION:
+ clr = style.background
+ self.scintilla.SendScintilla(scintillacon.SCI_SETSELBACK, True, clr)
+
+ ## Can't change font for selection, but could set color
+ ## However, the font color dropbox has no option for default, and thus would
+ ## always override syntax coloring
+ ## clr = style.format[4]
+ ## self.scintilla.SendScintilla(scintillacon.SCI_SETSELFORE, clr != CLR_INVALID, clr)
+ return
+
+ assert style.stylenum is not None, "Unregistered style."
+ # print("Reformat style", style.name, style.stylenum)
+ scintilla = self.scintilla
+ stylenum = style.stylenum
+ # Now we have the style number, indirect for the actual style.
+ if style.aliased is not None:
+ style = self.styles[style.aliased]
+ f = style.format
+ if style.IsBasedOnDefault():
+ baseFormat = self.GetDefaultFormat()
+ else:
+ baseFormat = f
+ scintilla.SCIStyleSetFore(stylenum, f[4])
+ scintilla.SCIStyleSetFont(stylenum, baseFormat[7], baseFormat[5])
+ if f[1] & 1:
+ scintilla.SCIStyleSetBold(stylenum, 1)
+ else:
+ scintilla.SCIStyleSetBold(stylenum, 0)
+ if f[1] & 2:
+ scintilla.SCIStyleSetItalic(stylenum, 1)
+ else:
+ scintilla.SCIStyleSetItalic(stylenum, 0)
+ scintilla.SCIStyleSetSize(stylenum, int(baseFormat[2] / 20))
+ scintilla.SCIStyleSetEOLFilled(stylenum, 1) # Only needed for unclosed strings.
+
+ ## Default style background to whitespace background if set,
+ ## otherwise use system window color
+ bg = style.background
+ if bg == CLR_INVALID:
+ bg = self.styles[STYLE_DEFAULT].background
+ if bg == CLR_INVALID:
+ bg = win32api.GetSysColor(win32con.COLOR_WINDOW)
+ scintilla.SCIStyleSetBack(stylenum, bg)
+
+ def GetStyleByNum(self, stylenum):
+ return self.styles_by_id[stylenum]
+
+ def ApplyFormattingStyles(self, bReload=1):
+ if bReload:
+ self.LoadPreferences()
+ baseFormat = self.GetDefaultFormat()
+ defaultStyle = Style("default", baseFormat)
+ defaultStyle.stylenum = scintillacon.STYLE_DEFAULT
+ self._ReformatStyle(defaultStyle)
+ for style in self.styles.values():
+ if style.aliased is None:
+ style.NormalizeAgainstDefault(baseFormat)
+ self._ReformatStyle(style)
+ self.scintilla.InvalidateRect()
+
+ # Some functions for loading and saving preferences. By default
+ # an INI file (well, MFC maps this to the registry) is used.
+ def LoadPreferences(self):
+ self.baseFormatFixed = eval(
+ self.LoadPreference("Base Format Fixed", str(self.baseFormatFixed))
+ )
+ self.baseFormatProp = eval(
+ self.LoadPreference("Base Format Proportional", str(self.baseFormatProp))
+ )
+ self.bUseFixed = int(self.LoadPreference("Use Fixed", 1))
+
+ for style in self.styles.values():
+ new = self.LoadPreference(style.name, str(style.format))
+ try:
+ style.format = eval(new)
+ except:
+ print("Error loading style data for", style.name)
+ # Use "vanilla" background hardcoded in PYTHON_STYLES if no settings in registry
+ style.background = int(
+ self.LoadPreference(
+ style.name + " background", style.default_background
+ )
+ )
+
+ def LoadPreference(self, name, default):
+ return win32ui.GetProfileVal("Format", name, default)
+
+ def SavePreferences(self):
+ self.SavePreference("Base Format Fixed", str(self.baseFormatFixed))
+ self.SavePreference("Base Format Proportional", str(self.baseFormatProp))
+ self.SavePreference("Use Fixed", self.bUseFixed)
+ for style in self.styles.values():
+ if style.aliased is None:
+ self.SavePreference(style.name, str(style.format))
+ bg_name = style.name + " background"
+ self.SavePreference(bg_name, style.background)
+
+ def SavePreference(self, name, value):
+ win32ui.WriteProfileVal("Format", name, value)
+
+
+# An abstract formatter
+# For all formatters we actually implement here.
+# (as opposed to those formatters built in to Scintilla)
+class Formatter(FormatterBase):
+ def __init__(self, scintilla):
+ self.bCompleteWhileIdle = 0
+ self.bHaveIdleHandler = 0 # Don't currently have an idle handle
+ self.nextstylenum = 0
+ FormatterBase.__init__(self, scintilla)
+
+ def HookFormatter(self, parent=None):
+ if parent is None:
+ parent = self.scintilla.GetParent() # was GetParentFrame()!?
+ parent.HookNotify(self.OnStyleNeeded, scintillacon.SCN_STYLENEEDED)
+
+ def OnStyleNeeded(self, std, extra):
+ notify = self.scintilla.SCIUnpackNotifyMessage(extra)
+ endStyledChar = self.scintilla.SendScintilla(scintillacon.SCI_GETENDSTYLED)
+ lineEndStyled = self.scintilla.LineFromChar(endStyledChar)
+ endStyled = self.scintilla.LineIndex(lineEndStyled)
+ # print(
+ # "endPosPaint",
+ # endPosPaint,
+ # "endStyledChar",
+ # endStyledChar,
+ # "lineEndStyled",
+ # lineEndStyled,
+ # "endStyled",
+ # endStyled,
+ # )
+ self.Colorize(endStyled, notify.position)
+
+ def ColorSeg(self, start, end, styleName):
+ end += 1
+ # assert end-start>=0, "Can't have negative styling"
+ stylenum = self.styles[styleName].stylenum
+ while start < end:
+ self.style_buffer[start] = stylenum
+ start += 1
+ # self.scintilla.SCISetStyling(end - start + 1, stylenum)
+
+ def RegisterStyle(self, style, stylenum=None):
+ if stylenum is None:
+ stylenum = self.nextstylenum
+ self.nextstylenum += 1
+ FormatterBase.RegisterStyle(self, style, stylenum)
+
+ def ColorizeString(self, str, styleStart):
+ raise RuntimeError("You must override this method")
+
+ def Colorize(self, start=0, end=-1):
+ scintilla = self.scintilla
+ # scintilla's formatting is all done in terms of utf, so
+ # we work with utf8 bytes instead of unicode. This magically
+ # works as any extended chars found in the utf8 don't change
+ # the semantics.
+ stringVal = scintilla.GetTextRange(start, end, decode=False)
+ if start > 0:
+ stylenum = scintilla.SCIGetStyleAt(start - 1)
+ styleStart = self.GetStyleByNum(stylenum).name
+ else:
+ styleStart = None
+ # trace("Coloring", start, end, end-start, len(stringVal), styleStart, self.scintilla.SCIGetCharAt(start))
+ scintilla.SCIStartStyling(start, 31)
+ self.style_buffer = array.array("b", (0,) * len(stringVal))
+ self.ColorizeString(stringVal, styleStart)
+ scintilla.SCISetStylingEx(self.style_buffer)
+ self.style_buffer = None
+ # trace("After styling, end styled is", self.scintilla.SCIGetEndStyled())
+ if (
+ self.bCompleteWhileIdle
+ and not self.bHaveIdleHandler
+ and end != -1
+ and end < scintilla.GetTextLength()
+ ):
+ self.bHaveIdleHandler = 1
+ win32ui.GetApp().AddIdleHandler(self.DoMoreColoring)
+ # Kicking idle makes the app seem slower when initially repainting!
+
+ # win32ui.GetMainFrame().PostMessage(WM_KICKIDLE, 0, 0)
+
+ def DoMoreColoring(self, handler, count):
+ try:
+ scintilla = self.scintilla
+ endStyled = scintilla.SCIGetEndStyled()
+ lineStartStyled = scintilla.LineFromChar(endStyled)
+ start = scintilla.LineIndex(lineStartStyled)
+ end = scintilla.LineIndex(lineStartStyled + 1)
+ textlen = scintilla.GetTextLength()
+ if end < 0:
+ end = textlen
+
+ finished = end >= textlen
+ self.Colorize(start, end)
+ except (win32ui.error, AttributeError):
+ # Window may have closed before we finished - no big deal!
+ finished = 1
+
+ if finished:
+ self.bHaveIdleHandler = 0
+ win32ui.GetApp().DeleteIdleHandler(handler)
+ return not finished
+
+
+# A Formatter that knows how to format Python source
+from keyword import iskeyword, kwlist
+
+wordstarts = "_0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+wordchars = "._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
+operators = "%^&*()-+=|{}[]:;<>,/?!.~"
+
+STYLE_DEFAULT = "Whitespace"
+STYLE_COMMENT = "Comment"
+STYLE_COMMENT_BLOCK = "Comment Blocks"
+STYLE_NUMBER = "Number"
+STYLE_STRING = "String"
+STYLE_SQSTRING = "SQ String"
+STYLE_TQSSTRING = "TQS String"
+STYLE_TQDSTRING = "TQD String"
+STYLE_KEYWORD = "Keyword"
+STYLE_CLASS = "Class"
+STYLE_METHOD = "Method"
+STYLE_OPERATOR = "Operator"
+STYLE_IDENTIFIER = "Identifier"
+STYLE_BRACE = "Brace/Paren - matching"
+STYLE_BRACEBAD = "Brace/Paren - unmatched"
+STYLE_STRINGEOL = "String with no terminator"
+STYLE_LINENUMBER = "Line numbers"
+STYLE_INDENTGUIDE = "Indent guide"
+STYLE_SELECTION = "Selection"
+
+STRING_STYLES = [
+ STYLE_STRING,
+ STYLE_SQSTRING,
+ STYLE_TQSSTRING,
+ STYLE_TQDSTRING,
+ STYLE_STRINGEOL,
+]
+
+# These styles can have any ID - they are not special to scintilla itself.
+# However, if we use the built-in lexer, then we must use its style numbers
+# so in that case, they _are_ special.
+# (name, format, background, scintilla id)
+PYTHON_STYLES = [
+ (STYLE_DEFAULT, (0, 0, 200, 0, 0x808080), CLR_INVALID, scintillacon.SCE_P_DEFAULT),
+ (
+ STYLE_COMMENT,
+ (0, 2, 200, 0, 0x008000),
+ CLR_INVALID,
+ scintillacon.SCE_P_COMMENTLINE,
+ ),
+ (
+ STYLE_COMMENT_BLOCK,
+ (0, 2, 200, 0, 0x808080),
+ CLR_INVALID,
+ scintillacon.SCE_P_COMMENTBLOCK,
+ ),
+ (STYLE_NUMBER, (0, 0, 200, 0, 0x808000), CLR_INVALID, scintillacon.SCE_P_NUMBER),
+ (STYLE_STRING, (0, 0, 200, 0, 0x008080), CLR_INVALID, scintillacon.SCE_P_STRING),
+ (STYLE_SQSTRING, STYLE_STRING, CLR_INVALID, scintillacon.SCE_P_CHARACTER),
+ (STYLE_TQSSTRING, STYLE_STRING, CLR_INVALID, scintillacon.SCE_P_TRIPLE),
+ (STYLE_TQDSTRING, STYLE_STRING, CLR_INVALID, scintillacon.SCE_P_TRIPLEDOUBLE),
+ (STYLE_STRINGEOL, (0, 0, 200, 0, 0x000000), 0x008080, scintillacon.SCE_P_STRINGEOL),
+ (STYLE_KEYWORD, (0, 1, 200, 0, 0x800000), CLR_INVALID, scintillacon.SCE_P_WORD),
+ (STYLE_CLASS, (0, 1, 200, 0, 0xFF0000), CLR_INVALID, scintillacon.SCE_P_CLASSNAME),
+ (STYLE_METHOD, (0, 1, 200, 0, 0x808000), CLR_INVALID, scintillacon.SCE_P_DEFNAME),
+ (
+ STYLE_OPERATOR,
+ (0, 0, 200, 0, 0x000000),
+ CLR_INVALID,
+ scintillacon.SCE_P_OPERATOR,
+ ),
+ (
+ STYLE_IDENTIFIER,
+ (0, 0, 200, 0, 0x000000),
+ CLR_INVALID,
+ scintillacon.SCE_P_IDENTIFIER,
+ ),
+]
+
+# These styles _always_ have this specific style number, regardless of
+# internal or external formatter.
+SPECIAL_STYLES = [
+ (STYLE_BRACE, (0, 0, 200, 0, 0x000000), 0xFFFF80, scintillacon.STYLE_BRACELIGHT),
+ (STYLE_BRACEBAD, (0, 0, 200, 0, 0x000000), 0x8EA5F2, scintillacon.STYLE_BRACEBAD),
+ (
+ STYLE_LINENUMBER,
+ (0, 0, 200, 0, 0x000000),
+ win32api.GetSysColor(win32con.COLOR_3DFACE),
+ scintillacon.STYLE_LINENUMBER,
+ ),
+ (
+ STYLE_INDENTGUIDE,
+ (0, 0, 200, 0, 0x000000),
+ CLR_INVALID,
+ scintillacon.STYLE_INDENTGUIDE,
+ ),
+ ## Not actually a style; requires special handling to send appropriate messages to scintilla
+ (
+ STYLE_SELECTION,
+ (0, 0, 200, 0, CLR_INVALID),
+ win32api.RGB(0xC0, 0xC0, 0xC0),
+ 999999,
+ ),
+]
+
+PythonSampleCode = """\
+# Some Python
+class Sample(Super):
+ def Fn(self):
+\tself.v = 1024
+dest = 'dest.html'
+x = func(a + 1)|)
+s = "I forget...
+## A large
+## comment block"""
+
+
+class PythonSourceFormatter(Formatter):
+ string_style_names = STRING_STYLES
+
+ def GetSampleText(self):
+ return PythonSampleCode
+
+ def LoadStyles(self):
+ pass
+
+ def SetStyles(self):
+ for name, format, bg, ignore in PYTHON_STYLES:
+ self.RegisterStyle(Style(name, format, bg))
+ for name, format, bg, sc_id in SPECIAL_STYLES:
+ self.RegisterStyle(Style(name, format, bg), sc_id)
+
+ def ClassifyWord(self, cdoc, start, end, prevWord):
+ word = cdoc[start : end + 1].decode("latin-1")
+ attr = STYLE_IDENTIFIER
+ if prevWord == "class":
+ attr = STYLE_CLASS
+ elif prevWord == "def":
+ attr = STYLE_METHOD
+ elif word[0] in string.digits:
+ attr = STYLE_NUMBER
+ elif iskeyword(word):
+ attr = STYLE_KEYWORD
+ self.ColorSeg(start, end, attr)
+ return word
+
+ def ColorizeString(self, str, styleStart):
+ if styleStart is None:
+ styleStart = STYLE_DEFAULT
+ return self.ColorizePythonCode(str, 0, styleStart)
+
+ def ColorizePythonCode(self, cdoc, charStart, styleStart):
+ # Straight translation of C++, should do better
+ lengthDoc = len(cdoc)
+ if lengthDoc <= charStart:
+ return
+ prevWord = ""
+ state = styleStart
+ chPrev = chPrev2 = chPrev3 = " "
+ chNext2 = chNext = cdoc[charStart : charStart + 1].decode("latin-1")
+ startSeg = i = charStart
+ while i < lengthDoc:
+ ch = chNext
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1 : i + 2].decode("latin-1")
+ chNext2 = " "
+ if i + 2 < lengthDoc:
+ chNext2 = cdoc[i + 2 : i + 3].decode("latin-1")
+ if state == STYLE_DEFAULT:
+ if ch in wordstarts:
+ self.ColorSeg(startSeg, i - 1, STYLE_DEFAULT)
+ state = STYLE_KEYWORD
+ startSeg = i
+ elif ch == "#":
+ self.ColorSeg(startSeg, i - 1, STYLE_DEFAULT)
+ if chNext == "#":
+ state = STYLE_COMMENT_BLOCK
+ else:
+ state = STYLE_COMMENT
+ startSeg = i
+ elif ch == '"':
+ self.ColorSeg(startSeg, i - 1, STYLE_DEFAULT)
+ startSeg = i
+ state = STYLE_COMMENT
+ if chNext == '"' and chNext2 == '"':
+ i += 2
+ state = STYLE_TQDSTRING
+ ch = " "
+ chPrev = " "
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1]
+ else:
+ state = STYLE_STRING
+ elif ch == "'":
+ self.ColorSeg(startSeg, i - 1, STYLE_DEFAULT)
+ startSeg = i
+ state = STYLE_COMMENT
+ if chNext == "'" and chNext2 == "'":
+ i += 2
+ state = STYLE_TQSSTRING
+ ch = " "
+ chPrev = " "
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1]
+ else:
+ state = STYLE_SQSTRING
+ elif ch in operators:
+ self.ColorSeg(startSeg, i - 1, STYLE_DEFAULT)
+ self.ColorSeg(i, i, STYLE_OPERATOR)
+ startSeg = i + 1
+ elif state == STYLE_KEYWORD:
+ if ch not in wordchars:
+ prevWord = self.ClassifyWord(cdoc, startSeg, i - 1, prevWord)
+ state = STYLE_DEFAULT
+ startSeg = i
+ if ch == "#":
+ if chNext == "#":
+ state = STYLE_COMMENT_BLOCK
+ else:
+ state = STYLE_COMMENT
+ elif ch == '"':
+ if chNext == '"' and chNext2 == '"':
+ i += 2
+ state = STYLE_TQDSTRING
+ ch = " "
+ chPrev = " "
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1]
+ else:
+ state = STYLE_STRING
+ elif ch == "'":
+ if chNext == "'" and chNext2 == "'":
+ i += 2
+ state = STYLE_TQSSTRING
+ ch = " "
+ chPrev = " "
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1]
+ else:
+ state = STYLE_SQSTRING
+ elif ch in operators:
+ self.ColorSeg(startSeg, i, STYLE_OPERATOR)
+ startSeg = i + 1
+ elif state == STYLE_COMMENT or state == STYLE_COMMENT_BLOCK:
+ if ch == "\r" or ch == "\n":
+ self.ColorSeg(startSeg, i - 1, state)
+ state = STYLE_DEFAULT
+ startSeg = i
+ elif state == STYLE_STRING:
+ if ch == "\\":
+ if chNext == '"' or chNext == "'" or chNext == "\\":
+ i += 1
+ ch = chNext
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1]
+ elif ch == '"':
+ self.ColorSeg(startSeg, i, STYLE_STRING)
+ state = STYLE_DEFAULT
+ startSeg = i + 1
+ elif state == STYLE_SQSTRING:
+ if ch == "\\":
+ if chNext == '"' or chNext == "'" or chNext == "\\":
+ i += 1
+ ch = chNext
+ chNext = " "
+ if i + 1 < lengthDoc:
+ chNext = cdoc[i + 1]
+ elif ch == "'":
+ self.ColorSeg(startSeg, i, STYLE_SQSTRING)
+ state = STYLE_DEFAULT
+ startSeg = i + 1
+ elif state == STYLE_TQSSTRING:
+ if ch == "'" and chPrev == "'" and chPrev2 == "'" and chPrev3 != "\\":
+ self.ColorSeg(startSeg, i, STYLE_TQSSTRING)
+ state = STYLE_DEFAULT
+ startSeg = i + 1
+ elif (
+ state == STYLE_TQDSTRING
+ and ch == '"'
+ and chPrev == '"'
+ and chPrev2 == '"'
+ and chPrev3 != "\\"
+ ):
+ self.ColorSeg(startSeg, i, STYLE_TQDSTRING)
+ state = STYLE_DEFAULT
+ startSeg = i + 1
+ chPrev3 = chPrev2
+ chPrev2 = chPrev
+ chPrev = ch
+ i += 1
+ if startSeg < lengthDoc:
+ if state == STYLE_KEYWORD:
+ self.ClassifyWord(cdoc, startSeg, lengthDoc - 1, prevWord)
+ else:
+ self.ColorSeg(startSeg, lengthDoc - 1, state)
+
+
+# These taken from the SciTE properties file.
+source_formatter_extensions = [
+ (".py .pys .pyw".split(), scintillacon.SCLEX_PYTHON),
+ (".html .htm .asp .shtml".split(), scintillacon.SCLEX_HTML),
+ (
+ "c .cc .cpp .cxx .h .hh .hpp .hxx .idl .odl .php3 .phtml .inc .js".split(),
+ scintillacon.SCLEX_CPP,
+ ),
+ (".vbs .frm .ctl .cls".split(), scintillacon.SCLEX_VB),
+ (".pl .pm .cgi .pod".split(), scintillacon.SCLEX_PERL),
+ (".sql .spec .body .sps .spb .sf .sp".split(), scintillacon.SCLEX_SQL),
+ (".tex .sty".split(), scintillacon.SCLEX_LATEX),
+ (".xml .xul".split(), scintillacon.SCLEX_XML),
+ (".err".split(), scintillacon.SCLEX_ERRORLIST),
+ (".mak".split(), scintillacon.SCLEX_MAKEFILE),
+ (".bat .cmd".split(), scintillacon.SCLEX_BATCH),
+]
+
+
+class BuiltinSourceFormatter(FormatterBase):
+ # A class that represents a formatter built-in to Scintilla
+ def __init__(self, scintilla, ext):
+ self.ext = ext
+ FormatterBase.__init__(self, scintilla)
+
+ def Colorize(self, start=0, end=-1):
+ self.scintilla.SendScintilla(scintillacon.SCI_COLOURISE, start, end)
+
+ def RegisterStyle(self, style, stylenum=None):
+ assert style.stylenum is None, "Style has already been registered"
+ if stylenum is None:
+ stylenum = self.nextstylenum
+ self.nextstylenum += 1
+ assert self.styles.get(stylenum) is None, "We are reusing a style number!"
+ style.stylenum = stylenum
+ self.styles[style.name] = style
+ self.styles_by_id[stylenum] = style
+
+ def HookFormatter(self, parent=None):
+ sc = self.scintilla
+ for exts, formatter in source_formatter_extensions:
+ if self.ext in exts:
+ formatter_use = formatter
+ break
+ else:
+ formatter_use = scintillacon.SCLEX_PYTHON
+ sc.SendScintilla(scintillacon.SCI_SETLEXER, formatter_use)
+ keywords = " ".join(kwlist)
+ sc.SCISetKeywords(keywords)
+
+
+class BuiltinPythonSourceFormatter(BuiltinSourceFormatter):
+ sci_lexer_name = scintillacon.SCLEX_PYTHON
+ string_style_names = STRING_STYLES
+
+ def __init__(self, sc, ext=".py"):
+ BuiltinSourceFormatter.__init__(self, sc, ext)
+
+ def SetStyles(self):
+ for name, format, bg, sc_id in PYTHON_STYLES:
+ self.RegisterStyle(Style(name, format, bg), sc_id)
+ for name, format, bg, sc_id in SPECIAL_STYLES:
+ self.RegisterStyle(Style(name, format, bg), sc_id)
+
+ def GetSampleText(self):
+ return PythonSampleCode
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/keycodes.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/keycodes.py
new file mode 100644
index 0000000000000000000000000000000000000000..adf015ac4474e17d59f4f3c9f9b426abc1f9444c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/keycodes.py
@@ -0,0 +1,190 @@
+import win32api
+import win32con
+import win32ui
+
+MAPVK_VK_TO_CHAR = 2
+
+key_name_to_vk = {}
+key_code_to_name = {}
+
+_better_names = {
+ "escape": "esc",
+ "return": "enter",
+ "back": "pgup",
+ "next": "pgdn",
+}
+
+
+def _fillvkmap():
+ # Pull the VK_names from win32con
+ names = [entry for entry in win32con.__dict__ if entry.startswith("VK_")]
+ for name in names:
+ code = getattr(win32con, name)
+ n = name[3:].lower()
+ key_name_to_vk[n] = code
+ if n in _better_names:
+ n = _better_names[n]
+ key_name_to_vk[n] = code
+ key_code_to_name[code] = n
+
+
+_fillvkmap()
+
+
+def get_vk(chardesc):
+ if len(chardesc) == 1:
+ # it is a character.
+ info = win32api.VkKeyScan(chardesc)
+ if info == -1:
+ # Note: returning None, None causes an error when keyboard layout is non-English, see the report below
+ # https://stackoverflow.com/questions/45138084/pythonwin-occasionally-gives-an-error-on-opening
+ return 0, 0
+ vk = win32api.LOBYTE(info)
+ state = win32api.HIBYTE(info)
+ modifiers = 0
+ if state & 0x1:
+ modifiers |= win32con.SHIFT_PRESSED
+ if state & 0x2:
+ modifiers |= win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED
+ if state & 0x4:
+ modifiers |= win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED
+ return vk, modifiers
+ # must be a 'key name'
+ return key_name_to_vk.get(chardesc.lower()), 0
+
+
+modifiers = {
+ "alt": win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED,
+ "lalt": win32con.LEFT_ALT_PRESSED,
+ "ralt": win32con.RIGHT_ALT_PRESSED,
+ "ctrl": win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED,
+ "ctl": win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED,
+ "control": win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED,
+ "lctrl": win32con.LEFT_CTRL_PRESSED,
+ "lctl": win32con.LEFT_CTRL_PRESSED,
+ "rctrl": win32con.RIGHT_CTRL_PRESSED,
+ "rctl": win32con.RIGHT_CTRL_PRESSED,
+ "shift": win32con.SHIFT_PRESSED,
+ "key": 0, # ignore key tag.
+}
+
+
+def parse_key_name(name):
+ name += "-" # Add a sentinel
+ start = pos = 0
+ max = len(name)
+ toks = []
+ while pos < max:
+ if name[pos] in "+-":
+ tok = name[start:pos]
+ # use the ascii lower() version of tok, so ascii chars require
+ # an explicit shift modifier - ie 'Ctrl+G' should be treated as
+ # 'ctrl+g' - 'ctrl+shift+g' would be needed if desired.
+ # This is mainly to avoid changing all the old keystroke defs
+ toks.append(tok.lower())
+ pos += 1 # skip the sep
+ start = pos
+ pos += 1
+ flags = 0
+ # do the modifiers
+ for tok in toks[:-1]:
+ mod = modifiers.get(tok.lower())
+ if mod is not None:
+ flags |= mod
+ # the key name
+ vk, this_flags = get_vk(toks[-1])
+ return vk, flags | this_flags
+
+
+_checks = [
+ [ # Shift
+ ("Shift", win32con.SHIFT_PRESSED),
+ ],
+ [ # Ctrl key
+ ("Ctrl", win32con.LEFT_CTRL_PRESSED | win32con.RIGHT_CTRL_PRESSED),
+ ("LCtrl", win32con.LEFT_CTRL_PRESSED),
+ ("RCtrl", win32con.RIGHT_CTRL_PRESSED),
+ ],
+ [ # Alt key
+ ("Alt", win32con.LEFT_ALT_PRESSED | win32con.RIGHT_ALT_PRESSED),
+ ("LAlt", win32con.LEFT_ALT_PRESSED),
+ ("RAlt", win32con.RIGHT_ALT_PRESSED),
+ ],
+]
+
+
+def make_key_name(vk, flags):
+ # Check alt keys.
+ flags_done = 0
+ parts = []
+ for moddata in _checks:
+ for name, checkflag in moddata:
+ if flags & checkflag:
+ parts.append(name)
+ flags_done &= checkflag
+ break
+ if flags_done & flags:
+ parts.append(hex(flags & ~flags_done))
+ # Now the key name.
+ if vk is None:
+ parts.append("")
+ else:
+ try:
+ parts.append(key_code_to_name[vk])
+ except KeyError:
+ # Not in our virtual key map - ask Windows what character this
+ # key corresponds to.
+ scancode = win32api.MapVirtualKey(vk, MAPVK_VK_TO_CHAR)
+ parts.append(chr(scancode))
+ sep = "+"
+ if sep in parts:
+ sep = "-"
+ return sep.join([p.capitalize() for p in parts])
+
+
+def _psc(char):
+ sc, mods = get_vk(char)
+ print(f"Char {char!r} -> {sc} -> {key_code_to_name.get(sc)}")
+
+
+def test1():
+ for ch in """aA0/?[{}];:'"`~_-+=\\|,<.>/?""":
+ _psc(ch)
+ for code in ["Home", "End", "Left", "Right", "Up", "Down", "Menu", "Next"]:
+ _psc(code)
+
+
+def _pkn(n):
+ vk, flags = parse_key_name(n)
+ print(f"{n} -> {vk},{flags} -> {make_key_name(vk, flags)}")
+
+
+def test2():
+ _pkn("ctrl+alt-shift+x")
+ _pkn("ctrl-home")
+ _pkn("Shift-+")
+ _pkn("Shift--")
+ _pkn("Shift+-")
+ _pkn("Shift++")
+ _pkn("LShift-+")
+ _pkn("ctl+home")
+ _pkn("ctl+enter")
+ _pkn("alt+return")
+ _pkn("Alt+/")
+ _pkn("Alt+BadKeyName")
+ _pkn("A") # an ascii char - should be seen as 'a'
+ _pkn("a")
+ _pkn("Shift-A")
+ _pkn("Shift-a")
+ _pkn("a")
+ _pkn("(")
+ _pkn("Ctrl+(")
+ _pkn("Ctrl+Shift-8")
+ _pkn("Ctrl+*")
+ _pkn("{")
+ _pkn("!")
+ _pkn(".")
+
+
+if __name__ == "__main__":
+ test2()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/scintillacon.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/scintillacon.py
new file mode 100644
index 0000000000000000000000000000000000000000..b72b81152c2d0b9936f91eb4daed83453b0dc87d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/scintillacon.py
@@ -0,0 +1,3083 @@
+# Generated by h2py from Include\scintilla.h
+INVALID_POSITION = -1
+SCI_START = 2000
+SCI_OPTIONAL_START = 3000
+SCI_LEXER_START = 4000
+SCI_ADDTEXT = 2001
+SCI_ADDSTYLEDTEXT = 2002
+SCI_INSERTTEXT = 2003
+SCI_CHANGEINSERTION = 2672
+SCI_CLEARALL = 2004
+SCI_DELETERANGE = 2645
+SCI_CLEARDOCUMENTSTYLE = 2005
+SCI_GETLENGTH = 2006
+SCI_GETCHARAT = 2007
+SCI_GETCURRENTPOS = 2008
+SCI_GETANCHOR = 2009
+SCI_GETSTYLEAT = 2010
+SCI_REDO = 2011
+SCI_SETUNDOCOLLECTION = 2012
+SCI_SELECTALL = 2013
+SCI_SETSAVEPOINT = 2014
+SCI_GETSTYLEDTEXT = 2015
+SCI_CANREDO = 2016
+SCI_MARKERLINEFROMHANDLE = 2017
+SCI_MARKERDELETEHANDLE = 2018
+SCI_MARKERHANDLEFROMLINE = 2732
+SCI_MARKERNUMBERFROMLINE = 2733
+SCI_GETUNDOCOLLECTION = 2019
+SCWS_INVISIBLE = 0
+SCWS_VISIBLEALWAYS = 1
+SCWS_VISIBLEAFTERINDENT = 2
+SCWS_VISIBLEONLYININDENT = 3
+SCI_GETVIEWWS = 2020
+SCI_SETVIEWWS = 2021
+SCTD_LONGARROW = 0
+SCTD_STRIKEOUT = 1
+SCI_GETTABDRAWMODE = 2698
+SCI_SETTABDRAWMODE = 2699
+SCI_POSITIONFROMPOINT = 2022
+SCI_POSITIONFROMPOINTCLOSE = 2023
+SCI_GOTOLINE = 2024
+SCI_GOTOPOS = 2025
+SCI_SETANCHOR = 2026
+SCI_GETCURLINE = 2027
+SCI_GETENDSTYLED = 2028
+SC_EOL_CRLF = 0
+SC_EOL_CR = 1
+SC_EOL_LF = 2
+SCI_CONVERTEOLS = 2029
+SCI_GETEOLMODE = 2030
+SCI_SETEOLMODE = 2031
+SCI_STARTSTYLING = 2032
+SCI_SETSTYLING = 2033
+SCI_GETBUFFEREDDRAW = 2034
+SCI_SETBUFFEREDDRAW = 2035
+SCI_SETTABWIDTH = 2036
+SCI_GETTABWIDTH = 2121
+SCI_SETTABMINIMUMWIDTH = 2724
+SCI_GETTABMINIMUMWIDTH = 2725
+SCI_CLEARTABSTOPS = 2675
+SCI_ADDTABSTOP = 2676
+SCI_GETNEXTTABSTOP = 2677
+SC_CP_UTF8 = 65001
+SCI_SETCODEPAGE = 2037
+SC_IME_WINDOWED = 0
+SC_IME_INLINE = 1
+SCI_GETIMEINTERACTION = 2678
+SCI_SETIMEINTERACTION = 2679
+SC_ALPHA_TRANSPARENT = 0
+SC_ALPHA_OPAQUE = 255
+SC_ALPHA_NOALPHA = 256
+SC_CURSORNORMAL = -1
+SC_CURSORARROW = 2
+SC_CURSORWAIT = 4
+SC_CURSORREVERSEARROW = 7
+MARKER_MAX = 31
+SC_MARK_CIRCLE = 0
+SC_MARK_ROUNDRECT = 1
+SC_MARK_ARROW = 2
+SC_MARK_SMALLRECT = 3
+SC_MARK_SHORTARROW = 4
+SC_MARK_EMPTY = 5
+SC_MARK_ARROWDOWN = 6
+SC_MARK_MINUS = 7
+SC_MARK_PLUS = 8
+SC_MARK_VLINE = 9
+SC_MARK_LCORNER = 10
+SC_MARK_TCORNER = 11
+SC_MARK_BOXPLUS = 12
+SC_MARK_BOXPLUSCONNECTED = 13
+SC_MARK_BOXMINUS = 14
+SC_MARK_BOXMINUSCONNECTED = 15
+SC_MARK_LCORNERCURVE = 16
+SC_MARK_TCORNERCURVE = 17
+SC_MARK_CIRCLEPLUS = 18
+SC_MARK_CIRCLEPLUSCONNECTED = 19
+SC_MARK_CIRCLEMINUS = 20
+SC_MARK_CIRCLEMINUSCONNECTED = 21
+SC_MARK_BACKGROUND = 22
+SC_MARK_DOTDOTDOT = 23
+SC_MARK_ARROWS = 24
+SC_MARK_PIXMAP = 25
+SC_MARK_FULLRECT = 26
+SC_MARK_LEFTRECT = 27
+SC_MARK_AVAILABLE = 28
+SC_MARK_UNDERLINE = 29
+SC_MARK_RGBAIMAGE = 30
+SC_MARK_BOOKMARK = 31
+SC_MARK_VERTICALBOOKMARK = 32
+SC_MARK_CHARACTER = 10000
+SC_MARKNUM_FOLDEREND = 25
+SC_MARKNUM_FOLDEROPENMID = 26
+SC_MARKNUM_FOLDERMIDTAIL = 27
+SC_MARKNUM_FOLDERTAIL = 28
+SC_MARKNUM_FOLDERSUB = 29
+SC_MARKNUM_FOLDER = 30
+SC_MARKNUM_FOLDEROPEN = 31
+SC_MASK_FOLDERS = 0xFE000000
+SCI_MARKERDEFINE = 2040
+SCI_MARKERSETFORE = 2041
+SCI_MARKERSETBACK = 2042
+SCI_MARKERSETBACKSELECTED = 2292
+SCI_MARKERENABLEHIGHLIGHT = 2293
+SCI_MARKERADD = 2043
+SCI_MARKERDELETE = 2044
+SCI_MARKERDELETEALL = 2045
+SCI_MARKERGET = 2046
+SCI_MARKERNEXT = 2047
+SCI_MARKERPREVIOUS = 2048
+SCI_MARKERDEFINEPIXMAP = 2049
+SCI_MARKERADDSET = 2466
+SCI_MARKERSETALPHA = 2476
+SC_MAX_MARGIN = 4
+SC_MARGIN_SYMBOL = 0
+SC_MARGIN_NUMBER = 1
+SC_MARGIN_BACK = 2
+SC_MARGIN_FORE = 3
+SC_MARGIN_TEXT = 4
+SC_MARGIN_RTEXT = 5
+SC_MARGIN_COLOUR = 6
+SCI_SETMARGINTYPEN = 2240
+SCI_GETMARGINTYPEN = 2241
+SCI_SETMARGINWIDTHN = 2242
+SCI_GETMARGINWIDTHN = 2243
+SCI_SETMARGINMASKN = 2244
+SCI_GETMARGINMASKN = 2245
+SCI_SETMARGINSENSITIVEN = 2246
+SCI_GETMARGINSENSITIVEN = 2247
+SCI_SETMARGINCURSORN = 2248
+SCI_GETMARGINCURSORN = 2249
+SCI_SETMARGINBACKN = 2250
+SCI_GETMARGINBACKN = 2251
+SCI_SETMARGINS = 2252
+SCI_GETMARGINS = 2253
+STYLE_DEFAULT = 32
+STYLE_LINENUMBER = 33
+STYLE_BRACELIGHT = 34
+STYLE_BRACEBAD = 35
+STYLE_CONTROLCHAR = 36
+STYLE_INDENTGUIDE = 37
+STYLE_CALLTIP = 38
+STYLE_FOLDDISPLAYTEXT = 39
+STYLE_LASTPREDEFINED = 39
+STYLE_MAX = 255
+SC_CHARSET_ANSI = 0
+SC_CHARSET_DEFAULT = 1
+SC_CHARSET_BALTIC = 186
+SC_CHARSET_CHINESEBIG5 = 136
+SC_CHARSET_EASTEUROPE = 238
+SC_CHARSET_GB2312 = 134
+SC_CHARSET_GREEK = 161
+SC_CHARSET_HANGUL = 129
+SC_CHARSET_MAC = 77
+SC_CHARSET_OEM = 255
+SC_CHARSET_RUSSIAN = 204
+SC_CHARSET_OEM866 = 866
+SC_CHARSET_CYRILLIC = 1251
+SC_CHARSET_SHIFTJIS = 128
+SC_CHARSET_SYMBOL = 2
+SC_CHARSET_TURKISH = 162
+SC_CHARSET_JOHAB = 130
+SC_CHARSET_HEBREW = 177
+SC_CHARSET_ARABIC = 178
+SC_CHARSET_VIETNAMESE = 163
+SC_CHARSET_THAI = 222
+SC_CHARSET_8859_15 = 1000
+SCI_STYLECLEARALL = 2050
+SCI_STYLESETFORE = 2051
+SCI_STYLESETBACK = 2052
+SCI_STYLESETBOLD = 2053
+SCI_STYLESETITALIC = 2054
+SCI_STYLESETSIZE = 2055
+SCI_STYLESETFONT = 2056
+SCI_STYLESETEOLFILLED = 2057
+SCI_STYLERESETDEFAULT = 2058
+SCI_STYLESETUNDERLINE = 2059
+SC_CASE_MIXED = 0
+SC_CASE_UPPER = 1
+SC_CASE_LOWER = 2
+SC_CASE_CAMEL = 3
+SCI_STYLEGETFORE = 2481
+SCI_STYLEGETBACK = 2482
+SCI_STYLEGETBOLD = 2483
+SCI_STYLEGETITALIC = 2484
+SCI_STYLEGETSIZE = 2485
+SCI_STYLEGETFONT = 2486
+SCI_STYLEGETEOLFILLED = 2487
+SCI_STYLEGETUNDERLINE = 2488
+SCI_STYLEGETCASE = 2489
+SCI_STYLEGETCHARACTERSET = 2490
+SCI_STYLEGETVISIBLE = 2491
+SCI_STYLEGETCHANGEABLE = 2492
+SCI_STYLEGETHOTSPOT = 2493
+SCI_STYLESETCASE = 2060
+SC_FONT_SIZE_MULTIPLIER = 100
+SCI_STYLESETSIZEFRACTIONAL = 2061
+SCI_STYLEGETSIZEFRACTIONAL = 2062
+SC_WEIGHT_NORMAL = 400
+SC_WEIGHT_SEMIBOLD = 600
+SC_WEIGHT_BOLD = 700
+SCI_STYLESETWEIGHT = 2063
+SCI_STYLEGETWEIGHT = 2064
+SCI_STYLESETCHARACTERSET = 2066
+SCI_STYLESETHOTSPOT = 2409
+SCI_SETSELFORE = 2067
+SCI_SETSELBACK = 2068
+SCI_GETSELALPHA = 2477
+SCI_SETSELALPHA = 2478
+SCI_GETSELEOLFILLED = 2479
+SCI_SETSELEOLFILLED = 2480
+SCI_SETCARETFORE = 2069
+SCI_ASSIGNCMDKEY = 2070
+SCI_CLEARCMDKEY = 2071
+SCI_CLEARALLCMDKEYS = 2072
+SCI_SETSTYLINGEX = 2073
+SCI_STYLESETVISIBLE = 2074
+SCI_GETCARETPERIOD = 2075
+SCI_SETCARETPERIOD = 2076
+SCI_SETWORDCHARS = 2077
+SCI_GETWORDCHARS = 2646
+SCI_SETCHARACTERCATEGORYOPTIMIZATION = 2720
+SCI_GETCHARACTERCATEGORYOPTIMIZATION = 2721
+SCI_BEGINUNDOACTION = 2078
+SCI_ENDUNDOACTION = 2079
+INDIC_PLAIN = 0
+INDIC_SQUIGGLE = 1
+INDIC_TT = 2
+INDIC_DIAGONAL = 3
+INDIC_STRIKE = 4
+INDIC_HIDDEN = 5
+INDIC_BOX = 6
+INDIC_ROUNDBOX = 7
+INDIC_STRAIGHTBOX = 8
+INDIC_DASH = 9
+INDIC_DOTS = 10
+INDIC_SQUIGGLELOW = 11
+INDIC_DOTBOX = 12
+INDIC_SQUIGGLEPIXMAP = 13
+INDIC_COMPOSITIONTHICK = 14
+INDIC_COMPOSITIONTHIN = 15
+INDIC_FULLBOX = 16
+INDIC_TEXTFORE = 17
+INDIC_POINT = 18
+INDIC_POINTCHARACTER = 19
+INDIC_GRADIENT = 20
+INDIC_GRADIENTCENTRE = 21
+INDIC_CONTAINER = 8
+INDIC_IME = 32
+INDIC_IME_MAX = 35
+INDIC_MAX = 35
+INDICATOR_CONTAINER = 8
+INDICATOR_IME = 32
+INDICATOR_IME_MAX = 35
+INDICATOR_MAX = 35
+SCI_INDICSETSTYLE = 2080
+SCI_INDICGETSTYLE = 2081
+SCI_INDICSETFORE = 2082
+SCI_INDICGETFORE = 2083
+SCI_INDICSETUNDER = 2510
+SCI_INDICGETUNDER = 2511
+SCI_INDICSETHOVERSTYLE = 2680
+SCI_INDICGETHOVERSTYLE = 2681
+SCI_INDICSETHOVERFORE = 2682
+SCI_INDICGETHOVERFORE = 2683
+SC_INDICVALUEBIT = 0x1000000
+SC_INDICVALUEMASK = 0xFFFFFF
+SC_INDICFLAG_VALUEFORE = 1
+SCI_INDICSETFLAGS = 2684
+SCI_INDICGETFLAGS = 2685
+SCI_SETWHITESPACEFORE = 2084
+SCI_SETWHITESPACEBACK = 2085
+SCI_SETWHITESPACESIZE = 2086
+SCI_GETWHITESPACESIZE = 2087
+SCI_SETLINESTATE = 2092
+SCI_GETLINESTATE = 2093
+SCI_GETMAXLINESTATE = 2094
+SCI_GETCARETLINEVISIBLE = 2095
+SCI_SETCARETLINEVISIBLE = 2096
+SCI_GETCARETLINEBACK = 2097
+SCI_SETCARETLINEBACK = 2098
+SCI_GETCARETLINEFRAME = 2704
+SCI_SETCARETLINEFRAME = 2705
+SCI_STYLESETCHANGEABLE = 2099
+SCI_AUTOCSHOW = 2100
+SCI_AUTOCCANCEL = 2101
+SCI_AUTOCACTIVE = 2102
+SCI_AUTOCPOSSTART = 2103
+SCI_AUTOCCOMPLETE = 2104
+SCI_AUTOCSTOPS = 2105
+SCI_AUTOCSETSEPARATOR = 2106
+SCI_AUTOCGETSEPARATOR = 2107
+SCI_AUTOCSELECT = 2108
+SCI_AUTOCSETCANCELATSTART = 2110
+SCI_AUTOCGETCANCELATSTART = 2111
+SCI_AUTOCSETFILLUPS = 2112
+SCI_AUTOCSETCHOOSESINGLE = 2113
+SCI_AUTOCGETCHOOSESINGLE = 2114
+SCI_AUTOCSETIGNORECASE = 2115
+SCI_AUTOCGETIGNORECASE = 2116
+SCI_USERLISTSHOW = 2117
+SCI_AUTOCSETAUTOHIDE = 2118
+SCI_AUTOCGETAUTOHIDE = 2119
+SCI_AUTOCSETDROPRESTOFWORD = 2270
+SCI_AUTOCGETDROPRESTOFWORD = 2271
+SCI_REGISTERIMAGE = 2405
+SCI_CLEARREGISTEREDIMAGES = 2408
+SCI_AUTOCGETTYPESEPARATOR = 2285
+SCI_AUTOCSETTYPESEPARATOR = 2286
+SCI_AUTOCSETMAXWIDTH = 2208
+SCI_AUTOCGETMAXWIDTH = 2209
+SCI_AUTOCSETMAXHEIGHT = 2210
+SCI_AUTOCGETMAXHEIGHT = 2211
+SCI_SETINDENT = 2122
+SCI_GETINDENT = 2123
+SCI_SETUSETABS = 2124
+SCI_GETUSETABS = 2125
+SCI_SETLINEINDENTATION = 2126
+SCI_GETLINEINDENTATION = 2127
+SCI_GETLINEINDENTPOSITION = 2128
+SCI_GETCOLUMN = 2129
+SCI_COUNTCHARACTERS = 2633
+SCI_COUNTCODEUNITS = 2715
+SCI_SETHSCROLLBAR = 2130
+SCI_GETHSCROLLBAR = 2131
+SC_IV_NONE = 0
+SC_IV_REAL = 1
+SC_IV_LOOKFORWARD = 2
+SC_IV_LOOKBOTH = 3
+SCI_SETINDENTATIONGUIDES = 2132
+SCI_GETINDENTATIONGUIDES = 2133
+SCI_SETHIGHLIGHTGUIDE = 2134
+SCI_GETHIGHLIGHTGUIDE = 2135
+SCI_GETLINEENDPOSITION = 2136
+SCI_GETCODEPAGE = 2137
+SCI_GETCARETFORE = 2138
+SCI_GETREADONLY = 2140
+SCI_SETCURRENTPOS = 2141
+SCI_SETSELECTIONSTART = 2142
+SCI_GETSELECTIONSTART = 2143
+SCI_SETSELECTIONEND = 2144
+SCI_GETSELECTIONEND = 2145
+SCI_SETEMPTYSELECTION = 2556
+SCI_SETPRINTMAGNIFICATION = 2146
+SCI_GETPRINTMAGNIFICATION = 2147
+SC_PRINT_NORMAL = 0
+SC_PRINT_INVERTLIGHT = 1
+SC_PRINT_BLACKONWHITE = 2
+SC_PRINT_COLOURONWHITE = 3
+SC_PRINT_COLOURONWHITEDEFAULTBG = 4
+SC_PRINT_SCREENCOLOURS = 5
+SCI_SETPRINTCOLOURMODE = 2148
+SCI_GETPRINTCOLOURMODE = 2149
+SCFIND_NONE = 0x0
+SCFIND_WHOLEWORD = 0x2
+SCFIND_MATCHCASE = 0x4
+SCFIND_WORDSTART = 0x00100000
+SCFIND_REGEXP = 0x00200000
+SCFIND_POSIX = 0x00400000
+SCFIND_CXX11REGEX = 0x00800000
+SCI_FINDTEXT = 2150
+SCI_FORMATRANGE = 2151
+SCI_GETFIRSTVISIBLELINE = 2152
+SCI_GETLINE = 2153
+SCI_GETLINECOUNT = 2154
+SCI_SETMARGINLEFT = 2155
+SCI_GETMARGINLEFT = 2156
+SCI_SETMARGINRIGHT = 2157
+SCI_GETMARGINRIGHT = 2158
+SCI_GETMODIFY = 2159
+SCI_SETSEL = 2160
+SCI_GETSELTEXT = 2161
+SCI_GETTEXTRANGE = 2162
+SCI_HIDESELECTION = 2163
+SCI_POINTXFROMPOSITION = 2164
+SCI_POINTYFROMPOSITION = 2165
+SCI_LINEFROMPOSITION = 2166
+SCI_POSITIONFROMLINE = 2167
+SCI_LINESCROLL = 2168
+SCI_SCROLLCARET = 2169
+SCI_SCROLLRANGE = 2569
+SCI_REPLACESEL = 2170
+SCI_SETREADONLY = 2171
+SCI_NULL = 2172
+SCI_CANPASTE = 2173
+SCI_CANUNDO = 2174
+SCI_EMPTYUNDOBUFFER = 2175
+SCI_UNDO = 2176
+SCI_CUT = 2177
+SCI_COPY = 2178
+SCI_PASTE = 2179
+SCI_CLEAR = 2180
+SCI_SETTEXT = 2181
+SCI_GETTEXT = 2182
+SCI_GETTEXTLENGTH = 2183
+SCI_GETDIRECTFUNCTION = 2184
+SCI_GETDIRECTPOINTER = 2185
+SCI_SETOVERTYPE = 2186
+SCI_GETOVERTYPE = 2187
+SCI_SETCARETWIDTH = 2188
+SCI_GETCARETWIDTH = 2189
+SCI_SETTARGETSTART = 2190
+SCI_GETTARGETSTART = 2191
+SCI_SETTARGETSTARTVIRTUALSPACE = 2728
+SCI_GETTARGETSTARTVIRTUALSPACE = 2729
+SCI_SETTARGETEND = 2192
+SCI_GETTARGETEND = 2193
+SCI_SETTARGETENDVIRTUALSPACE = 2730
+SCI_GETTARGETENDVIRTUALSPACE = 2731
+SCI_SETTARGETRANGE = 2686
+SCI_GETTARGETTEXT = 2687
+SCI_TARGETFROMSELECTION = 2287
+SCI_TARGETWHOLEDOCUMENT = 2690
+SCI_REPLACETARGET = 2194
+SCI_REPLACETARGETRE = 2195
+SCI_SEARCHINTARGET = 2197
+SCI_SETSEARCHFLAGS = 2198
+SCI_GETSEARCHFLAGS = 2199
+SCI_CALLTIPSHOW = 2200
+SCI_CALLTIPCANCEL = 2201
+SCI_CALLTIPACTIVE = 2202
+SCI_CALLTIPPOSSTART = 2203
+SCI_CALLTIPSETPOSSTART = 2214
+SCI_CALLTIPSETHLT = 2204
+SCI_CALLTIPSETBACK = 2205
+SCI_CALLTIPSETFORE = 2206
+SCI_CALLTIPSETFOREHLT = 2207
+SCI_CALLTIPUSESTYLE = 2212
+SCI_CALLTIPSETPOSITION = 2213
+SCI_VISIBLEFROMDOCLINE = 2220
+SCI_DOCLINEFROMVISIBLE = 2221
+SCI_WRAPCOUNT = 2235
+SC_FOLDLEVELBASE = 0x400
+SC_FOLDLEVELWHITEFLAG = 0x1000
+SC_FOLDLEVELHEADERFLAG = 0x2000
+SC_FOLDLEVELNUMBERMASK = 0x0FFF
+SCI_SETFOLDLEVEL = 2222
+SCI_GETFOLDLEVEL = 2223
+SCI_GETLASTCHILD = 2224
+SCI_GETFOLDPARENT = 2225
+SCI_SHOWLINES = 2226
+SCI_HIDELINES = 2227
+SCI_GETLINEVISIBLE = 2228
+SCI_GETALLLINESVISIBLE = 2236
+SCI_SETFOLDEXPANDED = 2229
+SCI_GETFOLDEXPANDED = 2230
+SCI_TOGGLEFOLD = 2231
+SCI_TOGGLEFOLDSHOWTEXT = 2700
+SC_FOLDDISPLAYTEXT_HIDDEN = 0
+SC_FOLDDISPLAYTEXT_STANDARD = 1
+SC_FOLDDISPLAYTEXT_BOXED = 2
+SCI_FOLDDISPLAYTEXTSETSTYLE = 2701
+SCI_FOLDDISPLAYTEXTGETSTYLE = 2707
+SCI_SETDEFAULTFOLDDISPLAYTEXT = 2722
+SCI_GETDEFAULTFOLDDISPLAYTEXT = 2723
+SC_FOLDACTION_CONTRACT = 0
+SC_FOLDACTION_EXPAND = 1
+SC_FOLDACTION_TOGGLE = 2
+SCI_FOLDLINE = 2237
+SCI_FOLDCHILDREN = 2238
+SCI_EXPANDCHILDREN = 2239
+SCI_FOLDALL = 2662
+SCI_ENSUREVISIBLE = 2232
+SC_AUTOMATICFOLD_SHOW = 0x0001
+SC_AUTOMATICFOLD_CLICK = 0x0002
+SC_AUTOMATICFOLD_CHANGE = 0x0004
+SCI_SETAUTOMATICFOLD = 2663
+SCI_GETAUTOMATICFOLD = 2664
+SC_FOLDFLAG_LINEBEFORE_EXPANDED = 0x0002
+SC_FOLDFLAG_LINEBEFORE_CONTRACTED = 0x0004
+SC_FOLDFLAG_LINEAFTER_EXPANDED = 0x0008
+SC_FOLDFLAG_LINEAFTER_CONTRACTED = 0x0010
+SC_FOLDFLAG_LEVELNUMBERS = 0x0040
+SC_FOLDFLAG_LINESTATE = 0x0080
+SCI_SETFOLDFLAGS = 2233
+SCI_ENSUREVISIBLEENFORCEPOLICY = 2234
+SCI_SETTABINDENTS = 2260
+SCI_GETTABINDENTS = 2261
+SCI_SETBACKSPACEUNINDENTS = 2262
+SCI_GETBACKSPACEUNINDENTS = 2263
+SC_TIME_FOREVER = 10000000
+SCI_SETMOUSEDWELLTIME = 2264
+SCI_GETMOUSEDWELLTIME = 2265
+SCI_WORDSTARTPOSITION = 2266
+SCI_WORDENDPOSITION = 2267
+SCI_ISRANGEWORD = 2691
+SC_IDLESTYLING_NONE = 0
+SC_IDLESTYLING_TOVISIBLE = 1
+SC_IDLESTYLING_AFTERVISIBLE = 2
+SC_IDLESTYLING_ALL = 3
+SCI_SETIDLESTYLING = 2692
+SCI_GETIDLESTYLING = 2693
+SC_WRAP_NONE = 0
+SC_WRAP_WORD = 1
+SC_WRAP_CHAR = 2
+SC_WRAP_WHITESPACE = 3
+SCI_SETWRAPMODE = 2268
+SCI_GETWRAPMODE = 2269
+SC_WRAPVISUALFLAG_NONE = 0x0000
+SC_WRAPVISUALFLAG_END = 0x0001
+SC_WRAPVISUALFLAG_START = 0x0002
+SC_WRAPVISUALFLAG_MARGIN = 0x0004
+SCI_SETWRAPVISUALFLAGS = 2460
+SCI_GETWRAPVISUALFLAGS = 2461
+SC_WRAPVISUALFLAGLOC_DEFAULT = 0x0000
+SC_WRAPVISUALFLAGLOC_END_BY_TEXT = 0x0001
+SC_WRAPVISUALFLAGLOC_START_BY_TEXT = 0x0002
+SCI_SETWRAPVISUALFLAGSLOCATION = 2462
+SCI_GETWRAPVISUALFLAGSLOCATION = 2463
+SCI_SETWRAPSTARTINDENT = 2464
+SCI_GETWRAPSTARTINDENT = 2465
+SC_WRAPINDENT_FIXED = 0
+SC_WRAPINDENT_SAME = 1
+SC_WRAPINDENT_INDENT = 2
+SC_WRAPINDENT_DEEPINDENT = 3
+SCI_SETWRAPINDENTMODE = 2472
+SCI_GETWRAPINDENTMODE = 2473
+SC_CACHE_NONE = 0
+SC_CACHE_CARET = 1
+SC_CACHE_PAGE = 2
+SC_CACHE_DOCUMENT = 3
+SCI_SETLAYOUTCACHE = 2272
+SCI_GETLAYOUTCACHE = 2273
+SCI_SETSCROLLWIDTH = 2274
+SCI_GETSCROLLWIDTH = 2275
+SCI_SETSCROLLWIDTHTRACKING = 2516
+SCI_GETSCROLLWIDTHTRACKING = 2517
+SCI_TEXTWIDTH = 2276
+SCI_SETENDATLASTLINE = 2277
+SCI_GETENDATLASTLINE = 2278
+SCI_TEXTHEIGHT = 2279
+SCI_SETVSCROLLBAR = 2280
+SCI_GETVSCROLLBAR = 2281
+SCI_APPENDTEXT = 2282
+SC_PHASES_ONE = 0
+SC_PHASES_TWO = 1
+SC_PHASES_MULTIPLE = 2
+SCI_GETPHASESDRAW = 2673
+SCI_SETPHASESDRAW = 2674
+SC_EFF_QUALITY_MASK = 0xF
+SC_EFF_QUALITY_DEFAULT = 0
+SC_EFF_QUALITY_NON_ANTIALIASED = 1
+SC_EFF_QUALITY_ANTIALIASED = 2
+SC_EFF_QUALITY_LCD_OPTIMIZED = 3
+SCI_SETFONTQUALITY = 2611
+SCI_GETFONTQUALITY = 2612
+SCI_SETFIRSTVISIBLELINE = 2613
+SC_MULTIPASTE_ONCE = 0
+SC_MULTIPASTE_EACH = 1
+SCI_SETMULTIPASTE = 2614
+SCI_GETMULTIPASTE = 2615
+SCI_GETTAG = 2616
+SCI_LINESJOIN = 2288
+SCI_LINESSPLIT = 2289
+SCI_SETFOLDMARGINCOLOUR = 2290
+SCI_SETFOLDMARGINHICOLOUR = 2291
+SC_ACCESSIBILITY_DISABLED = 0
+SC_ACCESSIBILITY_ENABLED = 1
+SCI_SETACCESSIBILITY = 2702
+SCI_GETACCESSIBILITY = 2703
+SCI_LINEDOWN = 2300
+SCI_LINEDOWNEXTEND = 2301
+SCI_LINEUP = 2302
+SCI_LINEUPEXTEND = 2303
+SCI_CHARLEFT = 2304
+SCI_CHARLEFTEXTEND = 2305
+SCI_CHARRIGHT = 2306
+SCI_CHARRIGHTEXTEND = 2307
+SCI_WORDLEFT = 2308
+SCI_WORDLEFTEXTEND = 2309
+SCI_WORDRIGHT = 2310
+SCI_WORDRIGHTEXTEND = 2311
+SCI_HOME = 2312
+SCI_HOMEEXTEND = 2313
+SCI_LINEEND = 2314
+SCI_LINEENDEXTEND = 2315
+SCI_DOCUMENTSTART = 2316
+SCI_DOCUMENTSTARTEXTEND = 2317
+SCI_DOCUMENTEND = 2318
+SCI_DOCUMENTENDEXTEND = 2319
+SCI_PAGEUP = 2320
+SCI_PAGEUPEXTEND = 2321
+SCI_PAGEDOWN = 2322
+SCI_PAGEDOWNEXTEND = 2323
+SCI_EDITTOGGLEOVERTYPE = 2324
+SCI_CANCEL = 2325
+SCI_DELETEBACK = 2326
+SCI_TAB = 2327
+SCI_BACKTAB = 2328
+SCI_NEWLINE = 2329
+SCI_FORMFEED = 2330
+SCI_VCHOME = 2331
+SCI_VCHOMEEXTEND = 2332
+SCI_ZOOMIN = 2333
+SCI_ZOOMOUT = 2334
+SCI_DELWORDLEFT = 2335
+SCI_DELWORDRIGHT = 2336
+SCI_DELWORDRIGHTEND = 2518
+SCI_LINECUT = 2337
+SCI_LINEDELETE = 2338
+SCI_LINETRANSPOSE = 2339
+SCI_LINEREVERSE = 2354
+SCI_LINEDUPLICATE = 2404
+SCI_LOWERCASE = 2340
+SCI_UPPERCASE = 2341
+SCI_LINESCROLLDOWN = 2342
+SCI_LINESCROLLUP = 2343
+SCI_DELETEBACKNOTLINE = 2344
+SCI_HOMEDISPLAY = 2345
+SCI_HOMEDISPLAYEXTEND = 2346
+SCI_LINEENDDISPLAY = 2347
+SCI_LINEENDDISPLAYEXTEND = 2348
+SCI_HOMEWRAP = 2349
+SCI_HOMEWRAPEXTEND = 2450
+SCI_LINEENDWRAP = 2451
+SCI_LINEENDWRAPEXTEND = 2452
+SCI_VCHOMEWRAP = 2453
+SCI_VCHOMEWRAPEXTEND = 2454
+SCI_LINECOPY = 2455
+SCI_MOVECARETINSIDEVIEW = 2401
+SCI_LINELENGTH = 2350
+SCI_BRACEHIGHLIGHT = 2351
+SCI_BRACEHIGHLIGHTINDICATOR = 2498
+SCI_BRACEBADLIGHT = 2352
+SCI_BRACEBADLIGHTINDICATOR = 2499
+SCI_BRACEMATCH = 2353
+SCI_BRACEMATCHNEXT = 2369
+SCI_GETVIEWEOL = 2355
+SCI_SETVIEWEOL = 2356
+SCI_GETDOCPOINTER = 2357
+SCI_SETDOCPOINTER = 2358
+SCI_SETMODEVENTMASK = 2359
+EDGE_NONE = 0
+EDGE_LINE = 1
+EDGE_BACKGROUND = 2
+EDGE_MULTILINE = 3
+SCI_GETEDGECOLUMN = 2360
+SCI_SETEDGECOLUMN = 2361
+SCI_GETEDGEMODE = 2362
+SCI_SETEDGEMODE = 2363
+SCI_GETEDGECOLOUR = 2364
+SCI_SETEDGECOLOUR = 2365
+SCI_MULTIEDGEADDLINE = 2694
+SCI_MULTIEDGECLEARALL = 2695
+SCI_GETMULTIEDGECOLUMN = 2749
+SCI_SEARCHANCHOR = 2366
+SCI_SEARCHNEXT = 2367
+SCI_SEARCHPREV = 2368
+SCI_LINESONSCREEN = 2370
+SC_POPUP_NEVER = 0
+SC_POPUP_ALL = 1
+SC_POPUP_TEXT = 2
+SCI_USEPOPUP = 2371
+SCI_SELECTIONISRECTANGLE = 2372
+SCI_SETZOOM = 2373
+SCI_GETZOOM = 2374
+SC_DOCUMENTOPTION_DEFAULT = 0
+SC_DOCUMENTOPTION_STYLES_NONE = 0x1
+SC_DOCUMENTOPTION_TEXT_LARGE = 0x100
+SCI_CREATEDOCUMENT = 2375
+SCI_ADDREFDOCUMENT = 2376
+SCI_RELEASEDOCUMENT = 2377
+SCI_GETDOCUMENTOPTIONS = 2379
+SCI_GETMODEVENTMASK = 2378
+SCI_SETCOMMANDEVENTS = 2717
+SCI_GETCOMMANDEVENTS = 2718
+SCI_SETFOCUS = 2380
+SCI_GETFOCUS = 2381
+SC_STATUS_OK = 0
+SC_STATUS_FAILURE = 1
+SC_STATUS_BADALLOC = 2
+SC_STATUS_WARN_START = 1000
+SC_STATUS_WARN_REGEX = 1001
+SCI_SETSTATUS = 2382
+SCI_GETSTATUS = 2383
+SCI_SETMOUSEDOWNCAPTURES = 2384
+SCI_GETMOUSEDOWNCAPTURES = 2385
+SCI_SETMOUSEWHEELCAPTURES = 2696
+SCI_GETMOUSEWHEELCAPTURES = 2697
+SCI_SETCURSOR = 2386
+SCI_GETCURSOR = 2387
+SCI_SETCONTROLCHARSYMBOL = 2388
+SCI_GETCONTROLCHARSYMBOL = 2389
+SCI_WORDPARTLEFT = 2390
+SCI_WORDPARTLEFTEXTEND = 2391
+SCI_WORDPARTRIGHT = 2392
+SCI_WORDPARTRIGHTEXTEND = 2393
+VISIBLE_SLOP = 0x01
+VISIBLE_STRICT = 0x04
+SCI_SETVISIBLEPOLICY = 2394
+SCI_DELLINELEFT = 2395
+SCI_DELLINERIGHT = 2396
+SCI_SETXOFFSET = 2397
+SCI_GETXOFFSET = 2398
+SCI_CHOOSECARETX = 2399
+SCI_GRABFOCUS = 2400
+CARET_SLOP = 0x01
+CARET_STRICT = 0x04
+CARET_JUMPS = 0x10
+CARET_EVEN = 0x08
+SCI_SETXCARETPOLICY = 2402
+SCI_SETYCARETPOLICY = 2403
+SCI_SETPRINTWRAPMODE = 2406
+SCI_GETPRINTWRAPMODE = 2407
+SCI_SETHOTSPOTACTIVEFORE = 2410
+SCI_GETHOTSPOTACTIVEFORE = 2494
+SCI_SETHOTSPOTACTIVEBACK = 2411
+SCI_GETHOTSPOTACTIVEBACK = 2495
+SCI_SETHOTSPOTACTIVEUNDERLINE = 2412
+SCI_GETHOTSPOTACTIVEUNDERLINE = 2496
+SCI_SETHOTSPOTSINGLELINE = 2421
+SCI_GETHOTSPOTSINGLELINE = 2497
+SCI_PARADOWN = 2413
+SCI_PARADOWNEXTEND = 2414
+SCI_PARAUP = 2415
+SCI_PARAUPEXTEND = 2416
+SCI_POSITIONBEFORE = 2417
+SCI_POSITIONAFTER = 2418
+SCI_POSITIONRELATIVE = 2670
+SCI_POSITIONRELATIVECODEUNITS = 2716
+SCI_COPYRANGE = 2419
+SCI_COPYTEXT = 2420
+SC_SEL_STREAM = 0
+SC_SEL_RECTANGLE = 1
+SC_SEL_LINES = 2
+SC_SEL_THIN = 3
+SCI_SETSELECTIONMODE = 2422
+SCI_GETSELECTIONMODE = 2423
+SCI_GETMOVEEXTENDSSELECTION = 2706
+SCI_GETLINESELSTARTPOSITION = 2424
+SCI_GETLINESELENDPOSITION = 2425
+SCI_LINEDOWNRECTEXTEND = 2426
+SCI_LINEUPRECTEXTEND = 2427
+SCI_CHARLEFTRECTEXTEND = 2428
+SCI_CHARRIGHTRECTEXTEND = 2429
+SCI_HOMERECTEXTEND = 2430
+SCI_VCHOMERECTEXTEND = 2431
+SCI_LINEENDRECTEXTEND = 2432
+SCI_PAGEUPRECTEXTEND = 2433
+SCI_PAGEDOWNRECTEXTEND = 2434
+SCI_STUTTEREDPAGEUP = 2435
+SCI_STUTTEREDPAGEUPEXTEND = 2436
+SCI_STUTTEREDPAGEDOWN = 2437
+SCI_STUTTEREDPAGEDOWNEXTEND = 2438
+SCI_WORDLEFTEND = 2439
+SCI_WORDLEFTENDEXTEND = 2440
+SCI_WORDRIGHTEND = 2441
+SCI_WORDRIGHTENDEXTEND = 2442
+SCI_SETWHITESPACECHARS = 2443
+SCI_GETWHITESPACECHARS = 2647
+SCI_SETPUNCTUATIONCHARS = 2648
+SCI_GETPUNCTUATIONCHARS = 2649
+SCI_SETCHARSDEFAULT = 2444
+SCI_AUTOCGETCURRENT = 2445
+SCI_AUTOCGETCURRENTTEXT = 2610
+SC_CASEINSENSITIVEBEHAVIOUR_RESPECTCASE = 0
+SC_CASEINSENSITIVEBEHAVIOUR_IGNORECASE = 1
+SCI_AUTOCSETCASEINSENSITIVEBEHAVIOUR = 2634
+SCI_AUTOCGETCASEINSENSITIVEBEHAVIOUR = 2635
+SC_MULTIAUTOC_ONCE = 0
+SC_MULTIAUTOC_EACH = 1
+SCI_AUTOCSETMULTI = 2636
+SCI_AUTOCGETMULTI = 2637
+SC_ORDER_PRESORTED = 0
+SC_ORDER_PERFORMSORT = 1
+SC_ORDER_CUSTOM = 2
+SCI_AUTOCSETORDER = 2660
+SCI_AUTOCGETORDER = 2661
+SCI_ALLOCATE = 2446
+SCI_TARGETASUTF8 = 2447
+SCI_SETLENGTHFORENCODE = 2448
+SCI_ENCODEDFROMUTF8 = 2449
+SCI_FINDCOLUMN = 2456
+SC_CARETSTICKY_OFF = 0
+SC_CARETSTICKY_ON = 1
+SC_CARETSTICKY_WHITESPACE = 2
+SCI_GETCARETSTICKY = 2457
+SCI_SETCARETSTICKY = 2458
+SCI_TOGGLECARETSTICKY = 2459
+SCI_SETPASTECONVERTENDINGS = 2467
+SCI_GETPASTECONVERTENDINGS = 2468
+SCI_SELECTIONDUPLICATE = 2469
+SCI_SETCARETLINEBACKALPHA = 2470
+SCI_GETCARETLINEBACKALPHA = 2471
+CARETSTYLE_INVISIBLE = 0
+CARETSTYLE_LINE = 1
+CARETSTYLE_BLOCK = 2
+CARETSTYLE_OVERSTRIKE_BAR = 0
+CARETSTYLE_OVERSTRIKE_BLOCK = 0x10
+CARETSTYLE_INS_MASK = 0xF
+CARETSTYLE_BLOCK_AFTER = 0x100
+SCI_SETCARETSTYLE = 2512
+SCI_GETCARETSTYLE = 2513
+SCI_SETINDICATORCURRENT = 2500
+SCI_GETINDICATORCURRENT = 2501
+SCI_SETINDICATORVALUE = 2502
+SCI_GETINDICATORVALUE = 2503
+SCI_INDICATORFILLRANGE = 2504
+SCI_INDICATORCLEARRANGE = 2505
+SCI_INDICATORALLONFOR = 2506
+SCI_INDICATORVALUEAT = 2507
+SCI_INDICATORSTART = 2508
+SCI_INDICATOREND = 2509
+SCI_SETPOSITIONCACHE = 2514
+SCI_GETPOSITIONCACHE = 2515
+SCI_COPYALLOWLINE = 2519
+SCI_GETCHARACTERPOINTER = 2520
+SCI_GETRANGEPOINTER = 2643
+SCI_GETGAPPOSITION = 2644
+SCI_INDICSETALPHA = 2523
+SCI_INDICGETALPHA = 2524
+SCI_INDICSETOUTLINEALPHA = 2558
+SCI_INDICGETOUTLINEALPHA = 2559
+SCI_SETEXTRAASCENT = 2525
+SCI_GETEXTRAASCENT = 2526
+SCI_SETEXTRADESCENT = 2527
+SCI_GETEXTRADESCENT = 2528
+SCI_MARKERSYMBOLDEFINED = 2529
+SCI_MARGINSETTEXT = 2530
+SCI_MARGINGETTEXT = 2531
+SCI_MARGINSETSTYLE = 2532
+SCI_MARGINGETSTYLE = 2533
+SCI_MARGINSETSTYLES = 2534
+SCI_MARGINGETSTYLES = 2535
+SCI_MARGINTEXTCLEARALL = 2536
+SCI_MARGINSETSTYLEOFFSET = 2537
+SCI_MARGINGETSTYLEOFFSET = 2538
+SC_MARGINOPTION_NONE = 0
+SC_MARGINOPTION_SUBLINESELECT = 1
+SCI_SETMARGINOPTIONS = 2539
+SCI_GETMARGINOPTIONS = 2557
+SCI_ANNOTATIONSETTEXT = 2540
+SCI_ANNOTATIONGETTEXT = 2541
+SCI_ANNOTATIONSETSTYLE = 2542
+SCI_ANNOTATIONGETSTYLE = 2543
+SCI_ANNOTATIONSETSTYLES = 2544
+SCI_ANNOTATIONGETSTYLES = 2545
+SCI_ANNOTATIONGETLINES = 2546
+SCI_ANNOTATIONCLEARALL = 2547
+ANNOTATION_HIDDEN = 0
+ANNOTATION_STANDARD = 1
+ANNOTATION_BOXED = 2
+ANNOTATION_INDENTED = 3
+SCI_ANNOTATIONSETVISIBLE = 2548
+SCI_ANNOTATIONGETVISIBLE = 2549
+SCI_ANNOTATIONSETSTYLEOFFSET = 2550
+SCI_ANNOTATIONGETSTYLEOFFSET = 2551
+SCI_RELEASEALLEXTENDEDSTYLES = 2552
+SCI_ALLOCATEEXTENDEDSTYLES = 2553
+UNDO_NONE = 0
+UNDO_MAY_COALESCE = 1
+SCI_ADDUNDOACTION = 2560
+SCI_CHARPOSITIONFROMPOINT = 2561
+SCI_CHARPOSITIONFROMPOINTCLOSE = 2562
+SCI_SETMOUSESELECTIONRECTANGULARSWITCH = 2668
+SCI_GETMOUSESELECTIONRECTANGULARSWITCH = 2669
+SCI_SETMULTIPLESELECTION = 2563
+SCI_GETMULTIPLESELECTION = 2564
+SCI_SETADDITIONALSELECTIONTYPING = 2565
+SCI_GETADDITIONALSELECTIONTYPING = 2566
+SCI_SETADDITIONALCARETSBLINK = 2567
+SCI_GETADDITIONALCARETSBLINK = 2568
+SCI_SETADDITIONALCARETSVISIBLE = 2608
+SCI_GETADDITIONALCARETSVISIBLE = 2609
+SCI_GETSELECTIONS = 2570
+SCI_GETSELECTIONEMPTY = 2650
+SCI_CLEARSELECTIONS = 2571
+SCI_SETSELECTION = 2572
+SCI_ADDSELECTION = 2573
+SCI_DROPSELECTIONN = 2671
+SCI_SETMAINSELECTION = 2574
+SCI_GETMAINSELECTION = 2575
+SCI_SETSELECTIONNCARET = 2576
+SCI_GETSELECTIONNCARET = 2577
+SCI_SETSELECTIONNANCHOR = 2578
+SCI_GETSELECTIONNANCHOR = 2579
+SCI_SETSELECTIONNCARETVIRTUALSPACE = 2580
+SCI_GETSELECTIONNCARETVIRTUALSPACE = 2581
+SCI_SETSELECTIONNANCHORVIRTUALSPACE = 2582
+SCI_GETSELECTIONNANCHORVIRTUALSPACE = 2583
+SCI_SETSELECTIONNSTART = 2584
+SCI_GETSELECTIONNSTART = 2585
+SCI_GETSELECTIONNSTARTVIRTUALSPACE = 2726
+SCI_SETSELECTIONNEND = 2586
+SCI_GETSELECTIONNENDVIRTUALSPACE = 2727
+SCI_GETSELECTIONNEND = 2587
+SCI_SETRECTANGULARSELECTIONCARET = 2588
+SCI_GETRECTANGULARSELECTIONCARET = 2589
+SCI_SETRECTANGULARSELECTIONANCHOR = 2590
+SCI_GETRECTANGULARSELECTIONANCHOR = 2591
+SCI_SETRECTANGULARSELECTIONCARETVIRTUALSPACE = 2592
+SCI_GETRECTANGULARSELECTIONCARETVIRTUALSPACE = 2593
+SCI_SETRECTANGULARSELECTIONANCHORVIRTUALSPACE = 2594
+SCI_GETRECTANGULARSELECTIONANCHORVIRTUALSPACE = 2595
+SCVS_NONE = 0
+SCVS_RECTANGULARSELECTION = 1
+SCVS_USERACCESSIBLE = 2
+SCVS_NOWRAPLINESTART = 4
+SCI_SETVIRTUALSPACEOPTIONS = 2596
+SCI_GETVIRTUALSPACEOPTIONS = 2597
+SCI_SETRECTANGULARSELECTIONMODIFIER = 2598
+SCI_GETRECTANGULARSELECTIONMODIFIER = 2599
+SCI_SETADDITIONALSELFORE = 2600
+SCI_SETADDITIONALSELBACK = 2601
+SCI_SETADDITIONALSELALPHA = 2602
+SCI_GETADDITIONALSELALPHA = 2603
+SCI_SETADDITIONALCARETFORE = 2604
+SCI_GETADDITIONALCARETFORE = 2605
+SCI_ROTATESELECTION = 2606
+SCI_SWAPMAINANCHORCARET = 2607
+SCI_MULTIPLESELECTADDNEXT = 2688
+SCI_MULTIPLESELECTADDEACH = 2689
+SCI_CHANGELEXERSTATE = 2617
+SCI_CONTRACTEDFOLDNEXT = 2618
+SCI_VERTICALCENTRECARET = 2619
+SCI_MOVESELECTEDLINESUP = 2620
+SCI_MOVESELECTEDLINESDOWN = 2621
+SCI_SETIDENTIFIER = 2622
+SCI_GETIDENTIFIER = 2623
+SCI_RGBAIMAGESETWIDTH = 2624
+SCI_RGBAIMAGESETHEIGHT = 2625
+SCI_RGBAIMAGESETSCALE = 2651
+SCI_MARKERDEFINERGBAIMAGE = 2626
+SCI_REGISTERRGBAIMAGE = 2627
+SCI_SCROLLTOSTART = 2628
+SCI_SCROLLTOEND = 2629
+SC_TECHNOLOGY_DEFAULT = 0
+SC_TECHNOLOGY_DIRECTWRITE = 1
+SC_TECHNOLOGY_DIRECTWRITERETAIN = 2
+SC_TECHNOLOGY_DIRECTWRITEDC = 3
+SCI_SETTECHNOLOGY = 2630
+SCI_GETTECHNOLOGY = 2631
+SCI_CREATELOADER = 2632
+SCI_FINDINDICATORSHOW = 2640
+SCI_FINDINDICATORFLASH = 2641
+SCI_FINDINDICATORHIDE = 2642
+SCI_VCHOMEDISPLAY = 2652
+SCI_VCHOMEDISPLAYEXTEND = 2653
+SCI_GETCARETLINEVISIBLEALWAYS = 2654
+SCI_SETCARETLINEVISIBLEALWAYS = 2655
+SC_LINE_END_TYPE_DEFAULT = 0
+SC_LINE_END_TYPE_UNICODE = 1
+SCI_SETLINEENDTYPESALLOWED = 2656
+SCI_GETLINEENDTYPESALLOWED = 2657
+SCI_GETLINEENDTYPESACTIVE = 2658
+SCI_SETREPRESENTATION = 2665
+SCI_GETREPRESENTATION = 2666
+SCI_CLEARREPRESENTATION = 2667
+SCI_EOLANNOTATIONSETTEXT = 2740
+SCI_EOLANNOTATIONGETTEXT = 2741
+SCI_EOLANNOTATIONSETSTYLE = 2742
+SCI_EOLANNOTATIONGETSTYLE = 2743
+SCI_EOLANNOTATIONCLEARALL = 2744
+EOLANNOTATION_HIDDEN = 0
+EOLANNOTATION_STANDARD = 1
+EOLANNOTATION_BOXED = 2
+SCI_EOLANNOTATIONSETVISIBLE = 2745
+SCI_EOLANNOTATIONGETVISIBLE = 2746
+SCI_EOLANNOTATIONSETSTYLEOFFSET = 2747
+SCI_EOLANNOTATIONGETSTYLEOFFSET = 2748
+SCI_STARTRECORD = 3001
+SCI_STOPRECORD = 3002
+SCI_SETLEXER = 4001
+SCI_GETLEXER = 4002
+SCI_COLOURISE = 4003
+SCI_SETPROPERTY = 4004
+KEYWORDSET_MAX = 8
+SCI_SETKEYWORDS = 4005
+SCI_SETLEXERLANGUAGE = 4006
+SCI_LOADLEXERLIBRARY = 4007
+SCI_GETPROPERTY = 4008
+SCI_GETPROPERTYEXPANDED = 4009
+SCI_GETPROPERTYINT = 4010
+SCI_GETLEXERLANGUAGE = 4012
+SCI_PRIVATELEXERCALL = 4013
+SCI_PROPERTYNAMES = 4014
+SC_TYPE_BOOLEAN = 0
+SC_TYPE_INTEGER = 1
+SC_TYPE_STRING = 2
+SCI_PROPERTYTYPE = 4015
+SCI_DESCRIBEPROPERTY = 4016
+SCI_DESCRIBEKEYWORDSETS = 4017
+SCI_GETLINEENDTYPESSUPPORTED = 4018
+SCI_ALLOCATESUBSTYLES = 4020
+SCI_GETSUBSTYLESSTART = 4021
+SCI_GETSUBSTYLESLENGTH = 4022
+SCI_GETSTYLEFROMSUBSTYLE = 4027
+SCI_GETPRIMARYSTYLEFROMSTYLE = 4028
+SCI_FREESUBSTYLES = 4023
+SCI_SETIDENTIFIERS = 4024
+SCI_DISTANCETOSECONDARYSTYLES = 4025
+SCI_GETSUBSTYLEBASES = 4026
+SCI_GETNAMEDSTYLES = 4029
+SCI_NAMEOFSTYLE = 4030
+SCI_TAGSOFSTYLE = 4031
+SCI_DESCRIPTIONOFSTYLE = 4032
+SCI_SETILEXER = 4033
+SC_MOD_NONE = 0x0
+SC_MOD_INSERTTEXT = 0x1
+SC_MOD_DELETETEXT = 0x2
+SC_MOD_CHANGESTYLE = 0x4
+SC_MOD_CHANGEFOLD = 0x8
+SC_PERFORMED_USER = 0x10
+SC_PERFORMED_UNDO = 0x20
+SC_PERFORMED_REDO = 0x40
+SC_MULTISTEPUNDOREDO = 0x80
+SC_LASTSTEPINUNDOREDO = 0x100
+SC_MOD_CHANGEMARKER = 0x200
+SC_MOD_BEFOREINSERT = 0x400
+SC_MOD_BEFOREDELETE = 0x800
+SC_MULTILINEUNDOREDO = 0x1000
+SC_STARTACTION = 0x2000
+SC_MOD_CHANGEINDICATOR = 0x4000
+SC_MOD_CHANGELINESTATE = 0x8000
+SC_MOD_CHANGEMARGIN = 0x10000
+SC_MOD_CHANGEANNOTATION = 0x20000
+SC_MOD_CONTAINER = 0x40000
+SC_MOD_LEXERSTATE = 0x80000
+SC_MOD_INSERTCHECK = 0x100000
+SC_MOD_CHANGETABSTOPS = 0x200000
+SC_MOD_CHANGEEOLANNOTATION = 0x400000
+SC_MODEVENTMASKALL = 0x7FFFFF
+SC_UPDATE_CONTENT = 0x1
+SC_UPDATE_SELECTION = 0x2
+SC_UPDATE_V_SCROLL = 0x4
+SC_UPDATE_H_SCROLL = 0x8
+SCEN_CHANGE = 768
+SCEN_SETFOCUS = 512
+SCEN_KILLFOCUS = 256
+SCK_DOWN = 300
+SCK_UP = 301
+SCK_LEFT = 302
+SCK_RIGHT = 303
+SCK_HOME = 304
+SCK_END = 305
+SCK_PRIOR = 306
+SCK_NEXT = 307
+SCK_DELETE = 308
+SCK_INSERT = 309
+SCK_ESCAPE = 7
+SCK_BACK = 8
+SCK_TAB = 9
+SCK_RETURN = 13
+SCK_ADD = 310
+SCK_SUBTRACT = 311
+SCK_DIVIDE = 312
+SCK_WIN = 313
+SCK_RWIN = 314
+SCK_MENU = 315
+SCMOD_NORM = 0
+SCMOD_SHIFT = 1
+SCMOD_CTRL = 2
+SCMOD_ALT = 4
+SCMOD_SUPER = 8
+SCMOD_META = 16
+SC_AC_FILLUP = 1
+SC_AC_DOUBLECLICK = 2
+SC_AC_TAB = 3
+SC_AC_NEWLINE = 4
+SC_AC_COMMAND = 5
+SC_CHARACTERSOURCE_DIRECT_INPUT = 0
+SC_CHARACTERSOURCE_TENTATIVE_INPUT = 1
+SC_CHARACTERSOURCE_IME_RESULT = 2
+SCN_STYLENEEDED = 2000
+SCN_CHARADDED = 2001
+SCN_SAVEPOINTREACHED = 2002
+SCN_SAVEPOINTLEFT = 2003
+SCN_MODIFYATTEMPTRO = 2004
+SCN_KEY = 2005
+SCN_DOUBLECLICK = 2006
+SCN_UPDATEUI = 2007
+SCN_MODIFIED = 2008
+SCN_MACRORECORD = 2009
+SCN_MARGINCLICK = 2010
+SCN_NEEDSHOWN = 2011
+SCN_PAINTED = 2013
+SCN_USERLISTSELECTION = 2014
+SCN_URIDROPPED = 2015
+SCN_DWELLSTART = 2016
+SCN_DWELLEND = 2017
+SCN_ZOOM = 2018
+SCN_HOTSPOTCLICK = 2019
+SCN_HOTSPOTDOUBLECLICK = 2020
+SCN_CALLTIPCLICK = 2021
+SCN_AUTOCSELECTION = 2022
+SCN_INDICATORCLICK = 2023
+SCN_INDICATORRELEASE = 2024
+SCN_AUTOCCANCELLED = 2025
+SCN_AUTOCCHARDELETED = 2026
+SCN_HOTSPOTRELEASECLICK = 2027
+SCN_FOCUSIN = 2028
+SCN_FOCUSOUT = 2029
+SCN_AUTOCCOMPLETED = 2030
+SCN_MARGINRIGHTCLICK = 2031
+SCN_AUTOCSELECTIONCHANGE = 2032
+SC_BIDIRECTIONAL_DISABLED = 0
+SC_BIDIRECTIONAL_L2R = 1
+SC_BIDIRECTIONAL_R2L = 2
+SCI_GETBIDIRECTIONAL = 2708
+SCI_SETBIDIRECTIONAL = 2709
+SC_LINECHARACTERINDEX_NONE = 0
+SC_LINECHARACTERINDEX_UTF32 = 1
+SC_LINECHARACTERINDEX_UTF16 = 2
+SCI_GETLINECHARACTERINDEX = 2710
+SCI_ALLOCATELINECHARACTERINDEX = 2711
+SCI_RELEASELINECHARACTERINDEX = 2712
+SCI_LINEFROMINDEXPOSITION = 2713
+SCI_INDEXPOSITIONFROMLINE = 2714
+SCI_SETKEYSUNICODE = 2521
+SCI_GETKEYSUNICODE = 2522
+SCI_GETTWOPHASEDRAW = 2283
+SCI_SETTWOPHASEDRAW = 2284
+SCI_SETSTYLEBITS = 2090
+SCI_GETSTYLEBITS = 2091
+SCI_GETSTYLEBITSNEEDED = 4011
+INDIC0_MASK = 0x20
+INDIC1_MASK = 0x40
+INDIC2_MASK = 0x80
+INDICS_MASK = 0xE0
+# Generated by h2py from Include\scilexer.h
+SCLEX_CONTAINER = 0
+SCLEX_NULL = 1
+SCLEX_PYTHON = 2
+SCLEX_CPP = 3
+SCLEX_HTML = 4
+SCLEX_XML = 5
+SCLEX_PERL = 6
+SCLEX_SQL = 7
+SCLEX_VB = 8
+SCLEX_PROPERTIES = 9
+SCLEX_ERRORLIST = 10
+SCLEX_MAKEFILE = 11
+SCLEX_BATCH = 12
+SCLEX_XCODE = 13
+SCLEX_LATEX = 14
+SCLEX_LUA = 15
+SCLEX_DIFF = 16
+SCLEX_CONF = 17
+SCLEX_PASCAL = 18
+SCLEX_AVE = 19
+SCLEX_ADA = 20
+SCLEX_LISP = 21
+SCLEX_RUBY = 22
+SCLEX_EIFFEL = 23
+SCLEX_EIFFELKW = 24
+SCLEX_TCL = 25
+SCLEX_NNCRONTAB = 26
+SCLEX_BULLANT = 27
+SCLEX_VBSCRIPT = 28
+SCLEX_BAAN = 31
+SCLEX_MATLAB = 32
+SCLEX_SCRIPTOL = 33
+SCLEX_ASM = 34
+SCLEX_CPPNOCASE = 35
+SCLEX_FORTRAN = 36
+SCLEX_F77 = 37
+SCLEX_CSS = 38
+SCLEX_POV = 39
+SCLEX_LOUT = 40
+SCLEX_ESCRIPT = 41
+SCLEX_PS = 42
+SCLEX_NSIS = 43
+SCLEX_MMIXAL = 44
+SCLEX_CLW = 45
+SCLEX_CLWNOCASE = 46
+SCLEX_LOT = 47
+SCLEX_YAML = 48
+SCLEX_TEX = 49
+SCLEX_METAPOST = 50
+SCLEX_POWERBASIC = 51
+SCLEX_FORTH = 52
+SCLEX_ERLANG = 53
+SCLEX_OCTAVE = 54
+SCLEX_MSSQL = 55
+SCLEX_VERILOG = 56
+SCLEX_KIX = 57
+SCLEX_GUI4CLI = 58
+SCLEX_SPECMAN = 59
+SCLEX_AU3 = 60
+SCLEX_APDL = 61
+SCLEX_BASH = 62
+SCLEX_ASN1 = 63
+SCLEX_VHDL = 64
+SCLEX_CAML = 65
+SCLEX_BLITZBASIC = 66
+SCLEX_PUREBASIC = 67
+SCLEX_HASKELL = 68
+SCLEX_PHPSCRIPT = 69
+SCLEX_TADS3 = 70
+SCLEX_REBOL = 71
+SCLEX_SMALLTALK = 72
+SCLEX_FLAGSHIP = 73
+SCLEX_CSOUND = 74
+SCLEX_FREEBASIC = 75
+SCLEX_INNOSETUP = 76
+SCLEX_OPAL = 77
+SCLEX_SPICE = 78
+SCLEX_D = 79
+SCLEX_CMAKE = 80
+SCLEX_GAP = 81
+SCLEX_PLM = 82
+SCLEX_PROGRESS = 83
+SCLEX_ABAQUS = 84
+SCLEX_ASYMPTOTE = 85
+SCLEX_R = 86
+SCLEX_MAGIK = 87
+SCLEX_POWERSHELL = 88
+SCLEX_MYSQL = 89
+SCLEX_PO = 90
+SCLEX_TAL = 91
+SCLEX_COBOL = 92
+SCLEX_TACL = 93
+SCLEX_SORCUS = 94
+SCLEX_POWERPRO = 95
+SCLEX_NIMROD = 96
+SCLEX_SML = 97
+SCLEX_MARKDOWN = 98
+SCLEX_TXT2TAGS = 99
+SCLEX_A68K = 100
+SCLEX_MODULA = 101
+SCLEX_COFFEESCRIPT = 102
+SCLEX_TCMD = 103
+SCLEX_AVS = 104
+SCLEX_ECL = 105
+SCLEX_OSCRIPT = 106
+SCLEX_VISUALPROLOG = 107
+SCLEX_LITERATEHASKELL = 108
+SCLEX_STTXT = 109
+SCLEX_KVIRC = 110
+SCLEX_RUST = 111
+SCLEX_DMAP = 112
+SCLEX_AS = 113
+SCLEX_DMIS = 114
+SCLEX_REGISTRY = 115
+SCLEX_BIBTEX = 116
+SCLEX_SREC = 117
+SCLEX_IHEX = 118
+SCLEX_TEHEX = 119
+SCLEX_JSON = 120
+SCLEX_EDIFACT = 121
+SCLEX_INDENT = 122
+SCLEX_MAXIMA = 123
+SCLEX_STATA = 124
+SCLEX_SAS = 125
+SCLEX_NIM = 126
+SCLEX_CIL = 127
+SCLEX_X12 = 128
+SCLEX_DATAFLEX = 129
+SCLEX_HOLLYWOOD = 130
+SCLEX_RAKU = 131
+SCLEX_AUTOMATIC = 1000
+SCE_P_DEFAULT = 0
+SCE_P_COMMENTLINE = 1
+SCE_P_NUMBER = 2
+SCE_P_STRING = 3
+SCE_P_CHARACTER = 4
+SCE_P_WORD = 5
+SCE_P_TRIPLE = 6
+SCE_P_TRIPLEDOUBLE = 7
+SCE_P_CLASSNAME = 8
+SCE_P_DEFNAME = 9
+SCE_P_OPERATOR = 10
+SCE_P_IDENTIFIER = 11
+SCE_P_COMMENTBLOCK = 12
+SCE_P_STRINGEOL = 13
+SCE_P_WORD2 = 14
+SCE_P_DECORATOR = 15
+SCE_P_FSTRING = 16
+SCE_P_FCHARACTER = 17
+SCE_P_FTRIPLE = 18
+SCE_P_FTRIPLEDOUBLE = 19
+SCE_C_DEFAULT = 0
+SCE_C_COMMENT = 1
+SCE_C_COMMENTLINE = 2
+SCE_C_COMMENTDOC = 3
+SCE_C_NUMBER = 4
+SCE_C_WORD = 5
+SCE_C_STRING = 6
+SCE_C_CHARACTER = 7
+SCE_C_UUID = 8
+SCE_C_PREPROCESSOR = 9
+SCE_C_OPERATOR = 10
+SCE_C_IDENTIFIER = 11
+SCE_C_STRINGEOL = 12
+SCE_C_VERBATIM = 13
+SCE_C_REGEX = 14
+SCE_C_COMMENTLINEDOC = 15
+SCE_C_WORD2 = 16
+SCE_C_COMMENTDOCKEYWORD = 17
+SCE_C_COMMENTDOCKEYWORDERROR = 18
+SCE_C_GLOBALCLASS = 19
+SCE_C_STRINGRAW = 20
+SCE_C_TRIPLEVERBATIM = 21
+SCE_C_HASHQUOTEDSTRING = 22
+SCE_C_PREPROCESSORCOMMENT = 23
+SCE_C_PREPROCESSORCOMMENTDOC = 24
+SCE_C_USERLITERAL = 25
+SCE_C_TASKMARKER = 26
+SCE_C_ESCAPESEQUENCE = 27
+SCE_D_DEFAULT = 0
+SCE_D_COMMENT = 1
+SCE_D_COMMENTLINE = 2
+SCE_D_COMMENTDOC = 3
+SCE_D_COMMENTNESTED = 4
+SCE_D_NUMBER = 5
+SCE_D_WORD = 6
+SCE_D_WORD2 = 7
+SCE_D_WORD3 = 8
+SCE_D_TYPEDEF = 9
+SCE_D_STRING = 10
+SCE_D_STRINGEOL = 11
+SCE_D_CHARACTER = 12
+SCE_D_OPERATOR = 13
+SCE_D_IDENTIFIER = 14
+SCE_D_COMMENTLINEDOC = 15
+SCE_D_COMMENTDOCKEYWORD = 16
+SCE_D_COMMENTDOCKEYWORDERROR = 17
+SCE_D_STRINGB = 18
+SCE_D_STRINGR = 19
+SCE_D_WORD5 = 20
+SCE_D_WORD6 = 21
+SCE_D_WORD7 = 22
+SCE_TCL_DEFAULT = 0
+SCE_TCL_COMMENT = 1
+SCE_TCL_COMMENTLINE = 2
+SCE_TCL_NUMBER = 3
+SCE_TCL_WORD_IN_QUOTE = 4
+SCE_TCL_IN_QUOTE = 5
+SCE_TCL_OPERATOR = 6
+SCE_TCL_IDENTIFIER = 7
+SCE_TCL_SUBSTITUTION = 8
+SCE_TCL_SUB_BRACE = 9
+SCE_TCL_MODIFIER = 10
+SCE_TCL_EXPAND = 11
+SCE_TCL_WORD = 12
+SCE_TCL_WORD2 = 13
+SCE_TCL_WORD3 = 14
+SCE_TCL_WORD4 = 15
+SCE_TCL_WORD5 = 16
+SCE_TCL_WORD6 = 17
+SCE_TCL_WORD7 = 18
+SCE_TCL_WORD8 = 19
+SCE_TCL_COMMENT_BOX = 20
+SCE_TCL_BLOCK_COMMENT = 21
+SCE_H_DEFAULT = 0
+SCE_H_TAG = 1
+SCE_H_TAGUNKNOWN = 2
+SCE_H_ATTRIBUTE = 3
+SCE_H_ATTRIBUTEUNKNOWN = 4
+SCE_H_NUMBER = 5
+SCE_H_DOUBLESTRING = 6
+SCE_H_SINGLESTRING = 7
+SCE_H_OTHER = 8
+SCE_H_COMMENT = 9
+SCE_H_ENTITY = 10
+SCE_H_TAGEND = 11
+SCE_H_XMLSTART = 12
+SCE_H_XMLEND = 13
+SCE_H_SCRIPT = 14
+SCE_H_ASP = 15
+SCE_H_ASPAT = 16
+SCE_H_CDATA = 17
+SCE_H_QUESTION = 18
+SCE_H_VALUE = 19
+SCE_H_XCCOMMENT = 20
+SCE_H_SGML_DEFAULT = 21
+SCE_H_SGML_COMMAND = 22
+SCE_H_SGML_1ST_PARAM = 23
+SCE_H_SGML_DOUBLESTRING = 24
+SCE_H_SGML_SIMPLESTRING = 25
+SCE_H_SGML_ERROR = 26
+SCE_H_SGML_SPECIAL = 27
+SCE_H_SGML_ENTITY = 28
+SCE_H_SGML_COMMENT = 29
+SCE_H_SGML_1ST_PARAM_COMMENT = 30
+SCE_H_SGML_BLOCK_DEFAULT = 31
+SCE_HJ_START = 40
+SCE_HJ_DEFAULT = 41
+SCE_HJ_COMMENT = 42
+SCE_HJ_COMMENTLINE = 43
+SCE_HJ_COMMENTDOC = 44
+SCE_HJ_NUMBER = 45
+SCE_HJ_WORD = 46
+SCE_HJ_KEYWORD = 47
+SCE_HJ_DOUBLESTRING = 48
+SCE_HJ_SINGLESTRING = 49
+SCE_HJ_SYMBOLS = 50
+SCE_HJ_STRINGEOL = 51
+SCE_HJ_REGEX = 52
+SCE_HJA_START = 55
+SCE_HJA_DEFAULT = 56
+SCE_HJA_COMMENT = 57
+SCE_HJA_COMMENTLINE = 58
+SCE_HJA_COMMENTDOC = 59
+SCE_HJA_NUMBER = 60
+SCE_HJA_WORD = 61
+SCE_HJA_KEYWORD = 62
+SCE_HJA_DOUBLESTRING = 63
+SCE_HJA_SINGLESTRING = 64
+SCE_HJA_SYMBOLS = 65
+SCE_HJA_STRINGEOL = 66
+SCE_HJA_REGEX = 67
+SCE_HB_START = 70
+SCE_HB_DEFAULT = 71
+SCE_HB_COMMENTLINE = 72
+SCE_HB_NUMBER = 73
+SCE_HB_WORD = 74
+SCE_HB_STRING = 75
+SCE_HB_IDENTIFIER = 76
+SCE_HB_STRINGEOL = 77
+SCE_HBA_START = 80
+SCE_HBA_DEFAULT = 81
+SCE_HBA_COMMENTLINE = 82
+SCE_HBA_NUMBER = 83
+SCE_HBA_WORD = 84
+SCE_HBA_STRING = 85
+SCE_HBA_IDENTIFIER = 86
+SCE_HBA_STRINGEOL = 87
+SCE_HP_START = 90
+SCE_HP_DEFAULT = 91
+SCE_HP_COMMENTLINE = 92
+SCE_HP_NUMBER = 93
+SCE_HP_STRING = 94
+SCE_HP_CHARACTER = 95
+SCE_HP_WORD = 96
+SCE_HP_TRIPLE = 97
+SCE_HP_TRIPLEDOUBLE = 98
+SCE_HP_CLASSNAME = 99
+SCE_HP_DEFNAME = 100
+SCE_HP_OPERATOR = 101
+SCE_HP_IDENTIFIER = 102
+SCE_HPHP_COMPLEX_VARIABLE = 104
+SCE_HPA_START = 105
+SCE_HPA_DEFAULT = 106
+SCE_HPA_COMMENTLINE = 107
+SCE_HPA_NUMBER = 108
+SCE_HPA_STRING = 109
+SCE_HPA_CHARACTER = 110
+SCE_HPA_WORD = 111
+SCE_HPA_TRIPLE = 112
+SCE_HPA_TRIPLEDOUBLE = 113
+SCE_HPA_CLASSNAME = 114
+SCE_HPA_DEFNAME = 115
+SCE_HPA_OPERATOR = 116
+SCE_HPA_IDENTIFIER = 117
+SCE_HPHP_DEFAULT = 118
+SCE_HPHP_HSTRING = 119
+SCE_HPHP_SIMPLESTRING = 120
+SCE_HPHP_WORD = 121
+SCE_HPHP_NUMBER = 122
+SCE_HPHP_VARIABLE = 123
+SCE_HPHP_COMMENT = 124
+SCE_HPHP_COMMENTLINE = 125
+SCE_HPHP_HSTRING_VARIABLE = 126
+SCE_HPHP_OPERATOR = 127
+SCE_PL_DEFAULT = 0
+SCE_PL_ERROR = 1
+SCE_PL_COMMENTLINE = 2
+SCE_PL_POD = 3
+SCE_PL_NUMBER = 4
+SCE_PL_WORD = 5
+SCE_PL_STRING = 6
+SCE_PL_CHARACTER = 7
+SCE_PL_PUNCTUATION = 8
+SCE_PL_PREPROCESSOR = 9
+SCE_PL_OPERATOR = 10
+SCE_PL_IDENTIFIER = 11
+SCE_PL_SCALAR = 12
+SCE_PL_ARRAY = 13
+SCE_PL_HASH = 14
+SCE_PL_SYMBOLTABLE = 15
+SCE_PL_VARIABLE_INDEXER = 16
+SCE_PL_REGEX = 17
+SCE_PL_REGSUBST = 18
+SCE_PL_LONGQUOTE = 19
+SCE_PL_BACKTICKS = 20
+SCE_PL_DATASECTION = 21
+SCE_PL_HERE_DELIM = 22
+SCE_PL_HERE_Q = 23
+SCE_PL_HERE_QQ = 24
+SCE_PL_HERE_QX = 25
+SCE_PL_STRING_Q = 26
+SCE_PL_STRING_QQ = 27
+SCE_PL_STRING_QX = 28
+SCE_PL_STRING_QR = 29
+SCE_PL_STRING_QW = 30
+SCE_PL_POD_VERB = 31
+SCE_PL_SUB_PROTOTYPE = 40
+SCE_PL_FORMAT_IDENT = 41
+SCE_PL_FORMAT = 42
+SCE_PL_STRING_VAR = 43
+SCE_PL_XLAT = 44
+SCE_PL_REGEX_VAR = 54
+SCE_PL_REGSUBST_VAR = 55
+SCE_PL_BACKTICKS_VAR = 57
+SCE_PL_HERE_QQ_VAR = 61
+SCE_PL_HERE_QX_VAR = 62
+SCE_PL_STRING_QQ_VAR = 64
+SCE_PL_STRING_QX_VAR = 65
+SCE_PL_STRING_QR_VAR = 66
+SCE_RB_DEFAULT = 0
+SCE_RB_ERROR = 1
+SCE_RB_COMMENTLINE = 2
+SCE_RB_POD = 3
+SCE_RB_NUMBER = 4
+SCE_RB_WORD = 5
+SCE_RB_STRING = 6
+SCE_RB_CHARACTER = 7
+SCE_RB_CLASSNAME = 8
+SCE_RB_DEFNAME = 9
+SCE_RB_OPERATOR = 10
+SCE_RB_IDENTIFIER = 11
+SCE_RB_REGEX = 12
+SCE_RB_GLOBAL = 13
+SCE_RB_SYMBOL = 14
+SCE_RB_MODULE_NAME = 15
+SCE_RB_INSTANCE_VAR = 16
+SCE_RB_CLASS_VAR = 17
+SCE_RB_BACKTICKS = 18
+SCE_RB_DATASECTION = 19
+SCE_RB_HERE_DELIM = 20
+SCE_RB_HERE_Q = 21
+SCE_RB_HERE_QQ = 22
+SCE_RB_HERE_QX = 23
+SCE_RB_STRING_Q = 24
+SCE_RB_STRING_QQ = 25
+SCE_RB_STRING_QX = 26
+SCE_RB_STRING_QR = 27
+SCE_RB_STRING_QW = 28
+SCE_RB_WORD_DEMOTED = 29
+SCE_RB_STDIN = 30
+SCE_RB_STDOUT = 31
+SCE_RB_STDERR = 40
+SCE_RB_UPPER_BOUND = 41
+SCE_B_DEFAULT = 0
+SCE_B_COMMENT = 1
+SCE_B_NUMBER = 2
+SCE_B_KEYWORD = 3
+SCE_B_STRING = 4
+SCE_B_PREPROCESSOR = 5
+SCE_B_OPERATOR = 6
+SCE_B_IDENTIFIER = 7
+SCE_B_DATE = 8
+SCE_B_STRINGEOL = 9
+SCE_B_KEYWORD2 = 10
+SCE_B_KEYWORD3 = 11
+SCE_B_KEYWORD4 = 12
+SCE_B_CONSTANT = 13
+SCE_B_ASM = 14
+SCE_B_LABEL = 15
+SCE_B_ERROR = 16
+SCE_B_HEXNUMBER = 17
+SCE_B_BINNUMBER = 18
+SCE_B_COMMENTBLOCK = 19
+SCE_B_DOCLINE = 20
+SCE_B_DOCBLOCK = 21
+SCE_B_DOCKEYWORD = 22
+SCE_PROPS_DEFAULT = 0
+SCE_PROPS_COMMENT = 1
+SCE_PROPS_SECTION = 2
+SCE_PROPS_ASSIGNMENT = 3
+SCE_PROPS_DEFVAL = 4
+SCE_PROPS_KEY = 5
+SCE_L_DEFAULT = 0
+SCE_L_COMMAND = 1
+SCE_L_TAG = 2
+SCE_L_MATH = 3
+SCE_L_COMMENT = 4
+SCE_L_TAG2 = 5
+SCE_L_MATH2 = 6
+SCE_L_COMMENT2 = 7
+SCE_L_VERBATIM = 8
+SCE_L_SHORTCMD = 9
+SCE_L_SPECIAL = 10
+SCE_L_CMDOPT = 11
+SCE_L_ERROR = 12
+SCE_LUA_DEFAULT = 0
+SCE_LUA_COMMENT = 1
+SCE_LUA_COMMENTLINE = 2
+SCE_LUA_COMMENTDOC = 3
+SCE_LUA_NUMBER = 4
+SCE_LUA_WORD = 5
+SCE_LUA_STRING = 6
+SCE_LUA_CHARACTER = 7
+SCE_LUA_LITERALSTRING = 8
+SCE_LUA_PREPROCESSOR = 9
+SCE_LUA_OPERATOR = 10
+SCE_LUA_IDENTIFIER = 11
+SCE_LUA_STRINGEOL = 12
+SCE_LUA_WORD2 = 13
+SCE_LUA_WORD3 = 14
+SCE_LUA_WORD4 = 15
+SCE_LUA_WORD5 = 16
+SCE_LUA_WORD6 = 17
+SCE_LUA_WORD7 = 18
+SCE_LUA_WORD8 = 19
+SCE_LUA_LABEL = 20
+SCE_ERR_DEFAULT = 0
+SCE_ERR_PYTHON = 1
+SCE_ERR_GCC = 2
+SCE_ERR_MS = 3
+SCE_ERR_CMD = 4
+SCE_ERR_BORLAND = 5
+SCE_ERR_PERL = 6
+SCE_ERR_NET = 7
+SCE_ERR_LUA = 8
+SCE_ERR_CTAG = 9
+SCE_ERR_DIFF_CHANGED = 10
+SCE_ERR_DIFF_ADDITION = 11
+SCE_ERR_DIFF_DELETION = 12
+SCE_ERR_DIFF_MESSAGE = 13
+SCE_ERR_PHP = 14
+SCE_ERR_ELF = 15
+SCE_ERR_IFC = 16
+SCE_ERR_IFORT = 17
+SCE_ERR_ABSF = 18
+SCE_ERR_TIDY = 19
+SCE_ERR_JAVA_STACK = 20
+SCE_ERR_VALUE = 21
+SCE_ERR_GCC_INCLUDED_FROM = 22
+SCE_ERR_ESCSEQ = 23
+SCE_ERR_ESCSEQ_UNKNOWN = 24
+SCE_ERR_GCC_EXCERPT = 25
+SCE_ERR_ES_BLACK = 40
+SCE_ERR_ES_RED = 41
+SCE_ERR_ES_GREEN = 42
+SCE_ERR_ES_BROWN = 43
+SCE_ERR_ES_BLUE = 44
+SCE_ERR_ES_MAGENTA = 45
+SCE_ERR_ES_CYAN = 46
+SCE_ERR_ES_GRAY = 47
+SCE_ERR_ES_DARK_GRAY = 48
+SCE_ERR_ES_BRIGHT_RED = 49
+SCE_ERR_ES_BRIGHT_GREEN = 50
+SCE_ERR_ES_YELLOW = 51
+SCE_ERR_ES_BRIGHT_BLUE = 52
+SCE_ERR_ES_BRIGHT_MAGENTA = 53
+SCE_ERR_ES_BRIGHT_CYAN = 54
+SCE_ERR_ES_WHITE = 55
+SCE_BAT_DEFAULT = 0
+SCE_BAT_COMMENT = 1
+SCE_BAT_WORD = 2
+SCE_BAT_LABEL = 3
+SCE_BAT_HIDE = 4
+SCE_BAT_COMMAND = 5
+SCE_BAT_IDENTIFIER = 6
+SCE_BAT_OPERATOR = 7
+SCE_TCMD_DEFAULT = 0
+SCE_TCMD_COMMENT = 1
+SCE_TCMD_WORD = 2
+SCE_TCMD_LABEL = 3
+SCE_TCMD_HIDE = 4
+SCE_TCMD_COMMAND = 5
+SCE_TCMD_IDENTIFIER = 6
+SCE_TCMD_OPERATOR = 7
+SCE_TCMD_ENVIRONMENT = 8
+SCE_TCMD_EXPANSION = 9
+SCE_TCMD_CLABEL = 10
+SCE_MAKE_DEFAULT = 0
+SCE_MAKE_COMMENT = 1
+SCE_MAKE_PREPROCESSOR = 2
+SCE_MAKE_IDENTIFIER = 3
+SCE_MAKE_OPERATOR = 4
+SCE_MAKE_TARGET = 5
+SCE_MAKE_IDEOL = 9
+SCE_DIFF_DEFAULT = 0
+SCE_DIFF_COMMENT = 1
+SCE_DIFF_COMMAND = 2
+SCE_DIFF_HEADER = 3
+SCE_DIFF_POSITION = 4
+SCE_DIFF_DELETED = 5
+SCE_DIFF_ADDED = 6
+SCE_DIFF_CHANGED = 7
+SCE_DIFF_PATCH_ADD = 8
+SCE_DIFF_PATCH_DELETE = 9
+SCE_DIFF_REMOVED_PATCH_ADD = 10
+SCE_DIFF_REMOVED_PATCH_DELETE = 11
+SCE_CONF_DEFAULT = 0
+SCE_CONF_COMMENT = 1
+SCE_CONF_NUMBER = 2
+SCE_CONF_IDENTIFIER = 3
+SCE_CONF_EXTENSION = 4
+SCE_CONF_PARAMETER = 5
+SCE_CONF_STRING = 6
+SCE_CONF_OPERATOR = 7
+SCE_CONF_IP = 8
+SCE_CONF_DIRECTIVE = 9
+SCE_AVE_DEFAULT = 0
+SCE_AVE_COMMENT = 1
+SCE_AVE_NUMBER = 2
+SCE_AVE_WORD = 3
+SCE_AVE_STRING = 6
+SCE_AVE_ENUM = 7
+SCE_AVE_STRINGEOL = 8
+SCE_AVE_IDENTIFIER = 9
+SCE_AVE_OPERATOR = 10
+SCE_AVE_WORD1 = 11
+SCE_AVE_WORD2 = 12
+SCE_AVE_WORD3 = 13
+SCE_AVE_WORD4 = 14
+SCE_AVE_WORD5 = 15
+SCE_AVE_WORD6 = 16
+SCE_ADA_DEFAULT = 0
+SCE_ADA_WORD = 1
+SCE_ADA_IDENTIFIER = 2
+SCE_ADA_NUMBER = 3
+SCE_ADA_DELIMITER = 4
+SCE_ADA_CHARACTER = 5
+SCE_ADA_CHARACTEREOL = 6
+SCE_ADA_STRING = 7
+SCE_ADA_STRINGEOL = 8
+SCE_ADA_LABEL = 9
+SCE_ADA_COMMENTLINE = 10
+SCE_ADA_ILLEGAL = 11
+SCE_BAAN_DEFAULT = 0
+SCE_BAAN_COMMENT = 1
+SCE_BAAN_COMMENTDOC = 2
+SCE_BAAN_NUMBER = 3
+SCE_BAAN_WORD = 4
+SCE_BAAN_STRING = 5
+SCE_BAAN_PREPROCESSOR = 6
+SCE_BAAN_OPERATOR = 7
+SCE_BAAN_IDENTIFIER = 8
+SCE_BAAN_STRINGEOL = 9
+SCE_BAAN_WORD2 = 10
+SCE_BAAN_WORD3 = 11
+SCE_BAAN_WORD4 = 12
+SCE_BAAN_WORD5 = 13
+SCE_BAAN_WORD6 = 14
+SCE_BAAN_WORD7 = 15
+SCE_BAAN_WORD8 = 16
+SCE_BAAN_WORD9 = 17
+SCE_BAAN_TABLEDEF = 18
+SCE_BAAN_TABLESQL = 19
+SCE_BAAN_FUNCTION = 20
+SCE_BAAN_DOMDEF = 21
+SCE_BAAN_FUNCDEF = 22
+SCE_BAAN_OBJECTDEF = 23
+SCE_BAAN_DEFINEDEF = 24
+SCE_LISP_DEFAULT = 0
+SCE_LISP_COMMENT = 1
+SCE_LISP_NUMBER = 2
+SCE_LISP_KEYWORD = 3
+SCE_LISP_KEYWORD_KW = 4
+SCE_LISP_SYMBOL = 5
+SCE_LISP_STRING = 6
+SCE_LISP_STRINGEOL = 8
+SCE_LISP_IDENTIFIER = 9
+SCE_LISP_OPERATOR = 10
+SCE_LISP_SPECIAL = 11
+SCE_LISP_MULTI_COMMENT = 12
+SCE_EIFFEL_DEFAULT = 0
+SCE_EIFFEL_COMMENTLINE = 1
+SCE_EIFFEL_NUMBER = 2
+SCE_EIFFEL_WORD = 3
+SCE_EIFFEL_STRING = 4
+SCE_EIFFEL_CHARACTER = 5
+SCE_EIFFEL_OPERATOR = 6
+SCE_EIFFEL_IDENTIFIER = 7
+SCE_EIFFEL_STRINGEOL = 8
+SCE_NNCRONTAB_DEFAULT = 0
+SCE_NNCRONTAB_COMMENT = 1
+SCE_NNCRONTAB_TASK = 2
+SCE_NNCRONTAB_SECTION = 3
+SCE_NNCRONTAB_KEYWORD = 4
+SCE_NNCRONTAB_MODIFIER = 5
+SCE_NNCRONTAB_ASTERISK = 6
+SCE_NNCRONTAB_NUMBER = 7
+SCE_NNCRONTAB_STRING = 8
+SCE_NNCRONTAB_ENVIRONMENT = 9
+SCE_NNCRONTAB_IDENTIFIER = 10
+SCE_FORTH_DEFAULT = 0
+SCE_FORTH_COMMENT = 1
+SCE_FORTH_COMMENT_ML = 2
+SCE_FORTH_IDENTIFIER = 3
+SCE_FORTH_CONTROL = 4
+SCE_FORTH_KEYWORD = 5
+SCE_FORTH_DEFWORD = 6
+SCE_FORTH_PREWORD1 = 7
+SCE_FORTH_PREWORD2 = 8
+SCE_FORTH_NUMBER = 9
+SCE_FORTH_STRING = 10
+SCE_FORTH_LOCALE = 11
+SCE_MATLAB_DEFAULT = 0
+SCE_MATLAB_COMMENT = 1
+SCE_MATLAB_COMMAND = 2
+SCE_MATLAB_NUMBER = 3
+SCE_MATLAB_KEYWORD = 4
+SCE_MATLAB_STRING = 5
+SCE_MATLAB_OPERATOR = 6
+SCE_MATLAB_IDENTIFIER = 7
+SCE_MATLAB_DOUBLEQUOTESTRING = 8
+SCE_MAXIMA_OPERATOR = 0
+SCE_MAXIMA_COMMANDENDING = 1
+SCE_MAXIMA_COMMENT = 2
+SCE_MAXIMA_NUMBER = 3
+SCE_MAXIMA_STRING = 4
+SCE_MAXIMA_COMMAND = 5
+SCE_MAXIMA_VARIABLE = 6
+SCE_MAXIMA_UNKNOWN = 7
+SCE_SCRIPTOL_DEFAULT = 0
+SCE_SCRIPTOL_WHITE = 1
+SCE_SCRIPTOL_COMMENTLINE = 2
+SCE_SCRIPTOL_PERSISTENT = 3
+SCE_SCRIPTOL_CSTYLE = 4
+SCE_SCRIPTOL_COMMENTBLOCK = 5
+SCE_SCRIPTOL_NUMBER = 6
+SCE_SCRIPTOL_STRING = 7
+SCE_SCRIPTOL_CHARACTER = 8
+SCE_SCRIPTOL_STRINGEOL = 9
+SCE_SCRIPTOL_KEYWORD = 10
+SCE_SCRIPTOL_OPERATOR = 11
+SCE_SCRIPTOL_IDENTIFIER = 12
+SCE_SCRIPTOL_TRIPLE = 13
+SCE_SCRIPTOL_CLASSNAME = 14
+SCE_SCRIPTOL_PREPROCESSOR = 15
+SCE_ASM_DEFAULT = 0
+SCE_ASM_COMMENT = 1
+SCE_ASM_NUMBER = 2
+SCE_ASM_STRING = 3
+SCE_ASM_OPERATOR = 4
+SCE_ASM_IDENTIFIER = 5
+SCE_ASM_CPUINSTRUCTION = 6
+SCE_ASM_MATHINSTRUCTION = 7
+SCE_ASM_REGISTER = 8
+SCE_ASM_DIRECTIVE = 9
+SCE_ASM_DIRECTIVEOPERAND = 10
+SCE_ASM_COMMENTBLOCK = 11
+SCE_ASM_CHARACTER = 12
+SCE_ASM_STRINGEOL = 13
+SCE_ASM_EXTINSTRUCTION = 14
+SCE_ASM_COMMENTDIRECTIVE = 15
+SCE_F_DEFAULT = 0
+SCE_F_COMMENT = 1
+SCE_F_NUMBER = 2
+SCE_F_STRING1 = 3
+SCE_F_STRING2 = 4
+SCE_F_STRINGEOL = 5
+SCE_F_OPERATOR = 6
+SCE_F_IDENTIFIER = 7
+SCE_F_WORD = 8
+SCE_F_WORD2 = 9
+SCE_F_WORD3 = 10
+SCE_F_PREPROCESSOR = 11
+SCE_F_OPERATOR2 = 12
+SCE_F_LABEL = 13
+SCE_F_CONTINUATION = 14
+SCE_CSS_DEFAULT = 0
+SCE_CSS_TAG = 1
+SCE_CSS_CLASS = 2
+SCE_CSS_PSEUDOCLASS = 3
+SCE_CSS_UNKNOWN_PSEUDOCLASS = 4
+SCE_CSS_OPERATOR = 5
+SCE_CSS_IDENTIFIER = 6
+SCE_CSS_UNKNOWN_IDENTIFIER = 7
+SCE_CSS_VALUE = 8
+SCE_CSS_COMMENT = 9
+SCE_CSS_ID = 10
+SCE_CSS_IMPORTANT = 11
+SCE_CSS_DIRECTIVE = 12
+SCE_CSS_DOUBLESTRING = 13
+SCE_CSS_SINGLESTRING = 14
+SCE_CSS_IDENTIFIER2 = 15
+SCE_CSS_ATTRIBUTE = 16
+SCE_CSS_IDENTIFIER3 = 17
+SCE_CSS_PSEUDOELEMENT = 18
+SCE_CSS_EXTENDED_IDENTIFIER = 19
+SCE_CSS_EXTENDED_PSEUDOCLASS = 20
+SCE_CSS_EXTENDED_PSEUDOELEMENT = 21
+SCE_CSS_MEDIA = 22
+SCE_CSS_VARIABLE = 23
+SCE_POV_DEFAULT = 0
+SCE_POV_COMMENT = 1
+SCE_POV_COMMENTLINE = 2
+SCE_POV_NUMBER = 3
+SCE_POV_OPERATOR = 4
+SCE_POV_IDENTIFIER = 5
+SCE_POV_STRING = 6
+SCE_POV_STRINGEOL = 7
+SCE_POV_DIRECTIVE = 8
+SCE_POV_BADDIRECTIVE = 9
+SCE_POV_WORD2 = 10
+SCE_POV_WORD3 = 11
+SCE_POV_WORD4 = 12
+SCE_POV_WORD5 = 13
+SCE_POV_WORD6 = 14
+SCE_POV_WORD7 = 15
+SCE_POV_WORD8 = 16
+SCE_LOUT_DEFAULT = 0
+SCE_LOUT_COMMENT = 1
+SCE_LOUT_NUMBER = 2
+SCE_LOUT_WORD = 3
+SCE_LOUT_WORD2 = 4
+SCE_LOUT_WORD3 = 5
+SCE_LOUT_WORD4 = 6
+SCE_LOUT_STRING = 7
+SCE_LOUT_OPERATOR = 8
+SCE_LOUT_IDENTIFIER = 9
+SCE_LOUT_STRINGEOL = 10
+SCE_ESCRIPT_DEFAULT = 0
+SCE_ESCRIPT_COMMENT = 1
+SCE_ESCRIPT_COMMENTLINE = 2
+SCE_ESCRIPT_COMMENTDOC = 3
+SCE_ESCRIPT_NUMBER = 4
+SCE_ESCRIPT_WORD = 5
+SCE_ESCRIPT_STRING = 6
+SCE_ESCRIPT_OPERATOR = 7
+SCE_ESCRIPT_IDENTIFIER = 8
+SCE_ESCRIPT_BRACE = 9
+SCE_ESCRIPT_WORD2 = 10
+SCE_ESCRIPT_WORD3 = 11
+SCE_PS_DEFAULT = 0
+SCE_PS_COMMENT = 1
+SCE_PS_DSC_COMMENT = 2
+SCE_PS_DSC_VALUE = 3
+SCE_PS_NUMBER = 4
+SCE_PS_NAME = 5
+SCE_PS_KEYWORD = 6
+SCE_PS_LITERAL = 7
+SCE_PS_IMMEVAL = 8
+SCE_PS_PAREN_ARRAY = 9
+SCE_PS_PAREN_DICT = 10
+SCE_PS_PAREN_PROC = 11
+SCE_PS_TEXT = 12
+SCE_PS_HEXSTRING = 13
+SCE_PS_BASE85STRING = 14
+SCE_PS_BADSTRINGCHAR = 15
+SCE_NSIS_DEFAULT = 0
+SCE_NSIS_COMMENT = 1
+SCE_NSIS_STRINGDQ = 2
+SCE_NSIS_STRINGLQ = 3
+SCE_NSIS_STRINGRQ = 4
+SCE_NSIS_FUNCTION = 5
+SCE_NSIS_VARIABLE = 6
+SCE_NSIS_LABEL = 7
+SCE_NSIS_USERDEFINED = 8
+SCE_NSIS_SECTIONDEF = 9
+SCE_NSIS_SUBSECTIONDEF = 10
+SCE_NSIS_IFDEFINEDEF = 11
+SCE_NSIS_MACRODEF = 12
+SCE_NSIS_STRINGVAR = 13
+SCE_NSIS_NUMBER = 14
+SCE_NSIS_SECTIONGROUP = 15
+SCE_NSIS_PAGEEX = 16
+SCE_NSIS_FUNCTIONDEF = 17
+SCE_NSIS_COMMENTBOX = 18
+SCE_MMIXAL_LEADWS = 0
+SCE_MMIXAL_COMMENT = 1
+SCE_MMIXAL_LABEL = 2
+SCE_MMIXAL_OPCODE = 3
+SCE_MMIXAL_OPCODE_PRE = 4
+SCE_MMIXAL_OPCODE_VALID = 5
+SCE_MMIXAL_OPCODE_UNKNOWN = 6
+SCE_MMIXAL_OPCODE_POST = 7
+SCE_MMIXAL_OPERANDS = 8
+SCE_MMIXAL_NUMBER = 9
+SCE_MMIXAL_REF = 10
+SCE_MMIXAL_CHAR = 11
+SCE_MMIXAL_STRING = 12
+SCE_MMIXAL_REGISTER = 13
+SCE_MMIXAL_HEX = 14
+SCE_MMIXAL_OPERATOR = 15
+SCE_MMIXAL_SYMBOL = 16
+SCE_MMIXAL_INCLUDE = 17
+SCE_CLW_DEFAULT = 0
+SCE_CLW_LABEL = 1
+SCE_CLW_COMMENT = 2
+SCE_CLW_STRING = 3
+SCE_CLW_USER_IDENTIFIER = 4
+SCE_CLW_INTEGER_CONSTANT = 5
+SCE_CLW_REAL_CONSTANT = 6
+SCE_CLW_PICTURE_STRING = 7
+SCE_CLW_KEYWORD = 8
+SCE_CLW_COMPILER_DIRECTIVE = 9
+SCE_CLW_RUNTIME_EXPRESSIONS = 10
+SCE_CLW_BUILTIN_PROCEDURES_FUNCTION = 11
+SCE_CLW_STRUCTURE_DATA_TYPE = 12
+SCE_CLW_ATTRIBUTE = 13
+SCE_CLW_STANDARD_EQUATE = 14
+SCE_CLW_ERROR = 15
+SCE_CLW_DEPRECATED = 16
+SCE_LOT_DEFAULT = 0
+SCE_LOT_HEADER = 1
+SCE_LOT_BREAK = 2
+SCE_LOT_SET = 3
+SCE_LOT_PASS = 4
+SCE_LOT_FAIL = 5
+SCE_LOT_ABORT = 6
+SCE_YAML_DEFAULT = 0
+SCE_YAML_COMMENT = 1
+SCE_YAML_IDENTIFIER = 2
+SCE_YAML_KEYWORD = 3
+SCE_YAML_NUMBER = 4
+SCE_YAML_REFERENCE = 5
+SCE_YAML_DOCUMENT = 6
+SCE_YAML_TEXT = 7
+SCE_YAML_ERROR = 8
+SCE_YAML_OPERATOR = 9
+SCE_TEX_DEFAULT = 0
+SCE_TEX_SPECIAL = 1
+SCE_TEX_GROUP = 2
+SCE_TEX_SYMBOL = 3
+SCE_TEX_COMMAND = 4
+SCE_TEX_TEXT = 5
+SCE_METAPOST_DEFAULT = 0
+SCE_METAPOST_SPECIAL = 1
+SCE_METAPOST_GROUP = 2
+SCE_METAPOST_SYMBOL = 3
+SCE_METAPOST_COMMAND = 4
+SCE_METAPOST_TEXT = 5
+SCE_METAPOST_EXTRA = 6
+SCE_ERLANG_DEFAULT = 0
+SCE_ERLANG_COMMENT = 1
+SCE_ERLANG_VARIABLE = 2
+SCE_ERLANG_NUMBER = 3
+SCE_ERLANG_KEYWORD = 4
+SCE_ERLANG_STRING = 5
+SCE_ERLANG_OPERATOR = 6
+SCE_ERLANG_ATOM = 7
+SCE_ERLANG_FUNCTION_NAME = 8
+SCE_ERLANG_CHARACTER = 9
+SCE_ERLANG_MACRO = 10
+SCE_ERLANG_RECORD = 11
+SCE_ERLANG_PREPROC = 12
+SCE_ERLANG_NODE_NAME = 13
+SCE_ERLANG_COMMENT_FUNCTION = 14
+SCE_ERLANG_COMMENT_MODULE = 15
+SCE_ERLANG_COMMENT_DOC = 16
+SCE_ERLANG_COMMENT_DOC_MACRO = 17
+SCE_ERLANG_ATOM_QUOTED = 18
+SCE_ERLANG_MACRO_QUOTED = 19
+SCE_ERLANG_RECORD_QUOTED = 20
+SCE_ERLANG_NODE_NAME_QUOTED = 21
+SCE_ERLANG_BIFS = 22
+SCE_ERLANG_MODULES = 23
+SCE_ERLANG_MODULES_ATT = 24
+SCE_ERLANG_UNKNOWN = 31
+SCE_MSSQL_DEFAULT = 0
+SCE_MSSQL_COMMENT = 1
+SCE_MSSQL_LINE_COMMENT = 2
+SCE_MSSQL_NUMBER = 3
+SCE_MSSQL_STRING = 4
+SCE_MSSQL_OPERATOR = 5
+SCE_MSSQL_IDENTIFIER = 6
+SCE_MSSQL_VARIABLE = 7
+SCE_MSSQL_COLUMN_NAME = 8
+SCE_MSSQL_STATEMENT = 9
+SCE_MSSQL_DATATYPE = 10
+SCE_MSSQL_SYSTABLE = 11
+SCE_MSSQL_GLOBAL_VARIABLE = 12
+SCE_MSSQL_FUNCTION = 13
+SCE_MSSQL_STORED_PROCEDURE = 14
+SCE_MSSQL_DEFAULT_PREF_DATATYPE = 15
+SCE_MSSQL_COLUMN_NAME_2 = 16
+SCE_V_DEFAULT = 0
+SCE_V_COMMENT = 1
+SCE_V_COMMENTLINE = 2
+SCE_V_COMMENTLINEBANG = 3
+SCE_V_NUMBER = 4
+SCE_V_WORD = 5
+SCE_V_STRING = 6
+SCE_V_WORD2 = 7
+SCE_V_WORD3 = 8
+SCE_V_PREPROCESSOR = 9
+SCE_V_OPERATOR = 10
+SCE_V_IDENTIFIER = 11
+SCE_V_STRINGEOL = 12
+SCE_V_USER = 19
+SCE_V_COMMENT_WORD = 20
+SCE_V_INPUT = 21
+SCE_V_OUTPUT = 22
+SCE_V_INOUT = 23
+SCE_V_PORT_CONNECT = 24
+SCE_KIX_DEFAULT = 0
+SCE_KIX_COMMENT = 1
+SCE_KIX_STRING1 = 2
+SCE_KIX_STRING2 = 3
+SCE_KIX_NUMBER = 4
+SCE_KIX_VAR = 5
+SCE_KIX_MACRO = 6
+SCE_KIX_KEYWORD = 7
+SCE_KIX_FUNCTIONS = 8
+SCE_KIX_OPERATOR = 9
+SCE_KIX_COMMENTSTREAM = 10
+SCE_KIX_IDENTIFIER = 31
+SCE_GC_DEFAULT = 0
+SCE_GC_COMMENTLINE = 1
+SCE_GC_COMMENTBLOCK = 2
+SCE_GC_GLOBAL = 3
+SCE_GC_EVENT = 4
+SCE_GC_ATTRIBUTE = 5
+SCE_GC_CONTROL = 6
+SCE_GC_COMMAND = 7
+SCE_GC_STRING = 8
+SCE_GC_OPERATOR = 9
+SCE_SN_DEFAULT = 0
+SCE_SN_CODE = 1
+SCE_SN_COMMENTLINE = 2
+SCE_SN_COMMENTLINEBANG = 3
+SCE_SN_NUMBER = 4
+SCE_SN_WORD = 5
+SCE_SN_STRING = 6
+SCE_SN_WORD2 = 7
+SCE_SN_WORD3 = 8
+SCE_SN_PREPROCESSOR = 9
+SCE_SN_OPERATOR = 10
+SCE_SN_IDENTIFIER = 11
+SCE_SN_STRINGEOL = 12
+SCE_SN_REGEXTAG = 13
+SCE_SN_SIGNAL = 14
+SCE_SN_USER = 19
+SCE_AU3_DEFAULT = 0
+SCE_AU3_COMMENT = 1
+SCE_AU3_COMMENTBLOCK = 2
+SCE_AU3_NUMBER = 3
+SCE_AU3_FUNCTION = 4
+SCE_AU3_KEYWORD = 5
+SCE_AU3_MACRO = 6
+SCE_AU3_STRING = 7
+SCE_AU3_OPERATOR = 8
+SCE_AU3_VARIABLE = 9
+SCE_AU3_SENT = 10
+SCE_AU3_PREPROCESSOR = 11
+SCE_AU3_SPECIAL = 12
+SCE_AU3_EXPAND = 13
+SCE_AU3_COMOBJ = 14
+SCE_AU3_UDF = 15
+SCE_APDL_DEFAULT = 0
+SCE_APDL_COMMENT = 1
+SCE_APDL_COMMENTBLOCK = 2
+SCE_APDL_NUMBER = 3
+SCE_APDL_STRING = 4
+SCE_APDL_OPERATOR = 5
+SCE_APDL_WORD = 6
+SCE_APDL_PROCESSOR = 7
+SCE_APDL_COMMAND = 8
+SCE_APDL_SLASHCOMMAND = 9
+SCE_APDL_STARCOMMAND = 10
+SCE_APDL_ARGUMENT = 11
+SCE_APDL_FUNCTION = 12
+SCE_SH_DEFAULT = 0
+SCE_SH_ERROR = 1
+SCE_SH_COMMENTLINE = 2
+SCE_SH_NUMBER = 3
+SCE_SH_WORD = 4
+SCE_SH_STRING = 5
+SCE_SH_CHARACTER = 6
+SCE_SH_OPERATOR = 7
+SCE_SH_IDENTIFIER = 8
+SCE_SH_SCALAR = 9
+SCE_SH_PARAM = 10
+SCE_SH_BACKTICKS = 11
+SCE_SH_HERE_DELIM = 12
+SCE_SH_HERE_Q = 13
+SCE_ASN1_DEFAULT = 0
+SCE_ASN1_COMMENT = 1
+SCE_ASN1_IDENTIFIER = 2
+SCE_ASN1_STRING = 3
+SCE_ASN1_OID = 4
+SCE_ASN1_SCALAR = 5
+SCE_ASN1_KEYWORD = 6
+SCE_ASN1_ATTRIBUTE = 7
+SCE_ASN1_DESCRIPTOR = 8
+SCE_ASN1_TYPE = 9
+SCE_ASN1_OPERATOR = 10
+SCE_VHDL_DEFAULT = 0
+SCE_VHDL_COMMENT = 1
+SCE_VHDL_COMMENTLINEBANG = 2
+SCE_VHDL_NUMBER = 3
+SCE_VHDL_STRING = 4
+SCE_VHDL_OPERATOR = 5
+SCE_VHDL_IDENTIFIER = 6
+SCE_VHDL_STRINGEOL = 7
+SCE_VHDL_KEYWORD = 8
+SCE_VHDL_STDOPERATOR = 9
+SCE_VHDL_ATTRIBUTE = 10
+SCE_VHDL_STDFUNCTION = 11
+SCE_VHDL_STDPACKAGE = 12
+SCE_VHDL_STDTYPE = 13
+SCE_VHDL_USERWORD = 14
+SCE_VHDL_BLOCK_COMMENT = 15
+SCE_CAML_DEFAULT = 0
+SCE_CAML_IDENTIFIER = 1
+SCE_CAML_TAGNAME = 2
+SCE_CAML_KEYWORD = 3
+SCE_CAML_KEYWORD2 = 4
+SCE_CAML_KEYWORD3 = 5
+SCE_CAML_LINENUM = 6
+SCE_CAML_OPERATOR = 7
+SCE_CAML_NUMBER = 8
+SCE_CAML_CHAR = 9
+SCE_CAML_WHITE = 10
+SCE_CAML_STRING = 11
+SCE_CAML_COMMENT = 12
+SCE_CAML_COMMENT1 = 13
+SCE_CAML_COMMENT2 = 14
+SCE_CAML_COMMENT3 = 15
+SCE_HA_DEFAULT = 0
+SCE_HA_IDENTIFIER = 1
+SCE_HA_KEYWORD = 2
+SCE_HA_NUMBER = 3
+SCE_HA_STRING = 4
+SCE_HA_CHARACTER = 5
+SCE_HA_CLASS = 6
+SCE_HA_MODULE = 7
+SCE_HA_CAPITAL = 8
+SCE_HA_DATA = 9
+SCE_HA_IMPORT = 10
+SCE_HA_OPERATOR = 11
+SCE_HA_INSTANCE = 12
+SCE_HA_COMMENTLINE = 13
+SCE_HA_COMMENTBLOCK = 14
+SCE_HA_COMMENTBLOCK2 = 15
+SCE_HA_COMMENTBLOCK3 = 16
+SCE_HA_PRAGMA = 17
+SCE_HA_PREPROCESSOR = 18
+SCE_HA_STRINGEOL = 19
+SCE_HA_RESERVED_OPERATOR = 20
+SCE_HA_LITERATE_COMMENT = 21
+SCE_HA_LITERATE_CODEDELIM = 22
+SCE_T3_DEFAULT = 0
+SCE_T3_X_DEFAULT = 1
+SCE_T3_PREPROCESSOR = 2
+SCE_T3_BLOCK_COMMENT = 3
+SCE_T3_LINE_COMMENT = 4
+SCE_T3_OPERATOR = 5
+SCE_T3_KEYWORD = 6
+SCE_T3_NUMBER = 7
+SCE_T3_IDENTIFIER = 8
+SCE_T3_S_STRING = 9
+SCE_T3_D_STRING = 10
+SCE_T3_X_STRING = 11
+SCE_T3_LIB_DIRECTIVE = 12
+SCE_T3_MSG_PARAM = 13
+SCE_T3_HTML_TAG = 14
+SCE_T3_HTML_DEFAULT = 15
+SCE_T3_HTML_STRING = 16
+SCE_T3_USER1 = 17
+SCE_T3_USER2 = 18
+SCE_T3_USER3 = 19
+SCE_T3_BRACE = 20
+SCE_REBOL_DEFAULT = 0
+SCE_REBOL_COMMENTLINE = 1
+SCE_REBOL_COMMENTBLOCK = 2
+SCE_REBOL_PREFACE = 3
+SCE_REBOL_OPERATOR = 4
+SCE_REBOL_CHARACTER = 5
+SCE_REBOL_QUOTEDSTRING = 6
+SCE_REBOL_BRACEDSTRING = 7
+SCE_REBOL_NUMBER = 8
+SCE_REBOL_PAIR = 9
+SCE_REBOL_TUPLE = 10
+SCE_REBOL_BINARY = 11
+SCE_REBOL_MONEY = 12
+SCE_REBOL_ISSUE = 13
+SCE_REBOL_TAG = 14
+SCE_REBOL_FILE = 15
+SCE_REBOL_EMAIL = 16
+SCE_REBOL_URL = 17
+SCE_REBOL_DATE = 18
+SCE_REBOL_TIME = 19
+SCE_REBOL_IDENTIFIER = 20
+SCE_REBOL_WORD = 21
+SCE_REBOL_WORD2 = 22
+SCE_REBOL_WORD3 = 23
+SCE_REBOL_WORD4 = 24
+SCE_REBOL_WORD5 = 25
+SCE_REBOL_WORD6 = 26
+SCE_REBOL_WORD7 = 27
+SCE_REBOL_WORD8 = 28
+SCE_SQL_DEFAULT = 0
+SCE_SQL_COMMENT = 1
+SCE_SQL_COMMENTLINE = 2
+SCE_SQL_COMMENTDOC = 3
+SCE_SQL_NUMBER = 4
+SCE_SQL_WORD = 5
+SCE_SQL_STRING = 6
+SCE_SQL_CHARACTER = 7
+SCE_SQL_SQLPLUS = 8
+SCE_SQL_SQLPLUS_PROMPT = 9
+SCE_SQL_OPERATOR = 10
+SCE_SQL_IDENTIFIER = 11
+SCE_SQL_SQLPLUS_COMMENT = 13
+SCE_SQL_COMMENTLINEDOC = 15
+SCE_SQL_WORD2 = 16
+SCE_SQL_COMMENTDOCKEYWORD = 17
+SCE_SQL_COMMENTDOCKEYWORDERROR = 18
+SCE_SQL_USER1 = 19
+SCE_SQL_USER2 = 20
+SCE_SQL_USER3 = 21
+SCE_SQL_USER4 = 22
+SCE_SQL_QUOTEDIDENTIFIER = 23
+SCE_SQL_QOPERATOR = 24
+SCE_ST_DEFAULT = 0
+SCE_ST_STRING = 1
+SCE_ST_NUMBER = 2
+SCE_ST_COMMENT = 3
+SCE_ST_SYMBOL = 4
+SCE_ST_BINARY = 5
+SCE_ST_BOOL = 6
+SCE_ST_SELF = 7
+SCE_ST_SUPER = 8
+SCE_ST_NIL = 9
+SCE_ST_GLOBAL = 10
+SCE_ST_RETURN = 11
+SCE_ST_SPECIAL = 12
+SCE_ST_KWSEND = 13
+SCE_ST_ASSIGN = 14
+SCE_ST_CHARACTER = 15
+SCE_ST_SPEC_SEL = 16
+SCE_FS_DEFAULT = 0
+SCE_FS_COMMENT = 1
+SCE_FS_COMMENTLINE = 2
+SCE_FS_COMMENTDOC = 3
+SCE_FS_COMMENTLINEDOC = 4
+SCE_FS_COMMENTDOCKEYWORD = 5
+SCE_FS_COMMENTDOCKEYWORDERROR = 6
+SCE_FS_KEYWORD = 7
+SCE_FS_KEYWORD2 = 8
+SCE_FS_KEYWORD3 = 9
+SCE_FS_KEYWORD4 = 10
+SCE_FS_NUMBER = 11
+SCE_FS_STRING = 12
+SCE_FS_PREPROCESSOR = 13
+SCE_FS_OPERATOR = 14
+SCE_FS_IDENTIFIER = 15
+SCE_FS_DATE = 16
+SCE_FS_STRINGEOL = 17
+SCE_FS_CONSTANT = 18
+SCE_FS_WORDOPERATOR = 19
+SCE_FS_DISABLEDCODE = 20
+SCE_FS_DEFAULT_C = 21
+SCE_FS_COMMENTDOC_C = 22
+SCE_FS_COMMENTLINEDOC_C = 23
+SCE_FS_KEYWORD_C = 24
+SCE_FS_KEYWORD2_C = 25
+SCE_FS_NUMBER_C = 26
+SCE_FS_STRING_C = 27
+SCE_FS_PREPROCESSOR_C = 28
+SCE_FS_OPERATOR_C = 29
+SCE_FS_IDENTIFIER_C = 30
+SCE_FS_STRINGEOL_C = 31
+SCE_CSOUND_DEFAULT = 0
+SCE_CSOUND_COMMENT = 1
+SCE_CSOUND_NUMBER = 2
+SCE_CSOUND_OPERATOR = 3
+SCE_CSOUND_INSTR = 4
+SCE_CSOUND_IDENTIFIER = 5
+SCE_CSOUND_OPCODE = 6
+SCE_CSOUND_HEADERSTMT = 7
+SCE_CSOUND_USERKEYWORD = 8
+SCE_CSOUND_COMMENTBLOCK = 9
+SCE_CSOUND_PARAM = 10
+SCE_CSOUND_ARATE_VAR = 11
+SCE_CSOUND_KRATE_VAR = 12
+SCE_CSOUND_IRATE_VAR = 13
+SCE_CSOUND_GLOBAL_VAR = 14
+SCE_CSOUND_STRINGEOL = 15
+SCE_INNO_DEFAULT = 0
+SCE_INNO_COMMENT = 1
+SCE_INNO_KEYWORD = 2
+SCE_INNO_PARAMETER = 3
+SCE_INNO_SECTION = 4
+SCE_INNO_PREPROC = 5
+SCE_INNO_INLINE_EXPANSION = 6
+SCE_INNO_COMMENT_PASCAL = 7
+SCE_INNO_KEYWORD_PASCAL = 8
+SCE_INNO_KEYWORD_USER = 9
+SCE_INNO_STRING_DOUBLE = 10
+SCE_INNO_STRING_SINGLE = 11
+SCE_INNO_IDENTIFIER = 12
+SCE_OPAL_SPACE = 0
+SCE_OPAL_COMMENT_BLOCK = 1
+SCE_OPAL_COMMENT_LINE = 2
+SCE_OPAL_INTEGER = 3
+SCE_OPAL_KEYWORD = 4
+SCE_OPAL_SORT = 5
+SCE_OPAL_STRING = 6
+SCE_OPAL_PAR = 7
+SCE_OPAL_BOOL_CONST = 8
+SCE_OPAL_DEFAULT = 32
+SCE_SPICE_DEFAULT = 0
+SCE_SPICE_IDENTIFIER = 1
+SCE_SPICE_KEYWORD = 2
+SCE_SPICE_KEYWORD2 = 3
+SCE_SPICE_KEYWORD3 = 4
+SCE_SPICE_NUMBER = 5
+SCE_SPICE_DELIMITER = 6
+SCE_SPICE_VALUE = 7
+SCE_SPICE_COMMENTLINE = 8
+SCE_CMAKE_DEFAULT = 0
+SCE_CMAKE_COMMENT = 1
+SCE_CMAKE_STRINGDQ = 2
+SCE_CMAKE_STRINGLQ = 3
+SCE_CMAKE_STRINGRQ = 4
+SCE_CMAKE_COMMANDS = 5
+SCE_CMAKE_PARAMETERS = 6
+SCE_CMAKE_VARIABLE = 7
+SCE_CMAKE_USERDEFINED = 8
+SCE_CMAKE_WHILEDEF = 9
+SCE_CMAKE_FOREACHDEF = 10
+SCE_CMAKE_IFDEFINEDEF = 11
+SCE_CMAKE_MACRODEF = 12
+SCE_CMAKE_STRINGVAR = 13
+SCE_CMAKE_NUMBER = 14
+SCE_GAP_DEFAULT = 0
+SCE_GAP_IDENTIFIER = 1
+SCE_GAP_KEYWORD = 2
+SCE_GAP_KEYWORD2 = 3
+SCE_GAP_KEYWORD3 = 4
+SCE_GAP_KEYWORD4 = 5
+SCE_GAP_STRING = 6
+SCE_GAP_CHAR = 7
+SCE_GAP_OPERATOR = 8
+SCE_GAP_COMMENT = 9
+SCE_GAP_NUMBER = 10
+SCE_GAP_STRINGEOL = 11
+SCE_PLM_DEFAULT = 0
+SCE_PLM_COMMENT = 1
+SCE_PLM_STRING = 2
+SCE_PLM_NUMBER = 3
+SCE_PLM_IDENTIFIER = 4
+SCE_PLM_OPERATOR = 5
+SCE_PLM_CONTROL = 6
+SCE_PLM_KEYWORD = 7
+SCE_ABL_DEFAULT = 0
+SCE_ABL_NUMBER = 1
+SCE_ABL_WORD = 2
+SCE_ABL_STRING = 3
+SCE_ABL_CHARACTER = 4
+SCE_ABL_PREPROCESSOR = 5
+SCE_ABL_OPERATOR = 6
+SCE_ABL_IDENTIFIER = 7
+SCE_ABL_BLOCK = 8
+SCE_ABL_END = 9
+SCE_ABL_COMMENT = 10
+SCE_ABL_TASKMARKER = 11
+SCE_ABL_LINECOMMENT = 12
+SCE_ABAQUS_DEFAULT = 0
+SCE_ABAQUS_COMMENT = 1
+SCE_ABAQUS_COMMENTBLOCK = 2
+SCE_ABAQUS_NUMBER = 3
+SCE_ABAQUS_STRING = 4
+SCE_ABAQUS_OPERATOR = 5
+SCE_ABAQUS_WORD = 6
+SCE_ABAQUS_PROCESSOR = 7
+SCE_ABAQUS_COMMAND = 8
+SCE_ABAQUS_SLASHCOMMAND = 9
+SCE_ABAQUS_STARCOMMAND = 10
+SCE_ABAQUS_ARGUMENT = 11
+SCE_ABAQUS_FUNCTION = 12
+SCE_ASY_DEFAULT = 0
+SCE_ASY_COMMENT = 1
+SCE_ASY_COMMENTLINE = 2
+SCE_ASY_NUMBER = 3
+SCE_ASY_WORD = 4
+SCE_ASY_STRING = 5
+SCE_ASY_CHARACTER = 6
+SCE_ASY_OPERATOR = 7
+SCE_ASY_IDENTIFIER = 8
+SCE_ASY_STRINGEOL = 9
+SCE_ASY_COMMENTLINEDOC = 10
+SCE_ASY_WORD2 = 11
+SCE_R_DEFAULT = 0
+SCE_R_COMMENT = 1
+SCE_R_KWORD = 2
+SCE_R_BASEKWORD = 3
+SCE_R_OTHERKWORD = 4
+SCE_R_NUMBER = 5
+SCE_R_STRING = 6
+SCE_R_STRING2 = 7
+SCE_R_OPERATOR = 8
+SCE_R_IDENTIFIER = 9
+SCE_R_INFIX = 10
+SCE_R_INFIXEOL = 11
+SCE_MAGIK_DEFAULT = 0
+SCE_MAGIK_COMMENT = 1
+SCE_MAGIK_HYPER_COMMENT = 16
+SCE_MAGIK_STRING = 2
+SCE_MAGIK_CHARACTER = 3
+SCE_MAGIK_NUMBER = 4
+SCE_MAGIK_IDENTIFIER = 5
+SCE_MAGIK_OPERATOR = 6
+SCE_MAGIK_FLOW = 7
+SCE_MAGIK_CONTAINER = 8
+SCE_MAGIK_BRACKET_BLOCK = 9
+SCE_MAGIK_BRACE_BLOCK = 10
+SCE_MAGIK_SQBRACKET_BLOCK = 11
+SCE_MAGIK_UNKNOWN_KEYWORD = 12
+SCE_MAGIK_KEYWORD = 13
+SCE_MAGIK_PRAGMA = 14
+SCE_MAGIK_SYMBOL = 15
+SCE_POWERSHELL_DEFAULT = 0
+SCE_POWERSHELL_COMMENT = 1
+SCE_POWERSHELL_STRING = 2
+SCE_POWERSHELL_CHARACTER = 3
+SCE_POWERSHELL_NUMBER = 4
+SCE_POWERSHELL_VARIABLE = 5
+SCE_POWERSHELL_OPERATOR = 6
+SCE_POWERSHELL_IDENTIFIER = 7
+SCE_POWERSHELL_KEYWORD = 8
+SCE_POWERSHELL_CMDLET = 9
+SCE_POWERSHELL_ALIAS = 10
+SCE_POWERSHELL_FUNCTION = 11
+SCE_POWERSHELL_USER1 = 12
+SCE_POWERSHELL_COMMENTSTREAM = 13
+SCE_POWERSHELL_HERE_STRING = 14
+SCE_POWERSHELL_HERE_CHARACTER = 15
+SCE_POWERSHELL_COMMENTDOCKEYWORD = 16
+SCE_MYSQL_DEFAULT = 0
+SCE_MYSQL_COMMENT = 1
+SCE_MYSQL_COMMENTLINE = 2
+SCE_MYSQL_VARIABLE = 3
+SCE_MYSQL_SYSTEMVARIABLE = 4
+SCE_MYSQL_KNOWNSYSTEMVARIABLE = 5
+SCE_MYSQL_NUMBER = 6
+SCE_MYSQL_MAJORKEYWORD = 7
+SCE_MYSQL_KEYWORD = 8
+SCE_MYSQL_DATABASEOBJECT = 9
+SCE_MYSQL_PROCEDUREKEYWORD = 10
+SCE_MYSQL_STRING = 11
+SCE_MYSQL_SQSTRING = 12
+SCE_MYSQL_DQSTRING = 13
+SCE_MYSQL_OPERATOR = 14
+SCE_MYSQL_FUNCTION = 15
+SCE_MYSQL_IDENTIFIER = 16
+SCE_MYSQL_QUOTEDIDENTIFIER = 17
+SCE_MYSQL_USER1 = 18
+SCE_MYSQL_USER2 = 19
+SCE_MYSQL_USER3 = 20
+SCE_MYSQL_HIDDENCOMMAND = 21
+SCE_MYSQL_PLACEHOLDER = 22
+SCE_PO_DEFAULT = 0
+SCE_PO_COMMENT = 1
+SCE_PO_MSGID = 2
+SCE_PO_MSGID_TEXT = 3
+SCE_PO_MSGSTR = 4
+SCE_PO_MSGSTR_TEXT = 5
+SCE_PO_MSGCTXT = 6
+SCE_PO_MSGCTXT_TEXT = 7
+SCE_PO_FUZZY = 8
+SCE_PO_PROGRAMMER_COMMENT = 9
+SCE_PO_REFERENCE = 10
+SCE_PO_FLAGS = 11
+SCE_PO_MSGID_TEXT_EOL = 12
+SCE_PO_MSGSTR_TEXT_EOL = 13
+SCE_PO_MSGCTXT_TEXT_EOL = 14
+SCE_PO_ERROR = 15
+SCE_PAS_DEFAULT = 0
+SCE_PAS_IDENTIFIER = 1
+SCE_PAS_COMMENT = 2
+SCE_PAS_COMMENT2 = 3
+SCE_PAS_COMMENTLINE = 4
+SCE_PAS_PREPROCESSOR = 5
+SCE_PAS_PREPROCESSOR2 = 6
+SCE_PAS_NUMBER = 7
+SCE_PAS_HEXNUMBER = 8
+SCE_PAS_WORD = 9
+SCE_PAS_STRING = 10
+SCE_PAS_STRINGEOL = 11
+SCE_PAS_CHARACTER = 12
+SCE_PAS_OPERATOR = 13
+SCE_PAS_ASM = 14
+SCE_SORCUS_DEFAULT = 0
+SCE_SORCUS_COMMAND = 1
+SCE_SORCUS_PARAMETER = 2
+SCE_SORCUS_COMMENTLINE = 3
+SCE_SORCUS_STRING = 4
+SCE_SORCUS_STRINGEOL = 5
+SCE_SORCUS_IDENTIFIER = 6
+SCE_SORCUS_OPERATOR = 7
+SCE_SORCUS_NUMBER = 8
+SCE_SORCUS_CONSTANT = 9
+SCE_POWERPRO_DEFAULT = 0
+SCE_POWERPRO_COMMENTBLOCK = 1
+SCE_POWERPRO_COMMENTLINE = 2
+SCE_POWERPRO_NUMBER = 3
+SCE_POWERPRO_WORD = 4
+SCE_POWERPRO_WORD2 = 5
+SCE_POWERPRO_WORD3 = 6
+SCE_POWERPRO_WORD4 = 7
+SCE_POWERPRO_DOUBLEQUOTEDSTRING = 8
+SCE_POWERPRO_SINGLEQUOTEDSTRING = 9
+SCE_POWERPRO_LINECONTINUE = 10
+SCE_POWERPRO_OPERATOR = 11
+SCE_POWERPRO_IDENTIFIER = 12
+SCE_POWERPRO_STRINGEOL = 13
+SCE_POWERPRO_VERBATIM = 14
+SCE_POWERPRO_ALTQUOTE = 15
+SCE_POWERPRO_FUNCTION = 16
+SCE_SML_DEFAULT = 0
+SCE_SML_IDENTIFIER = 1
+SCE_SML_TAGNAME = 2
+SCE_SML_KEYWORD = 3
+SCE_SML_KEYWORD2 = 4
+SCE_SML_KEYWORD3 = 5
+SCE_SML_LINENUM = 6
+SCE_SML_OPERATOR = 7
+SCE_SML_NUMBER = 8
+SCE_SML_CHAR = 9
+SCE_SML_STRING = 11
+SCE_SML_COMMENT = 12
+SCE_SML_COMMENT1 = 13
+SCE_SML_COMMENT2 = 14
+SCE_SML_COMMENT3 = 15
+SCE_MARKDOWN_DEFAULT = 0
+SCE_MARKDOWN_LINE_BEGIN = 1
+SCE_MARKDOWN_STRONG1 = 2
+SCE_MARKDOWN_STRONG2 = 3
+SCE_MARKDOWN_EM1 = 4
+SCE_MARKDOWN_EM2 = 5
+SCE_MARKDOWN_HEADER1 = 6
+SCE_MARKDOWN_HEADER2 = 7
+SCE_MARKDOWN_HEADER3 = 8
+SCE_MARKDOWN_HEADER4 = 9
+SCE_MARKDOWN_HEADER5 = 10
+SCE_MARKDOWN_HEADER6 = 11
+SCE_MARKDOWN_PRECHAR = 12
+SCE_MARKDOWN_ULIST_ITEM = 13
+SCE_MARKDOWN_OLIST_ITEM = 14
+SCE_MARKDOWN_BLOCKQUOTE = 15
+SCE_MARKDOWN_STRIKEOUT = 16
+SCE_MARKDOWN_HRULE = 17
+SCE_MARKDOWN_LINK = 18
+SCE_MARKDOWN_CODE = 19
+SCE_MARKDOWN_CODE2 = 20
+SCE_MARKDOWN_CODEBK = 21
+SCE_TXT2TAGS_DEFAULT = 0
+SCE_TXT2TAGS_LINE_BEGIN = 1
+SCE_TXT2TAGS_STRONG1 = 2
+SCE_TXT2TAGS_STRONG2 = 3
+SCE_TXT2TAGS_EM1 = 4
+SCE_TXT2TAGS_EM2 = 5
+SCE_TXT2TAGS_HEADER1 = 6
+SCE_TXT2TAGS_HEADER2 = 7
+SCE_TXT2TAGS_HEADER3 = 8
+SCE_TXT2TAGS_HEADER4 = 9
+SCE_TXT2TAGS_HEADER5 = 10
+SCE_TXT2TAGS_HEADER6 = 11
+SCE_TXT2TAGS_PRECHAR = 12
+SCE_TXT2TAGS_ULIST_ITEM = 13
+SCE_TXT2TAGS_OLIST_ITEM = 14
+SCE_TXT2TAGS_BLOCKQUOTE = 15
+SCE_TXT2TAGS_STRIKEOUT = 16
+SCE_TXT2TAGS_HRULE = 17
+SCE_TXT2TAGS_LINK = 18
+SCE_TXT2TAGS_CODE = 19
+SCE_TXT2TAGS_CODE2 = 20
+SCE_TXT2TAGS_CODEBK = 21
+SCE_TXT2TAGS_COMMENT = 22
+SCE_TXT2TAGS_OPTION = 23
+SCE_TXT2TAGS_PREPROC = 24
+SCE_TXT2TAGS_POSTPROC = 25
+SCE_A68K_DEFAULT = 0
+SCE_A68K_COMMENT = 1
+SCE_A68K_NUMBER_DEC = 2
+SCE_A68K_NUMBER_BIN = 3
+SCE_A68K_NUMBER_HEX = 4
+SCE_A68K_STRING1 = 5
+SCE_A68K_OPERATOR = 6
+SCE_A68K_CPUINSTRUCTION = 7
+SCE_A68K_EXTINSTRUCTION = 8
+SCE_A68K_REGISTER = 9
+SCE_A68K_DIRECTIVE = 10
+SCE_A68K_MACRO_ARG = 11
+SCE_A68K_LABEL = 12
+SCE_A68K_STRING2 = 13
+SCE_A68K_IDENTIFIER = 14
+SCE_A68K_MACRO_DECLARATION = 15
+SCE_A68K_COMMENT_WORD = 16
+SCE_A68K_COMMENT_SPECIAL = 17
+SCE_A68K_COMMENT_DOXYGEN = 18
+SCE_MODULA_DEFAULT = 0
+SCE_MODULA_COMMENT = 1
+SCE_MODULA_DOXYCOMM = 2
+SCE_MODULA_DOXYKEY = 3
+SCE_MODULA_KEYWORD = 4
+SCE_MODULA_RESERVED = 5
+SCE_MODULA_NUMBER = 6
+SCE_MODULA_BASENUM = 7
+SCE_MODULA_FLOAT = 8
+SCE_MODULA_STRING = 9
+SCE_MODULA_STRSPEC = 10
+SCE_MODULA_CHAR = 11
+SCE_MODULA_CHARSPEC = 12
+SCE_MODULA_PROC = 13
+SCE_MODULA_PRAGMA = 14
+SCE_MODULA_PRGKEY = 15
+SCE_MODULA_OPERATOR = 16
+SCE_MODULA_BADSTR = 17
+SCE_COFFEESCRIPT_DEFAULT = 0
+SCE_COFFEESCRIPT_COMMENT = 1
+SCE_COFFEESCRIPT_COMMENTLINE = 2
+SCE_COFFEESCRIPT_COMMENTDOC = 3
+SCE_COFFEESCRIPT_NUMBER = 4
+SCE_COFFEESCRIPT_WORD = 5
+SCE_COFFEESCRIPT_STRING = 6
+SCE_COFFEESCRIPT_CHARACTER = 7
+SCE_COFFEESCRIPT_UUID = 8
+SCE_COFFEESCRIPT_PREPROCESSOR = 9
+SCE_COFFEESCRIPT_OPERATOR = 10
+SCE_COFFEESCRIPT_IDENTIFIER = 11
+SCE_COFFEESCRIPT_STRINGEOL = 12
+SCE_COFFEESCRIPT_VERBATIM = 13
+SCE_COFFEESCRIPT_REGEX = 14
+SCE_COFFEESCRIPT_COMMENTLINEDOC = 15
+SCE_COFFEESCRIPT_WORD2 = 16
+SCE_COFFEESCRIPT_COMMENTDOCKEYWORD = 17
+SCE_COFFEESCRIPT_COMMENTDOCKEYWORDERROR = 18
+SCE_COFFEESCRIPT_GLOBALCLASS = 19
+SCE_COFFEESCRIPT_STRINGRAW = 20
+SCE_COFFEESCRIPT_TRIPLEVERBATIM = 21
+SCE_COFFEESCRIPT_COMMENTBLOCK = 22
+SCE_COFFEESCRIPT_VERBOSE_REGEX = 23
+SCE_COFFEESCRIPT_VERBOSE_REGEX_COMMENT = 24
+SCE_COFFEESCRIPT_INSTANCEPROPERTY = 25
+SCE_AVS_DEFAULT = 0
+SCE_AVS_COMMENTBLOCK = 1
+SCE_AVS_COMMENTBLOCKN = 2
+SCE_AVS_COMMENTLINE = 3
+SCE_AVS_NUMBER = 4
+SCE_AVS_OPERATOR = 5
+SCE_AVS_IDENTIFIER = 6
+SCE_AVS_STRING = 7
+SCE_AVS_TRIPLESTRING = 8
+SCE_AVS_KEYWORD = 9
+SCE_AVS_FILTER = 10
+SCE_AVS_PLUGIN = 11
+SCE_AVS_FUNCTION = 12
+SCE_AVS_CLIPPROP = 13
+SCE_AVS_USERDFN = 14
+SCE_ECL_DEFAULT = 0
+SCE_ECL_COMMENT = 1
+SCE_ECL_COMMENTLINE = 2
+SCE_ECL_NUMBER = 3
+SCE_ECL_STRING = 4
+SCE_ECL_WORD0 = 5
+SCE_ECL_OPERATOR = 6
+SCE_ECL_CHARACTER = 7
+SCE_ECL_UUID = 8
+SCE_ECL_PREPROCESSOR = 9
+SCE_ECL_UNKNOWN = 10
+SCE_ECL_IDENTIFIER = 11
+SCE_ECL_STRINGEOL = 12
+SCE_ECL_VERBATIM = 13
+SCE_ECL_REGEX = 14
+SCE_ECL_COMMENTLINEDOC = 15
+SCE_ECL_WORD1 = 16
+SCE_ECL_COMMENTDOCKEYWORD = 17
+SCE_ECL_COMMENTDOCKEYWORDERROR = 18
+SCE_ECL_WORD2 = 19
+SCE_ECL_WORD3 = 20
+SCE_ECL_WORD4 = 21
+SCE_ECL_WORD5 = 22
+SCE_ECL_COMMENTDOC = 23
+SCE_ECL_ADDED = 24
+SCE_ECL_DELETED = 25
+SCE_ECL_CHANGED = 26
+SCE_ECL_MOVED = 27
+SCE_OSCRIPT_DEFAULT = 0
+SCE_OSCRIPT_LINE_COMMENT = 1
+SCE_OSCRIPT_BLOCK_COMMENT = 2
+SCE_OSCRIPT_DOC_COMMENT = 3
+SCE_OSCRIPT_PREPROCESSOR = 4
+SCE_OSCRIPT_NUMBER = 5
+SCE_OSCRIPT_SINGLEQUOTE_STRING = 6
+SCE_OSCRIPT_DOUBLEQUOTE_STRING = 7
+SCE_OSCRIPT_CONSTANT = 8
+SCE_OSCRIPT_IDENTIFIER = 9
+SCE_OSCRIPT_GLOBAL = 10
+SCE_OSCRIPT_KEYWORD = 11
+SCE_OSCRIPT_OPERATOR = 12
+SCE_OSCRIPT_LABEL = 13
+SCE_OSCRIPT_TYPE = 14
+SCE_OSCRIPT_FUNCTION = 15
+SCE_OSCRIPT_OBJECT = 16
+SCE_OSCRIPT_PROPERTY = 17
+SCE_OSCRIPT_METHOD = 18
+SCE_VISUALPROLOG_DEFAULT = 0
+SCE_VISUALPROLOG_KEY_MAJOR = 1
+SCE_VISUALPROLOG_KEY_MINOR = 2
+SCE_VISUALPROLOG_KEY_DIRECTIVE = 3
+SCE_VISUALPROLOG_COMMENT_BLOCK = 4
+SCE_VISUALPROLOG_COMMENT_LINE = 5
+SCE_VISUALPROLOG_COMMENT_KEY = 6
+SCE_VISUALPROLOG_COMMENT_KEY_ERROR = 7
+SCE_VISUALPROLOG_IDENTIFIER = 8
+SCE_VISUALPROLOG_VARIABLE = 9
+SCE_VISUALPROLOG_ANONYMOUS = 10
+SCE_VISUALPROLOG_NUMBER = 11
+SCE_VISUALPROLOG_OPERATOR = 12
+SCE_VISUALPROLOG_CHARACTER = 13
+SCE_VISUALPROLOG_CHARACTER_TOO_MANY = 14
+SCE_VISUALPROLOG_CHARACTER_ESCAPE_ERROR = 15
+SCE_VISUALPROLOG_STRING = 16
+SCE_VISUALPROLOG_STRING_ESCAPE = 17
+SCE_VISUALPROLOG_STRING_ESCAPE_ERROR = 18
+SCE_VISUALPROLOG_STRING_EOL_OPEN = 19
+SCE_VISUALPROLOG_STRING_VERBATIM = 20
+SCE_VISUALPROLOG_STRING_VERBATIM_SPECIAL = 21
+SCE_VISUALPROLOG_STRING_VERBATIM_EOL = 22
+SCE_STTXT_DEFAULT = 0
+SCE_STTXT_COMMENT = 1
+SCE_STTXT_COMMENTLINE = 2
+SCE_STTXT_KEYWORD = 3
+SCE_STTXT_TYPE = 4
+SCE_STTXT_FUNCTION = 5
+SCE_STTXT_FB = 6
+SCE_STTXT_NUMBER = 7
+SCE_STTXT_HEXNUMBER = 8
+SCE_STTXT_PRAGMA = 9
+SCE_STTXT_OPERATOR = 10
+SCE_STTXT_CHARACTER = 11
+SCE_STTXT_STRING1 = 12
+SCE_STTXT_STRING2 = 13
+SCE_STTXT_STRINGEOL = 14
+SCE_STTXT_IDENTIFIER = 15
+SCE_STTXT_DATETIME = 16
+SCE_STTXT_VARS = 17
+SCE_STTXT_PRAGMAS = 18
+SCE_KVIRC_DEFAULT = 0
+SCE_KVIRC_COMMENT = 1
+SCE_KVIRC_COMMENTBLOCK = 2
+SCE_KVIRC_STRING = 3
+SCE_KVIRC_WORD = 4
+SCE_KVIRC_KEYWORD = 5
+SCE_KVIRC_FUNCTION_KEYWORD = 6
+SCE_KVIRC_FUNCTION = 7
+SCE_KVIRC_VARIABLE = 8
+SCE_KVIRC_NUMBER = 9
+SCE_KVIRC_OPERATOR = 10
+SCE_KVIRC_STRING_FUNCTION = 11
+SCE_KVIRC_STRING_VARIABLE = 12
+SCE_RUST_DEFAULT = 0
+SCE_RUST_COMMENTBLOCK = 1
+SCE_RUST_COMMENTLINE = 2
+SCE_RUST_COMMENTBLOCKDOC = 3
+SCE_RUST_COMMENTLINEDOC = 4
+SCE_RUST_NUMBER = 5
+SCE_RUST_WORD = 6
+SCE_RUST_WORD2 = 7
+SCE_RUST_WORD3 = 8
+SCE_RUST_WORD4 = 9
+SCE_RUST_WORD5 = 10
+SCE_RUST_WORD6 = 11
+SCE_RUST_WORD7 = 12
+SCE_RUST_STRING = 13
+SCE_RUST_STRINGR = 14
+SCE_RUST_CHARACTER = 15
+SCE_RUST_OPERATOR = 16
+SCE_RUST_IDENTIFIER = 17
+SCE_RUST_LIFETIME = 18
+SCE_RUST_MACRO = 19
+SCE_RUST_LEXERROR = 20
+SCE_RUST_BYTESTRING = 21
+SCE_RUST_BYTESTRINGR = 22
+SCE_RUST_BYTECHARACTER = 23
+SCE_DMAP_DEFAULT = 0
+SCE_DMAP_COMMENT = 1
+SCE_DMAP_NUMBER = 2
+SCE_DMAP_STRING1 = 3
+SCE_DMAP_STRING2 = 4
+SCE_DMAP_STRINGEOL = 5
+SCE_DMAP_OPERATOR = 6
+SCE_DMAP_IDENTIFIER = 7
+SCE_DMAP_WORD = 8
+SCE_DMAP_WORD2 = 9
+SCE_DMAP_WORD3 = 10
+SCE_DMIS_DEFAULT = 0
+SCE_DMIS_COMMENT = 1
+SCE_DMIS_STRING = 2
+SCE_DMIS_NUMBER = 3
+SCE_DMIS_KEYWORD = 4
+SCE_DMIS_MAJORWORD = 5
+SCE_DMIS_MINORWORD = 6
+SCE_DMIS_UNSUPPORTED_MAJOR = 7
+SCE_DMIS_UNSUPPORTED_MINOR = 8
+SCE_DMIS_LABEL = 9
+SCE_REG_DEFAULT = 0
+SCE_REG_COMMENT = 1
+SCE_REG_VALUENAME = 2
+SCE_REG_STRING = 3
+SCE_REG_HEXDIGIT = 4
+SCE_REG_VALUETYPE = 5
+SCE_REG_ADDEDKEY = 6
+SCE_REG_DELETEDKEY = 7
+SCE_REG_ESCAPED = 8
+SCE_REG_KEYPATH_GUID = 9
+SCE_REG_STRING_GUID = 10
+SCE_REG_PARAMETER = 11
+SCE_REG_OPERATOR = 12
+SCE_BIBTEX_DEFAULT = 0
+SCE_BIBTEX_ENTRY = 1
+SCE_BIBTEX_UNKNOWN_ENTRY = 2
+SCE_BIBTEX_KEY = 3
+SCE_BIBTEX_PARAMETER = 4
+SCE_BIBTEX_VALUE = 5
+SCE_BIBTEX_COMMENT = 6
+SCE_HEX_DEFAULT = 0
+SCE_HEX_RECSTART = 1
+SCE_HEX_RECTYPE = 2
+SCE_HEX_RECTYPE_UNKNOWN = 3
+SCE_HEX_BYTECOUNT = 4
+SCE_HEX_BYTECOUNT_WRONG = 5
+SCE_HEX_NOADDRESS = 6
+SCE_HEX_DATAADDRESS = 7
+SCE_HEX_RECCOUNT = 8
+SCE_HEX_STARTADDRESS = 9
+SCE_HEX_ADDRESSFIELD_UNKNOWN = 10
+SCE_HEX_EXTENDEDADDRESS = 11
+SCE_HEX_DATA_ODD = 12
+SCE_HEX_DATA_EVEN = 13
+SCE_HEX_DATA_UNKNOWN = 14
+SCE_HEX_DATA_EMPTY = 15
+SCE_HEX_CHECKSUM = 16
+SCE_HEX_CHECKSUM_WRONG = 17
+SCE_HEX_GARBAGE = 18
+SCE_JSON_DEFAULT = 0
+SCE_JSON_NUMBER = 1
+SCE_JSON_STRING = 2
+SCE_JSON_STRINGEOL = 3
+SCE_JSON_PROPERTYNAME = 4
+SCE_JSON_ESCAPESEQUENCE = 5
+SCE_JSON_LINECOMMENT = 6
+SCE_JSON_BLOCKCOMMENT = 7
+SCE_JSON_OPERATOR = 8
+SCE_JSON_URI = 9
+SCE_JSON_COMPACTIRI = 10
+SCE_JSON_KEYWORD = 11
+SCE_JSON_LDKEYWORD = 12
+SCE_JSON_ERROR = 13
+SCE_EDI_DEFAULT = 0
+SCE_EDI_SEGMENTSTART = 1
+SCE_EDI_SEGMENTEND = 2
+SCE_EDI_SEP_ELEMENT = 3
+SCE_EDI_SEP_COMPOSITE = 4
+SCE_EDI_SEP_RELEASE = 5
+SCE_EDI_UNA = 6
+SCE_EDI_UNH = 7
+SCE_EDI_BADSEGMENT = 8
+SCE_STATA_DEFAULT = 0
+SCE_STATA_COMMENT = 1
+SCE_STATA_COMMENTLINE = 2
+SCE_STATA_COMMENTBLOCK = 3
+SCE_STATA_NUMBER = 4
+SCE_STATA_OPERATOR = 5
+SCE_STATA_IDENTIFIER = 6
+SCE_STATA_STRING = 7
+SCE_STATA_TYPE = 8
+SCE_STATA_WORD = 9
+SCE_STATA_GLOBAL_MACRO = 10
+SCE_STATA_MACRO = 11
+SCE_SAS_DEFAULT = 0
+SCE_SAS_COMMENT = 1
+SCE_SAS_COMMENTLINE = 2
+SCE_SAS_COMMENTBLOCK = 3
+SCE_SAS_NUMBER = 4
+SCE_SAS_OPERATOR = 5
+SCE_SAS_IDENTIFIER = 6
+SCE_SAS_STRING = 7
+SCE_SAS_TYPE = 8
+SCE_SAS_WORD = 9
+SCE_SAS_GLOBAL_MACRO = 10
+SCE_SAS_MACRO = 11
+SCE_SAS_MACRO_KEYWORD = 12
+SCE_SAS_BLOCK_KEYWORD = 13
+SCE_SAS_MACRO_FUNCTION = 14
+SCE_SAS_STATEMENT = 15
+SCE_NIM_DEFAULT = 0
+SCE_NIM_COMMENT = 1
+SCE_NIM_COMMENTDOC = 2
+SCE_NIM_COMMENTLINE = 3
+SCE_NIM_COMMENTLINEDOC = 4
+SCE_NIM_NUMBER = 5
+SCE_NIM_STRING = 6
+SCE_NIM_CHARACTER = 7
+SCE_NIM_WORD = 8
+SCE_NIM_TRIPLE = 9
+SCE_NIM_TRIPLEDOUBLE = 10
+SCE_NIM_BACKTICKS = 11
+SCE_NIM_FUNCNAME = 12
+SCE_NIM_STRINGEOL = 13
+SCE_NIM_NUMERROR = 14
+SCE_NIM_OPERATOR = 15
+SCE_NIM_IDENTIFIER = 16
+SCE_CIL_DEFAULT = 0
+SCE_CIL_COMMENT = 1
+SCE_CIL_COMMENTLINE = 2
+SCE_CIL_WORD = 3
+SCE_CIL_WORD2 = 4
+SCE_CIL_WORD3 = 5
+SCE_CIL_STRING = 6
+SCE_CIL_LABEL = 7
+SCE_CIL_OPERATOR = 8
+SCE_CIL_IDENTIFIER = 9
+SCE_CIL_STRINGEOL = 10
+SCE_X12_DEFAULT = 0
+SCE_X12_BAD = 1
+SCE_X12_ENVELOPE = 2
+SCE_X12_FUNCTIONGROUP = 3
+SCE_X12_TRANSACTIONSET = 4
+SCE_X12_SEGMENTHEADER = 5
+SCE_X12_SEGMENTEND = 6
+SCE_X12_SEP_ELEMENT = 7
+SCE_X12_SEP_SUBELEMENT = 8
+SCE_DF_DEFAULT = 0
+SCE_DF_IDENTIFIER = 1
+SCE_DF_METATAG = 2
+SCE_DF_IMAGE = 3
+SCE_DF_COMMENTLINE = 4
+SCE_DF_PREPROCESSOR = 5
+SCE_DF_PREPROCESSOR2 = 6
+SCE_DF_NUMBER = 7
+SCE_DF_HEXNUMBER = 8
+SCE_DF_WORD = 9
+SCE_DF_STRING = 10
+SCE_DF_STRINGEOL = 11
+SCE_DF_SCOPEWORD = 12
+SCE_DF_OPERATOR = 13
+SCE_DF_ICODE = 14
+SCE_HOLLYWOOD_DEFAULT = 0
+SCE_HOLLYWOOD_COMMENT = 1
+SCE_HOLLYWOOD_COMMENTBLOCK = 2
+SCE_HOLLYWOOD_NUMBER = 3
+SCE_HOLLYWOOD_KEYWORD = 4
+SCE_HOLLYWOOD_STDAPI = 5
+SCE_HOLLYWOOD_PLUGINAPI = 6
+SCE_HOLLYWOOD_PLUGINMETHOD = 7
+SCE_HOLLYWOOD_STRING = 8
+SCE_HOLLYWOOD_STRINGBLOCK = 9
+SCE_HOLLYWOOD_PREPROCESSOR = 10
+SCE_HOLLYWOOD_OPERATOR = 11
+SCE_HOLLYWOOD_IDENTIFIER = 12
+SCE_HOLLYWOOD_CONSTANT = 13
+SCE_HOLLYWOOD_HEXNUMBER = 14
+SCE_RAKU_DEFAULT = 0
+SCE_RAKU_ERROR = 1
+SCE_RAKU_COMMENTLINE = 2
+SCE_RAKU_COMMENTEMBED = 3
+SCE_RAKU_POD = 4
+SCE_RAKU_CHARACTER = 5
+SCE_RAKU_HEREDOC_Q = 6
+SCE_RAKU_HEREDOC_QQ = 7
+SCE_RAKU_STRING = 8
+SCE_RAKU_STRING_Q = 9
+SCE_RAKU_STRING_QQ = 10
+SCE_RAKU_STRING_Q_LANG = 11
+SCE_RAKU_STRING_VAR = 12
+SCE_RAKU_REGEX = 13
+SCE_RAKU_REGEX_VAR = 14
+SCE_RAKU_ADVERB = 15
+SCE_RAKU_NUMBER = 16
+SCE_RAKU_PREPROCESSOR = 17
+SCE_RAKU_OPERATOR = 18
+SCE_RAKU_WORD = 19
+SCE_RAKU_FUNCTION = 20
+SCE_RAKU_IDENTIFIER = 21
+SCE_RAKU_TYPEDEF = 22
+SCE_RAKU_MU = 23
+SCE_RAKU_POSITIONAL = 24
+SCE_RAKU_ASSOCIATIVE = 25
+SCE_RAKU_CALLABLE = 26
+SCE_RAKU_GRAMMAR = 27
+SCE_RAKU_CLASS = 28
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/view.py b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/view.py
new file mode 100644
index 0000000000000000000000000000000000000000..05f1534214213dfbc1124a74b1b24e7aed767251
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/scintilla/view.py
@@ -0,0 +1,841 @@
+# A general purpose MFC CCtrlView view that uses Scintilla.
+
+import os
+import re
+import string
+import struct
+import sys
+
+import __main__ # for attribute lookup
+import win32con
+import win32ui
+from pywin.mfc import afxres, docview
+
+from . import (
+ IDLEenvironment, # nopycln: import # Injects fast_readline into the IDLE auto-indent extension
+ bindings,
+ control,
+ scintillacon,
+)
+
+PRINTDLGORD = 1538
+IDC_PRINT_MAG_EDIT = 1010
+EM_FORMATRANGE = win32con.WM_USER + 57
+
+wordbreaks = "._" + string.ascii_uppercase + string.ascii_lowercase + string.digits
+
+patImport = re.compile(r"import (?P.*)")
+
+_event_commands = [
+ # File menu
+ "win32ui.ID_FILE_LOCATE",
+ "win32ui.ID_FILE_CHECK",
+ "afxres.ID_FILE_CLOSE",
+ "afxres.ID_FILE_NEW",
+ "afxres.ID_FILE_OPEN",
+ "afxres.ID_FILE_SAVE",
+ "afxres.ID_FILE_SAVE_AS",
+ "win32ui.ID_FILE_SAVE_ALL",
+ # Edit menu
+ "afxres.ID_EDIT_UNDO",
+ "afxres.ID_EDIT_REDO",
+ "afxres.ID_EDIT_CUT",
+ "afxres.ID_EDIT_COPY",
+ "afxres.ID_EDIT_PASTE",
+ "afxres.ID_EDIT_SELECT_ALL",
+ "afxres.ID_EDIT_FIND",
+ "afxres.ID_EDIT_REPEAT",
+ "afxres.ID_EDIT_REPLACE",
+ # View menu
+ "win32ui.ID_VIEW_WHITESPACE",
+ "win32ui.ID_VIEW_FIXED_FONT",
+ "win32ui.ID_VIEW_BROWSE",
+ "win32ui.ID_VIEW_INTERACTIVE",
+ # Window menu
+ "afxres.ID_WINDOW_ARRANGE",
+ "afxres.ID_WINDOW_CASCADE",
+ "afxres.ID_WINDOW_NEW",
+ "afxres.ID_WINDOW_SPLIT",
+ "afxres.ID_WINDOW_TILE_HORZ",
+ "afxres.ID_WINDOW_TILE_VERT",
+ # Others
+ "afxres.ID_APP_EXIT",
+ "afxres.ID_APP_ABOUT",
+]
+
+_extra_event_commands = [
+ ("EditDelete", afxres.ID_EDIT_CLEAR),
+ ("LocateModule", win32ui.ID_FILE_LOCATE),
+ ("GotoLine", win32ui.ID_EDIT_GOTO_LINE),
+ ("DbgBreakpointToggle", win32ui.IDC_DBG_ADD),
+ ("DbgGo", win32ui.IDC_DBG_GO),
+ ("DbgStepOver", win32ui.IDC_DBG_STEPOVER),
+ ("DbgStep", win32ui.IDC_DBG_STEP),
+ ("DbgStepOut", win32ui.IDC_DBG_STEPOUT),
+ ("DbgBreakpointClearAll", win32ui.IDC_DBG_CLEAR),
+ ("DbgClose", win32ui.IDC_DBG_CLOSE),
+]
+
+event_commands = []
+
+
+def _CreateEvents():
+ for name in _event_commands:
+ val = eval(name)
+ name_parts = name.split("_")[1:]
+ name_parts = [p.capitalize() for p in name_parts]
+ event = "".join(name_parts)
+ event_commands.append((event, val))
+ for name, id in _extra_event_commands:
+ event_commands.append((name, id))
+
+
+_CreateEvents()
+del _event_commands
+del _extra_event_commands
+
+command_reflectors = [
+ (win32ui.ID_EDIT_UNDO, win32con.WM_UNDO),
+ (win32ui.ID_EDIT_REDO, scintillacon.SCI_REDO),
+ (win32ui.ID_EDIT_CUT, win32con.WM_CUT),
+ (win32ui.ID_EDIT_COPY, win32con.WM_COPY),
+ (win32ui.ID_EDIT_PASTE, win32con.WM_PASTE),
+ (win32ui.ID_EDIT_CLEAR, win32con.WM_CLEAR),
+ (win32ui.ID_EDIT_SELECT_ALL, scintillacon.SCI_SELECTALL),
+]
+
+
+def DoBraceMatch(control):
+ curPos = control.SCIGetCurrentPos()
+ charBefore = " "
+ if curPos:
+ charBefore = control.SCIGetCharAt(curPos - 1)
+ charAt = control.SCIGetCharAt(curPos)
+ braceAtPos = braceOpposite = -1
+ if charBefore in "[](){}":
+ braceAtPos = curPos - 1
+ if braceAtPos == -1:
+ if charAt in "[](){}":
+ braceAtPos = curPos
+ if braceAtPos != -1:
+ braceOpposite = control.SCIBraceMatch(braceAtPos, 0)
+ if braceAtPos != -1 and braceOpposite == -1:
+ control.SCIBraceBadHighlight(braceAtPos)
+ else:
+ # either clear them both or set them both.
+ control.SCIBraceHighlight(braceAtPos, braceOpposite)
+
+
+def _get_class_attributes(ob):
+ # Recurse into base classes looking for attributes
+ items = []
+ try:
+ items.extend(dir(ob))
+ for i in ob.__bases__:
+ for item in _get_class_attributes(i):
+ if item not in items:
+ items.append(item)
+ except AttributeError:
+ pass
+ return items
+
+
+# Supposed to look like an MFC CEditView, but
+# also supports IDLE extensions and other source code generic features.
+class CScintillaView(docview.CtrlView, control.CScintillaColorEditInterface):
+ def __init__(self, doc):
+ docview.CtrlView.__init__(
+ self,
+ doc,
+ "Scintilla",
+ win32con.WS_CHILD
+ | win32con.WS_VSCROLL
+ | win32con.WS_HSCROLL
+ | win32con.WS_CLIPCHILDREN
+ | win32con.WS_VISIBLE,
+ )
+ self._tabWidth = (
+ 8 # Mirror of what we send to Scintilla - never change this directly
+ )
+ self.bAutoCompleteAttributes = 1
+ self.bShowCallTips = 1
+ self.bMatchBraces = 0 # Editor option will default this to true later!
+ self.bindings = bindings.BindingsManager(self)
+
+ self.idle = IDLEenvironment.IDLEEditorWindow(self)
+ self.idle.IDLEExtension("AutoExpand")
+ # SendScintilla is called so frequently it is worth optimizing.
+ self.SendScintilla = self._obj_.SendMessage
+
+ def _MakeColorizer(self):
+ ext = os.path.splitext(self.GetDocument().GetPathName())[1]
+ from . import formatter
+
+ return formatter.BuiltinPythonSourceFormatter(self, ext)
+
+ # def SendScintilla(self, msg, w=0, l=0):
+ # return self._obj_.SendMessage(msg, w, l)
+
+ def SCISetTabWidth(self, width):
+ # I need to remember the tab-width for the AutoIndent extension. This may go.
+ self._tabWidth = width
+ control.CScintillaEditInterface.SCISetTabWidth(self, width)
+
+ def GetTabWidth(self):
+ return self._tabWidth
+
+ def HookHandlers(self):
+ # Create events for all the menu names.
+ for name, val in event_commands:
+ # handler = lambda id, code, tosend=val, parent=parent: parent.OnCommand(tosend, 0) and 0
+ self.bindings.bind(name, None, cid=val)
+
+ # Hook commands that do nothing other than send Scintilla messages.
+ for command, reflection in command_reflectors:
+ handler = (
+ lambda id, code, ss=self.SendScintilla, tosend=reflection: ss(tosend)
+ and 0
+ )
+ self.HookCommand(handler, command)
+
+ self.HookCommand(self.OnCmdViewWS, win32ui.ID_VIEW_WHITESPACE)
+ self.HookCommandUpdate(self.OnUpdateViewWS, win32ui.ID_VIEW_WHITESPACE)
+ self.HookCommand(
+ self.OnCmdViewIndentationGuides, win32ui.ID_VIEW_INDENTATIONGUIDES
+ )
+ self.HookCommandUpdate(
+ self.OnUpdateViewIndentationGuides, win32ui.ID_VIEW_INDENTATIONGUIDES
+ )
+ self.HookCommand(self.OnCmdViewRightEdge, win32ui.ID_VIEW_RIGHT_EDGE)
+ self.HookCommandUpdate(self.OnUpdateViewRightEdge, win32ui.ID_VIEW_RIGHT_EDGE)
+ self.HookCommand(self.OnCmdViewEOL, win32ui.ID_VIEW_EOL)
+ self.HookCommandUpdate(self.OnUpdateViewEOL, win32ui.ID_VIEW_EOL)
+ self.HookCommand(self.OnCmdViewFixedFont, win32ui.ID_VIEW_FIXED_FONT)
+ self.HookCommandUpdate(self.OnUpdateViewFixedFont, win32ui.ID_VIEW_FIXED_FONT)
+ self.HookCommand(self.OnCmdFileLocate, win32ui.ID_FILE_LOCATE)
+ self.HookCommand(self.OnCmdEditFind, win32ui.ID_EDIT_FIND)
+ self.HookCommand(self.OnCmdEditRepeat, win32ui.ID_EDIT_REPEAT)
+ self.HookCommand(self.OnCmdEditReplace, win32ui.ID_EDIT_REPLACE)
+ self.HookCommand(self.OnCmdGotoLine, win32ui.ID_EDIT_GOTO_LINE)
+ self.HookCommand(self.OnFilePrint, afxres.ID_FILE_PRINT)
+ self.HookCommand(self.OnFilePrint, afxres.ID_FILE_PRINT_DIRECT)
+ self.HookCommand(self.OnFilePrintPreview, win32ui.ID_FILE_PRINT_PREVIEW)
+ # Key bindings.
+ self.HookMessage(self.OnKeyDown, win32con.WM_KEYDOWN)
+ self.HookMessage(self.OnKeyDown, win32con.WM_SYSKEYDOWN)
+ # Hook wheeley mouse events
+ # self.HookMessage(self.OnMouseWheel, win32con.WM_MOUSEWHEEL)
+ self.HookFormatter()
+
+ def OnInitialUpdate(self):
+ doc = self.GetDocument()
+
+ # Enable Unicode
+ self.SendScintilla(scintillacon.SCI_SETCODEPAGE, scintillacon.SC_CP_UTF8, 0)
+ self.SendScintilla(scintillacon.SCI_SETKEYSUNICODE, 1, 0)
+
+ # Create margins
+ self.SendScintilla(
+ scintillacon.SCI_SETMARGINTYPEN, 1, scintillacon.SC_MARGIN_SYMBOL
+ )
+ self.SendScintilla(scintillacon.SCI_SETMARGINMASKN, 1, 0xF)
+ self.SendScintilla(
+ scintillacon.SCI_SETMARGINTYPEN, 2, scintillacon.SC_MARGIN_SYMBOL
+ )
+ self.SendScintilla(
+ scintillacon.SCI_SETMARGINMASKN, 2, scintillacon.SC_MASK_FOLDERS
+ )
+ self.SendScintilla(scintillacon.SCI_SETMARGINSENSITIVEN, 2, 1)
+
+ self.GetDocument().HookViewNotifications(
+ self
+ ) # is there an MFC way to grab this?
+ self.HookHandlers()
+
+ # Load the configuration information.
+ self.OnWinIniChange(None)
+
+ self.SetSel()
+
+ self.GetDocument().FinalizeViewCreation(
+ self
+ ) # is there an MFC way to grab this?
+
+ def _GetSubConfigNames(self):
+ return None # By default we use only sections without sub-sections.
+
+ def OnWinIniChange(self, section=None):
+ self.bindings.prepare_configure()
+ try:
+ self.DoConfigChange()
+ finally:
+ self.bindings.complete_configure()
+
+ def DoConfigChange(self):
+ # Bit of a hack I don't kow what to do about - these should be "editor options"
+ from pywin.framework.editor import GetEditorOption
+
+ self.bAutoCompleteAttributes = GetEditorOption("Autocomplete Attributes", 1)
+ self.bShowCallTips = GetEditorOption("Show Call Tips", 1)
+ # Update the key map and extension data.
+ configManager.configure(self, self._GetSubConfigNames())
+ if configManager.last_error:
+ win32ui.MessageBox(configManager.last_error, "Configuration Error")
+ self.bMatchBraces = GetEditorOption("Match Braces", 1)
+ self.ApplyFormattingStyles(1)
+
+ def OnDestroy(self, msg):
+ self.bindings.close()
+ self.bindings = None
+ self.idle.close()
+ self.idle = None
+ control.CScintillaColorEditInterface.close(self)
+ return docview.CtrlView.OnDestroy(self, msg)
+
+ def OnMouseWheel(self, msg):
+ zDelta = msg[2] >> 16
+ vpos = self.GetScrollPos(win32con.SB_VERT)
+ vpos -= zDelta / 40 # 3 lines per notch
+ self.SetScrollPos(win32con.SB_VERT, vpos)
+ self.SendScintilla(
+ win32con.WM_VSCROLL, (vpos << 16) | win32con.SB_THUMBPOSITION, 0
+ )
+
+ def OnBraceMatch(self, std, extra):
+ if not self.bMatchBraces:
+ return
+ DoBraceMatch(self)
+
+ def OnNeedShown(self, std, extra):
+ notify = self.SCIUnpackNotifyMessage(extra)
+ # OnNeedShown is called before an edit operation when
+ # text is folded (as it is possible the text insertion will happen
+ # in a folded region.) As this happens _before_ the insert,
+ # we ignore the length (if we are at EOF, pos + length may
+ # actually be beyond the end of buffer)
+ self.EnsureCharsVisible(notify.position)
+
+ def EnsureCharsVisible(self, start, end=None):
+ if end is None:
+ end = start
+ lineStart = self.LineFromChar(min(start, end))
+ lineEnd = self.LineFromChar(max(start, end))
+ while lineStart <= lineEnd:
+ self.SCIEnsureVisible(lineStart)
+ lineStart += 1
+
+ # Helper to add an event to a menu.
+ def AppendMenu(self, menu, text="", event=None, flags=None, checked=0):
+ if event is None:
+ assert flags is not None, "No event or custom flags!"
+ cmdid = 0
+ else:
+ cmdid = self.bindings.get_command_id(event)
+ if cmdid is None:
+ # No event of that name - no point displaying it.
+ print(
+ 'View.AppendMenu(): Unknown event "{}" specified for menu text "{}" - ignored'.format(
+ event, text
+ )
+ )
+ return
+ keyname = configManager.get_key_binding(event, self._GetSubConfigNames())
+ if keyname is not None:
+ text += "\t" + keyname
+ if flags is None:
+ flags = win32con.MF_STRING | win32con.MF_ENABLED
+ if checked:
+ flags |= win32con.MF_CHECKED
+ menu.AppendMenu(flags, cmdid, text)
+
+ def OnKeyDown(self, msg):
+ return self.bindings.fire_key_event(msg)
+
+ def GotoEndOfFileEvent(self, event):
+ self.SetSel(-1)
+
+ def KeyDotEvent(self, event):
+ ## Don't trigger autocomplete if any text is selected
+ s, e = self.GetSel()
+ if s != e:
+ return 1
+ self.SCIAddText(".")
+ if self.bAutoCompleteAttributes:
+ self._AutoComplete()
+
+ # View Whitespace/EOL/Indentation UI.
+
+ def OnCmdViewWS(self, cmd, code): # Handle the menu command
+ viewWS = self.SCIGetViewWS()
+ self.SCISetViewWS(not viewWS)
+
+ def OnUpdateViewWS(self, cmdui): # Update the tick on the UI.
+ cmdui.SetCheck(self.SCIGetViewWS())
+ cmdui.Enable()
+
+ def OnCmdViewIndentationGuides(self, cmd, code): # Handle the menu command
+ viewIG = self.SCIGetIndentationGuides()
+ self.SCISetIndentationGuides(not viewIG)
+
+ def OnUpdateViewIndentationGuides(self, cmdui): # Update the tick on the UI.
+ cmdui.SetCheck(self.SCIGetIndentationGuides())
+ cmdui.Enable()
+
+ def OnCmdViewRightEdge(self, cmd, code): # Handle the menu command
+ if self.SCIGetEdgeMode() == scintillacon.EDGE_NONE:
+ mode = scintillacon.EDGE_BACKGROUND
+ else:
+ mode = scintillacon.EDGE_NONE
+ self.SCISetEdgeMode(mode)
+
+ def OnUpdateViewRightEdge(self, cmdui): # Update the tick on the UI.
+ cmdui.SetCheck(self.SCIGetEdgeMode() != scintillacon.EDGE_NONE)
+ cmdui.Enable()
+
+ def OnCmdViewEOL(self, cmd, code): # Handle the menu command
+ viewEOL = self.SCIGetViewEOL()
+ self.SCISetViewEOL(not viewEOL)
+
+ def OnUpdateViewEOL(self, cmdui): # Update the tick on the UI.
+ cmdui.SetCheck(self.SCIGetViewEOL())
+ cmdui.Enable()
+
+ def OnCmdViewFixedFont(self, cmd, code): # Handle the menu command
+ self._GetColorizer().bUseFixed = not self._GetColorizer().bUseFixed
+ self.ApplyFormattingStyles(0)
+ # Ensure the selection is visible!
+ self.ScrollCaret()
+
+ def OnUpdateViewFixedFont(self, cmdui): # Update the tick on the UI.
+ c = self._GetColorizer()
+ if c is not None:
+ cmdui.SetCheck(c.bUseFixed)
+ cmdui.Enable(c is not None)
+
+ def OnCmdEditFind(self, cmd, code):
+ from . import find
+
+ find.ShowFindDialog()
+
+ def OnCmdEditRepeat(self, cmd, code):
+ from . import find
+
+ find.FindNext()
+
+ def OnCmdEditReplace(self, cmd, code):
+ from . import find
+
+ find.ShowReplaceDialog()
+
+ def OnCmdFileLocate(self, cmd, id):
+ line = self.GetLine().strip()
+ import pywin.framework.scriptutils
+
+ m = patImport.match(line)
+ if m:
+ # Module name on this line - locate that!
+ modName = m.group("name")
+ fileName = pywin.framework.scriptutils.LocatePythonFile(modName)
+ if fileName is None:
+ win32ui.SetStatusText("Can't locate module %s" % modName)
+ return 1 # Let the default get it.
+ else:
+ win32ui.GetApp().OpenDocumentFile(fileName)
+ else:
+ # Just to a "normal" locate - let the default handler get it.
+ return 1
+ return 0
+
+ def OnCmdGotoLine(self, cmd, id):
+ try:
+ lineNo = int(input("Enter Line Number")) - 1
+ except (ValueError, KeyboardInterrupt):
+ return 0
+ self.SCIEnsureVisible(lineNo)
+ self.SCIGotoLine(lineNo)
+ return 0
+
+ def SaveTextFile(self, filename, encoding=None):
+ doc = self.GetDocument()
+ doc._SaveTextToFile(self, filename, encoding=encoding)
+ doc.SetModifiedFlag(0)
+ return 1
+
+ def _AutoComplete(self):
+ self.SCIAutoCCancel() # Cancel old auto-complete lists.
+ # First try and get an object without evaluating calls
+ ob = self._GetObjectAtPos(bAllowCalls=0)
+ # If that failed, try and process call or indexing to get the object.
+ if ob is None:
+ ob = self._GetObjectAtPos(bAllowCalls=1)
+ items_dict = {}
+ if ob is not None:
+ try: # Catch unexpected errors when fetching attribute names from the object
+ # extra attributes of win32ui objects
+ if hasattr(ob, "_obj_"):
+ try:
+ items_dict.update(dict.fromkeys(dir(ob._obj_)))
+ except AttributeError:
+ pass # object has no __dict__
+
+ # normal attributes
+ try:
+ items_dict.update(dict.fromkeys(dir(ob)))
+ except AttributeError:
+ pass # object has no __dict__
+ if hasattr(ob, "__class__"):
+ items_dict.update(
+ dict.fromkeys(_get_class_attributes(ob.__class__))
+ )
+ # The object may be a COM object with typelib support - let's see if we can get its props.
+ # (contributed by Stefan Migowsky)
+ try:
+ # Get the automation attributes
+ items_dict.update(ob.__class__._prop_map_get_)
+ # See if there is an write only property
+ # could be optimized
+ items_dict.update(ob.__class__._prop_map_put_)
+ # append to the already evaluated list
+ except AttributeError:
+ pass
+ # The object might be a pure COM dynamic dispatch with typelib support - let's see if we can get its props.
+ if hasattr(ob, "_oleobj_"):
+ try:
+ for iTI in range(0, ob._oleobj_.GetTypeInfoCount()):
+ typeInfo = ob._oleobj_.GetTypeInfo(iTI)
+ self._UpdateWithITypeInfo(items_dict, typeInfo)
+ except:
+ pass
+ except:
+ win32ui.SetStatusText(
+ f"Error attempting to get object attributes - {sys.exc_info()[0]!r}"
+ )
+
+ items = [
+ k
+ for k in
+ # ensure all keys are strings.
+ map(str, items_dict)
+ # All names that start with "_" go!
+ if not k.startswith("_")
+ ]
+
+ if not items:
+ # Heuristics a-la AutoExpand
+ # The idea is to find other usages of the current binding
+ # and assume, that it refers to the same object (or at least,
+ # to an object of the same type)
+ # Contributed by Vadim Chugunov [vadimch@yahoo.com]
+ left, right = self._GetWordSplit()
+ if left == "": # Ignore standalone dots
+ return None
+ # We limit our search to the current class, if that
+ # information is available
+ minline, maxline, curclass = self._GetClassInfoFromBrowser()
+ endpos = self.LineIndex(maxline)
+ text = self.GetTextRange(self.LineIndex(minline), endpos)
+ try:
+ l = re.findall(r"\b" + left + r"\.\w+", text)
+ except re.error:
+ # parens etc may make an invalid RE, but this code wouldnt
+ # benefit even if the RE did work :-)
+ l = []
+ prefix = len(left) + 1
+ unique = {}
+ for li in l:
+ unique[li[prefix:]] = 1
+ # Assuming traditional usage of self...
+ if curclass and left == "self":
+ self._UpdateWithClassMethods(unique, curclass)
+
+ items = [word for word in unique if word[:2] != "__" or word[-2:] != "__"]
+ # Ignore the word currently to the right of the dot - probably a red-herring.
+ try:
+ items.remove(right[1:])
+ except ValueError:
+ pass
+ if items:
+ items.sort()
+ self.SCIAutoCSetAutoHide(0)
+ self.SCIAutoCShow(items)
+
+ def _UpdateWithITypeInfo(self, items_dict, typeInfo):
+ import pythoncom
+
+ typeInfos = [typeInfo]
+ # suppress IDispatch and IUnknown methods
+ inspectedIIDs = {pythoncom.IID_IDispatch: None}
+
+ while len(typeInfos) > 0:
+ typeInfo = typeInfos.pop()
+ typeAttr = typeInfo.GetTypeAttr()
+
+ if typeAttr.iid not in inspectedIIDs:
+ inspectedIIDs[typeAttr.iid] = None
+ for iFun in range(0, typeAttr.cFuncs):
+ funDesc = typeInfo.GetFuncDesc(iFun)
+ funName = typeInfo.GetNames(funDesc.memid)[0]
+ if funName not in items_dict:
+ items_dict[funName] = None
+
+ # Inspect the type info of all implemented types
+ # E.g. IShellDispatch5 implements IShellDispatch4 which implements IShellDispatch3 ...
+ for iImplType in range(0, typeAttr.cImplTypes):
+ iRefType = typeInfo.GetRefTypeOfImplType(iImplType)
+ refTypeInfo = typeInfo.GetRefTypeInfo(iRefType)
+ typeInfos.append(refTypeInfo)
+
+ # TODO: This is kinda slow. Probably need some kind of cache
+ # here that is flushed upon file save
+ # Or maybe we don't need the superclass methods at all ?
+ def _UpdateWithClassMethods(self, dict, classinfo):
+ if not hasattr(classinfo, "methods"):
+ # No 'methods' - probably not what we think it is.
+ return
+ dict.update(classinfo.methods)
+ for super in classinfo.super:
+ if hasattr(super, "methods"):
+ self._UpdateWithClassMethods(dict, super)
+
+ # Find which class definition caret is currently in and return
+ # indexes of the the first and the last lines of that class definition
+ # Data is obtained from module browser (if enabled)
+ def _GetClassInfoFromBrowser(self, pos=-1):
+ minline = 0
+ maxline = self.GetLineCount() - 1
+ doc = self.GetParentFrame().GetActiveDocument()
+ browser = None
+ try:
+ if doc is not None:
+ browser = doc.GetAllViews()[1]
+ except IndexError:
+ pass
+ if browser is None:
+ return (minline, maxline, None) # Current window has no browser
+ if not browser.list:
+ return (minline, maxline, None) # Not initialized
+ path = self.GetDocument().GetPathName()
+ if not path:
+ return (minline, maxline, None) # No current path
+
+ import pywin.framework.scriptutils
+
+ curmodule, path = pywin.framework.scriptutils.GetPackageModuleName(path)
+ try:
+ clbrdata = browser.list.root.clbrdata
+ except AttributeError:
+ return (minline, maxline, None) # No class data for this module.
+ curline = self.LineFromChar(pos)
+ curclass = None
+ # Find out which class we are in
+ for item in clbrdata.values():
+ if item.module == curmodule:
+ item_lineno = (
+ item.lineno - 1
+ ) # Scintilla counts lines from 0, whereas pyclbr - from 1
+ if minline < item_lineno <= curline:
+ minline = item_lineno
+ curclass = item
+ if curline < item_lineno < maxline:
+ maxline = item_lineno
+ return (minline, maxline, curclass)
+
+ def _GetObjectAtPos(self, pos=-1, bAllowCalls=0):
+ left, right = self._GetWordSplit(pos, bAllowCalls)
+ if left: # It is an attribute lookup
+ # How is this for a hack!
+ namespace = sys.modules.copy()
+ namespace.update(__main__.__dict__)
+ # Get the debugger's context.
+ try:
+ from pywin.framework import interact
+
+ if interact.edit is not None and interact.edit.currentView is not None:
+ globs, locs = interact.edit.currentView.GetContext()[:2]
+ if globs:
+ namespace.update(globs)
+ if locs:
+ namespace.update(locs)
+ except ImportError:
+ pass
+ try:
+ return eval(left, namespace)
+ except:
+ pass
+ return None
+
+ def _GetWordSplit(self, pos=-1, bAllowCalls=0):
+ if pos == -1:
+ pos = self.GetSel()[0] - 1 # Character before current one
+ limit = self.GetTextLength()
+ before = []
+ after = []
+ index = pos - 1
+ wordbreaks_use = wordbreaks
+ if bAllowCalls:
+ wordbreaks_use += "()[]"
+ while index >= 0:
+ char = self.SCIGetCharAt(index)
+ if char not in wordbreaks_use:
+ break
+ before.insert(0, char)
+ index -= 1
+ index = pos
+ while index <= limit:
+ char = self.SCIGetCharAt(index)
+ if char not in wordbreaks_use:
+ break
+ after.append(char)
+ index += 1
+ return "".join(before), "".join(after)
+
+ def OnPrepareDC(self, dc, pInfo):
+ # print(
+ # "OnPrepareDC for page",
+ # pInfo.GetCurPage(),
+ # "of",
+ # pInfo.GetFromPage(),
+ # "to",
+ # pInfo.GetToPage(),
+ # ", starts=",
+ # self.starts,
+ # )
+ if dc.IsPrinting():
+ # Check if we are beyond the end.
+ # (only do this when actually printing, else messes up print preview!)
+ if not pInfo.GetPreview() and self.starts is not None:
+ prevPage = pInfo.GetCurPage() - 1
+ if prevPage > 0 and self.starts[prevPage] >= self.GetTextLength():
+ # All finished.
+ pInfo.SetContinuePrinting(0)
+ return
+ dc.SetMapMode(win32con.MM_TEXT)
+
+ def OnPreparePrinting(self, pInfo):
+ flags = (
+ win32ui.PD_USEDEVMODECOPIES | win32ui.PD_ALLPAGES | win32ui.PD_NOSELECTION
+ ) # Don't support printing just a selection.
+ # NOTE: Custom print dialogs are stopping the user's values from coming back :-(
+ # self.prtDlg = PrintDialog(pInfo, PRINTDLGORD, flags)
+ # pInfo.SetPrintDialog(self.prtDlg)
+ pInfo.SetMinPage(1)
+ # max page remains undefined for now.
+ pInfo.SetFromPage(1)
+ pInfo.SetToPage(1)
+ ret = self.DoPreparePrinting(pInfo)
+ return ret
+
+ def OnBeginPrinting(self, dc, pInfo):
+ self.starts = None
+ return self._obj_.OnBeginPrinting(dc, pInfo)
+
+ def CalculatePageRanges(self, dc, pInfo):
+ # Calculate page ranges and max page
+ self.starts = {0: 0}
+ metrics = dc.GetTextMetrics()
+ left, top, right, bottom = pInfo.GetDraw()
+ # Leave space at the top for the header.
+ rc = (left, top + int((9 * metrics["tmHeight"]) / 2), right, bottom)
+ pageStart = 0
+ maxPage = 0
+ textLen = self.GetTextLength()
+ while pageStart < textLen:
+ pageStart = self.FormatRange(dc, pageStart, textLen, rc, 0)
+ maxPage += 1
+ self.starts[maxPage] = pageStart
+ # And a sentinel for one page past the end
+ self.starts[maxPage + 1] = textLen
+ # When actually printing, maxPage doesn't have any effect at this late state.
+ # but is needed to make the Print Preview work correctly.
+ pInfo.SetMaxPage(maxPage)
+
+ def OnFilePrintPreview(self, *arg):
+ self._obj_.OnFilePrintPreview()
+
+ def OnFilePrint(self, *arg):
+ self._obj_.OnFilePrint()
+
+ def FormatRange(self, dc, pageStart, lengthDoc, rc, draw):
+ """
+ typedef struct _formatrange {
+ HDC hdc;
+ HDC hdcTarget;
+ RECT rc;
+ RECT rcPage;
+ CHARRANGE chrg;} FORMATRANGE;
+ """
+ fmt = "PPIIIIIIIIll"
+ hdcRender = dc.GetHandleOutput()
+ hdcFormat = dc.GetHandleAttrib()
+ fr = struct.pack(
+ fmt,
+ hdcRender,
+ hdcFormat,
+ rc[0],
+ rc[1],
+ rc[2],
+ rc[3],
+ rc[0],
+ rc[1],
+ rc[2],
+ rc[3],
+ pageStart,
+ lengthDoc,
+ )
+ nextPageStart = self.SendScintilla(EM_FORMATRANGE, draw, fr)
+ return nextPageStart
+
+ def OnPrint(self, dc, pInfo):
+ metrics = dc.GetTextMetrics()
+ # print("dev", w, h, l, metrics["tmAscent"], metrics["tmDescent"])
+ if self.starts is None:
+ self.CalculatePageRanges(dc, pInfo)
+ pageNum = pInfo.GetCurPage() - 1
+ # Setup the header of the page - docname on left, pagenum on right.
+ doc = self.GetDocument()
+ cxChar = metrics["tmAveCharWidth"]
+ cyChar = metrics["tmHeight"]
+ left, top, right, bottom = pInfo.GetDraw()
+ dc.TextOut(0, 2 * cyChar, doc.GetTitle())
+ pagenum_str = win32ui.LoadString(afxres.AFX_IDS_PRINTPAGENUM) % (pageNum + 1,)
+ dc.SetTextAlign(win32con.TA_RIGHT)
+ dc.TextOut(right, 2 * cyChar, pagenum_str)
+ dc.SetTextAlign(win32con.TA_LEFT)
+ top += int(7 * cyChar / 2)
+ dc.MoveTo(left, top)
+ dc.LineTo(right, top)
+ top += cyChar
+ rc = (left, top, right, bottom)
+ nextPageStart = self.FormatRange(
+ dc, self.starts[pageNum], self.starts[pageNum + 1], rc, 1
+ )
+
+
+def LoadConfiguration():
+ global configManager
+ # Bit of a hack I don't kow what to do about?
+ from .config import ConfigManager
+
+ configName = rc = win32ui.GetProfileVal("Editor", "Keyboard Config", "default")
+ configManager = ConfigManager(configName)
+ if configManager.last_error:
+ bTryDefault = 0
+ msg = "Error loading configuration '{}'\n\n{}".format(
+ configName,
+ configManager.last_error,
+ )
+ if configName != "default":
+ msg += "\n\nThe default configuration will be loaded."
+ bTryDefault = 1
+ win32ui.MessageBox(msg)
+ if bTryDefault:
+ configManager = ConfigManager("default")
+ if configManager.last_error:
+ win32ui.MessageBox(
+ "Error loading configuration 'default'\n\n%s"
+ % (configManager.last_error)
+ )
+
+
+configManager = None
+LoadConfiguration()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/TraceCollector.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/TraceCollector.py
new file mode 100644
index 0000000000000000000000000000000000000000..1a477f5b472b4d11950165d7215ed499e9215a9c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/TraceCollector.py
@@ -0,0 +1,79 @@
+# win32traceutil like utility for Pythonwin
+import _thread
+
+import win32api
+import win32event
+import win32trace
+from pywin.framework import winout
+
+outputWindow = None
+
+
+def CollectorThread(stopEvent, file):
+ win32trace.InitRead()
+ handle = win32trace.GetHandle()
+ # Run this thread at a lower priority to the main message-loop (and printing output)
+ # thread can keep up
+ import win32process
+
+ win32process.SetThreadPriority(
+ win32api.GetCurrentThread(), win32process.THREAD_PRIORITY_BELOW_NORMAL
+ )
+
+ try:
+ while 1:
+ rc = win32event.WaitForMultipleObjects(
+ (handle, stopEvent), 0, win32event.INFINITE
+ )
+ if rc == win32event.WAIT_OBJECT_0:
+ # About the only char we can't live with is \0!
+ file.write(win32trace.read().replace("\0", ""))
+ else:
+ # Stop event
+ break
+ finally:
+ win32trace.TermRead()
+ print("Thread dieing")
+
+
+class WindowOutput(winout.WindowOutput):
+ def __init__(self, *args):
+ winout.WindowOutput.__init__(*(self,) + args)
+ self.hStopThread = win32event.CreateEvent(None, 0, 0, None)
+ _thread.start_new(CollectorThread, (self.hStopThread, self))
+
+ def _StopThread(self):
+ win32event.SetEvent(self.hStopThread)
+ self.hStopThread = None
+
+ def Close(self):
+ self._StopThread()
+ winout.WindowOutput.Close(self)
+ # def OnViewDestroy(self, frame):
+ # return winout.WindowOutput.OnViewDestroy(self, frame)
+ # def Create(self, title=None, style = None):
+ # rc = winout.WindowOutput.Create(self, title, style)
+ # return rc
+
+
+def MakeOutputWindow():
+ # Note that it will not show until the first string written or
+ # you pass bShow = 1
+ global outputWindow
+ if outputWindow is None:
+ title = "Python Trace Collector"
+ # queueingFlag doesn't matter, as all output will come from new thread
+ outputWindow = WindowOutput(title, title)
+ # Let people know what this does!
+ msg = """\
+# This window will display output from any programs that import win32traceutil
+# win32com servers registered with '--debug' are in this category.
+"""
+ outputWindow.write(msg)
+ # force existing window open
+ outputWindow.write("")
+ return outputWindow
+
+
+if __name__ == "__main__":
+ MakeOutputWindow()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/__init__.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/browseProjects.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/browseProjects.py
new file mode 100644
index 0000000000000000000000000000000000000000..e798fcc432ad8a936fc7efd7c54397b6fdbf2371
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/browseProjects.py
@@ -0,0 +1,323 @@
+import glob
+import os
+import pyclbr
+
+import commctrl
+import pywin.framework.scriptutils
+import regutil
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import afxres, dialog
+
+from . import hierlist
+
+
+class HLIErrorItem(hierlist.HierListItem):
+ def __init__(self, text):
+ self.text = text
+ hierlist.HierListItem.__init__(self)
+
+ def GetText(self):
+ return self.text
+
+
+class HLICLBRItem(hierlist.HierListItem):
+ def __init__(self, name: str, file, lineno, suffix=""):
+ # If the 'name' object itself has a .name, use it. Not sure
+ # how this happens, but seems pyclbr related.
+ # See PyWin32 bug 817035
+ self.name = getattr(name, "name", name)
+ self.file = file
+ self.lineno = lineno
+ self.suffix = suffix
+
+ def __lt__(self, other):
+ return self.name < other.name
+
+ def __eq__(self, other):
+ return self.name == other.name
+
+ def GetText(self):
+ return self.name + self.suffix
+
+ def TakeDefaultAction(self):
+ if self.file:
+ pywin.framework.scriptutils.JumpToDocument(
+ self.file, self.lineno, bScrollToTop=1
+ )
+ else:
+ win32ui.SetStatusText("The source of this object is unknown")
+
+ def PerformItemSelected(self):
+ if self.file is None:
+ msg = f"{self.name} - source can not be located."
+ else:
+ msg = "%s defined at line %d of %s" % (self.name, self.lineno, self.file)
+ win32ui.SetStatusText(msg)
+
+
+class HLICLBRClass(HLICLBRItem):
+ def __init__(self, clbrclass, suffix=""):
+ try:
+ name = clbrclass.name
+ file = clbrclass.file
+ lineno = clbrclass.lineno
+ self.super = clbrclass.super
+ self.methods = clbrclass.methods
+ except AttributeError:
+ name = clbrclass
+ file = lineno = None
+ self.super = []
+ self.methods = {}
+ HLICLBRItem.__init__(self, name, file, lineno, suffix)
+
+ def GetSubList(self):
+ ret = []
+ for c in self.super:
+ ret.append(HLICLBRClass(c, " (Parent class)"))
+ for meth, lineno in self.methods.items():
+ ret.append(HLICLBRMethod(meth, self.file, lineno, " (method)"))
+ return ret
+
+ def IsExpandable(self):
+ return len(self.methods) + len(self.super)
+
+ def GetBitmapColumn(self):
+ return 21
+
+
+class HLICLBRFunction(HLICLBRClass):
+ def GetBitmapColumn(self):
+ return 22
+
+
+class HLICLBRMethod(HLICLBRItem):
+ def GetBitmapColumn(self):
+ return 22
+
+
+class HLIModuleItem(hierlist.HierListItem):
+ def __init__(self, path):
+ hierlist.HierListItem.__init__(self)
+ self.path = path
+
+ def GetText(self):
+ return os.path.split(self.path)[1] + " (module)"
+
+ def IsExpandable(self):
+ return 1
+
+ def TakeDefaultAction(self):
+ win32ui.GetApp().OpenDocumentFile(self.path)
+
+ def GetBitmapColumn(self):
+ col = 4 # Default
+ try:
+ if win32api.GetFileAttributes(self.path) & win32con.FILE_ATTRIBUTE_READONLY:
+ col = 5
+ except win32api.error:
+ pass
+ return col
+
+ def GetSubList(self):
+ mod, path = pywin.framework.scriptutils.GetPackageModuleName(self.path)
+ win32ui.SetStatusText("Building class list - please wait...", 1)
+ win32ui.DoWaitCursor(1)
+ try:
+ try:
+ reader = pyclbr.readmodule_ex # Post 1.5.2 interface.
+ extra_msg = " or functions"
+ except AttributeError:
+ reader = pyclbr.readmodule
+ extra_msg = ""
+ data = reader(mod, [path])
+ if data:
+ ret = []
+ for item in data.values():
+ if (
+ item.__class__ != pyclbr.Class
+ ): # ie, it is a pyclbr Function instance (only introduced post 1.5.2)
+ ret.append(HLICLBRFunction(item, " (function)"))
+ else:
+ ret.append(HLICLBRClass(item, " (class)"))
+ ret.sort()
+ return ret
+ else:
+ return [HLIErrorItem(f"No Python classes{extra_msg} in module.")]
+ finally:
+ win32ui.DoWaitCursor(0)
+ win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
+
+
+def MakePathSubList(path):
+ ret = []
+ for filename in glob.glob(os.path.join(path, "*")):
+ if os.path.isdir(filename) and os.path.isfile(
+ os.path.join(filename, "__init__.py")
+ ):
+ ret.append(HLIDirectoryItem(filename, os.path.split(filename)[1]))
+ else:
+ if os.path.splitext(filename)[1].lower() in [".py", ".pyw"]:
+ ret.append(HLIModuleItem(filename))
+ return ret
+
+
+class HLIDirectoryItem(hierlist.HierListItem):
+ def __init__(self, path, displayName=None, bSubDirs=0):
+ hierlist.HierListItem.__init__(self)
+ self.path = path
+ self.bSubDirs = bSubDirs
+ if displayName:
+ self.displayName = displayName
+ else:
+ self.displayName = path
+
+ def IsExpandable(self):
+ return 1
+
+ def GetText(self):
+ return self.displayName
+
+ def GetSubList(self):
+ ret = MakePathSubList(self.path)
+ if (
+ os.path.split(self.path)[1] == "win32com"
+ ): # Complete and utter hack for win32com.
+ try:
+ path = win32api.GetFullPathName(
+ os.path.join(self.path, "..\\win32comext")
+ )
+ ret.extend(MakePathSubList(path))
+ except win32ui.error:
+ pass
+ return ret
+
+
+class HLIProjectRoot(hierlist.HierListItem):
+ def __init__(self, projectName, displayName=None):
+ hierlist.HierListItem.__init__(self)
+ self.projectName = projectName
+ self.displayName = displayName or projectName
+
+ def GetText(self):
+ return self.displayName
+
+ def IsExpandable(self):
+ return 1
+
+ def GetSubList(self):
+ paths = regutil.GetRegisteredNamedPath(self.projectName)
+ pathList = paths.split(";")
+ if len(pathList) == 1: # Single dir - don't bother putting the dir in
+ ret = MakePathSubList(pathList[0])
+ else:
+ ret = list(map(HLIDirectoryItem, pathList))
+ return ret
+
+
+class HLIRoot(hierlist.HierListItem):
+ def __init__(self):
+ hierlist.HierListItem.__init__(self)
+
+ def IsExpandable(self):
+ return 1
+
+ def GetSubList(self):
+ keyStr = regutil.BuildDefaultPythonKey() + "\\PythonPath"
+ hKey = win32api.RegOpenKey(regutil.GetRootKey(), keyStr)
+ try:
+ ret = []
+ ret.append(HLIProjectRoot("", "Standard Python Library")) # The core path.
+ index = 0
+ while 1:
+ try:
+ ret.append(HLIProjectRoot(win32api.RegEnumKey(hKey, index)))
+ index += 1
+ except win32api.error:
+ break
+ return ret
+ finally:
+ win32api.RegCloseKey(hKey)
+
+
+class dynamic_browser(dialog.Dialog):
+ style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE
+ cs = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | commctrl.TVS_HASLINES
+ | commctrl.TVS_LINESATROOT
+ | commctrl.TVS_HASBUTTONS
+ )
+
+ dt = [
+ ["Python Projects", (0, 0, 200, 200), style, None, (8, "MS Sans Serif")],
+ ["SysTreeView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), cs],
+ ]
+
+ def __init__(self, hli_root):
+ dialog.Dialog.__init__(self, self.dt)
+ self.hier_list = hierlist.HierListWithItems(hli_root, win32ui.IDB_BROWSER_HIER)
+ self.HookMessage(self.on_size, win32con.WM_SIZE)
+
+ def OnInitDialog(self):
+ self.hier_list.HierInit(self)
+ return dialog.Dialog.OnInitDialog(self)
+
+ def on_size(self, params):
+ lparam = params[3]
+ w = win32api.LOWORD(lparam)
+ h = win32api.HIWORD(lparam)
+ self.GetDlgItem(win32ui.IDC_LIST1).MoveWindow((0, 0, w, h))
+
+
+def BrowseDialog():
+ root = HLIRoot()
+ if not root.IsExpandable():
+ raise TypeError(
+ "Browse() argument must have __dict__ attribute, or be a Browser supported type"
+ )
+
+ dlg = dynamic_browser(root)
+ dlg.CreateWindow()
+
+
+def DockableBrowserCreator(parent):
+ root = HLIRoot()
+ hl = hierlist.HierListWithItems(root, win32ui.IDB_BROWSER_HIER)
+
+ style = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | win32con.WS_BORDER
+ | commctrl.TVS_HASLINES
+ | commctrl.TVS_LINESATROOT
+ | commctrl.TVS_HASBUTTONS
+ )
+
+ control = win32ui.CreateTreeCtrl()
+ control.CreateWindow(style, (0, 0, 150, 300), parent, win32ui.IDC_LIST1)
+ list = hl.HierInit(parent, control)
+ return control
+
+
+def DockablePathBrowser():
+ import pywin.docking.DockingBar
+
+ bar = pywin.docking.DockingBar.DockingBar()
+ bar.CreateWindow(
+ win32ui.GetMainFrame(), DockableBrowserCreator, "Path Browser", 0x8E0A
+ )
+ bar.SetBarStyle(
+ bar.GetBarStyle()
+ | afxres.CBRS_TOOLTIPS
+ | afxres.CBRS_FLYBY
+ | afxres.CBRS_SIZE_DYNAMIC
+ )
+ bar.EnableDocking(afxres.CBRS_ALIGN_ANY)
+ win32ui.GetMainFrame().DockControlBar(bar)
+
+
+# The "default" entry point
+Browse = DockablePathBrowser
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/browser.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/browser.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfd5f10eb4d8b4dcc822d748ae5adddfb8f7b4ac
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/browser.py
@@ -0,0 +1,494 @@
+# basic module browser.
+
+# usage:
+# >>> import browser
+# >>> browser.Browse()
+# or
+# >>> browser.Browse(your_module)
+import sys
+import types
+
+import __main__
+import win32ui
+from pywin.mfc import dialog
+
+from . import hierlist
+
+special_names = ["__doc__", "__name__", "__self__"]
+
+
+#
+# HierList items
+class HLIPythonObject(hierlist.HierListItem):
+ def __init__(self, myobject=None, name=None):
+ hierlist.HierListItem.__init__(self)
+ self.myobject = myobject
+ self.knownExpandable = None
+ if name:
+ self.name = name
+ else:
+ try:
+ self.name = myobject.__name__
+ except (AttributeError, TypeError):
+ try:
+ r = repr(myobject)
+ if len(r) > 20:
+ r = r[:20] + "..."
+ self.name = r
+ except (AttributeError, TypeError):
+ self.name = "???"
+
+ def __lt__(self, other):
+ return self.name < other.name
+
+ def __eq__(self, other):
+ return self.name == other.name
+
+ def __repr__(self):
+ try:
+ type = self.GetHLIType()
+ except:
+ type = "Generic"
+ return f"HLIPythonObject({type}) - name: {self.name} object: {self.myobject!r}"
+
+ def GetText(self):
+ try:
+ return f"{self.name} ({self.GetHLIType()})"
+ except AttributeError:
+ return f"{self.name} = {self.myobject!r}"
+
+ def InsertDocString(self, lst):
+ ob = None
+ try:
+ ob = self.myobject.__doc__
+ except (AttributeError, TypeError):
+ pass
+ # I don't quite grok descriptors enough to know how to
+ # best hook them up. Eg:
+ # >>> object.__getattribute__.__class__.__doc__
+ #
+ if ob and isinstance(ob, str):
+ lst.insert(0, HLIDocString(ob, "Doc"))
+
+ def GetSubList(self):
+ ret = []
+ try:
+ for key, ob in self.myobject.__dict__.items():
+ if key not in special_names:
+ ret.append(MakeHLI(ob, key))
+ except (AttributeError, TypeError):
+ pass
+ try:
+ for name in self.myobject.__methods__:
+ ret.append(HLIMethod(name)) # no MakeHLI, as can't auto detect
+ except (AttributeError, TypeError):
+ pass
+ try:
+ for member in self.myobject.__members__:
+ if not member in special_names:
+ ret.append(MakeHLI(getattr(self.myobject, member), member))
+ except (AttributeError, TypeError):
+ pass
+ ret.sort()
+ self.InsertDocString(ret)
+ return ret
+
+ # if the has a dict, it is expandable.
+ def IsExpandable(self):
+ if self.knownExpandable is None:
+ self.knownExpandable = self.CalculateIsExpandable()
+ return self.knownExpandable
+
+ def CalculateIsExpandable(self):
+ if hasattr(self.myobject, "__doc__"):
+ return 1
+ try:
+ for key in self.myobject.__dict__:
+ if key not in special_names:
+ return 1
+ except (AttributeError, TypeError):
+ pass
+ try:
+ self.myobject.__methods__
+ return 1
+ except (AttributeError, TypeError):
+ pass
+ try:
+ for item in self.myobject.__members__:
+ if item not in special_names:
+ return 1
+ except (AttributeError, TypeError):
+ pass
+ return 0
+
+ def GetBitmapColumn(self):
+ if self.IsExpandable():
+ return 0
+ else:
+ return 4
+
+ def TakeDefaultAction(self):
+ ShowObject(self.myobject, self.name)
+
+
+class HLIDocString(HLIPythonObject):
+ def GetHLIType(self):
+ return "DocString"
+
+ def GetText(self):
+ return self.myobject.strip()
+
+ def IsExpandable(self):
+ return 0
+
+ def GetBitmapColumn(self):
+ return 6
+
+
+class HLIModule(HLIPythonObject):
+ def GetHLIType(self):
+ return "Module"
+
+
+class HLIFrame(HLIPythonObject):
+ def GetHLIType(self):
+ return "Stack Frame"
+
+
+class HLITraceback(HLIPythonObject):
+ def GetHLIType(self):
+ return "Traceback"
+
+
+class HLIClass(HLIPythonObject):
+ def GetHLIType(self):
+ return "Class"
+
+ def GetSubList(self):
+ ret = []
+ for base in self.myobject.__bases__:
+ ret.append(MakeHLI(base, "Base class: " + base.__name__))
+ ret.extend(HLIPythonObject.GetSubList(self))
+ return ret
+
+
+class HLIMethod(HLIPythonObject):
+ # myobject is just a string for methods.
+ def GetHLIType(self):
+ return "Method"
+
+ def GetText(self):
+ return "Method: " + self.myobject + "()"
+
+
+class HLICode(HLIPythonObject):
+ def GetHLIType(self):
+ return "Code"
+
+ def IsExpandable(self):
+ return self.myobject
+
+ def GetSubList(self):
+ ret = []
+ ret.append(MakeHLI(self.myobject.co_consts, "Constants (co_consts)"))
+ ret.append(MakeHLI(self.myobject.co_names, "Names (co_names)"))
+ ret.append(MakeHLI(self.myobject.co_filename, "Filename (co_filename)"))
+ ret.append(MakeHLI(self.myobject.co_argcount, "Number of args (co_argcount)"))
+ ret.append(MakeHLI(self.myobject.co_varnames, "Param names (co_varnames)"))
+
+ return ret
+
+
+class HLIInstance(HLIPythonObject):
+ def GetHLIType(self):
+ return "Instance"
+
+ def GetText(self):
+ return (
+ str(self.name)
+ + " (Instance of class "
+ + str(self.myobject.__class__.__name__)
+ + ")"
+ )
+
+ def IsExpandable(self):
+ return 1
+
+ def GetSubList(self):
+ ret = []
+ ret.append(MakeHLI(self.myobject.__class__))
+ ret.extend(HLIPythonObject.GetSubList(self))
+ return ret
+
+
+class HLIBuiltinFunction(HLIPythonObject):
+ def GetHLIType(self):
+ return "Builtin Function"
+
+
+class HLIFunction(HLIPythonObject):
+ def GetHLIType(self):
+ return "Function"
+
+ def IsExpandable(self):
+ return 1
+
+ def GetSubList(self):
+ ret = [
+ MakeHLI(self.myobject.__code__, "Code"),
+ MakeHLI(self.myobject.__globals__, "Globals"),
+ ]
+ self.InsertDocString(ret)
+ return ret
+
+
+class HLISeq(HLIPythonObject):
+ def GetHLIType(self):
+ return "Sequence (abstract!)"
+
+ def IsExpandable(self):
+ return len(self.myobject) > 0
+
+ def GetSubList(self):
+ ret = []
+ pos = 0
+ for item in self.myobject:
+ ret.append(MakeHLI(item, f"[{pos}]"))
+ pos += 1
+ self.InsertDocString(ret)
+ return ret
+
+
+class HLIList(HLISeq):
+ def GetHLIType(self):
+ return "List"
+
+
+class HLITuple(HLISeq):
+ def GetHLIType(self):
+ return "Tuple"
+
+
+class HLIDict(HLIPythonObject):
+ def GetHLIType(self):
+ return "Dict"
+
+ def IsExpandable(self):
+ try:
+ self.myobject.__doc__
+ return 1
+ except (AttributeError, TypeError):
+ return len(self.myobject) > 0
+
+ def GetSubList(self):
+ ret = [MakeHLI(self.myobject[key], str(key)) for key in sorted(self.myobject)]
+ self.InsertDocString(ret)
+ return ret
+
+
+# strings and Unicode have builtin methods, but we don't really want to see these
+class HLIString(HLIPythonObject):
+ def IsExpandable(self):
+ return 0
+
+
+TypeMap = {
+ type: HLIClass,
+ types.FunctionType: HLIFunction,
+ tuple: HLITuple,
+ dict: HLIDict,
+ list: HLIList,
+ types.ModuleType: HLIModule,
+ types.CodeType: HLICode,
+ types.BuiltinFunctionType: HLIBuiltinFunction,
+ types.FrameType: HLIFrame,
+ types.TracebackType: HLITraceback,
+ str: HLIString,
+ int: HLIPythonObject,
+ bool: HLIPythonObject,
+ float: HLIPythonObject,
+}
+
+
+def MakeHLI(ob, name=None):
+ try:
+ cls = TypeMap[type(ob)]
+ except KeyError:
+ # hrmph - this check gets more and more bogus as Python
+ # improves. It's possible we should just *always* use
+ # HLIInstance?
+ if hasattr(ob, "__class__"): # 'new style' class
+ cls = HLIInstance
+ else:
+ cls = HLIPythonObject
+ return cls(ob, name)
+
+
+#########################################
+#
+# Dialog related.
+
+
+class DialogShowObject(dialog.Dialog):
+ def __init__(self, object, title):
+ self.object = object
+ self.title = title
+ dialog.Dialog.__init__(self, win32ui.IDD_LARGE_EDIT)
+
+ def OnInitDialog(self):
+ import re
+
+ self.SetWindowText(self.title)
+ self.edit = self.GetDlgItem(win32ui.IDC_EDIT1)
+ try:
+ strval = str(self.object)
+ except:
+ t, v, tb = sys.exc_info()
+ strval = f"Exception getting object value\n\n{t}:{v}"
+ tb = None
+ strval = re.sub(r"\n", "\r\n", strval)
+ self.edit.ReplaceSel(strval)
+
+
+def ShowObject(object, title):
+ dlg = DialogShowObject(object, title)
+ dlg.DoModal()
+
+
+# And some mods for a sizable dialog from Sam Rushing!
+import commctrl
+import win32api
+import win32con
+
+
+class dynamic_browser(dialog.Dialog):
+ style = win32con.WS_OVERLAPPEDWINDOW | win32con.WS_VISIBLE
+ cs = (
+ win32con.WS_CHILD
+ | win32con.WS_VISIBLE
+ | commctrl.TVS_HASLINES
+ | commctrl.TVS_LINESATROOT
+ | commctrl.TVS_HASBUTTONS
+ )
+
+ dt = [
+ ["Python Object Browser", (0, 0, 200, 200), style, None, (8, "MS Sans Serif")],
+ ["SysTreeView32", None, win32ui.IDC_LIST1, (0, 0, 200, 200), cs],
+ ]
+
+ def __init__(self, hli_root):
+ dialog.Dialog.__init__(self, self.dt)
+ self.hier_list = hierlist.HierListWithItems(hli_root, win32ui.IDB_BROWSER_HIER)
+ self.HookMessage(self.on_size, win32con.WM_SIZE)
+
+ def OnInitDialog(self):
+ self.hier_list.HierInit(self)
+ return dialog.Dialog.OnInitDialog(self)
+
+ def OnOK(self):
+ self.hier_list.HierTerm()
+ self.hier_list = None
+ return self._obj_.OnOK()
+
+ def OnCancel(self):
+ self.hier_list.HierTerm()
+ self.hier_list = None
+ return self._obj_.OnCancel()
+
+ def on_size(self, params):
+ lparam = params[3]
+ w = win32api.LOWORD(lparam)
+ h = win32api.HIWORD(lparam)
+ self.GetDlgItem(win32ui.IDC_LIST1).MoveWindow((0, 0, w, h))
+
+
+def Browse(ob=__main__):
+ "Browse the argument, or the main dictionary"
+ root = MakeHLI(ob, "root")
+ if not root.IsExpandable():
+ raise TypeError(
+ "Browse() argument must have __dict__ attribute, or be a Browser supported type"
+ )
+
+ dlg = dynamic_browser(root)
+ dlg.CreateWindow()
+ return dlg
+
+
+#
+#
+# Classes for using the browser in an MDI window, rather than a dialog
+#
+from pywin.mfc import docview
+
+
+class BrowserTemplate(docview.DocTemplate):
+ def __init__(self):
+ docview.DocTemplate.__init__(
+ self, win32ui.IDR_PYTHONTYPE, BrowserDocument, None, BrowserView
+ )
+
+ def OpenObject(self, root): # Use this instead of OpenDocumentFile.
+ # Look for existing open document
+ for doc in self.GetDocumentList():
+ if doc.root == root:
+ doc.GetFirstView().ActivateFrame()
+ return doc
+ # not found - new one.
+ doc = BrowserDocument(self, root)
+ frame = self.CreateNewFrame(doc)
+ doc.OnNewDocument()
+ self.InitialUpdateFrame(frame, doc, 1)
+ return doc
+
+
+class BrowserDocument(docview.Document):
+ def __init__(self, template, root):
+ docview.Document.__init__(self, template)
+ self.root = root
+ self.SetTitle("Browser: " + root.name)
+
+ def OnOpenDocument(self, name):
+ raise TypeError("This template can not open files")
+ return 0
+
+
+class BrowserView(docview.TreeView):
+ def OnInitialUpdate(self):
+ import commctrl
+
+ rc = self._obj_.OnInitialUpdate()
+ list = hierlist.HierListWithItems(
+ self.GetDocument().root,
+ win32ui.IDB_BROWSER_HIER,
+ win32ui.AFX_IDW_PANE_FIRST,
+ )
+ list.HierInit(self.GetParent())
+ list.SetStyle(
+ commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS
+ )
+ return rc
+
+
+template = None
+
+
+def MakeTemplate():
+ global template
+ if template is None:
+ template = (
+ BrowserTemplate()
+ ) # win32ui.IDR_PYTHONTYPE, BrowserDocument, None, BrowserView)
+
+
+def BrowseMDI(ob=__main__):
+ """Browse an object using an MDI window."""
+
+ MakeTemplate()
+ root = MakeHLI(ob, repr(ob))
+ if not root.IsExpandable():
+ raise TypeError(
+ "Browse() argument must have __dict__ attribute, or be a Browser supported type"
+ )
+
+ template.OpenObject(root)
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/hierlist.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/hierlist.py
new file mode 100644
index 0000000000000000000000000000000000000000..01c6b06c0f57839365b12674a8b447cfe262eeec
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/hierlist.py
@@ -0,0 +1,353 @@
+# hierlist
+#
+# IMPORTANT - Please read before using.
+
+# This module exposes an API for a Hierarchical Tree Control.
+# Previously, a custom tree control was included in Pythonwin which
+# has an API very similar to this.
+
+# The current control used is the common "Tree Control". This module exists now
+# to provide an API similar to the old control, but for the new Tree control.
+
+# If you need to use the Tree Control, you may still find this API a reasonable
+# choice. However, you should investigate using the tree control directly
+# to provide maximum flexibility (but with extra work).
+from __future__ import annotations
+
+import commctrl
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog, object
+from win32api import RGB
+
+
+# helper to get the text of an arbitary item
+def GetItemText(item):
+ if isinstance(item, (tuple, list)):
+ use = item[0]
+ else:
+ use = item
+ if isinstance(use, str):
+ return use
+ else:
+ return repr(item)
+
+
+class HierDialog(dialog.Dialog):
+ def __init__(
+ self,
+ title,
+ hierList,
+ bitmapID=win32ui.IDB_HIERFOLDERS,
+ dlgID=win32ui.IDD_TREE,
+ dll=None,
+ childListBoxID=win32ui.IDC_LIST1,
+ ):
+ dialog.Dialog.__init__(self, dlgID, dll) # reuse this dialog.
+ self.hierList = hierList
+ self.dlgID = dlgID
+ self.title = title
+
+ # self.childListBoxID = childListBoxID
+ def OnInitDialog(self):
+ self.SetWindowText(self.title)
+ self.hierList.HierInit(self)
+ return dialog.Dialog.OnInitDialog(self)
+
+
+class HierList(object.Object):
+ def __init__(
+ self, root, bitmapID=win32ui.IDB_HIERFOLDERS, listBoxId=None, bitmapMask=None
+ ): # used to create object.
+ self.listControl = None
+ self.bitmapID = bitmapID
+ self.root = root
+ self.listBoxId = listBoxId
+ self.itemHandleMap = {}
+ self.filledItemHandlesMap = {}
+ self.bitmapMask = bitmapMask
+
+ def __getattr__(self, attr):
+ try:
+ return getattr(self.listControl, attr)
+ except AttributeError:
+ return object.Object.__getattr__(self, attr)
+
+ def ItemFromHandle(self, handle):
+ return self.itemHandleMap[handle]
+
+ def SetStyle(self, newStyle):
+ hwnd = self.listControl.GetSafeHwnd()
+ style = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
+ win32api.SetWindowLong(hwnd, win32con.GWL_STYLE, (style | newStyle))
+
+ def HierInit(self, parent, listControl=None): # Used when window first exists.
+ # this also calls "Create" on the listbox.
+ # params - id of listbbox, ID of bitmap, size of bitmaps
+ if self.bitmapMask is None:
+ bitmapMask = RGB(0, 0, 255)
+ else:
+ bitmapMask = self.bitmapMask
+ self.imageList = win32ui.CreateImageList(self.bitmapID, 16, 0, bitmapMask)
+ if listControl is None:
+ if self.listBoxId is None:
+ self.listBoxId = win32ui.IDC_LIST1
+ self.listControl = parent.GetDlgItem(self.listBoxId)
+ else:
+ self.listControl = listControl
+ lbid = listControl.GetDlgCtrlID()
+ assert (
+ self.listBoxId is None or self.listBoxId == lbid
+ ), "An invalid listbox control ID has been specified (specified as {}, but exists as {})".format(
+ self.listBoxId, lbid
+ )
+ self.listBoxId = lbid
+ self.listControl.SetImageList(self.imageList, commctrl.LVSIL_NORMAL)
+ # self.list.AttachObject(self)
+
+ parent.HookNotify(self.OnTreeItemExpanding, commctrl.TVN_ITEMEXPANDINGW)
+ parent.HookNotify(self.OnTreeItemSelChanged, commctrl.TVN_SELCHANGEDW)
+ parent.HookNotify(self.OnTreeItemDoubleClick, commctrl.NM_DBLCLK)
+ self.notify_parent = parent
+
+ if self.root:
+ self.AcceptRoot(self.root)
+
+ def DeleteAllItems(self):
+ self.listControl.DeleteAllItems()
+ self.root = None
+ self.itemHandleMap = {}
+ self.filledItemHandlesMap = {}
+
+ def HierTerm(self):
+ # Don't want notifies as we kill the list.
+ parent = self.notify_parent # GetParentFrame()
+ parent.HookNotify(None, commctrl.TVN_ITEMEXPANDINGW)
+ parent.HookNotify(None, commctrl.TVN_SELCHANGEDW)
+ parent.HookNotify(None, commctrl.NM_DBLCLK)
+
+ self.DeleteAllItems()
+ self.listControl = None
+ self.notify_parent = None # Break a possible cycle
+
+ def OnTreeItemDoubleClick(self, info, extra):
+ (hwndFrom, idFrom, code) = info
+ if idFrom != self.listBoxId:
+ return None
+ item = self.itemHandleMap[self.listControl.GetSelectedItem()]
+ self.TakeDefaultAction(item)
+ return 1
+
+ def OnTreeItemExpanding(self, info, extra):
+ (hwndFrom, idFrom, code) = info
+ if idFrom != self.listBoxId:
+ return None
+ action, itemOld, itemNew, pt = extra
+ itemHandle = itemNew[0]
+ if itemHandle not in self.filledItemHandlesMap:
+ item = self.itemHandleMap[itemHandle]
+ self.AddSubList(itemHandle, self.GetSubList(item))
+ self.filledItemHandlesMap[itemHandle] = None
+ return 0
+
+ def OnTreeItemSelChanged(self, info, extra):
+ (hwndFrom, idFrom, code) = info
+ if idFrom != self.listBoxId:
+ return None
+ action, itemOld, itemNew, pt = extra
+ itemHandle = itemNew[0]
+ item = self.itemHandleMap[itemHandle]
+ self.PerformItemSelected(item)
+ return 1
+
+ def AddSubList(self, parentHandle, subItems):
+ for item in subItems:
+ self.AddItem(parentHandle, item)
+
+ def AddItem(self, parentHandle, item, hInsertAfter=commctrl.TVI_LAST):
+ text = self.GetText(item)
+ if self.IsExpandable(item):
+ cItems = 1 # Trick it !!
+ else:
+ cItems = 0
+ bitmapCol = self.GetBitmapColumn(item)
+ bitmapSel = self.GetSelectedBitmapColumn(item)
+ if bitmapSel is None:
+ bitmapSel = bitmapCol
+ hitem = self.listControl.InsertItem(
+ parentHandle,
+ hInsertAfter,
+ (None, None, None, text, bitmapCol, bitmapSel, cItems, 0),
+ )
+ self.itemHandleMap[hitem] = item
+ return hitem
+
+ def _GetChildHandles(self, handle):
+ ret = []
+ try:
+ handle = self.listControl.GetChildItem(handle)
+ while 1:
+ ret.append(handle)
+ handle = self.listControl.GetNextItem(handle, commctrl.TVGN_NEXT)
+ except win32ui.error:
+ # out of children
+ pass
+ return ret
+
+ def Refresh(self, hparent=None):
+ # Attempt to refresh the given item's sub-entries, but maintain the tree state
+ # (ie, the selected item, expanded items, etc)
+ if hparent is None:
+ hparent = commctrl.TVI_ROOT
+ if hparent not in self.filledItemHandlesMap:
+ # This item has never been expanded, so no refresh can possibly be required.
+ return
+ root_item = self.itemHandleMap[hparent]
+ old_handles = self._GetChildHandles(hparent)
+ old_items = list(map(self.ItemFromHandle, old_handles))
+ new_items = self.GetSubList(root_item)
+ # Now an inefficient technique for synching the items.
+ inew = 0
+ hAfter = commctrl.TVI_FIRST
+ for iold in range(len(old_items)):
+ inewlook = inew
+ matched = 0
+ while inewlook < len(new_items):
+ if old_items[iold] == new_items[inewlook]:
+ matched = 1
+ break
+ inewlook += 1
+ if matched:
+ # Insert the new items.
+ # print("Inserting after", old_items[iold], old_handles[iold])
+ for i in range(inew, inewlook):
+ # print(f"Inserting index {i} ({new_items[i]})")
+ hAfter = self.AddItem(hparent, new_items[i], hAfter)
+
+ inew = inewlook + 1
+ # And recursively refresh iold
+ hold = old_handles[iold]
+ if hold in self.filledItemHandlesMap:
+ self.Refresh(hold)
+ else:
+ # Remove the deleted items.
+ # print(f"Deleting {iold} ({old_items[iold]})")
+ hdelete = old_handles[iold]
+ # First recurse and remove the children from the map.
+ for hchild in self._GetChildHandles(hdelete):
+ del self.itemHandleMap[hchild]
+ if hchild in self.filledItemHandlesMap:
+ del self.filledItemHandlesMap[hchild]
+ self.listControl.DeleteItem(hdelete)
+ hAfter = old_handles[iold]
+ # Fill any remaining new items:
+ for newItem in new_items[inew:]:
+ # print("Inserting new item", newItem)
+ self.AddItem(hparent, newItem)
+
+ def AcceptRoot(self, root):
+ self.listControl.DeleteAllItems()
+ self.itemHandleMap = {commctrl.TVI_ROOT: root}
+ self.filledItemHandlesMap = {commctrl.TVI_ROOT: root}
+ subItems = self.GetSubList(root)
+ self.AddSubList(0, subItems)
+
+ def GetBitmapColumn(self, item):
+ if self.IsExpandable(item):
+ return 0
+ else:
+ return 4
+
+ def GetSelectedBitmapColumn(self, item) -> int | None:
+ return 0
+
+ def CheckChangedChildren(self):
+ return self.listControl.CheckChangedChildren()
+
+ def GetText(self, item):
+ return GetItemText(item)
+
+ def PerformItemSelected(self, item):
+ try:
+ win32ui.SetStatusText("Selected " + self.GetText(item))
+ except win32ui.error: # No status bar!
+ pass
+
+ def TakeDefaultAction(self, item):
+ win32ui.MessageBox("Got item " + self.GetText(item))
+
+
+##########################################################################
+#
+# Classes for use with seperate HierListItems.
+#
+#
+class HierListWithItems(HierList):
+ def __init__(
+ self, root, bitmapID=win32ui.IDB_HIERFOLDERS, listBoxID=None, bitmapMask=None
+ ): # used to create object.
+ HierList.__init__(self, root, bitmapID, listBoxID, bitmapMask)
+
+ def DelegateCall(self, fn):
+ return fn()
+
+ def GetBitmapColumn(self, item):
+ rc = self.DelegateCall(item.GetBitmapColumn)
+ if rc is None:
+ rc = HierList.GetBitmapColumn(self, item)
+ return rc
+
+ def GetSelectedBitmapColumn(self, item):
+ return self.DelegateCall(item.GetSelectedBitmapColumn)
+
+ def IsExpandable(self, item):
+ return self.DelegateCall(item.IsExpandable)
+
+ def GetText(self, item):
+ return self.DelegateCall(item.GetText)
+
+ def GetSubList(self, item):
+ return self.DelegateCall(item.GetSubList)
+
+ def PerformItemSelected(self, item):
+ func = getattr(item, "PerformItemSelected", None)
+ if func is None:
+ return HierList.PerformItemSelected(self, item)
+ else:
+ return self.DelegateCall(func)
+
+ def TakeDefaultAction(self, item):
+ func = getattr(item, "TakeDefaultAction", None)
+ if func is None:
+ return HierList.TakeDefaultAction(self, item)
+ else:
+ return self.DelegateCall(func)
+
+
+# A hier list item - for use with a HierListWithItems
+class HierListItem:
+ def __init__(self):
+ pass
+
+ def GetText(self):
+ pass
+
+ def GetSubList(self):
+ pass
+
+ def IsExpandable(self):
+ pass
+
+ def GetBitmapColumn(self):
+ return None # indicate he should do it.
+
+ def GetSelectedBitmapColumn(self):
+ return None # same as other
+
+ def __lt__(self, other):
+ # we want unrelated items to be sortable...
+ return id(self) < id(other)
+
+ def __eq__(self, other):
+ return False
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/regedit.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/regedit.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa97b01598789075b66a2edf51b7b7b12763b6c8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/regedit.py
@@ -0,0 +1,382 @@
+# Regedit - a Registry Editor for Python
+
+import commctrl
+import regutil
+import win32api
+import win32con
+import win32ui
+from pywin.mfc import dialog, docview, window
+
+from . import hierlist
+
+
+def SafeApply(fn, args, err_desc=""):
+ try:
+ fn(*args)
+ return 1
+ except win32api.error as exc:
+ msg = "Error " + err_desc + "\r\n\r\n" + exc.strerror
+ win32ui.MessageBox(msg)
+ return 0
+
+
+class SplitterFrame(window.MDIChildWnd):
+ def __init__(self):
+ # call base CreateFrame
+ self.images = None
+ window.MDIChildWnd.__init__(self)
+
+ def OnCreateClient(self, cp, context):
+ splitter = win32ui.CreateSplitter()
+ doc = context.doc
+ frame_rect = self.GetWindowRect()
+ size = ((frame_rect[2] - frame_rect[0]), (frame_rect[3] - frame_rect[1]) // 2)
+ sub_size = (size[0] // 3, size[1])
+ splitter.CreateStatic(self, 1, 2)
+ # CTreeControl view
+ self.keysview = RegistryTreeView(doc)
+ # CListControl view
+ self.valuesview = RegistryValueView(doc)
+
+ splitter.CreatePane(self.keysview, 0, 0, (sub_size))
+ splitter.CreatePane(self.valuesview, 0, 1, (0, 0)) # size ignored.
+ splitter.SetRowInfo(0, size[1], 0)
+ # Setup items in the imagelist
+
+ return 1
+
+ def OnItemDoubleClick(self, info, extra):
+ (hwndFrom, idFrom, code) = info
+ if idFrom == win32ui.AFX_IDW_PANE_FIRST:
+ # Tree control
+ return None
+ elif idFrom == win32ui.AFX_IDW_PANE_FIRST + 1:
+ item = self.keysview.SelectedItem()
+ self.valuesview.EditValue(item)
+ return 0
+ # List control
+ else:
+ return None # Pass it on
+
+ def PerformItemSelected(self, item):
+ return self.valuesview.UpdateForRegItem(item)
+
+ def OnDestroy(self, msg):
+ window.MDIChildWnd.OnDestroy(self, msg)
+ if self.images:
+ self.images.DeleteImageList()
+ self.images = None
+
+
+class RegistryTreeView(docview.TreeView):
+ def OnInitialUpdate(self):
+ rc = self._obj_.OnInitialUpdate()
+ self.frame = self.GetParent().GetParent()
+ self.hierList = hierlist.HierListWithItems(
+ self.GetHLIRoot(), win32ui.IDB_HIERFOLDERS, win32ui.AFX_IDW_PANE_FIRST
+ )
+ self.hierList.HierInit(self.frame, self.GetTreeCtrl())
+ self.hierList.SetStyle(
+ commctrl.TVS_HASLINES | commctrl.TVS_LINESATROOT | commctrl.TVS_HASBUTTONS
+ )
+ self.hierList.PerformItemSelected = self.PerformItemSelected
+
+ self.frame.HookNotify(self.frame.OnItemDoubleClick, commctrl.NM_DBLCLK)
+ self.frame.HookNotify(self.OnItemRightClick, commctrl.NM_RCLICK)
+
+ # self.HookMessage(self.OnItemRightClick, win32con.WM_RBUTTONUP)
+
+ def GetHLIRoot(self):
+ doc = self.GetDocument()
+ regroot = doc.root
+ subkey = doc.subkey
+ return HLIRegistryKey(regroot, subkey, "Root")
+
+ def OnItemRightClick(self, notify_data, extra):
+ # First select the item we right-clicked on.
+ pt = self.ScreenToClient(win32api.GetCursorPos())
+ flags, hItem = self.HitTest(pt)
+ if hItem == 0 or commctrl.TVHT_ONITEM & flags == 0:
+ return None
+ self.Select(hItem, commctrl.TVGN_CARET)
+
+ menu = win32ui.CreatePopupMenu()
+ menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1000, "Add Key")
+ menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1001, "Add Value")
+ menu.AppendMenu(win32con.MF_STRING | win32con.MF_ENABLED, 1002, "Delete Key")
+ self.HookCommand(self.OnAddKey, 1000)
+ self.HookCommand(self.OnAddValue, 1001)
+ self.HookCommand(self.OnDeleteKey, 1002)
+ menu.TrackPopupMenu(win32api.GetCursorPos()) # track at mouse position.
+ return None
+
+ def OnDeleteKey(self, command, code):
+ hitem = self.hierList.GetSelectedItem()
+ item = self.hierList.ItemFromHandle(hitem)
+ msg = f"Are you sure you wish to delete the key '{item.keyName}'?"
+ id = win32ui.MessageBox(msg, None, win32con.MB_YESNO)
+ if id != win32con.IDYES:
+ return
+ if SafeApply(
+ win32api.RegDeleteKey, (item.keyRoot, item.keyName), "deleting registry key"
+ ):
+ # Get the items parent.
+ try:
+ hparent = self.GetParentItem(hitem)
+ except win32ui.error:
+ hparent = None
+ self.hierList.Refresh(hparent)
+
+ def OnAddKey(self, command, code):
+ val = dialog.GetSimpleInput("New key name", "", "Add new key")
+ if val is None:
+ return # cancelled.
+ hitem = self.hierList.GetSelectedItem()
+ item = self.hierList.ItemFromHandle(hitem)
+ if SafeApply(win32api.RegCreateKey, (item.keyRoot, item.keyName + "\\" + val)):
+ self.hierList.Refresh(hitem)
+
+ def OnAddValue(self, command, code):
+ val = dialog.GetSimpleInput("New value", "", "Add new value")
+ if val is None:
+ return # cancelled.
+ hitem = self.hierList.GetSelectedItem()
+ item = self.hierList.ItemFromHandle(hitem)
+ if SafeApply(
+ win32api.RegSetValue, (item.keyRoot, item.keyName, win32con.REG_SZ, val)
+ ):
+ # Simply re-select the current item to refresh the right spitter.
+ self.PerformItemSelected(item)
+
+ # self.Select(hitem, commctrl.TVGN_CARET)
+
+ def PerformItemSelected(self, item):
+ return self.frame.PerformItemSelected(item)
+
+ def SelectedItem(self):
+ return self.hierList.ItemFromHandle(self.hierList.GetSelectedItem())
+
+ def SearchSelectedItem(self):
+ handle = self.hierList.GetChildItem(0)
+ while 1:
+ # print("State is", self.hierList.GetItemState(handle, -1))
+ if self.hierList.GetItemState(handle, commctrl.TVIS_SELECTED):
+ # print("Item is ", self.hierList.ItemFromHandle(handle))
+ return self.hierList.ItemFromHandle(handle)
+ handle = self.hierList.GetNextSiblingItem(handle)
+
+
+class RegistryValueView(docview.ListView):
+ def OnInitialUpdate(self):
+ hwnd = self._obj_.GetSafeHwnd()
+ style = win32api.GetWindowLong(hwnd, win32con.GWL_STYLE)
+ win32api.SetWindowLong(
+ hwnd,
+ win32con.GWL_STYLE,
+ (style & ~commctrl.LVS_TYPEMASK) | commctrl.LVS_REPORT,
+ )
+
+ itemDetails = (commctrl.LVCFMT_LEFT, 100, "Name", 0)
+ self.InsertColumn(0, itemDetails)
+ itemDetails = (commctrl.LVCFMT_LEFT, 500, "Data", 0)
+ self.InsertColumn(1, itemDetails)
+
+ def UpdateForRegItem(self, item):
+ self.DeleteAllItems()
+ hkey = win32api.RegOpenKey(item.keyRoot, item.keyName)
+ try:
+ valNum = 0
+ ret = []
+ while 1:
+ try:
+ res = win32api.RegEnumValue(hkey, valNum)
+ except win32api.error:
+ break
+ name = res[0]
+ if not name:
+ name = "(Default)"
+ self.InsertItem(valNum, name)
+ self.SetItemText(valNum, 1, str(res[1]))
+ valNum += 1
+ finally:
+ win32api.RegCloseKey(hkey)
+
+ def EditValue(self, item):
+ # Edit the current value
+ class EditDialog(dialog.Dialog):
+ def __init__(self, item):
+ self.item = item
+ dialog.Dialog.__init__(self, win32ui.IDD_LARGE_EDIT)
+
+ def OnInitDialog(self):
+ self.SetWindowText("Enter new value")
+ self.GetDlgItem(win32con.IDCANCEL).ShowWindow(win32con.SW_SHOW)
+ self.edit = self.GetDlgItem(win32ui.IDC_EDIT1)
+ # Modify the edit windows style
+ style = win32api.GetWindowLong(
+ self.edit.GetSafeHwnd(), win32con.GWL_STYLE
+ )
+ style &= ~win32con.ES_WANTRETURN
+ win32api.SetWindowLong(
+ self.edit.GetSafeHwnd(), win32con.GWL_STYLE, style
+ )
+ self.edit.SetWindowText(str(self.item))
+ self.edit.SetSel(-1)
+ return dialog.Dialog.OnInitDialog(self)
+
+ def OnDestroy(self, msg):
+ self.newvalue = self.edit.GetWindowText()
+
+ try:
+ index = self.GetNextItem(-1, commctrl.LVNI_SELECTED)
+ except win32ui.error:
+ return # No item selected.
+
+ if index == 0:
+ keyVal = ""
+ else:
+ keyVal = self.GetItemText(index, 0)
+ # Query for a new value.
+ try:
+ newVal = self.GetItemsCurrentValue(item, keyVal)
+ except TypeError as details:
+ win32ui.MessageBox(details)
+ return
+
+ d = EditDialog(newVal)
+ if d.DoModal() == win32con.IDOK:
+ try:
+ self.SetItemsCurrentValue(item, keyVal, d.newvalue)
+ except win32api.error as exc:
+ win32ui.MessageBox("Error setting value\r\n\n%s" % exc.strerror)
+ self.UpdateForRegItem(item)
+
+ def GetItemsCurrentValue(self, item, valueName):
+ hkey = win32api.RegOpenKey(item.keyRoot, item.keyName)
+ try:
+ val, type = win32api.RegQueryValueEx(hkey, valueName)
+ if type != win32con.REG_SZ:
+ raise TypeError("Only strings can be edited")
+ return val
+ finally:
+ win32api.RegCloseKey(hkey)
+
+ def SetItemsCurrentValue(self, item, valueName, value):
+ # ** Assumes already checked is a string.
+ hkey = win32api.RegOpenKey(
+ item.keyRoot, item.keyName, 0, win32con.KEY_SET_VALUE
+ )
+ try:
+ win32api.RegSetValueEx(hkey, valueName, 0, win32con.REG_SZ, value)
+ finally:
+ win32api.RegCloseKey(hkey)
+
+
+class RegTemplate(docview.DocTemplate):
+ def __init__(self):
+ docview.DocTemplate.__init__(
+ self, win32ui.IDR_PYTHONTYPE, None, SplitterFrame, None
+ )
+
+ # def InitialUpdateFrame(self, frame, doc, makeVisible=1):
+ # self._obj_.InitialUpdateFrame(frame, doc, makeVisible) # call default handler.
+ # frame.InitialUpdateFrame(doc, makeVisible)
+
+ def OpenRegistryKey(
+ self, root=None, subkey=None
+ ): # Use this instead of OpenDocumentFile.
+ # Look for existing open document
+ if root is None:
+ root = regutil.GetRootKey()
+ if subkey is None:
+ subkey = regutil.BuildDefaultPythonKey()
+ for doc in self.GetDocumentList():
+ if doc.root == root and doc.subkey == subkey:
+ doc.GetFirstView().ActivateFrame()
+ return doc
+ # not found - new one.
+ doc = RegDocument(self, root, subkey)
+ frame = self.CreateNewFrame(doc)
+ doc.OnNewDocument()
+ self.InitialUpdateFrame(frame, doc, 1)
+ return doc
+
+
+class RegDocument(docview.Document):
+ def __init__(self, template, root, subkey):
+ docview.Document.__init__(self, template)
+ self.root = root
+ self.subkey = subkey
+ self.SetTitle("Registry Editor: " + subkey)
+
+ def OnOpenDocument(self, name):
+ raise TypeError("This template can not open files")
+ return 0
+
+
+class HLIRegistryKey(hierlist.HierListItem):
+ def __init__(self, keyRoot, keyName, userName):
+ self.keyRoot = keyRoot
+ self.keyName = keyName
+ self.userName = userName
+ hierlist.HierListItem.__init__(self)
+
+ def __lt__(self, other):
+ return self.name < other.name
+
+ def __eq__(self, other):
+ return (
+ self.keyRoot == other.keyRoot
+ and self.keyName == other.keyName
+ and self.userName == other.userName
+ )
+
+ def __repr__(self):
+ return "<{} with root={}, key={}>".format(
+ self.__class__.__name__,
+ self.keyRoot,
+ self.keyName,
+ )
+
+ def GetText(self):
+ return self.userName
+
+ def IsExpandable(self):
+ # All keys are expandable, even if they currently have zero children.
+ return 1
+
+ ## hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
+ ## try:
+ ## keys, vals, dt = win32api.RegQueryInfoKey(hkey)
+ ## return (keys>0)
+ ## finally:
+ ## win32api.RegCloseKey(hkey)
+
+ def GetSubList(self):
+ hkey = win32api.RegOpenKey(self.keyRoot, self.keyName)
+ win32ui.DoWaitCursor(1)
+ try:
+ keyNum = 0
+ ret = []
+ while 1:
+ try:
+ key = win32api.RegEnumKey(hkey, keyNum)
+ except win32api.error:
+ break
+ ret.append(HLIRegistryKey(self.keyRoot, self.keyName + "\\" + key, key))
+ keyNum += 1
+ finally:
+ win32api.RegCloseKey(hkey)
+ win32ui.DoWaitCursor(0)
+ return ret
+
+
+template = RegTemplate()
+
+
+def EditRegistry(root=None, key=None):
+ doc = template.OpenRegistryKey(root, key)
+
+
+if __name__ == "__main__":
+ EditRegistry()
diff --git a/python_embeded/Lib/site-packages/pythonwin/pywin/tools/regpy.py b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/regpy.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d4447b28008ea48c6e17346d16e9f07903de898
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pythonwin/pywin/tools/regpy.py
@@ -0,0 +1,80 @@
+# (sort-of) Registry editor
+import commctrl
+import win32con
+from pywin.mfc import dialog
+
+
+class RegistryControl:
+ def __init__(self, key):
+ self.key = key
+
+
+class RegEditPropertyPage(dialog.PropertyPage):
+ IDC_LISTVIEW = 1000
+
+ def GetTemplate(self):
+ "Return the template used to create this dialog"
+
+ w = 152 # Dialog width
+ h = 122 # Dialog height
+ SS_STD = win32con.WS_CHILD | win32con.WS_VISIBLE
+ FRAMEDLG_STD = win32con.WS_CAPTION | win32con.WS_SYSMENU
+ style = (
+ FRAMEDLG_STD
+ | win32con.WS_VISIBLE
+ | win32con.DS_SETFONT
+ | win32con.WS_MINIMIZEBOX
+ )
+ template = [
+ [self.caption, (0, 0, w, h), style, None, (8, "Helv")],
+ ]
+ lvStyle = (
+ SS_STD
+ | commctrl.LVS_EDITLABELS
+ | commctrl.LVS_REPORT
+ | commctrl.LVS_AUTOARRANGE
+ | commctrl.LVS_ALIGNLEFT
+ | win32con.WS_BORDER
+ | win32con.WS_TABSTOP
+ )
+ template.append(
+ ["SysListView32", "", self.IDC_LISTVIEW, (10, 10, 185, 100), lvStyle]
+ )
+ return template
+
+
+class RegistryPage(RegEditPropertyPage):
+ def __init__(self):
+ self.caption = "Path"
+ RegEditPropertyPage.__init__(self, self.GetTemplate())
+
+ def OnInitDialog(self):
+ self.listview = self.GetDlgItem(self.IDC_LISTVIEW)
+ RegEditPropertyPage.OnInitDialog(self)
+ # Setup the listview columns
+ itemDetails = (commctrl.LVCFMT_LEFT, 100, "App", 0)
+ self.listview.InsertColumn(0, itemDetails)
+ itemDetails = (commctrl.LVCFMT_LEFT, 1024, "Paths", 0)
+ self.listview.InsertColumn(1, itemDetails)
+
+ index = self.listview.InsertItem(0, "App")
+ self.listview.SetItemText(index, 1, "Path")
+
+
+class RegistrySheet(dialog.PropertySheet):
+ def __init__(self, title):
+ dialog.PropertySheet.__init__(self, title)
+ self.HookMessage(self.OnActivate, win32con.WM_ACTIVATE)
+
+ def OnActivate(self, msg):
+ print("OnAcivate")
+
+
+def t():
+ ps = RegistrySheet("Registry Settings")
+ ps.AddPage(RegistryPage())
+ ps.DoModal()
+
+
+if __name__ == "__main__":
+ t()
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Abidjan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Abidjan
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Abidjan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Accra b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Accra
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Accra differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Addis_Ababa b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Addis_Ababa
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Addis_Ababa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Algiers b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Algiers
new file mode 100644
index 0000000000000000000000000000000000000000..6cfd8a16e16ec08c7cd83e6c0e1f9e1bbc5dc18a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Algiers differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Asmara b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Asmara
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Asmara differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Asmera b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Asmera
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Asmera differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bamako b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bamako
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bamako differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bangui b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bangui
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bangui differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Banjul b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Banjul
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Banjul differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bissau b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bissau
new file mode 100644
index 0000000000000000000000000000000000000000..82ea5aaf0c6ae2b3ec582013b6d16e6d6f29eb0a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bissau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Blantyre b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Blantyre
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Blantyre differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Brazzaville b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Brazzaville
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Brazzaville differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bujumbura b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bujumbura
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Bujumbura differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Cairo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Cairo
new file mode 100644
index 0000000000000000000000000000000000000000..dd538c65db6ed0a0e47feb7b6001640516958e19
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Cairo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Casablanca b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Casablanca
new file mode 100644
index 0000000000000000000000000000000000000000..d39016b89d3c945030ce95f721ebb592c8105064
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Casablanca differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ceuta b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ceuta
new file mode 100644
index 0000000000000000000000000000000000000000..b41ec4f81ab104943e84105246f0e5d0157e6e2e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ceuta differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Conakry b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Conakry
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Conakry differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Dakar b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Dakar
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Dakar differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Dar_es_Salaam b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Dar_es_Salaam
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Dar_es_Salaam differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Djibouti b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Djibouti
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Djibouti differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Douala b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Douala
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Douala differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/El_Aaiun b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/El_Aaiun
new file mode 100644
index 0000000000000000000000000000000000000000..066fbed008cf662455eeca2c012ab8cb5bf1731a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/El_Aaiun differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Freetown b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Freetown
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Freetown differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Gaborone b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Gaborone
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Gaborone differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Harare b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Harare
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Harare differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Johannesburg b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Johannesburg
new file mode 100644
index 0000000000000000000000000000000000000000..b1c425daced454f53d7d18fea807bf8d081cf97e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Johannesburg differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Juba b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Juba
new file mode 100644
index 0000000000000000000000000000000000000000..06482943a45a58a02a43b9e2b6a3f215b21b045f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Juba differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kampala b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kampala
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kampala differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Khartoum b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Khartoum
new file mode 100644
index 0000000000000000000000000000000000000000..8ee8cb92e72d9c507ad0ee06dc6a38406ab06f34
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Khartoum differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kigali b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kigali
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kigali differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kinshasa b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kinshasa
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Kinshasa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lagos b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lagos
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lagos differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Libreville b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Libreville
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Libreville differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lome b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lome
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lome differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Luanda b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Luanda
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Luanda differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lubumbashi b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lubumbashi
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lubumbashi differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lusaka b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lusaka
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Lusaka differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Malabo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Malabo
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Malabo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Maputo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Maputo
new file mode 100644
index 0000000000000000000000000000000000000000..65f043f1d1833d26b5fe42a460f84b35d1dcba63
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Maputo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Maseru b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Maseru
new file mode 100644
index 0000000000000000000000000000000000000000..b1c425daced454f53d7d18fea807bf8d081cf97e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Maseru differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Mbabane b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Mbabane
new file mode 100644
index 0000000000000000000000000000000000000000..b1c425daced454f53d7d18fea807bf8d081cf97e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Mbabane differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Mogadishu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Mogadishu
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Mogadishu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Monrovia b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Monrovia
new file mode 100644
index 0000000000000000000000000000000000000000..6d688502a1ca80f2e57a6de2790ac3193879d248
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Monrovia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Nairobi b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Nairobi
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Nairobi differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ndjamena b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ndjamena
new file mode 100644
index 0000000000000000000000000000000000000000..a968845e29b8b2b47d4a73f74ae04ef681d7d485
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ndjamena differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Niamey b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Niamey
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Niamey differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Nouakchott b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Nouakchott
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Nouakchott differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ouagadougou b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ouagadougou
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Ouagadougou differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Porto-Novo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Porto-Novo
new file mode 100644
index 0000000000000000000000000000000000000000..afb6a4a8fb17b0d4670b8ea1b38f5cc6100244e4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Porto-Novo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Sao_Tome b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Sao_Tome
new file mode 100644
index 0000000000000000000000000000000000000000..59f3759c409a1fb50e632ef5ef613d3fee7af7ef
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Sao_Tome differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Timbuktu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Timbuktu
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Timbuktu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Tripoli b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Tripoli
new file mode 100644
index 0000000000000000000000000000000000000000..07b393bb7db14cef1e906ebe63cfbbe8cddc79d5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Tripoli differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Tunis b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Tunis
new file mode 100644
index 0000000000000000000000000000000000000000..427fa563033fdd8533ae56337fa20befe9719b42
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Tunis differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Windhoek b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Windhoek
new file mode 100644
index 0000000000000000000000000000000000000000..abecd137b1fc3220637b22ffea0e7256a58e9377
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Africa/Windhoek differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Adak b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Adak
new file mode 100644
index 0000000000000000000000000000000000000000..43236498f681cc06f64ca2afa613880331fe6fbb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Adak differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Anchorage b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Anchorage
new file mode 100644
index 0000000000000000000000000000000000000000..9bbb2fd3b361ea8aa4c126d14df5fa370343a63f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Anchorage differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Anguilla b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Anguilla
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Anguilla differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Antigua b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Antigua
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Antigua differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Araguaina b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Araguaina
new file mode 100644
index 0000000000000000000000000000000000000000..919723dc2ca581b4f95154d4192d8f732cc55a45
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Araguaina differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Buenos_Aires b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Buenos_Aires
new file mode 100644
index 0000000000000000000000000000000000000000..cc82e69898f161842b5001f10a84d3ac127c5c6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Buenos_Aires differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Catamarca b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Catamarca
new file mode 100644
index 0000000000000000000000000000000000000000..7268eb3738e5b3ba906f962533f48016cf3dcabc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Catamarca differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/ComodRivadavia b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/ComodRivadavia
new file mode 100644
index 0000000000000000000000000000000000000000..7268eb3738e5b3ba906f962533f48016cf3dcabc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/ComodRivadavia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Cordoba b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Cordoba
new file mode 100644
index 0000000000000000000000000000000000000000..2ad6ea5db204d599266412558f5a1fae076fc41a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Cordoba differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Jujuy b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Jujuy
new file mode 100644
index 0000000000000000000000000000000000000000..7ca0b46f680b80780981aab0699e64dd04070fe7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Jujuy differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/La_Rioja b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/La_Rioja
new file mode 100644
index 0000000000000000000000000000000000000000..a6a6694f3317a25e7bc4c66502e9f396fa106509
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/La_Rioja differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Mendoza b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Mendoza
new file mode 100644
index 0000000000000000000000000000000000000000..3232c80e2003489921578f7acbabc73fb9148205
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Mendoza differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Rio_Gallegos b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Rio_Gallegos
new file mode 100644
index 0000000000000000000000000000000000000000..8b1a2816ab136098d10a3d294993ea56b6c432dc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Rio_Gallegos differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Salta b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Salta
new file mode 100644
index 0000000000000000000000000000000000000000..7072dec22958ad5ac74ba3457a178a4faadaf570
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Salta differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/San_Juan b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/San_Juan
new file mode 100644
index 0000000000000000000000000000000000000000..f3e185c3ab516065c52557aaceaaeacae1f8b221
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/San_Juan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/San_Luis b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/San_Luis
new file mode 100644
index 0000000000000000000000000000000000000000..2d1da3ae3d6f9c6f92a8ddf01c2ff51ae28e4de2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/San_Luis differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Tucuman b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Tucuman
new file mode 100644
index 0000000000000000000000000000000000000000..c6449f582a7804ecf66858a7fceda207c5d979be
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Tucuman differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia
new file mode 100644
index 0000000000000000000000000000000000000000..e74ce049c793c96e855ebb15779887a48622bf26
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Argentina/Ushuaia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Aruba b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Aruba
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Aruba differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Asuncion b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Asuncion
new file mode 100644
index 0000000000000000000000000000000000000000..9b07a80b85687b9e52f0c1cc713bad3621919edd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Asuncion differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Atikokan b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Atikokan
new file mode 100644
index 0000000000000000000000000000000000000000..9964b9a33452f4b636f43703b7cdec4891cbda5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Atikokan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Atka b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Atka
new file mode 100644
index 0000000000000000000000000000000000000000..43236498f681cc06f64ca2afa613880331fe6fbb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Atka differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bahia b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bahia
new file mode 100644
index 0000000000000000000000000000000000000000..0b65e49fca21f1be92c3ab0dfa4cd05137f028b2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bahia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bahia_Banderas b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bahia_Banderas
new file mode 100644
index 0000000000000000000000000000000000000000..3a493e3d5a93f08201c41cb25616015963254589
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bahia_Banderas differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Barbados b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Barbados
new file mode 100644
index 0000000000000000000000000000000000000000..00cd045ac86d6060e9e8b8dc0460caa49d2479b5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Barbados differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Belem b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Belem
new file mode 100644
index 0000000000000000000000000000000000000000..0ae1202682c94ee52f74a795099f6a11d34e0d1e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Belem differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Belize b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Belize
new file mode 100644
index 0000000000000000000000000000000000000000..e6f5dfa6a8d82523e8cb12f17cf73560bc09a383
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Belize differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Blanc-Sablon b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Blanc-Sablon
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Blanc-Sablon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Boa_Vista b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Boa_Vista
new file mode 100644
index 0000000000000000000000000000000000000000..08d518b151425f85458727fbf69f6e601f12be86
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Boa_Vista differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bogota b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bogota
new file mode 100644
index 0000000000000000000000000000000000000000..331a1b7c4c3af257841900fe076e5393e15db100
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Bogota differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Boise b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Boise
new file mode 100644
index 0000000000000000000000000000000000000000..aad1d991c49c2e0fa28be3da4de447af33c8df1c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Boise differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Buenos_Aires b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Buenos_Aires
new file mode 100644
index 0000000000000000000000000000000000000000..cc82e69898f161842b5001f10a84d3ac127c5c6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Buenos_Aires differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cambridge_Bay b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cambridge_Bay
new file mode 100644
index 0000000000000000000000000000000000000000..7e58a203c6bdc9045092f879f8f58aa960084cad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cambridge_Bay differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Campo_Grande b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Campo_Grande
new file mode 100644
index 0000000000000000000000000000000000000000..53b3330fac2bd64c02d8dc171c722ec491bea41d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Campo_Grande differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cancun b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cancun
new file mode 100644
index 0000000000000000000000000000000000000000..0f7771e851b0e4242bcc65a9b838b8a1675541fb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cancun differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Caracas b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Caracas
new file mode 100644
index 0000000000000000000000000000000000000000..3f3ebc9c410fe2a33ad26a5d02bb99b9503e1f72
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Caracas differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Catamarca b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Catamarca
new file mode 100644
index 0000000000000000000000000000000000000000..7268eb3738e5b3ba906f962533f48016cf3dcabc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Catamarca differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cayenne b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cayenne
new file mode 100644
index 0000000000000000000000000000000000000000..e898594276143fa4cfd5d3815c4598b9e58dba07
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cayenne differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cayman b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cayman
new file mode 100644
index 0000000000000000000000000000000000000000..9964b9a33452f4b636f43703b7cdec4891cbda5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cayman differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Chicago b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Chicago
new file mode 100644
index 0000000000000000000000000000000000000000..c6981a06b1d9c26f447518efe265a6454726eae7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Chicago differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Chihuahua b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Chihuahua
new file mode 100644
index 0000000000000000000000000000000000000000..667a2191145170e34271bb2200b93a2eec41d2ba
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Chihuahua differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ciudad_Juarez b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ciudad_Juarez
new file mode 100644
index 0000000000000000000000000000000000000000..29af5982ac1c04357634570f15454d6f7fc30e04
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ciudad_Juarez differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Coral_Harbour b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Coral_Harbour
new file mode 100644
index 0000000000000000000000000000000000000000..9964b9a33452f4b636f43703b7cdec4891cbda5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Coral_Harbour differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cordoba b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cordoba
new file mode 100644
index 0000000000000000000000000000000000000000..2ad6ea5db204d599266412558f5a1fae076fc41a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cordoba differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Costa_Rica b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Costa_Rica
new file mode 100644
index 0000000000000000000000000000000000000000..37cb85e4dbfb7ac9c01eecf584a1a721ed251e93
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Costa_Rica differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Coyhaique b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Coyhaique
new file mode 100644
index 0000000000000000000000000000000000000000..e0c6832bb36bde2468038a1e8fa25f89835a4e5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Coyhaique differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Creston b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Creston
new file mode 100644
index 0000000000000000000000000000000000000000..ab37e845566aa95659b7b85be0051d0c67a7e53a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Creston differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cuiaba b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cuiaba
new file mode 100644
index 0000000000000000000000000000000000000000..26e97f6ebfc60c1517244840b77dbaedcbfabaaa
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Cuiaba differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Curacao b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Curacao
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Curacao differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Danmarkshavn b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Danmarkshavn
new file mode 100644
index 0000000000000000000000000000000000000000..9549adcb657569ea304592a4070ceecb4550a4db
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Danmarkshavn differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dawson b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dawson
new file mode 100644
index 0000000000000000000000000000000000000000..343b63227d2185863cd720bf449de000bbc794d0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dawson differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dawson_Creek b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dawson_Creek
new file mode 100644
index 0000000000000000000000000000000000000000..db9e3396557652707c0c2232e119e13a2dd172fb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dawson_Creek differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Denver b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Denver
new file mode 100644
index 0000000000000000000000000000000000000000..abb2b974a47eb3e5c8b4f5d4370baf4898b239ab
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Denver differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Detroit b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Detroit
new file mode 100644
index 0000000000000000000000000000000000000000..e104faa46545ee873295cde34e1d46bccad8647c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Detroit differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dominica b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dominica
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Dominica differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Edmonton b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Edmonton
new file mode 100644
index 0000000000000000000000000000000000000000..cd78a6f8be1dd55ac5afd25bbae39bd5706e42d1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Edmonton differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Eirunepe b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Eirunepe
new file mode 100644
index 0000000000000000000000000000000000000000..d4c46e3091fe37b7db8d8b67d383302cd667987e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Eirunepe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/El_Salvador b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/El_Salvador
new file mode 100644
index 0000000000000000000000000000000000000000..e2f22304aad56062cfb66d23f3a8c296689286ed
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/El_Salvador differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ensenada b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ensenada
new file mode 100644
index 0000000000000000000000000000000000000000..0fe73912cacab6c8aabef4f4264d1710825888e7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ensenada differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fort_Nelson b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fort_Nelson
new file mode 100644
index 0000000000000000000000000000000000000000..5a0b7f1ca032be1adf8ba91f863e727c5ec6a026
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fort_Nelson differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fort_Wayne b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fort_Wayne
new file mode 100644
index 0000000000000000000000000000000000000000..a84b6e99671f7305d1c459956e16a4dd772fc60e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fort_Wayne differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fortaleza b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fortaleza
new file mode 100644
index 0000000000000000000000000000000000000000..bee1a95152cbc37db7117d996d370ff9d3f11f79
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Fortaleza differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Glace_Bay b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Glace_Bay
new file mode 100644
index 0000000000000000000000000000000000000000..48412a4cbf9241ea83887876b1b8b22c367ff4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Glace_Bay differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Godthab b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Godthab
new file mode 100644
index 0000000000000000000000000000000000000000..29958cf12a9df7cf775e3337b4894e4cf4b82f58
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Godthab differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Goose_Bay b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Goose_Bay
new file mode 100644
index 0000000000000000000000000000000000000000..a3f299079aebb8524bf77e7f92e0a7e6d0a7b6fb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Goose_Bay differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Grand_Turk b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Grand_Turk
new file mode 100644
index 0000000000000000000000000000000000000000..06da1a6d7a3eeec0e82f7c5815a8fed4252e16b2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Grand_Turk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Grenada b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Grenada
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Grenada differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guadeloupe b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guadeloupe
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guadeloupe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guatemala b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guatemala
new file mode 100644
index 0000000000000000000000000000000000000000..407138caf94e467b52d925f96ad80b506e16d9ec
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guatemala differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guayaquil b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guayaquil
new file mode 100644
index 0000000000000000000000000000000000000000..40831be11e0ab028ada80cecf5fdc0e2a233ee17
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guayaquil differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guyana b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guyana
new file mode 100644
index 0000000000000000000000000000000000000000..9b7036723053b8e8e3888b0497528fe714b5b735
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Guyana differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Halifax b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Halifax
new file mode 100644
index 0000000000000000000000000000000000000000..756099abe6cee44295a5566ad6cd0c352fb82e64
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Halifax differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Havana b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Havana
new file mode 100644
index 0000000000000000000000000000000000000000..b69ac4510784f23ee794cd6d11e62315a7318e5e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Havana differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Hermosillo b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Hermosillo
new file mode 100644
index 0000000000000000000000000000000000000000..441fe3f2dd133fd081247131d860bac327107499
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Hermosillo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis
new file mode 100644
index 0000000000000000000000000000000000000000..a84b6e99671f7305d1c459956e16a4dd772fc60e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Indianapolis differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Knox b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Knox
new file mode 100644
index 0000000000000000000000000000000000000000..025d132dd48ba978c6fedf86d70173127be49d49
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Knox differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Marengo b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Marengo
new file mode 100644
index 0000000000000000000000000000000000000000..677bbff6a9d89180cfd2dd3279a1c412610b6540
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Marengo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Petersburg b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Petersburg
new file mode 100644
index 0000000000000000000000000000000000000000..3082de00c2e0bfe89d4ac5e093d9e5921aa63610
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Petersburg differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Tell_City b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Tell_City
new file mode 100644
index 0000000000000000000000000000000000000000..103c5cb31795edc15d548ef4ca71f1e04e2996b5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Tell_City differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Vevay b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Vevay
new file mode 100644
index 0000000000000000000000000000000000000000..315b4c45aef1f241d025900544133c085fe4f69d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Vevay differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Vincennes b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Vincennes
new file mode 100644
index 0000000000000000000000000000000000000000..35a24133446b9ee1e8f8a7931519d93517130315
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Vincennes differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Winamac b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Winamac
new file mode 100644
index 0000000000000000000000000000000000000000..6d4e19377e9f70c3782daa223753c640c60ab1eb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indiana/Winamac differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indianapolis b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indianapolis
new file mode 100644
index 0000000000000000000000000000000000000000..a84b6e99671f7305d1c459956e16a4dd772fc60e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Indianapolis differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Inuvik b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Inuvik
new file mode 100644
index 0000000000000000000000000000000000000000..04c2df456ff0f879a419331dc3e9f4d4f68f0ecd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Inuvik differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Iqaluit b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Iqaluit
new file mode 100644
index 0000000000000000000000000000000000000000..0b47b9032f11d4ea7dd6ac51aa329f7a98253638
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Iqaluit differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Jamaica b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Jamaica
new file mode 100644
index 0000000000000000000000000000000000000000..2a9b7fd52d37a1ffe9fc589daa04d88c6c71a6e0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Jamaica differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Jujuy b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Jujuy
new file mode 100644
index 0000000000000000000000000000000000000000..7ca0b46f680b80780981aab0699e64dd04070fe7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Jujuy differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Juneau b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Juneau
new file mode 100644
index 0000000000000000000000000000000000000000..451f3490096338f40e601628ac70f04112ace51d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Juneau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kentucky/Louisville b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kentucky/Louisville
new file mode 100644
index 0000000000000000000000000000000000000000..3a335b37165d2b3d6a09a1716cb158e272087c9f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kentucky/Louisville differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kentucky/Monticello b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kentucky/Monticello
new file mode 100644
index 0000000000000000000000000000000000000000..576f16bb2b21a7e0871a7222241ad65e533bb93a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kentucky/Monticello differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Knox_IN b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Knox_IN
new file mode 100644
index 0000000000000000000000000000000000000000..025d132dd48ba978c6fedf86d70173127be49d49
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Knox_IN differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kralendijk b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kralendijk
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Kralendijk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/La_Paz b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/La_Paz
new file mode 100644
index 0000000000000000000000000000000000000000..374586ea67601c4512b52859ff4e73bb30dbecc0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/La_Paz differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Lima b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Lima
new file mode 100644
index 0000000000000000000000000000000000000000..c13bb6be45a3be6cc747d056c571623528dc1e34
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Lima differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Los_Angeles b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Los_Angeles
new file mode 100644
index 0000000000000000000000000000000000000000..610e7af5fc13d9784de30d272c7c39d7938873a0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Los_Angeles differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Louisville b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Louisville
new file mode 100644
index 0000000000000000000000000000000000000000..3a335b37165d2b3d6a09a1716cb158e272087c9f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Louisville differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Lower_Princes b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Lower_Princes
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Lower_Princes differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Maceio b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Maceio
new file mode 100644
index 0000000000000000000000000000000000000000..437a47310ec174736b0efbbe9e7e9a8cc26c150c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Maceio differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Managua b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Managua
new file mode 100644
index 0000000000000000000000000000000000000000..e0242bff6e5df45de8b235abb4a8405fbb8ba6a6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Managua differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Manaus b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Manaus
new file mode 100644
index 0000000000000000000000000000000000000000..2708baea5af1d5169a1cebd00c4762d6bb937fda
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Manaus differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Marigot b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Marigot
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Marigot differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Martinique b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Martinique
new file mode 100644
index 0000000000000000000000000000000000000000..8df43dcf1c9f63d3ea9f056f062ea97e5c7c0b57
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Martinique differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Matamoros b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Matamoros
new file mode 100644
index 0000000000000000000000000000000000000000..bbe04e86610a302d0a4deb36dd56f17673f2d3dc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Matamoros differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mazatlan b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mazatlan
new file mode 100644
index 0000000000000000000000000000000000000000..386616a59cdb2a21f1f24a6c72526bce0360cd24
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mazatlan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mendoza b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mendoza
new file mode 100644
index 0000000000000000000000000000000000000000..3232c80e2003489921578f7acbabc73fb9148205
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mendoza differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Menominee b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Menominee
new file mode 100644
index 0000000000000000000000000000000000000000..314613866de53e1457f6cbf2fb617be7e4955edf
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Menominee differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Merida b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Merida
new file mode 100644
index 0000000000000000000000000000000000000000..c4b9b4e8801cd9447d3bbb6ebff71e26df669c3c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Merida differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Metlakatla b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Metlakatla
new file mode 100644
index 0000000000000000000000000000000000000000..1e94be3d552ea0d6e29824469866c2a51a187be9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Metlakatla differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mexico_City b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mexico_City
new file mode 100644
index 0000000000000000000000000000000000000000..ad70cf3e08498845aaafc38e4eccca7461c8d337
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Mexico_City differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Miquelon b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Miquelon
new file mode 100644
index 0000000000000000000000000000000000000000..f780ea990ff22675b5cc4e4dbe2c8690ae4e41b4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Miquelon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Moncton b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Moncton
new file mode 100644
index 0000000000000000000000000000000000000000..9df8d0f2ec9fc8f1974d83cdd8155c79340007ed
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Moncton differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Monterrey b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Monterrey
new file mode 100644
index 0000000000000000000000000000000000000000..2d7993a0d71720493175bd05b2b0b7409d67407a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Monterrey differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montevideo b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montevideo
new file mode 100644
index 0000000000000000000000000000000000000000..e7bbfbb8c332fee14ae1b4aa07cc4d128e6a3ca7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montevideo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montreal b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montreal
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montreal differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montserrat b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montserrat
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Montserrat differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nassau b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nassau
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nassau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/New_York b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/New_York
new file mode 100644
index 0000000000000000000000000000000000000000..a8b9ab1992257d721ad627b14f535c3d4b020888
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/New_York differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nipigon b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nipigon
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nipigon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nome b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nome
new file mode 100644
index 0000000000000000000000000000000000000000..10998df3bbe67aa8a02602301d10ec2b2c33006b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nome differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Noronha b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Noronha
new file mode 100644
index 0000000000000000000000000000000000000000..73b4b336ab55544e6061409261c16cacc39aff61
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Noronha differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/Beulah b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/Beulah
new file mode 100644
index 0000000000000000000000000000000000000000..33e317e25b127335de68052f57d33ceed620524e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/Beulah differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/Center b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/Center
new file mode 100644
index 0000000000000000000000000000000000000000..17fe13bcc1c73ecbc6738499667816f54c164e39
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/Center differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/New_Salem b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/New_Salem
new file mode 100644
index 0000000000000000000000000000000000000000..12dbe801aeb06823483525727f6f6695dec1bc24
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/North_Dakota/New_Salem differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nuuk b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nuuk
new file mode 100644
index 0000000000000000000000000000000000000000..29958cf12a9df7cf775e3337b4894e4cf4b82f58
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Nuuk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ojinaga b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ojinaga
new file mode 100644
index 0000000000000000000000000000000000000000..45118a4f4b73e55879aaa81a8536e7214538f0e8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Ojinaga differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Panama b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Panama
new file mode 100644
index 0000000000000000000000000000000000000000..9964b9a33452f4b636f43703b7cdec4891cbda5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Panama differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Pangnirtung b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Pangnirtung
new file mode 100644
index 0000000000000000000000000000000000000000..0b47b9032f11d4ea7dd6ac51aa329f7a98253638
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Pangnirtung differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Paramaribo b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Paramaribo
new file mode 100644
index 0000000000000000000000000000000000000000..f1b82b4f9a546fd067cf043ba5d35da6fbe41fbe
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Paramaribo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Phoenix b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Phoenix
new file mode 100644
index 0000000000000000000000000000000000000000..ab37e845566aa95659b7b85be0051d0c67a7e53a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Phoenix differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Port-au-Prince b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Port-au-Prince
new file mode 100644
index 0000000000000000000000000000000000000000..287f1439266639f9564149d6e162feaba3fbed86
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Port-au-Prince differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Port_of_Spain b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Port_of_Spain
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Port_of_Spain differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Porto_Acre b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Porto_Acre
new file mode 100644
index 0000000000000000000000000000000000000000..cdda168cb97b1d45a4f1b7791a74523b74c88e6d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Porto_Acre differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Porto_Velho b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Porto_Velho
new file mode 100644
index 0000000000000000000000000000000000000000..e00398602c634e6f1e9c0bc0e12b064f343ffe0c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Porto_Velho differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Puerto_Rico b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Puerto_Rico
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Puerto_Rico differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Punta_Arenas b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Punta_Arenas
new file mode 100644
index 0000000000000000000000000000000000000000..411a839b84d3c629bf7eb623024077efe614ed07
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Punta_Arenas differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rainy_River b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rainy_River
new file mode 100644
index 0000000000000000000000000000000000000000..ac40299f6b27043e8f2454ac594b0ec184c1a237
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rainy_River differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rankin_Inlet b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rankin_Inlet
new file mode 100644
index 0000000000000000000000000000000000000000..e2714921a8f3c05189d20a9151931fb6eadf493b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rankin_Inlet differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Recife b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Recife
new file mode 100644
index 0000000000000000000000000000000000000000..5bf6c211c19b7cd37107a2e3b317c2a7195c2947
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Recife differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Regina b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Regina
new file mode 100644
index 0000000000000000000000000000000000000000..20c9c84df491e4072ec4c5d2c931a7433d9fd394
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Regina differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Resolute b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Resolute
new file mode 100644
index 0000000000000000000000000000000000000000..19668900dea9249c1714b8838e44ac2070069138
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Resolute differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rio_Branco b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rio_Branco
new file mode 100644
index 0000000000000000000000000000000000000000..cdda168cb97b1d45a4f1b7791a74523b74c88e6d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rio_Branco differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rosario b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rosario
new file mode 100644
index 0000000000000000000000000000000000000000..2ad6ea5db204d599266412558f5a1fae076fc41a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Rosario differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santa_Isabel b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santa_Isabel
new file mode 100644
index 0000000000000000000000000000000000000000..0fe73912cacab6c8aabef4f4264d1710825888e7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santa_Isabel differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santarem b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santarem
new file mode 100644
index 0000000000000000000000000000000000000000..001638c2f2a964eb2cc75660f66a1bcc447d7a57
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santarem differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santiago b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santiago
new file mode 100644
index 0000000000000000000000000000000000000000..010c6bd04cae79078540da560ce38400bfe0ade6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santiago differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santo_Domingo b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santo_Domingo
new file mode 100644
index 0000000000000000000000000000000000000000..4fe36fd4c11f998ba3f626c5e23d97bd82d12791
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Santo_Domingo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Sao_Paulo b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Sao_Paulo
new file mode 100644
index 0000000000000000000000000000000000000000..67935ff4da8f527e03cd05ed2aa20e601e10f921
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Sao_Paulo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Scoresbysund b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Scoresbysund
new file mode 100644
index 0000000000000000000000000000000000000000..9bf411ef5ad5f81f3863223ea75117404d5d1421
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Scoresbysund differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Shiprock b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Shiprock
new file mode 100644
index 0000000000000000000000000000000000000000..abb2b974a47eb3e5c8b4f5d4370baf4898b239ab
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Shiprock differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Sitka b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Sitka
new file mode 100644
index 0000000000000000000000000000000000000000..31f7061371910ad42e4310b7a646ba1a98b6cba4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Sitka differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Barthelemy b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Barthelemy
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Barthelemy differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Johns b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Johns
new file mode 100644
index 0000000000000000000000000000000000000000..65a5b0c720dad151ffdcba3dbe91c8bd638845c6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Johns differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Kitts b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Kitts
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Kitts differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Lucia b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Lucia
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Lucia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Thomas b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Thomas
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Thomas differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Vincent b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Vincent
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/St_Vincent differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Swift_Current b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Swift_Current
new file mode 100644
index 0000000000000000000000000000000000000000..8e9ef255eeb11515b84126d9ee5c0c6b3c72f2a0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Swift_Current differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tegucigalpa b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tegucigalpa
new file mode 100644
index 0000000000000000000000000000000000000000..2adacb2e500e2f9621b2debc1756d308747b67f6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tegucigalpa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Thule b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Thule
new file mode 100644
index 0000000000000000000000000000000000000000..6f802f1c2acf9cc73481ae86c9e099fcfc28cf25
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Thule differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Thunder_Bay b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Thunder_Bay
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Thunder_Bay differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tijuana b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tijuana
new file mode 100644
index 0000000000000000000000000000000000000000..0fe73912cacab6c8aabef4f4264d1710825888e7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tijuana differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Toronto b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Toronto
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Toronto differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tortola b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tortola
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Tortola differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Vancouver b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Vancouver
new file mode 100644
index 0000000000000000000000000000000000000000..bb60cbced30763c08b6cf73554c8d6651ff387d0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Vancouver differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Virgin b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Virgin
new file mode 100644
index 0000000000000000000000000000000000000000..a662a57137b69e8ba445e899566222cdd422a764
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Virgin differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Whitehorse b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Whitehorse
new file mode 100644
index 0000000000000000000000000000000000000000..318c4a8e4003bcff00f9a21e294e7815f170235b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Whitehorse differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Winnipeg b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Winnipeg
new file mode 100644
index 0000000000000000000000000000000000000000..ac40299f6b27043e8f2454ac594b0ec184c1a237
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Winnipeg differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Yakutat b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Yakutat
new file mode 100644
index 0000000000000000000000000000000000000000..da209f9f0a07625ec83d4ec84917216347f5687f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Yakutat differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Yellowknife b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Yellowknife
new file mode 100644
index 0000000000000000000000000000000000000000..cd78a6f8be1dd55ac5afd25bbae39bd5706e42d1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/America/Yellowknife differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Casey b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Casey
new file mode 100644
index 0000000000000000000000000000000000000000..586a7653ef20d04440bfcb6645454ef215a1bba4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Casey differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Davis b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Davis
new file mode 100644
index 0000000000000000000000000000000000000000..d4d47b24647bcabc981440f0859e94228428798d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Davis differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/DumontDUrville b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/DumontDUrville
new file mode 100644
index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/DumontDUrville differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Macquarie b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Macquarie
new file mode 100644
index 0000000000000000000000000000000000000000..9e7cc687d76b00d8f112245d5c5d2f20a2a61814
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Macquarie differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Mawson b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Mawson
new file mode 100644
index 0000000000000000000000000000000000000000..6d93f6e1d3f76bcb6325f503958d19798b098fa0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Mawson differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/McMurdo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/McMurdo
new file mode 100644
index 0000000000000000000000000000000000000000..6575fdce31183d8238b18f2f30ab5b9227c7071c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/McMurdo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Palmer b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Palmer
new file mode 100644
index 0000000000000000000000000000000000000000..9c8fd317e0537afd4066001f6700cd6490fbe5a8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Palmer differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Rothera b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Rothera
new file mode 100644
index 0000000000000000000000000000000000000000..241cc44d507c50777f7225df197765e522f22313
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Rothera differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/South_Pole b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/South_Pole
new file mode 100644
index 0000000000000000000000000000000000000000..6575fdce31183d8238b18f2f30ab5b9227c7071c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/South_Pole differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Syowa b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Syowa
new file mode 100644
index 0000000000000000000000000000000000000000..8c8062471dce91a5be827d6908795ee7391a4afc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Syowa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Troll b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Troll
new file mode 100644
index 0000000000000000000000000000000000000000..a1dcea14de9cfb95311ebe94e8a1096c27800941
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Troll differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Vostok b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Vostok
new file mode 100644
index 0000000000000000000000000000000000000000..016e06b1bbc8d2e73d07265ef12e2be0c77982f4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Antarctica/Vostok differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Arctic/Longyearbyen b/python_embeded/Lib/site-packages/pytz/zoneinfo/Arctic/Longyearbyen
new file mode 100644
index 0000000000000000000000000000000000000000..7f6d958f8630cba512d8e58ca8edfbd516291522
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Arctic/Longyearbyen differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aden b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aden
new file mode 100644
index 0000000000000000000000000000000000000000..8c8062471dce91a5be827d6908795ee7391a4afc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aden differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Almaty b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Almaty
new file mode 100644
index 0000000000000000000000000000000000000000..855abbd6e3ee338c3d46bee7b592f3d645d2c273
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Almaty differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Amman b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Amman
new file mode 100644
index 0000000000000000000000000000000000000000..0a8e350a334bbee29b155fb9944c6831460d973e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Amman differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Anadyr b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Anadyr
new file mode 100644
index 0000000000000000000000000000000000000000..35c531c0709fabace97e52cacef74b4cfbbcd820
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Anadyr differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aqtau b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aqtau
new file mode 100644
index 0000000000000000000000000000000000000000..0e1c16d32eca7652aa7e1392e606cf5b54e26bc5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aqtau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aqtobe b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aqtobe
new file mode 100644
index 0000000000000000000000000000000000000000..3b5d6eb41883a7b32819f387b4c03c93e9d489cf
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Aqtobe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ashgabat b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ashgabat
new file mode 100644
index 0000000000000000000000000000000000000000..2bd1cb3da0f5a11024f1609b09ae68645e6ae75c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ashgabat differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ashkhabad b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ashkhabad
new file mode 100644
index 0000000000000000000000000000000000000000..2bd1cb3da0f5a11024f1609b09ae68645e6ae75c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ashkhabad differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Atyrau b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Atyrau
new file mode 100644
index 0000000000000000000000000000000000000000..e7ea9c545a56ae0b0fabd02e47748004a6d87c3b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Atyrau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Baghdad b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Baghdad
new file mode 100644
index 0000000000000000000000000000000000000000..c0e607234a07cd2650aabc1fd022bd5d4f99b175
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Baghdad differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bahrain b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bahrain
new file mode 100644
index 0000000000000000000000000000000000000000..098997e7dd972ca4acedc535c4a645ee966baa33
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bahrain differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Baku b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Baku
new file mode 100644
index 0000000000000000000000000000000000000000..ae0ce4e7c3d273b537fa3653784e73be68ebb441
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Baku differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bangkok b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bangkok
new file mode 100644
index 0000000000000000000000000000000000000000..fa799db39e7625dd74bd9caa5c29b4819a7cbd3f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bangkok differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Barnaul b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Barnaul
new file mode 100644
index 0000000000000000000000000000000000000000..2f6b8101d474642410af84260fb2b88c493945b1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Barnaul differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Beirut b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Beirut
new file mode 100644
index 0000000000000000000000000000000000000000..fb266ede2279b6aff913538d9d5aae3935e53aeb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Beirut differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bishkek b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bishkek
new file mode 100644
index 0000000000000000000000000000000000000000..547fd5e1bd16152073f7237ad265b5c643e7cbfe
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Bishkek differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Brunei b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Brunei
new file mode 100644
index 0000000000000000000000000000000000000000..098c6a0b0afc2c3ef3a6937104d270074ff2a9b6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Brunei differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Calcutta b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Calcutta
new file mode 100644
index 0000000000000000000000000000000000000000..0014046d29a38e9b8006f746fea794d7f71eb479
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Calcutta differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chita b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chita
new file mode 100644
index 0000000000000000000000000000000000000000..75b3d7b3a6b3bf2b7459532fce1142912b897efd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chita differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Choibalsan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Choibalsan
new file mode 100644
index 0000000000000000000000000000000000000000..2aa5cc4b84d369b03684c30cdb66b7abf087f467
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Choibalsan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chongqing b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chongqing
new file mode 100644
index 0000000000000000000000000000000000000000..91f6f8bc2e234bafd484146986bdb289082c3588
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chongqing differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chungking b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chungking
new file mode 100644
index 0000000000000000000000000000000000000000..91f6f8bc2e234bafd484146986bdb289082c3588
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Chungking differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Colombo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Colombo
new file mode 100644
index 0000000000000000000000000000000000000000..353fe2aa3564c79809e05e12711f90669e5e2388
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Colombo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dacca b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dacca
new file mode 100644
index 0000000000000000000000000000000000000000..3cf597d83f90403132573d78247e6d02e66d0583
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dacca differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Damascus b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Damascus
new file mode 100644
index 0000000000000000000000000000000000000000..afd956c878856e0e239887963b32ddb8327ccf38
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Damascus differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dhaka b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dhaka
new file mode 100644
index 0000000000000000000000000000000000000000..3cf597d83f90403132573d78247e6d02e66d0583
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dhaka differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dili b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dili
new file mode 100644
index 0000000000000000000000000000000000000000..4614e4fc4353a7094ba5173a0bd09158ef49d9a9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dili differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dubai b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dubai
new file mode 100644
index 0000000000000000000000000000000000000000..b3ac791aef4e73d6d644c40c614f37f15d462cdd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dubai differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dushanbe b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dushanbe
new file mode 100644
index 0000000000000000000000000000000000000000..89e875beaef780b2ceae08ee4703cd813f33d6a4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Dushanbe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Famagusta b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Famagusta
new file mode 100644
index 0000000000000000000000000000000000000000..653b146a60e5e5641a07bfc82f9590dad1ed69f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Famagusta differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Gaza b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Gaza
new file mode 100644
index 0000000000000000000000000000000000000000..dd5781e8ae26ed66aa2650c580c561fae50df4b5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Gaza differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Harbin b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Harbin
new file mode 100644
index 0000000000000000000000000000000000000000..91f6f8bc2e234bafd484146986bdb289082c3588
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Harbin differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hebron b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hebron
new file mode 100644
index 0000000000000000000000000000000000000000..a64fc9e7b2599e8f60d228ef3cf1743b5296cd4f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hebron differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ho_Chi_Minh b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ho_Chi_Minh
new file mode 100644
index 0000000000000000000000000000000000000000..9c45ed991a230919d129c63c660aa8d1ad74d0ea
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ho_Chi_Minh differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hong_Kong b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hong_Kong
new file mode 100644
index 0000000000000000000000000000000000000000..f9f7b134dd5c35e4718c6fa3697024cb95442c53
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hong_Kong differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hovd b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hovd
new file mode 100644
index 0000000000000000000000000000000000000000..8b9abca344daf199b554888fc4fff562a7a18e4a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Hovd differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Irkutsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Irkutsk
new file mode 100644
index 0000000000000000000000000000000000000000..e74a4d3f6b3a799b0fd12272c3aae0f084fb2783
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Irkutsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Istanbul b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Istanbul
new file mode 100644
index 0000000000000000000000000000000000000000..7c2336dd80c3c9cbf71cb53d2b2c1f89a65a8ba5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Istanbul differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jakarta b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jakarta
new file mode 100644
index 0000000000000000000000000000000000000000..ec4bd5747a8c9c528dfd22c8e3171851784ade59
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jakarta differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jayapura b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jayapura
new file mode 100644
index 0000000000000000000000000000000000000000..3002c82022f7e9a4ff1ad545ea617106a13b24e0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jayapura differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jerusalem b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jerusalem
new file mode 100644
index 0000000000000000000000000000000000000000..1ebd0664aa29c0abd722661f761031ec0304631c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Jerusalem differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kabul b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kabul
new file mode 100644
index 0000000000000000000000000000000000000000..661efc83294edbe5f615daa87a1f4a5590aae167
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kabul differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kamchatka b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kamchatka
new file mode 100644
index 0000000000000000000000000000000000000000..99776f515fd53a86a6886311d91ff33b401396c3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kamchatka differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Karachi b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Karachi
new file mode 100644
index 0000000000000000000000000000000000000000..ba65c0e8d31cb1d59935878af29baac722f45936
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Karachi differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kashgar b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kashgar
new file mode 100644
index 0000000000000000000000000000000000000000..62bdcac14db3f464ff561e32db2c6b55c0cb1866
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kashgar differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kathmandu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kathmandu
new file mode 100644
index 0000000000000000000000000000000000000000..751cf4a8939e898f8abe4358a98b2a5f59f65e21
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kathmandu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Katmandu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Katmandu
new file mode 100644
index 0000000000000000000000000000000000000000..751cf4a8939e898f8abe4358a98b2a5f59f65e21
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Katmandu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Khandyga b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Khandyga
new file mode 100644
index 0000000000000000000000000000000000000000..7cdc99a9803f4e1ce3c5f7f9e6cd761f178536ae
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Khandyga differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kolkata b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kolkata
new file mode 100644
index 0000000000000000000000000000000000000000..0014046d29a38e9b8006f746fea794d7f71eb479
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kolkata differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Krasnoyarsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Krasnoyarsk
new file mode 100644
index 0000000000000000000000000000000000000000..4c27b2decd1159cf47285f0b18b5ed5178641e82
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Krasnoyarsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuala_Lumpur b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuala_Lumpur
new file mode 100644
index 0000000000000000000000000000000000000000..3d9f191e3acad56fb4f73ab44a74c50cdf91c12e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuala_Lumpur differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuching b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuching
new file mode 100644
index 0000000000000000000000000000000000000000..098c6a0b0afc2c3ef3a6937104d270074ff2a9b6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuching differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuwait b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuwait
new file mode 100644
index 0000000000000000000000000000000000000000..8c8062471dce91a5be827d6908795ee7391a4afc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Kuwait differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Macao b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Macao
new file mode 100644
index 0000000000000000000000000000000000000000..cac65063d0dbf48e37c547fba3b67f34110d5a90
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Macao differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Macau b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Macau
new file mode 100644
index 0000000000000000000000000000000000000000..cac65063d0dbf48e37c547fba3b67f34110d5a90
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Macau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Magadan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Magadan
new file mode 100644
index 0000000000000000000000000000000000000000..70c198baf743457c58a8fe4d1f28186d8541a505
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Magadan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Makassar b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Makassar
new file mode 100644
index 0000000000000000000000000000000000000000..556ba866933d37f3cfcf8042045d64e209bae30f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Makassar differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Manila b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Manila
new file mode 100644
index 0000000000000000000000000000000000000000..168f72096d96e9f8a6dc4c6073086c19dbc20d0d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Manila differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Muscat b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Muscat
new file mode 100644
index 0000000000000000000000000000000000000000..b3ac791aef4e73d6d644c40c614f37f15d462cdd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Muscat differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Nicosia b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Nicosia
new file mode 100644
index 0000000000000000000000000000000000000000..f7f10ab7665e94ca44fd8cd98a362cd4b304eff1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Nicosia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Novokuznetsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Novokuznetsk
new file mode 100644
index 0000000000000000000000000000000000000000..a5e1b79600d21019a3b93f3e2d796129d9b1d655
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Novokuznetsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Novosibirsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Novosibirsk
new file mode 100644
index 0000000000000000000000000000000000000000..4ac7582ad5ee895bf9b354436142fd7ece1996ee
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Novosibirsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Omsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Omsk
new file mode 100644
index 0000000000000000000000000000000000000000..16c5f3cfed75151d50ffc2dc483ac6279816a01f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Omsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Oral b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Oral
new file mode 100644
index 0000000000000000000000000000000000000000..3b9ecacf6eef72366df1cc847c0d4666efc8a48c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Oral differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Phnom_Penh b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Phnom_Penh
new file mode 100644
index 0000000000000000000000000000000000000000..fa799db39e7625dd74bd9caa5c29b4819a7cbd3f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Phnom_Penh differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Pontianak b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Pontianak
new file mode 100644
index 0000000000000000000000000000000000000000..12ce24cbeae404efe6921081d21289be452ff88d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Pontianak differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Pyongyang b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Pyongyang
new file mode 100644
index 0000000000000000000000000000000000000000..7ad7e0b2cf8fa4fc844fe8cc9c58e4f3018cead1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Pyongyang differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qatar b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qatar
new file mode 100644
index 0000000000000000000000000000000000000000..098997e7dd972ca4acedc535c4a645ee966baa33
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qatar differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qostanay b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qostanay
new file mode 100644
index 0000000000000000000000000000000000000000..2ee9ef7e9859bc95da2450e3b282fd4275cbbb39
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qostanay differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qyzylorda b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qyzylorda
new file mode 100644
index 0000000000000000000000000000000000000000..27b522a7d5e24eafdf29dd541ebbca69ce4db7b8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Qyzylorda differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Rangoon b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Rangoon
new file mode 100644
index 0000000000000000000000000000000000000000..eef37b42e8a0e7179f8113bea01f4a71d668e8ef
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Rangoon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Riyadh b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Riyadh
new file mode 100644
index 0000000000000000000000000000000000000000..8c8062471dce91a5be827d6908795ee7391a4afc
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Riyadh differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Saigon b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Saigon
new file mode 100644
index 0000000000000000000000000000000000000000..9c45ed991a230919d129c63c660aa8d1ad74d0ea
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Saigon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Sakhalin b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Sakhalin
new file mode 100644
index 0000000000000000000000000000000000000000..beb77b449654decdfec1f6bfc16fafc8bc8ceeaa
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Sakhalin differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Samarkand b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Samarkand
new file mode 100644
index 0000000000000000000000000000000000000000..8a93767bfef2cecbeee15db413a0a7c277e761a1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Samarkand differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Seoul b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Seoul
new file mode 100644
index 0000000000000000000000000000000000000000..96199e73e73aafacd89e48cb2855a96d7a134e1d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Seoul differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Shanghai b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Shanghai
new file mode 100644
index 0000000000000000000000000000000000000000..91f6f8bc2e234bafd484146986bdb289082c3588
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Shanghai differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Singapore b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Singapore
new file mode 100644
index 0000000000000000000000000000000000000000..3d9f191e3acad56fb4f73ab44a74c50cdf91c12e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Singapore differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Srednekolymsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Srednekolymsk
new file mode 100644
index 0000000000000000000000000000000000000000..d21e7eeed5408affb3277bde903d6f5f2090ea61
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Srednekolymsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Taipei b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Taipei
new file mode 100644
index 0000000000000000000000000000000000000000..24c43444b6751343d2915843d03e55753d4d7359
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Taipei differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tashkent b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tashkent
new file mode 100644
index 0000000000000000000000000000000000000000..a9f6cd93c849c8b1677bc54f8bb836c91b40d63d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tashkent differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tbilisi b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tbilisi
new file mode 100644
index 0000000000000000000000000000000000000000..3b131bb10e100bc2dd619d57367a4e43c86e5316
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tbilisi differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tehran b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tehran
new file mode 100644
index 0000000000000000000000000000000000000000..78f28cc402027bd337cf67b937bf8c31a75ee8b3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tehran differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tel_Aviv b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tel_Aviv
new file mode 100644
index 0000000000000000000000000000000000000000..1ebd0664aa29c0abd722661f761031ec0304631c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tel_Aviv differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Thimbu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Thimbu
new file mode 100644
index 0000000000000000000000000000000000000000..95a9de9657f5b8b15aacb6e05c085c7e11bb8f55
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Thimbu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Thimphu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Thimphu
new file mode 100644
index 0000000000000000000000000000000000000000..95a9de9657f5b8b15aacb6e05c085c7e11bb8f55
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Thimphu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tokyo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tokyo
new file mode 100644
index 0000000000000000000000000000000000000000..26f4d34d67b46513491f26c2e661c6e653cc130d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tokyo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tomsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tomsk
new file mode 100644
index 0000000000000000000000000000000000000000..a6e494a78cef4baaa30d06cea4186391788eb30b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Tomsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ujung_Pandang b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ujung_Pandang
new file mode 100644
index 0000000000000000000000000000000000000000..556ba866933d37f3cfcf8042045d64e209bae30f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ujung_Pandang differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ulaanbaatar b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ulaanbaatar
new file mode 100644
index 0000000000000000000000000000000000000000..2aa5cc4b84d369b03684c30cdb66b7abf087f467
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ulaanbaatar differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ulan_Bator b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ulan_Bator
new file mode 100644
index 0000000000000000000000000000000000000000..2aa5cc4b84d369b03684c30cdb66b7abf087f467
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ulan_Bator differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Urumqi b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Urumqi
new file mode 100644
index 0000000000000000000000000000000000000000..62bdcac14db3f464ff561e32db2c6b55c0cb1866
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Urumqi differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ust-Nera b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ust-Nera
new file mode 100644
index 0000000000000000000000000000000000000000..d05726aba9fd67bf230290b3e2d74b75e46ee214
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Ust-Nera differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Vientiane b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Vientiane
new file mode 100644
index 0000000000000000000000000000000000000000..fa799db39e7625dd74bd9caa5c29b4819a7cbd3f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Vientiane differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Vladivostok b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Vladivostok
new file mode 100644
index 0000000000000000000000000000000000000000..274a10b43d8089ed522daf9ded5b6aa3653075c9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Vladivostok differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yakutsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yakutsk
new file mode 100644
index 0000000000000000000000000000000000000000..ae65a5f9b94d196b29b68ddec7862e098d829b59
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yakutsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yangon b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yangon
new file mode 100644
index 0000000000000000000000000000000000000000..eef37b42e8a0e7179f8113bea01f4a71d668e8ef
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yangon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yekaterinburg b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yekaterinburg
new file mode 100644
index 0000000000000000000000000000000000000000..d4d19ccf1e91121589a7cabff444bc916f67f9ce
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yekaterinburg differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yerevan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yerevan
new file mode 100644
index 0000000000000000000000000000000000000000..0d5f6853ac79c41fcb445a23062a27aca9e471f3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Asia/Yerevan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Azores b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Azores
new file mode 100644
index 0000000000000000000000000000000000000000..dd2c235bf9c4cc3c2ec4c2725a7cd5deac128fea
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Azores differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Bermuda b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Bermuda
new file mode 100644
index 0000000000000000000000000000000000000000..527524ed295aba41b9a0448ffd7993c489a2cb99
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Bermuda differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Canary b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Canary
new file mode 100644
index 0000000000000000000000000000000000000000..f3192156ff043a529461aa9004a8de9dda326f7d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Canary differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Cape_Verde b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Cape_Verde
new file mode 100644
index 0000000000000000000000000000000000000000..0d0d31a2f092d03f8512ed9c34f36a3f3f21209b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Cape_Verde differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Faeroe b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Faeroe
new file mode 100644
index 0000000000000000000000000000000000000000..4dab7ef0859c244b916d61b7489d7371881e0ca2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Faeroe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Faroe b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Faroe
new file mode 100644
index 0000000000000000000000000000000000000000..4dab7ef0859c244b916d61b7489d7371881e0ca2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Faroe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Jan_Mayen b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Jan_Mayen
new file mode 100644
index 0000000000000000000000000000000000000000..7f6d958f8630cba512d8e58ca8edfbd516291522
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Jan_Mayen differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Madeira b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Madeira
new file mode 100644
index 0000000000000000000000000000000000000000..6725a0ffc1f7cfc6cad54361ca91500e087e2b64
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Madeira differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Reykjavik b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Reykjavik
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Reykjavik differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/South_Georgia b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/South_Georgia
new file mode 100644
index 0000000000000000000000000000000000000000..a2b59a9d1088690cb2f9ad9011bfa59e6cb5c658
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/South_Georgia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/St_Helena b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/St_Helena
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/St_Helena differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Stanley b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Stanley
new file mode 100644
index 0000000000000000000000000000000000000000..1527d0e1a762674748735a95b6c3034d162f4240
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Atlantic/Stanley differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/ACT b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/ACT
new file mode 100644
index 0000000000000000000000000000000000000000..0aea4c3d43e504dafabc031d7ca9cbe8db46163c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/ACT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Adelaide b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Adelaide
new file mode 100644
index 0000000000000000000000000000000000000000..f5dedca59e2b220f7395c73f60ff26e610373e8b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Adelaide differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Brisbane b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Brisbane
new file mode 100644
index 0000000000000000000000000000000000000000..7ff9949ffa93e44835ab133998b89e440094f909
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Brisbane differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Broken_Hill b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Broken_Hill
new file mode 100644
index 0000000000000000000000000000000000000000..698c76e30e91f568a29daca12993cfacbfdbf83e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Broken_Hill differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Canberra b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Canberra
new file mode 100644
index 0000000000000000000000000000000000000000..0aea4c3d43e504dafabc031d7ca9cbe8db46163c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Canberra differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Currie b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Currie
new file mode 100644
index 0000000000000000000000000000000000000000..3adb8e1bf7c6ec51f1c100538799271d7d7a6e6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Currie differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Darwin b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Darwin
new file mode 100644
index 0000000000000000000000000000000000000000..74a30879bc6180d588a706451226cb4c95faf79d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Darwin differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Eucla b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Eucla
new file mode 100644
index 0000000000000000000000000000000000000000..1551e96cbc3de5565356954b61aac3c4388e90db
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Eucla differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Hobart b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Hobart
new file mode 100644
index 0000000000000000000000000000000000000000..3adb8e1bf7c6ec51f1c100538799271d7d7a6e6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Hobart differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/LHI b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/LHI
new file mode 100644
index 0000000000000000000000000000000000000000..069a95ad686c1139e2ff2b9ce94dc5ef5bc98c67
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/LHI differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Lindeman b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Lindeman
new file mode 100644
index 0000000000000000000000000000000000000000..4ee1825abfe65887069dcbd10bcf786d50ba0702
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Lindeman differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Lord_Howe b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Lord_Howe
new file mode 100644
index 0000000000000000000000000000000000000000..069a95ad686c1139e2ff2b9ce94dc5ef5bc98c67
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Lord_Howe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Melbourne b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Melbourne
new file mode 100644
index 0000000000000000000000000000000000000000..ee903f4b1fc292bc9cbec7b501a266030ef3510e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Melbourne differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/NSW b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/NSW
new file mode 100644
index 0000000000000000000000000000000000000000..0aea4c3d43e504dafabc031d7ca9cbe8db46163c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/NSW differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/North b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/North
new file mode 100644
index 0000000000000000000000000000000000000000..74a30879bc6180d588a706451226cb4c95faf79d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/North differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Perth b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Perth
new file mode 100644
index 0000000000000000000000000000000000000000..f8ddbdf215d34b022af11c3d1930dd6ea4dca87e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Perth differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Queensland b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Queensland
new file mode 100644
index 0000000000000000000000000000000000000000..7ff9949ffa93e44835ab133998b89e440094f909
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Queensland differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/South b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/South
new file mode 100644
index 0000000000000000000000000000000000000000..f5dedca59e2b220f7395c73f60ff26e610373e8b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/South differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Sydney b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Sydney
new file mode 100644
index 0000000000000000000000000000000000000000..0aea4c3d43e504dafabc031d7ca9cbe8db46163c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Sydney differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Tasmania b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Tasmania
new file mode 100644
index 0000000000000000000000000000000000000000..3adb8e1bf7c6ec51f1c100538799271d7d7a6e6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Tasmania differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Victoria b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Victoria
new file mode 100644
index 0000000000000000000000000000000000000000..ee903f4b1fc292bc9cbec7b501a266030ef3510e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Victoria differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/West b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/West
new file mode 100644
index 0000000000000000000000000000000000000000..f8ddbdf215d34b022af11c3d1930dd6ea4dca87e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/West differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Yancowinna b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Yancowinna
new file mode 100644
index 0000000000000000000000000000000000000000..698c76e30e91f568a29daca12993cfacbfdbf83e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Australia/Yancowinna differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/Acre b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/Acre
new file mode 100644
index 0000000000000000000000000000000000000000..cdda168cb97b1d45a4f1b7791a74523b74c88e6d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/Acre differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/DeNoronha b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/DeNoronha
new file mode 100644
index 0000000000000000000000000000000000000000..73b4b336ab55544e6061409261c16cacc39aff61
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/DeNoronha differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/East b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/East
new file mode 100644
index 0000000000000000000000000000000000000000..67935ff4da8f527e03cd05ed2aa20e601e10f921
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/East differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/West b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/West
new file mode 100644
index 0000000000000000000000000000000000000000..2708baea5af1d5169a1cebd00c4762d6bb937fda
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Brazil/West differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/CET b/python_embeded/Lib/site-packages/pytz/zoneinfo/CET
new file mode 100644
index 0000000000000000000000000000000000000000..40d7124e5346af056c75e2f7012a51d94e8154b7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/CET differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/CST6CDT b/python_embeded/Lib/site-packages/pytz/zoneinfo/CST6CDT
new file mode 100644
index 0000000000000000000000000000000000000000..c6981a06b1d9c26f447518efe265a6454726eae7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/CST6CDT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Atlantic b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Atlantic
new file mode 100644
index 0000000000000000000000000000000000000000..756099abe6cee44295a5566ad6cd0c352fb82e64
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Atlantic differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Central b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Central
new file mode 100644
index 0000000000000000000000000000000000000000..ac40299f6b27043e8f2454ac594b0ec184c1a237
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Central differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Eastern b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Eastern
new file mode 100644
index 0000000000000000000000000000000000000000..170137333f9f6dba10ac3ad7f32876aaf518c4fd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Eastern differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Mountain b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Mountain
new file mode 100644
index 0000000000000000000000000000000000000000..cd78a6f8be1dd55ac5afd25bbae39bd5706e42d1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Mountain differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Newfoundland b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Newfoundland
new file mode 100644
index 0000000000000000000000000000000000000000..65a5b0c720dad151ffdcba3dbe91c8bd638845c6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Newfoundland differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Pacific b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Pacific
new file mode 100644
index 0000000000000000000000000000000000000000..bb60cbced30763c08b6cf73554c8d6651ff387d0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Pacific differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Saskatchewan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Saskatchewan
new file mode 100644
index 0000000000000000000000000000000000000000..20c9c84df491e4072ec4c5d2c931a7433d9fd394
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Saskatchewan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Yukon b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Yukon
new file mode 100644
index 0000000000000000000000000000000000000000..318c4a8e4003bcff00f9a21e294e7815f170235b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Canada/Yukon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Chile/Continental b/python_embeded/Lib/site-packages/pytz/zoneinfo/Chile/Continental
new file mode 100644
index 0000000000000000000000000000000000000000..010c6bd04cae79078540da560ce38400bfe0ade6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Chile/Continental differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Chile/EasterIsland b/python_embeded/Lib/site-packages/pytz/zoneinfo/Chile/EasterIsland
new file mode 100644
index 0000000000000000000000000000000000000000..184cb6a83b3392d0492c42297531c85e7e38c4f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Chile/EasterIsland differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Cuba b/python_embeded/Lib/site-packages/pytz/zoneinfo/Cuba
new file mode 100644
index 0000000000000000000000000000000000000000..b69ac4510784f23ee794cd6d11e62315a7318e5e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Cuba differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/EET b/python_embeded/Lib/site-packages/pytz/zoneinfo/EET
new file mode 100644
index 0000000000000000000000000000000000000000..9f3a0678d766881389e129c93def7fffd74f14f1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/EET differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/EST b/python_embeded/Lib/site-packages/pytz/zoneinfo/EST
new file mode 100644
index 0000000000000000000000000000000000000000..9964b9a33452f4b636f43703b7cdec4891cbda5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/EST differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/EST5EDT b/python_embeded/Lib/site-packages/pytz/zoneinfo/EST5EDT
new file mode 100644
index 0000000000000000000000000000000000000000..a8b9ab1992257d721ad627b14f535c3d4b020888
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/EST5EDT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Egypt b/python_embeded/Lib/site-packages/pytz/zoneinfo/Egypt
new file mode 100644
index 0000000000000000000000000000000000000000..dd538c65db6ed0a0e47feb7b6001640516958e19
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Egypt differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Eire b/python_embeded/Lib/site-packages/pytz/zoneinfo/Eire
new file mode 100644
index 0000000000000000000000000000000000000000..c729def42fc0822e6b24f7bf503c67cc7e6965f0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Eire differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+0 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+0
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+0 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+1 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+1
new file mode 100644
index 0000000000000000000000000000000000000000..4dab6f9005bea50a065c685ec8260b0da2bff921
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+1 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+10 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+10
new file mode 100644
index 0000000000000000000000000000000000000000..c749290af2f6b5fe22770c34eb1e8fc87cd85aff
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+10 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+11 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+11
new file mode 100644
index 0000000000000000000000000000000000000000..d969982309e5ca7d32979a7dad814ca307d2cd8d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+11 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+12 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+12
new file mode 100644
index 0000000000000000000000000000000000000000..cdeec90973be28ee4075eadd22b8b574db2d7a5f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+12 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+2 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+2
new file mode 100644
index 0000000000000000000000000000000000000000..fbd2a941fda996f4abc1f0e09cdf99c271f5a1e2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+2 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+3 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+3
new file mode 100644
index 0000000000000000000000000000000000000000..ee246ef56f18de61105af0c14d201fd090f74905
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+3 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+4 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+4
new file mode 100644
index 0000000000000000000000000000000000000000..5a25ff2a6afda2cb09b9e147ad20610bc1923444
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+4 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+5 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+5
new file mode 100644
index 0000000000000000000000000000000000000000..c0b745f1cc44d03a00f8bdf127c154392e3baf27
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+5 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+6 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+6
new file mode 100644
index 0000000000000000000000000000000000000000..06e777d57e0267a0635b6b284729fddcfe6221dd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+6 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+7 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+7
new file mode 100644
index 0000000000000000000000000000000000000000..4e0b53a082f11f9b9debf5e110b97b1b0473c9a6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+7 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+8 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+8
new file mode 100644
index 0000000000000000000000000000000000000000..714b0c562889a8a774d9aa27810d8400164d00e6
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+8 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+9 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+9
new file mode 100644
index 0000000000000000000000000000000000000000..78b9daa373d2aa2856eafcc92ebc6d899cafde5c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT+9 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-0 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-0
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-0 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-1 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-1
new file mode 100644
index 0000000000000000000000000000000000000000..a838bebf5e7bac3e1257eeb0a61c1b83feb1324c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-1 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-10 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-10
new file mode 100644
index 0000000000000000000000000000000000000000..68ff77db0d95c7d054ef33c05e05ba71bcbbbdd8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-10 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-11 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-11
new file mode 100644
index 0000000000000000000000000000000000000000..66af5a42be440f1fb8fec3b915afb49b356f63a5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-11 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-12 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-12
new file mode 100644
index 0000000000000000000000000000000000000000..17ba5057727dd73bd5f6234cc5b239b71a861945
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-12 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-13 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-13
new file mode 100644
index 0000000000000000000000000000000000000000..5f3706ce64cadf081a6c56abd7ba423575a4abb2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-13 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-14 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-14
new file mode 100644
index 0000000000000000000000000000000000000000..7e9f9c465ce6211c65d617f60472c9b55b5052c5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-14 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-2 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-2
new file mode 100644
index 0000000000000000000000000000000000000000..fcef6d9acb247deb539fcc4b30149802572ea642
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-2 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-3 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-3
new file mode 100644
index 0000000000000000000000000000000000000000..27973bc857b4e618218ca2790acacb81f7c7bb82
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-3 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-4 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-4
new file mode 100644
index 0000000000000000000000000000000000000000..1efd841261a977ae218d408f9cc308c3e312a5e8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-4 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-5 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-5
new file mode 100644
index 0000000000000000000000000000000000000000..1f761844fc44f8228bb748235bfd30be6c389cd1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-5 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-6 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-6
new file mode 100644
index 0000000000000000000000000000000000000000..952681ed46cb60e59baf76a2c43b49d5f67255d1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-6 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-7 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-7
new file mode 100644
index 0000000000000000000000000000000000000000..cefc9126c691060225ff2eee1241b1e5e9825fcd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-7 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-8 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-8
new file mode 100644
index 0000000000000000000000000000000000000000..afb093da00685297cb11347c4840acf3a8e2e2bf
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-8 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-9 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-9
new file mode 100644
index 0000000000000000000000000000000000000000..9265fb7c2071ec0e66c657ad2ae42d5dd525fe97
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT-9 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT0 b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT0
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/GMT0 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Greenwich b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Greenwich
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Greenwich differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/UCT b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/UCT
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/UCT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/UTC b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/UTC
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/UTC differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Universal b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Universal
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Universal differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Zulu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Zulu
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Etc/Zulu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Amsterdam b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Amsterdam
new file mode 100644
index 0000000000000000000000000000000000000000..40d7124e5346af056c75e2f7012a51d94e8154b7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Amsterdam differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Andorra b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Andorra
new file mode 100644
index 0000000000000000000000000000000000000000..5962550392fa78514061582e9371c32b9f1d929b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Andorra differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Astrakhan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Astrakhan
new file mode 100644
index 0000000000000000000000000000000000000000..a41624f5df9698d78049008a2bd8a77395c0480a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Astrakhan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Athens b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Athens
new file mode 100644
index 0000000000000000000000000000000000000000..9f3a0678d766881389e129c93def7fffd74f14f1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Athens differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Belfast b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Belfast
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Belfast differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Belgrade b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Belgrade
new file mode 100644
index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Belgrade differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Berlin b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Berlin
new file mode 100644
index 0000000000000000000000000000000000000000..7f6d958f8630cba512d8e58ca8edfbd516291522
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Berlin differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Bratislava b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Bratislava
new file mode 100644
index 0000000000000000000000000000000000000000..ce8f433ece44f0b96b18d3b5780730e7f9cad9f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Bratislava differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Brussels b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Brussels
new file mode 100644
index 0000000000000000000000000000000000000000..40d7124e5346af056c75e2f7012a51d94e8154b7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Brussels differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Bucharest b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Bucharest
new file mode 100644
index 0000000000000000000000000000000000000000..4303b903e5e007484c0d8e1eea43a35e9b53f38b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Bucharest differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Budapest b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Budapest
new file mode 100644
index 0000000000000000000000000000000000000000..b76c873d9256e1d73c2ea672140b813f15657bc7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Budapest differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Busingen b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Busingen
new file mode 100644
index 0000000000000000000000000000000000000000..ad6cf59281a1046d9dcd045fda521585e3e33e06
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Busingen differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Chisinau b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Chisinau
new file mode 100644
index 0000000000000000000000000000000000000000..5ee23fe0e59f044598675db44d53c20590b88934
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Chisinau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Copenhagen b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Copenhagen
new file mode 100644
index 0000000000000000000000000000000000000000..7f6d958f8630cba512d8e58ca8edfbd516291522
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Copenhagen differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Dublin b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Dublin
new file mode 100644
index 0000000000000000000000000000000000000000..c729def42fc0822e6b24f7bf503c67cc7e6965f0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Dublin differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Gibraltar b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Gibraltar
new file mode 100644
index 0000000000000000000000000000000000000000..a38f11ffdf2a9e538695ea8cae20b1d2c04164af
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Gibraltar differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Guernsey b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Guernsey
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Guernsey differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Helsinki b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Helsinki
new file mode 100644
index 0000000000000000000000000000000000000000..b4f8f9cbb57450549933f83ac90dd56a2ca75344
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Helsinki differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Isle_of_Man b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Isle_of_Man
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Isle_of_Man differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Istanbul b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Istanbul
new file mode 100644
index 0000000000000000000000000000000000000000..7c2336dd80c3c9cbf71cb53d2b2c1f89a65a8ba5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Istanbul differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Jersey b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Jersey
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Jersey differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kaliningrad b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kaliningrad
new file mode 100644
index 0000000000000000000000000000000000000000..cc99beabe4ffc5107c4719d1201d6583b9ead03a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kaliningrad differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kiev b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kiev
new file mode 100644
index 0000000000000000000000000000000000000000..52efea88065b220e44fd876de3bf3090fe62cc79
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kiev differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kirov b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kirov
new file mode 100644
index 0000000000000000000000000000000000000000..0cfb956be223ab593ca27569ad554dae9b106117
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kirov differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kyiv b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kyiv
new file mode 100644
index 0000000000000000000000000000000000000000..52efea88065b220e44fd876de3bf3090fe62cc79
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Kyiv differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Lisbon b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Lisbon
new file mode 100644
index 0000000000000000000000000000000000000000..616de167b8a1c534c1c526e7bbff82f7d5da94f2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Lisbon differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Ljubljana b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Ljubljana
new file mode 100644
index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Ljubljana differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/London b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/London
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/London differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Luxembourg b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Luxembourg
new file mode 100644
index 0000000000000000000000000000000000000000..40d7124e5346af056c75e2f7012a51d94e8154b7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Luxembourg differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Madrid b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Madrid
new file mode 100644
index 0000000000000000000000000000000000000000..53f4cd101c18058a1ee4d4b9d1184ada11d74232
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Madrid differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Malta b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Malta
new file mode 100644
index 0000000000000000000000000000000000000000..1d1a7bcfcbbf37ff1ad7025f9843d0d2d8cb06d4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Malta differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Mariehamn b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Mariehamn
new file mode 100644
index 0000000000000000000000000000000000000000..b4f8f9cbb57450549933f83ac90dd56a2ca75344
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Mariehamn differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Minsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Minsk
new file mode 100644
index 0000000000000000000000000000000000000000..3731e40d8634c4d58ddb3378d828c92948f06d67
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Minsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Monaco b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Monaco
new file mode 100644
index 0000000000000000000000000000000000000000..7d366c6098c49ecd546e1cc1538919e1414a3aee
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Monaco differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Moscow b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Moscow
new file mode 100644
index 0000000000000000000000000000000000000000..ddb3f4e99a1030f33b56fad986c8d9c16e59eb32
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Moscow differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Nicosia b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Nicosia
new file mode 100644
index 0000000000000000000000000000000000000000..f7f10ab7665e94ca44fd8cd98a362cd4b304eff1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Nicosia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Oslo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Oslo
new file mode 100644
index 0000000000000000000000000000000000000000..7f6d958f8630cba512d8e58ca8edfbd516291522
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Oslo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Paris b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Paris
new file mode 100644
index 0000000000000000000000000000000000000000..7d366c6098c49ecd546e1cc1538919e1414a3aee
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Paris differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Podgorica b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Podgorica
new file mode 100644
index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Podgorica differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Prague b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Prague
new file mode 100644
index 0000000000000000000000000000000000000000..ce8f433ece44f0b96b18d3b5780730e7f9cad9f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Prague differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Riga b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Riga
new file mode 100644
index 0000000000000000000000000000000000000000..8db477d01736445cafce8af7a7085d226d81f546
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Riga differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Rome b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Rome
new file mode 100644
index 0000000000000000000000000000000000000000..32b2899a306dde401fa2e3952d06f5f4d9952bed
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Rome differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Samara b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Samara
new file mode 100644
index 0000000000000000000000000000000000000000..d0ea2f25e9b4acaf3167a09a1c647943425e51b1
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Samara differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/San_Marino b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/San_Marino
new file mode 100644
index 0000000000000000000000000000000000000000..32b2899a306dde401fa2e3952d06f5f4d9952bed
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/San_Marino differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Sarajevo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Sarajevo
new file mode 100644
index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Sarajevo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Saratov b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Saratov
new file mode 100644
index 0000000000000000000000000000000000000000..a863913358adb7a9118fcc48a6a5dcfba5f9914b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Saratov differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Simferopol b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Simferopol
new file mode 100644
index 0000000000000000000000000000000000000000..4bf24de1d9f8ebc410f120aa83d98b7e41d1e6c4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Simferopol differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Skopje b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Skopje
new file mode 100644
index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Skopje differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Sofia b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Sofia
new file mode 100644
index 0000000000000000000000000000000000000000..0e4d879332d21c93c229fc25587205020eeb3127
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Sofia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Stockholm b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Stockholm
new file mode 100644
index 0000000000000000000000000000000000000000..7f6d958f8630cba512d8e58ca8edfbd516291522
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Stockholm differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tallinn b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tallinn
new file mode 100644
index 0000000000000000000000000000000000000000..b5acca3cf51e7f7b3176965748688ff41720246f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tallinn differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tirane b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tirane
new file mode 100644
index 0000000000000000000000000000000000000000..0b86017d243f1b7bbb41d6b4feefcb2b7edfc7d8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tirane differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tiraspol b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tiraspol
new file mode 100644
index 0000000000000000000000000000000000000000..5ee23fe0e59f044598675db44d53c20590b88934
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Tiraspol differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Ulyanovsk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Ulyanovsk
new file mode 100644
index 0000000000000000000000000000000000000000..d668233b37f268a745e995177195b06ffab1e69b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Ulyanovsk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Uzhgorod b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Uzhgorod
new file mode 100644
index 0000000000000000000000000000000000000000..52efea88065b220e44fd876de3bf3090fe62cc79
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Uzhgorod differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vaduz b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vaduz
new file mode 100644
index 0000000000000000000000000000000000000000..ad6cf59281a1046d9dcd045fda521585e3e33e06
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vaduz differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vatican b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vatican
new file mode 100644
index 0000000000000000000000000000000000000000..32b2899a306dde401fa2e3952d06f5f4d9952bed
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vatican differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vienna b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vienna
new file mode 100644
index 0000000000000000000000000000000000000000..3582bb15cd7322088839b0134987ad10e717b6b5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vienna differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vilnius b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vilnius
new file mode 100644
index 0000000000000000000000000000000000000000..7abd63fa608e0186b9f154d9fcc32472c28f6759
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Vilnius differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Volgograd b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Volgograd
new file mode 100644
index 0000000000000000000000000000000000000000..9d51a38c0ea719c5042837d47e0f427057b845f0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Volgograd differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Warsaw b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Warsaw
new file mode 100644
index 0000000000000000000000000000000000000000..e33cf67171da78aa9e6eb02e50f9b9603da4c3f4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Warsaw differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zagreb b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zagreb
new file mode 100644
index 0000000000000000000000000000000000000000..27de456f16ab549627b284a39e2265cbdb4ad8e9
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zagreb differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zaporozhye b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zaporozhye
new file mode 100644
index 0000000000000000000000000000000000000000..52efea88065b220e44fd876de3bf3090fe62cc79
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zaporozhye differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zurich b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zurich
new file mode 100644
index 0000000000000000000000000000000000000000..ad6cf59281a1046d9dcd045fda521585e3e33e06
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Europe/Zurich differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Factory b/python_embeded/Lib/site-packages/pytz/zoneinfo/Factory
new file mode 100644
index 0000000000000000000000000000000000000000..60aa2a0d695ba577ff87624d479f1eb25c8f1caf
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Factory differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/GB b/python_embeded/Lib/site-packages/pytz/zoneinfo/GB
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/GB differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/GB-Eire b/python_embeded/Lib/site-packages/pytz/zoneinfo/GB-Eire
new file mode 100644
index 0000000000000000000000000000000000000000..5ad74220e83e6c30a0aeefda4a00271b8ebdfcad
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/GB-Eire differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT+0 b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT+0
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT+0 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT-0 b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT-0
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT-0 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT0 b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT0
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/GMT0 differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Greenwich b/python_embeded/Lib/site-packages/pytz/zoneinfo/Greenwich
new file mode 100644
index 0000000000000000000000000000000000000000..c63474664a289aa3c3c0d8b2ce06d484679754c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Greenwich differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/HST b/python_embeded/Lib/site-packages/pytz/zoneinfo/HST
new file mode 100644
index 0000000000000000000000000000000000000000..c7cd060159bd22fc5e6f10ac5a2089afb2c19c6a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/HST differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Hongkong b/python_embeded/Lib/site-packages/pytz/zoneinfo/Hongkong
new file mode 100644
index 0000000000000000000000000000000000000000..f9f7b134dd5c35e4718c6fa3697024cb95442c53
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Hongkong differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Iceland b/python_embeded/Lib/site-packages/pytz/zoneinfo/Iceland
new file mode 100644
index 0000000000000000000000000000000000000000..28b32ab2e0b9053f39a91d9f28b6072e41423954
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Iceland differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Antananarivo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Antananarivo
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Antananarivo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Chagos b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Chagos
new file mode 100644
index 0000000000000000000000000000000000000000..a5554816e2928c2bd5d02e032bbeb1e1cb101009
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Chagos differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Christmas b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Christmas
new file mode 100644
index 0000000000000000000000000000000000000000..fa799db39e7625dd74bd9caa5c29b4819a7cbd3f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Christmas differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Cocos b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Cocos
new file mode 100644
index 0000000000000000000000000000000000000000..eef37b42e8a0e7179f8113bea01f4a71d668e8ef
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Cocos differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Comoro b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Comoro
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Comoro differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Kerguelen b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Kerguelen
new file mode 100644
index 0000000000000000000000000000000000000000..555728b1a0187cc0ac63b8fe45c44bd1e0957918
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Kerguelen differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mahe b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mahe
new file mode 100644
index 0000000000000000000000000000000000000000..b3ac791aef4e73d6d644c40c614f37f15d462cdd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mahe differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Maldives b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Maldives
new file mode 100644
index 0000000000000000000000000000000000000000..555728b1a0187cc0ac63b8fe45c44bd1e0957918
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Maldives differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mauritius b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mauritius
new file mode 100644
index 0000000000000000000000000000000000000000..212d4b2e2afaed06110a1acff4fdb6bd6103b4ff
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mauritius differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mayotte b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mayotte
new file mode 100644
index 0000000000000000000000000000000000000000..9dcfc19c56e62b12b730f4335b34479695f273f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Mayotte differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Reunion b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Reunion
new file mode 100644
index 0000000000000000000000000000000000000000..b3ac791aef4e73d6d644c40c614f37f15d462cdd
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Indian/Reunion differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Iran b/python_embeded/Lib/site-packages/pytz/zoneinfo/Iran
new file mode 100644
index 0000000000000000000000000000000000000000..78f28cc402027bd337cf67b937bf8c31a75ee8b3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Iran differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Israel b/python_embeded/Lib/site-packages/pytz/zoneinfo/Israel
new file mode 100644
index 0000000000000000000000000000000000000000..1ebd0664aa29c0abd722661f761031ec0304631c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Israel differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Jamaica b/python_embeded/Lib/site-packages/pytz/zoneinfo/Jamaica
new file mode 100644
index 0000000000000000000000000000000000000000..2a9b7fd52d37a1ffe9fc589daa04d88c6c71a6e0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Jamaica differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Japan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Japan
new file mode 100644
index 0000000000000000000000000000000000000000..26f4d34d67b46513491f26c2e661c6e653cc130d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Japan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Kwajalein b/python_embeded/Lib/site-packages/pytz/zoneinfo/Kwajalein
new file mode 100644
index 0000000000000000000000000000000000000000..1887a607422edd499fdf24afe91a04294f1caf6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Kwajalein differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Libya b/python_embeded/Lib/site-packages/pytz/zoneinfo/Libya
new file mode 100644
index 0000000000000000000000000000000000000000..07b393bb7db14cef1e906ebe63cfbbe8cddc79d5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Libya differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/MET b/python_embeded/Lib/site-packages/pytz/zoneinfo/MET
new file mode 100644
index 0000000000000000000000000000000000000000..40d7124e5346af056c75e2f7012a51d94e8154b7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/MET differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/MST b/python_embeded/Lib/site-packages/pytz/zoneinfo/MST
new file mode 100644
index 0000000000000000000000000000000000000000..ab37e845566aa95659b7b85be0051d0c67a7e53a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/MST differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/MST7MDT b/python_embeded/Lib/site-packages/pytz/zoneinfo/MST7MDT
new file mode 100644
index 0000000000000000000000000000000000000000..abb2b974a47eb3e5c8b4f5d4370baf4898b239ab
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/MST7MDT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/BajaNorte b/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/BajaNorte
new file mode 100644
index 0000000000000000000000000000000000000000..0fe73912cacab6c8aabef4f4264d1710825888e7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/BajaNorte differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/BajaSur b/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/BajaSur
new file mode 100644
index 0000000000000000000000000000000000000000..386616a59cdb2a21f1f24a6c72526bce0360cd24
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/BajaSur differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/General b/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/General
new file mode 100644
index 0000000000000000000000000000000000000000..ad70cf3e08498845aaafc38e4eccca7461c8d337
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Mexico/General differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/NZ b/python_embeded/Lib/site-packages/pytz/zoneinfo/NZ
new file mode 100644
index 0000000000000000000000000000000000000000..6575fdce31183d8238b18f2f30ab5b9227c7071c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/NZ differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/NZ-CHAT b/python_embeded/Lib/site-packages/pytz/zoneinfo/NZ-CHAT
new file mode 100644
index 0000000000000000000000000000000000000000..bde46cf7e4b7909714b93cee39a5d953387d756c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/NZ-CHAT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Navajo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Navajo
new file mode 100644
index 0000000000000000000000000000000000000000..abb2b974a47eb3e5c8b4f5d4370baf4898b239ab
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Navajo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/PRC b/python_embeded/Lib/site-packages/pytz/zoneinfo/PRC
new file mode 100644
index 0000000000000000000000000000000000000000..91f6f8bc2e234bafd484146986bdb289082c3588
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/PRC differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/PST8PDT b/python_embeded/Lib/site-packages/pytz/zoneinfo/PST8PDT
new file mode 100644
index 0000000000000000000000000000000000000000..610e7af5fc13d9784de30d272c7c39d7938873a0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/PST8PDT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Apia b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Apia
new file mode 100644
index 0000000000000000000000000000000000000000..e592a68e53f6215de9e1d1ac61ce062a333283c0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Apia differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Auckland b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Auckland
new file mode 100644
index 0000000000000000000000000000000000000000..6575fdce31183d8238b18f2f30ab5b9227c7071c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Auckland differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Bougainville b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Bougainville
new file mode 100644
index 0000000000000000000000000000000000000000..c535acdabda1b6ed96420e589d4f6868d23d8933
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Bougainville differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Chatham b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Chatham
new file mode 100644
index 0000000000000000000000000000000000000000..bde46cf7e4b7909714b93cee39a5d953387d756c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Chatham differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Chuuk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Chuuk
new file mode 100644
index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Chuuk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Easter b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Easter
new file mode 100644
index 0000000000000000000000000000000000000000..184cb6a83b3392d0492c42297531c85e7e38c4f5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Easter differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Efate b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Efate
new file mode 100644
index 0000000000000000000000000000000000000000..777325fc6c6da8795d89aed5206c60f8bf80b0ab
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Efate differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Enderbury b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Enderbury
new file mode 100644
index 0000000000000000000000000000000000000000..b1c4b0734483033722c28c8b2884ac9dddd2ab45
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Enderbury differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Fakaofo b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Fakaofo
new file mode 100644
index 0000000000000000000000000000000000000000..4905ea72b1640ca67e35b06395e1c700dffa8d21
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Fakaofo differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Fiji b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Fiji
new file mode 100644
index 0000000000000000000000000000000000000000..acf8091ac85151a6c887e2b5049ee40754b7b0d3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Fiji differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Funafuti b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Funafuti
new file mode 100644
index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Funafuti differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Galapagos b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Galapagos
new file mode 100644
index 0000000000000000000000000000000000000000..40051ddf63a32d79e5233b916e3911d6dc3ef759
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Galapagos differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Gambier b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Gambier
new file mode 100644
index 0000000000000000000000000000000000000000..84acaf41520d2d302f75e300e2b47c5527218df4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Gambier differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Guadalcanal b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Guadalcanal
new file mode 100644
index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Guadalcanal differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Guam b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Guam
new file mode 100644
index 0000000000000000000000000000000000000000..66490d25dff9bcc8f710b0141f1a02e64aeb32f3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Guam differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Honolulu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Honolulu
new file mode 100644
index 0000000000000000000000000000000000000000..c7cd060159bd22fc5e6f10ac5a2089afb2c19c6a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Honolulu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Johnston b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Johnston
new file mode 100644
index 0000000000000000000000000000000000000000..c7cd060159bd22fc5e6f10ac5a2089afb2c19c6a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Johnston differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kanton b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kanton
new file mode 100644
index 0000000000000000000000000000000000000000..b1c4b0734483033722c28c8b2884ac9dddd2ab45
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kanton differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kiritimati b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kiritimati
new file mode 100644
index 0000000000000000000000000000000000000000..b4c6037a2d2a8f89539c3df05c32b6f52b1b1e92
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kiritimati differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kosrae b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kosrae
new file mode 100644
index 0000000000000000000000000000000000000000..0666fb0dd161cb732b29f84d49c49cc985a3559a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kosrae differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kwajalein b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kwajalein
new file mode 100644
index 0000000000000000000000000000000000000000..1887a607422edd499fdf24afe91a04294f1caf6f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Kwajalein differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Majuro b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Majuro
new file mode 100644
index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Majuro differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Marquesas b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Marquesas
new file mode 100644
index 0000000000000000000000000000000000000000..f546c03f96b24859521aab5b9997bfc5dd124ead
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Marquesas differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Midway b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Midway
new file mode 100644
index 0000000000000000000000000000000000000000..cb56709a77dedb471150f4907771bf38f1879ba4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Midway differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Nauru b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Nauru
new file mode 100644
index 0000000000000000000000000000000000000000..3339b6cf86d6e98ba70c9bd6cab3dbf50588acd2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Nauru differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Niue b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Niue
new file mode 100644
index 0000000000000000000000000000000000000000..f76972f8849a7d6ed8c3e2649b02f44de891094f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Niue differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Norfolk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Norfolk
new file mode 100644
index 0000000000000000000000000000000000000000..3b4186d61152629b764efc4222e41647b65f7fbb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Norfolk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Noumea b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Noumea
new file mode 100644
index 0000000000000000000000000000000000000000..959cc8cd26f8a7b10a70e0f93bf3b3c9bbc680d2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Noumea differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pago_Pago b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pago_Pago
new file mode 100644
index 0000000000000000000000000000000000000000..cb56709a77dedb471150f4907771bf38f1879ba4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pago_Pago differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Palau b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Palau
new file mode 100644
index 0000000000000000000000000000000000000000..1cbebe28afd90c0a2e02786655e18a157284a412
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Palau differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pitcairn b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pitcairn
new file mode 100644
index 0000000000000000000000000000000000000000..5ee90e70203d72484b8752475c86139671bcb102
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pitcairn differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pohnpei b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pohnpei
new file mode 100644
index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Pohnpei differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Ponape b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Ponape
new file mode 100644
index 0000000000000000000000000000000000000000..1ab8353464ddb93947f871f07cfd12540373269c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Ponape differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Port_Moresby b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Port_Moresby
new file mode 100644
index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Port_Moresby differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Rarotonga b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Rarotonga
new file mode 100644
index 0000000000000000000000000000000000000000..184a87c112b99536acbafa1ec7aba52c7a94b549
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Rarotonga differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Saipan b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Saipan
new file mode 100644
index 0000000000000000000000000000000000000000..66490d25dff9bcc8f710b0141f1a02e64aeb32f3
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Saipan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Samoa b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Samoa
new file mode 100644
index 0000000000000000000000000000000000000000..cb56709a77dedb471150f4907771bf38f1879ba4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Samoa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tahiti b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tahiti
new file mode 100644
index 0000000000000000000000000000000000000000..481edd30580f00eccf69de4f1c332fc048210011
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tahiti differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tarawa b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tarawa
new file mode 100644
index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tarawa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tongatapu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tongatapu
new file mode 100644
index 0000000000000000000000000000000000000000..c8824ab5434985650f33e12eace1981f8b116207
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Tongatapu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Truk b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Truk
new file mode 100644
index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Truk differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Wake b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Wake
new file mode 100644
index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Wake differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Wallis b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Wallis
new file mode 100644
index 0000000000000000000000000000000000000000..47661d40a4188eb39e8d52e5af8ab23ef7f23766
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Wallis differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Yap b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Yap
new file mode 100644
index 0000000000000000000000000000000000000000..7be2474dd91c8a7da181fcda09d838254b890d75
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Pacific/Yap differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Poland b/python_embeded/Lib/site-packages/pytz/zoneinfo/Poland
new file mode 100644
index 0000000000000000000000000000000000000000..e33cf67171da78aa9e6eb02e50f9b9603da4c3f4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Poland differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Portugal b/python_embeded/Lib/site-packages/pytz/zoneinfo/Portugal
new file mode 100644
index 0000000000000000000000000000000000000000..616de167b8a1c534c1c526e7bbff82f7d5da94f2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Portugal differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/ROC b/python_embeded/Lib/site-packages/pytz/zoneinfo/ROC
new file mode 100644
index 0000000000000000000000000000000000000000..24c43444b6751343d2915843d03e55753d4d7359
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/ROC differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/ROK b/python_embeded/Lib/site-packages/pytz/zoneinfo/ROK
new file mode 100644
index 0000000000000000000000000000000000000000..96199e73e73aafacd89e48cb2855a96d7a134e1d
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/ROK differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Singapore b/python_embeded/Lib/site-packages/pytz/zoneinfo/Singapore
new file mode 100644
index 0000000000000000000000000000000000000000..3d9f191e3acad56fb4f73ab44a74c50cdf91c12e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Singapore differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Turkey b/python_embeded/Lib/site-packages/pytz/zoneinfo/Turkey
new file mode 100644
index 0000000000000000000000000000000000000000..7c2336dd80c3c9cbf71cb53d2b2c1f89a65a8ba5
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Turkey differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/UCT b/python_embeded/Lib/site-packages/pytz/zoneinfo/UCT
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/UCT differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Alaska b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Alaska
new file mode 100644
index 0000000000000000000000000000000000000000..9bbb2fd3b361ea8aa4c126d14df5fa370343a63f
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Alaska differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Aleutian b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Aleutian
new file mode 100644
index 0000000000000000000000000000000000000000..43236498f681cc06f64ca2afa613880331fe6fbb
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Aleutian differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Arizona b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Arizona
new file mode 100644
index 0000000000000000000000000000000000000000..ab37e845566aa95659b7b85be0051d0c67a7e53a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Arizona differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Central b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Central
new file mode 100644
index 0000000000000000000000000000000000000000..c6981a06b1d9c26f447518efe265a6454726eae7
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Central differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/East-Indiana b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/East-Indiana
new file mode 100644
index 0000000000000000000000000000000000000000..a84b6e99671f7305d1c459956e16a4dd772fc60e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/East-Indiana differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Eastern b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Eastern
new file mode 100644
index 0000000000000000000000000000000000000000..a8b9ab1992257d721ad627b14f535c3d4b020888
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Eastern differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Hawaii b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Hawaii
new file mode 100644
index 0000000000000000000000000000000000000000..c7cd060159bd22fc5e6f10ac5a2089afb2c19c6a
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Hawaii differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Indiana-Starke b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Indiana-Starke
new file mode 100644
index 0000000000000000000000000000000000000000..025d132dd48ba978c6fedf86d70173127be49d49
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Indiana-Starke differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Michigan b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Michigan
new file mode 100644
index 0000000000000000000000000000000000000000..e104faa46545ee873295cde34e1d46bccad8647c
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Michigan differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Mountain b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Mountain
new file mode 100644
index 0000000000000000000000000000000000000000..abb2b974a47eb3e5c8b4f5d4370baf4898b239ab
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Mountain differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Pacific b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Pacific
new file mode 100644
index 0000000000000000000000000000000000000000..610e7af5fc13d9784de30d272c7c39d7938873a0
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Pacific differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Samoa b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Samoa
new file mode 100644
index 0000000000000000000000000000000000000000..cb56709a77dedb471150f4907771bf38f1879ba4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/US/Samoa differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/UTC b/python_embeded/Lib/site-packages/pytz/zoneinfo/UTC
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/UTC differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Universal b/python_embeded/Lib/site-packages/pytz/zoneinfo/Universal
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Universal differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/W-SU b/python_embeded/Lib/site-packages/pytz/zoneinfo/W-SU
new file mode 100644
index 0000000000000000000000000000000000000000..ddb3f4e99a1030f33b56fad986c8d9c16e59eb32
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/W-SU differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/WET b/python_embeded/Lib/site-packages/pytz/zoneinfo/WET
new file mode 100644
index 0000000000000000000000000000000000000000..616de167b8a1c534c1c526e7bbff82f7d5da94f2
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/WET differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/Zulu b/python_embeded/Lib/site-packages/pytz/zoneinfo/Zulu
new file mode 100644
index 0000000000000000000000000000000000000000..91558be0c2bf903b2364215ba26d5227d6126508
Binary files /dev/null and b/python_embeded/Lib/site-packages/pytz/zoneinfo/Zulu differ
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/iso3166.tab b/python_embeded/Lib/site-packages/pytz/zoneinfo/iso3166.tab
new file mode 100644
index 0000000000000000000000000000000000000000..402c015ec6b1071499155f7d28739db68be7763f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pytz/zoneinfo/iso3166.tab
@@ -0,0 +1,279 @@
+# ISO 3166 alpha-2 country codes
+#
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
+#
+# From Paul Eggert (2023-09-06):
+# This file contains a table of two-letter country codes. Columns are
+# separated by a single tab. Lines beginning with '#' are comments.
+# All text uses UTF-8 encoding. The columns of the table are as follows:
+#
+# 1. ISO 3166-1 alpha-2 country code, current as of
+# ISO/TC 46 N1108 (2023-04-05). See: ISO/TC 46 Documents
+# https://www.iso.org/committee/48750.html?view=documents
+# 2. The usual English name for the coded region. This sometimes
+# departs from ISO-listed names, sometimes so that sorted subsets
+# of names are useful (e.g., "Samoa (American)" and "Samoa
+# (western)" rather than "American Samoa" and "Samoa"),
+# sometimes to avoid confusion among non-experts (e.g.,
+# "Czech Republic" and "Turkey" rather than "Czechia" and "Türkiye"),
+# and sometimes to omit needless detail or churn (e.g., "Netherlands"
+# rather than "Netherlands (the)" or "Netherlands (Kingdom of the)").
+#
+# The table is sorted by country code.
+#
+# This table is intended as an aid for users, to help them select time
+# zone data appropriate for their practical needs. It is not intended
+# to take or endorse any position on legal or territorial claims.
+#
+#country-
+#code name of country, territory, area, or subdivision
+AD Andorra
+AE United Arab Emirates
+AF Afghanistan
+AG Antigua & Barbuda
+AI Anguilla
+AL Albania
+AM Armenia
+AO Angola
+AQ Antarctica
+AR Argentina
+AS Samoa (American)
+AT Austria
+AU Australia
+AW Aruba
+AX Ã…land Islands
+AZ Azerbaijan
+BA Bosnia & Herzegovina
+BB Barbados
+BD Bangladesh
+BE Belgium
+BF Burkina Faso
+BG Bulgaria
+BH Bahrain
+BI Burundi
+BJ Benin
+BL St Barthelemy
+BM Bermuda
+BN Brunei
+BO Bolivia
+BQ Caribbean NL
+BR Brazil
+BS Bahamas
+BT Bhutan
+BV Bouvet Island
+BW Botswana
+BY Belarus
+BZ Belize
+CA Canada
+CC Cocos (Keeling) Islands
+CD Congo (Dem. Rep.)
+CF Central African Rep.
+CG Congo (Rep.)
+CH Switzerland
+CI Côte d'Ivoire
+CK Cook Islands
+CL Chile
+CM Cameroon
+CN China
+CO Colombia
+CR Costa Rica
+CU Cuba
+CV Cape Verde
+CW Curaçao
+CX Christmas Island
+CY Cyprus
+CZ Czech Republic
+DE Germany
+DJ Djibouti
+DK Denmark
+DM Dominica
+DO Dominican Republic
+DZ Algeria
+EC Ecuador
+EE Estonia
+EG Egypt
+EH Western Sahara
+ER Eritrea
+ES Spain
+ET Ethiopia
+FI Finland
+FJ Fiji
+FK Falkland Islands
+FM Micronesia
+FO Faroe Islands
+FR France
+GA Gabon
+GB Britain (UK)
+GD Grenada
+GE Georgia
+GF French Guiana
+GG Guernsey
+GH Ghana
+GI Gibraltar
+GL Greenland
+GM Gambia
+GN Guinea
+GP Guadeloupe
+GQ Equatorial Guinea
+GR Greece
+GS South Georgia & the South Sandwich Islands
+GT Guatemala
+GU Guam
+GW Guinea-Bissau
+GY Guyana
+HK Hong Kong
+HM Heard Island & McDonald Islands
+HN Honduras
+HR Croatia
+HT Haiti
+HU Hungary
+ID Indonesia
+IE Ireland
+IL Israel
+IM Isle of Man
+IN India
+IO British Indian Ocean Territory
+IQ Iraq
+IR Iran
+IS Iceland
+IT Italy
+JE Jersey
+JM Jamaica
+JO Jordan
+JP Japan
+KE Kenya
+KG Kyrgyzstan
+KH Cambodia
+KI Kiribati
+KM Comoros
+KN St Kitts & Nevis
+KP Korea (North)
+KR Korea (South)
+KW Kuwait
+KY Cayman Islands
+KZ Kazakhstan
+LA Laos
+LB Lebanon
+LC St Lucia
+LI Liechtenstein
+LK Sri Lanka
+LR Liberia
+LS Lesotho
+LT Lithuania
+LU Luxembourg
+LV Latvia
+LY Libya
+MA Morocco
+MC Monaco
+MD Moldova
+ME Montenegro
+MF St Martin (French)
+MG Madagascar
+MH Marshall Islands
+MK North Macedonia
+ML Mali
+MM Myanmar (Burma)
+MN Mongolia
+MO Macau
+MP Northern Mariana Islands
+MQ Martinique
+MR Mauritania
+MS Montserrat
+MT Malta
+MU Mauritius
+MV Maldives
+MW Malawi
+MX Mexico
+MY Malaysia
+MZ Mozambique
+NA Namibia
+NC New Caledonia
+NE Niger
+NF Norfolk Island
+NG Nigeria
+NI Nicaragua
+NL Netherlands
+NO Norway
+NP Nepal
+NR Nauru
+NU Niue
+NZ New Zealand
+OM Oman
+PA Panama
+PE Peru
+PF French Polynesia
+PG Papua New Guinea
+PH Philippines
+PK Pakistan
+PL Poland
+PM St Pierre & Miquelon
+PN Pitcairn
+PR Puerto Rico
+PS Palestine
+PT Portugal
+PW Palau
+PY Paraguay
+QA Qatar
+RE Réunion
+RO Romania
+RS Serbia
+RU Russia
+RW Rwanda
+SA Saudi Arabia
+SB Solomon Islands
+SC Seychelles
+SD Sudan
+SE Sweden
+SG Singapore
+SH St Helena
+SI Slovenia
+SJ Svalbard & Jan Mayen
+SK Slovakia
+SL Sierra Leone
+SM San Marino
+SN Senegal
+SO Somalia
+SR Suriname
+SS South Sudan
+ST Sao Tome & Principe
+SV El Salvador
+SX St Maarten (Dutch)
+SY Syria
+SZ Eswatini (Swaziland)
+TC Turks & Caicos Is
+TD Chad
+TF French S. Terr.
+TG Togo
+TH Thailand
+TJ Tajikistan
+TK Tokelau
+TL East Timor
+TM Turkmenistan
+TN Tunisia
+TO Tonga
+TR Turkey
+TT Trinidad & Tobago
+TV Tuvalu
+TW Taiwan
+TZ Tanzania
+UA Ukraine
+UG Uganda
+UM US minor outlying islands
+US United States
+UY Uruguay
+UZ Uzbekistan
+VA Vatican City
+VC St Vincent
+VE Venezuela
+VG Virgin Islands (UK)
+VI Virgin Islands (US)
+VN Vietnam
+VU Vanuatu
+WF Wallis & Futuna
+WS Samoa (western)
+YE Yemen
+YT Mayotte
+ZA South Africa
+ZM Zambia
+ZW Zimbabwe
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/leapseconds b/python_embeded/Lib/site-packages/pytz/zoneinfo/leapseconds
new file mode 100644
index 0000000000000000000000000000000000000000..76f771427f25b91e6944ffd2fee6031bfd73979a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pytz/zoneinfo/leapseconds
@@ -0,0 +1,79 @@
+# Allowance for leap seconds added to each time zone file.
+
+# This file is in the public domain.
+
+# This file is generated automatically from the data in the public-domain
+# NIST/IERS format leap-seconds.list file, which can be copied from
+#
+# or, in a variant with different comments, from
+# .
+# For more about leap-seconds.list, please see
+# The NTP Timescale and Leap Seconds
+# .
+
+# The rules for leap seconds are specified in Annex 1 (Time scales) of:
+# Standard-frequency and time-signal emissions.
+# International Telecommunication Union - Radiocommunication Sector
+# (ITU-R) Recommendation TF.460-6 (02/2002)
+# .
+# The International Earth Rotation and Reference Systems Service (IERS)
+# periodically uses leap seconds to keep UTC to within 0.9 s of UT1
+# (a proxy for Earth's angle in space as measured by astronomers)
+# and publishes leap second data in a copyrighted file
+# .
+# See: Levine J. Coordinated Universal Time and the leap second.
+# URSI Radio Sci Bull. 2016;89(4):30-6. doi:10.23919/URSIRSB.2016.7909995
+# .
+
+# There were no leap seconds before 1972, as no official mechanism
+# accounted for the discrepancy between atomic time (TAI) and the earth's
+# rotation. The first ("1 Jan 1972") data line in leap-seconds.list
+# does not denote a leap second; it denotes the start of the current definition
+# of UTC.
+
+# All leap-seconds are Stationary (S) at the given UTC time.
+# The correction (+ or -) is made at the given time, so in the unlikely
+# event of a negative leap second, a line would look like this:
+# Leap YEAR MON DAY 23:59:59 - S
+# Typical lines look like this:
+# Leap YEAR MON DAY 23:59:60 + S
+Leap 1972 Jun 30 23:59:60 + S
+Leap 1972 Dec 31 23:59:60 + S
+Leap 1973 Dec 31 23:59:60 + S
+Leap 1974 Dec 31 23:59:60 + S
+Leap 1975 Dec 31 23:59:60 + S
+Leap 1976 Dec 31 23:59:60 + S
+Leap 1977 Dec 31 23:59:60 + S
+Leap 1978 Dec 31 23:59:60 + S
+Leap 1979 Dec 31 23:59:60 + S
+Leap 1981 Jun 30 23:59:60 + S
+Leap 1982 Jun 30 23:59:60 + S
+Leap 1983 Jun 30 23:59:60 + S
+Leap 1985 Jun 30 23:59:60 + S
+Leap 1987 Dec 31 23:59:60 + S
+Leap 1989 Dec 31 23:59:60 + S
+Leap 1990 Dec 31 23:59:60 + S
+Leap 1992 Jun 30 23:59:60 + S
+Leap 1993 Jun 30 23:59:60 + S
+Leap 1994 Jun 30 23:59:60 + S
+Leap 1995 Dec 31 23:59:60 + S
+Leap 1997 Jun 30 23:59:60 + S
+Leap 1998 Dec 31 23:59:60 + S
+Leap 2005 Dec 31 23:59:60 + S
+Leap 2008 Dec 31 23:59:60 + S
+Leap 2012 Jun 30 23:59:60 + S
+Leap 2015 Jun 30 23:59:60 + S
+Leap 2016 Dec 31 23:59:60 + S
+
+# UTC timestamp when this leap second list expires.
+# Any additional leap seconds will come after this.
+# This Expires line is commented out for now,
+# so that pre-2020a zic implementations do not reject this file.
+#Expires 2025 Dec 28 00:00:00
+
+# POSIX timestamps for the data in this file:
+#updated 1736208000 (2025-01-07 00:00:00 UTC)
+#expires 1766880000 (2025-12-28 00:00:00 UTC)
+
+# Updated through IERS Bulletin C (https://hpiers.obspm.fr/iers/bul/bulc/bulletinc.dat)
+# File expires on 28 December 2025
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/tzdata.zi b/python_embeded/Lib/site-packages/pytz/zoneinfo/tzdata.zi
new file mode 100644
index 0000000000000000000000000000000000000000..0bcae52e5efa123d39e17553fda5ebade3bcc394
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pytz/zoneinfo/tzdata.zi
@@ -0,0 +1,4300 @@
+# version unknown
+# This zic input file is in the public domain.
+R d 1916 o - Jun 14 23s 1 S
+R d 1916 1919 - O Su>=1 23s 0 -
+R d 1917 o - Mar 24 23s 1 S
+R d 1918 o - Mar 9 23s 1 S
+R d 1919 o - Mar 1 23s 1 S
+R d 1920 o - F 14 23s 1 S
+R d 1920 o - O 23 23s 0 -
+R d 1921 o - Mar 14 23s 1 S
+R d 1921 o - Jun 21 23s 0 -
+R d 1939 o - S 11 23s 1 S
+R d 1939 o - N 19 1 0 -
+R d 1944 1945 - Ap M>=1 2 1 S
+R d 1944 o - O 8 2 0 -
+R d 1945 o - S 16 1 0 -
+R d 1971 o - Ap 25 23s 1 S
+R d 1971 o - S 26 23s 0 -
+R d 1977 o - May 6 0 1 S
+R d 1977 o - O 21 0 0 -
+R d 1978 o - Mar 24 1 1 S
+R d 1978 o - S 22 3 0 -
+R d 1980 o - Ap 25 0 1 S
+R d 1980 o - O 31 2 0 -
+R K 1940 o - Jul 15 0 1 S
+R K 1940 o - O 1 0 0 -
+R K 1941 o - Ap 15 0 1 S
+R K 1941 o - S 16 0 0 -
+R K 1942 1944 - Ap 1 0 1 S
+R K 1942 o - O 27 0 0 -
+R K 1943 1945 - N 1 0 0 -
+R K 1945 o - Ap 16 0 1 S
+R K 1957 o - May 10 0 1 S
+R K 1957 1958 - O 1 0 0 -
+R K 1958 o - May 1 0 1 S
+R K 1959 1981 - May 1 1 1 S
+R K 1959 1965 - S 30 3 0 -
+R K 1966 1994 - O 1 3 0 -
+R K 1982 o - Jul 25 1 1 S
+R K 1983 o - Jul 12 1 1 S
+R K 1984 1988 - May 1 1 1 S
+R K 1989 o - May 6 1 1 S
+R K 1990 1994 - May 1 1 1 S
+R K 1995 2010 - Ap lastF 0s 1 S
+R K 1995 2005 - S lastTh 24 0 -
+R K 2006 o - S 21 24 0 -
+R K 2007 o - S Th>=1 24 0 -
+R K 2008 o - Au lastTh 24 0 -
+R K 2009 o - Au 20 24 0 -
+R K 2010 o - Au 10 24 0 -
+R K 2010 o - S 9 24 1 S
+R K 2010 o - S lastTh 24 0 -
+R K 2014 o - May 15 24 1 S
+R K 2014 o - Jun 26 24 0 -
+R K 2014 o - Jul 31 24 1 S
+R K 2014 o - S lastTh 24 0 -
+R K 2023 ma - Ap lastF 0 1 S
+R K 2023 ma - O lastTh 24 0 -
+R L 1951 o - O 14 2 1 S
+R L 1952 o - Ja 1 0 0 -
+R L 1953 o - O 9 2 1 S
+R L 1954 o - Ja 1 0 0 -
+R L 1955 o - S 30 0 1 S
+R L 1956 o - Ja 1 0 0 -
+R L 1982 1984 - Ap 1 0 1 S
+R L 1982 1985 - O 1 0 0 -
+R L 1985 o - Ap 6 0 1 S
+R L 1986 o - Ap 4 0 1 S
+R L 1986 o - O 3 0 0 -
+R L 1987 1989 - Ap 1 0 1 S
+R L 1987 1989 - O 1 0 0 -
+R L 1997 o - Ap 4 0 1 S
+R L 1997 o - O 4 0 0 -
+R L 2013 o - Mar lastF 1 1 S
+R L 2013 o - O lastF 2 0 -
+R MU 1982 o - O 10 0 1 -
+R MU 1983 o - Mar 21 0 0 -
+R MU 2008 o - O lastSu 2 1 -
+R MU 2009 o - Mar lastSu 2 0 -
+R M 1939 o - S 12 0 1 -
+R M 1939 o - N 19 0 0 -
+R M 1940 o - F 25 0 1 -
+R M 1945 o - N 18 0 0 -
+R M 1950 o - Jun 11 0 1 -
+R M 1950 o - O 29 0 0 -
+R M 1967 o - Jun 3 12 1 -
+R M 1967 o - O 1 0 0 -
+R M 1974 o - Jun 24 0 1 -
+R M 1974 o - S 1 0 0 -
+R M 1976 1977 - May 1 0 1 -
+R M 1976 o - Au 1 0 0 -
+R M 1977 o - S 28 0 0 -
+R M 1978 o - Jun 1 0 1 -
+R M 1978 o - Au 4 0 0 -
+R M 2008 o - Jun 1 0 1 -
+R M 2008 o - S 1 0 0 -
+R M 2009 o - Jun 1 0 1 -
+R M 2009 o - Au 21 0 0 -
+R M 2010 o - May 2 0 1 -
+R M 2010 o - Au 8 0 0 -
+R M 2011 o - Ap 3 0 1 -
+R M 2011 o - Jul 31 0 0 -
+R M 2012 2013 - Ap lastSu 2 1 -
+R M 2012 o - Jul 20 3 0 -
+R M 2012 o - Au 20 2 1 -
+R M 2012 o - S 30 3 0 -
+R M 2013 o - Jul 7 3 0 -
+R M 2013 o - Au 10 2 1 -
+R M 2013 2018 - O lastSu 3 0 -
+R M 2014 2018 - Mar lastSu 2 1 -
+R M 2014 o - Jun 28 3 0 -
+R M 2014 o - Au 2 2 1 -
+R M 2015 o - Jun 14 3 0 -
+R M 2015 o - Jul 19 2 1 -
+R M 2016 o - Jun 5 3 0 -
+R M 2016 o - Jul 10 2 1 -
+R M 2017 o - May 21 3 0 -
+R M 2017 o - Jul 2 2 1 -
+R M 2018 o - May 13 3 0 -
+R M 2018 o - Jun 17 2 1 -
+R M 2019 o - May 5 3 -1 -
+R M 2019 o - Jun 9 2 0 -
+R M 2020 o - Ap 19 3 -1 -
+R M 2020 o - May 31 2 0 -
+R M 2021 o - Ap 11 3 -1 -
+R M 2021 o - May 16 2 0 -
+R M 2022 o - Mar 27 3 -1 -
+R M 2022 o - May 8 2 0 -
+R M 2023 o - Mar 19 3 -1 -
+R M 2023 o - Ap 23 2 0 -
+R M 2024 o - Mar 10 3 -1 -
+R M 2024 o - Ap 14 2 0 -
+R M 2025 o - F 23 3 -1 -
+R M 2025 o - Ap 6 2 0 -
+R M 2026 o - F 15 3 -1 -
+R M 2026 o - Mar 22 2 0 -
+R M 2027 o - F 7 3 -1 -
+R M 2027 o - Mar 14 2 0 -
+R M 2028 o - Ja 23 3 -1 -
+R M 2028 o - Mar 5 2 0 -
+R M 2029 o - Ja 14 3 -1 -
+R M 2029 o - F 18 2 0 -
+R M 2029 o - D 30 3 -1 -
+R M 2030 o - F 10 2 0 -
+R M 2030 o - D 22 3 -1 -
+R M 2031 o - Ja 26 2 0 -
+R M 2031 o - D 14 3 -1 -
+R M 2032 o - Ja 18 2 0 -
+R M 2032 o - N 28 3 -1 -
+R M 2033 o - Ja 9 2 0 -
+R M 2033 o - N 20 3 -1 -
+R M 2033 o - D 25 2 0 -
+R M 2034 o - N 5 3 -1 -
+R M 2034 o - D 17 2 0 -
+R M 2035 o - O 28 3 -1 -
+R M 2035 o - D 9 2 0 -
+R M 2036 o - O 19 3 -1 -
+R M 2036 o - N 23 2 0 -
+R M 2037 o - O 4 3 -1 -
+R M 2037 o - N 15 2 0 -
+R M 2038 o - S 26 3 -1 -
+R M 2038 o - O 31 2 0 -
+R M 2039 o - S 18 3 -1 -
+R M 2039 o - O 23 2 0 -
+R M 2040 o - S 2 3 -1 -
+R M 2040 o - O 14 2 0 -
+R M 2041 o - Au 25 3 -1 -
+R M 2041 o - S 29 2 0 -
+R M 2042 o - Au 10 3 -1 -
+R M 2042 o - S 21 2 0 -
+R M 2043 o - Au 2 3 -1 -
+R M 2043 o - S 13 2 0 -
+R M 2044 o - Jul 24 3 -1 -
+R M 2044 o - Au 28 2 0 -
+R M 2045 o - Jul 9 3 -1 -
+R M 2045 o - Au 20 2 0 -
+R M 2046 o - Jul 1 3 -1 -
+R M 2046 o - Au 5 2 0 -
+R M 2047 o - Jun 23 3 -1 -
+R M 2047 o - Jul 28 2 0 -
+R M 2048 o - Jun 7 3 -1 -
+R M 2048 o - Jul 19 2 0 -
+R M 2049 o - May 30 3 -1 -
+R M 2049 o - Jul 4 2 0 -
+R M 2050 o - May 15 3 -1 -
+R M 2050 o - Jun 26 2 0 -
+R M 2051 o - May 7 3 -1 -
+R M 2051 o - Jun 18 2 0 -
+R M 2052 o - Ap 28 3 -1 -
+R M 2052 o - Jun 2 2 0 -
+R M 2053 o - Ap 13 3 -1 -
+R M 2053 o - May 25 2 0 -
+R M 2054 o - Ap 5 3 -1 -
+R M 2054 o - May 10 2 0 -
+R M 2055 o - Mar 28 3 -1 -
+R M 2055 o - May 2 2 0 -
+R M 2056 o - Mar 12 3 -1 -
+R M 2056 o - Ap 23 2 0 -
+R M 2057 o - Mar 4 3 -1 -
+R M 2057 o - Ap 8 2 0 -
+R M 2058 o - F 17 3 -1 -
+R M 2058 o - Mar 31 2 0 -
+R M 2059 o - F 9 3 -1 -
+R M 2059 o - Mar 23 2 0 -
+R M 2060 o - F 1 3 -1 -
+R M 2060 o - Mar 7 2 0 -
+R M 2061 o - Ja 16 3 -1 -
+R M 2061 o - F 27 2 0 -
+R M 2062 o - Ja 8 3 -1 -
+R M 2062 o - F 12 2 0 -
+R M 2062 o - D 31 3 -1 -
+R M 2063 o - F 4 2 0 -
+R M 2063 o - D 16 3 -1 -
+R M 2064 o - Ja 27 2 0 -
+R M 2064 o - D 7 3 -1 -
+R M 2065 o - Ja 11 2 0 -
+R M 2065 o - N 22 3 -1 -
+R M 2066 o - Ja 3 2 0 -
+R M 2066 o - N 14 3 -1 -
+R M 2066 o - D 26 2 0 -
+R M 2067 o - N 6 3 -1 -
+R M 2067 o - D 11 2 0 -
+R M 2068 o - O 21 3 -1 -
+R M 2068 o - D 2 2 0 -
+R M 2069 o - O 13 3 -1 -
+R M 2069 o - N 17 2 0 -
+R M 2070 o - O 5 3 -1 -
+R M 2070 o - N 9 2 0 -
+R M 2071 o - S 20 3 -1 -
+R M 2071 o - N 1 2 0 -
+R M 2072 o - S 11 3 -1 -
+R M 2072 o - O 16 2 0 -
+R M 2073 o - Au 27 3 -1 -
+R M 2073 o - O 8 2 0 -
+R M 2074 o - Au 19 3 -1 -
+R M 2074 o - S 30 2 0 -
+R M 2075 o - Au 11 3 -1 -
+R M 2075 o - S 15 2 0 -
+R M 2076 o - Jul 26 3 -1 -
+R M 2076 o - S 6 2 0 -
+R M 2077 o - Jul 18 3 -1 -
+R M 2077 o - Au 22 2 0 -
+R M 2078 o - Jul 10 3 -1 -
+R M 2078 o - Au 14 2 0 -
+R M 2079 o - Jun 25 3 -1 -
+R M 2079 o - Au 6 2 0 -
+R M 2080 o - Jun 16 3 -1 -
+R M 2080 o - Jul 21 2 0 -
+R M 2081 o - Jun 1 3 -1 -
+R M 2081 o - Jul 13 2 0 -
+R M 2082 o - May 24 3 -1 -
+R M 2082 o - Jun 28 2 0 -
+R M 2083 o - May 16 3 -1 -
+R M 2083 o - Jun 20 2 0 -
+R M 2084 o - Ap 30 3 -1 -
+R M 2084 o - Jun 11 2 0 -
+R M 2085 o - Ap 22 3 -1 -
+R M 2085 o - May 27 2 0 -
+R M 2086 o - Ap 14 3 -1 -
+R M 2086 o - May 19 2 0 -
+R M 2087 o - Mar 30 3 -1 -
+R M 2087 o - May 11 2 0 -
+R NA 1994 o - Mar 21 0 -1 WAT
+R NA 1994 2017 - S Su>=1 2 0 CAT
+R NA 1995 2017 - Ap Su>=1 2 -1 WAT
+R SA 1942 1943 - S Su>=15 2 1 -
+R SA 1943 1944 - Mar Su>=15 2 0 -
+R SD 1970 o - May 1 0 1 S
+R SD 1970 1985 - O 15 0 0 -
+R SD 1971 o - Ap 30 0 1 S
+R SD 1972 1985 - Ap lastSu 0 1 S
+R n 1939 o - Ap 15 23s 1 S
+R n 1939 o - N 18 23s 0 -
+R n 1940 o - F 25 23s 1 S
+R n 1941 o - O 6 0 0 -
+R n 1942 o - Mar 9 0 1 S
+R n 1942 o - N 2 3 0 -
+R n 1943 o - Mar 29 2 1 S
+R n 1943 o - Ap 17 2 0 -
+R n 1943 o - Ap 25 2 1 S
+R n 1943 o - O 4 2 0 -
+R n 1944 1945 - Ap M>=1 2 1 S
+R n 1944 o - O 8 0 0 -
+R n 1945 o - S 16 0 0 -
+R n 1977 o - Ap 30 0s 1 S
+R n 1977 o - S 24 0s 0 -
+R n 1978 o - May 1 0s 1 S
+R n 1978 o - O 1 0s 0 -
+R n 1988 o - Jun 1 0s 1 S
+R n 1988 1990 - S lastSu 0s 0 -
+R n 1989 o - Mar 26 0s 1 S
+R n 1990 o - May 1 0s 1 S
+R n 2005 o - May 1 0s 1 S
+R n 2005 o - S 30 1s 0 -
+R n 2006 2008 - Mar lastSu 2s 1 S
+R n 2006 2008 - O lastSu 2s 0 -
+R Tr 2005 ma - Mar lastSu 1u 2 +02
+R Tr 2004 ma - O lastSu 1u 0 +00
+R AM 2011 o - Mar lastSu 2s 1 -
+R AM 2011 o - O lastSu 2s 0 -
+R AZ 1997 2015 - Mar lastSu 4 1 -
+R AZ 1997 2015 - O lastSu 5 0 -
+R BD 2009 o - Jun 19 23 1 -
+R BD 2009 o - D 31 24 0 -
+R Sh 1919 o - Ap 12 24 1 D
+R Sh 1919 o - S 30 24 0 S
+R Sh 1940 o - Jun 1 0 1 D
+R Sh 1940 o - O 12 24 0 S
+R Sh 1941 o - Mar 15 0 1 D
+R Sh 1941 o - N 1 24 0 S
+R Sh 1942 o - Ja 31 0 1 D
+R Sh 1945 o - S 1 24 0 S
+R Sh 1946 o - May 15 0 1 D
+R Sh 1946 o - S 30 24 0 S
+R Sh 1947 o - Ap 15 0 1 D
+R Sh 1947 o - O 31 24 0 S
+R Sh 1948 1949 - May 1 0 1 D
+R Sh 1948 1949 - S 30 24 0 S
+R CN 1986 o - May 4 2 1 D
+R CN 1986 1991 - S Su>=11 2 0 S
+R CN 1987 1991 - Ap Su>=11 2 1 D
+R HK 1946 o - Ap 21 0 1 S
+R HK 1946 o - D 1 3:30s 0 -
+R HK 1947 o - Ap 13 3:30s 1 S
+R HK 1947 o - N 30 3:30s 0 -
+R HK 1948 o - May 2 3:30s 1 S
+R HK 1948 1952 - O Su>=28 3:30s 0 -
+R HK 1949 1953 - Ap Su>=1 3:30 1 S
+R HK 1953 1964 - O Su>=31 3:30 0 -
+R HK 1954 1964 - Mar Su>=18 3:30 1 S
+R HK 1965 1976 - Ap Su>=16 3:30 1 S
+R HK 1965 1976 - O Su>=16 3:30 0 -
+R HK 1973 o - D 30 3:30 1 S
+R HK 1979 o - May 13 3:30 1 S
+R HK 1979 o - O 21 3:30 0 -
+R f 1946 o - May 15 0 1 D
+R f 1946 o - O 1 0 0 S
+R f 1947 o - Ap 15 0 1 D
+R f 1947 o - N 1 0 0 S
+R f 1948 1951 - May 1 0 1 D
+R f 1948 1951 - O 1 0 0 S
+R f 1952 o - Mar 1 0 1 D
+R f 1952 1954 - N 1 0 0 S
+R f 1953 1959 - Ap 1 0 1 D
+R f 1955 1961 - O 1 0 0 S
+R f 1960 1961 - Jun 1 0 1 D
+R f 1974 1975 - Ap 1 0 1 D
+R f 1974 1975 - O 1 0 0 S
+R f 1979 o - Jul 1 0 1 D
+R f 1979 o - O 1 0 0 S
+R _ 1942 1943 - Ap 30 23 1 -
+R _ 1942 o - N 17 23 0 -
+R _ 1943 o - S 30 23 0 S
+R _ 1946 o - Ap 30 23s 1 D
+R _ 1946 o - S 30 23s 0 S
+R _ 1947 o - Ap 19 23s 1 D
+R _ 1947 o - N 30 23s 0 S
+R _ 1948 o - May 2 23s 1 D
+R _ 1948 o - O 31 23s 0 S
+R _ 1949 1950 - Ap Sa>=1 23s 1 D
+R _ 1949 1950 - O lastSa 23s 0 S
+R _ 1951 o - Mar 31 23s 1 D
+R _ 1951 o - O 28 23s 0 S
+R _ 1952 1953 - Ap Sa>=1 23s 1 D
+R _ 1952 o - N 1 23s 0 S
+R _ 1953 1954 - O lastSa 23s 0 S
+R _ 1954 1956 - Mar Sa>=17 23s 1 D
+R _ 1955 o - N 5 23s 0 S
+R _ 1956 1964 - N Su>=1 3:30 0 S
+R _ 1957 1964 - Mar Su>=18 3:30 1 D
+R _ 1965 1973 - Ap Su>=16 3:30 1 D
+R _ 1965 1966 - O Su>=16 2:30 0 S
+R _ 1967 1976 - O Su>=16 3:30 0 S
+R _ 1973 o - D 30 3:30 1 D
+R _ 1975 1976 - Ap Su>=16 3:30 1 D
+R _ 1979 o - May 13 3:30 1 D
+R _ 1979 o - O Su>=16 3:30 0 S
+R CY 1975 o - Ap 13 0 1 S
+R CY 1975 o - O 12 0 0 -
+R CY 1976 o - May 15 0 1 S
+R CY 1976 o - O 11 0 0 -
+R CY 1977 1980 - Ap Su>=1 0 1 S
+R CY 1977 o - S 25 0 0 -
+R CY 1978 o - O 2 0 0 -
+R CY 1979 1997 - S lastSu 0 0 -
+R CY 1981 1998 - Mar lastSu 0 1 S
+R i 1910 o - Ja 1 0 0 -
+R i 1977 o - Mar 21 23 1 -
+R i 1977 o - O 20 24 0 -
+R i 1978 o - Mar 24 24 1 -
+R i 1978 o - Au 5 1 0 -
+R i 1979 o - May 26 24 1 -
+R i 1979 o - S 18 24 0 -
+R i 1980 o - Mar 20 24 1 -
+R i 1980 o - S 22 24 0 -
+R i 1991 o - May 2 24 1 -
+R i 1992 1995 - Mar 21 24 1 -
+R i 1991 1995 - S 21 24 0 -
+R i 1996 o - Mar 20 24 1 -
+R i 1996 o - S 20 24 0 -
+R i 1997 1999 - Mar 21 24 1 -
+R i 1997 1999 - S 21 24 0 -
+R i 2000 o - Mar 20 24 1 -
+R i 2000 o - S 20 24 0 -
+R i 2001 2003 - Mar 21 24 1 -
+R i 2001 2003 - S 21 24 0 -
+R i 2004 o - Mar 20 24 1 -
+R i 2004 o - S 20 24 0 -
+R i 2005 o - Mar 21 24 1 -
+R i 2005 o - S 21 24 0 -
+R i 2008 o - Mar 20 24 1 -
+R i 2008 o - S 20 24 0 -
+R i 2009 2011 - Mar 21 24 1 -
+R i 2009 2011 - S 21 24 0 -
+R i 2012 o - Mar 20 24 1 -
+R i 2012 o - S 20 24 0 -
+R i 2013 2015 - Mar 21 24 1 -
+R i 2013 2015 - S 21 24 0 -
+R i 2016 o - Mar 20 24 1 -
+R i 2016 o - S 20 24 0 -
+R i 2017 2019 - Mar 21 24 1 -
+R i 2017 2019 - S 21 24 0 -
+R i 2020 o - Mar 20 24 1 -
+R i 2020 o - S 20 24 0 -
+R i 2021 2022 - Mar 21 24 1 -
+R i 2021 2022 - S 21 24 0 -
+R IQ 1982 o - May 1 0 1 -
+R IQ 1982 1984 - O 1 0 0 -
+R IQ 1983 o - Mar 31 0 1 -
+R IQ 1984 1985 - Ap 1 0 1 -
+R IQ 1985 1990 - S lastSu 1s 0 -
+R IQ 1986 1990 - Mar lastSu 1s 1 -
+R IQ 1991 2007 - Ap 1 3s 1 -
+R IQ 1991 2007 - O 1 3s 0 -
+R Z 1940 o - May 31 24u 1 D
+R Z 1940 o - S 30 24u 0 S
+R Z 1940 o - N 16 24u 1 D
+R Z 1942 1946 - O 31 24u 0 S
+R Z 1943 1944 - Mar 31 24u 1 D
+R Z 1945 1946 - Ap 15 24u 1 D
+R Z 1948 o - May 22 24u 2 DD
+R Z 1948 o - Au 31 24u 1 D
+R Z 1948 1949 - O 31 24u 0 S
+R Z 1949 o - Ap 30 24u 1 D
+R Z 1950 o - Ap 15 24u 1 D
+R Z 1950 o - S 14 24u 0 S
+R Z 1951 o - Mar 31 24u 1 D
+R Z 1951 o - N 10 24u 0 S
+R Z 1952 o - Ap 19 24u 1 D
+R Z 1952 o - O 18 24u 0 S
+R Z 1953 o - Ap 11 24u 1 D
+R Z 1953 o - S 12 24u 0 S
+R Z 1954 o - Jun 12 24u 1 D
+R Z 1954 o - S 11 24u 0 S
+R Z 1955 o - Jun 11 24u 1 D
+R Z 1955 o - S 10 24u 0 S
+R Z 1956 o - Jun 2 24u 1 D
+R Z 1956 o - S 29 24u 0 S
+R Z 1957 o - Ap 27 24u 1 D
+R Z 1957 o - S 21 24u 0 S
+R Z 1974 o - Jul 6 24 1 D
+R Z 1974 o - O 12 24 0 S
+R Z 1975 o - Ap 19 24 1 D
+R Z 1975 o - Au 30 24 0 S
+R Z 1980 o - Au 2 24s 1 D
+R Z 1980 o - S 13 24s 0 S
+R Z 1984 o - May 5 24s 1 D
+R Z 1984 o - Au 25 24s 0 S
+R Z 1985 o - Ap 13 24 1 D
+R Z 1985 o - Au 31 24 0 S
+R Z 1986 o - May 17 24 1 D
+R Z 1986 o - S 6 24 0 S
+R Z 1987 o - Ap 14 24 1 D
+R Z 1987 o - S 12 24 0 S
+R Z 1988 o - Ap 9 24 1 D
+R Z 1988 o - S 3 24 0 S
+R Z 1989 o - Ap 29 24 1 D
+R Z 1989 o - S 2 24 0 S
+R Z 1990 o - Mar 24 24 1 D
+R Z 1990 o - Au 25 24 0 S
+R Z 1991 o - Mar 23 24 1 D
+R Z 1991 o - Au 31 24 0 S
+R Z 1992 o - Mar 28 24 1 D
+R Z 1992 o - S 5 24 0 S
+R Z 1993 o - Ap 2 0 1 D
+R Z 1993 o - S 5 0 0 S
+R Z 1994 o - Ap 1 0 1 D
+R Z 1994 o - Au 28 0 0 S
+R Z 1995 o - Mar 31 0 1 D
+R Z 1995 o - S 3 0 0 S
+R Z 1996 o - Mar 14 24 1 D
+R Z 1996 o - S 15 24 0 S
+R Z 1997 o - Mar 20 24 1 D
+R Z 1997 o - S 13 24 0 S
+R Z 1998 o - Mar 20 0 1 D
+R Z 1998 o - S 6 0 0 S
+R Z 1999 o - Ap 2 2 1 D
+R Z 1999 o - S 3 2 0 S
+R Z 2000 o - Ap 14 2 1 D
+R Z 2000 o - O 6 1 0 S
+R Z 2001 o - Ap 9 1 1 D
+R Z 2001 o - S 24 1 0 S
+R Z 2002 o - Mar 29 1 1 D
+R Z 2002 o - O 7 1 0 S
+R Z 2003 o - Mar 28 1 1 D
+R Z 2003 o - O 3 1 0 S
+R Z 2004 o - Ap 7 1 1 D
+R Z 2004 o - S 22 1 0 S
+R Z 2005 2012 - Ap F<=1 2 1 D
+R Z 2005 o - O 9 2 0 S
+R Z 2006 o - O 1 2 0 S
+R Z 2007 o - S 16 2 0 S
+R Z 2008 o - O 5 2 0 S
+R Z 2009 o - S 27 2 0 S
+R Z 2010 o - S 12 2 0 S
+R Z 2011 o - O 2 2 0 S
+R Z 2012 o - S 23 2 0 S
+R Z 2013 ma - Mar F>=23 2 1 D
+R Z 2013 ma - O lastSu 2 0 S
+R JP 1948 o - May Sa>=1 24 1 D
+R JP 1948 1951 - S Sa>=8 25 0 S
+R JP 1949 o - Ap Sa>=1 24 1 D
+R JP 1950 1951 - May Sa>=1 24 1 D
+R J 1973 o - Jun 6 0 1 S
+R J 1973 1975 - O 1 0 0 -
+R J 1974 1977 - May 1 0 1 S
+R J 1976 o - N 1 0 0 -
+R J 1977 o - O 1 0 0 -
+R J 1978 o - Ap 30 0 1 S
+R J 1978 o - S 30 0 0 -
+R J 1985 o - Ap 1 0 1 S
+R J 1985 o - O 1 0 0 -
+R J 1986 1988 - Ap F>=1 0 1 S
+R J 1986 1990 - O F>=1 0 0 -
+R J 1989 o - May 8 0 1 S
+R J 1990 o - Ap 27 0 1 S
+R J 1991 o - Ap 17 0 1 S
+R J 1991 o - S 27 0 0 -
+R J 1992 o - Ap 10 0 1 S
+R J 1992 1993 - O F>=1 0 0 -
+R J 1993 1998 - Ap F>=1 0 1 S
+R J 1994 o - S F>=15 0 0 -
+R J 1995 1998 - S F>=15 0s 0 -
+R J 1999 o - Jul 1 0s 1 S
+R J 1999 2002 - S lastF 0s 0 -
+R J 2000 2001 - Mar lastTh 0s 1 S
+R J 2002 2012 - Mar lastTh 24 1 S
+R J 2003 o - O 24 0s 0 -
+R J 2004 o - O 15 0s 0 -
+R J 2005 o - S lastF 0s 0 -
+R J 2006 2011 - O lastF 0s 0 -
+R J 2013 o - D 20 0 0 -
+R J 2014 2021 - Mar lastTh 24 1 S
+R J 2014 2022 - O lastF 0s 0 -
+R J 2022 o - F lastTh 24 1 S
+R KG 1992 1996 - Ap Su>=7 0s 1 -
+R KG 1992 1996 - S lastSu 0 0 -
+R KG 1997 2005 - Mar lastSu 2:30 1 -
+R KG 1997 2004 - O lastSu 2:30 0 -
+R KR 1948 o - Jun 1 0 1 D
+R KR 1948 o - S 12 24 0 S
+R KR 1949 o - Ap 3 0 1 D
+R KR 1949 1951 - S Sa>=7 24 0 S
+R KR 1950 o - Ap 1 0 1 D
+R KR 1951 o - May 6 0 1 D
+R KR 1955 o - May 5 0 1 D
+R KR 1955 o - S 8 24 0 S
+R KR 1956 o - May 20 0 1 D
+R KR 1956 o - S 29 24 0 S
+R KR 1957 1960 - May Su>=1 0 1 D
+R KR 1957 1960 - S Sa>=17 24 0 S
+R KR 1987 1988 - May Su>=8 2 1 D
+R KR 1987 1988 - O Su>=8 3 0 S
+R l 1920 o - Mar 28 0 1 S
+R l 1920 o - O 25 0 0 -
+R l 1921 o - Ap 3 0 1 S
+R l 1921 o - O 3 0 0 -
+R l 1922 o - Mar 26 0 1 S
+R l 1922 o - O 8 0 0 -
+R l 1923 o - Ap 22 0 1 S
+R l 1923 o - S 16 0 0 -
+R l 1957 1961 - May 1 0 1 S
+R l 1957 1961 - O 1 0 0 -
+R l 1972 o - Jun 22 0 1 S
+R l 1972 1977 - O 1 0 0 -
+R l 1973 1977 - May 1 0 1 S
+R l 1978 o - Ap 30 0 1 S
+R l 1978 o - S 30 0 0 -
+R l 1984 1987 - May 1 0 1 S
+R l 1984 1991 - O 16 0 0 -
+R l 1988 o - Jun 1 0 1 S
+R l 1989 o - May 10 0 1 S
+R l 1990 1992 - May 1 0 1 S
+R l 1992 o - O 4 0 0 -
+R l 1993 ma - Mar lastSu 0 1 S
+R l 1993 1998 - S lastSu 0 0 -
+R l 1999 ma - O lastSu 0 0 -
+R NB 1935 1941 - S 14 0 0:20 -
+R NB 1935 1941 - D 14 0 0 -
+R X 1983 1984 - Ap 1 0 1 -
+R X 1983 o - O 1 0 0 -
+R X 1985 1998 - Mar lastSu 0 1 -
+R X 1984 1998 - S lastSu 0 0 -
+R X 2001 o - Ap lastSa 2 1 -
+R X 2001 2006 - S lastSa 2 0 -
+R X 2002 2006 - Mar lastSa 2 1 -
+R X 2015 2016 - Mar lastSa 2 1 -
+R X 2015 2016 - S lastSa 0 0 -
+R PK 2002 o - Ap Su>=2 0 1 S
+R PK 2002 o - O Su>=2 0 0 -
+R PK 2008 o - Jun 1 0 1 S
+R PK 2008 2009 - N 1 0 0 -
+R PK 2009 o - Ap 15 0 1 S
+R P 1999 2005 - Ap F>=15 0 1 S
+R P 1999 2003 - O F>=15 0 0 -
+R P 2004 o - O 1 1 0 -
+R P 2005 o - O 4 2 0 -
+R P 2006 2007 - Ap 1 0 1 S
+R P 2006 o - S 22 0 0 -
+R P 2007 o - S 13 2 0 -
+R P 2008 2009 - Mar lastF 0 1 S
+R P 2008 o - S 1 0 0 -
+R P 2009 o - S 4 1 0 -
+R P 2010 o - Mar 26 0 1 S
+R P 2010 o - Au 11 0 0 -
+R P 2011 o - Ap 1 0:1 1 S
+R P 2011 o - Au 1 0 0 -
+R P 2011 o - Au 30 0 1 S
+R P 2011 o - S 30 0 0 -
+R P 2012 2014 - Mar lastTh 24 1 S
+R P 2012 o - S 21 1 0 -
+R P 2013 o - S 27 0 0 -
+R P 2014 o - O 24 0 0 -
+R P 2015 o - Mar 28 0 1 S
+R P 2015 o - O 23 1 0 -
+R P 2016 2018 - Mar Sa<=30 1 1 S
+R P 2016 2018 - O Sa<=30 1 0 -
+R P 2019 o - Mar 29 0 1 S
+R P 2019 o - O Sa<=30 0 0 -
+R P 2020 2021 - Mar Sa<=30 0 1 S
+R P 2020 o - O 24 1 0 -
+R P 2021 o - O 29 1 0 -
+R P 2022 o - Mar 27 0 1 S
+R P 2022 2035 - O Sa<=30 2 0 -
+R P 2023 o - Ap 29 2 1 S
+R P 2024 o - Ap 20 2 1 S
+R P 2025 o - Ap 12 2 1 S
+R P 2026 2054 - Mar Sa<=30 2 1 S
+R P 2036 o - O 18 2 0 -
+R P 2037 o - O 10 2 0 -
+R P 2038 o - S 25 2 0 -
+R P 2039 o - S 17 2 0 -
+R P 2040 o - S 1 2 0 -
+R P 2040 o - O 20 2 1 S
+R P 2040 2067 - O Sa<=30 2 0 -
+R P 2041 o - Au 24 2 0 -
+R P 2041 o - O 5 2 1 S
+R P 2042 o - Au 16 2 0 -
+R P 2042 o - S 27 2 1 S
+R P 2043 o - Au 1 2 0 -
+R P 2043 o - S 19 2 1 S
+R P 2044 o - Jul 23 2 0 -
+R P 2044 o - S 3 2 1 S
+R P 2045 o - Jul 15 2 0 -
+R P 2045 o - Au 26 2 1 S
+R P 2046 o - Jun 30 2 0 -
+R P 2046 o - Au 18 2 1 S
+R P 2047 o - Jun 22 2 0 -
+R P 2047 o - Au 3 2 1 S
+R P 2048 o - Jun 6 2 0 -
+R P 2048 o - Jul 25 2 1 S
+R P 2049 o - May 29 2 0 -
+R P 2049 o - Jul 10 2 1 S
+R P 2050 o - May 21 2 0 -
+R P 2050 o - Jul 2 2 1 S
+R P 2051 o - May 6 2 0 -
+R P 2051 o - Jun 24 2 1 S
+R P 2052 o - Ap 27 2 0 -
+R P 2052 o - Jun 8 2 1 S
+R P 2053 o - Ap 12 2 0 -
+R P 2053 o - May 31 2 1 S
+R P 2054 o - Ap 4 2 0 -
+R P 2054 o - May 23 2 1 S
+R P 2055 o - May 8 2 1 S
+R P 2056 o - Ap 29 2 1 S
+R P 2057 o - Ap 14 2 1 S
+R P 2058 o - Ap 6 2 1 S
+R P 2059 ma - Mar Sa<=30 2 1 S
+R P 2068 o - O 20 2 0 -
+R P 2069 o - O 12 2 0 -
+R P 2070 o - O 4 2 0 -
+R P 2071 o - S 19 2 0 -
+R P 2072 o - S 10 2 0 -
+R P 2072 o - O 22 2 1 S
+R P 2072 ma - O Sa<=30 2 0 -
+R P 2073 o - S 2 2 0 -
+R P 2073 o - O 14 2 1 S
+R P 2074 o - Au 18 2 0 -
+R P 2074 o - O 6 2 1 S
+R P 2075 o - Au 10 2 0 -
+R P 2075 o - S 21 2 1 S
+R P 2076 o - Jul 25 2 0 -
+R P 2076 o - S 12 2 1 S
+R P 2077 o - Jul 17 2 0 -
+R P 2077 o - S 4 2 1 S
+R P 2078 o - Jul 9 2 0 -
+R P 2078 o - Au 20 2 1 S
+R P 2079 o - Jun 24 2 0 -
+R P 2079 o - Au 12 2 1 S
+R P 2080 o - Jun 15 2 0 -
+R P 2080 o - Jul 27 2 1 S
+R P 2081 o - Jun 7 2 0 -
+R P 2081 o - Jul 19 2 1 S
+R P 2082 o - May 23 2 0 -
+R P 2082 o - Jul 11 2 1 S
+R P 2083 o - May 15 2 0 -
+R P 2083 o - Jun 26 2 1 S
+R P 2084 o - Ap 29 2 0 -
+R P 2084 o - Jun 17 2 1 S
+R P 2085 o - Ap 21 2 0 -
+R P 2085 o - Jun 9 2 1 S
+R P 2086 o - Ap 13 2 0 -
+R P 2086 o - May 25 2 1 S
+R PH 1936 o - O 31 24 1 D
+R PH 1937 o - Ja 15 24 0 S
+R PH 1941 o - D 15 24 1 D
+R PH 1945 o - N 30 24 0 S
+R PH 1954 o - Ap 11 24 1 D
+R PH 1954 o - Jun 4 24 0 S
+R PH 1977 o - Mar 27 24 1 D
+R PH 1977 o - S 21 24 0 S
+R PH 1990 o - May 21 0 1 D
+R PH 1990 o - Jul 28 24 0 S
+R S 1920 1923 - Ap Su>=15 2 1 S
+R S 1920 1923 - O Su>=1 2 0 -
+R S 1962 o - Ap 29 2 1 S
+R S 1962 o - O 1 2 0 -
+R S 1963 1965 - May 1 2 1 S
+R S 1963 o - S 30 2 0 -
+R S 1964 o - O 1 2 0 -
+R S 1965 o - S 30 2 0 -
+R S 1966 o - Ap 24 2 1 S
+R S 1966 1976 - O 1 2 0 -
+R S 1967 1978 - May 1 2 1 S
+R S 1977 1978 - S 1 2 0 -
+R S 1983 1984 - Ap 9 2 1 S
+R S 1983 1984 - O 1 2 0 -
+R S 1986 o - F 16 2 1 S
+R S 1986 o - O 9 2 0 -
+R S 1987 o - Mar 1 2 1 S
+R S 1987 1988 - O 31 2 0 -
+R S 1988 o - Mar 15 2 1 S
+R S 1989 o - Mar 31 2 1 S
+R S 1989 o - O 1 2 0 -
+R S 1990 o - Ap 1 2 1 S
+R S 1990 o - S 30 2 0 -
+R S 1991 o - Ap 1 0 1 S
+R S 1991 1992 - O 1 0 0 -
+R S 1992 o - Ap 8 0 1 S
+R S 1993 o - Mar 26 0 1 S
+R S 1993 o - S 25 0 0 -
+R S 1994 1996 - Ap 1 0 1 S
+R S 1994 2005 - O 1 0 0 -
+R S 1997 1998 - Mar lastM 0 1 S
+R S 1999 2006 - Ap 1 0 1 S
+R S 2006 o - S 22 0 0 -
+R S 2007 o - Mar lastF 0 1 S
+R S 2007 o - N F>=1 0 0 -
+R S 2008 o - Ap F>=1 0 1 S
+R S 2008 o - N 1 0 0 -
+R S 2009 o - Mar lastF 0 1 S
+R S 2010 2011 - Ap F>=1 0 1 S
+R S 2012 2022 - Mar lastF 0 1 S
+R S 2009 2022 - O lastF 0 0 -
+R AU 1917 o - Ja 1 2s 1 D
+R AU 1917 o - Mar lastSu 2s 0 S
+R AU 1942 o - Ja 1 2s 1 D
+R AU 1942 o - Mar lastSu 2s 0 S
+R AU 1942 o - S 27 2s 1 D
+R AU 1943 1944 - Mar lastSu 2s 0 S
+R AU 1943 o - O 3 2s 1 D
+R AW 1974 o - O lastSu 2s 1 D
+R AW 1975 o - Mar Su>=1 2s 0 S
+R AW 1983 o - O lastSu 2s 1 D
+R AW 1984 o - Mar Su>=1 2s 0 S
+R AW 1991 o - N 17 2s 1 D
+R AW 1992 o - Mar Su>=1 2s 0 S
+R AW 2006 o - D 3 2s 1 D
+R AW 2007 2009 - Mar lastSu 2s 0 S
+R AW 2007 2008 - O lastSu 2s 1 D
+R AQ 1971 o - O lastSu 2s 1 D
+R AQ 1972 o - F lastSu 2s 0 S
+R AQ 1989 1991 - O lastSu 2s 1 D
+R AQ 1990 1992 - Mar Su>=1 2s 0 S
+R Ho 1992 1993 - O lastSu 2s 1 D
+R Ho 1993 1994 - Mar Su>=1 2s 0 S
+R AS 1971 1985 - O lastSu 2s 1 D
+R AS 1986 o - O 19 2s 1 D
+R AS 1987 2007 - O lastSu 2s 1 D
+R AS 1972 o - F 27 2s 0 S
+R AS 1973 1985 - Mar Su>=1 2s 0 S
+R AS 1986 1990 - Mar Su>=15 2s 0 S
+R AS 1991 o - Mar 3 2s 0 S
+R AS 1992 o - Mar 22 2s 0 S
+R AS 1993 o - Mar 7 2s 0 S
+R AS 1994 o - Mar 20 2s 0 S
+R AS 1995 2005 - Mar lastSu 2s 0 S
+R AS 2006 o - Ap 2 2s 0 S
+R AS 2007 o - Mar lastSu 2s 0 S
+R AS 2008 ma - Ap Su>=1 2s 0 S
+R AS 2008 ma - O Su>=1 2s 1 D
+R AT 1916 o - O Su>=1 2s 1 D
+R AT 1917 o - Mar lastSu 2s 0 S
+R AT 1917 1918 - O Su>=22 2s 1 D
+R AT 1918 1919 - Mar Su>=1 2s 0 S
+R AT 1967 o - O Su>=1 2s 1 D
+R AT 1968 o - Mar Su>=29 2s 0 S
+R AT 1968 1985 - O lastSu 2s 1 D
+R AT 1969 1971 - Mar Su>=8 2s 0 S
+R AT 1972 o - F lastSu 2s 0 S
+R AT 1973 1981 - Mar Su>=1 2s 0 S
+R AT 1982 1983 - Mar lastSu 2s 0 S
+R AT 1984 1986 - Mar Su>=1 2s 0 S
+R AT 1986 o - O Su>=15 2s 1 D
+R AT 1987 1990 - Mar Su>=15 2s 0 S
+R AT 1987 o - O Su>=22 2s 1 D
+R AT 1988 1990 - O lastSu 2s 1 D
+R AT 1991 1999 - O Su>=1 2s 1 D
+R AT 1991 2005 - Mar lastSu 2s 0 S
+R AT 2000 o - Au lastSu 2s 1 D
+R AT 2001 ma - O Su>=1 2s 1 D
+R AT 2006 o - Ap Su>=1 2s 0 S
+R AT 2007 o - Mar lastSu 2s 0 S
+R AT 2008 ma - Ap Su>=1 2s 0 S
+R AV 1971 1985 - O lastSu 2s 1 D
+R AV 1972 o - F lastSu 2s 0 S
+R AV 1973 1985 - Mar Su>=1 2s 0 S
+R AV 1986 1990 - Mar Su>=15 2s 0 S
+R AV 1986 1987 - O Su>=15 2s 1 D
+R AV 1988 1999 - O lastSu 2s 1 D
+R AV 1991 1994 - Mar Su>=1 2s 0 S
+R AV 1995 2005 - Mar lastSu 2s 0 S
+R AV 2000 o - Au lastSu 2s 1 D
+R AV 2001 2007 - O lastSu 2s 1 D
+R AV 2006 o - Ap Su>=1 2s 0 S
+R AV 2007 o - Mar lastSu 2s 0 S
+R AV 2008 ma - Ap Su>=1 2s 0 S
+R AV 2008 ma - O Su>=1 2s 1 D
+R AN 1971 1985 - O lastSu 2s 1 D
+R AN 1972 o - F 27 2s 0 S
+R AN 1973 1981 - Mar Su>=1 2s 0 S
+R AN 1982 o - Ap Su>=1 2s 0 S
+R AN 1983 1985 - Mar Su>=1 2s 0 S
+R AN 1986 1989 - Mar Su>=15 2s 0 S
+R AN 1986 o - O 19 2s 1 D
+R AN 1987 1999 - O lastSu 2s 1 D
+R AN 1990 1995 - Mar Su>=1 2s 0 S
+R AN 1996 2005 - Mar lastSu 2s 0 S
+R AN 2000 o - Au lastSu 2s 1 D
+R AN 2001 2007 - O lastSu 2s 1 D
+R AN 2006 o - Ap Su>=1 2s 0 S
+R AN 2007 o - Mar lastSu 2s 0 S
+R AN 2008 ma - Ap Su>=1 2s 0 S
+R AN 2008 ma - O Su>=1 2s 1 D
+R LH 1981 1984 - O lastSu 2 1 -
+R LH 1982 1985 - Mar Su>=1 2 0 -
+R LH 1985 o - O lastSu 2 0:30 -
+R LH 1986 1989 - Mar Su>=15 2 0 -
+R LH 1986 o - O 19 2 0:30 -
+R LH 1987 1999 - O lastSu 2 0:30 -
+R LH 1990 1995 - Mar Su>=1 2 0 -
+R LH 1996 2005 - Mar lastSu 2 0 -
+R LH 2000 o - Au lastSu 2 0:30 -
+R LH 2001 2007 - O lastSu 2 0:30 -
+R LH 2006 o - Ap Su>=1 2 0 -
+R LH 2007 o - Mar lastSu 2 0 -
+R LH 2008 ma - Ap Su>=1 2 0 -
+R LH 2008 ma - O Su>=1 2 0:30 -
+R FJ 1998 1999 - N Su>=1 2 1 -
+R FJ 1999 2000 - F lastSu 3 0 -
+R FJ 2009 o - N 29 2 1 -
+R FJ 2010 o - Mar lastSu 3 0 -
+R FJ 2010 2013 - O Su>=21 2 1 -
+R FJ 2011 o - Mar Su>=1 3 0 -
+R FJ 2012 2013 - Ja Su>=18 3 0 -
+R FJ 2014 o - Ja Su>=18 2 0 -
+R FJ 2014 2018 - N Su>=1 2 1 -
+R FJ 2015 2021 - Ja Su>=12 3 0 -
+R FJ 2019 o - N Su>=8 2 1 -
+R FJ 2020 o - D 20 2 1 -
+R Gu 1959 o - Jun 27 2 1 D
+R Gu 1961 o - Ja 29 2 0 S
+R Gu 1967 o - S 1 2 1 D
+R Gu 1969 o - Ja 26 0:1 0 S
+R Gu 1969 o - Jun 22 2 1 D
+R Gu 1969 o - Au 31 2 0 S
+R Gu 1970 1971 - Ap lastSu 2 1 D
+R Gu 1970 1971 - S Su>=1 2 0 S
+R Gu 1973 o - D 16 2 1 D
+R Gu 1974 o - F 24 2 0 S
+R Gu 1976 o - May 26 2 1 D
+R Gu 1976 o - Au 22 2:1 0 S
+R Gu 1977 o - Ap 24 2 1 D
+R Gu 1977 o - Au 28 2 0 S
+R NC 1977 1978 - D Su>=1 0 1 -
+R NC 1978 1979 - F 27 0 0 -
+R NC 1996 o - D 1 2s 1 -
+R NC 1997 o - Mar 2 2s 0 -
+R NZ 1927 o - N 6 2 1 S
+R NZ 1928 o - Mar 4 2 0 M
+R NZ 1928 1933 - O Su>=8 2 0:30 S
+R NZ 1929 1933 - Mar Su>=15 2 0 M
+R NZ 1934 1940 - Ap lastSu 2 0 M
+R NZ 1934 1940 - S lastSu 2 0:30 S
+R NZ 1946 o - Ja 1 0 0 S
+R NZ 1974 o - N Su>=1 2s 1 D
+R k 1974 o - N Su>=1 2:45s 1 -
+R NZ 1975 o - F lastSu 2s 0 S
+R k 1975 o - F lastSu 2:45s 0 -
+R NZ 1975 1988 - O lastSu 2s 1 D
+R k 1975 1988 - O lastSu 2:45s 1 -
+R NZ 1976 1989 - Mar Su>=1 2s 0 S
+R k 1976 1989 - Mar Su>=1 2:45s 0 -
+R NZ 1989 o - O Su>=8 2s 1 D
+R k 1989 o - O Su>=8 2:45s 1 -
+R NZ 1990 2006 - O Su>=1 2s 1 D
+R k 1990 2006 - O Su>=1 2:45s 1 -
+R NZ 1990 2007 - Mar Su>=15 2s 0 S
+R k 1990 2007 - Mar Su>=15 2:45s 0 -
+R NZ 2007 ma - S lastSu 2s 1 D
+R k 2007 ma - S lastSu 2:45s 1 -
+R NZ 2008 ma - Ap Su>=1 2s 0 S
+R k 2008 ma - Ap Su>=1 2:45s 0 -
+R CK 1978 o - N 12 0 0:30 -
+R CK 1979 1991 - Mar Su>=1 0 0 -
+R CK 1979 1990 - O lastSu 0 0:30 -
+R WS 2010 o - S lastSu 0 1 -
+R WS 2011 o - Ap Sa>=1 4 0 -
+R WS 2011 o - S lastSa 3 1 -
+R WS 2012 2021 - Ap Su>=1 4 0 -
+R WS 2012 2020 - S lastSu 3 1 -
+R TO 1999 o - O 7 2s 1 -
+R TO 2000 o - Mar 19 2s 0 -
+R TO 2000 2001 - N Su>=1 2 1 -
+R TO 2001 2002 - Ja lastSu 2 0 -
+R TO 2016 o - N Su>=1 2 1 -
+R TO 2017 o - Ja Su>=15 3 0 -
+R VU 1973 o - D 22 12u 1 -
+R VU 1974 o - Mar 30 12u 0 -
+R VU 1983 1991 - S Sa>=22 24 1 -
+R VU 1984 1991 - Mar Sa>=22 24 0 -
+R VU 1992 1993 - Ja Sa>=22 24 0 -
+R VU 1992 o - O Sa>=22 24 1 -
+R G 1916 o - May 21 2s 1 BST
+R G 1916 o - O 1 2s 0 GMT
+R G 1917 o - Ap 8 2s 1 BST
+R G 1917 o - S 17 2s 0 GMT
+R G 1918 o - Mar 24 2s 1 BST
+R G 1918 o - S 30 2s 0 GMT
+R G 1919 o - Mar 30 2s 1 BST
+R G 1919 o - S 29 2s 0 GMT
+R G 1920 o - Mar 28 2s 1 BST
+R G 1920 o - O 25 2s 0 GMT
+R G 1921 o - Ap 3 2s 1 BST
+R G 1921 o - O 3 2s 0 GMT
+R G 1922 o - Mar 26 2s 1 BST
+R G 1922 o - O 8 2s 0 GMT
+R G 1923 o - Ap Su>=16 2s 1 BST
+R G 1923 1924 - S Su>=16 2s 0 GMT
+R G 1924 o - Ap Su>=9 2s 1 BST
+R G 1925 1926 - Ap Su>=16 2s 1 BST
+R G 1925 1938 - O Su>=2 2s 0 GMT
+R G 1927 o - Ap Su>=9 2s 1 BST
+R G 1928 1929 - Ap Su>=16 2s 1 BST
+R G 1930 o - Ap Su>=9 2s 1 BST
+R G 1931 1932 - Ap Su>=16 2s 1 BST
+R G 1933 o - Ap Su>=9 2s 1 BST
+R G 1934 o - Ap Su>=16 2s 1 BST
+R G 1935 o - Ap Su>=9 2s 1 BST
+R G 1936 1937 - Ap Su>=16 2s 1 BST
+R G 1938 o - Ap Su>=9 2s 1 BST
+R G 1939 o - Ap Su>=16 2s 1 BST
+R G 1939 o - N Su>=16 2s 0 GMT
+R G 1940 o - F Su>=23 2s 1 BST
+R G 1941 o - May Su>=2 1s 2 BDST
+R G 1941 1943 - Au Su>=9 1s 1 BST
+R G 1942 1944 - Ap Su>=2 1s 2 BDST
+R G 1944 o - S Su>=16 1s 1 BST
+R G 1945 o - Ap M>=2 1s 2 BDST
+R G 1945 o - Jul Su>=9 1s 1 BST
+R G 1945 1946 - O Su>=2 2s 0 GMT
+R G 1946 o - Ap Su>=9 2s 1 BST
+R G 1947 o - Mar 16 2s 1 BST
+R G 1947 o - Ap 13 1s 2 BDST
+R G 1947 o - Au 10 1s 1 BST
+R G 1947 o - N 2 2s 0 GMT
+R G 1948 o - Mar 14 2s 1 BST
+R G 1948 o - O 31 2s 0 GMT
+R G 1949 o - Ap 3 2s 1 BST
+R G 1949 o - O 30 2s 0 GMT
+R G 1950 1952 - Ap Su>=14 2s 1 BST
+R G 1950 1952 - O Su>=21 2s 0 GMT
+R G 1953 o - Ap Su>=16 2s 1 BST
+R G 1953 1960 - O Su>=2 2s 0 GMT
+R G 1954 o - Ap Su>=9 2s 1 BST
+R G 1955 1956 - Ap Su>=16 2s 1 BST
+R G 1957 o - Ap Su>=9 2s 1 BST
+R G 1958 1959 - Ap Su>=16 2s 1 BST
+R G 1960 o - Ap Su>=9 2s 1 BST
+R G 1961 1963 - Mar lastSu 2s 1 BST
+R G 1961 1968 - O Su>=23 2s 0 GMT
+R G 1964 1967 - Mar Su>=19 2s 1 BST
+R G 1968 o - F 18 2s 1 BST
+R G 1972 1980 - Mar Su>=16 2s 1 BST
+R G 1972 1980 - O Su>=23 2s 0 GMT
+R G 1981 1995 - Mar lastSu 1u 1 BST
+R G 1981 1989 - O Su>=23 1u 0 GMT
+R G 1990 1995 - O Su>=22 1u 0 GMT
+R IE 1971 o - O 31 2u -1 -
+R IE 1972 1980 - Mar Su>=16 2u 0 -
+R IE 1972 1980 - O Su>=23 2u -1 -
+R IE 1981 ma - Mar lastSu 1u 0 -
+R IE 1981 1989 - O Su>=23 1u -1 -
+R IE 1990 1995 - O Su>=22 1u -1 -
+R IE 1996 ma - O lastSu 1u -1 -
+R E 1977 1980 - Ap Su>=1 1u 1 S
+R E 1977 o - S lastSu 1u 0 -
+R E 1978 o - O 1 1u 0 -
+R E 1979 1995 - S lastSu 1u 0 -
+R E 1981 ma - Mar lastSu 1u 1 S
+R E 1996 ma - O lastSu 1u 0 -
+R W- 1977 1980 - Ap Su>=1 1s 1 S
+R W- 1977 o - S lastSu 1s 0 -
+R W- 1978 o - O 1 1s 0 -
+R W- 1979 1995 - S lastSu 1s 0 -
+R W- 1981 ma - Mar lastSu 1s 1 S
+R W- 1996 ma - O lastSu 1s 0 -
+R c 1916 o - Ap 30 23 1 S
+R c 1916 o - O 1 1 0 -
+R c 1917 1918 - Ap M>=15 2s 1 S
+R c 1917 1918 - S M>=15 2s 0 -
+R c 1940 o - Ap 1 2s 1 S
+R c 1942 o - N 2 2s 0 -
+R c 1943 o - Mar 29 2s 1 S
+R c 1943 o - O 4 2s 0 -
+R c 1944 1945 - Ap M>=1 2s 1 S
+R c 1944 o - O 2 2s 0 -
+R c 1945 o - S 16 2s 0 -
+R c 1977 1980 - Ap Su>=1 2s 1 S
+R c 1977 o - S lastSu 2s 0 -
+R c 1978 o - O 1 2s 0 -
+R c 1979 1995 - S lastSu 2s 0 -
+R c 1981 ma - Mar lastSu 2s 1 S
+R c 1996 ma - O lastSu 2s 0 -
+R e 1977 1980 - Ap Su>=1 0 1 S
+R e 1977 o - S lastSu 0 0 -
+R e 1978 o - O 1 0 0 -
+R e 1979 1995 - S lastSu 0 0 -
+R e 1981 ma - Mar lastSu 0 1 S
+R e 1996 ma - O lastSu 0 0 -
+R R 1917 o - Jul 1 23 1 MST
+R R 1917 o - D 28 0 0 MMT
+R R 1918 o - May 31 22 2 MDST
+R R 1918 o - S 16 1 1 MST
+R R 1919 o - May 31 23 2 MDST
+R R 1919 o - Jul 1 0u 1 MSD
+R R 1919 o - Au 16 0 0 MSK
+R R 1921 o - F 14 23 1 MSD
+R R 1921 o - Mar 20 23 2 +05
+R R 1921 o - S 1 0 1 MSD
+R R 1921 o - O 1 0 0 -
+R R 1981 1984 - Ap 1 0 1 S
+R R 1981 1983 - O 1 0 0 -
+R R 1984 1995 - S lastSu 2s 0 -
+R R 1985 2010 - Mar lastSu 2s 1 S
+R R 1996 2010 - O lastSu 2s 0 -
+R q 1940 o - Jun 16 0 1 S
+R q 1942 o - N 2 3 0 -
+R q 1943 o - Mar 29 2 1 S
+R q 1943 o - Ap 10 3 0 -
+R q 1974 o - May 4 0 1 S
+R q 1974 o - O 2 0 0 -
+R q 1975 o - May 1 0 1 S
+R q 1975 o - O 2 0 0 -
+R q 1976 o - May 2 0 1 S
+R q 1976 o - O 3 0 0 -
+R q 1977 o - May 8 0 1 S
+R q 1977 o - O 2 0 0 -
+R q 1978 o - May 6 0 1 S
+R q 1978 o - O 1 0 0 -
+R q 1979 o - May 5 0 1 S
+R q 1979 o - S 30 0 0 -
+R q 1980 o - May 3 0 1 S
+R q 1980 o - O 4 0 0 -
+R q 1981 o - Ap 26 0 1 S
+R q 1981 o - S 27 0 0 -
+R q 1982 o - May 2 0 1 S
+R q 1982 o - O 3 0 0 -
+R q 1983 o - Ap 18 0 1 S
+R q 1983 o - O 1 0 0 -
+R q 1984 o - Ap 1 0 1 S
+R a 1920 o - Ap 5 2s 1 S
+R a 1920 o - S 13 2s 0 -
+R a 1946 o - Ap 14 2s 1 S
+R a 1946 o - O 7 2s 0 -
+R a 1947 1948 - O Su>=1 2s 0 -
+R a 1947 o - Ap 6 2s 1 S
+R a 1948 o - Ap 18 2s 1 S
+R a 1980 o - Ap 6 0 1 S
+R a 1980 o - S 28 0 0 -
+R b 1918 o - Mar 9 0s 1 S
+R b 1918 1919 - O Sa>=1 23s 0 -
+R b 1919 o - Mar 1 23s 1 S
+R b 1920 o - F 14 23s 1 S
+R b 1920 o - O 23 23s 0 -
+R b 1921 o - Mar 14 23s 1 S
+R b 1921 o - O 25 23s 0 -
+R b 1922 o - Mar 25 23s 1 S
+R b 1922 1927 - O Sa>=1 23s 0 -
+R b 1923 o - Ap 21 23s 1 S
+R b 1924 o - Mar 29 23s 1 S
+R b 1925 o - Ap 4 23s 1 S
+R b 1926 o - Ap 17 23s 1 S
+R b 1927 o - Ap 9 23s 1 S
+R b 1928 o - Ap 14 23s 1 S
+R b 1928 1938 - O Su>=2 2s 0 -
+R b 1929 o - Ap 21 2s 1 S
+R b 1930 o - Ap 13 2s 1 S
+R b 1931 o - Ap 19 2s 1 S
+R b 1932 o - Ap 3 2s 1 S
+R b 1933 o - Mar 26 2s 1 S
+R b 1934 o - Ap 8 2s 1 S
+R b 1935 o - Mar 31 2s 1 S
+R b 1936 o - Ap 19 2s 1 S
+R b 1937 o - Ap 4 2s 1 S
+R b 1938 o - Mar 27 2s 1 S
+R b 1939 o - Ap 16 2s 1 S
+R b 1939 o - N 19 2s 0 -
+R b 1940 o - F 25 2s 1 S
+R b 1944 o - S 17 2s 0 -
+R b 1945 o - Ap 2 2s 1 S
+R b 1945 o - S 16 2s 0 -
+R b 1946 o - May 19 2s 1 S
+R b 1946 o - O 7 2s 0 -
+R BG 1979 o - Mar 31 23 1 S
+R BG 1979 o - O 1 1 0 -
+R BG 1980 1982 - Ap Sa>=1 23 1 S
+R BG 1980 o - S 29 1 0 -
+R BG 1981 o - S 27 2 0 -
+R CZ 1945 o - Ap M>=1 2s 1 S
+R CZ 1945 o - O 1 2s 0 -
+R CZ 1946 o - May 6 2s 1 S
+R CZ 1946 1949 - O Su>=1 2s 0 -
+R CZ 1947 1948 - Ap Su>=15 2s 1 S
+R CZ 1949 o - Ap 9 2s 1 S
+R Th 1991 1992 - Mar lastSu 2 1 D
+R Th 1991 1992 - S lastSu 2 0 S
+R Th 1993 2006 - Ap Su>=1 2 1 D
+R Th 1993 2006 - O lastSu 2 0 S
+R Th 2007 ma - Mar Su>=8 2 1 D
+R Th 2007 ma - N Su>=1 2 0 S
+R FI 1942 o - Ap 2 24 1 S
+R FI 1942 o - O 4 1 0 -
+R FI 1981 1982 - Mar lastSu 2 1 S
+R FI 1981 1982 - S lastSu 3 0 -
+R F 1916 o - Jun 14 23s 1 S
+R F 1916 1919 - O Su>=1 23s 0 -
+R F 1917 o - Mar 24 23s 1 S
+R F 1918 o - Mar 9 23s 1 S
+R F 1919 o - Mar 1 23s 1 S
+R F 1920 o - F 14 23s 1 S
+R F 1920 o - O 23 23s 0 -
+R F 1921 o - Mar 14 23s 1 S
+R F 1921 o - O 25 23s 0 -
+R F 1922 o - Mar 25 23s 1 S
+R F 1922 1938 - O Sa>=1 23s 0 -
+R F 1923 o - May 26 23s 1 S
+R F 1924 o - Mar 29 23s 1 S
+R F 1925 o - Ap 4 23s 1 S
+R F 1926 o - Ap 17 23s 1 S
+R F 1927 o - Ap 9 23s 1 S
+R F 1928 o - Ap 14 23s 1 S
+R F 1929 o - Ap 20 23s 1 S
+R F 1930 o - Ap 12 23s 1 S
+R F 1931 o - Ap 18 23s 1 S
+R F 1932 o - Ap 2 23s 1 S
+R F 1933 o - Mar 25 23s 1 S
+R F 1934 o - Ap 7 23s 1 S
+R F 1935 o - Mar 30 23s 1 S
+R F 1936 o - Ap 18 23s 1 S
+R F 1937 o - Ap 3 23s 1 S
+R F 1938 o - Mar 26 23s 1 S
+R F 1939 o - Ap 15 23s 1 S
+R F 1939 o - N 18 23s 0 -
+R F 1940 o - F 25 2 1 S
+R F 1941 o - May 5 0 2 M
+R F 1941 o - O 6 0 1 S
+R F 1942 o - Mar 9 0 2 M
+R F 1942 o - N 2 3 1 S
+R F 1943 o - Mar 29 2 2 M
+R F 1943 o - O 4 3 1 S
+R F 1944 o - Ap 3 2 2 M
+R F 1944 o - O 8 1 1 S
+R F 1945 o - Ap 2 2 2 M
+R F 1945 o - S 16 3 0 -
+R F 1976 o - Mar 28 1 1 S
+R F 1976 o - S 26 1 0 -
+R DE 1946 o - Ap 14 2s 1 S
+R DE 1946 o - O 7 2s 0 -
+R DE 1947 1949 - O Su>=1 2s 0 -
+R DE 1947 o - Ap 6 3s 1 S
+R DE 1947 o - May 11 2s 2 M
+R DE 1947 o - Jun 29 3 1 S
+R DE 1948 o - Ap 18 2s 1 S
+R DE 1949 o - Ap 10 2s 1 S
+R So 1945 o - May 24 2 2 M
+R So 1945 o - S 24 3 1 S
+R So 1945 o - N 18 2s 0 -
+R g 1932 o - Jul 7 0 1 S
+R g 1932 o - S 1 0 0 -
+R g 1941 o - Ap 7 0 1 S
+R g 1942 o - N 2 3 0 -
+R g 1943 o - Mar 30 0 1 S
+R g 1943 o - O 4 0 0 -
+R g 1952 o - Jul 1 0 1 S
+R g 1952 o - N 2 0 0 -
+R g 1975 o - Ap 12 0s 1 S
+R g 1975 o - N 26 0s 0 -
+R g 1976 o - Ap 11 2s 1 S
+R g 1976 o - O 10 2s 0 -
+R g 1977 1978 - Ap Su>=1 2s 1 S
+R g 1977 o - S 26 2s 0 -
+R g 1978 o - S 24 4 0 -
+R g 1979 o - Ap 1 9 1 S
+R g 1979 o - S 29 2 0 -
+R g 1980 o - Ap 1 0 1 S
+R g 1980 o - S 28 0 0 -
+R h 1918 1919 - Ap 15 2 1 S
+R h 1918 1920 - S M>=15 3 0 -
+R h 1920 o - Ap 5 2 1 S
+R h 1945 o - May 1 23 1 S
+R h 1945 o - N 1 1 0 -
+R h 1946 o - Mar 31 2s 1 S
+R h 1946 o - O 7 2 0 -
+R h 1947 1949 - Ap Su>=4 2s 1 S
+R h 1947 1949 - O Su>=1 2s 0 -
+R h 1954 o - May 23 0 1 S
+R h 1954 o - O 3 0 0 -
+R h 1955 o - May 22 2 1 S
+R h 1955 o - O 2 3 0 -
+R h 1956 1957 - Jun Su>=1 2 1 S
+R h 1956 1957 - S lastSu 3 0 -
+R h 1980 o - Ap 6 0 1 S
+R h 1980 o - S 28 1 0 -
+R h 1981 1983 - Mar lastSu 0 1 S
+R h 1981 1983 - S lastSu 1 0 -
+R I 1916 o - Jun 3 24 1 S
+R I 1916 1917 - S 30 24 0 -
+R I 1917 o - Mar 31 24 1 S
+R I 1918 o - Mar 9 24 1 S
+R I 1918 o - O 6 24 0 -
+R I 1919 o - Mar 1 24 1 S
+R I 1919 o - O 4 24 0 -
+R I 1920 o - Mar 20 24 1 S
+R I 1920 o - S 18 24 0 -
+R I 1940 o - Jun 14 24 1 S
+R I 1942 o - N 2 2s 0 -
+R I 1943 o - Mar 29 2s 1 S
+R I 1943 o - O 4 2s 0 -
+R I 1944 o - Ap 2 2s 1 S
+R I 1944 o - S 17 2s 0 -
+R I 1945 o - Ap 2 2 1 S
+R I 1945 o - S 15 1 0 -
+R I 1946 o - Mar 17 2s 1 S
+R I 1946 o - O 6 2s 0 -
+R I 1947 o - Mar 16 0s 1 S
+R I 1947 o - O 5 0s 0 -
+R I 1948 o - F 29 2s 1 S
+R I 1948 o - O 3 2s 0 -
+R I 1966 1968 - May Su>=22 0s 1 S
+R I 1966 o - S 24 24 0 -
+R I 1967 1969 - S Su>=22 0s 0 -
+R I 1969 o - Jun 1 0s 1 S
+R I 1970 o - May 31 0s 1 S
+R I 1970 o - S lastSu 0s 0 -
+R I 1971 1972 - May Su>=22 0s 1 S
+R I 1971 o - S lastSu 0s 0 -
+R I 1972 o - O 1 0s 0 -
+R I 1973 o - Jun 3 0s 1 S
+R I 1973 1974 - S lastSu 0s 0 -
+R I 1974 o - May 26 0s 1 S
+R I 1975 o - Jun 1 0s 1 S
+R I 1975 1977 - S lastSu 0s 0 -
+R I 1976 o - May 30 0s 1 S
+R I 1977 1979 - May Su>=22 0s 1 S
+R I 1978 o - O 1 0s 0 -
+R I 1979 o - S 30 0s 0 -
+R LV 1989 1996 - Mar lastSu 2s 1 S
+R LV 1989 1996 - S lastSu 2s 0 -
+R MT 1973 o - Mar 31 0s 1 S
+R MT 1973 o - S 29 0s 0 -
+R MT 1974 o - Ap 21 0s 1 S
+R MT 1974 o - S 16 0s 0 -
+R MT 1975 1979 - Ap Su>=15 2 1 S
+R MT 1975 1980 - S Su>=15 2 0 -
+R MT 1980 o - Mar 31 2 1 S
+R MD 1997 ma - Mar lastSu 2 1 S
+R MD 1997 ma - O lastSu 3 0 -
+R O 1918 1919 - S 16 2s 0 -
+R O 1919 o - Ap 15 2s 1 S
+R O 1944 o - Ap 3 2s 1 S
+R O 1944 o - O 4 2 0 -
+R O 1945 o - Ap 29 0 1 S
+R O 1945 o - N 1 0 0 -
+R O 1946 o - Ap 14 0s 1 S
+R O 1946 o - O 7 2s 0 -
+R O 1947 o - May 4 2s 1 S
+R O 1947 1949 - O Su>=1 2s 0 -
+R O 1948 o - Ap 18 2s 1 S
+R O 1949 o - Ap 10 2s 1 S
+R O 1957 o - Jun 2 1s 1 S
+R O 1957 1958 - S lastSu 1s 0 -
+R O 1958 o - Mar 30 1s 1 S
+R O 1959 o - May 31 1s 1 S
+R O 1959 1961 - O Su>=1 1s 0 -
+R O 1960 o - Ap 3 1s 1 S
+R O 1961 1964 - May lastSu 1s 1 S
+R O 1962 1964 - S lastSu 1s 0 -
+R p 1916 o - Jun 17 23 1 S
+R p 1916 o - N 1 1 0 -
+R p 1917 1921 - Mar 1 0 1 S
+R p 1917 1921 - O 14 24 0 -
+R p 1924 o - Ap 16 23s 1 S
+R p 1924 o - O 4 23s 0 -
+R p 1926 o - Ap 17 23s 1 S
+R p 1926 1929 - O Sa>=1 23s 0 -
+R p 1927 o - Ap 9 23s 1 S
+R p 1928 o - Ap 14 23s 1 S
+R p 1929 o - Ap 20 23s 1 S
+R p 1931 o - Ap 18 23s 1 S
+R p 1931 1932 - O Sa>=1 23s 0 -
+R p 1932 o - Ap 2 23s 1 S
+R p 1934 o - Ap 7 23s 1 S
+R p 1934 1938 - O Sa>=1 23s 0 -
+R p 1935 o - Mar 30 23s 1 S
+R p 1936 o - Ap 18 23s 1 S
+R p 1937 o - Ap 3 23s 1 S
+R p 1938 o - Mar 26 23s 1 S
+R p 1939 o - Ap 15 23s 1 S
+R p 1939 o - N 18 23s 0 -
+R p 1940 o - F 24 23s 1 S
+R p 1940 o - O 7 23s 0 -
+R p 1941 o - Ap 5 23s 1 S
+R p 1941 o - O 5 23s 0 -
+R p 1942 1945 - Mar Sa>=8 23s 1 S
+R p 1942 o - Ap 25 22s 2 M
+R p 1942 o - Au 15 22s 1 S
+R p 1942 1945 - O Sa>=24 23s 0 -
+R p 1943 o - Ap 17 22s 2 M
+R p 1943 1945 - Au Sa>=25 22s 1 S
+R p 1944 1945 - Ap Sa>=21 22s 2 M
+R p 1946 o - Ap Sa>=1 23s 1 S
+R p 1946 o - O Sa>=1 23s 0 -
+R p 1947 1966 - Ap Su>=1 2s 1 S
+R p 1947 1965 - O Su>=1 2s 0 -
+R p 1976 o - S lastSu 1 0 -
+R p 1977 o - Mar lastSu 0s 1 S
+R p 1977 o - S lastSu 0s 0 -
+R p 1978 1980 - Ap Su>=1 1s 1 S
+R p 1978 o - O 1 1s 0 -
+R p 1979 1980 - S lastSu 1s 0 -
+R p 1981 1986 - Mar lastSu 0s 1 S
+R p 1981 1985 - S lastSu 0s 0 -
+R z 1932 o - May 21 0s 1 S
+R z 1932 1939 - O Su>=1 0s 0 -
+R z 1933 1939 - Ap Su>=2 0s 1 S
+R z 1979 o - May 27 0 1 S
+R z 1979 o - S lastSu 0 0 -
+R z 1980 o - Ap 5 23 1 S
+R z 1980 o - S lastSu 1 0 -
+R z 1991 1993 - Mar lastSu 0s 1 S
+R z 1991 1993 - S lastSu 0s 0 -
+R s 1918 o - Ap 15 23 1 S
+R s 1918 1919 - O 6 24s 0 -
+R s 1919 o - Ap 6 23 1 S
+R s 1924 o - Ap 16 23 1 S
+R s 1924 o - O 4 24s 0 -
+R s 1926 o - Ap 17 23 1 S
+R s 1926 1929 - O Sa>=1 24s 0 -
+R s 1927 o - Ap 9 23 1 S
+R s 1928 o - Ap 15 0 1 S
+R s 1929 o - Ap 20 23 1 S
+R s 1937 o - Jun 16 23 1 S
+R s 1937 o - O 2 24s 0 -
+R s 1938 o - Ap 2 23 1 S
+R s 1938 o - Ap 30 23 2 M
+R s 1938 o - O 2 24 1 S
+R s 1939 o - O 7 24s 0 -
+R s 1942 o - May 2 23 1 S
+R s 1942 o - S 1 1 0 -
+R s 1943 1946 - Ap Sa>=13 23 1 S
+R s 1943 1944 - O Su>=1 1 0 -
+R s 1945 1946 - S lastSu 1 0 -
+R s 1949 o - Ap 30 23 1 S
+R s 1949 o - O 2 1 0 -
+R s 1974 1975 - Ap Sa>=12 23 1 S
+R s 1974 1975 - O Su>=1 1 0 -
+R s 1976 o - Mar 27 23 1 S
+R s 1976 1977 - S lastSu 1 0 -
+R s 1977 o - Ap 2 23 1 S
+R s 1978 o - Ap 2 2s 1 S
+R s 1978 o - O 1 2s 0 -
+R Sp 1967 o - Jun 3 12 1 S
+R Sp 1967 o - O 1 0 0 -
+R Sp 1974 o - Jun 24 0 1 S
+R Sp 1974 o - S 1 0 0 -
+R Sp 1976 1977 - May 1 0 1 S
+R Sp 1976 o - Au 1 0 0 -
+R Sp 1977 o - S 28 0 0 -
+R Sp 1978 o - Jun 1 0 1 S
+R Sp 1978 o - Au 4 0 0 -
+R CH 1941 1942 - May M>=1 1 1 S
+R CH 1941 1942 - O M>=1 2 0 -
+R T 1916 o - May 1 0 1 S
+R T 1916 o - O 1 0 0 -
+R T 1920 o - Mar 28 0 1 S
+R T 1920 o - O 25 0 0 -
+R T 1921 o - Ap 3 0 1 S
+R T 1921 o - O 3 0 0 -
+R T 1922 o - Mar 26 0 1 S
+R T 1922 o - O 8 0 0 -
+R T 1924 o - May 13 0 1 S
+R T 1924 1925 - O 1 0 0 -
+R T 1925 o - May 1 0 1 S
+R T 1940 o - Jul 1 0 1 S
+R T 1940 o - O 6 0 0 -
+R T 1940 o - D 1 0 1 S
+R T 1941 o - S 21 0 0 -
+R T 1942 o - Ap 1 0 1 S
+R T 1945 o - O 8 0 0 -
+R T 1946 o - Jun 1 0 1 S
+R T 1946 o - O 1 0 0 -
+R T 1947 1948 - Ap Su>=16 0 1 S
+R T 1947 1951 - O Su>=2 0 0 -
+R T 1949 o - Ap 10 0 1 S
+R T 1950 o - Ap 16 0 1 S
+R T 1951 o - Ap 22 0 1 S
+R T 1962 o - Jul 15 0 1 S
+R T 1963 o - O 30 0 0 -
+R T 1964 o - May 15 0 1 S
+R T 1964 o - O 1 0 0 -
+R T 1973 o - Jun 3 1 1 S
+R T 1973 1976 - O Su>=31 2 0 -
+R T 1974 o - Mar 31 2 1 S
+R T 1975 o - Mar 22 2 1 S
+R T 1976 o - Mar 21 2 1 S
+R T 1977 1978 - Ap Su>=1 2 1 S
+R T 1977 1978 - O Su>=15 2 0 -
+R T 1978 o - Jun 29 0 0 -
+R T 1983 o - Jul 31 2 1 S
+R T 1983 o - O 2 2 0 -
+R T 1985 o - Ap 20 1s 1 S
+R T 1985 o - S 28 1s 0 -
+R T 1986 1993 - Mar lastSu 1s 1 S
+R T 1986 1995 - S lastSu 1s 0 -
+R T 1994 o - Mar 20 1s 1 S
+R T 1995 2006 - Mar lastSu 1s 1 S
+R T 1996 2006 - O lastSu 1s 0 -
+R u 1918 1919 - Mar lastSu 2 1 D
+R u 1918 1919 - O lastSu 2 0 S
+R u 1942 o - F 9 2 1 W
+R u 1945 o - Au 14 23u 1 P
+R u 1945 o - S 30 2 0 S
+R u 1967 2006 - O lastSu 2 0 S
+R u 1967 1973 - Ap lastSu 2 1 D
+R u 1974 o - Ja 6 2 1 D
+R u 1975 o - F lastSu 2 1 D
+R u 1976 1986 - Ap lastSu 2 1 D
+R u 1987 2006 - Ap Su>=1 2 1 D
+R u 2007 ma - Mar Su>=8 2 1 D
+R u 2007 ma - N Su>=1 2 0 S
+R NY 1920 o - Mar lastSu 2 1 D
+R NY 1920 o - O lastSu 2 0 S
+R NY 1921 1966 - Ap lastSu 2 1 D
+R NY 1921 1954 - S lastSu 2 0 S
+R NY 1955 1966 - O lastSu 2 0 S
+R Ch 1920 o - Jun 13 2 1 D
+R Ch 1920 1921 - O lastSu 2 0 S
+R Ch 1921 o - Mar lastSu 2 1 D
+R Ch 1922 1966 - Ap lastSu 2 1 D
+R Ch 1922 1954 - S lastSu 2 0 S
+R Ch 1955 1966 - O lastSu 2 0 S
+R De 1920 1921 - Mar lastSu 2 1 D
+R De 1920 o - O lastSu 2 0 S
+R De 1921 o - May 22 2 0 S
+R De 1965 1966 - Ap lastSu 2 1 D
+R De 1965 1966 - O lastSu 2 0 S
+R CA 1948 o - Mar 14 2:1 1 D
+R CA 1949 o - Ja 1 2 0 S
+R CA 1950 1966 - Ap lastSu 1 1 D
+R CA 1950 1961 - S lastSu 2 0 S
+R CA 1962 1966 - O lastSu 2 0 S
+R In 1941 o - Jun 22 2 1 D
+R In 1941 1954 - S lastSu 2 0 S
+R In 1946 1954 - Ap lastSu 2 1 D
+R Ma 1951 o - Ap lastSu 2 1 D
+R Ma 1951 o - S lastSu 2 0 S
+R Ma 1954 1960 - Ap lastSu 2 1 D
+R Ma 1954 1960 - S lastSu 2 0 S
+R V 1946 o - Ap lastSu 2 1 D
+R V 1946 o - S lastSu 2 0 S
+R V 1953 1954 - Ap lastSu 2 1 D
+R V 1953 1959 - S lastSu 2 0 S
+R V 1955 o - May 1 0 1 D
+R V 1956 1963 - Ap lastSu 2 1 D
+R V 1960 o - O lastSu 2 0 S
+R V 1961 o - S lastSu 2 0 S
+R V 1962 1963 - O lastSu 2 0 S
+R Pe 1955 o - May 1 0 1 D
+R Pe 1955 1960 - S lastSu 2 0 S
+R Pe 1956 1963 - Ap lastSu 2 1 D
+R Pe 1961 1963 - O lastSu 2 0 S
+R Pi 1955 o - May 1 0 1 D
+R Pi 1955 1960 - S lastSu 2 0 S
+R Pi 1956 1964 - Ap lastSu 2 1 D
+R Pi 1961 1964 - O lastSu 2 0 S
+R St 1947 1961 - Ap lastSu 2 1 D
+R St 1947 1954 - S lastSu 2 0 S
+R St 1955 1956 - O lastSu 2 0 S
+R St 1957 1958 - S lastSu 2 0 S
+R St 1959 1961 - O lastSu 2 0 S
+R Pu 1946 1960 - Ap lastSu 2 1 D
+R Pu 1946 1954 - S lastSu 2 0 S
+R Pu 1955 1956 - O lastSu 2 0 S
+R Pu 1957 1960 - S lastSu 2 0 S
+R v 1921 o - May 1 2 1 D
+R v 1921 o - S 1 2 0 S
+R v 1941 o - Ap lastSu 2 1 D
+R v 1941 o - S lastSu 2 0 S
+R v 1946 o - Ap lastSu 0:1 1 D
+R v 1946 o - Jun 2 2 0 S
+R v 1950 1961 - Ap lastSu 2 1 D
+R v 1950 1955 - S lastSu 2 0 S
+R v 1956 1961 - O lastSu 2 0 S
+R Dt 1948 o - Ap lastSu 2 1 D
+R Dt 1948 o - S lastSu 2 0 S
+R Me 1946 o - Ap lastSu 2 1 D
+R Me 1946 o - S lastSu 2 0 S
+R Me 1966 o - Ap lastSu 2 1 D
+R Me 1966 o - O lastSu 2 0 S
+R C 1918 o - Ap 14 2 1 D
+R C 1918 o - O 27 2 0 S
+R C 1942 o - F 9 2 1 W
+R C 1945 o - Au 14 23u 1 P
+R C 1945 o - S 30 2 0 S
+R C 1974 1986 - Ap lastSu 2 1 D
+R C 1974 2006 - O lastSu 2 0 S
+R C 1987 2006 - Ap Su>=1 2 1 D
+R C 2007 ma - Mar Su>=8 2 1 D
+R C 2007 ma - N Su>=1 2 0 S
+R j 1917 o - Ap 8 2 1 D
+R j 1917 o - S 17 2 0 S
+R j 1919 o - May 5 23 1 D
+R j 1919 o - Au 12 23 0 S
+R j 1920 1935 - May Su>=1 23 1 D
+R j 1920 1935 - O lastSu 23 0 S
+R j 1936 1941 - May M>=9 0 1 D
+R j 1936 1941 - O M>=2 0 0 S
+R j 1946 1950 - May Su>=8 2 1 D
+R j 1946 1950 - O Su>=2 2 0 S
+R j 1951 1986 - Ap lastSu 2 1 D
+R j 1951 1959 - S lastSu 2 0 S
+R j 1960 1986 - O lastSu 2 0 S
+R j 1987 o - Ap Su>=1 0:1 1 D
+R j 1987 2006 - O lastSu 0:1 0 S
+R j 1988 o - Ap Su>=1 0:1 2 DD
+R j 1989 2006 - Ap Su>=1 0:1 1 D
+R j 2007 2011 - Mar Su>=8 0:1 1 D
+R j 2007 2010 - N Su>=1 0:1 0 S
+R H 1916 o - Ap 1 0 1 D
+R H 1916 o - O 1 0 0 S
+R H 1920 o - May 9 0 1 D
+R H 1920 o - Au 29 0 0 S
+R H 1921 o - May 6 0 1 D
+R H 1921 1922 - S 5 0 0 S
+R H 1922 o - Ap 30 0 1 D
+R H 1923 1925 - May Su>=1 0 1 D
+R H 1923 o - S 4 0 0 S
+R H 1924 o - S 15 0 0 S
+R H 1925 o - S 28 0 0 S
+R H 1926 o - May 16 0 1 D
+R H 1926 o - S 13 0 0 S
+R H 1927 o - May 1 0 1 D
+R H 1927 o - S 26 0 0 S
+R H 1928 1931 - May Su>=8 0 1 D
+R H 1928 o - S 9 0 0 S
+R H 1929 o - S 3 0 0 S
+R H 1930 o - S 15 0 0 S
+R H 1931 1932 - S M>=24 0 0 S
+R H 1932 o - May 1 0 1 D
+R H 1933 o - Ap 30 0 1 D
+R H 1933 o - O 2 0 0 S
+R H 1934 o - May 20 0 1 D
+R H 1934 o - S 16 0 0 S
+R H 1935 o - Jun 2 0 1 D
+R H 1935 o - S 30 0 0 S
+R H 1936 o - Jun 1 0 1 D
+R H 1936 o - S 14 0 0 S
+R H 1937 1938 - May Su>=1 0 1 D
+R H 1937 1941 - S M>=24 0 0 S
+R H 1939 o - May 28 0 1 D
+R H 1940 1941 - May Su>=1 0 1 D
+R H 1946 1949 - Ap lastSu 2 1 D
+R H 1946 1949 - S lastSu 2 0 S
+R H 1951 1954 - Ap lastSu 2 1 D
+R H 1951 1954 - S lastSu 2 0 S
+R H 1956 1959 - Ap lastSu 2 1 D
+R H 1956 1959 - S lastSu 2 0 S
+R H 1962 1973 - Ap lastSu 2 1 D
+R H 1962 1973 - O lastSu 2 0 S
+R o 1933 1935 - Jun Su>=8 1 1 D
+R o 1933 1935 - S Su>=8 1 0 S
+R o 1936 1938 - Jun Su>=1 1 1 D
+R o 1936 1938 - S Su>=1 1 0 S
+R o 1939 o - May 27 1 1 D
+R o 1939 1941 - S Sa>=21 1 0 S
+R o 1940 o - May 19 1 1 D
+R o 1941 o - May 4 1 1 D
+R o 1946 1972 - Ap lastSu 2 1 D
+R o 1946 1956 - S lastSu 2 0 S
+R o 1957 1972 - O lastSu 2 0 S
+R o 1993 2006 - Ap Su>=1 0:1 1 D
+R o 1993 2006 - O lastSu 0:1 0 S
+R t 1919 o - Mar 30 23:30 1 D
+R t 1919 o - O 26 0 0 S
+R t 1920 o - May 2 2 1 D
+R t 1920 o - S 26 0 0 S
+R t 1921 o - May 15 2 1 D
+R t 1921 o - S 15 2 0 S
+R t 1922 1923 - May Su>=8 2 1 D
+R t 1922 1926 - S Su>=15 2 0 S
+R t 1924 1927 - May Su>=1 2 1 D
+R t 1927 1937 - S Su>=25 2 0 S
+R t 1928 1937 - Ap Su>=25 2 1 D
+R t 1938 1940 - Ap lastSu 2 1 D
+R t 1938 1939 - S lastSu 2 0 S
+R t 1945 1948 - S lastSu 2 0 S
+R t 1946 1973 - Ap lastSu 2 1 D
+R t 1949 1950 - N lastSu 2 0 S
+R t 1951 1956 - S lastSu 2 0 S
+R t 1957 1973 - O lastSu 2 0 S
+R W 1916 o - Ap 23 0 1 D
+R W 1916 o - S 17 0 0 S
+R W 1918 o - Ap 14 2 1 D
+R W 1918 o - O 27 2 0 S
+R W 1937 o - May 16 2 1 D
+R W 1937 o - S 26 2 0 S
+R W 1942 o - F 9 2 1 W
+R W 1945 o - Au 14 23u 1 P
+R W 1945 o - S lastSu 2 0 S
+R W 1946 o - May 12 2 1 D
+R W 1946 o - O 13 2 0 S
+R W 1947 1949 - Ap lastSu 2 1 D
+R W 1947 1949 - S lastSu 2 0 S
+R W 1950 o - May 1 2 1 D
+R W 1950 o - S 30 2 0 S
+R W 1951 1960 - Ap lastSu 2 1 D
+R W 1951 1958 - S lastSu 2 0 S
+R W 1959 o - O lastSu 2 0 S
+R W 1960 o - S lastSu 2 0 S
+R W 1963 o - Ap lastSu 2 1 D
+R W 1963 o - S 22 2 0 S
+R W 1966 1986 - Ap lastSu 2s 1 D
+R W 1966 2005 - O lastSu 2s 0 S
+R W 1987 2005 - Ap Su>=1 2s 1 D
+R r 1918 o - Ap 14 2 1 D
+R r 1918 o - O 27 2 0 S
+R r 1930 1934 - May Su>=1 0 1 D
+R r 1930 1934 - O Su>=1 0 0 S
+R r 1937 1941 - Ap Su>=8 0 1 D
+R r 1937 o - O Su>=8 0 0 S
+R r 1938 o - O Su>=1 0 0 S
+R r 1939 1941 - O Su>=8 0 0 S
+R r 1942 o - F 9 2 1 W
+R r 1945 o - Au 14 23u 1 P
+R r 1945 o - S lastSu 2 0 S
+R r 1946 o - Ap Su>=8 2 1 D
+R r 1946 o - O Su>=8 2 0 S
+R r 1947 1957 - Ap lastSu 2 1 D
+R r 1947 1957 - S lastSu 2 0 S
+R r 1959 o - Ap lastSu 2 1 D
+R r 1959 o - O lastSu 2 0 S
+R Sw 1957 o - Ap lastSu 2 1 D
+R Sw 1957 o - O lastSu 2 0 S
+R Sw 1959 1961 - Ap lastSu 2 1 D
+R Sw 1959 o - O lastSu 2 0 S
+R Sw 1960 1961 - S lastSu 2 0 S
+R Ed 1918 1919 - Ap Su>=8 2 1 D
+R Ed 1918 o - O 27 2 0 S
+R Ed 1919 o - May 27 2 0 S
+R Ed 1920 1923 - Ap lastSu 2 1 D
+R Ed 1920 o - O lastSu 2 0 S
+R Ed 1921 1923 - S lastSu 2 0 S
+R Ed 1942 o - F 9 2 1 W
+R Ed 1945 o - Au 14 23u 1 P
+R Ed 1945 o - S lastSu 2 0 S
+R Ed 1947 o - Ap lastSu 2 1 D
+R Ed 1947 o - S lastSu 2 0 S
+R Ed 1972 1986 - Ap lastSu 2 1 D
+R Ed 1972 2006 - O lastSu 2 0 S
+R Va 1918 o - Ap 14 2 1 D
+R Va 1918 o - O 27 2 0 S
+R Va 1942 o - F 9 2 1 W
+R Va 1945 o - Au 14 23u 1 P
+R Va 1945 o - S 30 2 0 S
+R Va 1946 1986 - Ap lastSu 2 1 D
+R Va 1946 o - S 29 2 0 S
+R Va 1947 1961 - S lastSu 2 0 S
+R Va 1962 2006 - O lastSu 2 0 S
+R Y 1918 o - Ap 14 2 1 D
+R Y 1918 o - O 27 2 0 S
+R Y 1919 o - May 25 2 1 D
+R Y 1919 o - N 1 0 0 S
+R Y 1942 o - F 9 2 1 W
+R Y 1945 o - Au 14 23u 1 P
+R Y 1945 o - S 30 2 0 S
+R Y 1972 1986 - Ap lastSu 2 1 D
+R Y 1972 2006 - O lastSu 2 0 S
+R Y 1987 2006 - Ap Su>=1 2 1 D
+R Yu 1965 o - Ap lastSu 0 2 DD
+R Yu 1965 o - O lastSu 2 0 S
+R m 1931 o - Ap 30 0 1 D
+R m 1931 o - O 1 0 0 S
+R m 1939 o - F 5 0 1 D
+R m 1939 o - Jun 25 0 0 S
+R m 1940 o - D 9 0 1 D
+R m 1941 o - Ap 1 0 0 S
+R m 1943 o - D 16 0 1 W
+R m 1944 o - May 1 0 0 S
+R m 1950 o - F 12 0 1 D
+R m 1950 o - Jul 30 0 0 S
+R m 1996 2000 - Ap Su>=1 2 1 D
+R m 1996 2000 - O lastSu 2 0 S
+R m 2001 o - May Su>=1 2 1 D
+R m 2001 o - S lastSu 2 0 S
+R m 2002 2022 - Ap Su>=1 2 1 D
+R m 2002 2022 - O lastSu 2 0 S
+R BB 1942 o - Ap 19 5u 1 D
+R BB 1942 o - Au 31 6u 0 S
+R BB 1943 o - May 2 5u 1 D
+R BB 1943 o - S 5 6u 0 S
+R BB 1944 o - Ap 10 5u 0:30 -
+R BB 1944 o - S 10 6u 0 S
+R BB 1977 o - Jun 12 2 1 D
+R BB 1977 1978 - O Su>=1 2 0 S
+R BB 1978 1980 - Ap Su>=15 2 1 D
+R BB 1979 o - S 30 2 0 S
+R BB 1980 o - S 25 2 0 S
+R BZ 1918 1941 - O Sa>=1 24 0:30 -0530
+R BZ 1919 1942 - F Sa>=8 24 0 CST
+R BZ 1942 o - Jun 27 24 1 CWT
+R BZ 1945 o - Au 14 23u 1 CPT
+R BZ 1945 o - D 15 24 0 CST
+R BZ 1947 1967 - O Sa>=1 24 0:30 -0530
+R BZ 1948 1968 - F Sa>=8 24 0 CST
+R BZ 1973 o - D 5 0 1 CDT
+R BZ 1974 o - F 9 0 0 CST
+R BZ 1982 o - D 18 0 1 CDT
+R BZ 1983 o - F 12 0 0 CST
+R Be 1917 o - Ap 5 24 1 -
+R Be 1917 o - S 30 24 0 -
+R Be 1918 o - Ap 13 24 1 -
+R Be 1918 o - S 15 24 0 S
+R Be 1942 o - Ja 11 2 1 D
+R Be 1942 o - O 18 2 0 S
+R Be 1943 o - Mar 21 2 1 D
+R Be 1943 o - O 31 2 0 S
+R Be 1944 1945 - Mar Su>=8 2 1 D
+R Be 1944 1945 - N Su>=1 2 0 S
+R Be 1947 o - May Su>=15 2 1 D
+R Be 1947 o - S Su>=8 2 0 S
+R Be 1948 1952 - May Su>=22 2 1 D
+R Be 1948 1952 - S Su>=1 2 0 S
+R Be 1956 o - May Su>=22 2 1 D
+R Be 1956 o - O lastSu 2 0 S
+R CR 1979 1980 - F lastSu 0 1 D
+R CR 1979 1980 - Jun Su>=1 0 0 S
+R CR 1991 1992 - Ja Sa>=15 0 1 D
+R CR 1991 o - Jul 1 0 0 S
+R CR 1992 o - Mar 15 0 0 S
+R Q 1928 o - Jun 10 0 1 D
+R Q 1928 o - O 10 0 0 S
+R Q 1940 1942 - Jun Su>=1 0 1 D
+R Q 1940 1942 - S Su>=1 0 0 S
+R Q 1945 1946 - Jun Su>=1 0 1 D
+R Q 1945 1946 - S Su>=1 0 0 S
+R Q 1965 o - Jun 1 0 1 D
+R Q 1965 o - S 30 0 0 S
+R Q 1966 o - May 29 0 1 D
+R Q 1966 o - O 2 0 0 S
+R Q 1967 o - Ap 8 0 1 D
+R Q 1967 1968 - S Su>=8 0 0 S
+R Q 1968 o - Ap 14 0 1 D
+R Q 1969 1977 - Ap lastSu 0 1 D
+R Q 1969 1971 - O lastSu 0 0 S
+R Q 1972 1974 - O 8 0 0 S
+R Q 1975 1977 - O lastSu 0 0 S
+R Q 1978 o - May 7 0 1 D
+R Q 1978 1990 - O Su>=8 0 0 S
+R Q 1979 1980 - Mar Su>=15 0 1 D
+R Q 1981 1985 - May Su>=5 0 1 D
+R Q 1986 1989 - Mar Su>=14 0 1 D
+R Q 1990 1997 - Ap Su>=1 0 1 D
+R Q 1991 1995 - O Su>=8 0s 0 S
+R Q 1996 o - O 6 0s 0 S
+R Q 1997 o - O 12 0s 0 S
+R Q 1998 1999 - Mar lastSu 0s 1 D
+R Q 1998 2003 - O lastSu 0s 0 S
+R Q 2000 2003 - Ap Su>=1 0s 1 D
+R Q 2004 o - Mar lastSu 0s 1 D
+R Q 2006 2010 - O lastSu 0s 0 S
+R Q 2007 o - Mar Su>=8 0s 1 D
+R Q 2008 o - Mar Su>=15 0s 1 D
+R Q 2009 2010 - Mar Su>=8 0s 1 D
+R Q 2011 o - Mar Su>=15 0s 1 D
+R Q 2011 o - N 13 0s 0 S
+R Q 2012 o - Ap 1 0s 1 D
+R Q 2012 ma - N Su>=1 0s 0 S
+R Q 2013 ma - Mar Su>=8 0s 1 D
+R DO 1966 o - O 30 0 1 EDT
+R DO 1967 o - F 28 0 0 EST
+R DO 1969 1973 - O lastSu 0 0:30 -0430
+R DO 1970 o - F 21 0 0 EST
+R DO 1971 o - Ja 20 0 0 EST
+R DO 1972 1974 - Ja 21 0 0 EST
+R SV 1987 1988 - May Su>=1 0 1 D
+R SV 1987 1988 - S lastSu 0 0 S
+R GT 1973 o - N 25 0 1 D
+R GT 1974 o - F 24 0 0 S
+R GT 1983 o - May 21 0 1 D
+R GT 1983 o - S 22 0 0 S
+R GT 1991 o - Mar 23 0 1 D
+R GT 1991 o - S 7 0 0 S
+R GT 2006 o - Ap 30 0 1 D
+R GT 2006 o - O 1 0 0 S
+R HT 1983 o - May 8 0 1 D
+R HT 1984 1987 - Ap lastSu 0 1 D
+R HT 1983 1987 - O lastSu 0 0 S
+R HT 1988 1997 - Ap Su>=1 1s 1 D
+R HT 1988 1997 - O lastSu 1s 0 S
+R HT 2005 2006 - Ap Su>=1 0 1 D
+R HT 2005 2006 - O lastSu 0 0 S
+R HT 2012 2015 - Mar Su>=8 2 1 D
+R HT 2012 2015 - N Su>=1 2 0 S
+R HT 2017 ma - Mar Su>=8 2 1 D
+R HT 2017 ma - N Su>=1 2 0 S
+R HN 1987 1988 - May Su>=1 0 1 D
+R HN 1987 1988 - S lastSu 0 0 S
+R HN 2006 o - May Su>=1 0 1 D
+R HN 2006 o - Au M>=1 0 0 S
+R NI 1979 1980 - Mar Su>=16 0 1 D
+R NI 1979 1980 - Jun M>=23 0 0 S
+R NI 2005 o - Ap 10 0 1 D
+R NI 2005 o - O Su>=1 0 0 S
+R NI 2006 o - Ap 30 2 1 D
+R NI 2006 o - O Su>=1 1 0 S
+R A 1930 o - D 1 0 1 -
+R A 1931 o - Ap 1 0 0 -
+R A 1931 o - O 15 0 1 -
+R A 1932 1940 - Mar 1 0 0 -
+R A 1932 1939 - N 1 0 1 -
+R A 1940 o - Jul 1 0 1 -
+R A 1941 o - Jun 15 0 0 -
+R A 1941 o - O 15 0 1 -
+R A 1943 o - Au 1 0 0 -
+R A 1943 o - O 15 0 1 -
+R A 1946 o - Mar 1 0 0 -
+R A 1946 o - O 1 0 1 -
+R A 1963 o - O 1 0 0 -
+R A 1963 o - D 15 0 1 -
+R A 1964 1966 - Mar 1 0 0 -
+R A 1964 1966 - O 15 0 1 -
+R A 1967 o - Ap 2 0 0 -
+R A 1967 1968 - O Su>=1 0 1 -
+R A 1968 1969 - Ap Su>=1 0 0 -
+R A 1974 o - Ja 23 0 1 -
+R A 1974 o - May 1 0 0 -
+R A 1988 o - D 1 0 1 -
+R A 1989 1993 - Mar Su>=1 0 0 -
+R A 1989 1992 - O Su>=15 0 1 -
+R A 1999 o - O Su>=1 0 1 -
+R A 2000 o - Mar 3 0 0 -
+R A 2007 o - D 30 0 1 -
+R A 2008 2009 - Mar Su>=15 0 0 -
+R A 2008 o - O Su>=15 0 1 -
+R Sa 2008 2009 - Mar Su>=8 0 0 -
+R Sa 2007 2008 - O Su>=8 0 1 -
+R B 1931 o - O 3 11 1 -
+R B 1932 1933 - Ap 1 0 0 -
+R B 1932 o - O 3 0 1 -
+R B 1949 1952 - D 1 0 1 -
+R B 1950 o - Ap 16 1 0 -
+R B 1951 1952 - Ap 1 0 0 -
+R B 1953 o - Mar 1 0 0 -
+R B 1963 o - D 9 0 1 -
+R B 1964 o - Mar 1 0 0 -
+R B 1965 o - Ja 31 0 1 -
+R B 1965 o - Mar 31 0 0 -
+R B 1965 o - D 1 0 1 -
+R B 1966 1968 - Mar 1 0 0 -
+R B 1966 1967 - N 1 0 1 -
+R B 1985 o - N 2 0 1 -
+R B 1986 o - Mar 15 0 0 -
+R B 1986 o - O 25 0 1 -
+R B 1987 o - F 14 0 0 -
+R B 1987 o - O 25 0 1 -
+R B 1988 o - F 7 0 0 -
+R B 1988 o - O 16 0 1 -
+R B 1989 o - Ja 29 0 0 -
+R B 1989 o - O 15 0 1 -
+R B 1990 o - F 11 0 0 -
+R B 1990 o - O 21 0 1 -
+R B 1991 o - F 17 0 0 -
+R B 1991 o - O 20 0 1 -
+R B 1992 o - F 9 0 0 -
+R B 1992 o - O 25 0 1 -
+R B 1993 o - Ja 31 0 0 -
+R B 1993 1995 - O Su>=11 0 1 -
+R B 1994 1995 - F Su>=15 0 0 -
+R B 1996 o - F 11 0 0 -
+R B 1996 o - O 6 0 1 -
+R B 1997 o - F 16 0 0 -
+R B 1997 o - O 6 0 1 -
+R B 1998 o - Mar 1 0 0 -
+R B 1998 o - O 11 0 1 -
+R B 1999 o - F 21 0 0 -
+R B 1999 o - O 3 0 1 -
+R B 2000 o - F 27 0 0 -
+R B 2000 2001 - O Su>=8 0 1 -
+R B 2001 2006 - F Su>=15 0 0 -
+R B 2002 o - N 3 0 1 -
+R B 2003 o - O 19 0 1 -
+R B 2004 o - N 2 0 1 -
+R B 2005 o - O 16 0 1 -
+R B 2006 o - N 5 0 1 -
+R B 2007 o - F 25 0 0 -
+R B 2007 o - O Su>=8 0 1 -
+R B 2008 2017 - O Su>=15 0 1 -
+R B 2008 2011 - F Su>=15 0 0 -
+R B 2012 o - F Su>=22 0 0 -
+R B 2013 2014 - F Su>=15 0 0 -
+R B 2015 o - F Su>=22 0 0 -
+R B 2016 2019 - F Su>=15 0 0 -
+R B 2018 o - N Su>=1 0 1 -
+R x 1927 1931 - S 1 0 1 -
+R x 1928 1932 - Ap 1 0 0 -
+R x 1968 o - N 3 4u 1 -
+R x 1969 o - Mar 30 3u 0 -
+R x 1969 o - N 23 4u 1 -
+R x 1970 o - Mar 29 3u 0 -
+R x 1971 o - Mar 14 3u 0 -
+R x 1970 1972 - O Su>=9 4u 1 -
+R x 1972 1986 - Mar Su>=9 3u 0 -
+R x 1973 o - S 30 4u 1 -
+R x 1974 1987 - O Su>=9 4u 1 -
+R x 1987 o - Ap 12 3u 0 -
+R x 1988 1990 - Mar Su>=9 3u 0 -
+R x 1988 1989 - O Su>=9 4u 1 -
+R x 1990 o - S 16 4u 1 -
+R x 1991 1996 - Mar Su>=9 3u 0 -
+R x 1991 1997 - O Su>=9 4u 1 -
+R x 1997 o - Mar 30 3u 0 -
+R x 1998 o - Mar Su>=9 3u 0 -
+R x 1998 o - S 27 4u 1 -
+R x 1999 o - Ap 4 3u 0 -
+R x 1999 2010 - O Su>=9 4u 1 -
+R x 2000 2007 - Mar Su>=9 3u 0 -
+R x 2008 o - Mar 30 3u 0 -
+R x 2009 o - Mar Su>=9 3u 0 -
+R x 2010 o - Ap Su>=1 3u 0 -
+R x 2011 o - May Su>=2 3u 0 -
+R x 2011 o - Au Su>=16 4u 1 -
+R x 2012 2014 - Ap Su>=23 3u 0 -
+R x 2012 2014 - S Su>=2 4u 1 -
+R x 2016 2018 - May Su>=9 3u 0 -
+R x 2016 2018 - Au Su>=9 4u 1 -
+R x 2019 ma - Ap Su>=2 3u 0 -
+R x 2019 2021 - S Su>=2 4u 1 -
+R x 2022 o - S Su>=9 4u 1 -
+R x 2023 ma - S Su>=2 4u 1 -
+R CO 1992 o - May 3 0 1 -
+R CO 1993 o - F 6 24 0 -
+R EC 1992 o - N 28 0 1 -
+R EC 1993 o - F 5 0 0 -
+R FK 1937 1938 - S lastSu 0 1 -
+R FK 1938 1942 - Mar Su>=19 0 0 -
+R FK 1939 o - O 1 0 1 -
+R FK 1940 1942 - S lastSu 0 1 -
+R FK 1943 o - Ja 1 0 0 -
+R FK 1983 o - S lastSu 0 1 -
+R FK 1984 1985 - Ap lastSu 0 0 -
+R FK 1984 o - S 16 0 1 -
+R FK 1985 2000 - S Su>=9 0 1 -
+R FK 1986 2000 - Ap Su>=16 0 0 -
+R FK 2001 2010 - Ap Su>=15 2 0 -
+R FK 2001 2010 - S Su>=1 2 1 -
+R y 1975 1988 - O 1 0 1 -
+R y 1975 1978 - Mar 1 0 0 -
+R y 1979 1991 - Ap 1 0 0 -
+R y 1989 o - O 22 0 1 -
+R y 1990 o - O 1 0 1 -
+R y 1991 o - O 6 0 1 -
+R y 1992 o - Mar 1 0 0 -
+R y 1992 o - O 5 0 1 -
+R y 1993 o - Mar 31 0 0 -
+R y 1993 1995 - O 1 0 1 -
+R y 1994 1995 - F lastSu 0 0 -
+R y 1996 o - Mar 1 0 0 -
+R y 1996 2001 - O Su>=1 0 1 -
+R y 1997 o - F lastSu 0 0 -
+R y 1998 2001 - Mar Su>=1 0 0 -
+R y 2002 2004 - Ap Su>=1 0 0 -
+R y 2002 2003 - S Su>=1 0 1 -
+R y 2004 2009 - O Su>=15 0 1 -
+R y 2005 2009 - Mar Su>=8 0 0 -
+R y 2010 2024 - O Su>=1 0 1 -
+R y 2010 2012 - Ap Su>=8 0 0 -
+R y 2013 2024 - Mar Su>=22 0 0 -
+R PE 1938 o - Ja 1 0 1 -
+R PE 1938 o - Ap 1 0 0 -
+R PE 1938 1939 - S lastSu 0 1 -
+R PE 1939 1940 - Mar Su>=24 0 0 -
+R PE 1986 1987 - Ja 1 0 1 -
+R PE 1986 1987 - Ap 1 0 0 -
+R PE 1990 o - Ja 1 0 1 -
+R PE 1990 o - Ap 1 0 0 -
+R PE 1994 o - Ja 1 0 1 -
+R PE 1994 o - Ap 1 0 0 -
+R U 1923 1925 - O 1 0 0:30 -
+R U 1924 1926 - Ap 1 0 0 -
+R U 1933 1938 - O lastSu 0 0:30 -
+R U 1934 1941 - Mar lastSa 24 0 -
+R U 1939 o - O 1 0 0:30 -
+R U 1940 o - O 27 0 0:30 -
+R U 1941 o - Au 1 0 0:30 -
+R U 1942 o - D 14 0 0:30 -
+R U 1943 o - Mar 14 0 0 -
+R U 1959 o - May 24 0 0:30 -
+R U 1959 o - N 15 0 0 -
+R U 1960 o - Ja 17 0 1 -
+R U 1960 o - Mar 6 0 0 -
+R U 1965 o - Ap 4 0 1 -
+R U 1965 o - S 26 0 0 -
+R U 1968 o - May 27 0 0:30 -
+R U 1968 o - D 1 0 0 -
+R U 1970 o - Ap 25 0 1 -
+R U 1970 o - Jun 14 0 0 -
+R U 1972 o - Ap 23 0 1 -
+R U 1972 o - Jul 16 0 0 -
+R U 1974 o - Ja 13 0 1:30 -
+R U 1974 o - Mar 10 0 0:30 -
+R U 1974 o - S 1 0 0 -
+R U 1974 o - D 22 0 1 -
+R U 1975 o - Mar 30 0 0 -
+R U 1976 o - D 19 0 1 -
+R U 1977 o - Mar 6 0 0 -
+R U 1977 o - D 4 0 1 -
+R U 1978 1979 - Mar Su>=1 0 0 -
+R U 1978 o - D 17 0 1 -
+R U 1979 o - Ap 29 0 1 -
+R U 1980 o - Mar 16 0 0 -
+R U 1987 o - D 14 0 1 -
+R U 1988 o - F 28 0 0 -
+R U 1988 o - D 11 0 1 -
+R U 1989 o - Mar 5 0 0 -
+R U 1989 o - O 29 0 1 -
+R U 1990 o - F 25 0 0 -
+R U 1990 1991 - O Su>=21 0 1 -
+R U 1991 1992 - Mar Su>=1 0 0 -
+R U 1992 o - O 18 0 1 -
+R U 1993 o - F 28 0 0 -
+R U 2004 o - S 19 0 1 -
+R U 2005 o - Mar 27 2 0 -
+R U 2005 o - O 9 2 1 -
+R U 2006 2015 - Mar Su>=8 2 0 -
+R U 2006 2014 - O Su>=1 2 1 -
+Z Africa/Abidjan -0:16:8 - LMT 1912
+0 - GMT
+Z Africa/Algiers 0:12:12 - LMT 1891 Mar 16
+0:9:21 - PMT 1911 Mar 11
+0 d WE%sT 1940 F 25 2
+1 d CE%sT 1946 O 7
+0 - WET 1956 Ja 29
+1 - CET 1963 Ap 14
+0 d WE%sT 1977 O 21
+1 d CE%sT 1979 O 26
+0 d WE%sT 1981 May
+1 - CET
+Z Africa/Bissau -1:2:20 - LMT 1912 Ja 1 1u
+-1 - %z 1975
+0 - GMT
+Z Africa/Cairo 2:5:9 - LMT 1900 O
+2 K EE%sT
+Z Africa/Casablanca -0:30:20 - LMT 1913 O 26
+0 M %z 1984 Mar 16
+1 - %z 1986
+0 M %z 2018 O 28 3
+1 M %z
+Z Africa/Ceuta -0:21:16 - LMT 1901 Ja 1 0u
+0 - WET 1918 May 6 23
+0 1 WEST 1918 O 7 23
+0 - WET 1924
+0 s WE%sT 1929
+0 - WET 1967
+0 Sp WE%sT 1984 Mar 16
+1 - CET 1986
+1 E CE%sT
+Z Africa/El_Aaiun -0:52:48 - LMT 1934
+-1 - %z 1976 Ap 14
+0 M %z 2018 O 28 3
+1 M %z
+Z Africa/Johannesburg 1:52 - LMT 1892 F 8
+1:30 - SAST 1903 Mar
+2 SA SAST
+Z Africa/Juba 2:6:28 - LMT 1931
+2 SD CA%sT 2000 Ja 15 12
+3 - EAT 2021 F
+2 - CAT
+Z Africa/Khartoum 2:10:8 - LMT 1931
+2 SD CA%sT 2000 Ja 15 12
+3 - EAT 2017 N
+2 - CAT
+Z Africa/Lagos 0:13:35 - LMT 1905 Jul
+0 - GMT 1908 Jul
+0:13:35 - LMT 1914
+0:30 - %z 1919 S
+1 - WAT
+Z Africa/Maputo 2:10:18 - LMT 1909
+2 - CAT
+Z Africa/Monrovia -0:43:8 - LMT 1882
+-0:43:8 - MMT 1919 Mar
+-0:44:30 - MMT 1972 Ja 7
+0 - GMT
+Z Africa/Nairobi 2:27:16 - LMT 1908 May
+2:30 - %z 1928 Jun 30 24
+3 - EAT 1930 Ja 4 24
+2:30 - %z 1936 D 31 24
+2:45 - %z 1942 Jul 31 24
+3 - EAT
+Z Africa/Ndjamena 1:0:12 - LMT 1912
+1 - WAT 1979 O 14
+1 1 WAST 1980 Mar 8
+1 - WAT
+Z Africa/Sao_Tome 0:26:56 - LMT 1884
+-0:36:45 - LMT 1912 Ja 1 0u
+0 - GMT 2018 Ja 1 1
+1 - WAT 2019 Ja 1 2
+0 - GMT
+Z Africa/Tripoli 0:52:44 - LMT 1920
+1 L CE%sT 1959
+2 - EET 1982
+1 L CE%sT 1990 May 4
+2 - EET 1996 S 30
+1 L CE%sT 1997 O 4
+2 - EET 2012 N 10 2
+1 L CE%sT 2013 O 25 2
+2 - EET
+Z Africa/Tunis 0:40:44 - LMT 1881 May 12
+0:9:21 - PMT 1911 Mar 11
+1 n CE%sT
+Z Africa/Windhoek 1:8:24 - LMT 1892 F 8
+1:30 - %z 1903 Mar
+2 - SAST 1942 S 20 2
+2 1 SAST 1943 Mar 21 2
+2 - SAST 1990 Mar 21
+2 NA %s
+Z America/Adak 12:13:22 - LMT 1867 O 19 12:44:35
+-11:46:38 - LMT 1900 Au 20 12
+-11 - NST 1942
+-11 u N%sT 1946
+-11 - NST 1967 Ap
+-11 - BST 1969
+-11 u B%sT 1983 O 30 2
+-10 u AH%sT 1983 N 30
+-10 u H%sT
+Z America/Anchorage 14:0:24 - LMT 1867 O 19 14:31:37
+-9:59:36 - LMT 1900 Au 20 12
+-10 - AST 1942
+-10 u A%sT 1967 Ap
+-10 - AHST 1969
+-10 u AH%sT 1983 O 30 2
+-9 u Y%sT 1983 N 30
+-9 u AK%sT
+Z America/Araguaina -3:12:48 - LMT 1914
+-3 B %z 1990 S 17
+-3 - %z 1995 S 14
+-3 B %z 2003 S 24
+-3 - %z 2012 O 21
+-3 B %z 2013 S
+-3 - %z
+Z America/Argentina/Buenos_Aires -3:53:48 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 A %z
+Z America/Argentina/Catamarca -4:23:8 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1991 Mar 3
+-4 - %z 1991 O 20
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 Jun
+-4 - %z 2004 Jun 20
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/Cordoba -4:16:48 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1991 Mar 3
+-4 - %z 1991 O 20
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 A %z
+Z America/Argentina/Jujuy -4:21:12 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1990 Mar 4
+-4 - %z 1990 O 28
+-4 1 %z 1991 Mar 17
+-4 - %z 1991 O 6
+-3 1 %z 1992
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/La_Rioja -4:27:24 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1991 Mar
+-4 - %z 1991 May 7
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 Jun
+-4 - %z 2004 Jun 20
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/Mendoza -4:35:16 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1990 Mar 4
+-4 - %z 1990 O 15
+-4 1 %z 1991 Mar
+-4 - %z 1991 O 15
+-4 1 %z 1992 Mar
+-4 - %z 1992 O 18
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 May 23
+-4 - %z 2004 S 26
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/Rio_Gallegos -4:36:52 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 Jun
+-4 - %z 2004 Jun 20
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/Salta -4:21:40 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1991 Mar 3
+-4 - %z 1991 O 20
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/San_Juan -4:34:4 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1991 Mar
+-4 - %z 1991 May 7
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 May 31
+-4 - %z 2004 Jul 25
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Argentina/San_Luis -4:25:24 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1990
+-3 1 %z 1990 Mar 14
+-4 - %z 1990 O 15
+-4 1 %z 1991 Mar
+-4 - %z 1991 Jun
+-3 - %z 1999 O 3
+-4 1 %z 2000 Mar 3
+-3 - %z 2004 May 31
+-4 - %z 2004 Jul 25
+-3 A %z 2008 Ja 21
+-4 Sa %z 2009 O 11
+-3 - %z
+Z America/Argentina/Tucuman -4:20:52 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1991 Mar 3
+-4 - %z 1991 O 20
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 Jun
+-4 - %z 2004 Jun 13
+-3 A %z
+Z America/Argentina/Ushuaia -4:33:12 - LMT 1894 O 31
+-4:16:48 - CMT 1920 May
+-4 - %z 1930 D
+-4 A %z 1969 O 5
+-3 A %z 1999 O 3
+-4 A %z 2000 Mar 3
+-3 - %z 2004 May 30
+-4 - %z 2004 Jun 20
+-3 A %z 2008 O 18
+-3 - %z
+Z America/Asuncion -3:50:40 - LMT 1890
+-3:50:40 - AMT 1931 O 10
+-4 - %z 1972 O
+-3 - %z 1974 Ap
+-4 y %z 2024 O 15
+-3 - %z
+Z America/Bahia -2:34:4 - LMT 1914
+-3 B %z 2003 S 24
+-3 - %z 2011 O 16
+-3 B %z 2012 O 21
+-3 - %z
+Z America/Bahia_Banderas -7:1 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1942 Ap 24
+-7 - MST 1970
+-7 m M%sT 2010 Ap 4 2
+-6 m C%sT
+Z America/Barbados -3:58:29 - LMT 1911 Au 28
+-4 BB A%sT 1944
+-4 BB AST/-0330 1945
+-4 BB A%sT
+Z America/Belem -3:13:56 - LMT 1914
+-3 B %z 1988 S 12
+-3 - %z
+Z America/Belize -5:52:48 - LMT 1912 Ap
+-6 BZ %s
+Z America/Boa_Vista -4:2:40 - LMT 1914
+-4 B %z 1988 S 12
+-4 - %z 1999 S 30
+-4 B %z 2000 O 15
+-4 - %z
+Z America/Bogota -4:56:16 - LMT 1884 Mar 13
+-4:56:16 - BMT 1914 N 23
+-5 CO %z
+Z America/Boise -7:44:49 - LMT 1883 N 18 20u
+-8 u P%sT 1923 May 13 2
+-7 u M%sT 1974
+-7 - MST 1974 F 3 2
+-7 u M%sT
+Z America/Cambridge_Bay 0 - -00 1920
+-7 Y M%sT 1999 O 31 2
+-6 C C%sT 2000 O 29 2
+-5 - EST 2000 N 5
+-6 - CST 2001 Ap 1 3
+-7 C M%sT
+Z America/Campo_Grande -3:38:28 - LMT 1914
+-4 B %z
+Z America/Cancun -5:47:4 - LMT 1922 Ja 1 6u
+-6 - CST 1981 D 26 2
+-5 - EST 1983 Ja 4
+-6 m C%sT 1997 O 26 2
+-5 m E%sT 1998 Au 2 2
+-6 m C%sT 2015 F 1 2
+-5 - EST
+Z America/Caracas -4:27:44 - LMT 1890
+-4:27:40 - CMT 1912 F 12
+-4:30 - %z 1965
+-4 - %z 2007 D 9 3
+-4:30 - %z 2016 May 1 2:30
+-4 - %z
+Z America/Cayenne -3:29:20 - LMT 1911 Jul
+-4 - %z 1967 O
+-3 - %z
+Z America/Chicago -5:50:36 - LMT 1883 N 18 18u
+-6 u C%sT 1920
+-6 Ch C%sT 1936 Mar 1 2
+-5 - EST 1936 N 15 2
+-6 Ch C%sT 1942
+-6 u C%sT 1946
+-6 Ch C%sT 1967
+-6 u C%sT
+Z America/Chihuahua -7:4:20 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1996
+-6 m C%sT 1998
+-6 - CST 1998 Ap Su>=1 3
+-7 m M%sT 2022 O 30 2
+-6 - CST
+Z America/Ciudad_Juarez -7:5:56 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1996
+-6 m C%sT 1998
+-6 - CST 1998 Ap Su>=1 3
+-7 m M%sT 2010
+-7 u M%sT 2022 O 30 2
+-6 - CST 2022 N 30
+-7 u M%sT
+Z America/Costa_Rica -5:36:13 - LMT 1890
+-5:36:13 - SJMT 1921 Ja 15
+-6 CR C%sT
+Z America/Coyhaique -4:48:16 - LMT 1890
+-4:42:45 - SMT 1910 Ja 10
+-5 - %z 1916 Jul
+-4:42:45 - SMT 1918 S 10
+-4 - %z 1919 Jul
+-4:42:45 - SMT 1927 S
+-5 x %z 1932 S
+-4 - %z 1942 Jun
+-5 - %z 1942 Au
+-4 - %z 1946 Au 28 24
+-5 1 %z 1947 Mar 31 24
+-5 - %z 1947 May 21 23
+-4 x %z 2025 Mar 20
+-3 - %z
+Z America/Cuiaba -3:44:20 - LMT 1914
+-4 B %z 2003 S 24
+-4 - %z 2004 O
+-4 B %z
+Z America/Danmarkshavn -1:14:40 - LMT 1916 Jul 28
+-3 - %z 1980 Ap 6 2
+-3 E %z 1996
+0 - GMT
+Z America/Dawson -9:17:40 - LMT 1900 Au 20
+-9 Y Y%sT 1965
+-9 Yu Y%sT 1973 O 28
+-8 - PST 1980
+-8 C P%sT 2020 N
+-7 - MST
+Z America/Dawson_Creek -8:0:56 - LMT 1884
+-8 C P%sT 1947
+-8 Va P%sT 1972 Au 30 2
+-7 - MST
+Z America/Denver -6:59:56 - LMT 1883 N 18 19u
+-7 u M%sT 1920
+-7 De M%sT 1942
+-7 u M%sT 1946
+-7 De M%sT 1967
+-7 u M%sT
+Z America/Detroit -5:32:11 - LMT 1905
+-6 - CST 1915 May 15 2
+-5 - EST 1942
+-5 u E%sT 1946
+-5 Dt E%sT 1967 Jun 14 0:1
+-5 u E%sT 1969
+-5 - EST 1973
+-5 u E%sT 1975
+-5 - EST 1975 Ap 27 2
+-5 u E%sT
+Z America/Edmonton -7:33:52 - LMT 1906 S
+-7 Ed M%sT 1987
+-7 C M%sT
+Z America/Eirunepe -4:39:28 - LMT 1914
+-5 B %z 1988 S 12
+-5 - %z 1993 S 28
+-5 B %z 1994 S 22
+-5 - %z 2008 Jun 24
+-4 - %z 2013 N 10
+-5 - %z
+Z America/El_Salvador -5:56:48 - LMT 1921
+-6 SV C%sT
+Z America/Fort_Nelson -8:10:47 - LMT 1884
+-8 Va P%sT 1946
+-8 - PST 1947
+-8 Va P%sT 1987
+-8 C P%sT 2015 Mar 8 2
+-7 - MST
+Z America/Fortaleza -2:34 - LMT 1914
+-3 B %z 1990 S 17
+-3 - %z 1999 S 30
+-3 B %z 2000 O 22
+-3 - %z 2001 S 13
+-3 B %z 2002 O
+-3 - %z
+Z America/Glace_Bay -3:59:48 - LMT 1902 Jun 15
+-4 C A%sT 1953
+-4 H A%sT 1954
+-4 - AST 1972
+-4 H A%sT 1974
+-4 C A%sT
+Z America/Goose_Bay -4:1:40 - LMT 1884
+-3:30:52 - NST 1918
+-3:30:52 C N%sT 1919
+-3:30:52 - NST 1935 Mar 30
+-3:30 - NST 1936
+-3:30 j N%sT 1942 May 11
+-3:30 C N%sT 1946
+-3:30 j N%sT 1966 Mar 15 2
+-4 j A%sT 2011 N
+-4 C A%sT
+Z America/Grand_Turk -4:44:32 - LMT 1890
+-5:7:10 - KMT 1912 F
+-5 - EST 1979
+-5 u E%sT 2015 Mar 8 2
+-4 - AST 2018 Mar 11 3
+-5 u E%sT
+Z America/Guatemala -6:2:4 - LMT 1918 O 5
+-6 GT C%sT
+Z America/Guayaquil -5:19:20 - LMT 1890
+-5:14 - QMT 1931
+-5 EC %z
+Z America/Guyana -3:52:39 - LMT 1911 Au
+-4 - %z 1915 Mar
+-3:45 - %z 1975 Au
+-3 - %z 1992 Mar 29 1
+-4 - %z
+Z America/Halifax -4:14:24 - LMT 1902 Jun 15
+-4 H A%sT 1918
+-4 C A%sT 1919
+-4 H A%sT 1942 F 9 2s
+-4 C A%sT 1946
+-4 H A%sT 1974
+-4 C A%sT
+Z America/Havana -5:29:28 - LMT 1890
+-5:29:36 - HMT 1925 Jul 19 12
+-5 Q C%sT
+Z America/Hermosillo -7:23:52 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1942 Ap 24
+-7 - MST 1996
+-7 m M%sT 1999
+-7 - MST
+Z America/Indiana/Indianapolis -5:44:38 - LMT 1883 N 18 18u
+-6 u C%sT 1920
+-6 In C%sT 1942
+-6 u C%sT 1946
+-6 In C%sT 1955 Ap 24 2
+-5 - EST 1957 S 29 2
+-6 - CST 1958 Ap 27 2
+-5 - EST 1969
+-5 u E%sT 1971
+-5 - EST 2006
+-5 u E%sT
+Z America/Indiana/Knox -5:46:30 - LMT 1883 N 18 18u
+-6 u C%sT 1947
+-6 St C%sT 1962 Ap 29 2
+-5 - EST 1963 O 27 2
+-6 u C%sT 1991 O 27 2
+-5 - EST 2006 Ap 2 2
+-6 u C%sT
+Z America/Indiana/Marengo -5:45:23 - LMT 1883 N 18 18u
+-6 u C%sT 1951
+-6 Ma C%sT 1961 Ap 30 2
+-5 - EST 1969
+-5 u E%sT 1974 Ja 6 2
+-6 1 CDT 1974 O 27 2
+-5 u E%sT 1976
+-5 - EST 2006
+-5 u E%sT
+Z America/Indiana/Petersburg -5:49:7 - LMT 1883 N 18 18u
+-6 u C%sT 1955
+-6 Pi C%sT 1965 Ap 25 2
+-5 - EST 1966 O 30 2
+-6 u C%sT 1977 O 30 2
+-5 - EST 2006 Ap 2 2
+-6 u C%sT 2007 N 4 2
+-5 u E%sT
+Z America/Indiana/Tell_City -5:47:3 - LMT 1883 N 18 18u
+-6 u C%sT 1946
+-6 Pe C%sT 1964 Ap 26 2
+-5 - EST 1967 O 29 2
+-6 u C%sT 1969 Ap 27 2
+-5 u E%sT 1971
+-5 - EST 2006 Ap 2 2
+-6 u C%sT
+Z America/Indiana/Vevay -5:40:16 - LMT 1883 N 18 18u
+-6 u C%sT 1954 Ap 25 2
+-5 - EST 1969
+-5 u E%sT 1973
+-5 - EST 2006
+-5 u E%sT
+Z America/Indiana/Vincennes -5:50:7 - LMT 1883 N 18 18u
+-6 u C%sT 1946
+-6 V C%sT 1964 Ap 26 2
+-5 - EST 1969
+-5 u E%sT 1971
+-5 - EST 2006 Ap 2 2
+-6 u C%sT 2007 N 4 2
+-5 u E%sT
+Z America/Indiana/Winamac -5:46:25 - LMT 1883 N 18 18u
+-6 u C%sT 1946
+-6 Pu C%sT 1961 Ap 30 2
+-5 - EST 1969
+-5 u E%sT 1971
+-5 - EST 2006 Ap 2 2
+-6 u C%sT 2007 Mar 11 2
+-5 u E%sT
+Z America/Inuvik 0 - -00 1953
+-8 Y P%sT 1979 Ap lastSu 2
+-7 Y M%sT 1980
+-7 C M%sT
+Z America/Iqaluit 0 - -00 1942 Au
+-5 Y E%sT 1999 O 31 2
+-6 C C%sT 2000 O 29 2
+-5 C E%sT
+Z America/Jamaica -5:7:10 - LMT 1890
+-5:7:10 - KMT 1912 F
+-5 - EST 1974
+-5 u E%sT 1984
+-5 - EST
+Z America/Juneau 15:2:19 - LMT 1867 O 19 15:33:32
+-8:57:41 - LMT 1900 Au 20 12
+-8 - PST 1942
+-8 u P%sT 1946
+-8 - PST 1969
+-8 u P%sT 1980 Ap 27 2
+-9 u Y%sT 1980 O 26 2
+-8 u P%sT 1983 O 30 2
+-9 u Y%sT 1983 N 30
+-9 u AK%sT
+Z America/Kentucky/Louisville -5:43:2 - LMT 1883 N 18 18u
+-6 u C%sT 1921
+-6 v C%sT 1942
+-6 u C%sT 1946
+-6 v C%sT 1961 Jul 23 2
+-5 - EST 1968
+-5 u E%sT 1974 Ja 6 2
+-6 1 CDT 1974 O 27 2
+-5 u E%sT
+Z America/Kentucky/Monticello -5:39:24 - LMT 1883 N 18 18u
+-6 u C%sT 1946
+-6 - CST 1968
+-6 u C%sT 2000 O 29 2
+-5 u E%sT
+Z America/La_Paz -4:32:36 - LMT 1890
+-4:32:36 - CMT 1931 O 15
+-4:32:36 1 BST 1932 Mar 21
+-4 - %z
+Z America/Lima -5:8:12 - LMT 1890
+-5:8:36 - LMT 1908 Jul 28
+-5 PE %z
+Z America/Los_Angeles -7:52:58 - LMT 1883 N 18 20u
+-8 u P%sT 1946
+-8 CA P%sT 1967
+-8 u P%sT
+Z America/Maceio -2:22:52 - LMT 1914
+-3 B %z 1990 S 17
+-3 - %z 1995 O 13
+-3 B %z 1996 S 4
+-3 - %z 1999 S 30
+-3 B %z 2000 O 22
+-3 - %z 2001 S 13
+-3 B %z 2002 O
+-3 - %z
+Z America/Managua -5:45:8 - LMT 1890
+-5:45:12 - MMT 1934 Jun 23
+-6 - CST 1973 May
+-5 - EST 1975 F 16
+-6 NI C%sT 1992 Ja 1 4
+-5 - EST 1992 S 24
+-6 - CST 1993
+-5 - EST 1997
+-6 NI C%sT
+Z America/Manaus -4:0:4 - LMT 1914
+-4 B %z 1988 S 12
+-4 - %z 1993 S 28
+-4 B %z 1994 S 22
+-4 - %z
+Z America/Martinique -4:4:20 - LMT 1890
+-4:4:20 - FFMT 1911 May
+-4 - AST 1980 Ap 6
+-4 1 ADT 1980 S 28
+-4 - AST
+Z America/Matamoros -6:30 - LMT 1922 Ja 1 6u
+-6 - CST 1988
+-6 u C%sT 1989
+-6 m C%sT 2010
+-6 u C%sT
+Z America/Mazatlan -7:5:40 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1942 Ap 24
+-7 - MST 1970
+-7 m M%sT
+Z America/Menominee -5:50:27 - LMT 1885 S 18 12
+-6 u C%sT 1946
+-6 Me C%sT 1969 Ap 27 2
+-5 - EST 1973 Ap 29 2
+-6 u C%sT
+Z America/Merida -5:58:28 - LMT 1922 Ja 1 6u
+-6 - CST 1981 D 26 2
+-5 - EST 1982 N 2 2
+-6 m C%sT
+Z America/Metlakatla 15:13:42 - LMT 1867 O 19 15:44:55
+-8:46:18 - LMT 1900 Au 20 12
+-8 - PST 1942
+-8 u P%sT 1946
+-8 - PST 1969
+-8 u P%sT 1983 O 30 2
+-8 - PST 2015 N 1 2
+-9 u AK%sT 2018 N 4 2
+-8 - PST 2019 Ja 20 2
+-9 u AK%sT
+Z America/Mexico_City -6:36:36 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 m C%sT 2001 S 30 2
+-6 - CST 2002 F 20
+-6 m C%sT
+Z America/Miquelon -3:44:40 - LMT 1911 Jun 15
+-4 - AST 1980 May
+-3 - %z 1987
+-3 C %z
+Z America/Moncton -4:19:8 - LMT 1883 D 9
+-5 - EST 1902 Jun 15
+-4 C A%sT 1933
+-4 o A%sT 1942
+-4 C A%sT 1946
+-4 o A%sT 1973
+-4 C A%sT 1993
+-4 o A%sT 2007
+-4 C A%sT
+Z America/Monterrey -6:41:16 - LMT 1922 Ja 1 6u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1988
+-6 u C%sT 1989
+-6 m C%sT
+Z America/Montevideo -3:44:51 - LMT 1908 Jun 10
+-3:44:51 - MMT 1920 May
+-4 - %z 1923 O
+-3:30 U %z 1942 D 14
+-3 U %z 1960
+-3 U %z 1968
+-3 U %z 1970
+-3 U %z 1974
+-3 U %z 1974 Mar 10
+-3 U %z 1974 D 22
+-3 U %z
+Z America/New_York -4:56:2 - LMT 1883 N 18 17u
+-5 u E%sT 1920
+-5 NY E%sT 1942
+-5 u E%sT 1946
+-5 NY E%sT 1967
+-5 u E%sT
+Z America/Nome 12:58:22 - LMT 1867 O 19 13:29:35
+-11:1:38 - LMT 1900 Au 20 12
+-11 - NST 1942
+-11 u N%sT 1946
+-11 - NST 1967 Ap
+-11 - BST 1969
+-11 u B%sT 1983 O 30 2
+-9 u Y%sT 1983 N 30
+-9 u AK%sT
+Z America/Noronha -2:9:40 - LMT 1914
+-2 B %z 1990 S 17
+-2 - %z 1999 S 30
+-2 B %z 2000 O 15
+-2 - %z 2001 S 13
+-2 B %z 2002 O
+-2 - %z
+Z America/North_Dakota/Beulah -6:47:7 - LMT 1883 N 18 19u
+-7 u M%sT 2010 N 7 2
+-6 u C%sT
+Z America/North_Dakota/Center -6:45:12 - LMT 1883 N 18 19u
+-7 u M%sT 1992 O 25 2
+-6 u C%sT
+Z America/North_Dakota/New_Salem -6:45:39 - LMT 1883 N 18 19u
+-7 u M%sT 2003 O 26 2
+-6 u C%sT
+Z America/Nuuk -3:26:56 - LMT 1916 Jul 28
+-3 - %z 1980 Ap 6 2
+-3 E %z 2023 Mar 26 1u
+-2 - %z 2023 O 29 1u
+-2 E %z
+Z America/Ojinaga -6:57:40 - LMT 1922 Ja 1 7u
+-7 - MST 1927 Jun 10
+-6 - CST 1930 N 15
+-7 m M%sT 1932 Ap
+-6 - CST 1996
+-6 m C%sT 1998
+-6 - CST 1998 Ap Su>=1 3
+-7 m M%sT 2010
+-7 u M%sT 2022 O 30 2
+-6 - CST 2022 N 30
+-6 u C%sT
+Z America/Panama -5:18:8 - LMT 1890
+-5:19:36 - CMT 1908 Ap 22
+-5 - EST
+Z America/Paramaribo -3:40:40 - LMT 1911
+-3:40:52 - PMT 1935
+-3:40:36 - PMT 1945 O
+-3:30 - %z 1984 O
+-3 - %z
+Z America/Phoenix -7:28:18 - LMT 1883 N 18 19u
+-7 u M%sT 1944 Ja 1 0:1
+-7 - MST 1944 Ap 1 0:1
+-7 u M%sT 1944 O 1 0:1
+-7 - MST 1967
+-7 u M%sT 1968 Mar 21
+-7 - MST
+Z America/Port-au-Prince -4:49:20 - LMT 1890
+-4:49 - PPMT 1917 Ja 24 12
+-5 HT E%sT
+Z America/Porto_Velho -4:15:36 - LMT 1914
+-4 B %z 1988 S 12
+-4 - %z
+Z America/Puerto_Rico -4:24:25 - LMT 1899 Mar 28 12
+-4 - AST 1942 May 3
+-4 u A%sT 1946
+-4 - AST
+Z America/Punta_Arenas -4:43:40 - LMT 1890
+-4:42:45 - SMT 1910 Ja 10
+-5 - %z 1916 Jul
+-4:42:45 - SMT 1918 S 10
+-4 - %z 1919 Jul
+-4:42:45 - SMT 1927 S
+-5 x %z 1932 S
+-4 - %z 1942 Jun
+-5 - %z 1942 Au
+-4 - %z 1946 Au 28 24
+-5 1 %z 1947 Mar 31 24
+-5 - %z 1947 May 21 23
+-4 x %z 2016 D 4
+-3 - %z
+Z America/Rankin_Inlet 0 - -00 1957
+-6 Y C%sT 2000 O 29 2
+-5 - EST 2001 Ap 1 3
+-6 C C%sT
+Z America/Recife -2:19:36 - LMT 1914
+-3 B %z 1990 S 17
+-3 - %z 1999 S 30
+-3 B %z 2000 O 15
+-3 - %z 2001 S 13
+-3 B %z 2002 O
+-3 - %z
+Z America/Regina -6:58:36 - LMT 1905 S
+-7 r M%sT 1960 Ap lastSu 2
+-6 - CST
+Z America/Resolute 0 - -00 1947 Au 31
+-6 Y C%sT 2000 O 29 2
+-5 - EST 2001 Ap 1 3
+-6 C C%sT 2006 O 29 2
+-5 - EST 2007 Mar 11 3
+-6 C C%sT
+Z America/Rio_Branco -4:31:12 - LMT 1914
+-5 B %z 1988 S 12
+-5 - %z 2008 Jun 24
+-4 - %z 2013 N 10
+-5 - %z
+Z America/Santarem -3:38:48 - LMT 1914
+-4 B %z 1988 S 12
+-4 - %z 2008 Jun 24
+-3 - %z
+Z America/Santiago -4:42:45 - LMT 1890
+-4:42:45 - SMT 1910 Ja 10
+-5 - %z 1916 Jul
+-4:42:45 - SMT 1918 S 10
+-4 - %z 1919 Jul
+-4:42:45 - SMT 1927 S
+-5 x %z 1932 S
+-4 - %z 1942 Jun
+-5 - %z 1942 Au
+-4 - %z 1946 Jul 14 24
+-4 1 %z 1946 Au 28 24
+-5 1 %z 1947 Mar 31 24
+-5 - %z 1947 May 21 23
+-4 x %z
+Z America/Santo_Domingo -4:39:36 - LMT 1890
+-4:40 - SDMT 1933 Ap 1 12
+-5 DO %s 1974 O 27
+-4 - AST 2000 O 29 2
+-5 u E%sT 2000 D 3 1
+-4 - AST
+Z America/Sao_Paulo -3:6:28 - LMT 1914
+-3 B %z 1963 O 23
+-3 1 %z 1964
+-3 B %z
+Z America/Scoresbysund -1:27:52 - LMT 1916 Jul 28
+-2 - %z 1980 Ap 6 2
+-2 c %z 1981 Mar 29
+-1 E %z 2024 Mar 31
+-2 E %z
+Z America/Sitka 14:58:47 - LMT 1867 O 19 15:30
+-9:1:13 - LMT 1900 Au 20 12
+-8 - PST 1942
+-8 u P%sT 1946
+-8 - PST 1969
+-8 u P%sT 1983 O 30 2
+-9 u Y%sT 1983 N 30
+-9 u AK%sT
+Z America/St_Johns -3:30:52 - LMT 1884
+-3:30:52 j N%sT 1918
+-3:30:52 C N%sT 1919
+-3:30:52 j N%sT 1935 Mar 30
+-3:30 j N%sT 1942 May 11
+-3:30 C N%sT 1946
+-3:30 j N%sT 2011 N
+-3:30 C N%sT
+Z America/Swift_Current -7:11:20 - LMT 1905 S
+-7 C M%sT 1946 Ap lastSu 2
+-7 r M%sT 1950
+-7 Sw M%sT 1972 Ap lastSu 2
+-6 - CST
+Z America/Tegucigalpa -5:48:52 - LMT 1921 Ap
+-6 HN C%sT
+Z America/Thule -4:35:8 - LMT 1916 Jul 28
+-4 Th A%sT
+Z America/Tijuana -7:48:4 - LMT 1922 Ja 1 7u
+-7 - MST 1924
+-8 - PST 1927 Jun 10
+-7 - MST 1930 N 15
+-8 - PST 1931 Ap
+-8 1 PDT 1931 S 30
+-8 - PST 1942 Ap 24
+-8 1 PWT 1945 Au 14 23u
+-8 1 PPT 1945 N 15
+-8 - PST 1948 Ap 5
+-8 1 PDT 1949 Ja 14
+-8 - PST 1950 May
+-8 1 PDT 1950 S 24
+-8 - PST 1951 Ap 29 2
+-8 1 PDT 1951 S 30 2
+-8 - PST 1952 Ap 27 2
+-8 1 PDT 1952 S 28 2
+-8 - PST 1954
+-8 CA P%sT 1961
+-8 - PST 1976
+-8 u P%sT 1996
+-8 m P%sT 2001
+-8 u P%sT 2002 F 20
+-8 m P%sT 2010
+-8 u P%sT
+Z America/Toronto -5:17:32 - LMT 1895
+-5 C E%sT 1919
+-5 t E%sT 1942 F 9 2s
+-5 C E%sT 1946
+-5 t E%sT 1974
+-5 C E%sT
+Z America/Vancouver -8:12:28 - LMT 1884
+-8 Va P%sT 1987
+-8 C P%sT
+Z America/Whitehorse -9:0:12 - LMT 1900 Au 20
+-9 Y Y%sT 1965
+-9 Yu Y%sT 1966 F 27
+-8 - PST 1980
+-8 C P%sT 2020 N
+-7 - MST
+Z America/Winnipeg -6:28:36 - LMT 1887 Jul 16
+-6 W C%sT 2006
+-6 C C%sT
+Z America/Yakutat 14:41:5 - LMT 1867 O 19 15:12:18
+-9:18:55 - LMT 1900 Au 20 12
+-9 - YST 1942
+-9 u Y%sT 1946
+-9 - YST 1969
+-9 u Y%sT 1983 N 30
+-9 u AK%sT
+Z Antarctica/Casey 0 - -00 1969
+8 - %z 2009 O 18 2
+11 - %z 2010 Mar 5 2
+8 - %z 2011 O 28 2
+11 - %z 2012 F 21 17u
+8 - %z 2016 O 22
+11 - %z 2018 Mar 11 4
+8 - %z 2018 O 7 4
+11 - %z 2019 Mar 17 3
+8 - %z 2019 O 4 3
+11 - %z 2020 Mar 8 3
+8 - %z 2020 O 4 0:1
+11 - %z 2021 Mar 14
+8 - %z 2021 O 3 0:1
+11 - %z 2022 Mar 13
+8 - %z 2022 O 2 0:1
+11 - %z 2023 Mar 9 3
+8 - %z
+Z Antarctica/Davis 0 - -00 1957 Ja 13
+7 - %z 1964 N
+0 - -00 1969 F
+7 - %z 2009 O 18 2
+5 - %z 2010 Mar 10 20u
+7 - %z 2011 O 28 2
+5 - %z 2012 F 21 20u
+7 - %z
+Z Antarctica/Macquarie 0 - -00 1899 N
+10 - AEST 1916 O 1 2
+10 1 AEDT 1917 F
+10 AU AE%sT 1919 Ap 1 0s
+0 - -00 1948 Mar 25
+10 AU AE%sT 1967
+10 AT AE%sT 2010
+10 1 AEDT 2011
+10 AT AE%sT
+Z Antarctica/Mawson 0 - -00 1954 F 13
+6 - %z 2009 O 18 2
+5 - %z
+Z Antarctica/Palmer 0 - -00 1965
+-4 A %z 1969 O 5
+-3 A %z 1982 May
+-4 x %z 2016 D 4
+-3 - %z
+Z Antarctica/Rothera 0 - -00 1976 D
+-3 - %z
+Z Antarctica/Troll 0 - -00 2005 F 12
+0 Tr %s
+Z Antarctica/Vostok 0 - -00 1957 D 16
+7 - %z 1994 F
+0 - -00 1994 N
+7 - %z 2023 D 18 2
+5 - %z
+Z Asia/Almaty 5:7:48 - LMT 1924 May 2
+5 - %z 1930 Jun 21
+6 R %z 1991 Mar 31 2s
+5 R %z 1992 Ja 19 2s
+6 R %z 2004 O 31 2s
+6 - %z 2024 Mar
+5 - %z
+Z Asia/Amman 2:23:44 - LMT 1931
+2 J EE%sT 2022 O 28 0s
+3 - %z
+Z Asia/Anadyr 11:49:56 - LMT 1924 May 2
+12 - %z 1930 Jun 21
+13 R %z 1982 Ap 1 0s
+12 R %z 1991 Mar 31 2s
+11 R %z 1992 Ja 19 2s
+12 R %z 2010 Mar 28 2s
+11 R %z 2011 Mar 27 2s
+12 - %z
+Z Asia/Aqtau 3:21:4 - LMT 1924 May 2
+4 - %z 1930 Jun 21
+5 - %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1991 Mar 31 2s
+4 R %z 1992 Ja 19 2s
+5 R %z 1994 S 25 2s
+4 R %z 2004 O 31 2s
+5 - %z
+Z Asia/Aqtobe 3:48:40 - LMT 1924 May 2
+4 - %z 1930 Jun 21
+5 - %z 1981 Ap
+5 1 %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1991 Mar 31 2s
+4 R %z 1992 Ja 19 2s
+5 R %z 2004 O 31 2s
+5 - %z
+Z Asia/Ashgabat 3:53:32 - LMT 1924 May 2
+4 - %z 1930 Jun 21
+5 R %z 1991 Mar 31 2
+4 R %z 1992 Ja 19 2
+5 - %z
+Z Asia/Atyrau 3:27:44 - LMT 1924 May 2
+3 - %z 1930 Jun 21
+5 - %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1991 Mar 31 2s
+4 R %z 1992 Ja 19 2s
+5 R %z 1999 Mar 28 2s
+4 R %z 2004 O 31 2s
+5 - %z
+Z Asia/Baghdad 2:57:40 - LMT 1890
+2:57:36 - BMT 1918
+3 - %z 1982 May
+3 IQ %z
+Z Asia/Baku 3:19:24 - LMT 1924 May 2
+3 - %z 1957 Mar
+4 R %z 1991 Mar 31 2s
+3 R %z 1992 S lastSu 2s
+4 - %z 1996
+4 E %z 1997
+4 AZ %z
+Z Asia/Bangkok 6:42:4 - LMT 1880
+6:42:4 - BMT 1920 Ap
+7 - %z
+Z Asia/Barnaul 5:35 - LMT 1919 D 10
+6 - %z 1930 Jun 21
+7 R %z 1991 Mar 31 2s
+6 R %z 1992 Ja 19 2s
+7 R %z 1995 May 28
+6 R %z 2011 Mar 27 2s
+7 - %z 2014 O 26 2s
+6 - %z 2016 Mar 27 2s
+7 - %z
+Z Asia/Beirut 2:22 - LMT 1880
+2 l EE%sT
+Z Asia/Bishkek 4:58:24 - LMT 1924 May 2
+5 - %z 1930 Jun 21
+6 R %z 1991 Mar 31 2s
+5 R %z 1991 Au 31 2
+5 KG %z 2005 Au 12
+6 - %z
+Z Asia/Chita 7:33:52 - LMT 1919 D 15
+8 - %z 1930 Jun 21
+9 R %z 1991 Mar 31 2s
+8 R %z 1992 Ja 19 2s
+9 R %z 2011 Mar 27 2s
+10 - %z 2014 O 26 2s
+8 - %z 2016 Mar 27 2
+9 - %z
+Z Asia/Colombo 5:19:24 - LMT 1880
+5:19:32 - MMT 1906
+5:30 - %z 1942 Ja 5
+5:30 0:30 %z 1942 S
+5:30 1 %z 1945 O 16 2
+5:30 - %z 1996 May 25
+6:30 - %z 1996 O 26 0:30
+6 - %z 2006 Ap 15 0:30
+5:30 - %z
+Z Asia/Damascus 2:25:12 - LMT 1920
+2 S EE%sT 2022 O 28
+3 - %z
+Z Asia/Dhaka 6:1:40 - LMT 1890
+5:53:20 - HMT 1941 O
+6:30 - %z 1942 May 15
+5:30 - %z 1942 S
+6:30 - %z 1951 S 30
+6 - %z 2009
+6 BD %z
+Z Asia/Dili 8:22:20 - LMT 1911 D 31 16u
+8 - %z 1942 F 21 23
+9 - %z 1976 May 3
+8 - %z 2000 S 17
+9 - %z
+Z Asia/Dubai 3:41:12 - LMT 1920
+4 - %z
+Z Asia/Dushanbe 4:35:12 - LMT 1924 May 2
+5 - %z 1930 Jun 21
+6 R %z 1991 Mar 31 2s
+5 1 %z 1991 S 9 2s
+5 - %z
+Z Asia/Famagusta 2:15:48 - LMT 1921 N 14
+2 CY EE%sT 1998 S
+2 E EE%sT 2016 S 8
+3 - %z 2017 O 29 1u
+2 E EE%sT
+Z Asia/Gaza 2:17:52 - LMT 1900 O
+2 Z EET/EEST 1948 May 15
+2 K EE%sT 1967 Jun 5
+2 Z I%sT 1996
+2 J EE%sT 1999
+2 P EE%sT 2008 Au 29
+2 - EET 2008 S
+2 P EE%sT 2010
+2 - EET 2010 Mar 27 0:1
+2 P EE%sT 2011 Au
+2 - EET 2012
+2 P EE%sT
+Z Asia/Hebron 2:20:23 - LMT 1900 O
+2 Z EET/EEST 1948 May 15
+2 K EE%sT 1967 Jun 5
+2 Z I%sT 1996
+2 J EE%sT 1999
+2 P EE%sT
+Z Asia/Ho_Chi_Minh 7:6:30 - LMT 1906 Jul
+7:6:30 - PLMT 1911 May
+7 - %z 1942 D 31 23
+8 - %z 1945 Mar 14 23
+9 - %z 1945 S 1 24
+7 - %z 1947 Ap
+8 - %z 1955 Jul 1 1
+7 - %z 1959 D 31 23
+8 - %z 1975 Jun 13
+7 - %z
+Z Asia/Hong_Kong 7:36:42 - LMT 1904 O 29 17u
+8 - HKT 1941 Jun 15 3
+8 1 HKST 1941 O 1 4
+8 0:30 HKWT 1941 D 25
+9 - JST 1945 N 18 2
+8 HK HK%sT
+Z Asia/Hovd 6:6:36 - LMT 1905 Au
+6 - %z 1978
+7 X %z
+Z Asia/Irkutsk 6:57:5 - LMT 1880
+6:57:5 - IMT 1920 Ja 25
+7 - %z 1930 Jun 21
+8 R %z 1991 Mar 31 2s
+7 R %z 1992 Ja 19 2s
+8 R %z 2011 Mar 27 2s
+9 - %z 2014 O 26 2s
+8 - %z
+Z Asia/Jakarta 7:7:12 - LMT 1867 Au 10
+7:7:12 - BMT 1923 D 31 16:40u
+7:20 - %z 1932 N
+7:30 - %z 1942 Mar 23
+9 - %z 1945 S 23
+7:30 - %z 1948 May
+8 - %z 1950 May
+7:30 - %z 1964
+7 - WIB
+Z Asia/Jayapura 9:22:48 - LMT 1932 N
+9 - %z 1944 S
+9:30 - %z 1964
+9 - WIT
+Z Asia/Jerusalem 2:20:54 - LMT 1880
+2:20:40 - JMT 1918
+2 Z I%sT
+Z Asia/Kabul 4:36:48 - LMT 1890
+4 - %z 1945
+4:30 - %z
+Z Asia/Kamchatka 10:34:36 - LMT 1922 N 10
+11 - %z 1930 Jun 21
+12 R %z 1991 Mar 31 2s
+11 R %z 1992 Ja 19 2s
+12 R %z 2010 Mar 28 2s
+11 R %z 2011 Mar 27 2s
+12 - %z
+Z Asia/Karachi 4:28:12 - LMT 1907
+5:30 - %z 1942 S
+5:30 1 %z 1945 O 15
+5:30 - %z 1951 S 30
+5 - %z 1971 Mar 26
+5 PK PK%sT
+Z Asia/Kathmandu 5:41:16 - LMT 1920
+5:30 - %z 1986
+5:45 - %z
+Z Asia/Khandyga 9:2:13 - LMT 1919 D 15
+8 - %z 1930 Jun 21
+9 R %z 1991 Mar 31 2s
+8 R %z 1992 Ja 19 2s
+9 R %z 2004
+10 R %z 2011 Mar 27 2s
+11 - %z 2011 S 13 0s
+10 - %z 2014 O 26 2s
+9 - %z
+Z Asia/Kolkata 5:53:28 - LMT 1854 Jun 28
+5:53:20 - HMT 1870
+5:21:10 - MMT 1906
+5:30 - IST 1941 O
+5:30 1 %z 1942 May 15
+5:30 - IST 1942 S
+5:30 1 %z 1945 O 15
+5:30 - IST
+Z Asia/Krasnoyarsk 6:11:26 - LMT 1920 Ja 6
+6 - %z 1930 Jun 21
+7 R %z 1991 Mar 31 2s
+6 R %z 1992 Ja 19 2s
+7 R %z 2011 Mar 27 2s
+8 - %z 2014 O 26 2s
+7 - %z
+Z Asia/Kuching 7:21:20 - LMT 1926 Mar
+7:30 - %z 1933
+8 NB %z 1942 F 16
+9 - %z 1945 S 12
+8 - %z
+Z Asia/Macau 7:34:10 - LMT 1904 O 30
+8 - CST 1941 D 21 23
+9 _ %z 1945 S 30 24
+8 _ C%sT
+Z Asia/Magadan 10:3:12 - LMT 1924 May 2
+10 - %z 1930 Jun 21
+11 R %z 1991 Mar 31 2s
+10 R %z 1992 Ja 19 2s
+11 R %z 2011 Mar 27 2s
+12 - %z 2014 O 26 2s
+10 - %z 2016 Ap 24 2s
+11 - %z
+Z Asia/Makassar 7:57:36 - LMT 1920
+7:57:36 - MMT 1932 N
+8 - %z 1942 F 9
+9 - %z 1945 S 23
+8 - WITA
+Z Asia/Manila -15:56:8 - LMT 1844 D 31
+8:3:52 - LMT 1899 S 6 4u
+8 PH P%sT 1942 F 11 24
+9 - JST 1945 Mar 4
+8 PH P%sT
+Z Asia/Nicosia 2:13:28 - LMT 1921 N 14
+2 CY EE%sT 1998 S
+2 E EE%sT
+Z Asia/Novokuznetsk 5:48:48 - LMT 1924 May
+6 - %z 1930 Jun 21
+7 R %z 1991 Mar 31 2s
+6 R %z 1992 Ja 19 2s
+7 R %z 2010 Mar 28 2s
+6 R %z 2011 Mar 27 2s
+7 - %z
+Z Asia/Novosibirsk 5:31:40 - LMT 1919 D 14 6
+6 - %z 1930 Jun 21
+7 R %z 1991 Mar 31 2s
+6 R %z 1992 Ja 19 2s
+7 R %z 1993 May 23
+6 R %z 2011 Mar 27 2s
+7 - %z 2014 O 26 2s
+6 - %z 2016 Jul 24 2s
+7 - %z
+Z Asia/Omsk 4:53:30 - LMT 1919 N 14
+5 - %z 1930 Jun 21
+6 R %z 1991 Mar 31 2s
+5 R %z 1992 Ja 19 2s
+6 R %z 2011 Mar 27 2s
+7 - %z 2014 O 26 2s
+6 - %z
+Z Asia/Oral 3:25:24 - LMT 1924 May 2
+3 - %z 1930 Jun 21
+5 - %z 1981 Ap
+5 1 %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1989 Mar 26 2s
+4 R %z 1992 Ja 19 2s
+5 R %z 1992 Mar 29 2s
+4 R %z 2004 O 31 2s
+5 - %z
+Z Asia/Pontianak 7:17:20 - LMT 1908 May
+7:17:20 - PMT 1932 N
+7:30 - %z 1942 Ja 29
+9 - %z 1945 S 23
+7:30 - %z 1948 May
+8 - %z 1950 May
+7:30 - %z 1964
+8 - WITA 1988
+7 - WIB
+Z Asia/Pyongyang 8:23 - LMT 1908 Ap
+8:30 - KST 1912
+9 - JST 1945 Au 24
+9 - KST 2015 Au 15
+8:30 - KST 2018 May 4 23:30
+9 - KST
+Z Asia/Qatar 3:26:8 - LMT 1920
+4 - %z 1972 Jun
+3 - %z
+Z Asia/Qostanay 4:14:28 - LMT 1924 May 2
+4 - %z 1930 Jun 21
+5 - %z 1981 Ap
+5 1 %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1991 Mar 31 2s
+4 R %z 1992 Ja 19 2s
+5 R %z 2004 O 31 2s
+6 - %z 2024 Mar
+5 - %z
+Z Asia/Qyzylorda 4:21:52 - LMT 1924 May 2
+4 - %z 1930 Jun 21
+5 - %z 1981 Ap
+5 1 %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1991 Mar 31 2s
+4 R %z 1991 S 29 2s
+5 R %z 1992 Ja 19 2s
+6 R %z 1992 Mar 29 2s
+5 R %z 2004 O 31 2s
+6 - %z 2018 D 21
+5 - %z
+Z Asia/Riyadh 3:6:52 - LMT 1947 Mar 14
+3 - %z
+Z Asia/Sakhalin 9:30:48 - LMT 1905 Au 23
+9 - %z 1945 Au 25
+11 R %z 1991 Mar 31 2s
+10 R %z 1992 Ja 19 2s
+11 R %z 1997 Mar lastSu 2s
+10 R %z 2011 Mar 27 2s
+11 - %z 2014 O 26 2s
+10 - %z 2016 Mar 27 2s
+11 - %z
+Z Asia/Samarkand 4:27:53 - LMT 1924 May 2
+4 - %z 1930 Jun 21
+5 - %z 1981 Ap
+5 1 %z 1981 O
+6 - %z 1982 Ap
+5 R %z 1992
+5 - %z
+Z Asia/Seoul 8:27:52 - LMT 1908 Ap
+8:30 - KST 1912
+9 - JST 1945 S 8
+9 KR K%sT 1954 Mar 21
+8:30 KR K%sT 1961 Au 10
+9 KR K%sT
+Z Asia/Shanghai 8:5:43 - LMT 1901
+8 Sh C%sT 1949 May 28
+8 CN C%sT
+Z Asia/Singapore 6:55:25 - LMT 1901
+6:55:25 - SMT 1905 Jun
+7 - %z 1933
+7 0:20 %z 1936
+7:20 - %z 1941 S
+7:30 - %z 1942 F 16
+9 - %z 1945 S 12
+7:30 - %z 1981 D 31 16u
+8 - %z
+Z Asia/Srednekolymsk 10:14:52 - LMT 1924 May 2
+10 - %z 1930 Jun 21
+11 R %z 1991 Mar 31 2s
+10 R %z 1992 Ja 19 2s
+11 R %z 2011 Mar 27 2s
+12 - %z 2014 O 26 2s
+11 - %z
+Z Asia/Taipei 8:6 - LMT 1896
+8 - CST 1937 O
+9 - JST 1945 S 21 1
+8 f C%sT
+Z Asia/Tashkent 4:37:11 - LMT 1924 May 2
+5 - %z 1930 Jun 21
+6 R %z 1991 Mar 31 2
+5 R %z 1992
+5 - %z
+Z Asia/Tbilisi 2:59:11 - LMT 1880
+2:59:11 - TBMT 1924 May 2
+3 - %z 1957 Mar
+4 R %z 1991 Mar 31 2s
+3 R %z 1992
+3 e %z 1994 S lastSu
+4 e %z 1996 O lastSu
+4 1 %z 1997 Mar lastSu
+4 e %z 2004 Jun 27
+3 R %z 2005 Mar lastSu 2
+4 - %z
+Z Asia/Tehran 3:25:44 - LMT 1916
+3:25:44 - TMT 1935 Jun 13
+3:30 i %z 1977 O 20 24
+4 i %z 1978 N 10 24
+3:30 i %z
+Z Asia/Thimphu 5:58:36 - LMT 1947 Au 15
+5:30 - %z 1987 O
+6 - %z
+Z Asia/Tokyo 9:18:59 - LMT 1887 D 31 15u
+9 JP J%sT
+Z Asia/Tomsk 5:39:51 - LMT 1919 D 22
+6 - %z 1930 Jun 21
+7 R %z 1991 Mar 31 2s
+6 R %z 1992 Ja 19 2s
+7 R %z 2002 May 1 3
+6 R %z 2011 Mar 27 2s
+7 - %z 2014 O 26 2s
+6 - %z 2016 May 29 2s
+7 - %z
+Z Asia/Ulaanbaatar 7:7:32 - LMT 1905 Au
+7 - %z 1978
+8 X %z
+Z Asia/Urumqi 5:50:20 - LMT 1928
+6 - %z
+Z Asia/Ust-Nera 9:32:54 - LMT 1919 D 15
+8 - %z 1930 Jun 21
+9 R %z 1981 Ap
+11 R %z 1991 Mar 31 2s
+10 R %z 1992 Ja 19 2s
+11 R %z 2011 Mar 27 2s
+12 - %z 2011 S 13 0s
+11 - %z 2014 O 26 2s
+10 - %z
+Z Asia/Vladivostok 8:47:31 - LMT 1922 N 15
+9 - %z 1930 Jun 21
+10 R %z 1991 Mar 31 2s
+9 R %z 1992 Ja 19 2s
+10 R %z 2011 Mar 27 2s
+11 - %z 2014 O 26 2s
+10 - %z
+Z Asia/Yakutsk 8:38:58 - LMT 1919 D 15
+8 - %z 1930 Jun 21
+9 R %z 1991 Mar 31 2s
+8 R %z 1992 Ja 19 2s
+9 R %z 2011 Mar 27 2s
+10 - %z 2014 O 26 2s
+9 - %z
+Z Asia/Yangon 6:24:47 - LMT 1880
+6:24:47 - RMT 1920
+6:30 - %z 1942 May
+9 - %z 1945 May 3
+6:30 - %z
+Z Asia/Yekaterinburg 4:2:33 - LMT 1916 Jul 3
+3:45:5 - PMT 1919 Jul 15 4
+4 - %z 1930 Jun 21
+5 R %z 1991 Mar 31 2s
+4 R %z 1992 Ja 19 2s
+5 R %z 2011 Mar 27 2s
+6 - %z 2014 O 26 2s
+5 - %z
+Z Asia/Yerevan 2:58 - LMT 1924 May 2
+3 - %z 1957 Mar
+4 R %z 1991 Mar 31 2s
+3 R %z 1995 S 24 2s
+4 - %z 1997
+4 R %z 2011
+4 AM %z
+Z Atlantic/Azores -1:42:40 - LMT 1884
+-1:54:32 - HMT 1912 Ja 1 2u
+-2 p %z 1966 O 2 2s
+-1 - %z 1982 Mar 28 0s
+-1 p %z 1986
+-1 E %z 1992 D 27 1s
+0 E WE%sT 1993 Jun 17 1u
+-1 E %z
+Z Atlantic/Bermuda -4:19:18 - LMT 1890
+-4:19:18 Be BMT/BST 1930 Ja 1 2
+-4 Be A%sT 1974 Ap 28 2
+-4 C A%sT 1976
+-4 u A%sT
+Z Atlantic/Canary -1:1:36 - LMT 1922 Mar
+-1 - %z 1946 S 30 1
+0 - WET 1980 Ap 6 0s
+0 1 WEST 1980 S 28 1u
+0 E WE%sT
+Z Atlantic/Cape_Verde -1:34:4 - LMT 1912 Ja 1 2u
+-2 - %z 1942 S
+-2 1 %z 1945 O 15
+-2 - %z 1975 N 25 2
+-1 - %z
+Z Atlantic/Faroe -0:27:4 - LMT 1908 Ja 11
+0 - WET 1981
+0 E WE%sT
+Z Atlantic/Madeira -1:7:36 - LMT 1884
+-1:7:36 - FMT 1912 Ja 1 1u
+-1 p %z 1966 O 2 2s
+0 - WET 1982 Ap 4
+0 p WE%sT 1986 Jul 31
+0 E WE%sT
+Z Atlantic/South_Georgia -2:26:8 - LMT 1890
+-2 - %z
+Z Atlantic/Stanley -3:51:24 - LMT 1890
+-3:51:24 - SMT 1912 Mar 12
+-4 FK %z 1983 May
+-3 FK %z 1985 S 15
+-4 FK %z 2010 S 5 2
+-3 - %z
+Z Australia/Adelaide 9:14:20 - LMT 1895 F
+9 - ACST 1899 May
+9:30 AU AC%sT 1971
+9:30 AS AC%sT
+Z Australia/Brisbane 10:12:8 - LMT 1895
+10 AU AE%sT 1971
+10 AQ AE%sT
+Z Australia/Broken_Hill 9:25:48 - LMT 1895 F
+10 - AEST 1896 Au 23
+9 - ACST 1899 May
+9:30 AU AC%sT 1971
+9:30 AN AC%sT 2000
+9:30 AS AC%sT
+Z Australia/Darwin 8:43:20 - LMT 1895 F
+9 - ACST 1899 May
+9:30 AU AC%sT
+Z Australia/Eucla 8:35:28 - LMT 1895 D
+8:45 AU %z 1943 Jul
+8:45 AW %z
+Z Australia/Hobart 9:49:16 - LMT 1895 S
+10 AT AE%sT 1919 O 24
+10 AU AE%sT 1967
+10 AT AE%sT
+Z Australia/Lindeman 9:55:56 - LMT 1895
+10 AU AE%sT 1971
+10 AQ AE%sT 1992 Jul
+10 Ho AE%sT
+Z Australia/Lord_Howe 10:36:20 - LMT 1895 F
+10 - AEST 1981 Mar
+10:30 LH %z 1985 Jul
+10:30 LH %z
+Z Australia/Melbourne 9:39:52 - LMT 1895 F
+10 AU AE%sT 1971
+10 AV AE%sT
+Z Australia/Perth 7:43:24 - LMT 1895 D
+8 AU AW%sT 1943 Jul
+8 AW AW%sT
+Z Australia/Sydney 10:4:52 - LMT 1895 F
+10 AU AE%sT 1971
+10 AN AE%sT
+Z Etc/GMT 0 - GMT
+Z Etc/GMT+1 -1 - %z
+Z Etc/GMT+10 -10 - %z
+Z Etc/GMT+11 -11 - %z
+Z Etc/GMT+12 -12 - %z
+Z Etc/GMT+2 -2 - %z
+Z Etc/GMT+3 -3 - %z
+Z Etc/GMT+4 -4 - %z
+Z Etc/GMT+5 -5 - %z
+Z Etc/GMT+6 -6 - %z
+Z Etc/GMT+7 -7 - %z
+Z Etc/GMT+8 -8 - %z
+Z Etc/GMT+9 -9 - %z
+Z Etc/GMT-1 1 - %z
+Z Etc/GMT-10 10 - %z
+Z Etc/GMT-11 11 - %z
+Z Etc/GMT-12 12 - %z
+Z Etc/GMT-13 13 - %z
+Z Etc/GMT-14 14 - %z
+Z Etc/GMT-2 2 - %z
+Z Etc/GMT-3 3 - %z
+Z Etc/GMT-4 4 - %z
+Z Etc/GMT-5 5 - %z
+Z Etc/GMT-6 6 - %z
+Z Etc/GMT-7 7 - %z
+Z Etc/GMT-8 8 - %z
+Z Etc/GMT-9 9 - %z
+Z Etc/UTC 0 - UTC
+Z Europe/Andorra 0:6:4 - LMT 1901
+0 - WET 1946 S 30
+1 - CET 1985 Mar 31 2
+1 E CE%sT
+Z Europe/Astrakhan 3:12:12 - LMT 1924 May
+3 - %z 1930 Jun 21
+4 R %z 1989 Mar 26 2s
+3 R %z 1991 Mar 31 2s
+4 - %z 1992 Mar 29 2s
+3 R %z 2011 Mar 27 2s
+4 - %z 2014 O 26 2s
+3 - %z 2016 Mar 27 2s
+4 - %z
+Z Europe/Athens 1:34:52 - LMT 1895 S 14
+1:34:52 - AMT 1916 Jul 28 0:1
+2 g EE%sT 1941 Ap 30
+1 g CE%sT 1944 Ap 4
+2 g EE%sT 1981
+2 E EE%sT
+Z Europe/Belgrade 1:22 - LMT 1884
+1 - CET 1941 Ap 18 23
+1 c CE%sT 1945
+1 - CET 1945 May 8 2s
+1 1 CEST 1945 S 16 2s
+1 - CET 1982 N 27
+1 E CE%sT
+Z Europe/Berlin 0:53:28 - LMT 1893 Ap
+1 c CE%sT 1945 May 24 2
+1 So CE%sT 1946
+1 DE CE%sT 1980
+1 E CE%sT
+Z Europe/Brussels 0:17:30 - LMT 1880
+0:17:30 - BMT 1892 May 1 0:17:30
+0 - WET 1914 N 8
+1 - CET 1916 May
+1 c CE%sT 1918 N 11 11u
+0 b WE%sT 1940 May 20 2s
+1 c CE%sT 1944 S 3
+1 b CE%sT 1977
+1 E CE%sT
+Z Europe/Bucharest 1:44:24 - LMT 1891 O
+1:44:24 - BMT 1931 Jul 24
+2 z EE%sT 1981 Mar 29 2s
+2 c EE%sT 1991
+2 z EE%sT 1994
+2 e EE%sT 1997
+2 E EE%sT
+Z Europe/Budapest 1:16:20 - LMT 1890 N
+1 c CE%sT 1918
+1 h CE%sT 1941 Ap 7 23
+1 c CE%sT 1945
+1 h CE%sT 1984
+1 E CE%sT
+Z Europe/Chisinau 1:55:20 - LMT 1880
+1:55 - CMT 1918 F 15
+1:44:24 - BMT 1931 Jul 24
+2 z EE%sT 1940 Au 15
+2 1 EEST 1941 Jul 17
+1 c CE%sT 1944 Au 24
+3 R MSK/MSD 1990 May 6 2
+2 R EE%sT 1992
+2 e EE%sT 1997
+2 MD EE%sT
+Z Europe/Dublin -0:25:21 - LMT 1880 Au 2
+-0:25:21 - DMT 1916 May 21 2s
+-0:25:21 1 IST 1916 O 1 2s
+0 G %s 1921 D 6
+0 G GMT/IST 1940 F 25 2s
+0 1 IST 1946 O 6 2s
+0 - GMT 1947 Mar 16 2s
+0 1 IST 1947 N 2 2s
+0 - GMT 1948 Ap 18 2s
+0 G GMT/IST 1968 O 27
+1 IE IST/GMT
+Z Europe/Gibraltar -0:21:24 - LMT 1880 Au 2
+0 G %s 1957 Ap 14 2
+1 - CET 1982
+1 E CE%sT
+Z Europe/Helsinki 1:39:49 - LMT 1878 May 31
+1:39:49 - HMT 1921 May
+2 FI EE%sT 1983
+2 E EE%sT
+Z Europe/Istanbul 1:55:52 - LMT 1880
+1:56:56 - IMT 1910 O
+2 T EE%sT 1978 Jun 29
+3 T %z 1984 N 1 2
+2 T EE%sT 2007
+2 E EE%sT 2011 Mar 27 1u
+2 - EET 2011 Mar 28 1u
+2 E EE%sT 2014 Mar 30 1u
+2 - EET 2014 Mar 31 1u
+2 E EE%sT 2015 O 25 1u
+2 1 EEST 2015 N 8 1u
+2 E EE%sT 2016 S 7
+3 - %z
+Z Europe/Kaliningrad 1:22 - LMT 1893 Ap
+1 c CE%sT 1945 Ap 10
+2 O EE%sT 1946 Ap 7
+3 R MSK/MSD 1989 Mar 26 2s
+2 R EE%sT 2011 Mar 27 2s
+3 - %z 2014 O 26 2s
+2 - EET
+Z Europe/Kirov 3:18:48 - LMT 1919 Jul 1 0u
+3 - %z 1930 Jun 21
+4 R %z 1989 Mar 26 2s
+3 R MSK/MSD 1991 Mar 31 2s
+4 - %z 1992 Mar 29 2s
+3 R MSK/MSD 2011 Mar 27 2s
+4 - MSK 2014 O 26 2s
+3 - MSK
+Z Europe/Kyiv 2:2:4 - LMT 1880
+2:2:4 - KMT 1924 May 2
+2 - EET 1930 Jun 21
+3 - MSK 1941 S 20
+1 c CE%sT 1943 N 6
+3 R MSK/MSD 1990 Jul 1 2
+2 1 EEST 1991 S 29 3
+2 c EE%sT 1996 May 13
+2 E EE%sT
+Z Europe/Lisbon -0:36:45 - LMT 1884
+-0:36:45 - LMT 1912 Ja 1 0u
+0 p WE%sT 1966 O 2 2s
+1 - CET 1976 S 26 1
+0 p WE%sT 1986
+0 E WE%sT 1992 S 27 1u
+1 E CE%sT 1996 Mar 31 1u
+0 E WE%sT
+Z Europe/London -0:1:15 - LMT 1847 D
+0 G %s 1968 O 27
+1 - BST 1971 O 31 2u
+0 G %s 1996
+0 E GMT/BST
+Z Europe/Madrid -0:14:44 - LMT 1901 Ja 1 0u
+0 s WE%sT 1940 Mar 16 23
+1 s CE%sT 1979
+1 E CE%sT
+Z Europe/Malta 0:58:4 - LMT 1893 N 2
+1 I CE%sT 1973 Mar 31
+1 MT CE%sT 1981
+1 E CE%sT
+Z Europe/Minsk 1:50:16 - LMT 1880
+1:50 - MMT 1924 May 2
+2 - EET 1930 Jun 21
+3 - MSK 1941 Jun 28
+1 c CE%sT 1944 Jul 3
+3 R MSK/MSD 1990
+3 - MSK 1991 Mar 31 2s
+2 R EE%sT 2011 Mar 27 2s
+3 - %z
+Z Europe/Moscow 2:30:17 - LMT 1880
+2:30:17 - MMT 1916 Jul 3
+2:31:19 R %s 1919 Jul 1 0u
+3 R %s 1921 O
+3 R MSK/MSD 1922 O
+2 - EET 1930 Jun 21
+3 R MSK/MSD 1991 Mar 31 2s
+2 R EE%sT 1992 Ja 19 2s
+3 R MSK/MSD 2011 Mar 27 2s
+4 - MSK 2014 O 26 2s
+3 - MSK
+Z Europe/Paris 0:9:21 - LMT 1891 Mar 16
+0:9:21 - PMT 1911 Mar 11
+0 F WE%sT 1940 Jun 14 23
+1 c CE%sT 1944 Au 25
+0 F WE%sT 1945 S 16 3
+1 F CE%sT 1977
+1 E CE%sT
+Z Europe/Prague 0:57:44 - LMT 1850
+0:57:44 - PMT 1891 O
+1 c CE%sT 1945 May 9
+1 CZ CE%sT 1946 D 1 3
+1 -1 GMT 1947 F 23 2
+1 CZ CE%sT 1979
+1 E CE%sT
+Z Europe/Riga 1:36:34 - LMT 1880
+1:36:34 - RMT 1918 Ap 15 2
+1:36:34 1 LST 1918 S 16 3
+1:36:34 - RMT 1919 Ap 1 2
+1:36:34 1 LST 1919 May 22 3
+1:36:34 - RMT 1926 May 11
+2 - EET 1940 Au 5
+3 - MSK 1941 Jul
+1 c CE%sT 1944 O 13
+3 R MSK/MSD 1989 Mar lastSu 2s
+2 1 EEST 1989 S lastSu 2s
+2 LV EE%sT 1997 Ja 21
+2 E EE%sT 2000 F 29
+2 - EET 2001 Ja 2
+2 E EE%sT
+Z Europe/Rome 0:49:56 - LMT 1866 D 12
+0:49:56 - RMT 1893 O 31 23u
+1 I CE%sT 1943 S 10
+1 c CE%sT 1944 Jun 4
+1 I CE%sT 1980
+1 E CE%sT
+Z Europe/Samara 3:20:20 - LMT 1919 Jul 1 0u
+3 - %z 1930 Jun 21
+4 - %z 1935 Ja 27
+4 R %z 1989 Mar 26 2s
+3 R %z 1991 Mar 31 2s
+2 R %z 1991 S 29 2s
+3 - %z 1991 O 20 3
+4 R %z 2010 Mar 28 2s
+3 R %z 2011 Mar 27 2s
+4 - %z
+Z Europe/Saratov 3:4:18 - LMT 1919 Jul 1 0u
+3 - %z 1930 Jun 21
+4 R %z 1988 Mar 27 2s
+3 R %z 1991 Mar 31 2s
+4 - %z 1992 Mar 29 2s
+3 R %z 2011 Mar 27 2s
+4 - %z 2014 O 26 2s
+3 - %z 2016 D 4 2s
+4 - %z
+Z Europe/Simferopol 2:16:24 - LMT 1880
+2:16 - SMT 1924 May 2
+2 - EET 1930 Jun 21
+3 - MSK 1941 N
+1 c CE%sT 1944 Ap 13
+3 R MSK/MSD 1990
+3 - MSK 1990 Jul 1 2
+2 - EET 1992 Mar 20
+2 c EE%sT 1994 May
+3 c MSK/MSD 1996 Mar 31 0s
+3 1 MSD 1996 O 27 3s
+3 - MSK 1997 Mar lastSu 1u
+2 E EE%sT 2014 Mar 30 2
+4 - MSK 2014 O 26 2s
+3 - MSK
+Z Europe/Sofia 1:33:16 - LMT 1880
+1:56:56 - IMT 1894 N 30
+2 - EET 1942 N 2 3
+1 c CE%sT 1945
+1 - CET 1945 Ap 2 3
+2 - EET 1979 Mar 31 23
+2 BG EE%sT 1982 S 26 3
+2 c EE%sT 1991
+2 e EE%sT 1997
+2 E EE%sT
+Z Europe/Tallinn 1:39 - LMT 1880
+1:39 - TMT 1918 F
+1 c CE%sT 1919 Jul
+1:39 - TMT 1921 May
+2 - EET 1940 Au 6
+3 - MSK 1941 S 15
+1 c CE%sT 1944 S 22
+3 R MSK/MSD 1989 Mar 26 2s
+2 1 EEST 1989 S 24 2s
+2 c EE%sT 1998 S 22
+2 E EE%sT 1999 O 31 4
+2 - EET 2002 F 21
+2 E EE%sT
+Z Europe/Tirane 1:19:20 - LMT 1914
+1 - CET 1940 Jun 16
+1 q CE%sT 1984 Jul
+1 E CE%sT
+Z Europe/Ulyanovsk 3:13:36 - LMT 1919 Jul 1 0u
+3 - %z 1930 Jun 21
+4 R %z 1989 Mar 26 2s
+3 R %z 1991 Mar 31 2s
+2 R %z 1992 Ja 19 2s
+3 R %z 2011 Mar 27 2s
+4 - %z 2014 O 26 2s
+3 - %z 2016 Mar 27 2s
+4 - %z
+Z Europe/Vienna 1:5:21 - LMT 1893 Ap
+1 c CE%sT 1920
+1 a CE%sT 1940 Ap 1 2s
+1 c CE%sT 1945 Ap 2 2s
+1 1 CEST 1945 Ap 12 2s
+1 - CET 1946
+1 a CE%sT 1981
+1 E CE%sT
+Z Europe/Vilnius 1:41:16 - LMT 1880
+1:24 - WMT 1917
+1:35:36 - KMT 1919 O 10
+1 - CET 1920 Jul 12
+2 - EET 1920 O 9
+1 - CET 1940 Au 3
+3 - MSK 1941 Jun 24
+1 c CE%sT 1944 Au
+3 R MSK/MSD 1989 Mar 26 2s
+2 R EE%sT 1991 S 29 2s
+2 c EE%sT 1998
+2 - EET 1998 Mar 29 1u
+1 E CE%sT 1999 O 31 1u
+2 - EET 2003
+2 E EE%sT
+Z Europe/Volgograd 2:57:40 - LMT 1920 Ja 3
+3 - %z 1930 Jun 21
+4 - %z 1961 N 11
+4 R %z 1988 Mar 27 2s
+3 R MSK/MSD 1991 Mar 31 2s
+4 - %z 1992 Mar 29 2s
+3 R MSK/MSD 2011 Mar 27 2s
+4 - MSK 2014 O 26 2s
+3 - MSK 2018 O 28 2s
+4 - %z 2020 D 27 2s
+3 - MSK
+Z Europe/Warsaw 1:24 - LMT 1880
+1:24 - WMT 1915 Au 5
+1 c CE%sT 1918 S 16 3
+2 O EE%sT 1922 Jun
+1 O CE%sT 1940 Jun 23 2
+1 c CE%sT 1944 O
+1 O CE%sT 1977
+1 W- CE%sT 1988
+1 E CE%sT
+Z Europe/Zurich 0:34:8 - LMT 1853 Jul 16
+0:29:46 - BMT 1894 Jun
+1 CH CE%sT 1981
+1 E CE%sT
+Z Factory 0 - -00
+Z Indian/Chagos 4:49:40 - LMT 1907
+5 - %z 1996
+6 - %z
+Z Indian/Maldives 4:54 - LMT 1880
+4:54 - MMT 1960
+5 - %z
+Z Indian/Mauritius 3:50 - LMT 1907
+4 MU %z
+Z Pacific/Apia 12:33:4 - LMT 1892 Jul 5
+-11:26:56 - LMT 1911
+-11:30 - %z 1950
+-11 WS %z 2011 D 29 24
+13 WS %z
+Z Pacific/Auckland 11:39:4 - LMT 1868 N 2
+11:30 NZ NZ%sT 1946
+12 NZ NZ%sT
+Z Pacific/Bougainville 10:22:16 - LMT 1880
+9:48:32 - PMMT 1895
+10 - %z 1942 Jul
+9 - %z 1945 Au 21
+10 - %z 2014 D 28 2
+11 - %z
+Z Pacific/Chatham 12:13:48 - LMT 1868 N 2
+12:15 - %z 1946
+12:45 k %z
+Z Pacific/Easter -7:17:28 - LMT 1890
+-7:17:28 - EMT 1932 S
+-7 x %z 1982 Mar 14 3u
+-6 x %z
+Z Pacific/Efate 11:13:16 - LMT 1912 Ja 13
+11 VU %z
+Z Pacific/Fakaofo -11:24:56 - LMT 1901
+-11 - %z 2011 D 30
+13 - %z
+Z Pacific/Fiji 11:55:44 - LMT 1915 O 26
+12 FJ %z
+Z Pacific/Galapagos -5:58:24 - LMT 1931
+-5 - %z 1986
+-6 EC %z
+Z Pacific/Gambier -8:59:48 - LMT 1912 O
+-9 - %z
+Z Pacific/Guadalcanal 10:39:48 - LMT 1912 O
+11 - %z
+Z Pacific/Guam -14:21 - LMT 1844 D 31
+9:39 - LMT 1901
+10 - GST 1941 D 10
+9 - %z 1944 Jul 31
+10 Gu G%sT 2000 D 23
+10 - ChST
+Z Pacific/Honolulu -10:31:26 - LMT 1896 Ja 13 12
+-10:30 - HST 1933 Ap 30 2
+-10:30 1 HDT 1933 May 21 12
+-10:30 u H%sT 1947 Jun 8 2
+-10 - HST
+Z Pacific/Kanton 0 - -00 1937 Au 31
+-12 - %z 1979 O
+-11 - %z 1994 D 31
+13 - %z
+Z Pacific/Kiritimati -10:29:20 - LMT 1901
+-10:40 - %z 1979 O
+-10 - %z 1994 D 31
+14 - %z
+Z Pacific/Kosrae -13:8:4 - LMT 1844 D 31
+10:51:56 - LMT 1901
+11 - %z 1914 O
+9 - %z 1919 F
+11 - %z 1937
+10 - %z 1941 Ap
+9 - %z 1945 Au
+11 - %z 1969 O
+12 - %z 1999
+11 - %z
+Z Pacific/Kwajalein 11:9:20 - LMT 1901
+11 - %z 1937
+10 - %z 1941 Ap
+9 - %z 1944 F 6
+11 - %z 1969 O
+-12 - %z 1993 Au 20 24
+12 - %z
+Z Pacific/Marquesas -9:18 - LMT 1912 O
+-9:30 - %z
+Z Pacific/Nauru 11:7:40 - LMT 1921 Ja 15
+11:30 - %z 1942 Au 29
+9 - %z 1945 S 8
+11:30 - %z 1979 F 10 2
+12 - %z
+Z Pacific/Niue -11:19:40 - LMT 1952 O 16
+-11:20 - %z 1964 Jul
+-11 - %z
+Z Pacific/Norfolk 11:11:52 - LMT 1901
+11:12 - %z 1951
+11:30 - %z 1974 O 27 2s
+11:30 1 %z 1975 Mar 2 2s
+11:30 - %z 2015 O 4 2s
+11 - %z 2019 Jul
+11 AN %z
+Z Pacific/Noumea 11:5:48 - LMT 1912 Ja 13
+11 NC %z
+Z Pacific/Pago_Pago 12:37:12 - LMT 1892 Jul 5
+-11:22:48 - LMT 1911
+-11 - SST
+Z Pacific/Palau -15:2:4 - LMT 1844 D 31
+8:57:56 - LMT 1901
+9 - %z
+Z Pacific/Pitcairn -8:40:20 - LMT 1901
+-8:30 - %z 1998 Ap 27
+-8 - %z
+Z Pacific/Port_Moresby 9:48:40 - LMT 1880
+9:48:32 - PMMT 1895
+10 - %z
+Z Pacific/Rarotonga 13:20:56 - LMT 1899 D 26
+-10:39:4 - LMT 1952 O 16
+-10:30 - %z 1978 N 12
+-10 CK %z
+Z Pacific/Tahiti -9:58:16 - LMT 1912 O
+-10 - %z
+Z Pacific/Tarawa 11:32:4 - LMT 1901
+12 - %z
+Z Pacific/Tongatapu 12:19:12 - LMT 1945 S 10
+12:20 - %z 1961
+13 - %z 1999
+13 TO %z
+L Etc/GMT GMT
+L Australia/Sydney Australia/ACT
+L Australia/Lord_Howe Australia/LHI
+L Australia/Sydney Australia/NSW
+L Australia/Darwin Australia/North
+L Australia/Brisbane Australia/Queensland
+L Australia/Adelaide Australia/South
+L Australia/Hobart Australia/Tasmania
+L Australia/Melbourne Australia/Victoria
+L Australia/Perth Australia/West
+L Australia/Broken_Hill Australia/Yancowinna
+L America/Rio_Branco Brazil/Acre
+L America/Noronha Brazil/DeNoronha
+L America/Sao_Paulo Brazil/East
+L America/Manaus Brazil/West
+L Europe/Brussels CET
+L America/Chicago CST6CDT
+L America/Halifax Canada/Atlantic
+L America/Winnipeg Canada/Central
+L America/Toronto Canada/Eastern
+L America/Edmonton Canada/Mountain
+L America/St_Johns Canada/Newfoundland
+L America/Vancouver Canada/Pacific
+L America/Regina Canada/Saskatchewan
+L America/Whitehorse Canada/Yukon
+L America/Santiago Chile/Continental
+L Pacific/Easter Chile/EasterIsland
+L America/Havana Cuba
+L Europe/Athens EET
+L America/Panama EST
+L America/New_York EST5EDT
+L Africa/Cairo Egypt
+L Europe/Dublin Eire
+L Etc/GMT Etc/GMT+0
+L Etc/GMT Etc/GMT-0
+L Etc/GMT Etc/GMT0
+L Etc/GMT Etc/Greenwich
+L Etc/UTC Etc/UCT
+L Etc/UTC Etc/Universal
+L Etc/UTC Etc/Zulu
+L Europe/London GB
+L Europe/London GB-Eire
+L Etc/GMT GMT+0
+L Etc/GMT GMT-0
+L Etc/GMT GMT0
+L Etc/GMT Greenwich
+L Asia/Hong_Kong Hongkong
+L Africa/Abidjan Iceland
+L Asia/Tehran Iran
+L Asia/Jerusalem Israel
+L America/Jamaica Jamaica
+L Asia/Tokyo Japan
+L Pacific/Kwajalein Kwajalein
+L Africa/Tripoli Libya
+L Europe/Brussels MET
+L America/Phoenix MST
+L America/Denver MST7MDT
+L America/Tijuana Mexico/BajaNorte
+L America/Mazatlan Mexico/BajaSur
+L America/Mexico_City Mexico/General
+L Pacific/Auckland NZ
+L Pacific/Chatham NZ-CHAT
+L America/Denver Navajo
+L Asia/Shanghai PRC
+L Europe/Warsaw Poland
+L Europe/Lisbon Portugal
+L Asia/Taipei ROC
+L Asia/Seoul ROK
+L Asia/Singapore Singapore
+L Europe/Istanbul Turkey
+L Etc/UTC UCT
+L America/Anchorage US/Alaska
+L America/Adak US/Aleutian
+L America/Phoenix US/Arizona
+L America/Chicago US/Central
+L America/Indiana/Indianapolis US/East-Indiana
+L America/New_York US/Eastern
+L Pacific/Honolulu US/Hawaii
+L America/Indiana/Knox US/Indiana-Starke
+L America/Detroit US/Michigan
+L America/Denver US/Mountain
+L America/Los_Angeles US/Pacific
+L Pacific/Pago_Pago US/Samoa
+L Etc/UTC UTC
+L Etc/UTC Universal
+L Europe/Moscow W-SU
+L Etc/UTC Zulu
+L America/Argentina/Buenos_Aires America/Buenos_Aires
+L America/Argentina/Catamarca America/Catamarca
+L America/Argentina/Cordoba America/Cordoba
+L America/Indiana/Indianapolis America/Indianapolis
+L America/Argentina/Jujuy America/Jujuy
+L America/Indiana/Knox America/Knox_IN
+L America/Kentucky/Louisville America/Louisville
+L America/Argentina/Mendoza America/Mendoza
+L America/Puerto_Rico America/Virgin
+L Pacific/Pago_Pago Pacific/Samoa
+L Africa/Abidjan Africa/Accra
+L Africa/Nairobi Africa/Addis_Ababa
+L Africa/Nairobi Africa/Asmara
+L Africa/Abidjan Africa/Bamako
+L Africa/Lagos Africa/Bangui
+L Africa/Abidjan Africa/Banjul
+L Africa/Maputo Africa/Blantyre
+L Africa/Lagos Africa/Brazzaville
+L Africa/Maputo Africa/Bujumbura
+L Africa/Abidjan Africa/Conakry
+L Africa/Abidjan Africa/Dakar
+L Africa/Nairobi Africa/Dar_es_Salaam
+L Africa/Nairobi Africa/Djibouti
+L Africa/Lagos Africa/Douala
+L Africa/Abidjan Africa/Freetown
+L Africa/Maputo Africa/Gaborone
+L Africa/Maputo Africa/Harare
+L Africa/Nairobi Africa/Kampala
+L Africa/Maputo Africa/Kigali
+L Africa/Lagos Africa/Kinshasa
+L Africa/Lagos Africa/Libreville
+L Africa/Abidjan Africa/Lome
+L Africa/Lagos Africa/Luanda
+L Africa/Maputo Africa/Lubumbashi
+L Africa/Maputo Africa/Lusaka
+L Africa/Lagos Africa/Malabo
+L Africa/Johannesburg Africa/Maseru
+L Africa/Johannesburg Africa/Mbabane
+L Africa/Nairobi Africa/Mogadishu
+L Africa/Lagos Africa/Niamey
+L Africa/Abidjan Africa/Nouakchott
+L Africa/Abidjan Africa/Ouagadougou
+L Africa/Lagos Africa/Porto-Novo
+L America/Puerto_Rico America/Anguilla
+L America/Puerto_Rico America/Antigua
+L America/Puerto_Rico America/Aruba
+L America/Panama America/Atikokan
+L America/Puerto_Rico America/Blanc-Sablon
+L America/Panama America/Cayman
+L America/Phoenix America/Creston
+L America/Puerto_Rico America/Curacao
+L America/Puerto_Rico America/Dominica
+L America/Puerto_Rico America/Grenada
+L America/Puerto_Rico America/Guadeloupe
+L America/Puerto_Rico America/Kralendijk
+L America/Puerto_Rico America/Lower_Princes
+L America/Puerto_Rico America/Marigot
+L America/Puerto_Rico America/Montserrat
+L America/Toronto America/Nassau
+L America/Puerto_Rico America/Port_of_Spain
+L America/Puerto_Rico America/St_Barthelemy
+L America/Puerto_Rico America/St_Kitts
+L America/Puerto_Rico America/St_Lucia
+L America/Puerto_Rico America/St_Thomas
+L America/Puerto_Rico America/St_Vincent
+L America/Puerto_Rico America/Tortola
+L Pacific/Port_Moresby Antarctica/DumontDUrville
+L Pacific/Auckland Antarctica/McMurdo
+L Asia/Riyadh Antarctica/Syowa
+L Europe/Berlin Arctic/Longyearbyen
+L Asia/Riyadh Asia/Aden
+L Asia/Qatar Asia/Bahrain
+L Asia/Kuching Asia/Brunei
+L Asia/Singapore Asia/Kuala_Lumpur
+L Asia/Riyadh Asia/Kuwait
+L Asia/Dubai Asia/Muscat
+L Asia/Bangkok Asia/Phnom_Penh
+L Asia/Bangkok Asia/Vientiane
+L Africa/Abidjan Atlantic/Reykjavik
+L Africa/Abidjan Atlantic/St_Helena
+L Europe/Brussels Europe/Amsterdam
+L Europe/Prague Europe/Bratislava
+L Europe/Zurich Europe/Busingen
+L Europe/Berlin Europe/Copenhagen
+L Europe/London Europe/Guernsey
+L Europe/London Europe/Isle_of_Man
+L Europe/London Europe/Jersey
+L Europe/Belgrade Europe/Ljubljana
+L Europe/Brussels Europe/Luxembourg
+L Europe/Helsinki Europe/Mariehamn
+L Europe/Paris Europe/Monaco
+L Europe/Berlin Europe/Oslo
+L Europe/Belgrade Europe/Podgorica
+L Europe/Rome Europe/San_Marino
+L Europe/Belgrade Europe/Sarajevo
+L Europe/Belgrade Europe/Skopje
+L Europe/Berlin Europe/Stockholm
+L Europe/Zurich Europe/Vaduz
+L Europe/Rome Europe/Vatican
+L Europe/Belgrade Europe/Zagreb
+L Africa/Nairobi Indian/Antananarivo
+L Asia/Bangkok Indian/Christmas
+L Asia/Yangon Indian/Cocos
+L Africa/Nairobi Indian/Comoro
+L Indian/Maldives Indian/Kerguelen
+L Asia/Dubai Indian/Mahe
+L Africa/Nairobi Indian/Mayotte
+L Asia/Dubai Indian/Reunion
+L Pacific/Port_Moresby Pacific/Chuuk
+L Pacific/Tarawa Pacific/Funafuti
+L Pacific/Tarawa Pacific/Majuro
+L Pacific/Pago_Pago Pacific/Midway
+L Pacific/Guadalcanal Pacific/Pohnpei
+L Pacific/Guam Pacific/Saipan
+L Pacific/Tarawa Pacific/Wake
+L Pacific/Tarawa Pacific/Wallis
+L Africa/Abidjan Africa/Timbuktu
+L America/Argentina/Catamarca America/Argentina/ComodRivadavia
+L America/Adak America/Atka
+L America/Panama America/Coral_Harbour
+L America/Tijuana America/Ensenada
+L America/Indiana/Indianapolis America/Fort_Wayne
+L America/Toronto America/Montreal
+L America/Toronto America/Nipigon
+L America/Iqaluit America/Pangnirtung
+L America/Rio_Branco America/Porto_Acre
+L America/Winnipeg America/Rainy_River
+L America/Argentina/Cordoba America/Rosario
+L America/Tijuana America/Santa_Isabel
+L America/Denver America/Shiprock
+L America/Toronto America/Thunder_Bay
+L America/Edmonton America/Yellowknife
+L Pacific/Auckland Antarctica/South_Pole
+L Asia/Ulaanbaatar Asia/Choibalsan
+L Asia/Shanghai Asia/Chongqing
+L Asia/Shanghai Asia/Harbin
+L Asia/Urumqi Asia/Kashgar
+L Asia/Jerusalem Asia/Tel_Aviv
+L Europe/Berlin Atlantic/Jan_Mayen
+L Australia/Sydney Australia/Canberra
+L Australia/Hobart Australia/Currie
+L Europe/London Europe/Belfast
+L Europe/Chisinau Europe/Tiraspol
+L Europe/Kyiv Europe/Uzhgorod
+L Europe/Kyiv Europe/Zaporozhye
+L Pacific/Kanton Pacific/Enderbury
+L Pacific/Honolulu Pacific/Johnston
+L Pacific/Port_Moresby Pacific/Yap
+L Europe/Lisbon WET
+L Africa/Nairobi Africa/Asmera
+L America/Nuuk America/Godthab
+L Asia/Ashgabat Asia/Ashkhabad
+L Asia/Kolkata Asia/Calcutta
+L Asia/Shanghai Asia/Chungking
+L Asia/Dhaka Asia/Dacca
+L Europe/Istanbul Asia/Istanbul
+L Asia/Kathmandu Asia/Katmandu
+L Asia/Macau Asia/Macao
+L Asia/Yangon Asia/Rangoon
+L Asia/Ho_Chi_Minh Asia/Saigon
+L Asia/Thimphu Asia/Thimbu
+L Asia/Makassar Asia/Ujung_Pandang
+L Asia/Ulaanbaatar Asia/Ulan_Bator
+L Atlantic/Faroe Atlantic/Faeroe
+L Europe/Kyiv Europe/Kiev
+L Asia/Nicosia Europe/Nicosia
+L Pacific/Honolulu HST
+L America/Los_Angeles PST8PDT
+L Pacific/Guadalcanal Pacific/Ponape
+L Pacific/Port_Moresby Pacific/Truk
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/zone.tab b/python_embeded/Lib/site-packages/pytz/zoneinfo/zone.tab
new file mode 100644
index 0000000000000000000000000000000000000000..2626b0550341a0605087f33cac6952d5fbb24e67
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pytz/zoneinfo/zone.tab
@@ -0,0 +1,448 @@
+# tzdb timezone descriptions (deprecated version)
+#
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
+#
+# From Paul Eggert (2021-09-20):
+# This file is intended as a backward-compatibility aid for older programs.
+# New programs should use zone1970.tab. This file is like zone1970.tab (see
+# zone1970.tab's comments), but with the following additional restrictions:
+#
+# 1. This file contains only ASCII characters.
+# 2. The first data column contains exactly one country code.
+#
+# Because of (2), each row stands for an area that is the intersection
+# of a region identified by a country code and of a timezone where civil
+# clocks have agreed since 1970; this is a narrower definition than
+# that of zone1970.tab.
+#
+# Unlike zone1970.tab, a row's third column can be a Link from
+# 'backward' instead of a Zone.
+#
+# This table is intended as an aid for users, to help them select timezones
+# appropriate for their practical needs. It is not intended to take or
+# endorse any position on legal or territorial claims.
+#
+#country-
+#code coordinates TZ comments
+AD +4230+00131 Europe/Andorra
+AE +2518+05518 Asia/Dubai
+AF +3431+06912 Asia/Kabul
+AG +1703-06148 America/Antigua
+AI +1812-06304 America/Anguilla
+AL +4120+01950 Europe/Tirane
+AM +4011+04430 Asia/Yerevan
+AO -0848+01314 Africa/Luanda
+AQ -7750+16636 Antarctica/McMurdo New Zealand time - McMurdo, South Pole
+AQ -6617+11031 Antarctica/Casey Casey
+AQ -6835+07758 Antarctica/Davis Davis
+AQ -6640+14001 Antarctica/DumontDUrville Dumont-d'Urville
+AQ -6736+06253 Antarctica/Mawson Mawson
+AQ -6448-06406 Antarctica/Palmer Palmer
+AQ -6734-06808 Antarctica/Rothera Rothera
+AQ -690022+0393524 Antarctica/Syowa Syowa
+AQ -720041+0023206 Antarctica/Troll Troll
+AQ -7824+10654 Antarctica/Vostok Vostok
+AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF)
+AR -3124-06411 America/Argentina/Cordoba Argentina (most areas: CB, CC, CN, ER, FM, MN, SE, SF)
+AR -2447-06525 America/Argentina/Salta Salta (SA, LP, NQ, RN)
+AR -2411-06518 America/Argentina/Jujuy Jujuy (JY)
+AR -2649-06513 America/Argentina/Tucuman Tucuman (TM)
+AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH)
+AR -2926-06651 America/Argentina/La_Rioja La Rioja (LR)
+AR -3132-06831 America/Argentina/San_Juan San Juan (SJ)
+AR -3253-06849 America/Argentina/Mendoza Mendoza (MZ)
+AR -3319-06621 America/Argentina/San_Luis San Luis (SL)
+AR -5138-06913 America/Argentina/Rio_Gallegos Santa Cruz (SC)
+AR -5448-06818 America/Argentina/Ushuaia Tierra del Fuego (TF)
+AS -1416-17042 Pacific/Pago_Pago
+AT +4813+01620 Europe/Vienna
+AU -3133+15905 Australia/Lord_Howe Lord Howe Island
+AU -5430+15857 Antarctica/Macquarie Macquarie Island
+AU -4253+14719 Australia/Hobart Tasmania
+AU -3749+14458 Australia/Melbourne Victoria
+AU -3352+15113 Australia/Sydney New South Wales (most areas)
+AU -3157+14127 Australia/Broken_Hill New South Wales (Yancowinna)
+AU -2728+15302 Australia/Brisbane Queensland (most areas)
+AU -2016+14900 Australia/Lindeman Queensland (Whitsunday Islands)
+AU -3455+13835 Australia/Adelaide South Australia
+AU -1228+13050 Australia/Darwin Northern Territory
+AU -3157+11551 Australia/Perth Western Australia (most areas)
+AU -3143+12852 Australia/Eucla Western Australia (Eucla)
+AW +1230-06958 America/Aruba
+AX +6006+01957 Europe/Mariehamn
+AZ +4023+04951 Asia/Baku
+BA +4352+01825 Europe/Sarajevo
+BB +1306-05937 America/Barbados
+BD +2343+09025 Asia/Dhaka
+BE +5050+00420 Europe/Brussels
+BF +1222-00131 Africa/Ouagadougou
+BG +4241+02319 Europe/Sofia
+BH +2623+05035 Asia/Bahrain
+BI -0323+02922 Africa/Bujumbura
+BJ +0629+00237 Africa/Porto-Novo
+BL +1753-06251 America/St_Barthelemy
+BM +3217-06446 Atlantic/Bermuda
+BN +0456+11455 Asia/Brunei
+BO -1630-06809 America/La_Paz
+BQ +120903-0681636 America/Kralendijk
+BR -0351-03225 America/Noronha Atlantic islands
+BR -0127-04829 America/Belem Para (east), Amapa
+BR -0343-03830 America/Fortaleza Brazil (northeast: MA, PI, CE, RN, PB)
+BR -0803-03454 America/Recife Pernambuco
+BR -0712-04812 America/Araguaina Tocantins
+BR -0940-03543 America/Maceio Alagoas, Sergipe
+BR -1259-03831 America/Bahia Bahia
+BR -2332-04637 America/Sao_Paulo Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS)
+BR -2027-05437 America/Campo_Grande Mato Grosso do Sul
+BR -1535-05605 America/Cuiaba Mato Grosso
+BR -0226-05452 America/Santarem Para (west)
+BR -0846-06354 America/Porto_Velho Rondonia
+BR +0249-06040 America/Boa_Vista Roraima
+BR -0308-06001 America/Manaus Amazonas (east)
+BR -0640-06952 America/Eirunepe Amazonas (west)
+BR -0958-06748 America/Rio_Branco Acre
+BS +2505-07721 America/Nassau
+BT +2728+08939 Asia/Thimphu
+BW -2439+02555 Africa/Gaborone
+BY +5354+02734 Europe/Minsk
+BZ +1730-08812 America/Belize
+CA +4734-05243 America/St_Johns Newfoundland, Labrador (SE)
+CA +4439-06336 America/Halifax Atlantic - NS (most areas), PE
+CA +4612-05957 America/Glace_Bay Atlantic - NS (Cape Breton)
+CA +4606-06447 America/Moncton Atlantic - New Brunswick
+CA +5320-06025 America/Goose_Bay Atlantic - Labrador (most areas)
+CA +5125-05707 America/Blanc-Sablon AST - QC (Lower North Shore)
+CA +4339-07923 America/Toronto Eastern - ON & QC (most areas)
+CA +6344-06828 America/Iqaluit Eastern - NU (most areas)
+CA +484531-0913718 America/Atikokan EST - ON (Atikokan), NU (Coral H)
+CA +4953-09709 America/Winnipeg Central - ON (west), Manitoba
+CA +744144-0944945 America/Resolute Central - NU (Resolute)
+CA +624900-0920459 America/Rankin_Inlet Central - NU (central)
+CA +5024-10439 America/Regina CST - SK (most areas)
+CA +5017-10750 America/Swift_Current CST - SK (midwest)
+CA +5333-11328 America/Edmonton Mountain - AB, BC(E), NT(E), SK(W)
+CA +690650-1050310 America/Cambridge_Bay Mountain - NU (west)
+CA +682059-1334300 America/Inuvik Mountain - NT (west)
+CA +4906-11631 America/Creston MST - BC (Creston)
+CA +5546-12014 America/Dawson_Creek MST - BC (Dawson Cr, Ft St John)
+CA +5848-12242 America/Fort_Nelson MST - BC (Ft Nelson)
+CA +6043-13503 America/Whitehorse MST - Yukon (east)
+CA +6404-13925 America/Dawson MST - Yukon (west)
+CA +4916-12307 America/Vancouver Pacific - BC (most areas)
+CC -1210+09655 Indian/Cocos
+CD -0418+01518 Africa/Kinshasa Dem. Rep. of Congo (west)
+CD -1140+02728 Africa/Lubumbashi Dem. Rep. of Congo (east)
+CF +0422+01835 Africa/Bangui
+CG -0416+01517 Africa/Brazzaville
+CH +4723+00832 Europe/Zurich
+CI +0519-00402 Africa/Abidjan
+CK -2114-15946 Pacific/Rarotonga
+CL -3327-07040 America/Santiago most of Chile
+CL -4534-07204 America/Coyhaique Aysen Region
+CL -5309-07055 America/Punta_Arenas Magallanes Region
+CL -2709-10926 Pacific/Easter Easter Island
+CM +0403+00942 Africa/Douala
+CN +3114+12128 Asia/Shanghai Beijing Time
+CN +4348+08735 Asia/Urumqi Xinjiang Time
+CO +0436-07405 America/Bogota
+CR +0956-08405 America/Costa_Rica
+CU +2308-08222 America/Havana
+CV +1455-02331 Atlantic/Cape_Verde
+CW +1211-06900 America/Curacao
+CX -1025+10543 Indian/Christmas
+CY +3510+03322 Asia/Nicosia most of Cyprus
+CY +3507+03357 Asia/Famagusta Northern Cyprus
+CZ +5005+01426 Europe/Prague
+DE +5230+01322 Europe/Berlin most of Germany
+DE +4742+00841 Europe/Busingen Busingen
+DJ +1136+04309 Africa/Djibouti
+DK +5540+01235 Europe/Copenhagen
+DM +1518-06124 America/Dominica
+DO +1828-06954 America/Santo_Domingo
+DZ +3647+00303 Africa/Algiers
+EC -0210-07950 America/Guayaquil Ecuador (mainland)
+EC -0054-08936 Pacific/Galapagos Galapagos Islands
+EE +5925+02445 Europe/Tallinn
+EG +3003+03115 Africa/Cairo
+EH +2709-01312 Africa/El_Aaiun
+ER +1520+03853 Africa/Asmara
+ES +4024-00341 Europe/Madrid Spain (mainland)
+ES +3553-00519 Africa/Ceuta Ceuta, Melilla
+ES +2806-01524 Atlantic/Canary Canary Islands
+ET +0902+03842 Africa/Addis_Ababa
+FI +6010+02458 Europe/Helsinki
+FJ -1808+17825 Pacific/Fiji
+FK -5142-05751 Atlantic/Stanley
+FM +0725+15147 Pacific/Chuuk Chuuk/Truk, Yap
+FM +0658+15813 Pacific/Pohnpei Pohnpei/Ponape
+FM +0519+16259 Pacific/Kosrae Kosrae
+FO +6201-00646 Atlantic/Faroe
+FR +4852+00220 Europe/Paris
+GA +0023+00927 Africa/Libreville
+GB +513030-0000731 Europe/London
+GD +1203-06145 America/Grenada
+GE +4143+04449 Asia/Tbilisi
+GF +0456-05220 America/Cayenne
+GG +492717-0023210 Europe/Guernsey
+GH +0533-00013 Africa/Accra
+GI +3608-00521 Europe/Gibraltar
+GL +6411-05144 America/Nuuk most of Greenland
+GL +7646-01840 America/Danmarkshavn National Park (east coast)
+GL +7029-02158 America/Scoresbysund Scoresbysund/Ittoqqortoormiit
+GL +7634-06847 America/Thule Thule/Pituffik
+GM +1328-01639 Africa/Banjul
+GN +0931-01343 Africa/Conakry
+GP +1614-06132 America/Guadeloupe
+GQ +0345+00847 Africa/Malabo
+GR +3758+02343 Europe/Athens
+GS -5416-03632 Atlantic/South_Georgia
+GT +1438-09031 America/Guatemala
+GU +1328+14445 Pacific/Guam
+GW +1151-01535 Africa/Bissau
+GY +0648-05810 America/Guyana
+HK +2217+11409 Asia/Hong_Kong
+HN +1406-08713 America/Tegucigalpa
+HR +4548+01558 Europe/Zagreb
+HT +1832-07220 America/Port-au-Prince
+HU +4730+01905 Europe/Budapest
+ID -0610+10648 Asia/Jakarta Java, Sumatra
+ID -0002+10920 Asia/Pontianak Borneo (west, central)
+ID -0507+11924 Asia/Makassar Borneo (east, south), Sulawesi/Celebes, Bali, Nusa Tengarra, Timor (west)
+ID -0232+14042 Asia/Jayapura New Guinea (West Papua / Irian Jaya), Malukus/Moluccas
+IE +5320-00615 Europe/Dublin
+IL +314650+0351326 Asia/Jerusalem
+IM +5409-00428 Europe/Isle_of_Man
+IN +2232+08822 Asia/Kolkata
+IO -0720+07225 Indian/Chagos
+IQ +3321+04425 Asia/Baghdad
+IR +3540+05126 Asia/Tehran
+IS +6409-02151 Atlantic/Reykjavik
+IT +4154+01229 Europe/Rome
+JE +491101-0020624 Europe/Jersey
+JM +175805-0764736 America/Jamaica
+JO +3157+03556 Asia/Amman
+JP +353916+1394441 Asia/Tokyo
+KE -0117+03649 Africa/Nairobi
+KG +4254+07436 Asia/Bishkek
+KH +1133+10455 Asia/Phnom_Penh
+KI +0125+17300 Pacific/Tarawa Gilbert Islands
+KI -0247-17143 Pacific/Kanton Phoenix Islands
+KI +0152-15720 Pacific/Kiritimati Line Islands
+KM -1141+04316 Indian/Comoro
+KN +1718-06243 America/St_Kitts
+KP +3901+12545 Asia/Pyongyang
+KR +3733+12658 Asia/Seoul
+KW +2920+04759 Asia/Kuwait
+KY +1918-08123 America/Cayman
+KZ +4315+07657 Asia/Almaty most of Kazakhstan
+KZ +4448+06528 Asia/Qyzylorda Qyzylorda/Kyzylorda/Kzyl-Orda
+KZ +5312+06337 Asia/Qostanay Qostanay/Kostanay/Kustanay
+KZ +5017+05710 Asia/Aqtobe Aqtobe/Aktobe
+KZ +4431+05016 Asia/Aqtau Mangghystau/Mankistau
+KZ +4707+05156 Asia/Atyrau Atyrau/Atirau/Gur'yev
+KZ +5113+05121 Asia/Oral West Kazakhstan
+LA +1758+10236 Asia/Vientiane
+LB +3353+03530 Asia/Beirut
+LC +1401-06100 America/St_Lucia
+LI +4709+00931 Europe/Vaduz
+LK +0656+07951 Asia/Colombo
+LR +0618-01047 Africa/Monrovia
+LS -2928+02730 Africa/Maseru
+LT +5441+02519 Europe/Vilnius
+LU +4936+00609 Europe/Luxembourg
+LV +5657+02406 Europe/Riga
+LY +3254+01311 Africa/Tripoli
+MA +3339-00735 Africa/Casablanca
+MC +4342+00723 Europe/Monaco
+MD +4700+02850 Europe/Chisinau
+ME +4226+01916 Europe/Podgorica
+MF +1804-06305 America/Marigot
+MG -1855+04731 Indian/Antananarivo
+MH +0709+17112 Pacific/Majuro most of Marshall Islands
+MH +0905+16720 Pacific/Kwajalein Kwajalein
+MK +4159+02126 Europe/Skopje
+ML +1239-00800 Africa/Bamako
+MM +1647+09610 Asia/Yangon
+MN +4755+10653 Asia/Ulaanbaatar most of Mongolia
+MN +4801+09139 Asia/Hovd Bayan-Olgii, Hovd, Uvs
+MO +221150+1133230 Asia/Macau
+MP +1512+14545 Pacific/Saipan
+MQ +1436-06105 America/Martinique
+MR +1806-01557 Africa/Nouakchott
+MS +1643-06213 America/Montserrat
+MT +3554+01431 Europe/Malta
+MU -2010+05730 Indian/Mauritius
+MV +0410+07330 Indian/Maldives
+MW -1547+03500 Africa/Blantyre
+MX +1924-09909 America/Mexico_City Central Mexico
+MX +2105-08646 America/Cancun Quintana Roo
+MX +2058-08937 America/Merida Campeche, Yucatan
+MX +2540-10019 America/Monterrey Durango; Coahuila, Nuevo Leon, Tamaulipas (most areas)
+MX +2550-09730 America/Matamoros Coahuila, Nuevo Leon, Tamaulipas (US border)
+MX +2838-10605 America/Chihuahua Chihuahua (most areas)
+MX +3144-10629 America/Ciudad_Juarez Chihuahua (US border - west)
+MX +2934-10425 America/Ojinaga Chihuahua (US border - east)
+MX +2313-10625 America/Mazatlan Baja California Sur, Nayarit (most areas), Sinaloa
+MX +2048-10515 America/Bahia_Banderas Bahia de Banderas
+MX +2904-11058 America/Hermosillo Sonora
+MX +3232-11701 America/Tijuana Baja California
+MY +0310+10142 Asia/Kuala_Lumpur Malaysia (peninsula)
+MY +0133+11020 Asia/Kuching Sabah, Sarawak
+MZ -2558+03235 Africa/Maputo
+NA -2234+01706 Africa/Windhoek
+NC -2216+16627 Pacific/Noumea
+NE +1331+00207 Africa/Niamey
+NF -2903+16758 Pacific/Norfolk
+NG +0627+00324 Africa/Lagos
+NI +1209-08617 America/Managua
+NL +5222+00454 Europe/Amsterdam
+NO +5955+01045 Europe/Oslo
+NP +2743+08519 Asia/Kathmandu
+NR -0031+16655 Pacific/Nauru
+NU -1901-16955 Pacific/Niue
+NZ -3652+17446 Pacific/Auckland most of New Zealand
+NZ -4357-17633 Pacific/Chatham Chatham Islands
+OM +2336+05835 Asia/Muscat
+PA +0858-07932 America/Panama
+PE -1203-07703 America/Lima
+PF -1732-14934 Pacific/Tahiti Society Islands
+PF -0900-13930 Pacific/Marquesas Marquesas Islands
+PF -2308-13457 Pacific/Gambier Gambier Islands
+PG -0930+14710 Pacific/Port_Moresby most of Papua New Guinea
+PG -0613+15534 Pacific/Bougainville Bougainville
+PH +143512+1205804 Asia/Manila
+PK +2452+06703 Asia/Karachi
+PL +5215+02100 Europe/Warsaw
+PM +4703-05620 America/Miquelon
+PN -2504-13005 Pacific/Pitcairn
+PR +182806-0660622 America/Puerto_Rico
+PS +3130+03428 Asia/Gaza Gaza Strip
+PS +313200+0350542 Asia/Hebron West Bank
+PT +3843-00908 Europe/Lisbon Portugal (mainland)
+PT +3238-01654 Atlantic/Madeira Madeira Islands
+PT +3744-02540 Atlantic/Azores Azores
+PW +0720+13429 Pacific/Palau
+PY -2516-05740 America/Asuncion
+QA +2517+05132 Asia/Qatar
+RE -2052+05528 Indian/Reunion
+RO +4426+02606 Europe/Bucharest
+RS +4450+02030 Europe/Belgrade
+RU +5443+02030 Europe/Kaliningrad MSK-01 - Kaliningrad
+RU +554521+0373704 Europe/Moscow MSK+00 - Moscow area
+# The obsolescent zone.tab format cannot represent Europe/Simferopol well.
+# Put it in RU section and list as UA. See "territorial claims" above.
+# Programs should use zone1970.tab instead; see above.
+UA +4457+03406 Europe/Simferopol Crimea
+RU +5836+04939 Europe/Kirov MSK+00 - Kirov
+RU +4844+04425 Europe/Volgograd MSK+00 - Volgograd
+RU +4621+04803 Europe/Astrakhan MSK+01 - Astrakhan
+RU +5134+04602 Europe/Saratov MSK+01 - Saratov
+RU +5420+04824 Europe/Ulyanovsk MSK+01 - Ulyanovsk
+RU +5312+05009 Europe/Samara MSK+01 - Samara, Udmurtia
+RU +5651+06036 Asia/Yekaterinburg MSK+02 - Urals
+RU +5500+07324 Asia/Omsk MSK+03 - Omsk
+RU +5502+08255 Asia/Novosibirsk MSK+04 - Novosibirsk
+RU +5322+08345 Asia/Barnaul MSK+04 - Altai
+RU +5630+08458 Asia/Tomsk MSK+04 - Tomsk
+RU +5345+08707 Asia/Novokuznetsk MSK+04 - Kemerovo
+RU +5601+09250 Asia/Krasnoyarsk MSK+04 - Krasnoyarsk area
+RU +5216+10420 Asia/Irkutsk MSK+05 - Irkutsk, Buryatia
+RU +5203+11328 Asia/Chita MSK+06 - Zabaykalsky
+RU +6200+12940 Asia/Yakutsk MSK+06 - Lena River
+RU +623923+1353314 Asia/Khandyga MSK+06 - Tomponsky, Ust-Maysky
+RU +4310+13156 Asia/Vladivostok MSK+07 - Amur River
+RU +643337+1431336 Asia/Ust-Nera MSK+07 - Oymyakonsky
+RU +5934+15048 Asia/Magadan MSK+08 - Magadan
+RU +4658+14242 Asia/Sakhalin MSK+08 - Sakhalin Island
+RU +6728+15343 Asia/Srednekolymsk MSK+08 - Sakha (E), N Kuril Is
+RU +5301+15839 Asia/Kamchatka MSK+09 - Kamchatka
+RU +6445+17729 Asia/Anadyr MSK+09 - Bering Sea
+RW -0157+03004 Africa/Kigali
+SA +2438+04643 Asia/Riyadh
+SB -0932+16012 Pacific/Guadalcanal
+SC -0440+05528 Indian/Mahe
+SD +1536+03232 Africa/Khartoum
+SE +5920+01803 Europe/Stockholm
+SG +0117+10351 Asia/Singapore
+SH -1555-00542 Atlantic/St_Helena
+SI +4603+01431 Europe/Ljubljana
+SJ +7800+01600 Arctic/Longyearbyen
+SK +4809+01707 Europe/Bratislava
+SL +0830-01315 Africa/Freetown
+SM +4355+01228 Europe/San_Marino
+SN +1440-01726 Africa/Dakar
+SO +0204+04522 Africa/Mogadishu
+SR +0550-05510 America/Paramaribo
+SS +0451+03137 Africa/Juba
+ST +0020+00644 Africa/Sao_Tome
+SV +1342-08912 America/El_Salvador
+SX +180305-0630250 America/Lower_Princes
+SY +3330+03618 Asia/Damascus
+SZ -2618+03106 Africa/Mbabane
+TC +2128-07108 America/Grand_Turk
+TD +1207+01503 Africa/Ndjamena
+TF -492110+0701303 Indian/Kerguelen
+TG +0608+00113 Africa/Lome
+TH +1345+10031 Asia/Bangkok
+TJ +3835+06848 Asia/Dushanbe
+TK -0922-17114 Pacific/Fakaofo
+TL -0833+12535 Asia/Dili
+TM +3757+05823 Asia/Ashgabat
+TN +3648+01011 Africa/Tunis
+TO -210800-1751200 Pacific/Tongatapu
+TR +4101+02858 Europe/Istanbul
+TT +1039-06131 America/Port_of_Spain
+TV -0831+17913 Pacific/Funafuti
+TW +2503+12130 Asia/Taipei
+TZ -0648+03917 Africa/Dar_es_Salaam
+UA +5026+03031 Europe/Kyiv most of Ukraine
+UG +0019+03225 Africa/Kampala
+UM +2813-17722 Pacific/Midway Midway Islands
+UM +1917+16637 Pacific/Wake Wake Island
+US +404251-0740023 America/New_York Eastern (most areas)
+US +421953-0830245 America/Detroit Eastern - MI (most areas)
+US +381515-0854534 America/Kentucky/Louisville Eastern - KY (Louisville area)
+US +364947-0845057 America/Kentucky/Monticello Eastern - KY (Wayne)
+US +394606-0860929 America/Indiana/Indianapolis Eastern - IN (most areas)
+US +384038-0873143 America/Indiana/Vincennes Eastern - IN (Da, Du, K, Mn)
+US +410305-0863611 America/Indiana/Winamac Eastern - IN (Pulaski)
+US +382232-0862041 America/Indiana/Marengo Eastern - IN (Crawford)
+US +382931-0871643 America/Indiana/Petersburg Eastern - IN (Pike)
+US +384452-0850402 America/Indiana/Vevay Eastern - IN (Switzerland)
+US +415100-0873900 America/Chicago Central (most areas)
+US +375711-0864541 America/Indiana/Tell_City Central - IN (Perry)
+US +411745-0863730 America/Indiana/Knox Central - IN (Starke)
+US +450628-0873651 America/Menominee Central - MI (Wisconsin border)
+US +470659-1011757 America/North_Dakota/Center Central - ND (Oliver)
+US +465042-1012439 America/North_Dakota/New_Salem Central - ND (Morton rural)
+US +471551-1014640 America/North_Dakota/Beulah Central - ND (Mercer)
+US +394421-1045903 America/Denver Mountain (most areas)
+US +433649-1161209 America/Boise Mountain - ID (south), OR (east)
+US +332654-1120424 America/Phoenix MST - AZ (except Navajo)
+US +340308-1181434 America/Los_Angeles Pacific
+US +611305-1495401 America/Anchorage Alaska (most areas)
+US +581807-1342511 America/Juneau Alaska - Juneau area
+US +571035-1351807 America/Sitka Alaska - Sitka area
+US +550737-1313435 America/Metlakatla Alaska - Annette Island
+US +593249-1394338 America/Yakutat Alaska - Yakutat
+US +643004-1652423 America/Nome Alaska (west)
+US +515248-1763929 America/Adak Alaska - western Aleutians
+US +211825-1575130 Pacific/Honolulu Hawaii
+UY -345433-0561245 America/Montevideo
+UZ +3940+06648 Asia/Samarkand Uzbekistan (west)
+UZ +4120+06918 Asia/Tashkent Uzbekistan (east)
+VA +415408+0122711 Europe/Vatican
+VC +1309-06114 America/St_Vincent
+VE +1030-06656 America/Caracas
+VG +1827-06437 America/Tortola
+VI +1821-06456 America/St_Thomas
+VN +1045+10640 Asia/Ho_Chi_Minh
+VU -1740+16825 Pacific/Efate
+WF -1318-17610 Pacific/Wallis
+WS -1350-17144 Pacific/Apia
+YE +1245+04512 Asia/Aden
+YT -1247+04514 Indian/Mayotte
+ZA -2615+02800 Africa/Johannesburg
+ZM -1525+02817 Africa/Lusaka
+ZW -1750+03103 Africa/Harare
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/zone1970.tab b/python_embeded/Lib/site-packages/pytz/zoneinfo/zone1970.tab
new file mode 100644
index 0000000000000000000000000000000000000000..36535bdf5cfbdedfc70b4d7899de7351b8eb5070
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pytz/zoneinfo/zone1970.tab
@@ -0,0 +1,375 @@
+# tzdb timezone descriptions
+#
+# This file is in the public domain.
+#
+# From Paul Eggert (2018-06-27):
+# This file contains a table where each row stands for a timezone where
+# civil timestamps have agreed since 1970. Columns are separated by
+# a single tab. Lines beginning with '#' are comments. All text uses
+# UTF-8 encoding. The columns of the table are as follows:
+#
+# 1. The countries that overlap the timezone, as a comma-separated list
+# of ISO 3166 2-character country codes. See the file 'iso3166.tab'.
+# 2. Latitude and longitude of the timezone's principal location
+# in ISO 6709 sign-degrees-minutes-seconds format,
+# either ±DDMM±DDDMM or ±DDMMSS±DDDMMSS,
+# first latitude (+ is north), then longitude (+ is east).
+# 3. Timezone name used in value of TZ environment variable.
+# Please see the theory.html file for how these names are chosen.
+# If multiple timezones overlap a country, each has a row in the
+# table, with each column 1 containing the country code.
+# 4. Comments; present if and only if countries have multiple timezones,
+# and useful only for those countries. For example, the comments
+# for the row with countries CH,DE,LI and name Europe/Zurich
+# are useful only for DE, since CH and LI have no other timezones.
+#
+# If a timezone covers multiple countries, the most-populous city is used,
+# and that country is listed first in column 1; any other countries
+# are listed alphabetically by country code. The table is sorted
+# first by country code, then (if possible) by an order within the
+# country that (1) makes some geographical sense, and (2) puts the
+# most populous timezones first, where that does not contradict (1).
+#
+# This table is intended as an aid for users, to help them select timezones
+# appropriate for their practical needs. It is not intended to take or
+# endorse any position on legal or territorial claims.
+#
+#country-
+#codes coordinates TZ comments
+AD +4230+00131 Europe/Andorra
+AE,OM,RE,SC,TF +2518+05518 Asia/Dubai Crozet
+AF +3431+06912 Asia/Kabul
+AL +4120+01950 Europe/Tirane
+AM +4011+04430 Asia/Yerevan
+AQ -6617+11031 Antarctica/Casey Casey
+AQ -6835+07758 Antarctica/Davis Davis
+AQ -6736+06253 Antarctica/Mawson Mawson
+AQ -6448-06406 Antarctica/Palmer Palmer
+AQ -6734-06808 Antarctica/Rothera Rothera
+AQ -720041+0023206 Antarctica/Troll Troll
+AQ -7824+10654 Antarctica/Vostok Vostok
+AR -3436-05827 America/Argentina/Buenos_Aires Buenos Aires (BA, CF)
+AR -3124-06411 America/Argentina/Cordoba most areas: CB, CC, CN, ER, FM, MN, SE, SF
+AR -2447-06525 America/Argentina/Salta Salta (SA, LP, NQ, RN)
+AR -2411-06518 America/Argentina/Jujuy Jujuy (JY)
+AR -2649-06513 America/Argentina/Tucuman Tucumán (TM)
+AR -2828-06547 America/Argentina/Catamarca Catamarca (CT), Chubut (CH)
+AR -2926-06651 America/Argentina/La_Rioja La Rioja (LR)
+AR -3132-06831 America/Argentina/San_Juan San Juan (SJ)
+AR -3253-06849 America/Argentina/Mendoza Mendoza (MZ)
+AR -3319-06621 America/Argentina/San_Luis San Luis (SL)
+AR -5138-06913 America/Argentina/Rio_Gallegos Santa Cruz (SC)
+AR -5448-06818 America/Argentina/Ushuaia Tierra del Fuego (TF)
+AS,UM -1416-17042 Pacific/Pago_Pago Midway
+AT +4813+01620 Europe/Vienna
+AU -3133+15905 Australia/Lord_Howe Lord Howe Island
+AU -5430+15857 Antarctica/Macquarie Macquarie Island
+AU -4253+14719 Australia/Hobart Tasmania
+AU -3749+14458 Australia/Melbourne Victoria
+AU -3352+15113 Australia/Sydney New South Wales (most areas)
+AU -3157+14127 Australia/Broken_Hill New South Wales (Yancowinna)
+AU -2728+15302 Australia/Brisbane Queensland (most areas)
+AU -2016+14900 Australia/Lindeman Queensland (Whitsunday Islands)
+AU -3455+13835 Australia/Adelaide South Australia
+AU -1228+13050 Australia/Darwin Northern Territory
+AU -3157+11551 Australia/Perth Western Australia (most areas)
+AU -3143+12852 Australia/Eucla Western Australia (Eucla)
+AZ +4023+04951 Asia/Baku
+BB +1306-05937 America/Barbados
+BD +2343+09025 Asia/Dhaka
+BE,LU,NL +5050+00420 Europe/Brussels
+BG +4241+02319 Europe/Sofia
+BM +3217-06446 Atlantic/Bermuda
+BO -1630-06809 America/La_Paz
+BR -0351-03225 America/Noronha Atlantic islands
+BR -0127-04829 America/Belem Pará (east), Amapá
+BR -0343-03830 America/Fortaleza Brazil (northeast: MA, PI, CE, RN, PB)
+BR -0803-03454 America/Recife Pernambuco
+BR -0712-04812 America/Araguaina Tocantins
+BR -0940-03543 America/Maceio Alagoas, Sergipe
+BR -1259-03831 America/Bahia Bahia
+BR -2332-04637 America/Sao_Paulo Brazil (southeast: GO, DF, MG, ES, RJ, SP, PR, SC, RS)
+BR -2027-05437 America/Campo_Grande Mato Grosso do Sul
+BR -1535-05605 America/Cuiaba Mato Grosso
+BR -0226-05452 America/Santarem Pará (west)
+BR -0846-06354 America/Porto_Velho Rondônia
+BR +0249-06040 America/Boa_Vista Roraima
+BR -0308-06001 America/Manaus Amazonas (east)
+BR -0640-06952 America/Eirunepe Amazonas (west)
+BR -0958-06748 America/Rio_Branco Acre
+BT +2728+08939 Asia/Thimphu
+BY +5354+02734 Europe/Minsk
+BZ +1730-08812 America/Belize
+CA +4734-05243 America/St_Johns Newfoundland, Labrador (SE)
+CA +4439-06336 America/Halifax Atlantic - NS (most areas), PE
+CA +4612-05957 America/Glace_Bay Atlantic - NS (Cape Breton)
+CA +4606-06447 America/Moncton Atlantic - New Brunswick
+CA +5320-06025 America/Goose_Bay Atlantic - Labrador (most areas)
+CA,BS +4339-07923 America/Toronto Eastern - ON & QC (most areas)
+CA +6344-06828 America/Iqaluit Eastern - NU (most areas)
+CA +4953-09709 America/Winnipeg Central - ON (west), Manitoba
+CA +744144-0944945 America/Resolute Central - NU (Resolute)
+CA +624900-0920459 America/Rankin_Inlet Central - NU (central)
+CA +5024-10439 America/Regina CST - SK (most areas)
+CA +5017-10750 America/Swift_Current CST - SK (midwest)
+CA +5333-11328 America/Edmonton Mountain - AB, BC(E), NT(E), SK(W)
+CA +690650-1050310 America/Cambridge_Bay Mountain - NU (west)
+CA +682059-1334300 America/Inuvik Mountain - NT (west)
+CA +5546-12014 America/Dawson_Creek MST - BC (Dawson Cr, Ft St John)
+CA +5848-12242 America/Fort_Nelson MST - BC (Ft Nelson)
+CA +6043-13503 America/Whitehorse MST - Yukon (east)
+CA +6404-13925 America/Dawson MST - Yukon (west)
+CA +4916-12307 America/Vancouver Pacific - BC (most areas)
+CH,DE,LI +4723+00832 Europe/Zurich Büsingen
+CI,BF,GH,GM,GN,IS,ML,MR,SH,SL,SN,TG +0519-00402 Africa/Abidjan
+CK -2114-15946 Pacific/Rarotonga
+CL -3327-07040 America/Santiago most of Chile
+CL -4534-07204 America/Coyhaique Aysén Region
+CL -5309-07055 America/Punta_Arenas Magallanes Region
+CL -2709-10926 Pacific/Easter Easter Island
+CN +3114+12128 Asia/Shanghai Beijing Time
+CN +4348+08735 Asia/Urumqi Xinjiang Time
+CO +0436-07405 America/Bogota
+CR +0956-08405 America/Costa_Rica
+CU +2308-08222 America/Havana
+CV +1455-02331 Atlantic/Cape_Verde
+CY +3510+03322 Asia/Nicosia most of Cyprus
+CY +3507+03357 Asia/Famagusta Northern Cyprus
+CZ,SK +5005+01426 Europe/Prague
+DE,DK,NO,SE,SJ +5230+01322 Europe/Berlin most of Germany
+DO +1828-06954 America/Santo_Domingo
+DZ +3647+00303 Africa/Algiers
+EC -0210-07950 America/Guayaquil Ecuador (mainland)
+EC -0054-08936 Pacific/Galapagos Galápagos Islands
+EE +5925+02445 Europe/Tallinn
+EG +3003+03115 Africa/Cairo
+EH +2709-01312 Africa/El_Aaiun
+ES +4024-00341 Europe/Madrid Spain (mainland)
+ES +3553-00519 Africa/Ceuta Ceuta, Melilla
+ES +2806-01524 Atlantic/Canary Canary Islands
+FI,AX +6010+02458 Europe/Helsinki
+FJ -1808+17825 Pacific/Fiji
+FK -5142-05751 Atlantic/Stanley
+FM +0519+16259 Pacific/Kosrae Kosrae
+FO +6201-00646 Atlantic/Faroe
+FR,MC +4852+00220 Europe/Paris
+GB,GG,IM,JE +513030-0000731 Europe/London
+GE +4143+04449 Asia/Tbilisi
+GF +0456-05220 America/Cayenne
+GI +3608-00521 Europe/Gibraltar
+GL +6411-05144 America/Nuuk most of Greenland
+GL +7646-01840 America/Danmarkshavn National Park (east coast)
+GL +7029-02158 America/Scoresbysund Scoresbysund/Ittoqqortoormiit
+GL +7634-06847 America/Thule Thule/Pituffik
+GR +3758+02343 Europe/Athens
+GS -5416-03632 Atlantic/South_Georgia
+GT +1438-09031 America/Guatemala
+GU,MP +1328+14445 Pacific/Guam
+GW +1151-01535 Africa/Bissau
+GY +0648-05810 America/Guyana
+HK +2217+11409 Asia/Hong_Kong
+HN +1406-08713 America/Tegucigalpa
+HT +1832-07220 America/Port-au-Prince
+HU +4730+01905 Europe/Budapest
+ID -0610+10648 Asia/Jakarta Java, Sumatra
+ID -0002+10920 Asia/Pontianak Borneo (west, central)
+ID -0507+11924 Asia/Makassar Borneo (east, south), Sulawesi/Celebes, Bali, Nusa Tengarra, Timor (west)
+ID -0232+14042 Asia/Jayapura New Guinea (West Papua / Irian Jaya), Malukus/Moluccas
+IE +5320-00615 Europe/Dublin
+IL +314650+0351326 Asia/Jerusalem
+IN +2232+08822 Asia/Kolkata
+IO -0720+07225 Indian/Chagos
+IQ +3321+04425 Asia/Baghdad
+IR +3540+05126 Asia/Tehran
+IT,SM,VA +4154+01229 Europe/Rome
+JM +175805-0764736 America/Jamaica
+JO +3157+03556 Asia/Amman
+JP,AU +353916+1394441 Asia/Tokyo Eyre Bird Observatory
+KE,DJ,ER,ET,KM,MG,SO,TZ,UG,YT -0117+03649 Africa/Nairobi
+KG +4254+07436 Asia/Bishkek
+KI,MH,TV,UM,WF +0125+17300 Pacific/Tarawa Gilberts, Marshalls, Wake
+KI -0247-17143 Pacific/Kanton Phoenix Islands
+KI +0152-15720 Pacific/Kiritimati Line Islands
+KP +3901+12545 Asia/Pyongyang
+KR +3733+12658 Asia/Seoul
+KZ +4315+07657 Asia/Almaty most of Kazakhstan
+KZ +4448+06528 Asia/Qyzylorda Qyzylorda/Kyzylorda/Kzyl-Orda
+KZ +5312+06337 Asia/Qostanay Qostanay/Kostanay/Kustanay
+KZ +5017+05710 Asia/Aqtobe Aqtöbe/Aktobe
+KZ +4431+05016 Asia/Aqtau Mangghystaū/Mankistau
+KZ +4707+05156 Asia/Atyrau Atyraū/Atirau/Gur'yev
+KZ +5113+05121 Asia/Oral West Kazakhstan
+LB +3353+03530 Asia/Beirut
+LK +0656+07951 Asia/Colombo
+LR +0618-01047 Africa/Monrovia
+LT +5441+02519 Europe/Vilnius
+LV +5657+02406 Europe/Riga
+LY +3254+01311 Africa/Tripoli
+MA +3339-00735 Africa/Casablanca
+MD +4700+02850 Europe/Chisinau
+MH +0905+16720 Pacific/Kwajalein Kwajalein
+MM,CC +1647+09610 Asia/Yangon
+MN +4755+10653 Asia/Ulaanbaatar most of Mongolia
+MN +4801+09139 Asia/Hovd Bayan-Ölgii, Hovd, Uvs
+MO +221150+1133230 Asia/Macau
+MQ +1436-06105 America/Martinique
+MT +3554+01431 Europe/Malta
+MU -2010+05730 Indian/Mauritius
+MV,TF +0410+07330 Indian/Maldives Kerguelen, St Paul I, Amsterdam I
+MX +1924-09909 America/Mexico_City Central Mexico
+MX +2105-08646 America/Cancun Quintana Roo
+MX +2058-08937 America/Merida Campeche, Yucatán
+MX +2540-10019 America/Monterrey Durango; Coahuila, Nuevo León, Tamaulipas (most areas)
+MX +2550-09730 America/Matamoros Coahuila, Nuevo León, Tamaulipas (US border)
+MX +2838-10605 America/Chihuahua Chihuahua (most areas)
+MX +3144-10629 America/Ciudad_Juarez Chihuahua (US border - west)
+MX +2934-10425 America/Ojinaga Chihuahua (US border - east)
+MX +2313-10625 America/Mazatlan Baja California Sur, Nayarit (most areas), Sinaloa
+MX +2048-10515 America/Bahia_Banderas BahÃa de Banderas
+MX +2904-11058 America/Hermosillo Sonora
+MX +3232-11701 America/Tijuana Baja California
+MY,BN +0133+11020 Asia/Kuching Sabah, Sarawak
+MZ,BI,BW,CD,MW,RW,ZM,ZW -2558+03235 Africa/Maputo Central Africa Time
+NA -2234+01706 Africa/Windhoek
+NC -2216+16627 Pacific/Noumea
+NF -2903+16758 Pacific/Norfolk
+NG,AO,BJ,CD,CF,CG,CM,GA,GQ,NE +0627+00324 Africa/Lagos West Africa Time
+NI +1209-08617 America/Managua
+NP +2743+08519 Asia/Kathmandu
+NR -0031+16655 Pacific/Nauru
+NU -1901-16955 Pacific/Niue
+NZ,AQ -3652+17446 Pacific/Auckland New Zealand time
+NZ -4357-17633 Pacific/Chatham Chatham Islands
+PA,CA,KY +0858-07932 America/Panama EST - ON (Atikokan), NU (Coral H)
+PE -1203-07703 America/Lima
+PF -1732-14934 Pacific/Tahiti Society Islands
+PF -0900-13930 Pacific/Marquesas Marquesas Islands
+PF -2308-13457 Pacific/Gambier Gambier Islands
+PG,AQ,FM -0930+14710 Pacific/Port_Moresby Papua New Guinea (most areas), Chuuk, Yap, Dumont d'Urville
+PG -0613+15534 Pacific/Bougainville Bougainville
+PH +143512+1205804 Asia/Manila
+PK +2452+06703 Asia/Karachi
+PL +5215+02100 Europe/Warsaw
+PM +4703-05620 America/Miquelon
+PN -2504-13005 Pacific/Pitcairn
+PR,AG,CA,AI,AW,BL,BQ,CW,DM,GD,GP,KN,LC,MF,MS,SX,TT,VC,VG,VI +182806-0660622 America/Puerto_Rico AST - QC (Lower North Shore)
+PS +3130+03428 Asia/Gaza Gaza Strip
+PS +313200+0350542 Asia/Hebron West Bank
+PT +3843-00908 Europe/Lisbon Portugal (mainland)
+PT +3238-01654 Atlantic/Madeira Madeira Islands
+PT +3744-02540 Atlantic/Azores Azores
+PW +0720+13429 Pacific/Palau
+PY -2516-05740 America/Asuncion
+QA,BH +2517+05132 Asia/Qatar
+RO +4426+02606 Europe/Bucharest
+RS,BA,HR,ME,MK,SI +4450+02030 Europe/Belgrade
+RU +5443+02030 Europe/Kaliningrad MSK-01 - Kaliningrad
+RU +554521+0373704 Europe/Moscow MSK+00 - Moscow area
+# Mention RU and UA alphabetically. See "territorial claims" above.
+RU,UA +4457+03406 Europe/Simferopol Crimea
+RU +5836+04939 Europe/Kirov MSK+00 - Kirov
+RU +4844+04425 Europe/Volgograd MSK+00 - Volgograd
+RU +4621+04803 Europe/Astrakhan MSK+01 - Astrakhan
+RU +5134+04602 Europe/Saratov MSK+01 - Saratov
+RU +5420+04824 Europe/Ulyanovsk MSK+01 - Ulyanovsk
+RU +5312+05009 Europe/Samara MSK+01 - Samara, Udmurtia
+RU +5651+06036 Asia/Yekaterinburg MSK+02 - Urals
+RU +5500+07324 Asia/Omsk MSK+03 - Omsk
+RU +5502+08255 Asia/Novosibirsk MSK+04 - Novosibirsk
+RU +5322+08345 Asia/Barnaul MSK+04 - Altai
+RU +5630+08458 Asia/Tomsk MSK+04 - Tomsk
+RU +5345+08707 Asia/Novokuznetsk MSK+04 - Kemerovo
+RU +5601+09250 Asia/Krasnoyarsk MSK+04 - Krasnoyarsk area
+RU +5216+10420 Asia/Irkutsk MSK+05 - Irkutsk, Buryatia
+RU +5203+11328 Asia/Chita MSK+06 - Zabaykalsky
+RU +6200+12940 Asia/Yakutsk MSK+06 - Lena River
+RU +623923+1353314 Asia/Khandyga MSK+06 - Tomponsky, Ust-Maysky
+RU +4310+13156 Asia/Vladivostok MSK+07 - Amur River
+RU +643337+1431336 Asia/Ust-Nera MSK+07 - Oymyakonsky
+RU +5934+15048 Asia/Magadan MSK+08 - Magadan
+RU +4658+14242 Asia/Sakhalin MSK+08 - Sakhalin Island
+RU +6728+15343 Asia/Srednekolymsk MSK+08 - Sakha (E), N Kuril Is
+RU +5301+15839 Asia/Kamchatka MSK+09 - Kamchatka
+RU +6445+17729 Asia/Anadyr MSK+09 - Bering Sea
+SA,AQ,KW,YE +2438+04643 Asia/Riyadh Syowa
+SB,FM -0932+16012 Pacific/Guadalcanal Pohnpei
+SD +1536+03232 Africa/Khartoum
+SG,AQ,MY +0117+10351 Asia/Singapore peninsular Malaysia, Concordia
+SR +0550-05510 America/Paramaribo
+SS +0451+03137 Africa/Juba
+ST +0020+00644 Africa/Sao_Tome
+SV +1342-08912 America/El_Salvador
+SY +3330+03618 Asia/Damascus
+TC +2128-07108 America/Grand_Turk
+TD +1207+01503 Africa/Ndjamena
+TH,CX,KH,LA,VN +1345+10031 Asia/Bangkok north Vietnam
+TJ +3835+06848 Asia/Dushanbe
+TK -0922-17114 Pacific/Fakaofo
+TL -0833+12535 Asia/Dili
+TM +3757+05823 Asia/Ashgabat
+TN +3648+01011 Africa/Tunis
+TO -210800-1751200 Pacific/Tongatapu
+TR +4101+02858 Europe/Istanbul
+TW +2503+12130 Asia/Taipei
+UA +5026+03031 Europe/Kyiv most of Ukraine
+US +404251-0740023 America/New_York Eastern (most areas)
+US +421953-0830245 America/Detroit Eastern - MI (most areas)
+US +381515-0854534 America/Kentucky/Louisville Eastern - KY (Louisville area)
+US +364947-0845057 America/Kentucky/Monticello Eastern - KY (Wayne)
+US +394606-0860929 America/Indiana/Indianapolis Eastern - IN (most areas)
+US +384038-0873143 America/Indiana/Vincennes Eastern - IN (Da, Du, K, Mn)
+US +410305-0863611 America/Indiana/Winamac Eastern - IN (Pulaski)
+US +382232-0862041 America/Indiana/Marengo Eastern - IN (Crawford)
+US +382931-0871643 America/Indiana/Petersburg Eastern - IN (Pike)
+US +384452-0850402 America/Indiana/Vevay Eastern - IN (Switzerland)
+US +415100-0873900 America/Chicago Central (most areas)
+US +375711-0864541 America/Indiana/Tell_City Central - IN (Perry)
+US +411745-0863730 America/Indiana/Knox Central - IN (Starke)
+US +450628-0873651 America/Menominee Central - MI (Wisconsin border)
+US +470659-1011757 America/North_Dakota/Center Central - ND (Oliver)
+US +465042-1012439 America/North_Dakota/New_Salem Central - ND (Morton rural)
+US +471551-1014640 America/North_Dakota/Beulah Central - ND (Mercer)
+US +394421-1045903 America/Denver Mountain (most areas)
+US +433649-1161209 America/Boise Mountain - ID (south), OR (east)
+US,CA +332654-1120424 America/Phoenix MST - AZ (most areas), Creston BC
+US +340308-1181434 America/Los_Angeles Pacific
+US +611305-1495401 America/Anchorage Alaska (most areas)
+US +581807-1342511 America/Juneau Alaska - Juneau area
+US +571035-1351807 America/Sitka Alaska - Sitka area
+US +550737-1313435 America/Metlakatla Alaska - Annette Island
+US +593249-1394338 America/Yakutat Alaska - Yakutat
+US +643004-1652423 America/Nome Alaska (west)
+US +515248-1763929 America/Adak Alaska - western Aleutians
+US +211825-1575130 Pacific/Honolulu Hawaii
+UY -345433-0561245 America/Montevideo
+UZ +3940+06648 Asia/Samarkand Uzbekistan (west)
+UZ +4120+06918 Asia/Tashkent Uzbekistan (east)
+VE +1030-06656 America/Caracas
+VN +1045+10640 Asia/Ho_Chi_Minh south Vietnam
+VU -1740+16825 Pacific/Efate
+WS -1350-17144 Pacific/Apia
+ZA,LS,SZ -2615+02800 Africa/Johannesburg
+#
+# The next section contains experimental tab-separated comments for
+# use by user agents like tzselect that identify continents and oceans.
+#
+# For example, the comment "#@AQAntarctica/" means the country code
+# AQ is in the continent Antarctica regardless of the Zone name,
+# so Pacific/Auckland should be listed under Antarctica as well as
+# under the Pacific because its line's country codes include AQ.
+#
+# If more than one country code is affected each is listed separated
+# by commas, e.g., #@IS,SHAtlantic/". If a country code is in
+# more than one continent or ocean, each is listed separated by
+# commas, e.g., the second column of "#@CY,TRAsia/,Europe/".
+#
+# These experimental comments are present only for country codes where
+# the continent or ocean is not already obvious from the Zone name.
+# For example, there is no such comment for RU since it already
+# corresponds to Zone names starting with both "Europe/" and "Asia/".
+#
+#@AQ Antarctica/
+#@IS,SH Atlantic/
+#@CY,TR Asia/,Europe/
+#@SJ Arctic/
+#@CC,CX,KM,MG,YT Indian/
diff --git a/python_embeded/Lib/site-packages/pytz/zoneinfo/zonenow.tab b/python_embeded/Lib/site-packages/pytz/zoneinfo/zonenow.tab
new file mode 100644
index 0000000000000000000000000000000000000000..093f0a0cb7495b5d50751bc0cb5b22df4a67c763
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pytz/zoneinfo/zonenow.tab
@@ -0,0 +1,296 @@
+# tzdb timezone descriptions, for users who do not care about old timestamps
+#
+# This file is in the public domain.
+#
+# From Paul Eggert (2023-12-18):
+# This file contains a table where each row stands for a timezone
+# where civil timestamps are predicted to agree from now on.
+# This file is like zone1970.tab (see zone1970.tab's comments),
+# but with the following changes:
+#
+# 1. Each timezone corresponds to a set of clocks that are planned
+# to agree from now on. This is a larger set of clocks than in
+# zone1970.tab, where each timezone's clocks must agree from 1970 on.
+# 2. The first column is irrelevant and ignored.
+# 3. The table is sorted in a different way:
+# first by standard time UTC offset;
+# then, if DST is used, by daylight saving UTC offset;
+# then by time zone abbreviation.
+# 4. Every timezone has a nonempty comments column, with wording
+# distinguishing the timezone only from other timezones with the
+# same UTC offset at some point during the year.
+#
+# The format of this table is experimental, and may change in future versions.
+#
+# This table is intended as an aid for users, to help them select timezones
+# appropriate for their practical needs. It is not intended to take or
+# endorse any position on legal or territorial claims.
+#
+#XX coordinates TZ comments
+#
+# -11 - SST
+XX -1416-17042 Pacific/Pago_Pago Midway; Samoa ("SST")
+#
+# -11
+XX -1901-16955 Pacific/Niue Niue
+#
+# -10 - HST
+XX +211825-1575130 Pacific/Honolulu Hawaii ("HST")
+#
+# -10
+XX -1732-14934 Pacific/Tahiti Tahiti; Cook Islands
+#
+# -10/-09 - HST / HDT (North America DST)
+XX +515248-1763929 America/Adak western Aleutians in Alaska ("HST/HDT")
+#
+# -09:30
+XX -0900-13930 Pacific/Marquesas Marquesas
+#
+# -09
+XX -2308-13457 Pacific/Gambier Gambier
+#
+# -09/-08 - AKST/AKDT (North America DST)
+XX +611305-1495401 America/Anchorage most of Alaska ("AKST/AKDT")
+#
+# -08
+XX -2504-13005 Pacific/Pitcairn Pitcairn
+#
+# -08/-07 - PST/PDT (North America DST)
+XX +340308-1181434 America/Los_Angeles Pacific ("PST/PDT") - US & Canada; Mexico near US border
+#
+# -07 - MST
+XX +332654-1120424 America/Phoenix Mountain Standard ("MST") - Arizona; western Mexico; Yukon
+#
+# -07/-06 - MST/MDT (North America DST)
+XX +394421-1045903 America/Denver Mountain ("MST/MDT") - US & Canada; Mexico near US border
+#
+# -06
+XX -0054-08936 Pacific/Galapagos Galápagos
+#
+# -06 - CST
+XX +1924-09909 America/Mexico_City Central Standard ("CST") - Saskatchewan; central Mexico; Central America
+#
+# -06/-05 (Chile DST)
+XX -2709-10926 Pacific/Easter Easter Island
+#
+# -06/-05 - CST/CDT (North America DST)
+XX +415100-0873900 America/Chicago Central ("CST/CDT") - US & Canada; Mexico near US border
+#
+# -05
+XX -1203-07703 America/Lima eastern South America
+#
+# -05 - EST
+XX +175805-0764736 America/Jamaica Eastern Standard ("EST") - Caymans; Jamaica; eastern Mexico; Panama
+#
+# -05/-04 - CST/CDT (Cuba DST)
+XX +2308-08222 America/Havana Cuba
+#
+# -05/-04 - EST/EDT (North America DST)
+XX +404251-0740023 America/New_York Eastern ("EST/EDT") - US & Canada
+#
+# -04
+XX +1030-06656 America/Caracas western South America
+#
+# -04 - AST
+XX +1828-06954 America/Santo_Domingo Atlantic Standard ("AST") - eastern Caribbean
+#
+# -04/-03 (Chile DST)
+XX -3327-07040 America/Santiago most of Chile
+#
+# -04/-03 - AST/ADT (North America DST)
+XX +4439-06336 America/Halifax Atlantic ("AST/ADT") - Canada; Bermuda
+#
+# -03:30/-02:30 - NST/NDT (North America DST)
+XX +4734-05243 America/St_Johns Newfoundland ("NST/NDT")
+#
+# -03
+XX -2332-04637 America/Sao_Paulo eastern and southern South America
+#
+# -03/-02 (North America DST)
+XX +4703-05620 America/Miquelon St Pierre & Miquelon
+#
+# -02
+XX -0351-03225 America/Noronha Fernando de Noronha; South Georgia
+#
+# -02/-01 (EU DST)
+XX +6411-05144 America/Nuuk most of Greenland
+#
+# -01
+XX +1455-02331 Atlantic/Cape_Verde Cape Verde
+#
+# -01/+00 (EU DST)
+XX +3744-02540 Atlantic/Azores Azores
+#
+# +00 - GMT
+XX +0519-00402 Africa/Abidjan far western Africa; Iceland ("GMT")
+#
+# +00/+01 - GMT/BST (EU DST)
+XX +513030-0000731 Europe/London United Kingdom ("GMT/BST")
+#
+# +00/+01 - WET/WEST (EU DST)
+XX +3843-00908 Europe/Lisbon western Europe ("WET/WEST")
+#
+# +00/+02 - Troll DST
+XX -720041+0023206 Antarctica/Troll Troll Station in Antarctica
+#
+# +01 - CET
+XX +3647+00303 Africa/Algiers Algeria, Tunisia ("CET")
+#
+# +01 - WAT
+XX +0627+00324 Africa/Lagos western Africa ("WAT")
+#
+# +01/+00 - IST/GMT (EU DST in reverse)
+XX +5320-00615 Europe/Dublin Ireland ("IST/GMT")
+#
+# +01/+00 - (Morocco DST)
+XX +3339-00735 Africa/Casablanca Morocco
+#
+# +01/+02 - CET/CEST (EU DST)
+XX +4852+00220 Europe/Paris central Europe ("CET/CEST")
+#
+# +02 - CAT
+XX -2558+03235 Africa/Maputo central Africa ("CAT")
+#
+# +02 - EET
+XX +3254+01311 Africa/Tripoli Libya; Kaliningrad ("EET")
+#
+# +02 - SAST
+XX -2615+02800 Africa/Johannesburg southern Africa ("SAST")
+#
+# +02/+03 - EET/EEST (EU DST)
+XX +3758+02343 Europe/Athens eastern Europe ("EET/EEST")
+#
+# +02/+03 - EET/EEST (Egypt DST)
+XX +3003+03115 Africa/Cairo Egypt
+#
+# +02/+03 - EET/EEST (Lebanon DST)
+XX +3353+03530 Asia/Beirut Lebanon
+#
+# +02/+03 - EET/EEST (Moldova DST)
+XX +4700+02850 Europe/Chisinau Moldova
+#
+# +02/+03 - EET/EEST (Palestine DST)
+XX +3130+03428 Asia/Gaza Palestine
+#
+# +02/+03 - IST/IDT (Israel DST)
+XX +314650+0351326 Asia/Jerusalem Israel
+#
+# +03
+XX +4101+02858 Europe/Istanbul Near East; Belarus
+#
+# +03 - EAT
+XX -0117+03649 Africa/Nairobi eastern Africa ("EAT")
+#
+# +03 - MSK
+XX +554521+0373704 Europe/Moscow Moscow ("MSK")
+#
+# +03:30
+XX +3540+05126 Asia/Tehran Iran
+#
+# +04
+XX +2518+05518 Asia/Dubai Russia; Caucasus; Persian Gulf; Seychelles; Réunion
+#
+# +04:30
+XX +3431+06912 Asia/Kabul Afghanistan
+#
+# +05
+XX +4120+06918 Asia/Tashkent Russia; Kazakhstan; Tajikistan; Turkmenistan; Uzbekistan; Maldives
+#
+# +05 - PKT
+XX +2452+06703 Asia/Karachi Pakistan ("PKT")
+#
+# +05:30
+XX +0656+07951 Asia/Colombo Sri Lanka
+#
+# +05:30 - IST
+XX +2232+08822 Asia/Kolkata India ("IST")
+#
+# +05:45
+XX +2743+08519 Asia/Kathmandu Nepal
+#
+# +06
+XX +2343+09025 Asia/Dhaka Russia; Kyrgyzstan; Bhutan; Bangladesh; Chagos
+#
+# +06:30
+XX +1647+09610 Asia/Yangon Myanmar; Cocos
+#
+# +07
+XX +1345+10031 Asia/Bangkok Russia; Indochina; Christmas Island
+#
+# +07 - WIB
+XX -0610+10648 Asia/Jakarta Indonesia ("WIB")
+#
+# +08
+XX +0117+10351 Asia/Singapore Russia; Brunei; Malaysia; Singapore; Concordia
+#
+# +08 - AWST
+XX -3157+11551 Australia/Perth Western Australia ("AWST")
+#
+# +08 - CST
+XX +3114+12128 Asia/Shanghai China ("CST")
+#
+# +08 - HKT
+XX +2217+11409 Asia/Hong_Kong Hong Kong ("HKT")
+#
+# +08 - PHT
+XX +143512+1205804 Asia/Manila Philippines ("PHT")
+#
+# +08 - WITA
+XX -0507+11924 Asia/Makassar Indonesia ("WITA")
+#
+# +08:45
+XX -3143+12852 Australia/Eucla Eucla
+#
+# +09
+XX +5203+11328 Asia/Chita Russia; Palau; East Timor
+#
+# +09 - JST
+XX +353916+1394441 Asia/Tokyo Japan ("JST"); Eyre Bird Observatory
+#
+# +09 - KST
+XX +3733+12658 Asia/Seoul Korea ("KST")
+#
+# +09 - WIT
+XX -0232+14042 Asia/Jayapura Indonesia ("WIT")
+#
+# +09:30 - ACST
+XX -1228+13050 Australia/Darwin Northern Territory ("ACST")
+#
+# +09:30/+10:30 - ACST/ACDT (Australia DST)
+XX -3455+13835 Australia/Adelaide South Australia ("ACST/ACDT")
+#
+# +10
+XX +4310+13156 Asia/Vladivostok Russia; Yap; Chuuk; Papua New Guinea; Dumont d'Urville
+#
+# +10 - AEST
+XX -2728+15302 Australia/Brisbane Queensland ("AEST")
+#
+# +10 - ChST
+XX +1328+14445 Pacific/Guam Mariana Islands ("ChST")
+#
+# +10/+11 - AEST/AEDT (Australia DST)
+XX -3352+15113 Australia/Sydney southeast Australia ("AEST/AEDT")
+#
+# +10:30/+11
+XX -3133+15905 Australia/Lord_Howe Lord Howe Island
+#
+# +11
+XX -0613+15534 Pacific/Bougainville Russia; Kosrae; Bougainville; Solomons
+#
+# +11/+12 (Australia DST)
+XX -2903+16758 Pacific/Norfolk Norfolk Island
+#
+# +12
+XX +5301+15839 Asia/Kamchatka Russia; Tuvalu; Fiji; etc.
+#
+# +12/+13 (New Zealand DST)
+XX -3652+17446 Pacific/Auckland New Zealand ("NZST/NZDT")
+#
+# +12:45/+13:45 (Chatham DST)
+XX -4357-17633 Pacific/Chatham Chatham Islands
+#
+# +13
+XX -210800-1751200 Pacific/Tongatapu Kanton; Tokelau; Samoa (western); Tonga
+#
+# +14
+XX +0152-15720 Pacific/Kiritimati Kiritimati
diff --git a/python_embeded/Lib/site-packages/pywt/_extensions/_cwt.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/pywt/_extensions/_cwt.cp312-win_amd64.lib
new file mode 100644
index 0000000000000000000000000000000000000000..d9970be80e62e701624b4e9c5d96b0ff7d7f8645
Binary files /dev/null and b/python_embeded/Lib/site-packages/pywt/_extensions/_cwt.cp312-win_amd64.lib differ
diff --git a/python_embeded/Lib/site-packages/pywt/_extensions/_dwt.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/pywt/_extensions/_dwt.cp312-win_amd64.lib
new file mode 100644
index 0000000000000000000000000000000000000000..e12c4934ff08b47f5ffcb9b9d4b3c098a6ea7117
Binary files /dev/null and b/python_embeded/Lib/site-packages/pywt/_extensions/_dwt.cp312-win_amd64.lib differ
diff --git a/python_embeded/Lib/site-packages/pywt/_extensions/_pywt.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/pywt/_extensions/_pywt.cp312-win_amd64.lib
new file mode 100644
index 0000000000000000000000000000000000000000..599754f16e69fd8206b3c7030e82c869816bdf38
Binary files /dev/null and b/python_embeded/Lib/site-packages/pywt/_extensions/_pywt.cp312-win_amd64.lib differ
diff --git a/python_embeded/Lib/site-packages/pywt/_extensions/_swt.cp312-win_amd64.lib b/python_embeded/Lib/site-packages/pywt/_extensions/_swt.cp312-win_amd64.lib
new file mode 100644
index 0000000000000000000000000000000000000000..4a9a031808dcade84ca6347f9c77be477af6356b
Binary files /dev/null and b/python_embeded/Lib/site-packages/pywt/_extensions/_swt.cp312-win_amd64.lib differ
diff --git a/python_embeded/Lib/site-packages/pywt/data/__init__.py b/python_embeded/Lib/site-packages/pywt/data/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..85ae043fabfffe314135fd78bf5a74f13ad1189a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/data/__init__.py
@@ -0,0 +1,2 @@
+from ._readers import aero, ascent, camera, ecg, nino
+from ._wavelab_signals import demo_signal
diff --git a/python_embeded/Lib/site-packages/pywt/data/_readers.py b/python_embeded/Lib/site-packages/pywt/data/_readers.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a38450c0ad39321b793e4124698ba47dded5ab0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/data/_readers.py
@@ -0,0 +1,212 @@
+import functools
+import importlib.resources
+import os
+
+import numpy as np
+
+_DATADIR = importlib.resources.files('pywt.data')
+
+
+@functools.cache
+def ascent():
+ """
+ Get an 8-bit grayscale bit-depth, 512 x 512 derived image for
+ easy use in demos
+
+ The image is derived from accent-to-the-top.jpg at
+ http://www.public-domain-image.com/people-public-domain-images-pictures/
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ascent : ndarray
+ convenient image to use for testing and demonstration
+
+ Examples
+ --------
+ >>> import pywt.data
+ >>> ascent = pywt.data.ascent()
+ >>> ascent.shape == (512, 512)
+ True
+ >>> ascent.max()
+ 255
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.gray()
+ >>> plt.imshow(ascent)
+
+ >>> plt.show()
+
+ """
+ with importlib.resources.as_file(_DATADIR.joinpath('ascent.npz')) as f:
+ ascent = np.load(f)['data']
+
+ return ascent
+
+
+@functools.cache
+def aero():
+ """
+ Get an 8-bit grayscale bit-depth, 512 x 512 derived image for
+ easy use in demos
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ aero : ndarray
+ convenient image to use for testing and demonstration
+
+ Examples
+ --------
+ >>> import pywt.data
+ >>> aero = pywt.data.ascent()
+ >>> aero.shape == (512, 512)
+ True
+ >>> aero.max()
+ 255
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.gray()
+ >>> plt.imshow(aero)
+
+ >>> plt.show()
+
+ """
+ with importlib.resources.as_file(_DATADIR.joinpath('aero.npz')) as f:
+ aero = np.load(f)['data']
+
+ return aero
+
+
+@functools.cache
+def camera():
+ """
+ Get an 8-bit grayscale bit-depth, 512 x 512 derived image for
+ easy use in demos
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ camera : ndarray
+ convenient image to use for testing and demonstration
+
+ Notes
+ -----
+ No copyright restrictions. CC0 by the photographer (Lav Varshney).
+
+ .. versionchanged:: 0.18
+ This image was replaced due to copyright restrictions. For more
+ information, please see [1]_, where the same change was made in
+ scikit-image.
+
+ References
+ ----------
+ .. [1] https://github.com/scikit-image/scikit-image/issues/3927
+
+ Examples
+ --------
+ >>> import pywt.data
+ >>> camera = pywt.data.ascent()
+ >>> camera.shape == (512, 512)
+ True
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.gray()
+ >>> plt.imshow(camera)
+
+ >>> plt.show()
+
+ """
+ with importlib.resources.as_file(_DATADIR.joinpath('camera.npz')) as f:
+ camera = np.load(f)['data']
+
+ return camera
+
+
+@functools.cache
+def ecg():
+ """
+ Get 1024 points of an ECG timeseries.
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ ecg : ndarray
+ convenient timeseries to use for testing and demonstration
+
+ Examples
+ --------
+ >>> import pywt.data
+ >>> ecg = pywt.data.ecg()
+ >>> ecg.shape == (1024,)
+ True
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(ecg)
+ []
+ >>> plt.show()
+ """
+ with importlib.resources.as_file(_DATADIR.joinpath('ecg.npz')) as f:
+ ecg = np.load(f)['data']
+
+ return ecg
+
+
+@functools.cache
+def nino():
+ """
+ This data contains the averaged monthly sea surface temperature in degrees
+ Celsius of the Pacific Ocean, between 0-10 degrees South and 90-80 degrees West, from 1950 to 2016.
+ This dataset is in the public domain and was obtained from NOAA.
+ National Oceanic and Atmospheric Administration's National Weather Service
+ ERSSTv4 dataset, nino 3, http://www.cpc.ncep.noaa.gov/data/indices/
+
+ Parameters
+ ----------
+ None
+
+ Returns
+ -------
+ time : ndarray
+ convenient timeseries to use for testing and demonstration
+ sst : ndarray
+ convenient timeseries to use for testing and demonstration
+
+ Examples
+ --------
+ >>> import pywt.data
+ >>> time, sst = pywt.data.nino()
+ >>> sst.shape == (264,)
+ True
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(time,sst)
+ []
+ >>> plt.show()
+ """
+ with importlib.resources.as_file(_DATADIR.joinpath('sst_nino3.npz')) as f:
+ sst_csv = np.load(f)['data']
+
+ # sst_csv = pd.read_csv("http://www.cpc.ncep.noaa.gov/data/indices/ersst4.nino.mth.81-10.ascii", sep=' ', skipinitialspace=True)
+ # take only full years
+ n = int(np.floor(sst_csv.shape[0]/12.)*12.)
+ # Building the mean of three months
+ # the 4. column is nino 3
+ sst = np.mean(np.reshape(np.array(sst_csv)[:n, 4], (n//3, -1)), axis=1)
+ sst = (sst - np.mean(sst)) / np.std(sst, ddof=1)
+
+ dt = 0.25
+ time = np.arange(len(sst)) * dt + 1950.0 # construct time array
+ return time, sst
diff --git a/python_embeded/Lib/site-packages/pywt/data/_wavelab_signals.py b/python_embeded/Lib/site-packages/pywt/data/_wavelab_signals.py
new file mode 100644
index 0000000000000000000000000000000000000000..c48c2021add88e3f8c77467698b5b1ab4eac0f4d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/data/_wavelab_signals.py
@@ -0,0 +1,267 @@
+
+import numpy as np
+
+__all__ = ['demo_signal']
+
+_implemented_signals = [
+ 'Blocks',
+ 'Bumps',
+ 'HeaviSine',
+ 'Doppler',
+ 'Ramp',
+ 'HiSine',
+ 'LoSine',
+ 'LinChirp',
+ 'TwoChirp',
+ 'QuadChirp',
+ 'MishMash',
+ 'WernerSorrows',
+ 'HypChirps',
+ 'LinChirps',
+ 'Chirps',
+ 'Gabor',
+ 'sineoneoverx',
+ 'Piece-Regular',
+ 'Piece-Polynomial',
+ 'Riemann']
+
+
+def demo_signal(name='Bumps', n=None):
+ """Simple 1D wavelet test functions.
+
+ This function can generate a number of common 1D test signals used in
+ papers by David Donoho and colleagues (e.g. [1]_) as well as the wavelet
+ book by Stéphane Mallat [2]_.
+
+ Parameters
+ ----------
+ name : {'Blocks', 'Bumps', 'HeaviSine', 'Doppler', ...}
+ The type of test signal to generate (`name` is case-insensitive). If
+ `name` is set to `'list'`, a list of the available test functions is
+ returned.
+ n : int or None
+ The length of the test signal. This should be provided for all test
+ signals except `'Gabor'` and `'sineoneoverx'` which have a fixed
+ length.
+
+ Returns
+ -------
+ f : np.ndarray
+ Array of length ``n`` corresponding to the specified test signal type.
+
+ References
+ ----------
+ .. [1] D.L. Donoho and I.M. Johnstone. Ideal spatial adaptation by
+ wavelet shrinkage. Biometrika, vol. 81, pp. 425–455, 1994.
+ .. [2] S. Mallat. A Wavelet Tour of Signal Processing: The Sparse Way.
+ Academic Press. 2009.
+
+ Notes
+ -----
+ This function is a partial reimplementation of the `MakeSignal` function
+ from the [Wavelab](https://statweb.stanford.edu/~wavelab/) toolbox. These
+ test signals are provided with permission of Dr. Donoho to encourage
+ reproducible research.
+
+ Examples
+ --------
+ >>> import pywt
+ >>> camera = pywt.data.camera()
+ >>> doppler = pywt.data.demo_signal('doppler', 1024)
+ >>> available_signals = pywt.data.demo_signal('list')
+ >>> print(available_signals)
+ ['Blocks', 'Bumps', 'HeaviSine', 'Doppler', 'Ramp', 'HiSine', 'LoSine', 'LinChirp',
+ 'TwoChirp', 'QuadChirp', 'MishMash', 'WernerSorrows', 'HypChirps', 'LinChirps',
+ 'Chirps', 'Gabor', 'sineoneoverx', 'Piece-Regular', 'Piece-Polynomial', 'Riemann']
+
+ """
+ if name.lower() == 'list':
+ return _implemented_signals
+
+ if n is not None:
+ if n < 1 or (n % 1) != 0:
+ raise ValueError("n must be an integer >= 1")
+ t = np.arange(1/n, 1 + 1/n, 1/n)
+
+ # The following function types don't allow user-specified `n`.
+ n_hard_coded = ['gabor', 'sineoneoverx']
+
+ name = name.lower()
+ if name in n_hard_coded and n is not None:
+ raise ValueError(
+ f"Parameter n must be set to None when name is {name}")
+ elif n is None and name not in n_hard_coded:
+ raise ValueError(
+ f"Parameter n must be provided when name is {name}")
+
+ if name == 'blocks':
+ t0s = [.1, .13, .15, .23, .25, .4, .44, .65, .76, .78, .81]
+ hs = [4, -5, 3, -4, 5, -4.2, 2.1, 4.3, -3.1, 2.1, -4.2]
+ f = 0
+ for (t0, h) in zip(t0s, hs):
+ f += h * (1 + np.sign(t - t0)) / 2
+ elif name == 'bumps':
+ t0s = [.1, .13, .15, .23, .25, .4, .44, .65, .76, .78, .81]
+ hs = [4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 5.1, 4.2]
+ ws = [.005, .005, .006, .01, .01, .03, .01, .01, .005, .008, .005]
+ f = 0
+ for (t0, h, w) in zip(t0s, hs, ws):
+ f += h / (1 + np.abs((t - t0) / w))**4
+ elif name == 'heavisine':
+ f = 4 * np.sin(4 * np.pi * t) - np.sign(t - 0.3) - np.sign(0.72 - t)
+ elif name == 'doppler':
+ f = np.sqrt(t * (1 - t)) * np.sin(2 * np.pi * 1.05 / (t + 0.05))
+ elif name == 'ramp':
+ f = t - (t >= .37)
+ elif name == 'hisine':
+ f = np.sin(np.pi * (n * .6902) * t)
+ elif name == 'losine':
+ f = np.sin(np.pi * (n * .3333) * t)
+ elif name == 'linchirp':
+ f = np.sin(np.pi * t * ((n * .500) * t))
+ elif name == 'twochirp':
+ f = np.sin(np.pi * t * (n * t)) + np.sin((np.pi / 3) * t * (n * t))
+ elif name == 'quadchirp':
+ f = np.sin((np.pi / 3) * t * (n * t**2))
+ elif name == 'mishmash': # QuadChirp + LinChirp + HiSine
+ f = np.sin((np.pi / 3) * t * (n * t**2))
+ f += np.sin(np.pi * (n * .6902) * t)
+ f += np.sin(np.pi * t * (n * .125 * t))
+ elif name == 'wernersorrows':
+ f = np.sin(np.pi * t * (n / 2 * t**2))
+ f = f + np.sin(np.pi * (n * .6902) * t)
+ f = f + np.sin(np.pi * t * (n * t))
+ pos = [.1, .13, .15, .23, .25, .40, .44, .65, .76, .78, .81]
+ hgt = [4, 5, 3, 4, 5, 4.2, 2.1, 4.3, 3.1, 5.1, 4.2]
+ wth = [.005, .005, .006, .01, .01, .03, .01, .01, .005, .008, .005]
+ for p, h, w in zip(pos, hgt, wth):
+ f += h / (1 + np.abs((t - p) / w))**4
+ elif name == 'hypchirps': # Hyperbolic Chirps of Mallat's book
+ alpha = 15 * n * np.pi / 1024
+ beta = 5 * n * np.pi / 1024
+ t = np.arange(1.001, n + .001 + 1) / n
+ f1 = np.zeros(n)
+ f2 = np.zeros(n)
+ f1 = np.sin(alpha / (.8 - t)) * (0.1 < t) * (t < 0.68)
+ f2 = np.sin(beta / (.8 - t)) * (0.1 < t) * (t < 0.75)
+ m = int(np.round(0.65 * n))
+ p = m // 4
+ envelope = np.ones(m) # the rinp.sing cutoff function
+ tmp = np.arange(1, p + 1)-np.ones(p)
+ envelope[:p] = (1 + np.sin(-np.pi / 2 + tmp / (p - 1) * np.pi)) / 2
+ envelope[m-p:m] = envelope[:p][::-1]
+ env = np.zeros(n)
+ env[int(np.ceil(n / 10)) - 1:m + int(np.ceil(n / 10)) - 1] = \
+ envelope[:m]
+ f = (f1 + f2) * env
+ elif name == 'linchirps': # Linear Chirps of Mallat's book
+ b = 100 * n * np.pi / 1024
+ a = 250 * n * np.pi / 1024
+ t = np.arange(1, n + 1) / n
+ A1 = np.sqrt((t - 1 / n) * (1 - t))
+ f = A1 * (np.cos(a * t**2) + np.cos(b * t + a * t**2))
+ elif name == 'chirps': # Mixture of Chirps of Mallat's book
+ t = np.arange(1, n + 1)/n * 10 * np.pi
+ f1 = np.cos(t**2 * n / 1024)
+ a = 30 * n / 1024
+ t = np.arange(1, n + 1)/n * np.pi
+ f2 = np.cos(a * (t**3))
+ f2 = f2[::-1]
+ ix = np.arange(-n, n + 1) / n * 20
+ g = np.exp(-ix**2 * 4 * n / 1024)
+ i1 = slice(n // 2, n // 2 + n)
+ i2 = slice(n // 8, n // 8 + n)
+ j = np.arange(1, n + 1) / n
+ f3 = g[i1] * np.cos(50 * np.pi * j * n / 1024)
+ f4 = g[i2] * np.cos(350 * np.pi * j * n / 1024)
+ f = f1 + f2 + f3 + f4
+ envelope = np.ones(n) # the rinp.sing cutoff function
+ tmp = np.arange(1, n // 8 + 1) - np.ones(n // 8)
+ envelope[:n // 8] = (
+ 1 + np.sin(-np.pi / 2 + tmp / (n / 8 - 1) * np.pi)) / 2
+ envelope[7 * n // 8:n] = envelope[:n // 8][::-1]
+ f = f*envelope
+ elif name == 'gabor': # two modulated Gabor functions in Mallat's book
+ n = 512
+ t = np.arange(-n, n + 1)*5 / n
+ j = np.arange(1, n + 1) / n
+ g = np.exp(-t**2 * 20)
+ i1 = slice(2*n // 4, 2 * n // 4 + n)
+ i2 = slice(n // 4, n // 4 + n)
+ f1 = 3 * g[i1] * np.exp(1j * (n // 16) * np.pi * j)
+ f2 = 3 * g[i2] * np.exp(1j * (n // 4) * np.pi * j)
+ f = f1 + f2
+ elif name == 'sineoneoverx': # np.sin(1/x) in Mallat's book
+ n = 1024
+ i1 = np.arange(-n + 1, n + 1, dtype=float)
+ i1[i1 == 0] = 1 / 100
+ i1 = i1 / (n - 1)
+ f = np.sin(1.5 / i1)
+ f = f[512:1536]
+ elif name == 'piece-regular':
+ f = np.zeros(n)
+ n_12 = int(np.fix(n / 12))
+ n_7 = int(np.fix(n / 7))
+ n_5 = int(np.fix(n / 5))
+ n_3 = int(np.fix(n / 3))
+ n_2 = int(np.fix(n / 2))
+ n_20 = int(np.fix(n / 20))
+ f1 = -15 * demo_signal('bumps', n)
+ t = np.arange(1, n_12 + 1) / n_12
+ f2 = -np.exp(4 * t)
+ t = np.arange(1, n_7 + 1) / n_7
+ f5 = np.exp(4 * t)-np.exp(4)
+ t = np.arange(1, n_3 + 1) / n_3
+ fma = 6 / 40
+ f6 = -70 * np.exp(-((t - 0.5) * (t - 0.5)) / (2 * fma**2))
+ f[:n_7] = f6[:n_7]
+ f[n_7:n_5] = 0.5 * f6[n_7:n_5]
+ f[n_5:n_3] = f6[n_5:n_3]
+ f[n_3:n_2] = f1[n_3:n_2]
+ f[n_2:n_2 + n_12] = f2
+ f[n_2 + 2 * n_12 - 1:n_2 + n_12 - 1:-1] = f2
+ f[n_2 + 2 * n_12 + n_20:n_2 + 2 * n_12 + 3 * n_20] = -np.ones(
+ n_2 + 2*n_12 + 3*n_20 - n_2 - 2*n_12 - n_20) * 25
+ k = n_2 + 2 * n_12 + 3 * n_20
+ f[k:k + n_7] = f5
+ diff = n - 5 * n_5
+ f[5 * n_5:n] = f[diff - 1::-1]
+ # zero-mean
+ bias = np.sum(f) / n
+ f = bias - f
+ elif name == 'piece-polynomial':
+ f = np.zeros(n)
+ n_5 = int(np.fix(n / 5))
+ n_10 = int(np.fix(n / 10))
+ n_20 = int(np.fix(n / 20))
+ t = np.arange(1, n_5 + 1) / n_5
+ f1 = 20 * (t**3 + t**2 + 4)
+ f3 = 40 * (2 * t**3 + t) + 100
+ f2 = 10 * t**3 + 45
+ f4 = 16 * t**2 + 8 * t + 16
+ f5 = 20 * (t + 4)
+ f6 = np.ones(n_10) * 20
+ f[:n_5] = f1
+ f[2 * n_5 - 1:n_5 - 1:-1] = f2
+ f[2 * n_5:3 * n_5] = f3
+ f[3 * n_5:4 * n_5] = f4
+ f[4 * n_5:5 * n_5] = f5[n_5::-1]
+ diff = n - 5*n_5
+ f[5 * n_5:n] = f[diff - 1::-1]
+ f[n_20:n_20 + n_10] = np.ones(n_10) * 10
+ f[n - n_10:n + n_20 - n_10] = np.ones(n_20) * 150
+ # zero-mean
+ bias = np.sum(f) / n
+ f = f - bias
+ elif name == 'riemann':
+ # Riemann's Non-differentiable Function
+ sqn = int(np.round(np.sqrt(n)))
+ idx = np.arange(1, sqn + 1)
+ idx *= idx
+ f = np.zeros_like(t)
+ f[idx - 1] = 1. / np.arange(1, sqn + 1)
+ f = np.real(np.fft.ifft(f))
+ else:
+ raise ValueError(
+ f"unknown name: {name}. name must be one of: {_implemented_signals}")
+ return f
diff --git a/python_embeded/Lib/site-packages/pywt/data/create_dat.py b/python_embeded/Lib/site-packages/pywt/data/create_dat.py
new file mode 100644
index 0000000000000000000000000000000000000000..d66dc2c1ceeab472d068bd27bff0e48c9ee71d77
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/data/create_dat.py
@@ -0,0 +1,38 @@
+#!/usr/bin/env python
+
+"""Helper script for creating image .dat files by numpy.save
+
+Usage:
+
+ python create_dat.py
+
+Example (to create aero.dat):
+
+ python create_dat.py aero.png aero.dat
+
+Requires Scipy and PIL.
+"""
+
+
+import sys
+
+import numpy as np
+
+
+def main():
+ from scipy.misc import imread
+
+ if len(sys.argv) != 3:
+ print(__doc__)
+ exit()
+
+ image_fname = sys.argv[1]
+ dat_fname = sys.argv[2]
+
+ data = imread(image_fname)
+
+ np.savez_compressed(dat_fname, data=data)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/python_embeded/Lib/site-packages/pywt/tests/data/generate_matlab_data.py b/python_embeded/Lib/site-packages/pywt/tests/data/generate_matlab_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3cb070e8b89057e4b5ec568dc70bf39a64be211
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/data/generate_matlab_data.py
@@ -0,0 +1,94 @@
+""" This script was used to generate dwt_matlabR2012a_result.npz by storing
+the outputs from Matlab R2012a. """
+
+
+import numpy as np
+
+import pywt
+
+try:
+ from pymatbridge import Matlab
+ mlab = Matlab()
+ _matlab_missing = False
+except ImportError:
+ print("To run Matlab compatibility tests you need to have MathWorks "
+ "MATLAB, MathWorks Wavelet Toolbox and the pymatbridge Python "
+ "package installed.")
+ _matlab_missing = True
+
+if _matlab_missing:
+ raise OSError("Can't generate matlab data files without MATLAB")
+
+size_set = 'reduced'
+
+# list of mode names in pywt and matlab
+modes = [('zero', 'zpd'),
+ ('constant', 'sp0'),
+ ('symmetric', 'sym'),
+ ('reflect', 'symw'),
+ ('periodic', 'ppd'),
+ ('smooth', 'sp1'),
+ ('periodization', 'per'),
+ ('antisymmetric', 'asym'),
+ ('antireflect', 'asymw')]
+
+families = ('db', 'sym', 'coif', 'bior', 'rbio')
+wavelets = sum([pywt.wavelist(name) for name in families], [])
+
+rstate = np.random.RandomState(1234)
+mlab.start()
+try:
+ all_matlab_results = {}
+ for wavelet in wavelets:
+ w = pywt.Wavelet(wavelet)
+ mlab.set_variable('wavelet', wavelet)
+ if size_set == 'full':
+ data_sizes = list(range(w.dec_len, 40)) + \
+ [100, 200, 500, 1000, 50000]
+ else:
+ data_sizes = (w.dec_len, w.dec_len + 1)
+ for N in data_sizes:
+ data = rstate.randn(N)
+ mlab.set_variable('data', data)
+ for pmode, mmode in modes:
+ # Matlab result
+ if np.any((wavelet == np.array(['coif6', 'coif7', 'coif8', 'coif9', 'coif10', 'coif11', 'coif12', 'coif13', 'coif14', 'coif15', 'coif16', 'coif17'])),axis=0):
+ mlab.set_variable('Lo_D', w.dec_lo)
+ mlab.set_variable('Hi_D', w.dec_hi)
+ mlab_code = ("[ma, md] = dwt(data, Lo_D, Hi_D, "
+ "'mode', '%s');" % mmode)
+ else:
+ mlab_code = f"[ma, md] = dwt(data, wavelet, 'mode', '{mmode}');"
+ res = mlab.run_code(mlab_code)
+ if not res['success']:
+ raise RuntimeError(
+ "Matlab failed to execute the provided code. "
+ "Check that the wavelet toolbox is installed.")
+ # need np.asarray because sometimes the output is type float
+ ma = np.asarray(mlab.get_variable('ma'))
+ md = np.asarray(mlab.get_variable('md'))
+ ma_key = '_'.join([mmode, wavelet, str(N), 'ma'])
+ md_key = '_'.join([mmode, wavelet, str(N), 'md'])
+ all_matlab_results[ma_key] = ma
+ all_matlab_results[md_key] = md
+
+ # Matlab result
+ mlab.set_variable('Lo_D', w.dec_lo)
+ mlab.set_variable('Hi_D', w.dec_hi)
+ mlab_code = f"[ma, md] = dwt(data, Lo_D, Hi_D, 'mode', '{mmode}');"
+ res = mlab.run_code(mlab_code)
+ if not res['success']:
+ raise RuntimeError(
+ "Matlab failed to execute the provided code. "
+ "Check that the wavelet toolbox is installed.")
+ # need np.asarray because sometimes the output is type float
+ ma = np.asarray(mlab.get_variable('ma'))
+ md = np.asarray(mlab.get_variable('md'))
+ ma_key = '_'.join([mmode, wavelet, str(N), 'ma_pywtCoeffs'])
+ md_key = '_'.join([mmode, wavelet, str(N), 'md_pywtCoeffs'])
+ all_matlab_results[ma_key] = ma
+ all_matlab_results[md_key] = md
+finally:
+ mlab.stop()
+
+np.savez('dwt_matlabR2012a_result.npz', **all_matlab_results)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/data/generate_matlab_data_cwt.py b/python_embeded/Lib/site-packages/pywt/tests/data/generate_matlab_data_cwt.py
new file mode 100644
index 0000000000000000000000000000000000000000..0361ef0526ebf73d591e2c8414e0e0456c1a8fa6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/data/generate_matlab_data_cwt.py
@@ -0,0 +1,86 @@
+""" This script was used to generate dwt_matlabR2012a_result.npz by storing
+the outputs from Matlab R2012a. """
+
+
+import numpy as np
+
+import pywt
+
+try:
+ from pymatbridge import Matlab
+ mlab = Matlab()
+ _matlab_missing = False
+except ImportError:
+ print("To run Matlab compatibility tests you need to have MathWorks "
+ "MATLAB, MathWorks Wavelet Toolbox and the pymatbridge Python "
+ "package installed.")
+ _matlab_missing = True
+
+if _matlab_missing:
+ raise OSError("Can't generate matlab data files without MATLAB")
+
+size_set = 'reduced'
+
+# list of mode names in pywt and matlab
+modes = [('zero', 'zpd'),
+ ('constant', 'sp0'),
+ ('symmetric', 'sym'),
+ ('periodic', 'ppd'),
+ ('smooth', 'sp1'),
+ ('periodization', 'per')]
+
+families = ('gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor')
+wavelets = sum([pywt.wavelist(name) for name in families], [])
+
+rstate = np.random.RandomState(1234)
+mlab.start()
+try:
+ all_matlab_results = {}
+ for wavelet in wavelets:
+ w = pywt.ContinuousWavelet(wavelet)
+ if np.any((wavelet == np.array(['shan', 'cmor'])),axis=0):
+ mlab.set_variable('wavelet', wavelet+str(w.bandwidth_frequency)+'-'+str(w.center_frequency))
+ elif wavelet == 'fbsp':
+ mlab.set_variable('wavelet', wavelet+str(w.fbsp_order)+'-'+str(w.bandwidth_frequency)+'-'+str(w.center_frequency))
+ else:
+ mlab.set_variable('wavelet', wavelet)
+ if size_set == 'full':
+ data_sizes = list(range(100, 101)) + \
+ [100, 200, 500, 1000, 50000]
+ Scales = (1,np.arange(1,3),np.arange(1,4),np.arange(1,5))
+ else:
+ data_sizes = (1000, 1000 + 1)
+ Scales = (1,np.arange(1,3))
+ mlab_code = ("psi = wavefun(wavelet,10)")
+ res = mlab.run_code(mlab_code)
+ if not res['success']:
+ raise RuntimeError(
+ "Matlab failed to execute the provided code. "
+ "Check that the wavelet toolbox is installed.")
+ psi = np.asarray(mlab.get_variable('psi'))
+ psi_key = '_'.join([wavelet, 'psi'])
+ all_matlab_results[psi_key] = psi
+ for N in data_sizes:
+ data = rstate.randn(N)
+ mlab.set_variable('data', data)
+
+ # Matlab result
+ scale_count = 0
+ for scales in Scales:
+ scale_count += 1
+ mlab.set_variable('scales', scales)
+ mlab_code = ("coefs = cwt(data, scales, wavelet)")
+ res = mlab.run_code(mlab_code)
+ if not res['success']:
+ raise RuntimeError(
+ "Matlab failed to execute the provided code. "
+ "Check that the wavelet toolbox is installed.")
+ # need np.asarray because sometimes the output is type float
+ coefs = np.asarray(mlab.get_variable('coefs'))
+ coefs_key = '_'.join([str(scale_count), wavelet, str(N), 'coefs'])
+ all_matlab_results[coefs_key] = coefs
+
+finally:
+ mlab.stop()
+
+np.savez('cwt_matlabR2015b_result.npz', **all_matlab_results)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test__pywt.py b/python_embeded/Lib/site-packages/pywt/tests/test__pywt.py
new file mode 100644
index 0000000000000000000000000000000000000000..0210e5ba78ee3f64e9e18c74b21ef7ddb2c672bf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test__pywt.py
@@ -0,0 +1,169 @@
+#!/usr/bin/env python
+
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_raises
+
+import pywt
+
+
+def test_upcoef_reconstruct():
+ data = np.arange(3)
+ a = pywt.downcoef('a', data, 'haar')
+ d = pywt.downcoef('d', data, 'haar')
+
+ rec = (pywt.upcoef('a', a, 'haar', take=3) +
+ pywt.upcoef('d', d, 'haar', take=3))
+ assert_allclose(rec, data)
+
+
+def test_downcoef_multilevel():
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(16)
+ nlevels = 3
+ # calling with level=1 nlevels times
+ a1 = r.copy()
+ for i in range(nlevels):
+ a1 = pywt.downcoef('a', a1, 'haar', level=1)
+ # call with level=nlevels once
+ a3 = pywt.downcoef('a', r, 'haar', level=nlevels)
+ assert_allclose(a1, a3)
+
+
+def test_downcoef_complex():
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(16) + 1j * rstate.randn(16)
+ nlevels = 3
+ a = pywt.downcoef('a', r, 'haar', level=nlevels)
+ a_ref = pywt.downcoef('a', r.real, 'haar', level=nlevels)
+ a_ref = a_ref + 1j * pywt.downcoef('a', r.imag, 'haar', level=nlevels)
+ assert_allclose(a, a_ref)
+
+
+def test_downcoef_errs():
+ # invalid part string (not 'a' or 'd')
+ assert_raises(ValueError, pywt.downcoef, 'f', np.ones(16), 'haar')
+
+
+def test_compare_downcoef_coeffs():
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(16)
+ # compare downcoef against wavedec outputs
+ for nlevels in [1, 2, 3]:
+ for wavelet in pywt.wavelist():
+ if wavelet in ['cmor', 'shan', 'fbsp']:
+ # skip these CWT families to avoid warnings
+ continue
+ wavelet = pywt.DiscreteContinuousWavelet(wavelet)
+ if isinstance(wavelet, pywt.Wavelet):
+ max_level = pywt.dwt_max_level(r.size, wavelet.dec_len)
+ if nlevels <= max_level:
+ a = pywt.downcoef('a', r, wavelet, level=nlevels)
+ d = pywt.downcoef('d', r, wavelet, level=nlevels)
+ coeffs = pywt.wavedec(r, wavelet, level=nlevels)
+ assert_allclose(a, coeffs[0])
+ assert_allclose(d, coeffs[1])
+
+
+def test_upcoef_multilevel():
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(4)
+ nlevels = 3
+ # calling with level=1 nlevels times
+ a1 = r.copy()
+ for i in range(nlevels):
+ a1 = pywt.upcoef('a', a1, 'haar', level=1)
+ # call with level=nlevels once
+ a3 = pywt.upcoef('a', r, 'haar', level=nlevels)
+ assert_allclose(a1, a3)
+
+
+def test_upcoef_complex():
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(4) + 1j*rstate.randn(4)
+ nlevels = 3
+ a = pywt.upcoef('a', r, 'haar', level=nlevels)
+ a_ref = pywt.upcoef('a', r.real, 'haar', level=nlevels)
+ a_ref = a_ref + 1j*pywt.upcoef('a', r.imag, 'haar', level=nlevels)
+ assert_allclose(a, a_ref)
+
+
+def test_upcoef_errs():
+ # invalid part string (not 'a' or 'd')
+ assert_raises(ValueError, pywt.upcoef, 'f', np.ones(4), 'haar')
+
+
+def test_upcoef_and_downcoef_1d_only():
+ # upcoef and downcoef raise a ValueError if data.ndim > 1d
+ for ndim in [2, 3]:
+ data = np.ones((8, )*ndim)
+ assert_raises(ValueError, pywt.downcoef, 'a', data, 'haar')
+ assert_raises(ValueError, pywt.upcoef, 'a', data, 'haar')
+
+
+def test_wavelet_repr():
+ from pywt._extensions import _pywt
+ wavelet = _pywt.Wavelet('sym8')
+
+ repr_wavelet = eval(wavelet.__repr__())
+
+ assert_(wavelet.__repr__() == repr_wavelet.__repr__())
+
+
+def test_dwt_max_level():
+ assert_(pywt.dwt_max_level(16, 2) == 4)
+ assert_(pywt.dwt_max_level(16, 8) == 1)
+ assert_(pywt.dwt_max_level(16, 9) == 1)
+ assert_(pywt.dwt_max_level(16, 10) == 0)
+ assert_(pywt.dwt_max_level(16, np.int8(10)) == 0)
+ assert_(pywt.dwt_max_level(16, 10.) == 0)
+ assert_(pywt.dwt_max_level(16, 18) == 0)
+
+ # accepts discrete Wavelet object or string as well
+ assert_(pywt.dwt_max_level(32, pywt.Wavelet('sym5')) == 1)
+ assert_(pywt.dwt_max_level(32, 'sym5') == 1)
+
+ # string input that is not a discrete wavelet
+ assert_raises(ValueError, pywt.dwt_max_level, 16, 'mexh')
+
+ # filter_len must be an integer >= 2
+ assert_raises(ValueError, pywt.dwt_max_level, 16, 1)
+ assert_raises(ValueError, pywt.dwt_max_level, 16, -1)
+ assert_raises(ValueError, pywt.dwt_max_level, 16, 3.3)
+
+
+def test_ContinuousWavelet_errs():
+ assert_raises(ValueError, pywt.ContinuousWavelet, 'qwertz')
+
+
+def test_ContinuousWavelet_repr():
+ from pywt._extensions import _pywt
+ wavelet = _pywt.ContinuousWavelet('gaus2')
+
+ repr_wavelet = eval(wavelet.__repr__())
+
+ assert_(wavelet.__repr__() == repr_wavelet.__repr__())
+
+
+def test_wavelist():
+ for name in pywt.wavelist(family='coif'):
+ assert_(name.startswith('coif'))
+
+ assert_('cgau7' in pywt.wavelist(kind='continuous'))
+ assert_('sym20' in pywt.wavelist(kind='discrete'))
+ assert_(len(pywt.wavelist(kind='continuous')) +
+ len(pywt.wavelist(kind='discrete')) ==
+ len(pywt.wavelist(kind='all')))
+
+ assert_raises(ValueError, pywt.wavelist, kind='foobar')
+
+
+def test_wavelet_errormsgs():
+ try:
+ pywt.Wavelet('gaus1')
+ except ValueError as e:
+ assert_(e.args[0].startswith('The `Wavelet` class'))
+ try:
+ pywt.Wavelet('cmord')
+ except ValueError as e:
+ assert_(e.args[0] == "Invalid wavelet name 'cmord'.")
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_concurrent.py b/python_embeded/Lib/site-packages/pywt/tests/test_concurrent.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c2045ceedaf048a0c6006f74727239e87c7968c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_concurrent.py
@@ -0,0 +1,106 @@
+"""
+Tests used to verify running PyWavelets transforms in parallel via
+concurrent.futures.ThreadPoolExecutor does not raise errors.
+"""
+
+
+import warnings
+from functools import partial
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose, assert_array_equal
+
+import pywt
+from pywt._pytest import futures, max_workers, uses_futures
+
+
+def _assert_all_coeffs_equal(coefs1, coefs2):
+ # return True only if all coefficients of SWT or DWT match over all levels
+ if len(coefs1) != len(coefs2):
+ return False
+ for (c1, c2) in zip(coefs1, coefs2):
+ if isinstance(c1, tuple):
+ # for swt, swt2, dwt, dwt2, wavedec, wavedec2
+ for a1, a2 in zip(c1, c2):
+ assert_array_equal(a1, a2)
+ elif isinstance(c1, dict):
+ # for swtn, dwtn, wavedecn
+ for k, v in c1.items():
+ assert_array_equal(v, c2[k])
+ else:
+ return False
+ return True
+
+
+@uses_futures
+def test_concurrent_swt():
+ # tests error-free concurrent operation (see gh-288)
+ # swt on 1D data calls the Cython swt
+ # other cases call swt_axes
+ with warnings.catch_warnings():
+ # can remove catch_warnings once the swt2 FutureWarning is removed
+ warnings.simplefilter('ignore', FutureWarning)
+ for swt_func, x in zip([pywt.swt, pywt.swt2, pywt.swtn],
+ [np.ones(8), np.eye(16), np.eye(16)]):
+ transform = partial(swt_func, wavelet='haar', level=3)
+ for _ in range(10):
+ arrs = [x.copy() for _ in range(100)]
+ with futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
+ results = list(ex.map(transform, arrs))
+
+ # validate result from one of the concurrent runs
+ expected_result = transform(x)
+ _assert_all_coeffs_equal(expected_result, results[-1])
+
+
+@uses_futures
+def test_concurrent_wavedec():
+ # wavedec on 1D data calls the Cython dwt_single
+ # other cases call dwt_axis
+ for wavedec_func, x in zip([pywt.wavedec, pywt.wavedec2, pywt.wavedecn],
+ [np.ones(8), np.eye(16), np.eye(16)]):
+ transform = partial(wavedec_func, wavelet='haar', level=1)
+ for _ in range(10):
+ arrs = [x.copy() for _ in range(100)]
+ with futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
+ results = list(ex.map(transform, arrs))
+
+ # validate result from one of the concurrent runs
+ expected_result = transform(x)
+ _assert_all_coeffs_equal(expected_result, results[-1])
+
+
+@uses_futures
+def test_concurrent_dwt():
+ # dwt on 1D data calls the Cython dwt_single
+ # other cases call dwt_axis
+ for dwt_func, x in zip([pywt.dwt, pywt.dwt2, pywt.dwtn],
+ [np.ones(8), np.eye(16), np.eye(16)]):
+ transform = partial(dwt_func, wavelet='haar')
+ for _ in range(10):
+ arrs = [x.copy() for _ in range(100)]
+ with futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
+ results = list(ex.map(transform, arrs))
+
+ # validate result from one of the concurrent runs
+ expected_result = transform(x)
+ _assert_all_coeffs_equal([expected_result, ], [results[-1], ])
+
+
+@uses_futures
+def test_concurrent_cwt():
+ atol = rtol = 1e-14
+ time, sst = pywt.data.nino()
+ dt = time[1]-time[0]
+ transform = partial(pywt.cwt, scales=np.arange(1, 4), wavelet='cmor1.5-1',
+ sampling_period=dt)
+ for _ in range(10):
+ arrs = [sst.copy() for _ in range(50)]
+ with futures.ThreadPoolExecutor(max_workers=max_workers) as ex:
+ results = list(ex.map(transform, arrs))
+
+ # validate result from one of the concurrent runs
+ expected_result = transform(sst)
+ for a1, a2 in zip(expected_result, results[-1]):
+ assert_allclose(a1, a2, atol=atol, rtol=rtol)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_cwt_wavelets.py b/python_embeded/Lib/site-packages/pywt/tests/test_cwt_wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..adfeb5c23e6aa514344918d0927c2cd0b79237dc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_cwt_wavelets.py
@@ -0,0 +1,482 @@
+#!/usr/bin/env python
+import os
+import pickle
+from itertools import product
+
+import numpy as np
+import pytest
+from numpy.testing import (
+ assert_allclose,
+ assert_almost_equal,
+ assert_equal,
+ assert_raises,
+ assert_warns,
+)
+
+import pywt
+
+
+def ref_gaus(LB, UB, N, num):
+ X = np.linspace(LB, UB, N)
+ F0 = (2./np.pi)**(1./4.)*np.exp(-(X**2))
+ if (num == 1):
+ psi = -2.*X*F0
+ elif (num == 2):
+ psi = -2/(3**(1/2))*(-1 + 2*X**2)*F0
+ elif (num == 3):
+ psi = -4/(15**(1/2))*X*(3 - 2*X**2)*F0
+ elif (num == 4):
+ psi = 4/(105**(1/2))*(3 - 12*X**2 + 4*X**4)*F0
+ elif (num == 5):
+ psi = 8/(3*(105**(1/2)))*X*(-15 + 20*X**2 - 4*X**4)*F0
+ elif (num == 6):
+ psi = -8/(3*(1155**(1/2)))*(-15 + 90*X**2 - 60*X**4 + 8*X**6)*F0
+ elif (num == 7):
+ psi = -16/(3*(15015**(1/2)))*X*(105 - 210*X**2 + 84*X**4 - 8*X**6)*F0
+ elif (num == 8):
+ psi = 16/(45*(1001**(1/2)))*(105 - 840*X**2 + 840*X**4 -
+ 224*X**6 + 16*X**8)*F0
+ return (psi, X)
+
+
+def ref_cgau(LB, UB, N, num):
+ X = np.linspace(LB, UB, N)
+ F0 = np.exp(-X**2)
+ F1 = np.exp(-1j*X)
+ F2 = (F1*F0)/(np.exp(-1/2)*2**(1/2)*np.pi**(1/2))**(1/2)
+ if (num == 1):
+ psi = F2*(-1j - 2*X)*2**(1/2)
+ elif (num == 2):
+ psi = 1/3*F2*(-3 + 4j*X + 4*X**2)*6**(1/2)
+ elif (num == 3):
+ psi = 1/15*F2*(7j + 18*X - 12j*X**2 - 8*X**3)*30**(1/2)
+ elif (num == 4):
+ psi = 1/105*F2*(25 - 56j*X - 72*X**2 + 32j*X**3 + 16*X**4)*210**(1/2)
+ elif (num == 5):
+ psi = 1/315*F2*(-81j - 250*X + 280j*X**2 + 240*X**3 -
+ 80j*X**4 - 32*X**5)*210**(1/2)
+ elif (num == 6):
+ psi = 1/3465*F2*(-331 + 972j*X + 1500*X**2 - 1120j*X**3 - 720*X**4 +
+ 192j*X**5 + 64*X**6)*2310**(1/2)
+ elif (num == 7):
+ psi = 1/45045*F2*(
+ 1303j + 4634*X - 6804j*X**2 - 7000*X**3 + 3920j*X**4 + 2016*X**5 -
+ 448j*X**6 - 128*X**7)*30030**(1/2)
+ elif (num == 8):
+ psi = 1/45045*F2*(
+ 5937 - 20848j*X - 37072*X**2 + 36288j*X**3 + 28000*X**4 -
+ 12544j*X**5 - 5376*X**6 + 1024j*X**7 + 256*X**8)*2002**(1/2)
+
+ psi = psi/np.real(np.sqrt(np.real(np.sum(psi*np.conj(psi)))*(X[1] - X[0])))
+ return (psi, X)
+
+
+def sinc2(x):
+ y = np.ones_like(x)
+ k = np.where(x)[0]
+ y[k] = np.sin(np.pi*x[k])/(np.pi*x[k])
+ return y
+
+
+def ref_shan(LB, UB, N, Fb, Fc):
+ x = np.linspace(LB, UB, N)
+ psi = np.sqrt(Fb)*(sinc2(Fb*x)*np.exp(2j*np.pi*Fc*x))
+ return (psi, x)
+
+
+def ref_fbsp(LB, UB, N, m, Fb, Fc):
+ x = np.linspace(LB, UB, N)
+ psi = np.sqrt(Fb)*((sinc2(Fb*x/m)**m)*np.exp(2j*np.pi*Fc*x))
+ return (psi, x)
+
+
+def ref_cmor(LB, UB, N, Fb, Fc):
+ x = np.linspace(LB, UB, N)
+ psi = ((np.pi*Fb)**(-0.5))*np.exp(2j*np.pi*Fc*x)*np.exp(-(x**2)/Fb)
+ return (psi, x)
+
+
+def ref_morl(LB, UB, N):
+ x = np.linspace(LB, UB, N)
+ psi = np.exp(-(x**2)/2)*np.cos(5*x)
+ return (psi, x)
+
+
+def ref_mexh(LB, UB, N):
+ x = np.linspace(LB, UB, N)
+ psi = (2/(np.sqrt(3)*np.pi**0.25))*np.exp(-(x**2)/2)*(1 - (x**2))
+ return (psi, x)
+
+
+def test_gaus():
+ LB = -5
+ UB = 5
+ N = 1000
+ for num in np.arange(1, 9):
+ [psi, x] = ref_gaus(LB, UB, N, num)
+ w = pywt.ContinuousWavelet("gaus" + str(num))
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi))
+ assert_allclose(np.imag(PSI), np.imag(psi))
+ assert_allclose(X, x)
+
+
+@pytest.mark.parametrize('dtype', [np.float32, np.float64])
+def test_continuous_wavelet_dtype(dtype):
+ wavelet = pywt.ContinuousWavelet('cmor1.5-1.0', dtype)
+ int_psi, x = pywt.integrate_wavelet(wavelet)
+ assert int_psi.real.dtype == dtype
+ assert x.dtype == dtype
+
+
+def test_continuous_wavelet_invalid_dtype():
+ with pytest.raises(ValueError):
+ pywt.ContinuousWavelet('gaus5', np.complex64)
+ with pytest.raises(ValueError):
+ pywt.ContinuousWavelet('gaus5', np.int_)
+
+
+def test_cgau():
+ LB = -5
+ UB = 5
+ N = 1000
+ for num in np.arange(1, 9):
+ [psi, x] = ref_cgau(LB, UB, N, num)
+ w = pywt.ContinuousWavelet("cgau" + str(num))
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi))
+ assert_allclose(np.imag(PSI), np.imag(psi))
+ assert_allclose(X, x)
+
+
+def test_shan():
+ LB = -20
+ UB = 20
+ N = 1000
+ Fb = 1
+ Fc = 1.5
+
+ [psi, x] = ref_shan(LB, UB, N, Fb, Fc)
+ w = pywt.ContinuousWavelet(f"shan{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
+ assert_allclose(X, x, atol=1e-15)
+
+ LB = -20
+ UB = 20
+ N = 1000
+ Fb = 1.5
+ Fc = 1
+
+ [psi, x] = ref_shan(LB, UB, N, Fb, Fc)
+ w = pywt.ContinuousWavelet(f"shan{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
+ assert_allclose(X, x, atol=1e-15)
+
+
+def test_cmor():
+ LB = -20
+ UB = 20
+ N = 1000
+ Fb = 1
+ Fc = 1.5
+
+ [psi, x] = ref_cmor(LB, UB, N, Fb, Fc)
+ w = pywt.ContinuousWavelet(f"cmor{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
+ assert_allclose(X, x, atol=1e-15)
+
+ LB = -20
+ UB = 20
+ N = 1000
+ Fb = 1.5
+ Fc = 1
+
+ [psi, x] = ref_cmor(LB, UB, N, Fb, Fc)
+ w = pywt.ContinuousWavelet(f"cmor{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
+ assert_allclose(X, x, atol=1e-15)
+
+
+def test_fbsp():
+ LB = -20
+ UB = 20
+ N = 1000
+ M = 2
+ Fb = 1
+ Fc = 1.5
+
+ [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc)
+
+ w = pywt.ContinuousWavelet(f"fbsp{M}-{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.fbsp_order = M
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
+ assert_allclose(X, x, atol=1e-15)
+
+ LB = -20
+ UB = 20
+ N = 1000
+ M = 2
+ Fb = 1.5
+ Fc = 1
+
+ [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc)
+ w = pywt.ContinuousWavelet(f"fbsp{M}-{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.fbsp_order = M
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-15)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-15)
+ assert_allclose(X, x, atol=1e-15)
+
+ LB = -20
+ UB = 20
+ N = 1000
+ M = 3
+ Fb = 1.5
+ Fc = 1.2
+
+ [psi, x] = ref_fbsp(LB, UB, N, M, Fb, Fc)
+ w = pywt.ContinuousWavelet(f"fbsp{M}-{Fb}-{Fc}")
+ assert_almost_equal(w.center_frequency, Fc)
+ assert_almost_equal(w.bandwidth_frequency, Fb)
+ w.fbsp_order = M
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+ # TODO: investigate why atol = 1e-5 is necessary
+ assert_allclose(np.real(PSI), np.real(psi), atol=1e-5)
+ assert_allclose(np.imag(PSI), np.imag(psi), atol=1e-5)
+ assert_allclose(X, x, atol=1e-15)
+
+
+def test_morl():
+ LB = -5
+ UB = 5
+ N = 1000
+
+ [psi, x] = ref_morl(LB, UB, N)
+ w = pywt.ContinuousWavelet("morl")
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi))
+ assert_allclose(np.imag(PSI), np.imag(psi))
+ assert_allclose(X, x)
+
+
+def test_mexh():
+ LB = -5
+ UB = 5
+ N = 1000
+
+ [psi, x] = ref_mexh(LB, UB, N)
+ w = pywt.ContinuousWavelet("mexh")
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi))
+ assert_allclose(np.imag(PSI), np.imag(psi))
+ assert_allclose(X, x)
+
+ LB = -5
+ UB = 5
+ N = 1001
+
+ [psi, x] = ref_mexh(LB, UB, N)
+ w = pywt.ContinuousWavelet("mexh")
+ w.upper_bound = UB
+ w.lower_bound = LB
+ PSI, X = w.wavefun(length=N)
+
+ assert_allclose(np.real(PSI), np.real(psi))
+ assert_allclose(np.imag(PSI), np.imag(psi))
+ assert_allclose(X, x)
+
+
+def test_cwt_parameters_in_names():
+
+ for func in [pywt.ContinuousWavelet, pywt.DiscreteContinuousWavelet]:
+ for name in ['fbsp', 'cmor', 'shan']:
+ # additional parameters should be specified within the name
+ assert_warns(FutureWarning, func, name)
+
+ for name in ['cmor', 'shan']:
+ # valid names
+ func(name + '1.5-1.0')
+ func(name + '1-4')
+
+ # invalid names
+ assert_raises(ValueError, func, name + '1.0')
+ assert_raises(ValueError, func, name + 'B-C')
+ assert_raises(ValueError, func, name + '1.0-1.0-1.0')
+
+ # valid names
+ func('fbsp1-1.5-1.0')
+ func('fbsp1.0-1.5-1')
+ func('fbsp2-5-1')
+
+ # invalid name (non-integer order)
+ assert_raises(ValueError, func, 'fbsp1.5-1-1')
+ assert_raises(ValueError, func, 'fbspM-B-C')
+
+ # invalid name (too few or too many params)
+ assert_raises(ValueError, func, 'fbsp1.0')
+ assert_raises(ValueError, func, 'fbsp1.0-0.4')
+ assert_raises(ValueError, func, 'fbsp1-1-1-1')
+
+
+@pytest.mark.parametrize('dtype, tol, method',
+ [(np.float32, 1e-5, 'conv'),
+ (np.float32, 1e-5, 'fft'),
+ (np.float64, 1e-13, 'conv'),
+ (np.float64, 1e-13, 'fft')])
+def test_cwt_complex(dtype, tol, method):
+ time, sst = pywt.data.nino()
+ sst = np.asarray(sst, dtype=dtype)
+ dt = time[1] - time[0]
+ wavelet = 'cmor1.5-1.0'
+ scales = np.arange(1, 32)
+
+ # real-valued tranfsorm as a reference
+ [cfs, f] = pywt.cwt(sst, scales, wavelet, dt, method=method)
+
+ # verify same precision
+ assert_equal(cfs.real.dtype, sst.dtype)
+
+ # complex-valued transform equals sum of the transforms of the real
+ # and imaginary components
+ sst_complex = sst + 1j*sst
+ [cfs_complex, f] = pywt.cwt(sst_complex, scales, wavelet, dt,
+ method=method)
+ assert_allclose(cfs + 1j*cfs, cfs_complex, atol=tol, rtol=tol)
+ # verify dtype is preserved
+ assert_equal(cfs_complex.dtype, sst_complex.dtype)
+
+
+@pytest.mark.parametrize('axis, method', product([0, 1], ['conv', 'fft']))
+def test_cwt_batch(axis, method):
+ dtype = np.float64
+ time, sst = pywt.data.nino()
+ n_batch = 8
+ batch_axis = 1 - axis
+ sst1 = np.asarray(sst, dtype=dtype)
+ sst = np.stack((sst1, ) * n_batch, axis=batch_axis)
+ dt = time[1] - time[0]
+ wavelet = 'cmor1.5-1.0'
+ scales = np.arange(1, 32)
+
+ # non-batch transform as reference
+ [cfs1, f] = pywt.cwt(sst1, scales, wavelet, dt, method=method, axis=axis)
+
+ shape_in = sst.shape
+ [cfs, f] = pywt.cwt(sst, scales, wavelet, dt, method=method, axis=axis)
+
+ # shape of input is not modified
+ assert_equal(shape_in, sst.shape)
+
+ # verify same precision
+ assert_equal(cfs.real.dtype, sst.dtype)
+
+ # verify expected shape
+ assert_equal(cfs.shape[0], len(scales))
+ assert_equal(cfs.shape[1 + batch_axis], n_batch)
+ assert_equal(cfs.shape[1 + axis], sst.shape[axis])
+
+ # batch result on stacked input is the same as stacked 1d result
+ assert_almost_equal(cfs, np.stack((cfs1,) * n_batch, axis=batch_axis + 1),
+ decimal=12)
+
+
+def test_cwt_small_scales():
+ data = np.zeros(32)
+
+ # A scale of 0.1 was chosen specifically to give a filter of length 2 for
+ # mexh. This corner case should not raise an error.
+ cfs, f = pywt.cwt(data, scales=0.1, wavelet='mexh')
+ assert_allclose(cfs, np.zeros_like(cfs))
+
+ # extremely short scale factors raise a ValueError
+ assert_raises(ValueError, pywt.cwt, data, scales=0.01, wavelet='mexh')
+
+def test_cwt_zero_scale():
+ data = np.zeros(32)
+ scales = np.arange(0, 4)
+
+ # scale that includes 0 throws ValueError to prevent IndexError
+ assert_raises(ValueError, pywt.cwt, data, scales=scales, wavelet='morl')
+
+def test_cwt_negative_scale():
+ data = np.zeros(32)
+ scales = np.asarray([-1, -2, -3])
+
+ # scale that includes negative values throws ValueError to prevent IndexError
+ assert_raises(ValueError, pywt.cwt, data, scales=scales, wavelet='morl')
+
+
+def test_cwt_method_fft():
+ rstate = np.random.RandomState(1)
+ data = rstate.randn(50)
+ data[15] = 1.
+ scales = np.arange(1, 64)
+ wavelet = 'cmor1.5-1.0'
+
+ # build a reference cwt with the legacy np.conv() method
+ cfs_conv, _ = pywt.cwt(data, scales, wavelet, method='conv')
+
+ # compare with the fft based convolution
+ cfs_fft, _ = pywt.cwt(data, scales, wavelet, method='fft')
+ assert_allclose(cfs_conv, cfs_fft, rtol=0, atol=1e-13)
+
+
+def test_continuous_wavelet_pickle(tmpdir):
+ wavelet = pywt.ContinuousWavelet('cmor1.5-1.0')
+ filename = os.path.join(tmpdir, 'cwav.pickle')
+ with open(filename, 'wb') as f:
+ pickle.dump(wavelet, f)
+ with open(filename, 'rb') as f:
+ wavelet2 = pickle.load(f)
+ assert isinstance(wavelet2, pywt.ContinuousWavelet)
+ assert wavelet2.name == wavelet.name
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_data.py b/python_embeded/Lib/site-packages/pywt/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c5cb9eb91e181b884e537127efe49c868bcd35a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_data.py
@@ -0,0 +1,78 @@
+import os
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_raises
+
+import pywt.data
+
+data_dir = os.path.join(os.path.dirname(__file__), 'data')
+wavelab_data_file = os.path.join(data_dir, 'wavelab_test_signals.npz')
+wavelab_result_dict = np.load(wavelab_data_file)
+
+
+def test_data_aero():
+ aero = pywt.data.aero()
+
+ ref = np.array([[178, 178, 179],
+ [170, 173, 171],
+ [185, 174, 171]])
+
+ assert_allclose(aero[:3, :3], ref)
+
+
+def test_data_ascent():
+ ascent = pywt.data.ascent()
+
+ ref = np.array([[83, 83, 83],
+ [82, 82, 83],
+ [80, 81, 83]])
+
+ assert_allclose(ascent[:3, :3], ref)
+
+
+def test_data_camera():
+ camera = pywt.data.camera()
+
+ ref = np.array([[200, 200, 200],
+ [200, 199, 199],
+ [199, 199, 199]])
+
+ assert_allclose(camera[:3, :3], ref)
+
+
+def test_data_ecg():
+ ecg = pywt.data.ecg()
+
+ ref = np.array([-86, -87, -87])
+
+ assert_allclose(ecg[:3], ref)
+
+
+def test_wavelab_signals():
+ """Comparison with results generated using WaveLab"""
+ rtol = atol = 1e-12
+
+ # get a list of the available signals
+ available_signals = pywt.data.demo_signal('list')
+ assert_('Doppler' in available_signals)
+
+ for signal in available_signals:
+ # reference dictionary has lowercase names for the keys
+ key = signal.replace('-', '_').lower()
+ val = wavelab_result_dict[key]
+ if key in ['gabor', 'sineoneoverx']:
+ # these functions do not allow a size to be provided
+ assert_allclose(val, pywt.data.demo_signal(signal),
+ rtol=rtol, atol=atol)
+ assert_raises(ValueError, pywt.data.demo_signal, key, val.size)
+ else:
+ assert_allclose(val, pywt.data.demo_signal(signal, val.size),
+ rtol=rtol, atol=atol)
+ # these functions require a size to be provided
+ assert_raises(ValueError, pywt.data.demo_signal, key)
+
+ # ValueError on unrecognized signal type
+ assert_raises(ValueError, pywt.data.demo_signal, 'unknown_signal', 512)
+
+ # ValueError on invalid length
+ assert_raises(ValueError, pywt.data.demo_signal, 'Doppler', 0)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_deprecations.py b/python_embeded/Lib/site-packages/pywt/tests/test_deprecations.py
new file mode 100644
index 0000000000000000000000000000000000000000..c548167df27b8b66ad5037b6bf7302123ec4a543
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_deprecations.py
@@ -0,0 +1,89 @@
+import warnings
+
+import numpy as np
+from numpy.testing import assert_array_equal, assert_warns
+
+import pywt
+
+
+def test_intwave_deprecation():
+ wavelet = pywt.Wavelet('db3')
+ assert_warns(DeprecationWarning, pywt.intwave, wavelet)
+
+
+def test_centrfrq_deprecation():
+ wavelet = pywt.Wavelet('db3')
+ assert_warns(DeprecationWarning, pywt.centrfrq, wavelet)
+
+
+def test_scal2frq_deprecation():
+ wavelet = pywt.Wavelet('db3')
+ assert_warns(DeprecationWarning, pywt.scal2frq, wavelet, 1)
+
+
+def test_orthfilt_deprecation():
+ assert_warns(DeprecationWarning, pywt.orthfilt, range(6))
+
+
+def test_integrate_wave_tuple():
+ sig = [0, 1, 2, 3]
+ xgrid = [0, 1, 2, 3]
+ assert_warns(DeprecationWarning, pywt.integrate_wavelet, (sig, xgrid))
+
+
+old_modes = ['zpd',
+ 'cpd',
+ 'sym',
+ 'ppd',
+ 'sp1',
+ 'per',
+ ]
+
+
+def test_MODES_from_object_deprecation():
+ for mode in old_modes:
+ assert_warns(DeprecationWarning, pywt.Modes.from_object, mode)
+
+
+def test_MODES_attributes_deprecation():
+ def get_mode(Modes, name):
+ return getattr(Modes, name)
+
+ for mode in old_modes:
+ assert_warns(DeprecationWarning, get_mode, pywt.Modes, mode)
+
+
+def test_MODES_deprecation_new():
+ def use_MODES_new():
+ return pywt.MODES.symmetric
+
+ assert_warns(DeprecationWarning, use_MODES_new)
+
+
+def test_MODES_deprecation_old():
+ def use_MODES_old():
+ return pywt.MODES.sym
+
+ assert_warns(DeprecationWarning, use_MODES_old)
+
+
+def test_MODES_deprecation_getattr():
+ def use_MODES_new():
+ return getattr(pywt.MODES, 'symmetric')
+
+ assert_warns(DeprecationWarning, use_MODES_new)
+
+
+def test_mode_equivalence():
+ old_new = [('zpd', 'zero'),
+ ('cpd', 'constant'),
+ ('sym', 'symmetric'),
+ ('ppd', 'periodic'),
+ ('sp1', 'smooth'),
+ ('per', 'periodization')]
+ x = np.arange(8.)
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', DeprecationWarning)
+ for old, new in old_new:
+ assert_array_equal(pywt.dwt(x, 'db2', mode=old),
+ pywt.dwt(x, 'db2', mode=new))
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_doc.py b/python_embeded/Lib/site-packages/pywt/tests/test_doc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b416481cc7327af7e689c58682f3b75333c2c9f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_doc.py
@@ -0,0 +1,25 @@
+
+import doctest
+import glob
+import os
+import sys
+import unittest
+
+try:
+ import numpy as np
+ np.set_printoptions(legacy='1.13')
+except TypeError:
+ pass
+
+pdir = os.path.pardir
+docs_base = os.path.abspath(os.path.join(os.path.dirname(__file__),
+ pdir, pdir, "doc", "source"))
+
+files = glob.glob(os.path.join(docs_base, "*.rst")) + \
+ glob.glob(os.path.join(docs_base, "*", "*.rst"))
+
+suite = doctest.DocFileSuite(*files, module_relative=False, encoding="utf-8")
+
+
+if __name__ == "__main__":
+ sys.exit(int(not unittest.TextTestRunner().run(suite).wasSuccessful()))
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_dwt_idwt.py b/python_embeded/Lib/site-packages/pywt/tests/test_dwt_idwt.py
new file mode 100644
index 0000000000000000000000000000000000000000..8932f488b0ec4f49410e27088b6af7f849a832d7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_dwt_idwt.py
@@ -0,0 +1,306 @@
+#!/usr/bin/env python
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_array_equal, assert_raises
+
+import pywt
+
+# Check that float32, float64, complex64, complex128 are preserved.
+# Other real types get converted to float64.
+# complex256 gets converted to complex128
+dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64,
+ np.complex128]
+dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64,
+ np.complex128]
+
+# test complex256 as well if it is available
+try:
+ dtypes_in += [np.complex256, ]
+ dtypes_out += [np.complex128, ]
+except AttributeError:
+ pass
+
+
+def test_dwt_idwt_basic():
+ x = [3, 7, 1, 1, -2, 5, 4, 6]
+ cA, cD = pywt.dwt(x, 'db2')
+ cA_expect = [5.65685425, 7.39923721, 0.22414387, 3.33677403, 7.77817459]
+ cD_expect = [-2.44948974, -1.60368225, -4.44140056, -0.41361256,
+ 1.22474487]
+ assert_allclose(cA, cA_expect)
+ assert_allclose(cD, cD_expect)
+
+ x_roundtrip = pywt.idwt(cA, cD, 'db2')
+ assert_allclose(x_roundtrip, x, rtol=1e-10)
+
+ # mismatched dtypes OK
+ x_roundtrip2 = pywt.idwt(cA.astype(np.float64), cD.astype(np.float32),
+ 'db2')
+ assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
+ assert_(x_roundtrip2.dtype == np.float64)
+
+
+def test_idwt_mixed_complex_dtype():
+ x = np.arange(8).astype(float)
+ x = x + 1j*x[::-1]
+ cA, cD = pywt.dwt(x, 'db2')
+
+ x_roundtrip = pywt.idwt(cA, cD, 'db2')
+ assert_allclose(x_roundtrip, x, rtol=1e-10)
+
+ # mismatched dtypes OK
+ x_roundtrip2 = pywt.idwt(cA.astype(np.complex128), cD.astype(np.complex64),
+ 'db2')
+ assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
+ assert_(x_roundtrip2.dtype == np.complex128)
+
+
+def test_dwt_idwt_dtypes():
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ x = np.ones(4, dtype=dt_in)
+ errmsg = f"wrong dtype returned for {dt_in} input"
+
+ cA, cD = pywt.dwt(x, wavelet)
+ assert_(cA.dtype == cD.dtype == dt_out, "dwt: " + errmsg)
+
+ x_roundtrip = pywt.idwt(cA, cD, wavelet)
+ assert_(x_roundtrip.dtype == dt_out, "idwt: " + errmsg)
+
+
+def test_dwt_idwt_basic_complex():
+ x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6])
+ x = x + 0.5j*x
+ cA, cD = pywt.dwt(x, 'db2')
+ cA_expect = np.asarray([5.65685425, 7.39923721, 0.22414387, 3.33677403,
+ 7.77817459])
+ cA_expect = cA_expect + 0.5j*cA_expect
+ cD_expect = np.asarray([-2.44948974, -1.60368225, -4.44140056, -0.41361256,
+ 1.22474487])
+ cD_expect = cD_expect + 0.5j*cD_expect
+ assert_allclose(cA, cA_expect)
+ assert_allclose(cD, cD_expect)
+
+ x_roundtrip = pywt.idwt(cA, cD, 'db2')
+ assert_allclose(x_roundtrip, x, rtol=1e-10)
+
+
+def test_dwt_idwt_partial_complex():
+ x = np.asarray([3, 7, 1, 1, -2, 5, 4, 6])
+ x = x + 0.5j*x
+
+ cA, cD = pywt.dwt(x, 'haar')
+ cA_rec_expect = np.array([5.0+2.5j, 5.0+2.5j, 1.0+0.5j, 1.0+0.5j,
+ 1.5+0.75j, 1.5+0.75j, 5.0+2.5j, 5.0+2.5j])
+ cA_rec = pywt.idwt(cA, None, 'haar')
+ assert_allclose(cA_rec, cA_rec_expect)
+
+ cD_rec_expect = np.array([-2.0-1.0j, 2.0+1.0j, 0.0+0.0j, 0.0+0.0j,
+ -3.5-1.75j, 3.5+1.75j, -1.0-0.5j, 1.0+0.5j])
+ cD_rec = pywt.idwt(None, cD, 'haar')
+ assert_allclose(cD_rec, cD_rec_expect)
+
+ assert_allclose(cA_rec + cD_rec, x)
+
+
+def test_dwt_wavelet_kwd():
+ x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
+ w = pywt.Wavelet('sym3')
+ cA, cD = pywt.dwt(x, wavelet=w, mode='constant')
+ cA_expect = [4.38354585, 3.80302657, 7.31813271, -0.58565539, 4.09727044,
+ 7.81994027]
+ cD_expect = [-1.33068221, -2.78795192, -3.16825651, -0.67715519,
+ -0.09722957, -0.07045258]
+ assert_allclose(cA, cA_expect)
+ assert_allclose(cD, cD_expect)
+
+
+def test_dwt_coeff_len():
+ x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
+ w = pywt.Wavelet('sym3')
+ ln_modes = [pywt.dwt_coeff_len(len(x), w.dec_len, mode) for mode in
+ pywt.Modes.modes]
+
+ expected_result = [6, ] * len(pywt.Modes.modes)
+ expected_result[pywt.Modes.modes.index('periodization')] = 4
+
+ assert_allclose(ln_modes, expected_result)
+ ln_modes = [pywt.dwt_coeff_len(len(x), w, mode) for mode in
+ pywt.Modes.modes]
+ assert_allclose(ln_modes, expected_result)
+
+
+def test_idwt_none_input():
+ # None input equals arrays of zeros of the right length
+ res1 = pywt.idwt([1, 2, 0, 1], None, 'db2', 'symmetric')
+ res2 = pywt.idwt([1, 2, 0, 1], [0, 0, 0, 0], 'db2', 'symmetric')
+ assert_allclose(res1, res2, rtol=1e-15, atol=1e-15)
+
+ res1 = pywt.idwt(None, [1, 2, 0, 1], 'db2', 'symmetric')
+ res2 = pywt.idwt([0, 0, 0, 0], [1, 2, 0, 1], 'db2', 'symmetric')
+ assert_allclose(res1, res2, rtol=1e-15, atol=1e-15)
+
+ # Only one argument at a time can be None
+ assert_raises(ValueError, pywt.idwt, None, None, 'db2', 'symmetric')
+
+
+def test_idwt_invalid_input():
+ # Too short, min length is 4 for 'db4':
+ assert_raises(ValueError, pywt.idwt, [1, 2, 4], [4, 1, 3], 'db4', 'symmetric')
+
+
+def test_dwt_single_axis():
+ x = [[3, 7, 1, 1],
+ [-2, 5, 4, 6]]
+
+ cA, cD = pywt.dwt(x, 'db2', axis=-1)
+
+ cA0, cD0 = pywt.dwt(x[0], 'db2')
+ cA1, cD1 = pywt.dwt(x[1], 'db2')
+
+ assert_allclose(cA[0], cA0)
+ assert_allclose(cA[1], cA1)
+
+ assert_allclose(cD[0], cD0)
+ assert_allclose(cD[1], cD1)
+
+
+def test_idwt_single_axis():
+ x = [[3, 7, 1, 1],
+ [-2, 5, 4, 6]]
+
+ x = np.asarray(x)
+ x = x + 1j*x # test with complex data
+ cA, cD = pywt.dwt(x, 'db2', axis=-1)
+
+ x0 = pywt.idwt(cA[0], cD[0], 'db2', axis=-1)
+ x1 = pywt.idwt(cA[1], cD[1], 'db2', axis=-1)
+
+ assert_allclose(x[0], x0)
+ assert_allclose(x[1], x1)
+
+def test_dwt_invalid_input():
+ x = np.arange(1)
+ assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect')
+ assert_raises(ValueError, pywt.dwt, x, 'haar', 'antireflect')
+
+
+def test_dwt_axis_arg():
+ x = [[3, 7, 1, 1],
+ [-2, 5, 4, 6]]
+
+ cA_, cD_ = pywt.dwt(x, 'db2', axis=-1)
+ cA, cD = pywt.dwt(x, 'db2', axis=1)
+
+ assert_allclose(cA_, cA)
+ assert_allclose(cD_, cD)
+
+def test_dwt_axis_invalid_input():
+ x = np.ones((3,1))
+ assert_raises(ValueError, pywt.dwt, x, 'db2', 'reflect')
+
+def test_idwt_axis_arg():
+ x = [[3, 7, 1, 1],
+ [-2, 5, 4, 6]]
+
+ cA, cD = pywt.dwt(x, 'db2', axis=1)
+
+ x_ = pywt.idwt(cA, cD, 'db2', axis=-1)
+ x = pywt.idwt(cA, cD, 'db2', axis=1)
+
+ assert_allclose(x_, x)
+
+
+def test_dwt_idwt_axis_excess():
+ x = [[3, 7, 1, 1],
+ [-2, 5, 4, 6]]
+ # can't transform over axes that aren't there
+ assert_raises(ValueError,
+ pywt.dwt, x, 'db2', 'symmetric', axis=2)
+
+ assert_raises(ValueError,
+ pywt.idwt, [1, 2, 4], [4, 1, 3], 'db2', 'symmetric', axis=1)
+
+
+def test_error_on_continuous_wavelet():
+ # A ValueError is raised if a Continuous wavelet is selected
+ data = np.ones((32, ))
+ for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
+ assert_raises(ValueError, pywt.dwt, data, cwave)
+
+ cA, cD = pywt.dwt(data, 'db1')
+ assert_raises(ValueError, pywt.idwt, cA, cD, cwave)
+
+
+def test_dwt_zero_size_axes():
+ # raise on empty input array
+ assert_raises(ValueError, pywt.dwt, [], 'db2')
+
+ # >1D case uses a different code path so check there as well
+ x = np.ones((1, 4))[0:0, :] # 2D with a size zero axis
+ assert_raises(ValueError, pywt.dwt, x, 'db2', axis=0)
+
+
+def test_pad_1d():
+ x = [1, 2, 3]
+ assert_array_equal(pywt.pad(x, (4, 6), 'periodization'),
+ [1, 2, 3, 3, 1, 2, 3, 3, 1, 2, 3, 3, 1, 2])
+ assert_array_equal(pywt.pad(x, (4, 6), 'periodic'),
+ [3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3])
+ assert_array_equal(pywt.pad(x, (4, 6), 'constant'),
+ [1, 1, 1, 1, 1, 2, 3, 3, 3, 3, 3, 3, 3])
+ assert_array_equal(pywt.pad(x, (4, 6), 'zero'),
+ [0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0])
+ assert_array_equal(pywt.pad(x, (4, 6), 'smooth'),
+ [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+ assert_array_equal(pywt.pad(x, (4, 6), 'symmetric'),
+ [3, 3, 2, 1, 1, 2, 3, 3, 2, 1, 1, 2, 3])
+ assert_array_equal(pywt.pad(x, (4, 6), 'antisymmetric'),
+ [3, -3, -2, -1, 1, 2, 3, -3, -2, -1, 1, 2, 3])
+ assert_array_equal(pywt.pad(x, (4, 6), 'reflect'),
+ [1, 2, 3, 2, 1, 2, 3, 2, 1, 2, 3, 2, 1])
+ assert_array_equal(pywt.pad(x, (4, 6), 'antireflect'),
+ [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+
+ # equivalence of various pad_width formats
+ assert_array_equal(pywt.pad(x, 4, 'periodic'),
+ pywt.pad(x, (4, 4), 'periodic'))
+
+ assert_array_equal(pywt.pad(x, (4, ), 'periodic'),
+ pywt.pad(x, (4, 4), 'periodic'))
+
+ assert_array_equal(pywt.pad(x, [(4, 4)], 'periodic'),
+ pywt.pad(x, (4, 4), 'periodic'))
+
+
+def test_pad_errors():
+ # negative pad width
+ x = [1, 2, 3]
+ assert_raises(ValueError, pywt.pad, x, -2, 'periodic')
+
+ # wrong length pad width
+ assert_raises(ValueError, pywt.pad, x, (1, 1, 1), 'periodic')
+
+ # invalid mode name
+ assert_raises(ValueError, pywt.pad, x, 2, 'bad_mode')
+
+
+def test_pad_nd():
+ for ndim in [2, 3]:
+ x = np.arange(4**ndim).reshape((4, ) * ndim)
+ if ndim == 2:
+ pad_widths = [(2, 1), (2, 3)]
+ else:
+ pad_widths = [(2, 1), ] * ndim
+ for mode in pywt.Modes.modes:
+ xp = pywt.pad(x, pad_widths, mode)
+
+ # expected result is the same as applying along axes separably
+ xp_expected = x.copy()
+ for ax in range(ndim):
+ xp_expected = np.apply_along_axis(pywt.pad,
+ ax,
+ xp_expected,
+ pad_widths=[pad_widths[ax]],
+ mode=mode)
+ assert_array_equal(xp, xp_expected)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_functions.py b/python_embeded/Lib/site-packages/pywt/tests/test_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..70644f22e0f24baca1225137041f395fab359afe
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_functions.py
@@ -0,0 +1,44 @@
+#!/usr/bin/env python
+
+from numpy.testing import assert_allclose, assert_almost_equal
+
+import pywt
+
+
+def test_centrfreq():
+ # db1 is Haar function, frequency=1
+ w = pywt.Wavelet('db1')
+ expected = 1
+ result = pywt.central_frequency(w, precision=12)
+ assert_almost_equal(result, expected, decimal=3)
+ # db2, frequency=2/3
+ w = pywt.Wavelet('db2')
+ expected = 2/3.
+ result = pywt.central_frequency(w, precision=12)
+ assert_almost_equal(result, expected)
+
+
+def test_scal2frq_scale():
+ scale = 2
+ w = pywt.Wavelet('db1')
+ expected = 1. / scale
+ result = pywt.scale2frequency(w, scale, precision=12)
+ assert_almost_equal(result, expected, decimal=3)
+
+def test_frq2scal_freq():
+ freq = 2
+ w = pywt.Wavelet('db1')
+ expected = 1. / freq
+ result = pywt.frequency2scale(w, freq, precision=12)
+ assert_almost_equal(result, expected, decimal=3)
+
+
+def test_intwave_orthogonal():
+ w = pywt.Wavelet('db1')
+ int_psi, x = pywt.integrate_wavelet(w, precision=12)
+ ix = x < 0.5
+ # For x < 0.5, the integral is equal to x
+ assert_allclose(int_psi[ix], x[ix])
+ # For x > 0.5, the integral is equal to (1 - x)
+ # Ignore last point here, there x > 1 and something goes wrong
+ assert_allclose(int_psi[~ix][:-1], 1 - x[~ix][:-1], atol=1e-10)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_matlab_compatibility.py b/python_embeded/Lib/site-packages/pywt/tests/test_matlab_compatibility.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fedcef26b1ac96635b2fc75383adbd3b8306243
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_matlab_compatibility.py
@@ -0,0 +1,159 @@
+"""
+Test used to verify PyWavelets Discrete Wavelet Transform computation
+accuracy against MathWorks Wavelet Toolbox.
+"""
+
+
+import numpy as np
+import pytest
+from numpy.testing import assert_
+
+import pywt
+from pywt._pytest import matlab_result_dict_dwt as matlab_result_dict
+from pywt._pytest import size_set, uses_precomputed, uses_pymatbridge
+
+# list of mode names in pywt and matlab
+modes = [('zero', 'zpd'),
+ ('constant', 'sp0'),
+ ('symmetric', 'sym'),
+ ('reflect', 'symw'),
+ ('periodic', 'ppd'),
+ ('smooth', 'sp1'),
+ ('periodization', 'per'),
+ # TODO: Now have implemented asymmetric modes too.
+ # Would be nice to update the Matlab data to test these as well.
+ ('antisymmetric', 'asym'),
+ ('antireflect', 'asymw'),
+ ]
+
+families = ('db', 'sym', 'coif', 'bior', 'rbio')
+wavelets = sum([pywt.wavelist(name) for name in families], [])
+
+
+def _get_data_sizes(w):
+ """ Return the sizes to test for wavelet w. """
+ if size_set == 'full':
+ data_sizes = list(range(w.dec_len, 40)) + \
+ [100, 200, 500, 1000, 50000]
+ else:
+ data_sizes = (w.dec_len, w.dec_len + 1)
+ return data_sizes
+
+
+@uses_pymatbridge
+@pytest.mark.slow
+def test_accuracy_pymatbridge():
+ Matlab = pytest.importorskip("pymatbridge.Matlab")
+ mlab = Matlab()
+
+ rstate = np.random.RandomState(1234)
+ # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients)
+ epsilon = 5.0e-5
+ epsilon_pywt_coeffs = 1.0e-10
+ mlab.start()
+ try:
+ for wavelet in wavelets:
+ w = pywt.Wavelet(wavelet)
+ mlab.set_variable('wavelet', wavelet)
+ for N in _get_data_sizes(w):
+ data = rstate.randn(N)
+ mlab.set_variable('data', data)
+ for pmode, mmode in modes:
+ ma, md = _compute_matlab_result(data, wavelet, mmode, mlab)
+ _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon)
+ ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode)
+ _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs)
+
+ finally:
+ mlab.stop()
+
+
+@uses_precomputed
+@pytest.mark.slow
+def test_accuracy_precomputed():
+ # Keep this specific random seed to match the precomputed Matlab result.
+ rstate = np.random.RandomState(1234)
+ # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients)
+ epsilon = 5.0e-5
+ epsilon_pywt_coeffs = 1.0e-10
+ for wavelet in wavelets:
+ w = pywt.Wavelet(wavelet)
+ for N in _get_data_sizes(w):
+ data = rstate.randn(N)
+ for pmode, mmode in modes:
+ ma, md = _load_matlab_result(data, wavelet, mmode)
+ _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon)
+ ma, md = _load_matlab_result_pywt_coeffs(data, wavelet, mmode)
+ _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon_pywt_coeffs)
+
+
+def _compute_matlab_result(data, wavelet, mmode, mlab):
+ """ Compute the result using MATLAB.
+
+ This function assumes that the Matlab variables `wavelet` and `data` have
+ already been set externally.
+ """
+ if np.any((wavelet == np.array(['coif6', 'coif7', 'coif8', 'coif9', 'coif10', 'coif11', 'coif12', 'coif13', 'coif14', 'coif15', 'coif16', 'coif17'])),axis=0):
+ w = pywt.Wavelet(wavelet)
+ mlab.set_variable('Lo_D', w.dec_lo)
+ mlab.set_variable('Hi_D', w.dec_hi)
+ mlab_code = f"[ma, md] = dwt(data, Lo_D, Hi_D, 'mode', '{mmode}');"
+ else:
+ mlab_code = f"[ma, md] = dwt(data, wavelet, 'mode', '{mmode}');"
+ res = mlab.run_code(mlab_code)
+ if not res['success']:
+ raise RuntimeError("Matlab failed to execute the provided code. "
+ "Check that the wavelet toolbox is installed.")
+ # need np.asarray because sometimes the output is a single float64
+ ma = np.asarray(mlab.get_variable('ma'))
+ md = np.asarray(mlab.get_variable('md'))
+ return ma, md
+
+
+def _load_matlab_result(data, wavelet, mmode):
+ """ Load the precomputed result.
+ """
+ N = len(data)
+ ma_key = '_'.join([mmode, wavelet, str(N), 'ma'])
+ md_key = '_'.join([mmode, wavelet, str(N), 'md'])
+ if (ma_key not in matlab_result_dict) or \
+ (md_key not in matlab_result_dict):
+ raise KeyError(
+ "Precompted Matlab result not found for wavelet: "
+ f"{wavelet}, mode: {mmode}, size: {N}")
+ ma = matlab_result_dict[ma_key]
+ md = matlab_result_dict[md_key]
+ return ma, md
+
+
+def _load_matlab_result_pywt_coeffs(data, wavelet, mmode):
+ """ Load the precomputed result.
+ """
+ N = len(data)
+ ma_key = '_'.join([mmode, wavelet, str(N), 'ma_pywtCoeffs'])
+ md_key = '_'.join([mmode, wavelet, str(N), 'md_pywtCoeffs'])
+ if (ma_key not in matlab_result_dict) or \
+ (md_key not in matlab_result_dict):
+ raise KeyError(
+ "Precompted Matlab result not found for wavelet: "
+ f"{wavelet}, mode: {mmode}, size: {N}")
+ ma = matlab_result_dict[ma_key]
+ md = matlab_result_dict[md_key]
+ return ma, md
+
+
+def _check_accuracy(data, w, pmode, ma, md, wavelet, epsilon):
+ # PyWavelets result
+ pa, pd = pywt.dwt(data, w, pmode)
+
+ # calculate error measures
+ rms_a = np.sqrt(np.mean((pa - ma) ** 2))
+ rms_d = np.sqrt(np.mean((pd - md) ** 2))
+
+ msg = ('[RMS_A > EPSILON] for Mode: %s, Wavelet: %s, '
+ 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_a))
+ assert_(rms_a < epsilon, msg=msg)
+
+ msg = ('[RMS_D > EPSILON] for Mode: %s, Wavelet: %s, '
+ 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_d))
+ assert_(rms_d < epsilon, msg=msg)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_matlab_compatibility_cwt.py b/python_embeded/Lib/site-packages/pywt/tests/test_matlab_compatibility_cwt.py
new file mode 100644
index 0000000000000000000000000000000000000000..bdac6c08ea78d0b1312fbe9520087b538ce7244d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_matlab_compatibility_cwt.py
@@ -0,0 +1,177 @@
+"""
+Test used to verify PyWavelets Continuous Wavelet Transform computation
+accuracy against MathWorks Wavelet Toolbox.
+"""
+
+
+import warnings
+
+import numpy as np
+import pytest
+from numpy.testing import assert_
+
+import pywt
+from pywt._pytest import (
+ matlab_result_dict_cwt,
+ size_set,
+ uses_precomputed,
+ uses_pymatbridge,
+)
+
+families = ('gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor')
+wavelets = sum([pywt.wavelist(name) for name in families], [])
+
+
+def _get_data_sizes(w):
+ """ Return the sizes to test for wavelet w. """
+ if size_set == 'full':
+ data_sizes = list(range(100, 101)) + \
+ [100, 200, 500, 1000, 50000]
+ else:
+ data_sizes = (1000, 1000 + 1)
+ return data_sizes
+
+
+def _get_scales(w):
+ """ Return the scales to test for wavelet w. """
+ if size_set == 'full':
+ scales = (1, np.arange(1, 3), np.arange(1, 4), np.arange(1, 5))
+ else:
+ scales = (1, np.arange(1, 3))
+ return scales
+
+
+@uses_pymatbridge # skip this case if precomputed results are used instead
+@pytest.mark.slow
+def test_accuracy_pymatbridge_cwt():
+ Matlab = pytest.importorskip("pymatbridge.Matlab")
+ mlab = Matlab()
+ rstate = np.random.RandomState(1234)
+ # max RMSE (was 1.0e-10, is reduced to 5.0e-5 due to different coefficients)
+ epsilon = 1e-15
+ epsilon_psi = 1e-15
+ mlab.start()
+ try:
+ for wavelet in wavelets:
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', FutureWarning)
+ w = pywt.ContinuousWavelet(wavelet)
+ if np.any((wavelet == np.array(['shan', 'cmor'])),axis=0):
+ mlab.set_variable('wavelet', wavelet+str(w.bandwidth_frequency)+'-'+str(w.center_frequency))
+ elif wavelet == 'fbsp':
+ mlab.set_variable('wavelet', wavelet+str(w.fbsp_order)+'-'+str(w.bandwidth_frequency)+'-'+str(w.center_frequency))
+ else:
+ mlab.set_variable('wavelet', wavelet)
+ mlab_code = ("psi = wavefun(wavelet,10)")
+ res = mlab.run_code(mlab_code)
+ psi = np.asarray(mlab.get_variable('psi'))
+ _check_accuracy_psi(w, psi, wavelet, epsilon_psi)
+ for N in _get_data_sizes(w):
+ data = rstate.randn(N)
+ mlab.set_variable('data', data)
+ for scales in _get_scales(w):
+ coefs = _compute_matlab_result(data, wavelet, scales, mlab)
+ _check_accuracy(data, w, scales, coefs, wavelet, epsilon)
+
+ finally:
+ mlab.stop()
+
+
+@uses_precomputed # skip this case if pymatbridge + Matlab are being used
+@pytest.mark.slow
+def test_accuracy_precomputed_cwt():
+ # Keep this specific random seed to match the precomputed Matlab result.
+ rstate = np.random.RandomState(1234)
+ # has to be improved
+ epsilon = 2e-15
+ epsilon32 = 1e-5
+ epsilon_psi = 1e-15
+ for wavelet in wavelets:
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', FutureWarning)
+ w = pywt.ContinuousWavelet(wavelet)
+ w32 = pywt.ContinuousWavelet(wavelet,dtype=np.float32)
+ psi = _load_matlab_result_psi(wavelet)
+ _check_accuracy_psi(w, psi, wavelet, epsilon_psi)
+
+ for N in _get_data_sizes(w):
+ data = rstate.randn(N)
+ data32 = data.astype(np.float32)
+ scales_count = 0
+ for scales in _get_scales(w):
+ scales_count += 1
+ coefs = _load_matlab_result(data, wavelet, scales_count)
+ _check_accuracy(data, w, scales, coefs, wavelet, epsilon)
+ _check_accuracy(data32, w32, scales, coefs, wavelet, epsilon32)
+
+
+def _compute_matlab_result(data, wavelet, scales, mlab):
+ """ Compute the result using MATLAB.
+
+ This function assumes that the Matlab variables `wavelet` and `data` have
+ already been set externally.
+ """
+ mlab.set_variable('scales', scales)
+ mlab_code = ("coefs = cwt(data, scales, wavelet)")
+ res = mlab.run_code(mlab_code)
+ if not res['success']:
+ raise RuntimeError("Matlab failed to execute the provided code. "
+ "Check that the wavelet toolbox is installed.")
+ # need np.asarray because sometimes the output is a single float64
+ coefs = np.asarray(mlab.get_variable('coefs'))
+ return coefs
+
+
+def _load_matlab_result(data, wavelet, scales):
+ """ Load the precomputed result.
+ """
+ N = len(data)
+ coefs_key = '_'.join([str(scales), wavelet, str(N), 'coefs'])
+ if (coefs_key not in matlab_result_dict_cwt):
+ raise KeyError(
+ "Precompted Matlab result not found for wavelet: "
+ f"{wavelet}, mode: {scales}, size: {N}")
+ coefs = matlab_result_dict_cwt[coefs_key]
+ return coefs
+
+
+def _load_matlab_result_psi(wavelet):
+ """ Load the precomputed result.
+ """
+ psi_key = '_'.join([wavelet, 'psi'])
+ if (psi_key not in matlab_result_dict_cwt):
+ raise KeyError(
+ "Precompted Matlab psi result not found for wavelet: "
+ "{0}}".format(wavelet))
+ psi = matlab_result_dict_cwt[psi_key]
+ return psi
+
+
+def _check_accuracy(data, w, scales, coefs, wavelet, epsilon):
+ # PyWavelets result
+ coefs_pywt, freq = pywt.cwt(data, scales, w)
+
+ # coefs from Matlab are from R2012a which is missing the complex conjugate
+ # as shown in Eq. 2 of Torrence and Compo. We take the complex conjugate of
+ # the precomputed Matlab result to account for this.
+ coefs = np.conj(coefs)
+
+ # calculate error measures
+ err = coefs_pywt - coefs
+ rms = np.real(np.sqrt(np.mean(np.conj(err) * err)))
+
+ msg = ('[RMS > EPSILON] for Scale: %s, Wavelet: %s, '
+ 'Length: %d, rms=%.3g' % (scales, wavelet, len(data), rms))
+ assert_(rms < epsilon, msg=msg)
+
+
+def _check_accuracy_psi(w, psi, wavelet, epsilon):
+ # PyWavelets result
+ psi_pywt, x = w.wavefun(length=1024)
+
+ # calculate error measures
+ err = psi_pywt.flatten() - psi.flatten()
+ rms = np.real(np.sqrt(np.mean(np.conj(err) * err)))
+
+ msg = f'[RMS > EPSILON] for Wavelet: {wavelet}, rms={rms:.3g}'
+ assert_(rms < epsilon, msg=msg)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_modes.py b/python_embeded/Lib/site-packages/pywt/tests/test_modes.py
new file mode 100644
index 0000000000000000000000000000000000000000..97018b2d721be3f6a10458e3ef03d8ca09b4cb08
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_modes.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_raises
+
+import pywt
+
+
+def test_available_modes():
+ modes = ['zero', 'constant', 'symmetric', 'periodic', 'smooth',
+ 'periodization', 'reflect', 'antisymmetric', 'antireflect']
+ assert_equal(pywt.Modes.modes, modes)
+ assert_equal(pywt.Modes.from_object('constant'), 2)
+
+
+def test_invalid_modes():
+ x = np.arange(4)
+ assert_raises(ValueError, pywt.dwt, x, 'db2', 'unknown')
+ assert_raises(ValueError, pywt.dwt, x, 'db2', -1)
+ assert_raises(ValueError, pywt.dwt, x, 'db2', 9)
+ assert_raises(TypeError, pywt.dwt, x, 'db2', None)
+
+ assert_raises(ValueError, pywt.Modes.from_object, 'unknown')
+ assert_raises(ValueError, pywt.Modes.from_object, -1)
+ assert_raises(ValueError, pywt.Modes.from_object, 9)
+ assert_raises(TypeError, pywt.Modes.from_object, None)
+
+
+def test_dwt_idwt_allmodes():
+ # Test that :func:`dwt` and :func:`idwt` can be performed using every mode
+ x = [1, 2, 1, 5, -1, 8, 4, 6]
+ dwt_results = {
+ 'zero': ([-0.03467518, 1.73309178, 3.40612438, 6.32928585, 6.95094948],
+ [-0.12940952, -2.15599552, -5.95034847, -1.21545369,
+ -1.8625013]),
+ 'constant': ([1.28480404, 1.73309178, 3.40612438, 6.32928585,
+ 7.51935555],
+ [-0.48296291, -2.15599552, -5.95034847, -1.21545369,
+ 0.25881905]),
+ 'symmetric': ([1.76776695, 1.73309178, 3.40612438, 6.32928585,
+ 7.77817459],
+ [-0.61237244, -2.15599552, -5.95034847, -1.21545369,
+ 1.22474487]),
+ 'reflect': ([2.12132034, 1.73309178, 3.40612438, 6.32928585,
+ 6.81224877],
+ [-0.70710678, -2.15599552, -5.95034847, -1.21545369,
+ -2.38013939]),
+ 'periodic': ([6.9162743, 1.73309178, 3.40612438, 6.32928585,
+ 6.9162743],
+ [-1.99191082, -2.15599552, -5.95034847, -1.21545369,
+ -1.99191082]),
+ 'smooth': ([-0.51763809, 1.73309178, 3.40612438, 6.32928585,
+ 7.45000519],
+ [0, -2.15599552, -5.95034847, -1.21545369, 0]),
+ 'periodization': ([4.053172, 3.05257099, 2.85381112, 8.42522221],
+ [0.18946869, 4.18258152, 4.33737503, 2.60428326]),
+ 'antisymmetric': ([-1.83711731, 1.73309178, 3.40612438, 6.32928585,
+ 6.12372436],
+ [0.353553391, -2.15599552, -5.95034847, -1.21545369,
+ -4.94974747]),
+ 'antireflect': ([0.44828774, 1.73309178, 3.40612438, 6.32928585,
+ 8.22646233],
+ [-0.25881905, -2.15599552, -5.95034847, -1.21545369,
+ 2.89777748])
+ }
+
+ for mode in pywt.Modes.modes:
+ cA, cD = pywt.dwt(x, 'db2', mode)
+ assert_allclose(cA, dwt_results[mode][0], rtol=1e-7, atol=1e-8)
+ assert_allclose(cD, dwt_results[mode][1], rtol=1e-7, atol=1e-8)
+ assert_allclose(pywt.idwt(cA, cD, 'db2', mode), x, rtol=1e-10)
+
+
+def test_dwt_short_input_allmodes():
+ # some test cases where the input is shorter than the DWT filter
+ x = [1, 3, 2]
+ wavelet = 'db2'
+ # manually pad each end by the filter size (4 for 'db2' used here)
+ padded_x = {'zero': [0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0],
+ 'constant': [1, 1, 1, 1, 1, 3, 2, 2, 2, 2, 2],
+ 'symmetric': [2, 2, 3, 1, 1, 3, 2, 2, 3, 1, 1],
+ 'reflect': [1, 3, 2, 3, 1, 3, 2, 3, 1, 3, 2],
+ 'periodic': [2, 1, 3, 2, 1, 3, 2, 1, 3, 2, 1],
+ 'smooth': [-7, -5, -3, -1, 1, 3, 2, 1, 0, -1, -2],
+ 'antisymmetric': [2, -2, -3, -1, 1, 3, 2, -2, -3, -1, 1],
+ 'antireflect': [1, -1, 0, -1, 1, 3, 2, 1, 3, 5, 4],
+ }
+ for mode, xpad in padded_x.items():
+ # DWT of the manually padded array. will discard edges later so
+ # symmetric mode used here doesn't matter.
+ cApad, cDpad = pywt.dwt(xpad, wavelet, mode='symmetric')
+
+ # central region of the padded output (unaffected by mode )
+ expected_result = (cApad[2:-2], cDpad[2:-2])
+
+ cA, cD = pywt.dwt(x, wavelet, mode)
+ assert_allclose(cA, expected_result[0], rtol=1e-7, atol=1e-8)
+ assert_allclose(cD, expected_result[1], rtol=1e-7, atol=1e-8)
+
+
+def test_default_mode():
+ # The default mode should be 'symmetric'
+ x = [1, 2, 1, 5, -1, 8, 4, 6]
+ cA, cD = pywt.dwt(x, 'db2')
+ cA2, cD2 = pywt.dwt(x, 'db2', mode='symmetric')
+ assert_allclose(cA, cA2)
+ assert_allclose(cD, cD2)
+ assert_allclose(pywt.idwt(cA, cD, 'db2'), x)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_mra.py b/python_embeded/Lib/site-packages/pywt/tests/test_mra.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5f4a3d1a19b8d6e6517c0c6947665b4a6872b31
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_mra.py
@@ -0,0 +1,257 @@
+#!/usr/bin/env python
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+
+import pywt
+from pywt import data
+from pywt._utils import AxisError
+
+# tolerances used in accuracy comparisons
+tol_single = 1e-6
+tol_double = 1e-13
+atol = 1e-7
+
+
+####
+# 1d mra tests
+####
+
+@pytest.mark.parametrize('wavelet', ['db2', 'sym4', 'coif5'])
+@pytest.mark.parametrize('transform', ['dwt', 'swt'])
+@pytest.mark.parametrize('mode', pywt.Modes.modes)
+@pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64', 'complex64', 'complex128']
+)
+def test_mra_roundtrip(wavelet, transform, mode, dtype):
+ x = data.ecg()[:64].astype(dtype)
+ if x.dtype.kind == 'c':
+ # fill some data for the imaginary channel
+ x.imag = x[::-1].real
+
+ if transform == 'swt':
+ # swt mode only supports periodization
+ if mode != 'periodization':
+ with pytest.raises(ValueError):
+ pywt.mra(x, wavelet, transform=transform, mode=mode)
+ return
+
+ coeffs = pywt.mra(x, wavelet, transform=transform, mode=mode)
+ assert isinstance(coeffs, list)
+ assert isinstance(coeffs[0], np.ndarray)
+ # assert all(isinstance(coeffs[i], dict) for i in range(1, len(coeffs)))
+
+ y = pywt.imra(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+@pytest.mark.parametrize('wavelet', ['rbio1.3', 'bior2.4'])
+@pytest.mark.parametrize('transform', ['dwt', 'swt'])
+def test_mra_warns_on_non_orthogonal(wavelet, transform):
+ dtype = np.float64
+ x = data.ecg()[:64].astype(dtype)
+
+ assert not pywt.Wavelet(wavelet).orthogonal
+
+ if transform == 'swt':
+ # bi-orthogonal wavelets raise a warning for SWT case
+ msg = 'norm=True, but the wavelet is not orthogonal'
+ with pytest.warns(UserWarning, match=msg):
+ coeffs = pywt.mra(x, wavelet, transform=transform)
+ else:
+ coeffs = pywt.mra(x, wavelet, transform=transform)
+
+ y = pywt.imra(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+@pytest.mark.parametrize('axis', [0, -1, 1, 2, -3])
+@pytest.mark.parametrize('ndim', [1, 2, 3])
+@pytest.mark.parametrize('transform', ['dwt', 'swt'])
+@pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+def test_mra_axis(transform, ndim, axis, dtype):
+ # Test transforms over a specific axis of 1D, 2D or 3D data
+ if ndim == 1:
+ x = data.ecg()[:64]
+ elif ndim == 2:
+ x = data.camera()[:64, :32]
+ elif ndim == 3:
+ x = data.camera()[:48, :8]
+ x = np.stack((x,) * 8, axis=-1)
+ x = x.astype(dtype, copy=False)
+
+ # out of range axis
+ if axis < -x.ndim or axis >= x.ndim:
+ with pytest.raises(AxisError):
+ pywt.mra(x, 'db1', transform=transform, axis=axis)
+ return
+
+ coeffs = pywt.mra(x, 'db1', transform=transform, axis=axis)
+ y = pywt.imra(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+####
+# 2d mra tests
+####
+
+@pytest.mark.parametrize('wavelet', ['db2', 'sym4', 'coif5'])
+@pytest.mark.parametrize('transform', ['dwt2', 'swt2'])
+@pytest.mark.parametrize('mode', pywt.Modes.modes)
+@pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64', 'complex64', 'complex128']
+)
+def test_mra2_roundtrip(wavelet, transform, mode, dtype):
+ x = data.camera()[:32, :16].astype(dtype, copy=False)
+ if x.dtype.kind == 'c':
+ # fill some data for the imaginary channel
+ x.imag = x[::-1, :].real
+
+ if transform == 'swt2':
+ # swt mode only supports periodization
+ if mode != 'periodization':
+ with pytest.raises(ValueError):
+ pywt.mra2(x, wavelet, transform=transform, mode=mode)
+ return
+
+ coeffs = pywt.mra2(x, wavelet, transform=transform, mode=mode)
+ assert isinstance(coeffs, list)
+ assert isinstance(coeffs[0], np.ndarray)
+ # assert all(isinstance(coeffs[i], dict) for i in range(1, len(coeffs)))
+
+ y = pywt.imra2(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+@pytest.mark.parametrize('wavelet', ['rbio1.3', 'bior2.4'])
+@pytest.mark.parametrize('transform', ['dwt2', 'swt2'])
+def test_mra2_warns_on_non_orthogonal(wavelet, transform):
+ dtype = np.float64
+ x = data.camera()[:32, :8].astype(dtype, copy=False)
+
+ assert not pywt.Wavelet(wavelet).orthogonal
+
+ if transform == 'swt2':
+ # bi-orthogonal wavelets raise a warning for SWT case
+ msg = 'norm=True, but the wavelets used are not orthogonal'
+ with pytest.warns(UserWarning, match=msg):
+ coeffs = pywt.mra2(x, wavelet, transform=transform)
+ else:
+ coeffs = pywt.mra2(x, wavelet, transform=transform)
+
+ y = pywt.imra2(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+@pytest.mark.parametrize('transform', ['dwt2', 'swt2'])
+@pytest.mark.parametrize('ndim', [2, 3])
+@pytest.mark.parametrize('axes', [(0, 1), (-2, -1), (0, 2), (-3, 1), (0, 4)])
+@pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+def test_mra2_axes(transform, axes, ndim, dtype):
+ # Test transforms over various axes of 2D or 3D data.
+ x = data.camera()[:32, :16].astype(dtype, copy=False)
+ if ndim == 3:
+ x = np.stack((x,) * 8, axis=-1)
+
+ # out of range axis
+ if any(axis < -x.ndim or axis >= x.ndim for axis in axes):
+ with pytest.raises(AxisError):
+ pywt.mra2(x, 'db1', transform=transform, axes=axes)
+ return
+
+ coeffs = pywt.mra2(x, 'db1', transform=transform, axes=axes)
+ y = pywt.imra2(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+####
+# nd mra tests
+####
+
+@pytest.mark.slow
+@pytest.mark.parametrize('wavelet', ['sym2', ])
+@pytest.mark.parametrize('transform', ['dwtn', 'swtn'])
+@pytest.mark.parametrize('mode', pywt.Modes.modes)
+@pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64', 'complex64', 'complex128']
+)
+@pytest.mark.parametrize('ndim', [1, 2, 3])
+def test_mran_roundtrip(wavelet, transform, mode, dtype, ndim):
+ if ndim == 1:
+ x = data.ecg()[:48].astype(dtype, copy=False)
+ elif ndim == 2:
+ x = data.camera()[:16, :8].astype(dtype, copy=False)
+ elif ndim == 3:
+ x = data.camera()[:16, :8].astype(dtype, copy=False)
+ x = np.stack((x,) * 8, axis=-1)
+
+ if x.dtype.kind == 'c':
+ # fill some data for the imaginary channel
+ x.imag = x[::-1, ...].real
+
+ if transform == 'swtn':
+ # swt mode only supports periodization
+ if mode != 'periodization':
+ with pytest.raises(ValueError):
+ pywt.mran(x, wavelet, transform=transform, mode=mode)
+ return
+
+ coeffs = pywt.mran(x, wavelet, transform=transform, mode=mode)
+ assert isinstance(coeffs, list)
+ assert isinstance(coeffs[0], np.ndarray)
+ # assert all(isinstance(coeffs[i], dict) for i in range(1, len(coeffs)))
+
+ y = pywt.imran(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+@pytest.mark.parametrize('wavelet', ['rbio1.3', 'bior2.4'])
+@pytest.mark.parametrize('transform', ['dwtn', 'swtn'])
+def test_mran_warns_on_non_orthogonal(wavelet, transform):
+ dtype = np.float64
+ x = data.camera()[:32, :8].astype(dtype, copy=False)
+
+ assert not pywt.Wavelet(wavelet).orthogonal
+
+ if transform == 'swtn':
+ # bi-orthogonal wavelets raise a warning for SWT case
+ msg = 'norm=True, but the wavelets used are not orthogonal'
+ with pytest.warns(UserWarning, match=msg):
+ coeffs = pywt.mran(x, wavelet, transform=transform)
+ else:
+ coeffs = pywt.mran(x, wavelet, transform=transform)
+
+ y = pywt.imran(coeffs)
+ rtol = tol_single if x.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x, y, rtol=rtol, atol=rtol)
+
+
+@pytest.mark.parametrize(
+ 'axes', [(0, 1), (-2, -1), (0, 2), (-3, 1), (0, 4), (-3, -2, -1),
+ (0, 2, 1), (0, 5, 1), (0,), (1,), (2,), (-2,), (-3,), (-4,)])
+@pytest.mark.parametrize('transform', ['dwtn', 'swtn'])
+def test_mran_axes(axes, transform):
+ # Test with transforms over 1, 2 or 3 axes of 3d data.
+ # Cases with out of range axes are also tested
+ dtype = np.float64
+ x = data.camera()[:32, :16].astype(dtype, copy=False)
+ x3d = np.stack((x,) * 8, axis=-1)
+
+ # out of range axis
+ if any(axis < -x.ndim or axis >= x.ndim for axis in axes):
+ with pytest.raises(AxisError):
+ pywt.mran(x, 'db1', transform='dwtn', axes=axes)
+ return
+
+ coeffs = pywt.mran(x3d, 'db1', transform='dwtn', axes=axes)
+ y = pywt.imran(coeffs)
+ rtol = tol_single if x3d.real.dtype.kind == 'f' else tol_double
+ assert_allclose(x3d, y, rtol=rtol, atol=rtol)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_multidim.py b/python_embeded/Lib/site-packages/pywt/tests/test_multidim.py
new file mode 100644
index 0000000000000000000000000000000000000000..1eaa90a965401bf9fa3fa60c58dc45d11a089606
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_multidim.py
@@ -0,0 +1,444 @@
+#!/usr/bin/env python
+
+
+from itertools import combinations
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises
+
+import pywt
+
+# Check that float32, float64, complex64, complex128 are preserved.
+# Other real types get converted to float64.
+# complex256 gets converted to complex128
+dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64,
+ np.complex128]
+dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64,
+ np.complex128]
+
+# test complex256 as well if it is available
+try:
+ dtypes_in += [np.complex256, ]
+ dtypes_out += [np.complex128, ]
+except AttributeError:
+ pass
+
+
+def test_dwtn_input():
+ # Array-like must be accepted
+ pywt.dwtn([1, 2, 3, 4], 'haar')
+ # Others must not
+ data = {}
+ assert_raises(TypeError, pywt.dwtn, data, 'haar')
+ # Must be at least 1D
+ assert_raises(ValueError, pywt.dwtn, 2, 'haar')
+
+
+def test_3D_reconstruct():
+ data = np.array([
+ [[0, 4, 1, 5, 1, 4],
+ [0, 5, 26, 3, 2, 1],
+ [5, 8, 2, 33, 4, 9],
+ [2, 5, 19, 4, 19, 1]],
+ [[1, 5, 1, 2, 3, 4],
+ [7, 12, 6, 52, 7, 8],
+ [2, 12, 3, 52, 6, 8],
+ [5, 2, 6, 78, 12, 2]]])
+
+ wavelet = pywt.Wavelet('haar')
+ for mode in pywt.Modes.modes:
+ d = pywt.dwtn(data, wavelet, mode=mode)
+ assert_allclose(data, pywt.idwtn(d, wavelet, mode=mode),
+ rtol=1e-13, atol=1e-13)
+
+
+def test_dwdtn_idwtn_allwavelets():
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(16, 16)
+ # test 2D case only for all wavelet types
+ wavelist = pywt.wavelist()
+ if 'dmey' in wavelist:
+ wavelist.remove('dmey')
+ for wavelet in wavelist:
+ if wavelet in ['cmor', 'shan', 'fbsp']:
+ # skip these CWT families to avoid warnings
+ continue
+ if isinstance(pywt.DiscreteContinuousWavelet(wavelet), pywt.Wavelet):
+ for mode in pywt.Modes.modes:
+ coeffs = pywt.dwtn(r, wavelet, mode=mode)
+ assert_allclose(pywt.idwtn(coeffs, wavelet, mode=mode),
+ r, rtol=1e-7, atol=1e-7)
+
+
+def test_stride():
+ wavelet = pywt.Wavelet('haar')
+
+ for dtype in ('float32', 'float64'):
+ data = np.array([[0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]],
+ dtype=dtype)
+
+ for mode in pywt.Modes.modes:
+ expected = pywt.dwtn(data, wavelet)
+ strided = np.ones((3, 12), dtype=data.dtype)
+ strided[::-1, ::2] = data
+ strided_dwtn = pywt.dwtn(strided[::-1, ::2], wavelet)
+ for key in expected:
+ assert_allclose(strided_dwtn[key], expected[key])
+
+
+def test_byte_offset():
+ wavelet = pywt.Wavelet('haar')
+ for dtype in ('float32', 'float64'):
+ data = np.array([[0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]],
+ dtype=dtype)
+
+ for mode in pywt.Modes.modes:
+ expected = pywt.dwtn(data, wavelet)
+ padded = np.ones((3, 6), dtype=np.dtype({'data': (data.dtype, 0),
+ 'pad': ('byte', data.dtype.itemsize)},
+ align=True))
+ padded[:] = data
+ padded_dwtn = pywt.dwtn(padded['data'], wavelet)
+ for key in expected:
+ assert_allclose(padded_dwtn[key], expected[key])
+
+
+def test_3D_reconstruct_complex():
+ # All dimensions even length so `take` does not need to be specified
+ data = np.array([
+ [[0, 4, 1, 5, 1, 4],
+ [0, 5, 26, 3, 2, 1],
+ [5, 8, 2, 33, 4, 9],
+ [2, 5, 19, 4, 19, 1]],
+ [[1, 5, 1, 2, 3, 4],
+ [7, 12, 6, 52, 7, 8],
+ [2, 12, 3, 52, 6, 8],
+ [5, 2, 6, 78, 12, 2]]])
+ data = data + 1j
+
+ wavelet = pywt.Wavelet('haar')
+ d = pywt.dwtn(data, wavelet)
+ # idwtn creates even-length shapes (2x dwtn size)
+ original_shape = tuple([slice(None, s) for s in data.shape])
+ assert_allclose(data, pywt.idwtn(d, wavelet)[original_shape],
+ rtol=1e-13, atol=1e-13)
+
+
+def test_idwtn_idwt2():
+ data = np.array([
+ [0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]])
+
+ wavelet = pywt.Wavelet('haar')
+
+ LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
+ d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
+
+ for mode in pywt.Modes.modes:
+ assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode),
+ pywt.idwtn(d, wavelet, mode=mode),
+ rtol=1e-14, atol=1e-14)
+
+
+def test_idwtn_idwt2_complex():
+ data = np.array([
+ [0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]])
+ data = data + 1j
+ wavelet = pywt.Wavelet('haar')
+
+ LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
+ d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
+
+ for mode in pywt.Modes.modes:
+ assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet, mode=mode),
+ pywt.idwtn(d, wavelet, mode=mode),
+ rtol=1e-14, atol=1e-14)
+
+
+def test_idwtn_missing():
+ # Test to confirm missing data behave as zeroes
+ data = np.array([
+ [0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]])
+
+ wavelet = pywt.Wavelet('haar')
+
+ coefs = pywt.dwtn(data, wavelet)
+
+ # No point removing zero, or all
+ for num_missing in range(1, len(coefs)):
+ for missing in combinations(coefs.keys(), num_missing):
+ missing_coefs = coefs.copy()
+ for key in missing:
+ del missing_coefs[key]
+ LL = missing_coefs.get('aa', None)
+ HL = missing_coefs.get('da', None)
+ LH = missing_coefs.get('ad', None)
+ HH = missing_coefs.get('dd', None)
+
+ assert_allclose(pywt.idwt2((LL, (HL, LH, HH)), wavelet),
+ pywt.idwtn(missing_coefs, 'haar'), atol=1e-15)
+
+
+def test_idwtn_all_coeffs_None():
+ coefs = {'aa': None, 'da': None, 'ad': None, 'dd': None}
+ assert_raises(ValueError, pywt.idwtn, coefs, 'haar')
+
+
+def test_error_on_invalid_keys():
+ data = np.array([
+ [0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]])
+
+ wavelet = pywt.Wavelet('haar')
+
+ LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
+
+ # unexpected key
+ d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH, 'ff': LH}
+ assert_raises(ValueError, pywt.idwtn, d, wavelet)
+
+ # mismatched key lengths
+ d = {'a': LL, 'da': HL, 'ad': LH, 'dd': HH}
+ assert_raises(ValueError, pywt.idwtn, d, wavelet)
+
+
+def test_error_mismatched_size():
+ data = np.array([
+ [0, 4, 1, 5, 1, 4],
+ [0, 5, 6, 3, 2, 1],
+ [2, 5, 19, 4, 19, 1]])
+
+ wavelet = pywt.Wavelet('haar')
+
+ LL, (HL, LH, HH) = pywt.dwt2(data, wavelet)
+
+ # Pass/fail depends on first element being shorter than remaining ones so
+ # set 3/4 to an incorrect size to maximize chances. Order of dict items
+ # is random so may not trigger on every test run. Dict is constructed
+ # inside idwtn function so no use using an OrderedDict here.
+ LL = LL[:, :-1]
+ LH = LH[:, :-1]
+ HH = HH[:, :-1]
+ d = {'aa': LL, 'da': HL, 'ad': LH, 'dd': HH}
+
+ assert_raises(ValueError, pywt.idwtn, d, wavelet)
+
+
+def test_dwt2_idwt2_dtypes():
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ x = np.ones((4, 4), dtype=dt_in)
+ errmsg = f"wrong dtype returned for {dt_in} input"
+
+ cA, (cH, cV, cD) = pywt.dwt2(x, wavelet)
+ assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype,
+ "dwt2: " + errmsg)
+
+ x_roundtrip = pywt.idwt2((cA, (cH, cV, cD)), wavelet)
+ assert_(x_roundtrip.dtype == dt_out, "idwt2: " + errmsg)
+
+
+def test_dwtn_axes():
+ data = np.array([[0, 1, 2, 3],
+ [1, 1, 1, 1],
+ [1, 4, 2, 8]])
+ data = data + 1j*data # test with complex data
+ coefs = pywt.dwtn(data, 'haar', axes=(1,))
+ expected_a = [pywt.dwt(x, 'haar')[0] for x in data]
+ assert_equal(coefs['a'], expected_a)
+ expected_d = [pywt.dwt(x, 'haar')[1] for x in data]
+ assert_equal(coefs['d'], expected_d)
+
+ coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
+ expected_aa = [pywt.dwt(x, 'haar')[0] for x in expected_a]
+ assert_equal(coefs['aa'], expected_aa)
+ expected_ad = [pywt.dwt(x, 'haar')[1] for x in expected_a]
+ assert_equal(coefs['ad'], expected_ad)
+
+
+def test_idwtn_axes():
+ data = np.array([[0, 1, 2, 3],
+ [1, 1, 1, 1],
+ [1, 4, 2, 8]])
+ data = data + 1j*data # test with complex data
+ coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
+ assert_allclose(pywt.idwtn(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
+
+
+def test_idwt2_none_coeffs():
+ data = np.array([[0, 1, 2, 3],
+ [1, 1, 1, 1],
+ [1, 4, 2, 8]])
+ data = data + 1j*data # test with complex data
+ cA, (cH, cV, cD) = pywt.dwt2(data, 'haar', axes=(1, 1))
+
+ # verify setting coefficients to None is the same as zeroing them
+ cD = np.zeros_like(cD)
+ result_zeros = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1))
+
+ cD = None
+ result_none = pywt.idwt2((cA, (cH, cV, cD)), 'haar', axes=(1, 1))
+
+ assert_equal(result_zeros, result_none)
+
+
+def test_idwtn_none_coeffs():
+ data = np.array([[0, 1, 2, 3],
+ [1, 1, 1, 1],
+ [1, 4, 2, 8]])
+ data = data + 1j*data # test with complex data
+ coefs = pywt.dwtn(data, 'haar', axes=(1, 1))
+
+ # verify setting coefficients to None is the same as zeroing them
+ coefs['dd'] = np.zeros_like(coefs['dd'])
+ result_zeros = pywt.idwtn(coefs, 'haar', axes=(1, 1))
+
+ coefs['dd'] = None
+ result_none = pywt.idwtn(coefs, 'haar', axes=(1, 1))
+
+ assert_equal(result_zeros, result_none)
+
+
+def test_idwt2_axes():
+ data = np.array([[0, 1, 2, 3],
+ [1, 1, 1, 1],
+ [1, 4, 2, 8]])
+ coefs = pywt.dwt2(data, 'haar', axes=(1, 1))
+ assert_allclose(pywt.idwt2(coefs, 'haar', axes=(1, 1)), data, atol=1e-14)
+
+ # too many axes
+ assert_raises(ValueError, pywt.idwt2, coefs, 'haar', axes=(0, 1, 1))
+
+
+def test_idwt2_axes_subsets():
+ data = np.array(np.random.standard_normal((4, 4, 4)))
+ # test all combinations of 2 out of 3 axes transformed
+ for axes in combinations((0, 1, 2), 2):
+ coefs = pywt.dwt2(data, 'haar', axes=axes)
+ assert_allclose(pywt.idwt2(coefs, 'haar', axes=axes), data, atol=1e-14)
+
+
+def test_idwtn_axes_subsets():
+ data = np.array(np.random.standard_normal((4, 4, 4, 4)))
+ # test all combinations of 3 out of 4 axes transformed
+ for axes in combinations((0, 1, 2, 3), 3):
+ coefs = pywt.dwtn(data, 'haar', axes=axes)
+ assert_allclose(pywt.idwtn(coefs, 'haar', axes=axes), data, atol=1e-14)
+
+
+def test_negative_axes():
+ data = np.array([[0, 1, 2, 3],
+ [1, 1, 1, 1],
+ [1, 4, 2, 8]])
+ coefs1 = pywt.dwtn(data, 'haar', axes=(1, 1))
+ coefs2 = pywt.dwtn(data, 'haar', axes=(-1, -1))
+ assert_equal(coefs1, coefs2)
+
+ rec1 = pywt.idwtn(coefs1, 'haar', axes=(1, 1))
+ rec2 = pywt.idwtn(coefs1, 'haar', axes=(-1, -1))
+ assert_equal(rec1, rec2)
+
+
+def test_dwtn_idwtn_dtypes():
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ x = np.ones((4, 4), dtype=dt_in)
+ errmsg = f"wrong dtype returned for {dt_in} input"
+
+ coeffs = pywt.dwtn(x, wavelet)
+ for k, v in coeffs.items():
+ assert_(v.dtype == dt_out, "dwtn: " + errmsg)
+
+ x_roundtrip = pywt.idwtn(coeffs, wavelet)
+ assert_(x_roundtrip.dtype == dt_out, "idwtn: " + errmsg)
+
+
+def test_idwtn_mixed_complex_dtype():
+ rstate = np.random.RandomState(0)
+ x = rstate.randn(8, 8, 8)
+ x = x + 1j*x
+ coeffs = pywt.dwtn(x, 'db2')
+
+ x_roundtrip = pywt.idwtn(coeffs, 'db2')
+ assert_allclose(x_roundtrip, x, rtol=1e-10)
+
+ # mismatched dtypes OK
+ coeffs['a' * x.ndim] = coeffs['a' * x.ndim].astype(np.complex64)
+ x_roundtrip2 = pywt.idwtn(coeffs, 'db2')
+ assert_allclose(x_roundtrip2, x, rtol=1e-7, atol=1e-7)
+ assert_(x_roundtrip2.dtype == np.complex128)
+
+
+def test_idwt2_size_mismatch_error():
+ LL = np.zeros((6, 6))
+ LH = HL = HH = np.zeros((5, 5))
+
+ assert_raises(ValueError, pywt.idwt2, (LL, (LH, HL, HH)), wavelet='haar')
+
+
+def test_dwt2_dimension_error():
+ data = np.ones(16)
+ wavelet = pywt.Wavelet('haar')
+
+ # wrong number of input dimensions
+ assert_raises(ValueError, pywt.dwt2, data, wavelet)
+
+ # too many axes
+ data2 = np.ones((8, 8))
+ assert_raises(ValueError, pywt.dwt2, data2, wavelet, axes=(0, 1, 1))
+
+
+def test_per_axis_wavelets_and_modes():
+ # tests separate wavelet and edge mode for each axis.
+ rstate = np.random.RandomState(1234)
+ data = rstate.randn(16, 16, 16)
+
+ # wavelet can be a string or wavelet object
+ wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4')
+
+ # mode can be a string or a Modes enum
+ modes = ('symmetric', 'periodization',
+ pywt._extensions._pywt.Modes.reflect)
+
+ coefs = pywt.dwtn(data, wavelets, modes)
+ assert_allclose(pywt.idwtn(coefs, wavelets, modes), data, atol=1e-14)
+
+ coefs = pywt.dwtn(data, wavelets[:1], modes)
+ assert_allclose(pywt.idwtn(coefs, wavelets[:1], modes), data, atol=1e-14)
+
+ coefs = pywt.dwtn(data, wavelets, modes[:1])
+ assert_allclose(pywt.idwtn(coefs, wavelets, modes[:1]), data, atol=1e-14)
+
+ # length of wavelets or modes doesn't match the length of axes
+ assert_raises(ValueError, pywt.dwtn, data, wavelets[:2])
+ assert_raises(ValueError, pywt.dwtn, data, wavelets, mode=modes[:2])
+ assert_raises(ValueError, pywt.idwtn, coefs, wavelets[:2])
+ assert_raises(ValueError, pywt.idwtn, coefs, wavelets, mode=modes[:2])
+
+ # dwt2/idwt2 also support per-axis wavelets/modes
+ data2 = data[..., 0]
+ coefs2 = pywt.dwt2(data2, wavelets[:2], modes[:2])
+ assert_allclose(pywt.idwt2(coefs2, wavelets[:2], modes[:2]), data2,
+ atol=1e-14)
+
+
+def test_error_on_continuous_wavelet():
+ # A ValueError is raised if a Continuous wavelet is selected
+ data = np.ones((16, 16))
+ for dec_fun, rec_fun in zip([pywt.dwt2, pywt.dwtn],
+ [pywt.idwt2, pywt.idwtn]):
+ for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
+ assert_raises(ValueError, dec_fun, data, wavelet=cwave)
+
+ c = dec_fun(data, 'db1')
+ assert_raises(ValueError, rec_fun, c, wavelet=cwave)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_multilevel.py b/python_embeded/Lib/site-packages/pywt/tests/test_multilevel.py
new file mode 100644
index 0000000000000000000000000000000000000000..86a3d1b2033001dd3d62a62c430924238f067969
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_multilevel.py
@@ -0,0 +1,1042 @@
+#!/usr/bin/env python
+
+
+import warnings
+from itertools import combinations
+
+import numpy as np
+import pytest
+from numpy.testing import (
+ assert_,
+ assert_allclose,
+ assert_almost_equal,
+ assert_array_equal,
+ assert_equal,
+ assert_raises,
+ assert_raises_regex,
+ assert_warns,
+)
+
+import pywt
+
+# Check that float32, float64, complex64, complex128 are preserved.
+# Other real types get converted to float64.
+# complex256 gets converted to complex128
+dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64,
+ np.complex128]
+dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64,
+ np.complex128]
+
+# tolerances used in accuracy comparisons
+tol_single = 1e-6
+tol_double = 1e-13
+dtypes_and_tolerances = [(np.float16, tol_single), (np.float32, tol_single),
+ (np.float64, tol_double), (np.int8, tol_double),
+ (np.complex64, tol_single),
+ (np.complex128, tol_double)]
+
+# test complex256 as well if it is available
+try:
+ dtypes_in += [np.complex256, ]
+ dtypes_out += [np.complex128, ]
+ dtypes_and_tolerances += [(np.complex256, tol_double), ]
+except AttributeError:
+ pass
+
+
+# determine which wavelets to test
+wavelist = pywt.wavelist()
+if 'dmey' in wavelist:
+ # accuracy is very low for dmey, so omit it
+ wavelist.remove('dmey')
+
+# removing wavelets with dwt_possible == False
+del_list = []
+for wavelet in wavelist:
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', FutureWarning)
+ if not isinstance(pywt.DiscreteContinuousWavelet(wavelet),
+ pywt.Wavelet):
+ del_list.append(wavelet)
+for del_ind in del_list:
+ wavelist.remove(del_ind)
+
+
+####
+# 1d multilevel dwt tests
+####
+
+def test_wavedec():
+ x = [3, 7, 1, 1, -2, 5, 4, 6]
+ db1 = pywt.Wavelet('db1')
+ cA3, cD3, cD2, cD1 = pywt.wavedec(x, db1)
+ assert_almost_equal(cA3, [8.83883476])
+ assert_almost_equal(cD3, [-0.35355339])
+ assert_allclose(cD2, [4., -3.5])
+ assert_allclose(cD1, [-2.82842712, 0, -4.94974747, -1.41421356])
+ assert_(pywt.dwt_max_level(len(x), db1) == 3)
+
+
+def test_waverec_invalid_inputs():
+ # input must be list or tuple
+ assert_raises(ValueError, pywt.waverec, np.ones(8), 'haar')
+
+ # input list cannot be empty
+ assert_raises(ValueError, pywt.waverec, [], 'haar')
+
+ # 'array_to_coeffs must specify 'output_format' to perform waverec
+ x = [3, 7, 1, 1, -2, 5, 4, 6]
+ coeffs = pywt.wavedec(x, 'db1')
+ arr, coeff_slices = pywt.coeffs_to_array(coeffs)
+ coeffs_from_arr = pywt.array_to_coeffs(arr, coeff_slices)
+ message = "Unexpected detail coefficient type"
+ assert_raises_regex(ValueError, message, pywt.waverec, coeffs_from_arr,
+ 'haar')
+
+
+def test_waverec_accuracies():
+ rstate = np.random.RandomState(1234)
+ x0 = rstate.randn(8)
+ for dt, tol in dtypes_and_tolerances:
+ x = x0.astype(dt)
+ if np.iscomplexobj(x):
+ x += 1j*rstate.randn(8).astype(x.real.dtype)
+ coeffs = pywt.wavedec(x, 'db1')
+ assert_allclose(pywt.waverec(coeffs, 'db1'), x, atol=tol, rtol=tol)
+
+
+def test_waverec_none():
+ x = [3, 7, 1, 1, -2, 5, 4, 6]
+ coeffs = pywt.wavedec(x, 'db1')
+
+ # set some coefficients to None
+ coeffs[2] = None
+ coeffs[0] = None
+ assert_(pywt.waverec(coeffs, 'db1').size, len(x))
+
+
+def test_waverec_odd_length():
+ x = [3, 7, 1, 1, -2, 5]
+ coeffs = pywt.wavedec(x, 'db1')
+ assert_allclose(pywt.waverec(coeffs, 'db1'), x, rtol=1e-12)
+
+
+def test_waverec_complex():
+ x = np.array([3, 7, 1, 1, -2, 5, 4, 6])
+ x = x + 1j
+ coeffs = pywt.wavedec(x, 'db1')
+ assert_allclose(pywt.waverec(coeffs, 'db1'), x, rtol=1e-12)
+
+
+def test_multilevel_dtypes_1d():
+ # only checks that the result is of the expected type
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ # wavedec, waverec
+ x = np.ones(8, dtype=dt_in)
+ errmsg = f"wrong dtype returned for {dt_in} input"
+
+ coeffs = pywt.wavedec(x, wavelet, level=2)
+ for c in coeffs:
+ assert_(c.dtype == dt_out, "wavedec: " + errmsg)
+ x_roundtrip = pywt.waverec(coeffs, wavelet)
+ assert_(x_roundtrip.dtype == dt_out, "waverec: " + errmsg)
+
+
+def test_waverec_all_wavelets_modes():
+ # test 2D case using all wavelets and modes
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(80)
+ for wavelet in wavelist:
+ for mode in pywt.Modes.modes:
+ coeffs = pywt.wavedec(r, wavelet, mode=mode)
+ assert_allclose(pywt.waverec(coeffs, wavelet, mode=mode),
+ r, rtol=tol_single, atol=tol_single)
+
+####
+# 2d multilevel dwt function tests
+####
+
+
+def test_waverec2_accuracies():
+ rstate = np.random.RandomState(1234)
+ x0 = rstate.randn(4, 4)
+ for dt, tol in dtypes_and_tolerances:
+ x = x0.astype(dt)
+ if np.iscomplexobj(x):
+ x += 1j*rstate.randn(4, 4).astype(x.real.dtype)
+ coeffs = pywt.wavedec2(x, 'db1')
+ assert_(len(coeffs) == 3)
+ assert_allclose(pywt.waverec2(coeffs, 'db1'), x, atol=tol, rtol=tol)
+
+
+def test_multilevel_dtypes_2d():
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ # wavedec2, waverec2
+ x = np.ones((8, 8), dtype=dt_in)
+ errmsg = f"wrong dtype returned for {dt_in} input"
+ cA, coeffsD2, coeffsD1 = pywt.wavedec2(x, wavelet, level=2)
+ assert_(cA.dtype == dt_out, "wavedec2: " + errmsg)
+ for c in coeffsD1:
+ assert_(c.dtype == dt_out, "wavedec2: " + errmsg)
+ for c in coeffsD2:
+ assert_(c.dtype == dt_out, "wavedec2: " + errmsg)
+ x_roundtrip = pywt.waverec2([cA, coeffsD2, coeffsD1], wavelet)
+ assert_(x_roundtrip.dtype == dt_out, "waverec2: " + errmsg)
+
+
+@pytest.mark.slow
+def test_waverec2_all_wavelets_modes():
+ # test 2D case using all wavelets and modes
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(80, 96)
+ for wavelet in wavelist:
+ for mode in pywt.Modes.modes:
+ coeffs = pywt.wavedec2(r, wavelet, mode=mode)
+ assert_allclose(pywt.waverec2(coeffs, wavelet, mode=mode),
+ r, rtol=tol_single, atol=tol_single)
+
+
+def test_wavedec2_complex():
+ data = np.ones((4, 4)) + 1j
+ coeffs = pywt.wavedec2(data, 'db1')
+ assert_(len(coeffs) == 3)
+ assert_allclose(pywt.waverec2(coeffs, 'db1'), data, rtol=1e-12)
+
+
+def test_wavedec2_invalid_inputs():
+ # input array has too few dimensions
+ data = np.ones(4)
+ assert_raises(ValueError, pywt.wavedec2, data, 'haar')
+
+
+def test_waverec2_invalid_inputs():
+ # input must be list or tuple
+ assert_raises(ValueError, pywt.waverec2, np.ones((8, 8)), 'haar')
+
+ # input list cannot be empty
+ assert_raises(ValueError, pywt.waverec2, [], 'haar')
+
+ # coefficients from a difference decomposition used as input
+ for dec_func in [pywt.wavedec, pywt.wavedecn]:
+ coeffs = dec_func(np.ones((8, 8)), 'haar')
+ message = "Unexpected detail coefficient type"
+ assert_raises_regex(ValueError, message, pywt.waverec2, coeffs,
+ 'haar')
+
+
+def test_waverec2_coeff_shape_mismatch():
+ x = np.ones((8, 8))
+ coeffs = pywt.wavedec2(x, 'db1')
+
+ # introduce a shape mismatch in the coefficients
+ coeffs = list(coeffs)
+ coeffs[1] = list(coeffs[1])
+ coeffs[1][1] = np.zeros((16, 1))
+ assert_raises(ValueError, pywt.waverec2, coeffs, 'db1')
+
+
+def test_waverec2_odd_length():
+ x = np.ones((10, 6))
+ coeffs = pywt.wavedec2(x, 'db1')
+ assert_allclose(pywt.waverec2(coeffs, 'db1'), x, rtol=1e-12)
+
+
+def test_waverec2_none_coeffs():
+ x = np.arange(24).reshape(6, 4)
+ coeffs = pywt.wavedec2(x, 'db1')
+ coeffs[1] = (None, None, None)
+ assert_(x.shape == pywt.waverec2(coeffs, 'db1').shape)
+
+####
+# nd multilevel dwt function tests
+####
+
+
+def test_waverecn():
+ rstate = np.random.RandomState(1234)
+ # test 1D through 4D cases
+ for nd in range(1, 5):
+ x = rstate.randn(*(4, )*nd)
+ coeffs = pywt.wavedecn(x, 'db1')
+ assert_(len(coeffs) == 3)
+ assert_allclose(pywt.waverecn(coeffs, 'db1'), x, rtol=tol_double)
+
+
+def test_waverecn_empty_coeff():
+ coeffs = [np.ones((2, 2, 2)), {}, {}]
+ assert_equal(pywt.waverecn(coeffs, 'db1').shape, (8, 8, 8))
+
+ assert_equal(pywt.waverecn(coeffs, 'db1').shape, (8, 8, 8))
+ coeffs = [np.ones((2, 2, 2)), {}, {'daa': np.ones((4, 4, 4))}]
+
+ coeffs = [np.ones((2, 2, 2)), {}, {}, {'daa': np.ones((8, 8, 8))}]
+ assert_equal(pywt.waverecn(coeffs, 'db1').shape, (16, 16, 16))
+
+
+def test_waverecn_invalid_coeffs():
+ # approximation coeffs as None and no valid detail oeffs
+ coeffs = [None, {}]
+ assert_raises(ValueError, pywt.waverecn, coeffs, 'db1')
+
+ # use of None for a coefficient value
+ coeffs = [np.ones((2, 2, 2)), {}, {'daa': None}, ]
+ assert_raises(ValueError, pywt.waverecn, coeffs, 'db1')
+
+ # invalid key names in coefficient list
+ coeffs = [np.ones((4, 4, 4)), {'daa': np.ones((4, 4, 4)),
+ 'foo': np.ones((4, 4, 4))}]
+ assert_raises(ValueError, pywt.waverecn, coeffs, 'db1')
+
+ # mismatched key name lengths
+ coeffs = [np.ones((4, 4, 4)), {'daa': np.ones((4, 4, 4)),
+ 'da': np.ones((4, 4, 4))}]
+ assert_raises(ValueError, pywt.waverecn, coeffs, 'db1')
+
+ # key name lengths don't match the array dimensions
+ coeffs = [[[[1.0]]], {'ad': [[[0.0]]], 'da': [[[0.0]]], 'dd': [[[0.0]]]}]
+ assert_raises(ValueError, pywt.waverecn, coeffs, 'db1')
+
+ # input list cannot be empty
+ assert_raises(ValueError, pywt.waverecn, [], 'haar')
+
+
+def test_waverecn_invalid_inputs():
+
+ # coefficients from a difference decomposition used as input
+ for dec_func in [pywt.wavedec, pywt.wavedec2]:
+ coeffs = dec_func(np.ones((8, 8)), 'haar')
+ message = "Unexpected detail coefficient type"
+ assert_raises_regex(ValueError, message, pywt.waverecn, coeffs,
+ 'haar')
+
+
+def test_waverecn_lists():
+ # support coefficient arrays specified as lists instead of arrays
+ coeffs = [[[1.0]], {'ad': [[0.0]], 'da': [[0.0]], 'dd': [[0.0]]}]
+ assert_equal(pywt.waverecn(coeffs, 'db1').shape, (2, 2))
+
+
+def test_waverecn_invalid_coeffs2():
+ # shape mismatch should raise an error
+ coeffs = [np.ones((4, 4, 4)), {'ada': np.ones((4, 4))}]
+ assert_raises(ValueError, pywt.waverecn, coeffs, 'db1')
+
+
+def test_wavedecn_invalid_inputs():
+ # input array has too few dimensions
+ data = np.array(0)
+ assert_raises(ValueError, pywt.wavedecn, data, 'haar')
+
+ # invalid number of levels
+ data = np.ones(16)
+ assert_raises(ValueError, pywt.wavedecn, data, 'haar', level=-1)
+
+
+def test_wavedecn_many_levels():
+ # perfect reconstruction even when level > pywt.dwt_max_level
+ data = np.arange(64).reshape(8, 8)
+ tol = 1e-12
+ dec_funcs = [pywt.wavedec, pywt.wavedec2, pywt.wavedecn]
+ rec_funcs = [pywt.waverec, pywt.waverec2, pywt.waverecn]
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', UserWarning)
+ for dec_func, rec_func in zip(dec_funcs, rec_funcs):
+ for mode in ['periodization', 'symmetric']:
+ coeffs = dec_func(data, 'haar', mode=mode, level=20)
+ r = rec_func(coeffs, 'haar', mode=mode)
+ assert_allclose(data, r, atol=tol, rtol=tol)
+
+
+def test_waverecn_accuracies():
+ # testing 3D only here
+ rstate = np.random.RandomState(1234)
+ x0 = rstate.randn(4, 4, 4)
+ for dt, tol in dtypes_and_tolerances:
+ x = x0.astype(dt)
+ if np.iscomplexobj(x):
+ x += 1j*rstate.randn(4, 4, 4).astype(x.real.dtype)
+ coeffs = pywt.wavedecn(x.astype(dt), 'db1')
+ assert_allclose(pywt.waverecn(coeffs, 'db1'), x, atol=tol, rtol=tol)
+
+
+def test_multilevel_dtypes_nd():
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ # wavedecn, waverecn
+ x = np.ones((8, 8), dtype=dt_in)
+ errmsg = f"wrong dtype returned for {dt_in} input"
+ cA, coeffsD2, coeffsD1 = pywt.wavedecn(x, wavelet, level=2)
+ assert_(cA.dtype == dt_out, "wavedecn: " + errmsg)
+ for key, c in coeffsD1.items():
+ assert_(c.dtype == dt_out, "wavedecn: " + errmsg)
+ for key, c in coeffsD2.items():
+ assert_(c.dtype == dt_out, "wavedecn: " + errmsg)
+ x_roundtrip = pywt.waverecn([cA, coeffsD2, coeffsD1], wavelet)
+ assert_(x_roundtrip.dtype == dt_out, "waverecn: " + errmsg)
+
+
+def test_wavedecn_complex():
+ data = np.ones((4, 4, 4)) + 1j
+ coeffs = pywt.wavedecn(data, 'db1')
+ assert_allclose(pywt.waverecn(coeffs, 'db1'), data, rtol=1e-12)
+
+
+def test_waverecn_dtypes():
+ x = np.ones((4, 4, 4))
+ for dt, tol in dtypes_and_tolerances:
+ coeffs = pywt.wavedecn(x.astype(dt), 'db1')
+ assert_allclose(pywt.waverecn(coeffs, 'db1'), x, atol=tol, rtol=tol)
+
+
+@pytest.mark.slow
+def test_waverecn_all_wavelets_modes():
+ # test 2D case using all wavelets and modes
+ rstate = np.random.RandomState(1234)
+ r = rstate.randn(80, 96)
+ for wavelet in wavelist:
+ for mode in pywt.Modes.modes:
+ coeffs = pywt.wavedecn(r, wavelet, mode=mode)
+ assert_allclose(pywt.waverecn(coeffs, wavelet, mode=mode),
+ r, rtol=tol_single, atol=tol_single)
+
+
+def test_coeffs_to_array():
+ # single element list returns the first element
+ a_coeffs = [np.arange(8).reshape(2, 4), ]
+ arr, arr_slices = pywt.coeffs_to_array(a_coeffs)
+ assert_allclose(arr, a_coeffs[0])
+ assert_allclose(arr, arr[arr_slices[0]])
+
+ assert_raises(ValueError, pywt.coeffs_to_array, [])
+ # invalid second element: array as in wavedec, but not 1D
+ assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0], ] * 2)
+ # invalid second element: tuple as in wavedec2, but not a 3-tuple
+ assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs[0],
+ (a_coeffs[0], )])
+ # coefficients as None is not supported
+ assert_raises(ValueError, pywt.coeffs_to_array, [None, ])
+ assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs,
+ (None, None, None)])
+
+ # invalid type for second coefficient list element
+ assert_raises(ValueError, pywt.coeffs_to_array, [a_coeffs, None])
+
+ # use an invalid key name in the coef dictionary
+ coeffs = [np.array([0]), {'d': np.array([0]), 'c': np.array([0])}]
+ assert_raises(ValueError, pywt.coeffs_to_array, coeffs)
+
+
+def test_wavedecn_coeff_reshape_even():
+ # verify round trip is correct:
+ # wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
+ # This is done for wavedec{1, 2, n}
+ rng = np.random.RandomState(1234)
+ params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec},
+ 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2},
+ 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}}
+ N = 28
+ for f in params:
+ x1 = rng.randn(*([N] * params[f]['d']))
+ for mode in pywt.Modes.modes:
+ for wave in wavelist:
+ w = pywt.Wavelet(wave)
+ maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
+ if maxlevel == 0:
+ continue
+
+ coeffs = params[f]['dec'](x1, w, mode=mode)
+ coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
+ coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices,
+ output_format=f)
+ x1r = params[f]['rec'](coeffs2, w, mode=mode)
+
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+
+def test_wavedecn_coeff_reshape_axes_subset():
+ # verify round trip is correct when only a subset of axes are transformed:
+ # wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
+ # This is done for wavedec{1, 2, n}
+ rng = np.random.RandomState(1234)
+ mode = 'symmetric'
+ w = pywt.Wavelet('db2')
+ N = 16
+ ndim = 3
+ for axes in [(-1, ), (0, ), (1, ), (0, 1), (1, 2), (0, 2), None]:
+ x1 = rng.randn(*([N] * ndim))
+ coeffs = pywt.wavedecn(x1, w, mode=mode, axes=axes)
+ coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, axes=axes)
+ if axes is not None:
+ # if axes is not None, it must be provided to coeffs_to_array
+ assert_raises(ValueError, pywt.coeffs_to_array, coeffs)
+
+ # mismatched axes size
+ assert_raises(ValueError, pywt.coeffs_to_array, coeffs,
+ axes=(0, 1, 2, 3))
+ assert_raises(ValueError, pywt.coeffs_to_array, coeffs,
+ axes=())
+
+ coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices)
+ x1r = pywt.waverecn(coeffs2, w, mode=mode, axes=axes)
+
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+
+def test_coeffs_to_array_padding():
+ rng = np.random.RandomState(1234)
+ x1 = rng.randn(32, 32)
+ mode = 'symmetric'
+ coeffs = pywt.wavedecn(x1, 'db2', mode=mode)
+
+ # padding=None raises a ValueError when tight packing is not possible
+ assert_raises(ValueError, pywt.coeffs_to_array, coeffs, padding=None)
+
+ # set padded values to nan
+ coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, padding=np.nan)
+ npad = np.sum(np.isnan(coeff_arr))
+ assert_(npad > 0)
+
+ # pad with zeros
+ coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs, padding=0)
+ assert_(np.sum(np.isnan(coeff_arr)) == 0)
+ assert_(np.sum(coeff_arr == 0) == npad)
+
+ # Haar case with N as a power of 2 can be tightly packed
+ coeffs_haar = pywt.wavedecn(x1, 'haar', mode=mode)
+ coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs_haar, padding=None)
+ # shape of coeff_arr will match in this case, but not in general
+ assert_equal(coeff_arr.shape, x1.shape)
+
+
+def test_waverecn_coeff_reshape_odd():
+ # verify round trip is correct:
+ # wavedecn - >coeffs_to_array-> array_to_coeffs -> waverecn
+ rng = np.random.RandomState(1234)
+ x1 = rng.randn(35, 33)
+ for mode in pywt.Modes.modes:
+ for wave in ['haar', ]:
+ w = pywt.Wavelet(wave)
+ maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
+ if maxlevel == 0:
+ continue
+ coeffs = pywt.wavedecn(x1, w, mode=mode)
+ coeff_arr, coeff_slices = pywt.coeffs_to_array(coeffs)
+ coeffs2 = pywt.array_to_coeffs(coeff_arr, coeff_slices)
+ x1r = pywt.waverecn(coeffs2, w, mode=mode)
+ # truncate reconstructed values to original shape
+ x1r = x1r[tuple([slice(s) for s in x1.shape])]
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+
+def test_array_to_coeffs_invalid_inputs():
+ coeffs = pywt.wavedecn(np.ones(2), 'haar')
+ arr, arr_slices = pywt.coeffs_to_array(coeffs)
+
+ # empty list of array slices
+ assert_raises(ValueError, pywt.array_to_coeffs, arr, [])
+
+ # invalid format name
+ assert_raises(ValueError, pywt.array_to_coeffs, arr, arr_slices, 'foo')
+
+
+def test_wavedecn_coeff_ravel():
+ # verify round trip is correct:
+ # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn
+ # This is done for wavedec{1, 2, n}
+ rng = np.random.RandomState(1234)
+ params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec},
+ 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2},
+ 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}}
+ N = 12
+ for f in params:
+ x1 = rng.randn(*([N] * params[f]['d']))
+ for mode in pywt.Modes.modes:
+ for wave in wavelist:
+ w = pywt.Wavelet(wave)
+ maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
+ if maxlevel == 0:
+ continue
+
+ coeffs = params[f]['dec'](x1, w, mode=mode)
+ coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs)
+ coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes,
+ output_format=f)
+ x1r = params[f]['rec'](coeffs2, w, mode=mode)
+
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+
+def test_wavedecn_coeff_ravel_zero_level():
+ # verify round trip is correct:
+ # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn
+ # This is done for wavedec{1, 2, n}
+ rng = np.random.RandomState(1234)
+ params = {'wavedec': {'d': 1, 'dec': pywt.wavedec, 'rec': pywt.waverec},
+ 'wavedec2': {'d': 2, 'dec': pywt.wavedec2, 'rec': pywt.waverec2},
+ 'wavedecn': {'d': 3, 'dec': pywt.wavedecn, 'rec': pywt.waverecn}}
+ N = 16
+ for f in params:
+ x1 = rng.randn(*([N] * params[f]['d']))
+ for mode in pywt.Modes.modes:
+ w = pywt.Wavelet('db2')
+
+ coeffs = params[f]['dec'](x1, w, mode=mode, level=0)
+ coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs)
+ coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes,
+ output_format=f)
+ x1r = params[f]['rec'](coeffs2, w, mode=mode)
+
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+
+def test_waverecn_coeff_ravel_odd():
+ # verify round trip is correct:
+ # wavedecn - >ravel_coeffs-> unravel_coeffs -> waverecn
+ rng = np.random.RandomState(1234)
+ x1 = rng.randn(35, 33)
+ for mode in pywt.Modes.modes:
+ for wave in ['haar', ]:
+ w = pywt.Wavelet(wave)
+ maxlevel = pywt.dwt_max_level(np.min(x1.shape), w.dec_len)
+ if maxlevel == 0:
+ continue
+ coeffs = pywt.wavedecn(x1, w, mode=mode)
+ coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs)
+ coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes)
+ x1r = pywt.waverecn(coeffs2, w, mode=mode)
+ # truncate reconstructed values to original shape
+ x1r = x1r[tuple([slice(s) for s in x1.shape])]
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+
+def test_ravel_wavedec2_with_lists():
+ x1 = np.ones((8, 8))
+ wav = pywt.Wavelet('haar')
+ coeffs = pywt.wavedec2(x1, wav)
+
+ # list [cHn, cVn, cDn] instead of tuple is okay
+ coeffs[1:] = [list(c) for c in coeffs[1:]]
+ coeff_arr, slices, shapes = pywt.ravel_coeffs(coeffs)
+ coeffs2 = pywt.unravel_coeffs(coeff_arr, slices, shapes,
+ output_format='wavedec2')
+ x1r = pywt.waverec2(coeffs2, wav)
+ assert_allclose(x1, x1r, rtol=1e-4, atol=1e-4)
+
+ # wrong length list will cause a ValueError
+ coeffs[1:] = [list(c[:-1]) for c in coeffs[1:]] # truncate diag coeffs
+ assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
+
+
+def test_ravel_invalid_input():
+ # wavedec ravel does not support any coefficient arrays being set to None
+ coeffs = pywt.wavedec(np.ones(8), 'haar')
+ coeffs[1] = None
+ assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
+
+ # wavedec2 ravel cannot have None or a tuple/list of None
+ coeffs = pywt.wavedec2(np.ones((8, 8)), 'haar')
+ coeffs[1] = (None, None, None)
+ assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
+ coeffs[1] = [None, None, None]
+ assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
+ coeffs[1] = None
+ assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
+
+ # wavedecn ravel cannot have any dictionary elements as None
+ coeffs = pywt.wavedecn(np.ones((8, 8, 8)), 'haar')
+ coeffs[1]['ddd'] = None
+ assert_raises(ValueError, pywt.ravel_coeffs, coeffs)
+
+
+def test_unravel_invalid_inputs():
+ coeffs = pywt.wavedecn(np.ones(2), 'haar')
+ arr, slices, shapes = pywt.ravel_coeffs(coeffs)
+
+ # empty list for slices or shapes
+ assert_raises(ValueError, pywt.unravel_coeffs, arr, slices, [])
+ assert_raises(ValueError, pywt.unravel_coeffs, arr, [], shapes)
+
+ # unequal length for slices/shapes
+ assert_raises(ValueError, pywt.unravel_coeffs, arr, slices[:-1], shapes)
+
+ # invalid format name
+ assert_raises(ValueError, pywt.unravel_coeffs, arr, slices, shapes, 'foo')
+
+
+def test_wavedecn_shapes_and_size():
+ wav = pywt.Wavelet('db2')
+ for data_shape in [(33, ), (64, 32), (1, 15, 30)]:
+ for axes in [None, 0, -1]:
+ for mode in pywt.Modes.modes:
+ coeffs = pywt.wavedecn(np.ones(data_shape), wav,
+ mode=mode, axes=axes)
+
+ # verify that the shapes match the coefficient shapes
+ shapes = pywt.wavedecn_shapes(data_shape, wav,
+ mode=mode, axes=axes)
+
+ assert_equal(coeffs[0].shape, shapes[0])
+ expected_size = coeffs[0].size
+ for level in range(1, len(coeffs)):
+ for k, v in coeffs[level].items():
+ expected_size += v.size
+ assert_equal(shapes[level][k], v.shape)
+
+ # size can be determined from either the shapes or coeffs
+ size = pywt.wavedecn_size(shapes)
+ assert_equal(size, expected_size)
+
+ size = pywt.wavedecn_size(coeffs)
+ assert_equal(size, expected_size)
+
+
+def test_dwtn_max_level():
+ # predicted and empirical dwtn_max_level match
+ for wav in [pywt.Wavelet('db2'), 'sym8']:
+ for data_shape in [(33, ), (64, 32), (1, 15, 30)]:
+ for axes in [None, 0, -1]:
+ for mode in pywt.Modes.modes:
+ coeffs = pywt.wavedecn(np.ones(data_shape), wav,
+ mode=mode, axes=axes)
+ max_lev = pywt.dwtn_max_level(data_shape, wav, axes)
+ assert_equal(len(coeffs[1:]), max_lev)
+
+
+def test_waverec_axes_subsets():
+ rstate = np.random.RandomState(0)
+ data = rstate.standard_normal((8, 8, 8))
+ # test all combinations of 1 out of 3 axes transformed
+ for axis in [0, 1, 2]:
+ coefs = pywt.wavedec(data, 'haar', axis=axis)
+ rec = pywt.waverec(coefs, 'haar', axis=axis)
+ assert_allclose(rec, data, atol=1e-14)
+
+
+def test_waverec_axis_db2():
+ # test for fix to issue gh-293
+ rstate = np.random.RandomState(0)
+ data = rstate.standard_normal((16, 16))
+ for axis in [0, 1]:
+ coefs = pywt.wavedec(data, 'db2', axis=axis)
+ rec = pywt.waverec(coefs, 'db2', axis=axis)
+ assert_allclose(rec, data, atol=1e-14)
+
+
+def test_waverec2_axes_subsets():
+ rstate = np.random.RandomState(0)
+ data = rstate.standard_normal((8, 8, 8))
+ # test all combinations of 2 out of 3 axes transformed
+ for axes in combinations((0, 1, 2), 2):
+ coefs = pywt.wavedec2(data, 'haar', axes=axes)
+ rec = pywt.waverec2(coefs, 'haar', axes=axes)
+ assert_allclose(rec, data, atol=1e-14)
+
+
+def test_waverecn_axes_subsets():
+ rstate = np.random.RandomState(0)
+ data = rstate.standard_normal((8, 8, 8, 8))
+ # test all combinations of 3 out of 4 axes transformed
+ for axes in combinations((0, 1, 2, 3), 3):
+ coefs = pywt.wavedecn(data, 'haar', axes=axes)
+ rec = pywt.waverecn(coefs, 'haar', axes=axes)
+ assert_allclose(rec, data, atol=1e-14)
+
+
+def test_waverecn_int_axis():
+ # waverecn should also work for axes as an integer
+ rstate = np.random.RandomState(0)
+ data = rstate.standard_normal((8, 8))
+ for axis in [0, 1]:
+ coefs = pywt.wavedecn(data, 'haar', axes=axis)
+ rec = pywt.waverecn(coefs, 'haar', axes=axis)
+ assert_allclose(rec, data, atol=1e-14)
+
+
+def test_wavedec_axis_error():
+ data = np.ones(4)
+ # out of range axis not allowed
+ assert_raises(ValueError, pywt.wavedec, data, 'haar', axis=1)
+
+
+def test_waverec_axis_error():
+ c = pywt.wavedec(np.ones(4), 'haar')
+ # out of range axis not allowed
+ assert_raises(ValueError, pywt.waverec, c, 'haar', axis=1)
+
+
+def test_waverec_shape_mismatch_error():
+ c = pywt.wavedec(np.ones(16), 'haar')
+ # truncate a detail coefficient to an incorrect shape
+ c[3] = c[3][:-1]
+ assert_raises(ValueError, pywt.waverec, c, 'haar', axis=1)
+
+
+def test_wavedec2_axes_errors():
+ data = np.ones((4, 4))
+ # integer axes not allowed
+ assert_raises(TypeError, pywt.wavedec2, data, 'haar', axes=1)
+ # non-unique axes not allowed
+ assert_raises(ValueError, pywt.wavedec2, data, 'haar', axes=(0, 0))
+ # out of range axis not allowed
+ assert_raises(ValueError, pywt.wavedec2, data, 'haar', axes=(0, 2))
+
+
+def test_waverec2_axes_errors():
+ data = np.ones((4, 4))
+ c = pywt.wavedec2(data, 'haar')
+ # integer axes not allowed
+ assert_raises(TypeError, pywt.waverec2, c, 'haar', axes=1)
+ # non-unique axes not allowed
+ assert_raises(ValueError, pywt.waverec2, c, 'haar', axes=(0, 0))
+ # out of range axis not allowed
+ assert_raises(ValueError, pywt.waverec2, c, 'haar', axes=(0, 2))
+
+
+def test_wavedecn_axes_errors():
+ data = np.ones((8, 8, 8))
+ # repeated axes not allowed
+ assert_raises(ValueError, pywt.wavedecn, data, 'haar', axes=(1, 1))
+ # out of range axis not allowed
+ assert_raises(ValueError, pywt.wavedecn, data, 'haar', axes=(0, 1, 3))
+
+
+def test_waverecn_axes_errors():
+ data = np.ones((8, 8, 8))
+ c = pywt.wavedecn(data, 'haar')
+ # repeated axes not allowed
+ assert_raises(ValueError, pywt.waverecn, c, 'haar', axes=(1, 1))
+ # out of range axis not allowed
+ assert_raises(ValueError, pywt.waverecn, c, 'haar', axes=(0, 1, 3))
+
+
+def test_per_axis_wavelets_and_modes():
+ # tests separate wavelet and edge mode for each axis.
+ rstate = np.random.RandomState(1234)
+ data = rstate.randn(24, 24, 16)
+
+ # wavelet can be a string or wavelet object
+ wavelets = (pywt.Wavelet('haar'), 'sym2', 'db2')
+
+ # The default number of levels should be the minimum over this list
+ max_levels = [pywt._dwt.dwt_max_level(nd, nf) for nd, nf in
+ zip(data.shape, wavelets)]
+
+ # mode can be a string or a Modes enum
+ modes = ('symmetric', 'periodization',
+ pywt._extensions._pywt.Modes.reflect)
+
+ coefs = pywt.wavedecn(data, wavelets, modes)
+ assert_allclose(pywt.waverecn(coefs, wavelets, modes), data, atol=1e-14)
+ assert_equal(min(max_levels), len(coefs[1:]))
+
+ coefs = pywt.wavedecn(data, wavelets[:1], modes)
+ assert_allclose(pywt.waverecn(coefs, wavelets[:1], modes), data,
+ atol=1e-14)
+
+ coefs = pywt.wavedecn(data, wavelets, modes[:1])
+ assert_allclose(pywt.waverecn(coefs, wavelets, modes[:1]), data,
+ atol=1e-14)
+
+ # length of wavelets or modes doesn't match the length of axes
+ assert_raises(ValueError, pywt.wavedecn, data, wavelets[:2])
+ assert_raises(ValueError, pywt.wavedecn, data, wavelets, mode=modes[:2])
+ assert_raises(ValueError, pywt.waverecn, coefs, wavelets[:2])
+ assert_raises(ValueError, pywt.waverecn, coefs, wavelets, mode=modes[:2])
+
+ # dwt2/idwt2 also support per-axis wavelets/modes
+ data2 = data[..., 0]
+ coefs2 = pywt.wavedec2(data2, wavelets[:2], modes[:2])
+ assert_allclose(pywt.waverec2(coefs2, wavelets[:2], modes[:2]), data2,
+ atol=1e-14)
+ assert_equal(min(max_levels[:2]), len(coefs2[1:]))
+
+# Tests for fully separable multi-level transforms
+
+
+def test_fswavedecn_fswaverecn_roundtrip():
+ # verify proper round trip result for 1D through 4D data
+ # same DWT as wavedecn/waverecn so don't need to test all modes/wavelets
+ rstate = np.random.RandomState(0)
+ for ndim in range(1, 5):
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ for levels in (1, None):
+ data = rstate.standard_normal((8, )*ndim)
+ data = data.astype(dt_in)
+ T = pywt.fswavedecn(data, 'haar', levels=levels)
+ rec = pywt.fswaverecn(T)
+ if data.real.dtype in [np.float32, np.float16]:
+ assert_allclose(rec, data, rtol=1e-6, atol=1e-6)
+ else:
+ assert_allclose(rec, data, rtol=1e-14, atol=1e-14)
+ assert_(T.coeffs.dtype == dt_out)
+ assert_(rec.dtype == dt_out)
+
+
+def test_fswavedecn_fswaverecn_zero_levels():
+ # zero level transform gives coefs matching the original data
+ rstate = np.random.RandomState(0)
+ ndim = 2
+ data = rstate.standard_normal((8, )*ndim)
+ T = pywt.fswavedecn(data, 'haar', levels=0)
+ assert_array_equal(T.coeffs, data)
+ rec = pywt.fswaverecn(T)
+ assert_array_equal(T.coeffs, rec)
+
+
+def test_fswavedecn_fswaverecn_variable_levels():
+ # test with differing number of transform levels per axis
+ rstate = np.random.RandomState(0)
+ ndim = 3
+ data = rstate.standard_normal((16, )*ndim)
+ T = pywt.fswavedecn(data, 'haar', levels=(1, 2, 3))
+ rec = pywt.fswaverecn(T)
+ assert_allclose(rec, data, atol=1e-14)
+
+ # levels doesn't match number of axes
+ assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1))
+ assert_raises(ValueError, pywt.fswavedecn, data, 'haar', levels=(1, 1, 1, 1))
+
+ # levels too large for array size
+ assert_warns(UserWarning, pywt.fswavedecn, data, 'haar',
+ levels=int(np.log2(np.min(data.shape)))+1)
+
+
+def test_fswavedecn_fswaverecn_variable_wavelets_and_modes():
+ # test with differing number of transform levels per axis
+ rstate = np.random.RandomState(0)
+ ndim = 3
+ data = rstate.standard_normal((16, )*ndim)
+ wavelets = ('haar', 'db2', 'sym3')
+ modes = ('periodic', 'symmetric', 'periodization')
+ T = pywt.fswavedecn(data, wavelet=wavelets, mode=modes)
+ for ax in range(ndim):
+ # expect approx + dwt_max_level detail coeffs along each axis
+ assert_equal(len(T.coeff_slices[ax]),
+ pywt.dwt_max_level(data.shape[ax], wavelets[ax])+1)
+
+ rec = pywt.fswaverecn(T)
+ assert_allclose(rec, data, atol=1e-14)
+
+ # number of wavelets doesn't match number of axes
+ assert_raises(ValueError, pywt.fswavedecn, data, wavelets[:2])
+
+ # number of modes doesn't match number of axes
+ assert_raises(ValueError, pywt.fswavedecn, data, wavelets[0], mode=modes[:2])
+
+
+def test_fswavedecn_fswaverecn_axes_subsets():
+ """Fully separable DWT over only a subset of axes"""
+ rstate = np.random.RandomState(0)
+ # use anisotropic data to result in unique number of levels per axis
+ data = rstate.standard_normal((4, 8, 16, 32))
+ # test all combinations of 3 out of 4 axes transformed
+ for axes in combinations((0, 1, 2, 3), 3):
+ T = pywt.fswavedecn(data, 'haar', axes=axes)
+ rec = pywt.fswaverecn(T)
+ assert_allclose(rec, data, atol=1e-14)
+
+ # some axes exceed data dimensions
+ assert_raises(ValueError, pywt.fswavedecn, data, 'haar', axes=(1, 5))
+
+
+def test_fswavedecnresult():
+ data = np.ones((32, 32))
+ levels = (1, 2)
+ result = pywt.fswavedecn(data, 'sym2', levels=levels)
+
+ # can access the lowpass band via .approx or via __getitem__
+ approx_key = (0, ) * data.ndim
+ assert_array_equal(result[approx_key], result.approx)
+
+ dkeys = result.detail_keys()
+ # the approximation key shouldn't be present in the detail_keys
+ assert_(approx_key not in dkeys)
+
+ # can access all detail coefficients and they have matching ndim
+ for k in dkeys:
+ d = result[k]
+ assert_equal(d.ndim, data.ndim)
+
+ # can assign modified coefficients
+ result[k] = np.zeros_like(d)
+
+ # assigning a differently sized array raises a ValueError
+ assert_raises(ValueError, result.__setitem__,
+ k, np.zeros(tuple([s + 1 for s in d.shape])))
+
+ # warns on assigning with a non-matching dtype
+ assert_warns(UserWarning, result.__setitem__,
+ k, np.zeros_like(d).astype(np.float32))
+
+ # all coefficients are stacked into result.coeffs (same ndim)
+ assert_equal(result.coeffs.ndim, data.ndim)
+
+
+def test_error_on_continuous_wavelet():
+ # A ValueError is raised if a Continuous wavelet is selected
+ data = np.ones((16, 16))
+ for dec_fun, rec_fun in zip([pywt.wavedec, pywt.wavedec2, pywt.wavedecn],
+ [pywt.waverec, pywt.waverec2, pywt.waverecn]):
+ for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
+ assert_raises(ValueError, dec_fun, data, wavelet=cwave)
+
+ c = dec_fun(data, 'db1')
+ assert_raises(ValueError, rec_fun, c, wavelet=cwave)
+
+
+def test_default_level():
+ # default level is the maximum permissible for the transformed axes
+ data = np.ones((128, 32, 4))
+ wavelet = ('db8', 'db1')
+ for dec_func in [pywt.wavedec2, pywt.wavedecn]:
+ for axes in [(0, 1), (2, 1), (0, 2)]:
+ c = dec_func(data, wavelet, axes=axes)
+ max_lev = np.min([pywt.dwt_max_level(data.shape[ax], wav)
+ for ax, wav in zip(axes, wavelet)])
+ assert_equal(len(c[1:]), max_lev)
+
+ for ax in [0, 1]:
+ c = pywt.wavedecn(data, wavelet[ax], axes=(ax, ))
+ assert_equal(len(c[1:]),
+ pywt.dwt_max_level(data.shape[ax], wavelet[ax]))
+
+
+def test_waverec_mixed_precision():
+ rstate = np.random.RandomState(0)
+ for func, ifunc, shape in [(pywt.wavedec, pywt.waverec, (8, )),
+ (pywt.wavedec2, pywt.waverec2, (8, 8)),
+ (pywt.wavedecn, pywt.waverecn, (8, 8, 8))]:
+ x = rstate.randn(*shape)
+ coeffs_real = func(x, 'db1')
+
+ # real: single precision approx, double precision details
+ coeffs_real[0] = coeffs_real[0].astype(np.float32)
+ r = ifunc(coeffs_real, 'db1')
+ assert_allclose(r, x, rtol=1e-7, atol=1e-7)
+ assert_equal(r.dtype, np.float64)
+
+ x = x + 1j*x
+ coeffs = func(x, 'db1')
+
+ # complex: single precision approx, double precision details
+ coeffs[0] = coeffs[0].astype(np.complex64)
+ r = ifunc(coeffs, 'db1')
+ assert_allclose(r, x, rtol=1e-7, atol=1e-7)
+ assert_equal(r.dtype, np.complex128)
+
+ # complex: double precision approx, single precision details
+ if x.ndim == 1:
+ coeffs[0] = coeffs[0].astype(np.complex128)
+ coeffs[1] = coeffs[1].astype(np.complex64)
+ if x.ndim == 2:
+ coeffs[0] = coeffs[0].astype(np.complex128)
+ coeffs[1] = tuple([v.astype(np.complex64) for v in coeffs[1]])
+ if x.ndim == 3:
+ coeffs[0] = coeffs[0].astype(np.complex128)
+ coeffs[1] = {k: v.astype(np.complex64)
+ for k, v in coeffs[1].items()}
+ r = ifunc(coeffs, 'db1')
+ assert_allclose(r, x, rtol=1e-7, atol=1e-7)
+ assert_equal(r.dtype, np.complex128)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_perfect_reconstruction.py b/python_embeded/Lib/site-packages/pywt/tests/test_perfect_reconstruction.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1bf626886d345ebde79e6985d3b71c462107a63
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_perfect_reconstruction.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python
+
+"""
+Verify DWT perfect reconstruction.
+"""
+
+
+import numpy as np
+import pytest
+from numpy.testing import assert_
+
+import pywt
+
+
+@pytest.mark.slow
+def test_perfect_reconstruction():
+ families = ('db', 'sym', 'coif', 'bior', 'rbio')
+ wavelets = sum([pywt.wavelist(name) for name in families], [])
+ # list of mode names in pywt and matlab
+ modes = [('zero', 'zpd'),
+ ('constant', 'sp0'),
+ ('symmetric', 'sym'),
+ ('periodic', 'ppd'),
+ ('smooth', 'sp1'),
+ ('periodization', 'per')]
+
+ dtypes = (np.float32, np.float64)
+
+ for wavelet in wavelets:
+ for pmode, mmode in modes:
+ for dt in dtypes:
+ check_reconstruction(pmode, mmode, wavelet, dt)
+
+
+def check_reconstruction(pmode, mmode, wavelet, dtype):
+ data_size = list(range(2, 40)) + [100, 200, 500, 1000, 2000, 10000,
+ 50000, 100000]
+ np.random.seed(12345)
+ # TODO: smoke testing - more failures for different seeds
+
+ if dtype == np.float32:
+ # was 3e-7 has to be lowered as db21, db29, db33, db35, coif14, coif16 were failing
+ epsilon = 6e-7
+ else:
+ epsilon = 5e-11
+
+ for N in data_size:
+ data = np.asarray(np.random.random(N), dtype)
+
+ # compute dwt coefficients
+ pa, pd = pywt.dwt(data, wavelet, pmode)
+
+ # compute reconstruction
+ rec = pywt.idwt(pa, pd, wavelet, pmode)
+
+ if len(data) % 2:
+ rec = rec[:len(data)]
+
+ rms_rec = np.sqrt(np.mean((data-rec)**2))
+ msg = ('[RMS_REC > EPSILON] for Mode: %s, Wavelet: %s, '
+ 'Length: %d, rms=%.3g' % (pmode, wavelet, len(data), rms_rec))
+ assert_(rms_rec < epsilon, msg=msg)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_swt.py b/python_embeded/Lib/site-packages/pywt/tests/test_swt.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0311a291127cd62db43370eae62e2645d105916
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_swt.py
@@ -0,0 +1,638 @@
+#!/usr/bin/env python
+
+
+import warnings
+from copy import deepcopy
+from itertools import combinations, permutations
+
+import numpy as np
+import pytest
+from numpy.testing import (
+ assert_,
+ assert_allclose,
+ assert_array_equal,
+ assert_equal,
+ assert_raises,
+ assert_warns,
+)
+
+import pywt
+from pywt._extensions._swt import swt_axis
+
+# Check that float32 and complex64 are preserved. Other real types get
+# converted to float64.
+dtypes_in = [np.int8, np.float16, np.float32, np.float64, np.complex64,
+ np.complex128]
+dtypes_out = [np.float64, np.float32, np.float32, np.float64, np.complex64,
+ np.complex128]
+
+# tolerances used in accuracy comparisons
+tol_single = 1e-6
+tol_double = 1e-13
+
+####
+# 1d multilevel swt tests
+####
+
+
+def test_swt_decomposition():
+ x = [3, 7, 1, 3, -2, 6, 4, 6]
+ db1 = pywt.Wavelet('db1')
+ atol = tol_double
+ (cA3, cD3), (cA2, cD2), (cA1, cD1) = pywt.swt(x, db1, level=3)
+ expected_cA1 = [7.07106781, 5.65685425, 2.82842712, 0.70710678,
+ 2.82842712, 7.07106781, 7.07106781, 6.36396103]
+ assert_allclose(cA1, expected_cA1, rtol=1e-8, atol=atol)
+ expected_cD1 = [-2.82842712, 4.24264069, -1.41421356, 3.53553391,
+ -5.65685425, 1.41421356, -1.41421356, 2.12132034]
+ assert_allclose(cD1, expected_cD1, rtol=1e-8, atol=atol)
+ expected_cA2 = [7, 4.5, 4, 5.5, 7, 9.5, 10, 8.5]
+ assert_allclose(cA2, expected_cA2, rtol=tol_double, atol=atol)
+ expected_cD2 = [3, 3.5, 0, -4.5, -3, 0.5, 0, 0.5]
+ assert_allclose(cD2, expected_cD2, rtol=tol_double, atol=atol)
+ expected_cA3 = [9.89949494, ] * 8
+ assert_allclose(cA3, expected_cA3, rtol=1e-8, atol=atol)
+ expected_cD3 = [0.00000000, -3.53553391, -4.24264069, -2.12132034,
+ 0.00000000, 3.53553391, 4.24264069, 2.12132034]
+ assert_allclose(cD3, expected_cD3, rtol=1e-8, atol=atol)
+
+ # level=1, start_level=1 decomposition should match level=2
+ res = pywt.swt(cA1, db1, level=1, start_level=1)
+ cA2, cD2 = res[0]
+ assert_allclose(cA2, expected_cA2, rtol=tol_double, atol=atol)
+ assert_allclose(cD2, expected_cD2, rtol=tol_double, atol=atol)
+
+ coeffs = pywt.swt(x, db1)
+ assert_(len(coeffs) == 3)
+ assert_(pywt.swt_max_level(len(x)), 3)
+
+
+def test_swt_max_level():
+ # odd sized signal will warn about no levels of decomposition possible
+ assert_warns(UserWarning, pywt.swt_max_level, 11)
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', UserWarning)
+ assert_equal(pywt.swt_max_level(11), 0)
+
+ # no warnings when >= 1 level of decomposition possible
+ assert_equal(pywt.swt_max_level(2), 1) # divisible by 2**1
+ assert_equal(pywt.swt_max_level(4*3), 2) # divisible by 2**2
+ assert_equal(pywt.swt_max_level(16), 4) # divisible by 2**4
+ assert_equal(pywt.swt_max_level(16*3), 4) # divisible by 2**4
+
+
+def test_swt_axis():
+ x = [3, 7, 1, 3, -2, 6, 4, 6]
+
+ db1 = pywt.Wavelet('db1')
+ (cA2, cD2), (cA1, cD1) = pywt.swt(x, db1, level=2)
+
+ # test cases use 2D arrays based on tiling x along an axis and then
+ # calling swt along the other axis.
+ for order in ['C', 'F']:
+ # test SWT of 2D data along default axis (-1)
+ x_2d = np.asarray(x).reshape((1, -1))
+ x_2d = np.concatenate((x_2d, )*5, axis=0)
+ if order == 'C':
+ x_2d = np.ascontiguousarray(x_2d)
+ elif order == 'F':
+ x_2d = np.asfortranarray(x_2d)
+ (cA2_2d, cD2_2d), (cA1_2d, cD1_2d) = pywt.swt(x_2d, db1, level=2)
+
+ for c in [cA2_2d, cD2_2d, cA1_2d, cD1_2d]:
+ assert_(c.shape == x_2d.shape)
+ # each row should match the 1D result
+ for row in cA1_2d:
+ assert_array_equal(row, cA1)
+ for row in cA2_2d:
+ assert_array_equal(row, cA2)
+ for row in cD1_2d:
+ assert_array_equal(row, cD1)
+ for row in cD2_2d:
+ assert_array_equal(row, cD2)
+
+ # test SWT of 2D data along other axis (0)
+ x_2d = np.asarray(x).reshape((-1, 1))
+ x_2d = np.concatenate((x_2d, )*5, axis=1)
+ if order == 'C':
+ x_2d = np.ascontiguousarray(x_2d)
+ elif order == 'F':
+ x_2d = np.asfortranarray(x_2d)
+ (cA2_2d, cD2_2d), (cA1_2d, cD1_2d) = pywt.swt(x_2d, db1, level=2,
+ axis=0)
+
+ for c in [cA2_2d, cD2_2d, cA1_2d, cD1_2d]:
+ assert_(c.shape == x_2d.shape)
+ # each column should match the 1D result
+ for row in cA1_2d.transpose((1, 0)):
+ assert_array_equal(row, cA1)
+ for row in cA2_2d.transpose((1, 0)):
+ assert_array_equal(row, cA2)
+ for row in cD1_2d.transpose((1, 0)):
+ assert_array_equal(row, cD1)
+ for row in cD2_2d.transpose((1, 0)):
+ assert_array_equal(row, cD2)
+
+ # axis too large
+ assert_raises(ValueError, pywt.swt, x, db1, level=2, axis=5)
+
+
+def test_swt_iswt_integration():
+ # This function performs a round-trip swt/iswt transform test on
+ # all available types of wavelets in PyWavelets - except the
+ # 'dmey' wavelet. The latter has been excluded because it does not
+ # produce very precise results. This is likely due to the fact
+ # that the 'dmey' wavelet is a discrete approximation of a
+ # continuous wavelet. All wavelets are tested up to 3 levels. The
+ # test validates neither swt or iswt as such, but it does ensure
+ # that they are each other's inverse.
+
+ max_level = 3
+ wavelets = pywt.wavelist(kind='discrete')
+ if 'dmey' in wavelets:
+ # The 'dmey' wavelet seems to be a bit special - disregard it for now
+ wavelets.remove('dmey')
+ for current_wavelet_str in wavelets:
+ current_wavelet = pywt.Wavelet(current_wavelet_str)
+ input_length_power = int(np.ceil(np.log2(max(
+ current_wavelet.dec_len,
+ current_wavelet.rec_len))))
+ input_length = 2**(input_length_power + max_level - 1)
+ X = np.arange(input_length)
+ for norm in [True, False]:
+ if norm and not current_wavelet.orthogonal:
+ # non-orthogonal wavelets to avoid warnings when norm=True
+ continue
+ for trim_approx in [True, False]:
+ coeffs = pywt.swt(X, current_wavelet, max_level,
+ trim_approx=trim_approx, norm=norm)
+ Y = pywt.iswt(coeffs, current_wavelet, norm=norm)
+ assert_allclose(Y, X, rtol=1e-5, atol=1e-7)
+
+
+def test_swt_dtypes():
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ errmsg = f"wrong dtype returned for {dt_in} input"
+
+ # swt
+ x = np.ones(8, dtype=dt_in)
+ (cA2, cD2), (cA1, cD1) = pywt.swt(x, wavelet, level=2)
+ assert_(cA2.dtype == cD2.dtype == cA1.dtype == cD1.dtype == dt_out,
+ "swt: " + errmsg)
+
+ # swt2
+ x = np.ones((8, 8), dtype=dt_in)
+ cA, (cH, cV, cD) = pywt.swt2(x, wavelet, level=1)[0]
+ assert_(cA.dtype == cH.dtype == cV.dtype == cD.dtype == dt_out,
+ "swt2: " + errmsg)
+
+
+def test_swt_roundtrip_dtypes():
+ # verify perfect reconstruction for all dtypes
+ rstate = np.random.RandomState(5)
+ wavelet = pywt.Wavelet('haar')
+ for dt_in, dt_out in zip(dtypes_in, dtypes_out):
+ # swt, iswt
+ x = rstate.standard_normal((8, )).astype(dt_in)
+ c = pywt.swt(x, wavelet, level=2)
+ xr = pywt.iswt(c, wavelet)
+ assert_allclose(x, xr, rtol=1e-6, atol=1e-7)
+
+ # swt2, iswt2
+ x = rstate.standard_normal((8, 8)).astype(dt_in)
+ c = pywt.swt2(x, wavelet, level=2)
+ xr = pywt.iswt2(c, wavelet)
+ assert_allclose(x, xr, rtol=1e-6, atol=1e-7)
+
+
+def test_swt_default_level_by_axis():
+ # make sure default number of levels matches the max level along the axis
+ wav = 'db2'
+ x = np.ones((2**3, 2**4, 2**5))
+ for axis in (0, 1, 2):
+ sdec = pywt.swt(x, wav, level=None, start_level=0, axis=axis)
+ assert_equal(len(sdec), pywt.swt_max_level(x.shape[axis]))
+
+
+def test_swt2_ndim_error():
+ x = np.ones(8)
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', FutureWarning)
+ assert_raises(ValueError, pywt.swt2, x, 'haar', level=1)
+
+
+@pytest.mark.slow
+def test_swt2_iswt2_integration(wavelets=None):
+ # This function performs a round-trip swt2/iswt2 transform test on
+ # all available types of wavelets in PyWavelets - except the
+ # 'dmey' wavelet. The latter has been excluded because it does not
+ # produce very precise results. This is likely due to the fact
+ # that the 'dmey' wavelet is a discrete approximation of a
+ # continuous wavelet. All wavelets are tested up to 3 levels. The
+ # test validates neither swt2 or iswt2 as such, but it does ensure
+ # that they are each other's inverse.
+
+ max_level = 3
+ if wavelets is None:
+ wavelets = pywt.wavelist(kind='discrete')
+ if 'dmey' in wavelets:
+ # The 'dmey' wavelet is a special case - disregard it for now
+ wavelets.remove('dmey')
+ for current_wavelet_str in wavelets:
+ current_wavelet = pywt.Wavelet(current_wavelet_str)
+ input_length_power = int(np.ceil(np.log2(max(
+ current_wavelet.dec_len,
+ current_wavelet.rec_len))))
+ input_length = 2**(input_length_power + max_level - 1)
+ X = np.arange(input_length**2).reshape(input_length, input_length)
+
+ for norm in [True, False]:
+ if norm and not current_wavelet.orthogonal:
+ # non-orthogonal wavelets to avoid warnings when norm=True
+ continue
+ for trim_approx in [True, False]:
+ coeffs = pywt.swt2(X, current_wavelet, max_level,
+ trim_approx=trim_approx, norm=norm)
+ Y = pywt.iswt2(coeffs, current_wavelet, norm=norm)
+ assert_allclose(Y, X, rtol=1e-5, atol=1e-5)
+
+
+def test_swt2_iswt2_quick():
+ test_swt2_iswt2_integration(wavelets=['db1', ])
+
+
+def test_swt2_iswt2_non_square(wavelets=None):
+ for nrows in [8, 16, 48]:
+ X = np.arange(nrows*32).reshape(nrows, 32)
+ current_wavelet = 'db1'
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', FutureWarning)
+ coeffs = pywt.swt2(X, current_wavelet, level=2)
+ Y = pywt.iswt2(coeffs, current_wavelet)
+ assert_allclose(Y, X, rtol=tol_single, atol=tol_single)
+
+
+def test_swt2_axes():
+ atol = 1e-14
+ current_wavelet = pywt.Wavelet('db2')
+ input_length_power = int(np.ceil(np.log2(max(
+ current_wavelet.dec_len,
+ current_wavelet.rec_len))))
+ input_length = 2**(input_length_power)
+ X = np.arange(input_length**2).reshape(input_length, input_length)
+
+ (cA1, (cH1, cV1, cD1)) = pywt.swt2(X, current_wavelet, level=1)[0]
+ # opposite order
+ (cA2, (cH2, cV2, cD2)) = pywt.swt2(X, current_wavelet, level=1,
+ axes=(1, 0))[0]
+ assert_allclose(cA1, cA2, atol=atol)
+ assert_allclose(cH1, cV2, atol=atol)
+ assert_allclose(cV1, cH2, atol=atol)
+ assert_allclose(cD1, cD2, atol=atol)
+
+ # reverify iswt2 restores the original data
+ r1 = pywt.iswt2([cA1, (cH1, cV1, cD1)], current_wavelet)
+ assert_allclose(X, r1, atol=atol)
+ r2 = pywt.iswt2([cA2, (cH2, cV2, cD2)], current_wavelet, axes=(1, 0))
+ assert_allclose(X, r2, atol=atol)
+
+ # duplicate axes not allowed
+ assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1,
+ axes=(0, 0))
+ # too few axes
+ assert_raises(ValueError, pywt.swt2, X, current_wavelet, 1, axes=(0, ))
+
+
+def test_swtn_axes():
+ atol = 1e-14
+ current_wavelet = pywt.Wavelet('db2')
+ input_length_power = int(np.ceil(np.log2(max(
+ current_wavelet.dec_len,
+ current_wavelet.rec_len))))
+ input_length = 2**(input_length_power)
+ X = np.arange(input_length**2).reshape(input_length, input_length)
+ coeffs = pywt.swtn(X, current_wavelet, level=1, axes=None)[0]
+ # opposite order
+ coeffs2 = pywt.swtn(X, current_wavelet, level=1, axes=(1, 0))[0]
+ assert_allclose(coeffs['aa'], coeffs2['aa'], atol=atol)
+ assert_allclose(coeffs['ad'], coeffs2['da'], atol=atol)
+ assert_allclose(coeffs['da'], coeffs2['ad'], atol=atol)
+ assert_allclose(coeffs['dd'], coeffs2['dd'], atol=atol)
+
+ # 0-level transform
+ empty = pywt.swtn(X, current_wavelet, level=0)
+ assert_equal(empty, [])
+
+ # duplicate axes not allowed
+ assert_raises(ValueError, pywt.swtn, X, current_wavelet, 1, axes=(0, 0))
+
+ # data.ndim = 0
+ assert_raises(ValueError, pywt.swtn, np.asarray([]), current_wavelet, 1)
+
+ # start_level too large
+ assert_raises(ValueError, pywt.swtn, X, current_wavelet,
+ level=1, start_level=2)
+
+ # level < 1 in swt_axis call
+ assert_raises(ValueError, swt_axis, X, current_wavelet, level=0,
+ start_level=0)
+ # odd-sized data not allowed
+ assert_raises(ValueError, swt_axis, X[:-1, :], current_wavelet, level=0,
+ start_level=0, axis=0)
+
+
+@pytest.mark.slow
+def test_swtn_iswtn_integration(wavelets=None):
+ # This function performs a round-trip swtn/iswtn transform for various
+ # possible combinations of:
+ # 1.) 1 out of 2 axes of a 2D array
+ # 2.) 2 out of 3 axes of a 3D array
+ #
+ # To keep test time down, only wavelets of length <= 8 are run.
+ #
+ # This test does not validate swtn or iswtn individually, but only
+ # confirms that iswtn yields an (almost) perfect reconstruction of swtn.
+ max_level = 3
+ if wavelets is None:
+ wavelets = pywt.wavelist(kind='discrete')
+ if 'dmey' in wavelets:
+ # The 'dmey' wavelet is a special case - disregard it for now
+ wavelets.remove('dmey')
+ for ndim_transform in range(1, 3):
+ ndim = ndim_transform + 1
+ for axes in combinations(range(ndim), ndim_transform):
+ for current_wavelet_str in wavelets:
+ wav = pywt.Wavelet(current_wavelet_str)
+ if wav.dec_len > 8:
+ continue # avoid excessive test duration
+ input_length_power = int(np.ceil(np.log2(max(
+ wav.dec_len,
+ wav.rec_len))))
+ N = 2**(input_length_power + max_level - 1)
+ X = np.arange(N**ndim).reshape((N, )*ndim)
+
+ for norm in [True, False]:
+ if norm and not wav.orthogonal:
+ # non-orthogonal wavelets to avoid warnings
+ continue
+ for trim_approx in [True, False]:
+ coeffs = pywt.swtn(X, wav, max_level, axes=axes,
+ trim_approx=trim_approx, norm=norm)
+ coeffs_copy = deepcopy(coeffs)
+ Y = pywt.iswtn(coeffs, wav, axes=axes, norm=norm)
+ assert_allclose(Y, X, rtol=1e-5, atol=1e-5)
+
+ # verify the inverse transform didn't modify any coeffs
+ for c, c2 in zip(coeffs, coeffs_copy):
+ for k, v in c.items():
+ assert_array_equal(c2[k], v)
+
+
+def test_swtn_iswtn_quick():
+ test_swtn_iswtn_integration(wavelets=['db1', ])
+
+
+def test_iswtn_errors():
+ x = np.arange(8**3).reshape(8, 8, 8)
+ max_level = 2
+ axes = (0, 1)
+ w = pywt.Wavelet('db1')
+ coeffs = pywt.swtn(x, w, max_level, axes=axes)
+
+ # more axes than dimensions transformed
+ assert_raises(ValueError, pywt.iswtn, coeffs, w, axes=(0, 1, 2))
+ # duplicate axes not allowed
+ assert_raises(ValueError, pywt.iswtn, coeffs, w, axes=(0, 0))
+ # mismatched coefficient size
+ coeffs[0]['da'] = coeffs[0]['da'][:-1, :]
+ assert_raises(RuntimeError, pywt.iswtn, coeffs, w, axes=axes)
+
+
+def test_swtn_iswtn_unique_shape_per_axis():
+ # test case for gh-460
+ _shape = (1, 48, 32) # unique shape per axis
+ wav = 'sym2'
+ max_level = 3
+ rstate = np.random.RandomState(0)
+ for shape in permutations(_shape):
+ # transform only along the non-singleton axes
+ axes = [ax for ax, s in enumerate(shape) if s != 1]
+ x = rstate.standard_normal(shape)
+ c = pywt.swtn(x, wav, max_level, axes=axes)
+ r = pywt.iswtn(c, wav, axes=axes)
+ assert_allclose(x, r, rtol=1e-10, atol=1e-10)
+
+
+def test_per_axis_wavelets():
+ # tests separate wavelet for each axis.
+ rstate = np.random.RandomState(1234)
+ data = rstate.randn(16, 16, 16)
+ level = 3
+
+ # wavelet can be a string or wavelet object
+ wavelets = (pywt.Wavelet('haar'), 'sym2', 'db4')
+
+ coefs = pywt.swtn(data, wavelets, level=level)
+ assert_allclose(pywt.iswtn(coefs, wavelets), data, atol=1e-14)
+
+ # 1-tuple also okay
+ coefs = pywt.swtn(data, wavelets[:1], level=level)
+ assert_allclose(pywt.iswtn(coefs, wavelets[:1]), data, atol=1e-14)
+
+ # length of wavelets doesn't match the length of axes
+ assert_raises(ValueError, pywt.swtn, data, wavelets[:2], level)
+ assert_raises(ValueError, pywt.iswtn, coefs, wavelets[:2])
+
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', FutureWarning)
+ # swt2/iswt2 also support per-axis wavelets/modes
+ data2 = data[..., 0]
+ coefs2 = pywt.swt2(data2, wavelets[:2], level)
+ assert_allclose(pywt.iswt2(coefs2, wavelets[:2]), data2, atol=1e-14)
+
+
+def test_error_on_continuous_wavelet():
+ # A ValueError is raised if a Continuous wavelet is selected
+ data = np.ones((16, 16))
+ for dec_func, rec_func in zip([pywt.swt, pywt.swt2, pywt.swtn],
+ [pywt.iswt, pywt.iswt2, pywt.iswtn]):
+ for cwave in ['morl', pywt.DiscreteContinuousWavelet('morl')]:
+ assert_raises(ValueError, dec_func, data, wavelet=cwave,
+ level=3)
+
+ c = dec_func(data, 'db1', level=3)
+ assert_raises(ValueError, rec_func, c, wavelet=cwave)
+
+
+def test_iswt_mixed_dtypes():
+ # Mixed precision inputs give double precision output
+ x_real = np.arange(16).astype(np.float64)
+ x_complex = x_real + 1j*x_real
+ wav = 'sym2'
+ for dtype1, dtype2 in [(np.float64, np.float32),
+ (np.float32, np.float64),
+ (np.float16, np.float64),
+ (np.complex128, np.complex64),
+ (np.complex64, np.complex128)]:
+
+ if dtype1 in [np.complex64, np.complex128]:
+ x = x_complex
+ output_dtype = np.complex128
+ else:
+ x = x_real
+ output_dtype = np.float64
+
+ coeffs = pywt.swt(x, wav, 2)
+ # different precision for the approximation coefficients
+ coeffs[0] = [coeffs[0][0].astype(dtype1),
+ coeffs[0][1].astype(dtype2)]
+ y = pywt.iswt(coeffs, wav)
+ assert_equal(output_dtype, y.dtype)
+ assert_allclose(y, x, rtol=1e-3, atol=1e-3)
+
+
+def test_iswt2_mixed_dtypes():
+ # Mixed precision inputs give double precision output
+ rstate = np.random.RandomState(0)
+ x_real = rstate.randn(8, 8)
+ x_complex = x_real + 1j*x_real
+ wav = 'sym2'
+ for dtype1, dtype2 in [(np.float64, np.float32),
+ (np.float32, np.float64),
+ (np.float16, np.float64),
+ (np.complex128, np.complex64),
+ (np.complex64, np.complex128)]:
+
+ if dtype1 in [np.complex64, np.complex128]:
+ x = x_complex
+ output_dtype = np.complex128
+ else:
+ x = x_real
+ output_dtype = np.float64
+
+ coeffs = pywt.swt2(x, wav, 2)
+ # different precision for the approximation coefficients
+ coeffs[0] = [coeffs[0][0].astype(dtype1),
+ tuple([c.astype(dtype2) for c in coeffs[0][1]])]
+ y = pywt.iswt2(coeffs, wav)
+ assert_equal(output_dtype, y.dtype)
+ assert_allclose(y, x, rtol=1e-3, atol=1e-3)
+
+
+def test_iswtn_mixed_dtypes():
+ # Mixed precision inputs give double precision output
+ rstate = np.random.RandomState(0)
+ x_real = rstate.randn(8, 8, 8)
+ x_complex = x_real + 1j*x_real
+ wav = 'sym2'
+ for dtype1, dtype2 in [(np.float64, np.float32),
+ (np.float32, np.float64),
+ (np.float16, np.float64),
+ (np.complex128, np.complex64),
+ (np.complex64, np.complex128)]:
+
+ if dtype1 in [np.complex64, np.complex128]:
+ x = x_complex
+ output_dtype = np.complex128
+ else:
+ x = x_real
+ output_dtype = np.float64
+
+ coeffs = pywt.swtn(x, wav, 2)
+ # different precision for the approximation coefficients
+ a = coeffs[0].pop('a' * x.ndim)
+ a = a.astype(dtype1)
+ coeffs[0] = {k: c.astype(dtype2) for k, c in coeffs[0].items()}
+ coeffs[0]['a' * x.ndim] = a
+ y = pywt.iswtn(coeffs, wav)
+ assert_equal(output_dtype, y.dtype)
+ assert_allclose(y, x, rtol=1e-3, atol=1e-3)
+
+
+def test_swt_zero_size_axes():
+ # raise on empty input array
+ assert_raises(ValueError, pywt.swt, [], 'db2')
+
+ # >1D case uses a different code path so check there as well
+ x = np.ones((1, 4))[0:0, :] # 2D with a size zero axis
+ assert_raises(ValueError, pywt.swtn, x, 'db2', level=1, axes=(0,))
+
+
+def test_swt_variance_and_energy_preservation():
+ """Verify that the 1D SWT partitions variance among the coefficients."""
+ # When norm is True and the wavelet is orthogonal, the sum of the
+ # variances of the coefficients should equal the variance of the signal.
+ wav = 'db2'
+ rstate = np.random.RandomState(5)
+ x = rstate.randn(256)
+ coeffs = pywt.swt(x, wav, trim_approx=True, norm=True)
+ variances = [np.var(c) for c in coeffs]
+ assert_allclose(np.sum(variances), np.var(x))
+
+ # also verify L2-norm energy preservation property
+ assert_allclose(np.linalg.norm(x),
+ np.linalg.norm(np.concatenate(coeffs)))
+
+ # non-orthogonal wavelet with norm=True raises a warning
+ assert_warns(UserWarning, pywt.swt, x, 'bior2.2', norm=True)
+
+
+def test_swt2_variance_and_energy_preservation():
+ """Verify that the 2D SWT partitions variance among the coefficients."""
+ # When norm is True and the wavelet is orthogonal, the sum of the
+ # variances of the coefficients should equal the variance of the signal.
+ wav = 'db2'
+ rstate = np.random.RandomState(5)
+ x = rstate.randn(64, 64)
+ coeffs = pywt.swt2(x, wav, level=4, trim_approx=True, norm=True)
+ coeff_list = [coeffs[0].ravel()]
+ for d in coeffs[1:]:
+ for v in d:
+ coeff_list.append(v.ravel())
+ variances = [np.var(v) for v in coeff_list]
+ assert_allclose(np.sum(variances), np.var(x))
+
+ # also verify L2-norm energy preservation property
+ assert_allclose(np.linalg.norm(x),
+ np.linalg.norm(np.concatenate(coeff_list)))
+
+ # non-orthogonal wavelet with norm=True raises a warning
+ assert_warns(UserWarning, pywt.swt2, x, 'bior2.2', level=4, norm=True)
+
+
+def test_swtn_variance_and_energy_preservation():
+ """Verify that the nD SWT partitions variance among the coefficients."""
+ # When norm is True and the wavelet is orthogonal, the sum of the
+ # variances of the coefficients should equal the variance of the signal.
+ wav = 'db2'
+ rstate = np.random.RandomState(5)
+ x = rstate.randn(64, 64)
+ coeffs = pywt.swtn(x, wav, level=4, trim_approx=True, norm=True)
+ coeff_list = [coeffs[0].ravel()]
+ for d in coeffs[1:]:
+ for k, v in d.items():
+ coeff_list.append(v.ravel())
+ variances = [np.var(v) for v in coeff_list]
+ assert_allclose(np.sum(variances), np.var(x))
+
+ # also verify L2-norm energy preservation property
+ assert_allclose(np.linalg.norm(x),
+ np.linalg.norm(np.concatenate(coeff_list)))
+
+ # non-orthogonal wavelet with norm=True raises a warning
+ assert_warns(UserWarning, pywt.swtn, x, 'bior2.2', level=4, norm=True)
+
+
+def test_swt_ravel_and_unravel():
+ # When trim_approx=True, all swt functions can user pywt.ravel_coeffs
+ for ndim, _swt, _iswt, ravel_type in [
+ (1, pywt.swt, pywt.iswt, 'swt'),
+ (2, pywt.swt2, pywt.iswt2, 'swt2'),
+ (3, pywt.swtn, pywt.iswtn, 'swtn')]:
+ x = np.ones((16, ) * ndim)
+ c = _swt(x, 'sym2', level=3, trim_approx=True)
+ arr, slices, shapes = pywt.ravel_coeffs(c)
+ c = pywt.unravel_coeffs(arr, slices, shapes, output_format=ravel_type)
+ r = _iswt(c, 'sym2')
+ assert_allclose(x, r)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_thresholding.py b/python_embeded/Lib/site-packages/pywt/tests/test_thresholding.py
new file mode 100644
index 0000000000000000000000000000000000000000..e7ce2ae59f511b7ba7a2339997569dc52498669f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_thresholding.py
@@ -0,0 +1,167 @@
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises
+
+import pywt
+
+float_dtypes = [np.float32, np.float64, np.complex64, np.complex128]
+real_dtypes = [np.float32, np.float64]
+
+
+def _sign(x):
+ # Matlab-like sign function (numpy uses a different convention).
+ return x / np.abs(x)
+
+
+def _soft(x, thresh):
+ """soft thresholding supporting complex values.
+
+ Notes
+ -----
+ This version is not robust to zeros in x.
+ """
+ return _sign(x) * np.maximum(np.abs(x) - thresh, 0)
+
+
+def test_threshold():
+ data = np.linspace(1, 4, 7)
+
+ # soft
+ soft_result = [0., 0., 0., 0.5, 1., 1.5, 2.]
+ assert_allclose(pywt.threshold(data, 2, 'soft'),
+ np.array(soft_result), rtol=1e-12)
+ assert_allclose(pywt.threshold(-data, 2, 'soft'),
+ -np.array(soft_result), rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'soft'),
+ [[0, 1]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'soft'),
+ [[0, 0]] * 2, rtol=1e-12)
+
+ # soft thresholding complex values
+ assert_allclose(pywt.threshold([[1j, 2j]] * 2, 1, 'soft'),
+ [[0j, 1j]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1+1j, 2+2j]] * 2, 6, 'soft'),
+ [[0, 0]] * 2, rtol=1e-12)
+ complex_data = [[1+2j, 2+2j]]*2
+ for thresh in [1, 2]:
+ assert_allclose(pywt.threshold(complex_data, thresh, 'soft'),
+ _soft(complex_data, thresh), rtol=1e-12)
+
+ # test soft thresholding with non-default substitute argument
+ s = 5
+ assert_allclose(pywt.threshold([[1j, 2]] * 2, 1.5, 'soft', substitute=s),
+ [[s, 0.5]] * 2, rtol=1e-12)
+
+ # soft: no divide by zero warnings when input contains zeros
+ assert_allclose(pywt.threshold(np.zeros(16), 2, 'soft'),
+ np.zeros(16), rtol=1e-12)
+
+ # hard
+ hard_result = [0., 0., 2., 2.5, 3., 3.5, 4.]
+ assert_allclose(pywt.threshold(data, 2, 'hard'),
+ np.array(hard_result), rtol=1e-12)
+ assert_allclose(pywt.threshold(-data, 2, 'hard'),
+ -np.array(hard_result), rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'hard'),
+ [[1, 2]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'hard'),
+ [[0, 2]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'hard', substitute=s),
+ [[s, 2]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1+1j, 2+2j]] * 2, 2, 'hard'),
+ [[0, 2+2j]] * 2, rtol=1e-12)
+
+ # greater
+ greater_result = [0., 0., 2., 2.5, 3., 3.5, 4.]
+ assert_allclose(pywt.threshold(data, 2, 'greater'),
+ np.array(greater_result), rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'greater'),
+ [[1, 2]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'greater'),
+ [[0, 2]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'greater', substitute=s),
+ [[s, 2]] * 2, rtol=1e-12)
+ # greater doesn't allow complex-valued inputs
+ assert_raises(ValueError, pywt.threshold, [1j, 2j], 2, 'greater')
+
+ # less
+ assert_allclose(pywt.threshold(data, 2, 'less'),
+ np.array([1., 1.5, 2., 0., 0., 0., 0.]), rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'less'),
+ [[1, 0]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 1, 'less', substitute=s),
+ [[1, s]] * 2, rtol=1e-12)
+ assert_allclose(pywt.threshold([[1, 2]] * 2, 2, 'less'),
+ [[1, 2]] * 2, rtol=1e-12)
+
+ # less doesn't allow complex-valued inputs
+ assert_raises(ValueError, pywt.threshold, [1j, 2j], 2, 'less')
+
+ # invalid
+ assert_raises(ValueError, pywt.threshold, data, 2, 'foo')
+
+
+def test_nonnegative_garotte():
+ thresh = 0.3
+ data_real = np.linspace(-1, 1, 100)
+ for dtype in float_dtypes:
+ if dtype in real_dtypes:
+ data = np.asarray(data_real, dtype=dtype)
+ else:
+ data = np.asarray(data_real + 0.1j, dtype=dtype)
+ d_hard = pywt.threshold(data, thresh, 'hard')
+ d_soft = pywt.threshold(data, thresh, 'soft')
+ d_garotte = pywt.threshold(data, thresh, 'garotte')
+
+ # check dtypes
+ assert_equal(d_hard.dtype, data.dtype)
+ assert_equal(d_soft.dtype, data.dtype)
+ assert_equal(d_garotte.dtype, data.dtype)
+
+ # values < threshold are zero
+ lt = np.where(np.abs(data) < thresh)
+ assert_(np.all(d_garotte[lt] == 0))
+
+ # values > than the threshold are intermediate between soft and hard
+ gt = np.where(np.abs(data) > thresh)
+ gt_abs_garotte = np.abs(d_garotte[gt])
+ assert_(np.all(gt_abs_garotte < np.abs(d_hard[gt])))
+ assert_(np.all(gt_abs_garotte > np.abs(d_soft[gt])))
+
+
+def test_threshold_firm():
+ thresh = 0.2
+ thresh2 = 3 * thresh
+ data_real = np.linspace(-1, 1, 100)
+ for dtype in float_dtypes:
+ if dtype in real_dtypes:
+ data = np.asarray(data_real, dtype=dtype)
+ else:
+ data = np.asarray(data_real + 0.1j, dtype=dtype)
+ if data.real.dtype == np.float32:
+ rtol = atol = 1e-6
+ else:
+ rtol = atol = 1e-14
+ d_hard = pywt.threshold(data, thresh, 'hard')
+ d_soft = pywt.threshold(data, thresh, 'soft')
+ d_firm = pywt.threshold_firm(data, thresh, thresh2)
+
+ # check dtypes
+ assert_equal(d_hard.dtype, data.dtype)
+ assert_equal(d_soft.dtype, data.dtype)
+ assert_equal(d_firm.dtype, data.dtype)
+
+ # values < threshold are zero
+ lt = np.where(np.abs(data) < thresh)
+ assert_(np.all(d_firm[lt] == 0))
+
+ # values > than the threshold are equal to hard-thresholding
+ gt = np.where(np.abs(data) >= thresh2)
+ assert_allclose(np.abs(d_hard[gt]), np.abs(d_firm[gt]),
+ rtol=rtol, atol=atol)
+
+ # other values are intermediate between soft and hard thresholding
+ mt = np.where(np.logical_and(np.abs(data) > thresh,
+ np.abs(data) < thresh2))
+ mt_abs_firm = np.abs(d_firm[mt])
+ assert_(np.all(mt_abs_firm < np.abs(d_hard[mt])))
+ assert_(np.all(mt_abs_firm > np.abs(d_soft[mt])))
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_wavelet.py b/python_embeded/Lib/site-packages/pywt/tests/test_wavelet.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7056ed18b8da53af29472f503f07d2d99a11a2c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_wavelet.py
@@ -0,0 +1,278 @@
+#!/usr/bin/env python
+import os
+import pickle
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose
+
+import pywt
+
+
+def test_wavelet_properties():
+ w = pywt.Wavelet('db3')
+
+ # Name
+ assert_(w.name == 'db3')
+ assert_(w.short_family_name == 'db')
+ assert_(w.family_name, 'Daubechies')
+
+ # String representation
+ fields = ('Family name', 'Short name', 'Filters length', 'Orthogonal',
+ 'Biorthogonal', 'Symmetry')
+ for field in fields:
+ assert_(field in str(w))
+
+ # Filter coefficients
+ dec_lo = [0.03522629188210, -0.08544127388224, -0.13501102001039,
+ 0.45987750211933, 0.80689150931334, 0.33267055295096]
+ dec_hi = [-0.33267055295096, 0.80689150931334, -0.45987750211933,
+ -0.13501102001039, 0.08544127388224, 0.03522629188210]
+ rec_lo = [0.33267055295096, 0.80689150931334, 0.45987750211933,
+ -0.13501102001039, -0.08544127388224, 0.03522629188210]
+ rec_hi = [0.03522629188210, 0.08544127388224, -0.13501102001039,
+ -0.45987750211933, 0.80689150931334, -0.33267055295096]
+ assert_allclose(w.dec_lo, dec_lo)
+ assert_allclose(w.dec_hi, dec_hi)
+ assert_allclose(w.rec_lo, rec_lo)
+ assert_allclose(w.rec_hi, rec_hi)
+
+ assert_(len(w.filter_bank) == 4)
+
+ # Orthogonality
+ assert_(w.orthogonal)
+ assert_(w.biorthogonal)
+
+ # Symmetry
+ assert_(w.symmetry)
+
+ # Vanishing moments
+ assert_(w.vanishing_moments_phi == 0)
+ assert_(w.vanishing_moments_psi == 3)
+
+
+def test_wavelet_coefficients():
+ families = ('db', 'sym', 'coif', 'bior', 'rbio')
+ wavelets = sum([pywt.wavelist(name) for name in families], [])
+ for wavelet in wavelets:
+ if (pywt.Wavelet(wavelet).orthogonal):
+ check_coefficients_orthogonal(wavelet)
+ elif(pywt.Wavelet(wavelet).biorthogonal):
+ check_coefficients_biorthogonal(wavelet)
+ else:
+ check_coefficients(wavelet)
+
+
+def check_coefficients_orthogonal(wavelet):
+
+ epsilon = 5e-11
+ level = 5
+ w = pywt.Wavelet(wavelet)
+ phi, psi, x = w.wavefun(level=level)
+
+ # Lowpass filter coefficients sum to sqrt2
+ res = np.sum(w.dec_lo)-np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # sum even coef = sum odd coef = 1 / sqrt(2)
+ res = np.sum(w.dec_lo[::2])-1./np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+
+ res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # Highpass filter coefficients sum to zero
+ res = np.sum(w.dec_hi)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # Scaling function integrates to unity
+
+ res = np.sum(phi) - 2**level
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # Wavelet function is orthogonal to the scaling function at the same scale
+ res = np.sum(phi*psi)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # The lowpass and highpass filter coefficients are orthogonal
+ res = np.sum(np.array(w.dec_lo)*np.array(w.dec_hi))
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+
+
+def check_coefficients_biorthogonal(wavelet):
+
+ epsilon = 5e-11
+ level = 5
+ w = pywt.Wavelet(wavelet)
+ phi_d, psi_d, phi_r, psi_r, x = w.wavefun(level=level)
+
+ # Lowpass filter coefficients sum to sqrt2
+ res = np.sum(w.dec_lo)-np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # sum even coef = sum odd coef = 1 / sqrt(2)
+ res = np.sum(w.dec_lo[::2])-1./np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # Highpass filter coefficients sum to zero
+ res = np.sum(w.dec_hi)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # Scaling function integrates to unity
+ res = np.sum(phi_d) - 2**level
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ res = np.sum(phi_r) - 2**level
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+
+
+def check_coefficients(wavelet):
+ epsilon = 5e-11
+ level = 10
+ w = pywt.Wavelet(wavelet)
+ # Lowpass filter coefficients sum to sqrt2
+ res = np.sum(w.dec_lo)-np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # sum even coef = sum odd coef = 1 / sqrt(2)
+ res = np.sum(w.dec_lo[::2])-1./np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+
+ res = np.sum(w.dec_lo[1::2])-1./np.sqrt(2)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+ # Highpass filter coefficients sum to zero
+ res = np.sum(w.dec_hi)
+ msg = f'[RMS_REC > EPSILON] for Wavelet: {wavelet}, rms={res:.3g}'
+ assert_(res < epsilon, msg=msg)
+
+
+class _CustomHaarFilterBank:
+ @property
+ def filter_bank(self):
+ val = np.sqrt(2) / 2
+ return ([val]*2, [-val, val], [val]*2, [val, -val])
+
+
+def test_custom_wavelet():
+ haar_custom1 = pywt.Wavelet('Custom Haar Wavelet',
+ filter_bank=_CustomHaarFilterBank())
+ haar_custom1.orthogonal = True
+ haar_custom1.biorthogonal = True
+
+ val = np.sqrt(2) / 2
+ filter_bank = ([val]*2, [-val, val], [val]*2, [val, -val])
+ haar_custom2 = pywt.Wavelet('Custom Haar Wavelet',
+ filter_bank=filter_bank)
+
+ # check expected default wavelet properties
+ assert_(not haar_custom2.orthogonal)
+ assert_(not haar_custom2.biorthogonal)
+ assert_(haar_custom2.symmetry == 'unknown')
+ assert_(haar_custom2.family_name == '')
+ assert_(haar_custom2.short_family_name == '')
+ assert_(haar_custom2.vanishing_moments_phi == 0)
+ assert_(haar_custom2.vanishing_moments_psi == 0)
+
+ # Some properties can be set by the user
+ haar_custom2.orthogonal = True
+ haar_custom2.biorthogonal = True
+
+
+def test_wavefun_sym3():
+ w = pywt.Wavelet('sym3')
+ # sym3 is an orthogonal wavelet, so 3 outputs from wavefun
+ phi, psi, x = w.wavefun(level=3)
+ assert_(phi.size == 41)
+ assert_(psi.size == 41)
+ assert_(x.size == 41)
+
+ assert_allclose(x, np.linspace(0, 5, num=x.size))
+ phi_expect = np.array([0.00000000e+00, 1.04132926e-01, 2.52574126e-01,
+ 3.96525521e-01, 5.70356539e-01, 7.18934305e-01,
+ 8.70293448e-01, 1.05363620e+00, 1.24921722e+00,
+ 1.15296888e+00, 9.41669683e-01, 7.55875887e-01,
+ 4.96118565e-01, 3.28293151e-01, 1.67624969e-01,
+ -7.33690312e-02, -3.35452855e-01, -3.31221131e-01,
+ -2.32061503e-01, -1.66854239e-01, -4.34091324e-02,
+ -2.86152390e-02, -3.63563035e-02, 2.06034491e-02,
+ 8.30280254e-02, 7.17779073e-02, 3.85914311e-02,
+ 1.47527100e-02, -2.31896077e-02, -1.86122172e-02,
+ -1.56211329e-03, -8.70615088e-04, 3.20760857e-03,
+ 2.34142153e-03, -7.73737194e-04, -2.99879354e-04,
+ 1.23636238e-04, 0.00000000e+00, 0.00000000e+00,
+ 0.00000000e+00, 0.00000000e+00])
+
+ psi_expect = np.array([0.00000000e+00, 1.10265752e-02, 2.67449277e-02,
+ 4.19878574e-02, 6.03947231e-02, 7.61275365e-02,
+ 9.21548684e-02, 1.11568926e-01, 1.32278887e-01,
+ 6.45829680e-02, -3.97635130e-02, -1.38929884e-01,
+ -2.62428322e-01, -3.62246804e-01, -4.62843343e-01,
+ -5.89607507e-01, -7.25363076e-01, -3.36865858e-01,
+ 2.67715108e-01, 8.40176767e-01, 1.55574430e+00,
+ 1.18688954e+00, 4.20276324e-01, -1.51697311e-01,
+ -9.42076108e-01, -7.93172332e-01, -3.26343710e-01,
+ -1.24552779e-01, 2.12909254e-01, 1.75770320e-01,
+ 1.47523075e-02, 8.22192707e-03, -3.02920592e-02,
+ -2.21119497e-02, 7.30703025e-03, 2.83200488e-03,
+ -1.16759765e-03, 0.00000000e+00, 0.00000000e+00,
+ 0.00000000e+00, 0.00000000e+00])
+
+ assert_allclose(phi, phi_expect)
+ assert_allclose(psi, psi_expect)
+
+
+def test_wavefun_bior13():
+ w = pywt.Wavelet('bior1.3')
+ # bior1.3 is not an orthogonal wavelet, so 5 outputs from wavefun
+ phi_d, psi_d, phi_r, psi_r, x = w.wavefun(level=3)
+ for arr in [phi_d, psi_d, phi_r, psi_r]:
+ assert_(arr.size == 40)
+
+ phi_d_expect = np.array([0., -0.00195313, 0.00195313, 0.01757813,
+ 0.01367188, 0.00390625, -0.03515625, -0.12890625,
+ -0.15234375, -0.125, -0.09375, -0.0625, 0.03125,
+ 0.15234375, 0.37890625, 0.78515625, 0.99609375,
+ 1.08203125, 1.13671875, 1.13671875, 1.08203125,
+ 0.99609375, 0.78515625, 0.37890625, 0.15234375,
+ 0.03125, -0.0625, -0.09375, -0.125, -0.15234375,
+ -0.12890625, -0.03515625, 0.00390625, 0.01367188,
+ 0.01757813, 0.00195313, -0.00195313, 0., 0., 0.])
+ phi_r_expect = np.zeros(x.size, dtype=np.float64)
+ phi_r_expect[15:23] = 1
+
+ psi_d_expect = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0.015625, -0.015625, -0.140625, -0.109375,
+ -0.03125, 0.28125, 1.03125, 1.21875, 1.125, 0.625,
+ -0.625, -1.125, -1.21875, -1.03125, -0.28125,
+ 0.03125, 0.109375, 0.140625, 0.015625, -0.015625,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+
+ psi_r_expect = np.zeros(x.size, dtype=np.float64)
+ psi_r_expect[7:15] = -0.125
+ psi_r_expect[15:19] = 1
+ psi_r_expect[19:23] = -1
+ psi_r_expect[23:31] = 0.125
+
+ assert_allclose(x, np.linspace(0, 5, x.size, endpoint=False))
+ assert_allclose(phi_d, phi_d_expect, rtol=1e-5, atol=1e-9)
+ assert_allclose(phi_r, phi_r_expect, rtol=1e-10, atol=1e-12)
+ assert_allclose(psi_d, psi_d_expect, rtol=1e-10, atol=1e-12)
+ assert_allclose(psi_r, psi_r_expect, rtol=1e-10, atol=1e-12)
+
+
+def test_wavelet_pickle(tmpdir):
+ wavelet = pywt.Wavelet('sym4')
+ filename = os.path.join(tmpdir, 'wav.pickle')
+ with open(filename, 'wb') as f:
+ pickle.dump(wavelet, f)
+ with open(filename, 'rb') as f:
+ wavelet2 = pickle.load(f)
+ assert isinstance(wavelet2, pywt.Wavelet)
+ assert wavelet2.name == wavelet.name
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_wp.py b/python_embeded/Lib/site-packages/pywt/tests/test_wp.py
new file mode 100644
index 0000000000000000000000000000000000000000..90b598984739af5546908f17185b4791237e401e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_wp.py
@@ -0,0 +1,243 @@
+#!/usr/bin/env python
+
+import os
+import pickle
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises
+
+import pywt
+
+
+def test_wavelet_packet_structure():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(wp.data == [1, 2, 3, 4, 5, 6, 7, 8])
+ assert_(wp.path == '')
+ assert_(wp.level == 0)
+ assert_(wp['ad'].maxlevel == 3)
+
+
+def test_traversing_wp_tree():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(wp.maxlevel == 3)
+
+ # First level
+ assert_allclose(wp['a'].data, np.array([2.12132034356, 4.949747468306,
+ 7.778174593052, 10.606601717798]),
+ rtol=1e-12)
+
+ # Second level
+ assert_allclose(wp['aa'].data, np.array([5., 13.]), rtol=1e-12)
+
+ # Third level
+ assert_allclose(wp['aaa'].data, np.array([12.727922061358]), rtol=1e-12)
+
+
+def test_acess_path():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(wp['a'].path == 'a')
+ assert_(wp['aa'].path == 'aa')
+ assert_(wp['aaa'].path == 'aaa')
+
+ # Maximum level reached:
+ assert_raises(IndexError, lambda: wp['aaaa'].path)
+
+ # Wrong path
+ assert_raises(ValueError, lambda: wp['ac'].path)
+
+
+def test_access_node_attributes():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+
+ assert_allclose(wp['ad'].data, np.array([-2., -2.]), rtol=1e-12)
+ assert_(wp['ad'].path == 'ad')
+ assert_(wp['ad'].node_name == 'd')
+ assert_(wp['ad'].parent.path == 'a')
+ assert_(wp['ad'].level == 2)
+ assert_(wp['ad'].maxlevel == 3)
+ assert_(wp['ad'].mode == 'symmetric')
+
+ # tuple-based access is also supported
+ node = wp[('a', 'd')]
+ # can access a node's path as either a single string or in tuple form
+ assert_(node.path == 'ad')
+ assert_(node.path_tuple == ('a', 'd'))
+
+
+def test_collecting_nodes():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+
+ # All nodes in natural order
+ assert_([node.path for node in wp.get_level(3, 'natural')] ==
+ ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd'])
+
+ # and in frequency order.
+ assert_([node.path for node in wp.get_level(3, 'freq')] ==
+ ['aaa', 'aad', 'add', 'ada', 'dda', 'ddd', 'dad', 'daa'])
+
+ assert_raises(ValueError, wp.get_level, 3, 'invalid_order')
+
+
+def test_reconstructing_data():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+
+ # Create another Wavelet Packet and feed it with some data.
+ new_wp = pywt.WaveletPacket(data=None, wavelet='db1', mode='symmetric')
+ new_wp['aa'] = wp['aa'].data
+ new_wp['ad'] = [-2., -2.]
+
+ # For convenience, :attr:`Node.data` gets automatically extracted
+ # from the :class:`Node` object:
+ new_wp['d'] = wp['d']
+
+ # Reconstruct data from aa, ad, and d packets.
+ assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12)
+
+ # The node's :attr:`~Node.data` will not be updated
+ assert_(new_wp.data is None)
+
+ # When `update` is True:
+ assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12)
+ assert_allclose(new_wp.data, np.arange(1, 9), rtol=1e-12)
+
+ assert_([n.path for n in new_wp.get_leaf_nodes(False)] ==
+ ['aa', 'ad', 'd'])
+ assert_([n.path for n in new_wp.get_leaf_nodes(True)] ==
+ ['aaa', 'aad', 'ada', 'add', 'daa', 'dad', 'dda', 'ddd'])
+
+
+def test_removing_nodes():
+ x = [1, 2, 3, 4, 5, 6, 7, 8]
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+ wp.get_level(2)
+
+ dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
+ expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]])
+
+ for i in range(4):
+ assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)
+
+ node = wp['ad']
+ del(wp['ad'])
+ dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
+ expected = np.array([[5., 13.], [-1, -1], [0, 0]])
+
+ for i in range(3):
+ assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)
+
+ wp.reconstruct()
+ # The reconstruction is:
+ assert_allclose(wp.reconstruct(),
+ np.array([2., 3., 2., 3., 6., 7., 6., 7.]), rtol=1e-12)
+
+ # Restore the data
+ wp['ad'].data = node.data
+
+ dataleafs = [n.data for n in wp.get_leaf_nodes(False)]
+ expected = np.array([[5., 13.], [-2, -2], [-1, -1], [0, 0]])
+
+ for i in range(4):
+ assert_allclose(dataleafs[i], expected[i, :], atol=1e-12)
+
+ assert_allclose(wp.reconstruct(), np.arange(1, 9), rtol=1e-12)
+
+
+def test_wavelet_packet_dtypes():
+ rstate = np.random.RandomState(0)
+ N = 32
+ for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
+ x = rstate.randn(N).astype(dtype)
+ if np.iscomplexobj(x):
+ x = x + 1j*np.random.randn(N).astype(x.real.dtype)
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric')
+ # no unnecessary copy made
+ assert_(wp.data is x)
+
+ # assigning to a node should not change supported dtypes
+ wp['d'] = wp['d'].data
+ assert_equal(wp['d'].data.dtype, x.dtype)
+
+ # full decomposition
+ wp.get_level(wp.maxlevel)
+
+ # reconstruction from coefficients should preserve dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, x.dtype)
+ assert_allclose(r, x, atol=1e-5, rtol=1e-5)
+
+ # first element of the tuple is the input dtype
+ # second element of the tuple is the transform dtype
+ dtype_pairs = [(np.uint8, np.float64),
+ (np.intp, np.float64), ]
+ if hasattr(np, "complex256"):
+ dtype_pairs += [(np.complex256, np.complex128), ]
+ if hasattr(np, "half"):
+ dtype_pairs += [(np.half, np.float32), ]
+ for (dtype, transform_dtype) in dtype_pairs:
+ x = np.arange(N, dtype=dtype)
+ wp = pywt.WaveletPacket(x, wavelet='db1', mode='symmetric')
+
+ # no unnecessary copy made of top-level data
+ assert_(wp.data is x)
+
+ # full decomposition
+ wp.get_level(wp.maxlevel)
+
+ # reconstructed data will have modified dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, transform_dtype)
+ assert_allclose(r, x.astype(transform_dtype), atol=1e-5, rtol=1e-5)
+
+
+def test_db3_roundtrip():
+ original = np.arange(512)
+ wp = pywt.WaveletPacket(data=original, wavelet='db3', mode='smooth',
+ maxlevel=3)
+ r = wp.reconstruct()
+ assert_allclose(original, r, atol=1e-12, rtol=1e-12)
+
+
+def test_wavelet_packet_axis():
+ rstate = np.random.RandomState(0)
+ shape = (32, 16)
+ x = rstate.standard_normal(shape)
+ for axis in [0, 1, -1]:
+ wp = pywt.WaveletPacket(data=x, wavelet='db1', mode='symmetric',
+ axis=axis)
+
+ # partial decomposition
+ nodes = wp.get_level(2)
+ # size along the transformed axis has changed
+ for ax2 in range(x.ndim):
+ if ax2 == (axis % x.ndim):
+ nodes[0].data.shape[ax2] < x.shape[ax2]
+ else:
+ nodes[0].data.shape[ax2] == x.shape[ax2]
+
+ # recontsruction from coefficients should preserve dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, x.dtype)
+ assert_allclose(r, x, atol=1e-12, rtol=1e-12)
+
+ # ValueError if axis is out of range
+ assert_raises(ValueError, pywt.WaveletPacket, data=x, wavelet='db1',
+ axis=x.ndim)
+
+
+def test_wavelet_packet_pickle(tmpdir):
+ packet = pywt.WaveletPacket(np.arange(16), 'sym4')
+ filename = os.path.join(tmpdir, 'wp.pickle')
+ with open(filename, 'wb') as f:
+ pickle.dump(packet, f)
+ with open(filename, 'rb') as f:
+ packet2 = pickle.load(f)
+ assert isinstance(packet2, pywt.WaveletPacket)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_wp2d.py b/python_embeded/Lib/site-packages/pywt/tests/test_wp2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba30588f7921ff97c55f02f007f048d892ef157f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_wp2d.py
@@ -0,0 +1,244 @@
+#!/usr/bin/env python
+
+import os
+import pickle
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises
+
+import pywt
+
+
+def test_traversing_tree_2d():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(np.all(wp.data == x))
+ assert_(wp.path == '')
+ assert_(wp.level == 0)
+ assert_(wp.maxlevel == 3)
+
+ assert_allclose(wp['a'].data, np.array([[3., 7., 11., 15.]] * 4),
+ rtol=1e-12)
+ assert_allclose(wp['h'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14)
+ assert_allclose(wp['v'].data, -np.ones((4, 4)), rtol=1e-12, atol=1e-14)
+ assert_allclose(wp['d'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14)
+
+ assert_allclose(wp['aa'].data, np.array([[10., 26.]] * 2), rtol=1e-12)
+
+ assert_(wp['a']['a'].data is wp['aa'].data)
+ assert_allclose(wp['aaa'].data, np.array([[36.]]), rtol=1e-12)
+
+ assert_raises(IndexError, lambda: wp['aaaa'])
+ assert_raises(ValueError, lambda: wp['f'])
+
+
+def test_accessing_node_attributes_2d():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+
+ assert_allclose(wp['av'].data, np.zeros((2, 2)) - 4, rtol=1e-12)
+ assert_(wp['av'].path == 'av')
+ assert_(wp['av'].node_name == 'v')
+ assert_(wp['av'].parent.path == 'a')
+
+ assert_allclose(wp['av'].parent.data, np.array([[3., 7., 11., 15.]] * 4),
+ rtol=1e-12)
+ # can also index via a tuple instead of concatenated strings
+ assert_(wp['av'].level == 2)
+ assert_(wp['av'].maxlevel == 3)
+ assert_(wp['av'].mode == 'symmetric')
+
+ # tuple-based access is also supported
+ node = wp[('a', 'v')]
+ # can access a node's path as either a single string or in tuple form
+ assert_(node.path == 'av')
+ assert_(node.path_tuple == ('a', 'v'))
+
+
+def test_collecting_nodes_2d():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(len(wp.get_level(0)) == 1)
+ assert_(wp.get_level(0)[0].path == '')
+
+ # First level
+ assert_(len(wp.get_level(1)) == 4)
+ assert_([node.path for node in wp.get_level(1)] == ['a', 'h', 'v', 'd'])
+
+ # Second level
+ assert_(len(wp.get_level(2)) == 16)
+ paths = [node.path for node in wp.get_level(2)]
+ expected_paths = ['aa', 'ah', 'av', 'ad', 'ha', 'hh', 'hv', 'hd', 'va',
+ 'vh', 'vv', 'vd', 'da', 'dh', 'dv', 'dd']
+ assert_(paths == expected_paths)
+
+ # Third level.
+ assert_(len(wp.get_level(3)) == 64)
+ paths = [node.path for node in wp.get_level(3)]
+ expected_paths = ['aaa', 'aah', 'aav', 'aad', 'aha', 'ahh', 'ahv', 'ahd',
+ 'ava', 'avh', 'avv', 'avd', 'ada', 'adh', 'adv', 'add',
+ 'haa', 'hah', 'hav', 'had', 'hha', 'hhh', 'hhv', 'hhd',
+ 'hva', 'hvh', 'hvv', 'hvd', 'hda', 'hdh', 'hdv', 'hdd',
+ 'vaa', 'vah', 'vav', 'vad', 'vha', 'vhh', 'vhv', 'vhd',
+ 'vva', 'vvh', 'vvv', 'vvd', 'vda', 'vdh', 'vdv', 'vdd',
+ 'daa', 'dah', 'dav', 'dad', 'dha', 'dhh', 'dhv', 'dhd',
+ 'dva', 'dvh', 'dvv', 'dvd', 'dda', 'ddh', 'ddv', 'ddd']
+
+ assert_(paths == expected_paths)
+
+ # test 2D frequency ordering at the first level
+ fnodes = wp.get_level(1, order='freq')
+ assert_(fnodes[0][0].path == 'a')
+ assert_(fnodes[0][1].path == 'v')
+ assert_(fnodes[1][0].path == 'h')
+ assert_(fnodes[1][1].path == 'd')
+
+ # test 2D frequency ordering at the second level
+ fnodes = wp.get_level(2, order='freq')
+ assert_([n.path for n in fnodes[0]] == ['aa', 'av', 'vv', 'va'])
+ assert_([n.path for n in fnodes[1]] == ['ah', 'ad', 'vd', 'vh'])
+ assert_([n.path for n in fnodes[2]] == ['hh', 'hd', 'dd', 'dh'])
+ assert_([n.path for n in fnodes[3]] == ['ha', 'hv', 'dv', 'da'])
+
+ # invalid node collection order
+ assert_raises(ValueError, wp.get_level, 2, 'invalid_order')
+
+
+def test_data_reconstruction_2d():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+
+ new_wp = pywt.WaveletPacket2D(data=None, wavelet='db1', mode='symmetric')
+ new_wp['vh'] = wp['vh'].data
+ new_wp['vv'] = wp['vh'].data
+ new_wp['vd'] = np.zeros((2, 2), dtype=np.float64)
+ new_wp['a'] = [[3.0, 7.0, 11.0, 15.0]] * 4
+ new_wp['d'] = np.zeros((4, 4), dtype=np.float64)
+ new_wp['h'] = wp['h'] # all zeros
+
+ assert_allclose(new_wp.reconstruct(update=False),
+ np.array([[1.5, 1.5, 3.5, 3.5, 5.5, 5.5, 7.5, 7.5]] * 8),
+ rtol=1e-12)
+ assert_allclose(wp['va'].data, np.zeros((2, 2)) - 2, rtol=1e-12)
+
+ new_wp['va'] = wp['va'].data
+ assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12)
+
+
+def test_data_reconstruction_delete_nodes_2d():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+
+ new_wp = pywt.WaveletPacket2D(data=None, wavelet='db1', mode='symmetric')
+ new_wp['vh'] = wp['vh'].data
+ new_wp['vv'] = wp['vh'].data
+ new_wp['vd'] = np.zeros((2, 2), dtype=np.float64)
+ new_wp['a'] = [[3.0, 7.0, 11.0, 15.0]] * 4
+ new_wp['d'] = np.zeros((4, 4), dtype=np.float64)
+ new_wp['h'] = wp['h'] # all zeros
+
+ assert_allclose(new_wp.reconstruct(update=False),
+ np.array([[1.5, 1.5, 3.5, 3.5, 5.5, 5.5, 7.5, 7.5]] * 8),
+ rtol=1e-12)
+
+ new_wp['va'] = wp['va'].data
+ assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12)
+
+ del(new_wp['va'])
+ # TypeError on accessing deleted node
+ assert_raises(TypeError, lambda: new_wp['va'])
+ new_wp['va'] = wp['va'].data
+ assert_(new_wp.data is None)
+
+ assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12)
+ assert_allclose(new_wp.data, x, rtol=1e-12)
+
+ # TODO: decompose=True
+
+
+def test_lazy_evaluation_2D():
+ # Note: internal implementation detail not to be relied on. Testing for
+ # now for backwards compatibility, but this test may be broken in needed.
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(wp.a is None)
+ assert_allclose(wp['a'].data, np.array([[3., 7., 11., 15.]] * 4),
+ rtol=1e-12)
+ assert_allclose(wp.a.data, np.array([[3., 7., 11., 15.]] * 4), rtol=1e-12)
+ assert_allclose(wp.d.data, np.zeros((4, 4)), rtol=1e-12, atol=1e-12)
+
+
+def test_wavelet_packet_dtypes():
+ shape = (16, 16)
+ for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
+ x = np.random.randn(*shape).astype(dtype)
+ if np.iscomplexobj(x):
+ x = x + 1j*np.random.randn(*shape).astype(x.real.dtype)
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric')
+ # no unnecessary copy made
+ assert_(wp.data is x)
+
+ # assigning to a node should not change supported dtypes
+ wp['d'] = wp['d'].data
+ assert_equal(wp['d'].data.dtype, x.dtype)
+
+ # full decomposition
+ wp.get_level(wp.maxlevel)
+
+ # reconstruction from coefficients should preserve dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, x.dtype)
+ assert_allclose(r, x, atol=1e-5, rtol=1e-5)
+
+
+def test_2d_roundtrip():
+ # test case corresponding to PyWavelets issue 447
+ original = pywt.data.camera()
+ wp = pywt.WaveletPacket2D(data=original, wavelet='db3', mode='smooth',
+ maxlevel=3)
+ r = wp.reconstruct()
+ assert_allclose(original, r, atol=1e-12, rtol=1e-12)
+
+
+def test_wavelet_packet_axes():
+ rstate = np.random.RandomState(0)
+ shape = (32, 16)
+ x = rstate.standard_normal(shape)
+ for axes in [(0, 1), (1, 0), (-2, 1)]:
+ wp = pywt.WaveletPacket2D(data=x, wavelet='db1', mode='symmetric',
+ axes=axes)
+
+ # partial decomposition
+ nodes = wp.get_level(2)
+ # size along the transformed axes has changed
+ for ax2 in range(x.ndim):
+ if ax2 in tuple(np.asarray(axes) % x.ndim):
+ nodes[0].data.shape[ax2] < x.shape[ax2]
+ else:
+ nodes[0].data.shape[ax2] == x.shape[ax2]
+
+ # recontsruction from coefficients should preserve dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, x.dtype)
+ assert_allclose(r, x, atol=1e-12, rtol=1e-12)
+
+ # must have two non-duplicate axes
+ assert_raises(ValueError, pywt.WaveletPacket2D, data=x, wavelet='db1',
+ axes=(0, 0))
+ assert_raises(ValueError, pywt.WaveletPacket2D, data=x, wavelet='db1',
+ axes=(0, ))
+ assert_raises(ValueError, pywt.WaveletPacket2D, data=x, wavelet='db1',
+ axes=(0, 1, 2))
+
+
+def test_wavelet_packet2d_pickle(tmpdir):
+ packet = pywt.WaveletPacket2D(np.arange(256).reshape(16, 16), 'sym4')
+ filename = os.path.join(tmpdir, 'wp2d.pickle')
+ with open(filename, 'wb') as f:
+ pickle.dump(packet, f)
+ with open(filename, 'rb') as f:
+ packet2 = pickle.load(f)
+ assert isinstance(packet2, pywt.WaveletPacket2D)
diff --git a/python_embeded/Lib/site-packages/pywt/tests/test_wpnd.py b/python_embeded/Lib/site-packages/pywt/tests/test_wpnd.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa8c82b351e91d84243e07fdf60ca452598bc80b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pywt/tests/test_wpnd.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env python
+
+
+import operator
+from functools import reduce
+from itertools import product
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal, assert_raises
+
+import pywt
+
+
+def test_traversing_tree_nd():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(np.all(wp.data == x))
+ assert_(wp.path == '')
+ assert_(wp.level == 0)
+ assert_(wp.maxlevel == 3)
+
+ assert_allclose(wp['aa'].data, np.array([[3., 7., 11., 15.]] * 4),
+ rtol=1e-12)
+ assert_allclose(wp['da'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14)
+ assert_allclose(wp['ad'].data, -np.ones((4, 4)), rtol=1e-12, atol=1e-14)
+ assert_allclose(wp['dd'].data, np.zeros((4, 4)), rtol=1e-12, atol=1e-14)
+
+ assert_allclose(wp['aa'*2].data, np.array([[10., 26.]] * 2), rtol=1e-12)
+ # __getitem__ using a tuple access instead
+ assert_allclose(wp[('aa', 'aa')].data, np.array([[10., 26.]] * 2),
+ rtol=1e-12)
+
+ assert_(wp['aa']['aa'].data is wp['aa'*2].data)
+ assert_allclose(wp['aa'*3].data, np.array([[36.]]), rtol=1e-12)
+
+ assert_raises(IndexError, lambda: wp['aa'*(wp.maxlevel+1)])
+ assert_raises(ValueError, lambda: wp['f'])
+
+ # getitem input must be a string or tuple of strings
+ assert_raises(TypeError, wp.__getitem__, (5, 3))
+ assert_raises(TypeError, wp.__getitem__, 5)
+
+
+def test_accessing_node_attributes_nd():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric')
+
+ assert_allclose(wp['aa'+'ad'].data, np.zeros((2, 2)) - 4, rtol=1e-12)
+ assert_(wp['aa'+'ad'].path == 'aa'+'ad')
+ assert_(wp['aa'+'ad'].node_name == 'ad')
+ assert_(wp['aa'+'ad'].parent.path == 'aa')
+
+ assert_allclose(wp['aa'+'ad'].parent.data,
+ np.array([[3., 7., 11., 15.]] * 4), rtol=1e-12)
+ # can also index via a tuple instead of concatenated strings
+ assert_(wp[('aa', 'ad')].level == 2)
+ assert_(wp[('aa', 'ad')].maxlevel == 3)
+ assert_(wp[('aa', 'ad')].mode == 'symmetric')
+
+ # can access a node's path as either a single string or in tuple form
+ node = wp[('ad', 'dd')]
+ assert_(node.path == 'addd')
+ assert_(node.path_tuple == ('ad', 'dd'))
+
+
+def test_collecting_nodes_nd():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric')
+
+ assert_(len(wp.get_level(0)) == 1)
+ assert_(wp.get_level(0)[0].path == '')
+
+ # First level
+ assert_(len(wp.get_level(1)) == 4)
+ assert_(
+ [node.path for node in wp.get_level(1)] == ['aa', 'ad', 'da', 'dd'])
+
+ # Second and third levels
+ for lev in [2, 3]:
+ assert_(len(wp.get_level(lev)) == (2**x.ndim)**lev)
+ paths = [node.path for node in wp.get_level(lev)]
+ expected_paths = [
+ reduce(operator.add, p) for
+ p in sorted(product(['aa', 'ad', 'da', 'dd'], repeat=lev))]
+ assert_(paths == expected_paths)
+
+
+def test_data_reconstruction_delete_nodes_nd():
+ x = np.array([[1, 2, 3, 4, 5, 6, 7, 8]] * 8, dtype=np.float64)
+ wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric')
+
+ # The user must supply either data or axes
+ assert_raises(ValueError, pywt.WaveletPacketND, data=None, wavelet='db1',
+ axes=None)
+
+ new_wp = pywt.WaveletPacketND(data=None, wavelet='db1', mode='symmetric',
+ axes=range(x.ndim))
+
+ new_wp['ad'+'da'] = wp['ad'+'da'].data
+ new_wp['ad'*2] = wp['ad'+'da'].data
+ new_wp['ad'+'dd'] = np.zeros((2, 2), dtype=np.float64)
+ new_wp['aa'] = [[3.0, 7.0, 11.0, 15.0]] * 4
+ new_wp['dd'] = np.zeros((4, 4), dtype=np.float64)
+ new_wp['da'] = wp['da'] # all zeros
+
+ assert_allclose(new_wp.reconstruct(update=False),
+ np.array([[1.5, 1.5, 3.5, 3.5, 5.5, 5.5, 7.5, 7.5]] * 8),
+ rtol=1e-12)
+
+ new_wp['ad'+'aa'] = wp['ad'+'aa'].data
+ assert_allclose(new_wp.reconstruct(update=False), x, rtol=1e-12)
+
+ del(new_wp['ad'+'aa'])
+ # TypeError on accessing deleted node
+ assert_raises(TypeError, lambda: new_wp['ad'+'aa'])
+
+ new_wp['ad'+'aa'] = wp['ad'+'aa'].data
+ assert_(new_wp.data is None)
+
+ assert_allclose(new_wp.reconstruct(update=True), x, rtol=1e-12)
+ assert_allclose(new_wp.data, x, rtol=1e-12)
+
+ # TODO: decompose=True
+
+
+def test_wavelet_packet_dtypes():
+ shape = (16, 8, 8)
+ for dtype in [np.float32, np.float64, np.complex64, np.complex128]:
+ x = np.random.randn(*shape).astype(dtype)
+ if np.iscomplexobj(x):
+ x = x + 1j*np.random.randn(*shape).astype(x.real.dtype)
+ wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric')
+ # no unnecessary copy made
+ assert_(wp.data is x)
+
+ # full decomposition
+ wp.get_level(wp.maxlevel)
+
+ # reconstruction from coefficients should preserve dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, x.dtype)
+ assert_allclose(r, x, atol=1e-6, rtol=1e-6)
+
+
+def test_wavelet_packet_axes():
+ rstate = np.random.RandomState(0)
+ shape = (32, 16, 8)
+ x = rstate.standard_normal(shape)
+ for axes in [(0, 1), 1, (-3, -2, -1), (0, 2), (1, )]:
+ wp = pywt.WaveletPacketND(data=x, wavelet='db1', mode='symmetric',
+ axes=axes)
+
+ # partial decomposition
+ nodes = wp.get_level(1)
+ # size along the transformed axes has changed
+ for ax2 in range(x.ndim):
+ if ax2 in tuple(np.atleast_1d(axes) % x.ndim):
+ nodes[0].data.shape[ax2] < x.shape[ax2]
+ else:
+ nodes[0].data.shape[ax2] == x.shape[ax2]
+
+ # recontsruction from coefficients should preserve dtype
+ r = wp.reconstruct(False)
+ assert_equal(r.dtype, x.dtype)
+ assert_allclose(r, x, atol=1e-12, rtol=1e-12)
+
+ # must have non-duplicate axes
+ assert_raises(ValueError, pywt.WaveletPacketND, data=x, wavelet='db1',
+ axes=(0, 0))
diff --git a/python_embeded/Lib/site-packages/pyzbar/scripts/__init__.py b/python_embeded/Lib/site-packages/pyzbar/scripts/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pyzbar/scripts/read_zbar.py b/python_embeded/Lib/site-packages/pyzbar/scripts/read_zbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5bf21a619ab8de6bd222243ff76d6de3d1edda8
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyzbar/scripts/read_zbar.py
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+from __future__ import print_function
+
+import argparse
+import sys
+
+import pyzbar
+from pyzbar.pyzbar import decode
+
+
+def main(args=None):
+ if args is None:
+ args = sys.argv[1:]
+
+ parser = argparse.ArgumentParser(
+ description='Reads barcodes in images, using the zbar library'
+ )
+ parser.add_argument('image', nargs='+')
+ parser.add_argument(
+ '-v', '--version', action='version',
+ version='%(prog)s ' + pyzbar.__version__
+ )
+ args = parser.parse_args(args)
+
+ from PIL import Image
+
+ for image in args.image:
+ for barcode in decode(Image.open(image)):
+ print(barcode.data)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/__init__.py b/python_embeded/Lib/site-packages/pyzbar/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/code128.png b/python_embeded/Lib/site-packages/pyzbar/tests/code128.png
new file mode 100644
index 0000000000000000000000000000000000000000..45a63599b1b81eecb0fe628d35f36a9b37761491
Binary files /dev/null and b/python_embeded/Lib/site-packages/pyzbar/tests/code128.png differ
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/code128_null_character.png b/python_embeded/Lib/site-packages/pyzbar/tests/code128_null_character.png
new file mode 100644
index 0000000000000000000000000000000000000000..575ba7738aaa3c634f43c96da1fe4f172befd539
Binary files /dev/null and b/python_embeded/Lib/site-packages/pyzbar/tests/code128_null_character.png differ
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/empty.png b/python_embeded/Lib/site-packages/pyzbar/tests/empty.png
new file mode 100644
index 0000000000000000000000000000000000000000..0636ae9057c96de358c83a2b2a3660f5aba3997e
Binary files /dev/null and b/python_embeded/Lib/site-packages/pyzbar/tests/empty.png differ
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/qrcode.png b/python_embeded/Lib/site-packages/pyzbar/tests/qrcode.png
new file mode 100644
index 0000000000000000000000000000000000000000..246835dd86095f76f92244adef5b8983e46f3ed8
Binary files /dev/null and b/python_embeded/Lib/site-packages/pyzbar/tests/qrcode.png differ
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/qrcode_rotated.png b/python_embeded/Lib/site-packages/pyzbar/tests/qrcode_rotated.png
new file mode 100644
index 0000000000000000000000000000000000000000..729ae449c44d0c35e7aed5f57212a51141de77a4
Binary files /dev/null and b/python_embeded/Lib/site-packages/pyzbar/tests/qrcode_rotated.png differ
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/test_locations.py b/python_embeded/Lib/site-packages/pyzbar/tests/test_locations.py
new file mode 100644
index 0000000000000000000000000000000000000000..205f1f0602f04f16dc367ce6599895254fae1ca5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyzbar/tests/test_locations.py
@@ -0,0 +1,50 @@
+import unittest
+
+from pyzbar.locations import bounding_box, convex_hull, Rect
+
+
+class TestLocations(unittest.TestCase):
+ def test_bounding_box(self):
+ self.assertRaises(ValueError, bounding_box, [])
+ self.assertEqual(
+ Rect(left=0, top=0, width=0, height=0),
+ bounding_box([(0, 0)])
+ )
+ self.assertEqual(
+ Rect(left=37, top=550, width=324, height=76),
+ bounding_box([(37, 551), (37, 625), (361, 626), (361, 550)])
+ )
+
+ def test_convex_hull_empty(self):
+ self.assertEqual([], convex_hull([]))
+
+ def test_convex_square(self):
+ points = [(0, 0), (0, 1), (1, 1), (1, 0)]
+ self.assertEqual(points, convex_hull(points)),
+
+ def test_convex_duplicates(self):
+ points = [(0, 0), (0, 1), (1, 1), (1, 0)]
+ self.assertEqual(points, convex_hull(points * 10)),
+
+ def test_other(self):
+ # Taken from
+ # https://codegolf.stackexchange.com/questions/11035/find-the-convex-hull-of-a-set-of-2d-points
+ res = convex_hull([(1, 1), (2, 2), (3, 3), (1, 3)])
+ self.assertEqual([(1, 1), (1, 3), (3, 3)], res)
+
+ res = convex_hull([
+ (4.4, 14), (6.7, 15.25), (6.9, 12.8), (2.1, 11.1), (9.5, 14.9),
+ (13.2, 11.9), (10.3, 12.3), (6.8, 9.5), (3.3, 7.7), (0.6, 5.1),
+ (5.3, 2.4), (8.45, 4.7), (11.5, 9.6), (13.8, 7.3), (12.9, 3.1),
+ (11, 1.1)
+ ])
+
+ expected = [
+ (0.6, 5.1), (2.1, 11.1), (4.4, 14), (6.7, 15.25), (9.5, 14.9),
+ (13.2, 11.9), (13.8, 7.3), (12.9, 3.1), (11, 1.1), (5.3, 2.4)
+ ]
+ self.assertEqual(expected, res)
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/test_pyzbar.py b/python_embeded/Lib/site-packages/pyzbar/tests/test_pyzbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6152d80e22f756ca3222d809934c0e5f33b9a4e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyzbar/tests/test_pyzbar.py
@@ -0,0 +1,258 @@
+import platform
+import unittest
+
+from pathlib import Path
+
+try:
+ from unittest.mock import patch
+except ImportError:
+ # Python 2
+ from mock import patch
+
+import numpy as np
+
+from PIL import Image
+
+try:
+ import cv2
+except ImportError:
+ cv2 = None
+
+try:
+ import imageio
+except ImportError:
+ imageio = None
+
+from pyzbar import wrapper
+from pyzbar.pyzbar import (
+ decode, Decoded, Rect, ZBarSymbol, EXTERNAL_DEPENDENCIES, ORIENTATION_AVAILABLE
+)
+from pyzbar.pyzbar_error import PyZbarError
+
+
+TESTDATA = Path(__file__).parent
+
+
+class TestDecode(unittest.TestCase):
+ EXPECTED_CODE128 = [
+ Decoded(
+ data=b'Foramenifera',
+ type='CODE128',
+ rect=Rect(left=37, top=550, width=324, height=76),
+ polygon=[(37, 551), (37, 625), (361, 626), (361, 550)],
+ orientation='UP' if ORIENTATION_AVAILABLE else None,
+ quality=77,
+ ),
+ Decoded(
+ data=b'Rana temporaria',
+ type='CODE128',
+ rect=Rect(left=4, top=0, width=390, height=76),
+ polygon=[(4, 1), (4, 75), (394, 76), (394, 0)],
+ orientation='UP' if ORIENTATION_AVAILABLE else None,
+ quality=77,
+ ),
+ ]
+
+ EXPECTED_CODE128_NULL_CHARACTER = [
+ Decoded(
+ data=b'Hello\0Goodbye',
+ type='CODE128',
+ rect=Rect(left=4, top=0, width=390, height=75),
+ polygon=[(4, 1), (4, 75), (394, 74), (394, 0)],
+ orientation="UP" if ORIENTATION_AVAILABLE else None,
+ quality=76,
+ ),
+ ]
+
+ EXPECTED_QRCODE = [
+ Decoded(
+ b'Thalassiodracon',
+ type='QRCODE',
+ rect=Rect(left=27, top=27, width=145, height=145),
+ polygon=[(27, 27), (27, 172), (172, 172), (172, 27)],
+ orientation='UP' if ORIENTATION_AVAILABLE else None,
+ quality=1,
+ ),
+ ]
+
+ # Two barcodes, both with same content
+ EXPECTED_QRCODE_ROTATED = [
+ Decoded(
+ data=b'Thalassiodracon',
+ type='QRCODE',
+ rect=Rect(left=173, top=10, width=205, height=205),
+ polygon=[(173, 113), (276, 215), (378, 113), (276, 10)],
+ orientation='UP' if ORIENTATION_AVAILABLE else None,
+ quality=1,
+ ),
+ Decoded(
+ data=b'Thalassiodracon',
+ type='QRCODE',
+ rect=Rect(left=32, top=208, width=158, height=158),
+ polygon=[(32, 352), (177, 366), (190, 222), (46, 208)],
+ orientation='RIGHT' if ORIENTATION_AVAILABLE else None,
+ quality=1,
+ ),
+ ]
+
+ @classmethod
+ def setUpClass(cls):
+ cls.code128, cls.code128_null_character, cls.qrcode, cls.qrcode_rotated, cls.empty = (
+ Image.open(str(TESTDATA.joinpath(fname)))
+ for fname in
+ ('code128.png', 'code128_null_character.png', 'qrcode.png', 'qrcode_rotated.png', 'empty.png')
+ )
+
+ cls.maxDiff = None
+
+ # assertRaisesRegexp was a deprecated alias removed in Python 3.11
+ if not hasattr(cls, 'assertRaisesRegex'):
+ cls.assertRaisesRegex = cls.assertRaisesRegexp
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.code128 = cls.code128_null_character = cls.qrcode = cls.qrcode_rotated = cls.empty = None
+
+ def test_decode_code128(self):
+ "Read both barcodes in `code128.png`"
+ res = decode(self.code128)
+ self.assertEqual(self.EXPECTED_CODE128, res)
+
+ def test_decode_code128_null_character(self):
+ "Read barcode in `code128_null_character.png` containing a null character"
+ res = decode(self.code128_null_character)
+ self.assertEqual(self.EXPECTED_CODE128_NULL_CHARACTER, res)
+
+ def test_decode_qrcode(self):
+ "Read barcode in `qrcode.png`"
+ res = decode(self.qrcode)
+ self.assertEqual(self.EXPECTED_QRCODE, res)
+
+ def test_decode_qrcode_rotated(self):
+ "Read barcode in `qrcode_rotated.png`"
+ # Test computation of the polygon around the barcode
+ res = decode(self.qrcode_rotated)
+ self.assertEqual(self.EXPECTED_QRCODE_ROTATED, res)
+
+ def test_symbols(self):
+ "Read only qrcodes in `qrcode.png`"
+ res = decode(self.qrcode, symbols=[ZBarSymbol.QRCODE])
+ self.assertEqual(self.EXPECTED_QRCODE, res)
+
+ def test_symbols_not_present(self):
+ "Read only code128 in `qrcode.png`"
+ res = decode(self.qrcode, symbols=[ZBarSymbol.CODE128])
+ self.assertEqual([], res)
+
+ def test_decode_tuple(self):
+ "Read barcodes in pixels"
+ pixels = self.code128.copy().convert('L').tobytes()
+ width, height = self.code128.size
+ res = decode((pixels, width, height))
+ self.assertEqual(self.EXPECTED_CODE128, res)
+
+ def test_unsupported_bpp(self):
+ pixels = self.code128.tobytes()
+ width, height = self.code128.size
+ self.assertRaises(PyZbarError, decode, (pixels, width, height))
+
+ def test_empty(self):
+ "Do not show any output for an image that does not contain a barcode"
+ res = decode(self.empty)
+ self.assertEqual([], res)
+
+ def test_decode_numpy(self):
+ "Read image using Pillow and convert to numpy.ndarray"
+ res = decode(np.asarray(self.code128))
+ self.assertEqual(self.EXPECTED_CODE128, res)
+
+ @unittest.skipIf(imageio is None, 'imageio not installed')
+ def test_decode_imageio(self):
+ "Read image using imageio"
+ res = decode(imageio.imread(TESTDATA.joinpath('code128.png')))
+ self.assertEqual(self.EXPECTED_CODE128, res)
+
+ @unittest.skipIf(cv2 is None, 'OpenCV not installed')
+ def test_decode_opencv(self):
+ "Read image using OpenCV"
+ res = decode(cv2.imread(str(TESTDATA.joinpath('code128.png'))))
+ self.assertEqual(self.EXPECTED_CODE128, res)
+
+ @patch('pyzbar.pyzbar.zbar_image_first_symbol', autospec=True)
+ def test_unrecognised_symbol_type(self, zbar_image_first_symbol):
+ "The type of the first symbol is not recognised"
+ def zbar_image_first_symbol_set_symbol_type(image):
+ symbol = wrapper.zbar_image_first_symbol(image)
+ if symbol:
+ symbol.contents.type = -1
+ return symbol
+
+ zbar_image_first_symbol.side_effect = zbar_image_first_symbol_set_symbol_type
+
+ res = decode(np.asarray(self.code128))
+
+ expected = [
+ self.EXPECTED_CODE128[0]._replace(type='Unrecognised type [-1]')
+ ] + self.EXPECTED_CODE128[1:]
+ self.assertEqual(expected, res)
+
+ def test_external_dependencies(self):
+ "External dependencies"
+ if 'Windows' == platform.system():
+ self.assertEqual(2, len(EXTERNAL_DEPENDENCIES))
+ self.assertTrue(
+ any('libiconv' in d._name for d in EXTERNAL_DEPENDENCIES)
+ )
+ self.assertTrue(
+ any('libzbar' in d._name for d in EXTERNAL_DEPENDENCIES)
+ )
+
+ @patch('pyzbar.pyzbar.zbar_image_create', autospec=True)
+ def test_zbar_image_create_fail(self, zbar_image_create):
+ zbar_image_create.return_value = None
+ self.assertRaisesRegex(
+ PyZbarError, 'Could not create zbar image', decode, self.code128
+ )
+ zbar_image_create.assert_called_once_with()
+
+ @patch('pyzbar.pyzbar.zbar_image_scanner_create', autospec=True)
+ def test_zbar_image_scanner_create_fail(self, zbar_image_scanner_create):
+ zbar_image_scanner_create.return_value = None
+ self.assertRaisesRegex(
+ PyZbarError, 'Could not create image scanner', decode, self.code128
+ )
+ zbar_image_scanner_create.assert_called_once_with()
+
+ @patch('pyzbar.pyzbar.zbar_scan_image', autospec=True)
+ def test_zbar_scan_image_fail(self, zbar_scan_image):
+ zbar_scan_image.return_value = -1
+ self.assertRaisesRegex(
+ PyZbarError, 'Unsupported image format', decode, self.code128
+ )
+ self.assertEqual(1, zbar_scan_image.call_count)
+
+ def test_unsupported_bits_per_pixel(self):
+ # 16 bits-per-pixel
+ data = (list(range(3 * 3 * 2)), 3, 3)
+ self.assertRaisesRegex(
+ PyZbarError,
+ r'Unsupported bits-per-pixel \[16\]. Only \[8\] is supported.',
+ decode, data
+ )
+ self.assertRaises(PyZbarError, decode, data)
+
+ def test_inconsistent_dimensions(self):
+ # Ten bytes but width x height indicates nine bytes
+ data = (list(range(10)), 3, 3)
+ self.assertRaisesRegex(
+ PyZbarError,
+ (
+ r'Inconsistent dimensions: image data of 10 bytes is not '
+ r'divisible by \(width x height = 9\)'
+ ),
+ decode, data
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/test_read_zbar.py b/python_embeded/Lib/site-packages/pyzbar/tests/test_read_zbar.py
new file mode 100644
index 0000000000000000000000000000000000000000..ddc74910dd7fc54bf87b04198120759d3d936f6e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyzbar/tests/test_read_zbar.py
@@ -0,0 +1,52 @@
+import sys
+import unittest
+
+from pathlib import Path
+from contextlib import contextmanager
+
+# TODO Would io.StringIO not work in all cases?
+try:
+ from cStringIO import StringIO
+except ImportError:
+ from io import StringIO
+
+from pyzbar.scripts.read_zbar import main
+
+
+@contextmanager
+def capture_stdout():
+ sys.stdout, old_stdout = StringIO(), sys.stdout
+ try:
+ yield sys.stdout
+ finally:
+ sys.stdout = old_stdout
+
+
+class TestReadZbar(unittest.TestCase):
+ def test_read_qrcode(self):
+ "Read QR code"
+ with capture_stdout() as stdout:
+ main([str(Path(__file__).parent.joinpath('qrcode.png'))])
+
+ if 2 == sys.version_info[0]:
+ expected = "Thalassiodracon"
+ else:
+ expected = "b'Thalassiodracon'"
+
+ self.assertEqual(expected, stdout.getvalue().strip())
+
+ def test_read_code128(self):
+ "Read CODE 128 barcodes"
+ with capture_stdout() as stdout:
+ main([str(Path(__file__).parent.joinpath('code128.png'))])
+
+ if 2 == sys.version_info[0]:
+ expected = "Foramenifera\nRana temporaria"
+ else:
+ expected = "b'Foramenifera'\nb'Rana temporaria'"
+
+ self.assertEqual(expected, stdout.getvalue().strip())
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python_embeded/Lib/site-packages/pyzbar/tests/test_zbar_library.py b/python_embeded/Lib/site-packages/pyzbar/tests/test_zbar_library.py
new file mode 100644
index 0000000000000000000000000000000000000000..137568c58224a445d456925cde53aabb7c58b660
--- /dev/null
+++ b/python_embeded/Lib/site-packages/pyzbar/tests/test_zbar_library.py
@@ -0,0 +1,138 @@
+import unittest
+
+from pathlib import Path
+
+try:
+ from unittest.mock import call, patch
+except ImportError:
+ # Python 2
+ from mock import call, patch
+
+from pyzbar import zbar_library
+
+
+class TestLoad(unittest.TestCase):
+ def setUp(self):
+ self.addCleanup(patch.stopall)
+ self.cdll = patch(
+ 'pyzbar.zbar_library.cdll', autospec=True
+ ).start()
+ self.find_library = patch(
+ 'pyzbar.zbar_library.find_library', autospec=True
+ ).start()
+ self.platform = patch(
+ 'pyzbar.zbar_library.platform', autospec=True
+ ).start()
+ self.windows_fnames = patch(
+ 'pyzbar.zbar_library._windows_fnames', autospec=True,
+ return_value=('dll fname', ['dependency fname'])
+ ).start()
+
+ def test_found_non_windows(self):
+ "zbar loaded ok on non-Windows platform"
+ self.platform.system.return_value = 'Not windows'
+
+ res = zbar_library.load()
+
+ self.platform.system.assert_called_once_with()
+ self.find_library.assert_called_once_with('zbar')
+ self.cdll.LoadLibrary.assert_called_once_with(
+ self.find_library.return_value
+ )
+
+ self.assertEqual((self.cdll.LoadLibrary.return_value, []), res)
+ self.assertEqual(0, self.windows_fnames.call_count)
+
+ def test_not_found_non_windows(self):
+ "zbar not found on non-Windows platform"
+ self.platform.system.return_value = 'Not windows'
+ self.find_library.return_value = None
+
+ self.assertRaises(ImportError, zbar_library.load)
+
+ self.platform.system.assert_called_once_with()
+ self.find_library.assert_called_once_with('zbar')
+
+ def test_found_windows(self):
+ "zbar found on Windows"
+ self.platform.system.return_value = 'Windows'
+
+ res = zbar_library.load()
+
+ self.platform.system.assert_called_once_with()
+ self.cdll.LoadLibrary.assert_has_calls([
+ call('dependency fname'),
+ call('dll fname'),
+ ])
+ self.assertEqual(
+ (
+ self.cdll.LoadLibrary.return_value,
+ [self.cdll.LoadLibrary.return_value]
+ ),
+ res
+ )
+
+ def test_found_second_attempt_windows(self):
+ "zbar found on the second attempt on Windows"
+ self.platform.system.return_value = 'Windows'
+ self.cdll.LoadLibrary.side_effect = [
+ OSError, # First call does not load dependent DLL
+ 'loaded dependency', # Second call loads dependent DLL
+ 'loaded zbar', # Third call loads dependent DLL
+ ]
+
+ res = zbar_library.load()
+
+ self.platform.system.assert_called_once_with()
+ self.cdll.LoadLibrary.assert_has_calls([
+ call('dependency fname'),
+ call(str(Path(zbar_library.__file__).parent.joinpath(
+ 'dependency fname'
+ ))),
+ call(str(Path(zbar_library.__file__).parent.joinpath(
+ 'dll fname'
+ ))),
+ ])
+
+ self.assertEqual(('loaded zbar', ['loaded dependency']), res)
+
+ def test_not_found_windows(self):
+ "zbar not found on Windows"
+ self.platform.system.return_value = 'Windows'
+ self.cdll.LoadLibrary.side_effect = OSError
+
+ self.assertRaises(OSError, zbar_library.load)
+
+ self.platform.system.assert_called_once_with()
+ # Two attempts at loading
+ self.cdll.LoadLibrary.assert_has_calls([
+ call('dependency fname'),
+ call(str(Path(zbar_library.__file__).parent.joinpath(
+ 'dependency fname'
+ ))),
+ ])
+
+
+class TestWindowsFnames(unittest.TestCase):
+ def setUp(self):
+ self.addCleanup(patch.stopall)
+ self.sys = patch('pyzbar.zbar_library.sys', autospec=True).start()
+
+ def test_32bit(self):
+ self.sys.maxsize = 2**32
+ self.assertEqual(
+ ('libzbar-32.dll', ['libiconv-2.dll']),
+ zbar_library._windows_fnames()
+ )
+
+ def test_64bit(self):
+ # This is a 'long' on a 32-bit interpreter
+ self.sys.maxsize = 2**32 + 1
+ self.assertEqual(
+ ('libzbar-64.dll', ['libiconv.dll']),
+ zbar_library._windows_fnames()
+ )
+
+
+if __name__ == '__main__':
+ unittest.main()
diff --git a/python_embeded/Lib/site-packages/qrcode/compat/__init__.py b/python_embeded/Lib/site-packages/qrcode/compat/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/qrcode/compat/etree.py b/python_embeded/Lib/site-packages/qrcode/compat/etree.py
new file mode 100644
index 0000000000000000000000000000000000000000..6739d2271f2d5276b18560182699419cd6ffbd9e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/compat/etree.py
@@ -0,0 +1,4 @@
+try:
+ import lxml.etree as ET # type: ignore # noqa: F401
+except ImportError:
+ import xml.etree.ElementTree as ET # type: ignore # noqa: F401
diff --git a/python_embeded/Lib/site-packages/qrcode/compat/png.py b/python_embeded/Lib/site-packages/qrcode/compat/png.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d7b90566eddbab88972029a56d91427c576d71a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/compat/png.py
@@ -0,0 +1,7 @@
+# Try to import png library.
+PngWriter = None
+
+try:
+ from png import Writer as PngWriter # type: ignore # noqa: F401
+except ImportError: # pragma: no cover
+ pass
diff --git a/python_embeded/Lib/site-packages/qrcode/image/__init__.py b/python_embeded/Lib/site-packages/qrcode/image/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/qrcode/image/base.py b/python_embeded/Lib/site-packages/qrcode/image/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..119c30a67a474a3f414ee48b5d83d5987e31585b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/base.py
@@ -0,0 +1,164 @@
+import abc
+from typing import TYPE_CHECKING, Any, Optional, Union
+
+from qrcode.image.styles.moduledrawers.base import QRModuleDrawer
+
+if TYPE_CHECKING:
+ from qrcode.main import ActiveWithNeighbors, QRCode
+
+
+DrawerAliases = dict[str, tuple[type[QRModuleDrawer], dict[str, Any]]]
+
+
+class BaseImage:
+ """
+ Base QRCode image output class.
+ """
+
+ kind: Optional[str] = None
+ allowed_kinds: Optional[tuple[str]] = None
+ needs_context = False
+ needs_processing = False
+ needs_drawrect = True
+
+ def __init__(self, border, width, box_size, *args, **kwargs):
+ self.border = border
+ self.width = width
+ self.box_size = box_size
+ self.pixel_size = (self.width + self.border * 2) * self.box_size
+ self.modules = kwargs.pop("qrcode_modules")
+ self._img = self.new_image(**kwargs)
+ self.init_new_image()
+
+ @abc.abstractmethod
+ def drawrect(self, row, col):
+ """
+ Draw a single rectangle of the QR code.
+ """
+
+ def drawrect_context(self, row: int, col: int, qr: "QRCode"):
+ """
+ Draw a single rectangle of the QR code given the surrounding context
+ """
+ raise NotImplementedError("BaseImage.drawrect_context") # pragma: no cover
+
+ def process(self):
+ """
+ Processes QR code after completion
+ """
+ raise NotImplementedError("BaseImage.drawimage") # pragma: no cover
+
+ @abc.abstractmethod
+ def save(self, stream, kind=None):
+ """
+ Save the image file.
+ """
+
+ def pixel_box(self, row, col):
+ """
+ A helper method for pixel-based image generators that specifies the
+ four pixel coordinates for a single rect.
+ """
+ x = (col + self.border) * self.box_size
+ y = (row + self.border) * self.box_size
+ return (
+ (x, y),
+ (x + self.box_size - 1, y + self.box_size - 1),
+ )
+
+ @abc.abstractmethod
+ def new_image(self, **kwargs) -> Any:
+ """
+ Build the image class. Subclasses should return the class created.
+ """
+
+ def init_new_image(self):
+ pass
+
+ def get_image(self, **kwargs):
+ """
+ Return the image class for further processing.
+ """
+ return self._img
+
+ def check_kind(self, kind, transform=None):
+ """
+ Get the image type.
+ """
+ if kind is None:
+ kind = self.kind
+ allowed = not self.allowed_kinds or kind in self.allowed_kinds
+ if transform:
+ kind = transform(kind)
+ if not allowed:
+ allowed = kind in self.allowed_kinds
+ if not allowed:
+ raise ValueError(f"Cannot set {type(self).__name__} type to {kind}")
+ return kind
+
+ def is_eye(self, row: int, col: int):
+ """
+ Find whether the referenced module is in an eye.
+ """
+ return (
+ (row < 7 and col < 7)
+ or (row < 7 and self.width - col < 8)
+ or (self.width - row < 8 and col < 7)
+ )
+
+
+class BaseImageWithDrawer(BaseImage):
+ default_drawer_class: type[QRModuleDrawer]
+ drawer_aliases: DrawerAliases = {}
+
+ def get_default_module_drawer(self) -> QRModuleDrawer:
+ return self.default_drawer_class()
+
+ def get_default_eye_drawer(self) -> QRModuleDrawer:
+ return self.default_drawer_class()
+
+ needs_context = True
+
+ module_drawer: "QRModuleDrawer"
+ eye_drawer: "QRModuleDrawer"
+
+ def __init__(
+ self,
+ *args,
+ module_drawer: Union[QRModuleDrawer, str, None] = None,
+ eye_drawer: Union[QRModuleDrawer, str, None] = None,
+ **kwargs,
+ ):
+ self.module_drawer = (
+ self.get_drawer(module_drawer) or self.get_default_module_drawer()
+ )
+ # The eye drawer can be overridden by another module drawer as well,
+ # but you have to be more careful with these in order to make the QR
+ # code still parseable
+ self.eye_drawer = self.get_drawer(eye_drawer) or self.get_default_eye_drawer()
+ super().__init__(*args, **kwargs)
+
+ def get_drawer(
+ self, drawer: Union[QRModuleDrawer, str, None]
+ ) -> Optional[QRModuleDrawer]:
+ if not isinstance(drawer, str):
+ return drawer
+ drawer_cls, kwargs = self.drawer_aliases[drawer]
+ return drawer_cls(**kwargs)
+
+ def init_new_image(self):
+ self.module_drawer.initialize(img=self)
+ self.eye_drawer.initialize(img=self)
+
+ return super().init_new_image()
+
+ def drawrect_context(self, row: int, col: int, qr: "QRCode"):
+ box = self.pixel_box(row, col)
+ drawer = self.eye_drawer if self.is_eye(row, col) else self.module_drawer
+ is_active: Union[bool, ActiveWithNeighbors] = (
+ qr.active_with_neighbors(row, col)
+ if drawer.needs_neighbors
+ else bool(qr.modules[row][col])
+ )
+
+ drawer.drawrect(box, is_active)
diff --git a/python_embeded/Lib/site-packages/qrcode/image/pil.py b/python_embeded/Lib/site-packages/qrcode/image/pil.py
new file mode 100644
index 0000000000000000000000000000000000000000..57ee13a8d052456fbdd0b130b680eacae6141219
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/pil.py
@@ -0,0 +1,57 @@
+import qrcode.image.base
+from PIL import Image, ImageDraw
+
+
+class PilImage(qrcode.image.base.BaseImage):
+ """
+ PIL image builder, default format is PNG.
+ """
+
+ kind = "PNG"
+
+ def new_image(self, **kwargs):
+ if not Image:
+ raise ImportError("PIL library not found.")
+
+ back_color = kwargs.get("back_color", "white")
+ fill_color = kwargs.get("fill_color", "black")
+
+ try:
+ fill_color = fill_color.lower()
+ except AttributeError:
+ pass
+
+ try:
+ back_color = back_color.lower()
+ except AttributeError:
+ pass
+
+ # L mode (1 mode) color = (r*299 + g*587 + b*114)//1000
+ if fill_color == "black" and back_color == "white":
+ mode = "1"
+ fill_color = 0
+ if back_color == "white":
+ back_color = 255
+ elif back_color == "transparent":
+ mode = "RGBA"
+ back_color = None
+ else:
+ mode = "RGB"
+
+ img = Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
+ self.fill_color = fill_color
+ self._idr = ImageDraw.Draw(img)
+ return img
+
+ def drawrect(self, row, col):
+ box = self.pixel_box(row, col)
+ self._idr.rectangle(box, fill=self.fill_color)
+
+ def save(self, stream, format=None, **kwargs):
+ kind = kwargs.pop("kind", self.kind)
+ if format is None:
+ format = kind
+ self._img.save(stream, format=format, **kwargs)
+
+ def __getattr__(self, name):
+ return getattr(self._img, name)
diff --git a/python_embeded/Lib/site-packages/qrcode/image/pure.py b/python_embeded/Lib/site-packages/qrcode/image/pure.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a8b2c5e238857cc6503e5222efb3f493d9dab60
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/pure.py
@@ -0,0 +1,56 @@
+from itertools import chain
+
+from qrcode.compat.png import PngWriter
+from qrcode.image.base import BaseImage
+
+
+class PyPNGImage(BaseImage):
+ """
+ pyPNG image builder.
+ """
+
+ kind = "PNG"
+ allowed_kinds = ("PNG",)
+ needs_drawrect = False
+
+ def new_image(self, **kwargs):
+ if not PngWriter:
+ raise ImportError("PyPNG library not installed.")
+
+ return PngWriter(self.pixel_size, self.pixel_size, greyscale=True, bitdepth=1)
+
+ def drawrect(self, row, col):
+ """
+ Not used.
+ """
+
+ def save(self, stream, kind=None):
+ if isinstance(stream, str):
+ stream = open(stream, "wb")
+ self._img.write(stream, self.rows_iter())
+
+ def rows_iter(self):
+ yield from self.border_rows_iter()
+ border_col = [1] * (self.box_size * self.border)
+ for module_row in self.modules:
+ row = (
+ border_col
+ + list(
+ chain.from_iterable(
+ ([not point] * self.box_size) for point in module_row
+ )
+ )
+ + border_col
+ )
+ for _ in range(self.box_size):
+ yield row
+ yield from self.border_rows_iter()
+
+ def border_rows_iter(self):
+ border_row = [1] * (self.box_size * (self.width + self.border * 2))
+ for _ in range(self.border * self.box_size):
+ yield border_row
+
+
+# Keeping this for backwards compatibility.
+PymagingImage = PyPNGImage
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styledpil.py b/python_embeded/Lib/site-packages/qrcode/image/styledpil.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd63a6e0c9e5874a1792dbd4cf8613e29e8f4dfc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/styledpil.py
@@ -0,0 +1,120 @@
+import qrcode.image.base
+from PIL import Image
+from qrcode.image.styles.colormasks import QRColorMask, SolidFillColorMask
+from qrcode.image.styles.moduledrawers import SquareModuleDrawer
+
+
+class StyledPilImage(qrcode.image.base.BaseImageWithDrawer):
+ """
+ Styled PIL image builder, default format is PNG.
+
+ This differs from the PilImage in that there is a module_drawer, a
+ color_mask, and an optional image
+
+ The module_drawer should extend the QRModuleDrawer class and implement the
+ drawrect_context(self, box, active, context), and probably also the
+ initialize function. This will draw an individual "module" or square on
+ the QR code.
+
+ The color_mask will extend the QRColorMask class and will at very least
+ implement the get_fg_pixel(image, x, y) function, calculating a color to
+ put on the image at the pixel location (x,y) (more advanced functionality
+ can be gotten by instead overriding other functions defined in the
+ QRColorMask class)
+
+ The Image can be specified either by path or with a Pillow Image, and if it
+ is there will be placed in the middle of the QR code. No effort is done to
+ ensure that the QR code is still legible after the image has been placed
+ there; Q or H level error correction levels are recommended to maintain
+ data integrity A resampling filter can be specified (defaulting to
+ PIL.Image.Resampling.LANCZOS) for resizing; see PIL.Image.resize() for possible
+ options for this parameter.
+ The image size can be controlled by `embedded_image_ratio` which is a ratio
+ between 0 and 1 that's set in relation to the overall width of the QR code.
+ """
+
+ kind = "PNG"
+
+ needs_processing = True
+ color_mask: QRColorMask
+ default_drawer_class = SquareModuleDrawer
+
+ def __init__(self, *args, **kwargs):
+ self.color_mask = kwargs.get("color_mask", SolidFillColorMask())
+ # allow embeded_ parameters with typos for backwards compatibility
+ embedded_image_path = kwargs.get(
+ "embedded_image_path", kwargs.get("embeded_image_path", None)
+ )
+ self.embedded_image = kwargs.get(
+ "embedded_image", kwargs.get("embeded_image", None)
+ )
+ self.embedded_image_ratio = kwargs.get(
+ "embedded_image_ratio", kwargs.get("embeded_image_ratio", 0.25)
+ )
+ self.embedded_image_resample = kwargs.get(
+ "embedded_image_resample",
+ kwargs.get("embeded_image_resample", Image.Resampling.LANCZOS),
+ )
+ if not self.embedded_image and embedded_image_path:
+ self.embedded_image = Image.open(embedded_image_path)
+
+ # the paint_color is the color the module drawer will use to draw upon
+ # a canvas During the color mask process, pixels that are paint_color
+ # are replaced by a newly-calculated color
+ self.paint_color = tuple(0 for i in self.color_mask.back_color)
+ if self.color_mask.has_transparency:
+ self.paint_color = tuple([*self.color_mask.back_color[:3], 255])
+
+ super().__init__(*args, **kwargs)
+
+ def new_image(self, **kwargs):
+ mode = (
+ "RGBA"
+ if (
+ self.color_mask.has_transparency
+ or (self.embedded_image and "A" in self.embedded_image.getbands())
+ )
+ else "RGB"
+ )
+ # This is the background color. Should be white or whiteish
+ back_color = self.color_mask.back_color
+
+ return Image.new(mode, (self.pixel_size, self.pixel_size), back_color)
+
+ def init_new_image(self):
+ self.color_mask.initialize(self, self._img)
+ super().init_new_image()
+
+ def process(self):
+ self.color_mask.apply_mask(self._img)
+ if self.embedded_image:
+ self.draw_embedded_image()
+
+ def draw_embedded_image(self):
+ if not self.embedded_image:
+ return
+ total_width, _ = self._img.size
+ total_width = int(total_width)
+ logo_width_ish = int(total_width * self.embedded_image_ratio)
+ logo_offset = (
+ int((int(total_width / 2) - int(logo_width_ish / 2)) / self.box_size)
+ * self.box_size
+ ) # round the offset to the nearest module
+ logo_position = (logo_offset, logo_offset)
+ logo_width = total_width - logo_offset * 2
+ region = self.embedded_image
+ region = region.resize((logo_width, logo_width), self.embedded_image_resample)
+ if "A" in region.getbands():
+ self._img.alpha_composite(region, logo_position)
+ else:
+ self._img.paste(region, logo_position)
+
+ def save(self, stream, format=None, **kwargs):
+ if format is None:
+ format = kwargs.get("kind", self.kind)
+ if "kind" in kwargs:
+ del kwargs["kind"]
+ self._img.save(stream, format=format, **kwargs)
+
+ def __getattr__(self, name):
+ return getattr(self._img, name)
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styles/__init__.py b/python_embeded/Lib/site-packages/qrcode/image/styles/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styles/colormasks.py b/python_embeded/Lib/site-packages/qrcode/image/styles/colormasks.py
new file mode 100644
index 0000000000000000000000000000000000000000..9599f7fb2ed148dbcb2e53ba15fbca64044fbe75
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/styles/colormasks.py
@@ -0,0 +1,226 @@
+import math
+
+from PIL import Image
+
+
+class QRColorMask:
+ """
+ QRColorMask is used to color in the QRCode.
+
+ By the time apply_mask is called, the QRModuleDrawer of the StyledPilImage
+ will have drawn all of the modules on the canvas (the color of these
+ modules will be mostly black, although antialiasing may result in
+ gradients) In the base class, apply_mask is implemented such that the
+ background color will remain, but the foreground pixels will be replaced by
+ a color determined by a call to get_fg_pixel. There is additional
+ calculation done to preserve the gradient artifacts of antialiasing.
+
+ All QRColorMask objects should be careful about RGB vs RGBA color spaces.
+
+ For examples of what these look like, see doc/color_masks.png
+ """
+
+ back_color = (255, 255, 255)
+ has_transparency = False
+ paint_color = back_color
+
+ def initialize(self, styledPilImage, image):
+ self.paint_color = styledPilImage.paint_color
+
+ def apply_mask(self, image, use_cache=False):
+ width, height = image.size
+ pixels = image.load()
+ fg_color_cache = {} if use_cache else None
+ for x in range(width):
+ for y in range(height):
+ current_color = pixels[x, y]
+ if current_color == self.back_color:
+ continue
+ if use_cache and current_color in fg_color_cache:
+ pixels[x, y] = fg_color_cache[current_color]
+ continue
+ norm = self.extrap_color(
+ self.back_color, self.paint_color, current_color
+ )
+ if norm is not None:
+ new_color = self.interp_color(
+ self.get_bg_pixel(image, x, y),
+ self.get_fg_pixel(image, x, y),
+ norm,
+ )
+ pixels[x, y] = new_color
+
+ if use_cache:
+ fg_color_cache[current_color] = new_color
+ else:
+ pixels[x, y] = self.get_bg_pixel(image, x, y)
+
+ def get_fg_pixel(self, image, x, y):
+ raise NotImplementedError("QRModuleDrawer.paint_fg_pixel")
+
+ def get_bg_pixel(self, image, x, y):
+ return self.back_color
+
+ # The following functions are helpful for color calculation:
+
+ # interpolate a number between two numbers
+ def interp_num(self, n1, n2, norm):
+ return int(n2 * norm + n1 * (1 - norm))
+
+ # interpolate a color between two colorrs
+ def interp_color(self, col1, col2, norm):
+ return tuple(self.interp_num(col1[i], col2[i], norm) for i in range(len(col1)))
+
+ # find the interpolation coefficient between two numbers
+ def extrap_num(self, n1, n2, interped_num):
+ if n2 == n1:
+ return None
+ else:
+ return (interped_num - n1) / (n2 - n1)
+
+ # find the interpolation coefficient between two numbers
+ def extrap_color(self, col1, col2, interped_color):
+ normed = []
+ for c1, c2, ci in zip(col1, col2, interped_color):
+ extrap = self.extrap_num(c1, c2, ci)
+ if extrap is not None:
+ normed.append(extrap)
+ if not normed:
+ return None
+ return sum(normed) / len(normed)
+
+
+class SolidFillColorMask(QRColorMask):
+ """
+ Just fills in the background with one color and the foreground with another
+ """
+
+ def __init__(self, back_color=(255, 255, 255), front_color=(0, 0, 0)):
+ self.back_color = back_color
+ self.front_color = front_color
+ self.has_transparency = len(self.back_color) == 4
+
+ def apply_mask(self, image):
+ if self.back_color == (255, 255, 255) and self.front_color == (0, 0, 0):
+ # Optimization: the image is already drawn by QRModuleDrawer in
+ # black and white, so if these are also our mask colors we don't
+ # need to do anything. This is much faster than actually applying a
+ # mask.
+ pass
+ else:
+ # TODO there's probably a way to use PIL.ImageMath instead of doing
+ # the individual pixel comparisons that the base class uses, which
+ # would be a lot faster. (In fact doing this would probably remove
+ # the need for the B&W optimization above.)
+ QRColorMask.apply_mask(self, image, use_cache=True)
+
+ def get_fg_pixel(self, image, x, y):
+ return self.front_color
+
+
+class RadialGradiantColorMask(QRColorMask):
+ """
+ Fills in the foreground with a radial gradient from the center to the edge
+ """
+
+ def __init__(
+ self, back_color=(255, 255, 255), center_color=(0, 0, 0), edge_color=(0, 0, 255)
+ ):
+ self.back_color = back_color
+ self.center_color = center_color
+ self.edge_color = edge_color
+ self.has_transparency = len(self.back_color) == 4
+
+ def get_fg_pixel(self, image, x, y):
+ width, _ = image.size
+ normedDistanceToCenter = math.sqrt(
+ (x - width / 2) ** 2 + (y - width / 2) ** 2
+ ) / (math.sqrt(2) * width / 2)
+ return self.interp_color(
+ self.center_color, self.edge_color, normedDistanceToCenter
+ )
+
+
+class SquareGradiantColorMask(QRColorMask):
+ """
+ Fills in the foreground with a square gradient from the center to the edge
+ """
+
+ def __init__(
+ self, back_color=(255, 255, 255), center_color=(0, 0, 0), edge_color=(0, 0, 255)
+ ):
+ self.back_color = back_color
+ self.center_color = center_color
+ self.edge_color = edge_color
+ self.has_transparency = len(self.back_color) == 4
+
+ def get_fg_pixel(self, image, x, y):
+ width, _ = image.size
+ normedDistanceToCenter = max(abs(x - width / 2), abs(y - width / 2)) / (
+ width / 2
+ )
+ return self.interp_color(
+ self.center_color, self.edge_color, normedDistanceToCenter
+ )
+
+
+class HorizontalGradiantColorMask(QRColorMask):
+ """
+ Fills in the foreground with a gradient sweeping from the left to the right
+ """
+
+ def __init__(
+ self, back_color=(255, 255, 255), left_color=(0, 0, 0), right_color=(0, 0, 255)
+ ):
+ self.back_color = back_color
+ self.left_color = left_color
+ self.right_color = right_color
+ self.has_transparency = len(self.back_color) == 4
+
+ def get_fg_pixel(self, image, x, y):
+ width, _ = image.size
+ return self.interp_color(self.left_color, self.right_color, x / width)
+
+
+class VerticalGradiantColorMask(QRColorMask):
+ """
+ Fills in the forefround with a gradient sweeping from the top to the bottom
+ """
+
+ def __init__(
+ self, back_color=(255, 255, 255), top_color=(0, 0, 0), bottom_color=(0, 0, 255)
+ ):
+ self.back_color = back_color
+ self.top_color = top_color
+ self.bottom_color = bottom_color
+ self.has_transparency = len(self.back_color) == 4
+
+ def get_fg_pixel(self, image, x, y):
+ width, _ = image.size
+ return self.interp_color(self.top_color, self.bottom_color, y / width)
+
+
+class ImageColorMask(QRColorMask):
+ """
+ Fills in the foreground with pixels from another image, either passed by
+ path or passed by image object.
+ """
+
+ def __init__(
+ self, back_color=(255, 255, 255), color_mask_path=None, color_mask_image=None
+ ):
+ self.back_color = back_color
+ if color_mask_image:
+ self.color_img = color_mask_image
+ else:
+ self.color_img = Image.open(color_mask_path)
+
+ self.has_transparency = len(self.back_color) == 4
+
+ def initialize(self, styledPilImage, image):
+ self.paint_color = styledPilImage.paint_color
+ self.color_img = self.color_img.resize(image.size)
+
+ def get_fg_pixel(self, image, x, y):
+ width, _ = image.size
+ return self.color_img.getpixel((x, y))
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/__init__.py b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..99217d4966a112f294529f890fb57f1ea9b2f74c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/__init__.py
@@ -0,0 +1,10 @@
+# For backwards compatibility, importing the PIL drawers here.
+try:
+ from .pil import CircleModuleDrawer # noqa: F401
+ from .pil import GappedSquareModuleDrawer # noqa: F401
+ from .pil import HorizontalBarsDrawer # noqa: F401
+ from .pil import RoundedModuleDrawer # noqa: F401
+ from .pil import SquareModuleDrawer # noqa: F401
+ from .pil import VerticalBarsDrawer # noqa: F401
+except ImportError:
+ pass
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/base.py b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..154d2cfa83c6ca957624111658a9d61e1f335487
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/base.py
@@ -0,0 +1,33 @@
+import abc
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from qrcode.image.base import BaseImage
+
+
+class QRModuleDrawer(abc.ABC):
+ """
+ QRModuleDrawer exists to draw the modules of the QR Code onto images.
+
+ For this, technically all that is necessary is a ``drawrect(self, box,
+ is_active)`` function which takes in the box in which it is to draw,
+ whether or not the box is "active" (a module exists there). If
+ ``needs_neighbors`` is set to True, then the method should also accept a
+ ``neighbors`` kwarg (the neighboring pixels).
+
+ It is frequently necessary to also implement an "initialize" function to
+ set up values that only the containing Image class knows about.
+
+ For examples of what these look like, see doc/module_drawers.png
+ """
+
+ needs_neighbors = False
+
+ def __init__(self, **kwargs):
+ pass
+
+ def initialize(self, img: "BaseImage") -> None:
+ self.img = img
+
+ @abc.abstractmethod
+ def drawrect(self, box, is_active) -> None: ...
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/pil.py b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/pil.py
new file mode 100644
index 0000000000000000000000000000000000000000..4aa4249624ec79894cd4f560c76396710d9b7584
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/pil.py
@@ -0,0 +1,265 @@
+from typing import TYPE_CHECKING
+
+from PIL import Image, ImageDraw
+from qrcode.image.styles.moduledrawers.base import QRModuleDrawer
+
+if TYPE_CHECKING:
+ from qrcode.image.styledpil import StyledPilImage
+ from qrcode.main import ActiveWithNeighbors
+
+# When drawing antialiased things, make them bigger and then shrink them down
+# to size after the geometry has been drawn.
+ANTIALIASING_FACTOR = 4
+
+
+class StyledPilQRModuleDrawer(QRModuleDrawer):
+ """
+ A base class for StyledPilImage module drawers.
+
+ NOTE: the color that this draws in should be whatever is equivalent to
+ black in the color space, and the specified QRColorMask will handle adding
+ colors as necessary to the image
+ """
+
+ img: "StyledPilImage"
+
+
+class SquareModuleDrawer(StyledPilQRModuleDrawer):
+ """
+ Draws the modules as simple squares
+ """
+
+ def initialize(self, *args, **kwargs):
+ super().initialize(*args, **kwargs)
+ self.imgDraw = ImageDraw.Draw(self.img._img)
+
+ def drawrect(self, box, is_active: bool):
+ if is_active:
+ self.imgDraw.rectangle(box, fill=self.img.paint_color)
+
+
+class GappedSquareModuleDrawer(StyledPilQRModuleDrawer):
+ """
+ Draws the modules as simple squares that are not contiguous.
+
+ The size_ratio determines how wide the squares are relative to the width of
+ the space they are printed in
+ """
+
+ def __init__(self, size_ratio=0.8):
+ self.size_ratio = size_ratio
+
+ def initialize(self, *args, **kwargs):
+ super().initialize(*args, **kwargs)
+ self.imgDraw = ImageDraw.Draw(self.img._img)
+ self.delta = (1 - self.size_ratio) * self.img.box_size / 2
+
+ def drawrect(self, box, is_active: bool):
+ if is_active:
+ smaller_box = (
+ box[0][0] + self.delta,
+ box[0][1] + self.delta,
+ box[1][0] - self.delta,
+ box[1][1] - self.delta,
+ )
+ self.imgDraw.rectangle(smaller_box, fill=self.img.paint_color)
+
+
+class CircleModuleDrawer(StyledPilQRModuleDrawer):
+ """
+ Draws the modules as circles
+ """
+
+ circle = None
+
+ def initialize(self, *args, **kwargs):
+ super().initialize(*args, **kwargs)
+ box_size = self.img.box_size
+ fake_size = box_size * ANTIALIASING_FACTOR
+ self.circle = Image.new(
+ self.img.mode,
+ (fake_size, fake_size),
+ self.img.color_mask.back_color,
+ )
+ ImageDraw.Draw(self.circle).ellipse(
+ (0, 0, fake_size, fake_size), fill=self.img.paint_color
+ )
+ self.circle = self.circle.resize((box_size, box_size), Image.Resampling.LANCZOS)
+
+ def drawrect(self, box, is_active: bool):
+ if is_active:
+ self.img._img.paste(self.circle, (box[0][0], box[0][1]))
+
+
+class RoundedModuleDrawer(StyledPilQRModuleDrawer):
+ """
+ Draws the modules with all 90 degree corners replaced with rounded edges.
+
+ radius_ratio determines the radius of the rounded edges - a value of 1
+ means that an isolated module will be drawn as a circle, while a value of 0
+ means that the radius of the rounded edge will be 0 (and thus back to 90
+ degrees again).
+ """
+
+ needs_neighbors = True
+
+ def __init__(self, radius_ratio=1):
+ self.radius_ratio = radius_ratio
+
+ def initialize(self, *args, **kwargs):
+ super().initialize(*args, **kwargs)
+ self.corner_width = int(self.img.box_size / 2)
+ self.setup_corners()
+
+ def setup_corners(self):
+ mode = self.img.mode
+ back_color = self.img.color_mask.back_color
+ front_color = self.img.paint_color
+ self.SQUARE = Image.new(
+ mode, (self.corner_width, self.corner_width), front_color
+ )
+
+ fake_width = self.corner_width * ANTIALIASING_FACTOR
+ radius = self.radius_ratio * fake_width
+ diameter = radius * 2
+ base = Image.new(
+ mode, (fake_width, fake_width), back_color
+ ) # make something 4x bigger for antialiasing
+ base_draw = ImageDraw.Draw(base)
+ base_draw.ellipse((0, 0, diameter, diameter), fill=front_color)
+ base_draw.rectangle((radius, 0, fake_width, fake_width), fill=front_color)
+ base_draw.rectangle((0, radius, fake_width, fake_width), fill=front_color)
+ self.NW_ROUND = base.resize(
+ (self.corner_width, self.corner_width), Image.Resampling.LANCZOS
+ )
+ self.SW_ROUND = self.NW_ROUND.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
+ self.SE_ROUND = self.NW_ROUND.transpose(Image.Transpose.ROTATE_180)
+ self.NE_ROUND = self.NW_ROUND.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
+
+ def drawrect(self, box: list[list[int]], is_active: "ActiveWithNeighbors"):
+ if not is_active:
+ return
+ # find rounded edges
+ nw_rounded = not is_active.W and not is_active.N
+ ne_rounded = not is_active.N and not is_active.E
+ se_rounded = not is_active.E and not is_active.S
+ sw_rounded = not is_active.S and not is_active.W
+
+ nw = self.NW_ROUND if nw_rounded else self.SQUARE
+ ne = self.NE_ROUND if ne_rounded else self.SQUARE
+ se = self.SE_ROUND if se_rounded else self.SQUARE
+ sw = self.SW_ROUND if sw_rounded else self.SQUARE
+ self.img._img.paste(nw, (box[0][0], box[0][1]))
+ self.img._img.paste(ne, (box[0][0] + self.corner_width, box[0][1]))
+ self.img._img.paste(
+ se, (box[0][0] + self.corner_width, box[0][1] + self.corner_width)
+ )
+ self.img._img.paste(sw, (box[0][0], box[0][1] + self.corner_width))
+
+
+class VerticalBarsDrawer(StyledPilQRModuleDrawer):
+ """
+ Draws vertically contiguous groups of modules as long rounded rectangles,
+ with gaps between neighboring bands (the size of these gaps is inversely
+ proportional to the horizontal_shrink).
+ """
+
+ needs_neighbors = True
+
+ def __init__(self, horizontal_shrink=0.8):
+ self.horizontal_shrink = horizontal_shrink
+
+ def initialize(self, *args, **kwargs):
+ super().initialize(*args, **kwargs)
+ self.half_height = int(self.img.box_size / 2)
+ self.delta = int((1 - self.horizontal_shrink) * self.half_height)
+ self.setup_edges()
+
+ def setup_edges(self):
+ mode = self.img.mode
+ back_color = self.img.color_mask.back_color
+ front_color = self.img.paint_color
+
+ height = self.half_height
+ width = height * 2
+ shrunken_width = int(width * self.horizontal_shrink)
+ self.SQUARE = Image.new(mode, (shrunken_width, height), front_color)
+
+ fake_width = width * ANTIALIASING_FACTOR
+ fake_height = height * ANTIALIASING_FACTOR
+ base = Image.new(
+ mode, (fake_width, fake_height), back_color
+ ) # make something 4x bigger for antialiasing
+ base_draw = ImageDraw.Draw(base)
+ base_draw.ellipse((0, 0, fake_width, fake_height * 2), fill=front_color)
+
+ self.ROUND_TOP = base.resize((shrunken_width, height), Image.Resampling.LANCZOS)
+ self.ROUND_BOTTOM = self.ROUND_TOP.transpose(Image.Transpose.FLIP_TOP_BOTTOM)
+
+ def drawrect(self, box, is_active: "ActiveWithNeighbors"):
+ if is_active:
+ # find rounded edges
+ top_rounded = not is_active.N
+ bottom_rounded = not is_active.S
+
+ top = self.ROUND_TOP if top_rounded else self.SQUARE
+ bottom = self.ROUND_BOTTOM if bottom_rounded else self.SQUARE
+ self.img._img.paste(top, (box[0][0] + self.delta, box[0][1]))
+ self.img._img.paste(
+ bottom, (box[0][0] + self.delta, box[0][1] + self.half_height)
+ )
+
+
+class HorizontalBarsDrawer(StyledPilQRModuleDrawer):
+ """
+ Draws horizontally contiguous groups of modules as long rounded rectangles,
+ with gaps between neighboring bands (the size of these gaps is inversely
+ proportional to the vertical_shrink).
+ """
+
+ needs_neighbors = True
+
+ def __init__(self, vertical_shrink=0.8):
+ self.vertical_shrink = vertical_shrink
+
+ def initialize(self, *args, **kwargs):
+ super().initialize(*args, **kwargs)
+ self.half_width = int(self.img.box_size / 2)
+ self.delta = int((1 - self.vertical_shrink) * self.half_width)
+ self.setup_edges()
+
+ def setup_edges(self):
+ mode = self.img.mode
+ back_color = self.img.color_mask.back_color
+ front_color = self.img.paint_color
+
+ width = self.half_width
+ height = width * 2
+ shrunken_height = int(height * self.vertical_shrink)
+ self.SQUARE = Image.new(mode, (width, shrunken_height), front_color)
+
+ fake_width = width * ANTIALIASING_FACTOR
+ fake_height = height * ANTIALIASING_FACTOR
+ base = Image.new(
+ mode, (fake_width, fake_height), back_color
+ ) # make something 4x bigger for antialiasing
+ base_draw = ImageDraw.Draw(base)
+ base_draw.ellipse((0, 0, fake_width * 2, fake_height), fill=front_color)
+
+ self.ROUND_LEFT = base.resize(
+ (width, shrunken_height), Image.Resampling.LANCZOS
+ )
+ self.ROUND_RIGHT = self.ROUND_LEFT.transpose(Image.Transpose.FLIP_LEFT_RIGHT)
+
+ def drawrect(self, box, is_active: "ActiveWithNeighbors"):
+ if is_active:
+ # find rounded edges
+ left_rounded = not is_active.W
+ right_rounded = not is_active.E
+
+ left = self.ROUND_LEFT if left_rounded else self.SQUARE
+ right = self.ROUND_RIGHT if right_rounded else self.SQUARE
+ self.img._img.paste(left, (box[0][0], box[0][1] + self.delta))
+ self.img._img.paste(
+ right, (box[0][0] + self.half_width, box[0][1] + self.delta)
+ )
diff --git a/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/svg.py b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/svg.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf5b9e7d90a1c82e8910187d0b8a4f18f84dfe38
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/styles/moduledrawers/svg.py
@@ -0,0 +1,139 @@
+import abc
+from decimal import Decimal
+from typing import TYPE_CHECKING, NamedTuple
+
+from qrcode.image.styles.moduledrawers.base import QRModuleDrawer
+from qrcode.compat.etree import ET
+
+if TYPE_CHECKING:
+ from qrcode.image.svg import SvgFragmentImage, SvgPathImage
+
+ANTIALIASING_FACTOR = 4
+
+
+class Coords(NamedTuple):
+ x0: Decimal
+ y0: Decimal
+ x1: Decimal
+ y1: Decimal
+ xh: Decimal
+ yh: Decimal
+
+
+class BaseSvgQRModuleDrawer(QRModuleDrawer):
+ img: "SvgFragmentImage"
+
+ def __init__(self, *, size_ratio: Decimal = Decimal(1), **kwargs):
+ self.size_ratio = size_ratio
+
+ def initialize(self, *args, **kwargs) -> None:
+ super().initialize(*args, **kwargs)
+ self.box_delta = (1 - self.size_ratio) * self.img.box_size / 2
+ self.box_size = Decimal(self.img.box_size) * self.size_ratio
+ self.box_half = self.box_size / 2
+
+ def coords(self, box) -> Coords:
+ row, col = box[0]
+ x = row + self.box_delta
+ y = col + self.box_delta
+
+ return Coords(
+ x,
+ y,
+ x + self.box_size,
+ y + self.box_size,
+ x + self.box_half,
+ y + self.box_half,
+ )
+
+
+class SvgQRModuleDrawer(BaseSvgQRModuleDrawer):
+ tag = "rect"
+
+ def initialize(self, *args, **kwargs) -> None:
+ super().initialize(*args, **kwargs)
+ self.tag_qname = ET.QName(self.img._SVG_namespace, self.tag)
+
+ def drawrect(self, box, is_active: bool):
+ if not is_active:
+ return
+ self.img._img.append(self.el(box))
+
+ @abc.abstractmethod
+ def el(self, box): ...
+
+
+class SvgSquareDrawer(SvgQRModuleDrawer):
+ def initialize(self, *args, **kwargs) -> None:
+ super().initialize(*args, **kwargs)
+ self.unit_size = self.img.units(self.box_size)
+
+ def el(self, box):
+ coords = self.coords(box)
+ return ET.Element(
+ self.tag_qname, # type: ignore
+ x=self.img.units(coords.x0),
+ y=self.img.units(coords.y0),
+ width=self.unit_size,
+ height=self.unit_size,
+ )
+
+
+class SvgCircleDrawer(SvgQRModuleDrawer):
+ tag = "circle"
+
+ def initialize(self, *args, **kwargs) -> None:
+ super().initialize(*args, **kwargs)
+ self.radius = self.img.units(self.box_half)
+
+ def el(self, box):
+ coords = self.coords(box)
+ return ET.Element(
+ self.tag_qname, # type: ignore
+ cx=self.img.units(coords.xh),
+ cy=self.img.units(coords.yh),
+ r=self.radius,
+ )
+
+
+class SvgPathQRModuleDrawer(BaseSvgQRModuleDrawer):
+ img: "SvgPathImage"
+
+ def drawrect(self, box, is_active: bool):
+ if not is_active:
+ return
+ self.img._subpaths.append(self.subpath(box))
+
+ @abc.abstractmethod
+ def subpath(self, box) -> str: ...
+
+
+class SvgPathSquareDrawer(SvgPathQRModuleDrawer):
+ def subpath(self, box) -> str:
+ coords = self.coords(box)
+ x0 = self.img.units(coords.x0, text=False)
+ y0 = self.img.units(coords.y0, text=False)
+ x1 = self.img.units(coords.x1, text=False)
+ y1 = self.img.units(coords.y1, text=False)
+
+ return f"M{x0},{y0}H{x1}V{y1}H{x0}z"
+
+
+class SvgPathCircleDrawer(SvgPathQRModuleDrawer):
+ def initialize(self, *args, **kwargs) -> None:
+ super().initialize(*args, **kwargs)
+
+ def subpath(self, box) -> str:
+ coords = self.coords(box)
+ x0 = self.img.units(coords.x0, text=False)
+ yh = self.img.units(coords.yh, text=False)
+ h = self.img.units(self.box_half - self.box_delta, text=False)
+ x1 = self.img.units(coords.x1, text=False)
+
+ # rx,ry is the centerpoint of the arc
+ # 1? is the x-axis-rotation
+ # 2? is the large-arc-flag
+ # 3? is the sweep flag
+ # x,y is the point the arc is drawn to
+
+ return f"M{x0},{yh}A{h},{h} 0 0 0 {x1},{yh}A{h},{h} 0 0 0 {x0},{yh}z"
diff --git a/python_embeded/Lib/site-packages/qrcode/image/svg.py b/python_embeded/Lib/site-packages/qrcode/image/svg.py
new file mode 100644
index 0000000000000000000000000000000000000000..4117559ab8bdd78c9d2429e1d7d9b04b4b2306b7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/image/svg.py
@@ -0,0 +1,175 @@
+import decimal
+from decimal import Decimal
+from typing import Optional, Union, overload, Literal
+
+import qrcode.image.base
+from qrcode.compat.etree import ET
+from qrcode.image.styles.moduledrawers import svg as svg_drawers
+from qrcode.image.styles.moduledrawers.base import QRModuleDrawer
+
+
+class SvgFragmentImage(qrcode.image.base.BaseImageWithDrawer):
+ """
+ SVG image builder
+
+ Creates a QR-code image as a SVG document fragment.
+ """
+
+ _SVG_namespace = "http://www.w3.org/2000/svg"
+ kind = "SVG"
+ allowed_kinds = ("SVG",)
+ default_drawer_class: type[QRModuleDrawer] = svg_drawers.SvgSquareDrawer
+
+ def __init__(self, *args, **kwargs):
+ ET.register_namespace("svg", self._SVG_namespace)
+ super().__init__(*args, **kwargs)
+ # Save the unit size, for example the default box_size of 10 is '1mm'.
+ self.unit_size = self.units(self.box_size)
+
+ @overload
+ def units(self, pixels: Union[int, Decimal], text: Literal[False]) -> Decimal: ...
+
+ @overload
+ def units(self, pixels: Union[int, Decimal], text: Literal[True] = True) -> str: ...
+
+ def units(self, pixels, text=True):
+ """
+ A box_size of 10 (default) equals 1mm.
+ """
+ units = Decimal(pixels) / 10
+ if not text:
+ return units
+ units = units.quantize(Decimal("0.001"))
+ context = decimal.Context(traps=[decimal.Inexact])
+ try:
+ for d in (Decimal("0.01"), Decimal("0.1"), Decimal("0")):
+ units = units.quantize(d, context=context)
+ except decimal.Inexact:
+ pass
+ return f"{units}mm"
+
+ def save(self, stream, kind=None):
+ self.check_kind(kind=kind)
+ self._write(stream)
+
+ def to_string(self, **kwargs):
+ return ET.tostring(self._img, **kwargs)
+
+ def new_image(self, **kwargs):
+ return self._svg(**kwargs)
+
+ def _svg(self, tag=None, version="1.1", **kwargs):
+ if tag is None:
+ tag = ET.QName(self._SVG_namespace, "svg")
+ dimension = self.units(self.pixel_size)
+ return ET.Element(
+ tag, # type: ignore
+ width=dimension,
+ height=dimension,
+ version=version,
+ **kwargs,
+ )
+
+ def _write(self, stream):
+ ET.ElementTree(self._img).write(stream, xml_declaration=False)
+
+
+class SvgImage(SvgFragmentImage):
+ """
+ Standalone SVG image builder
+
+ Creates a QR-code image as a standalone SVG document.
+ """
+
+ background: Optional[str] = None
+ drawer_aliases: qrcode.image.base.DrawerAliases = {
+ "circle": (svg_drawers.SvgCircleDrawer, {}),
+ "gapped-circle": (svg_drawers.SvgCircleDrawer, {"size_ratio": Decimal(0.8)}),
+ "gapped-square": (svg_drawers.SvgSquareDrawer, {"size_ratio": Decimal(0.8)}),
+ }
+
+ def _svg(self, tag="svg", **kwargs):
+ svg = super()._svg(tag=tag, **kwargs)
+ svg.set("xmlns", self._SVG_namespace)
+ if self.background:
+ svg.append(
+ ET.Element(
+ "rect",
+ fill=self.background,
+ x="0",
+ y="0",
+ width="100%",
+ height="100%",
+ )
+ )
+ return svg
+
+ def _write(self, stream):
+ ET.ElementTree(self._img).write(stream, encoding="UTF-8", xml_declaration=True)
+
+
+class SvgPathImage(SvgImage):
+ """
+ SVG image builder with one single element (removes white spaces
+ between individual QR points).
+ """
+
+ QR_PATH_STYLE = {
+ "fill": "#000000",
+ "fill-opacity": "1",
+ "fill-rule": "nonzero",
+ "stroke": "none",
+ }
+
+ needs_processing = True
+ path: Optional[ET.Element] = None
+ default_drawer_class: type[QRModuleDrawer] = svg_drawers.SvgPathSquareDrawer
+ drawer_aliases = {
+ "circle": (svg_drawers.SvgPathCircleDrawer, {}),
+ "gapped-circle": (
+ svg_drawers.SvgPathCircleDrawer,
+ {"size_ratio": Decimal(0.8)},
+ ),
+ "gapped-square": (
+ svg_drawers.SvgPathSquareDrawer,
+ {"size_ratio": Decimal(0.8)},
+ ),
+ }
+
+ def __init__(self, *args, **kwargs):
+ self._subpaths: list[str] = []
+ super().__init__(*args, **kwargs)
+
+ def _svg(self, viewBox=None, **kwargs):
+ if viewBox is None:
+ dimension = self.units(self.pixel_size, text=False)
+ viewBox = "0 0 {d} {d}".format(d=dimension)
+ return super()._svg(viewBox=viewBox, **kwargs)
+
+ def process(self):
+ # Store the path just in case someone wants to use it again or in some
+ # unique way.
+ self.path = ET.Element(
+ ET.QName("path"), # type: ignore
+ d="".join(self._subpaths),
+ id="qr-path",
+ **self.QR_PATH_STYLE,
+ )
+ self._subpaths = []
+ self._img.append(self.path)
+
+
+class SvgFillImage(SvgImage):
+ """
+ An SvgImage that fills the background to white.
+ """
+
+ background = "white"
+
+
+class SvgPathFillImage(SvgPathImage):
+ """
+ An SvgPathImage that fills the background to white.
+ """
+
+ background = "white"
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/__init__.py b/python_embeded/Lib/site-packages/qrcode/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/consts.py b/python_embeded/Lib/site-packages/qrcode/tests/consts.py
new file mode 100644
index 0000000000000000000000000000000000000000..b1240139baa70df4629a0b13137daa0d18f6f7f2
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/consts.py
@@ -0,0 +1,4 @@
+UNICODE_TEXT = "\u03b1\u03b2\u03b3"
+WHITE = (255, 255, 255)
+BLACK = (0, 0, 0)
+RED = (255, 0, 0)
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_example.py b/python_embeded/Lib/site-packages/qrcode/tests/test_example.py
new file mode 100644
index 0000000000000000000000000000000000000000..7190fe3e75e24715e915d966d4b7abd4182cb9b3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_example.py
@@ -0,0 +1,13 @@
+from unittest import mock
+
+import pytest
+
+from qrcode import run_example
+
+pytest.importorskip("PIL", reason="Requires PIL")
+
+
+@mock.patch("PIL.Image.Image.show")
+def test_example(mock_show):
+ run_example()
+ mock_show.assert_called_with()
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode.py b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode.py
new file mode 100644
index 0000000000000000000000000000000000000000..652428480b59a8b018498e840031e049f643505e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode.py
@@ -0,0 +1,271 @@
+import io
+from unittest import mock
+
+import pytest
+
+import qrcode
+import qrcode.util
+from qrcode.exceptions import DataOverflowError
+from qrcode.image.base import BaseImage
+from qrcode.tests.consts import UNICODE_TEXT
+from qrcode.util import MODE_8BIT_BYTE, MODE_ALPHA_NUM, MODE_NUMBER, QRData
+
+
+def test_basic():
+ qr = qrcode.QRCode(version=1)
+ qr.add_data("a")
+ qr.make(fit=False)
+
+
+def test_large():
+ qr = qrcode.QRCode(version=27)
+ qr.add_data("a")
+ qr.make(fit=False)
+
+
+def test_invalid_version():
+ with pytest.raises(ValueError):
+ qrcode.QRCode(version=42)
+
+
+def test_invalid_border():
+ with pytest.raises(ValueError):
+ qrcode.QRCode(border=-1)
+
+
+def test_overflow():
+ qr = qrcode.QRCode(version=1)
+ qr.add_data("abcdefghijklmno")
+ with pytest.raises(DataOverflowError):
+ qr.make(fit=False)
+
+
+def test_add_qrdata():
+ qr = qrcode.QRCode(version=1)
+ data = QRData("a")
+ qr.add_data(data)
+ qr.make(fit=False)
+
+
+def test_fit():
+ qr = qrcode.QRCode()
+ qr.add_data("a")
+ qr.make()
+ assert qr.version == 1
+ qr.add_data("bcdefghijklmno")
+ qr.make()
+ assert qr.version == 2
+
+
+def test_mode_number():
+ qr = qrcode.QRCode()
+ qr.add_data("1234567890123456789012345678901234", optimize=0)
+ qr.make()
+ assert qr.version == 1
+ assert qr.data_list[0].mode == MODE_NUMBER
+
+
+def test_mode_alpha():
+ qr = qrcode.QRCode()
+ qr.add_data("ABCDEFGHIJ1234567890", optimize=0)
+ qr.make()
+ assert qr.version == 1
+ assert qr.data_list[0].mode == MODE_ALPHA_NUM
+
+
+def test_regression_mode_comma():
+ qr = qrcode.QRCode()
+ qr.add_data(",", optimize=0)
+ qr.make()
+ assert qr.data_list[0].mode == MODE_8BIT_BYTE
+
+
+def test_mode_8bit():
+ qr = qrcode.QRCode()
+ qr.add_data("abcABC" + UNICODE_TEXT, optimize=0)
+ qr.make()
+ assert qr.version == 1
+ assert qr.data_list[0].mode == MODE_8BIT_BYTE
+
+
+def test_mode_8bit_newline():
+ qr = qrcode.QRCode()
+ qr.add_data("ABCDEFGHIJ1234567890\n", optimize=0)
+ qr.make()
+ assert qr.data_list[0].mode == MODE_8BIT_BYTE
+
+
+def test_make_image_with_wrong_pattern():
+ with pytest.raises(TypeError):
+ qrcode.QRCode(mask_pattern="string pattern")
+
+ with pytest.raises(ValueError):
+ qrcode.QRCode(mask_pattern=-1)
+
+ with pytest.raises(ValueError):
+ qrcode.QRCode(mask_pattern=42)
+
+
+def test_mask_pattern_setter():
+ qr = qrcode.QRCode()
+
+ with pytest.raises(TypeError):
+ qr.mask_pattern = "string pattern"
+
+ with pytest.raises(ValueError):
+ qr.mask_pattern = -1
+
+ with pytest.raises(ValueError):
+ qr.mask_pattern = 8
+
+
+def test_qrcode_bad_factory():
+ with pytest.raises(TypeError):
+ qrcode.QRCode(image_factory="not_BaseImage") # type: ignore
+
+ with pytest.raises(AssertionError):
+ qrcode.QRCode(image_factory=dict) # type: ignore
+
+
+def test_qrcode_factory():
+ class MockFactory(BaseImage):
+ drawrect = mock.Mock()
+ new_image = mock.Mock()
+
+ qr = qrcode.QRCode(image_factory=MockFactory)
+ qr.add_data(UNICODE_TEXT)
+ qr.make_image()
+ assert MockFactory.new_image.called
+ assert MockFactory.drawrect.called
+
+
+def test_optimize():
+ qr = qrcode.QRCode()
+ text = "A1abc12345def1HELLOa"
+ qr.add_data(text, optimize=4)
+ qr.make()
+ assert [d.mode for d in qr.data_list] == [
+ MODE_8BIT_BYTE,
+ MODE_NUMBER,
+ MODE_8BIT_BYTE,
+ MODE_ALPHA_NUM,
+ MODE_8BIT_BYTE,
+ ]
+ assert qr.version == 2
+
+
+def test_optimize_short():
+ qr = qrcode.QRCode()
+ text = "A1abc1234567def1HELLOa"
+ qr.add_data(text, optimize=7)
+ qr.make()
+ assert len(qr.data_list) == 3
+ assert [d.mode for d in qr.data_list] == [
+ MODE_8BIT_BYTE,
+ MODE_NUMBER,
+ MODE_8BIT_BYTE,
+ ]
+ assert qr.version == 2
+
+
+def test_optimize_longer_than_data():
+ qr = qrcode.QRCode()
+ text = "ABCDEFGHIJK"
+ qr.add_data(text, optimize=12)
+ assert len(qr.data_list) == 1
+ assert qr.data_list[0].mode == MODE_ALPHA_NUM
+
+
+def test_optimize_size():
+ text = "A1abc12345123451234512345def1HELLOHELLOHELLOHELLOa" * 5
+
+ qr = qrcode.QRCode()
+ qr.add_data(text)
+ qr.make()
+ assert qr.version == 10
+
+ qr = qrcode.QRCode()
+ qr.add_data(text, optimize=0)
+ qr.make()
+ assert qr.version == 11
+
+
+def test_qrdata_repr():
+ data = b"hello"
+ data_obj = qrcode.util.QRData(data)
+ assert repr(data_obj) == repr(data)
+
+
+def test_print_ascii_stdout():
+ qr = qrcode.QRCode()
+ with mock.patch("sys.stdout") as fake_stdout:
+ fake_stdout.isatty.return_value = None
+ with pytest.raises(OSError):
+ qr.print_ascii(tty=True)
+ assert fake_stdout.isatty.called
+
+
+def test_print_ascii():
+ qr = qrcode.QRCode(border=0)
+ f = io.StringIO()
+ qr.print_ascii(out=f)
+ printed = f.getvalue()
+ f.close()
+ expected = "\u2588\u2580\u2580\u2580\u2580\u2580\u2588"
+ assert printed[: len(expected)] == expected
+
+ f = io.StringIO()
+ f.isatty = lambda: True
+ qr.print_ascii(out=f, tty=True)
+ printed = f.getvalue()
+ f.close()
+ expected = "\x1b[48;5;232m\x1b[38;5;255m" + "\xa0\u2584\u2584\u2584\u2584\u2584\xa0"
+ assert printed[: len(expected)] == expected
+
+
+def test_print_tty_stdout():
+ qr = qrcode.QRCode()
+ with mock.patch("sys.stdout") as fake_stdout:
+ fake_stdout.isatty.return_value = None
+ pytest.raises(OSError, qr.print_tty)
+ assert fake_stdout.isatty.called
+
+
+def test_print_tty():
+ qr = qrcode.QRCode()
+ f = io.StringIO()
+ f.isatty = lambda: True
+ qr.print_tty(out=f)
+ printed = f.getvalue()
+ f.close()
+ BOLD_WHITE_BG = "\x1b[1;47m"
+ BLACK_BG = "\x1b[40m"
+ WHITE_BLOCK = BOLD_WHITE_BG + " " + BLACK_BG
+ EOL = "\x1b[0m\n"
+ expected = BOLD_WHITE_BG + " " * 23 + EOL + WHITE_BLOCK + " " * 7 + WHITE_BLOCK
+ assert printed[: len(expected)] == expected
+
+
+def test_get_matrix():
+ qr = qrcode.QRCode(border=0)
+ qr.add_data("1")
+ assert qr.get_matrix() == qr.modules
+
+
+def test_get_matrix_border():
+ qr = qrcode.QRCode(border=1)
+ qr.add_data("1")
+ matrix = [row[1:-1] for row in qr.get_matrix()[1:-1]]
+ assert matrix == qr.modules
+
+
+def test_negative_size_at_construction():
+ with pytest.raises(ValueError):
+ qrcode.QRCode(box_size=-1)
+
+
+def test_negative_size_at_usage():
+ qr = qrcode.QRCode()
+ qr.box_size = -1
+ with pytest.raises(ValueError):
+ qr.make_image()
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_pil.py b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_pil.py
new file mode 100644
index 0000000000000000000000000000000000000000..95ef5af7ba881abdb4e375d7971f6c0babf8faf4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_pil.py
@@ -0,0 +1,157 @@
+import io
+
+import pytest
+
+import qrcode
+import qrcode.util
+from qrcode.tests.consts import BLACK, RED, UNICODE_TEXT, WHITE
+
+Image = pytest.importorskip("PIL.Image", reason="PIL is not installed")
+
+if Image:
+ from qrcode.image.styledpil import StyledPilImage
+ from qrcode.image.styles import colormasks, moduledrawers
+
+
+def test_render_pil():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image()
+ img.save(io.BytesIO())
+ assert isinstance(img.get_image(), Image.Image)
+
+
+@pytest.mark.parametrize("back_color", ["TransParent", "red", (255, 195, 235)])
+def test_render_pil_background(back_color):
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(back_color="TransParent")
+ img.save(io.BytesIO())
+
+
+def test_render_pil_with_rgb_color_tuples():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(back_color=(255, 195, 235), fill_color=(55, 95, 35))
+ img.save(io.BytesIO())
+
+
+def test_render_with_pattern():
+ qr = qrcode.QRCode(mask_pattern=3)
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image()
+ img.save(io.BytesIO())
+
+
+def test_render_styled_Image():
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=StyledPilImage)
+ img.save(io.BytesIO())
+
+
+def test_render_styled_with_embedded_image():
+ embedded_img = Image.new("RGB", (10, 10), color="red")
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_H)
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=StyledPilImage, embedded_image=embedded_img)
+ img.save(io.BytesIO())
+
+
+def test_render_styled_with_embedded_image_path(tmp_path):
+ tmpfile = str(tmp_path / "test.png")
+ embedded_img = Image.new("RGB", (10, 10), color="red")
+ embedded_img.save(tmpfile)
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_H)
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=StyledPilImage, embedded_image_path=tmpfile)
+ img.save(io.BytesIO())
+
+
+@pytest.mark.parametrize(
+ "drawer",
+ [
+ moduledrawers.CircleModuleDrawer,
+ moduledrawers.GappedSquareModuleDrawer,
+ moduledrawers.HorizontalBarsDrawer,
+ moduledrawers.RoundedModuleDrawer,
+ moduledrawers.SquareModuleDrawer,
+ moduledrawers.VerticalBarsDrawer,
+ ],
+)
+def test_render_styled_with_drawer(drawer):
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(
+ image_factory=StyledPilImage,
+ module_drawer=drawer(),
+ )
+ img.save(io.BytesIO())
+
+
+@pytest.mark.parametrize(
+ "mask",
+ [
+ colormasks.SolidFillColorMask(),
+ colormasks.SolidFillColorMask(back_color=WHITE, front_color=RED),
+ colormasks.SolidFillColorMask(back_color=(255, 0, 255, 255), front_color=RED),
+ colormasks.RadialGradiantColorMask(
+ back_color=WHITE, center_color=BLACK, edge_color=RED
+ ),
+ colormasks.SquareGradiantColorMask(
+ back_color=WHITE, center_color=BLACK, edge_color=RED
+ ),
+ colormasks.HorizontalGradiantColorMask(
+ back_color=WHITE, left_color=RED, right_color=BLACK
+ ),
+ colormasks.VerticalGradiantColorMask(
+ back_color=WHITE, top_color=RED, bottom_color=BLACK
+ ),
+ colormasks.ImageColorMask(
+ back_color=WHITE, color_mask_image=Image.new("RGB", (10, 10), color="red")
+ ),
+ ],
+)
+def test_render_styled_with_mask(mask):
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=StyledPilImage, color_mask=mask)
+ img.save(io.BytesIO())
+
+
+def test_embedded_image_and_error_correction(tmp_path):
+ "If an embedded image is specified, error correction must be the highest so the QR code is readable"
+ tmpfile = str(tmp_path / "test.png")
+ embedded_img = Image.new("RGB", (10, 10), color="red")
+ embedded_img.save(tmpfile)
+
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_L)
+ qr.add_data(UNICODE_TEXT)
+ with pytest.raises(ValueError):
+ qr.make_image(embedded_image_path=tmpfile)
+ with pytest.raises(ValueError):
+ qr.make_image(embedded_image=embedded_img)
+
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_M)
+ qr.add_data(UNICODE_TEXT)
+ with pytest.raises(ValueError):
+ qr.make_image(embedded_image_path=tmpfile)
+ with pytest.raises(ValueError):
+ qr.make_image(embedded_image=embedded_img)
+
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_Q)
+ qr.add_data(UNICODE_TEXT)
+ with pytest.raises(ValueError):
+ qr.make_image(embedded_image_path=tmpfile)
+ with pytest.raises(ValueError):
+ qr.make_image(embedded_image=embedded_img)
+
+ # The only accepted correction level when an embedded image is provided
+ qr = qrcode.QRCode(error_correction=qrcode.ERROR_CORRECT_H)
+ qr.add_data(UNICODE_TEXT)
+ qr.make_image(embedded_image_path=tmpfile)
+ qr.make_image(embedded_image=embedded_img)
+
+
+def test_shortcut():
+ qrcode.make("image")
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_pypng.py b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_pypng.py
new file mode 100644
index 0000000000000000000000000000000000000000..c502a3b3c35bc8d78227a9556af86dc8d54e007a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_pypng.py
@@ -0,0 +1,35 @@
+import io
+from unittest import mock
+
+import pytest
+
+
+import qrcode
+import qrcode.util
+from qrcode.image.pure import PyPNGImage
+from qrcode.tests.consts import UNICODE_TEXT
+
+png = pytest.importorskip("png", reason="png is not installed")
+
+
+def test_render_pypng():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=PyPNGImage)
+ assert isinstance(img.get_image(), png.Writer)
+
+ print(img.width, img.box_size, img.border)
+ img.save(io.BytesIO())
+
+
+def test_render_pypng_to_str():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=PyPNGImage)
+ assert isinstance(img.get_image(), png.Writer)
+
+ mock_open = mock.mock_open()
+ with mock.patch("qrcode.image.pure.open", mock_open, create=True):
+ img.save("test_file.png")
+ mock_open.assert_called_once_with("test_file.png", "wb")
+ mock_open("test_file.png", "wb").write.assert_called()
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_svg.py b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_svg.py
new file mode 100644
index 0000000000000000000000000000000000000000..4774b2451ccfdaa67ba957fe151d0d6104d9cf2d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_qrcode_svg.py
@@ -0,0 +1,54 @@
+import io
+
+import qrcode
+from qrcode.image import svg
+from qrcode.tests.consts import UNICODE_TEXT
+
+
+class SvgImageWhite(svg.SvgImage):
+ background = "white"
+
+
+def test_render_svg():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=svg.SvgImage)
+ img.save(io.BytesIO())
+
+
+def test_render_svg_path():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=svg.SvgPathImage)
+ img.save(io.BytesIO())
+
+
+def test_render_svg_fragment():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=svg.SvgFragmentImage)
+ img.save(io.BytesIO())
+
+
+def test_svg_string():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=svg.SvgFragmentImage)
+ file_like = io.BytesIO()
+ img.save(file_like)
+ file_like.seek(0)
+ assert file_like.read() in img.to_string()
+
+
+def test_render_svg_with_background():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=SvgImageWhite)
+ img.save(io.BytesIO())
+
+
+def test_svg_circle_drawer():
+ qr = qrcode.QRCode()
+ qr.add_data(UNICODE_TEXT)
+ img = qr.make_image(image_factory=svg.SvgPathImage, module_drawer="circle")
+ img.save(io.BytesIO())
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_release.py b/python_embeded/Lib/site-packages/qrcode/tests/test_release.py
new file mode 100644
index 0000000000000000000000000000000000000000..d61454b6ed03f79e9e185d7e03cdf0ed8e867e60
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_release.py
@@ -0,0 +1,43 @@
+import builtins
+import datetime
+import re
+from unittest import mock
+
+from qrcode.release import update_manpage
+
+OPEN = f"{builtins.__name__}.open"
+DATA = 'test\n.TH "date" "version" "description"\nthis'
+
+
+@mock.patch(OPEN, new_callable=mock.mock_open, read_data=".TH invalid")
+def test_invalid_data(mock_file):
+ update_manpage({"name": "qrcode", "new_version": "1.23"})
+ mock_file.assert_called()
+ mock_file().write.assert_not_called()
+
+
+@mock.patch(OPEN, new_callable=mock.mock_open, read_data=DATA)
+def test_not_qrcode(mock_file):
+ update_manpage({"name": "not-qrcode"})
+ mock_file.assert_not_called()
+
+
+@mock.patch(OPEN, new_callable=mock.mock_open, read_data=DATA)
+def test_no_change(mock_file):
+ update_manpage({"name": "qrcode", "new_version": "version"})
+ mock_file.assert_called()
+ mock_file().write.assert_not_called()
+
+
+@mock.patch(OPEN, new_callable=mock.mock_open, read_data=DATA)
+def test_change(mock_file):
+ update_manpage({"name": "qrcode", "new_version": "3.11"})
+ expected = re.split(r"([^\n]*(?:\n|$))", DATA)[1::2]
+ expected[1] = (
+ expected[1]
+ .replace("version", "3.11")
+ .replace("date", datetime.datetime.now().strftime("%-d %b %Y"))
+ )
+ mock_file().write.assert_has_calls(
+ [mock.call(line) for line in expected if line != ""], any_order=True
+ )
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_script.py b/python_embeded/Lib/site-packages/qrcode/tests/test_script.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6338ded4fbe9bcf9d6a63e5e280398dbdab5200
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_script.py
@@ -0,0 +1,97 @@
+import sys
+from unittest import mock
+
+import pytest
+
+from qrcode.console_scripts import commas, main
+
+
+def bad_read():
+ raise UnicodeDecodeError("utf-8", b"0x80", 0, 1, "invalid start byte")
+
+
+@mock.patch("os.isatty", lambda *args: True)
+@mock.patch("qrcode.main.QRCode.print_ascii")
+def test_isatty(mock_print_ascii):
+ main(["testtext"])
+ mock_print_ascii.assert_called_with(tty=True)
+
+
+@mock.patch("os.isatty", lambda *args: False)
+def test_piped():
+ pytest.importorskip("PIL", reason="Requires PIL")
+ main(["testtext"])
+
+
+@mock.patch("os.isatty", lambda *args: True)
+def test_stdin():
+ with mock.patch("qrcode.main.QRCode.print_ascii") as mock_print_ascii:
+ with mock.patch("sys.stdin") as mock_stdin:
+ mock_stdin.buffer.read.return_value = "testtext"
+ main([])
+ assert mock_stdin.buffer.read.called
+ mock_print_ascii.assert_called_with(tty=True)
+
+
+@mock.patch("os.isatty", lambda *args: True)
+def test_stdin_py3_unicodedecodeerror():
+ with mock.patch("qrcode.main.QRCode.print_ascii") as mock_print_ascii:
+ with mock.patch("sys.stdin") as mock_stdin:
+ mock_stdin.buffer.read.return_value = "testtext"
+ mock_stdin.read.side_effect = bad_read
+ # sys.stdin.read() will raise an error...
+ with pytest.raises(UnicodeDecodeError):
+ sys.stdin.read()
+ # ... but it won't be used now.
+ main([])
+ mock_print_ascii.assert_called_with(tty=True)
+
+
+def test_optimize():
+ pytest.importorskip("PIL", reason="Requires PIL")
+ main("testtext --optimize 0".split())
+
+
+def test_factory():
+ main(["testtext", "--factory", "svg"])
+
+
+def test_bad_factory():
+ with pytest.raises(SystemExit):
+ main(["testtext", "--factory", "nope"])
+
+
+@mock.patch.object(sys, "argv", "qr testtext output".split())
+def test_sys_argv():
+ pytest.importorskip("PIL", reason="Requires PIL")
+ main()
+
+
+def test_output(tmp_path):
+ pytest.importorskip("PIL", reason="Requires PIL")
+ main(["testtext", "--output", str(tmp_path / "test.png")])
+
+
+def test_factory_drawer_none(capsys):
+ pytest.importorskip("PIL", reason="Requires PIL")
+ with pytest.raises(SystemExit):
+ main("testtext --factory pil --factory-drawer nope".split())
+ assert "The selected factory has no drawer aliases" in capsys.readouterr()[1]
+
+
+def test_factory_drawer_bad(capsys):
+ with pytest.raises(SystemExit):
+ main("testtext --factory svg --factory-drawer sobad".split())
+ assert "sobad factory drawer not found" in capsys.readouterr()[1]
+
+
+def test_factory_drawer(capsys):
+ main("testtext --factory svg --factory-drawer circle".split())
+
+
+def test_commas():
+ assert commas([]) == ""
+ assert commas(["A"]) == "A"
+ assert commas("AB") == "A or B"
+ assert commas("ABC") == "A, B or C"
+ assert commas("ABC", joiner="and") == "A, B and C"
diff --git a/python_embeded/Lib/site-packages/qrcode/tests/test_util.py b/python_embeded/Lib/site-packages/qrcode/tests/test_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..e57badbccb000da14f38b3e05546d7d7f5cc6ec6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/qrcode/tests/test_util.py
@@ -0,0 +1,11 @@
+import pytest
+
+from qrcode import util
+
+
+def test_check_wrong_version():
+ with pytest.raises(ValueError):
+ util.check_version(0)
+
+ with pytest.raises(ValueError):
+ util.check_version(41)
diff --git a/python_embeded/Lib/site-packages/redis-6.2.0.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/redis-6.2.0.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..8509ccd678eea721e68a9c75139554e5d3aec8cf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis-6.2.0.dist-info/licenses/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2022-2023, Redis, inc.
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/__init__.py b/python_embeded/Lib/site-packages/redis/asyncio/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3545ab44c24f506389cc88a7ea42b6d750ebc840
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/__init__.py
@@ -0,0 +1,64 @@
+from redis.asyncio.client import Redis, StrictRedis
+from redis.asyncio.cluster import RedisCluster
+from redis.asyncio.connection import (
+ BlockingConnectionPool,
+ Connection,
+ ConnectionPool,
+ SSLConnection,
+ UnixDomainSocketConnection,
+)
+from redis.asyncio.sentinel import (
+ Sentinel,
+ SentinelConnectionPool,
+ SentinelManagedConnection,
+ SentinelManagedSSLConnection,
+)
+from redis.asyncio.utils import from_url
+from redis.backoff import default_backoff
+from redis.exceptions import (
+ AuthenticationError,
+ AuthenticationWrongNumberOfArgsError,
+ BusyLoadingError,
+ ChildDeadlockedError,
+ ConnectionError,
+ DataError,
+ InvalidResponse,
+ OutOfMemoryError,
+ PubSubError,
+ ReadOnlyError,
+ RedisError,
+ ResponseError,
+ TimeoutError,
+ WatchError,
+)
+
+__all__ = [
+ "AuthenticationError",
+ "AuthenticationWrongNumberOfArgsError",
+ "BlockingConnectionPool",
+ "BusyLoadingError",
+ "ChildDeadlockedError",
+ "Connection",
+ "ConnectionError",
+ "ConnectionPool",
+ "DataError",
+ "from_url",
+ "default_backoff",
+ "InvalidResponse",
+ "PubSubError",
+ "OutOfMemoryError",
+ "ReadOnlyError",
+ "Redis",
+ "RedisCluster",
+ "RedisError",
+ "ResponseError",
+ "Sentinel",
+ "SentinelConnectionPool",
+ "SentinelManagedConnection",
+ "SentinelManagedSSLConnection",
+ "SSLConnection",
+ "StrictRedis",
+ "TimeoutError",
+ "UnixDomainSocketConnection",
+ "WatchError",
+]
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/client.py b/python_embeded/Lib/site-packages/redis/asyncio/client.py
new file mode 100644
index 0000000000000000000000000000000000000000..aac409073f59bf924cc8167674c4d6f959585d09
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/client.py
@@ -0,0 +1,1618 @@
+import asyncio
+import copy
+import inspect
+import re
+import warnings
+from typing import (
+ TYPE_CHECKING,
+ Any,
+ AsyncIterator,
+ Awaitable,
+ Callable,
+ Dict,
+ Iterable,
+ List,
+ Mapping,
+ MutableMapping,
+ Optional,
+ Protocol,
+ Set,
+ Tuple,
+ Type,
+ TypedDict,
+ TypeVar,
+ Union,
+ cast,
+)
+
+from redis._parsers.helpers import (
+ _RedisCallbacks,
+ _RedisCallbacksRESP2,
+ _RedisCallbacksRESP3,
+ bool_ok,
+)
+from redis.asyncio.connection import (
+ Connection,
+ ConnectionPool,
+ SSLConnection,
+ UnixDomainSocketConnection,
+)
+from redis.asyncio.lock import Lock
+from redis.asyncio.retry import Retry
+from redis.backoff import ExponentialWithJitterBackoff
+from redis.client import (
+ EMPTY_RESPONSE,
+ NEVER_DECODE,
+ AbstractRedis,
+ CaseInsensitiveDict,
+)
+from redis.commands import (
+ AsyncCoreCommands,
+ AsyncRedisModuleCommands,
+ AsyncSentinelCommands,
+ list_or_args,
+)
+from redis.credentials import CredentialProvider
+from redis.event import (
+ AfterPooledConnectionsInstantiationEvent,
+ AfterPubSubConnectionInstantiationEvent,
+ AfterSingleConnectionInstantiationEvent,
+ ClientType,
+ EventDispatcher,
+)
+from redis.exceptions import (
+ ConnectionError,
+ ExecAbortError,
+ PubSubError,
+ RedisError,
+ ResponseError,
+ WatchError,
+)
+from redis.typing import ChannelT, EncodableT, KeyT
+from redis.utils import (
+ SSL_AVAILABLE,
+ _set_info_logger,
+ deprecated_args,
+ deprecated_function,
+ get_lib_version,
+ safe_str,
+ str_if_bytes,
+ truncate_text,
+)
+
+if TYPE_CHECKING and SSL_AVAILABLE:
+ from ssl import TLSVersion, VerifyMode
+else:
+ TLSVersion = None
+ VerifyMode = None
+
+PubSubHandler = Callable[[Dict[str, str]], Awaitable[None]]
+_KeyT = TypeVar("_KeyT", bound=KeyT)
+_ArgT = TypeVar("_ArgT", KeyT, EncodableT)
+_RedisT = TypeVar("_RedisT", bound="Redis")
+_NormalizeKeysT = TypeVar("_NormalizeKeysT", bound=Mapping[ChannelT, object])
+if TYPE_CHECKING:
+ from redis.commands.core import Script
+
+
+class ResponseCallbackProtocol(Protocol):
+ def __call__(self, response: Any, **kwargs): ...
+
+
+class AsyncResponseCallbackProtocol(Protocol):
+ async def __call__(self, response: Any, **kwargs): ...
+
+
+ResponseCallbackT = Union[ResponseCallbackProtocol, AsyncResponseCallbackProtocol]
+
+
+class Redis(
+ AbstractRedis, AsyncRedisModuleCommands, AsyncCoreCommands, AsyncSentinelCommands
+):
+ """
+ Implementation of the Redis protocol.
+
+ This abstract class provides a Python interface to all Redis commands
+ and an implementation of the Redis protocol.
+
+ Pipelines derive from this, implementing how
+ the commands are sent and received to the Redis server. Based on
+ configuration, an instance will either use a ConnectionPool, or
+ Connection object to talk to redis.
+ """
+
+ response_callbacks: MutableMapping[Union[str, bytes], ResponseCallbackT]
+
+ @classmethod
+ def from_url(
+ cls,
+ url: str,
+ single_connection_client: bool = False,
+ auto_close_connection_pool: Optional[bool] = None,
+ **kwargs,
+ ):
+ """
+ Return a Redis client object configured from the given URL
+
+ For example::
+
+ redis://[[username]:[password]]@localhost:6379/0
+ rediss://[[username]:[password]]@localhost:6379/0
+ unix://[username@]/path/to/socket.sock?db=0[&password=password]
+
+ Three URL schemes are supported:
+
+ - `redis://` creates a TCP socket connection. See more at:
+
+ - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
+
+ - ``unix://``: creates a Unix Domain Socket connection.
+
+ The username, password, hostname, path and all querystring values
+ are passed through urllib.parse.unquote in order to replace any
+ percent-encoded values with their corresponding characters.
+
+ There are several ways to specify a database number. The first value
+ found will be used:
+
+ 1. A ``db`` querystring option, e.g. redis://localhost?db=0
+
+ 2. If using the redis:// or rediss:// schemes, the path argument
+ of the url, e.g. redis://localhost/0
+
+ 3. A ``db`` keyword argument to this function.
+
+ If none of these options are specified, the default db=0 is used.
+
+ All querystring options are cast to their appropriate Python types.
+ Boolean arguments can be specified with string values "True"/"False"
+ or "Yes"/"No". Values that cannot be properly cast cause a
+ ``ValueError`` to be raised. Once parsed, the querystring arguments
+ and keyword arguments are passed to the ``ConnectionPool``'s
+ class initializer. In the case of conflicting arguments, querystring
+ arguments always win.
+
+ """
+ connection_pool = ConnectionPool.from_url(url, **kwargs)
+ client = cls(
+ connection_pool=connection_pool,
+ single_connection_client=single_connection_client,
+ )
+ if auto_close_connection_pool is not None:
+ warnings.warn(
+ DeprecationWarning(
+ '"auto_close_connection_pool" is deprecated '
+ "since version 5.0.1. "
+ "Please create a ConnectionPool explicitly and "
+ "provide to the Redis() constructor instead."
+ )
+ )
+ else:
+ auto_close_connection_pool = True
+ client.auto_close_connection_pool = auto_close_connection_pool
+ return client
+
+ @classmethod
+ def from_pool(
+ cls: Type["Redis"],
+ connection_pool: ConnectionPool,
+ ) -> "Redis":
+ """
+ Return a Redis client from the given connection pool.
+ The Redis client will take ownership of the connection pool and
+ close it when the Redis client is closed.
+ """
+ client = cls(
+ connection_pool=connection_pool,
+ )
+ client.auto_close_connection_pool = True
+ return client
+
+ @deprecated_args(
+ args_to_warn=["retry_on_timeout"],
+ reason="TimeoutError is included by default.",
+ version="6.0.0",
+ )
+ def __init__(
+ self,
+ *,
+ host: str = "localhost",
+ port: int = 6379,
+ db: Union[str, int] = 0,
+ password: Optional[str] = None,
+ socket_timeout: Optional[float] = None,
+ socket_connect_timeout: Optional[float] = None,
+ socket_keepalive: Optional[bool] = None,
+ socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
+ connection_pool: Optional[ConnectionPool] = None,
+ unix_socket_path: Optional[str] = None,
+ encoding: str = "utf-8",
+ encoding_errors: str = "strict",
+ decode_responses: bool = False,
+ retry_on_timeout: bool = False,
+ retry: Retry = Retry(
+ backoff=ExponentialWithJitterBackoff(base=1, cap=10), retries=3
+ ),
+ retry_on_error: Optional[list] = None,
+ ssl: bool = False,
+ ssl_keyfile: Optional[str] = None,
+ ssl_certfile: Optional[str] = None,
+ ssl_cert_reqs: Union[str, VerifyMode] = "required",
+ ssl_ca_certs: Optional[str] = None,
+ ssl_ca_data: Optional[str] = None,
+ ssl_check_hostname: bool = True,
+ ssl_min_version: Optional[TLSVersion] = None,
+ ssl_ciphers: Optional[str] = None,
+ max_connections: Optional[int] = None,
+ single_connection_client: bool = False,
+ health_check_interval: int = 0,
+ client_name: Optional[str] = None,
+ lib_name: Optional[str] = "redis-py",
+ lib_version: Optional[str] = get_lib_version(),
+ username: Optional[str] = None,
+ auto_close_connection_pool: Optional[bool] = None,
+ redis_connect_func=None,
+ credential_provider: Optional[CredentialProvider] = None,
+ protocol: Optional[int] = 2,
+ event_dispatcher: Optional[EventDispatcher] = None,
+ ):
+ """
+ Initialize a new Redis client.
+
+ To specify a retry policy for specific errors, you have two options:
+
+ 1. Set the `retry_on_error` to a list of the error/s to retry on, and
+ you can also set `retry` to a valid `Retry` object(in case the default
+ one is not appropriate) - with this approach the retries will be triggered
+ on the default errors specified in the Retry object enriched with the
+ errors specified in `retry_on_error`.
+
+ 2. Define a `Retry` object with configured 'supported_errors' and set
+ it to the `retry` parameter - with this approach you completely redefine
+ the errors on which retries will happen.
+
+ `retry_on_timeout` is deprecated - please include the TimeoutError
+ either in the Retry object or in the `retry_on_error` list.
+
+ When 'connection_pool' is provided - the retry configuration of the
+ provided pool will be used.
+ """
+ kwargs: Dict[str, Any]
+ if event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+ else:
+ self._event_dispatcher = event_dispatcher
+ # auto_close_connection_pool only has an effect if connection_pool is
+ # None. It is assumed that if connection_pool is not None, the user
+ # wants to manage the connection pool themselves.
+ if auto_close_connection_pool is not None:
+ warnings.warn(
+ DeprecationWarning(
+ '"auto_close_connection_pool" is deprecated '
+ "since version 5.0.1. "
+ "Please create a ConnectionPool explicitly and "
+ "provide to the Redis() constructor instead."
+ )
+ )
+ else:
+ auto_close_connection_pool = True
+
+ if not connection_pool:
+ # Create internal connection pool, expected to be closed by Redis instance
+ if not retry_on_error:
+ retry_on_error = []
+ kwargs = {
+ "db": db,
+ "username": username,
+ "password": password,
+ "credential_provider": credential_provider,
+ "socket_timeout": socket_timeout,
+ "encoding": encoding,
+ "encoding_errors": encoding_errors,
+ "decode_responses": decode_responses,
+ "retry_on_error": retry_on_error,
+ "retry": copy.deepcopy(retry),
+ "max_connections": max_connections,
+ "health_check_interval": health_check_interval,
+ "client_name": client_name,
+ "lib_name": lib_name,
+ "lib_version": lib_version,
+ "redis_connect_func": redis_connect_func,
+ "protocol": protocol,
+ }
+ # based on input, setup appropriate connection args
+ if unix_socket_path is not None:
+ kwargs.update(
+ {
+ "path": unix_socket_path,
+ "connection_class": UnixDomainSocketConnection,
+ }
+ )
+ else:
+ # TCP specific options
+ kwargs.update(
+ {
+ "host": host,
+ "port": port,
+ "socket_connect_timeout": socket_connect_timeout,
+ "socket_keepalive": socket_keepalive,
+ "socket_keepalive_options": socket_keepalive_options,
+ }
+ )
+
+ if ssl:
+ kwargs.update(
+ {
+ "connection_class": SSLConnection,
+ "ssl_keyfile": ssl_keyfile,
+ "ssl_certfile": ssl_certfile,
+ "ssl_cert_reqs": ssl_cert_reqs,
+ "ssl_ca_certs": ssl_ca_certs,
+ "ssl_ca_data": ssl_ca_data,
+ "ssl_check_hostname": ssl_check_hostname,
+ "ssl_min_version": ssl_min_version,
+ "ssl_ciphers": ssl_ciphers,
+ }
+ )
+ # This arg only used if no pool is passed in
+ self.auto_close_connection_pool = auto_close_connection_pool
+ connection_pool = ConnectionPool(**kwargs)
+ self._event_dispatcher.dispatch(
+ AfterPooledConnectionsInstantiationEvent(
+ [connection_pool], ClientType.ASYNC, credential_provider
+ )
+ )
+ else:
+ # If a pool is passed in, do not close it
+ self.auto_close_connection_pool = False
+ self._event_dispatcher.dispatch(
+ AfterPooledConnectionsInstantiationEvent(
+ [connection_pool], ClientType.ASYNC, credential_provider
+ )
+ )
+
+ self.connection_pool = connection_pool
+ self.single_connection_client = single_connection_client
+ self.connection: Optional[Connection] = None
+
+ self.response_callbacks = CaseInsensitiveDict(_RedisCallbacks)
+
+ if self.connection_pool.connection_kwargs.get("protocol") in ["3", 3]:
+ self.response_callbacks.update(_RedisCallbacksRESP3)
+ else:
+ self.response_callbacks.update(_RedisCallbacksRESP2)
+
+ # If using a single connection client, we need to lock creation-of and use-of
+ # the client in order to avoid race conditions such as using asyncio.gather
+ # on a set of redis commands
+ self._single_conn_lock = asyncio.Lock()
+
+ def __repr__(self):
+ return (
+ f"<{self.__class__.__module__}.{self.__class__.__name__}"
+ f"({self.connection_pool!r})>"
+ )
+
+ def __await__(self):
+ return self.initialize().__await__()
+
+ async def initialize(self: _RedisT) -> _RedisT:
+ if self.single_connection_client:
+ async with self._single_conn_lock:
+ if self.connection is None:
+ self.connection = await self.connection_pool.get_connection()
+
+ self._event_dispatcher.dispatch(
+ AfterSingleConnectionInstantiationEvent(
+ self.connection, ClientType.ASYNC, self._single_conn_lock
+ )
+ )
+ return self
+
+ def set_response_callback(self, command: str, callback: ResponseCallbackT):
+ """Set a custom Response Callback"""
+ self.response_callbacks[command] = callback
+
+ def get_encoder(self):
+ """Get the connection pool's encoder"""
+ return self.connection_pool.get_encoder()
+
+ def get_connection_kwargs(self):
+ """Get the connection's key-word arguments"""
+ return self.connection_pool.connection_kwargs
+
+ def get_retry(self) -> Optional[Retry]:
+ return self.get_connection_kwargs().get("retry")
+
+ def set_retry(self, retry: Retry) -> None:
+ self.get_connection_kwargs().update({"retry": retry})
+ self.connection_pool.set_retry(retry)
+
+ def load_external_module(self, funcname, func):
+ """
+ This function can be used to add externally defined redis modules,
+ and their namespaces to the redis client.
+
+ funcname - A string containing the name of the function to create
+ func - The function, being added to this class.
+
+ ex: Assume that one has a custom redis module named foomod that
+ creates command named 'foo.dothing' and 'foo.anotherthing' in redis.
+ To load function functions into this namespace:
+
+ from redis import Redis
+ from foomodule import F
+ r = Redis()
+ r.load_external_module("foo", F)
+ r.foo().dothing('your', 'arguments')
+
+ For a concrete example see the reimport of the redisjson module in
+ tests/test_connection.py::test_loading_external_modules
+ """
+ setattr(self, funcname, func)
+
+ def pipeline(
+ self, transaction: bool = True, shard_hint: Optional[str] = None
+ ) -> "Pipeline":
+ """
+ Return a new pipeline object that can queue multiple commands for
+ later execution. ``transaction`` indicates whether all commands
+ should be executed atomically. Apart from making a group of operations
+ atomic, pipelines are useful for reducing the back-and-forth overhead
+ between the client and server.
+ """
+ return Pipeline(
+ self.connection_pool, self.response_callbacks, transaction, shard_hint
+ )
+
+ async def transaction(
+ self,
+ func: Callable[["Pipeline"], Union[Any, Awaitable[Any]]],
+ *watches: KeyT,
+ shard_hint: Optional[str] = None,
+ value_from_callable: bool = False,
+ watch_delay: Optional[float] = None,
+ ):
+ """
+ Convenience method for executing the callable `func` as a transaction
+ while watching all keys specified in `watches`. The 'func' callable
+ should expect a single argument which is a Pipeline object.
+ """
+ pipe: Pipeline
+ async with self.pipeline(True, shard_hint) as pipe:
+ while True:
+ try:
+ if watches:
+ await pipe.watch(*watches)
+ func_value = func(pipe)
+ if inspect.isawaitable(func_value):
+ func_value = await func_value
+ exec_value = await pipe.execute()
+ return func_value if value_from_callable else exec_value
+ except WatchError:
+ if watch_delay is not None and watch_delay > 0:
+ await asyncio.sleep(watch_delay)
+ continue
+
+ def lock(
+ self,
+ name: KeyT,
+ timeout: Optional[float] = None,
+ sleep: float = 0.1,
+ blocking: bool = True,
+ blocking_timeout: Optional[float] = None,
+ lock_class: Optional[Type[Lock]] = None,
+ thread_local: bool = True,
+ raise_on_release_error: bool = True,
+ ) -> Lock:
+ """
+ Return a new Lock object using key ``name`` that mimics
+ the behavior of threading.Lock.
+
+ If specified, ``timeout`` indicates a maximum life for the lock.
+ By default, it will remain locked until release() is called.
+
+ ``sleep`` indicates the amount of time to sleep per loop iteration
+ when the lock is in blocking mode and another client is currently
+ holding the lock.
+
+ ``blocking`` indicates whether calling ``acquire`` should block until
+ the lock has been acquired or to fail immediately, causing ``acquire``
+ to return False and the lock not being acquired. Defaults to True.
+ Note this value can be overridden by passing a ``blocking``
+ argument to ``acquire``.
+
+ ``blocking_timeout`` indicates the maximum amount of time in seconds to
+ spend trying to acquire the lock. A value of ``None`` indicates
+ continue trying forever. ``blocking_timeout`` can be specified as a
+ float or integer, both representing the number of seconds to wait.
+
+ ``lock_class`` forces the specified lock implementation. Note that as
+ of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
+ a Lua-based lock). So, it's unlikely you'll need this parameter, unless
+ you have created your own custom lock class.
+
+ ``thread_local`` indicates whether the lock token is placed in
+ thread-local storage. By default, the token is placed in thread local
+ storage so that a thread only sees its token, not a token set by
+ another thread. Consider the following timeline:
+
+ time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
+ thread-1 sets the token to "abc"
+ time: 1, thread-2 blocks trying to acquire `my-lock` using the
+ Lock instance.
+ time: 5, thread-1 has not yet completed. redis expires the lock
+ key.
+ time: 5, thread-2 acquired `my-lock` now that it's available.
+ thread-2 sets the token to "xyz"
+ time: 6, thread-1 finishes its work and calls release(). if the
+ token is *not* stored in thread local storage, then
+ thread-1 would see the token value as "xyz" and would be
+ able to successfully release the thread-2's lock.
+
+ ``raise_on_release_error`` indicates whether to raise an exception when
+ the lock is no longer owned when exiting the context manager. By default,
+ this is True, meaning an exception will be raised. If False, the warning
+ will be logged and the exception will be suppressed.
+
+ In some use cases it's necessary to disable thread local storage. For
+ example, if you have code where one thread acquires a lock and passes
+ that lock instance to a worker thread to release later. If thread
+ local storage isn't disabled in this case, the worker thread won't see
+ the token set by the thread that acquired the lock. Our assumption
+ is that these cases aren't common and as such default to using
+ thread local storage."""
+ if lock_class is None:
+ lock_class = Lock
+ return lock_class(
+ self,
+ name,
+ timeout=timeout,
+ sleep=sleep,
+ blocking=blocking,
+ blocking_timeout=blocking_timeout,
+ thread_local=thread_local,
+ raise_on_release_error=raise_on_release_error,
+ )
+
+ def pubsub(self, **kwargs) -> "PubSub":
+ """
+ Return a Publish/Subscribe object. With this object, you can
+ subscribe to channels and listen for messages that get published to
+ them.
+ """
+ return PubSub(
+ self.connection_pool, event_dispatcher=self._event_dispatcher, **kwargs
+ )
+
+ def monitor(self) -> "Monitor":
+ return Monitor(self.connection_pool)
+
+ def client(self) -> "Redis":
+ return self.__class__(
+ connection_pool=self.connection_pool, single_connection_client=True
+ )
+
+ async def __aenter__(self: _RedisT) -> _RedisT:
+ return await self.initialize()
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.aclose()
+
+ _DEL_MESSAGE = "Unclosed Redis client"
+
+ # passing _warnings and _grl as argument default since they may be gone
+ # by the time __del__ is called at shutdown
+ def __del__(
+ self,
+ _warn: Any = warnings.warn,
+ _grl: Any = asyncio.get_running_loop,
+ ) -> None:
+ if hasattr(self, "connection") and (self.connection is not None):
+ _warn(f"Unclosed client session {self!r}", ResourceWarning, source=self)
+ try:
+ context = {"client": self, "message": self._DEL_MESSAGE}
+ _grl().call_exception_handler(context)
+ except RuntimeError:
+ pass
+ self.connection._close()
+
+ async def aclose(self, close_connection_pool: Optional[bool] = None) -> None:
+ """
+ Closes Redis client connection
+
+ Args:
+ close_connection_pool:
+ decides whether to close the connection pool used by this Redis client,
+ overriding Redis.auto_close_connection_pool.
+ By default, let Redis.auto_close_connection_pool decide
+ whether to close the connection pool.
+ """
+ conn = self.connection
+ if conn:
+ self.connection = None
+ await self.connection_pool.release(conn)
+ if close_connection_pool or (
+ close_connection_pool is None and self.auto_close_connection_pool
+ ):
+ await self.connection_pool.disconnect()
+
+ @deprecated_function(version="5.0.1", reason="Use aclose() instead", name="close")
+ async def close(self, close_connection_pool: Optional[bool] = None) -> None:
+ """
+ Alias for aclose(), for backwards compatibility
+ """
+ await self.aclose(close_connection_pool)
+
+ async def _send_command_parse_response(self, conn, command_name, *args, **options):
+ """
+ Send a command and parse the response
+ """
+ await conn.send_command(*args)
+ return await self.parse_response(conn, command_name, **options)
+
+ async def _close_connection(self, conn: Connection):
+ """
+ Close the connection before retrying.
+
+ The supported exceptions are already checked in the
+ retry object so we don't need to do it here.
+
+ After we disconnect the connection, it will try to reconnect and
+ do a health check as part of the send_command logic(on connection level).
+ """
+ await conn.disconnect()
+
+ # COMMAND EXECUTION AND PROTOCOL PARSING
+ async def execute_command(self, *args, **options):
+ """Execute a command and return a parsed response"""
+ await self.initialize()
+ pool = self.connection_pool
+ command_name = args[0]
+ conn = self.connection or await pool.get_connection()
+
+ if self.single_connection_client:
+ await self._single_conn_lock.acquire()
+ try:
+ return await conn.retry.call_with_retry(
+ lambda: self._send_command_parse_response(
+ conn, command_name, *args, **options
+ ),
+ lambda _: self._close_connection(conn),
+ )
+ finally:
+ if self.single_connection_client:
+ self._single_conn_lock.release()
+ if not self.connection:
+ await pool.release(conn)
+
+ async def parse_response(
+ self, connection: Connection, command_name: Union[str, bytes], **options
+ ):
+ """Parses a response from the Redis server"""
+ try:
+ if NEVER_DECODE in options:
+ response = await connection.read_response(disable_decoding=True)
+ options.pop(NEVER_DECODE)
+ else:
+ response = await connection.read_response()
+ except ResponseError:
+ if EMPTY_RESPONSE in options:
+ return options[EMPTY_RESPONSE]
+ raise
+
+ if EMPTY_RESPONSE in options:
+ options.pop(EMPTY_RESPONSE)
+
+ # Remove keys entry, it needs only for cache.
+ options.pop("keys", None)
+
+ if command_name in self.response_callbacks:
+ # Mypy bug: https://github.com/python/mypy/issues/10977
+ command_name = cast(str, command_name)
+ retval = self.response_callbacks[command_name](response, **options)
+ return await retval if inspect.isawaitable(retval) else retval
+ return response
+
+
+StrictRedis = Redis
+
+
+class MonitorCommandInfo(TypedDict):
+ time: float
+ db: int
+ client_address: str
+ client_port: str
+ client_type: str
+ command: str
+
+
+class Monitor:
+ """
+ Monitor is useful for handling the MONITOR command to the redis server.
+ next_command() method returns one command from monitor
+ listen() method yields commands from monitor.
+ """
+
+ monitor_re = re.compile(r"\[(\d+) (.*?)\] (.*)")
+ command_re = re.compile(r'"(.*?)(? MonitorCommandInfo:
+ """Parse the response from a monitor command"""
+ await self.connect()
+ response = await self.connection.read_response()
+ if isinstance(response, bytes):
+ response = self.connection.encoder.decode(response, force=True)
+ command_time, command_data = response.split(" ", 1)
+ m = self.monitor_re.match(command_data)
+ db_id, client_info, command = m.groups()
+ command = " ".join(self.command_re.findall(command))
+ # Redis escapes double quotes because each piece of the command
+ # string is surrounded by double quotes. We don't have that
+ # requirement so remove the escaping and leave the quote.
+ command = command.replace('\\"', '"')
+
+ if client_info == "lua":
+ client_address = "lua"
+ client_port = ""
+ client_type = "lua"
+ elif client_info.startswith("unix"):
+ client_address = "unix"
+ client_port = client_info[5:]
+ client_type = "unix"
+ else:
+ # use rsplit as ipv6 addresses contain colons
+ client_address, client_port = client_info.rsplit(":", 1)
+ client_type = "tcp"
+ return {
+ "time": float(command_time),
+ "db": int(db_id),
+ "client_address": client_address,
+ "client_port": client_port,
+ "client_type": client_type,
+ "command": command,
+ }
+
+ async def listen(self) -> AsyncIterator[MonitorCommandInfo]:
+ """Listen for commands coming to the server."""
+ while True:
+ yield await self.next_command()
+
+
+class PubSub:
+ """
+ PubSub provides publish, subscribe and listen support to Redis channels.
+
+ After subscribing to one or more channels, the listen() method will block
+ until a message arrives on one of the subscribed channels. That message
+ will be returned and it's safe to start listening again.
+ """
+
+ PUBLISH_MESSAGE_TYPES = ("message", "pmessage")
+ UNSUBSCRIBE_MESSAGE_TYPES = ("unsubscribe", "punsubscribe")
+ HEALTH_CHECK_MESSAGE = "redis-py-health-check"
+
+ def __init__(
+ self,
+ connection_pool: ConnectionPool,
+ shard_hint: Optional[str] = None,
+ ignore_subscribe_messages: bool = False,
+ encoder=None,
+ push_handler_func: Optional[Callable] = None,
+ event_dispatcher: Optional["EventDispatcher"] = None,
+ ):
+ if event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+ else:
+ self._event_dispatcher = event_dispatcher
+ self.connection_pool = connection_pool
+ self.shard_hint = shard_hint
+ self.ignore_subscribe_messages = ignore_subscribe_messages
+ self.connection = None
+ # we need to know the encoding options for this connection in order
+ # to lookup channel and pattern names for callback handlers.
+ self.encoder = encoder
+ self.push_handler_func = push_handler_func
+ if self.encoder is None:
+ self.encoder = self.connection_pool.get_encoder()
+ if self.encoder.decode_responses:
+ self.health_check_response = [
+ ["pong", self.HEALTH_CHECK_MESSAGE],
+ self.HEALTH_CHECK_MESSAGE,
+ ]
+ else:
+ self.health_check_response = [
+ [b"pong", self.encoder.encode(self.HEALTH_CHECK_MESSAGE)],
+ self.encoder.encode(self.HEALTH_CHECK_MESSAGE),
+ ]
+ if self.push_handler_func is None:
+ _set_info_logger()
+ self.channels = {}
+ self.pending_unsubscribe_channels = set()
+ self.patterns = {}
+ self.pending_unsubscribe_patterns = set()
+ self._lock = asyncio.Lock()
+
+ async def __aenter__(self):
+ return self
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.aclose()
+
+ def __del__(self):
+ if self.connection:
+ self.connection.deregister_connect_callback(self.on_connect)
+
+ async def aclose(self):
+ # In case a connection property does not yet exist
+ # (due to a crash earlier in the Redis() constructor), return
+ # immediately as there is nothing to clean-up.
+ if not hasattr(self, "connection"):
+ return
+ async with self._lock:
+ if self.connection:
+ await self.connection.disconnect()
+ self.connection.deregister_connect_callback(self.on_connect)
+ await self.connection_pool.release(self.connection)
+ self.connection = None
+ self.channels = {}
+ self.pending_unsubscribe_channels = set()
+ self.patterns = {}
+ self.pending_unsubscribe_patterns = set()
+
+ @deprecated_function(version="5.0.1", reason="Use aclose() instead", name="close")
+ async def close(self) -> None:
+ """Alias for aclose(), for backwards compatibility"""
+ await self.aclose()
+
+ @deprecated_function(version="5.0.1", reason="Use aclose() instead", name="reset")
+ async def reset(self) -> None:
+ """Alias for aclose(), for backwards compatibility"""
+ await self.aclose()
+
+ async def on_connect(self, connection: Connection):
+ """Re-subscribe to any channels and patterns previously subscribed to"""
+ # NOTE: for python3, we can't pass bytestrings as keyword arguments
+ # so we need to decode channel/pattern names back to unicode strings
+ # before passing them to [p]subscribe.
+ self.pending_unsubscribe_channels.clear()
+ self.pending_unsubscribe_patterns.clear()
+ if self.channels:
+ channels = {}
+ for k, v in self.channels.items():
+ channels[self.encoder.decode(k, force=True)] = v
+ await self.subscribe(**channels)
+ if self.patterns:
+ patterns = {}
+ for k, v in self.patterns.items():
+ patterns[self.encoder.decode(k, force=True)] = v
+ await self.psubscribe(**patterns)
+
+ @property
+ def subscribed(self):
+ """Indicates if there are subscriptions to any channels or patterns"""
+ return bool(self.channels or self.patterns)
+
+ async def execute_command(self, *args: EncodableT):
+ """Execute a publish/subscribe command"""
+
+ # NOTE: don't parse the response in this function -- it could pull a
+ # legitimate message off the stack if the connection is already
+ # subscribed to one or more channels
+
+ await self.connect()
+ connection = self.connection
+ kwargs = {"check_health": not self.subscribed}
+ await self._execute(connection, connection.send_command, *args, **kwargs)
+
+ async def connect(self):
+ """
+ Ensure that the PubSub is connected
+ """
+ if self.connection is None:
+ self.connection = await self.connection_pool.get_connection()
+ # register a callback that re-subscribes to any channels we
+ # were listening to when we were disconnected
+ self.connection.register_connect_callback(self.on_connect)
+ else:
+ await self.connection.connect()
+ if self.push_handler_func is not None:
+ self.connection._parser.set_pubsub_push_handler(self.push_handler_func)
+
+ self._event_dispatcher.dispatch(
+ AfterPubSubConnectionInstantiationEvent(
+ self.connection, self.connection_pool, ClientType.ASYNC, self._lock
+ )
+ )
+
+ async def _reconnect(self, conn):
+ """
+ Try to reconnect
+ """
+ await conn.disconnect()
+ await conn.connect()
+
+ async def _execute(self, conn, command, *args, **kwargs):
+ """
+ Connect manually upon disconnection. If the Redis server is down,
+ this will fail and raise a ConnectionError as desired.
+ After reconnection, the ``on_connect`` callback should have been
+ called by the # connection to resubscribe us to any channels and
+ patterns we were previously listening to
+ """
+ return await conn.retry.call_with_retry(
+ lambda: command(*args, **kwargs),
+ lambda _: self._reconnect(conn),
+ )
+
+ async def parse_response(self, block: bool = True, timeout: float = 0):
+ """Parse the response from a publish/subscribe command"""
+ conn = self.connection
+ if conn is None:
+ raise RuntimeError(
+ "pubsub connection not set: "
+ "did you forget to call subscribe() or psubscribe()?"
+ )
+
+ await self.check_health()
+
+ if not conn.is_connected:
+ await conn.connect()
+
+ read_timeout = None if block else timeout
+ response = await self._execute(
+ conn,
+ conn.read_response,
+ timeout=read_timeout,
+ disconnect_on_error=False,
+ push_request=True,
+ )
+
+ if conn.health_check_interval and response in self.health_check_response:
+ # ignore the health check message as user might not expect it
+ return None
+ return response
+
+ async def check_health(self):
+ conn = self.connection
+ if conn is None:
+ raise RuntimeError(
+ "pubsub connection not set: "
+ "did you forget to call subscribe() or psubscribe()?"
+ )
+
+ if (
+ conn.health_check_interval
+ and asyncio.get_running_loop().time() > conn.next_health_check
+ ):
+ await conn.send_command(
+ "PING", self.HEALTH_CHECK_MESSAGE, check_health=False
+ )
+
+ def _normalize_keys(self, data: _NormalizeKeysT) -> _NormalizeKeysT:
+ """
+ normalize channel/pattern names to be either bytes or strings
+ based on whether responses are automatically decoded. this saves us
+ from coercing the value for each message coming in.
+ """
+ encode = self.encoder.encode
+ decode = self.encoder.decode
+ return {decode(encode(k)): v for k, v in data.items()} # type: ignore[return-value] # noqa: E501
+
+ async def psubscribe(self, *args: ChannelT, **kwargs: PubSubHandler):
+ """
+ Subscribe to channel patterns. Patterns supplied as keyword arguments
+ expect a pattern name as the key and a callable as the value. A
+ pattern's callable will be invoked automatically when a message is
+ received on that pattern rather than producing a message via
+ ``listen()``.
+ """
+ parsed_args = list_or_args((args[0],), args[1:]) if args else args
+ new_patterns: Dict[ChannelT, PubSubHandler] = dict.fromkeys(parsed_args)
+ # Mypy bug: https://github.com/python/mypy/issues/10970
+ new_patterns.update(kwargs) # type: ignore[arg-type]
+ ret_val = await self.execute_command("PSUBSCRIBE", *new_patterns.keys())
+ # update the patterns dict AFTER we send the command. we don't want to
+ # subscribe twice to these patterns, once for the command and again
+ # for the reconnection.
+ new_patterns = self._normalize_keys(new_patterns)
+ self.patterns.update(new_patterns)
+ self.pending_unsubscribe_patterns.difference_update(new_patterns)
+ return ret_val
+
+ def punsubscribe(self, *args: ChannelT) -> Awaitable:
+ """
+ Unsubscribe from the supplied patterns. If empty, unsubscribe from
+ all patterns.
+ """
+ patterns: Iterable[ChannelT]
+ if args:
+ parsed_args = list_or_args((args[0],), args[1:])
+ patterns = self._normalize_keys(dict.fromkeys(parsed_args)).keys()
+ else:
+ parsed_args = []
+ patterns = self.patterns
+ self.pending_unsubscribe_patterns.update(patterns)
+ return self.execute_command("PUNSUBSCRIBE", *parsed_args)
+
+ async def subscribe(self, *args: ChannelT, **kwargs: Callable):
+ """
+ Subscribe to channels. Channels supplied as keyword arguments expect
+ a channel name as the key and a callable as the value. A channel's
+ callable will be invoked automatically when a message is received on
+ that channel rather than producing a message via ``listen()`` or
+ ``get_message()``.
+ """
+ parsed_args = list_or_args((args[0],), args[1:]) if args else ()
+ new_channels = dict.fromkeys(parsed_args)
+ # Mypy bug: https://github.com/python/mypy/issues/10970
+ new_channels.update(kwargs) # type: ignore[arg-type]
+ ret_val = await self.execute_command("SUBSCRIBE", *new_channels.keys())
+ # update the channels dict AFTER we send the command. we don't want to
+ # subscribe twice to these channels, once for the command and again
+ # for the reconnection.
+ new_channels = self._normalize_keys(new_channels)
+ self.channels.update(new_channels)
+ self.pending_unsubscribe_channels.difference_update(new_channels)
+ return ret_val
+
+ def unsubscribe(self, *args) -> Awaitable:
+ """
+ Unsubscribe from the supplied channels. If empty, unsubscribe from
+ all channels
+ """
+ if args:
+ parsed_args = list_or_args(args[0], args[1:])
+ channels = self._normalize_keys(dict.fromkeys(parsed_args))
+ else:
+ parsed_args = []
+ channels = self.channels
+ self.pending_unsubscribe_channels.update(channels)
+ return self.execute_command("UNSUBSCRIBE", *parsed_args)
+
+ async def listen(self) -> AsyncIterator:
+ """Listen for messages on channels this client has been subscribed to"""
+ while self.subscribed:
+ response = await self.handle_message(await self.parse_response(block=True))
+ if response is not None:
+ yield response
+
+ async def get_message(
+ self, ignore_subscribe_messages: bool = False, timeout: Optional[float] = 0.0
+ ):
+ """
+ Get the next message if one is available, otherwise None.
+
+ If timeout is specified, the system will wait for `timeout` seconds
+ before returning. Timeout should be specified as a floating point
+ number or None to wait indefinitely.
+ """
+ response = await self.parse_response(block=(timeout is None), timeout=timeout)
+ if response:
+ return await self.handle_message(response, ignore_subscribe_messages)
+ return None
+
+ def ping(self, message=None) -> Awaitable:
+ """
+ Ping the Redis server
+ """
+ args = ["PING", message] if message is not None else ["PING"]
+ return self.execute_command(*args)
+
+ async def handle_message(self, response, ignore_subscribe_messages=False):
+ """
+ Parses a pub/sub message. If the channel or pattern was subscribed to
+ with a message handler, the handler is invoked instead of a parsed
+ message being returned.
+ """
+ if response is None:
+ return None
+ if isinstance(response, bytes):
+ response = [b"pong", response] if response != b"PONG" else [b"pong", b""]
+ message_type = str_if_bytes(response[0])
+ if message_type == "pmessage":
+ message = {
+ "type": message_type,
+ "pattern": response[1],
+ "channel": response[2],
+ "data": response[3],
+ }
+ elif message_type == "pong":
+ message = {
+ "type": message_type,
+ "pattern": None,
+ "channel": None,
+ "data": response[1],
+ }
+ else:
+ message = {
+ "type": message_type,
+ "pattern": None,
+ "channel": response[1],
+ "data": response[2],
+ }
+
+ # if this is an unsubscribe message, remove it from memory
+ if message_type in self.UNSUBSCRIBE_MESSAGE_TYPES:
+ if message_type == "punsubscribe":
+ pattern = response[1]
+ if pattern in self.pending_unsubscribe_patterns:
+ self.pending_unsubscribe_patterns.remove(pattern)
+ self.patterns.pop(pattern, None)
+ else:
+ channel = response[1]
+ if channel in self.pending_unsubscribe_channels:
+ self.pending_unsubscribe_channels.remove(channel)
+ self.channels.pop(channel, None)
+
+ if message_type in self.PUBLISH_MESSAGE_TYPES:
+ # if there's a message handler, invoke it
+ if message_type == "pmessage":
+ handler = self.patterns.get(message["pattern"], None)
+ else:
+ handler = self.channels.get(message["channel"], None)
+ if handler:
+ if inspect.iscoroutinefunction(handler):
+ await handler(message)
+ else:
+ handler(message)
+ return None
+ elif message_type != "pong":
+ # this is a subscribe/unsubscribe message. ignore if we don't
+ # want them
+ if ignore_subscribe_messages or self.ignore_subscribe_messages:
+ return None
+
+ return message
+
+ async def run(
+ self,
+ *,
+ exception_handler: Optional["PSWorkerThreadExcHandlerT"] = None,
+ poll_timeout: float = 1.0,
+ ) -> None:
+ """Process pub/sub messages using registered callbacks.
+
+ This is the equivalent of :py:meth:`redis.PubSub.run_in_thread` in
+ redis-py, but it is a coroutine. To launch it as a separate task, use
+ ``asyncio.create_task``:
+
+ >>> task = asyncio.create_task(pubsub.run())
+
+ To shut it down, use asyncio cancellation:
+
+ >>> task.cancel()
+ >>> await task
+ """
+ for channel, handler in self.channels.items():
+ if handler is None:
+ raise PubSubError(f"Channel: '{channel}' has no handler registered")
+ for pattern, handler in self.patterns.items():
+ if handler is None:
+ raise PubSubError(f"Pattern: '{pattern}' has no handler registered")
+
+ await self.connect()
+ while True:
+ try:
+ await self.get_message(
+ ignore_subscribe_messages=True, timeout=poll_timeout
+ )
+ except asyncio.CancelledError:
+ raise
+ except BaseException as e:
+ if exception_handler is None:
+ raise
+ res = exception_handler(e, self)
+ if inspect.isawaitable(res):
+ await res
+ # Ensure that other tasks on the event loop get a chance to run
+ # if we didn't have to block for I/O anywhere.
+ await asyncio.sleep(0)
+
+
+class PubsubWorkerExceptionHandler(Protocol):
+ def __call__(self, e: BaseException, pubsub: PubSub): ...
+
+
+class AsyncPubsubWorkerExceptionHandler(Protocol):
+ async def __call__(self, e: BaseException, pubsub: PubSub): ...
+
+
+PSWorkerThreadExcHandlerT = Union[
+ PubsubWorkerExceptionHandler, AsyncPubsubWorkerExceptionHandler
+]
+
+
+CommandT = Tuple[Tuple[Union[str, bytes], ...], Mapping[str, Any]]
+CommandStackT = List[CommandT]
+
+
+class Pipeline(Redis): # lgtm [py/init-calls-subclass]
+ """
+ Pipelines provide a way to transmit multiple commands to the Redis server
+ in one transmission. This is convenient for batch processing, such as
+ saving all the values in a list to Redis.
+
+ All commands executed within a pipeline(when running in transactional mode,
+ which is the default behavior) are wrapped with MULTI and EXEC
+ calls. This guarantees all commands executed in the pipeline will be
+ executed atomically.
+
+ Any command raising an exception does *not* halt the execution of
+ subsequent commands in the pipeline. Instead, the exception is caught
+ and its instance is placed into the response list returned by execute().
+ Code iterating over the response list should be able to deal with an
+ instance of an exception as a potential value. In general, these will be
+ ResponseError exceptions, such as those raised when issuing a command
+ on a key of a different datatype.
+ """
+
+ UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
+
+ def __init__(
+ self,
+ connection_pool: ConnectionPool,
+ response_callbacks: MutableMapping[Union[str, bytes], ResponseCallbackT],
+ transaction: bool,
+ shard_hint: Optional[str],
+ ):
+ self.connection_pool = connection_pool
+ self.connection = None
+ self.response_callbacks = response_callbacks
+ self.is_transaction = transaction
+ self.shard_hint = shard_hint
+ self.watching = False
+ self.command_stack: CommandStackT = []
+ self.scripts: Set[Script] = set()
+ self.explicit_transaction = False
+
+ async def __aenter__(self: _RedisT) -> _RedisT:
+ return self
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.reset()
+
+ def __await__(self):
+ return self._async_self().__await__()
+
+ _DEL_MESSAGE = "Unclosed Pipeline client"
+
+ def __len__(self):
+ return len(self.command_stack)
+
+ def __bool__(self):
+ """Pipeline instances should always evaluate to True"""
+ return True
+
+ async def _async_self(self):
+ return self
+
+ async def reset(self):
+ self.command_stack = []
+ self.scripts = set()
+ # make sure to reset the connection state in the event that we were
+ # watching something
+ if self.watching and self.connection:
+ try:
+ # call this manually since our unwatch or
+ # immediate_execute_command methods can call reset()
+ await self.connection.send_command("UNWATCH")
+ await self.connection.read_response()
+ except ConnectionError:
+ # disconnect will also remove any previous WATCHes
+ if self.connection:
+ await self.connection.disconnect()
+ # clean up the other instance attributes
+ self.watching = False
+ self.explicit_transaction = False
+ # we can safely return the connection to the pool here since we're
+ # sure we're no longer WATCHing anything
+ if self.connection:
+ await self.connection_pool.release(self.connection)
+ self.connection = None
+
+ async def aclose(self) -> None:
+ """Alias for reset(), a standard method name for cleanup"""
+ await self.reset()
+
+ def multi(self):
+ """
+ Start a transactional block of the pipeline after WATCH commands
+ are issued. End the transactional block with `execute`.
+ """
+ if self.explicit_transaction:
+ raise RedisError("Cannot issue nested calls to MULTI")
+ if self.command_stack:
+ raise RedisError(
+ "Commands without an initial WATCH have already been issued"
+ )
+ self.explicit_transaction = True
+
+ def execute_command(
+ self, *args, **kwargs
+ ) -> Union["Pipeline", Awaitable["Pipeline"]]:
+ if (self.watching or args[0] == "WATCH") and not self.explicit_transaction:
+ return self.immediate_execute_command(*args, **kwargs)
+ return self.pipeline_execute_command(*args, **kwargs)
+
+ async def _disconnect_reset_raise_on_watching(
+ self,
+ conn: Connection,
+ error: Exception,
+ ):
+ """
+ Close the connection reset watching state and
+ raise an exception if we were watching.
+
+ The supported exceptions are already checked in the
+ retry object so we don't need to do it here.
+
+ After we disconnect the connection, it will try to reconnect and
+ do a health check as part of the send_command logic(on connection level).
+ """
+ await conn.disconnect()
+ # if we were already watching a variable, the watch is no longer
+ # valid since this connection has died. raise a WatchError, which
+ # indicates the user should retry this transaction.
+ if self.watching:
+ await self.reset()
+ raise WatchError(
+ f"A {type(error).__name__} occurred while watching one or more keys"
+ )
+
+ async def immediate_execute_command(self, *args, **options):
+ """
+ Execute a command immediately, but don't auto-retry on the supported
+ errors for retry if we're already WATCHing a variable.
+ Used when issuing WATCH or subsequent commands retrieving their values but before
+ MULTI is called.
+ """
+ command_name = args[0]
+ conn = self.connection
+ # if this is the first call, we need a connection
+ if not conn:
+ conn = await self.connection_pool.get_connection()
+ self.connection = conn
+
+ return await conn.retry.call_with_retry(
+ lambda: self._send_command_parse_response(
+ conn, command_name, *args, **options
+ ),
+ lambda error: self._disconnect_reset_raise_on_watching(conn, error),
+ )
+
+ def pipeline_execute_command(self, *args, **options):
+ """
+ Stage a command to be executed when execute() is next called
+
+ Returns the current Pipeline object back so commands can be
+ chained together, such as:
+
+ pipe = pipe.set('foo', 'bar').incr('baz').decr('bang')
+
+ At some other point, you can then run: pipe.execute(),
+ which will execute all commands queued in the pipe.
+ """
+ self.command_stack.append((args, options))
+ return self
+
+ async def _execute_transaction( # noqa: C901
+ self, connection: Connection, commands: CommandStackT, raise_on_error
+ ):
+ pre: CommandT = (("MULTI",), {})
+ post: CommandT = (("EXEC",), {})
+ cmds = (pre, *commands, post)
+ all_cmds = connection.pack_commands(
+ args for args, options in cmds if EMPTY_RESPONSE not in options
+ )
+ await connection.send_packed_command(all_cmds)
+ errors = []
+
+ # parse off the response for MULTI
+ # NOTE: we need to handle ResponseErrors here and continue
+ # so that we read all the additional command messages from
+ # the socket
+ try:
+ await self.parse_response(connection, "_")
+ except ResponseError as err:
+ errors.append((0, err))
+
+ # and all the other commands
+ for i, command in enumerate(commands):
+ if EMPTY_RESPONSE in command[1]:
+ errors.append((i, command[1][EMPTY_RESPONSE]))
+ else:
+ try:
+ await self.parse_response(connection, "_")
+ except ResponseError as err:
+ self.annotate_exception(err, i + 1, command[0])
+ errors.append((i, err))
+
+ # parse the EXEC.
+ try:
+ response = await self.parse_response(connection, "_")
+ except ExecAbortError as err:
+ if errors:
+ raise errors[0][1] from err
+ raise
+
+ # EXEC clears any watched keys
+ self.watching = False
+
+ if response is None:
+ raise WatchError("Watched variable changed.") from None
+
+ # put any parse errors into the response
+ for i, e in errors:
+ response.insert(i, e)
+
+ if len(response) != len(commands):
+ if self.connection:
+ await self.connection.disconnect()
+ raise ResponseError(
+ "Wrong number of response items from pipeline execution"
+ ) from None
+
+ # find any errors in the response and raise if necessary
+ if raise_on_error:
+ self.raise_first_error(commands, response)
+
+ # We have to run response callbacks manually
+ data = []
+ for r, cmd in zip(response, commands):
+ if not isinstance(r, Exception):
+ args, options = cmd
+ command_name = args[0]
+
+ # Remove keys entry, it needs only for cache.
+ options.pop("keys", None)
+
+ if command_name in self.response_callbacks:
+ r = self.response_callbacks[command_name](r, **options)
+ if inspect.isawaitable(r):
+ r = await r
+ data.append(r)
+ return data
+
+ async def _execute_pipeline(
+ self, connection: Connection, commands: CommandStackT, raise_on_error: bool
+ ):
+ # build up all commands into a single request to increase network perf
+ all_cmds = connection.pack_commands([args for args, _ in commands])
+ await connection.send_packed_command(all_cmds)
+
+ response = []
+ for args, options in commands:
+ try:
+ response.append(
+ await self.parse_response(connection, args[0], **options)
+ )
+ except ResponseError as e:
+ response.append(e)
+
+ if raise_on_error:
+ self.raise_first_error(commands, response)
+ return response
+
+ def raise_first_error(self, commands: CommandStackT, response: Iterable[Any]):
+ for i, r in enumerate(response):
+ if isinstance(r, ResponseError):
+ self.annotate_exception(r, i + 1, commands[i][0])
+ raise r
+
+ def annotate_exception(
+ self, exception: Exception, number: int, command: Iterable[object]
+ ) -> None:
+ cmd = " ".join(map(safe_str, command))
+ msg = (
+ f"Command # {number} ({truncate_text(cmd)}) "
+ "of pipeline caused error: {exception.args}"
+ )
+ exception.args = (msg,) + exception.args[1:]
+
+ async def parse_response(
+ self, connection: Connection, command_name: Union[str, bytes], **options
+ ):
+ result = await super().parse_response(connection, command_name, **options)
+ if command_name in self.UNWATCH_COMMANDS:
+ self.watching = False
+ elif command_name == "WATCH":
+ self.watching = True
+ return result
+
+ async def load_scripts(self):
+ # make sure all scripts that are about to be run on this pipeline exist
+ scripts = list(self.scripts)
+ immediate = self.immediate_execute_command
+ shas = [s.sha for s in scripts]
+ # we can't use the normal script_* methods because they would just
+ # get buffered in the pipeline.
+ exists = await immediate("SCRIPT EXISTS", *shas)
+ if not all(exists):
+ for s, exist in zip(scripts, exists):
+ if not exist:
+ s.sha = await immediate("SCRIPT LOAD", s.script)
+
+ async def _disconnect_raise_on_watching(self, conn: Connection, error: Exception):
+ """
+ Close the connection, raise an exception if we were watching.
+
+ The supported exceptions are already checked in the
+ retry object so we don't need to do it here.
+
+ After we disconnect the connection, it will try to reconnect and
+ do a health check as part of the send_command logic(on connection level).
+ """
+ await conn.disconnect()
+ # if we were watching a variable, the watch is no longer valid
+ # since this connection has died. raise a WatchError, which
+ # indicates the user should retry this transaction.
+ if self.watching:
+ raise WatchError(
+ f"A {type(error).__name__} occurred while watching one or more keys"
+ )
+
+ async def execute(self, raise_on_error: bool = True) -> List[Any]:
+ """Execute all the commands in the current pipeline"""
+ stack = self.command_stack
+ if not stack and not self.watching:
+ return []
+ if self.scripts:
+ await self.load_scripts()
+ if self.is_transaction or self.explicit_transaction:
+ execute = self._execute_transaction
+ else:
+ execute = self._execute_pipeline
+
+ conn = self.connection
+ if not conn:
+ conn = await self.connection_pool.get_connection()
+ # assign to self.connection so reset() releases the connection
+ # back to the pool after we're done
+ self.connection = conn
+ conn = cast(Connection, conn)
+
+ try:
+ return await conn.retry.call_with_retry(
+ lambda: execute(conn, stack, raise_on_error),
+ lambda error: self._disconnect_raise_on_watching(conn, error),
+ )
+ finally:
+ await self.reset()
+
+ async def discard(self):
+ """Flushes all previously queued commands
+ See: https://redis.io/commands/DISCARD
+ """
+ await self.execute_command("DISCARD")
+
+ async def watch(self, *names: KeyT):
+ """Watches the values at keys ``names``"""
+ if self.explicit_transaction:
+ raise RedisError("Cannot issue a WATCH after a MULTI")
+ return await self.execute_command("WATCH", *names)
+
+ async def unwatch(self):
+ """Unwatches all previously specified keys"""
+ return self.watching and await self.execute_command("UNWATCH") or True
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/cluster.py b/python_embeded/Lib/site-packages/redis/asyncio/cluster.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f34e03011fef3282ea36da9b2f75f4d90066c9c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/cluster.py
@@ -0,0 +1,2398 @@
+import asyncio
+import collections
+import random
+import socket
+import threading
+import time
+import warnings
+from abc import ABC, abstractmethod
+from copy import copy
+from itertools import chain
+from typing import (
+ Any,
+ Callable,
+ Coroutine,
+ Deque,
+ Dict,
+ Generator,
+ List,
+ Mapping,
+ Optional,
+ Set,
+ Tuple,
+ Type,
+ TypeVar,
+ Union,
+)
+
+from redis._parsers import AsyncCommandsParser, Encoder
+from redis._parsers.helpers import (
+ _RedisCallbacks,
+ _RedisCallbacksRESP2,
+ _RedisCallbacksRESP3,
+)
+from redis.asyncio.client import ResponseCallbackT
+from redis.asyncio.connection import Connection, SSLConnection, parse_url
+from redis.asyncio.lock import Lock
+from redis.asyncio.retry import Retry
+from redis.auth.token import TokenInterface
+from redis.backoff import ExponentialWithJitterBackoff, NoBackoff
+from redis.client import EMPTY_RESPONSE, NEVER_DECODE, AbstractRedis
+from redis.cluster import (
+ PIPELINE_BLOCKED_COMMANDS,
+ PRIMARY,
+ REPLICA,
+ SLOT_ID,
+ AbstractRedisCluster,
+ LoadBalancer,
+ LoadBalancingStrategy,
+ block_pipeline_command,
+ get_node_name,
+ parse_cluster_slots,
+)
+from redis.commands import READ_COMMANDS, AsyncRedisClusterCommands
+from redis.crc import REDIS_CLUSTER_HASH_SLOTS, key_slot
+from redis.credentials import CredentialProvider
+from redis.event import AfterAsyncClusterInstantiationEvent, EventDispatcher
+from redis.exceptions import (
+ AskError,
+ BusyLoadingError,
+ ClusterDownError,
+ ClusterError,
+ ConnectionError,
+ CrossSlotTransactionError,
+ DataError,
+ ExecAbortError,
+ InvalidPipelineStack,
+ MaxConnectionsError,
+ MovedError,
+ RedisClusterException,
+ RedisError,
+ ResponseError,
+ SlotNotCoveredError,
+ TimeoutError,
+ TryAgainError,
+ WatchError,
+)
+from redis.typing import AnyKeyT, EncodableT, KeyT
+from redis.utils import (
+ SSL_AVAILABLE,
+ deprecated_args,
+ deprecated_function,
+ get_lib_version,
+ safe_str,
+ str_if_bytes,
+ truncate_text,
+)
+
+if SSL_AVAILABLE:
+ from ssl import TLSVersion, VerifyMode
+else:
+ TLSVersion = None
+ VerifyMode = None
+
+TargetNodesT = TypeVar(
+ "TargetNodesT", str, "ClusterNode", List["ClusterNode"], Dict[Any, "ClusterNode"]
+)
+
+
+class RedisCluster(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands):
+ """
+ Create a new RedisCluster client.
+
+ Pass one of parameters:
+
+ - `host` & `port`
+ - `startup_nodes`
+
+ | Use ``await`` :meth:`initialize` to find cluster nodes & create connections.
+ | Use ``await`` :meth:`close` to disconnect connections & close client.
+
+ Many commands support the target_nodes kwarg. It can be one of the
+ :attr:`NODE_FLAGS`:
+
+ - :attr:`PRIMARIES`
+ - :attr:`REPLICAS`
+ - :attr:`ALL_NODES`
+ - :attr:`RANDOM`
+ - :attr:`DEFAULT_NODE`
+
+ Note: This client is not thread/process/fork safe.
+
+ :param host:
+ | Can be used to point to a startup node
+ :param port:
+ | Port used if **host** is provided
+ :param startup_nodes:
+ | :class:`~.ClusterNode` to used as a startup node
+ :param require_full_coverage:
+ | When set to ``False``: the client will not require a full coverage of
+ the slots. However, if not all slots are covered, and at least one node
+ has ``cluster-require-full-coverage`` set to ``yes``, the server will throw
+ a :class:`~.ClusterDownError` for some key-based commands.
+ | When set to ``True``: all slots must be covered to construct the cluster
+ client. If not all slots are covered, :class:`~.RedisClusterException` will be
+ thrown.
+ | See:
+ https://redis.io/docs/manual/scaling/#redis-cluster-configuration-parameters
+ :param read_from_replicas:
+ | @deprecated - please use load_balancing_strategy instead
+ | Enable read from replicas in READONLY mode.
+ When set to true, read commands will be assigned between the primary and
+ its replications in a Round-Robin manner.
+ The data read from replicas is eventually consistent with the data in primary nodes.
+ :param load_balancing_strategy:
+ | Enable read from replicas in READONLY mode and defines the load balancing
+ strategy that will be used for cluster node selection.
+ The data read from replicas is eventually consistent with the data in primary nodes.
+ :param dynamic_startup_nodes:
+ | Set the RedisCluster's startup nodes to all the discovered nodes.
+ If true (default value), the cluster's discovered nodes will be used to
+ determine the cluster nodes-slots mapping in the next topology refresh.
+ It will remove the initial passed startup nodes if their endpoints aren't
+ listed in the CLUSTER SLOTS output.
+ If you use dynamic DNS endpoints for startup nodes but CLUSTER SLOTS lists
+ specific IP addresses, it is best to set it to false.
+ :param reinitialize_steps:
+ | Specifies the number of MOVED errors that need to occur before reinitializing
+ the whole cluster topology. If a MOVED error occurs and the cluster does not
+ need to be reinitialized on this current error handling, only the MOVED slot
+ will be patched with the redirected node.
+ To reinitialize the cluster on every MOVED error, set reinitialize_steps to 1.
+ To avoid reinitializing the cluster on moved errors, set reinitialize_steps to
+ 0.
+ :param cluster_error_retry_attempts:
+ | @deprecated - Please configure the 'retry' object instead
+ In case 'retry' object is set - this argument is ignored!
+
+ Number of times to retry before raising an error when :class:`~.TimeoutError`,
+ :class:`~.ConnectionError`, :class:`~.SlotNotCoveredError`
+ or :class:`~.ClusterDownError` are encountered
+ :param retry:
+ | A retry object that defines the retry strategy and the number of
+ retries for the cluster client.
+ In current implementation for the cluster client (starting form redis-py version 6.0.0)
+ the retry object is not yet fully utilized, instead it is used just to determine
+ the number of retries for the cluster client.
+ In the future releases the retry object will be used to handle the cluster client retries!
+ :param max_connections:
+ | Maximum number of connections per node. If there are no free connections & the
+ maximum number of connections are already created, a
+ :class:`~.MaxConnectionsError` is raised.
+ :param address_remap:
+ | An optional callable which, when provided with an internal network
+ address of a node, e.g. a `(host, port)` tuple, will return the address
+ where the node is reachable. This can be used to map the addresses at
+ which the nodes _think_ they are, to addresses at which a client may
+ reach them, such as when they sit behind a proxy.
+
+ | Rest of the arguments will be passed to the
+ :class:`~redis.asyncio.connection.Connection` instances when created
+
+ :raises RedisClusterException:
+ if any arguments are invalid or unknown. Eg:
+
+ - `db` != 0 or None
+ - `path` argument for unix socket connection
+ - none of the `host`/`port` & `startup_nodes` were provided
+
+ """
+
+ @classmethod
+ def from_url(cls, url: str, **kwargs: Any) -> "RedisCluster":
+ """
+ Return a Redis client object configured from the given URL.
+
+ For example::
+
+ redis://[[username]:[password]]@localhost:6379/0
+ rediss://[[username]:[password]]@localhost:6379/0
+
+ Three URL schemes are supported:
+
+ - `redis://` creates a TCP socket connection. See more at:
+
+ - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
+
+
+ The username, password, hostname, path and all querystring values are passed
+ through ``urllib.parse.unquote`` in order to replace any percent-encoded values
+ with their corresponding characters.
+
+ All querystring options are cast to their appropriate Python types. Boolean
+ arguments can be specified with string values "True"/"False" or "Yes"/"No".
+ Values that cannot be properly cast cause a ``ValueError`` to be raised. Once
+ parsed, the querystring arguments and keyword arguments are passed to
+ :class:`~redis.asyncio.connection.Connection` when created.
+ In the case of conflicting arguments, querystring arguments are used.
+ """
+ kwargs.update(parse_url(url))
+ if kwargs.pop("connection_class", None) is SSLConnection:
+ kwargs["ssl"] = True
+ return cls(**kwargs)
+
+ __slots__ = (
+ "_initialize",
+ "_lock",
+ "retry",
+ "command_flags",
+ "commands_parser",
+ "connection_kwargs",
+ "encoder",
+ "node_flags",
+ "nodes_manager",
+ "read_from_replicas",
+ "reinitialize_counter",
+ "reinitialize_steps",
+ "response_callbacks",
+ "result_callbacks",
+ )
+
+ @deprecated_args(
+ args_to_warn=["read_from_replicas"],
+ reason="Please configure the 'load_balancing_strategy' instead",
+ version="5.3.0",
+ )
+ @deprecated_args(
+ args_to_warn=[
+ "cluster_error_retry_attempts",
+ ],
+ reason="Please configure the 'retry' object instead",
+ version="6.0.0",
+ )
+ def __init__(
+ self,
+ host: Optional[str] = None,
+ port: Union[str, int] = 6379,
+ # Cluster related kwargs
+ startup_nodes: Optional[List["ClusterNode"]] = None,
+ require_full_coverage: bool = True,
+ read_from_replicas: bool = False,
+ load_balancing_strategy: Optional[LoadBalancingStrategy] = None,
+ dynamic_startup_nodes: bool = True,
+ reinitialize_steps: int = 5,
+ cluster_error_retry_attempts: int = 3,
+ max_connections: int = 2**31,
+ retry: Optional["Retry"] = None,
+ retry_on_error: Optional[List[Type[Exception]]] = None,
+ # Client related kwargs
+ db: Union[str, int] = 0,
+ path: Optional[str] = None,
+ credential_provider: Optional[CredentialProvider] = None,
+ username: Optional[str] = None,
+ password: Optional[str] = None,
+ client_name: Optional[str] = None,
+ lib_name: Optional[str] = "redis-py",
+ lib_version: Optional[str] = get_lib_version(),
+ # Encoding related kwargs
+ encoding: str = "utf-8",
+ encoding_errors: str = "strict",
+ decode_responses: bool = False,
+ # Connection related kwargs
+ health_check_interval: float = 0,
+ socket_connect_timeout: Optional[float] = None,
+ socket_keepalive: bool = False,
+ socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
+ socket_timeout: Optional[float] = None,
+ # SSL related kwargs
+ ssl: bool = False,
+ ssl_ca_certs: Optional[str] = None,
+ ssl_ca_data: Optional[str] = None,
+ ssl_cert_reqs: Union[str, VerifyMode] = "required",
+ ssl_certfile: Optional[str] = None,
+ ssl_check_hostname: bool = True,
+ ssl_keyfile: Optional[str] = None,
+ ssl_min_version: Optional[TLSVersion] = None,
+ ssl_ciphers: Optional[str] = None,
+ protocol: Optional[int] = 2,
+ address_remap: Optional[Callable[[Tuple[str, int]], Tuple[str, int]]] = None,
+ event_dispatcher: Optional[EventDispatcher] = None,
+ ) -> None:
+ if db:
+ raise RedisClusterException(
+ "Argument 'db' must be 0 or None in cluster mode"
+ )
+
+ if path:
+ raise RedisClusterException(
+ "Unix domain socket is not supported in cluster mode"
+ )
+
+ if (not host or not port) and not startup_nodes:
+ raise RedisClusterException(
+ "RedisCluster requires at least one node to discover the cluster.\n"
+ "Please provide one of the following or use RedisCluster.from_url:\n"
+ ' - host and port: RedisCluster(host="localhost", port=6379)\n'
+ " - startup_nodes: RedisCluster(startup_nodes=["
+ 'ClusterNode("localhost", 6379), ClusterNode("localhost", 6380)])'
+ )
+
+ kwargs: Dict[str, Any] = {
+ "max_connections": max_connections,
+ "connection_class": Connection,
+ # Client related kwargs
+ "credential_provider": credential_provider,
+ "username": username,
+ "password": password,
+ "client_name": client_name,
+ "lib_name": lib_name,
+ "lib_version": lib_version,
+ # Encoding related kwargs
+ "encoding": encoding,
+ "encoding_errors": encoding_errors,
+ "decode_responses": decode_responses,
+ # Connection related kwargs
+ "health_check_interval": health_check_interval,
+ "socket_connect_timeout": socket_connect_timeout,
+ "socket_keepalive": socket_keepalive,
+ "socket_keepalive_options": socket_keepalive_options,
+ "socket_timeout": socket_timeout,
+ "protocol": protocol,
+ }
+
+ if ssl:
+ # SSL related kwargs
+ kwargs.update(
+ {
+ "connection_class": SSLConnection,
+ "ssl_ca_certs": ssl_ca_certs,
+ "ssl_ca_data": ssl_ca_data,
+ "ssl_cert_reqs": ssl_cert_reqs,
+ "ssl_certfile": ssl_certfile,
+ "ssl_check_hostname": ssl_check_hostname,
+ "ssl_keyfile": ssl_keyfile,
+ "ssl_min_version": ssl_min_version,
+ "ssl_ciphers": ssl_ciphers,
+ }
+ )
+
+ if read_from_replicas or load_balancing_strategy:
+ # Call our on_connect function to configure READONLY mode
+ kwargs["redis_connect_func"] = self.on_connect
+
+ if retry:
+ self.retry = retry
+ else:
+ self.retry = Retry(
+ backoff=ExponentialWithJitterBackoff(base=1, cap=10),
+ retries=cluster_error_retry_attempts,
+ )
+ if retry_on_error:
+ self.retry.update_supported_errors(retry_on_error)
+
+ kwargs["response_callbacks"] = _RedisCallbacks.copy()
+ if kwargs.get("protocol") in ["3", 3]:
+ kwargs["response_callbacks"].update(_RedisCallbacksRESP3)
+ else:
+ kwargs["response_callbacks"].update(_RedisCallbacksRESP2)
+ self.connection_kwargs = kwargs
+
+ if startup_nodes:
+ passed_nodes = []
+ for node in startup_nodes:
+ passed_nodes.append(
+ ClusterNode(node.host, node.port, **self.connection_kwargs)
+ )
+ startup_nodes = passed_nodes
+ else:
+ startup_nodes = []
+ if host and port:
+ startup_nodes.append(ClusterNode(host, port, **self.connection_kwargs))
+
+ if event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+ else:
+ self._event_dispatcher = event_dispatcher
+
+ self.nodes_manager = NodesManager(
+ startup_nodes,
+ require_full_coverage,
+ kwargs,
+ dynamic_startup_nodes=dynamic_startup_nodes,
+ address_remap=address_remap,
+ event_dispatcher=self._event_dispatcher,
+ )
+ self.encoder = Encoder(encoding, encoding_errors, decode_responses)
+ self.read_from_replicas = read_from_replicas
+ self.load_balancing_strategy = load_balancing_strategy
+ self.reinitialize_steps = reinitialize_steps
+ self.reinitialize_counter = 0
+ self.commands_parser = AsyncCommandsParser()
+ self.node_flags = self.__class__.NODE_FLAGS.copy()
+ self.command_flags = self.__class__.COMMAND_FLAGS.copy()
+ self.response_callbacks = kwargs["response_callbacks"]
+ self.result_callbacks = self.__class__.RESULT_CALLBACKS.copy()
+ self.result_callbacks["CLUSTER SLOTS"] = (
+ lambda cmd, res, **kwargs: parse_cluster_slots(
+ list(res.values())[0], **kwargs
+ )
+ )
+
+ self._initialize = True
+ self._lock: Optional[asyncio.Lock] = None
+
+ async def initialize(self) -> "RedisCluster":
+ """Get all nodes from startup nodes & creates connections if not initialized."""
+ if self._initialize:
+ if not self._lock:
+ self._lock = asyncio.Lock()
+ async with self._lock:
+ if self._initialize:
+ try:
+ await self.nodes_manager.initialize()
+ await self.commands_parser.initialize(
+ self.nodes_manager.default_node
+ )
+ self._initialize = False
+ except BaseException:
+ await self.nodes_manager.aclose()
+ await self.nodes_manager.aclose("startup_nodes")
+ raise
+ return self
+
+ async def aclose(self) -> None:
+ """Close all connections & client if initialized."""
+ if not self._initialize:
+ if not self._lock:
+ self._lock = asyncio.Lock()
+ async with self._lock:
+ if not self._initialize:
+ self._initialize = True
+ await self.nodes_manager.aclose()
+ await self.nodes_manager.aclose("startup_nodes")
+
+ @deprecated_function(version="5.0.0", reason="Use aclose() instead", name="close")
+ async def close(self) -> None:
+ """alias for aclose() for backwards compatibility"""
+ await self.aclose()
+
+ async def __aenter__(self) -> "RedisCluster":
+ return await self.initialize()
+
+ async def __aexit__(self, exc_type: None, exc_value: None, traceback: None) -> None:
+ await self.aclose()
+
+ def __await__(self) -> Generator[Any, None, "RedisCluster"]:
+ return self.initialize().__await__()
+
+ _DEL_MESSAGE = "Unclosed RedisCluster client"
+
+ def __del__(
+ self,
+ _warn: Any = warnings.warn,
+ _grl: Any = asyncio.get_running_loop,
+ ) -> None:
+ if hasattr(self, "_initialize") and not self._initialize:
+ _warn(f"{self._DEL_MESSAGE} {self!r}", ResourceWarning, source=self)
+ try:
+ context = {"client": self, "message": self._DEL_MESSAGE}
+ _grl().call_exception_handler(context)
+ except RuntimeError:
+ pass
+
+ async def on_connect(self, connection: Connection) -> None:
+ await connection.on_connect()
+
+ # Sending READONLY command to server to configure connection as
+ # readonly. Since each cluster node may change its server type due
+ # to a failover, we should establish a READONLY connection
+ # regardless of the server type. If this is a primary connection,
+ # READONLY would not affect executing write commands.
+ await connection.send_command("READONLY")
+ if str_if_bytes(await connection.read_response()) != "OK":
+ raise ConnectionError("READONLY command failed")
+
+ def get_nodes(self) -> List["ClusterNode"]:
+ """Get all nodes of the cluster."""
+ return list(self.nodes_manager.nodes_cache.values())
+
+ def get_primaries(self) -> List["ClusterNode"]:
+ """Get the primary nodes of the cluster."""
+ return self.nodes_manager.get_nodes_by_server_type(PRIMARY)
+
+ def get_replicas(self) -> List["ClusterNode"]:
+ """Get the replica nodes of the cluster."""
+ return self.nodes_manager.get_nodes_by_server_type(REPLICA)
+
+ def get_random_node(self) -> "ClusterNode":
+ """Get a random node of the cluster."""
+ return random.choice(list(self.nodes_manager.nodes_cache.values()))
+
+ def get_default_node(self) -> "ClusterNode":
+ """Get the default node of the client."""
+ return self.nodes_manager.default_node
+
+ def set_default_node(self, node: "ClusterNode") -> None:
+ """
+ Set the default node of the client.
+
+ :raises DataError: if None is passed or node does not exist in cluster.
+ """
+ if not node or not self.get_node(node_name=node.name):
+ raise DataError("The requested node does not exist in the cluster.")
+
+ self.nodes_manager.default_node = node
+
+ def get_node(
+ self,
+ host: Optional[str] = None,
+ port: Optional[int] = None,
+ node_name: Optional[str] = None,
+ ) -> Optional["ClusterNode"]:
+ """Get node by (host, port) or node_name."""
+ return self.nodes_manager.get_node(host, port, node_name)
+
+ def get_node_from_key(
+ self, key: str, replica: bool = False
+ ) -> Optional["ClusterNode"]:
+ """
+ Get the cluster node corresponding to the provided key.
+
+ :param key:
+ :param replica:
+ | Indicates if a replica should be returned
+ |
+ None will returned if no replica holds this key
+
+ :raises SlotNotCoveredError: if the key is not covered by any slot.
+ """
+ slot = self.keyslot(key)
+ slot_cache = self.nodes_manager.slots_cache.get(slot)
+ if not slot_cache:
+ raise SlotNotCoveredError(f'Slot "{slot}" is not covered by the cluster.')
+
+ if replica:
+ if len(self.nodes_manager.slots_cache[slot]) < 2:
+ return None
+ node_idx = 1
+ else:
+ node_idx = 0
+
+ return slot_cache[node_idx]
+
+ def keyslot(self, key: EncodableT) -> int:
+ """
+ Find the keyslot for a given key.
+
+ See: https://redis.io/docs/manual/scaling/#redis-cluster-data-sharding
+ """
+ return key_slot(self.encoder.encode(key))
+
+ def get_encoder(self) -> Encoder:
+ """Get the encoder object of the client."""
+ return self.encoder
+
+ def get_connection_kwargs(self) -> Dict[str, Optional[Any]]:
+ """Get the kwargs passed to :class:`~redis.asyncio.connection.Connection`."""
+ return self.connection_kwargs
+
+ def set_retry(self, retry: Retry) -> None:
+ self.retry = retry
+
+ def set_response_callback(self, command: str, callback: ResponseCallbackT) -> None:
+ """Set a custom response callback."""
+ self.response_callbacks[command] = callback
+
+ async def _determine_nodes(
+ self, command: str, *args: Any, node_flag: Optional[str] = None
+ ) -> List["ClusterNode"]:
+ # Determine which nodes should be executed the command on.
+ # Returns a list of target nodes.
+ if not node_flag:
+ # get the nodes group for this command if it was predefined
+ node_flag = self.command_flags.get(command)
+
+ if node_flag in self.node_flags:
+ if node_flag == self.__class__.DEFAULT_NODE:
+ # return the cluster's default node
+ return [self.nodes_manager.default_node]
+ if node_flag == self.__class__.PRIMARIES:
+ # return all primaries
+ return self.nodes_manager.get_nodes_by_server_type(PRIMARY)
+ if node_flag == self.__class__.REPLICAS:
+ # return all replicas
+ return self.nodes_manager.get_nodes_by_server_type(REPLICA)
+ if node_flag == self.__class__.ALL_NODES:
+ # return all nodes
+ return list(self.nodes_manager.nodes_cache.values())
+ if node_flag == self.__class__.RANDOM:
+ # return a random node
+ return [random.choice(list(self.nodes_manager.nodes_cache.values()))]
+
+ # get the node that holds the key's slot
+ return [
+ self.nodes_manager.get_node_from_slot(
+ await self._determine_slot(command, *args),
+ self.read_from_replicas and command in READ_COMMANDS,
+ self.load_balancing_strategy if command in READ_COMMANDS else None,
+ )
+ ]
+
+ async def _determine_slot(self, command: str, *args: Any) -> int:
+ if self.command_flags.get(command) == SLOT_ID:
+ # The command contains the slot ID
+ return int(args[0])
+
+ # Get the keys in the command
+
+ # EVAL and EVALSHA are common enough that it's wasteful to go to the
+ # redis server to parse the keys. Besides, there is a bug in redis<7.0
+ # where `self._get_command_keys()` fails anyway. So, we special case
+ # EVAL/EVALSHA.
+ # - issue: https://github.com/redis/redis/issues/9493
+ # - fix: https://github.com/redis/redis/pull/9733
+ if command.upper() in ("EVAL", "EVALSHA"):
+ # command syntax: EVAL "script body" num_keys ...
+ if len(args) < 2:
+ raise RedisClusterException(
+ f"Invalid args in command: {command, *args}"
+ )
+ keys = args[2 : 2 + int(args[1])]
+ # if there are 0 keys, that means the script can be run on any node
+ # so we can just return a random slot
+ if not keys:
+ return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
+ else:
+ keys = await self.commands_parser.get_keys(command, *args)
+ if not keys:
+ # FCALL can call a function with 0 keys, that means the function
+ # can be run on any node so we can just return a random slot
+ if command.upper() in ("FCALL", "FCALL_RO"):
+ return random.randrange(0, REDIS_CLUSTER_HASH_SLOTS)
+ raise RedisClusterException(
+ "No way to dispatch this command to Redis Cluster. "
+ "Missing key.\nYou can execute the command by specifying "
+ f"target nodes.\nCommand: {args}"
+ )
+
+ # single key command
+ if len(keys) == 1:
+ return self.keyslot(keys[0])
+
+ # multi-key command; we need to make sure all keys are mapped to
+ # the same slot
+ slots = {self.keyslot(key) for key in keys}
+ if len(slots) != 1:
+ raise RedisClusterException(
+ f"{command} - all keys must map to the same key slot"
+ )
+
+ return slots.pop()
+
+ def _is_node_flag(self, target_nodes: Any) -> bool:
+ return isinstance(target_nodes, str) and target_nodes in self.node_flags
+
+ def _parse_target_nodes(self, target_nodes: Any) -> List["ClusterNode"]:
+ if isinstance(target_nodes, list):
+ nodes = target_nodes
+ elif isinstance(target_nodes, ClusterNode):
+ # Supports passing a single ClusterNode as a variable
+ nodes = [target_nodes]
+ elif isinstance(target_nodes, dict):
+ # Supports dictionaries of the format {node_name: node}.
+ # It enables to execute commands with multi nodes as follows:
+ # rc.cluster_save_config(rc.get_primaries())
+ nodes = list(target_nodes.values())
+ else:
+ raise TypeError(
+ "target_nodes type can be one of the following: "
+ "node_flag (PRIMARIES, REPLICAS, RANDOM, ALL_NODES),"
+ "ClusterNode, list, or dict. "
+ f"The passed type is {type(target_nodes)}"
+ )
+ return nodes
+
+ async def execute_command(self, *args: EncodableT, **kwargs: Any) -> Any:
+ """
+ Execute a raw command on the appropriate cluster node or target_nodes.
+
+ It will retry the command as specified by the retries property of
+ the :attr:`retry` & then raise an exception.
+
+ :param args:
+ | Raw command args
+ :param kwargs:
+
+ - target_nodes: :attr:`NODE_FLAGS` or :class:`~.ClusterNode`
+ or List[:class:`~.ClusterNode`] or Dict[Any, :class:`~.ClusterNode`]
+ - Rest of the kwargs are passed to the Redis connection
+
+ :raises RedisClusterException: if target_nodes is not provided & the command
+ can't be mapped to a slot
+ """
+ command = args[0]
+ target_nodes = []
+ target_nodes_specified = False
+ retry_attempts = self.retry.get_retries()
+
+ passed_targets = kwargs.pop("target_nodes", None)
+ if passed_targets and not self._is_node_flag(passed_targets):
+ target_nodes = self._parse_target_nodes(passed_targets)
+ target_nodes_specified = True
+ retry_attempts = 0
+
+ # Add one for the first execution
+ execute_attempts = 1 + retry_attempts
+ for _ in range(execute_attempts):
+ if self._initialize:
+ await self.initialize()
+ if (
+ len(target_nodes) == 1
+ and target_nodes[0] == self.get_default_node()
+ ):
+ # Replace the default cluster node
+ self.replace_default_node()
+ try:
+ if not target_nodes_specified:
+ # Determine the nodes to execute the command on
+ target_nodes = await self._determine_nodes(
+ *args, node_flag=passed_targets
+ )
+ if not target_nodes:
+ raise RedisClusterException(
+ f"No targets were found to execute {args} command on"
+ )
+
+ if len(target_nodes) == 1:
+ # Return the processed result
+ ret = await self._execute_command(target_nodes[0], *args, **kwargs)
+ if command in self.result_callbacks:
+ return self.result_callbacks[command](
+ command, {target_nodes[0].name: ret}, **kwargs
+ )
+ return ret
+ else:
+ keys = [node.name for node in target_nodes]
+ values = await asyncio.gather(
+ *(
+ asyncio.create_task(
+ self._execute_command(node, *args, **kwargs)
+ )
+ for node in target_nodes
+ )
+ )
+ if command in self.result_callbacks:
+ return self.result_callbacks[command](
+ command, dict(zip(keys, values)), **kwargs
+ )
+ return dict(zip(keys, values))
+ except Exception as e:
+ if retry_attempts > 0 and type(e) in self.__class__.ERRORS_ALLOW_RETRY:
+ # The nodes and slots cache were should be reinitialized.
+ # Try again with the new cluster setup.
+ retry_attempts -= 1
+ continue
+ else:
+ # raise the exception
+ raise e
+
+ async def _execute_command(
+ self, target_node: "ClusterNode", *args: Union[KeyT, EncodableT], **kwargs: Any
+ ) -> Any:
+ asking = moved = False
+ redirect_addr = None
+ ttl = self.RedisClusterRequestTTL
+
+ while ttl > 0:
+ ttl -= 1
+ try:
+ if asking:
+ target_node = self.get_node(node_name=redirect_addr)
+ await target_node.execute_command("ASKING")
+ asking = False
+ elif moved:
+ # MOVED occurred and the slots cache was updated,
+ # refresh the target node
+ slot = await self._determine_slot(*args)
+ target_node = self.nodes_manager.get_node_from_slot(
+ slot,
+ self.read_from_replicas and args[0] in READ_COMMANDS,
+ self.load_balancing_strategy
+ if args[0] in READ_COMMANDS
+ else None,
+ )
+ moved = False
+
+ return await target_node.execute_command(*args, **kwargs)
+ except (BusyLoadingError, MaxConnectionsError):
+ raise
+ except (ConnectionError, TimeoutError):
+ # Connection retries are being handled in the node's
+ # Retry object.
+ # Remove the failed node from the startup nodes before we try
+ # to reinitialize the cluster
+ self.nodes_manager.startup_nodes.pop(target_node.name, None)
+ # Hard force of reinitialize of the node/slots setup
+ # and try again with the new setup
+ await self.aclose()
+ raise
+ except (ClusterDownError, SlotNotCoveredError):
+ # ClusterDownError can occur during a failover and to get
+ # self-healed, we will try to reinitialize the cluster layout
+ # and retry executing the command
+
+ # SlotNotCoveredError can occur when the cluster is not fully
+ # initialized or can be temporary issue.
+ # We will try to reinitialize the cluster topology
+ # and retry executing the command
+
+ await self.aclose()
+ await asyncio.sleep(0.25)
+ raise
+ except MovedError as e:
+ # First, we will try to patch the slots/nodes cache with the
+ # redirected node output and try again. If MovedError exceeds
+ # 'reinitialize_steps' number of times, we will force
+ # reinitializing the tables, and then try again.
+ # 'reinitialize_steps' counter will increase faster when
+ # the same client object is shared between multiple threads. To
+ # reduce the frequency you can set this variable in the
+ # RedisCluster constructor.
+ self.reinitialize_counter += 1
+ if (
+ self.reinitialize_steps
+ and self.reinitialize_counter % self.reinitialize_steps == 0
+ ):
+ await self.aclose()
+ # Reset the counter
+ self.reinitialize_counter = 0
+ else:
+ self.nodes_manager._moved_exception = e
+ moved = True
+ except AskError as e:
+ redirect_addr = get_node_name(host=e.host, port=e.port)
+ asking = True
+ except TryAgainError:
+ if ttl < self.RedisClusterRequestTTL / 2:
+ await asyncio.sleep(0.05)
+
+ raise ClusterError("TTL exhausted.")
+
+ def pipeline(
+ self, transaction: Optional[Any] = None, shard_hint: Optional[Any] = None
+ ) -> "ClusterPipeline":
+ """
+ Create & return a new :class:`~.ClusterPipeline` object.
+
+ Cluster implementation of pipeline does not support transaction or shard_hint.
+
+ :raises RedisClusterException: if transaction or shard_hint are truthy values
+ """
+ if shard_hint:
+ raise RedisClusterException("shard_hint is deprecated in cluster mode")
+
+ return ClusterPipeline(self, transaction)
+
+ def lock(
+ self,
+ name: KeyT,
+ timeout: Optional[float] = None,
+ sleep: float = 0.1,
+ blocking: bool = True,
+ blocking_timeout: Optional[float] = None,
+ lock_class: Optional[Type[Lock]] = None,
+ thread_local: bool = True,
+ raise_on_release_error: bool = True,
+ ) -> Lock:
+ """
+ Return a new Lock object using key ``name`` that mimics
+ the behavior of threading.Lock.
+
+ If specified, ``timeout`` indicates a maximum life for the lock.
+ By default, it will remain locked until release() is called.
+
+ ``sleep`` indicates the amount of time to sleep per loop iteration
+ when the lock is in blocking mode and another client is currently
+ holding the lock.
+
+ ``blocking`` indicates whether calling ``acquire`` should block until
+ the lock has been acquired or to fail immediately, causing ``acquire``
+ to return False and the lock not being acquired. Defaults to True.
+ Note this value can be overridden by passing a ``blocking``
+ argument to ``acquire``.
+
+ ``blocking_timeout`` indicates the maximum amount of time in seconds to
+ spend trying to acquire the lock. A value of ``None`` indicates
+ continue trying forever. ``blocking_timeout`` can be specified as a
+ float or integer, both representing the number of seconds to wait.
+
+ ``lock_class`` forces the specified lock implementation. Note that as
+ of redis-py 3.0, the only lock class we implement is ``Lock`` (which is
+ a Lua-based lock). So, it's unlikely you'll need this parameter, unless
+ you have created your own custom lock class.
+
+ ``thread_local`` indicates whether the lock token is placed in
+ thread-local storage. By default, the token is placed in thread local
+ storage so that a thread only sees its token, not a token set by
+ another thread. Consider the following timeline:
+
+ time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
+ thread-1 sets the token to "abc"
+ time: 1, thread-2 blocks trying to acquire `my-lock` using the
+ Lock instance.
+ time: 5, thread-1 has not yet completed. redis expires the lock
+ key.
+ time: 5, thread-2 acquired `my-lock` now that it's available.
+ thread-2 sets the token to "xyz"
+ time: 6, thread-1 finishes its work and calls release(). if the
+ token is *not* stored in thread local storage, then
+ thread-1 would see the token value as "xyz" and would be
+ able to successfully release the thread-2's lock.
+
+ ``raise_on_release_error`` indicates whether to raise an exception when
+ the lock is no longer owned when exiting the context manager. By default,
+ this is True, meaning an exception will be raised. If False, the warning
+ will be logged and the exception will be suppressed.
+
+ In some use cases it's necessary to disable thread local storage. For
+ example, if you have code where one thread acquires a lock and passes
+ that lock instance to a worker thread to release later. If thread
+ local storage isn't disabled in this case, the worker thread won't see
+ the token set by the thread that acquired the lock. Our assumption
+ is that these cases aren't common and as such default to using
+ thread local storage."""
+ if lock_class is None:
+ lock_class = Lock
+ return lock_class(
+ self,
+ name,
+ timeout=timeout,
+ sleep=sleep,
+ blocking=blocking,
+ blocking_timeout=blocking_timeout,
+ thread_local=thread_local,
+ raise_on_release_error=raise_on_release_error,
+ )
+
+ async def transaction(
+ self, func: Coroutine[None, "ClusterPipeline", Any], *watches, **kwargs
+ ):
+ """
+ Convenience method for executing the callable `func` as a transaction
+ while watching all keys specified in `watches`. The 'func' callable
+ should expect a single argument which is a Pipeline object.
+ """
+ shard_hint = kwargs.pop("shard_hint", None)
+ value_from_callable = kwargs.pop("value_from_callable", False)
+ watch_delay = kwargs.pop("watch_delay", None)
+ async with self.pipeline(True, shard_hint) as pipe:
+ while True:
+ try:
+ if watches:
+ await pipe.watch(*watches)
+ func_value = await func(pipe)
+ exec_value = await pipe.execute()
+ return func_value if value_from_callable else exec_value
+ except WatchError:
+ if watch_delay is not None and watch_delay > 0:
+ time.sleep(watch_delay)
+ continue
+
+
+class ClusterNode:
+ """
+ Create a new ClusterNode.
+
+ Each ClusterNode manages multiple :class:`~redis.asyncio.connection.Connection`
+ objects for the (host, port).
+ """
+
+ __slots__ = (
+ "_connections",
+ "_free",
+ "_lock",
+ "_event_dispatcher",
+ "connection_class",
+ "connection_kwargs",
+ "host",
+ "max_connections",
+ "name",
+ "port",
+ "response_callbacks",
+ "server_type",
+ )
+
+ def __init__(
+ self,
+ host: str,
+ port: Union[str, int],
+ server_type: Optional[str] = None,
+ *,
+ max_connections: int = 2**31,
+ connection_class: Type[Connection] = Connection,
+ **connection_kwargs: Any,
+ ) -> None:
+ if host == "localhost":
+ host = socket.gethostbyname(host)
+
+ connection_kwargs["host"] = host
+ connection_kwargs["port"] = port
+ self.host = host
+ self.port = port
+ self.name = get_node_name(host, port)
+ self.server_type = server_type
+
+ self.max_connections = max_connections
+ self.connection_class = connection_class
+ self.connection_kwargs = connection_kwargs
+ self.response_callbacks = connection_kwargs.pop("response_callbacks", {})
+
+ self._connections: List[Connection] = []
+ self._free: Deque[Connection] = collections.deque(maxlen=self.max_connections)
+ self._event_dispatcher = self.connection_kwargs.get("event_dispatcher", None)
+ if self._event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+
+ def __repr__(self) -> str:
+ return (
+ f"[host={self.host}, port={self.port}, "
+ f"name={self.name}, server_type={self.server_type}]"
+ )
+
+ def __eq__(self, obj: Any) -> bool:
+ return isinstance(obj, ClusterNode) and obj.name == self.name
+
+ _DEL_MESSAGE = "Unclosed ClusterNode object"
+
+ def __del__(
+ self,
+ _warn: Any = warnings.warn,
+ _grl: Any = asyncio.get_running_loop,
+ ) -> None:
+ for connection in self._connections:
+ if connection.is_connected:
+ _warn(f"{self._DEL_MESSAGE} {self!r}", ResourceWarning, source=self)
+
+ try:
+ context = {"client": self, "message": self._DEL_MESSAGE}
+ _grl().call_exception_handler(context)
+ except RuntimeError:
+ pass
+ break
+
+ async def disconnect(self) -> None:
+ ret = await asyncio.gather(
+ *(
+ asyncio.create_task(connection.disconnect())
+ for connection in self._connections
+ ),
+ return_exceptions=True,
+ )
+ exc = next((res for res in ret if isinstance(res, Exception)), None)
+ if exc:
+ raise exc
+
+ def acquire_connection(self) -> Connection:
+ try:
+ return self._free.popleft()
+ except IndexError:
+ if len(self._connections) < self.max_connections:
+ # We are configuring the connection pool not to retry
+ # connections on lower level clients to avoid retrying
+ # connections to nodes that are not reachable
+ # and to avoid blocking the connection pool.
+ # The only error that will have some handling in the lower
+ # level clients is ConnectionError which will trigger disconnection
+ # of the socket.
+ # The retries will be handled on cluster client level
+ # where we will have proper handling of the cluster topology
+ retry = Retry(
+ backoff=NoBackoff(),
+ retries=0,
+ supported_errors=(ConnectionError,),
+ )
+ connection_kwargs = self.connection_kwargs.copy()
+ connection_kwargs["retry"] = retry
+ connection = self.connection_class(**connection_kwargs)
+ self._connections.append(connection)
+ return connection
+
+ raise MaxConnectionsError()
+
+ def release(self, connection: Connection) -> None:
+ """
+ Release connection back to free queue.
+ """
+ self._free.append(connection)
+
+ async def parse_response(
+ self, connection: Connection, command: str, **kwargs: Any
+ ) -> Any:
+ try:
+ if NEVER_DECODE in kwargs:
+ response = await connection.read_response(disable_decoding=True)
+ kwargs.pop(NEVER_DECODE)
+ else:
+ response = await connection.read_response()
+ except ResponseError:
+ if EMPTY_RESPONSE in kwargs:
+ return kwargs[EMPTY_RESPONSE]
+ raise
+
+ if EMPTY_RESPONSE in kwargs:
+ kwargs.pop(EMPTY_RESPONSE)
+
+ # Remove keys entry, it needs only for cache.
+ kwargs.pop("keys", None)
+
+ # Return response
+ if command in self.response_callbacks:
+ return self.response_callbacks[command](response, **kwargs)
+
+ return response
+
+ async def execute_command(self, *args: Any, **kwargs: Any) -> Any:
+ # Acquire connection
+ connection = self.acquire_connection()
+
+ # Execute command
+ await connection.send_packed_command(connection.pack_command(*args), False)
+
+ # Read response
+ try:
+ return await self.parse_response(connection, args[0], **kwargs)
+ finally:
+ # Release connection
+ self._free.append(connection)
+
+ async def execute_pipeline(self, commands: List["PipelineCommand"]) -> bool:
+ # Acquire connection
+ connection = self.acquire_connection()
+
+ # Execute command
+ await connection.send_packed_command(
+ connection.pack_commands(cmd.args for cmd in commands), False
+ )
+
+ # Read responses
+ ret = False
+ for cmd in commands:
+ try:
+ cmd.result = await self.parse_response(
+ connection, cmd.args[0], **cmd.kwargs
+ )
+ except Exception as e:
+ cmd.result = e
+ ret = True
+
+ # Release connection
+ self._free.append(connection)
+
+ return ret
+
+ async def re_auth_callback(self, token: TokenInterface):
+ tmp_queue = collections.deque()
+ while self._free:
+ conn = self._free.popleft()
+ await conn.retry.call_with_retry(
+ lambda: conn.send_command(
+ "AUTH", token.try_get("oid"), token.get_value()
+ ),
+ lambda error: self._mock(error),
+ )
+ await conn.retry.call_with_retry(
+ lambda: conn.read_response(), lambda error: self._mock(error)
+ )
+ tmp_queue.append(conn)
+
+ while tmp_queue:
+ conn = tmp_queue.popleft()
+ self._free.append(conn)
+
+ async def _mock(self, error: RedisError):
+ """
+ Dummy functions, needs to be passed as error callback to retry object.
+ :param error:
+ :return:
+ """
+ pass
+
+
+class NodesManager:
+ __slots__ = (
+ "_dynamic_startup_nodes",
+ "_moved_exception",
+ "_event_dispatcher",
+ "connection_kwargs",
+ "default_node",
+ "nodes_cache",
+ "read_load_balancer",
+ "require_full_coverage",
+ "slots_cache",
+ "startup_nodes",
+ "address_remap",
+ )
+
+ def __init__(
+ self,
+ startup_nodes: List["ClusterNode"],
+ require_full_coverage: bool,
+ connection_kwargs: Dict[str, Any],
+ dynamic_startup_nodes: bool = True,
+ address_remap: Optional[Callable[[Tuple[str, int]], Tuple[str, int]]] = None,
+ event_dispatcher: Optional[EventDispatcher] = None,
+ ) -> None:
+ self.startup_nodes = {node.name: node for node in startup_nodes}
+ self.require_full_coverage = require_full_coverage
+ self.connection_kwargs = connection_kwargs
+ self.address_remap = address_remap
+
+ self.default_node: "ClusterNode" = None
+ self.nodes_cache: Dict[str, "ClusterNode"] = {}
+ self.slots_cache: Dict[int, List["ClusterNode"]] = {}
+ self.read_load_balancer = LoadBalancer()
+
+ self._dynamic_startup_nodes: bool = dynamic_startup_nodes
+ self._moved_exception: MovedError = None
+ if event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+ else:
+ self._event_dispatcher = event_dispatcher
+
+ def get_node(
+ self,
+ host: Optional[str] = None,
+ port: Optional[int] = None,
+ node_name: Optional[str] = None,
+ ) -> Optional["ClusterNode"]:
+ if host and port:
+ # the user passed host and port
+ if host == "localhost":
+ host = socket.gethostbyname(host)
+ return self.nodes_cache.get(get_node_name(host=host, port=port))
+ elif node_name:
+ return self.nodes_cache.get(node_name)
+ else:
+ raise DataError(
+ "get_node requires one of the following: 1. node name 2. host and port"
+ )
+
+ def set_nodes(
+ self,
+ old: Dict[str, "ClusterNode"],
+ new: Dict[str, "ClusterNode"],
+ remove_old: bool = False,
+ ) -> None:
+ if remove_old:
+ for name in list(old.keys()):
+ if name not in new:
+ task = asyncio.create_task(old.pop(name).disconnect()) # noqa
+
+ for name, node in new.items():
+ if name in old:
+ if old[name] is node:
+ continue
+ task = asyncio.create_task(old[name].disconnect()) # noqa
+ old[name] = node
+
+ def update_moved_exception(self, exception):
+ self._moved_exception = exception
+
+ def _update_moved_slots(self) -> None:
+ e = self._moved_exception
+ redirected_node = self.get_node(host=e.host, port=e.port)
+ if redirected_node:
+ # The node already exists
+ if redirected_node.server_type != PRIMARY:
+ # Update the node's server type
+ redirected_node.server_type = PRIMARY
+ else:
+ # This is a new node, we will add it to the nodes cache
+ redirected_node = ClusterNode(
+ e.host, e.port, PRIMARY, **self.connection_kwargs
+ )
+ self.set_nodes(self.nodes_cache, {redirected_node.name: redirected_node})
+ if redirected_node in self.slots_cache[e.slot_id]:
+ # The MOVED error resulted from a failover, and the new slot owner
+ # had previously been a replica.
+ old_primary = self.slots_cache[e.slot_id][0]
+ # Update the old primary to be a replica and add it to the end of
+ # the slot's node list
+ old_primary.server_type = REPLICA
+ self.slots_cache[e.slot_id].append(old_primary)
+ # Remove the old replica, which is now a primary, from the slot's
+ # node list
+ self.slots_cache[e.slot_id].remove(redirected_node)
+ # Override the old primary with the new one
+ self.slots_cache[e.slot_id][0] = redirected_node
+ if self.default_node == old_primary:
+ # Update the default node with the new primary
+ self.default_node = redirected_node
+ else:
+ # The new slot owner is a new server, or a server from a different
+ # shard. We need to remove all current nodes from the slot's list
+ # (including replications) and add just the new node.
+ self.slots_cache[e.slot_id] = [redirected_node]
+ # Reset moved_exception
+ self._moved_exception = None
+
+ def get_node_from_slot(
+ self,
+ slot: int,
+ read_from_replicas: bool = False,
+ load_balancing_strategy=None,
+ ) -> "ClusterNode":
+ if self._moved_exception:
+ self._update_moved_slots()
+
+ if read_from_replicas is True and load_balancing_strategy is None:
+ load_balancing_strategy = LoadBalancingStrategy.ROUND_ROBIN
+
+ try:
+ if len(self.slots_cache[slot]) > 1 and load_balancing_strategy:
+ # get the server index using the strategy defined in load_balancing_strategy
+ primary_name = self.slots_cache[slot][0].name
+ node_idx = self.read_load_balancer.get_server_index(
+ primary_name, len(self.slots_cache[slot]), load_balancing_strategy
+ )
+ return self.slots_cache[slot][node_idx]
+ return self.slots_cache[slot][0]
+ except (IndexError, TypeError):
+ raise SlotNotCoveredError(
+ f'Slot "{slot}" not covered by the cluster. '
+ f'"require_full_coverage={self.require_full_coverage}"'
+ )
+
+ def get_nodes_by_server_type(self, server_type: str) -> List["ClusterNode"]:
+ return [
+ node
+ for node in self.nodes_cache.values()
+ if node.server_type == server_type
+ ]
+
+ async def initialize(self) -> None:
+ self.read_load_balancer.reset()
+ tmp_nodes_cache: Dict[str, "ClusterNode"] = {}
+ tmp_slots: Dict[int, List["ClusterNode"]] = {}
+ disagreements = []
+ startup_nodes_reachable = False
+ fully_covered = False
+ exception = None
+ # Convert to tuple to prevent RuntimeError if self.startup_nodes
+ # is modified during iteration
+ for startup_node in tuple(self.startup_nodes.values()):
+ try:
+ # Make sure cluster mode is enabled on this node
+ try:
+ self._event_dispatcher.dispatch(
+ AfterAsyncClusterInstantiationEvent(
+ self.nodes_cache,
+ self.connection_kwargs.get("credential_provider", None),
+ )
+ )
+ cluster_slots = await startup_node.execute_command("CLUSTER SLOTS")
+ except ResponseError:
+ raise RedisClusterException(
+ "Cluster mode is not enabled on this node"
+ )
+ startup_nodes_reachable = True
+ except Exception as e:
+ # Try the next startup node.
+ # The exception is saved and raised only if we have no more nodes.
+ exception = e
+ continue
+
+ # CLUSTER SLOTS command results in the following output:
+ # [[slot_section[from_slot,to_slot,master,replica1,...,replicaN]]]
+ # where each node contains the following list: [IP, port, node_id]
+ # Therefore, cluster_slots[0][2][0] will be the IP address of the
+ # primary node of the first slot section.
+ # If there's only one server in the cluster, its ``host`` is ''
+ # Fix it to the host in startup_nodes
+ if (
+ len(cluster_slots) == 1
+ and not cluster_slots[0][2][0]
+ and len(self.startup_nodes) == 1
+ ):
+ cluster_slots[0][2][0] = startup_node.host
+
+ for slot in cluster_slots:
+ for i in range(2, len(slot)):
+ slot[i] = [str_if_bytes(val) for val in slot[i]]
+ primary_node = slot[2]
+ host = primary_node[0]
+ if host == "":
+ host = startup_node.host
+ port = int(primary_node[1])
+ host, port = self.remap_host_port(host, port)
+
+ nodes_for_slot = []
+
+ target_node = tmp_nodes_cache.get(get_node_name(host, port))
+ if not target_node:
+ target_node = ClusterNode(
+ host, port, PRIMARY, **self.connection_kwargs
+ )
+ # add this node to the nodes cache
+ tmp_nodes_cache[target_node.name] = target_node
+ nodes_for_slot.append(target_node)
+
+ replica_nodes = slot[3:]
+ for replica_node in replica_nodes:
+ host = replica_node[0]
+ port = replica_node[1]
+ host, port = self.remap_host_port(host, port)
+
+ target_replica_node = tmp_nodes_cache.get(get_node_name(host, port))
+ if not target_replica_node:
+ target_replica_node = ClusterNode(
+ host, port, REPLICA, **self.connection_kwargs
+ )
+ # add this node to the nodes cache
+ tmp_nodes_cache[target_replica_node.name] = target_replica_node
+ nodes_for_slot.append(target_replica_node)
+
+ for i in range(int(slot[0]), int(slot[1]) + 1):
+ if i not in tmp_slots:
+ tmp_slots[i] = nodes_for_slot
+ else:
+ # Validate that 2 nodes want to use the same slot cache
+ # setup
+ tmp_slot = tmp_slots[i][0]
+ if tmp_slot.name != target_node.name:
+ disagreements.append(
+ f"{tmp_slot.name} vs {target_node.name} on slot: {i}"
+ )
+
+ if len(disagreements) > 5:
+ raise RedisClusterException(
+ f"startup_nodes could not agree on a valid "
+ f"slots cache: {', '.join(disagreements)}"
+ )
+
+ # Validate if all slots are covered or if we should try next startup node
+ fully_covered = True
+ for i in range(REDIS_CLUSTER_HASH_SLOTS):
+ if i not in tmp_slots:
+ fully_covered = False
+ break
+ if fully_covered:
+ break
+
+ if not startup_nodes_reachable:
+ raise RedisClusterException(
+ f"Redis Cluster cannot be connected. Please provide at least "
+ f"one reachable node: {str(exception)}"
+ ) from exception
+
+ # Check if the slots are not fully covered
+ if not fully_covered and self.require_full_coverage:
+ # Despite the requirement that the slots be covered, there
+ # isn't a full coverage
+ raise RedisClusterException(
+ f"All slots are not covered after query all startup_nodes. "
+ f"{len(tmp_slots)} of {REDIS_CLUSTER_HASH_SLOTS} "
+ f"covered..."
+ )
+
+ # Set the tmp variables to the real variables
+ self.slots_cache = tmp_slots
+ self.set_nodes(self.nodes_cache, tmp_nodes_cache, remove_old=True)
+
+ if self._dynamic_startup_nodes:
+ # Populate the startup nodes with all discovered nodes
+ self.set_nodes(self.startup_nodes, self.nodes_cache, remove_old=True)
+
+ # Set the default node
+ self.default_node = self.get_nodes_by_server_type(PRIMARY)[0]
+ # If initialize was called after a MovedError, clear it
+ self._moved_exception = None
+
+ async def aclose(self, attr: str = "nodes_cache") -> None:
+ self.default_node = None
+ await asyncio.gather(
+ *(
+ asyncio.create_task(node.disconnect())
+ for node in getattr(self, attr).values()
+ )
+ )
+
+ def remap_host_port(self, host: str, port: int) -> Tuple[str, int]:
+ """
+ Remap the host and port returned from the cluster to a different
+ internal value. Useful if the client is not connecting directly
+ to the cluster.
+ """
+ if self.address_remap:
+ return self.address_remap((host, port))
+ return host, port
+
+
+class ClusterPipeline(AbstractRedis, AbstractRedisCluster, AsyncRedisClusterCommands):
+ """
+ Create a new ClusterPipeline object.
+
+ Usage::
+
+ result = await (
+ rc.pipeline()
+ .set("A", 1)
+ .get("A")
+ .hset("K", "F", "V")
+ .hgetall("K")
+ .mset_nonatomic({"A": 2, "B": 3})
+ .get("A")
+ .get("B")
+ .delete("A", "B", "K")
+ .execute()
+ )
+ # result = [True, "1", 1, {"F": "V"}, True, True, "2", "3", 1, 1, 1]
+
+ Note: For commands `DELETE`, `EXISTS`, `TOUCH`, `UNLINK`, `mset_nonatomic`, which
+ are split across multiple nodes, you'll get multiple results for them in the array.
+
+ Retryable errors:
+ - :class:`~.ClusterDownError`
+ - :class:`~.ConnectionError`
+ - :class:`~.TimeoutError`
+
+ Redirection errors:
+ - :class:`~.TryAgainError`
+ - :class:`~.MovedError`
+ - :class:`~.AskError`
+
+ :param client:
+ | Existing :class:`~.RedisCluster` client
+ """
+
+ __slots__ = ("cluster_client", "_transaction", "_execution_strategy")
+
+ def __init__(
+ self, client: RedisCluster, transaction: Optional[bool] = None
+ ) -> None:
+ self.cluster_client = client
+ self._transaction = transaction
+ self._execution_strategy: ExecutionStrategy = (
+ PipelineStrategy(self)
+ if not self._transaction
+ else TransactionStrategy(self)
+ )
+
+ async def initialize(self) -> "ClusterPipeline":
+ await self._execution_strategy.initialize()
+ return self
+
+ async def __aenter__(self) -> "ClusterPipeline":
+ return await self.initialize()
+
+ async def __aexit__(self, exc_type: None, exc_value: None, traceback: None) -> None:
+ await self.reset()
+
+ def __await__(self) -> Generator[Any, None, "ClusterPipeline"]:
+ return self.initialize().__await__()
+
+ def __enter__(self) -> "ClusterPipeline":
+ # TODO: Remove this method before 7.0.0
+ self._execution_strategy._command_queue = []
+ return self
+
+ def __exit__(self, exc_type: None, exc_value: None, traceback: None) -> None:
+ # TODO: Remove this method before 7.0.0
+ self._execution_strategy._command_queue = []
+
+ def __bool__(self) -> bool:
+ "Pipeline instances should always evaluate to True on Python 3+"
+ return True
+
+ def __len__(self) -> int:
+ return len(self._execution_strategy)
+
+ def execute_command(
+ self, *args: Union[KeyT, EncodableT], **kwargs: Any
+ ) -> "ClusterPipeline":
+ """
+ Append a raw command to the pipeline.
+
+ :param args:
+ | Raw command args
+ :param kwargs:
+
+ - target_nodes: :attr:`NODE_FLAGS` or :class:`~.ClusterNode`
+ or List[:class:`~.ClusterNode`] or Dict[Any, :class:`~.ClusterNode`]
+ - Rest of the kwargs are passed to the Redis connection
+ """
+ return self._execution_strategy.execute_command(*args, **kwargs)
+
+ async def execute(
+ self, raise_on_error: bool = True, allow_redirections: bool = True
+ ) -> List[Any]:
+ """
+ Execute the pipeline.
+
+ It will retry the commands as specified by retries specified in :attr:`retry`
+ & then raise an exception.
+
+ :param raise_on_error:
+ | Raise the first error if there are any errors
+ :param allow_redirections:
+ | Whether to retry each failed command individually in case of redirection
+ errors
+
+ :raises RedisClusterException: if target_nodes is not provided & the command
+ can't be mapped to a slot
+ """
+ try:
+ return await self._execution_strategy.execute(
+ raise_on_error, allow_redirections
+ )
+ finally:
+ await self.reset()
+
+ def _split_command_across_slots(
+ self, command: str, *keys: KeyT
+ ) -> "ClusterPipeline":
+ for slot_keys in self.cluster_client._partition_keys_by_slot(keys).values():
+ self.execute_command(command, *slot_keys)
+
+ return self
+
+ async def reset(self):
+ """
+ Reset back to empty pipeline.
+ """
+ await self._execution_strategy.reset()
+
+ def multi(self):
+ """
+ Start a transactional block of the pipeline after WATCH commands
+ are issued. End the transactional block with `execute`.
+ """
+ self._execution_strategy.multi()
+
+ async def discard(self):
+ """ """
+ await self._execution_strategy.discard()
+
+ async def watch(self, *names):
+ """Watches the values at keys ``names``"""
+ await self._execution_strategy.watch(*names)
+
+ async def unwatch(self):
+ """Unwatches all previously specified keys"""
+ await self._execution_strategy.unwatch()
+
+ async def unlink(self, *names):
+ await self._execution_strategy.unlink(*names)
+
+ def mset_nonatomic(
+ self, mapping: Mapping[AnyKeyT, EncodableT]
+ ) -> "ClusterPipeline":
+ return self._execution_strategy.mset_nonatomic(mapping)
+
+
+for command in PIPELINE_BLOCKED_COMMANDS:
+ command = command.replace(" ", "_").lower()
+ if command == "mset_nonatomic":
+ continue
+
+ setattr(ClusterPipeline, command, block_pipeline_command(command))
+
+
+class PipelineCommand:
+ def __init__(self, position: int, *args: Any, **kwargs: Any) -> None:
+ self.args = args
+ self.kwargs = kwargs
+ self.position = position
+ self.result: Union[Any, Exception] = None
+
+ def __repr__(self) -> str:
+ return f"[{self.position}] {self.args} ({self.kwargs})"
+
+
+class ExecutionStrategy(ABC):
+ @abstractmethod
+ async def initialize(self) -> "ClusterPipeline":
+ """
+ Initialize the execution strategy.
+
+ See ClusterPipeline.initialize()
+ """
+ pass
+
+ @abstractmethod
+ def execute_command(
+ self, *args: Union[KeyT, EncodableT], **kwargs: Any
+ ) -> "ClusterPipeline":
+ """
+ Append a raw command to the pipeline.
+
+ See ClusterPipeline.execute_command()
+ """
+ pass
+
+ @abstractmethod
+ async def execute(
+ self, raise_on_error: bool = True, allow_redirections: bool = True
+ ) -> List[Any]:
+ """
+ Execute the pipeline.
+
+ It will retry the commands as specified by retries specified in :attr:`retry`
+ & then raise an exception.
+
+ See ClusterPipeline.execute()
+ """
+ pass
+
+ @abstractmethod
+ def mset_nonatomic(
+ self, mapping: Mapping[AnyKeyT, EncodableT]
+ ) -> "ClusterPipeline":
+ """
+ Executes multiple MSET commands according to the provided slot/pairs mapping.
+
+ See ClusterPipeline.mset_nonatomic()
+ """
+ pass
+
+ @abstractmethod
+ async def reset(self):
+ """
+ Resets current execution strategy.
+
+ See: ClusterPipeline.reset()
+ """
+ pass
+
+ @abstractmethod
+ def multi(self):
+ """
+ Starts transactional context.
+
+ See: ClusterPipeline.multi()
+ """
+ pass
+
+ @abstractmethod
+ async def watch(self, *names):
+ """
+ Watch given keys.
+
+ See: ClusterPipeline.watch()
+ """
+ pass
+
+ @abstractmethod
+ async def unwatch(self):
+ """
+ Unwatches all previously specified keys
+
+ See: ClusterPipeline.unwatch()
+ """
+ pass
+
+ @abstractmethod
+ async def discard(self):
+ pass
+
+ @abstractmethod
+ async def unlink(self, *names):
+ """
+ "Unlink a key specified by ``names``"
+
+ See: ClusterPipeline.unlink()
+ """
+ pass
+
+ @abstractmethod
+ def __len__(self) -> int:
+ pass
+
+
+class AbstractStrategy(ExecutionStrategy):
+ def __init__(self, pipe: ClusterPipeline) -> None:
+ self._pipe: ClusterPipeline = pipe
+ self._command_queue: List["PipelineCommand"] = []
+
+ async def initialize(self) -> "ClusterPipeline":
+ if self._pipe.cluster_client._initialize:
+ await self._pipe.cluster_client.initialize()
+ self._command_queue = []
+ return self._pipe
+
+ def execute_command(
+ self, *args: Union[KeyT, EncodableT], **kwargs: Any
+ ) -> "ClusterPipeline":
+ self._command_queue.append(
+ PipelineCommand(len(self._command_queue), *args, **kwargs)
+ )
+ return self._pipe
+
+ def _annotate_exception(self, exception, number, command):
+ """
+ Provides extra context to the exception prior to it being handled
+ """
+ cmd = " ".join(map(safe_str, command))
+ msg = (
+ f"Command # {number} ({truncate_text(cmd)}) of pipeline "
+ f"caused error: {exception.args[0]}"
+ )
+ exception.args = (msg,) + exception.args[1:]
+
+ @abstractmethod
+ def mset_nonatomic(
+ self, mapping: Mapping[AnyKeyT, EncodableT]
+ ) -> "ClusterPipeline":
+ pass
+
+ @abstractmethod
+ async def execute(
+ self, raise_on_error: bool = True, allow_redirections: bool = True
+ ) -> List[Any]:
+ pass
+
+ @abstractmethod
+ async def reset(self):
+ pass
+
+ @abstractmethod
+ def multi(self):
+ pass
+
+ @abstractmethod
+ async def watch(self, *names):
+ pass
+
+ @abstractmethod
+ async def unwatch(self):
+ pass
+
+ @abstractmethod
+ async def discard(self):
+ pass
+
+ @abstractmethod
+ async def unlink(self, *names):
+ pass
+
+ def __len__(self) -> int:
+ return len(self._command_queue)
+
+
+class PipelineStrategy(AbstractStrategy):
+ def __init__(self, pipe: ClusterPipeline) -> None:
+ super().__init__(pipe)
+
+ def mset_nonatomic(
+ self, mapping: Mapping[AnyKeyT, EncodableT]
+ ) -> "ClusterPipeline":
+ encoder = self._pipe.cluster_client.encoder
+
+ slots_pairs = {}
+ for pair in mapping.items():
+ slot = key_slot(encoder.encode(pair[0]))
+ slots_pairs.setdefault(slot, []).extend(pair)
+
+ for pairs in slots_pairs.values():
+ self.execute_command("MSET", *pairs)
+
+ return self._pipe
+
+ async def execute(
+ self, raise_on_error: bool = True, allow_redirections: bool = True
+ ) -> List[Any]:
+ if not self._command_queue:
+ return []
+
+ try:
+ retry_attempts = self._pipe.cluster_client.retry.get_retries()
+ while True:
+ try:
+ if self._pipe.cluster_client._initialize:
+ await self._pipe.cluster_client.initialize()
+ return await self._execute(
+ self._pipe.cluster_client,
+ self._command_queue,
+ raise_on_error=raise_on_error,
+ allow_redirections=allow_redirections,
+ )
+
+ except RedisCluster.ERRORS_ALLOW_RETRY as e:
+ if retry_attempts > 0:
+ # Try again with the new cluster setup. All other errors
+ # should be raised.
+ retry_attempts -= 1
+ await self._pipe.cluster_client.aclose()
+ await asyncio.sleep(0.25)
+ else:
+ # All other errors should be raised.
+ raise e
+ finally:
+ await self.reset()
+
+ async def _execute(
+ self,
+ client: "RedisCluster",
+ stack: List["PipelineCommand"],
+ raise_on_error: bool = True,
+ allow_redirections: bool = True,
+ ) -> List[Any]:
+ todo = [
+ cmd for cmd in stack if not cmd.result or isinstance(cmd.result, Exception)
+ ]
+
+ nodes = {}
+ for cmd in todo:
+ passed_targets = cmd.kwargs.pop("target_nodes", None)
+ if passed_targets and not client._is_node_flag(passed_targets):
+ target_nodes = client._parse_target_nodes(passed_targets)
+ else:
+ target_nodes = await client._determine_nodes(
+ *cmd.args, node_flag=passed_targets
+ )
+ if not target_nodes:
+ raise RedisClusterException(
+ f"No targets were found to execute {cmd.args} command on"
+ )
+ if len(target_nodes) > 1:
+ raise RedisClusterException(f"Too many targets for command {cmd.args}")
+ node = target_nodes[0]
+ if node.name not in nodes:
+ nodes[node.name] = (node, [])
+ nodes[node.name][1].append(cmd)
+
+ errors = await asyncio.gather(
+ *(
+ asyncio.create_task(node[0].execute_pipeline(node[1]))
+ for node in nodes.values()
+ )
+ )
+
+ if any(errors):
+ if allow_redirections:
+ # send each errored command individually
+ for cmd in todo:
+ if isinstance(cmd.result, (TryAgainError, MovedError, AskError)):
+ try:
+ cmd.result = await client.execute_command(
+ *cmd.args, **cmd.kwargs
+ )
+ except Exception as e:
+ cmd.result = e
+
+ if raise_on_error:
+ for cmd in todo:
+ result = cmd.result
+ if isinstance(result, Exception):
+ command = " ".join(map(safe_str, cmd.args))
+ msg = (
+ f"Command # {cmd.position + 1} "
+ f"({truncate_text(command)}) "
+ f"of pipeline caused error: {result.args}"
+ )
+ result.args = (msg,) + result.args[1:]
+ raise result
+
+ default_cluster_node = client.get_default_node()
+
+ # Check whether the default node was used. In some cases,
+ # 'client.get_default_node()' may return None. The check below
+ # prevents a potential AttributeError.
+ if default_cluster_node is not None:
+ default_node = nodes.get(default_cluster_node.name)
+ if default_node is not None:
+ # This pipeline execution used the default node, check if we need
+ # to replace it.
+ # Note: when the error is raised we'll reset the default node in the
+ # caller function.
+ for cmd in default_node[1]:
+ # Check if it has a command that failed with a relevant
+ # exception
+ if type(cmd.result) in RedisCluster.ERRORS_ALLOW_RETRY:
+ client.replace_default_node()
+ break
+
+ return [cmd.result for cmd in stack]
+
+ async def reset(self):
+ """
+ Reset back to empty pipeline.
+ """
+ self._command_queue = []
+
+ def multi(self):
+ raise RedisClusterException(
+ "method multi() is not supported outside of transactional context"
+ )
+
+ async def watch(self, *names):
+ raise RedisClusterException(
+ "method watch() is not supported outside of transactional context"
+ )
+
+ async def unwatch(self):
+ raise RedisClusterException(
+ "method unwatch() is not supported outside of transactional context"
+ )
+
+ async def discard(self):
+ raise RedisClusterException(
+ "method discard() is not supported outside of transactional context"
+ )
+
+ async def unlink(self, *names):
+ if len(names) != 1:
+ raise RedisClusterException(
+ "unlinking multiple keys is not implemented in pipeline command"
+ )
+
+ return self.execute_command("UNLINK", names[0])
+
+
+class TransactionStrategy(AbstractStrategy):
+ NO_SLOTS_COMMANDS = {"UNWATCH"}
+ IMMEDIATE_EXECUTE_COMMANDS = {"WATCH", "UNWATCH"}
+ UNWATCH_COMMANDS = {"DISCARD", "EXEC", "UNWATCH"}
+ SLOT_REDIRECT_ERRORS = (AskError, MovedError)
+ CONNECTION_ERRORS = (
+ ConnectionError,
+ OSError,
+ ClusterDownError,
+ SlotNotCoveredError,
+ )
+
+ def __init__(self, pipe: ClusterPipeline) -> None:
+ super().__init__(pipe)
+ self._explicit_transaction = False
+ self._watching = False
+ self._pipeline_slots: Set[int] = set()
+ self._transaction_node: Optional[ClusterNode] = None
+ self._transaction_connection: Optional[Connection] = None
+ self._executing = False
+ self._retry = copy(self._pipe.cluster_client.retry)
+ self._retry.update_supported_errors(
+ RedisCluster.ERRORS_ALLOW_RETRY + self.SLOT_REDIRECT_ERRORS
+ )
+
+ def _get_client_and_connection_for_transaction(
+ self,
+ ) -> Tuple[ClusterNode, Connection]:
+ """
+ Find a connection for a pipeline transaction.
+
+ For running an atomic transaction, watch keys ensure that contents have not been
+ altered as long as the watch commands for those keys were sent over the same
+ connection. So once we start watching a key, we fetch a connection to the
+ node that owns that slot and reuse it.
+ """
+ if not self._pipeline_slots:
+ raise RedisClusterException(
+ "At least a command with a key is needed to identify a node"
+ )
+
+ node: ClusterNode = self._pipe.cluster_client.nodes_manager.get_node_from_slot(
+ list(self._pipeline_slots)[0], False
+ )
+ self._transaction_node = node
+
+ if not self._transaction_connection:
+ connection: Connection = self._transaction_node.acquire_connection()
+ self._transaction_connection = connection
+
+ return self._transaction_node, self._transaction_connection
+
+ def execute_command(self, *args: Union[KeyT, EncodableT], **kwargs: Any) -> "Any":
+ # Given the limitation of ClusterPipeline sync API, we have to run it in thread.
+ response = None
+ error = None
+
+ def runner():
+ nonlocal response
+ nonlocal error
+ try:
+ response = asyncio.run(self._execute_command(*args, **kwargs))
+ except Exception as e:
+ error = e
+
+ thread = threading.Thread(target=runner)
+ thread.start()
+ thread.join()
+
+ if error:
+ raise error
+
+ return response
+
+ async def _execute_command(
+ self, *args: Union[KeyT, EncodableT], **kwargs: Any
+ ) -> Any:
+ if self._pipe.cluster_client._initialize:
+ await self._pipe.cluster_client.initialize()
+
+ slot_number: Optional[int] = None
+ if args[0] not in self.NO_SLOTS_COMMANDS:
+ slot_number = await self._pipe.cluster_client._determine_slot(*args)
+
+ if (
+ self._watching or args[0] in self.IMMEDIATE_EXECUTE_COMMANDS
+ ) and not self._explicit_transaction:
+ if args[0] == "WATCH":
+ self._validate_watch()
+
+ if slot_number is not None:
+ if self._pipeline_slots and slot_number not in self._pipeline_slots:
+ raise CrossSlotTransactionError(
+ "Cannot watch or send commands on different slots"
+ )
+
+ self._pipeline_slots.add(slot_number)
+ elif args[0] not in self.NO_SLOTS_COMMANDS:
+ raise RedisClusterException(
+ f"Cannot identify slot number for command: {args[0]},"
+ "it cannot be triggered in a transaction"
+ )
+
+ return self._immediate_execute_command(*args, **kwargs)
+ else:
+ if slot_number is not None:
+ self._pipeline_slots.add(slot_number)
+
+ return super().execute_command(*args, **kwargs)
+
+ def _validate_watch(self):
+ if self._explicit_transaction:
+ raise RedisError("Cannot issue a WATCH after a MULTI")
+
+ self._watching = True
+
+ async def _immediate_execute_command(self, *args, **options):
+ return await self._retry.call_with_retry(
+ lambda: self._get_connection_and_send_command(*args, **options),
+ self._reinitialize_on_error,
+ )
+
+ async def _get_connection_and_send_command(self, *args, **options):
+ redis_node, connection = self._get_client_and_connection_for_transaction()
+ return await self._send_command_parse_response(
+ connection, redis_node, args[0], *args, **options
+ )
+
+ async def _send_command_parse_response(
+ self,
+ connection: Connection,
+ redis_node: ClusterNode,
+ command_name,
+ *args,
+ **options,
+ ):
+ """
+ Send a command and parse the response
+ """
+
+ await connection.send_command(*args)
+ output = await redis_node.parse_response(connection, command_name, **options)
+
+ if command_name in self.UNWATCH_COMMANDS:
+ self._watching = False
+ return output
+
+ async def _reinitialize_on_error(self, error):
+ if self._watching:
+ if type(error) in self.SLOT_REDIRECT_ERRORS and self._executing:
+ raise WatchError("Slot rebalancing occurred while watching keys")
+
+ if (
+ type(error) in self.SLOT_REDIRECT_ERRORS
+ or type(error) in self.CONNECTION_ERRORS
+ ):
+ if self._transaction_connection:
+ self._transaction_connection = None
+
+ self._pipe.cluster_client.reinitialize_counter += 1
+ if (
+ self._pipe.cluster_client.reinitialize_steps
+ and self._pipe.cluster_client.reinitialize_counter
+ % self._pipe.cluster_client.reinitialize_steps
+ == 0
+ ):
+ await self._pipe.cluster_client.nodes_manager.initialize()
+ self.reinitialize_counter = 0
+ else:
+ self._pipe.cluster_client.nodes_manager.update_moved_exception(error)
+
+ self._executing = False
+
+ def _raise_first_error(self, responses, stack):
+ """
+ Raise the first exception on the stack
+ """
+ for r, cmd in zip(responses, stack):
+ if isinstance(r, Exception):
+ self._annotate_exception(r, cmd.position + 1, cmd.args)
+ raise r
+
+ def mset_nonatomic(
+ self, mapping: Mapping[AnyKeyT, EncodableT]
+ ) -> "ClusterPipeline":
+ raise NotImplementedError("Method is not supported in transactional context.")
+
+ async def execute(
+ self, raise_on_error: bool = True, allow_redirections: bool = True
+ ) -> List[Any]:
+ stack = self._command_queue
+ if not stack and (not self._watching or not self._pipeline_slots):
+ return []
+
+ return await self._execute_transaction_with_retries(stack, raise_on_error)
+
+ async def _execute_transaction_with_retries(
+ self, stack: List["PipelineCommand"], raise_on_error: bool
+ ):
+ return await self._retry.call_with_retry(
+ lambda: self._execute_transaction(stack, raise_on_error),
+ self._reinitialize_on_error,
+ )
+
+ async def _execute_transaction(
+ self, stack: List["PipelineCommand"], raise_on_error: bool
+ ):
+ if len(self._pipeline_slots) > 1:
+ raise CrossSlotTransactionError(
+ "All keys involved in a cluster transaction must map to the same slot"
+ )
+
+ self._executing = True
+
+ redis_node, connection = self._get_client_and_connection_for_transaction()
+
+ stack = chain(
+ [PipelineCommand(0, "MULTI")],
+ stack,
+ [PipelineCommand(0, "EXEC")],
+ )
+ commands = [c.args for c in stack if EMPTY_RESPONSE not in c.kwargs]
+ packed_commands = connection.pack_commands(commands)
+ await connection.send_packed_command(packed_commands)
+ errors = []
+
+ # parse off the response for MULTI
+ # NOTE: we need to handle ResponseErrors here and continue
+ # so that we read all the additional command messages from
+ # the socket
+ try:
+ await redis_node.parse_response(connection, "MULTI")
+ except ResponseError as e:
+ self._annotate_exception(e, 0, "MULTI")
+ errors.append(e)
+ except self.CONNECTION_ERRORS as cluster_error:
+ self._annotate_exception(cluster_error, 0, "MULTI")
+ raise
+
+ # and all the other commands
+ for i, command in enumerate(self._command_queue):
+ if EMPTY_RESPONSE in command.kwargs:
+ errors.append((i, command.kwargs[EMPTY_RESPONSE]))
+ else:
+ try:
+ _ = await redis_node.parse_response(connection, "_")
+ except self.SLOT_REDIRECT_ERRORS as slot_error:
+ self._annotate_exception(slot_error, i + 1, command.args)
+ errors.append(slot_error)
+ except self.CONNECTION_ERRORS as cluster_error:
+ self._annotate_exception(cluster_error, i + 1, command.args)
+ raise
+ except ResponseError as e:
+ self._annotate_exception(e, i + 1, command.args)
+ errors.append(e)
+
+ response = None
+ # parse the EXEC.
+ try:
+ response = await redis_node.parse_response(connection, "EXEC")
+ except ExecAbortError:
+ if errors:
+ raise errors[0]
+ raise
+
+ self._executing = False
+
+ # EXEC clears any watched keys
+ self._watching = False
+
+ if response is None:
+ raise WatchError("Watched variable changed.")
+
+ # put any parse errors into the response
+ for i, e in errors:
+ response.insert(i, e)
+
+ if len(response) != len(self._command_queue):
+ raise InvalidPipelineStack(
+ "Unexpected response length for cluster pipeline EXEC."
+ " Command stack was {} but response had length {}".format(
+ [c.args[0] for c in self._command_queue], len(response)
+ )
+ )
+
+ # find any errors in the response and raise if necessary
+ if raise_on_error or len(errors) > 0:
+ self._raise_first_error(
+ response,
+ self._command_queue,
+ )
+
+ # We have to run response callbacks manually
+ data = []
+ for r, cmd in zip(response, self._command_queue):
+ if not isinstance(r, Exception):
+ command_name = cmd.args[0]
+ if command_name in self._pipe.cluster_client.response_callbacks:
+ r = self._pipe.cluster_client.response_callbacks[command_name](
+ r, **cmd.kwargs
+ )
+ data.append(r)
+ return data
+
+ async def reset(self):
+ self._command_queue = []
+
+ # make sure to reset the connection state in the event that we were
+ # watching something
+ if self._transaction_connection:
+ try:
+ # call this manually since our unwatch or
+ # immediate_execute_command methods can call reset()
+ await self._transaction_connection.send_command("UNWATCH")
+ await self._transaction_connection.read_response()
+ # we can safely return the connection to the pool here since we're
+ # sure we're no longer WATCHing anything
+ self._transaction_node.release(self._transaction_connection)
+ self._transaction_connection = None
+ except self.CONNECTION_ERRORS:
+ # disconnect will also remove any previous WATCHes
+ if self._transaction_connection:
+ await self._transaction_connection.disconnect()
+
+ # clean up the other instance attributes
+ self._transaction_node = None
+ self._watching = False
+ self._explicit_transaction = False
+ self._pipeline_slots = set()
+ self._executing = False
+
+ def multi(self):
+ if self._explicit_transaction:
+ raise RedisError("Cannot issue nested calls to MULTI")
+ if self._command_queue:
+ raise RedisError(
+ "Commands without an initial WATCH have already been issued"
+ )
+ self._explicit_transaction = True
+
+ async def watch(self, *names):
+ if self._explicit_transaction:
+ raise RedisError("Cannot issue a WATCH after a MULTI")
+
+ return await self.execute_command("WATCH", *names)
+
+ async def unwatch(self):
+ if self._watching:
+ return await self.execute_command("UNWATCH")
+
+ return True
+
+ async def discard(self):
+ await self.reset()
+
+ async def unlink(self, *names):
+ return self.execute_command("UNLINK", *names)
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/connection.py b/python_embeded/Lib/site-packages/redis/asyncio/connection.py
new file mode 100644
index 0000000000000000000000000000000000000000..326daaa8f8a60b053576c24705ae76d0a15af2a4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/connection.py
@@ -0,0 +1,1331 @@
+import asyncio
+import copy
+import enum
+import inspect
+import socket
+import sys
+import warnings
+import weakref
+from abc import abstractmethod
+from itertools import chain
+from types import MappingProxyType
+from typing import (
+ Any,
+ Callable,
+ Iterable,
+ List,
+ Mapping,
+ Optional,
+ Protocol,
+ Set,
+ Tuple,
+ Type,
+ TypedDict,
+ TypeVar,
+ Union,
+)
+from urllib.parse import ParseResult, parse_qs, unquote, urlparse
+
+from ..utils import SSL_AVAILABLE
+
+if SSL_AVAILABLE:
+ import ssl
+ from ssl import SSLContext, TLSVersion
+else:
+ ssl = None
+ TLSVersion = None
+ SSLContext = None
+
+from ..auth.token import TokenInterface
+from ..event import AsyncAfterConnectionReleasedEvent, EventDispatcher
+from ..utils import deprecated_args, format_error_message
+
+# the functionality is available in 3.11.x but has a major issue before
+# 3.11.3. See https://github.com/redis/redis-py/issues/2633
+if sys.version_info >= (3, 11, 3):
+ from asyncio import timeout as async_timeout
+else:
+ from async_timeout import timeout as async_timeout
+
+from redis.asyncio.retry import Retry
+from redis.backoff import NoBackoff
+from redis.connection import DEFAULT_RESP_VERSION
+from redis.credentials import CredentialProvider, UsernamePasswordCredentialProvider
+from redis.exceptions import (
+ AuthenticationError,
+ AuthenticationWrongNumberOfArgsError,
+ ConnectionError,
+ DataError,
+ RedisError,
+ ResponseError,
+ TimeoutError,
+)
+from redis.typing import EncodableT
+from redis.utils import HIREDIS_AVAILABLE, get_lib_version, str_if_bytes
+
+from .._parsers import (
+ BaseParser,
+ Encoder,
+ _AsyncHiredisParser,
+ _AsyncRESP2Parser,
+ _AsyncRESP3Parser,
+)
+
+SYM_STAR = b"*"
+SYM_DOLLAR = b"$"
+SYM_CRLF = b"\r\n"
+SYM_LF = b"\n"
+SYM_EMPTY = b""
+
+
+class _Sentinel(enum.Enum):
+ sentinel = object()
+
+
+SENTINEL = _Sentinel.sentinel
+
+
+DefaultParser: Type[Union[_AsyncRESP2Parser, _AsyncRESP3Parser, _AsyncHiredisParser]]
+if HIREDIS_AVAILABLE:
+ DefaultParser = _AsyncHiredisParser
+else:
+ DefaultParser = _AsyncRESP2Parser
+
+
+class ConnectCallbackProtocol(Protocol):
+ def __call__(self, connection: "AbstractConnection"): ...
+
+
+class AsyncConnectCallbackProtocol(Protocol):
+ async def __call__(self, connection: "AbstractConnection"): ...
+
+
+ConnectCallbackT = Union[ConnectCallbackProtocol, AsyncConnectCallbackProtocol]
+
+
+class AbstractConnection:
+ """Manages communication to and from a Redis server"""
+
+ __slots__ = (
+ "db",
+ "username",
+ "client_name",
+ "lib_name",
+ "lib_version",
+ "credential_provider",
+ "password",
+ "socket_timeout",
+ "socket_connect_timeout",
+ "redis_connect_func",
+ "retry_on_timeout",
+ "retry_on_error",
+ "health_check_interval",
+ "next_health_check",
+ "last_active_at",
+ "encoder",
+ "ssl_context",
+ "protocol",
+ "_reader",
+ "_writer",
+ "_parser",
+ "_connect_callbacks",
+ "_buffer_cutoff",
+ "_lock",
+ "_socket_read_size",
+ "__dict__",
+ )
+
+ def __init__(
+ self,
+ *,
+ db: Union[str, int] = 0,
+ password: Optional[str] = None,
+ socket_timeout: Optional[float] = None,
+ socket_connect_timeout: Optional[float] = None,
+ retry_on_timeout: bool = False,
+ retry_on_error: Union[list, _Sentinel] = SENTINEL,
+ encoding: str = "utf-8",
+ encoding_errors: str = "strict",
+ decode_responses: bool = False,
+ parser_class: Type[BaseParser] = DefaultParser,
+ socket_read_size: int = 65536,
+ health_check_interval: float = 0,
+ client_name: Optional[str] = None,
+ lib_name: Optional[str] = "redis-py",
+ lib_version: Optional[str] = get_lib_version(),
+ username: Optional[str] = None,
+ retry: Optional[Retry] = None,
+ redis_connect_func: Optional[ConnectCallbackT] = None,
+ encoder_class: Type[Encoder] = Encoder,
+ credential_provider: Optional[CredentialProvider] = None,
+ protocol: Optional[int] = 2,
+ event_dispatcher: Optional[EventDispatcher] = None,
+ ):
+ if (username or password) and credential_provider is not None:
+ raise DataError(
+ "'username' and 'password' cannot be passed along with 'credential_"
+ "provider'. Please provide only one of the following arguments: \n"
+ "1. 'password' and (optional) 'username'\n"
+ "2. 'credential_provider'"
+ )
+ if event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+ else:
+ self._event_dispatcher = event_dispatcher
+ self.db = db
+ self.client_name = client_name
+ self.lib_name = lib_name
+ self.lib_version = lib_version
+ self.credential_provider = credential_provider
+ self.password = password
+ self.username = username
+ self.socket_timeout = socket_timeout
+ if socket_connect_timeout is None:
+ socket_connect_timeout = socket_timeout
+ self.socket_connect_timeout = socket_connect_timeout
+ self.retry_on_timeout = retry_on_timeout
+ if retry_on_error is SENTINEL:
+ retry_on_error = []
+ if retry_on_timeout:
+ retry_on_error.append(TimeoutError)
+ retry_on_error.append(socket.timeout)
+ retry_on_error.append(asyncio.TimeoutError)
+ self.retry_on_error = retry_on_error
+ if retry or retry_on_error:
+ if not retry:
+ self.retry = Retry(NoBackoff(), 1)
+ else:
+ # deep-copy the Retry object as it is mutable
+ self.retry = copy.deepcopy(retry)
+ # Update the retry's supported errors with the specified errors
+ self.retry.update_supported_errors(retry_on_error)
+ else:
+ self.retry = Retry(NoBackoff(), 0)
+ self.health_check_interval = health_check_interval
+ self.next_health_check: float = -1
+ self.encoder = encoder_class(encoding, encoding_errors, decode_responses)
+ self.redis_connect_func = redis_connect_func
+ self._reader: Optional[asyncio.StreamReader] = None
+ self._writer: Optional[asyncio.StreamWriter] = None
+ self._socket_read_size = socket_read_size
+ self.set_parser(parser_class)
+ self._connect_callbacks: List[weakref.WeakMethod[ConnectCallbackT]] = []
+ self._buffer_cutoff = 6000
+ self._re_auth_token: Optional[TokenInterface] = None
+
+ try:
+ p = int(protocol)
+ except TypeError:
+ p = DEFAULT_RESP_VERSION
+ except ValueError:
+ raise ConnectionError("protocol must be an integer")
+ finally:
+ if p < 2 or p > 3:
+ raise ConnectionError("protocol must be either 2 or 3")
+ self.protocol = protocol
+
+ def __del__(self, _warnings: Any = warnings):
+ # For some reason, the individual streams don't get properly garbage
+ # collected and therefore produce no resource warnings. We add one
+ # here, in the same style as those from the stdlib.
+ if getattr(self, "_writer", None):
+ _warnings.warn(
+ f"unclosed Connection {self!r}", ResourceWarning, source=self
+ )
+
+ try:
+ asyncio.get_running_loop()
+ self._close()
+ except RuntimeError:
+ # No actions been taken if pool already closed.
+ pass
+
+ def _close(self):
+ """
+ Internal method to silently close the connection without waiting
+ """
+ if self._writer:
+ self._writer.close()
+ self._writer = self._reader = None
+
+ def __repr__(self):
+ repr_args = ",".join((f"{k}={v}" for k, v in self.repr_pieces()))
+ return f"<{self.__class__.__module__}.{self.__class__.__name__}({repr_args})>"
+
+ @abstractmethod
+ def repr_pieces(self):
+ pass
+
+ @property
+ def is_connected(self):
+ return self._reader is not None and self._writer is not None
+
+ def register_connect_callback(self, callback):
+ """
+ Register a callback to be called when the connection is established either
+ initially or reconnected. This allows listeners to issue commands that
+ are ephemeral to the connection, for example pub/sub subscription or
+ key tracking. The callback must be a _method_ and will be kept as
+ a weak reference.
+ """
+ wm = weakref.WeakMethod(callback)
+ if wm not in self._connect_callbacks:
+ self._connect_callbacks.append(wm)
+
+ def deregister_connect_callback(self, callback):
+ """
+ De-register a previously registered callback. It will no-longer receive
+ notifications on connection events. Calling this is not required when the
+ listener goes away, since the callbacks are kept as weak methods.
+ """
+ try:
+ self._connect_callbacks.remove(weakref.WeakMethod(callback))
+ except ValueError:
+ pass
+
+ def set_parser(self, parser_class: Type[BaseParser]) -> None:
+ """
+ Creates a new instance of parser_class with socket size:
+ _socket_read_size and assigns it to the parser for the connection
+ :param parser_class: The required parser class
+ """
+ self._parser = parser_class(socket_read_size=self._socket_read_size)
+
+ async def connect(self):
+ """Connects to the Redis server if not already connected"""
+ await self.connect_check_health(check_health=True)
+
+ async def connect_check_health(self, check_health: bool = True):
+ if self.is_connected:
+ return
+ try:
+ await self.retry.call_with_retry(
+ lambda: self._connect(), lambda error: self.disconnect()
+ )
+ except asyncio.CancelledError:
+ raise # in 3.7 and earlier, this is an Exception, not BaseException
+ except (socket.timeout, asyncio.TimeoutError):
+ raise TimeoutError("Timeout connecting to server")
+ except OSError as e:
+ raise ConnectionError(self._error_message(e))
+ except Exception as exc:
+ raise ConnectionError(exc) from exc
+
+ try:
+ if not self.redis_connect_func:
+ # Use the default on_connect function
+ await self.on_connect_check_health(check_health=check_health)
+ else:
+ # Use the passed function redis_connect_func
+ (
+ await self.redis_connect_func(self)
+ if asyncio.iscoroutinefunction(self.redis_connect_func)
+ else self.redis_connect_func(self)
+ )
+ except RedisError:
+ # clean up after any error in on_connect
+ await self.disconnect()
+ raise
+
+ # run any user callbacks. right now the only internal callback
+ # is for pubsub channel/pattern resubscription
+ # first, remove any dead weakrefs
+ self._connect_callbacks = [ref for ref in self._connect_callbacks if ref()]
+ for ref in self._connect_callbacks:
+ callback = ref()
+ task = callback(self)
+ if task and inspect.isawaitable(task):
+ await task
+
+ @abstractmethod
+ async def _connect(self):
+ pass
+
+ @abstractmethod
+ def _host_error(self) -> str:
+ pass
+
+ def _error_message(self, exception: BaseException) -> str:
+ return format_error_message(self._host_error(), exception)
+
+ def get_protocol(self):
+ return self.protocol
+
+ async def on_connect(self) -> None:
+ """Initialize the connection, authenticate and select a database"""
+ await self.on_connect_check_health(check_health=True)
+
+ async def on_connect_check_health(self, check_health: bool = True) -> None:
+ self._parser.on_connect(self)
+ parser = self._parser
+
+ auth_args = None
+ # if credential provider or username and/or password are set, authenticate
+ if self.credential_provider or (self.username or self.password):
+ cred_provider = (
+ self.credential_provider
+ or UsernamePasswordCredentialProvider(self.username, self.password)
+ )
+ auth_args = await cred_provider.get_credentials_async()
+
+ # if resp version is specified and we have auth args,
+ # we need to send them via HELLO
+ if auth_args and self.protocol not in [2, "2"]:
+ if isinstance(self._parser, _AsyncRESP2Parser):
+ self.set_parser(_AsyncRESP3Parser)
+ # update cluster exception classes
+ self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
+ self._parser.on_connect(self)
+ if len(auth_args) == 1:
+ auth_args = ["default", auth_args[0]]
+ # avoid checking health here -- PING will fail if we try
+ # to check the health prior to the AUTH
+ await self.send_command(
+ "HELLO", self.protocol, "AUTH", *auth_args, check_health=False
+ )
+ response = await self.read_response()
+ if response.get(b"proto") != int(self.protocol) and response.get(
+ "proto"
+ ) != int(self.protocol):
+ raise ConnectionError("Invalid RESP version")
+ # avoid checking health here -- PING will fail if we try
+ # to check the health prior to the AUTH
+ elif auth_args:
+ await self.send_command("AUTH", *auth_args, check_health=False)
+
+ try:
+ auth_response = await self.read_response()
+ except AuthenticationWrongNumberOfArgsError:
+ # a username and password were specified but the Redis
+ # server seems to be < 6.0.0 which expects a single password
+ # arg. retry auth with just the password.
+ # https://github.com/andymccurdy/redis-py/issues/1274
+ await self.send_command("AUTH", auth_args[-1], check_health=False)
+ auth_response = await self.read_response()
+
+ if str_if_bytes(auth_response) != "OK":
+ raise AuthenticationError("Invalid Username or Password")
+
+ # if resp version is specified, switch to it
+ elif self.protocol not in [2, "2"]:
+ if isinstance(self._parser, _AsyncRESP2Parser):
+ self.set_parser(_AsyncRESP3Parser)
+ # update cluster exception classes
+ self._parser.EXCEPTION_CLASSES = parser.EXCEPTION_CLASSES
+ self._parser.on_connect(self)
+ await self.send_command("HELLO", self.protocol, check_health=check_health)
+ response = await self.read_response()
+ # if response.get(b"proto") != self.protocol and response.get(
+ # "proto"
+ # ) != self.protocol:
+ # raise ConnectionError("Invalid RESP version")
+
+ # if a client_name is given, set it
+ if self.client_name:
+ await self.send_command(
+ "CLIENT",
+ "SETNAME",
+ self.client_name,
+ check_health=check_health,
+ )
+ if str_if_bytes(await self.read_response()) != "OK":
+ raise ConnectionError("Error setting client name")
+
+ # set the library name and version, pipeline for lower startup latency
+ if self.lib_name:
+ await self.send_command(
+ "CLIENT",
+ "SETINFO",
+ "LIB-NAME",
+ self.lib_name,
+ check_health=check_health,
+ )
+ if self.lib_version:
+ await self.send_command(
+ "CLIENT",
+ "SETINFO",
+ "LIB-VER",
+ self.lib_version,
+ check_health=check_health,
+ )
+ # if a database is specified, switch to it. Also pipeline this
+ if self.db:
+ await self.send_command("SELECT", self.db, check_health=check_health)
+
+ # read responses from pipeline
+ for _ in (sent for sent in (self.lib_name, self.lib_version) if sent):
+ try:
+ await self.read_response()
+ except ResponseError:
+ pass
+
+ if self.db:
+ if str_if_bytes(await self.read_response()) != "OK":
+ raise ConnectionError("Invalid Database")
+
+ async def disconnect(self, nowait: bool = False) -> None:
+ """Disconnects from the Redis server"""
+ try:
+ async with async_timeout(self.socket_connect_timeout):
+ self._parser.on_disconnect()
+ if not self.is_connected:
+ return
+ try:
+ self._writer.close() # type: ignore[union-attr]
+ # wait for close to finish, except when handling errors and
+ # forcefully disconnecting.
+ if not nowait:
+ await self._writer.wait_closed() # type: ignore[union-attr]
+ except OSError:
+ pass
+ finally:
+ self._reader = None
+ self._writer = None
+ except asyncio.TimeoutError:
+ raise TimeoutError(
+ f"Timed out closing connection after {self.socket_connect_timeout}"
+ ) from None
+
+ async def _send_ping(self):
+ """Send PING, expect PONG in return"""
+ await self.send_command("PING", check_health=False)
+ if str_if_bytes(await self.read_response()) != "PONG":
+ raise ConnectionError("Bad response from PING health check")
+
+ async def _ping_failed(self, error):
+ """Function to call when PING fails"""
+ await self.disconnect()
+
+ async def check_health(self):
+ """Check the health of the connection with a PING/PONG"""
+ if (
+ self.health_check_interval
+ and asyncio.get_running_loop().time() > self.next_health_check
+ ):
+ await self.retry.call_with_retry(self._send_ping, self._ping_failed)
+
+ async def _send_packed_command(self, command: Iterable[bytes]) -> None:
+ self._writer.writelines(command)
+ await self._writer.drain()
+
+ async def send_packed_command(
+ self, command: Union[bytes, str, Iterable[bytes]], check_health: bool = True
+ ) -> None:
+ if not self.is_connected:
+ await self.connect_check_health(check_health=False)
+ if check_health:
+ await self.check_health()
+
+ try:
+ if isinstance(command, str):
+ command = command.encode()
+ if isinstance(command, bytes):
+ command = [command]
+ if self.socket_timeout:
+ await asyncio.wait_for(
+ self._send_packed_command(command), self.socket_timeout
+ )
+ else:
+ self._writer.writelines(command)
+ await self._writer.drain()
+ except asyncio.TimeoutError:
+ await self.disconnect(nowait=True)
+ raise TimeoutError("Timeout writing to socket") from None
+ except OSError as e:
+ await self.disconnect(nowait=True)
+ if len(e.args) == 1:
+ err_no, errmsg = "UNKNOWN", e.args[0]
+ else:
+ err_no = e.args[0]
+ errmsg = e.args[1]
+ raise ConnectionError(
+ f"Error {err_no} while writing to socket. {errmsg}."
+ ) from e
+ except BaseException:
+ # BaseExceptions can be raised when a socket send operation is not
+ # finished, e.g. due to a timeout. Ideally, a caller could then re-try
+ # to send un-sent data. However, the send_packed_command() API
+ # does not support it so there is no point in keeping the connection open.
+ await self.disconnect(nowait=True)
+ raise
+
+ async def send_command(self, *args: Any, **kwargs: Any) -> None:
+ """Pack and send a command to the Redis server"""
+ await self.send_packed_command(
+ self.pack_command(*args), check_health=kwargs.get("check_health", True)
+ )
+
+ async def can_read_destructive(self):
+ """Poll the socket to see if there's data that can be read."""
+ try:
+ return await self._parser.can_read_destructive()
+ except OSError as e:
+ await self.disconnect(nowait=True)
+ host_error = self._host_error()
+ raise ConnectionError(f"Error while reading from {host_error}: {e.args}")
+
+ async def read_response(
+ self,
+ disable_decoding: bool = False,
+ timeout: Optional[float] = None,
+ *,
+ disconnect_on_error: bool = True,
+ push_request: Optional[bool] = False,
+ ):
+ """Read the response from a previously sent command"""
+ read_timeout = timeout if timeout is not None else self.socket_timeout
+ host_error = self._host_error()
+ try:
+ if read_timeout is not None and self.protocol in ["3", 3]:
+ async with async_timeout(read_timeout):
+ response = await self._parser.read_response(
+ disable_decoding=disable_decoding, push_request=push_request
+ )
+ elif read_timeout is not None:
+ async with async_timeout(read_timeout):
+ response = await self._parser.read_response(
+ disable_decoding=disable_decoding
+ )
+ elif self.protocol in ["3", 3]:
+ response = await self._parser.read_response(
+ disable_decoding=disable_decoding, push_request=push_request
+ )
+ else:
+ response = await self._parser.read_response(
+ disable_decoding=disable_decoding
+ )
+ except asyncio.TimeoutError:
+ if timeout is not None:
+ # user requested timeout, return None. Operation can be retried
+ return None
+ # it was a self.socket_timeout error.
+ if disconnect_on_error:
+ await self.disconnect(nowait=True)
+ raise TimeoutError(f"Timeout reading from {host_error}")
+ except OSError as e:
+ if disconnect_on_error:
+ await self.disconnect(nowait=True)
+ raise ConnectionError(f"Error while reading from {host_error} : {e.args}")
+ except BaseException:
+ # Also by default close in case of BaseException. A lot of code
+ # relies on this behaviour when doing Command/Response pairs.
+ # See #1128.
+ if disconnect_on_error:
+ await self.disconnect(nowait=True)
+ raise
+
+ if self.health_check_interval:
+ next_time = asyncio.get_running_loop().time() + self.health_check_interval
+ self.next_health_check = next_time
+
+ if isinstance(response, ResponseError):
+ raise response from None
+ return response
+
+ def pack_command(self, *args: EncodableT) -> List[bytes]:
+ """Pack a series of arguments into the Redis protocol"""
+ output = []
+ # the client might have included 1 or more literal arguments in
+ # the command name, e.g., 'CONFIG GET'. The Redis server expects these
+ # arguments to be sent separately, so split the first argument
+ # manually. These arguments should be bytestrings so that they are
+ # not encoded.
+ assert not isinstance(args[0], float)
+ if isinstance(args[0], str):
+ args = tuple(args[0].encode().split()) + args[1:]
+ elif b" " in args[0]:
+ args = tuple(args[0].split()) + args[1:]
+
+ buff = SYM_EMPTY.join((SYM_STAR, str(len(args)).encode(), SYM_CRLF))
+
+ buffer_cutoff = self._buffer_cutoff
+ for arg in map(self.encoder.encode, args):
+ # to avoid large string mallocs, chunk the command into the
+ # output list if we're sending large values or memoryviews
+ arg_length = len(arg)
+ if (
+ len(buff) > buffer_cutoff
+ or arg_length > buffer_cutoff
+ or isinstance(arg, memoryview)
+ ):
+ buff = SYM_EMPTY.join(
+ (buff, SYM_DOLLAR, str(arg_length).encode(), SYM_CRLF)
+ )
+ output.append(buff)
+ output.append(arg)
+ buff = SYM_CRLF
+ else:
+ buff = SYM_EMPTY.join(
+ (
+ buff,
+ SYM_DOLLAR,
+ str(arg_length).encode(),
+ SYM_CRLF,
+ arg,
+ SYM_CRLF,
+ )
+ )
+ output.append(buff)
+ return output
+
+ def pack_commands(self, commands: Iterable[Iterable[EncodableT]]) -> List[bytes]:
+ """Pack multiple commands into the Redis protocol"""
+ output: List[bytes] = []
+ pieces: List[bytes] = []
+ buffer_length = 0
+ buffer_cutoff = self._buffer_cutoff
+
+ for cmd in commands:
+ for chunk in self.pack_command(*cmd):
+ chunklen = len(chunk)
+ if (
+ buffer_length > buffer_cutoff
+ or chunklen > buffer_cutoff
+ or isinstance(chunk, memoryview)
+ ):
+ if pieces:
+ output.append(SYM_EMPTY.join(pieces))
+ buffer_length = 0
+ pieces = []
+
+ if chunklen > buffer_cutoff or isinstance(chunk, memoryview):
+ output.append(chunk)
+ else:
+ pieces.append(chunk)
+ buffer_length += chunklen
+
+ if pieces:
+ output.append(SYM_EMPTY.join(pieces))
+ return output
+
+ def _socket_is_empty(self):
+ """Check if the socket is empty"""
+ return len(self._reader._buffer) == 0
+
+ async def process_invalidation_messages(self):
+ while not self._socket_is_empty():
+ await self.read_response(push_request=True)
+
+ def set_re_auth_token(self, token: TokenInterface):
+ self._re_auth_token = token
+
+ async def re_auth(self):
+ if self._re_auth_token is not None:
+ await self.send_command(
+ "AUTH",
+ self._re_auth_token.try_get("oid"),
+ self._re_auth_token.get_value(),
+ )
+ await self.read_response()
+ self._re_auth_token = None
+
+
+class Connection(AbstractConnection):
+ "Manages TCP communication to and from a Redis server"
+
+ def __init__(
+ self,
+ *,
+ host: str = "localhost",
+ port: Union[str, int] = 6379,
+ socket_keepalive: bool = False,
+ socket_keepalive_options: Optional[Mapping[int, Union[int, bytes]]] = None,
+ socket_type: int = 0,
+ **kwargs,
+ ):
+ self.host = host
+ self.port = int(port)
+ self.socket_keepalive = socket_keepalive
+ self.socket_keepalive_options = socket_keepalive_options or {}
+ self.socket_type = socket_type
+ super().__init__(**kwargs)
+
+ def repr_pieces(self):
+ pieces = [("host", self.host), ("port", self.port), ("db", self.db)]
+ if self.client_name:
+ pieces.append(("client_name", self.client_name))
+ return pieces
+
+ def _connection_arguments(self) -> Mapping:
+ return {"host": self.host, "port": self.port}
+
+ async def _connect(self):
+ """Create a TCP socket connection"""
+ async with async_timeout(self.socket_connect_timeout):
+ reader, writer = await asyncio.open_connection(
+ **self._connection_arguments()
+ )
+ self._reader = reader
+ self._writer = writer
+ sock = writer.transport.get_extra_info("socket")
+ if sock:
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
+ try:
+ # TCP_KEEPALIVE
+ if self.socket_keepalive:
+ sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
+ for k, v in self.socket_keepalive_options.items():
+ sock.setsockopt(socket.SOL_TCP, k, v)
+
+ except (OSError, TypeError):
+ # `socket_keepalive_options` might contain invalid options
+ # causing an error. Do not leave the connection open.
+ writer.close()
+ raise
+
+ def _host_error(self) -> str:
+ return f"{self.host}:{self.port}"
+
+
+class SSLConnection(Connection):
+ """Manages SSL connections to and from the Redis server(s).
+ This class extends the Connection class, adding SSL functionality, and making
+ use of ssl.SSLContext (https://docs.python.org/3/library/ssl.html#ssl.SSLContext)
+ """
+
+ def __init__(
+ self,
+ ssl_keyfile: Optional[str] = None,
+ ssl_certfile: Optional[str] = None,
+ ssl_cert_reqs: Union[str, ssl.VerifyMode] = "required",
+ ssl_ca_certs: Optional[str] = None,
+ ssl_ca_data: Optional[str] = None,
+ ssl_check_hostname: bool = True,
+ ssl_min_version: Optional[TLSVersion] = None,
+ ssl_ciphers: Optional[str] = None,
+ **kwargs,
+ ):
+ if not SSL_AVAILABLE:
+ raise RedisError("Python wasn't built with SSL support")
+
+ self.ssl_context: RedisSSLContext = RedisSSLContext(
+ keyfile=ssl_keyfile,
+ certfile=ssl_certfile,
+ cert_reqs=ssl_cert_reqs,
+ ca_certs=ssl_ca_certs,
+ ca_data=ssl_ca_data,
+ check_hostname=ssl_check_hostname,
+ min_version=ssl_min_version,
+ ciphers=ssl_ciphers,
+ )
+ super().__init__(**kwargs)
+
+ def _connection_arguments(self) -> Mapping:
+ kwargs = super()._connection_arguments()
+ kwargs["ssl"] = self.ssl_context.get()
+ return kwargs
+
+ @property
+ def keyfile(self):
+ return self.ssl_context.keyfile
+
+ @property
+ def certfile(self):
+ return self.ssl_context.certfile
+
+ @property
+ def cert_reqs(self):
+ return self.ssl_context.cert_reqs
+
+ @property
+ def ca_certs(self):
+ return self.ssl_context.ca_certs
+
+ @property
+ def ca_data(self):
+ return self.ssl_context.ca_data
+
+ @property
+ def check_hostname(self):
+ return self.ssl_context.check_hostname
+
+ @property
+ def min_version(self):
+ return self.ssl_context.min_version
+
+
+class RedisSSLContext:
+ __slots__ = (
+ "keyfile",
+ "certfile",
+ "cert_reqs",
+ "ca_certs",
+ "ca_data",
+ "context",
+ "check_hostname",
+ "min_version",
+ "ciphers",
+ )
+
+ def __init__(
+ self,
+ keyfile: Optional[str] = None,
+ certfile: Optional[str] = None,
+ cert_reqs: Optional[Union[str, ssl.VerifyMode]] = None,
+ ca_certs: Optional[str] = None,
+ ca_data: Optional[str] = None,
+ check_hostname: bool = False,
+ min_version: Optional[TLSVersion] = None,
+ ciphers: Optional[str] = None,
+ ):
+ if not SSL_AVAILABLE:
+ raise RedisError("Python wasn't built with SSL support")
+
+ self.keyfile = keyfile
+ self.certfile = certfile
+ if cert_reqs is None:
+ cert_reqs = ssl.CERT_NONE
+ elif isinstance(cert_reqs, str):
+ CERT_REQS = { # noqa: N806
+ "none": ssl.CERT_NONE,
+ "optional": ssl.CERT_OPTIONAL,
+ "required": ssl.CERT_REQUIRED,
+ }
+ if cert_reqs not in CERT_REQS:
+ raise RedisError(
+ f"Invalid SSL Certificate Requirements Flag: {cert_reqs}"
+ )
+ cert_reqs = CERT_REQS[cert_reqs]
+ self.cert_reqs = cert_reqs
+ self.ca_certs = ca_certs
+ self.ca_data = ca_data
+ self.check_hostname = (
+ check_hostname if self.cert_reqs != ssl.CERT_NONE else False
+ )
+ self.min_version = min_version
+ self.ciphers = ciphers
+ self.context: Optional[SSLContext] = None
+
+ def get(self) -> SSLContext:
+ if not self.context:
+ context = ssl.create_default_context()
+ context.check_hostname = self.check_hostname
+ context.verify_mode = self.cert_reqs
+ if self.certfile and self.keyfile:
+ context.load_cert_chain(certfile=self.certfile, keyfile=self.keyfile)
+ if self.ca_certs or self.ca_data:
+ context.load_verify_locations(cafile=self.ca_certs, cadata=self.ca_data)
+ if self.min_version is not None:
+ context.minimum_version = self.min_version
+ if self.ciphers is not None:
+ context.set_ciphers(self.ciphers)
+ self.context = context
+ return self.context
+
+
+class UnixDomainSocketConnection(AbstractConnection):
+ "Manages UDS communication to and from a Redis server"
+
+ def __init__(self, *, path: str = "", **kwargs):
+ self.path = path
+ super().__init__(**kwargs)
+
+ def repr_pieces(self) -> Iterable[Tuple[str, Union[str, int]]]:
+ pieces = [("path", self.path), ("db", self.db)]
+ if self.client_name:
+ pieces.append(("client_name", self.client_name))
+ return pieces
+
+ async def _connect(self):
+ async with async_timeout(self.socket_connect_timeout):
+ reader, writer = await asyncio.open_unix_connection(path=self.path)
+ self._reader = reader
+ self._writer = writer
+ await self.on_connect()
+
+ def _host_error(self) -> str:
+ return self.path
+
+
+FALSE_STRINGS = ("0", "F", "FALSE", "N", "NO")
+
+
+def to_bool(value) -> Optional[bool]:
+ if value is None or value == "":
+ return None
+ if isinstance(value, str) and value.upper() in FALSE_STRINGS:
+ return False
+ return bool(value)
+
+
+URL_QUERY_ARGUMENT_PARSERS: Mapping[str, Callable[..., object]] = MappingProxyType(
+ {
+ "db": int,
+ "socket_timeout": float,
+ "socket_connect_timeout": float,
+ "socket_keepalive": to_bool,
+ "retry_on_timeout": to_bool,
+ "max_connections": int,
+ "health_check_interval": int,
+ "ssl_check_hostname": to_bool,
+ "timeout": float,
+ }
+)
+
+
+class ConnectKwargs(TypedDict, total=False):
+ username: str
+ password: str
+ connection_class: Type[AbstractConnection]
+ host: str
+ port: int
+ db: int
+ path: str
+
+
+def parse_url(url: str) -> ConnectKwargs:
+ parsed: ParseResult = urlparse(url)
+ kwargs: ConnectKwargs = {}
+
+ for name, value_list in parse_qs(parsed.query).items():
+ if value_list and len(value_list) > 0:
+ value = unquote(value_list[0])
+ parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
+ if parser:
+ try:
+ kwargs[name] = parser(value)
+ except (TypeError, ValueError):
+ raise ValueError(f"Invalid value for '{name}' in connection URL.")
+ else:
+ kwargs[name] = value
+
+ if parsed.username:
+ kwargs["username"] = unquote(parsed.username)
+ if parsed.password:
+ kwargs["password"] = unquote(parsed.password)
+
+ # We only support redis://, rediss:// and unix:// schemes.
+ if parsed.scheme == "unix":
+ if parsed.path:
+ kwargs["path"] = unquote(parsed.path)
+ kwargs["connection_class"] = UnixDomainSocketConnection
+
+ elif parsed.scheme in ("redis", "rediss"):
+ if parsed.hostname:
+ kwargs["host"] = unquote(parsed.hostname)
+ if parsed.port:
+ kwargs["port"] = int(parsed.port)
+
+ # If there's a path argument, use it as the db argument if a
+ # querystring value wasn't specified
+ if parsed.path and "db" not in kwargs:
+ try:
+ kwargs["db"] = int(unquote(parsed.path).replace("/", ""))
+ except (AttributeError, ValueError):
+ pass
+
+ if parsed.scheme == "rediss":
+ kwargs["connection_class"] = SSLConnection
+ else:
+ valid_schemes = "redis://, rediss://, unix://"
+ raise ValueError(
+ f"Redis URL must specify one of the following schemes ({valid_schemes})"
+ )
+
+ return kwargs
+
+
+_CP = TypeVar("_CP", bound="ConnectionPool")
+
+
+class ConnectionPool:
+ """
+ Create a connection pool. ``If max_connections`` is set, then this
+ object raises :py:class:`~redis.ConnectionError` when the pool's
+ limit is reached.
+
+ By default, TCP connections are created unless ``connection_class``
+ is specified. Use :py:class:`~redis.UnixDomainSocketConnection` for
+ unix sockets.
+
+ Any additional keyword arguments are passed to the constructor of
+ ``connection_class``.
+ """
+
+ @classmethod
+ def from_url(cls: Type[_CP], url: str, **kwargs) -> _CP:
+ """
+ Return a connection pool configured from the given URL.
+
+ For example::
+
+ redis://[[username]:[password]]@localhost:6379/0
+ rediss://[[username]:[password]]@localhost:6379/0
+ unix://[username@]/path/to/socket.sock?db=0[&password=password]
+
+ Three URL schemes are supported:
+
+ - `redis://` creates a TCP socket connection. See more at:
+
+ - `rediss://` creates a SSL wrapped TCP socket connection. See more at:
+
+ - ``unix://``: creates a Unix Domain Socket connection.
+
+ The username, password, hostname, path and all querystring values
+ are passed through urllib.parse.unquote in order to replace any
+ percent-encoded values with their corresponding characters.
+
+ There are several ways to specify a database number. The first value
+ found will be used:
+
+ 1. A ``db`` querystring option, e.g. redis://localhost?db=0
+
+ 2. If using the redis:// or rediss:// schemes, the path argument
+ of the url, e.g. redis://localhost/0
+
+ 3. A ``db`` keyword argument to this function.
+
+ If none of these options are specified, the default db=0 is used.
+
+ All querystring options are cast to their appropriate Python types.
+ Boolean arguments can be specified with string values "True"/"False"
+ or "Yes"/"No". Values that cannot be properly cast cause a
+ ``ValueError`` to be raised. Once parsed, the querystring arguments
+ and keyword arguments are passed to the ``ConnectionPool``'s
+ class initializer. In the case of conflicting arguments, querystring
+ arguments always win.
+ """
+ url_options = parse_url(url)
+ kwargs.update(url_options)
+ return cls(**kwargs)
+
+ def __init__(
+ self,
+ connection_class: Type[AbstractConnection] = Connection,
+ max_connections: Optional[int] = None,
+ **connection_kwargs,
+ ):
+ max_connections = max_connections or 2**31
+ if not isinstance(max_connections, int) or max_connections < 0:
+ raise ValueError('"max_connections" must be a positive integer')
+
+ self.connection_class = connection_class
+ self.connection_kwargs = connection_kwargs
+ self.max_connections = max_connections
+
+ self._available_connections: List[AbstractConnection] = []
+ self._in_use_connections: Set[AbstractConnection] = set()
+ self.encoder_class = self.connection_kwargs.get("encoder_class", Encoder)
+ self._lock = asyncio.Lock()
+ self._event_dispatcher = self.connection_kwargs.get("event_dispatcher", None)
+ if self._event_dispatcher is None:
+ self._event_dispatcher = EventDispatcher()
+
+ def __repr__(self):
+ return (
+ f"<{self.__class__.__module__}.{self.__class__.__name__}"
+ f"({self.connection_class(**self.connection_kwargs)!r})>"
+ )
+
+ def reset(self):
+ self._available_connections = []
+ self._in_use_connections = weakref.WeakSet()
+
+ def can_get_connection(self) -> bool:
+ """Return True if a connection can be retrieved from the pool."""
+ return (
+ self._available_connections
+ or len(self._in_use_connections) < self.max_connections
+ )
+
+ @deprecated_args(
+ args_to_warn=["*"],
+ reason="Use get_connection() without args instead",
+ version="5.3.0",
+ )
+ async def get_connection(self, command_name=None, *keys, **options):
+ async with self._lock:
+ """Get a connected connection from the pool"""
+ connection = self.get_available_connection()
+ try:
+ await self.ensure_connection(connection)
+ except BaseException:
+ await self.release(connection)
+ raise
+
+ return connection
+
+ def get_available_connection(self):
+ """Get a connection from the pool, without making sure it is connected"""
+ try:
+ connection = self._available_connections.pop()
+ except IndexError:
+ if len(self._in_use_connections) >= self.max_connections:
+ raise ConnectionError("Too many connections") from None
+ connection = self.make_connection()
+ self._in_use_connections.add(connection)
+ return connection
+
+ def get_encoder(self):
+ """Return an encoder based on encoding settings"""
+ kwargs = self.connection_kwargs
+ return self.encoder_class(
+ encoding=kwargs.get("encoding", "utf-8"),
+ encoding_errors=kwargs.get("encoding_errors", "strict"),
+ decode_responses=kwargs.get("decode_responses", False),
+ )
+
+ def make_connection(self):
+ """Create a new connection. Can be overridden by child classes."""
+ return self.connection_class(**self.connection_kwargs)
+
+ async def ensure_connection(self, connection: AbstractConnection):
+ """Ensure that the connection object is connected and valid"""
+ await connection.connect()
+ # connections that the pool provides should be ready to send
+ # a command. if not, the connection was either returned to the
+ # pool before all data has been read or the socket has been
+ # closed. either way, reconnect and verify everything is good.
+ try:
+ if await connection.can_read_destructive():
+ raise ConnectionError("Connection has data") from None
+ except (ConnectionError, TimeoutError, OSError):
+ await connection.disconnect()
+ await connection.connect()
+ if await connection.can_read_destructive():
+ raise ConnectionError("Connection not ready") from None
+
+ async def release(self, connection: AbstractConnection):
+ """Releases the connection back to the pool"""
+ # Connections should always be returned to the correct pool,
+ # not doing so is an error that will cause an exception here.
+ self._in_use_connections.remove(connection)
+ self._available_connections.append(connection)
+ await self._event_dispatcher.dispatch_async(
+ AsyncAfterConnectionReleasedEvent(connection)
+ )
+
+ async def disconnect(self, inuse_connections: bool = True):
+ """
+ Disconnects connections in the pool
+
+ If ``inuse_connections`` is True, disconnect connections that are
+ current in use, potentially by other tasks. Otherwise only disconnect
+ connections that are idle in the pool.
+ """
+ if inuse_connections:
+ connections: Iterable[AbstractConnection] = chain(
+ self._available_connections, self._in_use_connections
+ )
+ else:
+ connections = self._available_connections
+ resp = await asyncio.gather(
+ *(connection.disconnect() for connection in connections),
+ return_exceptions=True,
+ )
+ exc = next((r for r in resp if isinstance(r, BaseException)), None)
+ if exc:
+ raise exc
+
+ async def aclose(self) -> None:
+ """Close the pool, disconnecting all connections"""
+ await self.disconnect()
+
+ def set_retry(self, retry: "Retry") -> None:
+ for conn in self._available_connections:
+ conn.retry = retry
+ for conn in self._in_use_connections:
+ conn.retry = retry
+
+ async def re_auth_callback(self, token: TokenInterface):
+ async with self._lock:
+ for conn in self._available_connections:
+ await conn.retry.call_with_retry(
+ lambda: conn.send_command(
+ "AUTH", token.try_get("oid"), token.get_value()
+ ),
+ lambda error: self._mock(error),
+ )
+ await conn.retry.call_with_retry(
+ lambda: conn.read_response(), lambda error: self._mock(error)
+ )
+ for conn in self._in_use_connections:
+ conn.set_re_auth_token(token)
+
+ async def _mock(self, error: RedisError):
+ """
+ Dummy functions, needs to be passed as error callback to retry object.
+ :param error:
+ :return:
+ """
+ pass
+
+
+class BlockingConnectionPool(ConnectionPool):
+ """
+ A blocking connection pool::
+
+ >>> from redis.asyncio import Redis, BlockingConnectionPool
+ >>> client = Redis.from_pool(BlockingConnectionPool())
+
+ It performs the same function as the default
+ :py:class:`~redis.asyncio.ConnectionPool` implementation, in that,
+ it maintains a pool of reusable connections that can be shared by
+ multiple async redis clients.
+
+ The difference is that, in the event that a client tries to get a
+ connection from the pool when all of connections are in use, rather than
+ raising a :py:class:`~redis.ConnectionError` (as the default
+ :py:class:`~redis.asyncio.ConnectionPool` implementation does), it
+ blocks the current `Task` for a specified number of seconds until
+ a connection becomes available.
+
+ Use ``max_connections`` to increase / decrease the pool size::
+
+ >>> pool = BlockingConnectionPool(max_connections=10)
+
+ Use ``timeout`` to tell it either how many seconds to wait for a connection
+ to become available, or to block forever:
+
+ >>> # Block forever.
+ >>> pool = BlockingConnectionPool(timeout=None)
+
+ >>> # Raise a ``ConnectionError`` after five seconds if a connection is
+ >>> # not available.
+ >>> pool = BlockingConnectionPool(timeout=5)
+ """
+
+ def __init__(
+ self,
+ max_connections: int = 50,
+ timeout: Optional[int] = 20,
+ connection_class: Type[AbstractConnection] = Connection,
+ queue_class: Type[asyncio.Queue] = asyncio.LifoQueue, # deprecated
+ **connection_kwargs,
+ ):
+ super().__init__(
+ connection_class=connection_class,
+ max_connections=max_connections,
+ **connection_kwargs,
+ )
+ self._condition = asyncio.Condition()
+ self.timeout = timeout
+
+ @deprecated_args(
+ args_to_warn=["*"],
+ reason="Use get_connection() without args instead",
+ version="5.3.0",
+ )
+ async def get_connection(self, command_name=None, *keys, **options):
+ """Gets a connection from the pool, blocking until one is available"""
+ try:
+ async with self._condition:
+ async with async_timeout(self.timeout):
+ await self._condition.wait_for(self.can_get_connection)
+ connection = super().get_available_connection()
+ except asyncio.TimeoutError as err:
+ raise ConnectionError("No connection available.") from err
+
+ # We now perform the connection check outside of the lock.
+ try:
+ await self.ensure_connection(connection)
+ return connection
+ except BaseException:
+ await self.release(connection)
+ raise
+
+ async def release(self, connection: AbstractConnection):
+ """Releases the connection back to the pool."""
+ async with self._condition:
+ await super().release(connection)
+ self._condition.notify()
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/lock.py b/python_embeded/Lib/site-packages/redis/asyncio/lock.py
new file mode 100644
index 0000000000000000000000000000000000000000..16d7fb6957591f593ed6479abafa50a49cec1df3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/lock.py
@@ -0,0 +1,334 @@
+import asyncio
+import logging
+import threading
+import uuid
+from types import SimpleNamespace
+from typing import TYPE_CHECKING, Awaitable, Optional, Union
+
+from redis.exceptions import LockError, LockNotOwnedError
+from redis.typing import Number
+
+if TYPE_CHECKING:
+ from redis.asyncio import Redis, RedisCluster
+
+logger = logging.getLogger(__name__)
+
+
+class Lock:
+ """
+ A shared, distributed Lock. Using Redis for locking allows the Lock
+ to be shared across processes and/or machines.
+
+ It's left to the user to resolve deadlock issues and make sure
+ multiple clients play nicely together.
+ """
+
+ lua_release = None
+ lua_extend = None
+ lua_reacquire = None
+
+ # KEYS[1] - lock name
+ # ARGV[1] - token
+ # return 1 if the lock was released, otherwise 0
+ LUA_RELEASE_SCRIPT = """
+ local token = redis.call('get', KEYS[1])
+ if not token or token ~= ARGV[1] then
+ return 0
+ end
+ redis.call('del', KEYS[1])
+ return 1
+ """
+
+ # KEYS[1] - lock name
+ # ARGV[1] - token
+ # ARGV[2] - additional milliseconds
+ # ARGV[3] - "0" if the additional time should be added to the lock's
+ # existing ttl or "1" if the existing ttl should be replaced
+ # return 1 if the locks time was extended, otherwise 0
+ LUA_EXTEND_SCRIPT = """
+ local token = redis.call('get', KEYS[1])
+ if not token or token ~= ARGV[1] then
+ return 0
+ end
+ local expiration = redis.call('pttl', KEYS[1])
+ if not expiration then
+ expiration = 0
+ end
+ if expiration < 0 then
+ return 0
+ end
+
+ local newttl = ARGV[2]
+ if ARGV[3] == "0" then
+ newttl = ARGV[2] + expiration
+ end
+ redis.call('pexpire', KEYS[1], newttl)
+ return 1
+ """
+
+ # KEYS[1] - lock name
+ # ARGV[1] - token
+ # ARGV[2] - milliseconds
+ # return 1 if the locks time was reacquired, otherwise 0
+ LUA_REACQUIRE_SCRIPT = """
+ local token = redis.call('get', KEYS[1])
+ if not token or token ~= ARGV[1] then
+ return 0
+ end
+ redis.call('pexpire', KEYS[1], ARGV[2])
+ return 1
+ """
+
+ def __init__(
+ self,
+ redis: Union["Redis", "RedisCluster"],
+ name: Union[str, bytes, memoryview],
+ timeout: Optional[float] = None,
+ sleep: float = 0.1,
+ blocking: bool = True,
+ blocking_timeout: Optional[Number] = None,
+ thread_local: bool = True,
+ raise_on_release_error: bool = True,
+ ):
+ """
+ Create a new Lock instance named ``name`` using the Redis client
+ supplied by ``redis``.
+
+ ``timeout`` indicates a maximum life for the lock in seconds.
+ By default, it will remain locked until release() is called.
+ ``timeout`` can be specified as a float or integer, both representing
+ the number of seconds to wait.
+
+ ``sleep`` indicates the amount of time to sleep in seconds per loop
+ iteration when the lock is in blocking mode and another client is
+ currently holding the lock.
+
+ ``blocking`` indicates whether calling ``acquire`` should block until
+ the lock has been acquired or to fail immediately, causing ``acquire``
+ to return False and the lock not being acquired. Defaults to True.
+ Note this value can be overridden by passing a ``blocking``
+ argument to ``acquire``.
+
+ ``blocking_timeout`` indicates the maximum amount of time in seconds to
+ spend trying to acquire the lock. A value of ``None`` indicates
+ continue trying forever. ``blocking_timeout`` can be specified as a
+ float or integer, both representing the number of seconds to wait.
+
+ ``thread_local`` indicates whether the lock token is placed in
+ thread-local storage. By default, the token is placed in thread local
+ storage so that a thread only sees its token, not a token set by
+ another thread. Consider the following timeline:
+
+ time: 0, thread-1 acquires `my-lock`, with a timeout of 5 seconds.
+ thread-1 sets the token to "abc"
+ time: 1, thread-2 blocks trying to acquire `my-lock` using the
+ Lock instance.
+ time: 5, thread-1 has not yet completed. redis expires the lock
+ key.
+ time: 5, thread-2 acquired `my-lock` now that it's available.
+ thread-2 sets the token to "xyz"
+ time: 6, thread-1 finishes its work and calls release(). if the
+ token is *not* stored in thread local storage, then
+ thread-1 would see the token value as "xyz" and would be
+ able to successfully release the thread-2's lock.
+
+ ``raise_on_release_error`` indicates whether to raise an exception when
+ the lock is no longer owned when exiting the context manager. By default,
+ this is True, meaning an exception will be raised. If False, the warning
+ will be logged and the exception will be suppressed.
+
+ In some use cases it's necessary to disable thread local storage. For
+ example, if you have code where one thread acquires a lock and passes
+ that lock instance to a worker thread to release later. If thread
+ local storage isn't disabled in this case, the worker thread won't see
+ the token set by the thread that acquired the lock. Our assumption
+ is that these cases aren't common and as such default to using
+ thread local storage.
+ """
+ self.redis = redis
+ self.name = name
+ self.timeout = timeout
+ self.sleep = sleep
+ self.blocking = blocking
+ self.blocking_timeout = blocking_timeout
+ self.thread_local = bool(thread_local)
+ self.local = threading.local() if self.thread_local else SimpleNamespace()
+ self.raise_on_release_error = raise_on_release_error
+ self.local.token = None
+ self.register_scripts()
+
+ def register_scripts(self):
+ cls = self.__class__
+ client = self.redis
+ if cls.lua_release is None:
+ cls.lua_release = client.register_script(cls.LUA_RELEASE_SCRIPT)
+ if cls.lua_extend is None:
+ cls.lua_extend = client.register_script(cls.LUA_EXTEND_SCRIPT)
+ if cls.lua_reacquire is None:
+ cls.lua_reacquire = client.register_script(cls.LUA_REACQUIRE_SCRIPT)
+
+ async def __aenter__(self):
+ if await self.acquire():
+ return self
+ raise LockError("Unable to acquire lock within the time specified")
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ try:
+ await self.release()
+ except LockError:
+ if self.raise_on_release_error:
+ raise
+ logger.warning(
+ "Lock was unlocked or no longer owned when exiting context manager."
+ )
+
+ async def acquire(
+ self,
+ blocking: Optional[bool] = None,
+ blocking_timeout: Optional[Number] = None,
+ token: Optional[Union[str, bytes]] = None,
+ ):
+ """
+ Use Redis to hold a shared, distributed lock named ``name``.
+ Returns True once the lock is acquired.
+
+ If ``blocking`` is False, always return immediately. If the lock
+ was acquired, return True, otherwise return False.
+
+ ``blocking_timeout`` specifies the maximum number of seconds to
+ wait trying to acquire the lock.
+
+ ``token`` specifies the token value to be used. If provided, token
+ must be a bytes object or a string that can be encoded to a bytes
+ object with the default encoding. If a token isn't specified, a UUID
+ will be generated.
+ """
+ sleep = self.sleep
+ if token is None:
+ token = uuid.uuid1().hex.encode()
+ else:
+ try:
+ encoder = self.redis.connection_pool.get_encoder()
+ except AttributeError:
+ # Cluster
+ encoder = self.redis.get_encoder()
+ token = encoder.encode(token)
+ if blocking is None:
+ blocking = self.blocking
+ if blocking_timeout is None:
+ blocking_timeout = self.blocking_timeout
+ stop_trying_at = None
+ if blocking_timeout is not None:
+ stop_trying_at = asyncio.get_running_loop().time() + blocking_timeout
+ while True:
+ if await self.do_acquire(token):
+ self.local.token = token
+ return True
+ if not blocking:
+ return False
+ next_try_at = asyncio.get_running_loop().time() + sleep
+ if stop_trying_at is not None and next_try_at > stop_trying_at:
+ return False
+ await asyncio.sleep(sleep)
+
+ async def do_acquire(self, token: Union[str, bytes]) -> bool:
+ if self.timeout:
+ # convert to milliseconds
+ timeout = int(self.timeout * 1000)
+ else:
+ timeout = None
+ if await self.redis.set(self.name, token, nx=True, px=timeout):
+ return True
+ return False
+
+ async def locked(self) -> bool:
+ """
+ Returns True if this key is locked by any process, otherwise False.
+ """
+ return await self.redis.get(self.name) is not None
+
+ async def owned(self) -> bool:
+ """
+ Returns True if this key is locked by this lock, otherwise False.
+ """
+ stored_token = await self.redis.get(self.name)
+ # need to always compare bytes to bytes
+ # TODO: this can be simplified when the context manager is finished
+ if stored_token and not isinstance(stored_token, bytes):
+ try:
+ encoder = self.redis.connection_pool.get_encoder()
+ except AttributeError:
+ # Cluster
+ encoder = self.redis.get_encoder()
+ stored_token = encoder.encode(stored_token)
+ return self.local.token is not None and stored_token == self.local.token
+
+ def release(self) -> Awaitable[None]:
+ """Releases the already acquired lock"""
+ expected_token = self.local.token
+ if expected_token is None:
+ raise LockError(
+ "Cannot release a lock that's not owned or is already unlocked.",
+ lock_name=self.name,
+ )
+ self.local.token = None
+ return self.do_release(expected_token)
+
+ async def do_release(self, expected_token: bytes) -> None:
+ if not bool(
+ await self.lua_release(
+ keys=[self.name], args=[expected_token], client=self.redis
+ )
+ ):
+ raise LockNotOwnedError("Cannot release a lock that's no longer owned")
+
+ def extend(
+ self, additional_time: Number, replace_ttl: bool = False
+ ) -> Awaitable[bool]:
+ """
+ Adds more time to an already acquired lock.
+
+ ``additional_time`` can be specified as an integer or a float, both
+ representing the number of seconds to add.
+
+ ``replace_ttl`` if False (the default), add `additional_time` to
+ the lock's existing ttl. If True, replace the lock's ttl with
+ `additional_time`.
+ """
+ if self.local.token is None:
+ raise LockError("Cannot extend an unlocked lock")
+ if self.timeout is None:
+ raise LockError("Cannot extend a lock with no timeout")
+ return self.do_extend(additional_time, replace_ttl)
+
+ async def do_extend(self, additional_time, replace_ttl) -> bool:
+ additional_time = int(additional_time * 1000)
+ if not bool(
+ await self.lua_extend(
+ keys=[self.name],
+ args=[self.local.token, additional_time, replace_ttl and "1" or "0"],
+ client=self.redis,
+ )
+ ):
+ raise LockNotOwnedError("Cannot extend a lock that's no longer owned")
+ return True
+
+ def reacquire(self) -> Awaitable[bool]:
+ """
+ Resets a TTL of an already acquired lock back to a timeout value.
+ """
+ if self.local.token is None:
+ raise LockError("Cannot reacquire an unlocked lock")
+ if self.timeout is None:
+ raise LockError("Cannot reacquire a lock with no timeout")
+ return self.do_reacquire()
+
+ async def do_reacquire(self) -> bool:
+ timeout = int(self.timeout * 1000)
+ if not bool(
+ await self.lua_reacquire(
+ keys=[self.name], args=[self.local.token, timeout], client=self.redis
+ )
+ ):
+ raise LockNotOwnedError("Cannot reacquire a lock that's no longer owned")
+ return True
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/retry.py b/python_embeded/Lib/site-packages/redis/asyncio/retry.py
new file mode 100644
index 0000000000000000000000000000000000000000..a20f8b4849b971caeaa965fa9e42fa62a138f2cb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/retry.py
@@ -0,0 +1,79 @@
+from asyncio import sleep
+from typing import TYPE_CHECKING, Any, Awaitable, Callable, Tuple, Type, TypeVar
+
+from redis.exceptions import ConnectionError, RedisError, TimeoutError
+
+if TYPE_CHECKING:
+ from redis.backoff import AbstractBackoff
+
+
+T = TypeVar("T")
+
+
+class Retry:
+ """Retry a specific number of times after a failure"""
+
+ __slots__ = "_backoff", "_retries", "_supported_errors"
+
+ def __init__(
+ self,
+ backoff: "AbstractBackoff",
+ retries: int,
+ supported_errors: Tuple[Type[RedisError], ...] = (
+ ConnectionError,
+ TimeoutError,
+ ),
+ ):
+ """
+ Initialize a `Retry` object with a `Backoff` object
+ that retries a maximum of `retries` times.
+ `retries` can be negative to retry forever.
+ You can specify the types of supported errors which trigger
+ a retry with the `supported_errors` parameter.
+ """
+ self._backoff = backoff
+ self._retries = retries
+ self._supported_errors = supported_errors
+
+ def update_supported_errors(self, specified_errors: list):
+ """
+ Updates the supported errors with the specified error types
+ """
+ self._supported_errors = tuple(
+ set(self._supported_errors + tuple(specified_errors))
+ )
+
+ def get_retries(self) -> int:
+ """
+ Get the number of retries.
+ """
+ return self._retries
+
+ def update_retries(self, value: int) -> None:
+ """
+ Set the number of retries.
+ """
+ self._retries = value
+
+ async def call_with_retry(
+ self, do: Callable[[], Awaitable[T]], fail: Callable[[RedisError], Any]
+ ) -> T:
+ """
+ Execute an operation that might fail and returns its result, or
+ raise the exception that was thrown depending on the `Backoff` object.
+ `do`: the operation to call. Expects no argument.
+ `fail`: the failure handler, expects the last error that was thrown
+ """
+ self._backoff.reset()
+ failures = 0
+ while True:
+ try:
+ return await do()
+ except self._supported_errors as error:
+ failures += 1
+ await fail(error)
+ if self._retries >= 0 and failures > self._retries:
+ raise error
+ backoff = self._backoff.compute(failures)
+ if backoff > 0:
+ await sleep(backoff)
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/sentinel.py b/python_embeded/Lib/site-packages/redis/asyncio/sentinel.py
new file mode 100644
index 0000000000000000000000000000000000000000..fae6875d828e62c0094a1d42401f845fe8c939f3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/sentinel.py
@@ -0,0 +1,389 @@
+import asyncio
+import random
+import weakref
+from typing import AsyncIterator, Iterable, Mapping, Optional, Sequence, Tuple, Type
+
+from redis.asyncio.client import Redis
+from redis.asyncio.connection import (
+ Connection,
+ ConnectionPool,
+ EncodableT,
+ SSLConnection,
+)
+from redis.commands import AsyncSentinelCommands
+from redis.exceptions import ConnectionError, ReadOnlyError, ResponseError, TimeoutError
+from redis.utils import str_if_bytes
+
+
+class MasterNotFoundError(ConnectionError):
+ pass
+
+
+class SlaveNotFoundError(ConnectionError):
+ pass
+
+
+class SentinelManagedConnection(Connection):
+ def __init__(self, **kwargs):
+ self.connection_pool = kwargs.pop("connection_pool")
+ super().__init__(**kwargs)
+
+ def __repr__(self):
+ s = f"<{self.__class__.__module__}.{self.__class__.__name__}"
+ if self.host:
+ host_info = f",host={self.host},port={self.port}"
+ s += host_info
+ return s + ")>"
+
+ async def connect_to(self, address):
+ self.host, self.port = address
+ await super().connect()
+ if self.connection_pool.check_connection:
+ await self.send_command("PING")
+ if str_if_bytes(await self.read_response()) != "PONG":
+ raise ConnectionError("PING failed")
+
+ async def _connect_retry(self):
+ if self._reader:
+ return # already connected
+ if self.connection_pool.is_master:
+ await self.connect_to(await self.connection_pool.get_master_address())
+ else:
+ async for slave in self.connection_pool.rotate_slaves():
+ try:
+ return await self.connect_to(slave)
+ except ConnectionError:
+ continue
+ raise SlaveNotFoundError # Never be here
+
+ async def connect(self):
+ return await self.retry.call_with_retry(
+ self._connect_retry,
+ lambda error: asyncio.sleep(0),
+ )
+
+ async def read_response(
+ self,
+ disable_decoding: bool = False,
+ timeout: Optional[float] = None,
+ *,
+ disconnect_on_error: Optional[float] = True,
+ push_request: Optional[bool] = False,
+ ):
+ try:
+ return await super().read_response(
+ disable_decoding=disable_decoding,
+ timeout=timeout,
+ disconnect_on_error=disconnect_on_error,
+ push_request=push_request,
+ )
+ except ReadOnlyError:
+ if self.connection_pool.is_master:
+ # When talking to a master, a ReadOnlyError when likely
+ # indicates that the previous master that we're still connected
+ # to has been demoted to a slave and there's a new master.
+ # calling disconnect will force the connection to re-query
+ # sentinel during the next connect() attempt.
+ await self.disconnect()
+ raise ConnectionError("The previous master is now a slave")
+ raise
+
+
+class SentinelManagedSSLConnection(SentinelManagedConnection, SSLConnection):
+ pass
+
+
+class SentinelConnectionPool(ConnectionPool):
+ """
+ Sentinel backed connection pool.
+
+ If ``check_connection`` flag is set to True, SentinelManagedConnection
+ sends a PING command right after establishing the connection.
+ """
+
+ def __init__(self, service_name, sentinel_manager, **kwargs):
+ kwargs["connection_class"] = kwargs.get(
+ "connection_class",
+ (
+ SentinelManagedSSLConnection
+ if kwargs.pop("ssl", False)
+ else SentinelManagedConnection
+ ),
+ )
+ self.is_master = kwargs.pop("is_master", True)
+ self.check_connection = kwargs.pop("check_connection", False)
+ super().__init__(**kwargs)
+ self.connection_kwargs["connection_pool"] = weakref.proxy(self)
+ self.service_name = service_name
+ self.sentinel_manager = sentinel_manager
+ self.master_address = None
+ self.slave_rr_counter = None
+
+ def __repr__(self):
+ return (
+ f"<{self.__class__.__module__}.{self.__class__.__name__}"
+ f"(service={self.service_name}({self.is_master and 'master' or 'slave'}))>"
+ )
+
+ def reset(self):
+ super().reset()
+ self.master_address = None
+ self.slave_rr_counter = None
+
+ def owns_connection(self, connection: Connection):
+ check = not self.is_master or (
+ self.is_master and self.master_address == (connection.host, connection.port)
+ )
+ return check and super().owns_connection(connection)
+
+ async def get_master_address(self):
+ master_address = await self.sentinel_manager.discover_master(self.service_name)
+ if self.is_master:
+ if self.master_address != master_address:
+ self.master_address = master_address
+ # disconnect any idle connections so that they reconnect
+ # to the new master the next time that they are used.
+ await self.disconnect(inuse_connections=False)
+ return master_address
+
+ async def rotate_slaves(self) -> AsyncIterator:
+ """Round-robin slave balancer"""
+ slaves = await self.sentinel_manager.discover_slaves(self.service_name)
+ if slaves:
+ if self.slave_rr_counter is None:
+ self.slave_rr_counter = random.randint(0, len(slaves) - 1)
+ for _ in range(len(slaves)):
+ self.slave_rr_counter = (self.slave_rr_counter + 1) % len(slaves)
+ slave = slaves[self.slave_rr_counter]
+ yield slave
+ # Fallback to the master connection
+ try:
+ yield await self.get_master_address()
+ except MasterNotFoundError:
+ pass
+ raise SlaveNotFoundError(f"No slave found for {self.service_name!r}")
+
+
+class Sentinel(AsyncSentinelCommands):
+ """
+ Redis Sentinel cluster client
+
+ >>> from redis.sentinel import Sentinel
+ >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1)
+ >>> master = sentinel.master_for('mymaster', socket_timeout=0.1)
+ >>> await master.set('foo', 'bar')
+ >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1)
+ >>> await slave.get('foo')
+ b'bar'
+
+ ``sentinels`` is a list of sentinel nodes. Each node is represented by
+ a pair (hostname, port).
+
+ ``min_other_sentinels`` defined a minimum number of peers for a sentinel.
+ When querying a sentinel, if it doesn't meet this threshold, responses
+ from that sentinel won't be considered valid.
+
+ ``sentinel_kwargs`` is a dictionary of connection arguments used when
+ connecting to sentinel instances. Any argument that can be passed to
+ a normal Redis connection can be specified here. If ``sentinel_kwargs`` is
+ not specified, any socket_timeout and socket_keepalive options specified
+ in ``connection_kwargs`` will be used.
+
+ ``connection_kwargs`` are keyword arguments that will be used when
+ establishing a connection to a Redis server.
+ """
+
+ def __init__(
+ self,
+ sentinels,
+ min_other_sentinels=0,
+ sentinel_kwargs=None,
+ force_master_ip=None,
+ **connection_kwargs,
+ ):
+ # if sentinel_kwargs isn't defined, use the socket_* options from
+ # connection_kwargs
+ if sentinel_kwargs is None:
+ sentinel_kwargs = {
+ k: v for k, v in connection_kwargs.items() if k.startswith("socket_")
+ }
+ self.sentinel_kwargs = sentinel_kwargs
+
+ self.sentinels = [
+ Redis(host=hostname, port=port, **self.sentinel_kwargs)
+ for hostname, port in sentinels
+ ]
+ self.min_other_sentinels = min_other_sentinels
+ self.connection_kwargs = connection_kwargs
+ self._force_master_ip = force_master_ip
+
+ async def execute_command(self, *args, **kwargs):
+ """
+ Execute Sentinel command in sentinel nodes.
+ once - If set to True, then execute the resulting command on a single
+ node at random, rather than across the entire sentinel cluster.
+ """
+ once = bool(kwargs.get("once", False))
+ if "once" in kwargs.keys():
+ kwargs.pop("once")
+
+ if once:
+ await random.choice(self.sentinels).execute_command(*args, **kwargs)
+ else:
+ tasks = [
+ asyncio.Task(sentinel.execute_command(*args, **kwargs))
+ for sentinel in self.sentinels
+ ]
+ await asyncio.gather(*tasks)
+ return True
+
+ def __repr__(self):
+ sentinel_addresses = []
+ for sentinel in self.sentinels:
+ sentinel_addresses.append(
+ f"{sentinel.connection_pool.connection_kwargs['host']}:"
+ f"{sentinel.connection_pool.connection_kwargs['port']}"
+ )
+ return (
+ f"<{self.__class__}.{self.__class__.__name__}"
+ f"(sentinels=[{','.join(sentinel_addresses)}])>"
+ )
+
+ def check_master_state(self, state: dict, service_name: str) -> bool:
+ if not state["is_master"] or state["is_sdown"] or state["is_odown"]:
+ return False
+ # Check if our sentinel doesn't see other nodes
+ if state["num-other-sentinels"] < self.min_other_sentinels:
+ return False
+ return True
+
+ async def discover_master(self, service_name: str):
+ """
+ Asks sentinel servers for the Redis master's address corresponding
+ to the service labeled ``service_name``.
+
+ Returns a pair (address, port) or raises MasterNotFoundError if no
+ master is found.
+ """
+ collected_errors = list()
+ for sentinel_no, sentinel in enumerate(self.sentinels):
+ try:
+ masters = await sentinel.sentinel_masters()
+ except (ConnectionError, TimeoutError) as e:
+ collected_errors.append(f"{sentinel} - {e!r}")
+ continue
+ state = masters.get(service_name)
+ if state and self.check_master_state(state, service_name):
+ # Put this sentinel at the top of the list
+ self.sentinels[0], self.sentinels[sentinel_no] = (
+ sentinel,
+ self.sentinels[0],
+ )
+
+ ip = (
+ self._force_master_ip
+ if self._force_master_ip is not None
+ else state["ip"]
+ )
+ return ip, state["port"]
+
+ error_info = ""
+ if len(collected_errors) > 0:
+ error_info = f" : {', '.join(collected_errors)}"
+ raise MasterNotFoundError(f"No master found for {service_name!r}{error_info}")
+
+ def filter_slaves(
+ self, slaves: Iterable[Mapping]
+ ) -> Sequence[Tuple[EncodableT, EncodableT]]:
+ """Remove slaves that are in an ODOWN or SDOWN state"""
+ slaves_alive = []
+ for slave in slaves:
+ if slave["is_odown"] or slave["is_sdown"]:
+ continue
+ slaves_alive.append((slave["ip"], slave["port"]))
+ return slaves_alive
+
+ async def discover_slaves(
+ self, service_name: str
+ ) -> Sequence[Tuple[EncodableT, EncodableT]]:
+ """Returns a list of alive slaves for service ``service_name``"""
+ for sentinel in self.sentinels:
+ try:
+ slaves = await sentinel.sentinel_slaves(service_name)
+ except (ConnectionError, ResponseError, TimeoutError):
+ continue
+ slaves = self.filter_slaves(slaves)
+ if slaves:
+ return slaves
+ return []
+
+ def master_for(
+ self,
+ service_name: str,
+ redis_class: Type[Redis] = Redis,
+ connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool,
+ **kwargs,
+ ):
+ """
+ Returns a redis client instance for the ``service_name`` master.
+ Sentinel client will detect failover and reconnect Redis clients
+ automatically.
+
+ A :py:class:`~redis.sentinel.SentinelConnectionPool` class is
+ used to retrieve the master's address before establishing a new
+ connection.
+
+ NOTE: If the master's address has changed, any cached connections to
+ the old master are closed.
+
+ By default clients will be a :py:class:`~redis.Redis` instance.
+ Specify a different class to the ``redis_class`` argument if you
+ desire something different.
+
+ The ``connection_pool_class`` specifies the connection pool to
+ use. The :py:class:`~redis.sentinel.SentinelConnectionPool`
+ will be used by default.
+
+ All other keyword arguments are merged with any connection_kwargs
+ passed to this class and passed to the connection pool as keyword
+ arguments to be used to initialize Redis connections.
+ """
+ kwargs["is_master"] = True
+ connection_kwargs = dict(self.connection_kwargs)
+ connection_kwargs.update(kwargs)
+
+ connection_pool = connection_pool_class(service_name, self, **connection_kwargs)
+ # The Redis object "owns" the pool
+ return redis_class.from_pool(connection_pool)
+
+ def slave_for(
+ self,
+ service_name: str,
+ redis_class: Type[Redis] = Redis,
+ connection_pool_class: Type[SentinelConnectionPool] = SentinelConnectionPool,
+ **kwargs,
+ ):
+ """
+ Returns redis client instance for the ``service_name`` slave(s).
+
+ A SentinelConnectionPool class is used to retrieve the slave's
+ address before establishing a new connection.
+
+ By default clients will be a :py:class:`~redis.Redis` instance.
+ Specify a different class to the ``redis_class`` argument if you
+ desire something different.
+
+ The ``connection_pool_class`` specifies the connection pool to use.
+ The SentinelConnectionPool will be used by default.
+
+ All other keyword arguments are merged with any connection_kwargs
+ passed to this class and passed to the connection pool as keyword
+ arguments to be used to initialize Redis connections.
+ """
+ kwargs["is_master"] = False
+ connection_kwargs = dict(self.connection_kwargs)
+ connection_kwargs.update(kwargs)
+
+ connection_pool = connection_pool_class(service_name, self, **connection_kwargs)
+ # The Redis object "owns" the pool
+ return redis_class.from_pool(connection_pool)
diff --git a/python_embeded/Lib/site-packages/redis/asyncio/utils.py b/python_embeded/Lib/site-packages/redis/asyncio/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa014514ecdd75ce0efda371529163909727ea63
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/asyncio/utils.py
@@ -0,0 +1,28 @@
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from redis.asyncio.client import Pipeline, Redis
+
+
+def from_url(url, **kwargs):
+ """
+ Returns an active Redis client generated from the given database URL.
+
+ Will attempt to extract the database id from the path url fragment, if
+ none is provided.
+ """
+ from redis.asyncio.client import Redis
+
+ return Redis.from_url(url, **kwargs)
+
+
+class pipeline: # noqa: N801
+ def __init__(self, redis_obj: "Redis"):
+ self.p: "Pipeline" = redis_obj.pipeline()
+
+ async def __aenter__(self) -> "Pipeline":
+ return self.p
+
+ async def __aexit__(self, exc_type, exc_value, traceback):
+ await self.p.execute()
+ del self.p
diff --git a/python_embeded/Lib/site-packages/redis/auth/err.py b/python_embeded/Lib/site-packages/redis/auth/err.py
new file mode 100644
index 0000000000000000000000000000000000000000..743dab18fee6b92027272fe562f42cf1b665742d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/auth/err.py
@@ -0,0 +1,31 @@
+from typing import Iterable
+
+
+class RequestTokenErr(Exception):
+ """
+ Represents an exception during token request.
+ """
+
+ def __init__(self, *args):
+ super().__init__(*args)
+
+
+class InvalidTokenSchemaErr(Exception):
+ """
+ Represents an exception related to invalid token schema.
+ """
+
+ def __init__(self, missing_fields: Iterable[str] = []):
+ super().__init__(
+ "Unexpected token schema. Following fields are missing: "
+ + ", ".join(missing_fields)
+ )
+
+
+class TokenRenewalErr(Exception):
+ """
+ Represents an exception during token renewal process.
+ """
+
+ def __init__(self, *args):
+ super().__init__(*args)
diff --git a/python_embeded/Lib/site-packages/redis/commands/search/__init__.py b/python_embeded/Lib/site-packages/redis/commands/search/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2bb23b76d9efb454ed8aed0ffa649cff3d21431
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/search/__init__.py
@@ -0,0 +1,189 @@
+import redis
+
+from ...asyncio.client import Pipeline as AsyncioPipeline
+from .commands import (
+ AGGREGATE_CMD,
+ CONFIG_CMD,
+ INFO_CMD,
+ PROFILE_CMD,
+ SEARCH_CMD,
+ SPELLCHECK_CMD,
+ SYNDUMP_CMD,
+ AsyncSearchCommands,
+ SearchCommands,
+)
+
+
+class Search(SearchCommands):
+ """
+ Create a client for talking to search.
+ It abstracts the API of the module and lets you just use the engine.
+ """
+
+ class BatchIndexer:
+ """
+ A batch indexer allows you to automatically batch
+ document indexing in pipelines, flushing it every N documents.
+ """
+
+ def __init__(self, client, chunk_size=1000):
+ self.client = client
+ self.execute_command = client.execute_command
+ self._pipeline = client.pipeline(transaction=False, shard_hint=None)
+ self.total = 0
+ self.chunk_size = chunk_size
+ self.current_chunk = 0
+
+ def __del__(self):
+ if self.current_chunk:
+ self.commit()
+
+ def add_document(
+ self,
+ doc_id,
+ nosave=False,
+ score=1.0,
+ payload=None,
+ replace=False,
+ partial=False,
+ no_create=False,
+ **fields,
+ ):
+ """
+ Add a document to the batch query
+ """
+ self.client._add_document(
+ doc_id,
+ conn=self._pipeline,
+ nosave=nosave,
+ score=score,
+ payload=payload,
+ replace=replace,
+ partial=partial,
+ no_create=no_create,
+ **fields,
+ )
+ self.current_chunk += 1
+ self.total += 1
+ if self.current_chunk >= self.chunk_size:
+ self.commit()
+
+ def add_document_hash(self, doc_id, score=1.0, replace=False):
+ """
+ Add a hash to the batch query
+ """
+ self.client._add_document_hash(
+ doc_id, conn=self._pipeline, score=score, replace=replace
+ )
+ self.current_chunk += 1
+ self.total += 1
+ if self.current_chunk >= self.chunk_size:
+ self.commit()
+
+ def commit(self):
+ """
+ Manually commit and flush the batch indexing query
+ """
+ self._pipeline.execute()
+ self.current_chunk = 0
+
+ def __init__(self, client, index_name="idx"):
+ """
+ Create a new Client for the given index_name.
+ The default name is `idx`
+
+ If conn is not None, we employ an already existing redis connection
+ """
+ self._MODULE_CALLBACKS = {}
+ self.client = client
+ self.index_name = index_name
+ self.execute_command = client.execute_command
+ self._pipeline = client.pipeline
+ self._RESP2_MODULE_CALLBACKS = {
+ INFO_CMD: self._parse_info,
+ SEARCH_CMD: self._parse_search,
+ AGGREGATE_CMD: self._parse_aggregate,
+ PROFILE_CMD: self._parse_profile,
+ SPELLCHECK_CMD: self._parse_spellcheck,
+ CONFIG_CMD: self._parse_config_get,
+ SYNDUMP_CMD: self._parse_syndump,
+ }
+
+ def pipeline(self, transaction=True, shard_hint=None):
+ """Creates a pipeline for the SEARCH module, that can be used for executing
+ SEARCH commands, as well as classic core commands.
+ """
+ p = Pipeline(
+ connection_pool=self.client.connection_pool,
+ response_callbacks=self._MODULE_CALLBACKS,
+ transaction=transaction,
+ shard_hint=shard_hint,
+ )
+ p.index_name = self.index_name
+ return p
+
+
+class AsyncSearch(Search, AsyncSearchCommands):
+ class BatchIndexer(Search.BatchIndexer):
+ """
+ A batch indexer allows you to automatically batch
+ document indexing in pipelines, flushing it every N documents.
+ """
+
+ async def add_document(
+ self,
+ doc_id,
+ nosave=False,
+ score=1.0,
+ payload=None,
+ replace=False,
+ partial=False,
+ no_create=False,
+ **fields,
+ ):
+ """
+ Add a document to the batch query
+ """
+ self.client._add_document(
+ doc_id,
+ conn=self._pipeline,
+ nosave=nosave,
+ score=score,
+ payload=payload,
+ replace=replace,
+ partial=partial,
+ no_create=no_create,
+ **fields,
+ )
+ self.current_chunk += 1
+ self.total += 1
+ if self.current_chunk >= self.chunk_size:
+ await self.commit()
+
+ async def commit(self):
+ """
+ Manually commit and flush the batch indexing query
+ """
+ await self._pipeline.execute()
+ self.current_chunk = 0
+
+ def pipeline(self, transaction=True, shard_hint=None):
+ """Creates a pipeline for the SEARCH module, that can be used for executing
+ SEARCH commands, as well as classic core commands.
+ """
+ p = AsyncPipeline(
+ connection_pool=self.client.connection_pool,
+ response_callbacks=self._MODULE_CALLBACKS,
+ transaction=transaction,
+ shard_hint=shard_hint,
+ )
+ p.index_name = self.index_name
+ return p
+
+
+class Pipeline(SearchCommands, redis.client.Pipeline):
+ """Pipeline for the module."""
+
+
+class AsyncPipeline(AsyncSearchCommands, AsyncioPipeline, Pipeline):
+ """AsyncPipeline for the module."""
diff --git a/python_embeded/Lib/site-packages/redis/commands/search/_util.py b/python_embeded/Lib/site-packages/redis/commands/search/_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..191600d7c683d9503b000faf84f0527412c50ee7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/search/_util.py
@@ -0,0 +1,7 @@
+def to_string(s, encoding: str = "utf-8"):
+ if isinstance(s, str):
+ return s
+ elif isinstance(s, bytes):
+ return s.decode(encoding, "ignore")
+ else:
+ return s # Not a string we care about
diff --git a/python_embeded/Lib/site-packages/redis/commands/search/reducers.py b/python_embeded/Lib/site-packages/redis/commands/search/reducers.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b60f2328343407c0d16080015c71de185bed819
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/search/reducers.py
@@ -0,0 +1,182 @@
+from typing import Union
+
+from .aggregation import Asc, Desc, Reducer, SortDirection
+
+
+class FieldOnlyReducer(Reducer):
+ """See https://redis.io/docs/interact/search-and-query/search/aggregations/"""
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+ self._field = field
+
+
+class count(Reducer):
+ """
+ Counts the number of results in the group
+ """
+
+ NAME = "COUNT"
+
+ def __init__(self) -> None:
+ super().__init__()
+
+
+class sum(FieldOnlyReducer):
+ """
+ Calculates the sum of all the values in the given fields within the group
+ """
+
+ NAME = "SUM"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class min(FieldOnlyReducer):
+ """
+ Calculates the smallest value in the given field within the group
+ """
+
+ NAME = "MIN"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class max(FieldOnlyReducer):
+ """
+ Calculates the largest value in the given field within the group
+ """
+
+ NAME = "MAX"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class avg(FieldOnlyReducer):
+ """
+ Calculates the mean value in the given field within the group
+ """
+
+ NAME = "AVG"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class tolist(FieldOnlyReducer):
+ """
+ Returns all the matched properties in a list
+ """
+
+ NAME = "TOLIST"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class count_distinct(FieldOnlyReducer):
+ """
+ Calculate the number of distinct values contained in all the results in
+ the group for the given field
+ """
+
+ NAME = "COUNT_DISTINCT"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class count_distinctish(FieldOnlyReducer):
+ """
+ Calculate the number of distinct values contained in all the results in the
+ group for the given field. This uses a faster algorithm than
+ `count_distinct` but is less accurate
+ """
+
+ NAME = "COUNT_DISTINCTISH"
+
+
+class quantile(Reducer):
+ """
+ Return the value for the nth percentile within the range of values for the
+ field within the group.
+ """
+
+ NAME = "QUANTILE"
+
+ def __init__(self, field: str, pct: float) -> None:
+ super().__init__(field, str(pct))
+ self._field = field
+
+
+class stddev(FieldOnlyReducer):
+ """
+ Return the standard deviation for the values within the group
+ """
+
+ NAME = "STDDEV"
+
+ def __init__(self, field: str) -> None:
+ super().__init__(field)
+
+
+class first_value(Reducer):
+ """
+ Selects the first value within the group according to sorting parameters
+ """
+
+ NAME = "FIRST_VALUE"
+
+ def __init__(self, field: str, *byfields: Union[Asc, Desc]) -> None:
+ """
+ Selects the first value of the given field within the group.
+
+ ### Parameter
+
+ - **field**: Source field used for the value
+ - **byfields**: How to sort the results. This can be either the
+ *class* of `aggregation.Asc` or `aggregation.Desc` in which
+ case the field `field` is also used as the sort input.
+
+ `byfields` can also be one or more *instances* of `Asc` or `Desc`
+ indicating the sort order for these fields
+ """
+
+ fieldstrs = []
+ if (
+ len(byfields) == 1
+ and isinstance(byfields[0], type)
+ and issubclass(byfields[0], SortDirection)
+ ):
+ byfields = [byfields[0](field)]
+
+ for f in byfields:
+ fieldstrs += [f.field, f.DIRSTRING]
+
+ args = [field]
+ if fieldstrs:
+ args += ["BY"] + fieldstrs
+ super().__init__(*args)
+ self._field = field
+
+
+class random_sample(Reducer):
+ """
+ Returns a random sample of items from the dataset, from the given property
+ """
+
+ NAME = "RANDOM_SAMPLE"
+
+ def __init__(self, field: str, size: int) -> None:
+ """
+ ### Parameter
+
+ **field**: Field to sample from
+ **size**: Return this many items (can be less)
+ """
+ args = [field, str(size)]
+ super().__init__(*args)
+ self._field = field
diff --git a/python_embeded/Lib/site-packages/redis/commands/search/result.py b/python_embeded/Lib/site-packages/redis/commands/search/result.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2c7efb71fb06d839aa3c4924ba33f680cf2aa4a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/search/result.py
@@ -0,0 +1,87 @@
+from typing import Optional
+
+from ._util import to_string
+from .document import Document
+
+
+class Result:
+ """
+ Represents the result of a search query, and has an array of Document
+ objects
+ """
+
+ def __init__(
+ self,
+ res,
+ hascontent,
+ duration=0,
+ has_payload=False,
+ with_scores=False,
+ field_encodings: Optional[dict] = None,
+ ):
+ """
+ - duration: the execution time of the query
+ - has_payload: whether the query has payloads
+ - with_scores: whether the query has scores
+ - field_encodings: a dictionary of field encodings if any is provided
+ """
+
+ self.total = res[0]
+ self.duration = duration
+ self.docs = []
+
+ step = 1
+ if hascontent:
+ step = step + 1
+ if has_payload:
+ step = step + 1
+ if with_scores:
+ step = step + 1
+
+ offset = 2 if with_scores else 1
+
+ for i in range(1, len(res), step):
+ id = to_string(res[i])
+ payload = to_string(res[i + offset]) if has_payload else None
+ # fields_offset = 2 if has_payload else 1
+ fields_offset = offset + 1 if has_payload else offset
+ score = float(res[i + 1]) if with_scores else None
+
+ fields = {}
+ if hascontent and res[i + fields_offset] is not None:
+ keys = map(to_string, res[i + fields_offset][::2])
+ values = res[i + fields_offset][1::2]
+
+ for key, value in zip(keys, values):
+ if field_encodings is None or key not in field_encodings:
+ fields[key] = to_string(value)
+ continue
+
+ encoding = field_encodings[key]
+
+ # If the encoding is None, we don't need to decode the value
+ if encoding is None:
+ fields[key] = value
+ else:
+ fields[key] = to_string(value, encoding=encoding)
+
+ try:
+ del fields["id"]
+ except KeyError:
+ pass
+
+ try:
+ fields["json"] = fields["$"]
+ del fields["$"]
+ except KeyError:
+ pass
+
+ doc = (
+ Document(id, score=score, payload=payload, **fields)
+ if with_scores
+ else Document(id, payload=payload, **fields)
+ )
+ self.docs.append(doc)
+
+ def __repr__(self) -> str:
+ return f"Result{{{self.total} total, docs: {self.docs}}}"
diff --git a/python_embeded/Lib/site-packages/redis/commands/search/suggestion.py b/python_embeded/Lib/site-packages/redis/commands/search/suggestion.py
new file mode 100644
index 0000000000000000000000000000000000000000..499c8d917eec527af45740ccdb0351b0ea7ab9c4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/search/suggestion.py
@@ -0,0 +1,55 @@
+from typing import Optional
+
+from ._util import to_string
+
+
+class Suggestion:
+ """
+ Represents a single suggestion being sent or returned from the
+ autocomplete server
+ """
+
+ def __init__(
+ self, string: str, score: float = 1.0, payload: Optional[str] = None
+ ) -> None:
+ self.string = to_string(string)
+ self.payload = to_string(payload)
+ self.score = score
+
+ def __repr__(self) -> str:
+ return self.string
+
+
+class SuggestionParser:
+ """
+ Internal class used to parse results from the `SUGGET` command.
+ This needs to consume either 1, 2, or 3 values at a time from
+ the return value depending on what objects were requested
+ """
+
+ def __init__(self, with_scores: bool, with_payloads: bool, ret) -> None:
+ self.with_scores = with_scores
+ self.with_payloads = with_payloads
+
+ if with_scores and with_payloads:
+ self.sugsize = 3
+ self._scoreidx = 1
+ self._payloadidx = 2
+ elif with_scores:
+ self.sugsize = 2
+ self._scoreidx = 1
+ elif with_payloads:
+ self.sugsize = 2
+ self._payloadidx = 1
+ else:
+ self.sugsize = 1
+ self._scoreidx = -1
+
+ self._sugs = ret
+
+ def __iter__(self):
+ for i in range(0, len(self._sugs), self.sugsize):
+ ss = self._sugs[i]
+ score = float(self._sugs[i + self._scoreidx]) if self.with_scores else 1.0
+ payload = self._sugs[i + self._payloadidx] if self.with_payloads else None
+ yield Suggestion(ss, score, payload)
diff --git a/python_embeded/Lib/site-packages/redis/commands/timeseries/__init__.py b/python_embeded/Lib/site-packages/redis/commands/timeseries/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fbf82117203354736b2fda7bd10f1051b55b0b9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/timeseries/__init__.py
@@ -0,0 +1,108 @@
+import redis
+from redis._parsers.helpers import bool_ok
+
+from ..helpers import get_protocol_version, parse_to_list
+from .commands import (
+ ALTER_CMD,
+ CREATE_CMD,
+ CREATERULE_CMD,
+ DEL_CMD,
+ DELETERULE_CMD,
+ GET_CMD,
+ INFO_CMD,
+ MGET_CMD,
+ MRANGE_CMD,
+ MREVRANGE_CMD,
+ QUERYINDEX_CMD,
+ RANGE_CMD,
+ REVRANGE_CMD,
+ TimeSeriesCommands,
+)
+from .info import TSInfo
+from .utils import parse_get, parse_m_get, parse_m_range, parse_range
+
+
+class TimeSeries(TimeSeriesCommands):
+ """
+ This class subclasses redis-py's `Redis` and implements RedisTimeSeries's
+ commands (prefixed with "ts").
+ The client allows to interact with RedisTimeSeries and use all of it's
+ functionality.
+ """
+
+ def __init__(self, client=None, **kwargs):
+ """Create a new RedisTimeSeries client."""
+ # Set the module commands' callbacks
+ self._MODULE_CALLBACKS = {
+ ALTER_CMD: bool_ok,
+ CREATE_CMD: bool_ok,
+ CREATERULE_CMD: bool_ok,
+ DELETERULE_CMD: bool_ok,
+ }
+
+ _RESP2_MODULE_CALLBACKS = {
+ DEL_CMD: int,
+ GET_CMD: parse_get,
+ INFO_CMD: TSInfo,
+ MGET_CMD: parse_m_get,
+ MRANGE_CMD: parse_m_range,
+ MREVRANGE_CMD: parse_m_range,
+ RANGE_CMD: parse_range,
+ REVRANGE_CMD: parse_range,
+ QUERYINDEX_CMD: parse_to_list,
+ }
+ _RESP3_MODULE_CALLBACKS = {}
+
+ self.client = client
+ self.execute_command = client.execute_command
+
+ if get_protocol_version(self.client) in ["3", 3]:
+ self._MODULE_CALLBACKS.update(_RESP3_MODULE_CALLBACKS)
+ else:
+ self._MODULE_CALLBACKS.update(_RESP2_MODULE_CALLBACKS)
+
+ for k, v in self._MODULE_CALLBACKS.items():
+ self.client.set_response_callback(k, v)
+
+ def pipeline(self, transaction=True, shard_hint=None):
+ """Creates a pipeline for the TimeSeries module, that can be used
+ for executing only TimeSeries commands and core commands.
+
+ Usage example:
+
+ r = redis.Redis()
+ pipe = r.ts().pipeline()
+ for i in range(100):
+ pipeline.add("with_pipeline", i, 1.1 * i)
+ pipeline.execute()
+
+ """
+ if isinstance(self.client, redis.RedisCluster):
+ p = ClusterPipeline(
+ nodes_manager=self.client.nodes_manager,
+ commands_parser=self.client.commands_parser,
+ startup_nodes=self.client.nodes_manager.startup_nodes,
+ result_callbacks=self.client.result_callbacks,
+ cluster_response_callbacks=self.client.cluster_response_callbacks,
+ cluster_error_retry_attempts=self.client.retry.get_retries(),
+ read_from_replicas=self.client.read_from_replicas,
+ reinitialize_steps=self.client.reinitialize_steps,
+ lock=self.client._lock,
+ )
+
+ else:
+ p = Pipeline(
+ connection_pool=self.client.connection_pool,
+ response_callbacks=self._MODULE_CALLBACKS,
+ transaction=transaction,
+ shard_hint=shard_hint,
+ )
+ return p
+
+
+class ClusterPipeline(TimeSeriesCommands, redis.cluster.ClusterPipeline):
+ """Cluster pipeline for the module."""
+
+
+class Pipeline(TimeSeriesCommands, redis.client.Pipeline):
+ """Pipeline for the module."""
diff --git a/python_embeded/Lib/site-packages/redis/commands/timeseries/commands.py b/python_embeded/Lib/site-packages/redis/commands/timeseries/commands.py
new file mode 100644
index 0000000000000000000000000000000000000000..b0cb8642373bb95d0f0e20385ab66cd770da34ab
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/timeseries/commands.py
@@ -0,0 +1,1136 @@
+from typing import Dict, List, Optional, Tuple, Union
+
+from redis.exceptions import DataError
+from redis.typing import KeyT, Number
+
+ADD_CMD = "TS.ADD"
+ALTER_CMD = "TS.ALTER"
+CREATERULE_CMD = "TS.CREATERULE"
+CREATE_CMD = "TS.CREATE"
+DECRBY_CMD = "TS.DECRBY"
+DELETERULE_CMD = "TS.DELETERULE"
+DEL_CMD = "TS.DEL"
+GET_CMD = "TS.GET"
+INCRBY_CMD = "TS.INCRBY"
+INFO_CMD = "TS.INFO"
+MADD_CMD = "TS.MADD"
+MGET_CMD = "TS.MGET"
+MRANGE_CMD = "TS.MRANGE"
+MREVRANGE_CMD = "TS.MREVRANGE"
+QUERYINDEX_CMD = "TS.QUERYINDEX"
+RANGE_CMD = "TS.RANGE"
+REVRANGE_CMD = "TS.REVRANGE"
+
+
+class TimeSeriesCommands:
+ """RedisTimeSeries Commands."""
+
+ def create(
+ self,
+ key: KeyT,
+ retention_msecs: Optional[int] = None,
+ uncompressed: Optional[bool] = False,
+ labels: Optional[Dict[str, str]] = None,
+ chunk_size: Optional[int] = None,
+ duplicate_policy: Optional[str] = None,
+ ignore_max_time_diff: Optional[int] = None,
+ ignore_max_val_diff: Optional[Number] = None,
+ ):
+ """
+ Create a new time-series.
+
+ For more information see https://redis.io/commands/ts.create/
+
+ Args:
+ key:
+ The time-series key.
+ retention_msecs:
+ Maximum age for samples, compared to the highest reported timestamp in
+ milliseconds. If `None` or `0` is passed, the series is not trimmed at
+ all.
+ uncompressed:
+ Changes data storage from compressed (default) to uncompressed.
+ labels:
+ A dictionary of label-value pairs that represent metadata labels of the
+ key.
+ chunk_size:
+ Memory size, in bytes, allocated for each data chunk. Must be a multiple
+ of 8 in the range `[48..1048576]`. In earlier versions of the module the
+ minimum value was different.
+ duplicate_policy:
+ Policy for handling multiple samples with identical timestamps. Can be
+ one of:
+
+ - 'block': An error will occur and the new value will be ignored.
+ - 'first': Ignore the new value.
+ - 'last': Override with the latest value.
+ - 'min': Only override if the value is lower than the existing value.
+ - 'max': Only override if the value is higher than the existing value.
+ - 'sum': If a previous sample exists, add the new sample to it so
+ that the updated value is equal to (previous + new). If no
+ previous sample exists, set the updated value equal to the new
+ value.
+
+ ignore_max_time_diff:
+ A non-negative integer value, in milliseconds, that sets an ignore
+ threshold for added timestamps. If the difference between the last
+ timestamp and the new timestamp is lower than this threshold, the new
+ entry is ignored. Only applicable if `duplicate_policy` is set to
+ `last`, and if `ignore_max_val_diff` is also set. Available since
+ RedisTimeSeries version 1.12.0.
+ ignore_max_val_diff:
+ A non-negative floating point value, that sets an ignore threshold for
+ added values. If the difference between the last value and the new value
+ is lower than this threshold, the new entry is ignored. Only applicable
+ if `duplicate_policy` is set to `last`, and if `ignore_max_time_diff` is
+ also set. Available since RedisTimeSeries version 1.12.0.
+ """
+ params = [key]
+ self._append_retention(params, retention_msecs)
+ self._append_uncompressed(params, uncompressed)
+ self._append_chunk_size(params, chunk_size)
+ self._append_duplicate_policy(params, duplicate_policy)
+ self._append_labels(params, labels)
+ self._append_insertion_filters(
+ params, ignore_max_time_diff, ignore_max_val_diff
+ )
+
+ return self.execute_command(CREATE_CMD, *params)
+
+ def alter(
+ self,
+ key: KeyT,
+ retention_msecs: Optional[int] = None,
+ labels: Optional[Dict[str, str]] = None,
+ chunk_size: Optional[int] = None,
+ duplicate_policy: Optional[str] = None,
+ ignore_max_time_diff: Optional[int] = None,
+ ignore_max_val_diff: Optional[Number] = None,
+ ):
+ """
+ Update an existing time series.
+
+ For more information see https://redis.io/commands/ts.alter/
+
+ Args:
+ key:
+ The time-series key.
+ retention_msecs:
+ Maximum age for samples, compared to the highest reported timestamp in
+ milliseconds. If `None` or `0` is passed, the series is not trimmed at
+ all.
+ labels:
+ A dictionary of label-value pairs that represent metadata labels of the
+ key.
+ chunk_size:
+ Memory size, in bytes, allocated for each data chunk. Must be a multiple
+ of 8 in the range `[48..1048576]`. In earlier versions of the module the
+ minimum value was different. Changing this value does not affect
+ existing chunks.
+ duplicate_policy:
+ Policy for handling multiple samples with identical timestamps. Can be
+ one of:
+
+ - 'block': An error will occur and the new value will be ignored.
+ - 'first': Ignore the new value.
+ - 'last': Override with the latest value.
+ - 'min': Only override if the value is lower than the existing value.
+ - 'max': Only override if the value is higher than the existing value.
+ - 'sum': If a previous sample exists, add the new sample to it so
+ that the updated value is equal to (previous + new). If no
+ previous sample exists, set the updated value equal to the new
+ value.
+
+ ignore_max_time_diff:
+ A non-negative integer value, in milliseconds, that sets an ignore
+ threshold for added timestamps. If the difference between the last
+ timestamp and the new timestamp is lower than this threshold, the new
+ entry is ignored. Only applicable if `duplicate_policy` is set to
+ `last`, and if `ignore_max_val_diff` is also set. Available since
+ RedisTimeSeries version 1.12.0.
+ ignore_max_val_diff:
+ A non-negative floating point value, that sets an ignore threshold for
+ added values. If the difference between the last value and the new value
+ is lower than this threshold, the new entry is ignored. Only applicable
+ if `duplicate_policy` is set to `last`, and if `ignore_max_time_diff` is
+ also set. Available since RedisTimeSeries version 1.12.0.
+ """
+ params = [key]
+ self._append_retention(params, retention_msecs)
+ self._append_chunk_size(params, chunk_size)
+ self._append_duplicate_policy(params, duplicate_policy)
+ self._append_labels(params, labels)
+ self._append_insertion_filters(
+ params, ignore_max_time_diff, ignore_max_val_diff
+ )
+
+ return self.execute_command(ALTER_CMD, *params)
+
+ def add(
+ self,
+ key: KeyT,
+ timestamp: Union[int, str],
+ value: Number,
+ retention_msecs: Optional[int] = None,
+ uncompressed: Optional[bool] = False,
+ labels: Optional[Dict[str, str]] = None,
+ chunk_size: Optional[int] = None,
+ duplicate_policy: Optional[str] = None,
+ ignore_max_time_diff: Optional[int] = None,
+ ignore_max_val_diff: Optional[Number] = None,
+ on_duplicate: Optional[str] = None,
+ ):
+ """
+ Append a sample to a time series. When the specified key does not exist, a new
+ time series is created.
+
+ For more information see https://redis.io/commands/ts.add/
+
+ Args:
+ key:
+ The time-series key.
+ timestamp:
+ Timestamp of the sample. `*` can be used for automatic timestamp (using
+ the system clock).
+ value:
+ Numeric data value of the sample.
+ retention_msecs:
+ Maximum age for samples, compared to the highest reported timestamp in
+ milliseconds. If `None` or `0` is passed, the series is not trimmed at
+ all.
+ uncompressed:
+ Changes data storage from compressed (default) to uncompressed.
+ labels:
+ A dictionary of label-value pairs that represent metadata labels of the
+ key.
+ chunk_size:
+ Memory size, in bytes, allocated for each data chunk. Must be a multiple
+ of 8 in the range `[48..1048576]`. In earlier versions of the module the
+ minimum value was different.
+ duplicate_policy:
+ Policy for handling multiple samples with identical timestamps. Can be
+ one of:
+
+ - 'block': An error will occur and the new value will be ignored.
+ - 'first': Ignore the new value.
+ - 'last': Override with the latest value.
+ - 'min': Only override if the value is lower than the existing value.
+ - 'max': Only override if the value is higher than the existing value.
+ - 'sum': If a previous sample exists, add the new sample to it so
+ that the updated value is equal to (previous + new). If no
+ previous sample exists, set the updated value equal to the new
+ value.
+
+ ignore_max_time_diff:
+ A non-negative integer value, in milliseconds, that sets an ignore
+ threshold for added timestamps. If the difference between the last
+ timestamp and the new timestamp is lower than this threshold, the new
+ entry is ignored. Only applicable if `duplicate_policy` is set to
+ `last`, and if `ignore_max_val_diff` is also set. Available since
+ RedisTimeSeries version 1.12.0.
+ ignore_max_val_diff:
+ A non-negative floating point value, that sets an ignore threshold for
+ added values. If the difference between the last value and the new value
+ is lower than this threshold, the new entry is ignored. Only applicable
+ if `duplicate_policy` is set to `last`, and if `ignore_max_time_diff` is
+ also set. Available since RedisTimeSeries version 1.12.0.
+ on_duplicate:
+ Use a specific duplicate policy for the specified timestamp. Overrides
+ the duplicate policy set by `duplicate_policy`.
+ """
+ params = [key, timestamp, value]
+ self._append_retention(params, retention_msecs)
+ self._append_uncompressed(params, uncompressed)
+ self._append_chunk_size(params, chunk_size)
+ self._append_duplicate_policy(params, duplicate_policy)
+ self._append_labels(params, labels)
+ self._append_insertion_filters(
+ params, ignore_max_time_diff, ignore_max_val_diff
+ )
+ self._append_on_duplicate(params, on_duplicate)
+
+ return self.execute_command(ADD_CMD, *params)
+
+ def madd(self, ktv_tuples: List[Tuple[KeyT, Union[int, str], Number]]):
+ """
+ Append new samples to one or more time series.
+
+ Each time series must already exist.
+
+ The method expects a list of tuples. Each tuple should contain three elements:
+ (`key`, `timestamp`, `value`). The `value` will be appended to the time series
+ identified by 'key', at the given 'timestamp'.
+
+ For more information see https://redis.io/commands/ts.madd/
+
+ Args:
+ ktv_tuples:
+ A list of tuples, where each tuple contains:
+ - `key`: The key of the time series.
+ - `timestamp`: The timestamp at which the value should be appended.
+ - `value`: The value to append to the time series.
+
+ Returns:
+ A list that contains, for each sample, either the timestamp that was used,
+ or an error, if the sample could not be added.
+ """
+ params = []
+ for ktv in ktv_tuples:
+ params.extend(ktv)
+
+ return self.execute_command(MADD_CMD, *params)
+
+ def incrby(
+ self,
+ key: KeyT,
+ value: Number,
+ timestamp: Optional[Union[int, str]] = None,
+ retention_msecs: Optional[int] = None,
+ uncompressed: Optional[bool] = False,
+ labels: Optional[Dict[str, str]] = None,
+ chunk_size: Optional[int] = None,
+ duplicate_policy: Optional[str] = None,
+ ignore_max_time_diff: Optional[int] = None,
+ ignore_max_val_diff: Optional[Number] = None,
+ ):
+ """
+ Increment the latest sample's of a series. When the specified key does not
+ exist, a new time series is created.
+
+ This command can be used as a counter or gauge that automatically gets history
+ as a time series.
+
+ For more information see https://redis.io/commands/ts.incrby/
+
+ Args:
+ key:
+ The time-series key.
+ value:
+ Numeric value to be added (addend).
+ timestamp:
+ Timestamp of the sample. `*` can be used for automatic timestamp (using
+ the system clock). `timestamp` must be equal to or higher than the
+ maximum existing timestamp in the series. When equal, the value of the
+ sample with the maximum existing timestamp is increased. If it is
+ higher, a new sample with a timestamp set to `timestamp` is created, and
+ its value is set to the value of the sample with the maximum existing
+ timestamp plus the addend.
+ retention_msecs:
+ Maximum age for samples, compared to the highest reported timestamp in
+ milliseconds. If `None` or `0` is passed, the series is not trimmed at
+ all.
+ uncompressed:
+ Changes data storage from compressed (default) to uncompressed.
+ labels:
+ A dictionary of label-value pairs that represent metadata labels of the
+ key.
+ chunk_size:
+ Memory size, in bytes, allocated for each data chunk. Must be a multiple
+ of 8 in the range `[48..1048576]`. In earlier versions of the module the
+ minimum value was different.
+ duplicate_policy:
+ Policy for handling multiple samples with identical timestamps. Can be
+ one of:
+
+ - 'block': An error will occur and the new value will be ignored.
+ - 'first': Ignore the new value.
+ - 'last': Override with the latest value.
+ - 'min': Only override if the value is lower than the existing value.
+ - 'max': Only override if the value is higher than the existing value.
+ - 'sum': If a previous sample exists, add the new sample to it so
+ that the updated value is equal to (previous + new). If no
+ previous sample exists, set the updated value equal to the new
+ value.
+
+ ignore_max_time_diff:
+ A non-negative integer value, in milliseconds, that sets an ignore
+ threshold for added timestamps. If the difference between the last
+ timestamp and the new timestamp is lower than this threshold, the new
+ entry is ignored. Only applicable if `duplicate_policy` is set to
+ `last`, and if `ignore_max_val_diff` is also set. Available since
+ RedisTimeSeries version 1.12.0.
+ ignore_max_val_diff:
+ A non-negative floating point value, that sets an ignore threshold for
+ added values. If the difference between the last value and the new value
+ is lower than this threshold, the new entry is ignored. Only applicable
+ if `duplicate_policy` is set to `last`, and if `ignore_max_time_diff` is
+ also set. Available since RedisTimeSeries version 1.12.0.
+
+ Returns:
+ The timestamp of the sample that was modified or added.
+ """
+ params = [key, value]
+ self._append_timestamp(params, timestamp)
+ self._append_retention(params, retention_msecs)
+ self._append_uncompressed(params, uncompressed)
+ self._append_chunk_size(params, chunk_size)
+ self._append_duplicate_policy(params, duplicate_policy)
+ self._append_labels(params, labels)
+ self._append_insertion_filters(
+ params, ignore_max_time_diff, ignore_max_val_diff
+ )
+
+ return self.execute_command(INCRBY_CMD, *params)
+
+ def decrby(
+ self,
+ key: KeyT,
+ value: Number,
+ timestamp: Optional[Union[int, str]] = None,
+ retention_msecs: Optional[int] = None,
+ uncompressed: Optional[bool] = False,
+ labels: Optional[Dict[str, str]] = None,
+ chunk_size: Optional[int] = None,
+ duplicate_policy: Optional[str] = None,
+ ignore_max_time_diff: Optional[int] = None,
+ ignore_max_val_diff: Optional[Number] = None,
+ ):
+ """
+ Decrement the latest sample's of a series. When the specified key does not
+ exist, a new time series is created.
+
+ This command can be used as a counter or gauge that automatically gets history
+ as a time series.
+
+ For more information see https://redis.io/commands/ts.decrby/
+
+ Args:
+ key:
+ The time-series key.
+ value:
+ Numeric value to subtract (subtrahend).
+ timestamp:
+ Timestamp of the sample. `*` can be used for automatic timestamp (using
+ the system clock). `timestamp` must be equal to or higher than the
+ maximum existing timestamp in the series. When equal, the value of the
+ sample with the maximum existing timestamp is decreased. If it is
+ higher, a new sample with a timestamp set to `timestamp` is created, and
+ its value is set to the value of the sample with the maximum existing
+ timestamp minus subtrahend.
+ retention_msecs:
+ Maximum age for samples, compared to the highest reported timestamp in
+ milliseconds. If `None` or `0` is passed, the series is not trimmed at
+ all.
+ uncompressed:
+ Changes data storage from compressed (default) to uncompressed.
+ labels:
+ A dictionary of label-value pairs that represent metadata labels of the
+ key.
+ chunk_size:
+ Memory size, in bytes, allocated for each data chunk. Must be a multiple
+ of 8 in the range `[48..1048576]`. In earlier versions of the module the
+ minimum value was different.
+ duplicate_policy:
+ Policy for handling multiple samples with identical timestamps. Can be
+ one of:
+
+ - 'block': An error will occur and the new value will be ignored.
+ - 'first': Ignore the new value.
+ - 'last': Override with the latest value.
+ - 'min': Only override if the value is lower than the existing value.
+ - 'max': Only override if the value is higher than the existing value.
+ - 'sum': If a previous sample exists, add the new sample to it so
+ that the updated value is equal to (previous + new). If no
+ previous sample exists, set the updated value equal to the new
+ value.
+
+ ignore_max_time_diff:
+ A non-negative integer value, in milliseconds, that sets an ignore
+ threshold for added timestamps. If the difference between the last
+ timestamp and the new timestamp is lower than this threshold, the new
+ entry is ignored. Only applicable if `duplicate_policy` is set to
+ `last`, and if `ignore_max_val_diff` is also set. Available since
+ RedisTimeSeries version 1.12.0.
+ ignore_max_val_diff:
+ A non-negative floating point value, that sets an ignore threshold for
+ added values. If the difference between the last value and the new value
+ is lower than this threshold, the new entry is ignored. Only applicable
+ if `duplicate_policy` is set to `last`, and if `ignore_max_time_diff` is
+ also set. Available since RedisTimeSeries version 1.12.0.
+
+ Returns:
+ The timestamp of the sample that was modified or added.
+ """
+ params = [key, value]
+ self._append_timestamp(params, timestamp)
+ self._append_retention(params, retention_msecs)
+ self._append_uncompressed(params, uncompressed)
+ self._append_chunk_size(params, chunk_size)
+ self._append_duplicate_policy(params, duplicate_policy)
+ self._append_labels(params, labels)
+ self._append_insertion_filters(
+ params, ignore_max_time_diff, ignore_max_val_diff
+ )
+
+ return self.execute_command(DECRBY_CMD, *params)
+
+ def delete(self, key: KeyT, from_time: int, to_time: int):
+ """
+ Delete all samples between two timestamps for a given time series.
+
+ The given timestamp interval is closed (inclusive), meaning that samples whose
+ timestamp equals `from_time` or `to_time` are also deleted.
+
+ For more information see https://redis.io/commands/ts.del/
+
+ Args:
+ key:
+ The time-series key.
+ from_time:
+ Start timestamp for the range deletion.
+ to_time:
+ End timestamp for the range deletion.
+
+ Returns:
+ The number of samples deleted.
+ """
+ return self.execute_command(DEL_CMD, key, from_time, to_time)
+
+ def createrule(
+ self,
+ source_key: KeyT,
+ dest_key: KeyT,
+ aggregation_type: str,
+ bucket_size_msec: int,
+ align_timestamp: Optional[int] = None,
+ ):
+ """
+ Create a compaction rule from values added to `source_key` into `dest_key`.
+
+ For more information see https://redis.io/commands/ts.createrule/
+
+ Args:
+ source_key:
+ Key name for source time series.
+ dest_key:
+ Key name for destination (compacted) time series.
+ aggregation_type:
+ Aggregation type: One of the following:
+ [`avg`, `sum`, `min`, `max`, `range`, `count`, `first`, `last`, `std.p`,
+ `std.s`, `var.p`, `var.s`, `twa`]
+ bucket_size_msec:
+ Duration of each bucket, in milliseconds.
+ align_timestamp:
+ Assure that there is a bucket that starts at exactly align_timestamp and
+ align all other buckets accordingly.
+ """
+ params = [source_key, dest_key]
+ self._append_aggregation(params, aggregation_type, bucket_size_msec)
+ if align_timestamp is not None:
+ params.append(align_timestamp)
+
+ return self.execute_command(CREATERULE_CMD, *params)
+
+ def deleterule(self, source_key: KeyT, dest_key: KeyT):
+ """
+ Delete a compaction rule from `source_key` to `dest_key`.
+
+ For more information see https://redis.io/commands/ts.deleterule/
+ """
+ return self.execute_command(DELETERULE_CMD, source_key, dest_key)
+
+ def __range_params(
+ self,
+ key: KeyT,
+ from_time: Union[int, str],
+ to_time: Union[int, str],
+ count: Optional[int],
+ aggregation_type: Optional[str],
+ bucket_size_msec: Optional[int],
+ filter_by_ts: Optional[List[int]],
+ filter_by_min_value: Optional[int],
+ filter_by_max_value: Optional[int],
+ align: Optional[Union[int, str]],
+ latest: Optional[bool],
+ bucket_timestamp: Optional[str],
+ empty: Optional[bool],
+ ):
+ """Create TS.RANGE and TS.REVRANGE arguments."""
+ params = [key, from_time, to_time]
+ self._append_latest(params, latest)
+ self._append_filer_by_ts(params, filter_by_ts)
+ self._append_filer_by_value(params, filter_by_min_value, filter_by_max_value)
+ self._append_count(params, count)
+ self._append_align(params, align)
+ self._append_aggregation(params, aggregation_type, bucket_size_msec)
+ self._append_bucket_timestamp(params, bucket_timestamp)
+ self._append_empty(params, empty)
+
+ return params
+
+ def range(
+ self,
+ key: KeyT,
+ from_time: Union[int, str],
+ to_time: Union[int, str],
+ count: Optional[int] = None,
+ aggregation_type: Optional[str] = None,
+ bucket_size_msec: Optional[int] = 0,
+ filter_by_ts: Optional[List[int]] = None,
+ filter_by_min_value: Optional[int] = None,
+ filter_by_max_value: Optional[int] = None,
+ align: Optional[Union[int, str]] = None,
+ latest: Optional[bool] = False,
+ bucket_timestamp: Optional[str] = None,
+ empty: Optional[bool] = False,
+ ):
+ """
+ Query a range in forward direction for a specific time-series.
+
+ For more information see https://redis.io/commands/ts.range/
+
+ Args:
+ key:
+ Key name for timeseries.
+ from_time:
+ Start timestamp for the range query. `-` can be used to express the
+ minimum possible timestamp (0).
+ to_time:
+ End timestamp for range query, `+` can be used to express the maximum
+ possible timestamp.
+ count:
+ Limits the number of returned samples.
+ aggregation_type:
+ Optional aggregation type. Can be one of [`avg`, `sum`, `min`, `max`,
+ `range`, `count`, `first`, `last`, `std.p`, `std.s`, `var.p`, `var.s`,
+ `twa`]
+ bucket_size_msec:
+ Time bucket for aggregation in milliseconds.
+ filter_by_ts:
+ List of timestamps to filter the result by specific timestamps.
+ filter_by_min_value:
+ Filter result by minimum value (must mention also
+ `filter by_max_value`).
+ filter_by_max_value:
+ Filter result by maximum value (must mention also
+ `filter by_min_value`).
+ align:
+ Timestamp for alignment control for aggregation.
+ latest:
+ Used when a time series is a compaction, reports the compacted value of
+ the latest possibly partial bucket.
+ bucket_timestamp:
+ Controls how bucket timestamps are reported. Can be one of [`-`, `low`,
+ `+`, `high`, `~`, `mid`].
+ empty:
+ Reports aggregations for empty buckets.
+ """
+ params = self.__range_params(
+ key,
+ from_time,
+ to_time,
+ count,
+ aggregation_type,
+ bucket_size_msec,
+ filter_by_ts,
+ filter_by_min_value,
+ filter_by_max_value,
+ align,
+ latest,
+ bucket_timestamp,
+ empty,
+ )
+ return self.execute_command(RANGE_CMD, *params, keys=[key])
+
+ def revrange(
+ self,
+ key: KeyT,
+ from_time: Union[int, str],
+ to_time: Union[int, str],
+ count: Optional[int] = None,
+ aggregation_type: Optional[str] = None,
+ bucket_size_msec: Optional[int] = 0,
+ filter_by_ts: Optional[List[int]] = None,
+ filter_by_min_value: Optional[int] = None,
+ filter_by_max_value: Optional[int] = None,
+ align: Optional[Union[int, str]] = None,
+ latest: Optional[bool] = False,
+ bucket_timestamp: Optional[str] = None,
+ empty: Optional[bool] = False,
+ ):
+ """
+ Query a range in reverse direction for a specific time-series.
+
+ **Note**: This command is only available since RedisTimeSeries >= v1.4
+
+ For more information see https://redis.io/commands/ts.revrange/
+
+ Args:
+ key:
+ Key name for timeseries.
+ from_time:
+ Start timestamp for the range query. `-` can be used to express the
+ minimum possible timestamp (0).
+ to_time:
+ End timestamp for range query, `+` can be used to express the maximum
+ possible timestamp.
+ count:
+ Limits the number of returned samples.
+ aggregation_type:
+ Optional aggregation type. Can be one of [`avg`, `sum`, `min`, `max`,
+ `range`, `count`, `first`, `last`, `std.p`, `std.s`, `var.p`, `var.s`,
+ `twa`]
+ bucket_size_msec:
+ Time bucket for aggregation in milliseconds.
+ filter_by_ts:
+ List of timestamps to filter the result by specific timestamps.
+ filter_by_min_value:
+ Filter result by minimum value (must mention also
+ `filter_by_max_value`).
+ filter_by_max_value:
+ Filter result by maximum value (must mention also
+ `filter_by_min_value`).
+ align:
+ Timestamp for alignment control for aggregation.
+ latest:
+ Used when a time series is a compaction, reports the compacted value of
+ the latest possibly partial bucket.
+ bucket_timestamp:
+ Controls how bucket timestamps are reported. Can be one of [`-`, `low`,
+ `+`, `high`, `~`, `mid`].
+ empty:
+ Reports aggregations for empty buckets.
+ """
+ params = self.__range_params(
+ key,
+ from_time,
+ to_time,
+ count,
+ aggregation_type,
+ bucket_size_msec,
+ filter_by_ts,
+ filter_by_min_value,
+ filter_by_max_value,
+ align,
+ latest,
+ bucket_timestamp,
+ empty,
+ )
+ return self.execute_command(REVRANGE_CMD, *params, keys=[key])
+
+ def __mrange_params(
+ self,
+ aggregation_type: Optional[str],
+ bucket_size_msec: Optional[int],
+ count: Optional[int],
+ filters: List[str],
+ from_time: Union[int, str],
+ to_time: Union[int, str],
+ with_labels: Optional[bool],
+ filter_by_ts: Optional[List[int]],
+ filter_by_min_value: Optional[int],
+ filter_by_max_value: Optional[int],
+ groupby: Optional[str],
+ reduce: Optional[str],
+ select_labels: Optional[List[str]],
+ align: Optional[Union[int, str]],
+ latest: Optional[bool],
+ bucket_timestamp: Optional[str],
+ empty: Optional[bool],
+ ):
+ """Create TS.MRANGE and TS.MREVRANGE arguments."""
+ params = [from_time, to_time]
+ self._append_latest(params, latest)
+ self._append_filer_by_ts(params, filter_by_ts)
+ self._append_filer_by_value(params, filter_by_min_value, filter_by_max_value)
+ self._append_with_labels(params, with_labels, select_labels)
+ self._append_count(params, count)
+ self._append_align(params, align)
+ self._append_aggregation(params, aggregation_type, bucket_size_msec)
+ self._append_bucket_timestamp(params, bucket_timestamp)
+ self._append_empty(params, empty)
+ params.extend(["FILTER"])
+ params += filters
+ self._append_groupby_reduce(params, groupby, reduce)
+ return params
+
+ def mrange(
+ self,
+ from_time: Union[int, str],
+ to_time: Union[int, str],
+ filters: List[str],
+ count: Optional[int] = None,
+ aggregation_type: Optional[str] = None,
+ bucket_size_msec: Optional[int] = 0,
+ with_labels: Optional[bool] = False,
+ filter_by_ts: Optional[List[int]] = None,
+ filter_by_min_value: Optional[int] = None,
+ filter_by_max_value: Optional[int] = None,
+ groupby: Optional[str] = None,
+ reduce: Optional[str] = None,
+ select_labels: Optional[List[str]] = None,
+ align: Optional[Union[int, str]] = None,
+ latest: Optional[bool] = False,
+ bucket_timestamp: Optional[str] = None,
+ empty: Optional[bool] = False,
+ ):
+ """
+ Query a range across multiple time-series by filters in forward direction.
+
+ For more information see https://redis.io/commands/ts.mrange/
+
+ Args:
+ from_time:
+ Start timestamp for the range query. `-` can be used to express the
+ minimum possible timestamp (0).
+ to_time:
+ End timestamp for range query, `+` can be used to express the maximum
+ possible timestamp.
+ filters:
+ Filter to match the time-series labels.
+ count:
+ Limits the number of returned samples.
+ aggregation_type:
+ Optional aggregation type. Can be one of [`avg`, `sum`, `min`, `max`,
+ `range`, `count`, `first`, `last`, `std.p`, `std.s`, `var.p`, `var.s`,
+ `twa`]
+ bucket_size_msec:
+ Time bucket for aggregation in milliseconds.
+ with_labels:
+ Include in the reply all label-value pairs representing metadata labels
+ of the time series.
+ filter_by_ts:
+ List of timestamps to filter the result by specific timestamps.
+ filter_by_min_value:
+ Filter result by minimum value (must mention also
+ `filter_by_max_value`).
+ filter_by_max_value:
+ Filter result by maximum value (must mention also
+ `filter_by_min_value`).
+ groupby:
+ Grouping by fields the results (must mention also `reduce`).
+ reduce:
+ Applying reducer functions on each group. Can be one of [`avg` `sum`,
+ `min`, `max`, `range`, `count`, `std.p`, `std.s`, `var.p`, `var.s`].
+ select_labels:
+ Include in the reply only a subset of the key-value pair labels of a
+ series.
+ align:
+ Timestamp for alignment control for aggregation.
+ latest:
+ Used when a time series is a compaction, reports the compacted value of
+ the latest possibly partial bucket.
+ bucket_timestamp:
+ Controls how bucket timestamps are reported. Can be one of [`-`, `low`,
+ `+`, `high`, `~`, `mid`].
+ empty:
+ Reports aggregations for empty buckets.
+ """
+ params = self.__mrange_params(
+ aggregation_type,
+ bucket_size_msec,
+ count,
+ filters,
+ from_time,
+ to_time,
+ with_labels,
+ filter_by_ts,
+ filter_by_min_value,
+ filter_by_max_value,
+ groupby,
+ reduce,
+ select_labels,
+ align,
+ latest,
+ bucket_timestamp,
+ empty,
+ )
+
+ return self.execute_command(MRANGE_CMD, *params)
+
+ def mrevrange(
+ self,
+ from_time: Union[int, str],
+ to_time: Union[int, str],
+ filters: List[str],
+ count: Optional[int] = None,
+ aggregation_type: Optional[str] = None,
+ bucket_size_msec: Optional[int] = 0,
+ with_labels: Optional[bool] = False,
+ filter_by_ts: Optional[List[int]] = None,
+ filter_by_min_value: Optional[int] = None,
+ filter_by_max_value: Optional[int] = None,
+ groupby: Optional[str] = None,
+ reduce: Optional[str] = None,
+ select_labels: Optional[List[str]] = None,
+ align: Optional[Union[int, str]] = None,
+ latest: Optional[bool] = False,
+ bucket_timestamp: Optional[str] = None,
+ empty: Optional[bool] = False,
+ ):
+ """
+ Query a range across multiple time-series by filters in reverse direction.
+
+ For more information see https://redis.io/commands/ts.mrevrange/
+
+ Args:
+ from_time:
+ Start timestamp for the range query. '-' can be used to express the
+ minimum possible timestamp (0).
+ to_time:
+ End timestamp for range query, '+' can be used to express the maximum
+ possible timestamp.
+ filters:
+ Filter to match the time-series labels.
+ count:
+ Limits the number of returned samples.
+ aggregation_type:
+ Optional aggregation type. Can be one of [`avg`, `sum`, `min`, `max`,
+ `range`, `count`, `first`, `last`, `std.p`, `std.s`, `var.p`, `var.s`,
+ `twa`].
+ bucket_size_msec:
+ Time bucket for aggregation in milliseconds.
+ with_labels:
+ Include in the reply all label-value pairs representing metadata labels
+ of the time series.
+ filter_by_ts:
+ List of timestamps to filter the result by specific timestamps.
+ filter_by_min_value:
+ Filter result by minimum value (must mention also
+ `filter_by_max_value`).
+ filter_by_max_value:
+ Filter result by maximum value (must mention also
+ `filter_by_min_value`).
+ groupby:
+ Grouping by fields the results (must mention also `reduce`).
+ reduce:
+ Applying reducer functions on each group. Can be one of [`avg` `sum`,
+ `min`, `max`, `range`, `count`, `std.p`, `std.s`, `var.p`, `var.s`].
+ select_labels:
+ Include in the reply only a subset of the key-value pair labels of a
+ series.
+ align:
+ Timestamp for alignment control for aggregation.
+ latest:
+ Used when a time series is a compaction, reports the compacted value of
+ the latest possibly partial bucket.
+ bucket_timestamp:
+ Controls how bucket timestamps are reported. Can be one of [`-`, `low`,
+ `+`, `high`, `~`, `mid`].
+ empty:
+ Reports aggregations for empty buckets.
+ """
+ params = self.__mrange_params(
+ aggregation_type,
+ bucket_size_msec,
+ count,
+ filters,
+ from_time,
+ to_time,
+ with_labels,
+ filter_by_ts,
+ filter_by_min_value,
+ filter_by_max_value,
+ groupby,
+ reduce,
+ select_labels,
+ align,
+ latest,
+ bucket_timestamp,
+ empty,
+ )
+
+ return self.execute_command(MREVRANGE_CMD, *params)
+
+ def get(self, key: KeyT, latest: Optional[bool] = False):
+ """
+ Get the last sample of `key`.
+
+ For more information see https://redis.io/commands/ts.get/
+
+ Args:
+ latest:
+ Used when a time series is a compaction, reports the compacted value of
+ the latest (possibly partial) bucket.
+ """
+ params = [key]
+ self._append_latest(params, latest)
+ return self.execute_command(GET_CMD, *params, keys=[key])
+
+ def mget(
+ self,
+ filters: List[str],
+ with_labels: Optional[bool] = False,
+ select_labels: Optional[List[str]] = None,
+ latest: Optional[bool] = False,
+ ):
+ """
+ Get the last samples matching the specific `filter`.
+
+ For more information see https://redis.io/commands/ts.mget/
+
+ Args:
+ filters:
+ Filter to match the time-series labels.
+ with_labels:
+ Include in the reply all label-value pairs representing metadata labels
+ of the time series.
+ select_labels:
+ Include in the reply only a subset of the key-value pair labels o the
+ time series.
+ latest:
+ Used when a time series is a compaction, reports the compacted value of
+ the latest possibly partial bucket.
+ """
+ params = []
+ self._append_latest(params, latest)
+ self._append_with_labels(params, with_labels, select_labels)
+ params.extend(["FILTER"])
+ params += filters
+ return self.execute_command(MGET_CMD, *params)
+
+ def info(self, key: KeyT):
+ """
+ Get information of `key`.
+
+ For more information see https://redis.io/commands/ts.info/
+ """
+ return self.execute_command(INFO_CMD, key, keys=[key])
+
+ def queryindex(self, filters: List[str]):
+ """
+ Get all time series keys matching the `filter` list.
+
+ For more information see https://redis.io/commands/ts.queryindex/
+ """
+ return self.execute_command(QUERYINDEX_CMD, *filters)
+
+ @staticmethod
+ def _append_uncompressed(params: List[str], uncompressed: Optional[bool]):
+ """Append UNCOMPRESSED tag to params."""
+ if uncompressed:
+ params.extend(["ENCODING", "UNCOMPRESSED"])
+
+ @staticmethod
+ def _append_with_labels(
+ params: List[str],
+ with_labels: Optional[bool],
+ select_labels: Optional[List[str]],
+ ):
+ """Append labels behavior to params."""
+ if with_labels and select_labels:
+ raise DataError(
+ "with_labels and select_labels cannot be provided together."
+ )
+
+ if with_labels:
+ params.extend(["WITHLABELS"])
+ if select_labels:
+ params.extend(["SELECTED_LABELS", *select_labels])
+
+ @staticmethod
+ def _append_groupby_reduce(
+ params: List[str], groupby: Optional[str], reduce: Optional[str]
+ ):
+ """Append GROUPBY REDUCE property to params."""
+ if groupby is not None and reduce is not None:
+ params.extend(["GROUPBY", groupby, "REDUCE", reduce.upper()])
+
+ @staticmethod
+ def _append_retention(params: List[str], retention: Optional[int]):
+ """Append RETENTION property to params."""
+ if retention is not None:
+ params.extend(["RETENTION", retention])
+
+ @staticmethod
+ def _append_labels(params: List[str], labels: Optional[List[str]]):
+ """Append LABELS property to params."""
+ if labels:
+ params.append("LABELS")
+ for k, v in labels.items():
+ params.extend([k, v])
+
+ @staticmethod
+ def _append_count(params: List[str], count: Optional[int]):
+ """Append COUNT property to params."""
+ if count is not None:
+ params.extend(["COUNT", count])
+
+ @staticmethod
+ def _append_timestamp(params: List[str], timestamp: Optional[int]):
+ """Append TIMESTAMP property to params."""
+ if timestamp is not None:
+ params.extend(["TIMESTAMP", timestamp])
+
+ @staticmethod
+ def _append_align(params: List[str], align: Optional[Union[int, str]]):
+ """Append ALIGN property to params."""
+ if align is not None:
+ params.extend(["ALIGN", align])
+
+ @staticmethod
+ def _append_aggregation(
+ params: List[str],
+ aggregation_type: Optional[str],
+ bucket_size_msec: Optional[int],
+ ):
+ """Append AGGREGATION property to params."""
+ if aggregation_type is not None:
+ params.extend(["AGGREGATION", aggregation_type, bucket_size_msec])
+
+ @staticmethod
+ def _append_chunk_size(params: List[str], chunk_size: Optional[int]):
+ """Append CHUNK_SIZE property to params."""
+ if chunk_size is not None:
+ params.extend(["CHUNK_SIZE", chunk_size])
+
+ @staticmethod
+ def _append_duplicate_policy(params: List[str], duplicate_policy: Optional[str]):
+ """Append DUPLICATE_POLICY property to params."""
+ if duplicate_policy is not None:
+ params.extend(["DUPLICATE_POLICY", duplicate_policy])
+
+ @staticmethod
+ def _append_on_duplicate(params: List[str], on_duplicate: Optional[str]):
+ """Append ON_DUPLICATE property to params."""
+ if on_duplicate is not None:
+ params.extend(["ON_DUPLICATE", on_duplicate])
+
+ @staticmethod
+ def _append_filer_by_ts(params: List[str], ts_list: Optional[List[int]]):
+ """Append FILTER_BY_TS property to params."""
+ if ts_list is not None:
+ params.extend(["FILTER_BY_TS", *ts_list])
+
+ @staticmethod
+ def _append_filer_by_value(
+ params: List[str], min_value: Optional[int], max_value: Optional[int]
+ ):
+ """Append FILTER_BY_VALUE property to params."""
+ if min_value is not None and max_value is not None:
+ params.extend(["FILTER_BY_VALUE", min_value, max_value])
+
+ @staticmethod
+ def _append_latest(params: List[str], latest: Optional[bool]):
+ """Append LATEST property to params."""
+ if latest:
+ params.append("LATEST")
+
+ @staticmethod
+ def _append_bucket_timestamp(params: List[str], bucket_timestamp: Optional[str]):
+ """Append BUCKET_TIMESTAMP property to params."""
+ if bucket_timestamp is not None:
+ params.extend(["BUCKETTIMESTAMP", bucket_timestamp])
+
+ @staticmethod
+ def _append_empty(params: List[str], empty: Optional[bool]):
+ """Append EMPTY property to params."""
+ if empty:
+ params.append("EMPTY")
+
+ @staticmethod
+ def _append_insertion_filters(
+ params: List[str],
+ ignore_max_time_diff: Optional[int] = None,
+ ignore_max_val_diff: Optional[Number] = None,
+ ):
+ """Append insertion filters to params."""
+ if (ignore_max_time_diff is None) != (ignore_max_val_diff is None):
+ raise ValueError(
+ "Both ignore_max_time_diff and ignore_max_val_diff must be set."
+ )
+
+ if ignore_max_time_diff is not None and ignore_max_val_diff is not None:
+ params.extend(
+ ["IGNORE", str(ignore_max_time_diff), str(ignore_max_val_diff)]
+ )
diff --git a/python_embeded/Lib/site-packages/redis/commands/timeseries/info.py b/python_embeded/Lib/site-packages/redis/commands/timeseries/info.py
new file mode 100644
index 0000000000000000000000000000000000000000..861e3ef003886edf82702b1a8b04c3e79505fd64
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/timeseries/info.py
@@ -0,0 +1,91 @@
+from ..helpers import nativestr
+from .utils import list_to_dict
+
+
+class TSInfo:
+ """
+ Hold information and statistics on the time-series.
+ Can be created using ``tsinfo`` command
+ https://redis.io/docs/latest/commands/ts.info/
+ """
+
+ rules = []
+ labels = []
+ sourceKey = None
+ chunk_count = None
+ memory_usage = None
+ total_samples = None
+ retention_msecs = None
+ last_time_stamp = None
+ first_time_stamp = None
+
+ max_samples_per_chunk = None
+ chunk_size = None
+ duplicate_policy = None
+
+ def __init__(self, args):
+ """
+ Hold information and statistics on the time-series.
+
+ The supported params that can be passed as args:
+
+ rules:
+ A list of compaction rules of the time series.
+ sourceKey:
+ Key name for source time series in case the current series
+ is a target of a rule.
+ chunkCount:
+ Number of Memory Chunks used for the time series.
+ memoryUsage:
+ Total number of bytes allocated for the time series.
+ totalSamples:
+ Total number of samples in the time series.
+ labels:
+ A list of label-value pairs that represent the metadata
+ labels of the time series.
+ retentionTime:
+ Retention time, in milliseconds, for the time series.
+ lastTimestamp:
+ Last timestamp present in the time series.
+ firstTimestamp:
+ First timestamp present in the time series.
+ maxSamplesPerChunk:
+ Deprecated.
+ chunkSize:
+ Amount of memory, in bytes, allocated for data.
+ duplicatePolicy:
+ Policy that will define handling of duplicate samples.
+
+ Can read more about on
+ https://redis.io/docs/latest/develop/data-types/timeseries/configuration/#duplicate_policy
+ """
+ response = dict(zip(map(nativestr, args[::2]), args[1::2]))
+ self.rules = response.get("rules")
+ self.source_key = response.get("sourceKey")
+ self.chunk_count = response.get("chunkCount")
+ self.memory_usage = response.get("memoryUsage")
+ self.total_samples = response.get("totalSamples")
+ self.labels = list_to_dict(response.get("labels"))
+ self.retention_msecs = response.get("retentionTime")
+ self.last_timestamp = response.get("lastTimestamp")
+ self.first_timestamp = response.get("firstTimestamp")
+ if "maxSamplesPerChunk" in response:
+ self.max_samples_per_chunk = response["maxSamplesPerChunk"]
+ self.chunk_size = (
+ self.max_samples_per_chunk * 16
+ ) # backward compatible changes
+ if "chunkSize" in response:
+ self.chunk_size = response["chunkSize"]
+ if "duplicatePolicy" in response:
+ self.duplicate_policy = response["duplicatePolicy"]
+ if isinstance(self.duplicate_policy, bytes):
+ self.duplicate_policy = self.duplicate_policy.decode()
+
+ def get(self, item):
+ try:
+ return self.__getitem__(item)
+ except AttributeError:
+ return None
+
+ def __getitem__(self, item):
+ return getattr(self, item)
diff --git a/python_embeded/Lib/site-packages/redis/commands/timeseries/utils.py b/python_embeded/Lib/site-packages/redis/commands/timeseries/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..12ed6562777e9db85105d32a026a55a4d751ee80
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/timeseries/utils.py
@@ -0,0 +1,44 @@
+from ..helpers import nativestr
+
+
+def list_to_dict(aList):
+ return {nativestr(aList[i][0]): nativestr(aList[i][1]) for i in range(len(aList))}
+
+
+def parse_range(response, **kwargs):
+ """Parse range response. Used by TS.RANGE and TS.REVRANGE."""
+ return [tuple((r[0], float(r[1]))) for r in response]
+
+
+def parse_m_range(response):
+ """Parse multi range response. Used by TS.MRANGE and TS.MREVRANGE."""
+ res = []
+ for item in response:
+ res.append({nativestr(item[0]): [list_to_dict(item[1]), parse_range(item[2])]})
+ return sorted(res, key=lambda d: list(d.keys()))
+
+
+def parse_get(response):
+ """Parse get response. Used by TS.GET."""
+ if not response:
+ return None
+ return int(response[0]), float(response[1])
+
+
+def parse_m_get(response):
+ """Parse multi get response. Used by TS.MGET."""
+ res = []
+ for item in response:
+ if not item[2]:
+ res.append({nativestr(item[0]): [list_to_dict(item[1]), None, None]})
+ else:
+ res.append(
+ {
+ nativestr(item[0]): [
+ list_to_dict(item[1]),
+ int(item[2][0]),
+ float(item[2][1]),
+ ]
+ }
+ )
+ return sorted(res, key=lambda d: list(d.keys()))
diff --git a/python_embeded/Lib/site-packages/redis/commands/vectorset/__init__.py b/python_embeded/Lib/site-packages/redis/commands/vectorset/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d78580a73b52d557472dd464904bf19fc6992830
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/vectorset/__init__.py
@@ -0,0 +1,46 @@
+import json
+
+from redis._parsers.helpers import pairs_to_dict
+from redis.commands.vectorset.utils import (
+ parse_vemb_result,
+ parse_vlinks_result,
+ parse_vsim_result,
+)
+
+from ..helpers import get_protocol_version
+from .commands import (
+ VEMB_CMD,
+ VGETATTR_CMD,
+ VINFO_CMD,
+ VLINKS_CMD,
+ VSIM_CMD,
+ VectorSetCommands,
+)
+
+
+class VectorSet(VectorSetCommands):
+ def __init__(self, client, **kwargs):
+ """Create a new VectorSet client."""
+ # Set the module commands' callbacks
+ self._MODULE_CALLBACKS = {
+ VEMB_CMD: parse_vemb_result,
+ VGETATTR_CMD: lambda r: r and json.loads(r) or None,
+ }
+
+ self._RESP2_MODULE_CALLBACKS = {
+ VINFO_CMD: lambda r: r and pairs_to_dict(r) or None,
+ VSIM_CMD: parse_vsim_result,
+ VLINKS_CMD: parse_vlinks_result,
+ }
+ self._RESP3_MODULE_CALLBACKS = {}
+
+ self.client = client
+ self.execute_command = client.execute_command
+
+ if get_protocol_version(self.client) in ["3", 3]:
+ self._MODULE_CALLBACKS.update(self._RESP3_MODULE_CALLBACKS)
+ else:
+ self._MODULE_CALLBACKS.update(self._RESP2_MODULE_CALLBACKS)
+
+ for k, v in self._MODULE_CALLBACKS.items():
+ self.client.set_response_callback(k, v)
diff --git a/python_embeded/Lib/site-packages/redis/commands/vectorset/commands.py b/python_embeded/Lib/site-packages/redis/commands/vectorset/commands.py
new file mode 100644
index 0000000000000000000000000000000000000000..c24bd200ce6a9ec7081d2cbcad2f11064d9c19ac
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/vectorset/commands.py
@@ -0,0 +1,367 @@
+import json
+from enum import Enum
+from typing import Awaitable, Dict, List, Optional, Union
+
+from redis.client import NEVER_DECODE
+from redis.commands.helpers import get_protocol_version
+from redis.exceptions import DataError
+from redis.typing import CommandsProtocol, EncodableT, KeyT, Number
+
+VADD_CMD = "VADD"
+VSIM_CMD = "VSIM"
+VREM_CMD = "VREM"
+VDIM_CMD = "VDIM"
+VCARD_CMD = "VCARD"
+VEMB_CMD = "VEMB"
+VLINKS_CMD = "VLINKS"
+VINFO_CMD = "VINFO"
+VSETATTR_CMD = "VSETATTR"
+VGETATTR_CMD = "VGETATTR"
+VRANDMEMBER_CMD = "VRANDMEMBER"
+
+
+class QuantizationOptions(Enum):
+ """Quantization options for the VADD command."""
+
+ NOQUANT = "NOQUANT"
+ BIN = "BIN"
+ Q8 = "Q8"
+
+
+class CallbacksOptions(Enum):
+ """Options that can be set for the commands callbacks"""
+
+ RAW = "RAW"
+ WITHSCORES = "WITHSCORES"
+ ALLOW_DECODING = "ALLOW_DECODING"
+ RESP3 = "RESP3"
+
+
+class VectorSetCommands(CommandsProtocol):
+ """Redis VectorSet commands"""
+
+ def vadd(
+ self,
+ key: KeyT,
+ vector: Union[List[float], bytes],
+ element: str,
+ reduce_dim: Optional[int] = None,
+ cas: Optional[bool] = False,
+ quantization: Optional[QuantizationOptions] = None,
+ ef: Optional[Number] = None,
+ attributes: Optional[Union[dict, str]] = None,
+ numlinks: Optional[int] = None,
+ ) -> Union[Awaitable[int], int]:
+ """
+ Add vector ``vector`` for element ``element`` to a vector set ``key``.
+
+ ``reduce_dim`` sets the dimensions to reduce the vector to.
+ If not provided, the vector is not reduced.
+
+ ``cas`` is a boolean flag that indicates whether to use CAS (check-and-set style)
+ when adding the vector. If not provided, CAS is not used.
+
+ ``quantization`` sets the quantization type to use.
+ If not provided, int8 quantization is used.
+ The options are:
+ - NOQUANT: No quantization
+ - BIN: Binary quantization
+ - Q8: Signed 8-bit quantization
+
+ ``ef`` sets the exploration factor to use.
+ If not provided, the default exploration factor is used.
+
+ ``attributes`` is a dictionary or json string that contains the attributes to set for the vector.
+ If not provided, no attributes are set.
+
+ ``numlinks`` sets the number of links to create for the vector.
+ If not provided, the default number of links is used.
+
+ For more information see https://redis.io/commands/vadd
+ """
+ if not vector or not element:
+ raise DataError("Both vector and element must be provided")
+
+ pieces = []
+ if reduce_dim:
+ pieces.extend(["REDUCE", reduce_dim])
+
+ values_pieces = []
+ if isinstance(vector, bytes):
+ values_pieces.extend(["FP32", vector])
+ else:
+ values_pieces.extend(["VALUES", len(vector)])
+ values_pieces.extend(vector)
+ pieces.extend(values_pieces)
+
+ pieces.append(element)
+
+ if cas:
+ pieces.append("CAS")
+
+ if quantization:
+ pieces.append(quantization.value)
+
+ if ef:
+ pieces.extend(["EF", ef])
+
+ if attributes:
+ if isinstance(attributes, dict):
+ # transform attributes to json string
+ attributes_json = json.dumps(attributes)
+ else:
+ attributes_json = attributes
+ pieces.extend(["SETATTR", attributes_json])
+
+ if numlinks:
+ pieces.extend(["M", numlinks])
+
+ return self.execute_command(VADD_CMD, key, *pieces)
+
+ def vsim(
+ self,
+ key: KeyT,
+ input: Union[List[float], bytes, str],
+ with_scores: Optional[bool] = False,
+ count: Optional[int] = None,
+ ef: Optional[Number] = None,
+ filter: Optional[str] = None,
+ filter_ef: Optional[str] = None,
+ truth: Optional[bool] = False,
+ no_thread: Optional[bool] = False,
+ ) -> Union[
+ Awaitable[Optional[List[Union[List[EncodableT], Dict[EncodableT, Number]]]]],
+ Optional[List[Union[List[EncodableT], Dict[EncodableT, Number]]]],
+ ]:
+ """
+ Compare a vector or element ``input`` with the other vectors in a vector set ``key``.
+
+ ``with_scores`` sets if the results should be returned with the
+ similarity scores of the elements in the result.
+
+ ``count`` sets the number of results to return.
+
+ ``ef`` sets the exploration factor.
+
+ ``filter`` sets filter that should be applied for the search.
+
+ ``filter_ef`` sets the max filtering effort.
+
+ ``truth`` when enabled forces the command to perform linear scan.
+
+ ``no_thread`` when enabled forces the command to execute the search
+ on the data structure in the main thread.
+
+ For more information see https://redis.io/commands/vsim
+ """
+
+ if not input:
+ raise DataError("'input' should be provided")
+
+ pieces = []
+ options = {}
+
+ if isinstance(input, bytes):
+ pieces.extend(["FP32", input])
+ elif isinstance(input, list):
+ pieces.extend(["VALUES", len(input)])
+ pieces.extend(input)
+ else:
+ pieces.extend(["ELE", input])
+
+ if with_scores:
+ pieces.append("WITHSCORES")
+ options[CallbacksOptions.WITHSCORES.value] = True
+
+ if count:
+ pieces.extend(["COUNT", count])
+
+ if ef:
+ pieces.extend(["EF", ef])
+
+ if filter:
+ pieces.extend(["FILTER", filter])
+
+ if filter_ef:
+ pieces.extend(["FILTER-EF", filter_ef])
+
+ if truth:
+ pieces.append("TRUTH")
+
+ if no_thread:
+ pieces.append("NOTHREAD")
+
+ return self.execute_command(VSIM_CMD, key, *pieces, **options)
+
+ def vdim(self, key: KeyT) -> Union[Awaitable[int], int]:
+ """
+ Get the dimension of a vector set.
+
+ In the case of vectors that were populated using the `REDUCE`
+ option, for random projection, the vector set will report the size of
+ the projected (reduced) dimension.
+
+ Raises `redis.exceptions.ResponseError` if the vector set doesn't exist.
+
+ For more information see https://redis.io/commands/vdim
+ """
+ return self.execute_command(VDIM_CMD, key)
+
+ def vcard(self, key: KeyT) -> Union[Awaitable[int], int]:
+ """
+ Get the cardinality(the number of elements) of a vector set with key ``key``.
+
+ Raises `redis.exceptions.ResponseError` if the vector set doesn't exist.
+
+ For more information see https://redis.io/commands/vcard
+ """
+ return self.execute_command(VCARD_CMD, key)
+
+ def vrem(self, key: KeyT, element: str) -> Union[Awaitable[int], int]:
+ """
+ Remove an element from a vector set.
+
+ For more information see https://redis.io/commands/vrem
+ """
+ return self.execute_command(VREM_CMD, key, element)
+
+ def vemb(
+ self, key: KeyT, element: str, raw: Optional[bool] = False
+ ) -> Union[
+ Awaitable[Optional[Union[List[EncodableT], Dict[str, EncodableT]]]],
+ Optional[Union[List[EncodableT], Dict[str, EncodableT]]],
+ ]:
+ """
+ Get the approximated vector of an element ``element`` from vector set ``key``.
+
+ ``raw`` is a boolean flag that indicates whether to return the
+ interal representation used by the vector.
+
+
+ For more information see https://redis.io/commands/vembed
+ """
+ options = {}
+ pieces = []
+ pieces.extend([key, element])
+
+ if get_protocol_version(self.client) in ["3", 3]:
+ options[CallbacksOptions.RESP3.value] = True
+
+ if raw:
+ pieces.append("RAW")
+
+ options[NEVER_DECODE] = True
+ if (
+ hasattr(self.client, "connection_pool")
+ and self.client.connection_pool.connection_kwargs["decode_responses"]
+ ) or (
+ hasattr(self.client, "nodes_manager")
+ and self.client.nodes_manager.connection_kwargs["decode_responses"]
+ ):
+ # allow decoding in the postprocessing callback
+ # if the user set decode_responses=True
+ # in the connection pool
+ options[CallbacksOptions.ALLOW_DECODING.value] = True
+
+ options[CallbacksOptions.RAW.value] = True
+
+ return self.execute_command(VEMB_CMD, *pieces, **options)
+
+ def vlinks(
+ self, key: KeyT, element: str, with_scores: Optional[bool] = False
+ ) -> Union[
+ Awaitable[
+ Optional[
+ List[Union[List[Union[str, bytes]], Dict[Union[str, bytes], Number]]]
+ ]
+ ],
+ Optional[List[Union[List[Union[str, bytes]], Dict[Union[str, bytes], Number]]]],
+ ]:
+ """
+ Returns the neighbors for each level the element ``element`` exists in the vector set ``key``.
+
+ The result is a list of lists, where each list contains the neighbors for one level.
+ If the element does not exist, or if the vector set does not exist, None is returned.
+
+ If the ``WITHSCORES`` option is provided, the result is a list of dicts,
+ where each dict contains the neighbors for one level, with the scores as values.
+
+ For more information see https://redis.io/commands/vlinks
+ """
+ options = {}
+ pieces = []
+ pieces.extend([key, element])
+
+ if with_scores:
+ pieces.append("WITHSCORES")
+ options[CallbacksOptions.WITHSCORES.value] = True
+
+ return self.execute_command(VLINKS_CMD, *pieces, **options)
+
+ def vinfo(self, key: KeyT) -> Union[Awaitable[dict], dict]:
+ """
+ Get information about a vector set.
+
+ For more information see https://redis.io/commands/vinfo
+ """
+ return self.execute_command(VINFO_CMD, key)
+
+ def vsetattr(
+ self, key: KeyT, element: str, attributes: Optional[Union[dict, str]] = None
+ ) -> Union[Awaitable[int], int]:
+ """
+ Associate or remove JSON attributes ``attributes`` of element ``element``
+ for vector set ``key``.
+
+ For more information see https://redis.io/commands/vsetattr
+ """
+ if attributes is None:
+ attributes_json = "{}"
+ elif isinstance(attributes, dict):
+ # transform attributes to json string
+ attributes_json = json.dumps(attributes)
+ else:
+ attributes_json = attributes
+
+ return self.execute_command(VSETATTR_CMD, key, element, attributes_json)
+
+ def vgetattr(
+ self, key: KeyT, element: str
+ ) -> Union[Optional[Awaitable[dict]], Optional[dict]]:
+ """
+ Retrieve the JSON attributes of an element ``elemet`` for vector set ``key``.
+
+ If the element does not exist, or if the vector set does not exist, None is
+ returned.
+
+ For more information see https://redis.io/commands/vgetattr
+ """
+ return self.execute_command(VGETATTR_CMD, key, element)
+
+ def vrandmember(
+ self, key: KeyT, count: Optional[int] = None
+ ) -> Union[
+ Awaitable[Optional[Union[List[str], str]]], Optional[Union[List[str], str]]
+ ]:
+ """
+ Returns random elements from a vector set ``key``.
+
+ ``count`` is the number of elements to return.
+ If ``count`` is not provided, a single element is returned as a single string.
+ If ``count`` is positive(smaller than the number of elements
+ in the vector set), the command returns a list with up to ``count``
+ distinct elements from the vector set
+ If ``count`` is negative, the command returns a list with ``count`` random elements,
+ potentially with duplicates.
+ If ``count`` is greater than the number of elements in the vector set,
+ only the entire set is returned as a list.
+
+ If the vector set does not exist, ``None`` is returned.
+
+ For more information see https://redis.io/commands/vrandmember
+ """
+ pieces = []
+ pieces.append(key)
+ if count is not None:
+ pieces.append(count)
+ return self.execute_command(VRANDMEMBER_CMD, *pieces)
diff --git a/python_embeded/Lib/site-packages/redis/commands/vectorset/utils.py b/python_embeded/Lib/site-packages/redis/commands/vectorset/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed6d194ae06b87798ada5da91918be034ba059e0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/redis/commands/vectorset/utils.py
@@ -0,0 +1,94 @@
+from redis._parsers.helpers import pairs_to_dict
+from redis.commands.vectorset.commands import CallbacksOptions
+
+
+def parse_vemb_result(response, **options):
+ """
+ Handle VEMB result since the command can returning different result
+ structures depending on input options and on quantization type of the vector set.
+
+ Parsing VEMB result into:
+ - List[Union[bytes, Union[int, float]]]
+ - Dict[str, Union[bytes, str, float]]
+ """
+ if response is None:
+ return response
+
+ if options.get(CallbacksOptions.RAW.value):
+ result = {}
+ result["quantization"] = (
+ response[0].decode("utf-8")
+ if options.get(CallbacksOptions.ALLOW_DECODING.value)
+ else response[0]
+ )
+ result["raw"] = response[1]
+ result["l2"] = float(response[2])
+ if len(response) > 3:
+ result["range"] = float(response[3])
+ return result
+ else:
+ if options.get(CallbacksOptions.RESP3.value):
+ return response
+
+ result = []
+ for i in range(len(response)):
+ try:
+ result.append(int(response[i]))
+ except ValueError:
+ # if the value is not an integer, it should be a float
+ result.append(float(response[i]))
+
+ return result
+
+
+def parse_vlinks_result(response, **options):
+ """
+ Handle VLINKS result since the command can be returning different result
+ structures depending on input options.
+ Parsing VLINKS result into:
+ - List[List[str]]
+ - List[Dict[str, Number]]
+ """
+ if response is None:
+ return response
+
+ if options.get(CallbacksOptions.WITHSCORES.value):
+ result = []
+ # Redis will return a list of list of strings.
+ # This list have to be transformed to list of dicts
+ for level_item in response:
+ level_data_dict = {}
+ for key, value in pairs_to_dict(level_item).items():
+ value = float(value)
+ level_data_dict[key] = value
+ result.append(level_data_dict)
+ return result
+ else:
+ # return the list of elements for each level
+ # list of lists
+ return response
+
+
+def parse_vsim_result(response, **options):
+ """
+ Handle VSIM result since the command can be returning different result
+ structures depending on input options.
+ Parsing VSIM result into:
+ - List[List[str]]
+ - List[Dict[str, Number]]
+ """
+ if response is None:
+ return response
+
+ if options.get(CallbacksOptions.WITHSCORES.value):
+ # Redis will return a list of list of pairs.
+ # This list have to be transformed to dict
+ result_dict = {}
+ for key, value in pairs_to_dict(response).items():
+ value = float(value)
+ result_dict[key] = value
+ return result_dict
+ else:
+ # return the list of elements for each level
+ # list of lists
+ return response
diff --git a/python_embeded/Lib/site-packages/referencing-0.36.2.dist-info/licenses/COPYING b/python_embeded/Lib/site-packages/referencing-0.36.2.dist-info/licenses/COPYING
new file mode 100644
index 0000000000000000000000000000000000000000..a9f853e43069b8e3f8a156a4af2b1198a004230d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/referencing-0.36.2.dist-info/licenses/COPYING
@@ -0,0 +1,19 @@
+Copyright (c) 2022 Julian Berman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/python_embeded/Lib/site-packages/referencing/tests/__init__.py b/python_embeded/Lib/site-packages/referencing/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/referencing/tests/test_core.py b/python_embeded/Lib/site-packages/referencing/tests/test_core.py
new file mode 100644
index 0000000000000000000000000000000000000000..3edddbc3d96581e1c74069baa873900495366bab
--- /dev/null
+++ b/python_embeded/Lib/site-packages/referencing/tests/test_core.py
@@ -0,0 +1,1057 @@
+from rpds import HashTrieMap
+import pytest
+
+from referencing import Anchor, Registry, Resource, Specification, exceptions
+from referencing.jsonschema import DRAFT202012
+
+ID_AND_CHILDREN = Specification(
+ name="id-and-children",
+ id_of=lambda contents: contents.get("ID"),
+ subresources_of=lambda contents: contents.get("children", []),
+ anchors_in=lambda specification, contents: [
+ Anchor(
+ name=name,
+ resource=specification.create_resource(contents=each),
+ )
+ for name, each in contents.get("anchors", {}).items()
+ ],
+ maybe_in_subresource=lambda segments, resolver, subresource: (
+ resolver.in_subresource(subresource)
+ if not len(segments) % 2
+ and all(each == "children" for each in segments[::2])
+ else resolver
+ ),
+)
+
+
+def blow_up(uri): # pragma: no cover
+ """
+ A retriever suitable for use in tests which expect it never to be used.
+ """
+ raise RuntimeError("This retrieve function expects to never be called!")
+
+
+class TestRegistry:
+ def test_with_resource(self):
+ """
+ Adding a resource to the registry then allows re-retrieving it.
+ """
+
+ resource = Resource.opaque(contents={"foo": "bar"})
+ uri = "urn:example"
+ registry = Registry().with_resource(uri=uri, resource=resource)
+ assert registry[uri] is resource
+
+ def test_with_resources(self):
+ """
+ Adding multiple resources to the registry is like adding each one.
+ """
+
+ one = Resource.opaque(contents={})
+ two = Resource(contents={"foo": "bar"}, specification=ID_AND_CHILDREN)
+ registry = Registry().with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/foo/bar", two),
+ ],
+ )
+ assert registry == Registry().with_resource(
+ uri="http://example.com/1",
+ resource=one,
+ ).with_resource(
+ uri="http://example.com/foo/bar",
+ resource=two,
+ )
+
+ def test_matmul_resource(self):
+ uri = "urn:example:resource"
+ resource = ID_AND_CHILDREN.create_resource({"ID": uri, "foo": 12})
+ registry = resource @ Registry()
+ assert registry == Registry().with_resource(uri, resource)
+
+ def test_matmul_many_resources(self):
+ one_uri = "urn:example:one"
+ one = ID_AND_CHILDREN.create_resource({"ID": one_uri, "foo": 12})
+
+ two_uri = "urn:example:two"
+ two = ID_AND_CHILDREN.create_resource({"ID": two_uri, "foo": 12})
+
+ registry = [one, two] @ Registry()
+ assert registry == Registry().with_resources(
+ [(one_uri, one), (two_uri, two)],
+ )
+
+ def test_matmul_resource_without_id(self):
+ resource = Resource.opaque(contents={"foo": "bar"})
+ with pytest.raises(exceptions.NoInternalID) as e:
+ resource @ Registry()
+ assert e.value == exceptions.NoInternalID(resource=resource)
+
+ def test_with_contents_from_json_schema(self):
+ uri = "urn:example"
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ registry = Registry().with_contents([(uri, schema)])
+
+ expected = Resource(contents=schema, specification=DRAFT202012)
+ assert registry[uri] == expected
+
+ def test_with_contents_and_default_specification(self):
+ uri = "urn:example"
+ registry = Registry().with_contents(
+ [(uri, {"foo": "bar"})],
+ default_specification=Specification.OPAQUE,
+ )
+ assert registry[uri] == Resource.opaque({"foo": "bar"})
+
+ def test_len(self):
+ total = 5
+ registry = Registry().with_contents(
+ [(str(i), {"foo": "bar"}) for i in range(total)],
+ default_specification=Specification.OPAQUE,
+ )
+ assert len(registry) == total
+
+ def test_bool_empty(self):
+ assert not Registry()
+
+ def test_bool_not_empty(self):
+ registry = Registry().with_contents(
+ [(str(i), {"foo": "bar"}) for i in range(3)],
+ default_specification=Specification.OPAQUE,
+ )
+ assert registry
+
+ def test_iter(self):
+ registry = Registry().with_contents(
+ [(str(i), {"foo": "bar"}) for i in range(8)],
+ default_specification=Specification.OPAQUE,
+ )
+ assert set(registry) == {str(i) for i in range(8)}
+
+ def test_crawl_still_has_top_level_resource(self):
+ resource = Resource.opaque({"foo": "bar"})
+ uri = "urn:example"
+ registry = Registry({uri: resource}).crawl()
+ assert registry[uri] is resource
+
+ def test_crawl_finds_a_subresource(self):
+ child_id = "urn:child"
+ root = ID_AND_CHILDREN.create_resource(
+ {"ID": "urn:root", "children": [{"ID": child_id, "foo": 12}]},
+ )
+ registry = root @ Registry()
+ with pytest.raises(LookupError):
+ registry[child_id]
+
+ expected = ID_AND_CHILDREN.create_resource({"ID": child_id, "foo": 12})
+ assert registry.crawl()[child_id] == expected
+
+ def test_crawl_finds_anchors_with_id(self):
+ resource = ID_AND_CHILDREN.create_resource(
+ {"ID": "urn:bar", "anchors": {"foo": 12}},
+ )
+ registry = resource @ Registry()
+
+ assert registry.crawl().anchor(resource.id(), "foo").value == Anchor(
+ name="foo",
+ resource=ID_AND_CHILDREN.create_resource(12),
+ )
+
+ def test_crawl_finds_anchors_no_id(self):
+ resource = ID_AND_CHILDREN.create_resource({"anchors": {"foo": 12}})
+ registry = Registry().with_resource("urn:root", resource)
+
+ assert registry.crawl().anchor("urn:root", "foo").value == Anchor(
+ name="foo",
+ resource=ID_AND_CHILDREN.create_resource(12),
+ )
+
+ def test_contents(self):
+ resource = Resource.opaque({"foo": "bar"})
+ uri = "urn:example"
+ registry = Registry().with_resource(uri, resource)
+ assert registry.contents(uri) == {"foo": "bar"}
+
+ def test_getitem_strips_empty_fragments(self):
+ uri = "http://example.com/"
+ resource = ID_AND_CHILDREN.create_resource({"ID": uri + "#"})
+ registry = resource @ Registry()
+ assert registry[uri] == registry[uri + "#"] == resource
+
+ def test_contents_strips_empty_fragments(self):
+ uri = "http://example.com/"
+ resource = ID_AND_CHILDREN.create_resource({"ID": uri + "#"})
+ registry = resource @ Registry()
+ assert (
+ registry.contents(uri)
+ == registry.contents(uri + "#")
+ == {"ID": uri + "#"}
+ )
+
+ def test_contents_nonexistent_resource(self):
+ registry = Registry()
+ with pytest.raises(exceptions.NoSuchResource) as e:
+ registry.contents("urn:example")
+ assert e.value == exceptions.NoSuchResource(ref="urn:example")
+
+ def test_crawled_anchor(self):
+ resource = ID_AND_CHILDREN.create_resource({"anchors": {"foo": "bar"}})
+ registry = Registry().with_resource("urn:example", resource)
+ retrieved = registry.anchor("urn:example", "foo")
+ assert retrieved.value == Anchor(
+ name="foo",
+ resource=ID_AND_CHILDREN.create_resource("bar"),
+ )
+ assert retrieved.registry == registry.crawl()
+
+ def test_anchor_in_nonexistent_resource(self):
+ registry = Registry()
+ with pytest.raises(exceptions.NoSuchResource) as e:
+ registry.anchor("urn:example", "foo")
+ assert e.value == exceptions.NoSuchResource(ref="urn:example")
+
+ def test_init(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ registry = Registry(
+ {
+ "http://example.com/1": one,
+ "http://example.com/foo/bar": two,
+ },
+ )
+ assert (
+ registry
+ == Registry()
+ .with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/foo/bar", two),
+ ],
+ )
+ .crawl()
+ )
+
+ def test_dict_conversion(self):
+ """
+ Passing a `dict` to `Registry` gets converted to a `HashTrieMap`.
+
+ So continuing to use the registry works.
+ """
+
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ registry = Registry(
+ {"http://example.com/1": one},
+ ).with_resource("http://example.com/foo/bar", two)
+ assert (
+ registry.crawl()
+ == Registry()
+ .with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/foo/bar", two),
+ ],
+ )
+ .crawl()
+ )
+
+ def test_no_such_resource(self):
+ registry = Registry()
+ with pytest.raises(exceptions.NoSuchResource) as e:
+ registry["urn:bigboom"]
+ assert e.value == exceptions.NoSuchResource(ref="urn:bigboom")
+
+ def test_combine(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ three = ID_AND_CHILDREN.create_resource({"baz": "quux"})
+ four = ID_AND_CHILDREN.create_resource({"anchors": {"foo": 12}})
+
+ first = Registry({"http://example.com/1": one})
+ second = Registry().with_resource("http://example.com/foo/bar", two)
+ third = Registry(
+ {
+ "http://example.com/1": one,
+ "http://example.com/baz": three,
+ },
+ )
+ fourth = (
+ Registry()
+ .with_resource(
+ "http://example.com/foo/quux",
+ four,
+ )
+ .crawl()
+ )
+ assert first.combine(second, third, fourth) == Registry(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/baz", three),
+ ("http://example.com/foo/quux", four),
+ ],
+ anchors=HashTrieMap(
+ {
+ ("http://example.com/foo/quux", "foo"): Anchor(
+ name="foo",
+ resource=ID_AND_CHILDREN.create_resource(12),
+ ),
+ },
+ ),
+ ).with_resource("http://example.com/foo/bar", two)
+
+ def test_combine_self(self):
+ """
+ Combining a registry with itself short-circuits.
+
+ This is a performance optimization -- otherwise we do lots more work
+ (in jsonschema this seems to correspond to making the test suite take
+ *3x* longer).
+ """
+
+ registry = Registry({"urn:foo": "bar"})
+ assert registry.combine(registry) is registry
+
+ def test_combine_with_uncrawled_resources(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ three = ID_AND_CHILDREN.create_resource({"baz": "quux"})
+
+ first = Registry().with_resource("http://example.com/1", one)
+ second = Registry().with_resource("http://example.com/foo/bar", two)
+ third = Registry(
+ {
+ "http://example.com/1": one,
+ "http://example.com/baz": three,
+ },
+ )
+ expected = Registry(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/foo/bar", two),
+ ("http://example.com/baz", three),
+ ],
+ )
+ combined = first.combine(second, third)
+ assert combined != expected
+ assert combined.crawl() == expected
+
+ def test_combine_with_single_retrieve(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ three = ID_AND_CHILDREN.create_resource({"baz": "quux"})
+
+ def retrieve(uri): # pragma: no cover
+ pass
+
+ first = Registry().with_resource("http://example.com/1", one)
+ second = Registry(
+ retrieve=retrieve,
+ ).with_resource("http://example.com/2", two)
+ third = Registry().with_resource("http://example.com/3", three)
+
+ assert first.combine(second, third) == Registry(
+ retrieve=retrieve,
+ ).with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/2", two),
+ ("http://example.com/3", three),
+ ],
+ )
+ assert second.combine(first, third) == Registry(
+ retrieve=retrieve,
+ ).with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/2", two),
+ ("http://example.com/3", three),
+ ],
+ )
+
+ def test_combine_with_common_retrieve(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ three = ID_AND_CHILDREN.create_resource({"baz": "quux"})
+
+ def retrieve(uri): # pragma: no cover
+ pass
+
+ first = Registry(retrieve=retrieve).with_resource(
+ "http://example.com/1",
+ one,
+ )
+ second = Registry(
+ retrieve=retrieve,
+ ).with_resource("http://example.com/2", two)
+ third = Registry(retrieve=retrieve).with_resource(
+ "http://example.com/3",
+ three,
+ )
+
+ assert first.combine(second, third) == Registry(
+ retrieve=retrieve,
+ ).with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/2", two),
+ ("http://example.com/3", three),
+ ],
+ )
+ assert second.combine(first, third) == Registry(
+ retrieve=retrieve,
+ ).with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/2", two),
+ ("http://example.com/3", three),
+ ],
+ )
+
+ def test_combine_conflicting_retrieve(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ three = ID_AND_CHILDREN.create_resource({"baz": "quux"})
+
+ def foo_retrieve(uri): # pragma: no cover
+ pass
+
+ def bar_retrieve(uri): # pragma: no cover
+ pass
+
+ first = Registry(retrieve=foo_retrieve).with_resource(
+ "http://example.com/1",
+ one,
+ )
+ second = Registry().with_resource("http://example.com/2", two)
+ third = Registry(retrieve=bar_retrieve).with_resource(
+ "http://example.com/3",
+ three,
+ )
+
+ with pytest.raises(Exception, match="conflict.*retriev"):
+ first.combine(second, third)
+
+ def test_remove(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ registry = Registry({"urn:foo": one, "urn:bar": two})
+ assert registry.remove("urn:foo") == Registry({"urn:bar": two})
+
+ def test_remove_uncrawled(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ registry = Registry().with_resources(
+ [("urn:foo", one), ("urn:bar", two)],
+ )
+ assert registry.remove("urn:foo") == Registry().with_resource(
+ "urn:bar",
+ two,
+ )
+
+ def test_remove_with_anchors(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"anchors": {"foo": "bar"}})
+ registry = (
+ Registry()
+ .with_resources(
+ [("urn:foo", one), ("urn:bar", two)],
+ )
+ .crawl()
+ )
+ assert (
+ registry.remove("urn:bar")
+ == Registry()
+ .with_resource(
+ "urn:foo",
+ one,
+ )
+ .crawl()
+ )
+
+ def test_remove_nonexistent_uri(self):
+ with pytest.raises(exceptions.NoSuchResource) as e:
+ Registry().remove("urn:doesNotExist")
+ assert e.value == exceptions.NoSuchResource(ref="urn:doesNotExist")
+
+ def test_retrieve(self):
+ foo = Resource.opaque({"foo": "bar"})
+ registry = Registry(retrieve=lambda uri: foo)
+ assert registry.get_or_retrieve("urn:example").value == foo
+
+ def test_retrieve_arbitrary_exception(self):
+ foo = Resource.opaque({"foo": "bar"})
+
+ def retrieve(uri):
+ if uri == "urn:succeed":
+ return foo
+ raise Exception("Oh no!")
+
+ registry = Registry(retrieve=retrieve)
+ assert registry.get_or_retrieve("urn:succeed").value == foo
+ with pytest.raises(exceptions.Unretrievable):
+ registry.get_or_retrieve("urn:uhoh")
+
+ def test_retrieve_no_such_resource(self):
+ foo = Resource.opaque({"foo": "bar"})
+
+ def retrieve(uri):
+ if uri == "urn:succeed":
+ return foo
+ raise exceptions.NoSuchResource(ref=uri)
+
+ registry = Registry(retrieve=retrieve)
+ assert registry.get_or_retrieve("urn:succeed").value == foo
+ with pytest.raises(exceptions.NoSuchResource):
+ registry.get_or_retrieve("urn:uhoh")
+
+ def test_retrieve_cannot_determine_specification(self):
+ def retrieve(uri):
+ return Resource.from_contents({})
+
+ registry = Registry(retrieve=retrieve)
+ with pytest.raises(exceptions.CannotDetermineSpecification):
+ registry.get_or_retrieve("urn:uhoh")
+
+ def test_retrieve_already_available_resource(self):
+ foo = Resource.opaque({"foo": "bar"})
+ registry = Registry({"urn:example": foo}, retrieve=blow_up)
+ assert registry["urn:example"] == foo
+ assert registry.get_or_retrieve("urn:example").value == foo
+
+ def test_retrieve_first_checks_crawlable_resource(self):
+ child = ID_AND_CHILDREN.create_resource({"ID": "urn:child", "foo": 12})
+ root = ID_AND_CHILDREN.create_resource({"children": [child.contents]})
+ registry = Registry(retrieve=blow_up).with_resource("urn:root", root)
+ assert registry.crawl()["urn:child"] == child
+
+ def test_resolver(self):
+ one = Resource.opaque(contents={})
+ registry = Registry({"http://example.com": one})
+ resolver = registry.resolver(base_uri="http://example.com")
+ assert resolver.lookup("#").contents == {}
+
+ def test_resolver_with_root_identified(self):
+ root = ID_AND_CHILDREN.create_resource({"ID": "http://example.com"})
+ resolver = Registry().resolver_with_root(root)
+ assert resolver.lookup("http://example.com").contents == root.contents
+ assert resolver.lookup("#").contents == root.contents
+
+ def test_resolver_with_root_unidentified(self):
+ root = Resource.opaque(contents={})
+ resolver = Registry().resolver_with_root(root)
+ assert resolver.lookup("#").contents == root.contents
+
+ def test_repr(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ registry = Registry().with_resources(
+ [
+ ("http://example.com/1", one),
+ ("http://example.com/foo/bar", two),
+ ],
+ )
+ assert repr(registry) == ""
+ assert repr(registry.crawl()) == ""
+
+ def test_repr_mixed_crawled(self):
+ one = Resource.opaque(contents={})
+ two = ID_AND_CHILDREN.create_resource({"foo": "bar"})
+ registry = (
+ Registry(
+ {"http://example.com/1": one},
+ )
+ .crawl()
+ .with_resource(uri="http://example.com/foo/bar", resource=two)
+ )
+ assert repr(registry) == ""
+
+ def test_repr_one_resource(self):
+ registry = Registry().with_resource(
+ uri="http://example.com/1",
+ resource=Resource.opaque(contents={}),
+ )
+ assert repr(registry) == ""
+
+ def test_repr_empty(self):
+ assert repr(Registry()) == ""
+
+
+class TestResource:
+ def test_from_contents_from_json_schema(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ resource = Resource.from_contents(schema)
+ assert resource == Resource(contents=schema, specification=DRAFT202012)
+
+ def test_from_contents_with_no_discernible_information(self):
+ """
+ Creating a resource with no discernible way to see what
+ specification it belongs to (e.g. no ``$schema`` keyword for JSON
+ Schema) raises an error.
+ """
+
+ with pytest.raises(exceptions.CannotDetermineSpecification):
+ Resource.from_contents({"foo": "bar"})
+
+ def test_from_contents_with_no_discernible_information_and_default(self):
+ resource = Resource.from_contents(
+ {"foo": "bar"},
+ default_specification=Specification.OPAQUE,
+ )
+ assert resource == Resource.opaque(contents={"foo": "bar"})
+
+ def test_from_contents_unneeded_default(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ resource = Resource.from_contents(
+ schema,
+ default_specification=Specification.OPAQUE,
+ )
+ assert resource == Resource(
+ contents=schema,
+ specification=DRAFT202012,
+ )
+
+ def test_non_mapping_from_contents(self):
+ resource = Resource.from_contents(
+ True,
+ default_specification=ID_AND_CHILDREN,
+ )
+ assert resource == Resource(
+ contents=True,
+ specification=ID_AND_CHILDREN,
+ )
+
+ def test_from_contents_with_fallback(self):
+ resource = Resource.from_contents(
+ {"foo": "bar"},
+ default_specification=Specification.OPAQUE,
+ )
+ assert resource == Resource.opaque(contents={"foo": "bar"})
+
+ def test_id_delegates_to_specification(self):
+ specification = Specification(
+ name="",
+ id_of=lambda contents: "urn:fixedID",
+ subresources_of=lambda contents: [],
+ anchors_in=lambda specification, contents: [],
+ maybe_in_subresource=(
+ lambda segments, resolver, subresource: resolver
+ ),
+ )
+ resource = Resource(
+ contents={"foo": "baz"},
+ specification=specification,
+ )
+ assert resource.id() == "urn:fixedID"
+
+ def test_id_strips_empty_fragment(self):
+ uri = "http://example.com/"
+ root = ID_AND_CHILDREN.create_resource({"ID": uri + "#"})
+ assert root.id() == uri
+
+ def test_subresources_delegates_to_specification(self):
+ resource = ID_AND_CHILDREN.create_resource({"children": [{}, 12]})
+ assert list(resource.subresources()) == [
+ ID_AND_CHILDREN.create_resource(each) for each in [{}, 12]
+ ]
+
+ def test_subresource_with_different_specification(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ resource = ID_AND_CHILDREN.create_resource({"children": [schema]})
+ assert list(resource.subresources()) == [
+ DRAFT202012.create_resource(schema),
+ ]
+
+ def test_anchors_delegates_to_specification(self):
+ resource = ID_AND_CHILDREN.create_resource(
+ {"anchors": {"foo": {}, "bar": 1, "baz": ""}},
+ )
+ assert list(resource.anchors()) == [
+ Anchor(name="foo", resource=ID_AND_CHILDREN.create_resource({})),
+ Anchor(name="bar", resource=ID_AND_CHILDREN.create_resource(1)),
+ Anchor(name="baz", resource=ID_AND_CHILDREN.create_resource("")),
+ ]
+
+ def test_pointer_to_mapping(self):
+ resource = Resource.opaque(contents={"foo": "baz"})
+ resolver = Registry().resolver()
+ assert resource.pointer("/foo", resolver=resolver).contents == "baz"
+
+ def test_pointer_to_array(self):
+ resource = Resource.opaque(contents={"foo": {"bar": [3]}})
+ resolver = Registry().resolver()
+ assert resource.pointer("/foo/bar/0", resolver=resolver).contents == 3
+
+ def test_root_pointer(self):
+ contents = {"foo": "baz"}
+ resource = Resource.opaque(contents=contents)
+ resolver = Registry().resolver()
+ assert resource.pointer("", resolver=resolver).contents == contents
+
+ def test_opaque(self):
+ contents = {"foo": "bar"}
+ assert Resource.opaque(contents) == Resource(
+ contents=contents,
+ specification=Specification.OPAQUE,
+ )
+
+
+class TestResolver:
+ def test_lookup_exact_uri(self):
+ resource = Resource.opaque(contents={"foo": "baz"})
+ resolver = Registry({"http://example.com/1": resource}).resolver()
+ resolved = resolver.lookup("http://example.com/1")
+ assert resolved.contents == resource.contents
+
+ def test_lookup_subresource(self):
+ root = ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/",
+ "children": [
+ {"ID": "http://example.com/a", "foo": 12},
+ ],
+ },
+ )
+ registry = root @ Registry()
+ resolved = registry.resolver().lookup("http://example.com/a")
+ assert resolved.contents == {"ID": "http://example.com/a", "foo": 12}
+
+ def test_lookup_anchor_with_id(self):
+ root = ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/",
+ "anchors": {"foo": 12},
+ },
+ )
+ registry = root @ Registry()
+ resolved = registry.resolver().lookup("http://example.com/#foo")
+ assert resolved.contents == 12
+
+ def test_lookup_anchor_without_id(self):
+ root = ID_AND_CHILDREN.create_resource({"anchors": {"foo": 12}})
+ resolver = Registry().with_resource("urn:example", root).resolver()
+ resolved = resolver.lookup("urn:example#foo")
+ assert resolved.contents == 12
+
+ def test_lookup_unknown_reference(self):
+ resolver = Registry().resolver()
+ ref = "http://example.com/does/not/exist"
+ with pytest.raises(exceptions.Unresolvable) as e:
+ resolver.lookup(ref)
+ assert e.value == exceptions.Unresolvable(ref=ref)
+
+ def test_lookup_non_existent_pointer(self):
+ resource = Resource.opaque({"foo": {}})
+ resolver = Registry({"http://example.com/1": resource}).resolver()
+ ref = "http://example.com/1#/foo/bar"
+ with pytest.raises(exceptions.Unresolvable) as e:
+ resolver.lookup(ref)
+ assert e.value == exceptions.PointerToNowhere(
+ ref="/foo/bar",
+ resource=resource,
+ )
+ assert str(e.value) == "'/foo/bar' does not exist within {'foo': {}}"
+
+ def test_lookup_non_existent_pointer_to_array_index(self):
+ resource = Resource.opaque([1, 2, 4, 8])
+ resolver = Registry({"http://example.com/1": resource}).resolver()
+ ref = "http://example.com/1#/10"
+ with pytest.raises(exceptions.Unresolvable) as e:
+ resolver.lookup(ref)
+ assert e.value == exceptions.PointerToNowhere(
+ ref="/10",
+ resource=resource,
+ )
+
+ def test_lookup_pointer_to_empty_string(self):
+ resolver = Registry().resolver_with_root(Resource.opaque({"": {}}))
+ assert resolver.lookup("#/").contents == {}
+
+ def test_lookup_non_existent_pointer_to_empty_string(self):
+ resource = Resource.opaque({"foo": {}})
+ resolver = Registry().resolver_with_root(resource)
+ with pytest.raises(
+ exceptions.Unresolvable,
+ match="^'/' does not exist within {'foo': {}}.*'#'",
+ ) as e:
+ resolver.lookup("#/")
+ assert e.value == exceptions.PointerToNowhere(
+ ref="/",
+ resource=resource,
+ )
+
+ def test_lookup_non_existent_anchor(self):
+ root = ID_AND_CHILDREN.create_resource({"anchors": {}})
+ resolver = Registry().with_resource("urn:example", root).resolver()
+ resolved = resolver.lookup("urn:example")
+ assert resolved.contents == root.contents
+
+ ref = "urn:example#noSuchAnchor"
+ with pytest.raises(exceptions.Unresolvable) as e:
+ resolver.lookup(ref)
+ assert "'noSuchAnchor' does not exist" in str(e.value)
+ assert e.value == exceptions.NoSuchAnchor(
+ ref="urn:example",
+ resource=root,
+ anchor="noSuchAnchor",
+ )
+
+ def test_lookup_invalid_JSON_pointerish_anchor(self):
+ resolver = Registry().resolver_with_root(
+ ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/",
+ "foo": {"bar": 12},
+ },
+ ),
+ )
+
+ valid = resolver.lookup("#/foo/bar")
+ assert valid.contents == 12
+
+ with pytest.raises(exceptions.InvalidAnchor) as e:
+ resolver.lookup("#foo/bar")
+ assert " '#/foo/bar'" in str(e.value)
+
+ def test_lookup_retrieved_resource(self):
+ resource = Resource.opaque(contents={"foo": "baz"})
+ resolver = Registry(retrieve=lambda uri: resource).resolver()
+ resolved = resolver.lookup("http://example.com/")
+ assert resolved.contents == resource.contents
+
+ def test_lookup_failed_retrieved_resource(self):
+ """
+ Unretrievable exceptions are also wrapped in Unresolvable.
+ """
+
+ uri = "http://example.com/"
+
+ registry = Registry(retrieve=blow_up)
+ with pytest.raises(exceptions.Unretrievable):
+ registry.get_or_retrieve(uri)
+
+ resolver = registry.resolver()
+ with pytest.raises(exceptions.Unresolvable):
+ resolver.lookup(uri)
+
+ def test_repeated_lookup_from_retrieved_resource(self):
+ """
+ A (custom-)retrieved resource is added to the registry returned by
+ looking it up.
+ """
+ resource = Resource.opaque(contents={"foo": "baz"})
+ once = [resource]
+
+ def retrieve(uri):
+ return once.pop()
+
+ resolver = Registry(retrieve=retrieve).resolver()
+ resolved = resolver.lookup("http://example.com/")
+ assert resolved.contents == resource.contents
+
+ resolved = resolved.resolver.lookup("http://example.com/")
+ assert resolved.contents == resource.contents
+
+ def test_repeated_anchor_lookup_from_retrieved_resource(self):
+ resource = Resource.opaque(contents={"foo": "baz"})
+ once = [resource]
+
+ def retrieve(uri):
+ return once.pop()
+
+ resolver = Registry(retrieve=retrieve).resolver()
+ resolved = resolver.lookup("http://example.com/")
+ assert resolved.contents == resource.contents
+
+ resolved = resolved.resolver.lookup("#")
+ assert resolved.contents == resource.contents
+
+ # FIXME: The tests below aren't really representable in the current
+ # suite, though we should probably think of ways to do so.
+
+ def test_in_subresource(self):
+ root = ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/",
+ "children": [
+ {
+ "ID": "child/",
+ "children": [{"ID": "grandchild"}],
+ },
+ ],
+ },
+ )
+ registry = root @ Registry()
+
+ resolver = registry.resolver()
+ first = resolver.lookup("http://example.com/")
+ assert first.contents == root.contents
+
+ with pytest.raises(exceptions.Unresolvable):
+ first.resolver.lookup("grandchild")
+
+ sub = first.resolver.in_subresource(
+ ID_AND_CHILDREN.create_resource(first.contents["children"][0]),
+ )
+ second = sub.lookup("grandchild")
+ assert second.contents == {"ID": "grandchild"}
+
+ def test_in_pointer_subresource(self):
+ root = ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/",
+ "children": [
+ {
+ "ID": "child/",
+ "children": [{"ID": "grandchild"}],
+ },
+ ],
+ },
+ )
+ registry = root @ Registry()
+
+ resolver = registry.resolver()
+ first = resolver.lookup("http://example.com/")
+ assert first.contents == root.contents
+
+ with pytest.raises(exceptions.Unresolvable):
+ first.resolver.lookup("grandchild")
+
+ second = first.resolver.lookup("#/children/0")
+ third = second.resolver.lookup("grandchild")
+ assert third.contents == {"ID": "grandchild"}
+
+ def test_dynamic_scope(self):
+ one = ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/",
+ "children": [
+ {
+ "ID": "child/",
+ "children": [{"ID": "grandchild"}],
+ },
+ ],
+ },
+ )
+ two = ID_AND_CHILDREN.create_resource(
+ {
+ "ID": "http://example.com/two",
+ "children": [{"ID": "two-child/"}],
+ },
+ )
+ registry = [one, two] @ Registry()
+
+ resolver = registry.resolver()
+ first = resolver.lookup("http://example.com/")
+ second = first.resolver.lookup("#/children/0")
+ third = second.resolver.lookup("grandchild")
+ fourth = third.resolver.lookup("http://example.com/two")
+ assert list(fourth.resolver.dynamic_scope()) == [
+ ("http://example.com/child/grandchild", fourth.resolver._registry),
+ ("http://example.com/child/", fourth.resolver._registry),
+ ("http://example.com/", fourth.resolver._registry),
+ ]
+ assert list(third.resolver.dynamic_scope()) == [
+ ("http://example.com/child/", third.resolver._registry),
+ ("http://example.com/", third.resolver._registry),
+ ]
+ assert list(second.resolver.dynamic_scope()) == [
+ ("http://example.com/", second.resolver._registry),
+ ]
+ assert list(first.resolver.dynamic_scope()) == []
+
+
+class TestSpecification:
+ def test_create_resource(self):
+ specification = Specification(
+ name="",
+ id_of=lambda contents: "urn:fixedID",
+ subresources_of=lambda contents: [],
+ anchors_in=lambda specification, contents: [],
+ maybe_in_subresource=(
+ lambda segments, resolver, subresource: resolver
+ ),
+ )
+ resource = specification.create_resource(contents={"foo": "baz"})
+ assert resource == Resource(
+ contents={"foo": "baz"},
+ specification=specification,
+ )
+ assert resource.id() == "urn:fixedID"
+
+ def test_detect_from_json_schema(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ specification = Specification.detect(schema)
+ assert specification == DRAFT202012
+
+ def test_detect_with_no_discernible_information(self):
+ with pytest.raises(exceptions.CannotDetermineSpecification):
+ Specification.detect({"foo": "bar"})
+
+ def test_detect_with_non_URI_schema(self):
+ with pytest.raises(exceptions.CannotDetermineSpecification):
+ Specification.detect({"$schema": 37})
+
+ def test_detect_with_no_discernible_information_and_default(self):
+ specification = Specification.OPAQUE.detect({"foo": "bar"})
+ assert specification is Specification.OPAQUE
+
+ def test_detect_unneeded_default(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ specification = Specification.OPAQUE.detect(schema)
+ assert specification == DRAFT202012
+
+ def test_non_mapping_detect(self):
+ with pytest.raises(exceptions.CannotDetermineSpecification):
+ Specification.detect(True)
+
+ def test_non_mapping_detect_with_default(self):
+ specification = ID_AND_CHILDREN.detect(True)
+ assert specification is ID_AND_CHILDREN
+
+ def test_detect_with_fallback(self):
+ specification = Specification.OPAQUE.detect({"foo": "bar"})
+ assert specification is Specification.OPAQUE
+
+ def test_repr(self):
+ assert (
+ repr(ID_AND_CHILDREN) == ""
+ )
+
+
+class TestOpaqueSpecification:
+ THINGS = [{"foo": "bar"}, True, 37, "foo", object()]
+
+ @pytest.mark.parametrize("thing", THINGS)
+ def test_no_id(self, thing):
+ """
+ An arbitrary thing has no ID.
+ """
+
+ assert Specification.OPAQUE.id_of(thing) is None
+
+ @pytest.mark.parametrize("thing", THINGS)
+ def test_no_subresources(self, thing):
+ """
+ An arbitrary thing has no subresources.
+ """
+
+ assert list(Specification.OPAQUE.subresources_of(thing)) == []
+
+ @pytest.mark.parametrize("thing", THINGS)
+ def test_no_anchors(self, thing):
+ """
+ An arbitrary thing has no anchors.
+ """
+
+ assert list(Specification.OPAQUE.anchors_in(thing)) == []
+
+
+@pytest.mark.parametrize(
+ "cls",
+ [Anchor, Registry, Resource, Specification, exceptions.PointerToNowhere],
+)
+def test_nonsubclassable(cls):
+ with pytest.raises(Exception, match="(?i)subclassing"):
+
+ class Boom(cls): # pragma: no cover
+ pass
diff --git a/python_embeded/Lib/site-packages/referencing/tests/test_exceptions.py b/python_embeded/Lib/site-packages/referencing/tests/test_exceptions.py
new file mode 100644
index 0000000000000000000000000000000000000000..85cf99ecdd86c86e84df0b64f24aec6c447f4c08
--- /dev/null
+++ b/python_embeded/Lib/site-packages/referencing/tests/test_exceptions.py
@@ -0,0 +1,34 @@
+import itertools
+
+import pytest
+
+from referencing import Resource, exceptions
+
+
+def pairs(choices):
+ return itertools.combinations(choices, 2)
+
+
+TRUE = Resource.opaque(True)
+
+
+thunks = (
+ lambda: exceptions.CannotDetermineSpecification(TRUE),
+ lambda: exceptions.NoSuchResource("urn:example:foo"),
+ lambda: exceptions.NoInternalID(TRUE),
+ lambda: exceptions.InvalidAnchor(resource=TRUE, anchor="foo", ref="a#b"),
+ lambda: exceptions.NoSuchAnchor(resource=TRUE, anchor="foo", ref="a#b"),
+ lambda: exceptions.PointerToNowhere(resource=TRUE, ref="urn:example:foo"),
+ lambda: exceptions.Unresolvable("urn:example:foo"),
+ lambda: exceptions.Unretrievable("urn:example:foo"),
+)
+
+
+@pytest.mark.parametrize("one, two", pairs(each() for each in thunks))
+def test_eq_incompatible_types(one, two):
+ assert one != two
+
+
+@pytest.mark.parametrize("thunk", thunks)
+def test_hash(thunk):
+ assert thunk() in {thunk()}
diff --git a/python_embeded/Lib/site-packages/referencing/tests/test_jsonschema.py b/python_embeded/Lib/site-packages/referencing/tests/test_jsonschema.py
new file mode 100644
index 0000000000000000000000000000000000000000..c80714d0132bebbec33401f42a2e06aee3fed9c6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/referencing/tests/test_jsonschema.py
@@ -0,0 +1,382 @@
+import pytest
+
+from referencing import Registry, Resource, Specification
+import referencing.jsonschema
+
+
+@pytest.mark.parametrize(
+ "uri, expected",
+ [
+ (
+ "https://json-schema.org/draft/2020-12/schema",
+ referencing.jsonschema.DRAFT202012,
+ ),
+ (
+ "https://json-schema.org/draft/2019-09/schema",
+ referencing.jsonschema.DRAFT201909,
+ ),
+ (
+ "http://json-schema.org/draft-07/schema#",
+ referencing.jsonschema.DRAFT7,
+ ),
+ (
+ "http://json-schema.org/draft-06/schema#",
+ referencing.jsonschema.DRAFT6,
+ ),
+ (
+ "http://json-schema.org/draft-04/schema#",
+ referencing.jsonschema.DRAFT4,
+ ),
+ (
+ "http://json-schema.org/draft-03/schema#",
+ referencing.jsonschema.DRAFT3,
+ ),
+ ],
+)
+def test_schemas_with_explicit_schema_keywords_are_detected(uri, expected):
+ """
+ The $schema keyword in JSON Schema is a dialect identifier.
+ """
+ contents = {"$schema": uri}
+ resource = Resource.from_contents(contents)
+ assert resource == Resource(contents=contents, specification=expected)
+
+
+def test_unknown_dialect():
+ dialect_id = "http://example.com/unknown-json-schema-dialect-id"
+ with pytest.raises(referencing.jsonschema.UnknownDialect) as excinfo:
+ Resource.from_contents({"$schema": dialect_id})
+ assert excinfo.value.uri == dialect_id
+
+
+@pytest.mark.parametrize(
+ "id, specification",
+ [
+ ("$id", referencing.jsonschema.DRAFT202012),
+ ("$id", referencing.jsonschema.DRAFT201909),
+ ("$id", referencing.jsonschema.DRAFT7),
+ ("$id", referencing.jsonschema.DRAFT6),
+ ("id", referencing.jsonschema.DRAFT4),
+ ("id", referencing.jsonschema.DRAFT3),
+ ],
+)
+def test_id_of_mapping(id, specification):
+ uri = "http://example.com/some-schema"
+ assert specification.id_of({id: uri}) == uri
+
+
+@pytest.mark.parametrize(
+ "specification",
+ [
+ referencing.jsonschema.DRAFT202012,
+ referencing.jsonschema.DRAFT201909,
+ referencing.jsonschema.DRAFT7,
+ referencing.jsonschema.DRAFT6,
+ ],
+)
+@pytest.mark.parametrize("value", [True, False])
+def test_id_of_bool(specification, value):
+ assert specification.id_of(value) is None
+
+
+@pytest.mark.parametrize(
+ "specification",
+ [
+ referencing.jsonschema.DRAFT202012,
+ referencing.jsonschema.DRAFT201909,
+ referencing.jsonschema.DRAFT7,
+ referencing.jsonschema.DRAFT6,
+ ],
+)
+@pytest.mark.parametrize("value", [True, False])
+def test_anchors_in_bool(specification, value):
+ assert list(specification.anchors_in(value)) == []
+
+
+@pytest.mark.parametrize(
+ "specification",
+ [
+ referencing.jsonschema.DRAFT202012,
+ referencing.jsonschema.DRAFT201909,
+ referencing.jsonschema.DRAFT7,
+ referencing.jsonschema.DRAFT6,
+ ],
+)
+@pytest.mark.parametrize("value", [True, False])
+def test_subresources_of_bool(specification, value):
+ assert list(specification.subresources_of(value)) == []
+
+
+@pytest.mark.parametrize(
+ "uri, expected",
+ [
+ (
+ "https://json-schema.org/draft/2020-12/schema",
+ referencing.jsonschema.DRAFT202012,
+ ),
+ (
+ "https://json-schema.org/draft/2019-09/schema",
+ referencing.jsonschema.DRAFT201909,
+ ),
+ (
+ "http://json-schema.org/draft-07/schema#",
+ referencing.jsonschema.DRAFT7,
+ ),
+ (
+ "http://json-schema.org/draft-06/schema#",
+ referencing.jsonschema.DRAFT6,
+ ),
+ (
+ "http://json-schema.org/draft-04/schema#",
+ referencing.jsonschema.DRAFT4,
+ ),
+ (
+ "http://json-schema.org/draft-03/schema#",
+ referencing.jsonschema.DRAFT3,
+ ),
+ ],
+)
+def test_specification_with(uri, expected):
+ assert referencing.jsonschema.specification_with(uri) == expected
+
+
+@pytest.mark.parametrize(
+ "uri, expected",
+ [
+ (
+ "http://json-schema.org/draft-07/schema",
+ referencing.jsonschema.DRAFT7,
+ ),
+ (
+ "http://json-schema.org/draft-06/schema",
+ referencing.jsonschema.DRAFT6,
+ ),
+ (
+ "http://json-schema.org/draft-04/schema",
+ referencing.jsonschema.DRAFT4,
+ ),
+ (
+ "http://json-schema.org/draft-03/schema",
+ referencing.jsonschema.DRAFT3,
+ ),
+ ],
+)
+def test_specification_with_no_empty_fragment(uri, expected):
+ assert referencing.jsonschema.specification_with(uri) == expected
+
+
+def test_specification_with_unknown_dialect():
+ dialect_id = "http://example.com/unknown-json-schema-dialect-id"
+ with pytest.raises(referencing.jsonschema.UnknownDialect) as excinfo:
+ referencing.jsonschema.specification_with(dialect_id)
+ assert excinfo.value.uri == dialect_id
+
+
+def test_specification_with_default():
+ dialect_id = "http://example.com/unknown-json-schema-dialect-id"
+ specification = referencing.jsonschema.specification_with(
+ dialect_id,
+ default=Specification.OPAQUE,
+ )
+ assert specification is Specification.OPAQUE
+
+
+# FIXME: The tests below should move to the referencing suite but I haven't yet
+# figured out how to represent dynamic (& recursive) ref lookups in it.
+def test_lookup_trivial_dynamic_ref():
+ one = referencing.jsonschema.DRAFT202012.create_resource(
+ {"$dynamicAnchor": "foo"},
+ )
+ resolver = Registry().with_resource("http://example.com", one).resolver()
+ resolved = resolver.lookup("http://example.com#foo")
+ assert resolved.contents == one.contents
+
+
+def test_multiple_lookup_trivial_dynamic_ref():
+ TRUE = referencing.jsonschema.DRAFT202012.create_resource(True)
+ root = referencing.jsonschema.DRAFT202012.create_resource(
+ {
+ "$id": "http://example.com",
+ "$dynamicAnchor": "fooAnchor",
+ "$defs": {
+ "foo": {
+ "$id": "foo",
+ "$dynamicAnchor": "fooAnchor",
+ "$defs": {
+ "bar": True,
+ "baz": {
+ "$dynamicAnchor": "fooAnchor",
+ },
+ },
+ },
+ },
+ },
+ )
+ resolver = (
+ Registry()
+ .with_resources(
+ [
+ ("http://example.com", root),
+ ("http://example.com/foo/", TRUE),
+ ("http://example.com/foo/bar", root),
+ ],
+ )
+ .resolver()
+ )
+
+ first = resolver.lookup("http://example.com")
+ second = first.resolver.lookup("foo/")
+ resolver = second.resolver.lookup("bar").resolver
+ fourth = resolver.lookup("#fooAnchor")
+ assert fourth.contents == root.contents
+
+
+def test_multiple_lookup_dynamic_ref_to_nondynamic_ref():
+ one = referencing.jsonschema.DRAFT202012.create_resource(
+ {"$anchor": "fooAnchor"},
+ )
+ two = referencing.jsonschema.DRAFT202012.create_resource(
+ {
+ "$id": "http://example.com",
+ "$dynamicAnchor": "fooAnchor",
+ "$defs": {
+ "foo": {
+ "$id": "foo",
+ "$dynamicAnchor": "fooAnchor",
+ "$defs": {
+ "bar": True,
+ "baz": {
+ "$dynamicAnchor": "fooAnchor",
+ },
+ },
+ },
+ },
+ },
+ )
+ resolver = (
+ Registry()
+ .with_resources(
+ [
+ ("http://example.com", two),
+ ("http://example.com/foo/", one),
+ ("http://example.com/foo/bar", two),
+ ],
+ )
+ .resolver()
+ )
+
+ first = resolver.lookup("http://example.com")
+ second = first.resolver.lookup("foo/")
+ resolver = second.resolver.lookup("bar").resolver
+ fourth = resolver.lookup("#fooAnchor")
+ assert fourth.contents == two.contents
+
+
+def test_lookup_trivial_recursive_ref():
+ one = referencing.jsonschema.DRAFT201909.create_resource(
+ {"$recursiveAnchor": True},
+ )
+ resolver = Registry().with_resource("http://example.com", one).resolver()
+ first = resolver.lookup("http://example.com")
+ resolved = referencing.jsonschema.lookup_recursive_ref(
+ resolver=first.resolver,
+ )
+ assert resolved.contents == one.contents
+
+
+def test_lookup_recursive_ref_to_bool():
+ TRUE = referencing.jsonschema.DRAFT201909.create_resource(True)
+ registry = Registry({"http://example.com": TRUE})
+ resolved = referencing.jsonschema.lookup_recursive_ref(
+ resolver=registry.resolver(base_uri="http://example.com"),
+ )
+ assert resolved.contents == TRUE.contents
+
+
+def test_multiple_lookup_recursive_ref_to_bool():
+ TRUE = referencing.jsonschema.DRAFT201909.create_resource(True)
+ root = referencing.jsonschema.DRAFT201909.create_resource(
+ {
+ "$id": "http://example.com",
+ "$recursiveAnchor": True,
+ "$defs": {
+ "foo": {
+ "$id": "foo",
+ "$recursiveAnchor": True,
+ "$defs": {
+ "bar": True,
+ "baz": {
+ "$recursiveAnchor": True,
+ "$anchor": "fooAnchor",
+ },
+ },
+ },
+ },
+ },
+ )
+ resolver = (
+ Registry()
+ .with_resources(
+ [
+ ("http://example.com", root),
+ ("http://example.com/foo/", TRUE),
+ ("http://example.com/foo/bar", root),
+ ],
+ )
+ .resolver()
+ )
+
+ first = resolver.lookup("http://example.com")
+ second = first.resolver.lookup("foo/")
+ resolver = second.resolver.lookup("bar").resolver
+ fourth = referencing.jsonschema.lookup_recursive_ref(resolver=resolver)
+ assert fourth.contents == root.contents
+
+
+def test_multiple_lookup_recursive_ref_with_nonrecursive_ref():
+ one = referencing.jsonschema.DRAFT201909.create_resource(
+ {"$recursiveAnchor": True},
+ )
+ two = referencing.jsonschema.DRAFT201909.create_resource(
+ {
+ "$id": "http://example.com",
+ "$recursiveAnchor": True,
+ "$defs": {
+ "foo": {
+ "$id": "foo",
+ "$recursiveAnchor": True,
+ "$defs": {
+ "bar": True,
+ "baz": {
+ "$recursiveAnchor": True,
+ "$anchor": "fooAnchor",
+ },
+ },
+ },
+ },
+ },
+ )
+ three = referencing.jsonschema.DRAFT201909.create_resource(
+ {"$recursiveAnchor": False},
+ )
+ resolver = (
+ Registry()
+ .with_resources(
+ [
+ ("http://example.com", three),
+ ("http://example.com/foo/", two),
+ ("http://example.com/foo/bar", one),
+ ],
+ )
+ .resolver()
+ )
+
+ first = resolver.lookup("http://example.com")
+ second = first.resolver.lookup("foo/")
+ resolver = second.resolver.lookup("bar").resolver
+ fourth = referencing.jsonschema.lookup_recursive_ref(resolver=resolver)
+ assert fourth.contents == two.contents
+
+
+def test_empty_registry():
+ assert referencing.jsonschema.EMPTY_REGISTRY == Registry()
diff --git a/python_embeded/Lib/site-packages/referencing/tests/test_referencing_suite.py b/python_embeded/Lib/site-packages/referencing/tests/test_referencing_suite.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b8ae9177c197456bb3bbd62d4c1875bc95ff28b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/referencing/tests/test_referencing_suite.py
@@ -0,0 +1,66 @@
+from pathlib import Path
+import json
+import os
+
+import pytest
+
+from referencing import Registry
+from referencing.exceptions import Unresolvable
+import referencing.jsonschema
+
+
+class SuiteNotFound(Exception):
+ def __str__(self): # pragma: no cover
+ return (
+ "Cannot find the referencing suite. "
+ "Set the REFERENCING_SUITE environment variable to the path to "
+ "the suite, or run the test suite from alongside a full checkout "
+ "of the git repository."
+ )
+
+
+if "REFERENCING_SUITE" in os.environ: # pragma: no cover
+ SUITE = Path(os.environ["REFERENCING_SUITE"]) / "tests"
+else:
+ SUITE = Path(__file__).parent.parent.parent / "suite/tests"
+if not SUITE.is_dir(): # pragma: no cover
+ raise SuiteNotFound()
+DIALECT_IDS = json.loads(SUITE.joinpath("specifications.json").read_text())
+
+
+@pytest.mark.parametrize(
+ "test_path",
+ [
+ pytest.param(each, id=f"{each.parent.name}-{each.stem}")
+ for each in SUITE.glob("*/**/*.json")
+ ],
+)
+def test_referencing_suite(test_path, subtests):
+ dialect_id = DIALECT_IDS[test_path.relative_to(SUITE).parts[0]]
+ specification = referencing.jsonschema.specification_with(dialect_id)
+ loaded = json.loads(test_path.read_text())
+ registry = loaded["registry"]
+ registry = Registry().with_resources(
+ (uri, specification.create_resource(contents))
+ for uri, contents in loaded["registry"].items()
+ )
+ for test in loaded["tests"]:
+ with subtests.test(test=test):
+ if "normalization" in test_path.stem:
+ pytest.xfail("APIs need to change for proper URL support.")
+
+ resolver = registry.resolver(base_uri=test.get("base_uri", ""))
+
+ if test.get("error"):
+ with pytest.raises(Unresolvable):
+ resolver.lookup(test["ref"])
+ else:
+ resolved = resolver.lookup(test["ref"])
+ assert resolved.contents == test["target"]
+
+ then = test.get("then")
+ while then: # pragma: no cover
+ with subtests.test(test=test, then=then):
+ resolved = resolved.resolver.lookup(then["ref"])
+ assert resolved.contents == then["target"]
+ then = then.get("then")
diff --git a/python_embeded/Lib/site-packages/referencing/tests/test_retrieval.py b/python_embeded/Lib/site-packages/referencing/tests/test_retrieval.py
new file mode 100644
index 0000000000000000000000000000000000000000..d0a8f8ad9975d1a760bca14dea7b60d41fb8ea75
--- /dev/null
+++ b/python_embeded/Lib/site-packages/referencing/tests/test_retrieval.py
@@ -0,0 +1,106 @@
+from functools import lru_cache
+import json
+
+import pytest
+
+from referencing import Registry, Resource, exceptions
+from referencing.jsonschema import DRAFT202012
+from referencing.retrieval import to_cached_resource
+
+
+class TestToCachedResource:
+ def test_it_caches_retrieved_resources(self):
+ contents = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ stack = [json.dumps(contents)]
+
+ @to_cached_resource()
+ def retrieve(uri):
+ return stack.pop()
+
+ registry = Registry(retrieve=retrieve)
+
+ expected = Resource.from_contents(contents)
+
+ got = registry.get_or_retrieve("urn:example:schema")
+ assert got.value == expected
+
+ # And a second time we get the same value.
+ again = registry.get_or_retrieve("urn:example:schema")
+ assert again.value is got.value
+
+ def test_custom_loader(self):
+ contents = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ stack = [json.dumps(contents)[::-1]]
+
+ @to_cached_resource(loads=lambda s: json.loads(s[::-1]))
+ def retrieve(uri):
+ return stack.pop()
+
+ registry = Registry(retrieve=retrieve)
+
+ expected = Resource.from_contents(contents)
+
+ got = registry.get_or_retrieve("urn:example:schema")
+ assert got.value == expected
+
+ # And a second time we get the same value.
+ again = registry.get_or_retrieve("urn:example:schema")
+ assert again.value is got.value
+
+ def test_custom_from_contents(self):
+ contents = {}
+ stack = [json.dumps(contents)]
+
+ @to_cached_resource(from_contents=DRAFT202012.create_resource)
+ def retrieve(uri):
+ return stack.pop()
+
+ registry = Registry(retrieve=retrieve)
+
+ expected = DRAFT202012.create_resource(contents)
+
+ got = registry.get_or_retrieve("urn:example:schema")
+ assert got.value == expected
+
+ # And a second time we get the same value.
+ again = registry.get_or_retrieve("urn:example:schema")
+ assert again.value is got.value
+
+ def test_custom_cache(self):
+ schema = {"$schema": "https://json-schema.org/draft/2020-12/schema"}
+ mapping = {
+ "urn:example:1": dict(schema, foo=1),
+ "urn:example:2": dict(schema, foo=2),
+ "urn:example:3": dict(schema, foo=3),
+ }
+
+ resources = {
+ uri: Resource.from_contents(contents)
+ for uri, contents in mapping.items()
+ }
+
+ @to_cached_resource(cache=lru_cache(maxsize=2))
+ def retrieve(uri):
+ return json.dumps(mapping.pop(uri))
+
+ registry = Registry(retrieve=retrieve)
+
+ got = registry.get_or_retrieve("urn:example:1")
+ assert got.value == resources["urn:example:1"]
+ assert registry.get_or_retrieve("urn:example:1").value is got.value
+ assert registry.get_or_retrieve("urn:example:1").value is got.value
+
+ got = registry.get_or_retrieve("urn:example:2")
+ assert got.value == resources["urn:example:2"]
+ assert registry.get_or_retrieve("urn:example:2").value is got.value
+ assert registry.get_or_retrieve("urn:example:2").value is got.value
+
+ # This still succeeds, but evicts the first URI
+ got = registry.get_or_retrieve("urn:example:3")
+ assert got.value == resources["urn:example:3"]
+ assert registry.get_or_retrieve("urn:example:3").value is got.value
+ assert registry.get_or_retrieve("urn:example:3").value is got.value
+
+ # And now this fails (as we popped the value out of `mapping`)
+ with pytest.raises(exceptions.Unretrievable):
+ registry.get_or_retrieve("urn:example:1")
diff --git a/python_embeded/Lib/site-packages/rembg-2.0.66.dist-info/licenses/LICENSE.txt b/python_embeded/Lib/site-packages/rembg-2.0.66.dist-info/licenses/LICENSE.txt
new file mode 100644
index 0000000000000000000000000000000000000000..efe94fb589c9801994f763754fad5c978fd39a14
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg-2.0.66.dist-info/licenses/LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2020 Daniel Gatis
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/python_embeded/Lib/site-packages/rembg/commands/__init__.py b/python_embeded/Lib/site-packages/rembg/commands/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc2ac690c4220e42cf1df638df6525dfe6f9ed3c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/commands/__init__.py
@@ -0,0 +1,13 @@
+command_functions = []
+
+from .b_command import b_command
+from .d_command import d_command
+from .i_command import i_command
+from .p_command import p_command
+from .s_command import s_command
+
+command_functions.append(b_command)
+command_functions.append(d_command)
+command_functions.append(i_command)
+command_functions.append(p_command)
+command_functions.append(s_command)
diff --git a/python_embeded/Lib/site-packages/rembg/commands/b_command.py b/python_embeded/Lib/site-packages/rembg/commands/b_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..402e17ed889595f5df471781c47f98a5551d3987
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/commands/b_command.py
@@ -0,0 +1,178 @@
+import asyncio
+import io
+import json
+import os
+import sys
+from typing import IO
+
+import click
+import PIL
+
+from ..bg import remove
+from ..session_factory import new_session
+from ..sessions import sessions_names
+
+
+@click.command( # type: ignore
+ name="b",
+ help="for a byte stream as input",
+)
+@click.option(
+ "-m",
+ "--model",
+ default="u2net",
+ type=click.Choice(sessions_names),
+ show_default=True,
+ show_choices=True,
+ help="model name",
+)
+@click.option(
+ "-a",
+ "--alpha-matting",
+ is_flag=True,
+ show_default=True,
+ help="use alpha matting",
+)
+@click.option(
+ "-af",
+ "--alpha-matting-foreground-threshold",
+ default=240,
+ type=int,
+ show_default=True,
+ help="trimap fg threshold",
+)
+@click.option(
+ "-ab",
+ "--alpha-matting-background-threshold",
+ default=10,
+ type=int,
+ show_default=True,
+ help="trimap bg threshold",
+)
+@click.option(
+ "-ae",
+ "--alpha-matting-erode-size",
+ default=10,
+ type=int,
+ show_default=True,
+ help="erode size",
+)
+@click.option(
+ "-om",
+ "--only-mask",
+ is_flag=True,
+ show_default=True,
+ help="output only the mask",
+)
+@click.option(
+ "-ppm",
+ "--post-process-mask",
+ is_flag=True,
+ show_default=True,
+ help="post process the mask",
+)
+@click.option(
+ "-bgc",
+ "--bgcolor",
+ default=(0, 0, 0, 0),
+ type=(int, int, int, int),
+ nargs=4,
+ help="Background color (R G B A) to replace the removed background with",
+)
+@click.option("-x", "--extras", type=str)
+@click.option(
+ "-o",
+ "--output_specifier",
+ type=str,
+ help="printf-style specifier for output filenames (e.g. 'output-%d.png'))",
+)
+@click.argument(
+ "image_width",
+ type=int,
+)
+@click.argument(
+ "image_height",
+ type=int,
+)
+def b_command(
+ model: str,
+ extras: str,
+ image_width: int,
+ image_height: int,
+ output_specifier: str,
+ **kwargs
+) -> None:
+ """
+ Command-line interface for processing images by removing the background using a specified model and generating a mask.
+
+ This CLI command takes several options and arguments to configure the background removal process and save the processed images.
+
+ Parameters:
+ model (str): The name of the model to use for background removal.
+ extras (str): Additional options in JSON format that can be passed to customize the background removal process.
+ image_width (int): The width of the input images in pixels.
+ image_height (int): The height of the input images in pixels.
+ output_specifier (str): A printf-style specifier for the output filenames. If specified, the processed images will be saved to the specified output directory with filenames generated using the specifier.
+ **kwargs: Additional keyword arguments that can be used to customize the background removal process.
+
+ Returns:
+ None
+ """
+ if extras:
+ try:
+ kwargs.update(json.loads(extras))
+ except Exception:
+ raise click.BadParameter("extras must be a valid JSON string")
+
+ session = new_session(model, **kwargs)
+ bytes_per_img = image_width * image_height * 3
+
+ if output_specifier:
+ output_dir = os.path.dirname(
+ os.path.abspath(os.path.expanduser(output_specifier))
+ )
+
+ if not os.path.isdir(output_dir):
+ os.makedirs(output_dir, exist_ok=True)
+
+ def img_to_byte_array(img: PIL.Image.Image) -> bytes:
+ buff = io.BytesIO()
+ img.save(buff, format="PNG")
+ return buff.getvalue()
+
+ async def connect_stdin_stdout():
+ loop = asyncio.get_event_loop()
+ reader = asyncio.StreamReader()
+ protocol = asyncio.StreamReaderProtocol(reader)
+
+ await loop.connect_read_pipe(lambda: protocol, sys.stdin)
+ w_transport, w_protocol = await loop.connect_write_pipe(
+ asyncio.streams.FlowControlMixin, sys.stdout
+ )
+
+ writer = asyncio.StreamWriter(w_transport, w_protocol, reader, loop)
+ return reader, writer
+
+ async def main():
+ reader, writer = await connect_stdin_stdout()
+
+ idx = 0
+ while True:
+ try:
+ img_bytes = await reader.readexactly(bytes_per_img)
+ if not img_bytes:
+ break
+
+ img = PIL.Image.frombytes("RGB", (image_width, image_height), img_bytes)
+ output = remove(img, session=session, **kwargs)
+
+ if output_specifier:
+ output.save((output_specifier % idx), format="PNG")
+ else:
+ writer.write(img_to_byte_array(output))
+
+ idx += 1
+ except asyncio.IncompleteReadError:
+ break
+
+ asyncio.run(main())
diff --git a/python_embeded/Lib/site-packages/rembg/commands/d_command.py b/python_embeded/Lib/site-packages/rembg/commands/d_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe2f095b86c9ac529b6e6772e29a1b79b2b9c550
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/commands/d_command.py
@@ -0,0 +1,15 @@
+import click
+
+from ..bg import download_models
+
+
+@click.command( # type: ignore
+ name="d",
+ help="download models",
+)
+@click.argument("models", nargs=-1)
+def d_command(models: tuple[str, ...]) -> None:
+ """
+ Download models
+ """
+ download_models(models)
diff --git a/python_embeded/Lib/site-packages/rembg/commands/i_command.py b/python_embeded/Lib/site-packages/rembg/commands/i_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..84541428c4c8582b3a3ca1dab171c734be5fd1a0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/commands/i_command.py
@@ -0,0 +1,108 @@
+import json
+import sys
+from typing import IO
+
+import click
+
+from ..bg import remove
+from ..session_factory import new_session
+from ..sessions import sessions_names
+
+
+@click.command( # type: ignore
+ name="i",
+ help="for a file as input",
+)
+@click.option(
+ "-m",
+ "--model",
+ default="u2net",
+ type=click.Choice(sessions_names),
+ show_default=True,
+ show_choices=True,
+ help="model name",
+)
+@click.option(
+ "-a",
+ "--alpha-matting",
+ is_flag=True,
+ show_default=True,
+ help="use alpha matting",
+)
+@click.option(
+ "-af",
+ "--alpha-matting-foreground-threshold",
+ default=240,
+ type=int,
+ show_default=True,
+ help="trimap fg threshold",
+)
+@click.option(
+ "-ab",
+ "--alpha-matting-background-threshold",
+ default=10,
+ type=int,
+ show_default=True,
+ help="trimap bg threshold",
+)
+@click.option(
+ "-ae",
+ "--alpha-matting-erode-size",
+ default=10,
+ type=int,
+ show_default=True,
+ help="erode size",
+)
+@click.option(
+ "-om",
+ "--only-mask",
+ is_flag=True,
+ show_default=True,
+ help="output only the mask",
+)
+@click.option(
+ "-ppm",
+ "--post-process-mask",
+ is_flag=True,
+ show_default=True,
+ help="post process the mask",
+)
+@click.option(
+ "-bgc",
+ "--bgcolor",
+ default=(0, 0, 0, 0),
+ type=(int, int, int, int),
+ nargs=4,
+ help="Background color (R G B A) to replace the removed background with",
+)
+@click.option("-x", "--extras", type=str)
+@click.argument(
+ "input", default=(None if sys.stdin.isatty() else "-"), type=click.File("rb")
+)
+@click.argument(
+ "output",
+ default=(None if sys.stdin.isatty() else "-"),
+ type=click.File("wb", lazy=True),
+)
+def i_command(model: str, extras: str, input: IO, output: IO, **kwargs) -> None:
+ """
+ Click command line interface function to process an input file based on the provided options.
+
+ This function is the entry point for the CLI program. It reads an input file, applies image processing operations based on the provided options, and writes the output to a file.
+
+ Parameters:
+ model (str): The name of the model to use for image processing.
+ extras (str): Additional options in JSON format.
+ input: The input file to process.
+ output: The output file to write the processed image to.
+ **kwargs: Additional keyword arguments corresponding to the command line options.
+
+ Returns:
+ None
+ """
+ try:
+ kwargs.update(json.loads(extras))
+ except Exception:
+ pass
+
+ output.write(remove(input.read(), session=new_session(model, **kwargs), **kwargs))
diff --git a/python_embeded/Lib/site-packages/rembg/commands/p_command.py b/python_embeded/Lib/site-packages/rembg/commands/p_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..b9ce08e84d939d3c1aaf8120cd869b7b47119263
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/commands/p_command.py
@@ -0,0 +1,226 @@
+import json
+import pathlib
+import time
+from typing import cast
+
+import click
+import filetype
+from tqdm import tqdm
+from watchdog.events import FileSystemEvent, FileSystemEventHandler
+from watchdog.observers import Observer
+
+from ..bg import remove
+from ..session_factory import new_session
+from ..sessions import sessions_names
+
+
+@click.command( # type: ignore
+ name="p",
+ help="for a folder as input",
+)
+@click.option(
+ "-m",
+ "--model",
+ default="u2net",
+ type=click.Choice(sessions_names),
+ show_default=True,
+ show_choices=True,
+ help="model name",
+)
+@click.option(
+ "-a",
+ "--alpha-matting",
+ is_flag=True,
+ show_default=True,
+ help="use alpha matting",
+)
+@click.option(
+ "-af",
+ "--alpha-matting-foreground-threshold",
+ default=240,
+ type=int,
+ show_default=True,
+ help="trimap fg threshold",
+)
+@click.option(
+ "-ab",
+ "--alpha-matting-background-threshold",
+ default=10,
+ type=int,
+ show_default=True,
+ help="trimap bg threshold",
+)
+@click.option(
+ "-ae",
+ "--alpha-matting-erode-size",
+ default=10,
+ type=int,
+ show_default=True,
+ help="erode size",
+)
+@click.option(
+ "-om",
+ "--only-mask",
+ is_flag=True,
+ show_default=True,
+ help="output only the mask",
+)
+@click.option(
+ "-ppm",
+ "--post-process-mask",
+ is_flag=True,
+ show_default=True,
+ help="post process the mask",
+)
+@click.option(
+ "-w",
+ "--watch",
+ default=False,
+ is_flag=True,
+ show_default=True,
+ help="watches a folder for changes",
+)
+@click.option(
+ "-d",
+ "--delete_input",
+ default=False,
+ is_flag=True,
+ show_default=True,
+ help="delete input file after processing",
+)
+@click.option(
+ "-bgc",
+ "--bgcolor",
+ default=(0, 0, 0, 0),
+ type=(int, int, int, int),
+ nargs=4,
+ help="Background color (R G B A) to replace the removed background with",
+)
+@click.option("-x", "--extras", type=str)
+@click.argument(
+ "input",
+ type=click.Path(
+ exists=True,
+ path_type=pathlib.Path,
+ file_okay=False,
+ dir_okay=True,
+ readable=True,
+ ),
+)
+@click.argument(
+ "output",
+ type=click.Path(
+ exists=False,
+ path_type=pathlib.Path,
+ file_okay=False,
+ dir_okay=True,
+ writable=True,
+ ),
+)
+def p_command(
+ model: str,
+ extras: str,
+ input: pathlib.Path,
+ output: pathlib.Path,
+ watch: bool,
+ delete_input: bool,
+ **kwargs,
+) -> None:
+ """
+ Command-line interface (CLI) program for performing background removal on images in a folder.
+
+ This program takes a folder as input and uses a specified model to remove the background from the images in the folder.
+ It provides various options for configuration, such as choosing the model, enabling alpha matting, setting trimap thresholds, erode size, etc.
+ Additional options include outputting only the mask and post-processing the mask.
+ The program can also watch the input folder for changes and automatically process new images.
+ The resulting images with the background removed are saved in the specified output folder.
+
+ Parameters:
+ model (str): The name of the model to use for background removal.
+ extras (str): Additional options in JSON format.
+ input (pathlib.Path): The path to the input folder.
+ output (pathlib.Path): The path to the output folder.
+ watch (bool): Whether to watch the input folder for changes.
+ delete_input (bool): Whether to delete the input file after processing.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ None
+ """
+ try:
+ kwargs.update(json.loads(extras))
+ except Exception:
+ pass
+
+ session = new_session(model, **kwargs)
+
+ def process(each_input: pathlib.Path) -> None:
+ try:
+ mimetype = filetype.guess(each_input)
+ if mimetype is None:
+ return
+ if mimetype.mime.find("image") < 0:
+ return
+
+ each_output = (output / each_input.name).with_suffix(".png")
+ each_output.parents[0].mkdir(parents=True, exist_ok=True)
+
+ if not each_output.exists():
+ each_output.write_bytes(
+ cast(
+ bytes,
+ remove(each_input.read_bytes(), session=session, **kwargs),
+ )
+ )
+
+ if watch:
+ print(
+ f"processed: {each_input.absolute()} -> {each_output.absolute()}"
+ )
+
+ if delete_input:
+ each_input.unlink()
+
+ except Exception as e:
+ print(e)
+
+ inputs = list(input.glob("**/*"))
+ if not watch:
+ inputs_tqdm = tqdm(inputs)
+
+ for each_input in inputs_tqdm:
+ if not each_input.is_dir():
+ process(each_input)
+
+ if watch:
+ should_watch = True
+ observer = Observer()
+
+ class EventHandler(FileSystemEventHandler):
+ def on_any_event(self, event: FileSystemEvent) -> None:
+ src_path = cast(str, event.src_path)
+ if (
+ not (
+ event.is_directory or event.event_type in ["deleted", "closed"]
+ )
+ and pathlib.Path(src_path).exists()
+ ):
+ if src_path.endswith("stop.txt"):
+ nonlocal should_watch
+ should_watch = False
+ pathlib.Path(src_path).unlink()
+ return
+
+ process(pathlib.Path(src_path))
+
+ event_handler = EventHandler()
+ observer.schedule(event_handler, str(input), recursive=False)
+ observer.start()
+
+ try:
+ while should_watch:
+ time.sleep(1)
+
+ finally:
+ observer.stop()
+ observer.join()
diff --git a/python_embeded/Lib/site-packages/rembg/commands/s_command.py b/python_embeded/Lib/site-packages/rembg/commands/s_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f70cb7983486f2786d22f2461f7bfa8091367ce
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/commands/s_command.py
@@ -0,0 +1,322 @@
+import json
+import os
+import webbrowser
+from typing import Optional, Tuple, cast
+
+import aiohttp
+import click
+import gradio as gr
+import uvicorn
+from asyncer import asyncify
+from fastapi import Depends, FastAPI, File, Form, Query
+from fastapi.middleware.cors import CORSMiddleware
+from starlette.responses import Response
+
+from .._version import get_versions
+from ..bg import remove
+from ..session_factory import new_session
+from ..sessions import sessions_names
+from ..sessions.base import BaseSession
+
+
+@click.command( # type: ignore
+ name="s",
+ help="for a http server",
+)
+@click.option(
+ "-p",
+ "--port",
+ default=7000,
+ type=int,
+ show_default=True,
+ help="port",
+)
+@click.option(
+ "-h",
+ "--host",
+ default="0.0.0.0",
+ type=str,
+ show_default=True,
+ help="host",
+)
+@click.option(
+ "-l",
+ "--log_level",
+ default="info",
+ type=str,
+ show_default=True,
+ help="log level",
+)
+@click.option(
+ "-t",
+ "--threads",
+ default=None,
+ type=int,
+ show_default=True,
+ help="number of worker threads",
+)
+def s_command(port: int, host: str, log_level: str, threads: int) -> None:
+ """
+ Command-line interface for running the FastAPI web server.
+
+ This function starts the FastAPI web server with the specified port and log level.
+ If the number of worker threads is specified, it sets the thread limiter accordingly.
+ """
+ sessions: dict[str, BaseSession] = {}
+ tags_metadata = [
+ {
+ "name": "Background Removal",
+ "description": "Endpoints that perform background removal with different image sources.",
+ "externalDocs": {
+ "description": "GitHub Source",
+ "url": "https://github.com/danielgatis/rembg",
+ },
+ },
+ ]
+ app = FastAPI(
+ title="Rembg",
+ description="Rembg is a tool to remove images background. That is it.",
+ version=get_versions()["version"],
+ contact={
+ "name": "Daniel Gatis",
+ "url": "https://github.com/danielgatis",
+ "email": "danielgatis@gmail.com",
+ },
+ license_info={
+ "name": "MIT License",
+ "url": "https://github.com/danielgatis/rembg/blob/main/LICENSE.txt",
+ },
+ openapi_tags=tags_metadata,
+ docs_url="/api",
+ )
+
+ app.add_middleware(
+ CORSMiddleware,
+ allow_credentials=True,
+ allow_origins=["*"],
+ allow_methods=["*"],
+ allow_headers=["*"],
+ )
+
+ class CommonQueryParams:
+ def __init__(
+ self,
+ model: str = Query(
+ description="Model to use when processing image",
+ regex=r"(" + "|".join(sessions_names) + ")",
+ default="u2net",
+ ),
+ a: bool = Query(default=False, description="Enable Alpha Matting"),
+ af: int = Query(
+ default=240,
+ ge=0,
+ le=255,
+ description="Alpha Matting (Foreground Threshold)",
+ ),
+ ab: int = Query(
+ default=10,
+ ge=0,
+ le=255,
+ description="Alpha Matting (Background Threshold)",
+ ),
+ ae: int = Query(
+ default=10, ge=0, description="Alpha Matting (Erode Structure Size)"
+ ),
+ om: bool = Query(default=False, description="Only Mask"),
+ ppm: bool = Query(default=False, description="Post Process Mask"),
+ bgc: Optional[str] = Query(default=None, description="Background Color"),
+ extras: Optional[str] = Query(
+ default=None, description="Extra parameters as JSON"
+ ),
+ ):
+ self.model = model
+ self.a = a
+ self.af = af
+ self.ab = ab
+ self.ae = ae
+ self.om = om
+ self.ppm = ppm
+ self.extras = extras
+ self.bgc = (
+ cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))
+ if bgc
+ else None
+ )
+
+ class CommonQueryPostParams:
+ def __init__(
+ self,
+ model: str = Form(
+ description="Model to use when processing image",
+ regex=r"(" + "|".join(sessions_names) + ")",
+ default="u2net",
+ ),
+ a: bool = Form(default=False, description="Enable Alpha Matting"),
+ af: int = Form(
+ default=240,
+ ge=0,
+ le=255,
+ description="Alpha Matting (Foreground Threshold)",
+ ),
+ ab: int = Form(
+ default=10,
+ ge=0,
+ le=255,
+ description="Alpha Matting (Background Threshold)",
+ ),
+ ae: int = Form(
+ default=10, ge=0, description="Alpha Matting (Erode Structure Size)"
+ ),
+ om: bool = Form(default=False, description="Only Mask"),
+ ppm: bool = Form(default=False, description="Post Process Mask"),
+ bgc: Optional[str] = Query(default=None, description="Background Color"),
+ extras: Optional[str] = Query(
+ default=None, description="Extra parameters as JSON"
+ ),
+ ):
+ self.model = model
+ self.a = a
+ self.af = af
+ self.ab = ab
+ self.ae = ae
+ self.om = om
+ self.ppm = ppm
+ self.extras = extras
+ self.bgc = (
+ cast(Tuple[int, int, int, int], tuple(map(int, bgc.split(","))))
+ if bgc
+ else None
+ )
+
+ def im_without_bg(content: bytes, commons: CommonQueryParams) -> Response:
+ kwargs = {}
+
+ if commons.extras:
+ try:
+ kwargs.update(json.loads(commons.extras))
+ except Exception:
+ pass
+
+ return Response(
+ remove(
+ content,
+ session=sessions.setdefault(
+ commons.model, new_session(commons.model, **kwargs)
+ ),
+ alpha_matting=commons.a,
+ alpha_matting_foreground_threshold=commons.af,
+ alpha_matting_background_threshold=commons.ab,
+ alpha_matting_erode_size=commons.ae,
+ only_mask=commons.om,
+ post_process_mask=commons.ppm,
+ bgcolor=commons.bgc,
+ **kwargs,
+ ),
+ media_type="image/png",
+ )
+
+ @app.on_event("startup")
+ def startup():
+ try:
+ webbrowser.open(f"http://localhost:{port}")
+ except Exception:
+ pass
+
+ if threads is not None:
+ from anyio import CapacityLimiter
+ from anyio.lowlevel import RunVar
+
+ RunVar("_default_thread_limiter").set(CapacityLimiter(threads))
+
+ @app.get(
+ path="/api/remove",
+ tags=["Background Removal"],
+ summary="Remove from URL",
+ description="Removes the background from an image obtained by retrieving an URL.",
+ )
+ async def get_index(
+ url: str = Query(
+ default=..., description="URL of the image that has to be processed."
+ ),
+ commons: CommonQueryParams = Depends(),
+ ):
+ async with aiohttp.ClientSession() as session:
+ async with session.get(url) as response:
+ file = await response.read()
+ return await asyncify(im_without_bg)(file, commons)
+
+ @app.post(
+ path="/api/remove",
+ tags=["Background Removal"],
+ summary="Remove from Stream",
+ description="Removes the background from an image sent within the request itself.",
+ )
+ async def post_index(
+ file: bytes = File(
+ default=...,
+ description="Image file (byte stream) that has to be processed.",
+ ),
+ commons: CommonQueryPostParams = Depends(),
+ ):
+ return await asyncify(im_without_bg)(file, commons) # type: ignore
+
+ def gr_app(app):
+ def inference(input_path, model, *args):
+ output_path = "output.png"
+ a, af, ab, ae, om, ppm, cmd_args = args
+
+ kwargs = {
+ "alpha_matting": a,
+ "alpha_matting_foreground_threshold": af,
+ "alpha_matting_background_threshold": ab,
+ "alpha_matting_erode_size": ae,
+ "only_mask": om,
+ "post_process_mask": ppm,
+ }
+
+ if cmd_args:
+ kwargs.update(json.loads(cmd_args))
+ kwargs["session"] = new_session(model, **kwargs)
+
+ with open(input_path, "rb") as i:
+ with open(output_path, "wb") as o:
+ input = i.read()
+ output = remove(input, **kwargs)
+ o.write(output)
+ return os.path.join(output_path)
+
+ interface = gr.Interface(
+ inference,
+ [
+ gr.components.Image(type="filepath", label="Input"),
+ gr.components.Dropdown(sessions_names, value="u2net", label="Models"),
+ gr.components.Checkbox(value=True, label="Alpha matting"),
+ gr.components.Slider(
+ value=240, minimum=0, maximum=255, label="Foreground threshold"
+ ),
+ gr.components.Slider(
+ value=10, minimum=0, maximum=255, label="Background threshold"
+ ),
+ gr.components.Slider(
+ value=40, minimum=0, maximum=255, label="Erosion size"
+ ),
+ gr.components.Checkbox(value=False, label="Only mask"),
+ gr.components.Checkbox(value=True, label="Post process mask"),
+ gr.components.Textbox(label="Arguments"),
+ ],
+ gr.components.Image(type="filepath", label="Output"),
+ concurrency_limit=3,
+ analytics_enabled=False,
+ )
+
+ app = gr.mount_gradio_app(app, interface, path="/")
+ return app
+
+ print(
+ f"To access the API documentation, go to http://{'localhost' if host == '0.0.0.0' else host}:{port}/api"
+ )
+ print(
+ f"To access the UI, go to http://{'localhost' if host == '0.0.0.0' else host}:{port}"
+ )
+
+ uvicorn.run(gr_app(app), host=host, port=port, log_level=log_level)
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/__init__.py b/python_embeded/Lib/site-packages/rembg/sessions/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dbf4fb178d763bcd37ed0a70567a09d41237298c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/__init__.py
@@ -0,0 +1,78 @@
+from __future__ import annotations
+
+from typing import Dict, List
+
+from .base import BaseSession
+
+sessions: Dict[str, type[BaseSession]] = {}
+
+from .birefnet_general import BiRefNetSessionGeneral
+
+sessions[BiRefNetSessionGeneral.name()] = BiRefNetSessionGeneral
+
+from .birefnet_general_lite import BiRefNetSessionGeneralLite
+
+sessions[BiRefNetSessionGeneralLite.name()] = BiRefNetSessionGeneralLite
+
+from .birefnet_portrait import BiRefNetSessionPortrait
+
+sessions[BiRefNetSessionPortrait.name()] = BiRefNetSessionPortrait
+
+from .birefnet_dis import BiRefNetSessionDIS
+
+sessions[BiRefNetSessionDIS.name()] = BiRefNetSessionDIS
+
+from .birefnet_hrsod import BiRefNetSessionHRSOD
+
+sessions[BiRefNetSessionHRSOD.name()] = BiRefNetSessionHRSOD
+
+from .birefnet_cod import BiRefNetSessionCOD
+
+sessions[BiRefNetSessionCOD.name()] = BiRefNetSessionCOD
+
+from .birefnet_massive import BiRefNetSessionMassive
+
+sessions[BiRefNetSessionMassive.name()] = BiRefNetSessionMassive
+
+from .dis_anime import DisSession
+
+sessions[DisSession.name()] = DisSession
+
+from .dis_general_use import DisSession as DisSessionGeneralUse
+
+sessions[DisSessionGeneralUse.name()] = DisSessionGeneralUse
+
+from .sam import SamSession
+
+sessions[SamSession.name()] = SamSession
+
+from .silueta import SiluetaSession
+
+sessions[SiluetaSession.name()] = SiluetaSession
+
+from .u2net_cloth_seg import Unet2ClothSession
+
+sessions[Unet2ClothSession.name()] = Unet2ClothSession
+
+from .u2net_custom import U2netCustomSession
+
+sessions[U2netCustomSession.name()] = U2netCustomSession
+
+from .u2net_human_seg import U2netHumanSegSession
+
+sessions[U2netHumanSegSession.name()] = U2netHumanSegSession
+
+from .u2net import U2netSession
+
+sessions[U2netSession.name()] = U2netSession
+
+from .u2netp import U2netpSession
+
+sessions[U2netpSession.name()] = U2netpSession
+
+from .bria_rmbg import BriaRmBgSession
+
+sessions[BriaRmBgSession.name()] = BriaRmBgSession
+
+sessions_names = list(sessions.keys())
+sessions_class = list(sessions.values())
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/base.py b/python_embeded/Lib/site-packages/rembg/sessions/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..2e2bcd5b99bfea4c69b5f214e4419fdf86514894
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/base.py
@@ -0,0 +1,85 @@
+import os
+from typing import Dict, List, Tuple
+
+import numpy as np
+import onnxruntime as ort
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+
+class BaseSession:
+ """This is a base class for managing a session with a machine learning model."""
+
+ def __init__(self, model_name: str, sess_opts: ort.SessionOptions, *args, **kwargs):
+ """Initialize an instance of the BaseSession class."""
+ self.model_name = model_name
+
+ device_type = ort.get_device()
+ if (
+ device_type == "GPU"
+ and "CUDAExecutionProvider" in ort.get_available_providers()
+ ):
+ providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
+ elif (
+ device_type[0:3] == "GPU"
+ and "ROCMExecutionProvider" in ort.get_available_providers()
+ ):
+ providers = ["ROCMExecutionProvider", "CPUExecutionProvider"]
+ else:
+ providers = ["CPUExecutionProvider"]
+
+ self.inner_session = ort.InferenceSession(
+ str(self.__class__.download_models(*args, **kwargs)),
+ sess_options=sess_opts,
+ providers=providers,
+ )
+
+ def normalize(
+ self,
+ img: PILImage,
+ mean: Tuple[float, float, float],
+ std: Tuple[float, float, float],
+ size: Tuple[int, int],
+ *args,
+ **kwargs
+ ) -> Dict[str, np.ndarray]:
+ im = img.convert("RGB").resize(size, Image.Resampling.LANCZOS)
+
+ im_ary = np.array(im)
+ im_ary = im_ary / max(np.max(im_ary), 1e-6)
+
+ tmpImg = np.zeros((im_ary.shape[0], im_ary.shape[1], 3))
+ tmpImg[:, :, 0] = (im_ary[:, :, 0] - mean[0]) / std[0]
+ tmpImg[:, :, 1] = (im_ary[:, :, 1] - mean[1]) / std[1]
+ tmpImg[:, :, 2] = (im_ary[:, :, 2] - mean[2]) / std[2]
+
+ tmpImg = tmpImg.transpose((2, 0, 1))
+
+ return {
+ self.inner_session.get_inputs()[0]
+ .name: np.expand_dims(tmpImg, 0)
+ .astype(np.float32)
+ }
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ raise NotImplementedError
+
+ @classmethod
+ def checksum_disabled(cls, *args, **kwargs):
+ return os.getenv("MODEL_CHECKSUM_DISABLED", None) is not None
+
+ @classmethod
+ def u2net_home(cls, *args, **kwargs):
+ return os.path.expanduser(
+ os.getenv(
+ "U2NET_HOME", os.path.join(os.getenv("XDG_DATA_HOME", "~"), ".u2net")
+ )
+ )
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ raise NotImplementedError
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ raise NotImplementedError
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_cod.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_cod.py
new file mode 100644
index 0000000000000000000000000000000000000000..d678f1a51aaed7e46a5069f7fd60b9dc47ffec5a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_cod.py
@@ -0,0 +1,52 @@
+import os
+
+import pooch
+
+from . import BiRefNetSessionGeneral
+
+
+class BiRefNetSessionCOD(BiRefNetSessionGeneral):
+ """
+ This class represents a BiRefNet-COD session, which is a subclass of BiRefNetSessionGeneral.
+ """
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-COD model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-COD-epoch_125.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:f6d0d21ca89d287f17e7afe9f5fd3b45"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-COD session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-cod"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_dis.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_dis.py
new file mode 100644
index 0000000000000000000000000000000000000000..76bdb853def29dfd04363d1444f403c99f659184
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_dis.py
@@ -0,0 +1,52 @@
+import os
+
+import pooch
+
+from . import BiRefNetSessionGeneral
+
+
+class BiRefNetSessionDIS(BiRefNetSessionGeneral):
+ """
+ This class represents a BiRefNet-DIS session, which is a subclass of BiRefNetSessionGeneral.
+ """
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-DIS model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-DIS-epoch_590.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:2d4d44102b446f33a4ebb2e56c051f2b"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-DIS session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-dis"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_general.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_general.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fa1dca0e9387d80d86273bca23a41e3a08f64eb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_general.py
@@ -0,0 +1,91 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class BiRefNetSessionGeneral(BaseSession):
+ """
+ This class represents a BiRefNet-General session, which is a subclass of BaseSession.
+ """
+
+ def sigmoid(self, mat):
+ return 1 / (1 + np.exp(-mat))
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predicts the output masks for the input image using the inner session.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List[PILImage]: The list of output masks.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (1024, 1024)
+ ),
+ )
+
+ pred = self.sigmoid(ort_outs[0][:, 0, :, :])
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-General model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-epoch_244.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:7a35a0141cbbc80de11d9c9a28f52697"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-General session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-general"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_general_lite.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_general_lite.py
new file mode 100644
index 0000000000000000000000000000000000000000..619671239b2dbf7d8d5e9c19b09c51299b72875e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_general_lite.py
@@ -0,0 +1,52 @@
+import os
+
+import pooch
+
+from . import BiRefNetSessionGeneral
+
+
+class BiRefNetSessionGeneralLite(BiRefNetSessionGeneral):
+ """
+ This class represents a BiRefNet-General-Lite session, which is a subclass of BiRefNetSessionGeneral.
+ """
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-General-Lite model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-general-bb_swin_v1_tiny-epoch_232.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:4fab47adc4ff364be1713e97b7e66334"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-General-Lite session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-general-lite"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_hrsod.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_hrsod.py
new file mode 100644
index 0000000000000000000000000000000000000000..2260a20a7d5a5681a67c6c97c94d2523366d09f4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_hrsod.py
@@ -0,0 +1,52 @@
+import os
+
+import pooch
+
+from . import BiRefNetSessionGeneral
+
+
+class BiRefNetSessionHRSOD(BiRefNetSessionGeneral):
+ """
+ This class represents a BiRefNet-HRSOD session, which is a subclass of BiRefNetSessionGeneral.
+ """
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-HRSOD model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-HRSOD_DHU-epoch_115.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:c017ade5de8a50ff0fd74d790d268dda"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-HRSOD session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-hrsod"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_massive.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_massive.py
new file mode 100644
index 0000000000000000000000000000000000000000..79233b8b668b27ce0d1c5a19bc41a82353b1c58f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_massive.py
@@ -0,0 +1,52 @@
+import os
+
+import pooch
+
+from . import BiRefNetSessionGeneral
+
+
+class BiRefNetSessionMassive(BiRefNetSessionGeneral):
+ """
+ This class represents a BiRefNet-Massive session, which is a subclass of BiRefNetSessionGeneral.
+ """
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-Massive model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-massive-TR_DIS5K_TR_TEs-epoch_420.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:33e726a2136a3d59eb0fdf613e31e3e9"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-Massive session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-massive"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/birefnet_portrait.py b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_portrait.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6a5835c67deeff0a072f978460c96bcfa67e24b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/birefnet_portrait.py
@@ -0,0 +1,52 @@
+import os
+
+import pooch
+
+from . import BiRefNetSessionGeneral
+
+
+class BiRefNetSessionPortrait(BiRefNetSessionGeneral):
+ """
+ This class represents a BiRefNet-Portrait session, which is a subclass of BiRefNetSessionGeneral.
+ """
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BiRefNet-Portrait model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/BiRefNet-portrait-epoch_150.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:c3a64a6abf20250d090cd055f12a3b67"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the BiRefNet-Portrait session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "birefnet-portrait"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/bria_rmbg.py b/python_embeded/Lib/site-packages/rembg/sessions/bria_rmbg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1bda828a986afc5b4603fca3b719db04bd7ceca
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/bria_rmbg.py
@@ -0,0 +1,88 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class BriaRmBgSession(BaseSession):
+ """
+ This class represents a Bria-rmbg-2.0 session, which is a subclass of BaseSession.
+ """
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predicts the output masks for the input image using the inner session.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List[PILImage]: The list of output masks.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (1024, 1024)
+ ),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the BRIA-RMBG 2.0 model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/bria-rmbg-2.0.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "sha256:5b486f08200f513f460da46dd701db5fbb47d79b4be4b708a19444bcd4e79958"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the Bria-rmbg session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "bria-rmbg"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/dis_anime.py b/python_embeded/Lib/site-packages/rembg/sessions/dis_anime.py
new file mode 100644
index 0000000000000000000000000000000000000000..33d09a75fc27515ba21222a1c6139d6d5b2d225f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/dis_anime.py
@@ -0,0 +1,86 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class DisSession(BaseSession):
+ """
+ This class represents a session for object detection.
+ """
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Use a pre-trained model to predict the object in the given image.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ List[PILImage]: A list of predicted mask images.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(img, (0.485, 0.456, 0.406), (1.0, 1.0, 1.0), (1024, 1024)),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Download the pre-trained models.
+
+ Parameters:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The path of the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/isnet-anime.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:6f184e756bb3bd901c8849220a83e38e"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Get the name of the pre-trained model.
+
+ Parameters:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The name of the pre-trained model.
+ """
+ return "isnet-anime"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/dis_general_use.py b/python_embeded/Lib/site-packages/rembg/sessions/dis_general_use.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5f1d8883c7438f77e9de22562d5b336e15935cf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/dis_general_use.py
@@ -0,0 +1,86 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class DisSession(BaseSession):
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predicts the mask image for the input image.
+
+ This method takes a PILImage object as input and returns a list of PILImage objects as output. It performs several image processing operations to generate the mask image.
+
+ Parameters:
+ img (PILImage): The input image.
+
+ Returns:
+ List[PILImage]: A list of PILImage objects representing the generated mask image.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(img, (0.5, 0.5, 0.5), (1.0, 1.0, 1.0), (1024, 1024)),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the pre-trained model file.
+
+ This class method downloads the pre-trained model file from a specified URL using the pooch library.
+
+ Parameters:
+ args: Additional positional arguments.
+ kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/isnet-general-use.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:fc16ebd8b0c10d971d3513d564d01e29"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the model.
+
+ This class method returns the name of the model.
+
+ Parameters:
+ args: Additional positional arguments.
+ kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the model.
+ """
+ return "isnet-general-use"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/sam.py b/python_embeded/Lib/site-packages/rembg/sessions/sam.py
new file mode 100644
index 0000000000000000000000000000000000000000..a25a8345c552af5b65e0c29bf083030e913a61b6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/sam.py
@@ -0,0 +1,340 @@
+import os
+from copy import deepcopy
+from typing import List
+
+import cv2
+import numpy as np
+import onnxruntime as ort
+import pooch
+from jsonschema import validate
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int):
+ scale = long_side_length * 1.0 / max(oldh, oldw)
+ newh, neww = oldh * scale, oldw * scale
+ neww = int(neww + 0.5)
+ newh = int(newh + 0.5)
+
+ return (newh, neww)
+
+
+def apply_coords(coords: np.ndarray, original_size, target_length):
+ old_h, old_w = original_size
+ new_h, new_w = get_preprocess_shape(
+ original_size[0], original_size[1], target_length
+ )
+
+ coords = deepcopy(coords).astype(float)
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
+
+ return coords
+
+
+def get_input_points(prompt):
+ points = []
+ labels = []
+
+ for mark in prompt:
+ if mark["type"] == "point":
+ points.append(mark["data"])
+ labels.append(mark["label"])
+ elif mark["type"] == "rectangle":
+ points.append([mark["data"][0], mark["data"][1]])
+ points.append([mark["data"][2], mark["data"][3]])
+ labels.append(2)
+ labels.append(3)
+
+ points, labels = np.array(points), np.array(labels)
+ return points, labels
+
+
+def transform_masks(masks, original_size, transform_matrix):
+ output_masks = []
+
+ for batch in range(masks.shape[0]):
+ batch_masks = []
+ for mask_id in range(masks.shape[1]):
+ mask = masks[batch, mask_id]
+ mask = cv2.warpAffine(
+ mask,
+ transform_matrix[:2],
+ (original_size[1], original_size[0]),
+ flags=cv2.INTER_LINEAR,
+ )
+ batch_masks.append(mask)
+ output_masks.append(batch_masks)
+
+ return np.array(output_masks)
+
+
+class SamSession(BaseSession):
+ """
+ This class represents a session for the Sam model.
+
+ Args:
+ model_name (str): The name of the model.
+ sess_opts (ort.SessionOptions): The session options.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+ """
+
+ def __init__(
+ self,
+ model_name: str,
+ sess_opts: ort.SessionOptions,
+ *args,
+ **kwargs,
+ ):
+ """
+ Initialize a new SamSession with the given model name and session options.
+
+ Args:
+ model_name (str): The name of the model.
+ sess_opts (ort.SessionOptions): The session options.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+ """
+ self.model_name = model_name
+
+ paths = self.__class__.download_models(*args, **kwargs)
+ self.encoder = ort.InferenceSession(
+ str(paths[0]),
+ sess_options=sess_opts,
+ )
+ self.decoder = ort.InferenceSession(
+ str(paths[1]),
+ sess_options=sess_opts,
+ )
+
+ def predict(
+ self,
+ img: PILImage,
+ *args,
+ **kwargs,
+ ) -> List[PILImage]:
+ """
+ Predict masks for an input image.
+
+ This function takes an image as input and performs various preprocessing steps on the image. It then runs the image through an encoder to obtain an image embedding. The function also takes input labels and points as additional arguments. It concatenates the input points and labels with padding and transforms them. It creates an empty mask input and an indicator for no mask. The function then passes the image embedding, point coordinates, point labels, mask input, and has mask input to a decoder. The decoder generates masks based on the input and returns them as a list of images.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Additional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List[PILImage]: A list of masks generated by the decoder.
+ """
+ prompt = kwargs.get(
+ "sam_prompt",
+ [
+ {
+ "type": "point",
+ "label": 1,
+ "data": [int(img.width / 2), int(img.height / 2)],
+ }
+ ],
+ )
+ schema = {
+ "type": "array",
+ "items": {
+ "type": "object",
+ "properties": {
+ "type": {"type": "string"},
+ "label": {"type": "integer"},
+ "data": {
+ "type": "array",
+ "items": {"type": "number"},
+ },
+ },
+ },
+ }
+
+ validate(instance=prompt, schema=schema)
+
+ target_size = 1024
+ input_size = (684, 1024)
+ encoder_input_name = self.encoder.get_inputs()[0].name
+
+ img = img.convert("RGB")
+ cv_image = np.array(img)
+ original_size = cv_image.shape[:2]
+
+ scale_x = input_size[1] / cv_image.shape[1]
+ scale_y = input_size[0] / cv_image.shape[0]
+ scale = min(scale_x, scale_y)
+
+ transform_matrix = np.array(
+ [
+ [scale, 0, 0],
+ [0, scale, 0],
+ [0, 0, 1],
+ ]
+ )
+
+ cv_image = cv2.warpAffine(
+ cv_image,
+ transform_matrix[:2],
+ (input_size[1], input_size[0]),
+ flags=cv2.INTER_LINEAR,
+ )
+
+ ## encoder
+
+ encoder_inputs = {
+ encoder_input_name: cv_image.astype(np.float32),
+ }
+
+ encoder_output = self.encoder.run(None, encoder_inputs)
+ image_embedding = encoder_output[0]
+
+ embedding = {
+ "image_embedding": image_embedding,
+ "original_size": original_size,
+ "transform_matrix": transform_matrix,
+ }
+
+ ## decoder
+
+ input_points, input_labels = get_input_points(prompt)
+ onnx_coord = np.concatenate([input_points, np.array([[0.0, 0.0]])], axis=0)[
+ None, :, :
+ ]
+ onnx_label = np.concatenate([input_labels, np.array([-1])], axis=0)[
+ None, :
+ ].astype(np.float32)
+ onnx_coord = apply_coords(onnx_coord, input_size, target_size).astype(
+ np.float32
+ )
+
+ onnx_coord = np.concatenate(
+ [
+ onnx_coord,
+ np.ones((1, onnx_coord.shape[1], 1), dtype=np.float32),
+ ],
+ axis=2,
+ )
+ onnx_coord = np.matmul(onnx_coord, transform_matrix.T)
+ onnx_coord = onnx_coord[:, :, :2].astype(np.float32)
+
+ onnx_mask_input = np.zeros((1, 1, 256, 256), dtype=np.float32)
+ onnx_has_mask_input = np.zeros(1, dtype=np.float32)
+
+ decoder_inputs = {
+ "image_embeddings": image_embedding,
+ "point_coords": onnx_coord,
+ "point_labels": onnx_label,
+ "mask_input": onnx_mask_input,
+ "has_mask_input": onnx_has_mask_input,
+ "orig_im_size": np.array(input_size, dtype=np.float32),
+ }
+
+ masks, _, _ = self.decoder.run(None, decoder_inputs)
+ inv_transform_matrix = np.linalg.inv(transform_matrix)
+ masks = transform_masks(masks, original_size, inv_transform_matrix)
+
+ mask = np.zeros((masks.shape[2], masks.shape[3], 3), dtype=np.uint8)
+ for m in masks[0, :, :, :]:
+ mask[m > 0.0] = [255, 255, 255]
+
+ return [Image.fromarray(mask).convert("L")]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Class method to download ONNX model files.
+
+ This method is responsible for downloading two ONNX model files from specified URLs and saving them locally. The downloaded files are saved with the naming convention 'name_encoder.onnx' and 'name_decoder.onnx', where 'name' is the value returned by the 'name' method.
+
+ Parameters:
+ cls: The class object.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ tuple: A tuple containing the file paths of the downloaded encoder and decoder models.
+ """
+ model_name = kwargs.get("sam_model", "sam_vit_b_01ec64")
+ quant = kwargs.get("sam_quant", False)
+
+ fname_encoder = f"{model_name}.encoder.onnx"
+ fname_decoder = f"{model_name}.decoder.onnx"
+
+ if quant:
+ fname_encoder = f"{model_name}.encoder.quant.onnx"
+ fname_decoder = f"{model_name}.decoder.quant.onnx"
+
+ pooch.retrieve(
+ f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/{fname_encoder}",
+ None,
+ fname=fname_encoder,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ pooch.retrieve(
+ f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/{fname_decoder}",
+ None,
+ fname=fname_decoder,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ if fname_encoder == "sam_vit_h_4b8939.encoder.onnx" and not os.path.exists(
+ os.path.join(
+ cls.u2net_home(*args, **kwargs), "sam_vit_h_4b8939.encoder_data.bin"
+ )
+ ):
+ content = bytearray()
+
+ for i in range(1, 4):
+ pooch.retrieve(
+ f"https://github.com/danielgatis/rembg/releases/download/v0.0.0/sam_vit_h_4b8939.encoder_data.{i}.bin",
+ None,
+ fname=f"sam_vit_h_4b8939.encoder_data.{i}.bin",
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ fbin = os.path.join(
+ cls.u2net_home(*args, **kwargs),
+ f"sam_vit_h_4b8939.encoder_data.{i}.bin",
+ )
+ content.extend(open(fbin, "rb").read())
+ os.remove(fbin)
+
+ with open(
+ os.path.join(
+ cls.u2net_home(*args, **kwargs),
+ "sam_vit_h_4b8939.encoder_data.bin",
+ ),
+ "wb",
+ ) as fp:
+ fp.write(content)
+
+ return (
+ os.path.join(cls.u2net_home(*args, **kwargs), fname_encoder),
+ os.path.join(cls.u2net_home(*args, **kwargs), fname_decoder),
+ )
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Class method to return a string value.
+
+ This method returns the string value 'sam'.
+
+ Parameters:
+ cls: The class object.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The string value 'sam'.
+ """
+ return "sam"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/silueta.py b/python_embeded/Lib/site-packages/rembg/sessions/silueta.py
new file mode 100644
index 0000000000000000000000000000000000000000..574a33c3d9ad3ef8f1ee76abe30db66978259e9d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/silueta.py
@@ -0,0 +1,92 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class SiluetaSession(BaseSession):
+ """This is a class representing a SiluetaSession object."""
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predict the mask of the input image.
+
+ This method takes an image as input, preprocesses it, and performs a prediction to generate a mask. The generated mask is then post-processed and returned as a list of PILImage objects.
+
+ Parameters:
+ img (PILImage): The input image to be processed.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ List[PILImage]: A list of post-processed masks.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (320, 320)
+ ),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Download the pre-trained model file.
+
+ This method downloads the pre-trained model file from a specified URL. The file is saved to the U2NET home directory.
+
+ Parameters:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name()}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/silueta.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:55e59e0d8062d2f5d013f4725ee84782"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Return the name of the model.
+
+ This method returns the name of the Silueta model.
+
+ Parameters:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The name of the model.
+ """
+ return "silueta"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/u2net.py b/python_embeded/Lib/site-packages/rembg/sessions/u2net.py
new file mode 100644
index 0000000000000000000000000000000000000000..88922ae18f3777c97df7dcab66ea00e9097a8bd9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/u2net.py
@@ -0,0 +1,88 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class U2netSession(BaseSession):
+ """
+ This class represents a U2net session, which is a subclass of BaseSession.
+ """
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predicts the output masks for the input image using the inner session.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List[PILImage]: The list of output masks.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (320, 320)
+ ),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred.clip(0, 1) * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the U2net model file from a specific URL and saves it.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model file.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:60024c5c889badc19c04ad937298a77b"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the U2net session.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the session.
+ """
+ return "u2net"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/u2net_cloth_seg.py b/python_embeded/Lib/site-packages/rembg/sessions/u2net_cloth_seg.py
new file mode 100644
index 0000000000000000000000000000000000000000..aaac286c112a118b849890d46468126f15ec00f4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/u2net_cloth_seg.py
@@ -0,0 +1,146 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+from scipy.special import log_softmax
+
+from .base import BaseSession
+
+palette1 = [
+ 0,
+ 0,
+ 0,
+ 255,
+ 255,
+ 255,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+]
+
+palette2 = [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 255,
+ 255,
+ 255,
+ 0,
+ 0,
+ 0,
+]
+
+palette3 = [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 255,
+ 255,
+ 255,
+]
+
+
+class Unet2ClothSession(BaseSession):
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predict the cloth category of an image.
+
+ This method takes an image as input and predicts the cloth category of the image.
+ The method uses the inner_session to make predictions using a pre-trained model.
+ The predicted mask is then converted to an image and resized to match the size of the input image.
+ Depending on the cloth category specified in the method arguments, the method applies different color palettes to the mask and appends the resulting images to a list.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List[PILImage]: A list of images representing the predicted masks.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (768, 768)
+ ),
+ )
+
+ pred = ort_outs
+ pred = log_softmax(pred[0], 1)
+ pred = np.argmax(pred, axis=1, keepdims=True)
+ pred = np.squeeze(pred, 0)
+ pred = np.squeeze(pred, 0)
+
+ mask = Image.fromarray(pred.astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ masks = []
+
+ cloth_category = kwargs.get("cc") or kwargs.get("cloth_category")
+
+ def upper_cloth():
+ mask1 = mask.copy()
+ mask1.putpalette(palette1)
+ mask1 = mask1.convert("RGB").convert("L")
+ masks.append(mask1)
+
+ def lower_cloth():
+ mask2 = mask.copy()
+ mask2.putpalette(palette2)
+ mask2 = mask2.convert("RGB").convert("L")
+ masks.append(mask2)
+
+ def full_cloth():
+ mask3 = mask.copy()
+ mask3.putpalette(palette3)
+ mask3 = mask3.convert("RGB").convert("L")
+ masks.append(mask3)
+
+ if cloth_category == "upper":
+ upper_cloth()
+ elif cloth_category == "lower":
+ lower_cloth()
+ elif cloth_category == "full":
+ full_cloth()
+ else:
+ upper_cloth()
+ lower_cloth()
+ full_cloth()
+
+ return masks
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net_cloth_seg.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:2434d1f3cb744e0e49386c906e5a08bb"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ return "u2net_cloth_seg"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/u2net_custom.py b/python_embeded/Lib/site-packages/rembg/sessions/u2net_custom.py
new file mode 100644
index 0000000000000000000000000000000000000000..439313883de58c8888f062d42ad2f172cb6145b9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/u2net_custom.py
@@ -0,0 +1,97 @@
+import os
+from typing import List
+
+import numpy as np
+import onnxruntime as ort
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class U2netCustomSession(BaseSession):
+ """This is a class representing a custom session for the U2net model."""
+
+ def __init__(self, model_name: str, sess_opts: ort.SessionOptions, *args, **kwargs):
+ """
+ Initialize a new U2netCustomSession object.
+
+ Parameters:
+ model_name (str): The name of the model.
+ sess_opts (ort.SessionOptions): The session options.
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Raises:
+ ValueError: If model_path is None.
+ """
+ model_path = kwargs.get("model_path")
+ if model_path is None:
+ raise ValueError("model_path is required")
+
+ super().__init__(model_name, sess_opts, *args, **kwargs)
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predict the segmentation mask for the input image.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ List[PILImage]: A list of PILImage objects representing the segmentation mask.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (320, 320)
+ ),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Download the model files.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The absolute path to the model files.
+ """
+ model_path = kwargs.get("model_path")
+ if model_path is None:
+ return
+
+ return os.path.abspath(os.path.expanduser(model_path))
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Get the name of the model.
+
+ Parameters:
+ *args: Additional positional arguments.
+ **kwargs: Additional keyword arguments.
+
+ Returns:
+ str: The name of the model.
+ """
+ return "u2net_custom"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/u2net_human_seg.py b/python_embeded/Lib/site-packages/rembg/sessions/u2net_human_seg.py
new file mode 100644
index 0000000000000000000000000000000000000000..170e5abd4f1ae7012dcbb0cfd0b807ca98ed19ff
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/u2net_human_seg.py
@@ -0,0 +1,88 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class U2netHumanSegSession(BaseSession):
+ """
+ This class represents a session for performing human segmentation using the U2Net model.
+ """
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predicts human segmentation masks for the input image.
+
+ Parameters:
+ img (PILImage): The input image.
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ List[PILImage]: A list of predicted masks.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (320, 320)
+ ),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the U2Net model weights.
+
+ Parameters:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The path to the downloaded model weights.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2net_human_seg.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:c09ddc2e0104f800e3e1bb4652583d1f"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the U2Net model.
+
+ Parameters:
+ *args: Variable length argument list.
+ **kwargs: Arbitrary keyword arguments.
+
+ Returns:
+ str: The name of the model.
+ """
+ return "u2net_human_seg"
diff --git a/python_embeded/Lib/site-packages/rembg/sessions/u2netp.py b/python_embeded/Lib/site-packages/rembg/sessions/u2netp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2988afdbb50a2eee6b25d2199cdbc7c058db31fc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rembg/sessions/u2netp.py
@@ -0,0 +1,76 @@
+import os
+from typing import List
+
+import numpy as np
+import pooch
+from PIL import Image
+from PIL.Image import Image as PILImage
+
+from .base import BaseSession
+
+
+class U2netpSession(BaseSession):
+ """This class represents a session for using the U2netp model."""
+
+ def predict(self, img: PILImage, *args, **kwargs) -> List[PILImage]:
+ """
+ Predicts the mask for the given image using the U2netp model.
+
+ Parameters:
+ img (PILImage): The input image.
+
+ Returns:
+ List[PILImage]: The predicted mask.
+ """
+ ort_outs = self.inner_session.run(
+ None,
+ self.normalize(
+ img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (320, 320)
+ ),
+ )
+
+ pred = ort_outs[0][:, 0, :, :]
+
+ ma = np.max(pred)
+ mi = np.min(pred)
+
+ pred = (pred - mi) / (ma - mi)
+ pred = np.squeeze(pred)
+
+ mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
+ mask = mask.resize(img.size, Image.Resampling.LANCZOS)
+
+ return [mask]
+
+ @classmethod
+ def download_models(cls, *args, **kwargs):
+ """
+ Downloads the U2netp model.
+
+ Returns:
+ str: The path to the downloaded model.
+ """
+ fname = f"{cls.name(*args, **kwargs)}.onnx"
+ pooch.retrieve(
+ "https://github.com/danielgatis/rembg/releases/download/v0.0.0/u2netp.onnx",
+ (
+ None
+ if cls.checksum_disabled(*args, **kwargs)
+ else "md5:8e83ca70e441ab06c318d82300c84806"
+ ),
+ fname=fname,
+ path=cls.u2net_home(*args, **kwargs),
+ progressbar=True,
+ )
+
+ return os.path.join(cls.u2net_home(*args, **kwargs), fname)
+
+ @classmethod
+ def name(cls, *args, **kwargs):
+ """
+ Returns the name of the U2netp model.
+
+ Returns:
+ str: The name of the model.
+ """
+ return "u2netp"
diff --git a/python_embeded/Lib/site-packages/replicate-1.0.7.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/replicate-1.0.7.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..f600d9a51d84e768cb05588dcf2b9addb5afa3a3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/replicate-1.0.7.dist-info/licenses/LICENSE
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2022, Replicate, Inc.
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/python_embeded/Lib/site-packages/requests-2.32.4.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/requests-2.32.4.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..67db8588217f266eb561f75fae738656325deac9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/requests-2.32.4.dist-info/licenses/LICENSE
@@ -0,0 +1,175 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
diff --git a/python_embeded/Lib/site-packages/rpds_py-0.25.1.dist-info/licenses/LICENSE b/python_embeded/Lib/site-packages/rpds_py-0.25.1.dist-info/licenses/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..9a3970a75793bcf642507d42ffafaf2986e84075
--- /dev/null
+++ b/python_embeded/Lib/site-packages/rpds_py-0.25.1.dist-info/licenses/LICENSE
@@ -0,0 +1,19 @@
+Copyright (c) 2023 Julian Berman
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/cluster/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py b/python_embeded/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ad7da3af7fa3acf8f399c9eedb149a1420d5a17
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/cluster/tests/hierarchy_test_data.py
@@ -0,0 +1,145 @@
+from numpy import array
+
+
+Q_X = array([[5.26563660e-01, 3.14160190e-01, 8.00656370e-02],
+ [7.50205180e-01, 4.60299830e-01, 8.98696460e-01],
+ [6.65461230e-01, 6.94011420e-01, 9.10465700e-01],
+ [9.64047590e-01, 1.43082200e-03, 7.39874220e-01],
+ [1.08159060e-01, 5.53028790e-01, 6.63804780e-02],
+ [9.31359130e-01, 8.25424910e-01, 9.52315440e-01],
+ [6.78086960e-01, 3.41903970e-01, 5.61481950e-01],
+ [9.82730940e-01, 7.04605210e-01, 8.70978630e-02],
+ [6.14691610e-01, 4.69989230e-02, 6.02406450e-01],
+ [5.80161260e-01, 9.17354970e-01, 5.88163850e-01],
+ [1.38246310e+00, 1.96358160e+00, 1.94437880e+00],
+ [2.10675860e+00, 1.67148730e+00, 1.34854480e+00],
+ [1.39880070e+00, 1.66142050e+00, 1.32224550e+00],
+ [1.71410460e+00, 1.49176380e+00, 1.45432170e+00],
+ [1.54102340e+00, 1.84374950e+00, 1.64658950e+00],
+ [2.08512480e+00, 1.84524350e+00, 2.17340850e+00],
+ [1.30748740e+00, 1.53801650e+00, 2.16007740e+00],
+ [1.41447700e+00, 1.99329070e+00, 1.99107420e+00],
+ [1.61943490e+00, 1.47703280e+00, 1.89788160e+00],
+ [1.59880600e+00, 1.54988980e+00, 1.57563350e+00],
+ [3.37247380e+00, 2.69635310e+00, 3.39981700e+00],
+ [3.13705120e+00, 3.36528090e+00, 3.06089070e+00],
+ [3.29413250e+00, 3.19619500e+00, 2.90700170e+00],
+ [2.65510510e+00, 3.06785900e+00, 2.97198540e+00],
+ [3.30941040e+00, 2.59283970e+00, 2.57714110e+00],
+ [2.59557220e+00, 3.33477370e+00, 3.08793190e+00],
+ [2.58206180e+00, 3.41615670e+00, 3.26441990e+00],
+ [2.71127000e+00, 2.77032450e+00, 2.63466500e+00],
+ [2.79617850e+00, 3.25473720e+00, 3.41801560e+00],
+ [2.64741750e+00, 2.54538040e+00, 3.25354110e+00]])
+
+ytdist = array([662., 877., 255., 412., 996., 295., 468., 268., 400., 754.,
+ 564., 138., 219., 869., 669.])
+
+linkage_ytdist_single = array([[2., 5., 138., 2.],
+ [3., 4., 219., 2.],
+ [0., 7., 255., 3.],
+ [1., 8., 268., 4.],
+ [6., 9., 295., 6.]])
+
+linkage_ytdist_complete = array([[2., 5., 138., 2.],
+ [3., 4., 219., 2.],
+ [1., 6., 400., 3.],
+ [0., 7., 412., 3.],
+ [8., 9., 996., 6.]])
+
+linkage_ytdist_average = array([[2., 5., 138., 2.],
+ [3., 4., 219., 2.],
+ [0., 7., 333.5, 3.],
+ [1., 6., 347.5, 3.],
+ [8., 9., 680.77777778, 6.]])
+
+linkage_ytdist_weighted = array([[2., 5., 138., 2.],
+ [3., 4., 219., 2.],
+ [0., 7., 333.5, 3.],
+ [1., 6., 347.5, 3.],
+ [8., 9., 670.125, 6.]])
+
+# the optimal leaf ordering of linkage_ytdist_single
+linkage_ytdist_single_olo = array([[5., 2., 138., 2.],
+ [4., 3., 219., 2.],
+ [7., 0., 255., 3.],
+ [1., 8., 268., 4.],
+ [6., 9., 295., 6.]])
+
+X = array([[1.43054825, -7.5693489],
+ [6.95887839, 6.82293382],
+ [2.87137846, -9.68248579],
+ [7.87974764, -6.05485803],
+ [8.24018364, -6.09495602],
+ [7.39020262, 8.54004355]])
+
+linkage_X_centroid = array([[3., 4., 0.36265956, 2.],
+ [1., 5., 1.77045373, 2.],
+ [0., 2., 2.55760419, 2.],
+ [6., 8., 6.43614494, 4.],
+ [7., 9., 15.17363237, 6.]])
+
+linkage_X_median = array([[3., 4., 0.36265956, 2.],
+ [1., 5., 1.77045373, 2.],
+ [0., 2., 2.55760419, 2.],
+ [6., 8., 6.43614494, 4.],
+ [7., 9., 15.17363237, 6.]])
+
+linkage_X_ward = array([[3., 4., 0.36265956, 2.],
+ [1., 5., 1.77045373, 2.],
+ [0., 2., 2.55760419, 2.],
+ [6., 8., 9.10208346, 4.],
+ [7., 9., 24.7784379, 6.]])
+
+# the optimal leaf ordering of linkage_X_ward
+linkage_X_ward_olo = array([[4., 3., 0.36265956, 2.],
+ [5., 1., 1.77045373, 2.],
+ [2., 0., 2.55760419, 2.],
+ [6., 8., 9.10208346, 4.],
+ [7., 9., 24.7784379, 6.]])
+
+inconsistent_ytdist = {
+ 1: array([[138., 0., 1., 0.],
+ [219., 0., 1., 0.],
+ [255., 0., 1., 0.],
+ [268., 0., 1., 0.],
+ [295., 0., 1., 0.]]),
+ 2: array([[138., 0., 1., 0.],
+ [219., 0., 1., 0.],
+ [237., 25.45584412, 2., 0.70710678],
+ [261.5, 9.19238816, 2., 0.70710678],
+ [233.66666667, 83.9424406, 3., 0.7306594]]),
+ 3: array([[138., 0., 1., 0.],
+ [219., 0., 1., 0.],
+ [237., 25.45584412, 2., 0.70710678],
+ [247.33333333, 25.38372182, 3., 0.81417007],
+ [239., 69.36377537, 4., 0.80733783]]),
+ 4: array([[138., 0., 1., 0.],
+ [219., 0., 1., 0.],
+ [237., 25.45584412, 2., 0.70710678],
+ [247.33333333, 25.38372182, 3., 0.81417007],
+ [235., 60.73302232, 5., 0.98793042]])}
+
+fcluster_inconsistent = {
+ 0.8: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1]),
+ 1.0: array([6, 2, 2, 4, 6, 2, 3, 7, 3, 5, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1]),
+ 2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1])}
+
+fcluster_distance = {
+ 0.6: array([4, 4, 4, 4, 4, 4, 4, 5, 4, 4, 6, 6, 6, 6, 6, 7, 6, 6, 6, 6, 3,
+ 1, 1, 1, 2, 1, 1, 1, 1, 1]),
+ 1.0: array([2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1]),
+ 2.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1])}
+
+fcluster_maxclust = {
+ 8.0: array([5, 5, 5, 5, 5, 5, 5, 6, 5, 5, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 4,
+ 1, 1, 1, 3, 1, 1, 1, 1, 2]),
+ 4.0: array([3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 2,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1]),
+ 1.0: array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 1, 1])}
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py b/python_embeded/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py
new file mode 100644
index 0000000000000000000000000000000000000000..c9518ea1af28df04d811f46ff114d5cf58e594d7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/cluster/tests/test_disjoint_set.py
@@ -0,0 +1,202 @@
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.cluster.hierarchy import DisjointSet
+import string
+
+
+def generate_random_token():
+ k = len(string.ascii_letters)
+ tokens = list(np.arange(k, dtype=int))
+ tokens += list(np.arange(k, dtype=float))
+ tokens += list(string.ascii_letters)
+ tokens += [None for i in range(k)]
+ tokens = np.array(tokens, dtype=object)
+ rng = np.random.RandomState(seed=0)
+
+ while 1:
+ size = rng.randint(1, 3)
+ element = rng.choice(tokens, size)
+ if size == 1:
+ yield element[0]
+ else:
+ yield tuple(element)
+
+
+def get_elements(n):
+ # dict is deterministic without difficulty of comparing numpy ints
+ elements = {}
+ for element in generate_random_token():
+ if element not in elements:
+ elements[element] = len(elements)
+ if len(elements) >= n:
+ break
+ return list(elements.keys())
+
+
+def test_init():
+ n = 10
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+ assert dis.n_subsets == n
+ assert list(dis) == elements
+
+
+def test_len():
+ n = 10
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+ assert len(dis) == n
+
+ dis.add("dummy")
+ assert len(dis) == n + 1
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_contains(n):
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+ for x in elements:
+ assert x in dis
+
+ assert "dummy" not in dis
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_add(n):
+ elements = get_elements(n)
+ dis1 = DisjointSet(elements)
+
+ dis2 = DisjointSet()
+ for i, x in enumerate(elements):
+ dis2.add(x)
+ assert len(dis2) == i + 1
+
+ # test idempotency by adding element again
+ dis2.add(x)
+ assert len(dis2) == i + 1
+
+ assert list(dis1) == list(dis2)
+
+
+def test_element_not_present():
+ elements = get_elements(n=10)
+ dis = DisjointSet(elements)
+
+ with assert_raises(KeyError):
+ dis["dummy"]
+
+ with assert_raises(KeyError):
+ dis.merge(elements[0], "dummy")
+
+ with assert_raises(KeyError):
+ dis.connected(elements[0], "dummy")
+
+
+@pytest.mark.parametrize("direction", ["forwards", "backwards"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_linear_union_sequence(n, direction):
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+ assert elements == list(dis)
+
+ indices = list(range(n - 1))
+ if direction == "backwards":
+ indices = indices[::-1]
+
+ for it, i in enumerate(indices):
+ assert not dis.connected(elements[i], elements[i + 1])
+ assert dis.merge(elements[i], elements[i + 1])
+ assert dis.connected(elements[i], elements[i + 1])
+ assert dis.n_subsets == n - 1 - it
+
+ roots = [dis[i] for i in elements]
+ if direction == "forwards":
+ assert all(elements[0] == r for r in roots)
+ else:
+ assert all(elements[-2] == r for r in roots)
+ assert not dis.merge(elements[0], elements[-1])
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_self_unions(n):
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+
+ for x in elements:
+ assert dis.connected(x, x)
+ assert not dis.merge(x, x)
+ assert dis.connected(x, x)
+ assert dis.n_subsets == len(elements)
+
+ assert elements == list(dis)
+ roots = [dis[x] for x in elements]
+ assert elements == roots
+
+
+@pytest.mark.parametrize("order", ["ab", "ba"])
+@pytest.mark.parametrize("n", [10, 100])
+def test_equal_size_ordering(n, order):
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+
+ rng = np.random.RandomState(seed=0)
+ indices = np.arange(n)
+ rng.shuffle(indices)
+
+ for i in range(0, len(indices), 2):
+ a, b = elements[indices[i]], elements[indices[i + 1]]
+ if order == "ab":
+ assert dis.merge(a, b)
+ else:
+ assert dis.merge(b, a)
+
+ expected = elements[min(indices[i], indices[i + 1])]
+ assert dis[a] == expected
+ assert dis[b] == expected
+
+
+@pytest.mark.parametrize("kmax", [5, 10])
+def test_binary_tree(kmax):
+ n = 2**kmax
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+ rng = np.random.RandomState(seed=0)
+
+ for k in 2**np.arange(kmax):
+ for i in range(0, n, 2 * k):
+ r1, r2 = rng.randint(0, k, size=2)
+ a, b = elements[i + r1], elements[i + k + r2]
+ assert not dis.connected(a, b)
+ assert dis.merge(a, b)
+ assert dis.connected(a, b)
+
+ assert elements == list(dis)
+ roots = [dis[i] for i in elements]
+ expected_indices = np.arange(n) - np.arange(n) % (2 * k)
+ expected = [elements[i] for i in expected_indices]
+ assert roots == expected
+
+
+@pytest.mark.parametrize("n", [10, 100])
+def test_subsets(n):
+ elements = get_elements(n)
+ dis = DisjointSet(elements)
+
+ rng = np.random.RandomState(seed=0)
+ for i, j in rng.randint(0, n, (n, 2)):
+ x = elements[i]
+ y = elements[j]
+
+ expected = {element for element in dis if {dis[element]} == {dis[x]}}
+ assert dis.subset_size(x) == len(dis.subset(x))
+ assert expected == dis.subset(x)
+
+ expected = {dis[element]: set() for element in dis}
+ for element in dis:
+ expected[dis[element]].add(element)
+ expected = list(expected.values())
+ assert expected == dis.subsets()
+
+ dis.merge(x, y)
+ assert dis.subset(x) == dis.subset(y)
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py b/python_embeded/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py
new file mode 100644
index 0000000000000000000000000000000000000000..03baf9486ab2909b377b2e326d433fcb4c97d67a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/cluster/tests/test_hierarchy.py
@@ -0,0 +1,1300 @@
+#
+# Author: Damian Eads
+# Date: April 17, 2008
+#
+# Copyright (C) 2008 Damian Eads
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+import numpy as np
+from numpy.testing import (assert_allclose, assert_equal, assert_array_equal, assert_,
+ assert_warns)
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.cluster.hierarchy
+from scipy.cluster.hierarchy import (
+ ClusterWarning, linkage, from_mlab_linkage, to_mlab_linkage,
+ num_obs_linkage, inconsistent, cophenet, fclusterdata, fcluster,
+ is_isomorphic, single, leaders,
+ correspond, is_monotonic, maxdists, maxinconsts, maxRstat,
+ is_valid_linkage, is_valid_im, to_tree, leaves_list, dendrogram,
+ set_link_color_palette, cut_tree, optimal_leaf_ordering,
+ _order_cluster_tree, _hierarchy, _LINKAGE_METHODS)
+from scipy.spatial.distance import pdist
+from scipy.cluster._hierarchy import Heap
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal
+
+from threading import Lock
+
+from . import hierarchy_test_data
+
+
+# Matplotlib is not a scipy dependency but is optionally used in dendrogram, so
+# check if it's available
+try:
+ import matplotlib
+ # and set the backend to be Agg (no gui)
+ matplotlib.use('Agg')
+ # before importing pyplot
+ import matplotlib.pyplot as plt
+ have_matplotlib = True
+except Exception:
+ have_matplotlib = False
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestLinkage:
+
+ @skip_xp_backends(cpu_only=True)
+ def test_linkage_non_finite_elements_in_distance_matrix(self, xp):
+ # Tests linkage(Y) where Y contains a non-finite element (e.g. NaN or Inf).
+ # Exception expected.
+ y = xp.asarray([xp.nan] + [0.0]*5)
+ assert_raises(ValueError, linkage, y)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_linkage_empty_distance_matrix(self, xp):
+ # Tests linkage(Y) where Y is a 0x4 linkage matrix. Exception expected.
+ y = xp.zeros((0,))
+ assert_raises(ValueError, linkage, y)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_linkage_tdist(self, xp):
+ for method in ['single', 'complete', 'average', 'weighted']:
+ self.check_linkage_tdist(method, xp)
+
+ def check_linkage_tdist(self, method, xp):
+ # Tests linkage(Y, method) on the tdist data set.
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), method)
+ expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_' + method)
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_linkage_X(self, xp):
+ for method in ['centroid', 'median', 'ward']:
+ self.check_linkage_q(method, xp)
+
+ def check_linkage_q(self, method, xp):
+ # Tests linkage(Y, method) on the Q data set.
+ Z = linkage(xp.asarray(hierarchy_test_data.X), method)
+ expectedZ = getattr(hierarchy_test_data, 'linkage_X_' + method)
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+ y = scipy.spatial.distance.pdist(hierarchy_test_data.X,
+ metric="euclidean")
+ Z = linkage(xp.asarray(y), method)
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_compare_with_trivial(self, xp):
+ rng = np.random.RandomState(0)
+ n = 20
+ X = rng.rand(n, 2)
+ d = pdist(X)
+
+ for method, code in _LINKAGE_METHODS.items():
+ Z_trivial = _hierarchy.linkage(d, n, code)
+ Z = linkage(xp.asarray(d), method)
+ xp_assert_close(Z, xp.asarray(Z_trivial), rtol=1e-14, atol=1e-15)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_optimal_leaf_ordering(self, xp):
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), optimal_ordering=True)
+ expectedZ = getattr(hierarchy_test_data, 'linkage_ytdist_single_olo')
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestLinkageTies:
+
+ _expectations = {
+ 'single': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 1.41421356, 3]]),
+ 'complete': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 2.82842712, 3]]),
+ 'average': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 2.12132034, 3]]),
+ 'weighted': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 2.12132034, 3]]),
+ 'centroid': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 2.12132034, 3]]),
+ 'median': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 2.12132034, 3]]),
+ 'ward': np.array([[0, 1, 1.41421356, 2],
+ [2, 3, 2.44948974, 3]]),
+ }
+
+ def test_linkage_ties(self, xp):
+ for method in ['single', 'complete', 'average', 'weighted',
+ 'centroid', 'median', 'ward']:
+ self.check_linkage_ties(method, xp)
+
+ def check_linkage_ties(self, method, xp):
+ X = xp.asarray([[-1, -1], [0, 0], [1, 1]])
+ Z = linkage(X, method=method)
+ expectedZ = self._expectations[method]
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestInconsistent:
+
+ def test_inconsistent_tdist(self, xp):
+ for depth in hierarchy_test_data.inconsistent_ytdist:
+ self.check_inconsistent_tdist(depth, xp)
+
+ def check_inconsistent_tdist(self, depth, xp):
+ Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+ xp_assert_close(inconsistent(Z, depth),
+ xp.asarray(hierarchy_test_data.inconsistent_ytdist[depth]))
+
+
+@skip_xp_backends(cpu_only=True)
+class TestCopheneticDistance:
+
+ def test_linkage_cophenet_tdist_Z(self, xp):
+ # Tests cophenet(Z) on tdist data set.
+ expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+ 295, 138, 219, 295, 295])
+ Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+ M = cophenet(Z)
+ xp_assert_close(M, xp.asarray(expectedM, dtype=xp.float64), atol=1e-10)
+
+ def test_linkage_cophenet_tdist_Z_Y(self, xp):
+ # Tests cophenet(Z, Y) on tdist data set.
+ Z = xp.asarray(hierarchy_test_data.linkage_ytdist_single)
+ (c, M) = cophenet(Z, xp.asarray(hierarchy_test_data.ytdist))
+ expectedM = xp.asarray([268, 295, 255, 255, 295, 295, 268, 268, 295, 295,
+ 295, 138, 219, 295, 295], dtype=xp.float64)
+ expectedc = xp.asarray(0.639931296433393415057366837573, dtype=xp.float64)[()]
+ xp_assert_close(c, expectedc, atol=1e-10)
+ xp_assert_close(M, expectedM, atol=1e-10)
+
+ def test_gh_22183(self, xp):
+ # check for lack of segfault
+ # (out of bounds memory access)
+ # and correct interception of
+ # invalid linkage matrix
+ arr=[[0.0, 1.0, 1.0, 2.0],
+ [2.0, 12.0, 1.0, 3.0],
+ [3.0, 4.0, 1.0, 2.0],
+ [5.0, 14.0, 1.0, 3.0],
+ [6.0, 7.0, 1.0, 2.0],
+ [8.0, 16.0, 1.0, 3.0],
+ [9.0, 10.0, 1.0, 2.0],
+ [11.0, 18.0, 1.0, 3.0],
+ [13.0, 15.0, 2.0, 6.0],
+ [17.0, 20.0, 2.0, 32.0],
+ [19.0, 21.0, 2.0, 12.0]]
+ with pytest.raises(ValueError, match="excessive observations"):
+ cophenet(xp.asarray(arr))
+
+
+class TestMLabLinkageConversion:
+
+ def test_mlab_linkage_conversion_empty(self, xp):
+ # Tests from/to_mlab_linkage on empty linkage array.
+ X = xp.asarray([], dtype=xp.float64)
+ xp_assert_equal(from_mlab_linkage(X), X)
+ xp_assert_equal(to_mlab_linkage(X), X)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_mlab_linkage_conversion_single_row(self, xp):
+ # Tests from/to_mlab_linkage on linkage array with single row.
+ Z = xp.asarray([[0., 1., 3., 2.]])
+ Zm = xp.asarray([[1, 2, 3]])
+ xp_assert_close(from_mlab_linkage(Zm), xp.asarray(Z, dtype=xp.float64),
+ rtol=1e-15)
+ xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+ rtol=1e-15)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_mlab_linkage_conversion_multiple_rows(self, xp):
+ # Tests from/to_mlab_linkage on linkage array with multiple rows.
+ Zm = xp.asarray([[3, 6, 138], [4, 5, 219],
+ [1, 8, 255], [2, 9, 268], [7, 10, 295]])
+ Z = xp.asarray([[2., 5., 138., 2.],
+ [3., 4., 219., 2.],
+ [0., 7., 255., 3.],
+ [1., 8., 268., 4.],
+ [6., 9., 295., 6.]],
+ dtype=xp.float64)
+ xp_assert_close(from_mlab_linkage(Zm), Z, rtol=1e-15)
+ xp_assert_close(to_mlab_linkage(Z), xp.asarray(Zm, dtype=xp.float64),
+ rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestFcluster:
+
+ def test_fclusterdata(self, xp):
+ for t in hierarchy_test_data.fcluster_inconsistent:
+ self.check_fclusterdata(t, 'inconsistent', xp)
+ for t in hierarchy_test_data.fcluster_distance:
+ self.check_fclusterdata(t, 'distance', xp)
+ for t in hierarchy_test_data.fcluster_maxclust:
+ self.check_fclusterdata(t, 'maxclust', xp)
+
+ def check_fclusterdata(self, t, criterion, xp):
+ # Tests fclusterdata(X, criterion=criterion, t=t) on a random 3-cluster data set
+ expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ T = fclusterdata(X, criterion=criterion, t=t)
+ assert_(is_isomorphic(T, expectedT))
+
+ def test_fcluster(self, xp):
+ for t in hierarchy_test_data.fcluster_inconsistent:
+ self.check_fcluster(t, 'inconsistent', xp)
+ for t in hierarchy_test_data.fcluster_distance:
+ self.check_fcluster(t, 'distance', xp)
+ for t in hierarchy_test_data.fcluster_maxclust:
+ self.check_fcluster(t, 'maxclust', xp)
+
+ def check_fcluster(self, t, criterion, xp):
+ # Tests fcluster(Z, criterion=criterion, t=t) on a random 3-cluster data set.
+ expectedT = xp.asarray(getattr(hierarchy_test_data, 'fcluster_' + criterion)[t])
+ Z = single(xp.asarray(hierarchy_test_data.Q_X))
+ T = fcluster(Z, criterion=criterion, t=t)
+ assert_(is_isomorphic(T, expectedT))
+
+ def test_fcluster_monocrit(self, xp):
+ for t in hierarchy_test_data.fcluster_distance:
+ self.check_fcluster_monocrit(t, xp)
+ for t in hierarchy_test_data.fcluster_maxclust:
+ self.check_fcluster_maxclust_monocrit(t, xp)
+
+ def check_fcluster_monocrit(self, t, xp):
+ expectedT = xp.asarray(hierarchy_test_data.fcluster_distance[t])
+ Z = single(xp.asarray(hierarchy_test_data.Q_X))
+ T = fcluster(Z, t, criterion='monocrit', monocrit=maxdists(Z))
+ assert_(is_isomorphic(T, expectedT))
+
+ def check_fcluster_maxclust_monocrit(self, t, xp):
+ expectedT = xp.asarray(hierarchy_test_data.fcluster_maxclust[t])
+ Z = single(xp.asarray(hierarchy_test_data.Q_X))
+ T = fcluster(Z, t, criterion='maxclust_monocrit', monocrit=maxdists(Z))
+ assert_(is_isomorphic(T, expectedT))
+
+ def test_fcluster_maxclust_gh_12651(self, xp):
+ y = xp.asarray([[1], [4], [5]])
+ Z = single(y)
+ assert_array_equal(fcluster(Z, t=1, criterion="maxclust"),
+ xp.asarray([1, 1, 1]))
+ assert_array_equal(fcluster(Z, t=2, criterion="maxclust"),
+ xp.asarray([2, 1, 1]))
+ assert_array_equal(fcluster(Z, t=3, criterion="maxclust"),
+ xp.asarray([1, 2, 3]))
+ assert_array_equal(fcluster(Z, t=5, criterion="maxclust"),
+ xp.asarray([1, 2, 3]))
+
+
+@skip_xp_backends(cpu_only=True)
+class TestLeaders:
+
+ def test_leaders_single(self, xp):
+ # Tests leaders using a flat clustering generated by single linkage.
+ X = hierarchy_test_data.Q_X
+ Y = pdist(X)
+ Y = xp.asarray(Y)
+ Z = linkage(Y)
+ T = fcluster(Z, criterion='maxclust', t=3)
+ Lright = (xp.asarray([53, 55, 56]), xp.asarray([2, 3, 1]))
+ T = xp.asarray(T, dtype=xp.int32)
+ L = leaders(Z, T)
+ assert_allclose(np.concatenate(L), np.concatenate(Lright), rtol=1e-15)
+
+
+@skip_xp_backends(np_only=True,
+ reason='`is_isomorphic` only supports NumPy backend')
+class TestIsIsomorphic:
+
+ @skip_xp_backends(np_only=True,
+ reason='array-likes only supported for NumPy backend')
+ def test_array_like(self, xp):
+ assert is_isomorphic([1, 1, 1], [2, 2, 2])
+ assert is_isomorphic([], [])
+
+ def test_is_isomorphic_1(self, xp):
+ # Tests is_isomorphic on test case #1 (one flat cluster, different labellings)
+ a = xp.asarray([1, 1, 1])
+ b = xp.asarray([2, 2, 2])
+ assert is_isomorphic(a, b)
+ assert is_isomorphic(b, a)
+
+ def test_is_isomorphic_2(self, xp):
+ # Tests is_isomorphic on test case #2 (two flat clusters, different labelings)
+ a = xp.asarray([1, 7, 1])
+ b = xp.asarray([2, 3, 2])
+ assert is_isomorphic(a, b)
+ assert is_isomorphic(b, a)
+
+ def test_is_isomorphic_3(self, xp):
+ # Tests is_isomorphic on test case #3 (no flat clusters)
+ a = xp.asarray([])
+ b = xp.asarray([])
+ assert is_isomorphic(a, b)
+
+ def test_is_isomorphic_4A(self, xp):
+ # Tests is_isomorphic on test case #4A
+ # (3 flat clusters, different labelings, isomorphic)
+ a = xp.asarray([1, 2, 3])
+ b = xp.asarray([1, 3, 2])
+ assert is_isomorphic(a, b)
+ assert is_isomorphic(b, a)
+
+ def test_is_isomorphic_4B(self, xp):
+ # Tests is_isomorphic on test case #4B
+ # (3 flat clusters, different labelings, nonisomorphic)
+ a = xp.asarray([1, 2, 3, 3])
+ b = xp.asarray([1, 3, 2, 3])
+ assert is_isomorphic(a, b) is False
+ assert is_isomorphic(b, a) is False
+
+ def test_is_isomorphic_4C(self, xp):
+ # Tests is_isomorphic on test case #4C
+ # (3 flat clusters, different labelings, isomorphic)
+ a = xp.asarray([7, 2, 3])
+ b = xp.asarray([6, 3, 2])
+ assert is_isomorphic(a, b)
+ assert is_isomorphic(b, a)
+
+ def test_is_isomorphic_5(self, xp):
+ # Tests is_isomorphic on test case #5 (1000 observations, 2/3/5 random
+ # clusters, random permutation of the labeling).
+ for nc in [2, 3, 5]:
+ self.help_is_isomorphic_randperm(1000, nc, xp=xp)
+
+ def test_is_isomorphic_6(self, xp):
+ # Tests is_isomorphic on test case #5A (1000 observations, 2/3/5 random
+ # clusters, random permutation of the labeling, slightly
+ # nonisomorphic.)
+ for nc in [2, 3, 5]:
+ self.help_is_isomorphic_randperm(1000, nc, True, 5, xp=xp)
+
+ def test_is_isomorphic_7(self, xp):
+ # Regression test for gh-6271
+ a = xp.asarray([1, 2, 3])
+ b = xp.asarray([1, 1, 1])
+ assert not is_isomorphic(a, b)
+
+ def help_is_isomorphic_randperm(self, nobs, nclusters, noniso=False, nerrors=0,
+ *, xp):
+ for k in range(3):
+ a = (np.random.rand(nobs) * nclusters).astype(int)
+ b = np.zeros(a.size, dtype=int)
+ P = np.random.permutation(nclusters)
+ for i in range(0, a.shape[0]):
+ b[i] = P[a[i]]
+ if noniso:
+ Q = np.random.permutation(nobs)
+ b[Q[0:nerrors]] += 1
+ b[Q[0:nerrors]] %= nclusters
+ a = xp.asarray(a)
+ b = xp.asarray(b)
+ assert is_isomorphic(a, b) == (not noniso)
+ assert is_isomorphic(b, a) == (not noniso)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestIsValidLinkage:
+
+ def test_is_valid_linkage_various_size(self, xp):
+ for nrow, ncol, valid in [(2, 5, False), (2, 3, False),
+ (1, 4, True), (2, 4, True)]:
+ self.check_is_valid_linkage_various_size(nrow, ncol, valid, xp)
+
+ def check_is_valid_linkage_various_size(self, nrow, ncol, valid, xp):
+ # Tests is_valid_linkage(Z) with linkage matrices of various sizes
+ Z = xp.asarray([[0, 1, 3.0, 2, 5],
+ [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+ Z = Z[:nrow, :ncol]
+ assert_(is_valid_linkage(Z) == valid)
+ if not valid:
+ assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+ def test_is_valid_linkage_int_type(self, xp):
+ # Tests is_valid_linkage(Z) with integer type.
+ Z = xp.asarray([[0, 1, 3.0, 2],
+ [3, 2, 4.0, 3]], dtype=xp.int64)
+ assert_(is_valid_linkage(Z) is False)
+ assert_raises(TypeError, is_valid_linkage, Z, throw=True)
+
+ def test_is_valid_linkage_empty(self, xp):
+ # Tests is_valid_linkage(Z) with empty linkage.
+ Z = xp.zeros((0, 4), dtype=xp.float64)
+ assert_(is_valid_linkage(Z) is False)
+ assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+ def test_is_valid_linkage_4_and_up(self, xp):
+ # Tests is_valid_linkage(Z) on linkage on observation sets between
+ # sizes 4 and 15 (step size 3).
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ assert_(is_valid_linkage(Z) is True)
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_is_valid_linkage_4_and_up_neg_index_left(self, xp):
+ # Tests is_valid_linkage(Z) on linkage on observation sets between
+ # sizes 4 and 15 (step size 3) with negative indices (left).
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ Z[i//2,0] = -2
+ assert_(is_valid_linkage(Z) is False)
+ assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_is_valid_linkage_4_and_up_neg_index_right(self, xp):
+ # Tests is_valid_linkage(Z) on linkage on observation sets between
+ # sizes 4 and 15 (step size 3) with negative indices (right).
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ Z[i//2,1] = -2
+ assert_(is_valid_linkage(Z) is False)
+ assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_is_valid_linkage_4_and_up_neg_dist(self, xp):
+ # Tests is_valid_linkage(Z) on linkage on observation sets between
+ # sizes 4 and 15 (step size 3) with negative distances.
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ Z[i//2,2] = -0.5
+ assert_(is_valid_linkage(Z) is False)
+ assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_is_valid_linkage_4_and_up_neg_counts(self, xp):
+ # Tests is_valid_linkage(Z) on linkage on observation sets between
+ # sizes 4 and 15 (step size 3) with negative counts.
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ Z[i//2,3] = -2
+ assert_(is_valid_linkage(Z) is False)
+ assert_raises(ValueError, is_valid_linkage, Z, throw=True)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestIsValidInconsistent:
+
+ def test_is_valid_im_int_type(self, xp):
+ # Tests is_valid_im(R) with integer type.
+ R = xp.asarray([[0, 1, 3.0, 2],
+ [3, 2, 4.0, 3]], dtype=xp.int64)
+ assert_(is_valid_im(R) is False)
+ assert_raises(TypeError, is_valid_im, R, throw=True)
+
+ def test_is_valid_im_various_size(self, xp):
+ for nrow, ncol, valid in [(2, 5, False), (2, 3, False),
+ (1, 4, True), (2, 4, True)]:
+ self.check_is_valid_im_various_size(nrow, ncol, valid, xp)
+
+ def check_is_valid_im_various_size(self, nrow, ncol, valid, xp):
+ # Tests is_valid_im(R) with linkage matrices of various sizes
+ R = xp.asarray([[0, 1, 3.0, 2, 5],
+ [3, 2, 4.0, 3, 3]], dtype=xp.float64)
+ R = R[:nrow, :ncol]
+ assert_(is_valid_im(R) == valid)
+ if not valid:
+ assert_raises(ValueError, is_valid_im, R, throw=True)
+
+ def test_is_valid_im_empty(self, xp):
+ # Tests is_valid_im(R) with empty inconsistency matrix.
+ R = xp.zeros((0, 4), dtype=xp.float64)
+ assert_(is_valid_im(R) is False)
+ assert_raises(ValueError, is_valid_im, R, throw=True)
+
+ def test_is_valid_im_4_and_up(self, xp):
+ # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+ # (step size 3).
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ R = inconsistent(Z)
+ assert_(is_valid_im(R) is True)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+ def test_is_valid_im_4_and_up_neg_index_left(self, xp):
+ # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+ # (step size 3) with negative link height means.
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ R = inconsistent(Z)
+ R[i//2,0] = -2.0
+ assert_(is_valid_im(R) is False)
+ assert_raises(ValueError, is_valid_im, R, throw=True)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+ def test_is_valid_im_4_and_up_neg_index_right(self, xp):
+ # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+ # (step size 3) with negative link height standard deviations.
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ R = inconsistent(Z)
+ R[i//2,1] = -2.0
+ assert_(is_valid_im(R) is False)
+ assert_raises(ValueError, is_valid_im, R, throw=True)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+ def test_is_valid_im_4_and_up_neg_dist(self, xp):
+ # Tests is_valid_im(R) on im on observation sets between sizes 4 and 15
+ # (step size 3) with negative link counts.
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ R = inconsistent(Z)
+ R[i//2,2] = -0.5
+ assert_(is_valid_im(R) is False)
+ assert_raises(ValueError, is_valid_im, R, throw=True)
+
+
+class TestNumObsLinkage:
+
+ @skip_xp_backends(cpu_only=True)
+ def test_num_obs_linkage_empty(self, xp):
+ # Tests num_obs_linkage(Z) with empty linkage.
+ Z = xp.zeros((0, 4), dtype=xp.float64)
+ assert_raises(ValueError, num_obs_linkage, Z)
+
+ def test_num_obs_linkage_1x4(self, xp):
+ # Tests num_obs_linkage(Z) on linkage over 2 observations.
+ Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+ assert_equal(num_obs_linkage(Z), 2)
+
+ def test_num_obs_linkage_2x4(self, xp):
+ # Tests num_obs_linkage(Z) on linkage over 3 observations.
+ Z = xp.asarray([[0, 1, 3.0, 2],
+ [3, 2, 4.0, 3]], dtype=xp.float64)
+ assert_equal(num_obs_linkage(Z), 3)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_num_obs_linkage_4_and_up(self, xp):
+ # Tests num_obs_linkage(Z) on linkage on observation sets between sizes
+ # 4 and 15 (step size 3).
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ assert_equal(num_obs_linkage(Z), i)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestLeavesList:
+
+ def test_leaves_list_1x4(self, xp):
+ # Tests leaves_list(Z) on a 1x4 linkage.
+ Z = xp.asarray([[0, 1, 3.0, 2]], dtype=xp.float64)
+ to_tree(Z)
+ assert_allclose(leaves_list(Z), [0, 1], rtol=1e-15)
+
+ def test_leaves_list_2x4(self, xp):
+ # Tests leaves_list(Z) on a 2x4 linkage.
+ Z = xp.asarray([[0, 1, 3.0, 2],
+ [3, 2, 4.0, 3]], dtype=xp.float64)
+ to_tree(Z)
+ assert_allclose(leaves_list(Z), [0, 1, 2], rtol=1e-15)
+
+ def test_leaves_list_Q(self, xp):
+ for method in ['single', 'complete', 'average', 'weighted', 'centroid',
+ 'median', 'ward']:
+ self.check_leaves_list_Q(method, xp)
+
+ def check_leaves_list_Q(self, method, xp):
+ # Tests leaves_list(Z) on the Q data set
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ Z = linkage(X, method)
+ node = to_tree(Z)
+ assert_allclose(node.pre_order(), leaves_list(Z), rtol=1e-15)
+
+ def test_Q_subtree_pre_order(self, xp):
+ # Tests that pre_order() works when called on sub-trees.
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ Z = linkage(X, 'single')
+ node = to_tree(Z)
+ assert_allclose(node.pre_order(), (node.get_left().pre_order()
+ + node.get_right().pre_order()),
+ rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestCorrespond:
+
+ def test_correspond_empty(self, xp):
+ # Tests correspond(Z, y) with empty linkage and condensed distance matrix.
+ y = xp.zeros((0,), dtype=xp.float64)
+ Z = xp.zeros((0,4), dtype=xp.float64)
+ assert_raises(ValueError, correspond, Z, y)
+
+ def test_correspond_2_and_up(self, xp):
+ # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+ # different sizes.
+ for i in range(2, 4):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ assert_(correspond(Z, y))
+ for i in range(4, 15, 3):
+ y = np.random.rand(i*(i-1)//2)
+ y = xp.asarray(y)
+ Z = linkage(y)
+ assert_(correspond(Z, y))
+
+ def test_correspond_4_and_up(self, xp):
+ # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+ # different sizes. Correspondence should be false.
+ for (i, j) in (list(zip(list(range(2, 4)), list(range(3, 5)))) +
+ list(zip(list(range(3, 5)), list(range(2, 4))))):
+ y = np.random.rand(i*(i-1)//2)
+ y2 = np.random.rand(j*(j-1)//2)
+ y = xp.asarray(y)
+ y2 = xp.asarray(y2)
+ Z = linkage(y)
+ Z2 = linkage(y2)
+ assert not correspond(Z, y2)
+ assert not correspond(Z2, y)
+
+ def test_correspond_4_and_up_2(self, xp):
+ # Tests correspond(Z, y) on linkage and CDMs over observation sets of
+ # different sizes. Correspondence should be false.
+ for (i, j) in (list(zip(list(range(2, 7)), list(range(16, 21)))) +
+ list(zip(list(range(2, 7)), list(range(16, 21))))):
+ y = np.random.rand(i*(i-1)//2)
+ y2 = np.random.rand(j*(j-1)//2)
+ y = xp.asarray(y)
+ y2 = xp.asarray(y2)
+ Z = linkage(y)
+ Z2 = linkage(y2)
+ assert not correspond(Z, y2)
+ assert not correspond(Z2, y)
+
+ def test_num_obs_linkage_multi_matrix(self, xp):
+ # Tests num_obs_linkage with observation matrices of multiple sizes.
+ for n in range(2, 10):
+ X = np.random.rand(n, 4)
+ Y = pdist(X)
+ Y = xp.asarray(Y)
+ Z = linkage(Y)
+ assert_equal(num_obs_linkage(Z), n)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestIsMonotonic:
+
+ def test_is_monotonic_empty(self, xp):
+ # Tests is_monotonic(Z) on an empty linkage.
+ Z = xp.zeros((0, 4), dtype=xp.float64)
+ assert_raises(ValueError, is_monotonic, Z)
+
+ def test_is_monotonic_1x4(self, xp):
+ # Tests is_monotonic(Z) on 1x4 linkage. Expecting True.
+ Z = xp.asarray([[0, 1, 0.3, 2]], dtype=xp.float64)
+ assert is_monotonic(Z)
+
+ def test_is_monotonic_2x4_T(self, xp):
+ # Tests is_monotonic(Z) on 2x4 linkage. Expecting True.
+ Z = xp.asarray([[0, 1, 0.3, 2],
+ [2, 3, 0.4, 3]], dtype=xp.float64)
+ assert is_monotonic(Z)
+
+ def test_is_monotonic_2x4_F(self, xp):
+ # Tests is_monotonic(Z) on 2x4 linkage. Expecting False.
+ Z = xp.asarray([[0, 1, 0.4, 2],
+ [2, 3, 0.3, 3]], dtype=xp.float64)
+ assert not is_monotonic(Z)
+
+ def test_is_monotonic_3x4_T(self, xp):
+ # Tests is_monotonic(Z) on 3x4 linkage. Expecting True.
+ Z = xp.asarray([[0, 1, 0.3, 2],
+ [2, 3, 0.4, 2],
+ [4, 5, 0.6, 4]], dtype=xp.float64)
+ assert is_monotonic(Z)
+
+ def test_is_monotonic_3x4_F1(self, xp):
+ # Tests is_monotonic(Z) on 3x4 linkage (case 1). Expecting False.
+ Z = xp.asarray([[0, 1, 0.3, 2],
+ [2, 3, 0.2, 2],
+ [4, 5, 0.6, 4]], dtype=xp.float64)
+ assert not is_monotonic(Z)
+
+ def test_is_monotonic_3x4_F2(self, xp):
+ # Tests is_monotonic(Z) on 3x4 linkage (case 2). Expecting False.
+ Z = xp.asarray([[0, 1, 0.8, 2],
+ [2, 3, 0.4, 2],
+ [4, 5, 0.6, 4]], dtype=xp.float64)
+ assert not is_monotonic(Z)
+
+ def test_is_monotonic_3x4_F3(self, xp):
+ # Tests is_monotonic(Z) on 3x4 linkage (case 3). Expecting False
+ Z = xp.asarray([[0, 1, 0.3, 2],
+ [2, 3, 0.4, 2],
+ [4, 5, 0.2, 4]], dtype=xp.float64)
+ assert not is_monotonic(Z)
+
+ def test_is_monotonic_tdist_linkage1(self, xp):
+ # Tests is_monotonic(Z) on clustering generated by single linkage on
+ # tdist data set. Expecting True.
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+ assert is_monotonic(Z)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+ def test_is_monotonic_tdist_linkage2(self, xp):
+ # Tests is_monotonic(Z) on clustering generated by single linkage on
+ # tdist data set. Perturbing. Expecting False.
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+ Z[2,2] = 0.0
+ assert not is_monotonic(Z)
+
+ def test_is_monotonic_Q_linkage(self, xp):
+ # Tests is_monotonic(Z) on clustering generated by single linkage on
+ # Q data set. Expecting True.
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ Z = linkage(X, 'single')
+ assert is_monotonic(Z)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestMaxDists:
+
+ def test_maxdists_empty_linkage(self, xp):
+ # Tests maxdists(Z) on empty linkage. Expecting exception.
+ Z = xp.zeros((0, 4), dtype=xp.float64)
+ assert_raises(ValueError, maxdists, Z)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+ def test_maxdists_one_cluster_linkage(self, xp):
+ # Tests maxdists(Z) on linkage with one cluster.
+ Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+ MD = maxdists(Z)
+ expectedMD = calculate_maximum_distances(Z, xp)
+ xp_assert_close(MD, expectedMD, atol=1e-15)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment')
+ def test_maxdists_Q_linkage(self, xp):
+ for method in ['single', 'complete', 'ward', 'centroid', 'median']:
+ self.check_maxdists_Q_linkage(method, xp)
+
+ def check_maxdists_Q_linkage(self, method, xp):
+ # Tests maxdists(Z) on the Q data set
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ Z = linkage(X, method)
+ MD = maxdists(Z)
+ expectedMD = calculate_maximum_distances(Z, xp)
+ xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+class TestMaxInconsts:
+
+ @skip_xp_backends(cpu_only=True)
+ def test_maxinconsts_empty_linkage(self, xp):
+ # Tests maxinconsts(Z, R) on empty linkage. Expecting exception.
+ Z = xp.zeros((0, 4), dtype=xp.float64)
+ R = xp.zeros((0, 4), dtype=xp.float64)
+ assert_raises(ValueError, maxinconsts, Z, R)
+
+ def test_maxinconsts_difrow_linkage(self, xp):
+ # Tests maxinconsts(Z, R) on linkage and inconsistency matrices with
+ # different numbers of clusters. Expecting exception.
+ Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+ R = np.random.rand(2, 4)
+ R = xp.asarray(R)
+ assert_raises(ValueError, maxinconsts, Z, R)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+ cpu_only=True)
+ def test_maxinconsts_one_cluster_linkage(self, xp):
+ # Tests maxinconsts(Z, R) on linkage with one cluster.
+ Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+ R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+ MD = maxinconsts(Z, R)
+ expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+ xp_assert_close(MD, expectedMD, atol=1e-15)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+ cpu_only=True)
+ def test_maxinconsts_Q_linkage(self, xp):
+ for method in ['single', 'complete', 'ward', 'centroid', 'median']:
+ self.check_maxinconsts_Q_linkage(method, xp)
+
+ def check_maxinconsts_Q_linkage(self, method, xp):
+ # Tests maxinconsts(Z, R) on the Q data set
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ Z = linkage(X, method)
+ R = inconsistent(Z)
+ MD = maxinconsts(Z, R)
+ expectedMD = calculate_maximum_inconsistencies(Z, R, xp=xp)
+ xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+class TestMaxRStat:
+
+ def test_maxRstat_invalid_index(self, xp):
+ for i in [3.3, -1, 4]:
+ self.check_maxRstat_invalid_index(i, xp)
+
+ def check_maxRstat_invalid_index(self, i, xp):
+ # Tests maxRstat(Z, R, i). Expecting exception.
+ Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+ R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+ if isinstance(i, int):
+ assert_raises(ValueError, maxRstat, Z, R, i)
+ else:
+ assert_raises(TypeError, maxRstat, Z, R, i)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_maxRstat_empty_linkage(self, xp):
+ for i in range(4):
+ self.check_maxRstat_empty_linkage(i, xp)
+
+ def check_maxRstat_empty_linkage(self, i, xp):
+ # Tests maxRstat(Z, R, i) on empty linkage. Expecting exception.
+ Z = xp.zeros((0, 4), dtype=xp.float64)
+ R = xp.zeros((0, 4), dtype=xp.float64)
+ assert_raises(ValueError, maxRstat, Z, R, i)
+
+ def test_maxRstat_difrow_linkage(self, xp):
+ for i in range(4):
+ self.check_maxRstat_difrow_linkage(i, xp)
+
+ def check_maxRstat_difrow_linkage(self, i, xp):
+ # Tests maxRstat(Z, R, i) on linkage and inconsistency matrices with
+ # different numbers of clusters. Expecting exception.
+ Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+ R = np.random.rand(2, 4)
+ R = xp.asarray(R)
+ assert_raises(ValueError, maxRstat, Z, R, i)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+ cpu_only=True)
+ def test_maxRstat_one_cluster_linkage(self, xp):
+ for i in range(4):
+ self.check_maxRstat_one_cluster_linkage(i, xp)
+
+ def check_maxRstat_one_cluster_linkage(self, i, xp):
+ # Tests maxRstat(Z, R, i) on linkage with one cluster.
+ Z = xp.asarray([[0, 1, 0.3, 4]], dtype=xp.float64)
+ R = xp.asarray([[0, 0, 0, 0.3]], dtype=xp.float64)
+ MD = maxRstat(Z, R, 1)
+ expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+ xp_assert_close(MD, expectedMD, atol=1e-15)
+
+ @skip_xp_backends('jax.numpy', reason='jax arrays do not support item assignment',
+ cpu_only=True)
+ def test_maxRstat_Q_linkage(self, xp):
+ for method in ['single', 'complete', 'ward', 'centroid', 'median']:
+ for i in range(4):
+ self.check_maxRstat_Q_linkage(method, i, xp)
+
+ def check_maxRstat_Q_linkage(self, method, i, xp):
+ # Tests maxRstat(Z, R, i) on the Q data set
+ X = xp.asarray(hierarchy_test_data.Q_X)
+ Z = linkage(X, method)
+ R = inconsistent(Z)
+ MD = maxRstat(Z, R, 1)
+ expectedMD = calculate_maximum_inconsistencies(Z, R, 1, xp)
+ xp_assert_close(MD, expectedMD, atol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+class TestDendrogram:
+
+ def test_dendrogram_single_linkage_tdist(self, xp):
+ # Tests dendrogram calculation on single linkage of the tdist data set.
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+ R = dendrogram(Z, no_plot=True)
+ leaves = R["leaves"]
+ assert_equal(leaves, [2, 5, 1, 0, 3, 4])
+
+ def test_valid_orientation(self, xp):
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+ assert_raises(ValueError, dendrogram, Z, orientation="foo")
+
+ def test_labels_as_array_or_list(self, xp):
+ # test for gh-12418
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+ labels = [1, 3, 2, 6, 4, 5]
+ result1 = dendrogram(Z, labels=xp.asarray(labels), no_plot=True)
+ result2 = dendrogram(Z, labels=labels, no_plot=True)
+ assert result1 == result2
+
+ @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+ def test_valid_label_size(self, xp):
+ link = xp.asarray([
+ [0, 1, 1.0, 4],
+ [2, 3, 1.0, 5],
+ [4, 5, 2.0, 6],
+ ])
+ plt.figure()
+ with pytest.raises(ValueError) as exc_info:
+ dendrogram(link, labels=list(range(100)))
+ assert "Dimensions of Z and labels must be consistent."\
+ in str(exc_info.value)
+
+ with pytest.raises(
+ ValueError,
+ match="Dimensions of Z and labels must be consistent."):
+ dendrogram(link, labels=[])
+
+ plt.close()
+
+ @skip_xp_backends('torch',
+ reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+ ' and NumPy 2.0'
+ )
+ @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+ def test_dendrogram_plot(self, xp):
+ for orientation in ['top', 'bottom', 'left', 'right']:
+ self.check_dendrogram_plot(orientation, xp)
+
+ def check_dendrogram_plot(self, orientation, xp):
+ # Tests dendrogram plotting.
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+ expected = {'color_list': ['C1', 'C0', 'C0', 'C0', 'C0'],
+ 'dcoord': [[0.0, 138.0, 138.0, 0.0],
+ [0.0, 219.0, 219.0, 0.0],
+ [0.0, 255.0, 255.0, 219.0],
+ [0.0, 268.0, 268.0, 255.0],
+ [138.0, 295.0, 295.0, 268.0]],
+ 'icoord': [[5.0, 5.0, 15.0, 15.0],
+ [45.0, 45.0, 55.0, 55.0],
+ [35.0, 35.0, 50.0, 50.0],
+ [25.0, 25.0, 42.5, 42.5],
+ [10.0, 10.0, 33.75, 33.75]],
+ 'ivl': ['2', '5', '1', '0', '3', '4'],
+ 'leaves': [2, 5, 1, 0, 3, 4],
+ 'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0', 'C0'],
+ }
+
+ fig = plt.figure()
+ ax = fig.add_subplot(221)
+
+ # test that dendrogram accepts ax keyword
+ R1 = dendrogram(Z, ax=ax, orientation=orientation)
+ R1['dcoord'] = np.asarray(R1['dcoord'])
+ assert_equal(R1, expected)
+
+ # test that dendrogram accepts and handle the leaf_font_size and
+ # leaf_rotation keywords
+ dendrogram(Z, ax=ax, orientation=orientation,
+ leaf_font_size=20, leaf_rotation=90)
+ testlabel = (
+ ax.get_xticklabels()[0]
+ if orientation in ['top', 'bottom']
+ else ax.get_yticklabels()[0]
+ )
+ assert_equal(testlabel.get_rotation(), 90)
+ assert_equal(testlabel.get_size(), 20)
+ dendrogram(Z, ax=ax, orientation=orientation,
+ leaf_rotation=90)
+ testlabel = (
+ ax.get_xticklabels()[0]
+ if orientation in ['top', 'bottom']
+ else ax.get_yticklabels()[0]
+ )
+ assert_equal(testlabel.get_rotation(), 90)
+ dendrogram(Z, ax=ax, orientation=orientation,
+ leaf_font_size=20)
+ testlabel = (
+ ax.get_xticklabels()[0]
+ if orientation in ['top', 'bottom']
+ else ax.get_yticklabels()[0]
+ )
+ assert_equal(testlabel.get_size(), 20)
+ plt.close()
+
+ # test plotting to gca (will import pylab)
+ R2 = dendrogram(Z, orientation=orientation)
+ plt.close()
+ R2['dcoord'] = np.asarray(R2['dcoord'])
+ assert_equal(R2, expected)
+
+ @skip_xp_backends('torch',
+ reason='MPL 3.9.2 & torch DeprecationWarning from __array_wrap__'
+ ' and NumPy 2.0'
+ )
+ @pytest.mark.skipif(not have_matplotlib, reason="no matplotlib")
+ def test_dendrogram_truncate_mode(self, xp):
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+
+ R = dendrogram(Z, 2, 'lastp', show_contracted=True)
+ plt.close()
+ R['dcoord'] = np.asarray(R['dcoord'])
+ assert_equal(R, {'color_list': ['C0'],
+ 'dcoord': [[0.0, 295.0, 295.0, 0.0]],
+ 'icoord': [[5.0, 5.0, 15.0, 15.0]],
+ 'ivl': ['(2)', '(4)'],
+ 'leaves': [6, 9],
+ 'leaves_color_list': ['C0', 'C0'],
+ })
+
+ R = dendrogram(Z, 2, 'mtica', show_contracted=True)
+ plt.close()
+ R['dcoord'] = np.asarray(R['dcoord'])
+ assert_equal(R, {'color_list': ['C1', 'C0', 'C0', 'C0'],
+ 'dcoord': [[0.0, 138.0, 138.0, 0.0],
+ [0.0, 255.0, 255.0, 0.0],
+ [0.0, 268.0, 268.0, 255.0],
+ [138.0, 295.0, 295.0, 268.0]],
+ 'icoord': [[5.0, 5.0, 15.0, 15.0],
+ [35.0, 35.0, 45.0, 45.0],
+ [25.0, 25.0, 40.0, 40.0],
+ [10.0, 10.0, 32.5, 32.5]],
+ 'ivl': ['2', '5', '1', '0', '(2)'],
+ 'leaves': [2, 5, 1, 0, 7],
+ 'leaves_color_list': ['C1', 'C1', 'C0', 'C0', 'C0'],
+ })
+
+ @pytest.fixture
+ def dendrogram_lock(self):
+ return Lock()
+
+ def test_dendrogram_colors(self, xp, dendrogram_lock):
+ # Tests dendrogram plots with alternate colors
+ Z = linkage(xp.asarray(hierarchy_test_data.ytdist), 'single')
+
+ with dendrogram_lock:
+ # Global color palette might be changed concurrently
+ set_link_color_palette(['c', 'm', 'y', 'k'])
+ R = dendrogram(Z, no_plot=True,
+ above_threshold_color='g', color_threshold=250)
+ set_link_color_palette(['g', 'r', 'c', 'm', 'y', 'k'])
+
+ color_list = R['color_list']
+ assert_equal(color_list, ['c', 'm', 'g', 'g', 'g'])
+
+ # reset color palette (global list)
+ set_link_color_palette(None)
+
+ def test_dendrogram_leaf_colors_zero_dist(self, xp):
+ # tests that the colors of leafs are correct for tree
+ # with two identical points
+ x = xp.asarray([[1, 0, 0],
+ [0, 0, 1],
+ [0, 2, 0],
+ [0, 0, 1],
+ [0, 1, 0],
+ [0, 1, 0]])
+ z = linkage(x, "single")
+ d = dendrogram(z, no_plot=True)
+ exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+ colors = d["leaves_color_list"]
+ assert_equal(colors, exp_colors)
+
+ def test_dendrogram_leaf_colors(self, xp):
+ # tests that the colors are correct for a tree
+ # with two near points ((0, 0, 1.1) and (0, 0, 1))
+ x = xp.asarray([[1, 0, 0],
+ [0, 0, 1.1],
+ [0, 2, 0],
+ [0, 0, 1],
+ [0, 1, 0],
+ [0, 1, 0]])
+ z = linkage(x, "single")
+ d = dendrogram(z, no_plot=True)
+ exp_colors = ['C0', 'C1', 'C1', 'C0', 'C2', 'C2']
+ colors = d["leaves_color_list"]
+ assert_equal(colors, exp_colors)
+
+
+def calculate_maximum_distances(Z, xp):
+ # Used for testing correctness of maxdists.
+ n = Z.shape[0] + 1
+ B = xp.zeros((n-1,), dtype=Z.dtype)
+ q = xp.zeros((3,))
+ for i in range(0, n - 1):
+ q[:] = 0.0
+ left = Z[i, 0]
+ right = Z[i, 1]
+ if left >= n:
+ q[0] = B[xp.asarray(left, dtype=xp.int64) - n]
+ if right >= n:
+ q[1] = B[xp.asarray(right, dtype=xp.int64) - n]
+ q[2] = Z[i, 2]
+ B[i] = xp.max(q)
+ return B
+
+
+def calculate_maximum_inconsistencies(Z, R, k=3, xp=np):
+ # Used for testing correctness of maxinconsts.
+ n = Z.shape[0] + 1
+ dtype = xp.result_type(Z, R)
+ B = xp.zeros((n-1,), dtype=dtype)
+ q = xp.zeros((3,))
+ for i in range(0, n - 1):
+ q[:] = 0.0
+ left = Z[i, 0]
+ right = Z[i, 1]
+ if left >= n:
+ q[0] = B[xp.asarray(left, dtype=xp.int64) - n]
+ if right >= n:
+ q[1] = B[xp.asarray(right, dtype=xp.int64) - n]
+ q[2] = R[i, k]
+ B[i] = xp.max(q)
+ return B
+
+
+@pytest.mark.thread_unsafe
+@skip_xp_backends(cpu_only=True)
+def test_unsupported_uncondensed_distance_matrix_linkage_warning(xp):
+ assert_warns(ClusterWarning, linkage, xp.asarray([[0, 1], [1, 0]]))
+
+
+def test_euclidean_linkage_value_error(xp):
+ for method in scipy.cluster.hierarchy._EUCLIDEAN_METHODS:
+ assert_raises(ValueError, linkage, xp.asarray([[1, 1], [1, 1]]),
+ method=method, metric='cityblock')
+
+
+@skip_xp_backends(cpu_only=True)
+def test_2x2_linkage(xp):
+ Z1 = linkage(xp.asarray([1]), method='single', metric='euclidean')
+ Z2 = linkage(xp.asarray([[0, 1], [0, 0]]), method='single', metric='euclidean')
+ xp_assert_close(Z1, Z2, rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+def test_node_compare(xp):
+ np.random.seed(23)
+ nobs = 50
+ X = np.random.randn(nobs, 4)
+ X = xp.asarray(X)
+ Z = scipy.cluster.hierarchy.ward(X)
+ tree = to_tree(Z)
+ assert_(tree > tree.get_left())
+ assert_(tree.get_right() > tree.get_left())
+ assert_(tree.get_right() == tree.get_right())
+ assert_(tree.get_right() != tree.get_left())
+
+
+@skip_xp_backends(np_only=True, reason='`cut_tree` uses non-standard indexing')
+def test_cut_tree(xp):
+ np.random.seed(23)
+ nobs = 50
+ X = np.random.randn(nobs, 4)
+ X = xp.asarray(X)
+ Z = scipy.cluster.hierarchy.ward(X)
+ cutree = cut_tree(Z)
+
+ # cutree.dtype varies between int32 and int64 over platforms
+ xp_assert_close(cutree[:, 0], xp.arange(nobs), rtol=1e-15, check_dtype=False)
+ xp_assert_close(cutree[:, -1], xp.zeros(nobs), rtol=1e-15, check_dtype=False)
+ assert_equal(np.asarray(cutree).max(0), np.arange(nobs - 1, -1, -1))
+
+ xp_assert_close(cutree[:, [-5]], cut_tree(Z, n_clusters=5), rtol=1e-15)
+ xp_assert_close(cutree[:, [-5, -10]], cut_tree(Z, n_clusters=[5, 10]), rtol=1e-15)
+ xp_assert_close(cutree[:, [-10, -5]], cut_tree(Z, n_clusters=[10, 5]), rtol=1e-15)
+
+ nodes = _order_cluster_tree(Z)
+ heights = xp.asarray([node.dist for node in nodes])
+
+ xp_assert_close(cutree[:, np.searchsorted(heights, [5])],
+ cut_tree(Z, height=5), rtol=1e-15)
+ xp_assert_close(cutree[:, np.searchsorted(heights, [5, 10])],
+ cut_tree(Z, height=[5, 10]), rtol=1e-15)
+ xp_assert_close(cutree[:, np.searchsorted(heights, [10, 5])],
+ cut_tree(Z, height=[10, 5]), rtol=1e-15)
+
+
+@skip_xp_backends(cpu_only=True)
+def test_optimal_leaf_ordering(xp):
+ # test with the distance vector y
+ Z = optimal_leaf_ordering(linkage(xp.asarray(hierarchy_test_data.ytdist)),
+ xp.asarray(hierarchy_test_data.ytdist))
+ expectedZ = hierarchy_test_data.linkage_ytdist_single_olo
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-10)
+
+ # test with the observation matrix X
+ Z = optimal_leaf_ordering(linkage(xp.asarray(hierarchy_test_data.X), 'ward'),
+ xp.asarray(hierarchy_test_data.X))
+ expectedZ = hierarchy_test_data.linkage_X_ward_olo
+ xp_assert_close(Z, xp.asarray(expectedZ), atol=1e-06)
+
+
+@skip_xp_backends(np_only=True, reason='`Heap` only supports NumPy backend')
+def test_Heap(xp):
+ values = xp.asarray([2, -1, 0, -1.5, 3])
+ heap = Heap(values)
+
+ pair = heap.get_min()
+ assert_equal(pair['key'], 3)
+ assert_equal(pair['value'], -1.5)
+
+ heap.remove_min()
+ pair = heap.get_min()
+ assert_equal(pair['key'], 1)
+ assert_equal(pair['value'], -1)
+
+ heap.change_value(1, 2.5)
+ pair = heap.get_min()
+ assert_equal(pair['key'], 2)
+ assert_equal(pair['value'], 0)
+
+ heap.remove_min()
+ heap.remove_min()
+
+ heap.change_value(1, 10)
+ pair = heap.get_min()
+ assert_equal(pair['key'], 4)
+ assert_equal(pair['value'], 3)
+
+ heap.remove_min()
+ pair = heap.get_min()
+ assert_equal(pair['key'], 1)
+ assert_equal(pair['value'], 10)
+
+
+@skip_xp_backends(cpu_only=True)
+def test_centroid_neg_distance(xp):
+ # gh-21011
+ values = xp.asarray([0, 0, -1])
+ with pytest.raises(ValueError):
+ # This is just checking that this doesn't crash
+ linkage(values, method='centroid')
diff --git a/python_embeded/Lib/site-packages/scipy/cluster/tests/test_vq.py b/python_embeded/Lib/site-packages/scipy/cluster/tests/test_vq.py
new file mode 100644
index 0000000000000000000000000000000000000000..1902041fdce6b4f9241356cf45b83e7fbdda389d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/cluster/tests/test_vq.py
@@ -0,0 +1,450 @@
+import warnings
+import sys
+from copy import deepcopy
+from threading import Lock
+
+import numpy as np
+from numpy.testing import (
+ assert_array_equal, assert_equal, assert_, suppress_warnings
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.cluster.vq import (kmeans, kmeans2, py_vq, vq, whiten,
+ ClusterError, _krandinit)
+from scipy.cluster import _vq
+from scipy.conftest import array_api_compatible
+from scipy.sparse._sputils import matrix
+
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._array_api import (
+ SCIPY_ARRAY_API, array_namespace, xp_copy, xp_assert_close, xp_assert_equal
+)
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+TESTDATA_2D = np.array([
+ -2.2, 1.17, -1.63, 1.69, -2.04, 4.38, -3.09, 0.95, -1.7, 4.79, -1.68, 0.68,
+ -2.26, 3.34, -2.29, 2.55, -1.72, -0.72, -1.99, 2.34, -2.75, 3.43, -2.45,
+ 2.41, -4.26, 3.65, -1.57, 1.87, -1.96, 4.03, -3.01, 3.86, -2.53, 1.28,
+ -4.0, 3.95, -1.62, 1.25, -3.42, 3.17, -1.17, 0.12, -3.03, -0.27, -2.07,
+ -0.55, -1.17, 1.34, -2.82, 3.08, -2.44, 0.24, -1.71, 2.48, -5.23, 4.29,
+ -2.08, 3.69, -1.89, 3.62, -2.09, 0.26, -0.92, 1.07, -2.25, 0.88, -2.25,
+ 2.02, -4.31, 3.86, -2.03, 3.42, -2.76, 0.3, -2.48, -0.29, -3.42, 3.21,
+ -2.3, 1.73, -2.84, 0.69, -1.81, 2.48, -5.24, 4.52, -2.8, 1.31, -1.67,
+ -2.34, -1.18, 2.17, -2.17, 2.82, -1.85, 2.25, -2.45, 1.86, -6.79, 3.94,
+ -2.33, 1.89, -1.55, 2.08, -1.36, 0.93, -2.51, 2.74, -2.39, 3.92, -3.33,
+ 2.99, -2.06, -0.9, -2.83, 3.35, -2.59, 3.05, -2.36, 1.85, -1.69, 1.8,
+ -1.39, 0.66, -2.06, 0.38, -1.47, 0.44, -4.68, 3.77, -5.58, 3.44, -2.29,
+ 2.24, -1.04, -0.38, -1.85, 4.23, -2.88, 0.73, -2.59, 1.39, -1.34, 1.75,
+ -1.95, 1.3, -2.45, 3.09, -1.99, 3.41, -5.55, 5.21, -1.73, 2.52, -2.17,
+ 0.85, -2.06, 0.49, -2.54, 2.07, -2.03, 1.3, -3.23, 3.09, -1.55, 1.44,
+ -0.81, 1.1, -2.99, 2.92, -1.59, 2.18, -2.45, -0.73, -3.12, -1.3, -2.83,
+ 0.2, -2.77, 3.24, -1.98, 1.6, -4.59, 3.39, -4.85, 3.75, -2.25, 1.71, -3.28,
+ 3.38, -1.74, 0.88, -2.41, 1.92, -2.24, 1.19, -2.48, 1.06, -1.68, -0.62,
+ -1.3, 0.39, -1.78, 2.35, -3.54, 2.44, -1.32, 0.66, -2.38, 2.76, -2.35,
+ 3.95, -1.86, 4.32, -2.01, -1.23, -1.79, 2.76, -2.13, -0.13, -5.25, 3.84,
+ -2.24, 1.59, -4.85, 2.96, -2.41, 0.01, -0.43, 0.13, -3.92, 2.91, -1.75,
+ -0.53, -1.69, 1.69, -1.09, 0.15, -2.11, 2.17, -1.53, 1.22, -2.1, -0.86,
+ -2.56, 2.28, -3.02, 3.33, -1.12, 3.86, -2.18, -1.19, -3.03, 0.79, -0.83,
+ 0.97, -3.19, 1.45, -1.34, 1.28, -2.52, 4.22, -4.53, 3.22, -1.97, 1.75,
+ -2.36, 3.19, -0.83, 1.53, -1.59, 1.86, -2.17, 2.3, -1.63, 2.71, -2.03,
+ 3.75, -2.57, -0.6, -1.47, 1.33, -1.95, 0.7, -1.65, 1.27, -1.42, 1.09, -3.0,
+ 3.87, -2.51, 3.06, -2.6, 0.74, -1.08, -0.03, -2.44, 1.31, -2.65, 2.99,
+ -1.84, 1.65, -4.76, 3.75, -2.07, 3.98, -2.4, 2.67, -2.21, 1.49, -1.21,
+ 1.22, -5.29, 2.38, -2.85, 2.28, -5.6, 3.78, -2.7, 0.8, -1.81, 3.5, -3.75,
+ 4.17, -1.29, 2.99, -5.92, 3.43, -1.83, 1.23, -1.24, -1.04, -2.56, 2.37,
+ -3.26, 0.39, -4.63, 2.51, -4.52, 3.04, -1.7, 0.36, -1.41, 0.04, -2.1, 1.0,
+ -1.87, 3.78, -4.32, 3.59, -2.24, 1.38, -1.99, -0.22, -1.87, 1.95, -0.84,
+ 2.17, -5.38, 3.56, -1.27, 2.9, -1.79, 3.31, -5.47, 3.85, -1.44, 3.69,
+ -2.02, 0.37, -1.29, 0.33, -2.34, 2.56, -1.74, -1.27, -1.97, 1.22, -2.51,
+ -0.16, -1.64, -0.96, -2.99, 1.4, -1.53, 3.31, -2.24, 0.45, -2.46, 1.71,
+ -2.88, 1.56, -1.63, 1.46, -1.41, 0.68, -1.96, 2.76, -1.61,
+ 2.11]).reshape((200, 2))
+
+
+# Global data
+X = np.array([[3.0, 3], [4, 3], [4, 2],
+ [9, 2], [5, 1], [6, 2], [9, 4],
+ [5, 2], [5, 4], [7, 4], [6, 5]])
+
+CODET1 = np.array([[3.0000, 3.0000],
+ [6.2000, 4.0000],
+ [5.8000, 1.8000]])
+
+CODET2 = np.array([[11.0/3, 8.0/3],
+ [6.7500, 4.2500],
+ [6.2500, 1.7500]])
+
+LABEL1 = np.array([0, 1, 2, 2, 2, 2, 1, 2, 1, 1, 1])
+
+
+class TestWhiten:
+
+ def test_whiten(self, xp):
+ desired = xp.asarray([[5.08738849, 2.97091878],
+ [3.19909255, 0.69660580],
+ [4.51041982, 0.02640918],
+ [4.38567074, 0.95120889],
+ [2.32191480, 1.63195503]])
+
+ obs = xp.asarray([[0.98744510, 0.82766775],
+ [0.62093317, 0.19406729],
+ [0.87545741, 0.00735733],
+ [0.85124403, 0.26499712],
+ [0.45067590, 0.45464607]])
+ xp_assert_close(whiten(obs), desired, rtol=1e-5)
+
+ @pytest.fixture
+ def whiten_lock(self):
+ return Lock()
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_whiten_zero_std(self, xp, whiten_lock):
+ desired = xp.asarray([[0., 1.0, 2.86666544],
+ [0., 1.0, 1.32460034],
+ [0., 1.0, 3.74382172]])
+
+ obs = xp.asarray([[0., 1., 0.74109533],
+ [0., 1., 0.34243798],
+ [0., 1., 0.96785929]])
+
+ with whiten_lock:
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+
+ xp_assert_close(whiten(obs), desired, rtol=1e-5)
+
+ assert_equal(len(w), 1)
+ assert_(issubclass(w[-1].category, RuntimeWarning))
+
+ def test_whiten_not_finite(self, xp):
+ for bad_value in xp.nan, xp.inf, -xp.inf:
+ obs = xp.asarray([[0.98744510, bad_value],
+ [0.62093317, 0.19406729],
+ [0.87545741, 0.00735733],
+ [0.85124403, 0.26499712],
+ [0.45067590, 0.45464607]])
+ assert_raises(ValueError, whiten, obs)
+
+ @pytest.mark.skipif(SCIPY_ARRAY_API,
+ reason='`np.matrix` unsupported in array API mode')
+ def test_whiten_not_finite_matrix(self, xp):
+ for bad_value in np.nan, np.inf, -np.inf:
+ obs = matrix([[0.98744510, bad_value],
+ [0.62093317, 0.19406729],
+ [0.87545741, 0.00735733],
+ [0.85124403, 0.26499712],
+ [0.45067590, 0.45464607]])
+ assert_raises(ValueError, whiten, obs)
+
+
+class TestVq:
+
+ @skip_xp_backends(cpu_only=True)
+ def test_py_vq(self, xp):
+ initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+ # label1.dtype varies between int32 and int64 over platforms
+ label1 = py_vq(xp.asarray(X), xp.asarray(initc))[0]
+ xp_assert_equal(label1, xp.asarray(LABEL1, dtype=xp.int64),
+ check_dtype=False)
+
+ @pytest.mark.skipif(SCIPY_ARRAY_API,
+ reason='`np.matrix` unsupported in array API mode')
+ def test_py_vq_matrix(self, xp):
+ initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+ # label1.dtype varies between int32 and int64 over platforms
+ label1 = py_vq(matrix(X), matrix(initc))[0]
+ assert_array_equal(label1, LABEL1)
+
+ @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend')
+ def test_vq(self, xp):
+ initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+ label1, _ = _vq.vq(xp.asarray(X), xp.asarray(initc))
+ assert_array_equal(label1, LABEL1)
+ _, _ = vq(xp.asarray(X), xp.asarray(initc))
+
+ @pytest.mark.skipif(SCIPY_ARRAY_API,
+ reason='`np.matrix` unsupported in array API mode')
+ def test_vq_matrix(self, xp):
+ initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+ label1, _ = _vq.vq(matrix(X), matrix(initc))
+ assert_array_equal(label1, LABEL1)
+ _, _ = vq(matrix(X), matrix(initc))
+
+ @skip_xp_backends(cpu_only=True)
+ def test_vq_1d(self, xp):
+ # Test special rank 1 vq algo, python implementation.
+ data = X[:, 0]
+ initc = data[:3]
+ a, b = _vq.vq(data, initc)
+ data = xp.asarray(data)
+ initc = xp.asarray(initc)
+ ta, tb = py_vq(data[:, np.newaxis], initc[:, np.newaxis])
+ # ta.dtype varies between int32 and int64 over platforms
+ xp_assert_equal(ta, xp.asarray(a, dtype=xp.int64), check_dtype=False)
+ xp_assert_equal(tb, xp.asarray(b))
+
+ @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend')
+ def test__vq_sametype(self, xp):
+ a = xp.asarray([1.0, 2.0], dtype=xp.float64)
+ b = a.astype(xp.float32)
+ assert_raises(TypeError, _vq.vq, a, b)
+
+ @skip_xp_backends(np_only=True, reason='`_vq` only supports NumPy backend')
+ def test__vq_invalid_type(self, xp):
+ a = xp.asarray([1, 2], dtype=int)
+ assert_raises(TypeError, _vq.vq, a, a)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_vq_large_nfeat(self, xp):
+ X = np.random.rand(20, 20)
+ code_book = np.random.rand(3, 20)
+
+ codes0, dis0 = _vq.vq(X, code_book)
+ codes1, dis1 = py_vq(
+ xp.asarray(X), xp.asarray(code_book)
+ )
+ xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+ # codes1.dtype varies between int32 and int64 over platforms
+ xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+ X = X.astype(np.float32)
+ code_book = code_book.astype(np.float32)
+
+ codes0, dis0 = _vq.vq(X, code_book)
+ codes1, dis1 = py_vq(
+ xp.asarray(X), xp.asarray(code_book)
+ )
+ xp_assert_close(dis1, xp.asarray(dis0, dtype=xp.float64), rtol=1e-5)
+ # codes1.dtype varies between int32 and int64 over platforms
+ xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+ @skip_xp_backends(cpu_only=True)
+ def test_vq_large_features(self, xp):
+ X = np.random.rand(10, 5) * 1000000
+ code_book = np.random.rand(2, 5) * 1000000
+
+ codes0, dis0 = _vq.vq(X, code_book)
+ codes1, dis1 = py_vq(
+ xp.asarray(X), xp.asarray(code_book)
+ )
+ xp_assert_close(dis1, xp.asarray(dis0), rtol=1e-5)
+ # codes1.dtype varies between int32 and int64 over platforms
+ xp_assert_equal(codes1, xp.asarray(codes0, dtype=xp.int64), check_dtype=False)
+
+
+# Whole class skipped on GPU for now;
+# once pdist/cdist are hooked up for CuPy, more tests will work
+@skip_xp_backends(cpu_only=True)
+class TestKMean:
+
+ def test_large_features(self, xp):
+ # Generate a data set with large values, and run kmeans on it to
+ # (regression for 1077).
+ d = 300
+ n = 100
+
+ m1 = np.random.randn(d)
+ m2 = np.random.randn(d)
+ x = 10000 * np.random.randn(n, d) - 20000 * m1
+ y = 10000 * np.random.randn(n, d) + 20000 * m2
+
+ data = np.empty((x.shape[0] + y.shape[0], d), np.float64)
+ data[:x.shape[0]] = x
+ data[x.shape[0]:] = y
+
+ # use `seed` to ensure backwards compatibility after SPEC7
+ kmeans(xp.asarray(data), 2, seed=1)
+
+ def test_kmeans_simple(self, xp):
+ rng = np.random.default_rng(54321)
+ initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+ code1 = kmeans(xp.asarray(X), xp.asarray(initc), iter=1, rng=rng)[0]
+ xp_assert_close(code1, xp.asarray(CODET2))
+
+ @pytest.mark.skipif(SCIPY_ARRAY_API,
+ reason='`np.matrix` unsupported in array API mode')
+ def test_kmeans_simple_matrix(self, xp):
+ rng = np.random.default_rng(54321)
+ initc = np.concatenate([[X[0]], [X[1]], [X[2]]])
+ code1 = kmeans(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+ xp_assert_close(code1, CODET2)
+
+ def test_kmeans_lost_cluster(self, xp):
+ # This will cause kmeans to have a cluster with no points.
+ data = xp.asarray(TESTDATA_2D)
+ initk = xp.asarray([[-1.8127404, -0.67128041],
+ [2.04621601, 0.07401111],
+ [-2.31149087, -0.05160469]])
+
+ kmeans(data, initk)
+ with suppress_warnings() as sup:
+ sup.filter(UserWarning,
+ "One of the clusters is empty. Re-run kmeans with a "
+ "different initialization")
+ kmeans2(data, initk, missing='warn')
+
+ assert_raises(ClusterError, kmeans2, data, initk, missing='raise')
+
+ def test_kmeans2_simple(self, xp):
+ rng = np.random.default_rng(12345678)
+ initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]]))
+ arrays = [xp.asarray] if SCIPY_ARRAY_API else [np.asarray, matrix]
+ for tp in arrays:
+ code1 = kmeans2(tp(X), tp(initc), iter=1, rng=rng)[0]
+ code2 = kmeans2(tp(X), tp(initc), iter=2, rng=rng)[0]
+
+ xp_assert_close(code1, xp.asarray(CODET1))
+ xp_assert_close(code2, xp.asarray(CODET2))
+
+ @pytest.mark.skipif(SCIPY_ARRAY_API,
+ reason='`np.matrix` unsupported in array API mode')
+ def test_kmeans2_simple_matrix(self, xp):
+ rng = np.random.default_rng(12345678)
+ initc = xp.asarray(np.concatenate([[X[0]], [X[1]], [X[2]]]))
+ code1 = kmeans2(matrix(X), matrix(initc), iter=1, rng=rng)[0]
+ code2 = kmeans2(matrix(X), matrix(initc), iter=2, rng=rng)[0]
+
+ xp_assert_close(code1, CODET1)
+ xp_assert_close(code2, CODET2)
+
+ def test_kmeans2_rank1(self, xp):
+ data = xp.asarray(TESTDATA_2D)
+ data1 = data[:, 0]
+
+ initc = data1[:3]
+ code = xp_copy(initc, xp=xp)
+
+ # use `seed` to ensure backwards compatibility after SPEC7
+ kmeans2(data1, code, iter=1, seed=1)[0]
+ kmeans2(data1, code, iter=2)[0]
+
+ def test_kmeans2_rank1_2(self, xp):
+ data = xp.asarray(TESTDATA_2D)
+ data1 = data[:, 0]
+ kmeans2(data1, 2, iter=1)
+
+ def test_kmeans2_high_dim(self, xp):
+ # test kmeans2 when the number of dimensions exceeds the number
+ # of input points
+ data = xp.asarray(TESTDATA_2D)
+ data = xp.reshape(data, (20, 20))[:10, :]
+ kmeans2(data, 2)
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_kmeans2_init(self, xp):
+ rng = np.random.default_rng(12345678)
+ data = xp.asarray(TESTDATA_2D)
+ k = 3
+
+ kmeans2(data, k, minit='points', rng=rng)
+ kmeans2(data[:, 1], k, minit='points', rng=rng) # special case (1-D)
+
+ kmeans2(data, k, minit='++', rng=rng)
+ kmeans2(data[:, 1], k, minit='++', rng=rng) # special case (1-D)
+
+ # minit='random' can give warnings, filter those
+ with suppress_warnings() as sup:
+ sup.filter(message="One of the clusters is empty. Re-run.")
+ kmeans2(data, k, minit='random', rng=rng)
+ kmeans2(data[:, 1], k, minit='random', rng=rng) # special case (1-D)
+
+ @pytest.fixture
+ def krand_lock(self):
+ return Lock()
+
+ @pytest.mark.skipif(sys.platform == 'win32',
+ reason='Fails with MemoryError in Wine.')
+ def test_krandinit(self, xp, krand_lock):
+ data = xp.asarray(TESTDATA_2D)
+ datas = [xp.reshape(data, (200, 2)),
+ xp.reshape(data, (20, 20))[:10, :]]
+ k = int(1e6)
+ xp_test = array_namespace(data)
+ with krand_lock:
+ for data in datas:
+ rng = np.random.default_rng(1234)
+ init = _krandinit(data, k, rng, xp_test)
+ orig_cov = xpx.cov(data.T, xp=xp_test)
+ init_cov = xpx.cov(init.T, xp=xp_test)
+ xp_assert_close(orig_cov, init_cov, atol=1.1e-2)
+
+ def test_kmeans2_empty(self, xp):
+ # Regression test for gh-1032.
+ assert_raises(ValueError, kmeans2, xp.asarray([]), 2)
+
+ def test_kmeans_0k(self, xp):
+ # Regression test for gh-1073: fail when k arg is 0.
+ assert_raises(ValueError, kmeans, xp.asarray(X), 0)
+ assert_raises(ValueError, kmeans2, xp.asarray(X), 0)
+ assert_raises(ValueError, kmeans2, xp.asarray(X), xp.asarray([]))
+
+ def test_kmeans_large_thres(self, xp):
+ # Regression test for gh-1774
+ x = xp.asarray([1, 2, 3, 4, 10], dtype=xp.float64)
+ res = kmeans(x, 1, thresh=1e16)
+ xp_assert_close(res[0], xp.asarray([4.], dtype=xp.float64))
+ xp_assert_close(res[1], xp.asarray(2.3999999999999999, dtype=xp.float64)[()])
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_kmeans2_kpp_low_dim(self, xp):
+ # Regression test for gh-11462
+ rng = np.random.default_rng(2358792345678234568)
+ prev_res = xp.asarray([[-1.95266667, 0.898],
+ [-3.153375, 3.3945]], dtype=xp.float64)
+ res, _ = kmeans2(xp.asarray(TESTDATA_2D), 2, minit='++', rng=rng)
+ xp_assert_close(res, prev_res)
+
+ @pytest.mark.thread_unsafe
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_kmeans2_kpp_high_dim(self, xp):
+ # Regression test for gh-11462
+ rng = np.random.default_rng(23587923456834568)
+ n_dim = 100
+ size = 10
+ centers = np.vstack([5 * np.ones(n_dim),
+ -5 * np.ones(n_dim)])
+
+ data = np.vstack([
+ rng.multivariate_normal(centers[0], np.eye(n_dim), size=size),
+ rng.multivariate_normal(centers[1], np.eye(n_dim), size=size)
+ ])
+
+ data = xp.asarray(data)
+ res, _ = kmeans2(data, 2, minit='++', rng=rng)
+ xp_assert_equal(xp.sign(res), xp.sign(xp.asarray(centers)))
+
+ def test_kmeans_diff_convergence(self, xp):
+ # Regression test for gh-8727
+ obs = xp.asarray([-3, -1, 0, 1, 1, 8], dtype=xp.float64)
+ res = kmeans(obs, xp.asarray([-3., 0.99]))
+ xp_assert_close(res[0], xp.asarray([-0.4, 8.], dtype=xp.float64))
+ xp_assert_close(res[1], xp.asarray(1.0666666666666667, dtype=xp.float64)[()])
+
+ @skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment')
+ def test_kmeans_and_kmeans2_random_seed(self, xp):
+
+ seed_list = [
+ 1234, np.random.RandomState(1234), np.random.default_rng(1234)
+ ]
+
+ for seed in seed_list:
+ seed1 = deepcopy(seed)
+ seed2 = deepcopy(seed)
+ data = xp.asarray(TESTDATA_2D)
+ # test for kmeans
+ res1, _ = kmeans(data, 2, seed=seed1)
+ res2, _ = kmeans(data, 2, seed=seed2)
+ xp_assert_close(res1, res2) # should be same results
+ # test for kmeans2
+ for minit in ["random", "points", "++"]:
+ res1, _ = kmeans2(data, 2, minit=minit, seed=seed1)
+ res2, _ = kmeans2(data, 2, minit=minit, seed=seed2)
+ xp_assert_close(res1, res2) # should be same results
diff --git a/python_embeded/Lib/site-packages/scipy/constants/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/constants/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/constants/tests/test_codata.py b/python_embeded/Lib/site-packages/scipy/constants/tests/test_codata.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5a203762274e66f48bea265680471ceec607de4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/constants/tests/test_codata.py
@@ -0,0 +1,78 @@
+from scipy.constants import find, value, c, speed_of_light, precision
+from numpy.testing import assert_equal, assert_, assert_almost_equal
+import scipy.constants._codata as _cd
+from scipy import constants
+
+
+def test_find():
+ keys = find('weak mixing', disp=False)
+ assert_equal(keys, ['weak mixing angle'])
+
+ keys = find('qwertyuiop', disp=False)
+ assert_equal(keys, [])
+
+ keys = find('natural unit', disp=False)
+ assert_equal(keys, sorted(['natural unit of velocity',
+ 'natural unit of action',
+ 'natural unit of action in eV s',
+ 'natural unit of mass',
+ 'natural unit of energy',
+ 'natural unit of energy in MeV',
+ 'natural unit of momentum',
+ 'natural unit of momentum in MeV/c',
+ 'natural unit of length',
+ 'natural unit of time']))
+
+
+def test_basic_table_parse():
+ c_s = 'speed of light in vacuum'
+ assert_equal(value(c_s), c)
+ assert_equal(value(c_s), speed_of_light)
+
+
+def test_basic_lookup():
+ assert_equal('%d %s' % (_cd.value('speed of light in vacuum'),
+ _cd.unit('speed of light in vacuum')),
+ '299792458 m s^-1')
+
+
+def test_find_all():
+ assert_(len(find(disp=False)) > 300)
+
+
+def test_find_single():
+ assert_equal(find('Wien freq', disp=False)[0],
+ 'Wien frequency displacement law constant')
+
+
+def test_2002_vs_2006():
+ assert_almost_equal(value('magn. flux quantum'),
+ value('mag. flux quantum'))
+
+
+def test_exact_values():
+ # Check that updating stored values with exact ones worked.
+ exact = dict((k, v[0]) for k, v in _cd._physical_constants_2018.items())
+ replace = _cd.exact2018(exact)
+ for key, val in replace.items():
+ assert_equal(val, value(key))
+ assert precision(key) == 0
+
+
+def test_gh11341():
+ # gh-11341 noted that these three constants should exist (for backward
+ # compatibility) and should always have the same value:
+ a = constants.epsilon_0
+ b = constants.physical_constants['electric constant'][0]
+ c = constants.physical_constants['vacuum electric permittivity'][0]
+ assert a == b == c
+
+
+def test_gh14467():
+ # gh-14467 noted that some physical constants in CODATA are rounded
+ # to only ten significant figures even though they are supposed to be
+ # exact. Check that (at least) the case mentioned in the issue is resolved.
+ res = constants.physical_constants['Boltzmann constant in eV/K'][0]
+ ref = (constants.physical_constants['Boltzmann constant'][0]
+ / constants.physical_constants['elementary charge'][0])
+ assert res == ref
diff --git a/python_embeded/Lib/site-packages/scipy/constants/tests/test_constants.py b/python_embeded/Lib/site-packages/scipy/constants/tests/test_constants.py
new file mode 100644
index 0000000000000000000000000000000000000000..757f6413c6039c6eb2f01a0e9237b702ed2b222b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/constants/tests/test_constants.py
@@ -0,0 +1,90 @@
+import pytest
+
+import scipy.constants as sc
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api_no_0d import xp_assert_equal, xp_assert_close
+from numpy.testing import assert_allclose
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestConvertTemperature:
+ def test_convert_temperature(self, xp):
+ xp_assert_equal(sc.convert_temperature(xp.asarray(32.), 'f', 'Celsius'),
+ xp.asarray(0.0))
+ xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]),
+ 'celsius', 'Kelvin'),
+ xp.asarray([273.15, 273.15]))
+ xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'kelvin', 'c'),
+ xp.asarray([-273.15, -273.15]))
+ xp_assert_equal(sc.convert_temperature(xp.asarray([32., 32.]), 'f', 'k'),
+ xp.asarray([273.15, 273.15]))
+ xp_assert_equal(sc.convert_temperature(xp.asarray([273.15, 273.15]),
+ 'kelvin', 'F'),
+ xp.asarray([32., 32.]))
+ xp_assert_equal(sc.convert_temperature(xp.asarray([0., 0.]), 'C', 'fahrenheit'),
+ xp.asarray([32., 32.]))
+ xp_assert_close(sc.convert_temperature(xp.asarray([0., 0.], dtype=xp.float64),
+ 'c', 'r'),
+ xp.asarray([491.67, 491.67], dtype=xp.float64),
+ rtol=0., atol=1e-13)
+ xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+ dtype=xp.float64),
+ 'Rankine', 'C'),
+ xp.asarray([0., 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+ xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 491.67],
+ dtype=xp.float64),
+ 'r', 'F'),
+ xp.asarray([32., 32.], dtype=xp.float64), rtol=0., atol=1e-13)
+ xp_assert_close(sc.convert_temperature(xp.asarray([32., 32.], dtype=xp.float64),
+ 'fahrenheit', 'R'),
+ xp.asarray([491.67, 491.67], dtype=xp.float64),
+ rtol=0., atol=1e-13)
+ xp_assert_close(sc.convert_temperature(xp.asarray([273.15, 273.15],
+ dtype=xp.float64),
+ 'K', 'R'),
+ xp.asarray([491.67, 491.67], dtype=xp.float64),
+ rtol=0., atol=1e-13)
+ xp_assert_close(sc.convert_temperature(xp.asarray([491.67, 0.],
+ dtype=xp.float64),
+ 'rankine', 'kelvin'),
+ xp.asarray([273.15, 0.], dtype=xp.float64), rtol=0., atol=1e-13)
+
+ @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+ def test_convert_temperature_array_like(self):
+ assert_allclose(sc.convert_temperature([491.67, 0.], 'rankine', 'kelvin'),
+ [273.15, 0.], rtol=0., atol=1e-13)
+
+
+ @skip_xp_backends(np_only=True, reason='Python int input uses NumPy backend')
+ def test_convert_temperature_errors(self, xp):
+ with pytest.raises(NotImplementedError, match="old_scale="):
+ sc.convert_temperature(1, old_scale="cheddar", new_scale="kelvin")
+ with pytest.raises(NotImplementedError, match="new_scale="):
+ sc.convert_temperature(1, old_scale="kelvin", new_scale="brie")
+
+
+class TestLambdaToNu:
+ def test_lambda_to_nu(self, xp):
+ xp_assert_equal(sc.lambda2nu(xp.asarray([sc.speed_of_light, 1])),
+ xp.asarray([1, sc.speed_of_light]))
+
+
+ @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+ def test_lambda_to_nu_array_like(self, xp):
+ assert_allclose(sc.lambda2nu([sc.speed_of_light, 1]),
+ [1, sc.speed_of_light])
+
+
+class TestNuToLambda:
+ def test_nu_to_lambda(self, xp):
+ xp_assert_equal(sc.nu2lambda(xp.asarray([sc.speed_of_light, 1])),
+ xp.asarray([1, sc.speed_of_light]))
+
+ @skip_xp_backends(np_only=True, reason='Python list input uses NumPy backend')
+ def test_nu_to_lambda_array_like(self, xp):
+ assert_allclose(sc.nu2lambda([sc.speed_of_light, 1]),
+ [1, sc.speed_of_light])
+
diff --git a/python_embeded/Lib/site-packages/scipy/datasets/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/datasets/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/datasets/tests/test_data.py b/python_embeded/Lib/site-packages/scipy/datasets/tests/test_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ebc27bdae480ef00346f3b9808884fbc48738512
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/datasets/tests/test_data.py
@@ -0,0 +1,128 @@
+from scipy.datasets._registry import registry
+from scipy.datasets._fetchers import data_fetcher
+from scipy.datasets._utils import _clear_cache
+from scipy.datasets import ascent, face, electrocardiogram, download_all
+from numpy.testing import assert_equal, assert_almost_equal
+import os
+from threading import get_ident
+import pytest
+
+try:
+ import pooch
+except ImportError:
+ raise ImportError("Missing optional dependency 'pooch' required "
+ "for scipy.datasets module. Please use pip or "
+ "conda to install 'pooch'.")
+
+
+data_dir = data_fetcher.path # type: ignore
+
+
+def _has_hash(path, expected_hash):
+ """Check if the provided path has the expected hash."""
+ if not os.path.exists(path):
+ return False
+ return pooch.file_hash(path) == expected_hash
+
+
+class TestDatasets:
+
+ @pytest.fixture(scope='module', autouse=True)
+ def test_download_all(self):
+ # This fixture requires INTERNET CONNECTION
+
+ # test_setup phase
+ download_all()
+
+ yield
+
+ @pytest.mark.fail_slow(10)
+ def test_existence_all(self):
+ assert len(os.listdir(data_dir)) >= len(registry)
+
+ def test_ascent(self):
+ assert_equal(ascent().shape, (512, 512))
+
+ # hash check
+ assert _has_hash(os.path.join(data_dir, "ascent.dat"),
+ registry["ascent.dat"])
+
+ def test_face(self):
+ assert_equal(face().shape, (768, 1024, 3))
+
+ # hash check
+ assert _has_hash(os.path.join(data_dir, "face.dat"),
+ registry["face.dat"])
+
+ def test_electrocardiogram(self):
+ # Test shape, dtype and stats of signal
+ ecg = electrocardiogram()
+ assert_equal(ecg.dtype, float)
+ assert_equal(ecg.shape, (108000,))
+ assert_almost_equal(ecg.mean(), -0.16510875)
+ assert_almost_equal(ecg.std(), 0.5992473991177294)
+
+ # hash check
+ assert _has_hash(os.path.join(data_dir, "ecg.dat"),
+ registry["ecg.dat"])
+
+
+def test_clear_cache(tmp_path):
+ # Note: `tmp_path` is a pytest fixture, it handles cleanup
+ thread_basepath = tmp_path / str(get_ident())
+ thread_basepath.mkdir()
+
+ dummy_basepath = thread_basepath / "dummy_cache_dir"
+ dummy_basepath.mkdir()
+
+ # Create three dummy dataset files for dummy dataset methods
+ dummy_method_map = {}
+ for i in range(4):
+ dummy_method_map[f"data{i}"] = [f"data{i}.dat"]
+ data_filepath = dummy_basepath / f"data{i}.dat"
+ data_filepath.write_text("")
+
+ # clear files associated to single dataset method data0
+ # also test callable argument instead of list of callables
+ def data0():
+ pass
+ _clear_cache(datasets=data0, cache_dir=dummy_basepath,
+ method_map=dummy_method_map)
+ assert not os.path.exists(dummy_basepath/"data0.dat")
+
+ # clear files associated to multiple dataset methods "data3" and "data4"
+ def data1():
+ pass
+
+ def data2():
+ pass
+ _clear_cache(datasets=[data1, data2], cache_dir=dummy_basepath,
+ method_map=dummy_method_map)
+ assert not os.path.exists(dummy_basepath/"data1.dat")
+ assert not os.path.exists(dummy_basepath/"data2.dat")
+
+ # clear multiple dataset files "data3_0.dat" and "data3_1.dat"
+ # associated with dataset method "data3"
+ def data4():
+ pass
+ # create files
+ (dummy_basepath / "data4_0.dat").write_text("")
+ (dummy_basepath / "data4_1.dat").write_text("")
+
+ dummy_method_map["data4"] = ["data4_0.dat", "data4_1.dat"]
+ _clear_cache(datasets=[data4], cache_dir=dummy_basepath,
+ method_map=dummy_method_map)
+ assert not os.path.exists(dummy_basepath/"data4_0.dat")
+ assert not os.path.exists(dummy_basepath/"data4_1.dat")
+
+ # wrong dataset method should raise ValueError since it
+ # doesn't exist in the dummy_method_map
+ def data5():
+ pass
+ with pytest.raises(ValueError):
+ _clear_cache(datasets=[data5], cache_dir=dummy_basepath,
+ method_map=dummy_method_map)
+
+ # remove all dataset cache
+ _clear_cache(datasets=None, cache_dir=dummy_basepath)
+ assert not os.path.exists(dummy_basepath)
diff --git a/python_embeded/Lib/site-packages/scipy/differentiate/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/differentiate/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py b/python_embeded/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e6309d764bb837094f60156955160f599b36284
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/differentiate/tests/test_differentiate.py
@@ -0,0 +1,695 @@
+import math
+import pytest
+
+import numpy as np
+
+from scipy.conftest import array_api_compatible
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._array_api_no_0d import xp_assert_close, xp_assert_equal, xp_assert_less
+from scipy._lib._array_api import is_numpy, is_torch, array_namespace
+
+from scipy import stats, optimize, special
+from scipy.differentiate import derivative, jacobian, hessian
+from scipy.differentiate._differentiate import _EERRORINCREASE
+
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+
+array_api_strict_skip_reason = 'Array API does not support fancy indexing assignment.'
+jax_skip_reason = 'JAX arrays do not support item assignment.'
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestDerivative:
+
+ def f(self, x):
+ return special.ndtr(x)
+
+ @pytest.mark.parametrize('x', [0.6, np.linspace(-0.05, 1.05, 10)])
+ def test_basic(self, x, xp):
+ # Invert distribution CDF and compare against distribution `ppf`
+ default_dtype = xp.asarray(1.).dtype
+ res = derivative(self.f, xp.asarray(x, dtype=default_dtype))
+ ref = xp.asarray(stats.norm().pdf(x), dtype=default_dtype)
+ xp_assert_close(res.df, ref)
+ # This would be nice, but doesn't always work out. `error` is an
+ # estimate, not a bound.
+ if not is_torch(xp):
+ xp_assert_less(xp.abs(res.df - ref), res.error)
+
+ @pytest.mark.skip_xp_backends(np_only=True)
+ @pytest.mark.parametrize('case', stats._distr_params.distcont)
+ def test_accuracy(self, case):
+ distname, params = case
+ dist = getattr(stats, distname)(*params)
+ x = dist.median() + 0.1
+ res = derivative(dist.cdf, x)
+ ref = dist.pdf(x)
+ xp_assert_close(res.df, ref, atol=1e-10)
+
+ @pytest.mark.parametrize('order', [1, 6])
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, order, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ x = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+ n = np.size(x)
+ state = {}
+
+ @np.vectorize
+ def _derivative_single(x):
+ return derivative(self.f, x, order=order)
+
+ def f(x, *args, **kwargs):
+ state['nit'] += 1
+ state['feval'] += 1 if (x.size == n or x.ndim <=1) else x.shape[-1]
+ return self.f(x, *args, **kwargs)
+
+ state['nit'] = -1
+ state['feval'] = 0
+
+ res = derivative(f, xp.asarray(x, dtype=xp.float64), order=order)
+ refs = _derivative_single(x).ravel()
+
+ ref_x = [ref.x for ref in refs]
+ xp_assert_close(xp.reshape(res.x, (-1,)), xp.asarray(ref_x))
+
+ ref_df = [ref.df for ref in refs]
+ xp_assert_close(xp.reshape(res.df, (-1,)), xp.asarray(ref_df))
+
+ ref_error = [ref.error for ref in refs]
+ xp_assert_close(xp.reshape(res.error, (-1,)), xp.asarray(ref_error),
+ atol=1e-12)
+
+ ref_success = [bool(ref.success) for ref in refs]
+ xp_assert_equal(xp.reshape(res.success, (-1,)), xp.asarray(ref_success))
+
+ ref_flag = [np.int32(ref.status) for ref in refs]
+ xp_assert_equal(xp.reshape(res.status, (-1,)), xp.asarray(ref_flag))
+
+ ref_nfev = [np.int32(ref.nfev) for ref in refs]
+ xp_assert_equal(xp.reshape(res.nfev, (-1,)), xp.asarray(ref_nfev))
+ if is_numpy(xp): # can't expect other backends to be exactly the same
+ assert xp.max(res.nfev) == state['feval']
+
+ ref_nit = [np.int32(ref.nit) for ref in refs]
+ xp_assert_equal(xp.reshape(res.nit, (-1,)), xp.asarray(ref_nit))
+ if is_numpy(xp): # can't expect other backends to be exactly the same
+ assert xp.max(res.nit) == state['nit']
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ rng = np.random.default_rng(5651219684984213)
+ def f(xs, js):
+ f.nit += 1
+ funcs = [lambda x: x - 2.5, # converges
+ lambda x: xp.exp(x)*rng.random(), # error increases
+ lambda x: xp.exp(x), # reaches maxiter due to order=2
+ lambda x: xp.full_like(x, xp.nan)] # stops due to NaN
+ res = [funcs[int(j)](x) for x, j in zip(xs, xp.reshape(js, (-1,)))]
+ return xp.stack(res)
+ f.nit = 0
+
+ args = (xp.arange(4, dtype=xp.int64),)
+ res = derivative(f, xp.ones(4, dtype=xp.float64),
+ tolerances=dict(rtol=1e-14),
+ order=2, args=args)
+
+ ref_flags = xp.asarray([eim._ECONVERGED,
+ _EERRORINCREASE,
+ eim._ECONVERR,
+ eim._EVALUEERR], dtype=xp.int32)
+ xp_assert_equal(res.status, ref_flags)
+
+ def test_flags_preserve_shape(self, xp):
+ # Same test as above but using `preserve_shape` option to simplify.
+ rng = np.random.default_rng(5651219684984213)
+ def f(x):
+ out = [x - 2.5, # converges
+ xp.exp(x)*rng.random(), # error increases
+ xp.exp(x), # reaches maxiter due to order=2
+ xp.full_like(x, xp.nan)] # stops due to NaN
+ return xp.stack(out)
+
+ res = derivative(f, xp.asarray(1, dtype=xp.float64),
+ tolerances=dict(rtol=1e-14),
+ order=2, preserve_shape=True)
+
+ ref_flags = xp.asarray([eim._ECONVERGED,
+ _EERRORINCREASE,
+ eim._ECONVERR,
+ eim._EVALUEERR], dtype=xp.int32)
+ xp_assert_equal(res.status, ref_flags)
+
+ def test_preserve_shape(self, xp):
+ # Test `preserve_shape` option
+ def f(x):
+ out = [x, xp.sin(3*x), x+xp.sin(10*x), xp.sin(20*x)*(x-1)**2]
+ return xp.stack(out)
+
+ x = xp.asarray(0.)
+ ref = xp.asarray([xp.asarray(1), 3*xp.cos(3*x), 1+10*xp.cos(10*x),
+ 20*xp.cos(20*x)*(x-1)**2 + 2*xp.sin(20*x)*(x-1)])
+ res = derivative(f, x, preserve_shape=True)
+ xp_assert_close(res.df, ref)
+
+ def test_convergence(self, xp):
+ # Test that the convergence tolerances behave as expected
+ x = xp.asarray(1., dtype=xp.float64)
+ f = special.ndtr
+ ref = float(stats.norm.pdf(1.))
+ tolerances0 = dict(atol=0, rtol=0)
+
+ tolerances = tolerances0.copy()
+ tolerances['atol'] = 1e-3
+ res1 = derivative(f, x, tolerances=tolerances, order=4)
+ assert abs(res1.df - ref) < 1e-3
+ tolerances['atol'] = 1e-6
+ res2 = derivative(f, x, tolerances=tolerances, order=4)
+ assert abs(res2.df - ref) < 1e-6
+ assert abs(res2.df - ref) < abs(res1.df - ref)
+
+ tolerances = tolerances0.copy()
+ tolerances['rtol'] = 1e-3
+ res1 = derivative(f, x, tolerances=tolerances, order=4)
+ assert abs(res1.df - ref) < 1e-3 * ref
+ tolerances['rtol'] = 1e-6
+ res2 = derivative(f, x, tolerances=tolerances, order=4)
+ assert abs(res2.df - ref) < 1e-6 * ref
+ assert abs(res2.df - ref) < abs(res1.df - ref)
+
+ def test_step_parameters(self, xp):
+ # Test that step factors have the expected effect on accuracy
+ x = xp.asarray(1., dtype=xp.float64)
+ f = special.ndtr
+ ref = float(stats.norm.pdf(1.))
+
+ res1 = derivative(f, x, initial_step=0.5, maxiter=1)
+ res2 = derivative(f, x, initial_step=0.05, maxiter=1)
+ assert abs(res2.df - ref) < abs(res1.df - ref)
+
+ res1 = derivative(f, x, step_factor=2, maxiter=1)
+ res2 = derivative(f, x, step_factor=20, maxiter=1)
+ assert abs(res2.df - ref) < abs(res1.df - ref)
+
+ # `step_factor` can be less than 1: `initial_step` is the minimum step
+ kwargs = dict(order=4, maxiter=1, step_direction=0)
+ res = derivative(f, x, initial_step=0.5, step_factor=0.5, **kwargs)
+ ref = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+ xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+ # This is a similar test for one-sided difference
+ kwargs = dict(order=2, maxiter=1, step_direction=1)
+ res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+ ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+ xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+ kwargs['step_direction'] = -1
+ res = derivative(f, x, initial_step=1, step_factor=2, **kwargs)
+ ref = derivative(f, x, initial_step=1/np.sqrt(2), step_factor=0.5, **kwargs)
+ xp_assert_close(res.df, ref.df, rtol=5e-15)
+
+ def test_step_direction(self, xp):
+ # test that `step_direction` works as expected
+ def f(x):
+ y = xp.exp(x)
+ y[(x < 0) + (x > 2)] = xp.nan
+ return y
+
+ x = xp.linspace(0, 2, 10)
+ step_direction = xp.zeros_like(x)
+ step_direction[x < 0.6], step_direction[x > 1.4] = 1, -1
+ res = derivative(f, x, step_direction=step_direction)
+ xp_assert_close(res.df, xp.exp(x))
+ assert xp.all(res.success)
+
+ def test_vectorized_step_direction_args(self, xp):
+ # test that `step_direction` and `args` are vectorized properly
+ def f(x, p):
+ return x ** p
+
+ def df(x, p):
+ return p * x ** (p - 1)
+
+ x = xp.reshape(xp.asarray([1, 2, 3, 4]), (-1, 1, 1))
+ hdir = xp.reshape(xp.asarray([-1, 0, 1]), (1, -1, 1))
+ p = xp.reshape(xp.asarray([2, 3]), (1, 1, -1))
+ res = derivative(f, x, step_direction=hdir, args=(p,))
+ ref = xp.broadcast_to(df(x, p), res.df.shape)
+ ref = xp.asarray(ref, dtype=xp.asarray(1.).dtype)
+ xp_assert_close(res.df, ref)
+
+ def test_initial_step(self, xp):
+ # Test that `initial_step` works as expected and is vectorized
+ def f(x):
+ return xp.exp(x)
+
+ x = xp.asarray(0., dtype=xp.float64)
+ step_direction = xp.asarray([-1, 0, 1])
+ h0 = xp.reshape(xp.logspace(-3, 0, 10), (-1, 1))
+ res = derivative(f, x, initial_step=h0, order=2, maxiter=1,
+ step_direction=step_direction)
+ err = xp.abs(res.df - f(x))
+
+ # error should be smaller for smaller step sizes
+ assert xp.all(err[:-1, ...] < err[1:, ...])
+
+ # results of vectorized call should match results with
+ # initial_step taken one at a time
+ for i in range(h0.shape[0]):
+ ref = derivative(f, x, initial_step=h0[i, 0], order=2, maxiter=1,
+ step_direction=step_direction)
+ xp_assert_close(res.df[i, :], ref.df, rtol=1e-14)
+
+ def test_maxiter_callback(self, xp):
+ # Test behavior of `maxiter` parameter and `callback` interface
+ x = xp.asarray(0.612814, dtype=xp.float64)
+ maxiter = 3
+
+ def f(x):
+ res = special.ndtr(x)
+ return res
+
+ default_order = 8
+ res = derivative(f, x, maxiter=maxiter, tolerances=dict(rtol=1e-15))
+ assert not xp.any(res.success)
+ assert xp.all(res.nfev == default_order + 1 + (maxiter - 1)*2)
+ assert xp.all(res.nit == maxiter)
+
+ def callback(res):
+ callback.iter += 1
+ callback.res = res
+ assert hasattr(res, 'x')
+ assert float(res.df) not in callback.dfs
+ callback.dfs.add(float(res.df))
+ assert res.status == eim._EINPROGRESS
+ if callback.iter == maxiter:
+ raise StopIteration
+ callback.iter = -1 # callback called once before first iteration
+ callback.res = None
+ callback.dfs = set()
+
+ res2 = derivative(f, x, callback=callback, tolerances=dict(rtol=1e-15))
+ # terminating with callback is identical to terminating due to maxiter
+ # (except for `status`)
+ for key in res.keys():
+ if key == 'status':
+ assert res[key] == eim._ECONVERR
+ assert res2[key] == eim._ECALLBACK
+ else:
+ assert res2[key] == callback.res[key] == res[key]
+
+ @pytest.mark.parametrize("hdir", (-1, 0, 1))
+ @pytest.mark.parametrize("x", (0.65, [0.65, 0.7]))
+ @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+ def test_dtype(self, hdir, x, dtype, xp):
+ if dtype == 'float16' and not is_numpy(xp):
+ pytest.skip('float16 not tested for alternative backends')
+
+ # Test that dtypes are preserved
+ dtype = getattr(xp, dtype)
+ x = xp.asarray(x, dtype=dtype)
+
+ def f(x):
+ assert x.dtype == dtype
+ return xp.exp(x)
+
+ def callback(res):
+ assert res.x.dtype == dtype
+ assert res.df.dtype == dtype
+ assert res.error.dtype == dtype
+
+ res = derivative(f, x, order=4, step_direction=hdir, callback=callback)
+ assert res.x.dtype == dtype
+ assert res.df.dtype == dtype
+ assert res.error.dtype == dtype
+ eps = xp.finfo(dtype).eps
+ # not sure why torch is less accurate here; might be worth investigating
+ rtol = eps**0.5 * 50 if is_torch(xp) else eps**0.5
+ xp_assert_close(res.df, xp.exp(res.x), rtol=rtol)
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+ one = xp.asarray(1)
+
+ message = '`f` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ derivative(None, one)
+
+ message = 'Abscissae and function output must be real numbers.'
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, xp.asarray(-4+1j))
+
+ message = "When `preserve_shape=False`, the shape of the array..."
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: [1, 2, 3], xp.asarray([-2, -3]))
+
+ message = 'Tolerances and step parameters must be non-negative...'
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, tolerances=dict(atol=-1))
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, tolerances=dict(rtol='ekki'))
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, step_factor=object())
+
+ message = '`maxiter` must be a positive integer.'
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, maxiter=0)
+
+ message = '`order` must be a positive integer'
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, order=1.5)
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, order=0)
+
+ message = '`preserve_shape` must be True or False.'
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, preserve_shape='herring')
+
+ message = '`callback` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ derivative(lambda x: x, one, callback='shrubbery')
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ xp_test = array_namespace(x) # needs `isdtype`
+ assert xp_test.isdtype(x.dtype, 'real floating')
+ return x ** 99 - 1
+
+ if not is_torch(xp): # torch defaults to float32
+ res = derivative(f, xp.asarray(7), tolerances=dict(rtol=1e-10))
+ assert res.success
+ xp_assert_close(res.df, xp.asarray(99*7.**98))
+
+ # Test invalid step size and direction
+ res = derivative(xp.exp, xp.asarray(1), step_direction=xp.nan)
+ xp_assert_equal(res.df, xp.asarray(xp.nan))
+ xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+ res = derivative(xp.exp, xp.asarray(1), initial_step=0)
+ xp_assert_equal(res.df, xp.asarray(xp.nan))
+ xp_assert_equal(res.status, xp.asarray(-3, dtype=xp.int32))
+
+ # Test that if success is achieved in the correct number
+ # of iterations if function is a polynomial. Ideally, all polynomials
+ # of order 0-2 would get exact result with 0 refinement iterations,
+ # all polynomials of order 3-4 would be differentiated exactly after
+ # 1 iteration, etc. However, it seems that `derivative` needs an
+ # extra iteration to detect convergence based on the error estimate.
+
+ for n in range(6):
+ x = xp.asarray(1.5, dtype=xp.float64)
+ def f(x):
+ return 2*x**n
+
+ ref = 2*n*x**(n-1)
+
+ res = derivative(f, x, maxiter=1, order=max(1, n))
+ xp_assert_close(res.df, ref, rtol=1e-15)
+ xp_assert_equal(res.error, xp.asarray(xp.nan, dtype=xp.float64))
+
+ res = derivative(f, x, order=max(1, n))
+ assert res.success
+ assert res.nit == 2
+ xp_assert_close(res.df, ref, rtol=1e-15)
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x - 1
+
+ res = derivative(f, xp.asarray(2), args=xp.asarray(3))
+ xp_assert_close(res.df, xp.asarray(3.))
+
+ # no need to run a test on multiple backends if it's xfailed
+ @pytest.mark.skip_xp_backends(np_only=True)
+ @pytest.mark.xfail
+ @pytest.mark.parametrize("case", ( # function, evaluation point
+ (lambda x: (x - 1) ** 3, 1),
+ (lambda x: np.where(x > 1, (x - 1) ** 5, (x - 1) ** 3), 1)
+ ))
+ def test_saddle_gh18811(self, case):
+ # With default settings, `derivative` will not always converge when
+ # the true derivative is exactly zero. This tests that specifying a
+ # (tight) `atol` alleviates the problem. See discussion in gh-18811.
+ atol = 1e-16
+ res = derivative(*case, step_direction=[-1, 0, 1], atol=atol)
+ assert np.all(res.success)
+ xp_assert_close(res.df, 0, atol=atol)
+
+
+class JacobianHessianTest:
+ def test_iv(self, xp):
+ jh_func = self.jh_func.__func__
+
+ # Test input validation
+ message = "Argument `x` must be at least 1-D."
+ with pytest.raises(ValueError, match=message):
+ jh_func(xp.sin, 1, tolerances=dict(atol=-1))
+
+ # Confirm that other parameters are being passed to `derivative`,
+ # which raises an appropriate error message.
+ x = xp.ones(3)
+ func = optimize.rosen
+ message = 'Tolerances and step parameters must be non-negative scalars.'
+ with pytest.raises(ValueError, match=message):
+ jh_func(func, x, tolerances=dict(atol=-1))
+ with pytest.raises(ValueError, match=message):
+ jh_func(func, x, tolerances=dict(rtol=-1))
+ with pytest.raises(ValueError, match=message):
+ jh_func(func, x, step_factor=-1)
+
+ message = '`order` must be a positive integer.'
+ with pytest.raises(ValueError, match=message):
+ jh_func(func, x, order=-1)
+
+ message = '`maxiter` must be a positive integer.'
+ with pytest.raises(ValueError, match=message):
+ jh_func(func, x, maxiter=-1)
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestJacobian(JacobianHessianTest):
+ jh_func = jacobian
+
+ # Example functions and Jacobians from Wikipedia:
+ # https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant#Examples
+
+ def f1(z, xp):
+ x, y = z
+ return xp.stack([x ** 2 * y, 5 * x + xp.sin(y)])
+
+ def df1(z):
+ x, y = z
+ return [[2 * x * y, x ** 2], [np.full_like(x, 5), np.cos(y)]]
+
+ f1.mn = 2, 2 # type: ignore[attr-defined]
+ f1.ref = df1 # type: ignore[attr-defined]
+
+ def f2(z, xp):
+ r, phi = z
+ return xp.stack([r * xp.cos(phi), r * xp.sin(phi)])
+
+ def df2(z):
+ r, phi = z
+ return [[np.cos(phi), -r * np.sin(phi)],
+ [np.sin(phi), r * np.cos(phi)]]
+
+ f2.mn = 2, 2 # type: ignore[attr-defined]
+ f2.ref = df2 # type: ignore[attr-defined]
+
+ def f3(z, xp):
+ r, phi, th = z
+ return xp.stack([r * xp.sin(phi) * xp.cos(th), r * xp.sin(phi) * xp.sin(th),
+ r * xp.cos(phi)])
+
+ def df3(z):
+ r, phi, th = z
+ return [[np.sin(phi) * np.cos(th), r * np.cos(phi) * np.cos(th),
+ -r * np.sin(phi) * np.sin(th)],
+ [np.sin(phi) * np.sin(th), r * np.cos(phi) * np.sin(th),
+ r * np.sin(phi) * np.cos(th)],
+ [np.cos(phi), -r * np.sin(phi), np.zeros_like(r)]]
+
+ f3.mn = 3, 3 # type: ignore[attr-defined]
+ f3.ref = df3 # type: ignore[attr-defined]
+
+ def f4(x, xp):
+ x1, x2, x3 = x
+ return xp.stack([x1, 5 * x3, 4 * x2 ** 2 - 2 * x3, x3 * xp.sin(x1)])
+
+ def df4(x):
+ x1, x2, x3 = x
+ one = np.ones_like(x1)
+ return [[one, 0 * one, 0 * one],
+ [0 * one, 0 * one, 5 * one],
+ [0 * one, 8 * x2, -2 * one],
+ [x3 * np.cos(x1), 0 * one, np.sin(x1)]]
+
+ f4.mn = 3, 4 # type: ignore[attr-defined]
+ f4.ref = df4 # type: ignore[attr-defined]
+
+ def f5(x, xp):
+ x1, x2, x3 = x
+ return xp.stack([5 * x2, 4 * x1 ** 2 - 2 * xp.sin(x2 * x3), x2 * x3])
+
+ def df5(x):
+ x1, x2, x3 = x
+ one = np.ones_like(x1)
+ return [[0 * one, 5 * one, 0 * one],
+ [8 * x1, -2 * x3 * np.cos(x2 * x3), -2 * x2 * np.cos(x2 * x3)],
+ [0 * one, x3, x2]]
+
+ f5.mn = 3, 3 # type: ignore[attr-defined]
+ f5.ref = df5 # type: ignore[attr-defined]
+
+ def rosen(x, _): return optimize.rosen(x)
+ rosen.mn = 5, 1 # type: ignore[attr-defined]
+ rosen.ref = optimize.rosen_der # type: ignore[attr-defined]
+
+ @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+ @pytest.mark.parametrize('size', [(), (6,), (2, 3)])
+ @pytest.mark.parametrize('func', [f1, f2, f3, f4, f5, rosen])
+ def test_examples(self, dtype, size, func, xp):
+ atol = 1e-10 if dtype == 'float64' else 1.99e-3
+ dtype = getattr(xp, dtype)
+ rng = np.random.default_rng(458912319542)
+ m, n = func.mn
+ x = rng.random(size=(m,) + size)
+ res = jacobian(lambda x: func(x , xp), xp.asarray(x, dtype=dtype))
+ # convert list of arrays to single array before converting to xp array
+ ref = xp.asarray(np.asarray(func.ref(x)), dtype=dtype)
+ xp_assert_close(res.df, ref, atol=atol)
+
+ def test_attrs(self, xp):
+ # Test attributes of result object
+ z = xp.asarray([0.5, 0.25])
+
+ # case in which some elements of the Jacobian are harder
+ # to calculate than others
+ def df1(z):
+ x, y = z
+ return xp.stack([xp.cos(0.5*x) * xp.cos(y), xp.sin(2*x) * y**2])
+
+ def df1_0xy(x, y):
+ return xp.cos(0.5*x) * xp.cos(y)
+
+ def df1_1xy(x, y):
+ return xp.sin(2*x) * y**2
+
+ res = jacobian(df1, z, initial_step=10)
+ if is_numpy(xp):
+ assert len(np.unique(res.nit)) == 4
+ assert len(np.unique(res.nfev)) == 4
+
+ res00 = jacobian(lambda x: df1_0xy(x, z[1]), z[0:1], initial_step=10)
+ res01 = jacobian(lambda y: df1_0xy(z[0], y), z[1:2], initial_step=10)
+ res10 = jacobian(lambda x: df1_1xy(x, z[1]), z[0:1], initial_step=10)
+ res11 = jacobian(lambda y: df1_1xy(z[0], y), z[1:2], initial_step=10)
+ ref = optimize.OptimizeResult()
+ for attr in ['success', 'status', 'df', 'nit', 'nfev']:
+ ref_attr = xp.asarray([[getattr(res00, attr), getattr(res01, attr)],
+ [getattr(res10, attr), getattr(res11, attr)]])
+ ref[attr] = xp.squeeze(ref_attr)
+ rtol = 1.5e-5 if res[attr].dtype == xp.float32 else 1.5e-14
+ xp_assert_close(res[attr], ref[attr], rtol=rtol)
+
+ def test_step_direction_size(self, xp):
+ # Check that `step_direction` and `initial_step` can be used to ensure that
+ # the usable domain of a function is respected.
+ rng = np.random.default_rng(23892589425245)
+ b = rng.random(3)
+ eps = 1e-7 # torch needs wiggle room?
+
+ def f(x):
+ x[0, x[0] < b[0]] = xp.nan
+ x[0, x[0] > b[0] + 0.25] = xp.nan
+ x[1, x[1] > b[1]] = xp.nan
+ x[1, x[1] < b[1] - 0.1-eps] = xp.nan
+ return TestJacobian.f5(x, xp)
+
+ dir = [1, -1, 0]
+ h0 = [0.25, 0.1, 0.5]
+ atol = {'atol': 1e-8}
+ res = jacobian(f, xp.asarray(b, dtype=xp.float64), initial_step=h0,
+ step_direction=dir, tolerances=atol)
+ ref = xp.asarray(TestJacobian.df5(b), dtype=xp.float64)
+ xp_assert_close(res.df, ref, atol=1e-8)
+ assert xp.all(xp.isfinite(ref))
+
+
+@pytest.mark.skip_xp_backends('array_api_strict', reason=array_api_strict_skip_reason)
+@pytest.mark.skip_xp_backends('jax.numpy',reason=jax_skip_reason)
+class TestHessian(JacobianHessianTest):
+ jh_func = hessian
+
+ @pytest.mark.parametrize('shape', [(), (4,), (2, 4)])
+ def test_example(self, shape, xp):
+ rng = np.random.default_rng(458912319542)
+ m = 3
+ x = xp.asarray(rng.random((m,) + shape), dtype=xp.float64)
+ res = hessian(optimize.rosen, x)
+ if shape:
+ x = xp.reshape(x, (m, -1))
+ ref = xp.stack([optimize.rosen_hess(xi) for xi in x.T])
+ ref = xp.moveaxis(ref, 0, -1)
+ ref = xp.reshape(ref, (m, m,) + shape)
+ else:
+ ref = optimize.rosen_hess(x)
+ xp_assert_close(res.ddf, ref, atol=1e-8)
+
+ # # Removed symmetry enforcement; consider adding back in as a feature
+ # # check symmetry
+ # for key in ['ddf', 'error', 'nfev', 'success', 'status']:
+ # assert_equal(res[key], np.swapaxes(res[key], 0, 1))
+
+ def test_float32(self, xp):
+ rng = np.random.default_rng(458912319542)
+ x = xp.asarray(rng.random(3), dtype=xp.float32)
+ res = hessian(optimize.rosen, x)
+ ref = optimize.rosen_hess(x)
+ mask = (ref != 0)
+ xp_assert_close(res.ddf[mask], ref[mask])
+ atol = 1e-2 * xp.abs(xp.min(ref[mask]))
+ xp_assert_close(res.ddf[~mask], ref[~mask], atol=atol)
+
+ def test_nfev(self, xp):
+ z = xp.asarray([0.5, 0.25])
+ xp_test = array_namespace(z)
+
+ def f1(z):
+ x, y = xp_test.broadcast_arrays(*z)
+ f1.nfev = f1.nfev + (math.prod(x.shape[2:]) if x.ndim > 2 else 1)
+ return xp.sin(x) * y ** 3
+ f1.nfev = 0
+
+
+ res = hessian(f1, z, initial_step=10)
+ f1.nfev = 0
+ res00 = hessian(lambda x: f1([x[0], z[1]]), z[0:1], initial_step=10)
+ assert res.nfev[0, 0] == f1.nfev == res00.nfev[0, 0]
+
+ f1.nfev = 0
+ res11 = hessian(lambda y: f1([z[0], y[0]]), z[1:2], initial_step=10)
+ assert res.nfev[1, 1] == f1.nfev == res11.nfev[0, 0]
+
+ # Removed symmetry enforcement; consider adding back in as a feature
+ # assert_equal(res.nfev, res.nfev.T) # check symmetry
+ # assert np.unique(res.nfev).size == 3
+
+
+ @pytest.mark.thread_unsafe
+ @pytest.mark.skip_xp_backends(np_only=True,
+ reason='Python list input uses NumPy backend')
+ def test_small_rtol_warning(self, xp):
+ message = 'The specified `rtol=1e-15`, but...'
+ with pytest.warns(RuntimeWarning, match=message):
+ hessian(xp.sin, [1.], tolerances=dict(rtol=1e-15))
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/LICENSE.md b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/LICENSE.md
new file mode 100644
index 0000000000000000000000000000000000000000..b5aa9769746affa6c430599612a3146108f0a974
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/LICENSE.md
@@ -0,0 +1,25 @@
+Copyright (C) 2010-2019 Max-Planck-Society
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+* Redistributions in binary form must reproduce the above copyright notice, this
+ list of conditions and the following disclaimer in the documentation and/or
+ other materials provided with the distribution.
+* Neither the name of the copyright holder nor the names of its contributors may
+ be used to endorse or promote products derived from this software without
+ specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/__init__.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c792b8c23a0fc76098950623875e45427d848077
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/__init__.py
@@ -0,0 +1,9 @@
+""" FFT backend using pypocketfft """
+
+from .basic import *
+from .realtransforms import *
+from .helper import *
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/basic.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..928335c2cd0a1d3a0250278179dae773243808d4
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/basic.py
@@ -0,0 +1,251 @@
+"""
+Discrete Fourier Transforms - basic.py
+"""
+import numpy as np
+import functools
+from . import pypocketfft as pfft
+from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
+ _fix_shape, _fix_shape_1d, _normalization,
+ _workers)
+
+def c2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+ workers=None, *, plan=None):
+ """ Return discrete Fourier transform of real or complex sequence. """
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ tmp = _asfarray(x)
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+
+ if n is not None:
+ tmp, copied = _fix_shape_1d(tmp, n, axis)
+ overwrite_x = overwrite_x or copied
+ elif tmp.shape[axis] < 1:
+ message = f"invalid number of data points ({tmp.shape[axis]}) specified"
+ raise ValueError(message)
+
+ out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
+
+ return pfft.c2c(tmp, (axis,), forward, norm, out, workers)
+
+
+fft = functools.partial(c2c, True)
+fft.__name__ = 'fft'
+ifft = functools.partial(c2c, False)
+ifft.__name__ = 'ifft'
+
+
+def r2c(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+ workers=None, *, plan=None):
+ """
+ Discrete Fourier transform of a real sequence.
+ """
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ tmp = _asfarray(x)
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+
+ if not np.isrealobj(tmp):
+ raise TypeError("x must be a real sequence")
+
+ if n is not None:
+ tmp, _ = _fix_shape_1d(tmp, n, axis)
+ elif tmp.shape[axis] < 1:
+ raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+ # Note: overwrite_x is not utilised
+ return pfft.r2c(tmp, (axis,), forward, norm, None, workers)
+
+
+rfft = functools.partial(r2c, True)
+rfft.__name__ = 'rfft'
+ihfft = functools.partial(r2c, False)
+ihfft.__name__ = 'ihfft'
+
+
+def c2r(forward, x, n=None, axis=-1, norm=None, overwrite_x=False,
+ workers=None, *, plan=None):
+ """
+ Return inverse discrete Fourier transform of real sequence x.
+ """
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ tmp = _asfarray(x)
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+
+ # TODO: Optimize for hermitian and real?
+ if np.isrealobj(tmp):
+ tmp = tmp + 0.j
+
+ # Last axis utilizes hermitian symmetry
+ if n is None:
+ n = (tmp.shape[axis] - 1) * 2
+ if n < 1:
+ raise ValueError(f"Invalid number of data points ({n}) specified")
+ else:
+ tmp, _ = _fix_shape_1d(tmp, (n//2) + 1, axis)
+
+ # Note: overwrite_x is not utilized
+ return pfft.c2r(tmp, (axis,), n, forward, norm, None, workers)
+
+
+hfft = functools.partial(c2r, True)
+hfft.__name__ = 'hfft'
+irfft = functools.partial(c2r, False)
+irfft.__name__ = 'irfft'
+
+
+def hfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
+ *, plan=None):
+ """
+ 2-D discrete Fourier transform of a Hermitian sequence
+ """
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ return hfftn(x, s, axes, norm, overwrite_x, workers)
+
+
+def ihfft2(x, s=None, axes=(-2,-1), norm=None, overwrite_x=False, workers=None,
+ *, plan=None):
+ """
+ 2-D discrete inverse Fourier transform of a Hermitian sequence
+ """
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ return ihfftn(x, s, axes, norm, overwrite_x, workers)
+
+
+def c2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+ workers=None, *, plan=None):
+ """
+ Return multidimensional discrete Fourier transform.
+ """
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ tmp = _asfarray(x)
+
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
+ workers = _workers(workers)
+
+ if len(axes) == 0:
+ return x
+
+ tmp, copied = _fix_shape(tmp, shape, axes)
+ overwrite_x = overwrite_x or copied
+
+ norm = _normalization(norm, forward)
+ out = (tmp if overwrite_x and tmp.dtype.kind == 'c' else None)
+
+ return pfft.c2c(tmp, axes, forward, norm, out, workers)
+
+
+fftn = functools.partial(c2cn, True)
+fftn.__name__ = 'fftn'
+ifftn = functools.partial(c2cn, False)
+ifftn.__name__ = 'ifftn'
+
+def r2cn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+ workers=None, *, plan=None):
+ """Return multidimensional discrete Fourier transform of real input"""
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ tmp = _asfarray(x)
+
+ if not np.isrealobj(tmp):
+ raise TypeError("x must be a real sequence")
+
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+ tmp, _ = _fix_shape(tmp, shape, axes)
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+
+ if len(axes) == 0:
+ raise ValueError("at least 1 axis must be transformed")
+
+ # Note: overwrite_x is not utilized
+ return pfft.r2c(tmp, axes, forward, norm, None, workers)
+
+
+rfftn = functools.partial(r2cn, True)
+rfftn.__name__ = 'rfftn'
+ihfftn = functools.partial(r2cn, False)
+ihfftn.__name__ = 'ihfftn'
+
+
+def c2rn(forward, x, s=None, axes=None, norm=None, overwrite_x=False,
+ workers=None, *, plan=None):
+ """Multidimensional inverse discrete fourier transform with real output"""
+ if plan is not None:
+ raise NotImplementedError('Passing a precomputed plan is not yet '
+ 'supported by scipy.fft functions')
+ tmp = _asfarray(x)
+
+ # TODO: Optimize for hermitian and real?
+ if np.isrealobj(tmp):
+ tmp = tmp + 0.j
+
+ noshape = s is None
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+
+ if len(axes) == 0:
+ raise ValueError("at least 1 axis must be transformed")
+
+ shape = list(shape)
+ if noshape:
+ shape[-1] = (x.shape[axes[-1]] - 1) * 2
+
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+
+ # Last axis utilizes hermitian symmetry
+ lastsize = shape[-1]
+ shape[-1] = (shape[-1] // 2) + 1
+
+ tmp, _ = tuple(_fix_shape(tmp, shape, axes))
+
+ # Note: overwrite_x is not utilized
+ return pfft.c2r(tmp, axes, lastsize, forward, norm, None, workers)
+
+
+hfftn = functools.partial(c2rn, True)
+hfftn.__name__ = 'hfftn'
+irfftn = functools.partial(c2rn, False)
+irfftn.__name__ = 'irfftn'
+
+
+def r2r_fftpack(forward, x, n=None, axis=-1, norm=None, overwrite_x=False):
+ """FFT of a real sequence, returning fftpack half complex format"""
+ tmp = _asfarray(x)
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
+ norm = _normalization(norm, forward)
+ workers = _workers(None)
+
+ if tmp.dtype.kind == 'c':
+ raise TypeError('x must be a real sequence')
+
+ if n is not None:
+ tmp, copied = _fix_shape_1d(tmp, n, axis)
+ overwrite_x = overwrite_x or copied
+ elif tmp.shape[axis] < 1:
+ raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+ out = (tmp if overwrite_x else None)
+
+ return pfft.r2r_fftpack(tmp, (axis,), forward, forward, norm, out, workers)
+
+
+rfft_fftpack = functools.partial(r2r_fftpack, True)
+rfft_fftpack.__name__ = 'rfft_fftpack'
+irfft_fftpack = functools.partial(r2r_fftpack, False)
+irfft_fftpack.__name__ = 'irfft_fftpack'
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/helper.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3175d9e0ad1e605d559cf032ed5fbbec26a1ce5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/helper.py
@@ -0,0 +1,221 @@
+from numbers import Number
+import operator
+import os
+import threading
+import contextlib
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+
+# good_size is exposed (and used) from this import
+from .pypocketfft import good_size, prev_good_size
+
+
+__all__ = ['good_size', 'prev_good_size', 'set_workers', 'get_workers']
+
+_config = threading.local()
+_cpu_count = os.cpu_count()
+
+
+def _iterable_of_int(x, name=None):
+ """Convert ``x`` to an iterable sequence of int
+
+ Parameters
+ ----------
+ x : value, or sequence of values, convertible to int
+ name : str, optional
+ Name of the argument being converted, only used in the error message
+
+ Returns
+ -------
+ y : ``List[int]``
+ """
+ if isinstance(x, Number):
+ x = (x,)
+
+ try:
+ x = [operator.index(a) for a in x]
+ except TypeError as e:
+ name = name or "value"
+ raise ValueError(f"{name} must be a scalar or iterable of integers") from e
+
+ return x
+
+
+def _init_nd_shape_and_axes(x, shape, axes):
+ """Handles shape and axes arguments for nd transforms"""
+ noshape = shape is None
+ noaxes = axes is None
+
+ if not noaxes:
+ axes = _iterable_of_int(axes, 'axes')
+ axes = [a + x.ndim if a < 0 else a for a in axes]
+
+ if any(a >= x.ndim or a < 0 for a in axes):
+ raise ValueError("axes exceeds dimensionality of input")
+ if len(set(axes)) != len(axes):
+ raise ValueError("all axes must be unique")
+
+ if not noshape:
+ shape = _iterable_of_int(shape, 'shape')
+
+ if axes and len(axes) != len(shape):
+ raise ValueError("when given, axes and shape arguments"
+ " have to be of the same length")
+ if noaxes:
+ if len(shape) > x.ndim:
+ raise ValueError("shape requires more axes than are present")
+ axes = range(x.ndim - len(shape), x.ndim)
+
+ shape = [x.shape[a] if s == -1 else s for s, a in zip(shape, axes)]
+ elif noaxes:
+ shape = list(x.shape)
+ axes = range(x.ndim)
+ else:
+ shape = [x.shape[a] for a in axes]
+
+ if any(s < 1 for s in shape):
+ raise ValueError(
+ f"invalid number of data points ({shape}) specified")
+
+ return tuple(shape), list(axes)
+
+
+def _asfarray(x):
+ """
+ Convert to array with floating or complex dtype.
+
+ float16 values are also promoted to float32.
+ """
+ if not hasattr(x, "dtype"):
+ x = np.asarray(x)
+
+ if x.dtype == np.float16:
+ return np.asarray(x, np.float32)
+ elif x.dtype.kind not in 'fc':
+ return np.asarray(x, np.float64)
+
+ # Require native byte order
+ dtype = x.dtype.newbyteorder('=')
+ # Always align input
+ copy = True if not x.flags['ALIGNED'] else copy_if_needed
+ return np.array(x, dtype=dtype, copy=copy)
+
+def _datacopied(arr, original):
+ """
+ Strict check for `arr` not sharing any data with `original`,
+ under the assumption that arr = asarray(original)
+ """
+ if arr is original:
+ return False
+ if not isinstance(original, np.ndarray) and hasattr(original, '__array__'):
+ return False
+ return arr.base is None
+
+
+def _fix_shape(x, shape, axes):
+ """Internal auxiliary function for _raw_fft, _raw_fftnd."""
+ must_copy = False
+
+ # Build an nd slice with the dimensions to be read from x
+ index = [slice(None)]*x.ndim
+ for n, ax in zip(shape, axes):
+ if x.shape[ax] >= n:
+ index[ax] = slice(0, n)
+ else:
+ index[ax] = slice(0, x.shape[ax])
+ must_copy = True
+
+ index = tuple(index)
+
+ if not must_copy:
+ return x[index], False
+
+ s = list(x.shape)
+ for n, axis in zip(shape, axes):
+ s[axis] = n
+
+ z = np.zeros(s, x.dtype)
+ z[index] = x[index]
+ return z, True
+
+
+def _fix_shape_1d(x, n, axis):
+ if n < 1:
+ raise ValueError(
+ f"invalid number of data points ({n}) specified")
+
+ return _fix_shape(x, (n,), (axis,))
+
+
+_NORM_MAP = {None: 0, 'backward': 0, 'ortho': 1, 'forward': 2}
+
+
+def _normalization(norm, forward):
+ """Returns the pypocketfft normalization mode from the norm argument"""
+ try:
+ inorm = _NORM_MAP[norm]
+ return inorm if forward else (2 - inorm)
+ except KeyError:
+ raise ValueError(
+ f'Invalid norm value {norm!r}, should '
+ 'be "backward", "ortho" or "forward"') from None
+
+
+def _workers(workers):
+ if workers is None:
+ return getattr(_config, 'default_workers', 1)
+
+ if workers < 0:
+ if workers >= -_cpu_count:
+ workers += 1 + _cpu_count
+ else:
+ raise ValueError(f"workers value out of range; got {workers}, must not be"
+ f" less than {-_cpu_count}")
+ elif workers == 0:
+ raise ValueError("workers must not be zero")
+
+ return workers
+
+
+@contextlib.contextmanager
+def set_workers(workers):
+ """Context manager for the default number of workers used in `scipy.fft`
+
+ Parameters
+ ----------
+ workers : int
+ The default number of workers to use
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import fft, signal
+ >>> rng = np.random.default_rng()
+ >>> x = rng.standard_normal((128, 64))
+ >>> with fft.set_workers(4):
+ ... y = signal.fftconvolve(x, x)
+
+ """
+ old_workers = get_workers()
+ _config.default_workers = _workers(operator.index(workers))
+ try:
+ yield
+ finally:
+ _config.default_workers = old_workers
+
+
+def get_workers():
+ """Returns the default number of workers within the current context
+
+ Examples
+ --------
+ >>> from scipy import fft
+ >>> fft.get_workers()
+ 1
+ >>> with fft.set_workers(4):
+ ... fft.get_workers()
+ 4
+ """
+ return getattr(_config, 'default_workers', 1)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/pypocketfft.cp312-win_amd64.dll.a b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/pypocketfft.cp312-win_amd64.dll.a
new file mode 100644
index 0000000000000000000000000000000000000000..ed15922c90621a43f1ecc60fcee9458a53f36432
Binary files /dev/null and b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/pypocketfft.cp312-win_amd64.dll.a differ
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/realtransforms.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/realtransforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..781f04a62a436ec0ad4b73338a9c60737da47fa3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/realtransforms.py
@@ -0,0 +1,109 @@
+import numpy as np
+from . import pypocketfft as pfft
+from .helper import (_asfarray, _init_nd_shape_and_axes, _datacopied,
+ _fix_shape, _fix_shape_1d, _normalization, _workers)
+import functools
+
+
+def _r2r(forward, transform, x, type=2, n=None, axis=-1, norm=None,
+ overwrite_x=False, workers=None, orthogonalize=None):
+ """Forward or backward 1-D DCT/DST
+
+ Parameters
+ ----------
+ forward : bool
+ Transform direction (determines type and normalisation)
+ transform : {pypocketfft.dct, pypocketfft.dst}
+ The transform to perform
+ """
+ tmp = _asfarray(x)
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+
+ if not forward:
+ if type == 2:
+ type = 3
+ elif type == 3:
+ type = 2
+
+ if n is not None:
+ tmp, copied = _fix_shape_1d(tmp, n, axis)
+ overwrite_x = overwrite_x or copied
+ elif tmp.shape[axis] < 1:
+ raise ValueError(f"invalid number of data points ({tmp.shape[axis]}) specified")
+
+ out = (tmp if overwrite_x else None)
+
+ # For complex input, transform real and imaginary components separably
+ if np.iscomplexobj(x):
+ out = np.empty_like(tmp) if out is None else out
+ transform(tmp.real, type, (axis,), norm, out.real, workers)
+ transform(tmp.imag, type, (axis,), norm, out.imag, workers)
+ return out
+
+ return transform(tmp, type, (axis,), norm, out, workers, orthogonalize)
+
+
+dct = functools.partial(_r2r, True, pfft.dct)
+dct.__name__ = 'dct'
+idct = functools.partial(_r2r, False, pfft.dct)
+idct.__name__ = 'idct'
+
+dst = functools.partial(_r2r, True, pfft.dst)
+dst.__name__ = 'dst'
+idst = functools.partial(_r2r, False, pfft.dst)
+idst.__name__ = 'idst'
+
+
+def _r2rn(forward, transform, x, type=2, s=None, axes=None, norm=None,
+ overwrite_x=False, workers=None, orthogonalize=None):
+ """Forward or backward nd DCT/DST
+
+ Parameters
+ ----------
+ forward : bool
+ Transform direction (determines type and normalisation)
+ transform : {pypocketfft.dct, pypocketfft.dst}
+ The transform to perform
+ """
+ tmp = _asfarray(x)
+
+ shape, axes = _init_nd_shape_and_axes(tmp, s, axes)
+ overwrite_x = overwrite_x or _datacopied(tmp, x)
+
+ if len(axes) == 0:
+ return x
+
+ tmp, copied = _fix_shape(tmp, shape, axes)
+ overwrite_x = overwrite_x or copied
+
+ if not forward:
+ if type == 2:
+ type = 3
+ elif type == 3:
+ type = 2
+
+ norm = _normalization(norm, forward)
+ workers = _workers(workers)
+ out = (tmp if overwrite_x else None)
+
+ # For complex input, transform real and imaginary components separably
+ if np.iscomplexobj(x):
+ out = np.empty_like(tmp) if out is None else out
+ transform(tmp.real, type, axes, norm, out.real, workers)
+ transform(tmp.imag, type, axes, norm, out.imag, workers)
+ return out
+
+ return transform(tmp, type, axes, norm, out, workers, orthogonalize)
+
+
+dctn = functools.partial(_r2rn, True, pfft.dct)
+dctn.__name__ = 'dctn'
+idctn = functools.partial(_r2rn, False, pfft.dct)
+idctn.__name__ = 'idctn'
+
+dstn = functools.partial(_r2rn, True, pfft.dst)
+dstn.__name__ = 'dstn'
+idstn = functools.partial(_r2rn, False, pfft.dst)
+idstn.__name__ = 'idstn'
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/test_basic.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4101c48ebf0faad74b129ab793c4c1ee79ba37b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/test_basic.py
@@ -0,0 +1,1013 @@
+# Created by Pearu Peterson, September 2002
+
+from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
+ assert_array_almost_equal_nulp, assert_array_less,
+ assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+from scipy.fft._pocketfft import (ifft, fft, fftn, ifftn,
+ rfft, irfft, rfftn, irfftn,
+ hfft, ihfft, hfftn, ihfftn)
+
+from numpy import (arange, array, asarray, zeros, dot, exp, pi,
+ swapaxes, cdouble)
+import numpy as np
+import numpy.fft
+from numpy.random import rand
+
+# "large" composite numbers supported by FFT._PYPOCKETFFT
+LARGE_COMPOSITE_SIZES = [
+ 2**13,
+ 2**5 * 3**5,
+ 2**3 * 3**3 * 5**2,
+]
+SMALL_COMPOSITE_SIZES = [
+ 2,
+ 2*3*5,
+ 2*2*3*3,
+]
+# prime
+LARGE_PRIME_SIZES = [
+ 2011
+]
+SMALL_PRIME_SIZES = [
+ 29
+]
+
+
+def _assert_close_in_norm(x, y, rtol, size, rdt):
+ # helper function for testing
+ err_msg = f"size: {size} rdt: {rdt}"
+ assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
+
+
+def random(size):
+ return rand(*size)
+
+def swap_byteorder(arr):
+ """Returns the same array with swapped byteorder"""
+ dtype = arr.dtype.newbyteorder('S')
+ return arr.astype(dtype)
+
+def direct_dft(x):
+ x = asarray(x)
+ n = len(x)
+ y = zeros(n, dtype=cdouble)
+ w = -arange(n)*(2j*pi/n)
+ for i in range(n):
+ y[i] = dot(exp(i*w), x)
+ return y
+
+
+def direct_idft(x):
+ x = asarray(x)
+ n = len(x)
+ y = zeros(n, dtype=cdouble)
+ w = arange(n)*(2j*pi/n)
+ for i in range(n):
+ y[i] = dot(exp(i*w), x)/n
+ return y
+
+
+def direct_dftn(x):
+ x = asarray(x)
+ for axis in range(x.ndim):
+ x = fft(x, axis=axis)
+ return x
+
+
+def direct_idftn(x):
+ x = asarray(x)
+ for axis in range(x.ndim):
+ x = ifft(x, axis=axis)
+ return x
+
+
+def direct_rdft(x):
+ x = asarray(x)
+ n = len(x)
+ w = -arange(n)*(2j*pi/n)
+ y = zeros(n//2+1, dtype=cdouble)
+ for i in range(n//2+1):
+ y[i] = dot(exp(i*w), x)
+ return y
+
+
+def direct_irdft(x, n):
+ x = asarray(x)
+ x1 = zeros(n, dtype=cdouble)
+ for i in range(n//2+1):
+ x1[i] = x[i]
+ if i > 0 and 2*i < n:
+ x1[n-i] = np.conj(x[i])
+ return direct_idft(x1).real
+
+
+def direct_rdftn(x):
+ return fftn(rfft(x), axes=range(x.ndim - 1))
+
+
+class _TestFFTBase:
+ def setup_method(self):
+ self.cdt = None
+ self.rdt = None
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
+ y = fft(x)
+ assert_equal(y.dtype, self.cdt)
+ y1 = direct_dft(x)
+ assert_array_almost_equal(y,y1)
+ x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
+ assert_array_almost_equal(fft(x),direct_dft(x))
+
+ def test_n_argument_real(self):
+ x1 = np.array([1,2,3,4], dtype=self.rdt)
+ x2 = np.array([1,2,3,4], dtype=self.rdt)
+ y = fft([x1,x2],n=4)
+ assert_equal(y.dtype, self.cdt)
+ assert_equal(y.shape,(2,4))
+ assert_array_almost_equal(y[0],direct_dft(x1))
+ assert_array_almost_equal(y[1],direct_dft(x2))
+
+ def _test_n_argument_complex(self):
+ x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
+ x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
+ y = fft([x1,x2],n=4)
+ assert_equal(y.dtype, self.cdt)
+ assert_equal(y.shape,(2,4))
+ assert_array_almost_equal(y[0],direct_dft(x1))
+ assert_array_almost_equal(y[1],direct_dft(x2))
+
+ def test_djbfft(self):
+ for i in range(2,14):
+ n = 2**i
+ x = np.arange(n)
+ y = fft(x.astype(complex))
+ y2 = numpy.fft.fft(x)
+ assert_array_almost_equal(y,y2)
+ y = fft(x)
+ assert_array_almost_equal(y,y2)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, fft, [])
+ assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
+
+
+class TestLongDoubleFFT(_TestFFTBase):
+ def setup_method(self):
+ self.cdt = np.clongdouble
+ self.rdt = np.longdouble
+
+
+class TestDoubleFFT(_TestFFTBase):
+ def setup_method(self):
+ self.cdt = np.cdouble
+ self.rdt = np.float64
+
+
+class TestSingleFFT(_TestFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+
+
+class TestFloat16FFT:
+
+ def test_1_argument_real(self):
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+ y = fft(x1, n=4)
+ assert_equal(y.dtype, np.complex64)
+ assert_equal(y.shape, (4, ))
+ assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
+
+ def test_n_argument_real(self):
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+ x2 = np.array([1, 2, 3, 4], dtype=np.float16)
+ y = fft([x1, x2], n=4)
+ assert_equal(y.dtype, np.complex64)
+ assert_equal(y.shape, (2, 4))
+ assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
+ assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
+
+
+class _TestIFFTBase:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
+ y = ifft(x)
+ y1 = direct_idft(x)
+ assert_equal(y.dtype, self.cdt)
+ assert_array_almost_equal(y,y1)
+
+ x = np.array([1,2,3,4+0j,5], self.cdt)
+ assert_array_almost_equal(ifft(x),direct_idft(x))
+
+ def test_definition_real(self):
+ x = np.array([1,2,3,4,1,2,3,4], self.rdt)
+ y = ifft(x)
+ assert_equal(y.dtype, self.cdt)
+ y1 = direct_idft(x)
+ assert_array_almost_equal(y,y1)
+
+ x = np.array([1,2,3,4,5], dtype=self.rdt)
+ assert_equal(y.dtype, self.cdt)
+ assert_array_almost_equal(ifft(x),direct_idft(x))
+
+ def test_djbfft(self):
+ for i in range(2,14):
+ n = 2**i
+ x = np.arange(n)
+ y = ifft(x.astype(self.cdt))
+ y2 = numpy.fft.ifft(x.astype(self.cdt))
+ assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
+ y = ifft(x)
+ assert_allclose(y,y2, rtol=self.rtol, atol=self.atol)
+
+ def test_random_complex(self):
+ for size in [1,51,111,100,200,64,128,256,1024]:
+ x = random([size]).astype(self.cdt)
+ x = random([size]).astype(self.cdt) + 1j*x
+ y1 = ifft(fft(x))
+ y2 = fft(ifft(x))
+ assert_equal(y1.dtype, self.cdt)
+ assert_equal(y2.dtype, self.cdt)
+ assert_array_almost_equal(y1, x)
+ assert_array_almost_equal(y2, x)
+
+ def test_random_real(self):
+ for size in [1,51,111,100,200,64,128,256,1024]:
+ x = random([size]).astype(self.rdt)
+ y1 = ifft(fft(x))
+ y2 = fft(ifft(x))
+ assert_equal(y1.dtype, self.cdt)
+ assert_equal(y2.dtype, self.cdt)
+ assert_array_almost_equal(y1, x)
+ assert_array_almost_equal(y2, x)
+
+ def test_size_accuracy(self):
+ # Sanity check for the accuracy for prime and non-prime sized inputs
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+ np.random.seed(1234)
+ x = np.random.rand(size).astype(self.rdt)
+ y = ifft(fft(x))
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+ y = fft(ifft(x))
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+
+ x = (x + 1j*np.random.rand(size)).astype(self.cdt)
+ y = ifft(fft(x))
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+ y = fft(ifft(x))
+ _assert_close_in_norm(x, y, self.rtol, size, self.rdt)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, ifft, [])
+ assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
+
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+ reason="Long double is aliased to double")
+class TestLongDoubleIFFT(_TestIFFTBase):
+ def setup_method(self):
+ self.cdt = np.clongdouble
+ self.rdt = np.longdouble
+ self.rtol = 1e-10
+ self.atol = 1e-10
+
+
+class TestDoubleIFFT(_TestIFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+ self.rtol = 1e-10
+ self.atol = 1e-10
+
+
+class TestSingleIFFT(_TestIFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+ self.rtol = 1e-5
+ self.atol = 1e-4
+
+
+class _TestRFFTBase:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
+ x = np.array(t, dtype=self.rdt)
+ y = rfft(x)
+ y1 = direct_rdft(x)
+ assert_array_almost_equal(y,y1)
+ assert_equal(y.dtype, self.cdt)
+
+ def test_djbfft(self):
+ for i in range(2,14):
+ n = 2**i
+ x = np.arange(n)
+ y1 = np.fft.rfft(x)
+ y = rfft(x)
+ assert_array_almost_equal(y,y1)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, rfft, [])
+ assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
+
+ def test_complex_input(self):
+ x = np.zeros(10, dtype=self.cdt)
+ with assert_raises(TypeError, match="x must be a real sequence"):
+ rfft(x)
+
+ # See gh-5790
+ class MockSeries:
+ def __init__(self, data):
+ self.data = np.asarray(data)
+
+ def __getattr__(self, item):
+ try:
+ return getattr(self.data, item)
+ except AttributeError as e:
+ raise AttributeError("'MockSeries' object "
+ f"has no attribute '{item}'") from e
+
+ def test_non_ndarray_with_dtype(self):
+ x = np.array([1., 2., 3., 4., 5.])
+ xs = _TestRFFTBase.MockSeries(x)
+
+ expected = [1, 2, 3, 4, 5]
+ rfft(xs)
+
+ # Data should not have been overwritten
+ assert_equal(x, expected)
+ assert_equal(xs.data, expected)
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+ reason="Long double is aliased to double")
+class TestRFFTLongDouble(_TestRFFTBase):
+ def setup_method(self):
+ self.cdt = np.clongdouble
+ self.rdt = np.longdouble
+
+
+class TestRFFTDouble(_TestRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+
+
+class TestRFFTSingle(_TestRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+
+
+class _TestIRFFTBase:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x1 = [1,2+3j,4+1j,1+2j,3+4j]
+ x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
+ x1 = x1_1[:5]
+ x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
+ x2 = x2_1[:5]
+
+ def _test(x, xr):
+ y = irfft(np.array(x, dtype=self.cdt), n=len(xr))
+ y1 = direct_irdft(x, len(xr))
+ assert_equal(y.dtype, self.rdt)
+ assert_array_almost_equal(y,y1, decimal=self.ndec)
+ assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
+
+ _test(x1, x1_1)
+ _test(x2, x2_1)
+
+ def test_djbfft(self):
+ for i in range(2,14):
+ n = 2**i
+ x = np.arange(-1, n, 2) + 1j * np.arange(0, n+1, 2)
+ x[0] = 0
+ if n % 2 == 0:
+ x[-1] = np.real(x[-1])
+ y1 = np.fft.irfft(x)
+ y = irfft(x)
+ assert_array_almost_equal(y,y1)
+
+ def test_random_real(self):
+ for size in [1,51,111,100,200,64,128,256,1024]:
+ x = random([size]).astype(self.rdt)
+ y1 = irfft(rfft(x), n=size)
+ y2 = rfft(irfft(x, n=(size*2-1)))
+ assert_equal(y1.dtype, self.rdt)
+ assert_equal(y2.dtype, self.cdt)
+ assert_array_almost_equal(y1, x, decimal=self.ndec,
+ err_msg="size=%d" % size)
+ assert_array_almost_equal(y2, x, decimal=self.ndec,
+ err_msg="size=%d" % size)
+
+ def test_size_accuracy(self):
+ # Sanity check for the accuracy for prime and non-prime sized inputs
+ if self.rdt == np.float32:
+ rtol = 1e-5
+ elif self.rdt == np.float64:
+ rtol = 1e-10
+
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+ np.random.seed(1234)
+ x = np.random.rand(size).astype(self.rdt)
+ y = irfft(rfft(x), len(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+ y = rfft(irfft(x, 2 * len(x) - 1))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, irfft, [])
+ assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
+
+
+# self.ndec is bogus; we should have a assert_array_approx_equal for number of
+# significant digits
+
+@pytest.mark.skipif(np.longdouble is np.float64,
+ reason="Long double is aliased to double")
+class TestIRFFTLongDouble(_TestIRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+ self.ndec = 14
+
+
+class TestIRFFTDouble(_TestIRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+ self.ndec = 14
+
+
+class TestIRFFTSingle(_TestIRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+ self.ndec = 5
+
+
+class TestFftnSingle:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ y = fftn(np.array(x, np.float32))
+ assert_(y.dtype == np.complex64,
+ msg="double precision output with single precision")
+
+ y_r = np.array(fftn(x), np.complex64)
+ assert_array_almost_equal_nulp(y, y_r)
+
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+ def test_size_accuracy_small(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, size)) + 1j * rng.random((size, size))
+ y1 = fftn(x.real.astype(np.float32))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 2000)
+
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+ def test_size_accuracy_large(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, 3)) + 1j * rng.random((size, 3))
+ y1 = fftn(x.real.astype(np.float32))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 2000)
+
+ def test_definition_float16(self):
+ x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ y = fftn(np.array(x, np.float16))
+ assert_equal(y.dtype, np.complex64)
+ y_r = np.array(fftn(x), np.complex64)
+ assert_array_almost_equal_nulp(y, y_r)
+
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+ def test_float16_input_small(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, size)) + 1j*rng.random((size, size))
+ y1 = fftn(x.real.astype(np.float16))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 5e5)
+
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+ def test_float16_input_large(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, 3)) + 1j*rng.random((size, 3))
+ y1 = fftn(x.real.astype(np.float16))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 2e6)
+
+
+class TestFftn:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ y = fftn(x)
+ assert_array_almost_equal(y, direct_dftn(x))
+
+ x = random((20, 26))
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+ x = random((5, 4, 3, 20))
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+ def test_axes_argument(self):
+ # plane == ji_plane, x== kji_space
+ plane1 = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ plane2 = [[10, 11, 12],
+ [13, 14, 15],
+ [16, 17, 18]]
+ plane3 = [[19, 20, 21],
+ [22, 23, 24],
+ [25, 26, 27]]
+ ki_plane1 = [[1, 2, 3],
+ [10, 11, 12],
+ [19, 20, 21]]
+ ki_plane2 = [[4, 5, 6],
+ [13, 14, 15],
+ [22, 23, 24]]
+ ki_plane3 = [[7, 8, 9],
+ [16, 17, 18],
+ [25, 26, 27]]
+ jk_plane1 = [[1, 10, 19],
+ [4, 13, 22],
+ [7, 16, 25]]
+ jk_plane2 = [[2, 11, 20],
+ [5, 14, 23],
+ [8, 17, 26]]
+ jk_plane3 = [[3, 12, 21],
+ [6, 15, 24],
+ [9, 18, 27]]
+ kj_plane1 = [[1, 4, 7],
+ [10, 13, 16], [19, 22, 25]]
+ kj_plane2 = [[2, 5, 8],
+ [11, 14, 17], [20, 23, 26]]
+ kj_plane3 = [[3, 6, 9],
+ [12, 15, 18], [21, 24, 27]]
+ ij_plane1 = [[1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9]]
+ ij_plane2 = [[10, 13, 16],
+ [11, 14, 17],
+ [12, 15, 18]]
+ ij_plane3 = [[19, 22, 25],
+ [20, 23, 26],
+ [21, 24, 27]]
+ ik_plane1 = [[1, 10, 19],
+ [2, 11, 20],
+ [3, 12, 21]]
+ ik_plane2 = [[4, 13, 22],
+ [5, 14, 23],
+ [6, 15, 24]]
+ ik_plane3 = [[7, 16, 25],
+ [8, 17, 26],
+ [9, 18, 27]]
+ ijk_space = [jk_plane1, jk_plane2, jk_plane3]
+ ikj_space = [kj_plane1, kj_plane2, kj_plane3]
+ jik_space = [ik_plane1, ik_plane2, ik_plane3]
+ jki_space = [ki_plane1, ki_plane2, ki_plane3]
+ kij_space = [ij_plane1, ij_plane2, ij_plane3]
+ x = array([plane1, plane2, plane3])
+
+ assert_array_almost_equal(fftn(x),
+ fftn(x, axes=(-3, -2, -1))) # kji_space
+ assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
+ assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
+ y = fftn(x, axes=(2, 1, 0)) # ijk_space
+ assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
+ y = fftn(x, axes=(2, 0, 1)) # ikj_space
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
+ fftn(ikj_space))
+ y = fftn(x, axes=(1, 2, 0)) # jik_space
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
+ fftn(jik_space))
+ y = fftn(x, axes=(1, 0, 2)) # jki_space
+ assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
+ y = fftn(x, axes=(0, 2, 1)) # kij_space
+ assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
+
+ y = fftn(x, axes=(-2, -1)) # ji_plane
+ assert_array_almost_equal(fftn(plane1), y[0])
+ assert_array_almost_equal(fftn(plane2), y[1])
+ assert_array_almost_equal(fftn(plane3), y[2])
+
+ y = fftn(x, axes=(1, 2)) # ji_plane
+ assert_array_almost_equal(fftn(plane1), y[0])
+ assert_array_almost_equal(fftn(plane2), y[1])
+ assert_array_almost_equal(fftn(plane3), y[2])
+
+ y = fftn(x, axes=(-3, -2)) # kj_plane
+ assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
+ assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
+ assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
+
+ y = fftn(x, axes=(-3, -1)) # ki_plane
+ assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
+ assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
+ assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
+
+ y = fftn(x, axes=(-1, -2)) # ij_plane
+ assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
+ assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
+ assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
+
+ y = fftn(x, axes=(-1, -3)) # ik_plane
+ assert_array_almost_equal(fftn(ik_plane1),
+ swapaxes(y[:, 0, :], -1, -2))
+ assert_array_almost_equal(fftn(ik_plane2),
+ swapaxes(y[:, 1, :], -1, -2))
+ assert_array_almost_equal(fftn(ik_plane3),
+ swapaxes(y[:, 2, :], -1, -2))
+
+ y = fftn(x, axes=(-2, -3)) # jk_plane
+ assert_array_almost_equal(fftn(jk_plane1),
+ swapaxes(y[:, :, 0], -1, -2))
+ assert_array_almost_equal(fftn(jk_plane2),
+ swapaxes(y[:, :, 1], -1, -2))
+ assert_array_almost_equal(fftn(jk_plane3),
+ swapaxes(y[:, :, 2], -1, -2))
+
+ y = fftn(x, axes=(-1,)) # i_line
+ for i in range(3):
+ for j in range(3):
+ assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
+ y = fftn(x, axes=(-2,)) # j_line
+ for i in range(3):
+ for j in range(3):
+ assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
+ y = fftn(x, axes=(0,)) # k_line
+ for i in range(3):
+ for j in range(3):
+ assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
+
+ y = fftn(x, axes=()) # point
+ assert_array_almost_equal(y, x)
+
+ def test_shape_argument(self):
+ small_x = [[1, 2, 3],
+ [4, 5, 6]]
+ large_x1 = [[1, 2, 3, 0],
+ [4, 5, 6, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]]
+
+ y = fftn(small_x, s=(4, 4))
+ assert_array_almost_equal(y, fftn(large_x1))
+
+ y = fftn(small_x, s=(3, 4))
+ assert_array_almost_equal(y, fftn(large_x1[:-1]))
+
+ def test_shape_axes_argument(self):
+ small_x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ large_x1 = array([[1, 2, 3, 0],
+ [4, 5, 6, 0],
+ [7, 8, 9, 0],
+ [0, 0, 0, 0]])
+ y = fftn(small_x, s=(4, 4), axes=(-2, -1))
+ assert_array_almost_equal(y, fftn(large_x1))
+ y = fftn(small_x, s=(4, 4), axes=(-1, -2))
+
+ assert_array_almost_equal(y, swapaxes(
+ fftn(swapaxes(large_x1, -1, -2)), -1, -2))
+
+ def test_shape_axes_argument2(self):
+ # Change shape of the last axis
+ x = numpy.random.random((10, 5, 3, 7))
+ y = fftn(x, axes=(-1,), s=(8,))
+ assert_array_almost_equal(y, fft(x, axis=-1, n=8))
+
+ # Change shape of an arbitrary axis which is not the last one
+ x = numpy.random.random((10, 5, 3, 7))
+ y = fftn(x, axes=(-2,), s=(8,))
+ assert_array_almost_equal(y, fft(x, axis=-2, n=8))
+
+ # Change shape of axes: cf #244, where shape and axes were mixed up
+ x = numpy.random.random((4, 4, 2))
+ y = fftn(x, axes=(-3, -2), s=(8, 8))
+ assert_array_almost_equal(y,
+ numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
+
+ def test_shape_argument_more(self):
+ x = zeros((4, 4, 2))
+ with assert_raises(ValueError,
+ match="shape requires more axes than are present"):
+ fftn(x, s=(8, 8, 2, 1))
+
+ def test_invalid_sizes(self):
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[1, 0\]\) specified"):
+ fftn([[]])
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[4, -3\]\) specified"):
+ fftn([[1, 1], [2, 2]], (4, -3))
+
+ def test_no_axes(self):
+ x = numpy.random.random((2,2,2))
+ assert_allclose(fftn(x, axes=[]), x, atol=1e-7)
+
+ def test_regression_244(self):
+ """FFT returns wrong result with axes parameter."""
+ # fftn (and hence fft2) used to break when both axes and shape were used
+ x = numpy.ones((4, 4, 2))
+ y = fftn(x, s=(8, 8), axes=(-3, -2))
+ y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
+ assert_allclose(y, y_r)
+
+
+class TestIfftn:
+ dtype = None
+ cdtype = None
+
+ def setup_method(self):
+ np.random.seed(1234)
+
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+ [(np.float64, np.complex128, 2000),
+ (np.float32, np.complex64, 3500)])
+ def test_definition(self, dtype, cdtype, maxnlp):
+ rng = np.random.default_rng(1234)
+ x = np.array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]], dtype=dtype)
+ y = ifftn(x)
+ assert_equal(y.dtype, cdtype)
+ assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
+
+ x = rng.random((20, 26))
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+ x = rng.random((5, 4, 3, 20))
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+ @pytest.mark.parametrize('maxnlp', [2000, 3500])
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+ def test_random_complex(self, maxnlp, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random([size, size]) + 1j * rng.random([size, size])
+ assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
+ assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
+
+ def test_invalid_sizes(self):
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[1, 0\]\) specified"):
+ ifftn([[]])
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[4, -3\]\) specified"):
+ ifftn([[1, 1], [2, 2]], (4, -3))
+
+ def test_no_axes(self):
+ x = numpy.random.random((2,2,2))
+ assert_allclose(ifftn(x, axes=[]), x, atol=1e-7)
+
+class TestRfftn:
+ dtype = None
+ cdtype = None
+
+ def setup_method(self):
+ np.random.seed(1234)
+
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+ [(np.float64, np.complex128, 2000),
+ (np.float32, np.complex64, 3500)])
+ def test_definition(self, dtype, cdtype, maxnlp):
+ rng = np.random.default_rng(1234)
+ x = np.array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]], dtype=dtype)
+ y = rfftn(x)
+ assert_equal(y.dtype, cdtype)
+ assert_array_almost_equal_nulp(y, direct_rdftn(x), maxnlp)
+
+ x = rng.random((20, 26))
+ assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
+
+ x = rng.random((5, 4, 3, 20))
+ assert_array_almost_equal_nulp(rfftn(x), direct_rdftn(x), maxnlp)
+
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+ def test_random(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random([size, size])
+ assert_allclose(irfftn(rfftn(x), x.shape), x, atol=1e-10)
+
+ @pytest.mark.parametrize('func', [rfftn, irfftn])
+ def test_invalid_sizes(self, func):
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[1, 0\]\) specified"):
+ func([[]])
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[4, -3\]\) specified"):
+ func([[1, 1], [2, 2]], (4, -3))
+
+ @pytest.mark.parametrize('func', [rfftn, irfftn])
+ def test_no_axes(self, func):
+ with assert_raises(ValueError,
+ match="at least 1 axis must be transformed"):
+ func([], axes=[])
+
+ def test_complex_input(self):
+ with assert_raises(TypeError, match="x must be a real sequence"):
+ rfftn(np.zeros(10, dtype=np.complex64))
+
+
+class FakeArray:
+ def __init__(self, data):
+ self._data = data
+ self.__array_interface__ = data.__array_interface__
+
+
+class FakeArray2:
+ def __init__(self, data):
+ self._data = data
+
+ def __array__(self, dtype=None, copy=None):
+ return self._data
+
+# TODO: Is this test actually valuable? The behavior it's testing shouldn't be
+# relied upon by users except for overwrite_x = False
+class TestOverwrite:
+ """Check input overwrite behavior of the FFT functions."""
+
+ real_dtypes = [np.float32, np.float64, np.longdouble]
+ dtypes = real_dtypes + [np.complex64, np.complex128, np.clongdouble]
+ fftsizes = [8, 16, 32]
+
+ def _check(self, x, routine, fftsize, axis, overwrite_x, should_overwrite):
+ x2 = x.copy()
+ for fake in [lambda x: x, FakeArray, FakeArray2]:
+ routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
+
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+ f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+ if not should_overwrite:
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+ def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
+ fftsize, overwrite_x):
+ np.random.seed(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+ else:
+ data = np.random.randn(*shape)
+ data = data.astype(dtype)
+
+ should_overwrite = (overwrite_x
+ and dtype in overwritable_dtypes
+ and fftsize <= shape[axis])
+ self._check(data, routine, fftsize, axis,
+ overwrite_x=overwrite_x,
+ should_overwrite=should_overwrite)
+
+ @pytest.mark.parametrize('dtype', dtypes)
+ @pytest.mark.parametrize('fftsize', fftsizes)
+ @pytest.mark.parametrize('overwrite_x', [True, False])
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
+ ((16, 2), 0),
+ ((2, 16), 1)])
+ def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
+ overwritable = (np.clongdouble, np.complex128, np.complex64)
+ self._check_1d(fft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+ self._check_1d(ifft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+
+ @pytest.mark.parametrize('dtype', real_dtypes)
+ @pytest.mark.parametrize('fftsize', fftsizes)
+ @pytest.mark.parametrize('overwrite_x', [True, False])
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
+ ((16, 2), 0),
+ ((2, 16), 1)])
+ def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
+ overwritable = self.real_dtypes
+ self._check_1d(irfft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+ self._check_1d(rfft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+
+ def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
+ overwrite_x):
+ np.random.seed(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+ else:
+ data = np.random.randn(*shape)
+ data = data.astype(dtype)
+
+ def fftshape_iter(shp):
+ if len(shp) <= 0:
+ yield ()
+ else:
+ for j in (shp[0]//2, shp[0], shp[0]*2):
+ for rest in fftshape_iter(shp[1:]):
+ yield (j,) + rest
+
+ def part_shape(shape, axes):
+ if axes is None:
+ return shape
+ else:
+ return tuple(np.take(shape, axes))
+
+ def should_overwrite(data, shape, axes):
+ s = part_shape(data.shape, axes)
+ return (overwrite_x and
+ np.prod(shape) <= np.prod(s)
+ and dtype in overwritable_dtypes)
+
+ for fftshape in fftshape_iter(part_shape(shape, axes)):
+ self._check(data, routine, fftshape, axes,
+ overwrite_x=overwrite_x,
+ should_overwrite=should_overwrite(data, fftshape, axes))
+ if data.ndim > 1:
+ # check fortran order
+ self._check(data.T, routine, fftshape, axes,
+ overwrite_x=overwrite_x,
+ should_overwrite=should_overwrite(
+ data.T, fftshape, axes))
+
+ @pytest.mark.parametrize('dtype', dtypes)
+ @pytest.mark.parametrize('overwrite_x', [True, False])
+ @pytest.mark.parametrize('shape,axes', [((16,), None),
+ ((16,), (0,)),
+ ((16, 2), (0,)),
+ ((2, 16), (1,)),
+ ((8, 16), None),
+ ((8, 16), (0, 1)),
+ ((8, 16, 2), (0, 1)),
+ ((8, 16, 2), (1, 2)),
+ ((8, 16, 2), (0,)),
+ ((8, 16, 2), (1,)),
+ ((8, 16, 2), (2,)),
+ ((8, 16, 2), None),
+ ((8, 16, 2), (0, 1, 2))])
+ def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
+ overwritable = (np.clongdouble, np.complex128, np.complex64)
+ self._check_nd_one(fftn, dtype, shape, axes, overwritable,
+ overwrite_x)
+ self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
+ overwrite_x)
+
+
+@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
+ rfft, irfft, rfftn, irfftn])
+def test_invalid_norm(func):
+ x = np.arange(10, dtype=float)
+ with assert_raises(ValueError,
+ match='Invalid norm value \'o\', should be'
+ ' "backward", "ortho" or "forward"'):
+ func(x, norm='o')
+
+
+@pytest.mark.parametrize('func', [fft, ifft, fftn, ifftn,
+ irfft, irfftn, hfft, hfftn])
+def test_swapped_byte_order_complex(func):
+ rng = np.random.RandomState(1234)
+ x = rng.rand(10) + 1j * rng.rand(10)
+ assert_allclose(func(swap_byteorder(x)), func(x))
+
+
+@pytest.mark.parametrize('func', [ihfft, ihfftn, rfft, rfftn])
+def test_swapped_byte_order_real(func):
+ rng = np.random.RandomState(1234)
+ x = rng.rand(10)
+ assert_allclose(func(swap_byteorder(x)), func(x))
diff --git a/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..c86ea9e4c0a5ba6201faca6f22a1b33ffb104288
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/_pocketfft/tests/test_real_transforms.py
@@ -0,0 +1,505 @@
+from os.path import join, dirname
+from collections.abc import Callable
+from threading import Lock
+
+import numpy as np
+from numpy.testing import (
+ assert_array_almost_equal, assert_equal, assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fft._pocketfft.realtransforms import (
+ dct, idct, dst, idst, dctn, idctn, dstn, idstn)
+
+fftpack_test_dir = join(dirname(__file__), '..', '..', '..', 'fftpack', 'tests')
+
+MDATA_COUNT = 8
+FFTWDATA_COUNT = 14
+
+def is_longdouble_binary_compatible():
+ try:
+ one = np.frombuffer(
+ b'\x00\x00\x00\x00\x00\x00\x00\x80\xff\x3f\x00\x00\x00\x00\x00\x00',
+ dtype=' decimal
+dec_map: DecMapType = {
+ # DCT
+ (dct, np.float64, 1): 13,
+ (dct, np.float32, 1): 6,
+
+ (dct, np.float64, 2): 14,
+ (dct, np.float32, 2): 5,
+
+ (dct, np.float64, 3): 14,
+ (dct, np.float32, 3): 5,
+
+ (dct, np.float64, 4): 13,
+ (dct, np.float32, 4): 6,
+
+ # IDCT
+ (idct, np.float64, 1): 14,
+ (idct, np.float32, 1): 6,
+
+ (idct, np.float64, 2): 14,
+ (idct, np.float32, 2): 5,
+
+ (idct, np.float64, 3): 14,
+ (idct, np.float32, 3): 5,
+
+ (idct, np.float64, 4): 14,
+ (idct, np.float32, 4): 6,
+
+ # DST
+ (dst, np.float64, 1): 13,
+ (dst, np.float32, 1): 6,
+
+ (dst, np.float64, 2): 14,
+ (dst, np.float32, 2): 6,
+
+ (dst, np.float64, 3): 14,
+ (dst, np.float32, 3): 7,
+
+ (dst, np.float64, 4): 13,
+ (dst, np.float32, 4): 5,
+
+ # IDST
+ (idst, np.float64, 1): 14,
+ (idst, np.float32, 1): 6,
+
+ (idst, np.float64, 2): 14,
+ (idst, np.float32, 2): 6,
+
+ (idst, np.float64, 3): 14,
+ (idst, np.float32, 3): 6,
+
+ (idst, np.float64, 4): 14,
+ (idst, np.float32, 4): 6,
+}
+
+for k,v in dec_map.copy().items():
+ if k[1] == np.float64:
+ dec_map[(k[0], np.longdouble, k[2])] = v
+ elif k[1] == np.float32:
+ dec_map[(k[0], int, k[2])] = v
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+class TestDCT:
+ def test_definition(self, rdt, type, fftwdata_size,
+ reference_data, ref_lock):
+ with ref_lock:
+ x, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
+ y = dct(x, type=type)
+ assert_equal(y.dtype, dt)
+ dec = dec_map[(dct, rdt, type)]
+ assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
+
+ @pytest.mark.parametrize('size', [7, 8, 9, 16, 32, 64])
+ def test_axis(self, rdt, type, size):
+ nt = 2
+ dec = dec_map[(dct, rdt, type)]
+ x = np.random.randn(nt, size)
+ y = dct(x, type=type)
+ for j in range(nt):
+ assert_array_almost_equal(y[j], dct(x[j], type=type),
+ decimal=dec)
+
+ x = x.T
+ y = dct(x, axis=0, type=type)
+ for j in range(nt):
+ assert_array_almost_equal(y[:,j], dct(x[:,j], type=type),
+ decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct1_definition_ortho(rdt, mdata_x):
+ # Test orthornomal mode.
+ dec = dec_map[(dct, rdt, 1)]
+ x = np.array(mdata_x, dtype=rdt)
+ dt = np.result_type(np.float32, rdt)
+ y = dct(x, norm='ortho', type=1)
+ y2 = naive_dct1(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct2_definition_matlab(mdata_xy, rdt):
+ # Test correspondence with matlab (orthornomal mode).
+ dt = np.result_type(np.float32, rdt)
+ x = np.array(mdata_xy[0], dtype=dt)
+
+ yr = mdata_xy[1]
+ y = dct(x, norm="ortho", type=2)
+ dec = dec_map[(dct, rdt, 2)]
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y, yr, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct3_definition_ortho(mdata_x, rdt):
+ # Test orthornomal mode.
+ x = np.array(mdata_x, dtype=rdt)
+ dt = np.result_type(np.float32, rdt)
+ y = dct(x, norm='ortho', type=2)
+ xi = dct(y, norm="ortho", type=3)
+ dec = dec_map[(dct, rdt, 3)]
+ assert_equal(xi.dtype, dt)
+ assert_array_almost_equal(xi, x, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dct4_definition_ortho(mdata_x, rdt):
+ # Test orthornomal mode.
+ x = np.array(mdata_x, dtype=rdt)
+ dt = np.result_type(np.float32, rdt)
+ y = dct(x, norm='ortho', type=4)
+ y2 = naive_dct4(x, norm='ortho')
+ dec = dec_map[(dct, rdt, 4)]
+ assert_equal(y.dtype, dt)
+ assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_idct_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+ with ref_lock:
+ xr, yr, dt = fftw_dct_ref(type, fftwdata_size, rdt, reference_data)
+ x = idct(yr, type=type)
+ dec = dec_map[(idct, rdt, type)]
+ assert_equal(x.dtype, dt)
+ assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+ with ref_lock:
+ xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
+ y = dst(xr, type=type)
+ dec = dec_map[(dst, rdt, type)]
+ assert_equal(y.dtype, dt)
+ assert_allclose(y, yr, rtol=0., atol=np.max(yr)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dst1_definition_ortho(rdt, mdata_x):
+ # Test orthornomal mode.
+ dec = dec_map[(dst, rdt, 1)]
+ x = np.array(mdata_x, dtype=rdt)
+ dt = np.result_type(np.float32, rdt)
+ y = dst(x, norm='ortho', type=1)
+ y2 = naive_dst1(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_allclose(y, y2, rtol=0., atol=np.max(y2)*10**(-dec))
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+def test_dst4_definition_ortho(rdt, mdata_x):
+ # Test orthornomal mode.
+ dec = dec_map[(dst, rdt, 4)]
+ x = np.array(mdata_x, dtype=rdt)
+ dt = np.result_type(np.float32, rdt)
+ y = dst(x, norm='ortho', type=4)
+ y2 = naive_dst4(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y, y2, decimal=dec)
+
+
+@pytest.mark.parametrize('rdt', [np.longdouble, np.float64, np.float32, int])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+def test_idst_definition(fftwdata_size, rdt, type, reference_data, ref_lock):
+ with ref_lock:
+ xr, yr, dt = fftw_dst_ref(type, fftwdata_size, rdt, reference_data)
+ x = idst(yr, type=type)
+ dec = dec_map[(idst, rdt, type)]
+ assert_equal(x.dtype, dt)
+ assert_allclose(x, xr, rtol=0., atol=np.max(xr)*10**(-dec))
+
+
+@pytest.mark.parametrize('routine', [dct, dst, idct, idst])
+@pytest.mark.parametrize('dtype', [np.float32, np.float64, np.longdouble])
+@pytest.mark.parametrize('shape, axis', [
+ ((16,), -1), ((16, 2), 0), ((2, 16), 1)
+])
+@pytest.mark.parametrize('type', [1, 2, 3, 4])
+@pytest.mark.parametrize('overwrite_x', [True, False])
+@pytest.mark.parametrize('norm', [None, 'ortho'])
+def test_overwrite(routine, dtype, shape, axis, type, norm, overwrite_x):
+ # Check input overwrite behavior
+ np.random.seed(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ x = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+ else:
+ x = np.random.randn(*shape)
+ x = x.astype(dtype)
+ x2 = x.copy()
+ routine(x2, type, None, axis, norm, overwrite_x=overwrite_x)
+
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {None!r}, axis={axis!r}, "
+ f"overwrite_x={overwrite_x!r})")
+ if not overwrite_x:
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+
+class Test_DCTN_IDCTN:
+ dec = 14
+ dct_type = [1, 2, 3, 4]
+ norms = [None, 'backward', 'ortho', 'forward']
+ rstate = np.random.RandomState(1234)
+ shape = (32, 16)
+ data = rstate.randn(*shape)
+
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+ (dstn, idstn)])
+ @pytest.mark.parametrize('axes', [None,
+ 1, (1,), [1],
+ 0, (0,), [0],
+ (0, 1), [0, 1],
+ (-2, -1), [-2, -1]])
+ @pytest.mark.parametrize('dct_type', dct_type)
+ @pytest.mark.parametrize('norm', ['ortho'])
+ def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
+ tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
+ tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
+ assert_array_almost_equal(self.data, tmp, decimal=12)
+
+ @pytest.mark.parametrize('funcn,func', [(dctn, dct), (dstn, dst)])
+ @pytest.mark.parametrize('dct_type', dct_type)
+ @pytest.mark.parametrize('norm', norms)
+ def test_dctn_vs_2d_reference(self, funcn, func, dct_type, norm):
+ y1 = funcn(self.data, type=dct_type, axes=None, norm=norm)
+ y2 = ref_2d(func, self.data, type=dct_type, norm=norm)
+ assert_array_almost_equal(y1, y2, decimal=11)
+
+ @pytest.mark.parametrize('funcn,func', [(idctn, idct), (idstn, idst)])
+ @pytest.mark.parametrize('dct_type', dct_type)
+ @pytest.mark.parametrize('norm', norms)
+ def test_idctn_vs_2d_reference(self, funcn, func, dct_type, norm):
+ fdata = dctn(self.data, type=dct_type, norm=norm)
+ y1 = funcn(fdata, type=dct_type, norm=norm)
+ y2 = ref_2d(func, fdata, type=dct_type, norm=norm)
+ assert_array_almost_equal(y1, y2, decimal=11)
+
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+ (dstn, idstn)])
+ def test_axes_and_shape(self, fforward, finverse):
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ fforward(self.data, s=self.data.shape[0], axes=(0, 1))
+
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ fforward(self.data, s=self.data.shape, axes=0)
+
+ @pytest.mark.parametrize('fforward', [dctn, dstn])
+ def test_shape(self, fforward):
+ tmp = fforward(self.data, s=(128, 128), axes=None)
+ assert_equal(tmp.shape, (128, 128))
+
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+ (dstn, idstn)])
+ @pytest.mark.parametrize('axes', [1, (1,), [1],
+ 0, (0,), [0]])
+ def test_shape_is_none_with_axes(self, fforward, finverse, axes):
+ tmp = fforward(self.data, s=None, axes=axes, norm='ortho')
+ tmp = finverse(tmp, s=None, axes=axes, norm='ortho')
+ assert_array_almost_equal(self.data, tmp, decimal=self.dec)
+
+
+@pytest.mark.parametrize('func', [dct, dctn, idct, idctn,
+ dst, dstn, idst, idstn])
+def test_swapped_byte_order(func):
+ rng = np.random.RandomState(1234)
+ x = rng.rand(10)
+ swapped_dt = x.dtype.newbyteorder('S')
+ assert_allclose(func(x.astype(swapped_dt)), func(x))
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/fft/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/mock_backend.py b/python_embeded/Lib/site-packages/scipy/fft/tests/mock_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..73b7c31d12378c23f6f12d2ff3e6ee9503a7ec29
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/mock_backend.py
@@ -0,0 +1,96 @@
+import numpy as np
+import scipy.fft
+import threading
+
+class _MockFunction:
+ def __init__(self, return_value = None):
+ self.number_calls = threading.local()
+ self.return_value = return_value
+ self.last_args = threading.local()
+
+ def __call__(self, *args, **kwargs):
+ if not hasattr(self.number_calls, 'c'):
+ self.number_calls.c = 0
+
+ self.number_calls.c += 1
+ self.last_args.l = (args, kwargs)
+ return self.return_value
+
+
+fft = _MockFunction(np.random.random(10))
+fft2 = _MockFunction(np.random.random(10))
+fftn = _MockFunction(np.random.random(10))
+
+ifft = _MockFunction(np.random.random(10))
+ifft2 = _MockFunction(np.random.random(10))
+ifftn = _MockFunction(np.random.random(10))
+
+rfft = _MockFunction(np.random.random(10))
+rfft2 = _MockFunction(np.random.random(10))
+rfftn = _MockFunction(np.random.random(10))
+
+irfft = _MockFunction(np.random.random(10))
+irfft2 = _MockFunction(np.random.random(10))
+irfftn = _MockFunction(np.random.random(10))
+
+hfft = _MockFunction(np.random.random(10))
+hfft2 = _MockFunction(np.random.random(10))
+hfftn = _MockFunction(np.random.random(10))
+
+ihfft = _MockFunction(np.random.random(10))
+ihfft2 = _MockFunction(np.random.random(10))
+ihfftn = _MockFunction(np.random.random(10))
+
+dct = _MockFunction(np.random.random(10))
+idct = _MockFunction(np.random.random(10))
+dctn = _MockFunction(np.random.random(10))
+idctn = _MockFunction(np.random.random(10))
+
+dst = _MockFunction(np.random.random(10))
+idst = _MockFunction(np.random.random(10))
+dstn = _MockFunction(np.random.random(10))
+idstn = _MockFunction(np.random.random(10))
+
+fht = _MockFunction(np.random.random(10))
+ifht = _MockFunction(np.random.random(10))
+
+
+__ua_domain__ = "numpy.scipy.fft"
+
+
+_implements = {
+ scipy.fft.fft: fft,
+ scipy.fft.fft2: fft2,
+ scipy.fft.fftn: fftn,
+ scipy.fft.ifft: ifft,
+ scipy.fft.ifft2: ifft2,
+ scipy.fft.ifftn: ifftn,
+ scipy.fft.rfft: rfft,
+ scipy.fft.rfft2: rfft2,
+ scipy.fft.rfftn: rfftn,
+ scipy.fft.irfft: irfft,
+ scipy.fft.irfft2: irfft2,
+ scipy.fft.irfftn: irfftn,
+ scipy.fft.hfft: hfft,
+ scipy.fft.hfft2: hfft2,
+ scipy.fft.hfftn: hfftn,
+ scipy.fft.ihfft: ihfft,
+ scipy.fft.ihfft2: ihfft2,
+ scipy.fft.ihfftn: ihfftn,
+ scipy.fft.dct: dct,
+ scipy.fft.idct: idct,
+ scipy.fft.dctn: dctn,
+ scipy.fft.idctn: idctn,
+ scipy.fft.dst: dst,
+ scipy.fft.idst: idst,
+ scipy.fft.dstn: dstn,
+ scipy.fft.idstn: idstn,
+ scipy.fft.fht: fht,
+ scipy.fft.ifht: ifht
+}
+
+
+def __ua_function__(method, args, kwargs):
+ fn = _implements.get(method)
+ return (fn(*args, **kwargs) if fn is not None
+ else NotImplemented)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/test_backend.py b/python_embeded/Lib/site-packages/scipy/fft/tests/test_backend.py
new file mode 100644
index 0000000000000000000000000000000000000000..1fe89acd12f6b2f2e2cfa7d026455a9b281adf43
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/test_backend.py
@@ -0,0 +1,98 @@
+from functools import partial
+
+import numpy as np
+import scipy.fft
+from scipy.fft import _fftlog, _pocketfft, set_backend
+from scipy.fft.tests import mock_backend
+
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+fnames = ('fft', 'fft2', 'fftn',
+ 'ifft', 'ifft2', 'ifftn',
+ 'rfft', 'rfft2', 'rfftn',
+ 'irfft', 'irfft2', 'irfftn',
+ 'dct', 'idct', 'dctn', 'idctn',
+ 'dst', 'idst', 'dstn', 'idstn',
+ 'fht', 'ifht')
+
+np_funcs = (np.fft.fft, np.fft.fft2, np.fft.fftn,
+ np.fft.ifft, np.fft.ifft2, np.fft.ifftn,
+ np.fft.rfft, np.fft.rfft2, np.fft.rfftn,
+ np.fft.irfft, np.fft.irfft2, np.fft.irfftn,
+ np.fft.hfft, _pocketfft.hfft2, _pocketfft.hfftn, # np has no hfftn
+ np.fft.ihfft, _pocketfft.ihfft2, _pocketfft.ihfftn,
+ _pocketfft.dct, _pocketfft.idct, _pocketfft.dctn, _pocketfft.idctn,
+ _pocketfft.dst, _pocketfft.idst, _pocketfft.dstn, _pocketfft.idstn,
+ # must provide required kwargs for fht, ifht
+ partial(_fftlog.fht, dln=2, mu=0.5),
+ partial(_fftlog.ifht, dln=2, mu=0.5))
+
+funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
+ scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
+ scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
+ scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
+ scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
+ scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn,
+ scipy.fft.dct, scipy.fft.idct, scipy.fft.dctn, scipy.fft.idctn,
+ scipy.fft.dst, scipy.fft.idst, scipy.fft.dstn, scipy.fft.idstn,
+ # must provide required kwargs for fht, ifht
+ partial(scipy.fft.fht, dln=2, mu=0.5),
+ partial(scipy.fft.ifht, dln=2, mu=0.5))
+
+mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
+ mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
+ mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
+ mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
+ mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
+ mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn,
+ mock_backend.dct, mock_backend.idct,
+ mock_backend.dctn, mock_backend.idctn,
+ mock_backend.dst, mock_backend.idst,
+ mock_backend.dstn, mock_backend.idstn,
+ mock_backend.fht, mock_backend.ifht)
+
+
+@pytest.mark.parametrize("func, np_func, mock", zip(funcs, np_funcs, mocks))
+def test_backend_call(func, np_func, mock):
+ x = np.arange(20).reshape((10,2))
+ answer = np_func(x.astype(np.float64))
+ assert_allclose(func(x), answer, atol=1e-10)
+
+ with set_backend(mock_backend, only=True):
+ mock.number_calls.c = 0
+ y = func(x)
+ assert_equal(y, mock.return_value)
+ assert_equal(mock.number_calls.c, 1)
+
+ assert_allclose(func(x), answer, atol=1e-10)
+
+
+plan_funcs = (scipy.fft.fft, scipy.fft.fft2, scipy.fft.fftn,
+ scipy.fft.ifft, scipy.fft.ifft2, scipy.fft.ifftn,
+ scipy.fft.rfft, scipy.fft.rfft2, scipy.fft.rfftn,
+ scipy.fft.irfft, scipy.fft.irfft2, scipy.fft.irfftn,
+ scipy.fft.hfft, scipy.fft.hfft2, scipy.fft.hfftn,
+ scipy.fft.ihfft, scipy.fft.ihfft2, scipy.fft.ihfftn)
+
+plan_mocks = (mock_backend.fft, mock_backend.fft2, mock_backend.fftn,
+ mock_backend.ifft, mock_backend.ifft2, mock_backend.ifftn,
+ mock_backend.rfft, mock_backend.rfft2, mock_backend.rfftn,
+ mock_backend.irfft, mock_backend.irfft2, mock_backend.irfftn,
+ mock_backend.hfft, mock_backend.hfft2, mock_backend.hfftn,
+ mock_backend.ihfft, mock_backend.ihfft2, mock_backend.ihfftn)
+
+
+@pytest.mark.parametrize("func, mock", zip(plan_funcs, plan_mocks))
+def test_backend_plan(func, mock):
+ x = np.arange(20).reshape((10, 2))
+
+ with pytest.raises(NotImplementedError, match='precomputed plan'):
+ func(x, plan='foo')
+
+ with set_backend(mock_backend, only=True):
+ mock.number_calls.c = 0
+ y = func(x, plan='foo')
+ assert_equal(y, mock.return_value)
+ assert_equal(mock.number_calls.c, 1)
+ assert_equal(mock.last_args.l[1]['plan'], 'foo')
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/test_basic.py b/python_embeded/Lib/site-packages/scipy/fft/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..eecf0c1dc2e1ec6203aabb358dac49b96f465c52
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/test_basic.py
@@ -0,0 +1,502 @@
+import queue
+import threading
+import multiprocessing
+import numpy as np
+import pytest
+from numpy.random import random
+from numpy.testing import assert_array_almost_equal, assert_allclose
+from pytest import raises as assert_raises
+import scipy.fft as fft
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+ array_namespace, xp_size, xp_assert_close, xp_assert_equal
+)
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+# Expected input dtypes. Note that `scipy.fft` is more flexible for numpy,
+# but for C2C transforms like `fft.fft`, the array API standard only mandates
+# that complex dtypes should work, float32/float64 aren't guaranteed to.
+def get_expected_input_dtype(func, xp):
+ if func in [fft.fft, fft.fftn, fft.fft2,
+ fft.ifft, fft.ifftn, fft.ifft2,
+ fft.hfft, fft.hfftn, fft.hfft2,
+ fft.irfft, fft.irfftn, fft.irfft2]:
+ dtype = xp.complex128
+ elif func in [fft.rfft, fft.rfftn, fft.rfft2,
+ fft.ihfft, fft.ihfftn, fft.ihfft2]:
+ dtype = xp.float64
+ else:
+ raise ValueError(f'Unknown FFT function: {func}')
+
+ return dtype
+
+
+def fft1(x):
+ L = len(x)
+ phase = -2j*np.pi*(np.arange(L)/float(L))
+ phase = np.arange(L).reshape(-1, 1) * phase
+ return np.sum(x*np.exp(phase), axis=1)
+
+class TestFFT:
+
+ def test_identity(self, xp):
+ maxlen = 512
+ x = xp.asarray(random(maxlen) + 1j*random(maxlen))
+ xr = xp.asarray(random(maxlen))
+ # Check some powers of 2 and some primes
+ for i in [1, 2, 16, 128, 512, 53, 149, 281, 397]:
+ xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
+ xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
+
+ @skip_xp_backends(np_only=True, reason='significant overhead for some backends')
+ def test_identity_extensive(self, xp):
+ maxlen = 512
+ x = xp.asarray(random(maxlen) + 1j*random(maxlen))
+ xr = xp.asarray(random(maxlen))
+ for i in range(1, maxlen):
+ xp_assert_close(fft.ifft(fft.fft(x[0:i])), x[0:i])
+ xp_assert_close(fft.irfft(fft.rfft(xr[0:i]), i), xr[0:i])
+
+ def test_fft(self, xp):
+ x = random(30) + 1j*random(30)
+ expect = xp.asarray(fft1(x))
+ x = xp.asarray(x)
+ xp_assert_close(fft.fft(x), expect)
+ xp_assert_close(fft.fft(x, norm="backward"), expect)
+ xp_assert_close(fft.fft(x, norm="ortho"),
+ expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)),)
+ xp_assert_close(fft.fft(x, norm="forward"), expect / 30)
+
+ @skip_xp_backends(np_only=True, reason='some backends allow `n=0`')
+ def test_fft_n(self, xp):
+ x = xp.asarray([1, 2, 3], dtype=xp.complex128)
+ assert_raises(ValueError, fft.fft, x, 0)
+
+ def test_ifft(self, xp):
+ x = xp.asarray(random(30) + 1j*random(30))
+ xp_assert_close(fft.ifft(fft.fft(x)), x)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.ifft(fft.fft(x, norm=norm), norm=norm), x)
+
+ def test_fft2(self, xp):
+ x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
+ expect = fft.fft(fft.fft(x, axis=1), axis=0)
+ xp_assert_close(fft.fft2(x), expect)
+ xp_assert_close(fft.fft2(x, norm="backward"), expect)
+ xp_assert_close(fft.fft2(x, norm="ortho"),
+ expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+ xp_assert_close(fft.fft2(x, norm="forward"), expect / (30 * 20))
+
+ def test_ifft2(self, xp):
+ x = xp.asarray(random((30, 20)) + 1j*random((30, 20)))
+ expect = fft.ifft(fft.ifft(x, axis=1), axis=0)
+ xp_assert_close(fft.ifft2(x), expect)
+ xp_assert_close(fft.ifft2(x, norm="backward"), expect)
+ xp_assert_close(fft.ifft2(x, norm="ortho"),
+ expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+ xp_assert_close(fft.ifft2(x, norm="forward"), expect * (30 * 20))
+
+ def test_fftn(self, xp):
+ x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
+ expect = fft.fft(fft.fft(fft.fft(x, axis=2), axis=1), axis=0)
+ xp_assert_close(fft.fftn(x), expect)
+ xp_assert_close(fft.fftn(x, norm="backward"), expect)
+ xp_assert_close(fft.fftn(x, norm="ortho"),
+ expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
+ xp_assert_close(fft.fftn(x, norm="forward"), expect / (30 * 20 * 10))
+
+ def test_ifftn(self, xp):
+ x = xp.asarray(random((30, 20, 10)) + 1j*random((30, 20, 10)))
+ expect = fft.ifft(fft.ifft(fft.ifft(x, axis=2), axis=1), axis=0)
+ xp_assert_close(fft.ifftn(x), expect, rtol=1e-7)
+ xp_assert_close(fft.ifftn(x, norm="backward"), expect, rtol=1e-7)
+ xp_assert_close(
+ fft.ifftn(x, norm="ortho"),
+ fft.ifftn(x) * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
+ )
+ xp_assert_close(fft.ifftn(x, norm="forward"),
+ expect * (30 * 20 * 10),
+ rtol=1e-7)
+
+ def test_rfft(self, xp):
+ x = xp.asarray(random(29), dtype=xp.float64)
+ for n in [xp_size(x), 2*xp_size(x)]:
+ for norm in [None, "backward", "ortho", "forward"]:
+ xp_assert_close(fft.rfft(x, n=n, norm=norm),
+ fft.fft(xp.asarray(x, dtype=xp.complex128),
+ n=n, norm=norm)[:(n//2 + 1)])
+ xp_assert_close(
+ fft.rfft(x, n=n, norm="ortho"),
+ fft.rfft(x, n=n) / xp.sqrt(xp.asarray(n, dtype=xp.float64))
+ )
+
+ def test_irfft(self, xp):
+ x = xp.asarray(random(30))
+ xp_assert_close(fft.irfft(fft.rfft(x)), x)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.irfft(fft.rfft(x, norm=norm), norm=norm), x)
+
+ def test_rfft2(self, xp):
+ x = xp.asarray(random((30, 20)), dtype=xp.float64)
+ expect = fft.fft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
+ xp_assert_close(fft.rfft2(x), expect)
+ xp_assert_close(fft.rfft2(x, norm="backward"), expect)
+ xp_assert_close(fft.rfft2(x, norm="ortho"),
+ expect / xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64)))
+ xp_assert_close(fft.rfft2(x, norm="forward"), expect / (30 * 20))
+
+ def test_irfft2(self, xp):
+ x = xp.asarray(random((30, 20)))
+ xp_assert_close(fft.irfft2(fft.rfft2(x)), x)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.irfft2(fft.rfft2(x, norm=norm), norm=norm), x)
+
+ def test_rfftn(self, xp):
+ x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
+ expect = fft.fftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
+ xp_assert_close(fft.rfftn(x), expect)
+ xp_assert_close(fft.rfftn(x, norm="backward"), expect)
+ xp_assert_close(fft.rfftn(x, norm="ortho"),
+ expect / xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64)))
+ xp_assert_close(fft.rfftn(x, norm="forward"), expect / (30 * 20 * 10))
+
+ def test_irfftn(self, xp):
+ x = xp.asarray(random((30, 20, 10)))
+ xp_assert_close(fft.irfftn(fft.rfftn(x)), x)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.irfftn(fft.rfftn(x, norm=norm), norm=norm), x)
+
+ def test_hfft(self, xp):
+ x = random(14) + 1j*random(14)
+ x_herm = np.concatenate((random(1), x, random(1)))
+ x = np.concatenate((x_herm, x[::-1].conj()))
+ x = xp.asarray(x)
+ x_herm = xp.asarray(x_herm)
+ expect = xp.real(fft.fft(x))
+ xp_assert_close(fft.hfft(x_herm), expect)
+ xp_assert_close(fft.hfft(x_herm, norm="backward"), expect)
+ xp_assert_close(fft.hfft(x_herm, norm="ortho"),
+ expect / xp.sqrt(xp.asarray(30, dtype=xp.float64)))
+ xp_assert_close(fft.hfft(x_herm, norm="forward"), expect / 30)
+
+ def test_ihfft(self, xp):
+ x = random(14) + 1j*random(14)
+ x_herm = np.concatenate((random(1), x, random(1)))
+ x = np.concatenate((x_herm, x[::-1].conj()))
+ x = xp.asarray(x)
+ x_herm = xp.asarray(x_herm)
+ xp_assert_close(fft.ihfft(fft.hfft(x_herm)), x_herm)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.ihfft(fft.hfft(x_herm, norm=norm), norm=norm), x_herm)
+
+ def test_hfft2(self, xp):
+ x = xp.asarray(random((30, 20)))
+ xp_assert_close(fft.hfft2(fft.ihfft2(x)), x)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.hfft2(fft.ihfft2(x, norm=norm), norm=norm), x)
+
+ def test_ihfft2(self, xp):
+ x = xp.asarray(random((30, 20)), dtype=xp.float64)
+ expect = fft.ifft2(xp.asarray(x, dtype=xp.complex128))[:, :11]
+ xp_assert_close(fft.ihfft2(x), expect)
+ xp_assert_close(fft.ihfft2(x, norm="backward"), expect)
+ xp_assert_close(
+ fft.ihfft2(x, norm="ortho"),
+ expect * xp.sqrt(xp.asarray(30 * 20, dtype=xp.float64))
+ )
+ xp_assert_close(fft.ihfft2(x, norm="forward"), expect * (30 * 20))
+
+ def test_hfftn(self, xp):
+ x = xp.asarray(random((30, 20, 10)))
+ xp_assert_close(fft.hfftn(fft.ihfftn(x)), x)
+ for norm in ["backward", "ortho", "forward"]:
+ xp_assert_close(fft.hfftn(fft.ihfftn(x, norm=norm), norm=norm), x)
+
+ def test_ihfftn(self, xp):
+ x = xp.asarray(random((30, 20, 10)), dtype=xp.float64)
+ expect = fft.ifftn(xp.asarray(x, dtype=xp.complex128))[:, :, :6]
+ xp_assert_close(expect, fft.ihfftn(x))
+ xp_assert_close(expect, fft.ihfftn(x, norm="backward"))
+ xp_assert_close(
+ fft.ihfftn(x, norm="ortho"),
+ expect * xp.sqrt(xp.asarray(30 * 20 * 10, dtype=xp.float64))
+ )
+ xp_assert_close(fft.ihfftn(x, norm="forward"), expect * (30 * 20 * 10))
+
+ def _check_axes(self, op, xp):
+ dtype = get_expected_input_dtype(op, xp)
+ x = xp.asarray(random((30, 20, 10)), dtype=dtype)
+ axes = [(0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)]
+ xp_test = array_namespace(x)
+ for a in axes:
+ op_tr = op(xp_test.permute_dims(x, axes=a))
+ tr_op = xp_test.permute_dims(op(x, axes=a), axes=a)
+ xp_assert_close(op_tr, tr_op)
+
+ @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn, fft.rfftn, fft.irfftn])
+ def test_axes_standard(self, op, xp):
+ self._check_axes(op, xp)
+
+ @pytest.mark.parametrize("op", [fft.hfftn, fft.ihfftn])
+ def test_axes_non_standard(self, op, xp):
+ self._check_axes(op, xp)
+
+ @pytest.mark.parametrize("op", [fft.fftn, fft.ifftn,
+ fft.rfftn, fft.irfftn])
+ def test_axes_subset_with_shape_standard(self, op, xp):
+ dtype = get_expected_input_dtype(op, xp)
+ x = xp.asarray(random((16, 8, 4)), dtype=dtype)
+ axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
+ xp_test = array_namespace(x)
+ for a in axes:
+ # different shape on the first two axes
+ shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
+ for ax in range(x.ndim)])
+ # transform only the first two axes
+ op_tr = op(xp_test.permute_dims(x, axes=a),
+ s=shape[:2], axes=(0, 1))
+ tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]),
+ axes=a)
+ xp_assert_close(op_tr, tr_op)
+
+ @pytest.mark.parametrize("op", [fft.fft2, fft.ifft2,
+ fft.rfft2, fft.irfft2,
+ fft.hfft2, fft.ihfft2,
+ fft.hfftn, fft.ihfftn])
+ def test_axes_subset_with_shape_non_standard(self, op, xp):
+ dtype = get_expected_input_dtype(op, xp)
+ x = xp.asarray(random((16, 8, 4)), dtype=dtype)
+ axes = [(0, 1, 2), (0, 2, 1), (1, 2, 0)]
+ xp_test = array_namespace(x)
+ for a in axes:
+ # different shape on the first two axes
+ shape = tuple([2*x.shape[ax] if ax in a[:2] else x.shape[ax]
+ for ax in range(x.ndim)])
+ # transform only the first two axes
+ op_tr = op(xp_test.permute_dims(x, axes=a), s=shape[:2], axes=(0, 1))
+ tr_op = xp_test.permute_dims(op(x, s=shape[:2], axes=a[:2]), axes=a)
+ xp_assert_close(op_tr, tr_op)
+
+ def test_all_1d_norm_preserving(self, xp):
+ # verify that round-trip transforms are norm-preserving
+ x = xp.asarray(random(30), dtype=xp.float64)
+ xp_test = array_namespace(x)
+ x_norm = xp_test.linalg.vector_norm(x)
+ n = xp_size(x) * 2
+ func_pairs = [(fft.rfft, fft.irfft),
+ # hfft: order so the first function takes x.size samples
+ # (necessary for comparison to x_norm above)
+ (fft.ihfft, fft.hfft),
+ # functions that expect complex dtypes at the end
+ (fft.fft, fft.ifft),
+ ]
+ for forw, back in func_pairs:
+ if forw == fft.fft:
+ x = xp.asarray(x, dtype=xp.complex128)
+ x_norm = xp_test.linalg.vector_norm(x)
+ for n in [xp_size(x), 2*xp_size(x)]:
+ for norm in ['backward', 'ortho', 'forward']:
+ tmp = forw(x, n=n, norm=norm)
+ tmp = back(tmp, n=n, norm=norm)
+ xp_assert_close(xp_test.linalg.vector_norm(tmp), x_norm)
+
+ @skip_xp_backends(np_only=True)
+ @pytest.mark.parametrize("dtype", [np.float16, np.longdouble])
+ def test_dtypes_nonstandard(self, dtype):
+ x = random(30).astype(dtype)
+ out_dtypes = {np.float16: np.complex64, np.longdouble: np.clongdouble}
+ x_complex = x.astype(out_dtypes[dtype])
+
+ res_fft = fft.ifft(fft.fft(x))
+ res_rfft = fft.irfft(fft.rfft(x))
+ res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
+ # Check both numerical results and exact dtype matches
+ assert_array_almost_equal(res_fft, x_complex)
+ assert_array_almost_equal(res_rfft, x)
+ assert_array_almost_equal(res_hfft, x)
+ assert res_fft.dtype == x_complex.dtype
+ assert res_rfft.dtype == np.result_type(np.float32, x.dtype)
+ assert res_hfft.dtype == np.result_type(np.float32, x.dtype)
+
+ @pytest.mark.parametrize("dtype", ["float32", "float64"])
+ def test_dtypes_real(self, dtype, xp):
+ x = xp.asarray(random(30), dtype=getattr(xp, dtype))
+
+ res_rfft = fft.irfft(fft.rfft(x))
+ res_hfft = fft.hfft(fft.ihfft(x), x.shape[0])
+ # Check both numerical results and exact dtype matches
+ xp_assert_close(res_rfft, x)
+ xp_assert_close(res_hfft, x)
+
+ @pytest.mark.parametrize("dtype", ["complex64", "complex128"])
+ def test_dtypes_complex(self, dtype, xp):
+ rng = np.random.default_rng(1234)
+ x = xp.asarray(rng.random(30), dtype=getattr(xp, dtype))
+
+ res_fft = fft.ifft(fft.fft(x))
+ # Check both numerical results and exact dtype matches
+ xp_assert_close(res_fft, x)
+
+ @skip_xp_backends(np_only=True,
+ reason='array-likes only supported for NumPy backend')
+ @pytest.mark.parametrize("op", [fft.fft, fft.ifft,
+ fft.fft2, fft.ifft2,
+ fft.fftn, fft.ifftn,
+ fft.rfft, fft.irfft,
+ fft.rfft2, fft.irfft2,
+ fft.rfftn, fft.irfftn,
+ fft.hfft, fft.ihfft,
+ fft.hfft2, fft.ihfft2,
+ fft.hfftn, fft.ihfftn,])
+ def test_array_like(self, xp, op):
+ x = [[[1.0, 1.0], [1.0, 1.0]],
+ [[1.0, 1.0], [1.0, 1.0]],
+ [[1.0, 1.0], [1.0, 1.0]]]
+ xp_assert_close(op(x), op(xp.asarray(x)))
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize(
+ "dtype",
+ [np.float32, np.float64, np.longdouble,
+ np.complex64, np.complex128, np.clongdouble])
+@pytest.mark.parametrize("order", ["F", 'non-contiguous'])
+@pytest.mark.parametrize(
+ "fft",
+ [fft.fft, fft.fft2, fft.fftn,
+ fft.ifft, fft.ifft2, fft.ifftn])
+def test_fft_with_order(dtype, order, fft):
+ # Check that FFT/IFFT produces identical results for C, Fortran and
+ # non contiguous arrays
+ rng = np.random.RandomState(42)
+ X = rng.rand(8, 7, 13).astype(dtype, copy=False)
+ if order == 'F':
+ Y = np.asfortranarray(X)
+ else:
+ # Make a non contiguous array
+ Y = X[::-1]
+ X = np.ascontiguousarray(X[::-1])
+
+ if fft.__name__.endswith('fft'):
+ for axis in range(3):
+ X_res = fft(X, axis=axis)
+ Y_res = fft(Y, axis=axis)
+ assert_array_almost_equal(X_res, Y_res)
+ elif fft.__name__.endswith(('fft2', 'fftn')):
+ axes = [(0, 1), (1, 2), (0, 2)]
+ if fft.__name__.endswith('fftn'):
+ axes.extend([(0,), (1,), (2,), None])
+ for ax in axes:
+ X_res = fft(X, axes=ax)
+ Y_res = fft(Y, axes=ax)
+ assert_array_almost_equal(X_res, Y_res)
+ else:
+ raise ValueError
+
+
+@skip_xp_backends(cpu_only=True)
+class TestFFTThreadSafe:
+ threads = 16
+ input_shape = (800, 200)
+
+ def _test_mtsame(self, func, *args, xp=None):
+ def worker(args, q):
+ q.put(func(*args))
+
+ q = queue.Queue()
+ expected = func(*args)
+
+ # Spin off a bunch of threads to call the same function simultaneously
+ t = [threading.Thread(target=worker, args=(args, q))
+ for i in range(self.threads)]
+ [x.start() for x in t]
+
+ [x.join() for x in t]
+
+ # Make sure all threads returned the correct value
+ for i in range(self.threads):
+ xp_assert_equal(
+ q.get(timeout=5), expected,
+ err_msg='Function returned wrong value in multithreaded context'
+ )
+
+ def test_fft(self, xp):
+ a = xp.ones(self.input_shape, dtype=xp.complex128)
+ self._test_mtsame(fft.fft, a, xp=xp)
+
+ def test_ifft(self, xp):
+ a = xp.full(self.input_shape, 1+0j)
+ self._test_mtsame(fft.ifft, a, xp=xp)
+
+ def test_rfft(self, xp):
+ a = xp.ones(self.input_shape)
+ self._test_mtsame(fft.rfft, a, xp=xp)
+
+ def test_irfft(self, xp):
+ a = xp.full(self.input_shape, 1+0j)
+ self._test_mtsame(fft.irfft, a, xp=xp)
+
+ def test_hfft(self, xp):
+ a = xp.ones(self.input_shape, dtype=xp.complex64)
+ self._test_mtsame(fft.hfft, a, xp=xp)
+
+ def test_ihfft(self, xp):
+ a = xp.ones(self.input_shape)
+ self._test_mtsame(fft.ihfft, a, xp=xp)
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft])
+def test_multiprocess(func):
+ # Test that fft still works after fork (gh-10422)
+
+ with multiprocessing.Pool(2) as p:
+ res = p.map(func, [np.ones(100) for _ in range(4)])
+
+ expect = func(np.ones(100))
+ for x in res:
+ assert_allclose(x, expect)
+
+
+class TestIRFFTN:
+
+ def test_not_last_axis_success(self, xp):
+ ar, ai = np.random.random((2, 16, 8, 32))
+ a = ar + 1j*ai
+ a = xp.asarray(a)
+
+ axes = (-2,)
+
+ # Should not raise error
+ fft.irfftn(a, axes=axes)
+
+
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.rfft, fft.irfft,
+ fft.fftn, fft.ifftn,
+ fft.rfftn, fft.irfftn, fft.hfft, fft.ihfft])
+def test_non_standard_params(func, xp):
+ if func in [fft.rfft, fft.rfftn, fft.ihfft]:
+ dtype = xp.float64
+ else:
+ dtype = xp.complex128
+
+ if xp.__name__ != 'numpy':
+ x = xp.asarray([1, 2, 3], dtype=dtype)
+ # func(x) should not raise an exception
+ func(x)
+ assert_raises(ValueError, func, x, workers=2)
+ # `plan` param is not tested since SciPy does not use it currently
+ # but should be tested if it comes into use
+
+
+@pytest.mark.parametrize("dtype", ['float32', 'float64'])
+@pytest.mark.parametrize("func", [fft.fft, fft.ifft, fft.irfft,
+ fft.fftn, fft.ifftn,
+ fft.irfftn, fft.hfft,])
+def test_real_input(func, dtype, xp):
+ x = xp.asarray([1, 2, 3], dtype=getattr(xp, dtype))
+ # func(x) should not raise an exception
+ func(x)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/test_fftlog.py b/python_embeded/Lib/site-packages/scipy/fft/tests/test_fftlog.py
new file mode 100644
index 0000000000000000000000000000000000000000..8947d2622a8b0c941fe7b4741044ad2779efd102
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/test_fftlog.py
@@ -0,0 +1,206 @@
+import warnings
+import math
+
+import numpy as np
+import pytest
+
+from scipy.fft._fftlog import fht, ifht, fhtoffset
+from scipy.special import poch
+
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import xp_assert_close, xp_assert_less, array_namespace
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends"),]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+def test_fht_agrees_with_fftlog(xp):
+ # check that fht numerically agrees with the output from Fortran FFTLog,
+ # the results were generated with the provided `fftlogtest` program,
+ # after fixing how the k array is generated (divide range by n-1, not n)
+
+ # test function, analytical Hankel transform is of the same form
+ def f(r, mu):
+ return r**(mu+1)*np.exp(-r**2/2)
+
+ r = np.logspace(-4, 4, 16)
+
+ dln = np.log(r[1]/r[0])
+ mu = 0.3
+ offset = 0.0
+ bias = 0.0
+
+ a = xp.asarray(f(r, mu))
+
+ # test 1: compute as given
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
+ theirs = [-0.1159922613593045E-02, +0.1625822618458832E-02,
+ -0.1949518286432330E-02, +0.3789220182554077E-02,
+ +0.5093959119952945E-03, +0.2785387803618774E-01,
+ +0.9944952700848897E-01, +0.4599202164586588E+00,
+ +0.3157462160881342E+00, -0.8201236844404755E-03,
+ -0.7834031308271878E-03, +0.3931444945110708E-03,
+ -0.2697710625194777E-03, +0.3568398050238820E-03,
+ -0.5554454827797206E-03, +0.8286331026468585E-03]
+ theirs = xp.asarray(theirs, dtype=xp.float64)
+ xp_assert_close(ours, theirs)
+
+ # test 2: change to optimal offset
+ offset = fhtoffset(dln, mu, bias=bias)
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
+ theirs = [+0.4353768523152057E-04, -0.9197045663594285E-05,
+ +0.3150140927838524E-03, +0.9149121960963704E-03,
+ +0.5808089753959363E-02, +0.2548065256377240E-01,
+ +0.1339477692089897E+00, +0.4821530509479356E+00,
+ +0.2659899781579785E+00, -0.1116475278448113E-01,
+ +0.1791441617592385E-02, -0.4181810476548056E-03,
+ +0.1314963536765343E-03, -0.5422057743066297E-04,
+ +0.3208681804170443E-04, -0.2696849476008234E-04]
+ theirs = xp.asarray(theirs, dtype=xp.float64)
+ xp_assert_close(ours, theirs)
+
+ # test 3: positive bias
+ bias = 0.8
+ offset = fhtoffset(dln, mu, bias=bias)
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
+ theirs = [-7.3436673558316850E+00, +0.1710271207817100E+00,
+ +0.1065374386206564E+00, -0.5121739602708132E-01,
+ +0.2636649319269470E-01, +0.1697209218849693E-01,
+ +0.1250215614723183E+00, +0.4739583261486729E+00,
+ +0.2841149874912028E+00, -0.8312764741645729E-02,
+ +0.1024233505508988E-02, -0.1644902767389120E-03,
+ +0.3305775476926270E-04, -0.7786993194882709E-05,
+ +0.1962258449520547E-05, -0.8977895734909250E-06]
+ theirs = xp.asarray(theirs, dtype=xp.float64)
+ xp_assert_close(ours, theirs)
+
+ # test 4: negative bias
+ bias = -0.8
+ offset = fhtoffset(dln, mu, bias=bias)
+ ours = fht(a, dln, mu, offset=offset, bias=bias)
+ theirs = [+0.8985777068568745E-05, +0.4074898209936099E-04,
+ +0.2123969254700955E-03, +0.1009558244834628E-02,
+ +0.5131386375222176E-02, +0.2461678673516286E-01,
+ +0.1235812845384476E+00, +0.4719570096404403E+00,
+ +0.2893487490631317E+00, -0.1686570611318716E-01,
+ +0.2231398155172505E-01, -0.1480742256379873E-01,
+ +0.1692387813500801E+00, +0.3097490354365797E+00,
+ +2.7593607182401860E+00, 10.5251075070045800E+00]
+ theirs = xp.asarray(theirs, dtype=xp.float64)
+ xp_assert_close(ours, theirs)
+
+
+@pytest.mark.parametrize('optimal', [True, False])
+@pytest.mark.parametrize('offset', [0.0, 1.0, -1.0])
+@pytest.mark.parametrize('bias', [0, 0.1, -0.1])
+@pytest.mark.parametrize('n', [64, 63])
+def test_fht_identity(n, bias, offset, optimal, xp):
+ rng = np.random.RandomState(3491349965)
+
+ a = xp.asarray(rng.standard_normal(n))
+ dln = rng.uniform(-1, 1)
+ mu = rng.uniform(-2, 2)
+
+ if optimal:
+ offset = fhtoffset(dln, mu, initial=offset, bias=bias)
+
+ A = fht(a, dln, mu, offset=offset, bias=bias)
+ a_ = ifht(A, dln, mu, offset=offset, bias=bias)
+
+ xp_assert_close(a_, a, rtol=1.5e-7)
+
+
+
+
+@pytest.mark.thread_unsafe
+def test_fht_special_cases(xp):
+ rng = np.random.RandomState(3491349965)
+
+ a = xp.asarray(rng.standard_normal(64))
+ dln = rng.uniform(-1, 1)
+
+ # let x = (mu+1+q)/2, y = (mu+1-q)/2, M = {0, -1, -2, ...}
+
+ # case 1: x in M, y in M => well-defined transform
+ mu, bias = -4.0, 1.0
+ with warnings.catch_warnings(record=True) as record:
+ fht(a, dln, mu, bias=bias)
+ assert not record, 'fht warned about a well-defined transform'
+
+ # case 2: x not in M, y in M => well-defined transform
+ mu, bias = -2.5, 0.5
+ with warnings.catch_warnings(record=True) as record:
+ fht(a, dln, mu, bias=bias)
+ assert not record, 'fht warned about a well-defined transform'
+
+ # with fht_lock:
+ # case 3: x in M, y not in M => singular transform
+ mu, bias = -3.5, 0.5
+ with pytest.warns(Warning) as record:
+ fht(a, dln, mu, bias=bias)
+ assert record, 'fht did not warn about a singular transform'
+
+ # with fht_lock:
+ # case 4: x not in M, y in M => singular inverse transform
+ mu, bias = -2.5, 0.5
+ with pytest.warns(Warning) as record:
+ ifht(a, dln, mu, bias=bias)
+ assert record, 'ifht did not warn about a singular transform'
+
+
+@pytest.mark.parametrize('n', [64, 63])
+def test_fht_exact(n, xp):
+ rng = np.random.RandomState(3491349965)
+
+ # for a(r) a power law r^\gamma, the fast Hankel transform produces the
+ # exact continuous Hankel transform if biased with q = \gamma
+
+ mu = rng.uniform(0, 3)
+
+ # convergence of HT: -1-mu < gamma < 1/2
+ gamma = rng.uniform(-1-mu, 1/2)
+
+ r = np.logspace(-2, 2, n)
+ a = xp.asarray(r**gamma)
+
+ dln = np.log(r[1]/r[0])
+
+ offset = fhtoffset(dln, mu, initial=0.0, bias=gamma)
+
+ A = fht(a, dln, mu, offset=offset, bias=gamma)
+
+ k = np.exp(offset)/r[::-1]
+
+ # analytical result
+ At = xp.asarray((2/k)**gamma * poch((mu+1-gamma)/2, gamma))
+
+ xp_assert_close(A, At)
+
+@skip_xp_backends(np_only=True,
+ reason='array-likes only supported for NumPy backend')
+@pytest.mark.parametrize("op", [fht, ifht])
+def test_array_like(xp, op):
+ x = [[[1.0, 1.0], [1.0, 1.0]],
+ [[1.0, 1.0], [1.0, 1.0]],
+ [[1.0, 1.0], [1.0, 1.0]]]
+ xp_assert_close(op(x, 1.0, 2.0), op(xp.asarray(x), 1.0, 2.0))
+
+@pytest.mark.parametrize('n', [128, 129])
+def test_gh_21661(xp, n):
+ one = xp.asarray(1.0)
+ xp_test = array_namespace(one)
+ mu = 0.0
+ r = np.logspace(-7, 1, n)
+ dln = math.log(r[1] / r[0])
+ offset = fhtoffset(dln, initial=-6 * np.log(10), mu=mu)
+ r = xp.asarray(r, dtype=one.dtype)
+ k = math.exp(offset) / xp_test.flip(r, axis=-1)
+
+ def f(x, mu):
+ return x**(mu + 1)*xp.exp(-x**2/2)
+
+ a_r = f(r, mu)
+ fht_val = fht(a_r, dln, mu=mu, offset=offset)
+ a_k = f(k, mu)
+ rel_err = xp.max(xp.abs((fht_val - a_k) / a_k))
+ xp_assert_less(rel_err, xp.asarray(7.28e+16)[()])
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/test_helper.py b/python_embeded/Lib/site-packages/scipy/fft/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fae0036c15a31db42ec3a901880239973e3c215
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/test_helper.py
@@ -0,0 +1,574 @@
+"""Includes test functions for fftpack.helper module
+
+Copied from fftpack.helper by Pearu Peterson, October 2005
+Modified for Array API, 2023
+
+"""
+from scipy.fft._helper import next_fast_len, prev_fast_len, _init_nd_shape_and_axes
+from numpy.testing import assert_equal
+from pytest import raises as assert_raises
+import pytest
+import numpy as np
+import sys
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import (
+ xp_assert_close, get_xp_devices, xp_device, array_namespace
+)
+from scipy import fft
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+_5_smooth_numbers = [
+ 2, 3, 4, 5, 6, 8, 9, 10,
+ 2 * 3 * 5,
+ 2**3 * 3**5,
+ 2**3 * 3**3 * 5**2,
+]
+
+def test_next_fast_len():
+ for n in _5_smooth_numbers:
+ assert_equal(next_fast_len(n), n)
+
+
+def _assert_n_smooth(x, n):
+ x_orig = x
+ if n < 2:
+ assert False
+
+ while True:
+ q, r = divmod(x, 2)
+ if r != 0:
+ break
+ x = q
+
+ for d in range(3, n+1, 2):
+ while True:
+ q, r = divmod(x, d)
+ if r != 0:
+ break
+ x = q
+
+ assert x == 1, \
+ f'x={x_orig} is not {n}-smooth, remainder={x}'
+
+
+@skip_xp_backends(np_only=True)
+class TestNextFastLen:
+
+ def test_next_fast_len(self):
+ np.random.seed(1234)
+
+ def nums():
+ yield from range(1, 1000)
+ yield 2**5 * 3**5 * 4**5 + 1
+
+ for n in nums():
+ m = next_fast_len(n)
+ _assert_n_smooth(m, 11)
+ assert m == next_fast_len(n, False)
+
+ m = next_fast_len(n, True)
+ _assert_n_smooth(m, 5)
+
+ def test_np_integers(self):
+ ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32, np.uint64]
+ for ityp in ITYPES:
+ x = ityp(12345)
+ testN = next_fast_len(x)
+ assert_equal(testN, next_fast_len(int(x)))
+
+ def testnext_fast_len_small(self):
+ hams = {
+ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 8, 8: 8, 14: 15, 15: 15,
+ 16: 16, 17: 18, 1021: 1024, 1536: 1536, 51200000: 51200000
+ }
+ for x, y in hams.items():
+ assert_equal(next_fast_len(x, True), y)
+
+ @pytest.mark.xfail(sys.maxsize < 2**32,
+ reason="Hamming Numbers too large for 32-bit",
+ raises=ValueError, strict=True)
+ def testnext_fast_len_big(self):
+ hams = {
+ 510183360: 510183360, 510183360 + 1: 512000000,
+ 511000000: 512000000,
+ 854296875: 854296875, 854296875 + 1: 859963392,
+ 196608000000: 196608000000, 196608000000 + 1: 196830000000,
+ 8789062500000: 8789062500000, 8789062500000 + 1: 8796093022208,
+ 206391214080000: 206391214080000,
+ 206391214080000 + 1: 206624260800000,
+ 470184984576000: 470184984576000,
+ 470184984576000 + 1: 470715894135000,
+ 7222041363087360: 7222041363087360,
+ 7222041363087360 + 1: 7230196133913600,
+ # power of 5 5**23
+ 11920928955078125: 11920928955078125,
+ 11920928955078125 - 1: 11920928955078125,
+ # power of 3 3**34
+ 16677181699666569: 16677181699666569,
+ 16677181699666569 - 1: 16677181699666569,
+ # power of 2 2**54
+ 18014398509481984: 18014398509481984,
+ 18014398509481984 - 1: 18014398509481984,
+ # above this, int(ceil(n)) == int(ceil(n+1))
+ 19200000000000000: 19200000000000000,
+ 19200000000000000 + 1: 19221679687500000,
+ 288230376151711744: 288230376151711744,
+ 288230376151711744 + 1: 288325195312500000,
+ 288325195312500000 - 1: 288325195312500000,
+ 288325195312500000: 288325195312500000,
+ 288325195312500000 + 1: 288555831593533440,
+ }
+ for x, y in hams.items():
+ assert_equal(next_fast_len(x, True), y)
+
+ def test_keyword_args(self):
+ assert next_fast_len(11, real=True) == 12
+ assert next_fast_len(target=7, real=False) == 7
+
+@skip_xp_backends(np_only=True)
+class TestPrevFastLen:
+
+ def test_prev_fast_len(self):
+ np.random.seed(1234)
+
+ def nums():
+ yield from range(1, 1000)
+ yield 2**5 * 3**5 * 4**5 + 1
+
+ for n in nums():
+ m = prev_fast_len(n)
+ _assert_n_smooth(m, 11)
+ assert m == prev_fast_len(n, False)
+
+ m = prev_fast_len(n, True)
+ _assert_n_smooth(m, 5)
+
+ def test_np_integers(self):
+ ITYPES = [np.int16, np.int32, np.int64, np.uint16, np.uint32,
+ np.uint64]
+ for ityp in ITYPES:
+ x = ityp(12345)
+ testN = prev_fast_len(x)
+ assert_equal(testN, prev_fast_len(int(x)))
+
+ testN = prev_fast_len(x, real=True)
+ assert_equal(testN, prev_fast_len(int(x), real=True))
+
+ def testprev_fast_len_small(self):
+ hams = {
+ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 6, 8: 8, 14: 12, 15: 15,
+ 16: 16, 17: 16, 1021: 1000, 1536: 1536, 51200000: 51200000
+ }
+ for x, y in hams.items():
+ assert_equal(prev_fast_len(x, True), y)
+
+ hams = {
+ 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10,
+ 11: 11, 12: 12, 13: 12, 14: 14, 15: 15, 16: 16, 17: 16, 18: 18,
+ 19: 18, 20: 20, 21: 21, 22: 22, 120: 120, 121: 121, 122: 121,
+ 1021: 1008, 1536: 1536, 51200000: 51200000
+ }
+ for x, y in hams.items():
+ assert_equal(prev_fast_len(x, False), y)
+
+ @pytest.mark.xfail(sys.maxsize < 2**32,
+ reason="Hamming Numbers too large for 32-bit",
+ raises=ValueError, strict=True)
+ def testprev_fast_len_big(self):
+ hams = {
+ # 2**6 * 3**13 * 5**1
+ 510183360: 510183360,
+ 510183360 + 1: 510183360,
+ 510183360 - 1: 509607936, # 2**21 * 3**5
+ # 2**6 * 5**6 * 7**1 * 73**1
+ 511000000: 510183360,
+ 511000000 + 1: 510183360,
+ 511000000 - 1: 510183360, # 2**6 * 3**13 * 5**1
+ # 3**7 * 5**8
+ 854296875: 854296875,
+ 854296875 + 1: 854296875,
+ 854296875 - 1: 850305600, # 2**6 * 3**12 * 5**2
+ # 2**22 * 3**1 * 5**6
+ 196608000000: 196608000000,
+ 196608000000 + 1: 196608000000,
+ 196608000000 - 1: 195910410240, # 2**13 * 3**14 * 5**1
+ # 2**5 * 3**2 * 5**15
+ 8789062500000: 8789062500000,
+ 8789062500000 + 1: 8789062500000,
+ 8789062500000 - 1: 8748000000000, # 2**11 * 3**7 * 5**9
+ # 2**24 * 3**9 * 5**4
+ 206391214080000: 206391214080000,
+ 206391214080000 + 1: 206391214080000,
+ 206391214080000 - 1: 206158430208000, # 2**39 * 3**1 * 5**3
+ # 2**18 * 3**15 * 5**3
+ 470184984576000: 470184984576000,
+ 470184984576000 + 1: 470184984576000,
+ 470184984576000 - 1: 469654673817600, # 2**33 * 3**7 **5**2
+ # 2**25 * 3**16 * 5**1
+ 7222041363087360: 7222041363087360,
+ 7222041363087360 + 1: 7222041363087360,
+ 7222041363087360 - 1: 7213895789838336, # 2**40 * 3**8
+ # power of 5 5**23
+ 11920928955078125: 11920928955078125,
+ 11920928955078125 + 1: 11920928955078125,
+ 11920928955078125 - 1: 11901557422080000, # 2**14 * 3**19 * 5**4
+ # power of 3 3**34
+ 16677181699666569: 16677181699666569,
+ 16677181699666569 + 1: 16677181699666569,
+ 16677181699666569 - 1: 16607531250000000, # 2**7 * 3**12 * 5**12
+ # power of 2 2**54
+ 18014398509481984: 18014398509481984,
+ 18014398509481984 + 1: 18014398509481984,
+ 18014398509481984 - 1: 18000000000000000, # 2**16 * 3**2 * 5**15
+ # 2**20 * 3**1 * 5**14
+ 19200000000000000: 19200000000000000,
+ 19200000000000000 + 1: 19200000000000000,
+ 19200000000000000 - 1: 19131876000000000, # 2**11 * 3**14 * 5**9
+ # 2**58
+ 288230376151711744: 288230376151711744,
+ 288230376151711744 + 1: 288230376151711744,
+ 288230376151711744 - 1: 288000000000000000, # 2**20 * 3**2 * 5**15
+ # 2**5 * 3**10 * 5**16
+ 288325195312500000: 288325195312500000,
+ 288325195312500000 + 1: 288325195312500000,
+ 288325195312500000 - 1: 288230376151711744, # 2**58
+ }
+ for x, y in hams.items():
+ assert_equal(prev_fast_len(x, True), y)
+
+ def test_keyword_args(self):
+ assert prev_fast_len(11, real=True) == 10
+ assert prev_fast_len(target=7, real=False) == 7
+
+
+@skip_xp_backends(cpu_only=True)
+class Test_init_nd_shape_and_axes:
+
+ def test_py_0d_defaults(self, xp):
+ x = xp.asarray(4)
+ shape = None
+ axes = None
+
+ shape_expected = ()
+ axes_expected = []
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_0d_defaults(self, xp):
+ x = xp.asarray(7.)
+ shape = None
+ axes = None
+
+ shape_expected = ()
+ axes_expected = []
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_py_1d_defaults(self, xp):
+ x = xp.asarray([1, 2, 3])
+ shape = None
+ axes = None
+
+ shape_expected = (3,)
+ axes_expected = [0]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_1d_defaults(self, xp):
+ x = xp.arange(0, 1, .1)
+ shape = None
+ axes = None
+
+ shape_expected = (10,)
+ axes_expected = [0]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_py_2d_defaults(self, xp):
+ x = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8]])
+ shape = None
+ axes = None
+
+ shape_expected = (2, 4)
+ axes_expected = [0, 1]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_2d_defaults(self, xp):
+ x = xp.arange(0, 1, .1)
+ x = xp.reshape(x, (5, 2))
+ shape = None
+ axes = None
+
+ shape_expected = (5, 2)
+ axes_expected = [0, 1]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_5d_defaults(self, xp):
+ x = xp.zeros([6, 2, 5, 3, 4])
+ shape = None
+ axes = None
+
+ shape_expected = (6, 2, 5, 3, 4)
+ axes_expected = [0, 1, 2, 3, 4]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_5d_set_shape(self, xp):
+ x = xp.zeros([6, 2, 5, 3, 4])
+ shape = [10, -1, -1, 1, 4]
+ axes = None
+
+ shape_expected = (10, 2, 5, 1, 4)
+ axes_expected = [0, 1, 2, 3, 4]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_5d_set_axes(self, xp):
+ x = xp.zeros([6, 2, 5, 3, 4])
+ shape = None
+ axes = [4, 1, 2]
+
+ shape_expected = (4, 2, 5)
+ axes_expected = [4, 1, 2]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_xp_5d_set_shape_axes(self, xp):
+ x = xp.zeros([6, 2, 5, 3, 4])
+ shape = [10, -1, 2]
+ axes = [1, 0, 3]
+
+ shape_expected = (10, 6, 2)
+ axes_expected = [1, 0, 3]
+
+ shape_res, axes_res = _init_nd_shape_and_axes(x, shape, axes)
+
+ assert shape_res == shape_expected
+ assert axes_res == axes_expected
+
+ def test_shape_axes_subset(self, xp):
+ x = xp.zeros((2, 3, 4, 5))
+ shape, axes = _init_nd_shape_and_axes(x, shape=(5, 5, 5), axes=None)
+
+ assert shape == (5, 5, 5)
+ assert axes == [1, 2, 3]
+
+ def test_errors(self, xp):
+ x = xp.zeros(1)
+ with assert_raises(ValueError, match="axes must be a scalar or "
+ "iterable of integers"):
+ _init_nd_shape_and_axes(x, shape=None, axes=[[1, 2], [3, 4]])
+
+ with assert_raises(ValueError, match="axes must be a scalar or "
+ "iterable of integers"):
+ _init_nd_shape_and_axes(x, shape=None, axes=[1., 2., 3., 4.])
+
+ with assert_raises(ValueError,
+ match="axes exceeds dimensionality of input"):
+ _init_nd_shape_and_axes(x, shape=None, axes=[1])
+
+ with assert_raises(ValueError,
+ match="axes exceeds dimensionality of input"):
+ _init_nd_shape_and_axes(x, shape=None, axes=[-2])
+
+ with assert_raises(ValueError,
+ match="all axes must be unique"):
+ _init_nd_shape_and_axes(x, shape=None, axes=[0, 0])
+
+ with assert_raises(ValueError, match="shape must be a scalar or "
+ "iterable of integers"):
+ _init_nd_shape_and_axes(x, shape=[[1, 2], [3, 4]], axes=None)
+
+ with assert_raises(ValueError, match="shape must be a scalar or "
+ "iterable of integers"):
+ _init_nd_shape_and_axes(x, shape=[1., 2., 3., 4.], axes=None)
+
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ _init_nd_shape_and_axes(xp.zeros([1, 1, 1, 1]),
+ shape=[1, 2, 3], axes=[1])
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[0\]\) specified"):
+ _init_nd_shape_and_axes(x, shape=[0], axes=None)
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[-2\]\) specified"):
+ _init_nd_shape_and_axes(x, shape=-2, axes=None)
+
+
+class TestFFTShift:
+
+ def test_definition(self, xp):
+ x = xp.asarray([0., 1, 2, 3, 4, -4, -3, -2, -1])
+ y = xp.asarray([-4., -3, -2, -1, 0, 1, 2, 3, 4])
+ xp_assert_close(fft.fftshift(x), y)
+ xp_assert_close(fft.ifftshift(y), x)
+ x = xp.asarray([0., 1, 2, 3, 4, -5, -4, -3, -2, -1])
+ y = xp.asarray([-5., -4, -3, -2, -1, 0, 1, 2, 3, 4])
+ xp_assert_close(fft.fftshift(x), y)
+ xp_assert_close(fft.ifftshift(y), x)
+
+ def test_inverse(self, xp):
+ for n in [1, 4, 9, 100, 211]:
+ x = xp.asarray(np.random.random((n,)))
+ xp_assert_close(fft.ifftshift(fft.fftshift(x)), x)
+
+ @skip_xp_backends('cupy', reason='cupy/cupy#8393')
+ def test_axes_keyword(self, xp):
+ freqs = xp.asarray([[0., 1, 2], [3, 4, -4], [-3, -2, -1]])
+ shifted = xp.asarray([[-1., -3, -2], [2, 0, 1], [-4, 3, 4]])
+ xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shifted)
+ xp_assert_close(fft.fftshift(freqs, axes=0), fft.fftshift(freqs, axes=(0,)))
+ xp_assert_close(fft.ifftshift(shifted, axes=(0, 1)), freqs)
+ xp_assert_close(fft.ifftshift(shifted, axes=0),
+ fft.ifftshift(shifted, axes=(0,)))
+ xp_assert_close(fft.fftshift(freqs), shifted)
+ xp_assert_close(fft.ifftshift(shifted), freqs)
+
+ @skip_xp_backends('cupy', reason='cupy/cupy#8393')
+ def test_uneven_dims(self, xp):
+ """ Test 2D input, which has uneven dimension sizes """
+ freqs = xp.asarray([
+ [0, 1],
+ [2, 3],
+ [4, 5]
+ ], dtype=xp.float64)
+
+ # shift in dimension 0
+ shift_dim0 = xp.asarray([
+ [4, 5],
+ [0, 1],
+ [2, 3]
+ ], dtype=xp.float64)
+ xp_assert_close(fft.fftshift(freqs, axes=0), shift_dim0)
+ xp_assert_close(fft.ifftshift(shift_dim0, axes=0), freqs)
+ xp_assert_close(fft.fftshift(freqs, axes=(0,)), shift_dim0)
+ xp_assert_close(fft.ifftshift(shift_dim0, axes=[0]), freqs)
+
+ # shift in dimension 1
+ shift_dim1 = xp.asarray([
+ [1, 0],
+ [3, 2],
+ [5, 4]
+ ], dtype=xp.float64)
+ xp_assert_close(fft.fftshift(freqs, axes=1), shift_dim1)
+ xp_assert_close(fft.ifftshift(shift_dim1, axes=1), freqs)
+
+ # shift in both dimensions
+ shift_dim_both = xp.asarray([
+ [5, 4],
+ [1, 0],
+ [3, 2]
+ ], dtype=xp.float64)
+ xp_assert_close(fft.fftshift(freqs, axes=(0, 1)), shift_dim_both)
+ xp_assert_close(fft.ifftshift(shift_dim_both, axes=(0, 1)), freqs)
+ xp_assert_close(fft.fftshift(freqs, axes=[0, 1]), shift_dim_both)
+ xp_assert_close(fft.ifftshift(shift_dim_both, axes=[0, 1]), freqs)
+
+ # axes=None (default) shift in all dimensions
+ xp_assert_close(fft.fftshift(freqs, axes=None), shift_dim_both)
+ xp_assert_close(fft.ifftshift(shift_dim_both, axes=None), freqs)
+ xp_assert_close(fft.fftshift(freqs), shift_dim_both)
+ xp_assert_close(fft.ifftshift(shift_dim_both), freqs)
+
+
+@skip_xp_backends("cupy",
+ reason="CuPy has not implemented the `device` param")
+@skip_xp_backends("jax.numpy",
+ reason="JAX has not implemented the `device` param")
+class TestFFTFreq:
+
+ def test_definition(self, xp):
+ x = xp.asarray([0, 1, 2, 3, 4, -4, -3, -2, -1], dtype=xp.float64)
+ x2 = xp.asarray([0, 1, 2, 3, 4, -5, -4, -3, -2, -1], dtype=xp.float64)
+
+ # default dtype varies across backends
+
+ y = 9 * fft.fftfreq(9, xp=xp)
+ xp_assert_close(y, x, check_dtype=False, check_namespace=True)
+
+ y = 9 * xp.pi * fft.fftfreq(9, xp.pi, xp=xp)
+ xp_assert_close(y, x, check_dtype=False)
+
+ y = 10 * fft.fftfreq(10, xp=xp)
+ xp_assert_close(y, x2, check_dtype=False)
+
+ y = 10 * xp.pi * fft.fftfreq(10, xp.pi, xp=xp)
+ xp_assert_close(y, x2, check_dtype=False)
+
+ def test_device(self, xp):
+ xp_test = array_namespace(xp.empty(0))
+ devices = get_xp_devices(xp)
+ for d in devices:
+ y = fft.fftfreq(9, xp=xp, device=d)
+ x = xp_test.empty(0, device=d)
+ assert xp_device(y) == xp_device(x)
+
+
+@skip_xp_backends("cupy",
+ reason="CuPy has not implemented the `device` param")
+@skip_xp_backends("jax.numpy",
+ reason="JAX has not implemented the `device` param")
+class TestRFFTFreq:
+
+ def test_definition(self, xp):
+ x = xp.asarray([0, 1, 2, 3, 4], dtype=xp.float64)
+ x2 = xp.asarray([0, 1, 2, 3, 4, 5], dtype=xp.float64)
+
+ # default dtype varies across backends
+
+ y = 9 * fft.rfftfreq(9, xp=xp)
+ xp_assert_close(y, x, check_dtype=False, check_namespace=True)
+
+ y = 9 * xp.pi * fft.rfftfreq(9, xp.pi, xp=xp)
+ xp_assert_close(y, x, check_dtype=False)
+
+ y = 10 * fft.rfftfreq(10, xp=xp)
+ xp_assert_close(y, x2, check_dtype=False)
+
+ y = 10 * xp.pi * fft.rfftfreq(10, xp.pi, xp=xp)
+ xp_assert_close(y, x2, check_dtype=False)
+
+ def test_device(self, xp):
+ xp_test = array_namespace(xp.empty(0))
+ devices = get_xp_devices(xp)
+ for d in devices:
+ y = fft.rfftfreq(9, xp=xp, device=d)
+ x = xp_test.empty(0, device=d)
+ assert xp_device(y) == xp_device(x)
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/test_multithreading.py b/python_embeded/Lib/site-packages/scipy/fft/tests/test_multithreading.py
new file mode 100644
index 0000000000000000000000000000000000000000..eddaccf8b063ba0cd1a3727c871bd5df7422f99d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/test_multithreading.py
@@ -0,0 +1,84 @@
+from scipy import fft
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose
+import multiprocessing
+import os
+
+
+@pytest.fixture(scope='module')
+def x():
+ return np.random.randn(512, 128) # Must be large enough to qualify for mt
+
+
+@pytest.mark.parametrize("func", [
+ fft.fft, fft.ifft, fft.fft2, fft.ifft2, fft.fftn, fft.ifftn,
+ fft.rfft, fft.irfft, fft.rfft2, fft.irfft2, fft.rfftn, fft.irfftn,
+ fft.hfft, fft.ihfft, fft.hfft2, fft.ihfft2, fft.hfftn, fft.ihfftn,
+ fft.dct, fft.idct, fft.dctn, fft.idctn,
+ fft.dst, fft.idst, fft.dstn, fft.idstn,
+])
+@pytest.mark.parametrize("workers", [2, -1])
+def test_threaded_same(x, func, workers):
+ expected = func(x, workers=1)
+ actual = func(x, workers=workers)
+ assert_allclose(actual, expected)
+
+
+def _mt_fft(x):
+ return fft.fft(x, workers=2)
+
+
+@pytest.mark.slow
+def test_mixed_threads_processes(x):
+ # Test that the fft threadpool is safe to use before & after fork
+
+ expect = fft.fft(x, workers=2)
+
+ with multiprocessing.Pool(2) as p:
+ res = p.map(_mt_fft, [x for _ in range(4)])
+
+ for r in res:
+ assert_allclose(r, expect)
+
+ fft.fft(x, workers=2)
+
+
+def test_invalid_workers(x):
+ cpus = os.cpu_count()
+
+ fft.ifft([1], workers=-cpus)
+
+ with pytest.raises(ValueError, match='workers must not be zero'):
+ fft.fft(x, workers=0)
+
+ with pytest.raises(ValueError, match='workers value out of range'):
+ fft.ifft(x, workers=-cpus-1)
+
+
+def test_set_get_workers():
+ cpus = os.cpu_count()
+ assert fft.get_workers() == 1
+ with fft.set_workers(4):
+ assert fft.get_workers() == 4
+
+ with fft.set_workers(-1):
+ assert fft.get_workers() == cpus
+
+ assert fft.get_workers() == 4
+
+ assert fft.get_workers() == 1
+
+ with fft.set_workers(-cpus):
+ assert fft.get_workers() == 1
+
+
+def test_set_workers_invalid():
+
+ with pytest.raises(ValueError, match='workers must not be zero'):
+ with fft.set_workers(0):
+ pass
+
+ with pytest.raises(ValueError, match='workers value out of range'):
+ with fft.set_workers(-os.cpu_count()-1):
+ pass
diff --git a/python_embeded/Lib/site-packages/scipy/fft/tests/test_real_transforms.py b/python_embeded/Lib/site-packages/scipy/fft/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..bbb434faa9304f4545c4343dba430d6a2bb46915
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fft/tests/test_real_transforms.py
@@ -0,0 +1,249 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+import pytest
+import math
+
+from scipy.fft import dct, idct, dctn, idctn, dst, idst, dstn, idstn
+import scipy.fft as fft
+from scipy import fftpack
+from scipy.conftest import array_api_compatible
+from scipy._lib._array_api import xp_copy, xp_assert_close
+
+pytestmark = [array_api_compatible, pytest.mark.usefixtures("skip_xp_backends")]
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+SQRT_2 = math.sqrt(2)
+
+# scipy.fft wraps the fftpack versions but with normalized inverse transforms.
+# So, the forward transforms and definitions are already thoroughly tested in
+# fftpack/test_real_transforms.py
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("n", [2, 3, 4, 5, 10, 16])
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("orthogonalize", [False, True])
+def test_identity_1d(forward, backward, type, n, axis, norm, orthogonalize, xp):
+ # Test the identity f^-1(f(x)) == x
+ x = xp.asarray(np.random.rand(n, n))
+
+ y = forward(x, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
+ z = backward(y, type, axis=axis, norm=norm, orthogonalize=orthogonalize)
+ xp_assert_close(z, x)
+
+ pad = [(0, 0)] * 2
+ pad[axis] = (0, 4)
+
+ y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
+ z2 = backward(y2, type, n, axis, norm, orthogonalize=orthogonalize)
+ xp_assert_close(z2, x)
+
+
+@skip_xp_backends(np_only=True,
+ reason='`overwrite_x` only supported for NumPy backend.')
+@pytest.mark.parametrize("forward, backward", [(dct, idct), (dst, idst)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
+ np.complex64, np.complex128])
+@pytest.mark.parametrize("axis", [0, 1])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("overwrite_x", [True, False])
+def test_identity_1d_overwrite(forward, backward, type, dtype, axis, norm,
+ overwrite_x):
+ # Test the identity f^-1(f(x)) == x
+ x = np.random.rand(7, 8).astype(dtype)
+ x_orig = x.copy()
+
+ y = forward(x, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
+ y_orig = y.copy()
+ z = backward(y, type, axis=axis, norm=norm, overwrite_x=overwrite_x)
+ if not overwrite_x:
+ assert_allclose(z, x, rtol=1e-6, atol=1e-6)
+ assert_array_equal(x, x_orig)
+ assert_array_equal(y, y_orig)
+ else:
+ assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("shape, axes",
+ [
+ ((4, 4), 0),
+ ((4, 4), 1),
+ ((4, 4), None),
+ ((4, 4), (0, 1)),
+ ((10, 12), None),
+ ((10, 12), (0, 1)),
+ ((4, 5, 6), None),
+ ((4, 5, 6), 1),
+ ((4, 5, 6), (0, 2)),
+ ])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("orthogonalize", [False, True])
+def test_identity_nd(forward, backward, type, shape, axes, norm,
+ orthogonalize, xp):
+ # Test the identity f^-1(f(x)) == x
+
+ x = xp.asarray(np.random.random(shape))
+
+ if axes is not None:
+ shape = np.take(shape, axes)
+
+ y = forward(x, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
+ z = backward(y, type, axes=axes, norm=norm, orthogonalize=orthogonalize)
+ xp_assert_close(z, x)
+
+ if axes is None:
+ pad = [(0, 4)] * x.ndim
+ elif isinstance(axes, int):
+ pad = [(0, 0)] * x.ndim
+ pad[axes] = (0, 4)
+ else:
+ pad = [(0, 0)] * x.ndim
+
+ for a in axes:
+ pad[a] = (0, 4)
+
+ # TODO write an array-agnostic pad
+ y2 = xp.asarray(np.pad(np.asarray(y), pad, mode='edge'))
+ z2 = backward(y2, type, shape, axes, norm, orthogonalize=orthogonalize)
+ xp_assert_close(z2, x)
+
+
+@skip_xp_backends(np_only=True,
+ reason='`overwrite_x` only supported for NumPy backend.')
+@pytest.mark.parametrize("forward, backward", [(dctn, idctn), (dstn, idstn)])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("shape, axes",
+ [
+ ((4, 5), 0),
+ ((4, 5), 1),
+ ((4, 5), None),
+ ])
+@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64,
+ np.complex64, np.complex128])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+@pytest.mark.parametrize("overwrite_x", [False, True])
+def test_identity_nd_overwrite(forward, backward, type, shape, axes, dtype,
+ norm, overwrite_x):
+ # Test the identity f^-1(f(x)) == x
+
+ x = np.random.random(shape).astype(dtype)
+ x_orig = x.copy()
+
+ if axes is not None:
+ shape = np.take(shape, axes)
+
+ y = forward(x, type, axes=axes, norm=norm)
+ y_orig = y.copy()
+ z = backward(y, type, axes=axes, norm=norm)
+ if overwrite_x:
+ assert_allclose(z, x_orig, rtol=1e-6, atol=1e-6)
+ else:
+ assert_allclose(z, x, rtol=1e-6, atol=1e-6)
+ assert_array_equal(x, x_orig)
+ assert_array_equal(y, y_orig)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("func", ['dct', 'dst', 'dctn', 'dstn'])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+@pytest.mark.parametrize("norm", [None, 'backward', 'ortho', 'forward'])
+def test_fftpack_equivalience(func, type, norm, xp):
+ x = np.random.rand(8, 16)
+ fftpack_res = xp.asarray(getattr(fftpack, func)(x, type, norm=norm))
+ x = xp.asarray(x)
+ fft_res = getattr(fft, func)(x, type, norm=norm)
+
+ xp_assert_close(fft_res, fftpack_res)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("func", [dct, dst, dctn, dstn])
+@pytest.mark.parametrize("type", [1, 2, 3, 4])
+def test_orthogonalize_default(func, type, xp):
+ # Test orthogonalize is the default when norm="ortho", but not otherwise
+ x = xp.asarray(np.random.rand(100))
+
+ for norm, ortho in [
+ ("forward", False),
+ ("backward", False),
+ ("ortho", True),
+ ]:
+ a = func(x, type=type, norm=norm, orthogonalize=ortho)
+ b = func(x, type=type, norm=norm)
+ xp_assert_close(a, b)
+
+
+@skip_xp_backends(cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func, type", [
+ (dct, 4), (dst, 1), (dst, 4)])
+def test_orthogonalize_noop(func, type, norm, xp):
+ # Transforms where orthogonalize is a no-op
+ x = xp.asarray(np.random.rand(100))
+ y1 = func(x, type=type, norm=norm, orthogonalize=True)
+ y2 = func(x, type=type, norm=norm, orthogonalize=False)
+ xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment',
+ cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+def test_orthogonalize_dct1(norm, xp):
+ x = xp.asarray(np.random.rand(100))
+
+ x2 = xp_copy(x, xp=xp)
+ x2[0] *= SQRT_2
+ x2[-1] *= SQRT_2
+
+ y1 = dct(x, type=1, norm=norm, orthogonalize=True)
+ y2 = dct(x2, type=1, norm=norm, orthogonalize=False)
+
+ y2[0] /= SQRT_2
+ y2[-1] /= SQRT_2
+ xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment',
+ cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [dct, dst])
+def test_orthogonalize_dcst2(func, norm, xp):
+ x = xp.asarray(np.random.rand(100))
+ y1 = func(x, type=2, norm=norm, orthogonalize=True)
+ y2 = func(x, type=2, norm=norm, orthogonalize=False)
+
+ y2[0 if func == dct else -1] /= SQRT_2
+ xp_assert_close(y1, y2)
+
+
+@skip_xp_backends('jax.numpy',
+ reason='jax arrays do not support item assignment',
+ cpu_only=True)
+@pytest.mark.parametrize("norm", ["backward", "ortho", "forward"])
+@pytest.mark.parametrize("func", [dct, dst])
+def test_orthogonalize_dcst3(func, norm, xp):
+ x = xp.asarray(np.random.rand(100))
+ x2 = xp_copy(x, xp=xp)
+ x2[0 if func == dct else -1] *= SQRT_2
+
+ y1 = func(x, type=3, norm=norm, orthogonalize=True)
+ y2 = func(x2, type=3, norm=norm, orthogonalize=False)
+ xp_assert_close(y1, y2)
+
+@skip_xp_backends(np_only=True,
+ reason='array-likes only supported for NumPy backend')
+@pytest.mark.parametrize("func", [dct, idct, dctn, idctn, dst, idst, dstn, idstn])
+def test_array_like(xp, func):
+ x = [[[1.0, 1.0], [1.0, 1.0]],
+ [[1.0, 1.0], [1.0, 1.0]],
+ [[1.0, 1.0], [1.0, 1.0]]]
+ xp_assert_close(func(x), func(xp.asarray(x)))
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/fftpack/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_basic.py b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_basic.py
new file mode 100644
index 0000000000000000000000000000000000000000..b13f4f5c5e1d2b38948ba168049984adb94e3dd9
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_basic.py
@@ -0,0 +1,879 @@
+# Created by Pearu Peterson, September 2002
+
+from numpy.testing import (assert_, assert_equal, assert_array_almost_equal,
+ assert_array_almost_equal_nulp, assert_array_less)
+import pytest
+from pytest import raises as assert_raises
+from scipy.fftpack import ifft, fft, fftn, ifftn, rfft, irfft, fft2
+
+from numpy import (arange, array, asarray, zeros, dot, exp, pi,
+ swapaxes, double, cdouble)
+import numpy as np
+import numpy.fft
+from numpy.random import rand
+
+# "large" composite numbers supported by FFTPACK
+LARGE_COMPOSITE_SIZES = [
+ 2**13,
+ 2**5 * 3**5,
+ 2**3 * 3**3 * 5**2,
+]
+SMALL_COMPOSITE_SIZES = [
+ 2,
+ 2*3*5,
+ 2*2*3*3,
+]
+# prime
+LARGE_PRIME_SIZES = [
+ 2011
+]
+SMALL_PRIME_SIZES = [
+ 29
+]
+
+
+def _assert_close_in_norm(x, y, rtol, size, rdt):
+ # helper function for testing
+ err_msg = f"size: {size} rdt: {rdt}"
+ assert_array_less(np.linalg.norm(x - y), rtol*np.linalg.norm(x), err_msg)
+
+
+def random(size):
+ return rand(*size)
+
+
+def direct_dft(x):
+ x = asarray(x)
+ n = len(x)
+ y = zeros(n, dtype=cdouble)
+ w = -arange(n)*(2j*pi/n)
+ for i in range(n):
+ y[i] = dot(exp(i*w), x)
+ return y
+
+
+def direct_idft(x):
+ x = asarray(x)
+ n = len(x)
+ y = zeros(n, dtype=cdouble)
+ w = arange(n)*(2j*pi/n)
+ for i in range(n):
+ y[i] = dot(exp(i*w), x)/n
+ return y
+
+
+def direct_dftn(x):
+ x = asarray(x)
+ for axis in range(len(x.shape)):
+ x = fft(x, axis=axis)
+ return x
+
+
+def direct_idftn(x):
+ x = asarray(x)
+ for axis in range(len(x.shape)):
+ x = ifft(x, axis=axis)
+ return x
+
+
+def direct_rdft(x):
+ x = asarray(x)
+ n = len(x)
+ w = -arange(n)*(2j*pi/n)
+ r = zeros(n, dtype=double)
+ for i in range(n//2+1):
+ y = dot(exp(i*w), x)
+ if i:
+ r[2*i-1] = y.real
+ if 2*i < n:
+ r[2*i] = y.imag
+ else:
+ r[0] = y.real
+ return r
+
+
+def direct_irdft(x):
+ x = asarray(x)
+ n = len(x)
+ x1 = zeros(n, dtype=cdouble)
+ for i in range(n//2+1):
+ if i:
+ if 2*i < n:
+ x1[i] = x[2*i-1] + 1j*x[2*i]
+ x1[n-i] = x[2*i-1] - 1j*x[2*i]
+ else:
+ x1[i] = x[2*i-1]
+ else:
+ x1[0] = x[0]
+ return direct_idft(x1).real
+
+
+class _TestFFTBase:
+ def setup_method(self):
+ self.cdt = None
+ self.rdt = None
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], dtype=self.cdt)
+ y = fft(x)
+ assert_equal(y.dtype, self.cdt)
+ y1 = direct_dft(x)
+ assert_array_almost_equal(y,y1)
+ x = np.array([1,2,3,4+0j,5], dtype=self.cdt)
+ assert_array_almost_equal(fft(x),direct_dft(x))
+
+ def test_n_argument_real(self):
+ x1 = np.array([1,2,3,4], dtype=self.rdt)
+ x2 = np.array([1,2,3,4], dtype=self.rdt)
+ y = fft([x1,x2],n=4)
+ assert_equal(y.dtype, self.cdt)
+ assert_equal(y.shape,(2,4))
+ assert_array_almost_equal(y[0],direct_dft(x1))
+ assert_array_almost_equal(y[1],direct_dft(x2))
+
+ def _test_n_argument_complex(self):
+ x1 = np.array([1,2,3,4+1j], dtype=self.cdt)
+ x2 = np.array([1,2,3,4+1j], dtype=self.cdt)
+ y = fft([x1,x2],n=4)
+ assert_equal(y.dtype, self.cdt)
+ assert_equal(y.shape,(2,4))
+ assert_array_almost_equal(y[0],direct_dft(x1))
+ assert_array_almost_equal(y[1],direct_dft(x2))
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, fft, [])
+ assert_raises(ValueError, fft, [[1,1],[2,2]], -5)
+
+
+class TestDoubleFFT(_TestFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+
+
+class TestSingleFFT(_TestFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+
+ reason = ("single-precision FFT implementation is partially disabled, "
+ "until accuracy issues with large prime powers are resolved")
+
+ @pytest.mark.xfail(run=False, reason=reason)
+ def test_notice(self):
+ pass
+
+
+class TestFloat16FFT:
+
+ def test_1_argument_real(self):
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+ y = fft(x1, n=4)
+ assert_equal(y.dtype, np.complex64)
+ assert_equal(y.shape, (4, ))
+ assert_array_almost_equal(y, direct_dft(x1.astype(np.float32)))
+
+ def test_n_argument_real(self):
+ x1 = np.array([1, 2, 3, 4], dtype=np.float16)
+ x2 = np.array([1, 2, 3, 4], dtype=np.float16)
+ y = fft([x1, x2], n=4)
+ assert_equal(y.dtype, np.complex64)
+ assert_equal(y.shape, (2, 4))
+ assert_array_almost_equal(y[0], direct_dft(x1.astype(np.float32)))
+ assert_array_almost_equal(y[1], direct_dft(x2.astype(np.float32)))
+
+
+class _TestIFFTBase:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = np.array([1,2,3,4+1j,1,2,3,4+2j], self.cdt)
+ y = ifft(x)
+ y1 = direct_idft(x)
+ assert_equal(y.dtype, self.cdt)
+ assert_array_almost_equal(y,y1)
+
+ x = np.array([1,2,3,4+0j,5], self.cdt)
+ assert_array_almost_equal(ifft(x),direct_idft(x))
+
+ def test_definition_real(self):
+ x = np.array([1,2,3,4,1,2,3,4], self.rdt)
+ y = ifft(x)
+ assert_equal(y.dtype, self.cdt)
+ y1 = direct_idft(x)
+ assert_array_almost_equal(y,y1)
+
+ x = np.array([1,2,3,4,5], dtype=self.rdt)
+ assert_equal(y.dtype, self.cdt)
+ assert_array_almost_equal(ifft(x),direct_idft(x))
+
+ def test_random_complex(self):
+ for size in [1,51,111,100,200,64,128,256,1024]:
+ x = random([size]).astype(self.cdt)
+ x = random([size]).astype(self.cdt) + 1j*x
+ y1 = ifft(fft(x))
+ y2 = fft(ifft(x))
+ assert_equal(y1.dtype, self.cdt)
+ assert_equal(y2.dtype, self.cdt)
+ assert_array_almost_equal(y1, x)
+ assert_array_almost_equal(y2, x)
+
+ def test_random_real(self):
+ for size in [1,51,111,100,200,64,128,256,1024]:
+ x = random([size]).astype(self.rdt)
+ y1 = ifft(fft(x))
+ y2 = fft(ifft(x))
+ assert_equal(y1.dtype, self.cdt)
+ assert_equal(y2.dtype, self.cdt)
+ assert_array_almost_equal(y1, x)
+ assert_array_almost_equal(y2, x)
+
+ def test_size_accuracy(self):
+ # Sanity check for the accuracy for prime and non-prime sized inputs
+ if self.rdt == np.float32:
+ rtol = 1e-5
+ elif self.rdt == np.float64:
+ rtol = 1e-10
+
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+ np.random.seed(1234)
+ x = np.random.rand(size).astype(self.rdt)
+ y = ifft(fft(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+ y = fft(ifft(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+ x = (x + 1j*np.random.rand(size)).astype(self.cdt)
+ y = ifft(fft(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+ y = fft(ifft(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, ifft, [])
+ assert_raises(ValueError, ifft, [[1,1],[2,2]], -5)
+
+
+class TestDoubleIFFT(_TestIFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+
+
+class TestSingleIFFT(_TestIFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+
+
+class _TestRFFTBase:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ for t in [[1, 2, 3, 4, 1, 2, 3, 4], [1, 2, 3, 4, 1, 2, 3, 4, 5]]:
+ x = np.array(t, dtype=self.rdt)
+ y = rfft(x)
+ y1 = direct_rdft(x)
+ assert_array_almost_equal(y,y1)
+ assert_equal(y.dtype, self.rdt)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, rfft, [])
+ assert_raises(ValueError, rfft, [[1,1],[2,2]], -5)
+
+ # See gh-5790
+ class MockSeries:
+ def __init__(self, data):
+ self.data = np.asarray(data)
+
+ def __getattr__(self, item):
+ try:
+ return getattr(self.data, item)
+ except AttributeError as e:
+ raise AttributeError("'MockSeries' object "
+ f"has no attribute '{item}'") from e
+
+ def test_non_ndarray_with_dtype(self):
+ x = np.array([1., 2., 3., 4., 5.])
+ xs = _TestRFFTBase.MockSeries(x)
+
+ expected = [1, 2, 3, 4, 5]
+ rfft(xs)
+
+ # Data should not have been overwritten
+ assert_equal(x, expected)
+ assert_equal(xs.data, expected)
+
+ def test_complex_input(self):
+ assert_raises(TypeError, rfft, np.arange(4, dtype=np.complex64))
+
+
+class TestRFFTDouble(_TestRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+
+
+class TestRFFTSingle(_TestRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+
+
+class _TestIRFFTBase:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x1 = [1,2,3,4,1,2,3,4]
+ x1_1 = [1,2+3j,4+1j,2+3j,4,2-3j,4-1j,2-3j]
+ x2 = [1,2,3,4,1,2,3,4,5]
+ x2_1 = [1,2+3j,4+1j,2+3j,4+5j,4-5j,2-3j,4-1j,2-3j]
+
+ def _test(x, xr):
+ y = irfft(np.array(x, dtype=self.rdt))
+ y1 = direct_irdft(x)
+ assert_equal(y.dtype, self.rdt)
+ assert_array_almost_equal(y,y1, decimal=self.ndec)
+ assert_array_almost_equal(y,ifft(xr), decimal=self.ndec)
+
+ _test(x1, x1_1)
+ _test(x2, x2_1)
+
+ def test_random_real(self):
+ for size in [1,51,111,100,200,64,128,256,1024]:
+ x = random([size]).astype(self.rdt)
+ y1 = irfft(rfft(x))
+ y2 = rfft(irfft(x))
+ assert_equal(y1.dtype, self.rdt)
+ assert_equal(y2.dtype, self.rdt)
+ assert_array_almost_equal(y1, x, decimal=self.ndec,
+ err_msg="size=%d" % size)
+ assert_array_almost_equal(y2, x, decimal=self.ndec,
+ err_msg="size=%d" % size)
+
+ def test_size_accuracy(self):
+ # Sanity check for the accuracy for prime and non-prime sized inputs
+ if self.rdt == np.float32:
+ rtol = 1e-5
+ elif self.rdt == np.float64:
+ rtol = 1e-10
+
+ for size in LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES:
+ np.random.seed(1234)
+ x = np.random.rand(size).astype(self.rdt)
+ y = irfft(rfft(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+ y = rfft(irfft(x))
+ _assert_close_in_norm(x, y, rtol, size, self.rdt)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, irfft, [])
+ assert_raises(ValueError, irfft, [[1,1],[2,2]], -5)
+
+ def test_complex_input(self):
+ assert_raises(TypeError, irfft, np.arange(4, dtype=np.complex64))
+
+
+# self.ndec is bogus; we should have a assert_array_approx_equal for number of
+# significant digits
+
+class TestIRFFTDouble(_TestIRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex128
+ self.rdt = np.float64
+ self.ndec = 14
+
+
+class TestIRFFTSingle(_TestIRFFTBase):
+ def setup_method(self):
+ self.cdt = np.complex64
+ self.rdt = np.float32
+ self.ndec = 5
+
+
+class Testfft2:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_regression_244(self):
+ """FFT returns wrong result with axes parameter."""
+ # fftn (and hence fft2) used to break when both axes and shape were
+ # used
+ x = numpy.ones((4, 4, 2))
+ y = fft2(x, shape=(8, 8), axes=(-3, -2))
+ y_r = numpy.fft.fftn(x, s=(8, 8), axes=(-3, -2))
+ assert_array_almost_equal(y, y_r)
+
+ def test_invalid_sizes(self):
+ assert_raises(ValueError, fft2, [[]])
+ assert_raises(ValueError, fft2, [[1, 1], [2, 2]], (4, -3))
+
+
+class TestFftnSingle:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ y = fftn(np.array(x, np.float32))
+ assert_(y.dtype == np.complex64,
+ msg="double precision output with single precision")
+
+ y_r = np.array(fftn(x), np.complex64)
+ assert_array_almost_equal_nulp(y, y_r)
+
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+ def test_size_accuracy_small(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, size)) + 1j*rng.random((size, size))
+ y1 = fftn(x.real.astype(np.float32))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 2000)
+
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+ def test_size_accuracy_large(self, size):
+ rand = np.random.default_rng(1234)
+ x = rand.random((size, 3)) + 1j*rand.random((size, 3))
+ y1 = fftn(x.real.astype(np.float32))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 2000)
+
+ def test_definition_float16(self):
+ x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ y = fftn(np.array(x, np.float16))
+ assert_equal(y.dtype, np.complex64)
+ y_r = np.array(fftn(x), np.complex64)
+ assert_array_almost_equal_nulp(y, y_r)
+
+ @pytest.mark.parametrize('size', SMALL_COMPOSITE_SIZES + SMALL_PRIME_SIZES)
+ def test_float16_input_small(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, size)) + 1j * rng.random((size, size))
+ y1 = fftn(x.real.astype(np.float16))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 5e5)
+
+ @pytest.mark.parametrize('size', LARGE_COMPOSITE_SIZES + LARGE_PRIME_SIZES)
+ def test_float16_input_large(self, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random((size, 3)) + 1j*rng.random((size, 3))
+ y1 = fftn(x.real.astype(np.float16))
+ y2 = fftn(x.real.astype(np.float64)).astype(np.complex64)
+
+ assert_equal(y1.dtype, np.complex64)
+ assert_array_almost_equal_nulp(y1, y2, 2e6)
+
+
+class TestFftn:
+ def setup_method(self):
+ np.random.seed(1234)
+
+ def test_definition(self):
+ x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ y = fftn(x)
+ assert_array_almost_equal(y, direct_dftn(x))
+
+ x = random((20, 26))
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+ x = random((5, 4, 3, 20))
+ assert_array_almost_equal(fftn(x), direct_dftn(x))
+
+ def test_axes_argument(self):
+ # plane == ji_plane, x== kji_space
+ plane1 = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ plane2 = [[10, 11, 12],
+ [13, 14, 15],
+ [16, 17, 18]]
+ plane3 = [[19, 20, 21],
+ [22, 23, 24],
+ [25, 26, 27]]
+ ki_plane1 = [[1, 2, 3],
+ [10, 11, 12],
+ [19, 20, 21]]
+ ki_plane2 = [[4, 5, 6],
+ [13, 14, 15],
+ [22, 23, 24]]
+ ki_plane3 = [[7, 8, 9],
+ [16, 17, 18],
+ [25, 26, 27]]
+ jk_plane1 = [[1, 10, 19],
+ [4, 13, 22],
+ [7, 16, 25]]
+ jk_plane2 = [[2, 11, 20],
+ [5, 14, 23],
+ [8, 17, 26]]
+ jk_plane3 = [[3, 12, 21],
+ [6, 15, 24],
+ [9, 18, 27]]
+ kj_plane1 = [[1, 4, 7],
+ [10, 13, 16], [19, 22, 25]]
+ kj_plane2 = [[2, 5, 8],
+ [11, 14, 17], [20, 23, 26]]
+ kj_plane3 = [[3, 6, 9],
+ [12, 15, 18], [21, 24, 27]]
+ ij_plane1 = [[1, 4, 7],
+ [2, 5, 8],
+ [3, 6, 9]]
+ ij_plane2 = [[10, 13, 16],
+ [11, 14, 17],
+ [12, 15, 18]]
+ ij_plane3 = [[19, 22, 25],
+ [20, 23, 26],
+ [21, 24, 27]]
+ ik_plane1 = [[1, 10, 19],
+ [2, 11, 20],
+ [3, 12, 21]]
+ ik_plane2 = [[4, 13, 22],
+ [5, 14, 23],
+ [6, 15, 24]]
+ ik_plane3 = [[7, 16, 25],
+ [8, 17, 26],
+ [9, 18, 27]]
+ ijk_space = [jk_plane1, jk_plane2, jk_plane3]
+ ikj_space = [kj_plane1, kj_plane2, kj_plane3]
+ jik_space = [ik_plane1, ik_plane2, ik_plane3]
+ jki_space = [ki_plane1, ki_plane2, ki_plane3]
+ kij_space = [ij_plane1, ij_plane2, ij_plane3]
+ x = array([plane1, plane2, plane3])
+
+ assert_array_almost_equal(fftn(x),
+ fftn(x, axes=(-3, -2, -1))) # kji_space
+ assert_array_almost_equal(fftn(x), fftn(x, axes=(0, 1, 2)))
+ assert_array_almost_equal(fftn(x, axes=(0, 2)), fftn(x, axes=(0, -1)))
+ y = fftn(x, axes=(2, 1, 0)) # ijk_space
+ assert_array_almost_equal(swapaxes(y, -1, -3), fftn(ijk_space))
+ y = fftn(x, axes=(2, 0, 1)) # ikj_space
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -1, -2),
+ fftn(ikj_space))
+ y = fftn(x, axes=(1, 2, 0)) # jik_space
+ assert_array_almost_equal(swapaxes(swapaxes(y, -1, -3), -3, -2),
+ fftn(jik_space))
+ y = fftn(x, axes=(1, 0, 2)) # jki_space
+ assert_array_almost_equal(swapaxes(y, -2, -3), fftn(jki_space))
+ y = fftn(x, axes=(0, 2, 1)) # kij_space
+ assert_array_almost_equal(swapaxes(y, -2, -1), fftn(kij_space))
+
+ y = fftn(x, axes=(-2, -1)) # ji_plane
+ assert_array_almost_equal(fftn(plane1), y[0])
+ assert_array_almost_equal(fftn(plane2), y[1])
+ assert_array_almost_equal(fftn(plane3), y[2])
+
+ y = fftn(x, axes=(1, 2)) # ji_plane
+ assert_array_almost_equal(fftn(plane1), y[0])
+ assert_array_almost_equal(fftn(plane2), y[1])
+ assert_array_almost_equal(fftn(plane3), y[2])
+
+ y = fftn(x, axes=(-3, -2)) # kj_plane
+ assert_array_almost_equal(fftn(x[:, :, 0]), y[:, :, 0])
+ assert_array_almost_equal(fftn(x[:, :, 1]), y[:, :, 1])
+ assert_array_almost_equal(fftn(x[:, :, 2]), y[:, :, 2])
+
+ y = fftn(x, axes=(-3, -1)) # ki_plane
+ assert_array_almost_equal(fftn(x[:, 0, :]), y[:, 0, :])
+ assert_array_almost_equal(fftn(x[:, 1, :]), y[:, 1, :])
+ assert_array_almost_equal(fftn(x[:, 2, :]), y[:, 2, :])
+
+ y = fftn(x, axes=(-1, -2)) # ij_plane
+ assert_array_almost_equal(fftn(ij_plane1), swapaxes(y[0], -2, -1))
+ assert_array_almost_equal(fftn(ij_plane2), swapaxes(y[1], -2, -1))
+ assert_array_almost_equal(fftn(ij_plane3), swapaxes(y[2], -2, -1))
+
+ y = fftn(x, axes=(-1, -3)) # ik_plane
+ assert_array_almost_equal(fftn(ik_plane1),
+ swapaxes(y[:, 0, :], -1, -2))
+ assert_array_almost_equal(fftn(ik_plane2),
+ swapaxes(y[:, 1, :], -1, -2))
+ assert_array_almost_equal(fftn(ik_plane3),
+ swapaxes(y[:, 2, :], -1, -2))
+
+ y = fftn(x, axes=(-2, -3)) # jk_plane
+ assert_array_almost_equal(fftn(jk_plane1),
+ swapaxes(y[:, :, 0], -1, -2))
+ assert_array_almost_equal(fftn(jk_plane2),
+ swapaxes(y[:, :, 1], -1, -2))
+ assert_array_almost_equal(fftn(jk_plane3),
+ swapaxes(y[:, :, 2], -1, -2))
+
+ y = fftn(x, axes=(-1,)) # i_line
+ for i in range(3):
+ for j in range(3):
+ assert_array_almost_equal(fft(x[i, j, :]), y[i, j, :])
+ y = fftn(x, axes=(-2,)) # j_line
+ for i in range(3):
+ for j in range(3):
+ assert_array_almost_equal(fft(x[i, :, j]), y[i, :, j])
+ y = fftn(x, axes=(0,)) # k_line
+ for i in range(3):
+ for j in range(3):
+ assert_array_almost_equal(fft(x[:, i, j]), y[:, i, j])
+
+ y = fftn(x, axes=()) # point
+ assert_array_almost_equal(y, x)
+
+ def test_shape_argument(self):
+ small_x = [[1, 2, 3],
+ [4, 5, 6]]
+ large_x1 = [[1, 2, 3, 0],
+ [4, 5, 6, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]]
+
+ y = fftn(small_x, shape=(4, 4))
+ assert_array_almost_equal(y, fftn(large_x1))
+
+ y = fftn(small_x, shape=(3, 4))
+ assert_array_almost_equal(y, fftn(large_x1[:-1]))
+
+ def test_shape_axes_argument(self):
+ small_x = [[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]]
+ large_x1 = array([[1, 2, 3, 0],
+ [4, 5, 6, 0],
+ [7, 8, 9, 0],
+ [0, 0, 0, 0]])
+ y = fftn(small_x, shape=(4, 4), axes=(-2, -1))
+ assert_array_almost_equal(y, fftn(large_x1))
+ y = fftn(small_x, shape=(4, 4), axes=(-1, -2))
+
+ assert_array_almost_equal(y, swapaxes(
+ fftn(swapaxes(large_x1, -1, -2)), -1, -2))
+
+ def test_shape_axes_argument2(self):
+ # Change shape of the last axis
+ x = numpy.random.random((10, 5, 3, 7))
+ y = fftn(x, axes=(-1,), shape=(8,))
+ assert_array_almost_equal(y, fft(x, axis=-1, n=8))
+
+ # Change shape of an arbitrary axis which is not the last one
+ x = numpy.random.random((10, 5, 3, 7))
+ y = fftn(x, axes=(-2,), shape=(8,))
+ assert_array_almost_equal(y, fft(x, axis=-2, n=8))
+
+ # Change shape of axes: cf #244, where shape and axes were mixed up
+ x = numpy.random.random((4, 4, 2))
+ y = fftn(x, axes=(-3, -2), shape=(8, 8))
+ assert_array_almost_equal(y,
+ numpy.fft.fftn(x, axes=(-3, -2), s=(8, 8)))
+
+ def test_shape_argument_more(self):
+ x = zeros((4, 4, 2))
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ fftn(x, shape=(8, 8, 2, 1))
+
+ def test_invalid_sizes(self):
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[1, 0\]\) specified"):
+ fftn([[]])
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[4, -3\]\) specified"):
+ fftn([[1, 1], [2, 2]], (4, -3))
+
+
+class TestIfftn:
+ dtype = None
+ cdtype = None
+
+ def setup_method(self):
+ np.random.seed(1234)
+
+ @pytest.mark.parametrize('dtype,cdtype,maxnlp',
+ [(np.float64, np.complex128, 2000),
+ (np.float32, np.complex64, 3500)])
+ def test_definition(self, dtype, cdtype, maxnlp):
+ rng = np.random.default_rng(1234)
+ x = np.array([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]], dtype=dtype)
+ y = ifftn(x)
+ assert_equal(y.dtype, cdtype)
+ assert_array_almost_equal_nulp(y, direct_idftn(x), maxnlp)
+
+ x = rng.random((20, 26))
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+ x = rng.random((5, 4, 3, 20))
+ assert_array_almost_equal_nulp(ifftn(x), direct_idftn(x), maxnlp)
+
+ @pytest.mark.parametrize('maxnlp', [2000, 3500])
+ @pytest.mark.parametrize('size', [1, 2, 51, 32, 64, 92])
+ def test_random_complex(self, maxnlp, size):
+ rng = np.random.default_rng(1234)
+ x = rng.random([size, size]) + 1j * rng.random([size, size])
+ assert_array_almost_equal_nulp(ifftn(fftn(x)), x, maxnlp)
+ assert_array_almost_equal_nulp(fftn(ifftn(x)), x, maxnlp)
+
+ def test_invalid_sizes(self):
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[1, 0\]\) specified"):
+ ifftn([[]])
+
+ with assert_raises(ValueError,
+ match="invalid number of data points"
+ r" \(\[4, -3\]\) specified"):
+ ifftn([[1, 1], [2, 2]], (4, -3))
+
+
+class FakeArray:
+ def __init__(self, data):
+ self._data = data
+ self.__array_interface__ = data.__array_interface__
+
+
+class FakeArray2:
+ def __init__(self, data):
+ self._data = data
+
+ def __array__(self, dtype=None, copy=None):
+ return self._data
+
+
+class TestOverwrite:
+ """Check input overwrite behavior of the FFT functions."""
+
+ real_dtypes = (np.float32, np.float64)
+ dtypes = real_dtypes + (np.complex64, np.complex128)
+ fftsizes = [8, 16, 32]
+
+ def _check(self, x, routine, fftsize, axis, overwrite_x):
+ x2 = x.copy()
+ for fake in [lambda x: x, FakeArray, FakeArray2]:
+ routine(fake(x2), fftsize, axis, overwrite_x=overwrite_x)
+
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+ f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+ if not overwrite_x:
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+ def _check_1d(self, routine, dtype, shape, axis, overwritable_dtypes,
+ fftsize, overwrite_x):
+ np.random.seed(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+ else:
+ data = np.random.randn(*shape)
+ data = data.astype(dtype)
+
+ self._check(data, routine, fftsize, axis,
+ overwrite_x=overwrite_x)
+
+ @pytest.mark.parametrize('dtype', dtypes)
+ @pytest.mark.parametrize('fftsize', fftsizes)
+ @pytest.mark.parametrize('overwrite_x', [True, False])
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
+ ((16, 2), 0),
+ ((2, 16), 1)])
+ def test_fft_ifft(self, dtype, fftsize, overwrite_x, shape, axes):
+ overwritable = (np.complex128, np.complex64)
+ self._check_1d(fft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+ self._check_1d(ifft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+
+ @pytest.mark.parametrize('dtype', real_dtypes)
+ @pytest.mark.parametrize('fftsize', fftsizes)
+ @pytest.mark.parametrize('overwrite_x', [True, False])
+ @pytest.mark.parametrize('shape,axes', [((16,), -1),
+ ((16, 2), 0),
+ ((2, 16), 1)])
+ def test_rfft_irfft(self, dtype, fftsize, overwrite_x, shape, axes):
+ overwritable = self.real_dtypes
+ self._check_1d(irfft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+ self._check_1d(rfft, dtype, shape, axes, overwritable,
+ fftsize, overwrite_x)
+
+ def _check_nd_one(self, routine, dtype, shape, axes, overwritable_dtypes,
+ overwrite_x):
+ np.random.seed(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ data = np.random.randn(*shape) + 1j*np.random.randn(*shape)
+ else:
+ data = np.random.randn(*shape)
+ data = data.astype(dtype)
+
+ def fftshape_iter(shp):
+ if len(shp) <= 0:
+ yield ()
+ else:
+ for j in (shp[0]//2, shp[0], shp[0]*2):
+ for rest in fftshape_iter(shp[1:]):
+ yield (j,) + rest
+
+ if axes is None:
+ part_shape = shape
+ else:
+ part_shape = tuple(np.take(shape, axes))
+
+ for fftshape in fftshape_iter(part_shape):
+ self._check(data, routine, fftshape, axes,
+ overwrite_x=overwrite_x)
+ if data.ndim > 1:
+ self._check(data.T, routine, fftshape, axes,
+ overwrite_x=overwrite_x)
+
+ @pytest.mark.parametrize('dtype', dtypes)
+ @pytest.mark.parametrize('overwrite_x', [True, False])
+ @pytest.mark.parametrize('shape,axes', [((16,), None),
+ ((16,), (0,)),
+ ((16, 2), (0,)),
+ ((2, 16), (1,)),
+ ((8, 16), None),
+ ((8, 16), (0, 1)),
+ ((8, 16, 2), (0, 1)),
+ ((8, 16, 2), (1, 2)),
+ ((8, 16, 2), (0,)),
+ ((8, 16, 2), (1,)),
+ ((8, 16, 2), (2,)),
+ ((8, 16, 2), None),
+ ((8, 16, 2), (0, 1, 2))])
+ def test_fftn_ifftn(self, dtype, overwrite_x, shape, axes):
+ overwritable = (np.complex128, np.complex64)
+ self._check_nd_one(fftn, dtype, shape, axes, overwritable,
+ overwrite_x)
+ self._check_nd_one(ifftn, dtype, shape, axes, overwritable,
+ overwrite_x)
+
+
+@pytest.mark.parametrize('func', [fftn, ifftn, fft2])
+def test_shape_axes_ndarray(func):
+ # Test fftn and ifftn work with NumPy arrays for shape and axes arguments
+ # Regression test for gh-13342
+ a = np.random.rand(10, 10)
+
+ expect = func(a, shape=(5, 5))
+ actual = func(a, shape=np.array([5, 5]))
+ assert_equal(expect, actual)
+
+ expect = func(a, axes=(-1,))
+ actual = func(a, axes=np.array([-1,]))
+ assert_equal(expect, actual)
+
+ expect = func(a, shape=(4, 7), axes=(1, 0))
+ actual = func(a, shape=np.array([4, 7]), axes=np.array([1, 0]))
+ assert_equal(expect, actual)
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_helper.py b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ede3120ed3e434bb8019148e5689fdc168e4bc5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_helper.py
@@ -0,0 +1,54 @@
+# Created by Pearu Peterson, September 2002
+
+__usage__ = """
+Build fftpack:
+ python setup_fftpack.py build
+Run tests if scipy is installed:
+ python -c 'import scipy;scipy.fftpack.test()'
+Run tests if fftpack is not installed:
+ python tests/test_helper.py []
+"""
+
+from numpy.testing import assert_array_almost_equal
+from scipy.fftpack import fftshift, ifftshift, fftfreq, rfftfreq
+
+from numpy import pi, random
+
+class TestFFTShift:
+
+ def test_definition(self):
+ x = [0,1,2,3,4,-4,-3,-2,-1]
+ y = [-4,-3,-2,-1,0,1,2,3,4]
+ assert_array_almost_equal(fftshift(x),y)
+ assert_array_almost_equal(ifftshift(y),x)
+ x = [0,1,2,3,4,-5,-4,-3,-2,-1]
+ y = [-5,-4,-3,-2,-1,0,1,2,3,4]
+ assert_array_almost_equal(fftshift(x),y)
+ assert_array_almost_equal(ifftshift(y),x)
+
+ def test_inverse(self):
+ for n in [1,4,9,100,211]:
+ x = random.random((n,))
+ assert_array_almost_equal(ifftshift(fftshift(x)),x)
+
+
+class TestFFTFreq:
+
+ def test_definition(self):
+ x = [0,1,2,3,4,-4,-3,-2,-1]
+ assert_array_almost_equal(9*fftfreq(9),x)
+ assert_array_almost_equal(9*pi*fftfreq(9,pi),x)
+ x = [0,1,2,3,4,-5,-4,-3,-2,-1]
+ assert_array_almost_equal(10*fftfreq(10),x)
+ assert_array_almost_equal(10*pi*fftfreq(10,pi),x)
+
+
+class TestRFFTFreq:
+
+ def test_definition(self):
+ x = [0,1,1,2,2,3,3,4,4]
+ assert_array_almost_equal(9*rfftfreq(9),x)
+ assert_array_almost_equal(9*pi*rfftfreq(9,pi),x)
+ x = [0,1,1,2,2,3,3,4,4,5]
+ assert_array_almost_equal(10*rfftfreq(10),x)
+ assert_array_almost_equal(10*pi*rfftfreq(10,pi),x)
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_import.py b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_import.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d2166b1f2e3eff94a82d103c6caa8b881522c84
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_import.py
@@ -0,0 +1,33 @@
+"""Test possibility of patching fftpack with pyfftw.
+
+No module source outside of scipy.fftpack should contain an import of
+the form `from scipy.fftpack import ...`, so that a simple replacement
+of scipy.fftpack by the corresponding fftw interface completely swaps
+the two FFT implementations.
+
+Because this simply inspects source files, we only need to run the test
+on one version of Python.
+"""
+
+
+from pathlib import Path
+import re
+import tokenize
+import pytest
+from numpy.testing import assert_
+import scipy
+
+class TestFFTPackImport:
+ @pytest.mark.slow
+ def test_fftpack_import(self):
+ base = Path(scipy.__file__).parent
+ regexp = r"\s*from.+\.fftpack import .*\n"
+ for path in base.rglob("*.py"):
+ if base / "fftpack" in path.parents:
+ continue
+ # use tokenize to auto-detect encoding on systems where no
+ # default encoding is defined (e.g., LANG='C')
+ with tokenize.open(str(path)) as file:
+ assert_(all(not re.fullmatch(regexp, line)
+ for line in file),
+ f"{path} contains an import from fftpack")
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
new file mode 100644
index 0000000000000000000000000000000000000000..b462663eff3d127715915e8167498974f3c00405
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_pseudo_diffs.py
@@ -0,0 +1,388 @@
+# Created by Pearu Peterson, September 2002
+
+__usage__ = """
+Build fftpack:
+ python setup_fftpack.py build
+Run tests if scipy is installed:
+ python -c 'import scipy;scipy.fftpack.test()'
+Run tests if fftpack is not installed:
+ python tests/test_pseudo_diffs.py []
+"""
+
+from numpy.testing import (assert_equal, assert_almost_equal,
+ assert_array_almost_equal)
+from scipy.fftpack import (diff, fft, ifft, tilbert, itilbert, hilbert,
+ ihilbert, shift, fftfreq, cs_diff, sc_diff,
+ ss_diff, cc_diff)
+
+import numpy as np
+from numpy import arange, sin, cos, pi, exp, tanh, sum, sign
+from numpy.random import random
+
+
+def direct_diff(x,k=1,period=None):
+ fx = fft(x)
+ n = len(fx)
+ if period is None:
+ period = 2*pi
+ w = fftfreq(n)*2j*pi/period*n
+ if k < 0:
+ w = 1 / w**k
+ w[0] = 0.0
+ else:
+ w = w**k
+ if n > 2000:
+ w[250:n-250] = 0.0
+ return ifft(w*fx).real
+
+
+def direct_tilbert(x,h=1,period=None):
+ fx = fft(x)
+ n = len(fx)
+ if period is None:
+ period = 2*pi
+ w = fftfreq(n)*h*2*pi/period*n
+ w[0] = 1
+ w = 1j/tanh(w)
+ w[0] = 0j
+ return ifft(w*fx)
+
+
+def direct_itilbert(x,h=1,period=None):
+ fx = fft(x)
+ n = len(fx)
+ if period is None:
+ period = 2*pi
+ w = fftfreq(n)*h*2*pi/period*n
+ w = -1j*tanh(w)
+ return ifft(w*fx)
+
+
+def direct_hilbert(x):
+ fx = fft(x)
+ n = len(fx)
+ w = fftfreq(n)*n
+ w = 1j*sign(w)
+ return ifft(w*fx)
+
+
+def direct_ihilbert(x):
+ return -direct_hilbert(x)
+
+
+def direct_shift(x,a,period=None):
+ n = len(x)
+ if period is None:
+ k = fftfreq(n)*1j*n
+ else:
+ k = fftfreq(n)*2j*pi/period*n
+ return ifft(fft(x)*exp(k*a)).real
+
+
+class TestDiff:
+
+ def test_definition(self):
+ for n in [16,17,64,127,32]:
+ x = arange(n)*2*pi/n
+ assert_array_almost_equal(diff(sin(x)),direct_diff(sin(x)))
+ assert_array_almost_equal(diff(sin(x),2),direct_diff(sin(x),2))
+ assert_array_almost_equal(diff(sin(x),3),direct_diff(sin(x),3))
+ assert_array_almost_equal(diff(sin(x),4),direct_diff(sin(x),4))
+ assert_array_almost_equal(diff(sin(x),5),direct_diff(sin(x),5))
+ assert_array_almost_equal(diff(sin(2*x),3),direct_diff(sin(2*x),3))
+ assert_array_almost_equal(diff(sin(2*x),4),direct_diff(sin(2*x),4))
+ assert_array_almost_equal(diff(cos(x)),direct_diff(cos(x)))
+ assert_array_almost_equal(diff(cos(x),2),direct_diff(cos(x),2))
+ assert_array_almost_equal(diff(cos(x),3),direct_diff(cos(x),3))
+ assert_array_almost_equal(diff(cos(x),4),direct_diff(cos(x),4))
+ assert_array_almost_equal(diff(cos(2*x)),direct_diff(cos(2*x)))
+ assert_array_almost_equal(diff(sin(x*n/8)),direct_diff(sin(x*n/8)))
+ assert_array_almost_equal(diff(cos(x*n/8)),direct_diff(cos(x*n/8)))
+ for k in range(5):
+ assert_array_almost_equal(diff(sin(4*x),k),direct_diff(sin(4*x),k))
+ assert_array_almost_equal(diff(cos(4*x),k),direct_diff(cos(4*x),k))
+
+ def test_period(self):
+ for n in [17,64]:
+ x = arange(n)/float(n)
+ assert_array_almost_equal(diff(sin(2*pi*x),period=1),
+ 2*pi*cos(2*pi*x))
+ assert_array_almost_equal(diff(sin(2*pi*x),3,period=1),
+ -(2*pi)**3*cos(2*pi*x))
+
+ def test_sin(self):
+ for n in [32,64,77]:
+ x = arange(n)*2*pi/n
+ assert_array_almost_equal(diff(sin(x)),cos(x))
+ assert_array_almost_equal(diff(cos(x)),-sin(x))
+ assert_array_almost_equal(diff(sin(x),2),-sin(x))
+ assert_array_almost_equal(diff(sin(x),4),sin(x))
+ assert_array_almost_equal(diff(sin(4*x)),4*cos(4*x))
+ assert_array_almost_equal(diff(sin(sin(x))),cos(x)*cos(sin(x)))
+
+ def test_expr(self):
+ for n in [64,77,100,128,256,512,1024,2048,4096,8192][:5]:
+ x = arange(n)*2*pi/n
+ f = sin(x)*cos(4*x)+exp(sin(3*x))
+ df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
+ ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
+ - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
+ d1 = diff(f)
+ assert_array_almost_equal(d1,df)
+ assert_array_almost_equal(diff(df),ddf)
+ assert_array_almost_equal(diff(f,2),ddf)
+ assert_array_almost_equal(diff(ddf,-1),df)
+
+ def test_expr_large(self):
+ for n in [2048,4096]:
+ x = arange(n)*2*pi/n
+ f = sin(x)*cos(4*x)+exp(sin(3*x))
+ df = cos(x)*cos(4*x)-4*sin(x)*sin(4*x)+3*cos(3*x)*exp(sin(3*x))
+ ddf = -17*sin(x)*cos(4*x)-8*cos(x)*sin(4*x)\
+ - 9*sin(3*x)*exp(sin(3*x))+9*cos(3*x)**2*exp(sin(3*x))
+ assert_array_almost_equal(diff(f),df)
+ assert_array_almost_equal(diff(df),ddf)
+ assert_array_almost_equal(diff(ddf,-1),df)
+ assert_array_almost_equal(diff(f,2),ddf)
+
+ def test_int(self):
+ n = 64
+ x = arange(n)*2*pi/n
+ assert_array_almost_equal(diff(sin(x),-1),-cos(x))
+ assert_array_almost_equal(diff(sin(x),-2),-sin(x))
+ assert_array_almost_equal(diff(sin(x),-4),sin(x))
+ assert_array_almost_equal(diff(2*cos(2*x),-1),sin(2*x))
+
+ def test_random_even(self):
+ rng = np.random.default_rng(1234)
+ for k in [0,2,4,6]:
+ for n in [60,32,64,56,55]:
+ f = rng.random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ # zeroing Nyquist mode:
+ f = diff(diff(f,1),-1)
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+ def test_random_odd(self):
+ rng = np.random.default_rng(1234)
+ for k in [0,1,2,3,4,5,6]:
+ for n in [33,65,55]:
+ f = rng.random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+ def test_zero_nyquist(self):
+ rng = np.random.default_rng(1234)
+ for k in [0,1,2,3,4,5,6]:
+ for n in [32,33,64,56,55]:
+ f = rng.random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ # zeroing Nyquist mode:
+ f = diff(diff(f,1),-1)
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(diff(diff(f,k),-k),f)
+ assert_array_almost_equal(diff(diff(f,-k),k),f)
+
+
+class TestTilbert:
+
+ def test_definition(self):
+ for h in [0.1,0.5,1,5.5,10]:
+ for n in [16,17,64,127]:
+ x = arange(n)*2*pi/n
+ y = tilbert(sin(x),h)
+ y1 = direct_tilbert(sin(x),h)
+ assert_array_almost_equal(y,y1)
+ assert_array_almost_equal(tilbert(sin(x),h),
+ direct_tilbert(sin(x),h))
+ assert_array_almost_equal(tilbert(sin(2*x),h),
+ direct_tilbert(sin(2*x),h))
+
+ def test_random_even(self):
+ for h in [0.1,0.5,1,5.5,10]:
+ for n in [32,64,56]:
+ f = random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(direct_tilbert(direct_itilbert(f,h),h),f)
+
+ def test_random_odd(self):
+ rng = np.random.default_rng(1234)
+ for h in [0.1,0.5,1,5.5,10]:
+ for n in [33,65,55]:
+ f = rng.random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(itilbert(tilbert(f,h),h),f)
+ assert_array_almost_equal(tilbert(itilbert(f,h),h),f)
+
+
+class TestITilbert:
+
+ def test_definition(self):
+ for h in [0.1,0.5,1,5.5,10]:
+ for n in [16,17,64,127]:
+ x = arange(n)*2*pi/n
+ y = itilbert(sin(x),h)
+ y1 = direct_itilbert(sin(x),h)
+ assert_array_almost_equal(y,y1)
+ assert_array_almost_equal(itilbert(sin(x),h),
+ direct_itilbert(sin(x),h))
+ assert_array_almost_equal(itilbert(sin(2*x),h),
+ direct_itilbert(sin(2*x),h))
+
+
+class TestHilbert:
+
+ def test_definition(self):
+ for n in [16,17,64,127]:
+ x = arange(n)*2*pi/n
+ y = hilbert(sin(x))
+ y1 = direct_hilbert(sin(x))
+ assert_array_almost_equal(y,y1)
+ assert_array_almost_equal(hilbert(sin(2*x)),
+ direct_hilbert(sin(2*x)))
+
+ def test_tilbert_relation(self):
+ for n in [16,17,64,127]:
+ x = arange(n)*2*pi/n
+ f = sin(x)+cos(2*x)*sin(x)
+ y = hilbert(f)
+ y1 = direct_hilbert(f)
+ assert_array_almost_equal(y,y1)
+ y2 = tilbert(f,h=10)
+ assert_array_almost_equal(y,y2)
+
+ def test_random_odd(self):
+ rng = np.random.default_rng(1234)
+ for n in [33,65,55]:
+ f = rng.random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(ihilbert(hilbert(f)),f)
+ assert_array_almost_equal(hilbert(ihilbert(f)),f)
+
+ def test_random_even(self):
+ rng = np.random.default_rng(1234)
+ for n in [32,64,56]:
+ f = rng.random((n,))
+ af = sum(f,axis=0)/n
+ f = f-af
+ # zeroing Nyquist mode:
+ f = diff(diff(f,1),-1)
+ assert_almost_equal(sum(f,axis=0),0.0)
+ assert_array_almost_equal(direct_hilbert(direct_ihilbert(f)),f)
+ assert_array_almost_equal(hilbert(ihilbert(f)),f)
+
+
+class TestIHilbert:
+
+ def test_definition(self):
+ for n in [16,17,64,127]:
+ x = arange(n)*2*pi/n
+ y = ihilbert(sin(x))
+ y1 = direct_ihilbert(sin(x))
+ assert_array_almost_equal(y,y1)
+ assert_array_almost_equal(ihilbert(sin(2*x)),
+ direct_ihilbert(sin(2*x)))
+
+ def test_itilbert_relation(self):
+ for n in [16,17,64,127]:
+ x = arange(n)*2*pi/n
+ f = sin(x)+cos(2*x)*sin(x)
+ y = ihilbert(f)
+ y1 = direct_ihilbert(f)
+ assert_array_almost_equal(y,y1)
+ y2 = itilbert(f,h=10)
+ assert_array_almost_equal(y,y2)
+
+
+class TestShift:
+
+ def test_definition(self):
+ for n in [18,17,64,127,32,2048,256]:
+ x = arange(n)*2*pi/n
+ for a in [0.1,3]:
+ assert_array_almost_equal(shift(sin(x),a),direct_shift(sin(x),a))
+ assert_array_almost_equal(shift(sin(x),a),sin(x+a))
+ assert_array_almost_equal(shift(cos(x),a),cos(x+a))
+ assert_array_almost_equal(shift(cos(2*x)+sin(x),a),
+ cos(2*(x+a))+sin(x+a))
+ assert_array_almost_equal(shift(exp(sin(x)),a),exp(sin(x+a)))
+ assert_array_almost_equal(shift(sin(x),2*pi),sin(x))
+ assert_array_almost_equal(shift(sin(x),pi),-sin(x))
+ assert_array_almost_equal(shift(sin(x),pi/2),cos(x))
+
+
+class TestOverwrite:
+ """Check input overwrite behavior """
+
+ real_dtypes = (np.float32, np.float64)
+ dtypes = real_dtypes + (np.complex64, np.complex128)
+
+ def _check(self, x, routine, *args, **kwargs):
+ x2 = x.copy()
+ routine(x2, *args, **kwargs)
+ sig = routine.__name__
+ if args:
+ sig += repr(args)
+ if kwargs:
+ sig += repr(kwargs)
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+ def _check_1d(self, routine, dtype, shape, *args, **kwargs):
+ # rng = np.random.default_rng(1234)
+ rng = np.random.RandomState(1234)
+ # np.random.seed(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ data = rng.randn(*shape) + 1j*rng.randn(*shape)
+ else:
+ data = rng.randn(*shape)
+ data = data.astype(dtype)
+ self._check(data, routine, *args, **kwargs)
+
+ def test_diff(self):
+ for dtype in self.dtypes:
+ self._check_1d(diff, dtype, (16,))
+
+ def test_tilbert(self):
+ for dtype in self.dtypes:
+ self._check_1d(tilbert, dtype, (16,), 1.6)
+
+ def test_itilbert(self):
+ for dtype in self.dtypes:
+ self._check_1d(itilbert, dtype, (16,), 1.6)
+
+ def test_hilbert(self):
+ for dtype in self.dtypes:
+ self._check_1d(hilbert, dtype, (16,))
+
+ def test_cs_diff(self):
+ for dtype in self.dtypes:
+ self._check_1d(cs_diff, dtype, (16,), 1.0, 4.0)
+
+ def test_sc_diff(self):
+ for dtype in self.dtypes:
+ self._check_1d(sc_diff, dtype, (16,), 1.0, 4.0)
+
+ def test_ss_diff(self):
+ for dtype in self.dtypes:
+ self._check_1d(ss_diff, dtype, (16,), 1.0, 4.0)
+
+ def test_cc_diff(self):
+ for dtype in self.dtypes:
+ self._check_1d(cc_diff, dtype, (16,), 1.0, 4.0)
+
+ def test_shift(self):
+ for dtype in self.dtypes:
+ self._check_1d(shift, dtype, (16,), 1.0)
diff --git a/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_real_transforms.py b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_real_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..6090336a1cd29a12cfa74245cb00fbaf6cd592f1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/fftpack/tests/test_real_transforms.py
@@ -0,0 +1,837 @@
+from os.path import join, dirname
+import threading
+
+import numpy as np
+from numpy.testing import assert_array_almost_equal, assert_equal
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fftpack._realtransforms import (
+ dct, idct, dst, idst, dctn, idctn, dstn, idstn)
+
+# Matlab reference data
+MDATA = np.load(join(dirname(__file__), 'test.npz'))
+X = [MDATA['x%d' % i] for i in range(8)]
+Y = [MDATA['y%d' % i] for i in range(8)]
+
+# FFTW reference data: the data are organized as follows:
+# * SIZES is an array containing all available sizes
+# * for every type (1, 2, 3, 4) and every size, the array dct_type_size
+# contains the output of the DCT applied to the input np.linspace(0, size-1,
+# size)
+FFTWDATA_DOUBLE = np.load(join(dirname(__file__), 'fftw_double_ref.npz'))
+FFTWDATA_SINGLE = np.load(join(dirname(__file__), 'fftw_single_ref.npz'))
+FFTWDATA_SIZES = FFTWDATA_DOUBLE['sizes']
+
+
+def fftw_dct_ref(type, size, dt):
+ x = np.linspace(0, size-1, size).astype(dt)
+ dt = np.result_type(np.float32, dt)
+ if dt == np.float64:
+ data = FFTWDATA_DOUBLE
+ elif dt == np.float32:
+ data = FFTWDATA_SINGLE
+ else:
+ raise ValueError()
+ y = (data['dct_%d_%d' % (type, size)]).astype(dt)
+ return x, y, dt
+
+
+def fftw_dst_ref(type, size, dt):
+ x = np.linspace(0, size-1, size).astype(dt)
+ dt = np.result_type(np.float32, dt)
+ if dt == np.float64:
+ data = FFTWDATA_DOUBLE
+ elif dt == np.float32:
+ data = FFTWDATA_SINGLE
+ else:
+ raise ValueError()
+ y = (data['dst_%d_%d' % (type, size)]).astype(dt)
+ return x, y, dt
+
+
+def dct_2d_ref(x, **kwargs):
+ """Calculate reference values for testing dct2."""
+ x = np.array(x, copy=True)
+ for row in range(x.shape[0]):
+ x[row, :] = dct(x[row, :], **kwargs)
+ for col in range(x.shape[1]):
+ x[:, col] = dct(x[:, col], **kwargs)
+ return x
+
+
+def idct_2d_ref(x, **kwargs):
+ """Calculate reference values for testing idct2."""
+ x = np.array(x, copy=True)
+ for row in range(x.shape[0]):
+ x[row, :] = idct(x[row, :], **kwargs)
+ for col in range(x.shape[1]):
+ x[:, col] = idct(x[:, col], **kwargs)
+ return x
+
+
+def dst_2d_ref(x, **kwargs):
+ """Calculate reference values for testing dst2."""
+ x = np.array(x, copy=True)
+ for row in range(x.shape[0]):
+ x[row, :] = dst(x[row, :], **kwargs)
+ for col in range(x.shape[1]):
+ x[:, col] = dst(x[:, col], **kwargs)
+ return x
+
+
+def idst_2d_ref(x, **kwargs):
+ """Calculate reference values for testing idst2."""
+ x = np.array(x, copy=True)
+ for row in range(x.shape[0]):
+ x[row, :] = idst(x[row, :], **kwargs)
+ for col in range(x.shape[1]):
+ x[:, col] = idst(x[:, col], **kwargs)
+ return x
+
+
+def naive_dct1(x, norm=None):
+ """Calculate textbook definition version of DCT-I."""
+ x = np.array(x, copy=True)
+ N = len(x)
+ M = N-1
+ y = np.zeros(N)
+ m0, m = 1, 2
+ if norm == 'ortho':
+ m0 = np.sqrt(1.0/M)
+ m = np.sqrt(2.0/M)
+ for k in range(N):
+ for n in range(1, N-1):
+ y[k] += m*x[n]*np.cos(np.pi*n*k/M)
+ y[k] += m0 * x[0]
+ y[k] += m0 * x[N-1] * (1 if k % 2 == 0 else -1)
+ if norm == 'ortho':
+ y[0] *= 1/np.sqrt(2)
+ y[N-1] *= 1/np.sqrt(2)
+ return y
+
+
+def naive_dst1(x, norm=None):
+ """Calculate textbook definition version of DST-I."""
+ x = np.array(x, copy=True)
+ N = len(x)
+ M = N+1
+ y = np.zeros(N)
+ for k in range(N):
+ for n in range(N):
+ y[k] += 2*x[n]*np.sin(np.pi*(n+1.0)*(k+1.0)/M)
+ if norm == 'ortho':
+ y *= np.sqrt(0.5/M)
+ return y
+
+
+def naive_dct4(x, norm=None):
+ """Calculate textbook definition version of DCT-IV."""
+ x = np.array(x, copy=True)
+ N = len(x)
+ y = np.zeros(N)
+ for k in range(N):
+ for n in range(N):
+ y[k] += x[n]*np.cos(np.pi*(n+0.5)*(k+0.5)/(N))
+ if norm == 'ortho':
+ y *= np.sqrt(2.0/N)
+ else:
+ y *= 2
+ return y
+
+
+def naive_dst4(x, norm=None):
+ """Calculate textbook definition version of DST-IV."""
+ x = np.array(x, copy=True)
+ N = len(x)
+ y = np.zeros(N)
+ for k in range(N):
+ for n in range(N):
+ y[k] += x[n]*np.sin(np.pi*(n+0.5)*(k+0.5)/(N))
+ if norm == 'ortho':
+ y *= np.sqrt(2.0/N)
+ else:
+ y *= 2
+ return y
+
+
+class TestComplex:
+ def test_dct_complex64(self):
+ y = dct(1j*np.arange(5, dtype=np.complex64))
+ x = 1j*dct(np.arange(5))
+ assert_array_almost_equal(x, y)
+
+ def test_dct_complex(self):
+ y = dct(np.arange(5)*1j)
+ x = 1j*dct(np.arange(5))
+ assert_array_almost_equal(x, y)
+
+ def test_idct_complex(self):
+ y = idct(np.arange(5)*1j)
+ x = 1j*idct(np.arange(5))
+ assert_array_almost_equal(x, y)
+
+ def test_dst_complex64(self):
+ y = dst(np.arange(5, dtype=np.complex64)*1j)
+ x = 1j*dst(np.arange(5))
+ assert_array_almost_equal(x, y)
+
+ def test_dst_complex(self):
+ y = dst(np.arange(5)*1j)
+ x = 1j*dst(np.arange(5))
+ assert_array_almost_equal(x, y)
+
+ def test_idst_complex(self):
+ y = idst(np.arange(5)*1j)
+ x = 1j*idst(np.arange(5))
+ assert_array_almost_equal(x, y)
+
+
+class _TestDCTBase:
+ def setup_method(self):
+ self.rdt = None
+ self.dec = 14
+ self.type = None
+
+ @pytest.fixture
+ def dct_lock(self):
+ return threading.Lock()
+
+ def test_definition(self, dct_lock):
+ for i in FFTWDATA_SIZES:
+ with dct_lock:
+ x, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
+ y = dct(x, type=self.type)
+ assert_equal(y.dtype, dt)
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
+ # should really use something like assert_array_approx_equal. The
+ # difference is due to fftw using a better algorithm w.r.t error
+ # propagation compared to the ones from fftpack.
+ assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
+ err_msg="Size %d failed" % i)
+
+ def test_axis(self):
+ nt = 2
+ rng = np.random.RandomState(1234)
+ for i in [7, 8, 9, 16, 32, 64]:
+ x = rng.randn(nt, i)
+ y = dct(x, type=self.type)
+ for j in range(nt):
+ assert_array_almost_equal(y[j], dct(x[j], type=self.type),
+ decimal=self.dec)
+
+ x = x.T
+ y = dct(x, axis=0, type=self.type)
+ for j in range(nt):
+ assert_array_almost_equal(y[:,j], dct(x[:,j], type=self.type),
+ decimal=self.dec)
+
+
+class _TestDCTIBase(_TestDCTBase):
+ def test_definition_ortho(self):
+ # Test orthornomal mode.
+ dt = np.result_type(np.float32, self.rdt)
+ for xr in X:
+ x = np.array(xr, dtype=self.rdt)
+ y = dct(x, norm='ortho', type=1)
+ y2 = naive_dct1(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+class _TestDCTIIBase(_TestDCTBase):
+ def test_definition_matlab(self):
+ # Test correspondence with MATLAB (orthornomal mode).
+ dt = np.result_type(np.float32, self.rdt)
+ for xr, yr in zip(X, Y):
+ x = np.array(xr, dtype=dt)
+ y = dct(x, norm="ortho", type=2)
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y, yr, decimal=self.dec)
+
+
+class _TestDCTIIIBase(_TestDCTBase):
+ def test_definition_ortho(self):
+ # Test orthornomal mode.
+ dt = np.result_type(np.float32, self.rdt)
+ for xr in X:
+ x = np.array(xr, dtype=self.rdt)
+ y = dct(x, norm='ortho', type=2)
+ xi = dct(y, norm="ortho", type=3)
+ assert_equal(xi.dtype, dt)
+ assert_array_almost_equal(xi, x, decimal=self.dec)
+
+class _TestDCTIVBase(_TestDCTBase):
+ def test_definition_ortho(self):
+ # Test orthornomal mode.
+ dt = np.result_type(np.float32, self.rdt)
+ for xr in X:
+ x = np.array(xr, dtype=self.rdt)
+ y = dct(x, norm='ortho', type=4)
+ y2 = naive_dct4(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+
+class TestDCTIDouble(_TestDCTIBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 10
+ self.type = 1
+
+
+class TestDCTIFloat(_TestDCTIBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 4
+ self.type = 1
+
+
+class TestDCTIInt(_TestDCTIBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 1
+
+
+class TestDCTIIDouble(_TestDCTIIBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 10
+ self.type = 2
+
+
+class TestDCTIIFloat(_TestDCTIIBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 5
+ self.type = 2
+
+
+class TestDCTIIInt(_TestDCTIIBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 2
+
+
+class TestDCTIIIDouble(_TestDCTIIIBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 14
+ self.type = 3
+
+
+class TestDCTIIIFloat(_TestDCTIIIBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 5
+ self.type = 3
+
+
+class TestDCTIIIInt(_TestDCTIIIBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 3
+
+
+class TestDCTIVDouble(_TestDCTIVBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 12
+ self.type = 3
+
+
+class TestDCTIVFloat(_TestDCTIVBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 5
+ self.type = 3
+
+
+class TestDCTIVInt(_TestDCTIVBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 3
+
+
+class _TestIDCTBase:
+ def setup_method(self):
+ self.rdt = None
+ self.dec = 14
+ self.type = None
+
+ @pytest.fixture
+ def idct_lock(self):
+ return threading.Lock()
+
+ def test_definition(self, idct_lock):
+ for i in FFTWDATA_SIZES:
+ with idct_lock:
+ xr, yr, dt = fftw_dct_ref(self.type, i, self.rdt)
+ x = idct(yr, type=self.type)
+ if self.type == 1:
+ x /= 2 * (i-1)
+ else:
+ x /= 2 * i
+ assert_equal(x.dtype, dt)
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
+ # should really use something like assert_array_approx_equal. The
+ # difference is due to fftw using a better algorithm w.r.t error
+ # propagation compared to the ones from fftpack.
+ assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
+ err_msg="Size %d failed" % i)
+
+
+class TestIDCTIDouble(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 10
+ self.type = 1
+
+
+class TestIDCTIFloat(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 4
+ self.type = 1
+
+
+class TestIDCTIInt(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 4
+ self.type = 1
+
+
+class TestIDCTIIDouble(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 10
+ self.type = 2
+
+
+class TestIDCTIIFloat(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 5
+ self.type = 2
+
+
+class TestIDCTIIInt(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 2
+
+
+class TestIDCTIIIDouble(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 14
+ self.type = 3
+
+
+class TestIDCTIIIFloat(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 5
+ self.type = 3
+
+
+class TestIDCTIIIInt(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 3
+
+class TestIDCTIVDouble(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 12
+ self.type = 4
+
+
+class TestIDCTIVFloat(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 5
+ self.type = 4
+
+
+class TestIDCTIVInt(_TestIDCTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 4
+
+class _TestDSTBase:
+ def setup_method(self):
+ self.rdt = None # dtype
+ self.dec = None # number of decimals to match
+ self.type = None # dst type
+
+ @pytest.fixture
+ def dst_lock(self):
+ return threading.Lock()
+
+ def test_definition(self, dst_lock):
+ for i in FFTWDATA_SIZES:
+ with dst_lock:
+ xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
+ y = dst(xr, type=self.type)
+ assert_equal(y.dtype, dt)
+ # XXX: we divide by np.max(y) because the tests fail otherwise. We
+ # should really use something like assert_array_approx_equal. The
+ # difference is due to fftw using a better algorithm w.r.t error
+ # propagation compared to the ones from fftpack.
+ assert_array_almost_equal(y / np.max(y), yr / np.max(y), decimal=self.dec,
+ err_msg="Size %d failed" % i)
+
+
+class _TestDSTIBase(_TestDSTBase):
+ def test_definition_ortho(self):
+ # Test orthornomal mode.
+ dt = np.result_type(np.float32, self.rdt)
+ for xr in X:
+ x = np.array(xr, dtype=self.rdt)
+ y = dst(x, norm='ortho', type=1)
+ y2 = naive_dst1(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y / np.max(y), y2 / np.max(y), decimal=self.dec)
+
+class _TestDSTIVBase(_TestDSTBase):
+ def test_definition_ortho(self):
+ # Test orthornomal mode.
+ dt = np.result_type(np.float32, self.rdt)
+ for xr in X:
+ x = np.array(xr, dtype=self.rdt)
+ y = dst(x, norm='ortho', type=4)
+ y2 = naive_dst4(x, norm='ortho')
+ assert_equal(y.dtype, dt)
+ assert_array_almost_equal(y, y2, decimal=self.dec)
+
+class TestDSTIDouble(_TestDSTIBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 12
+ self.type = 1
+
+
+class TestDSTIFloat(_TestDSTIBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 4
+ self.type = 1
+
+
+class TestDSTIInt(_TestDSTIBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 1
+
+
+class TestDSTIIDouble(_TestDSTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 14
+ self.type = 2
+
+
+class TestDSTIIFloat(_TestDSTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 6
+ self.type = 2
+
+
+class TestDSTIIInt(_TestDSTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 6
+ self.type = 2
+
+
+class TestDSTIIIDouble(_TestDSTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 14
+ self.type = 3
+
+
+class TestDSTIIIFloat(_TestDSTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 7
+ self.type = 3
+
+
+class TestDSTIIIInt(_TestDSTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 7
+ self.type = 3
+
+
+class TestDSTIVDouble(_TestDSTIVBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 12
+ self.type = 4
+
+
+class TestDSTIVFloat(_TestDSTIVBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 4
+ self.type = 4
+
+
+class TestDSTIVInt(_TestDSTIVBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 5
+ self.type = 4
+
+
+class _TestIDSTBase:
+ def setup_method(self):
+ self.rdt = None
+ self.dec = None
+ self.type = None
+
+ @pytest.fixture
+ def idst_lock(self):
+ return threading.Lock()
+
+ def test_definition(self, idst_lock):
+ for i in FFTWDATA_SIZES:
+ with idst_lock:
+ xr, yr, dt = fftw_dst_ref(self.type, i, self.rdt)
+ x = idst(yr, type=self.type)
+ if self.type == 1:
+ x /= 2 * (i+1)
+ else:
+ x /= 2 * i
+ assert_equal(x.dtype, dt)
+ # XXX: we divide by np.max(x) because the tests fail otherwise. We
+ # should really use something like assert_array_approx_equal. The
+ # difference is due to fftw using a better algorithm w.r.t error
+ # propagation compared to the ones from fftpack.
+ assert_array_almost_equal(x / np.max(x), xr / np.max(x), decimal=self.dec,
+ err_msg="Size %d failed" % i)
+
+
+class TestIDSTIDouble(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 12
+ self.type = 1
+
+
+class TestIDSTIFloat(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 4
+ self.type = 1
+
+
+class TestIDSTIInt(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 4
+ self.type = 1
+
+
+class TestIDSTIIDouble(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 14
+ self.type = 2
+
+
+class TestIDSTIIFloat(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 6
+ self.type = 2
+
+
+class TestIDSTIIInt(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 6
+ self.type = 2
+
+
+class TestIDSTIIIDouble(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 14
+ self.type = 3
+
+
+class TestIDSTIIIFloat(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 6
+ self.type = 3
+
+
+class TestIDSTIIIInt(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 6
+ self.type = 3
+
+
+class TestIDSTIVDouble(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float64
+ self.dec = 12
+ self.type = 4
+
+
+class TestIDSTIVFloat(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = np.float32
+ self.dec = 6
+ self.type = 4
+
+
+class TestIDSTIVnt(_TestIDSTBase):
+ def setup_method(self):
+ self.rdt = int
+ self.dec = 6
+ self.type = 4
+
+
+class TestOverwrite:
+ """Check input overwrite behavior."""
+
+ real_dtypes = [np.float32, np.float64]
+
+ def _check(self, x, routine, type, fftsize, axis, norm, overwrite_x, **kw):
+ x2 = x.copy()
+ routine(x2, type, fftsize, axis, norm, overwrite_x=overwrite_x)
+
+ sig = (f"{routine.__name__}({x.dtype}{x.shape!r}, {fftsize!r}, "
+ f"axis={axis!r}, overwrite_x={overwrite_x!r})")
+ if not overwrite_x:
+ assert_equal(x2, x, err_msg=f"spurious overwrite in {sig}")
+
+ def _check_1d(self, routine, dtype, shape, axis):
+ rng = np.random.RandomState(1234)
+ if np.issubdtype(dtype, np.complexfloating):
+ data = rng.randn(*shape) + 1j*rng.randn(*shape)
+ else:
+ data = rng.randn(*shape)
+ data = data.astype(dtype)
+
+ for type in [1, 2, 3, 4]:
+ for overwrite_x in [True, False]:
+ for norm in [None, 'ortho']:
+ self._check(data, routine, type, None, axis, norm,
+ overwrite_x)
+
+ def test_dct(self):
+ for dtype in self.real_dtypes:
+ self._check_1d(dct, dtype, (16,), -1)
+ self._check_1d(dct, dtype, (16, 2), 0)
+ self._check_1d(dct, dtype, (2, 16), 1)
+
+ def test_idct(self):
+ for dtype in self.real_dtypes:
+ self._check_1d(idct, dtype, (16,), -1)
+ self._check_1d(idct, dtype, (16, 2), 0)
+ self._check_1d(idct, dtype, (2, 16), 1)
+
+ def test_dst(self):
+ for dtype in self.real_dtypes:
+ self._check_1d(dst, dtype, (16,), -1)
+ self._check_1d(dst, dtype, (16, 2), 0)
+ self._check_1d(dst, dtype, (2, 16), 1)
+
+ def test_idst(self):
+ for dtype in self.real_dtypes:
+ self._check_1d(idst, dtype, (16,), -1)
+ self._check_1d(idst, dtype, (16, 2), 0)
+ self._check_1d(idst, dtype, (2, 16), 1)
+
+
+class Test_DCTN_IDCTN:
+ dec = 14
+ dct_type = [1, 2, 3, 4]
+ norms = [None, 'ortho']
+ rstate = np.random.RandomState(1234)
+ shape = (32, 16)
+ data = rstate.randn(*shape)
+
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+ (dstn, idstn)])
+ @pytest.mark.parametrize('axes', [None,
+ 1, (1,), [1],
+ 0, (0,), [0],
+ (0, 1), [0, 1],
+ (-2, -1), [-2, -1]])
+ @pytest.mark.parametrize('dct_type', dct_type)
+ @pytest.mark.parametrize('norm', ['ortho'])
+ def test_axes_round_trip(self, fforward, finverse, axes, dct_type, norm):
+ tmp = fforward(self.data, type=dct_type, axes=axes, norm=norm)
+ tmp = finverse(tmp, type=dct_type, axes=axes, norm=norm)
+ assert_array_almost_equal(self.data, tmp, decimal=12)
+
+ @pytest.mark.parametrize('fforward,fforward_ref', [(dctn, dct_2d_ref),
+ (dstn, dst_2d_ref)])
+ @pytest.mark.parametrize('dct_type', dct_type)
+ @pytest.mark.parametrize('norm', norms)
+ def test_dctn_vs_2d_reference(self, fforward, fforward_ref,
+ dct_type, norm):
+ y1 = fforward(self.data, type=dct_type, axes=None, norm=norm)
+ y2 = fforward_ref(self.data, type=dct_type, norm=norm)
+ assert_array_almost_equal(y1, y2, decimal=11)
+
+ @pytest.mark.parametrize('finverse,finverse_ref', [(idctn, idct_2d_ref),
+ (idstn, idst_2d_ref)])
+ @pytest.mark.parametrize('dct_type', dct_type)
+ @pytest.mark.parametrize('norm', [None, 'ortho'])
+ def test_idctn_vs_2d_reference(self, finverse, finverse_ref,
+ dct_type, norm):
+ fdata = dctn(self.data, type=dct_type, norm=norm)
+ y1 = finverse(fdata, type=dct_type, norm=norm)
+ y2 = finverse_ref(fdata, type=dct_type, norm=norm)
+ assert_array_almost_equal(y1, y2, decimal=11)
+
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+ (dstn, idstn)])
+ def test_axes_and_shape(self, fforward, finverse):
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ fforward(self.data, shape=self.data.shape[0], axes=(0, 1))
+
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ fforward(self.data, shape=self.data.shape[0], axes=None)
+
+ with assert_raises(ValueError,
+ match="when given, axes and shape arguments"
+ " have to be of the same length"):
+ fforward(self.data, shape=self.data.shape, axes=0)
+
+ @pytest.mark.parametrize('fforward', [dctn, dstn])
+ def test_shape(self, fforward):
+ tmp = fforward(self.data, shape=(128, 128), axes=None)
+ assert_equal(tmp.shape, (128, 128))
+
+ @pytest.mark.parametrize('fforward,finverse', [(dctn, idctn),
+ (dstn, idstn)])
+ @pytest.mark.parametrize('axes', [1, (1,), [1],
+ 0, (0,), [0]])
+ def test_shape_is_none_with_axes(self, fforward, finverse, axes):
+ tmp = fforward(self.data, shape=None, axes=axes, norm='ortho')
+ tmp = finverse(tmp, shape=None, axes=axes, norm='ortho')
+ assert_array_almost_equal(self.data, tmp, decimal=self.dec)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/__init__.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..75fadc9ceb2c14e32d9db6c61aa940c66b49d62d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/__init__.py
@@ -0,0 +1,8 @@
+"""Suite of ODE solvers implemented in Python."""
+from .ivp import solve_ivp
+from .rk import RK23, RK45, DOP853
+from .radau import Radau
+from .bdf import BDF
+from .lsoda import LSODA
+from .common import OdeSolution
+from .base import DenseOutput, OdeSolver
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/dop853_coefficients.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e734c930f49f0065396e7fa46b80e53692385b5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/dop853_coefficients.py
@@ -0,0 +1,193 @@
+import numpy as np
+
+N_STAGES = 12
+N_STAGES_EXTENDED = 16
+INTERPOLATOR_POWER = 7
+
+C = np.array([0.0,
+ 0.526001519587677318785587544488e-01,
+ 0.789002279381515978178381316732e-01,
+ 0.118350341907227396726757197510,
+ 0.281649658092772603273242802490,
+ 0.333333333333333333333333333333,
+ 0.25,
+ 0.307692307692307692307692307692,
+ 0.651282051282051282051282051282,
+ 0.6,
+ 0.857142857142857142857142857142,
+ 1.0,
+ 1.0,
+ 0.1,
+ 0.2,
+ 0.777777777777777777777777777778])
+
+A = np.zeros((N_STAGES_EXTENDED, N_STAGES_EXTENDED))
+A[1, 0] = 5.26001519587677318785587544488e-2
+
+A[2, 0] = 1.97250569845378994544595329183e-2
+A[2, 1] = 5.91751709536136983633785987549e-2
+
+A[3, 0] = 2.95875854768068491816892993775e-2
+A[3, 2] = 8.87627564304205475450678981324e-2
+
+A[4, 0] = 2.41365134159266685502369798665e-1
+A[4, 2] = -8.84549479328286085344864962717e-1
+A[4, 3] = 9.24834003261792003115737966543e-1
+
+A[5, 0] = 3.7037037037037037037037037037e-2
+A[5, 3] = 1.70828608729473871279604482173e-1
+A[5, 4] = 1.25467687566822425016691814123e-1
+
+A[6, 0] = 3.7109375e-2
+A[6, 3] = 1.70252211019544039314978060272e-1
+A[6, 4] = 6.02165389804559606850219397283e-2
+A[6, 5] = -1.7578125e-2
+
+A[7, 0] = 3.70920001185047927108779319836e-2
+A[7, 3] = 1.70383925712239993810214054705e-1
+A[7, 4] = 1.07262030446373284651809199168e-1
+A[7, 5] = -1.53194377486244017527936158236e-2
+A[7, 6] = 8.27378916381402288758473766002e-3
+
+A[8, 0] = 6.24110958716075717114429577812e-1
+A[8, 3] = -3.36089262944694129406857109825
+A[8, 4] = -8.68219346841726006818189891453e-1
+A[8, 5] = 2.75920996994467083049415600797e1
+A[8, 6] = 2.01540675504778934086186788979e1
+A[8, 7] = -4.34898841810699588477366255144e1
+
+A[9, 0] = 4.77662536438264365890433908527e-1
+A[9, 3] = -2.48811461997166764192642586468
+A[9, 4] = -5.90290826836842996371446475743e-1
+A[9, 5] = 2.12300514481811942347288949897e1
+A[9, 6] = 1.52792336328824235832596922938e1
+A[9, 7] = -3.32882109689848629194453265587e1
+A[9, 8] = -2.03312017085086261358222928593e-2
+
+A[10, 0] = -9.3714243008598732571704021658e-1
+A[10, 3] = 5.18637242884406370830023853209
+A[10, 4] = 1.09143734899672957818500254654
+A[10, 5] = -8.14978701074692612513997267357
+A[10, 6] = -1.85200656599969598641566180701e1
+A[10, 7] = 2.27394870993505042818970056734e1
+A[10, 8] = 2.49360555267965238987089396762
+A[10, 9] = -3.0467644718982195003823669022
+
+A[11, 0] = 2.27331014751653820792359768449
+A[11, 3] = -1.05344954667372501984066689879e1
+A[11, 4] = -2.00087205822486249909675718444
+A[11, 5] = -1.79589318631187989172765950534e1
+A[11, 6] = 2.79488845294199600508499808837e1
+A[11, 7] = -2.85899827713502369474065508674
+A[11, 8] = -8.87285693353062954433549289258
+A[11, 9] = 1.23605671757943030647266201528e1
+A[11, 10] = 6.43392746015763530355970484046e-1
+
+A[12, 0] = 5.42937341165687622380535766363e-2
+A[12, 5] = 4.45031289275240888144113950566
+A[12, 6] = 1.89151789931450038304281599044
+A[12, 7] = -5.8012039600105847814672114227
+A[12, 8] = 3.1116436695781989440891606237e-1
+A[12, 9] = -1.52160949662516078556178806805e-1
+A[12, 10] = 2.01365400804030348374776537501e-1
+A[12, 11] = 4.47106157277725905176885569043e-2
+
+A[13, 0] = 5.61675022830479523392909219681e-2
+A[13, 6] = 2.53500210216624811088794765333e-1
+A[13, 7] = -2.46239037470802489917441475441e-1
+A[13, 8] = -1.24191423263816360469010140626e-1
+A[13, 9] = 1.5329179827876569731206322685e-1
+A[13, 10] = 8.20105229563468988491666602057e-3
+A[13, 11] = 7.56789766054569976138603589584e-3
+A[13, 12] = -8.298e-3
+
+A[14, 0] = 3.18346481635021405060768473261e-2
+A[14, 5] = 2.83009096723667755288322961402e-2
+A[14, 6] = 5.35419883074385676223797384372e-2
+A[14, 7] = -5.49237485713909884646569340306e-2
+A[14, 10] = -1.08347328697249322858509316994e-4
+A[14, 11] = 3.82571090835658412954920192323e-4
+A[14, 12] = -3.40465008687404560802977114492e-4
+A[14, 13] = 1.41312443674632500278074618366e-1
+
+A[15, 0] = -4.28896301583791923408573538692e-1
+A[15, 5] = -4.69762141536116384314449447206
+A[15, 6] = 7.68342119606259904184240953878
+A[15, 7] = 4.06898981839711007970213554331
+A[15, 8] = 3.56727187455281109270669543021e-1
+A[15, 12] = -1.39902416515901462129418009734e-3
+A[15, 13] = 2.9475147891527723389556272149
+A[15, 14] = -9.15095847217987001081870187138
+
+
+B = A[N_STAGES, :N_STAGES]
+
+E3 = np.zeros(N_STAGES + 1)
+E3[:-1] = B.copy()
+E3[0] -= 0.244094488188976377952755905512
+E3[8] -= 0.733846688281611857341361741547
+E3[11] -= 0.220588235294117647058823529412e-1
+
+E5 = np.zeros(N_STAGES + 1)
+E5[0] = 0.1312004499419488073250102996e-1
+E5[5] = -0.1225156446376204440720569753e+1
+E5[6] = -0.4957589496572501915214079952
+E5[7] = 0.1664377182454986536961530415e+1
+E5[8] = -0.3503288487499736816886487290
+E5[9] = 0.3341791187130174790297318841
+E5[10] = 0.8192320648511571246570742613e-1
+E5[11] = -0.2235530786388629525884427845e-1
+
+# First 3 coefficients are computed separately.
+D = np.zeros((INTERPOLATOR_POWER - 3, N_STAGES_EXTENDED))
+D[0, 0] = -0.84289382761090128651353491142e+1
+D[0, 5] = 0.56671495351937776962531783590
+D[0, 6] = -0.30689499459498916912797304727e+1
+D[0, 7] = 0.23846676565120698287728149680e+1
+D[0, 8] = 0.21170345824450282767155149946e+1
+D[0, 9] = -0.87139158377797299206789907490
+D[0, 10] = 0.22404374302607882758541771650e+1
+D[0, 11] = 0.63157877876946881815570249290
+D[0, 12] = -0.88990336451333310820698117400e-1
+D[0, 13] = 0.18148505520854727256656404962e+2
+D[0, 14] = -0.91946323924783554000451984436e+1
+D[0, 15] = -0.44360363875948939664310572000e+1
+
+D[1, 0] = 0.10427508642579134603413151009e+2
+D[1, 5] = 0.24228349177525818288430175319e+3
+D[1, 6] = 0.16520045171727028198505394887e+3
+D[1, 7] = -0.37454675472269020279518312152e+3
+D[1, 8] = -0.22113666853125306036270938578e+2
+D[1, 9] = 0.77334326684722638389603898808e+1
+D[1, 10] = -0.30674084731089398182061213626e+2
+D[1, 11] = -0.93321305264302278729567221706e+1
+D[1, 12] = 0.15697238121770843886131091075e+2
+D[1, 13] = -0.31139403219565177677282850411e+2
+D[1, 14] = -0.93529243588444783865713862664e+1
+D[1, 15] = 0.35816841486394083752465898540e+2
+
+D[2, 0] = 0.19985053242002433820987653617e+2
+D[2, 5] = -0.38703730874935176555105901742e+3
+D[2, 6] = -0.18917813819516756882830838328e+3
+D[2, 7] = 0.52780815920542364900561016686e+3
+D[2, 8] = -0.11573902539959630126141871134e+2
+D[2, 9] = 0.68812326946963000169666922661e+1
+D[2, 10] = -0.10006050966910838403183860980e+1
+D[2, 11] = 0.77771377980534432092869265740
+D[2, 12] = -0.27782057523535084065932004339e+1
+D[2, 13] = -0.60196695231264120758267380846e+2
+D[2, 14] = 0.84320405506677161018159903784e+2
+D[2, 15] = 0.11992291136182789328035130030e+2
+
+D[3, 0] = -0.25693933462703749003312586129e+2
+D[3, 5] = -0.15418974869023643374053993627e+3
+D[3, 6] = -0.23152937917604549567536039109e+3
+D[3, 7] = 0.35763911791061412378285349910e+3
+D[3, 8] = 0.93405324183624310003907691704e+2
+D[3, 9] = -0.37458323136451633156875139351e+2
+D[3, 10] = 0.10409964950896230045147246184e+3
+D[3, 11] = 0.29840293426660503123344363579e+2
+D[3, 12] = -0.43533456590011143754432175058e+2
+D[3, 13] = 0.96324553959188282948394950600e+2
+D[3, 14] = -0.39177261675615439165231486172e+2
+D[3, 15] = -0.14972683625798562581422125276e+3
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/ivp.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..58cd75b7293b30d9bf32403cfde5be909bfad44a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/ivp.py
@@ -0,0 +1,755 @@
+import inspect
+import numpy as np
+from .bdf import BDF
+from .radau import Radau
+from .rk import RK23, RK45, DOP853
+from .lsoda import LSODA
+from scipy.optimize import OptimizeResult
+from .common import EPS, OdeSolution
+from .base import OdeSolver
+
+
+METHODS = {'RK23': RK23,
+ 'RK45': RK45,
+ 'DOP853': DOP853,
+ 'Radau': Radau,
+ 'BDF': BDF,
+ 'LSODA': LSODA}
+
+
+MESSAGES = {0: "The solver successfully reached the end of the integration interval.",
+ 1: "A termination event occurred."}
+
+
+class OdeResult(OptimizeResult):
+ pass
+
+
+def prepare_events(events):
+ """Standardize event functions and extract attributes."""
+ if callable(events):
+ events = (events,)
+
+ max_events = np.empty(len(events))
+ direction = np.empty(len(events))
+ for i, event in enumerate(events):
+ terminal = getattr(event, 'terminal', None)
+ direction[i] = getattr(event, 'direction', 0)
+
+ message = ('The `terminal` attribute of each event '
+ 'must be a boolean or positive integer.')
+ if terminal is None or terminal == 0:
+ max_events[i] = np.inf
+ elif int(terminal) == terminal and terminal > 0:
+ max_events[i] = terminal
+ else:
+ raise ValueError(message)
+
+ return events, max_events, direction
+
+
+def solve_event_equation(event, sol, t_old, t):
+ """Solve an equation corresponding to an ODE event.
+
+ The equation is ``event(t, y(t)) = 0``, here ``y(t)`` is known from an
+ ODE solver using some sort of interpolation. It is solved by
+ `scipy.optimize.brentq` with xtol=atol=4*EPS.
+
+ Parameters
+ ----------
+ event : callable
+ Function ``event(t, y)``.
+ sol : callable
+ Function ``sol(t)`` which evaluates an ODE solution between `t_old`
+ and `t`.
+ t_old, t : float
+ Previous and new values of time. They will be used as a bracketing
+ interval.
+
+ Returns
+ -------
+ root : float
+ Found solution.
+ """
+ from scipy.optimize import brentq
+ return brentq(lambda t: event(t, sol(t)), t_old, t,
+ xtol=4 * EPS, rtol=4 * EPS)
+
+
+def handle_events(sol, events, active_events, event_count, max_events,
+ t_old, t):
+ """Helper function to handle events.
+
+ Parameters
+ ----------
+ sol : DenseOutput
+ Function ``sol(t)`` which evaluates an ODE solution between `t_old`
+ and `t`.
+ events : list of callables, length n_events
+ Event functions with signatures ``event(t, y)``.
+ active_events : ndarray
+ Indices of events which occurred.
+ event_count : ndarray
+ Current number of occurrences for each event.
+ max_events : ndarray, shape (n_events,)
+ Number of occurrences allowed for each event before integration
+ termination is issued.
+ t_old, t : float
+ Previous and new values of time.
+
+ Returns
+ -------
+ root_indices : ndarray
+ Indices of events which take zero between `t_old` and `t` and before
+ a possible termination.
+ roots : ndarray
+ Values of t at which events occurred.
+ terminate : bool
+ Whether a terminal event occurred.
+ """
+ roots = [solve_event_equation(events[event_index], sol, t_old, t)
+ for event_index in active_events]
+
+ roots = np.asarray(roots)
+
+ if np.any(event_count[active_events] >= max_events[active_events]):
+ if t > t_old:
+ order = np.argsort(roots)
+ else:
+ order = np.argsort(-roots)
+ active_events = active_events[order]
+ roots = roots[order]
+ t = np.nonzero(event_count[active_events]
+ >= max_events[active_events])[0][0]
+ active_events = active_events[:t + 1]
+ roots = roots[:t + 1]
+ terminate = True
+ else:
+ terminate = False
+
+ return active_events, roots, terminate
+
+
+def find_active_events(g, g_new, direction):
+ """Find which event occurred during an integration step.
+
+ Parameters
+ ----------
+ g, g_new : array_like, shape (n_events,)
+ Values of event functions at a current and next points.
+ direction : ndarray, shape (n_events,)
+ Event "direction" according to the definition in `solve_ivp`.
+
+ Returns
+ -------
+ active_events : ndarray
+ Indices of events which occurred during the step.
+ """
+ g, g_new = np.asarray(g), np.asarray(g_new)
+ up = (g <= 0) & (g_new >= 0)
+ down = (g >= 0) & (g_new <= 0)
+ either = up | down
+ mask = (up & (direction > 0) |
+ down & (direction < 0) |
+ either & (direction == 0))
+
+ return np.nonzero(mask)[0]
+
+
+def solve_ivp(fun, t_span, y0, method='RK45', t_eval=None, dense_output=False,
+ events=None, vectorized=False, args=None, **options):
+ """Solve an initial value problem for a system of ODEs.
+
+ This function numerically integrates a system of ordinary differential
+ equations given an initial value::
+
+ dy / dt = f(t, y)
+ y(t0) = y0
+
+ Here t is a 1-D independent variable (time), y(t) is an
+ N-D vector-valued function (state), and an N-D
+ vector-valued function f(t, y) determines the differential equations.
+ The goal is to find y(t) approximately satisfying the differential
+ equations, given an initial value y(t0)=y0.
+
+ Some of the solvers support integration in the complex domain, but note
+ that for stiff ODE solvers, the right-hand side must be
+ complex-differentiable (satisfy Cauchy-Riemann equations [11]_).
+ To solve a problem in the complex domain, pass y0 with a complex data type.
+ Another option always available is to rewrite your problem for real and
+ imaginary parts separately.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system: the time derivative of the state ``y``
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. Additional
+ arguments need to be passed if ``args`` is used (see documentation of
+ ``args`` argument). ``fun`` must return an array of the same shape as
+ ``y``. See `vectorized` for more information.
+ t_span : 2-member sequence
+ Interval of integration (t0, tf). The solver starts with t=t0 and
+ integrates until it reaches t=tf. Both t0 and tf must be floats
+ or values interpretable by the float conversion function.
+ y0 : array_like, shape (n,)
+ Initial state. For problems in the complex domain, pass `y0` with a
+ complex data type (even if the initial value is purely real).
+ method : string or `OdeSolver`, optional
+ Integration method to use:
+
+ * 'RK45' (default): Explicit Runge-Kutta method of order 5(4) [1]_.
+ The error is controlled assuming accuracy of the fourth-order
+ method, but steps are taken using the fifth-order accurate
+ formula (local extrapolation is done). A quartic interpolation
+ polynomial is used for the dense output [2]_. Can be applied in
+ the complex domain.
+ * 'RK23': Explicit Runge-Kutta method of order 3(2) [3]_. The error
+ is controlled assuming accuracy of the second-order method, but
+ steps are taken using the third-order accurate formula (local
+ extrapolation is done). A cubic Hermite polynomial is used for the
+ dense output. Can be applied in the complex domain.
+ * 'DOP853': Explicit Runge-Kutta method of order 8 [13]_.
+ Python implementation of the "DOP853" algorithm originally
+ written in Fortran [14]_. A 7-th order interpolation polynomial
+ accurate to 7-th order is used for the dense output.
+ Can be applied in the complex domain.
+ * 'Radau': Implicit Runge-Kutta method of the Radau IIA family of
+ order 5 [4]_. The error is controlled with a third-order accurate
+ embedded formula. A cubic polynomial which satisfies the
+ collocation conditions is used for the dense output.
+ * 'BDF': Implicit multi-step variable-order (1 to 5) method based
+ on a backward differentiation formula for the derivative
+ approximation [5]_. The implementation follows the one described
+ in [6]_. A quasi-constant step scheme is used and accuracy is
+ enhanced using the NDF modification. Can be applied in the
+ complex domain.
+ * 'LSODA': Adams/BDF method with automatic stiffness detection and
+ switching [7]_, [8]_. This is a wrapper of the Fortran solver
+ from ODEPACK.
+
+ Explicit Runge-Kutta methods ('RK23', 'RK45', 'DOP853') should be used
+ for non-stiff problems and implicit methods ('Radau', 'BDF') for
+ stiff problems [9]_. Among Runge-Kutta methods, 'DOP853' is recommended
+ for solving with high precision (low values of `rtol` and `atol`).
+
+ If not sure, first try to run 'RK45'. If it makes unusually many
+ iterations, diverges, or fails, your problem is likely to be stiff and
+ you should use 'Radau' or 'BDF'. 'LSODA' can also be a good universal
+ choice, but it might be somewhat less convenient to work with as it
+ wraps old Fortran code.
+
+ You can also pass an arbitrary class derived from `OdeSolver` which
+ implements the solver.
+ t_eval : array_like or None, optional
+ Times at which to store the computed solution, must be sorted and lie
+ within `t_span`. If None (default), use points selected by the solver.
+ dense_output : bool, optional
+ Whether to compute a continuous solution. Default is False.
+ events : callable, or list of callables, optional
+ Events to track. If None (default), no events will be tracked.
+ Each event occurs at the zeros of a continuous function of time and
+ state. Each function must have the signature ``event(t, y)`` where
+ additional argument have to be passed if ``args`` is used (see
+ documentation of ``args`` argument). Each function must return a
+ float. The solver will find an accurate value of `t` at which
+ ``event(t, y(t)) = 0`` using a root-finding algorithm. By default,
+ all zeros will be found. The solver looks for a sign change over
+ each step, so if multiple zero crossings occur within one step,
+ events may be missed. Additionally each `event` function might
+ have the following attributes:
+
+ terminal: bool or int, optional
+ When boolean, whether to terminate integration if this event occurs.
+ When integral, termination occurs after the specified the number of
+ occurrences of this event.
+ Implicitly False if not assigned.
+ direction: float, optional
+ Direction of a zero crossing. If `direction` is positive,
+ `event` will only trigger when going from negative to positive,
+ and vice versa if `direction` is negative. If 0, then either
+ direction will trigger event. Implicitly 0 if not assigned.
+
+ You can assign attributes like ``event.terminal = True`` to any
+ function in Python.
+ vectorized : bool, optional
+ Whether `fun` can be called in a vectorized fashion. Default is False.
+
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
+ shape ``(n,)``, where ``n = len(y0)``.
+
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+ the returned array is the time derivative of the state corresponding
+ with a column of ``y``).
+
+ Setting ``vectorized=True`` allows for faster finite difference
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
+ will result in slower execution for other methods and for 'Radau' and
+ 'BDF' in some circumstances (e.g. small ``len(y0)``).
+ args : tuple, optional
+ Additional arguments to pass to the user-defined functions. If given,
+ the additional arguments are passed to all user-defined functions.
+ So if, for example, `fun` has the signature ``fun(t, y, a, b, c)``,
+ then `jac` (if given) and any event functions must have the same
+ signature, and `args` must be a tuple of length 3.
+ **options
+ Options passed to a chosen solver. All options available for already
+ implemented solvers are listed below.
+ first_step : float or None, optional
+ Initial step size. Default is `None` which means that the algorithm
+ should choose.
+ max_step : float, optional
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
+ bounded and determined solely by the solver.
+ rtol, atol : float or array_like, optional
+ Relative and absolute tolerances. The solver keeps the local error
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+ relative accuracy (number of correct digits), while `atol` controls
+ absolute accuracy (number of correct decimal places). To achieve the
+ desired `rtol`, set `atol` to be smaller than the smallest value that
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+ number of correct digits is not guaranteed. Conversely, to achieve the
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+ than `atol`. If components of y have different scales, it might be
+ beneficial to set different `atol` values for different components by
+ passing array_like with shape (n,) for `atol`. Default values are
+ 1e-3 for `rtol` and 1e-6 for `atol`.
+ jac : array_like, sparse_matrix, callable or None, optional
+ Jacobian matrix of the right-hand side of the system with respect
+ to y, required by the 'Radau', 'BDF' and 'LSODA' method. The
+ Jacobian matrix has shape (n, n) and its element (i, j) is equal to
+ ``d f_i / d y_j``. There are three ways to define the Jacobian:
+
+ * If array_like or sparse_matrix, the Jacobian is assumed to
+ be constant. Not supported by 'LSODA'.
+ * If callable, the Jacobian is assumed to depend on both
+ t and y; it will be called as ``jac(t, y)``, as necessary.
+ Additional arguments have to be passed if ``args`` is
+ used (see documentation of ``args`` argument).
+ For 'Radau' and 'BDF' methods, the return value might be a
+ sparse matrix.
+ * If None (default), the Jacobian will be approximated by
+ finite differences.
+
+ It is generally recommended to provide the Jacobian rather than
+ relying on a finite-difference approximation.
+ jac_sparsity : array_like, sparse matrix or None, optional
+ Defines a sparsity structure of the Jacobian matrix for a finite-
+ difference approximation. Its shape must be (n, n). This argument
+ is ignored if `jac` is not `None`. If the Jacobian has only few
+ non-zero elements in *each* row, providing the sparsity structure
+ will greatly speed up the computations [10]_. A zero entry means that
+ a corresponding element in the Jacobian is always zero. If None
+ (default), the Jacobian is assumed to be dense.
+ Not supported by 'LSODA', see `lband` and `uband` instead.
+ lband, uband : int or None, optional
+ Parameters defining the bandwidth of the Jacobian for the 'LSODA'
+ method, i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``.
+ Default is None. Setting these requires your jac routine to return the
+ Jacobian in the packed format: the returned array must have ``n``
+ columns and ``uband + lband + 1`` rows in which Jacobian diagonals are
+ written. Specifically ``jac_packed[uband + i - j , j] = jac[i, j]``.
+ The same format is used in `scipy.linalg.solve_banded` (check for an
+ illustration). These parameters can be also used with ``jac=None`` to
+ reduce the number of Jacobian elements estimated by finite differences.
+ min_step : float, optional
+ The minimum allowed step size for 'LSODA' method.
+ By default `min_step` is zero.
+
+ Returns
+ -------
+ Bunch object with the following fields defined:
+ t : ndarray, shape (n_points,)
+ Time points.
+ y : ndarray, shape (n, n_points)
+ Values of the solution at `t`.
+ sol : `OdeSolution` or None
+ Found solution as `OdeSolution` instance; None if `dense_output` was
+ set to False.
+ t_events : list of ndarray or None
+ Contains for each event type a list of arrays at which an event of
+ that type event was detected. None if `events` was None.
+ y_events : list of ndarray or None
+ For each value of `t_events`, the corresponding value of the solution.
+ None if `events` was None.
+ nfev : int
+ Number of evaluations of the right-hand side.
+ njev : int
+ Number of evaluations of the Jacobian.
+ nlu : int
+ Number of LU decompositions.
+ status : int
+ Reason for algorithm termination:
+
+ * -1: Integration step failed.
+ * 0: The solver successfully reached the end of `tspan`.
+ * 1: A termination event occurred.
+
+ message : string
+ Human-readable description of the termination reason.
+ success : bool
+ True if the solver reached the interval end or a termination event
+ occurred (``status >= 0``).
+
+ References
+ ----------
+ .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
+ formulae", Journal of Computational and Applied Mathematics, Vol. 6,
+ No. 1, pp. 19-26, 1980.
+ .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
+ of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
+ .. [3] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
+ Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
+ .. [4] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
+ Stiff and Differential-Algebraic Problems", Sec. IV.8.
+ .. [5] `Backward Differentiation Formula
+ `_
+ on Wikipedia.
+ .. [6] L. F. Shampine, M. W. Reichelt, "THE MATLAB ODE SUITE", SIAM J. SCI.
+ COMPUTE., Vol. 18, No. 1, pp. 1-22, January 1997.
+ .. [7] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
+ Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
+ pp. 55-64, 1983.
+ .. [8] L. Petzold, "Automatic selection of methods for solving stiff and
+ nonstiff systems of ordinary differential equations", SIAM Journal
+ on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
+ 1983.
+ .. [9] `Stiff equation `_ on
+ Wikipedia.
+ .. [10] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
+ and its Applications, 13, pp. 117-120, 1974.
+ .. [11] `Cauchy-Riemann equations
+ `_ on
+ Wikipedia.
+ .. [12] `Lotka-Volterra equations
+ `_
+ on Wikipedia.
+ .. [13] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+ Equations I: Nonstiff Problems", Sec. II.
+ .. [14] `Page with original Fortran code of DOP853
+ `_.
+
+ Examples
+ --------
+ Basic exponential decay showing automatically chosen time points.
+
+ >>> import numpy as np
+ >>> from scipy.integrate import solve_ivp
+ >>> def exponential_decay(t, y): return -0.5 * y
+ >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8])
+ >>> print(sol.t)
+ [ 0. 0.11487653 1.26364188 3.06061781 4.81611105 6.57445806
+ 8.33328988 10. ]
+ >>> print(sol.y)
+ [[2. 1.88836035 1.06327177 0.43319312 0.18017253 0.07483045
+ 0.03107158 0.01350781]
+ [4. 3.7767207 2.12654355 0.86638624 0.36034507 0.14966091
+ 0.06214316 0.02701561]
+ [8. 7.5534414 4.25308709 1.73277247 0.72069014 0.29932181
+ 0.12428631 0.05403123]]
+
+ Specifying points where the solution is desired.
+
+ >>> sol = solve_ivp(exponential_decay, [0, 10], [2, 4, 8],
+ ... t_eval=[0, 1, 2, 4, 10])
+ >>> print(sol.t)
+ [ 0 1 2 4 10]
+ >>> print(sol.y)
+ [[2. 1.21305369 0.73534021 0.27066736 0.01350938]
+ [4. 2.42610739 1.47068043 0.54133472 0.02701876]
+ [8. 4.85221478 2.94136085 1.08266944 0.05403753]]
+
+ Cannon fired upward with terminal event upon impact. The ``terminal`` and
+ ``direction`` fields of an event are applied by monkey patching a function.
+ Here ``y[0]`` is position and ``y[1]`` is velocity. The projectile starts
+ at position 0 with velocity +10. Note that the integration never reaches
+ t=100 because the event is terminal.
+
+ >>> def upward_cannon(t, y): return [y[1], -0.5]
+ >>> def hit_ground(t, y): return y[0]
+ >>> hit_ground.terminal = True
+ >>> hit_ground.direction = -1
+ >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10], events=hit_ground)
+ >>> print(sol.t_events)
+ [array([40.])]
+ >>> print(sol.t)
+ [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
+ 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
+
+ Use `dense_output` and `events` to find position, which is 100, at the apex
+ of the cannonball's trajectory. Apex is not defined as terminal, so both
+ apex and hit_ground are found. There is no information at t=20, so the sol
+ attribute is used to evaluate the solution. The sol attribute is returned
+ by setting ``dense_output=True``. Alternatively, the `y_events` attribute
+ can be used to access the solution at the time of the event.
+
+ >>> def apex(t, y): return y[1]
+ >>> sol = solve_ivp(upward_cannon, [0, 100], [0, 10],
+ ... events=(hit_ground, apex), dense_output=True)
+ >>> print(sol.t_events)
+ [array([40.]), array([20.])]
+ >>> print(sol.t)
+ [0.00000000e+00 9.99900010e-05 1.09989001e-03 1.10988901e-02
+ 1.11088891e-01 1.11098890e+00 1.11099890e+01 4.00000000e+01]
+ >>> print(sol.sol(sol.t_events[1][0]))
+ [100. 0.]
+ >>> print(sol.y_events)
+ [array([[-5.68434189e-14, -1.00000000e+01]]),
+ array([[1.00000000e+02, 1.77635684e-15]])]
+
+ As an example of a system with additional parameters, we'll implement
+ the Lotka-Volterra equations [12]_.
+
+ >>> def lotkavolterra(t, z, a, b, c, d):
+ ... x, y = z
+ ... return [a*x - b*x*y, -c*y + d*x*y]
+ ...
+
+ We pass in the parameter values a=1.5, b=1, c=3 and d=1 with the `args`
+ argument.
+
+ >>> sol = solve_ivp(lotkavolterra, [0, 15], [10, 5], args=(1.5, 1, 3, 1),
+ ... dense_output=True)
+
+ Compute a dense solution and plot it.
+
+ >>> t = np.linspace(0, 15, 300)
+ >>> z = sol.sol(t)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t, z.T)
+ >>> plt.xlabel('t')
+ >>> plt.legend(['x', 'y'], shadow=True)
+ >>> plt.title('Lotka-Volterra System')
+ >>> plt.show()
+
+ A couple examples of using solve_ivp to solve the differential
+ equation ``y' = Ay`` with complex matrix ``A``.
+
+ >>> A = np.array([[-0.25 + 0.14j, 0, 0.33 + 0.44j],
+ ... [0.25 + 0.58j, -0.2 + 0.14j, 0],
+ ... [0, 0.2 + 0.4j, -0.1 + 0.97j]])
+
+ Solving an IVP with ``A`` from above and ``y`` as 3x1 vector:
+
+ >>> def deriv_vec(t, y):
+ ... return A @ y
+ >>> result = solve_ivp(deriv_vec, [0, 25],
+ ... np.array([10 + 0j, 20 + 0j, 30 + 0j]),
+ ... t_eval=np.linspace(0, 25, 101))
+ >>> print(result.y[:, 0])
+ [10.+0.j 20.+0.j 30.+0.j]
+ >>> print(result.y[:, -1])
+ [18.46291039+45.25653651j 10.01569306+36.23293216j
+ -4.98662741+80.07360388j]
+
+ Solving an IVP with ``A`` from above with ``y`` as 3x3 matrix :
+
+ >>> def deriv_mat(t, y):
+ ... return (A @ y.reshape(3, 3)).flatten()
+ >>> y0 = np.array([[2 + 0j, 3 + 0j, 4 + 0j],
+ ... [5 + 0j, 6 + 0j, 7 + 0j],
+ ... [9 + 0j, 34 + 0j, 78 + 0j]])
+
+ >>> result = solve_ivp(deriv_mat, [0, 25], y0.flatten(),
+ ... t_eval=np.linspace(0, 25, 101))
+ >>> print(result.y[:, 0].reshape(3, 3))
+ [[ 2.+0.j 3.+0.j 4.+0.j]
+ [ 5.+0.j 6.+0.j 7.+0.j]
+ [ 9.+0.j 34.+0.j 78.+0.j]]
+ >>> print(result.y[:, -1].reshape(3, 3))
+ [[ 5.67451179 +12.07938445j 17.2888073 +31.03278837j
+ 37.83405768 +63.25138759j]
+ [ 3.39949503 +11.82123994j 21.32530996 +44.88668871j
+ 53.17531184+103.80400411j]
+ [ -2.26105874 +22.19277664j -15.1255713 +70.19616341j
+ -38.34616845+153.29039931j]]
+
+
+ """
+ if method not in METHODS and not (
+ inspect.isclass(method) and issubclass(method, OdeSolver)):
+ raise ValueError(f"`method` must be one of {METHODS} or OdeSolver class.")
+
+ t0, tf = map(float, t_span)
+
+ if args is not None:
+ # Wrap the user's fun (and jac, if given) in lambdas to hide the
+ # additional parameters. Pass in the original fun as a keyword
+ # argument to keep it in the scope of the lambda.
+ try:
+ _ = [*(args)]
+ except TypeError as exp:
+ suggestion_tuple = (
+ "Supplied 'args' cannot be unpacked. Please supply `args`"
+ f" as a tuple (e.g. `args=({args},)`)"
+ )
+ raise TypeError(suggestion_tuple) from exp
+
+ def fun(t, x, fun=fun):
+ return fun(t, x, *args)
+ jac = options.get('jac')
+ if callable(jac):
+ options['jac'] = lambda t, x: jac(t, x, *args)
+
+ if t_eval is not None:
+ t_eval = np.asarray(t_eval)
+ if t_eval.ndim != 1:
+ raise ValueError("`t_eval` must be 1-dimensional.")
+
+ if np.any(t_eval < min(t0, tf)) or np.any(t_eval > max(t0, tf)):
+ raise ValueError("Values in `t_eval` are not within `t_span`.")
+
+ d = np.diff(t_eval)
+ if tf > t0 and np.any(d <= 0) or tf < t0 and np.any(d >= 0):
+ raise ValueError("Values in `t_eval` are not properly sorted.")
+
+ if tf > t0:
+ t_eval_i = 0
+ else:
+ # Make order of t_eval decreasing to use np.searchsorted.
+ t_eval = t_eval[::-1]
+ # This will be an upper bound for slices.
+ t_eval_i = t_eval.shape[0]
+
+ if method in METHODS:
+ method = METHODS[method]
+
+ solver = method(fun, t0, y0, tf, vectorized=vectorized, **options)
+
+ if t_eval is None:
+ ts = [t0]
+ ys = [y0]
+ elif t_eval is not None and dense_output:
+ ts = []
+ ti = [t0]
+ ys = []
+ else:
+ ts = []
+ ys = []
+
+ interpolants = []
+
+ if events is not None:
+ events, max_events, event_dir = prepare_events(events)
+ event_count = np.zeros(len(events))
+ if args is not None:
+ # Wrap user functions in lambdas to hide the additional parameters.
+ # The original event function is passed as a keyword argument to the
+ # lambda to keep the original function in scope (i.e., avoid the
+ # late binding closure "gotcha").
+ events = [lambda t, x, event=event: event(t, x, *args)
+ for event in events]
+ g = [event(t0, y0) for event in events]
+ t_events = [[] for _ in range(len(events))]
+ y_events = [[] for _ in range(len(events))]
+ else:
+ t_events = None
+ y_events = None
+
+ status = None
+ while status is None:
+ message = solver.step()
+
+ if solver.status == 'finished':
+ status = 0
+ elif solver.status == 'failed':
+ status = -1
+ break
+
+ t_old = solver.t_old
+ t = solver.t
+ y = solver.y
+
+ if dense_output:
+ sol = solver.dense_output()
+ interpolants.append(sol)
+ else:
+ sol = None
+
+ if events is not None:
+ g_new = [event(t, y) for event in events]
+ active_events = find_active_events(g, g_new, event_dir)
+ if active_events.size > 0:
+ if sol is None:
+ sol = solver.dense_output()
+
+ event_count[active_events] += 1
+ root_indices, roots, terminate = handle_events(
+ sol, events, active_events, event_count, max_events,
+ t_old, t)
+
+ for e, te in zip(root_indices, roots):
+ t_events[e].append(te)
+ y_events[e].append(sol(te))
+
+ if terminate:
+ status = 1
+ t = roots[-1]
+ y = sol(t)
+
+ g = g_new
+
+ if t_eval is None:
+ donot_append = (len(ts) > 1 and
+ ts[-1] == t and
+ dense_output)
+ if not donot_append:
+ ts.append(t)
+ ys.append(y)
+ else:
+ if len(interpolants) > 0:
+ interpolants.pop()
+ else:
+ # The value in t_eval equal to t will be included.
+ if solver.direction > 0:
+ t_eval_i_new = np.searchsorted(t_eval, t, side='right')
+ t_eval_step = t_eval[t_eval_i:t_eval_i_new]
+ else:
+ t_eval_i_new = np.searchsorted(t_eval, t, side='left')
+ # It has to be done with two slice operations, because
+ # you can't slice to 0th element inclusive using backward
+ # slicing.
+ t_eval_step = t_eval[t_eval_i_new:t_eval_i][::-1]
+
+ if t_eval_step.size > 0:
+ if sol is None:
+ sol = solver.dense_output()
+ ts.append(t_eval_step)
+ ys.append(sol(t_eval_step))
+ t_eval_i = t_eval_i_new
+
+ if t_eval is not None and dense_output:
+ ti.append(t)
+
+ message = MESSAGES.get(status, message)
+
+ if t_events is not None:
+ t_events = [np.asarray(te) for te in t_events]
+ y_events = [np.asarray(ye) for ye in y_events]
+
+ if t_eval is None:
+ ts = np.array(ts)
+ ys = np.vstack(ys).T
+ elif ts:
+ ts = np.hstack(ts)
+ ys = np.hstack(ys)
+
+ if dense_output:
+ if t_eval is None:
+ sol = OdeSolution(
+ ts, interpolants, alt_segment=True if method in [BDF, LSODA] else False
+ )
+ else:
+ sol = OdeSolution(
+ ti, interpolants, alt_segment=True if method in [BDF, LSODA] else False
+ )
+ else:
+ sol = None
+
+ return OdeResult(t=ts, y=ys, sol=sol, t_events=t_events, y_events=y_events,
+ nfev=solver.nfev, njev=solver.njev, nlu=solver.nlu,
+ status=status, message=message, success=status >= 0)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/lsoda.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/lsoda.py
new file mode 100644
index 0000000000000000000000000000000000000000..f48c4f32c32b6eda6f6499786f8b3fab59f14e8c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/lsoda.py
@@ -0,0 +1,224 @@
+import numpy as np
+from scipy.integrate import ode
+from .common import validate_tol, validate_first_step, warn_extraneous
+from .base import OdeSolver, DenseOutput
+
+
+class LSODA(OdeSolver):
+ """Adams/BDF method with automatic stiffness detection and switching.
+
+ This is a wrapper to the Fortran solver from ODEPACK [1]_. It switches
+ automatically between the nonstiff Adams method and the stiff BDF method.
+ The method was originally detailed in [2]_.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system: the time derivative of the state ``y``
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+ return an array of the same shape as ``y``. See `vectorized` for more
+ information.
+ t0 : float
+ Initial time.
+ y0 : array_like, shape (n,)
+ Initial state.
+ t_bound : float
+ Boundary time - the integration won't continue beyond it. It also
+ determines the direction of the integration.
+ first_step : float or None, optional
+ Initial step size. Default is ``None`` which means that the algorithm
+ should choose.
+ min_step : float, optional
+ Minimum allowed step size. Default is 0.0, i.e., the step size is not
+ bounded and determined solely by the solver.
+ max_step : float, optional
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
+ bounded and determined solely by the solver.
+ rtol, atol : float and array_like, optional
+ Relative and absolute tolerances. The solver keeps the local error
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+ relative accuracy (number of correct digits), while `atol` controls
+ absolute accuracy (number of correct decimal places). To achieve the
+ desired `rtol`, set `atol` to be smaller than the smallest value that
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+ number of correct digits is not guaranteed. Conversely, to achieve the
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+ than `atol`. If components of y have different scales, it might be
+ beneficial to set different `atol` values for different components by
+ passing array_like with shape (n,) for `atol`. Default values are
+ 1e-3 for `rtol` and 1e-6 for `atol`.
+ jac : None or callable, optional
+ Jacobian matrix of the right-hand side of the system with respect to
+ ``y``. The Jacobian matrix has shape (n, n) and its element (i, j) is
+ equal to ``d f_i / d y_j``. The function will be called as
+ ``jac(t, y)``. If None (default), the Jacobian will be
+ approximated by finite differences. It is generally recommended to
+ provide the Jacobian rather than relying on a finite-difference
+ approximation.
+ lband, uband : int or None
+ Parameters defining the bandwidth of the Jacobian,
+ i.e., ``jac[i, j] != 0 only for i - lband <= j <= i + uband``. Setting
+ these requires your jac routine to return the Jacobian in the packed format:
+ the returned array must have ``n`` columns and ``uband + lband + 1``
+ rows in which Jacobian diagonals are written. Specifically
+ ``jac_packed[uband + i - j , j] = jac[i, j]``. The same format is used
+ in `scipy.linalg.solve_banded` (check for an illustration).
+ These parameters can be also used with ``jac=None`` to reduce the
+ number of Jacobian elements estimated by finite differences.
+ vectorized : bool, optional
+ Whether `fun` may be called in a vectorized fashion. False (default)
+ is recommended for this solver.
+
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
+ shape ``(n,)``, where ``n = len(y0)``.
+
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+ the returned array is the time derivative of the state corresponding
+ with a column of ``y``).
+
+ Setting ``vectorized=True`` allows for faster finite difference
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
+ will result in slower execution for this solver.
+
+ Attributes
+ ----------
+ n : int
+ Number of equations.
+ status : string
+ Current status of the solver: 'running', 'finished' or 'failed'.
+ t_bound : float
+ Boundary time.
+ direction : float
+ Integration direction: +1 or -1.
+ t : float
+ Current time.
+ y : ndarray
+ Current state.
+ t_old : float
+ Previous time. None if no steps were made yet.
+ nfev : int
+ Number of evaluations of the right-hand side.
+ njev : int
+ Number of evaluations of the Jacobian.
+
+ References
+ ----------
+ .. [1] A. C. Hindmarsh, "ODEPACK, A Systematized Collection of ODE
+ Solvers," IMACS Transactions on Scientific Computation, Vol 1.,
+ pp. 55-64, 1983.
+ .. [2] L. Petzold, "Automatic selection of methods for solving stiff and
+ nonstiff systems of ordinary differential equations", SIAM Journal
+ on Scientific and Statistical Computing, Vol. 4, No. 1, pp. 136-148,
+ 1983.
+ """
+ def __init__(self, fun, t0, y0, t_bound, first_step=None, min_step=0.0,
+ max_step=np.inf, rtol=1e-3, atol=1e-6, jac=None, lband=None,
+ uband=None, vectorized=False, **extraneous):
+ warn_extraneous(extraneous)
+ super().__init__(fun, t0, y0, t_bound, vectorized)
+
+ if first_step is None:
+ first_step = 0 # LSODA value for automatic selection.
+ else:
+ first_step = validate_first_step(first_step, t0, t_bound)
+
+ first_step *= self.direction
+
+ if max_step == np.inf:
+ max_step = 0 # LSODA value for infinity.
+ elif max_step <= 0:
+ raise ValueError("`max_step` must be positive.")
+
+ if min_step < 0:
+ raise ValueError("`min_step` must be nonnegative.")
+
+ rtol, atol = validate_tol(rtol, atol, self.n)
+
+ solver = ode(self.fun, jac)
+ solver.set_integrator('lsoda', rtol=rtol, atol=atol, max_step=max_step,
+ min_step=min_step, first_step=first_step,
+ lband=lband, uband=uband)
+ solver.set_initial_value(y0, t0)
+
+ # Inject t_bound into rwork array as needed for itask=5.
+ solver._integrator.rwork[0] = self.t_bound
+ solver._integrator.call_args[4] = solver._integrator.rwork
+
+ self._lsoda_solver = solver
+
+ def _step_impl(self):
+ solver = self._lsoda_solver
+ integrator = solver._integrator
+
+ # From lsoda.step and lsoda.integrate itask=5 means take a single
+ # step and do not go past t_bound.
+ itask = integrator.call_args[2]
+ integrator.call_args[2] = 5
+ solver._y, solver.t = integrator.run(
+ solver.f, solver.jac or (lambda: None), solver._y, solver.t,
+ self.t_bound, solver.f_params, solver.jac_params)
+ integrator.call_args[2] = itask
+
+ if solver.successful():
+ self.t = solver.t
+ self.y = solver._y
+ # From LSODA Fortran source njev is equal to nlu.
+ self.njev = integrator.iwork[12]
+ self.nlu = integrator.iwork[12]
+ return True, None
+ else:
+ return False, 'Unexpected istate in LSODA.'
+
+ def _dense_output_impl(self):
+ iwork = self._lsoda_solver._integrator.iwork
+ rwork = self._lsoda_solver._integrator.rwork
+
+ # We want to produce the Nordsieck history array, yh, up to the order
+ # used in the last successful iteration. The step size is unimportant
+ # because it will be scaled out in LsodaDenseOutput. Some additional
+ # work may be required because ODEPACK's LSODA implementation produces
+ # the Nordsieck history in the state needed for the next iteration.
+
+ # iwork[13] contains order from last successful iteration, while
+ # iwork[14] contains order to be attempted next.
+ order = iwork[13]
+
+ # rwork[11] contains the step size to be attempted next, while
+ # rwork[10] contains step size from last successful iteration.
+ h = rwork[11]
+
+ # rwork[20:20 + (iwork[14] + 1) * self.n] contains entries of the
+ # Nordsieck array in state needed for next iteration. We want
+ # the entries up to order for the last successful step so use the
+ # following.
+ yh = np.reshape(rwork[20:20 + (order + 1) * self.n],
+ (self.n, order + 1), order='F').copy()
+ if iwork[14] < order:
+ # If the order is set to decrease then the final column of yh
+ # has not been updated within ODEPACK's LSODA
+ # implementation because this column will not be used in the
+ # next iteration. We must rescale this column to make the
+ # associated step size consistent with the other columns.
+ yh[:, -1] *= (h / rwork[10]) ** order
+
+ return LsodaDenseOutput(self.t_old, self.t, h, order, yh)
+
+
+class LsodaDenseOutput(DenseOutput):
+ def __init__(self, t_old, t, h, order, yh):
+ super().__init__(t_old, t)
+ self.h = h
+ self.yh = yh
+ self.p = np.arange(order + 1)
+
+ def _call_impl(self, t):
+ if t.ndim == 0:
+ x = ((t - self.t) / self.h) ** self.p
+ else:
+ x = ((t - self.t) / self.h) ** self.p[:, None]
+
+ return np.dot(self.yh, x)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/radau.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/radau.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f42243a169d135302f8547217fbfefda0648e18
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/radau.py
@@ -0,0 +1,572 @@
+import numpy as np
+from scipy.linalg import lu_factor, lu_solve
+from scipy.sparse import csc_matrix, issparse, eye
+from scipy.sparse.linalg import splu
+from scipy.optimize._numdiff import group_columns
+from .common import (validate_max_step, validate_tol, select_initial_step,
+ norm, num_jac, EPS, warn_extraneous,
+ validate_first_step)
+from .base import OdeSolver, DenseOutput
+
+S6 = 6 ** 0.5
+
+# Butcher tableau. A is not used directly, see below.
+C = np.array([(4 - S6) / 10, (4 + S6) / 10, 1])
+E = np.array([-13 - 7 * S6, -13 + 7 * S6, -1]) / 3
+
+# Eigendecomposition of A is done: A = T L T**-1. There is 1 real eigenvalue
+# and a complex conjugate pair. They are written below.
+MU_REAL = 3 + 3 ** (2 / 3) - 3 ** (1 / 3)
+MU_COMPLEX = (3 + 0.5 * (3 ** (1 / 3) - 3 ** (2 / 3))
+ - 0.5j * (3 ** (5 / 6) + 3 ** (7 / 6)))
+
+# These are transformation matrices.
+T = np.array([
+ [0.09443876248897524, -0.14125529502095421, 0.03002919410514742],
+ [0.25021312296533332, 0.20412935229379994, -0.38294211275726192],
+ [1, 1, 0]])
+TI = np.array([
+ [4.17871859155190428, 0.32768282076106237, 0.52337644549944951],
+ [-4.17871859155190428, -0.32768282076106237, 0.47662355450055044],
+ [0.50287263494578682, -2.57192694985560522, 0.59603920482822492]])
+# These linear combinations are used in the algorithm.
+TI_REAL = TI[0]
+TI_COMPLEX = TI[1] + 1j * TI[2]
+
+# Interpolator coefficients.
+P = np.array([
+ [13/3 + 7*S6/3, -23/3 - 22*S6/3, 10/3 + 5 * S6],
+ [13/3 - 7*S6/3, -23/3 + 22*S6/3, 10/3 - 5 * S6],
+ [1/3, -8/3, 10/3]])
+
+
+NEWTON_MAXITER = 6 # Maximum number of Newton iterations.
+MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
+MAX_FACTOR = 10 # Maximum allowed increase in a step size.
+
+
+def solve_collocation_system(fun, t, y, h, Z0, scale, tol,
+ LU_real, LU_complex, solve_lu):
+ """Solve the collocation system.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system.
+ t : float
+ Current time.
+ y : ndarray, shape (n,)
+ Current state.
+ h : float
+ Step to try.
+ Z0 : ndarray, shape (3, n)
+ Initial guess for the solution. It determines new values of `y` at
+ ``t + h * C`` as ``y + Z0``, where ``C`` is the Radau method constants.
+ scale : ndarray, shape (n)
+ Problem tolerance scale, i.e. ``rtol * abs(y) + atol``.
+ tol : float
+ Tolerance to which solve the system. This value is compared with
+ the normalized by `scale` error.
+ LU_real, LU_complex
+ LU decompositions of the system Jacobians.
+ solve_lu : callable
+ Callable which solves a linear system given a LU decomposition. The
+ signature is ``solve_lu(LU, b)``.
+
+ Returns
+ -------
+ converged : bool
+ Whether iterations converged.
+ n_iter : int
+ Number of completed iterations.
+ Z : ndarray, shape (3, n)
+ Found solution.
+ rate : float
+ The rate of convergence.
+ """
+ n = y.shape[0]
+ M_real = MU_REAL / h
+ M_complex = MU_COMPLEX / h
+
+ W = TI.dot(Z0)
+ Z = Z0
+
+ F = np.empty((3, n))
+ ch = h * C
+
+ dW_norm_old = None
+ dW = np.empty_like(W)
+ converged = False
+ rate = None
+ for k in range(NEWTON_MAXITER):
+ for i in range(3):
+ F[i] = fun(t + ch[i], y + Z[i])
+
+ if not np.all(np.isfinite(F)):
+ break
+
+ f_real = F.T.dot(TI_REAL) - M_real * W[0]
+ f_complex = F.T.dot(TI_COMPLEX) - M_complex * (W[1] + 1j * W[2])
+
+ dW_real = solve_lu(LU_real, f_real)
+ dW_complex = solve_lu(LU_complex, f_complex)
+
+ dW[0] = dW_real
+ dW[1] = dW_complex.real
+ dW[2] = dW_complex.imag
+
+ dW_norm = norm(dW / scale)
+ if dW_norm_old is not None:
+ rate = dW_norm / dW_norm_old
+
+ if (rate is not None and (rate >= 1 or
+ rate ** (NEWTON_MAXITER - k) / (1 - rate) * dW_norm > tol)):
+ break
+
+ W += dW
+ Z = T.dot(W)
+
+ if (dW_norm == 0 or
+ rate is not None and rate / (1 - rate) * dW_norm < tol):
+ converged = True
+ break
+
+ dW_norm_old = dW_norm
+
+ return converged, k + 1, Z, rate
+
+
+def predict_factor(h_abs, h_abs_old, error_norm, error_norm_old):
+ """Predict by which factor to increase/decrease the step size.
+
+ The algorithm is described in [1]_.
+
+ Parameters
+ ----------
+ h_abs, h_abs_old : float
+ Current and previous values of the step size, `h_abs_old` can be None
+ (see Notes).
+ error_norm, error_norm_old : float
+ Current and previous values of the error norm, `error_norm_old` can
+ be None (see Notes).
+
+ Returns
+ -------
+ factor : float
+ Predicted factor.
+
+ Notes
+ -----
+ If `h_abs_old` and `error_norm_old` are both not None then a two-step
+ algorithm is used, otherwise a one-step algorithm is used.
+
+ References
+ ----------
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+ Equations II: Stiff and Differential-Algebraic Problems", Sec. IV.8.
+ """
+ if error_norm_old is None or h_abs_old is None or error_norm == 0:
+ multiplier = 1
+ else:
+ multiplier = h_abs / h_abs_old * (error_norm_old / error_norm) ** 0.25
+
+ with np.errstate(divide='ignore'):
+ factor = min(1, multiplier) * error_norm ** -0.25
+
+ return factor
+
+
+class Radau(OdeSolver):
+ """Implicit Runge-Kutta method of Radau IIA family of order 5.
+
+ The implementation follows [1]_. The error is controlled with a
+ third-order accurate embedded formula. A cubic polynomial which satisfies
+ the collocation conditions is used for the dense output.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system: the time derivative of the state ``y``
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+ return an array of the same shape as ``y``. See `vectorized` for more
+ information.
+ t0 : float
+ Initial time.
+ y0 : array_like, shape (n,)
+ Initial state.
+ t_bound : float
+ Boundary time - the integration won't continue beyond it. It also
+ determines the direction of the integration.
+ first_step : float or None, optional
+ Initial step size. Default is ``None`` which means that the algorithm
+ should choose.
+ max_step : float, optional
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
+ bounded and determined solely by the solver.
+ rtol, atol : float and array_like, optional
+ Relative and absolute tolerances. The solver keeps the local error
+ estimates less than ``atol + rtol * abs(y)``. HHere `rtol` controls a
+ relative accuracy (number of correct digits), while `atol` controls
+ absolute accuracy (number of correct decimal places). To achieve the
+ desired `rtol`, set `atol` to be smaller than the smallest value that
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+ number of correct digits is not guaranteed. Conversely, to achieve the
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+ than `atol`. If components of y have different scales, it might be
+ beneficial to set different `atol` values for different components by
+ passing array_like with shape (n,) for `atol`. Default values are
+ 1e-3 for `rtol` and 1e-6 for `atol`.
+ jac : {None, array_like, sparse_matrix, callable}, optional
+ Jacobian matrix of the right-hand side of the system with respect to
+ y, required by this method. The Jacobian matrix has shape (n, n) and
+ its element (i, j) is equal to ``d f_i / d y_j``.
+ There are three ways to define the Jacobian:
+
+ * If array_like or sparse_matrix, the Jacobian is assumed to
+ be constant.
+ * If callable, the Jacobian is assumed to depend on both
+ t and y; it will be called as ``jac(t, y)`` as necessary.
+ For the 'Radau' and 'BDF' methods, the return value might be a
+ sparse matrix.
+ * If None (default), the Jacobian will be approximated by
+ finite differences.
+
+ It is generally recommended to provide the Jacobian rather than
+ relying on a finite-difference approximation.
+ jac_sparsity : {None, array_like, sparse matrix}, optional
+ Defines a sparsity structure of the Jacobian matrix for a
+ finite-difference approximation. Its shape must be (n, n). This argument
+ is ignored if `jac` is not `None`. If the Jacobian has only few non-zero
+ elements in *each* row, providing the sparsity structure will greatly
+ speed up the computations [2]_. A zero entry means that a corresponding
+ element in the Jacobian is always zero. If None (default), the Jacobian
+ is assumed to be dense.
+ vectorized : bool, optional
+ Whether `fun` can be called in a vectorized fashion. Default is False.
+
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
+ shape ``(n,)``, where ``n = len(y0)``.
+
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+ the returned array is the time derivative of the state corresponding
+ with a column of ``y``).
+
+ Setting ``vectorized=True`` allows for faster finite difference
+ approximation of the Jacobian by this method, but may result in slower
+ execution overall in some circumstances (e.g. small ``len(y0)``).
+
+ Attributes
+ ----------
+ n : int
+ Number of equations.
+ status : string
+ Current status of the solver: 'running', 'finished' or 'failed'.
+ t_bound : float
+ Boundary time.
+ direction : float
+ Integration direction: +1 or -1.
+ t : float
+ Current time.
+ y : ndarray
+ Current state.
+ t_old : float
+ Previous time. None if no steps were made yet.
+ step_size : float
+ Size of the last successful step. None if no steps were made yet.
+ nfev : int
+ Number of evaluations of the right-hand side.
+ njev : int
+ Number of evaluations of the Jacobian.
+ nlu : int
+ Number of LU decompositions.
+
+ References
+ ----------
+ .. [1] E. Hairer, G. Wanner, "Solving Ordinary Differential Equations II:
+ Stiff and Differential-Algebraic Problems", Sec. IV.8.
+ .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
+ and its Applications, 13, pp. 117-120, 1974.
+ """
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+ rtol=1e-3, atol=1e-6, jac=None, jac_sparsity=None,
+ vectorized=False, first_step=None, **extraneous):
+ warn_extraneous(extraneous)
+ super().__init__(fun, t0, y0, t_bound, vectorized)
+ self.y_old = None
+ self.max_step = validate_max_step(max_step)
+ self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+ self.f = self.fun(self.t, self.y)
+ # Select initial step assuming the same order which is used to control
+ # the error.
+ if first_step is None:
+ self.h_abs = select_initial_step(
+ self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
+ 3, self.rtol, self.atol)
+ else:
+ self.h_abs = validate_first_step(first_step, t0, t_bound)
+ self.h_abs_old = None
+ self.error_norm_old = None
+
+ self.newton_tol = max(10 * EPS / rtol, min(0.03, rtol ** 0.5))
+ self.sol = None
+
+ self.jac_factor = None
+ self.jac, self.J = self._validate_jac(jac, jac_sparsity)
+ if issparse(self.J):
+ def lu(A):
+ self.nlu += 1
+ return splu(A)
+
+ def solve_lu(LU, b):
+ return LU.solve(b)
+
+ I = eye(self.n, format='csc')
+ else:
+ def lu(A):
+ self.nlu += 1
+ return lu_factor(A, overwrite_a=True)
+
+ def solve_lu(LU, b):
+ return lu_solve(LU, b, overwrite_b=True)
+
+ I = np.identity(self.n)
+
+ self.lu = lu
+ self.solve_lu = solve_lu
+ self.I = I
+
+ self.current_jac = True
+ self.LU_real = None
+ self.LU_complex = None
+ self.Z = None
+
+ def _validate_jac(self, jac, sparsity):
+ t0 = self.t
+ y0 = self.y
+
+ if jac is None:
+ if sparsity is not None:
+ if issparse(sparsity):
+ sparsity = csc_matrix(sparsity)
+ groups = group_columns(sparsity)
+ sparsity = (sparsity, groups)
+
+ def jac_wrapped(t, y, f):
+ self.njev += 1
+ J, self.jac_factor = num_jac(self.fun_vectorized, t, y, f,
+ self.atol, self.jac_factor,
+ sparsity)
+ return J
+ J = jac_wrapped(t0, y0, self.f)
+ elif callable(jac):
+ J = jac(t0, y0)
+ self.njev = 1
+ if issparse(J):
+ J = csc_matrix(J)
+
+ def jac_wrapped(t, y, _=None):
+ self.njev += 1
+ return csc_matrix(jac(t, y), dtype=float)
+
+ else:
+ J = np.asarray(J, dtype=float)
+
+ def jac_wrapped(t, y, _=None):
+ self.njev += 1
+ return np.asarray(jac(t, y), dtype=float)
+
+ if J.shape != (self.n, self.n):
+ raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+ f" but actually has {J.shape}.")
+ else:
+ if issparse(jac):
+ J = csc_matrix(jac)
+ else:
+ J = np.asarray(jac, dtype=float)
+
+ if J.shape != (self.n, self.n):
+ raise ValueError(f"`jac` is expected to have shape {(self.n, self.n)},"
+ f" but actually has {J.shape}.")
+ jac_wrapped = None
+
+ return jac_wrapped, J
+
+ def _step_impl(self):
+ t = self.t
+ y = self.y
+ f = self.f
+
+ max_step = self.max_step
+ atol = self.atol
+ rtol = self.rtol
+
+ min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+ if self.h_abs > max_step:
+ h_abs = max_step
+ h_abs_old = None
+ error_norm_old = None
+ elif self.h_abs < min_step:
+ h_abs = min_step
+ h_abs_old = None
+ error_norm_old = None
+ else:
+ h_abs = self.h_abs
+ h_abs_old = self.h_abs_old
+ error_norm_old = self.error_norm_old
+
+ J = self.J
+ LU_real = self.LU_real
+ LU_complex = self.LU_complex
+
+ current_jac = self.current_jac
+ jac = self.jac
+
+ rejected = False
+ step_accepted = False
+ message = None
+ while not step_accepted:
+ if h_abs < min_step:
+ return False, self.TOO_SMALL_STEP
+
+ h = h_abs * self.direction
+ t_new = t + h
+
+ if self.direction * (t_new - self.t_bound) > 0:
+ t_new = self.t_bound
+
+ h = t_new - t
+ h_abs = np.abs(h)
+
+ if self.sol is None:
+ Z0 = np.zeros((3, y.shape[0]))
+ else:
+ Z0 = self.sol(t + h * C).T - y
+
+ scale = atol + np.abs(y) * rtol
+
+ converged = False
+ while not converged:
+ if LU_real is None or LU_complex is None:
+ LU_real = self.lu(MU_REAL / h * self.I - J)
+ LU_complex = self.lu(MU_COMPLEX / h * self.I - J)
+
+ converged, n_iter, Z, rate = solve_collocation_system(
+ self.fun, t, y, h, Z0, scale, self.newton_tol,
+ LU_real, LU_complex, self.solve_lu)
+
+ if not converged:
+ if current_jac:
+ break
+
+ J = self.jac(t, y, f)
+ current_jac = True
+ LU_real = None
+ LU_complex = None
+
+ if not converged:
+ h_abs *= 0.5
+ LU_real = None
+ LU_complex = None
+ continue
+
+ y_new = y + Z[-1]
+ ZE = Z.T.dot(E) / h
+ error = self.solve_lu(LU_real, f + ZE)
+ scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
+ error_norm = norm(error / scale)
+ safety = 0.9 * (2 * NEWTON_MAXITER + 1) / (2 * NEWTON_MAXITER
+ + n_iter)
+
+ if rejected and error_norm > 1:
+ error = self.solve_lu(LU_real, self.fun(t, y + error) + ZE)
+ error_norm = norm(error / scale)
+
+ if error_norm > 1:
+ factor = predict_factor(h_abs, h_abs_old,
+ error_norm, error_norm_old)
+ h_abs *= max(MIN_FACTOR, safety * factor)
+
+ LU_real = None
+ LU_complex = None
+ rejected = True
+ else:
+ step_accepted = True
+
+ recompute_jac = jac is not None and n_iter > 2 and rate > 1e-3
+
+ factor = predict_factor(h_abs, h_abs_old, error_norm, error_norm_old)
+ factor = min(MAX_FACTOR, safety * factor)
+
+ if not recompute_jac and factor < 1.2:
+ factor = 1
+ else:
+ LU_real = None
+ LU_complex = None
+
+ f_new = self.fun(t_new, y_new)
+ if recompute_jac:
+ J = jac(t_new, y_new, f_new)
+ current_jac = True
+ elif jac is not None:
+ current_jac = False
+
+ self.h_abs_old = self.h_abs
+ self.error_norm_old = error_norm
+
+ self.h_abs = h_abs * factor
+
+ self.y_old = y
+
+ self.t = t_new
+ self.y = y_new
+ self.f = f_new
+
+ self.Z = Z
+
+ self.LU_real = LU_real
+ self.LU_complex = LU_complex
+ self.current_jac = current_jac
+ self.J = J
+
+ self.t_old = t
+ self.sol = self._compute_dense_output()
+
+ return step_accepted, message
+
+ def _compute_dense_output(self):
+ Q = np.dot(self.Z.T, P)
+ return RadauDenseOutput(self.t_old, self.t, self.y_old, Q)
+
+ def _dense_output_impl(self):
+ return self.sol
+
+
+class RadauDenseOutput(DenseOutput):
+ def __init__(self, t_old, t, y_old, Q):
+ super().__init__(t_old, t)
+ self.h = t - t_old
+ self.Q = Q
+ self.order = Q.shape[1] - 1
+ self.y_old = y_old
+
+ def _call_impl(self, t):
+ x = (t - self.t_old) / self.h
+ if t.ndim == 0:
+ p = np.tile(x, self.order + 1)
+ p = np.cumprod(p)
+ else:
+ p = np.tile(x, (self.order + 1, 1))
+ p = np.cumprod(p, axis=0)
+ # Here we don't multiply by h, not a mistake.
+ y = np.dot(self.Q, p)
+ if y.ndim == 2:
+ y += self.y_old[:, None]
+ else:
+ y += self.y_old
+
+ return y
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/rk.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..1810b5623159cb898435702cf5d4100646109d34
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/rk.py
@@ -0,0 +1,601 @@
+import numpy as np
+from .base import OdeSolver, DenseOutput
+from .common import (validate_max_step, validate_tol, select_initial_step,
+ norm, warn_extraneous, validate_first_step)
+from . import dop853_coefficients
+
+# Multiply steps computed from asymptotic behaviour of errors by this.
+SAFETY = 0.9
+
+MIN_FACTOR = 0.2 # Minimum allowed decrease in a step size.
+MAX_FACTOR = 10 # Maximum allowed increase in a step size.
+
+
+def rk_step(fun, t, y, f, h, A, B, C, K):
+ """Perform a single Runge-Kutta step.
+
+ This function computes a prediction of an explicit Runge-Kutta method and
+ also estimates the error of a less accurate method.
+
+ Notation for Butcher tableau is as in [1]_.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system.
+ t : float
+ Current time.
+ y : ndarray, shape (n,)
+ Current state.
+ f : ndarray, shape (n,)
+ Current value of the derivative, i.e., ``fun(x, y)``.
+ h : float
+ Step to use.
+ A : ndarray, shape (n_stages, n_stages)
+ Coefficients for combining previous RK stages to compute the next
+ stage. For explicit methods the coefficients at and above the main
+ diagonal are zeros.
+ B : ndarray, shape (n_stages,)
+ Coefficients for combining RK stages for computing the final
+ prediction.
+ C : ndarray, shape (n_stages,)
+ Coefficients for incrementing time for consecutive RK stages.
+ The value for the first stage is always zero.
+ K : ndarray, shape (n_stages + 1, n)
+ Storage array for putting RK stages here. Stages are stored in rows.
+ The last row is a linear combination of the previous rows with
+ coefficients
+
+ Returns
+ -------
+ y_new : ndarray, shape (n,)
+ Solution at t + h computed with a higher accuracy.
+ f_new : ndarray, shape (n,)
+ Derivative ``fun(t + h, y_new)``.
+
+ References
+ ----------
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+ Equations I: Nonstiff Problems", Sec. II.4.
+ """
+ K[0] = f
+ for s, (a, c) in enumerate(zip(A[1:], C[1:]), start=1):
+ dy = np.dot(K[:s].T, a[:s]) * h
+ K[s] = fun(t + c * h, y + dy)
+
+ y_new = y + h * np.dot(K[:-1].T, B)
+ f_new = fun(t + h, y_new)
+
+ K[-1] = f_new
+
+ return y_new, f_new
+
+
+class RungeKutta(OdeSolver):
+ """Base class for explicit Runge-Kutta methods."""
+ C: np.ndarray = NotImplemented
+ A: np.ndarray = NotImplemented
+ B: np.ndarray = NotImplemented
+ E: np.ndarray = NotImplemented
+ P: np.ndarray = NotImplemented
+ order: int = NotImplemented
+ error_estimator_order: int = NotImplemented
+ n_stages: int = NotImplemented
+
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+ rtol=1e-3, atol=1e-6, vectorized=False,
+ first_step=None, **extraneous):
+ warn_extraneous(extraneous)
+ super().__init__(fun, t0, y0, t_bound, vectorized,
+ support_complex=True)
+ self.y_old = None
+ self.max_step = validate_max_step(max_step)
+ self.rtol, self.atol = validate_tol(rtol, atol, self.n)
+ self.f = self.fun(self.t, self.y)
+ if first_step is None:
+ self.h_abs = select_initial_step(
+ self.fun, self.t, self.y, t_bound, max_step, self.f, self.direction,
+ self.error_estimator_order, self.rtol, self.atol)
+ else:
+ self.h_abs = validate_first_step(first_step, t0, t_bound)
+ self.K = np.empty((self.n_stages + 1, self.n), dtype=self.y.dtype)
+ self.error_exponent = -1 / (self.error_estimator_order + 1)
+ self.h_previous = None
+
+ def _estimate_error(self, K, h):
+ return np.dot(K.T, self.E) * h
+
+ def _estimate_error_norm(self, K, h, scale):
+ return norm(self._estimate_error(K, h) / scale)
+
+ def _step_impl(self):
+ t = self.t
+ y = self.y
+
+ max_step = self.max_step
+ rtol = self.rtol
+ atol = self.atol
+
+ min_step = 10 * np.abs(np.nextafter(t, self.direction * np.inf) - t)
+
+ if self.h_abs > max_step:
+ h_abs = max_step
+ elif self.h_abs < min_step:
+ h_abs = min_step
+ else:
+ h_abs = self.h_abs
+
+ step_accepted = False
+ step_rejected = False
+
+ while not step_accepted:
+ if h_abs < min_step:
+ return False, self.TOO_SMALL_STEP
+
+ h = h_abs * self.direction
+ t_new = t + h
+
+ if self.direction * (t_new - self.t_bound) > 0:
+ t_new = self.t_bound
+
+ h = t_new - t
+ h_abs = np.abs(h)
+
+ y_new, f_new = rk_step(self.fun, t, y, self.f, h, self.A,
+ self.B, self.C, self.K)
+ scale = atol + np.maximum(np.abs(y), np.abs(y_new)) * rtol
+ error_norm = self._estimate_error_norm(self.K, h, scale)
+
+ if error_norm < 1:
+ if error_norm == 0:
+ factor = MAX_FACTOR
+ else:
+ factor = min(MAX_FACTOR,
+ SAFETY * error_norm ** self.error_exponent)
+
+ if step_rejected:
+ factor = min(1, factor)
+
+ h_abs *= factor
+
+ step_accepted = True
+ else:
+ h_abs *= max(MIN_FACTOR,
+ SAFETY * error_norm ** self.error_exponent)
+ step_rejected = True
+
+ self.h_previous = h
+ self.y_old = y
+
+ self.t = t_new
+ self.y = y_new
+
+ self.h_abs = h_abs
+ self.f = f_new
+
+ return True, None
+
+ def _dense_output_impl(self):
+ Q = self.K.T.dot(self.P)
+ return RkDenseOutput(self.t_old, self.t, self.y_old, Q)
+
+
+class RK23(RungeKutta):
+ """Explicit Runge-Kutta method of order 3(2).
+
+ This uses the Bogacki-Shampine pair of formulas [1]_. The error is controlled
+ assuming accuracy of the second-order method, but steps are taken using the
+ third-order accurate formula (local extrapolation is done). A cubic Hermite
+ polynomial is used for the dense output.
+
+ Can be applied in the complex domain.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system: the time derivative of the state ``y``
+ at time ``t``. The calling signature is ``fun(t, y)``, where ``t`` is a
+ scalar and ``y`` is an ndarray with ``len(y) = len(y0)``. ``fun`` must
+ return an array of the same shape as ``y``. See `vectorized` for more
+ information.
+ t0 : float
+ Initial time.
+ y0 : array_like, shape (n,)
+ Initial state.
+ t_bound : float
+ Boundary time - the integration won't continue beyond it. It also
+ determines the direction of the integration.
+ first_step : float or None, optional
+ Initial step size. Default is ``None`` which means that the algorithm
+ should choose.
+ max_step : float, optional
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
+ bounded and determined solely by the solver.
+ rtol, atol : float and array_like, optional
+ Relative and absolute tolerances. The solver keeps the local error
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+ relative accuracy (number of correct digits), while `atol` controls
+ absolute accuracy (number of correct decimal places). To achieve the
+ desired `rtol`, set `atol` to be smaller than the smallest value that
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+ number of correct digits is not guaranteed. Conversely, to achieve the
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+ than `atol`. If components of y have different scales, it might be
+ beneficial to set different `atol` values for different components by
+ passing array_like with shape (n,) for `atol`. Default values are
+ 1e-3 for `rtol` and 1e-6 for `atol`.
+ vectorized : bool, optional
+ Whether `fun` may be called in a vectorized fashion. False (default)
+ is recommended for this solver.
+
+ If ``vectorized`` is False, `fun` will always be called with ``y`` of
+ shape ``(n,)``, where ``n = len(y0)``.
+
+ If ``vectorized`` is True, `fun` may be called with ``y`` of shape
+ ``(n, k)``, where ``k`` is an integer. In this case, `fun` must behave
+ such that ``fun(t, y)[:, i] == fun(t, y[:, i])`` (i.e. each column of
+ the returned array is the time derivative of the state corresponding
+ with a column of ``y``).
+
+ Setting ``vectorized=True`` allows for faster finite difference
+ approximation of the Jacobian by methods 'Radau' and 'BDF', but
+ will result in slower execution for this solver.
+
+ Attributes
+ ----------
+ n : int
+ Number of equations.
+ status : string
+ Current status of the solver: 'running', 'finished' or 'failed'.
+ t_bound : float
+ Boundary time.
+ direction : float
+ Integration direction: +1 or -1.
+ t : float
+ Current time.
+ y : ndarray
+ Current state.
+ t_old : float
+ Previous time. None if no steps were made yet.
+ step_size : float
+ Size of the last successful step. None if no steps were made yet.
+ nfev : int
+ Number evaluations of the system's right-hand side.
+ njev : int
+ Number of evaluations of the Jacobian.
+ Is always 0 for this solver as it does not use the Jacobian.
+ nlu : int
+ Number of LU decompositions. Is always 0 for this solver.
+
+ References
+ ----------
+ .. [1] P. Bogacki, L.F. Shampine, "A 3(2) Pair of Runge-Kutta Formulas",
+ Appl. Math. Lett. Vol. 2, No. 4. pp. 321-325, 1989.
+ """
+ order = 3
+ error_estimator_order = 2
+ n_stages = 3
+ C = np.array([0, 1/2, 3/4])
+ A = np.array([
+ [0, 0, 0],
+ [1/2, 0, 0],
+ [0, 3/4, 0]
+ ])
+ B = np.array([2/9, 1/3, 4/9])
+ E = np.array([5/72, -1/12, -1/9, 1/8])
+ P = np.array([[1, -4 / 3, 5 / 9],
+ [0, 1, -2/3],
+ [0, 4/3, -8/9],
+ [0, -1, 1]])
+
+
+class RK45(RungeKutta):
+ """Explicit Runge-Kutta method of order 5(4).
+
+ This uses the Dormand-Prince pair of formulas [1]_. The error is controlled
+ assuming accuracy of the fourth-order method accuracy, but steps are taken
+ using the fifth-order accurate formula (local extrapolation is done).
+ A quartic interpolation polynomial is used for the dense output [2]_.
+
+ Can be applied in the complex domain.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system. The calling signature is ``fun(t, y)``.
+ Here ``t`` is a scalar, and there are two options for the ndarray ``y``:
+ It can either have shape (n,); then ``fun`` must return array_like with
+ shape (n,). Alternatively it can have shape (n, k); then ``fun``
+ must return an array_like with shape (n, k), i.e., each column
+ corresponds to a single column in ``y``. The choice between the two
+ options is determined by `vectorized` argument (see below).
+ t0 : float
+ Initial time.
+ y0 : array_like, shape (n,)
+ Initial state.
+ t_bound : float
+ Boundary time - the integration won't continue beyond it. It also
+ determines the direction of the integration.
+ first_step : float or None, optional
+ Initial step size. Default is ``None`` which means that the algorithm
+ should choose.
+ max_step : float, optional
+ Maximum allowed step size. Default is np.inf, i.e., the step size is not
+ bounded and determined solely by the solver.
+ rtol, atol : float and array_like, optional
+ Relative and absolute tolerances. The solver keeps the local error
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+ relative accuracy (number of correct digits), while `atol` controls
+ absolute accuracy (number of correct decimal places). To achieve the
+ desired `rtol`, set `atol` to be smaller than the smallest value that
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+ number of correct digits is not guaranteed. Conversely, to achieve the
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+ than `atol`. If components of y have different scales, it might be
+ beneficial to set different `atol` values for different components by
+ passing array_like with shape (n,) for `atol`. Default values are
+ 1e-3 for `rtol` and 1e-6 for `atol`.
+ vectorized : bool, optional
+ Whether `fun` is implemented in a vectorized fashion. Default is False.
+
+ Attributes
+ ----------
+ n : int
+ Number of equations.
+ status : string
+ Current status of the solver: 'running', 'finished' or 'failed'.
+ t_bound : float
+ Boundary time.
+ direction : float
+ Integration direction: +1 or -1.
+ t : float
+ Current time.
+ y : ndarray
+ Current state.
+ t_old : float
+ Previous time. None if no steps were made yet.
+ step_size : float
+ Size of the last successful step. None if no steps were made yet.
+ nfev : int
+ Number evaluations of the system's right-hand side.
+ njev : int
+ Number of evaluations of the Jacobian.
+ Is always 0 for this solver as it does not use the Jacobian.
+ nlu : int
+ Number of LU decompositions. Is always 0 for this solver.
+
+ References
+ ----------
+ .. [1] J. R. Dormand, P. J. Prince, "A family of embedded Runge-Kutta
+ formulae", Journal of Computational and Applied Mathematics, Vol. 6,
+ No. 1, pp. 19-26, 1980.
+ .. [2] L. W. Shampine, "Some Practical Runge-Kutta Formulas", Mathematics
+ of Computation,, Vol. 46, No. 173, pp. 135-150, 1986.
+ """
+ order = 5
+ error_estimator_order = 4
+ n_stages = 6
+ C = np.array([0, 1/5, 3/10, 4/5, 8/9, 1])
+ A = np.array([
+ [0, 0, 0, 0, 0],
+ [1/5, 0, 0, 0, 0],
+ [3/40, 9/40, 0, 0, 0],
+ [44/45, -56/15, 32/9, 0, 0],
+ [19372/6561, -25360/2187, 64448/6561, -212/729, 0],
+ [9017/3168, -355/33, 46732/5247, 49/176, -5103/18656]
+ ])
+ B = np.array([35/384, 0, 500/1113, 125/192, -2187/6784, 11/84])
+ E = np.array([-71/57600, 0, 71/16695, -71/1920, 17253/339200, -22/525,
+ 1/40])
+ # Corresponds to the optimum value of c_6 from [2]_.
+ P = np.array([
+ [1, -8048581381/2820520608, 8663915743/2820520608,
+ -12715105075/11282082432],
+ [0, 0, 0, 0],
+ [0, 131558114200/32700410799, -68118460800/10900136933,
+ 87487479700/32700410799],
+ [0, -1754552775/470086768, 14199869525/1410260304,
+ -10690763975/1880347072],
+ [0, 127303824393/49829197408, -318862633887/49829197408,
+ 701980252875 / 199316789632],
+ [0, -282668133/205662961, 2019193451/616988883, -1453857185/822651844],
+ [0, 40617522/29380423, -110615467/29380423, 69997945/29380423]])
+
+
+class DOP853(RungeKutta):
+ """Explicit Runge-Kutta method of order 8.
+
+ This is a Python implementation of "DOP853" algorithm originally written
+ in Fortran [1]_, [2]_. Note that this is not a literal translation, but
+ the algorithmic core and coefficients are the same.
+
+ Can be applied in the complex domain.
+
+ Parameters
+ ----------
+ fun : callable
+ Right-hand side of the system. The calling signature is ``fun(t, y)``.
+ Here, ``t`` is a scalar, and there are two options for the ndarray ``y``:
+ It can either have shape (n,); then ``fun`` must return array_like with
+ shape (n,). Alternatively it can have shape (n, k); then ``fun``
+ must return an array_like with shape (n, k), i.e. each column
+ corresponds to a single column in ``y``. The choice between the two
+ options is determined by `vectorized` argument (see below).
+ t0 : float
+ Initial time.
+ y0 : array_like, shape (n,)
+ Initial state.
+ t_bound : float
+ Boundary time - the integration won't continue beyond it. It also
+ determines the direction of the integration.
+ first_step : float or None, optional
+ Initial step size. Default is ``None`` which means that the algorithm
+ should choose.
+ max_step : float, optional
+ Maximum allowed step size. Default is np.inf, i.e. the step size is not
+ bounded and determined solely by the solver.
+ rtol, atol : float and array_like, optional
+ Relative and absolute tolerances. The solver keeps the local error
+ estimates less than ``atol + rtol * abs(y)``. Here `rtol` controls a
+ relative accuracy (number of correct digits), while `atol` controls
+ absolute accuracy (number of correct decimal places). To achieve the
+ desired `rtol`, set `atol` to be smaller than the smallest value that
+ can be expected from ``rtol * abs(y)`` so that `rtol` dominates the
+ allowable error. If `atol` is larger than ``rtol * abs(y)`` the
+ number of correct digits is not guaranteed. Conversely, to achieve the
+ desired `atol` set `rtol` such that ``rtol * abs(y)`` is always smaller
+ than `atol`. If components of y have different scales, it might be
+ beneficial to set different `atol` values for different components by
+ passing array_like with shape (n,) for `atol`. Default values are
+ 1e-3 for `rtol` and 1e-6 for `atol`.
+ vectorized : bool, optional
+ Whether `fun` is implemented in a vectorized fashion. Default is False.
+
+ Attributes
+ ----------
+ n : int
+ Number of equations.
+ status : string
+ Current status of the solver: 'running', 'finished' or 'failed'.
+ t_bound : float
+ Boundary time.
+ direction : float
+ Integration direction: +1 or -1.
+ t : float
+ Current time.
+ y : ndarray
+ Current state.
+ t_old : float
+ Previous time. None if no steps were made yet.
+ step_size : float
+ Size of the last successful step. None if no steps were made yet.
+ nfev : int
+ Number evaluations of the system's right-hand side.
+ njev : int
+ Number of evaluations of the Jacobian. Is always 0 for this solver
+ as it does not use the Jacobian.
+ nlu : int
+ Number of LU decompositions. Is always 0 for this solver.
+
+ References
+ ----------
+ .. [1] E. Hairer, S. P. Norsett G. Wanner, "Solving Ordinary Differential
+ Equations I: Nonstiff Problems", Sec. II.
+ .. [2] `Page with original Fortran code of DOP853
+ `_.
+ """
+ n_stages = dop853_coefficients.N_STAGES
+ order = 8
+ error_estimator_order = 7
+ A = dop853_coefficients.A[:n_stages, :n_stages]
+ B = dop853_coefficients.B
+ C = dop853_coefficients.C[:n_stages]
+ E3 = dop853_coefficients.E3
+ E5 = dop853_coefficients.E5
+ D = dop853_coefficients.D
+
+ A_EXTRA = dop853_coefficients.A[n_stages + 1:]
+ C_EXTRA = dop853_coefficients.C[n_stages + 1:]
+
+ def __init__(self, fun, t0, y0, t_bound, max_step=np.inf,
+ rtol=1e-3, atol=1e-6, vectorized=False,
+ first_step=None, **extraneous):
+ super().__init__(fun, t0, y0, t_bound, max_step, rtol, atol,
+ vectorized, first_step, **extraneous)
+ self.K_extended = np.empty((dop853_coefficients.N_STAGES_EXTENDED,
+ self.n), dtype=self.y.dtype)
+ self.K = self.K_extended[:self.n_stages + 1]
+
+ def _estimate_error(self, K, h): # Left for testing purposes.
+ err5 = np.dot(K.T, self.E5)
+ err3 = np.dot(K.T, self.E3)
+ denom = np.hypot(np.abs(err5), 0.1 * np.abs(err3))
+ correction_factor = np.ones_like(err5)
+ mask = denom > 0
+ correction_factor[mask] = np.abs(err5[mask]) / denom[mask]
+ return h * err5 * correction_factor
+
+ def _estimate_error_norm(self, K, h, scale):
+ err5 = np.dot(K.T, self.E5) / scale
+ err3 = np.dot(K.T, self.E3) / scale
+ err5_norm_2 = np.linalg.norm(err5)**2
+ err3_norm_2 = np.linalg.norm(err3)**2
+ if err5_norm_2 == 0 and err3_norm_2 == 0:
+ return 0.0
+ denom = err5_norm_2 + 0.01 * err3_norm_2
+ return np.abs(h) * err5_norm_2 / np.sqrt(denom * len(scale))
+
+ def _dense_output_impl(self):
+ K = self.K_extended
+ h = self.h_previous
+ for s, (a, c) in enumerate(zip(self.A_EXTRA, self.C_EXTRA),
+ start=self.n_stages + 1):
+ dy = np.dot(K[:s].T, a[:s]) * h
+ K[s] = self.fun(self.t_old + c * h, self.y_old + dy)
+
+ F = np.empty((dop853_coefficients.INTERPOLATOR_POWER, self.n),
+ dtype=self.y_old.dtype)
+
+ f_old = K[0]
+ delta_y = self.y - self.y_old
+
+ F[0] = delta_y
+ F[1] = h * f_old - delta_y
+ F[2] = 2 * delta_y - h * (self.f + f_old)
+ F[3:] = h * np.dot(self.D, K)
+
+ return Dop853DenseOutput(self.t_old, self.t, self.y_old, F)
+
+
+class RkDenseOutput(DenseOutput):
+ def __init__(self, t_old, t, y_old, Q):
+ super().__init__(t_old, t)
+ self.h = t - t_old
+ self.Q = Q
+ self.order = Q.shape[1] - 1
+ self.y_old = y_old
+
+ def _call_impl(self, t):
+ x = (t - self.t_old) / self.h
+ if t.ndim == 0:
+ p = np.tile(x, self.order + 1)
+ p = np.cumprod(p)
+ else:
+ p = np.tile(x, (self.order + 1, 1))
+ p = np.cumprod(p, axis=0)
+ y = self.h * np.dot(self.Q, p)
+ if y.ndim == 2:
+ y += self.y_old[:, None]
+ else:
+ y += self.y_old
+
+ return y
+
+
+class Dop853DenseOutput(DenseOutput):
+ def __init__(self, t_old, t, y_old, F):
+ super().__init__(t_old, t)
+ self.h = t - t_old
+ self.F = F
+ self.y_old = y_old
+
+ def _call_impl(self, t):
+ x = (t - self.t_old) / self.h
+
+ if t.ndim == 0:
+ y = np.zeros_like(self.y_old)
+ else:
+ x = x[:, None]
+ y = np.zeros((len(x), len(self.y_old)), dtype=self.y_old.dtype)
+
+ for i, f in enumerate(reversed(self.F)):
+ y += f
+ if i % 2 == 0:
+ y *= x
+ else:
+ y *= 1 - x
+ y += self.y_old
+
+ return y.T
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/__init__.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/test_ivp.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
new file mode 100644
index 0000000000000000000000000000000000000000..e219fb866e1e3a6a5d8f8ab64d1c24976d308fdf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/test_ivp.py
@@ -0,0 +1,1287 @@
+from itertools import product
+from numpy.testing import (assert_, assert_allclose, assert_array_less,
+ assert_equal, assert_no_warnings, suppress_warnings)
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from scipy.optimize._numdiff import group_columns
+from scipy.integrate import solve_ivp, RK23, RK45, DOP853, Radau, BDF, LSODA
+from scipy.integrate import OdeSolution
+from scipy.integrate._ivp.common import num_jac, select_initial_step
+from scipy.integrate._ivp.base import ConstantDenseOutput
+from scipy.sparse import coo_matrix, csc_matrix
+
+
+def fun_zero(t, y):
+ return np.zeros_like(y)
+
+
+def fun_linear(t, y):
+ return np.array([-y[0] - 5 * y[1], y[0] + y[1]])
+
+
+def jac_linear():
+ return np.array([[-1, -5], [1, 1]])
+
+
+def sol_linear(t):
+ return np.vstack((-5 * np.sin(2 * t),
+ 2 * np.cos(2 * t) + np.sin(2 * t)))
+
+
+def fun_rational(t, y):
+ return np.array([y[1] / t,
+ y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))])
+
+
+def fun_rational_vectorized(t, y):
+ return np.vstack((y[1] / t,
+ y[1] * (y[0] + 2 * y[1] - 1) / (t * (y[0] - 1))))
+
+
+def jac_rational(t, y):
+ return np.array([
+ [0, 1 / t],
+ [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
+ (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
+ ])
+
+
+def jac_rational_sparse(t, y):
+ return csc_matrix([
+ [0, 1 / t],
+ [-2 * y[1] ** 2 / (t * (y[0] - 1) ** 2),
+ (y[0] + 4 * y[1] - 1) / (t * (y[0] - 1))]
+ ])
+
+
+def sol_rational(t):
+ return np.asarray((t / (t + 10), 10 * t / (t + 10) ** 2))
+
+
+def fun_medazko(t, y):
+ n = y.shape[0] // 2
+ k = 100
+ c = 4
+
+ phi = 2 if t <= 5 else 0
+ y = np.hstack((phi, 0, y, y[-2]))
+
+ d = 1 / n
+ j = np.arange(n) + 1
+ alpha = 2 * (j * d - 1) ** 3 / c ** 2
+ beta = (j * d - 1) ** 4 / c ** 2
+
+ j_2_p1 = 2 * j + 2
+ j_2_m3 = 2 * j - 2
+ j_2_m1 = 2 * j
+ j_2 = 2 * j + 1
+
+ f = np.empty(2 * n)
+ f[::2] = (alpha * (y[j_2_p1] - y[j_2_m3]) / (2 * d) +
+ beta * (y[j_2_m3] - 2 * y[j_2_m1] + y[j_2_p1]) / d ** 2 -
+ k * y[j_2_m1] * y[j_2])
+ f[1::2] = -k * y[j_2] * y[j_2_m1]
+
+ return f
+
+
+def medazko_sparsity(n):
+ cols = []
+ rows = []
+
+ i = np.arange(n) * 2
+
+ cols.append(i[1:])
+ rows.append(i[1:] - 2)
+
+ cols.append(i)
+ rows.append(i)
+
+ cols.append(i)
+ rows.append(i + 1)
+
+ cols.append(i[:-1])
+ rows.append(i[:-1] + 2)
+
+ i = np.arange(n) * 2 + 1
+
+ cols.append(i)
+ rows.append(i)
+
+ cols.append(i)
+ rows.append(i - 1)
+
+ cols = np.hstack(cols)
+ rows = np.hstack(rows)
+
+ return coo_matrix((np.ones_like(cols), (cols, rows)))
+
+
+def fun_complex(t, y):
+ return -y
+
+
+def jac_complex(t, y):
+ return -np.eye(y.shape[0])
+
+
+def jac_complex_sparse(t, y):
+ return csc_matrix(jac_complex(t, y))
+
+
+def sol_complex(t):
+ y = (0.5 + 1j) * np.exp(-t)
+ return y.reshape((1, -1))
+
+
+def fun_event_dense_output_LSODA(t, y):
+ return y * (t - 2)
+
+
+def jac_event_dense_output_LSODA(t, y):
+ return t - 2
+
+
+def sol_event_dense_output_LSODA(t):
+ return np.exp(t ** 2 / 2 - 2 * t + np.log(0.05) - 6)
+
+
+def compute_error(y, y_true, rtol, atol):
+ e = (y - y_true) / (atol + rtol * np.abs(y_true))
+ return np.linalg.norm(e, axis=0) / np.sqrt(e.shape[0])
+
+def test_duplicate_timestamps():
+ def upward_cannon(t, y):
+ return [y[1], -9.80665]
+
+ def hit_ground(t, y):
+ return y[0]
+
+ hit_ground.terminal = True
+ hit_ground.direction = -1
+
+ sol = solve_ivp(upward_cannon, [0, np.inf], [0, 0.01],
+ max_step=0.05 * 0.001 / 9.80665,
+ events=hit_ground, dense_output=True)
+ assert_allclose(sol.sol(0.01), np.asarray([-0.00039033, -0.08806632]),
+ rtol=1e-5, atol=1e-8)
+ assert_allclose(sol.t_events, np.asarray([[0.00203943]]), rtol=1e-5, atol=1e-8)
+ assert_allclose(sol.y_events, [np.asarray([[ 0.0, -0.01 ]])], atol=1e-9)
+ assert sol.success
+ assert_equal(sol.status, 1)
+
+@pytest.mark.thread_unsafe
+def test_integration():
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [1/3, 2/9]
+
+ for vectorized, method, t_span, jac in product(
+ [False, True],
+ ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'],
+ [[5, 9], [5, 1]],
+ [None, jac_rational, jac_rational_sparse]):
+
+ if vectorized:
+ fun = fun_rational_vectorized
+ else:
+ fun = fun_rational
+
+ with suppress_warnings() as sup:
+ sup.filter(UserWarning,
+ "The following arguments have no effect for a chosen "
+ "solver: `jac`")
+ res = solve_ivp(fun, t_span, y0, rtol=rtol,
+ atol=atol, method=method, dense_output=True,
+ jac=jac, vectorized=vectorized)
+ assert_equal(res.t[0], t_span[0])
+ assert_(res.t_events is None)
+ assert_(res.y_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ if method == 'DOP853':
+ # DOP853 spends more functions evaluation because it doesn't
+ # have enough time to develop big enough step size.
+ assert_(res.nfev < 50)
+ else:
+ assert_(res.nfev < 40)
+
+ if method in ['RK23', 'RK45', 'DOP853', 'LSODA']:
+ assert_equal(res.njev, 0)
+ assert_equal(res.nlu, 0)
+ else:
+ assert_(0 < res.njev < 3)
+ assert_(0 < res.nlu < 10)
+
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ tc = np.linspace(*t_span)
+ yc_true = sol_rational(tc)
+ yc = res.sol(tc)
+
+ e = compute_error(yc, yc_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ tc = (t_span[0] + t_span[-1]) / 2
+ yc_true = sol_rational(tc)
+ yc = res.sol(tc)
+
+ e = compute_error(yc, yc_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+
+@pytest.mark.thread_unsafe
+def test_integration_complex():
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [0.5 + 1j]
+ t_span = [0, 1]
+ tc = np.linspace(t_span[0], t_span[1])
+ for method, jac in product(['RK23', 'RK45', 'DOP853', 'BDF'],
+ [None, jac_complex, jac_complex_sparse]):
+ with suppress_warnings() as sup:
+ sup.filter(UserWarning,
+ "The following arguments have no effect for a chosen "
+ "solver: `jac`")
+ res = solve_ivp(fun_complex, t_span, y0, method=method,
+ dense_output=True, rtol=rtol, atol=atol, jac=jac)
+
+ assert_equal(res.t[0], t_span[0])
+ assert_(res.t_events is None)
+ assert_(res.y_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ if method == 'DOP853':
+ assert res.nfev < 35
+ else:
+ assert res.nfev < 25
+
+ if method == 'BDF':
+ assert_equal(res.njev, 1)
+ assert res.nlu < 6
+ else:
+ assert res.njev == 0
+ assert res.nlu == 0
+
+ y_true = sol_complex(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert np.all(e < 5)
+
+ yc_true = sol_complex(tc)
+ yc = res.sol(tc)
+ e = compute_error(yc, yc_true, rtol, atol)
+
+ assert np.all(e < 5)
+
+
+@pytest.mark.fail_slow(5)
+def test_integration_sparse_difference():
+ n = 200
+ t_span = [0, 20]
+ y0 = np.zeros(2 * n)
+ y0[1::2] = 1
+ sparsity = medazko_sparsity(n)
+
+ for method in ['BDF', 'Radau']:
+ res = solve_ivp(fun_medazko, t_span, y0, method=method,
+ jac_sparsity=sparsity)
+
+ assert_equal(res.t[0], t_span[0])
+ assert_(res.t_events is None)
+ assert_(res.y_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ assert_allclose(res.y[78, -1], 0.233994e-3, rtol=1e-2)
+ assert_allclose(res.y[79, -1], 0, atol=1e-3)
+ assert_allclose(res.y[148, -1], 0.359561e-3, rtol=1e-2)
+ assert_allclose(res.y[149, -1], 0, atol=1e-3)
+ assert_allclose(res.y[198, -1], 0.117374129e-3, rtol=1e-2)
+ assert_allclose(res.y[199, -1], 0.6190807e-5, atol=1e-3)
+ assert_allclose(res.y[238, -1], 0, atol=1e-3)
+ assert_allclose(res.y[239, -1], 0.9999997, rtol=1e-2)
+
+
+def test_integration_const_jac():
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [0, 2]
+ t_span = [0, 2]
+ J = jac_linear()
+ J_sparse = csc_matrix(J)
+
+ for method, jac in product(['Radau', 'BDF'], [J, J_sparse]):
+ res = solve_ivp(fun_linear, t_span, y0, rtol=rtol, atol=atol,
+ method=method, dense_output=True, jac=jac)
+ assert_equal(res.t[0], t_span[0])
+ assert_(res.t_events is None)
+ assert_(res.y_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ assert_(res.nfev < 100)
+ assert_equal(res.njev, 0)
+ assert_(0 < res.nlu < 15)
+
+ y_true = sol_linear(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 10))
+
+ tc = np.linspace(*t_span)
+ yc_true = sol_linear(tc)
+ yc = res.sol(tc)
+
+ e = compute_error(yc, yc_true, rtol, atol)
+ assert_(np.all(e < 15))
+
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-14, atol=1e-14)
+
+
+@pytest.mark.slow
+@pytest.mark.parametrize('method', ['Radau', 'BDF', 'LSODA'])
+def test_integration_stiff(method, num_parallel_threads):
+ rtol = 1e-6
+ atol = 1e-6
+ y0 = [1e4, 0, 0]
+ tspan = [0, 1e8]
+
+ if method == 'LSODA' and num_parallel_threads > 1:
+ pytest.skip(reason='LSODA does not allow for concurrent calls')
+
+ def fun_robertson(t, state):
+ x, y, z = state
+ return [
+ -0.04 * x + 1e4 * y * z,
+ 0.04 * x - 1e4 * y * z - 3e7 * y * y,
+ 3e7 * y * y,
+ ]
+
+ res = solve_ivp(fun_robertson, tspan, y0, rtol=rtol,
+ atol=atol, method=method)
+
+ # If the stiff mode is not activated correctly, these numbers will be much bigger
+ assert res.nfev < 5000
+ assert res.njev < 200
+
+
+def test_events(num_parallel_threads):
+ def event_rational_1(t, y):
+ return y[0] - y[1] ** 0.7
+
+ def event_rational_2(t, y):
+ return y[1] ** 0.6 - y[0]
+
+ def event_rational_3(t, y):
+ return t - 7.4
+
+ event_rational_3.terminal = True
+
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+ if method == 'LSODA' and num_parallel_threads > 1:
+ continue
+
+ res = solve_ivp(fun_rational, [5, 8], [1/3, 2/9], method=method,
+ events=(event_rational_1, event_rational_2))
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 1)
+ assert_equal(res.t_events[1].size, 1)
+ assert_(5.3 < res.t_events[0][0] < 5.7)
+ assert_(7.3 < res.t_events[1][0] < 7.7)
+
+ assert_equal(res.y_events[0].shape, (1, 2))
+ assert_equal(res.y_events[1].shape, (1, 2))
+ assert np.isclose(
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+ assert np.isclose(
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+ event_rational_1.direction = 1
+ event_rational_2.direction = 1
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+ events=(event_rational_1, event_rational_2))
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 1)
+ assert_equal(res.t_events[1].size, 0)
+ assert_(5.3 < res.t_events[0][0] < 5.7)
+ assert_equal(res.y_events[0].shape, (1, 2))
+ assert_equal(res.y_events[1].shape, (0,))
+ assert np.isclose(
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+ event_rational_1.direction = -1
+ event_rational_2.direction = -1
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+ events=(event_rational_1, event_rational_2))
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 0)
+ assert_equal(res.t_events[1].size, 1)
+ assert_(7.3 < res.t_events[1][0] < 7.7)
+ assert_equal(res.y_events[0].shape, (0,))
+ assert_equal(res.y_events[1].shape, (1, 2))
+ assert np.isclose(
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+ event_rational_1.direction = 0
+ event_rational_2.direction = 0
+
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+ events=(event_rational_1, event_rational_2,
+ event_rational_3), dense_output=True)
+ assert_equal(res.status, 1)
+ assert_equal(res.t_events[0].size, 1)
+ assert_equal(res.t_events[1].size, 0)
+ assert_equal(res.t_events[2].size, 1)
+ assert_(5.3 < res.t_events[0][0] < 5.7)
+ assert_(7.3 < res.t_events[2][0] < 7.5)
+ assert_equal(res.y_events[0].shape, (1, 2))
+ assert_equal(res.y_events[1].shape, (0,))
+ assert_equal(res.y_events[2].shape, (1, 2))
+ assert np.isclose(
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+ assert np.isclose(
+ event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
+
+ res = solve_ivp(fun_rational, [5, 8], [1 / 3, 2 / 9], method=method,
+ events=event_rational_1, dense_output=True)
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 1)
+ assert_(5.3 < res.t_events[0][0] < 5.7)
+
+ assert_equal(res.y_events[0].shape, (1, 2))
+ assert np.isclose(
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+ # Also test that termination by event doesn't break interpolants.
+ tc = np.linspace(res.t[0], res.t[-1])
+ yc_true = sol_rational(tc)
+ yc = res.sol(tc)
+ e = compute_error(yc, yc_true, 1e-3, 1e-6)
+ assert_(np.all(e < 5))
+
+ # Test that the y_event matches solution
+ assert np.allclose(sol_rational(res.t_events[0][0]), res.y_events[0][0],
+ rtol=1e-3, atol=1e-6)
+
+ # Test in backward direction.
+ event_rational_1.direction = 0
+ event_rational_2.direction = 0
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+ if method == 'LSODA' and num_parallel_threads > 1:
+ continue
+
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+ events=(event_rational_1, event_rational_2))
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 1)
+ assert_equal(res.t_events[1].size, 1)
+ assert_(5.3 < res.t_events[0][0] < 5.7)
+ assert_(7.3 < res.t_events[1][0] < 7.7)
+
+ assert_equal(res.y_events[0].shape, (1, 2))
+ assert_equal(res.y_events[1].shape, (1, 2))
+ assert np.isclose(
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+ assert np.isclose(
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+ event_rational_1.direction = -1
+ event_rational_2.direction = -1
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+ events=(event_rational_1, event_rational_2))
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 1)
+ assert_equal(res.t_events[1].size, 0)
+ assert_(5.3 < res.t_events[0][0] < 5.7)
+
+ assert_equal(res.y_events[0].shape, (1, 2))
+ assert_equal(res.y_events[1].shape, (0,))
+ assert np.isclose(
+ event_rational_1(res.t_events[0][0], res.y_events[0][0]), 0)
+
+ event_rational_1.direction = 1
+ event_rational_2.direction = 1
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+ events=(event_rational_1, event_rational_2))
+ assert_equal(res.status, 0)
+ assert_equal(res.t_events[0].size, 0)
+ assert_equal(res.t_events[1].size, 1)
+ assert_(7.3 < res.t_events[1][0] < 7.7)
+
+ assert_equal(res.y_events[0].shape, (0,))
+ assert_equal(res.y_events[1].shape, (1, 2))
+ assert np.isclose(
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+
+ event_rational_1.direction = 0
+ event_rational_2.direction = 0
+
+ res = solve_ivp(fun_rational, [8, 5], [4/9, 20/81], method=method,
+ events=(event_rational_1, event_rational_2,
+ event_rational_3), dense_output=True)
+ assert_equal(res.status, 1)
+ assert_equal(res.t_events[0].size, 0)
+ assert_equal(res.t_events[1].size, 1)
+ assert_equal(res.t_events[2].size, 1)
+ assert_(7.3 < res.t_events[1][0] < 7.7)
+ assert_(7.3 < res.t_events[2][0] < 7.5)
+
+ assert_equal(res.y_events[0].shape, (0,))
+ assert_equal(res.y_events[1].shape, (1, 2))
+ assert_equal(res.y_events[2].shape, (1, 2))
+ assert np.isclose(
+ event_rational_2(res.t_events[1][0], res.y_events[1][0]), 0)
+ assert np.isclose(
+ event_rational_3(res.t_events[2][0], res.y_events[2][0]), 0)
+
+ # Also test that termination by event doesn't break interpolants.
+ tc = np.linspace(res.t[-1], res.t[0])
+ yc_true = sol_rational(tc)
+ yc = res.sol(tc)
+ e = compute_error(yc, yc_true, 1e-3, 1e-6)
+ assert_(np.all(e < 5))
+
+ assert np.allclose(sol_rational(res.t_events[1][0]), res.y_events[1][0],
+ rtol=1e-3, atol=1e-6)
+ assert np.allclose(sol_rational(res.t_events[2][0]), res.y_events[2][0],
+ rtol=1e-3, atol=1e-6)
+
+
+def _get_harmonic_oscillator():
+ def f(t, y):
+ return [y[1], -y[0]]
+
+ def event(t, y):
+ return y[0]
+
+ return f, event
+
+
+@pytest.mark.parametrize('n_events', [3, 4])
+def test_event_terminal_integer(n_events):
+ f, event = _get_harmonic_oscillator()
+ event.terminal = n_events
+ res = solve_ivp(f, (0, 100), [1, 0], events=event)
+ assert len(res.t_events[0]) == n_events
+ assert len(res.y_events[0]) == n_events
+ assert_allclose(res.y_events[0][:, 0], 0, atol=1e-14)
+
+
+def test_event_terminal_iv():
+ f, event = _get_harmonic_oscillator()
+ args = (f, (0, 100), [1, 0])
+
+ event.terminal = None
+ res = solve_ivp(*args, events=event)
+ event.terminal = 0
+ ref = solve_ivp(*args, events=event)
+ assert_allclose(res.t_events, ref.t_events)
+
+ message = "The `terminal` attribute..."
+ event.terminal = -1
+ with pytest.raises(ValueError, match=message):
+ solve_ivp(*args, events=event)
+ event.terminal = 3.5
+ with pytest.raises(ValueError, match=message):
+ solve_ivp(*args, events=event)
+
+
+def test_max_step(num_parallel_threads):
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [1/3, 2/9]
+ for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+ if method is LSODA and num_parallel_threads > 1:
+ continue
+ for t_span in ([5, 9], [5, 1]):
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
+ max_step=0.5, atol=atol, method=method,
+ dense_output=True)
+ assert_equal(res.t[0], t_span[0])
+ assert_equal(res.t[-1], t_span[-1])
+ assert_(np.all(np.abs(np.diff(res.t)) <= 0.5 + 1e-15))
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ tc = np.linspace(*t_span)
+ yc_true = sol_rational(tc)
+ yc = res.sol(tc)
+
+ e = compute_error(yc, yc_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+ assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+ t_span[1], max_step=-1)
+
+ if method is not LSODA:
+ solver = method(fun_rational, t_span[0], y0, t_span[1],
+ rtol=rtol, atol=atol, max_step=1e-20)
+ message = solver.step()
+ message = solver.step() # First step succeeds but second step fails.
+ assert_equal(solver.status, 'failed')
+ assert_("step size is less" in message)
+ assert_raises(RuntimeError, solver.step)
+
+
+def test_first_step(num_parallel_threads):
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [1/3, 2/9]
+ first_step = 0.1
+ for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+ if method is LSODA and num_parallel_threads > 1:
+ continue
+ for t_span in ([5, 9], [5, 1]):
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol,
+ max_step=0.5, atol=atol, method=method,
+ dense_output=True, first_step=first_step)
+
+ assert_equal(res.t[0], t_span[0])
+ assert_equal(res.t[-1], t_span[-1])
+ assert_allclose(first_step, np.abs(res.t[1] - 5))
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ tc = np.linspace(*t_span)
+ yc_true = sol_rational(tc)
+ yc = res.sol(tc)
+
+ e = compute_error(yc, yc_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+ assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+ t_span[1], first_step=-1)
+ assert_raises(ValueError, method, fun_rational, t_span[0], y0,
+ t_span[1], first_step=5)
+
+
+def test_t_eval():
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [1/3, 2/9]
+ for t_span in ([5, 9], [5, 1]):
+ t_eval = np.linspace(t_span[0], t_span[1], 10)
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+ t_eval=t_eval)
+ assert_equal(res.t, t_eval)
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ t_eval = [5, 5.01, 7, 8, 8.01, 9]
+ res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
+ t_eval=t_eval)
+ assert_equal(res.t, t_eval)
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ t_eval = [5, 4.99, 3, 1.5, 1.1, 1.01, 1]
+ res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
+ t_eval=t_eval)
+ assert_equal(res.t, t_eval)
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ t_eval = [5.01, 7, 8, 8.01]
+ res = solve_ivp(fun_rational, [5, 9], y0, rtol=rtol, atol=atol,
+ t_eval=t_eval)
+ assert_equal(res.t, t_eval)
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+ t_eval = [4.99, 3, 1.5, 1.1, 1.01]
+ res = solve_ivp(fun_rational, [5, 1], y0, rtol=rtol, atol=atol,
+ t_eval=t_eval)
+ assert_equal(res.t, t_eval)
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ t_eval = [4, 6]
+ assert_raises(ValueError, solve_ivp, fun_rational, [5, 9], y0,
+ rtol=rtol, atol=atol, t_eval=t_eval)
+
+
+def test_t_eval_dense_output():
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [1/3, 2/9]
+ t_span = [5, 9]
+ t_eval = np.linspace(t_span[0], t_span[1], 10)
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+ t_eval=t_eval)
+ res_d = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+ t_eval=t_eval, dense_output=True)
+ assert_equal(res.t, t_eval)
+ assert_(res.t_events is None)
+ assert_(res.success)
+ assert_equal(res.status, 0)
+
+ assert_equal(res.t, res_d.t)
+ assert_equal(res.y, res_d.y)
+ assert_(res_d.t_events is None)
+ assert_(res_d.success)
+ assert_equal(res_d.status, 0)
+
+ # if t and y are equal only test values for one case
+ y_true = sol_rational(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_(np.all(e < 5))
+
+
+@pytest.mark.thread_unsafe
+def test_t_eval_early_event():
+ def early_event(t, y):
+ return t - 7
+
+ early_event.terminal = True
+
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [1/3, 2/9]
+ t_span = [5, 9]
+ t_eval = np.linspace(7.5, 9, 16)
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+ with suppress_warnings() as sup:
+ sup.filter(UserWarning,
+ "The following arguments have no effect for a chosen "
+ "solver: `jac`")
+ res = solve_ivp(fun_rational, t_span, y0, rtol=rtol, atol=atol,
+ method=method, t_eval=t_eval, events=early_event,
+ jac=jac_rational)
+ assert res.success
+ assert res.message == 'A termination event occurred.'
+ assert res.status == 1
+ assert not res.t and not res.y
+ assert len(res.t_events) == 1
+ assert res.t_events[0].size == 1
+ assert res.t_events[0][0] == 7
+
+
+def test_event_dense_output_LSODA(num_parallel_threads):
+ if num_parallel_threads > 1:
+ pytest.skip('LSODA does not allow for concurrent execution')
+
+ def event_lsoda(t, y):
+ return y[0] - 2.02e-5
+
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = [0.05]
+ t_span = [-2, 2]
+ first_step = 1e-3
+ res = solve_ivp(
+ fun_event_dense_output_LSODA,
+ t_span,
+ y0,
+ method="LSODA",
+ dense_output=True,
+ events=event_lsoda,
+ first_step=first_step,
+ max_step=1,
+ rtol=rtol,
+ atol=atol,
+ jac=jac_event_dense_output_LSODA,
+ )
+
+ assert_equal(res.t[0], t_span[0])
+ assert_equal(res.t[-1], t_span[-1])
+ assert_allclose(first_step, np.abs(res.t[1] - t_span[0]))
+ assert res.success
+ assert_equal(res.status, 0)
+
+ y_true = sol_event_dense_output_LSODA(res.t)
+ e = compute_error(res.y, y_true, rtol, atol)
+ assert_array_less(e, 5)
+
+ tc = np.linspace(*t_span)
+ yc_true = sol_event_dense_output_LSODA(tc)
+ yc = res.sol(tc)
+ e = compute_error(yc, yc_true, rtol, atol)
+ assert_array_less(e, 5)
+
+ assert_allclose(res.sol(res.t), res.y, rtol=1e-15, atol=1e-15)
+
+
+def test_no_integration():
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+ sol = solve_ivp(lambda t, y: -y, [4, 4], [2, 3],
+ method=method, dense_output=True)
+ assert_equal(sol.sol(4), [2, 3])
+ assert_equal(sol.sol([4, 5, 6]), [[2, 2, 2], [3, 3, 3]])
+
+
+def test_no_integration_class():
+ for method in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+ solver = method(lambda t, y: -y, 0.0, [10.0, 0.0], 0.0)
+ solver.step()
+ assert_equal(solver.status, 'finished')
+ sol = solver.dense_output()
+ assert_equal(sol(0.0), [10.0, 0.0])
+ assert_equal(sol([0, 1, 2]), [[10, 10, 10], [0, 0, 0]])
+
+ solver = method(lambda t, y: -y, 0.0, [], np.inf)
+ solver.step()
+ assert_equal(solver.status, 'finished')
+ sol = solver.dense_output()
+ assert_equal(sol(100.0), [])
+ assert_equal(sol([0, 1, 2]), np.empty((0, 3)))
+
+
+def test_empty():
+ def fun(t, y):
+ return np.zeros((0,))
+
+ y0 = np.zeros((0,))
+
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+ sol = assert_no_warnings(solve_ivp, fun, [0, 10], y0,
+ method=method, dense_output=True)
+ assert_equal(sol.sol(10), np.zeros((0,)))
+ assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
+
+ for method in ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA']:
+ sol = assert_no_warnings(solve_ivp, fun, [0, np.inf], y0,
+ method=method, dense_output=True)
+ assert_equal(sol.sol(10), np.zeros((0,)))
+ assert_equal(sol.sol([1, 2, 3]), np.zeros((0, 3)))
+
+
+def test_ConstantDenseOutput():
+ sol = ConstantDenseOutput(0, 1, np.array([1, 2]))
+ assert_allclose(sol(1.5), [1, 2])
+ assert_allclose(sol([1, 1.5, 2]), [[1, 1, 1], [2, 2, 2]])
+
+ sol = ConstantDenseOutput(0, 1, np.array([]))
+ assert_allclose(sol(1.5), np.empty(0))
+ assert_allclose(sol([1, 1.5, 2]), np.empty((0, 3)))
+
+
+def test_classes():
+ y0 = [1 / 3, 2 / 9]
+ for cls in [RK23, RK45, DOP853, Radau, BDF, LSODA]:
+ solver = cls(fun_rational, 5, y0, np.inf)
+ assert_equal(solver.n, 2)
+ assert_equal(solver.status, 'running')
+ assert_equal(solver.t_bound, np.inf)
+ assert_equal(solver.direction, 1)
+ assert_equal(solver.t, 5)
+ assert_equal(solver.y, y0)
+ assert_(solver.step_size is None)
+ if cls is not LSODA:
+ assert_(solver.nfev > 0)
+ assert_(solver.njev >= 0)
+ assert_equal(solver.nlu, 0)
+ else:
+ assert_equal(solver.nfev, 0)
+ assert_equal(solver.njev, 0)
+ assert_equal(solver.nlu, 0)
+
+ assert_raises(RuntimeError, solver.dense_output)
+
+ message = solver.step()
+ assert_equal(solver.status, 'running')
+ assert_equal(message, None)
+ assert_equal(solver.n, 2)
+ assert_equal(solver.t_bound, np.inf)
+ assert_equal(solver.direction, 1)
+ assert_(solver.t > 5)
+ assert_(not np.all(np.equal(solver.y, y0)))
+ assert_(solver.step_size > 0)
+ assert_(solver.nfev > 0)
+ assert_(solver.njev >= 0)
+ assert_(solver.nlu >= 0)
+ sol = solver.dense_output()
+ assert_allclose(sol(5), y0, rtol=1e-15, atol=0)
+
+
+def test_OdeSolution():
+ ts = np.array([0, 2, 5], dtype=float)
+ s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
+ s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
+
+ sol = OdeSolution(ts, [s1, s2])
+
+ assert_equal(sol(-1), [-1])
+ assert_equal(sol(1), [-1])
+ assert_equal(sol(2), [-1])
+ assert_equal(sol(3), [1])
+ assert_equal(sol(5), [1])
+ assert_equal(sol(6), [1])
+
+ assert_equal(sol([0, 6, -2, 1.5, 4.5, 2.5, 5, 5.5, 2]),
+ np.array([[-1, 1, -1, -1, 1, 1, 1, 1, -1]]))
+
+ ts = np.array([10, 4, -3])
+ s1 = ConstantDenseOutput(ts[0], ts[1], np.array([-1]))
+ s2 = ConstantDenseOutput(ts[1], ts[2], np.array([1]))
+
+ sol = OdeSolution(ts, [s1, s2])
+ assert_equal(sol(11), [-1])
+ assert_equal(sol(10), [-1])
+ assert_equal(sol(5), [-1])
+ assert_equal(sol(4), [-1])
+ assert_equal(sol(0), [1])
+ assert_equal(sol(-3), [1])
+ assert_equal(sol(-4), [1])
+
+ assert_equal(sol([12, -5, 10, -3, 6, 1, 4]),
+ np.array([[-1, 1, -1, 1, -1, 1, -1]]))
+
+ ts = np.array([1, 1])
+ s = ConstantDenseOutput(1, 1, np.array([10]))
+ sol = OdeSolution(ts, [s])
+ assert_equal(sol(0), [10])
+ assert_equal(sol(1), [10])
+ assert_equal(sol(2), [10])
+
+ assert_equal(sol([2, 1, 0]), np.array([[10, 10, 10]]))
+
+
+def test_num_jac():
+ def fun(t, y):
+ return np.vstack([
+ -0.04 * y[0] + 1e4 * y[1] * y[2],
+ 0.04 * y[0] - 1e4 * y[1] * y[2] - 3e7 * y[1] ** 2,
+ 3e7 * y[1] ** 2
+ ])
+
+ def jac(t, y):
+ return np.array([
+ [-0.04, 1e4 * y[2], 1e4 * y[1]],
+ [0.04, -1e4 * y[2] - 6e7 * y[1], -1e4 * y[1]],
+ [0, 6e7 * y[1], 0]
+ ])
+
+ t = 1
+ y = np.array([1, 0, 0])
+ J_true = jac(t, y)
+ threshold = 1e-5
+ f = fun(t, y).ravel()
+
+ J_num, factor = num_jac(fun, t, y, f, threshold, None)
+ assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
+
+ J_num, factor = num_jac(fun, t, y, f, threshold, factor)
+ assert_allclose(J_num, J_true, rtol=1e-5, atol=1e-5)
+
+
+def test_num_jac_sparse():
+ def fun(t, y):
+ e = y[1:]**3 - y[:-1]**2
+ z = np.zeros(y.shape[1])
+ return np.vstack((z, 3 * e)) + np.vstack((2 * e, z))
+
+ def structure(n):
+ A = np.zeros((n, n), dtype=int)
+ A[0, 0] = 1
+ A[0, 1] = 1
+ for i in range(1, n - 1):
+ A[i, i - 1: i + 2] = 1
+ A[-1, -1] = 1
+ A[-1, -2] = 1
+
+ return A
+
+ np.random.seed(0)
+ n = 20
+ y = np.random.randn(n)
+ A = structure(n)
+ groups = group_columns(A)
+
+ f = fun(0, y[:, None]).ravel()
+
+ # Compare dense and sparse results, assuming that dense implementation
+ # is correct (as it is straightforward).
+ J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, None,
+ sparsity=(A, groups))
+ J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, None)
+ assert_allclose(J_num_dense, J_num_sparse.toarray(),
+ rtol=1e-12, atol=1e-14)
+ assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
+
+ # Take small factors to trigger their recomputing inside.
+ factor = np.random.uniform(0, 1e-12, size=n)
+ J_num_sparse, factor_sparse = num_jac(fun, 0, y.ravel(), f, 1e-8, factor,
+ sparsity=(A, groups))
+ J_num_dense, factor_dense = num_jac(fun, 0, y.ravel(), f, 1e-8, factor)
+
+ assert_allclose(J_num_dense, J_num_sparse.toarray(),
+ rtol=1e-12, atol=1e-14)
+ assert_allclose(factor_dense, factor_sparse, rtol=1e-12, atol=1e-14)
+
+
+def test_args():
+
+ # sys3 is actually two decoupled systems. (x, y) form a
+ # linear oscillator, while z is a nonlinear first order
+ # system with equilibria at z=0 and z=1. If k > 0, z=1
+ # is stable and z=0 is unstable.
+
+ def sys3(t, w, omega, k, zfinal):
+ x, y, z = w
+ return [-omega*y, omega*x, k*z*(1 - z)]
+
+ def sys3_jac(t, w, omega, k, zfinal):
+ x, y, z = w
+ J = np.array([[0, -omega, 0],
+ [omega, 0, 0],
+ [0, 0, k*(1 - 2*z)]])
+ return J
+
+ def sys3_x0decreasing(t, w, omega, k, zfinal):
+ x, y, z = w
+ return x
+
+ def sys3_y0increasing(t, w, omega, k, zfinal):
+ x, y, z = w
+ return y
+
+ def sys3_zfinal(t, w, omega, k, zfinal):
+ x, y, z = w
+ return z - zfinal
+
+ # Set the event flags for the event functions.
+ sys3_x0decreasing.direction = -1
+ sys3_y0increasing.direction = 1
+ sys3_zfinal.terminal = True
+
+ omega = 2
+ k = 4
+
+ tfinal = 5
+ zfinal = 0.99
+ # Find z0 such that when z(0) = z0, z(tfinal) = zfinal.
+ # The condition z(tfinal) = zfinal is the terminal event.
+ z0 = np.exp(-k*tfinal)/((1 - zfinal)/zfinal + np.exp(-k*tfinal))
+
+ w0 = [0, -1, z0]
+
+ # Provide the jac argument and use the Radau method to ensure that the use
+ # of the Jacobian function is exercised.
+ # If event handling is working, the solution will stop at tfinal, not tend.
+ tend = 2*tfinal
+ sol = solve_ivp(sys3, [0, tend], w0,
+ events=[sys3_x0decreasing, sys3_y0increasing, sys3_zfinal],
+ dense_output=True, args=(omega, k, zfinal),
+ method='Radau', jac=sys3_jac,
+ rtol=1e-10, atol=1e-13)
+
+ # Check that we got the expected events at the expected times.
+ x0events_t = sol.t_events[0]
+ y0events_t = sol.t_events[1]
+ zfinalevents_t = sol.t_events[2]
+ assert_allclose(x0events_t, [0.5*np.pi, 1.5*np.pi])
+ assert_allclose(y0events_t, [0.25*np.pi, 1.25*np.pi])
+ assert_allclose(zfinalevents_t, [tfinal])
+
+ # Check that the solution agrees with the known exact solution.
+ t = np.linspace(0, zfinalevents_t[0], 250)
+ w = sol.sol(t)
+ assert_allclose(w[0], np.sin(omega*t), rtol=1e-9, atol=1e-12)
+ assert_allclose(w[1], -np.cos(omega*t), rtol=1e-9, atol=1e-12)
+ assert_allclose(w[2], 1/(((1 - z0)/z0)*np.exp(-k*t) + 1),
+ rtol=1e-9, atol=1e-12)
+
+ # Check that the state variables have the expected values at the events.
+ x0events = sol.sol(x0events_t)
+ y0events = sol.sol(y0events_t)
+ zfinalevents = sol.sol(zfinalevents_t)
+ assert_allclose(x0events[0], np.zeros_like(x0events[0]), atol=5e-14)
+ assert_allclose(x0events[1], np.ones_like(x0events[1]))
+ assert_allclose(y0events[0], np.ones_like(y0events[0]))
+ assert_allclose(y0events[1], np.zeros_like(y0events[1]), atol=5e-14)
+ assert_allclose(zfinalevents[2], [zfinal])
+
+
+@pytest.mark.thread_unsafe
+def test_array_rtol():
+ # solve_ivp had a bug with array_like `rtol`; see gh-15482
+ # check that it's fixed
+ def f(t, y):
+ return y[0], y[1]
+
+ # no warning (or error) when `rtol` is array_like
+ sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-1])
+ err1 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
+
+ # warning when an element of `rtol` is too small
+ with pytest.warns(UserWarning, match="At least one element..."):
+ sol = solve_ivp(f, (0, 1), [1., 1.], rtol=[1e-1, 1e-16])
+ err2 = np.abs(np.linalg.norm(sol.y[:, -1] - np.exp(1)))
+
+ # tighter rtol improves the error
+ assert err2 < err1
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF', 'LSODA'])
+def test_integration_zero_rhs(method, num_parallel_threads):
+ if method == 'LSODA' and num_parallel_threads > 1:
+ pytest.skip(reason='LSODA does not allow for concurrent execution')
+
+ result = solve_ivp(fun_zero, [0, 10], np.ones(3), method=method)
+ assert_(result.success)
+ assert_equal(result.status, 0)
+ assert_allclose(result.y, 1.0, rtol=1e-15)
+
+
+def test_args_single_value():
+ def fun_with_arg(t, y, a):
+ return a*y
+
+ message = "Supplied 'args' cannot be unpacked."
+ with pytest.raises(TypeError, match=message):
+ solve_ivp(fun_with_arg, (0, 0.1), [1], args=-1)
+
+ sol = solve_ivp(fun_with_arg, (0, 0.1), [1], args=(-1,))
+ assert_allclose(sol.y[0, -1], np.exp(-0.1))
+
+
+@pytest.mark.parametrize("f0_fill", [np.nan, np.inf])
+def test_initial_state_finiteness(f0_fill):
+ # regression test for gh-17846
+ msg = "All components of the initial state `y0` must be finite."
+ with pytest.raises(ValueError, match=msg):
+ solve_ivp(fun_zero, [0, 10], np.full(3, f0_fill))
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_zero_interval(method):
+ # Case where upper and lower limits of integration are the same
+ # Result of integration should match initial state.
+ # f[y(t)] = 2y(t)
+ def f(t, y):
+ return 2 * y
+ res = solve_ivp(f, (0.0, 0.0), np.array([1.0]), method=method)
+ assert res.success
+ assert_allclose(res.y[0, -1], 1.0)
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_small_interval(method):
+ """Regression test for gh-17341"""
+ SMALL = 1e-4
+
+ # f[y(t)] = 2y(t) on t in [0,SMALL]
+ # undefined otherwise
+ def f(t, y):
+ if t > SMALL:
+ raise ValueError("Function was evaluated outside interval")
+ return 2 * y
+ res = solve_ivp(f, (0.0, SMALL), np.array([1]), method=method)
+ assert res.success
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_larger_interval(method):
+ """Regression test for gh-8848"""
+ def V(r):
+ return -11/r + 10 * r / (0.05 + r**2)
+
+ def func(t, p):
+ if t < -17 or t > 2:
+ raise ValueError("Function was evaluated outside interval")
+ P = p[0]
+ Q = p[1]
+ r = np.exp(t)
+ dPdr = r * Q
+ dQdr = -2.0 * r * ((-0.2 - V(r)) * P + 1 / r * Q)
+ return np.array([dPdr, dQdr])
+
+ result = solve_ivp(func,
+ (-17, 2),
+ y0=np.array([1, -11]),
+ max_step=0.03,
+ vectorized=False,
+ t_eval=None,
+ atol=1e-8,
+ rtol=1e-5)
+ assert result.success
+
+
+@pytest.mark.parametrize('method', ['RK23', 'RK45', 'DOP853', 'Radau', 'BDF'])
+def test_tbound_respected_oscillator(method):
+ "Regression test for gh-9198"
+ def reactions_func(t, y):
+ if (t > 205):
+ raise ValueError("Called outside interval")
+ yprime = np.array([1.73307544e-02,
+ 6.49376470e-06,
+ 0.00000000e+00,
+ 0.00000000e+00])
+ return yprime
+
+ def run_sim2(t_end, n_timepoints=10, shortest_delay_line=10000000):
+ init_state = np.array([134.08298555, 138.82348612, 100., 0.])
+ t0 = 100.0
+ t1 = 200.0
+ return solve_ivp(reactions_func,
+ (t0, t1),
+ init_state.copy(),
+ dense_output=True,
+ max_step=t1 - t0)
+ result = run_sim2(1000, 100, 100)
+ assert result.success
+
+
+def test_inital_maxstep():
+ """Verify that select_inital_step respects max_step"""
+ rtol = 1e-3
+ atol = 1e-6
+ y0 = np.array([1/3, 2/9])
+ for (t0, t_bound) in ((5, 9), (5, 1)):
+ for method_order in [RK23.error_estimator_order,
+ RK45.error_estimator_order,
+ DOP853.error_estimator_order,
+ 3, #RADAU
+ 1 #BDF
+ ]:
+ step_no_max = select_initial_step(fun_rational, t0, y0, t_bound,
+ np.inf,
+ fun_rational(t0,y0),
+ np.sign(t_bound - t0),
+ method_order,
+ rtol, atol)
+ max_step = step_no_max/2
+ step_with_max = select_initial_step(fun_rational, t0, y0, t_bound,
+ max_step,
+ fun_rational(t0, y0),
+ np.sign(t_bound - t0),
+ method_order,
+ rtol, atol)
+ assert_equal(max_step, step_with_max)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/test_rk.py b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/test_rk.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dd196c43b866e7bcbb05a447f67cc7e190fcfbe
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_ivp/tests/test_rk.py
@@ -0,0 +1,37 @@
+import pytest
+from numpy.testing import assert_allclose, assert_
+import numpy as np
+from scipy.integrate import RK23, RK45, DOP853
+from scipy.integrate._ivp import dop853_coefficients
+
+
+@pytest.mark.parametrize("solver", [RK23, RK45, DOP853])
+def test_coefficient_properties(solver):
+ assert_allclose(np.sum(solver.B), 1, rtol=1e-15)
+ assert_allclose(np.sum(solver.A, axis=1), solver.C, rtol=1e-14)
+
+
+def test_coefficient_properties_dop853():
+ assert_allclose(np.sum(dop853_coefficients.B), 1, rtol=1e-15)
+ assert_allclose(np.sum(dop853_coefficients.A, axis=1),
+ dop853_coefficients.C,
+ rtol=1e-14)
+
+
+@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
+def test_error_estimation(solver_class):
+ step = 0.2
+ solver = solver_class(lambda t, y: y, 0, [1], 1, first_step=step)
+ solver.step()
+ error_estimate = solver._estimate_error(solver.K, step)
+ error = solver.y - np.exp([step])
+ assert_(np.abs(error) < np.abs(error_estimate))
+
+
+@pytest.mark.parametrize("solver_class", [RK23, RK45, DOP853])
+def test_error_estimation_complex(solver_class):
+ h = 0.2
+ solver = solver_class(lambda t, y: 1j * y, 0, [1j], 1, first_step=h)
+ solver.step()
+ err_norm = solver._estimate_error_norm(solver.K, h, scale=[1])
+ assert np.isrealobj(err_norm)
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_rules/__init__.py b/python_embeded/Lib/site-packages/scipy/integrate/_rules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..37521c54486f26fbb76538b74658b5a9f73e54a6
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_rules/__init__.py
@@ -0,0 +1,12 @@
+"""Numerical cubature algorithms"""
+
+from ._base import (
+ Rule, FixedRule,
+ NestedFixedRule,
+ ProductNestedFixed,
+)
+from ._genz_malik import GenzMalikCubature
+from ._gauss_kronrod import GaussKronrodQuadrature
+from ._gauss_legendre import GaussLegendreQuadrature
+
+__all__ = [s for s in dir() if not s.startswith('_')]
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_rules/_base.py b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..f115f0919cba777a4b1904ba38725dfedb6ad7eb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_base.py
@@ -0,0 +1,518 @@
+from scipy._lib._array_api import array_namespace, xp_size
+
+from functools import cached_property
+
+
+class Rule:
+ """
+ Base class for numerical integration algorithms (cubatures).
+
+ Finds an estimate for the integral of ``f`` over the region described by two arrays
+ ``a`` and ``b`` via `estimate`, and find an estimate for the error of this
+ approximation via `estimate_error`.
+
+ If a subclass does not implement its own `estimate_error`, then it will use a
+ default error estimate based on the difference between the estimate over the whole
+ region and the sum of estimates over that region divided into ``2^ndim`` subregions.
+
+ See Also
+ --------
+ FixedRule
+
+ Examples
+ --------
+ In the following, a custom rule is created which uses 3D Genz-Malik cubature for
+ the estimate of the integral, and the difference between this estimate and a less
+ accurate estimate using 5-node Gauss-Legendre quadrature as an estimate for the
+ error.
+
+ >>> import numpy as np
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import (
+ ... Rule, ProductNestedFixed, GenzMalikCubature, GaussLegendreQuadrature
+ ... )
+ >>> def f(x, r, alphas):
+ ... # f(x) = cos(2*pi*r + alpha @ x)
+ ... # Need to allow r and alphas to be arbitrary shape
+ ... npoints, ndim = x.shape[0], x.shape[-1]
+ ... alphas_reshaped = alphas[np.newaxis, :]
+ ... x_reshaped = x.reshape(npoints, *([1]*(len(alphas.shape) - 1)), ndim)
+ ... return np.cos(2*np.pi*r + np.sum(alphas_reshaped * x_reshaped, axis=-1))
+ >>> genz = GenzMalikCubature(ndim=3)
+ >>> gauss = GaussKronrodQuadrature(npoints=21)
+ >>> # Gauss-Kronrod is 1D, so we find the 3D product rule:
+ >>> gauss_3d = ProductNestedFixed([gauss, gauss, gauss])
+ >>> class CustomRule(Rule):
+ ... def estimate(self, f, a, b, args=()):
+ ... return genz.estimate(f, a, b, args)
+ ... def estimate_error(self, f, a, b, args=()):
+ ... return np.abs(
+ ... genz.estimate(f, a, b, args)
+ ... - gauss_3d.estimate(f, a, b, args)
+ ... )
+ >>> rng = np.random.default_rng()
+ >>> res = cubature(
+ ... f=f,
+ ... a=np.array([0, 0, 0]),
+ ... b=np.array([1, 1, 1]),
+ ... rule=CustomRule(),
+ ... args=(rng.random((2,)), rng.random((3, 2, 3)))
+ ... )
+ >>> res.estimate
+ array([[-0.95179502, 0.12444608],
+ [-0.96247411, 0.60866385],
+ [-0.97360014, 0.25515587]])
+ """
+
+ def estimate(self, f, a, b, args=()):
+ r"""
+ Calculate estimate of integral of `f` in rectangular region described by
+ corners `a` and ``b``.
+
+ Parameters
+ ----------
+ f : callable
+ Function to integrate. `f` must have the signature::
+ f(x : ndarray, \*args) -> ndarray
+
+ `f` should accept arrays ``x`` of shape::
+ (npoints, ndim)
+
+ and output arrays of shape::
+ (npoints, output_dim_1, ..., output_dim_n)
+
+ In this case, `estimate` will return arrays of shape::
+ (output_dim_1, ..., output_dim_n)
+ a, b : ndarray
+ Lower and upper limits of integration as rank-1 arrays specifying the left
+ and right endpoints of the intervals being integrated over. Infinite limits
+ are currently not supported.
+ args : tuple, optional
+ Additional positional args passed to ``f``, if any.
+
+ Returns
+ -------
+ est : ndarray
+ Result of estimation. If `f` returns arrays of shape ``(npoints,
+ output_dim_1, ..., output_dim_n)``, then `est` will be of shape
+ ``(output_dim_1, ..., output_dim_n)``.
+ """
+ raise NotImplementedError
+
+ def estimate_error(self, f, a, b, args=()):
+ r"""
+ Estimate the error of the approximation for the integral of `f` in rectangular
+ region described by corners `a` and `b`.
+
+ If a subclass does not override this method, then a default error estimator is
+ used. This estimates the error as ``|est - refined_est|`` where ``est`` is
+ ``estimate(f, a, b)`` and ``refined_est`` is the sum of
+ ``estimate(f, a_k, b_k)`` where ``a_k, b_k`` are the coordinates of each
+ subregion of the region described by ``a`` and ``b``. In the 1D case, this
+ is equivalent to comparing the integral over an entire interval ``[a, b]`` to
+ the sum of the integrals over the left and right subintervals, ``[a, (a+b)/2]``
+ and ``[(a+b)/2, b]``.
+
+ Parameters
+ ----------
+ f : callable
+ Function to estimate error for. `f` must have the signature::
+ f(x : ndarray, \*args) -> ndarray
+
+ `f` should accept arrays `x` of shape::
+ (npoints, ndim)
+
+ and output arrays of shape::
+ (npoints, output_dim_1, ..., output_dim_n)
+
+ In this case, `estimate` will return arrays of shape::
+ (output_dim_1, ..., output_dim_n)
+ a, b : ndarray
+ Lower and upper limits of integration as rank-1 arrays specifying the left
+ and right endpoints of the intervals being integrated over. Infinite limits
+ are currently not supported.
+ args : tuple, optional
+ Additional positional args passed to `f`, if any.
+
+ Returns
+ -------
+ err_est : ndarray
+ Result of error estimation. If `f` returns arrays of shape
+ ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
+ of shape ``(output_dim_1, ..., output_dim_n)``.
+ """
+
+ est = self.estimate(f, a, b, args)
+ refined_est = 0
+
+ for a_k, b_k in _split_subregion(a, b):
+ refined_est += self.estimate(f, a_k, b_k, args)
+
+ return self.xp.abs(est - refined_est)
+
+
+class FixedRule(Rule):
+ """
+ A rule implemented as the weighted sum of function evaluations at fixed nodes.
+
+ Attributes
+ ----------
+ nodes_and_weights : (ndarray, ndarray)
+ A tuple ``(nodes, weights)`` of nodes at which to evaluate ``f`` and the
+ corresponding weights. ``nodes`` should be of shape ``(num_nodes,)`` for 1D
+ cubature rules (quadratures) and more generally for N-D cubature rules, it
+ should be of shape ``(num_nodes, ndim)``. ``weights`` should be of shape
+ ``(num_nodes,)``. The nodes and weights should be for integrals over
+ :math:`[-1, 1]^n`.
+
+ See Also
+ --------
+ GaussLegendreQuadrature, GaussKronrodQuadrature, GenzMalikCubature
+
+ Examples
+ --------
+
+ Implementing Simpson's 1/3 rule:
+
+ >>> import numpy as np
+ >>> from scipy.integrate._rules import FixedRule
+ >>> class SimpsonsQuad(FixedRule):
+ ... @property
+ ... def nodes_and_weights(self):
+ ... nodes = np.array([-1, 0, 1])
+ ... weights = np.array([1/3, 4/3, 1/3])
+ ... return (nodes, weights)
+ >>> rule = SimpsonsQuad()
+ >>> rule.estimate(
+ ... f=lambda x: x**2,
+ ... a=np.array([0]),
+ ... b=np.array([1]),
+ ... )
+ [0.3333333]
+ """
+
+ def __init__(self):
+ self.xp = None
+
+ @property
+ def nodes_and_weights(self):
+ raise NotImplementedError
+
+ def estimate(self, f, a, b, args=()):
+ r"""
+ Calculate estimate of integral of `f` in rectangular region described by
+ corners `a` and `b` as ``sum(weights * f(nodes))``.
+
+ Nodes and weights will automatically be adjusted from calculating integrals over
+ :math:`[-1, 1]^n` to :math:`[a, b]^n`.
+
+ Parameters
+ ----------
+ f : callable
+ Function to integrate. `f` must have the signature::
+ f(x : ndarray, \*args) -> ndarray
+
+ `f` should accept arrays `x` of shape::
+ (npoints, ndim)
+
+ and output arrays of shape::
+ (npoints, output_dim_1, ..., output_dim_n)
+
+ In this case, `estimate` will return arrays of shape::
+ (output_dim_1, ..., output_dim_n)
+ a, b : ndarray
+ Lower and upper limits of integration as rank-1 arrays specifying the left
+ and right endpoints of the intervals being integrated over. Infinite limits
+ are currently not supported.
+ args : tuple, optional
+ Additional positional args passed to `f`, if any.
+
+ Returns
+ -------
+ est : ndarray
+ Result of estimation. If `f` returns arrays of shape ``(npoints,
+ output_dim_1, ..., output_dim_n)``, then `est` will be of shape
+ ``(output_dim_1, ..., output_dim_n)``.
+ """
+ nodes, weights = self.nodes_and_weights
+
+ if self.xp is None:
+ self.xp = array_namespace(nodes)
+
+ return _apply_fixed_rule(f, a, b, nodes, weights, args, self.xp)
+
+
+class NestedFixedRule(FixedRule):
+ r"""
+ A cubature rule with error estimate given by the difference between two underlying
+ fixed rules.
+
+ If constructed as ``NestedFixedRule(higher, lower)``, this will use::
+
+ estimate(f, a, b) := higher.estimate(f, a, b)
+ estimate_error(f, a, b) := \|higher.estimate(f, a, b) - lower.estimate(f, a, b)|
+
+ (where the absolute value is taken elementwise).
+
+ Attributes
+ ----------
+ higher : Rule
+ Higher accuracy rule.
+
+ lower : Rule
+ Lower accuracy rule.
+
+ See Also
+ --------
+ GaussKronrodQuadrature
+
+ Examples
+ --------
+
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import (
+ ... GaussLegendreQuadrature, NestedFixedRule, ProductNestedFixed
+ ... )
+ >>> higher = GaussLegendreQuadrature(10)
+ >>> lower = GaussLegendreQuadrature(5)
+ >>> rule = NestedFixedRule(
+ ... higher,
+ ... lower
+ ... )
+ >>> rule_2d = ProductNestedFixed([rule, rule])
+ """
+
+ def __init__(self, higher, lower):
+ self.higher = higher
+ self.lower = lower
+ self.xp = None
+
+ @property
+ def nodes_and_weights(self):
+ if self.higher is not None:
+ return self.higher.nodes_and_weights
+ else:
+ raise NotImplementedError
+
+ @property
+ def lower_nodes_and_weights(self):
+ if self.lower is not None:
+ return self.lower.nodes_and_weights
+ else:
+ raise NotImplementedError
+
+ def estimate_error(self, f, a, b, args=()):
+ r"""
+ Estimate the error of the approximation for the integral of `f` in rectangular
+ region described by corners `a` and `b`.
+
+ Parameters
+ ----------
+ f : callable
+ Function to estimate error for. `f` must have the signature::
+ f(x : ndarray, \*args) -> ndarray
+
+ `f` should accept arrays `x` of shape::
+ (npoints, ndim)
+
+ and output arrays of shape::
+ (npoints, output_dim_1, ..., output_dim_n)
+
+ In this case, `estimate` will return arrays of shape::
+ (output_dim_1, ..., output_dim_n)
+ a, b : ndarray
+ Lower and upper limits of integration as rank-1 arrays specifying the left
+ and right endpoints of the intervals being integrated over. Infinite limits
+ are currently not supported.
+ args : tuple, optional
+ Additional positional args passed to `f`, if any.
+
+ Returns
+ -------
+ err_est : ndarray
+ Result of error estimation. If `f` returns arrays of shape
+ ``(npoints, output_dim_1, ..., output_dim_n)``, then `est` will be
+ of shape ``(output_dim_1, ..., output_dim_n)``.
+ """
+
+ nodes, weights = self.nodes_and_weights
+ lower_nodes, lower_weights = self.lower_nodes_and_weights
+
+ if self.xp is None:
+ self.xp = array_namespace(nodes)
+
+ error_nodes = self.xp.concat([nodes, lower_nodes], axis=0)
+ error_weights = self.xp.concat([weights, -lower_weights], axis=0)
+
+ return self.xp.abs(
+ _apply_fixed_rule(f, a, b, error_nodes, error_weights, args, self.xp)
+ )
+
+
+class ProductNestedFixed(NestedFixedRule):
+ """
+ Find the n-dimensional cubature rule constructed from the Cartesian product of 1-D
+ `NestedFixedRule` quadrature rules.
+
+ Given a list of N 1-dimensional quadrature rules which support error estimation
+ using NestedFixedRule, this will find the N-dimensional cubature rule obtained by
+ taking the Cartesian product of their nodes, and estimating the error by taking the
+ difference with a lower-accuracy N-dimensional cubature rule obtained using the
+ ``.lower_nodes_and_weights`` rule in each of the base 1-dimensional rules.
+
+ Parameters
+ ----------
+ base_rules : list of NestedFixedRule
+ List of base 1-dimensional `NestedFixedRule` quadrature rules.
+
+ Attributes
+ ----------
+ base_rules : list of NestedFixedRule
+ List of base 1-dimensional `NestedFixedRule` qudarature rules.
+
+ Examples
+ --------
+
+ Evaluate a 2D integral by taking the product of two 1D rules:
+
+ >>> import numpy as np
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import (
+ ... ProductNestedFixed, GaussKronrodQuadrature
+ ... )
+ >>> def f(x):
+ ... # f(x) = cos(x_1) + cos(x_2)
+ ... return np.sum(np.cos(x), axis=-1)
+ >>> rule = ProductNestedFixed(
+ ... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
+ ... ) # Use 15-point Gauss-Kronrod, which implements NestedFixedRule
+ >>> a, b = np.array([0, 0]), np.array([1, 1])
+ >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
+ np.float64(1.682941969615793)
+ >>> rule.estimate_error(f, a, b)
+ np.float64(2.220446049250313e-16)
+ """
+
+ def __init__(self, base_rules):
+ for rule in base_rules:
+ if not isinstance(rule, NestedFixedRule):
+ raise ValueError("base rules for product need to be instance of"
+ "NestedFixedRule")
+
+ self.base_rules = base_rules
+ self.xp = None
+
+ @cached_property
+ def nodes_and_weights(self):
+ nodes = _cartesian_product(
+ [rule.nodes_and_weights[0] for rule in self.base_rules]
+ )
+
+ if self.xp is None:
+ self.xp = array_namespace(nodes)
+
+ weights = self.xp.prod(
+ _cartesian_product(
+ [rule.nodes_and_weights[1] for rule in self.base_rules]
+ ),
+ axis=-1,
+ )
+
+ return nodes, weights
+
+ @cached_property
+ def lower_nodes_and_weights(self):
+ nodes = _cartesian_product(
+ [cubature.lower_nodes_and_weights[0] for cubature in self.base_rules]
+ )
+
+ if self.xp is None:
+ self.xp = array_namespace(nodes)
+
+ weights = self.xp.prod(
+ _cartesian_product(
+ [cubature.lower_nodes_and_weights[1] for cubature in self.base_rules]
+ ),
+ axis=-1,
+ )
+
+ return nodes, weights
+
+
+def _cartesian_product(arrays):
+ xp = array_namespace(*arrays)
+
+ arrays_ix = xp.meshgrid(*arrays, indexing='ij')
+ result = xp.reshape(xp.stack(arrays_ix, axis=-1), (-1, len(arrays)))
+
+ return result
+
+
+def _split_subregion(a, b, xp, split_at=None):
+ """
+ Given the coordinates of a region like a=[0, 0] and b=[1, 1], yield the coordinates
+ of all subregions, which in this case would be::
+
+ ([0, 0], [1/2, 1/2]),
+ ([0, 1/2], [1/2, 1]),
+ ([1/2, 0], [1, 1/2]),
+ ([1/2, 1/2], [1, 1])
+ """
+ xp = array_namespace(a, b)
+
+ if split_at is None:
+ split_at = (a + b) / 2
+
+ left = [xp.asarray([a[i], split_at[i]]) for i in range(a.shape[0])]
+ right = [xp.asarray([split_at[i], b[i]]) for i in range(b.shape[0])]
+
+ a_sub = _cartesian_product(left)
+ b_sub = _cartesian_product(right)
+
+ for i in range(a_sub.shape[0]):
+ yield a_sub[i, ...], b_sub[i, ...]
+
+
+def _apply_fixed_rule(f, a, b, orig_nodes, orig_weights, args, xp):
+ # Downcast nodes and weights to common dtype of a and b
+ result_dtype = a.dtype
+ orig_nodes = xp.astype(orig_nodes, result_dtype)
+ orig_weights = xp.astype(orig_weights, result_dtype)
+
+ # Ensure orig_nodes are at least 2D, since 1D cubature methods can return arrays of
+ # shape (npoints,) rather than (npoints, 1)
+ if orig_nodes.ndim == 1:
+ orig_nodes = orig_nodes[:, None]
+
+ rule_ndim = orig_nodes.shape[-1]
+
+ a_ndim = xp_size(a)
+ b_ndim = xp_size(b)
+
+ if rule_ndim != a_ndim or rule_ndim != b_ndim:
+ raise ValueError(f"rule and function are of incompatible dimension, nodes have"
+ f"ndim {rule_ndim}, while limit of integration has ndim"
+ f"a_ndim={a_ndim}, b_ndim={b_ndim}")
+
+ lengths = b - a
+
+ # The underlying rule is for the hypercube [-1, 1]^n.
+ #
+ # To handle arbitrary regions of integration, it's necessary to apply a linear
+ # change of coordinates to map each interval [a[i], b[i]] to [-1, 1].
+ nodes = (orig_nodes + 1) * (lengths * 0.5) + a
+
+ # Also need to multiply the weights by a scale factor equal to the determinant
+ # of the Jacobian for this coordinate change.
+ weight_scale_factor = xp.prod(lengths, dtype=result_dtype) / 2**rule_ndim
+ weights = orig_weights * weight_scale_factor
+
+ f_nodes = f(nodes, *args)
+ weights_reshaped = xp.reshape(weights, (-1, *([1] * (f_nodes.ndim - 1))))
+
+ # f(nodes) will have shape (num_nodes, output_dim_1, ..., output_dim_n)
+ # Summing along the first axis means estimate will shape (output_dim_1, ...,
+ # output_dim_n)
+ est = xp.sum(weights_reshaped * f_nodes, axis=0, dtype=result_dtype)
+
+ return est
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_rules/_gauss_kronrod.py b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
new file mode 100644
index 0000000000000000000000000000000000000000..68c319e0b145f78c8d08aec7025da16830a81a64
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_gauss_kronrod.py
@@ -0,0 +1,202 @@
+from scipy._lib._array_api import np_compat, array_namespace
+
+from functools import cached_property
+
+from ._base import NestedFixedRule
+from ._gauss_legendre import GaussLegendreQuadrature
+
+
+class GaussKronrodQuadrature(NestedFixedRule):
+ """
+ Gauss-Kronrod quadrature.
+
+ Gauss-Kronrod rules consist of two quadrature rules, one higher-order and one
+ lower-order. The higher-order rule is used as the estimate of the integral and the
+ difference between them is used as an estimate for the error.
+
+ Gauss-Kronrod is a 1D rule. To use it for multidimensional integrals, it will be
+ necessary to use ProductNestedFixed and multiple Gauss-Kronrod rules. See Examples.
+
+ For n-node Gauss-Kronrod, the lower-order rule has ``n//2`` nodes, which are the
+ ordinary Gauss-Legendre nodes with corresponding weights. The higher-order rule has
+ ``n`` nodes, ``n//2`` of which are the same as the lower-order rule and the
+ remaining nodes are the Kronrod extension of those nodes.
+
+ Parameters
+ ----------
+ npoints : int
+ Number of nodes for the higher-order rule.
+
+ xp : array_namespace, optional
+ The namespace for the node and weight arrays. Default is None, where NumPy is
+ used.
+
+ Attributes
+ ----------
+ lower : Rule
+ Lower-order rule.
+
+ References
+ ----------
+ .. [1] R. Piessens, E. de Doncker, Quadpack: A Subroutine Package for Automatic
+ Integration, files: dqk21.f, dqk15.f (1983).
+
+ Examples
+ --------
+ Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
+ estimates will also be arrays, despite the fact that this is a 1D problem.
+
+ >>> import numpy as np
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import GaussKronrodQuadrature
+ >>> def f(x):
+ ... return np.cos(x)
+ >>> rule = GaussKronrodQuadrature(21) # Use 21-point GaussKronrod
+ >>> a, b = np.array([0]), np.array([1])
+ >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
+ array([0.84147098])
+ >>> rule.estimate_error(f, a, b)
+ array([1.11022302e-16])
+
+ Evaluate a 2D integral. Note that in this example ``f`` returns a float, so the
+ estimates will also be floats.
+
+ >>> import numpy as np
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import (
+ ... ProductNestedFixed, GaussKronrodQuadrature
+ ... )
+ >>> def f(x):
+ ... # f(x) = cos(x_1) + cos(x_2)
+ ... return np.sum(np.cos(x), axis=-1)
+ >>> rule = ProductNestedFixed(
+ ... [GaussKronrodQuadrature(15), GaussKronrodQuadrature(15)]
+ ... ) # Use 15-point Gauss-Kronrod
+ >>> a, b = np.array([0, 0]), np.array([1, 1])
+ >>> rule.estimate(f, a, b) # True value 2*sin(1), approximately 1.6829
+ np.float64(1.682941969615793)
+ >>> rule.estimate_error(f, a, b)
+ np.float64(2.220446049250313e-16)
+ """
+
+ def __init__(self, npoints, xp=None):
+ # TODO: nodes and weights are currently hard-coded for values 15 and 21, but in
+ # the future it would be best to compute the Kronrod extension of the lower rule
+ if npoints != 15 and npoints != 21:
+ raise NotImplementedError("Gauss-Kronrod quadrature is currently only"
+ "supported for 15 or 21 nodes")
+
+ self.npoints = npoints
+
+ if xp is None:
+ xp = np_compat
+
+ self.xp = array_namespace(xp.empty(0))
+
+ self.gauss = GaussLegendreQuadrature(npoints//2, xp=self.xp)
+
+ @cached_property
+ def nodes_and_weights(self):
+ # These values are from QUADPACK's `dqk21.f` and `dqk15.f` (1983).
+ if self.npoints == 21:
+ nodes = self.xp.asarray(
+ [
+ 0.995657163025808080735527280689003,
+ 0.973906528517171720077964012084452,
+ 0.930157491355708226001207180059508,
+ 0.865063366688984510732096688423493,
+ 0.780817726586416897063717578345042,
+ 0.679409568299024406234327365114874,
+ 0.562757134668604683339000099272694,
+ 0.433395394129247190799265943165784,
+ 0.294392862701460198131126603103866,
+ 0.148874338981631210884826001129720,
+ 0,
+ -0.148874338981631210884826001129720,
+ -0.294392862701460198131126603103866,
+ -0.433395394129247190799265943165784,
+ -0.562757134668604683339000099272694,
+ -0.679409568299024406234327365114874,
+ -0.780817726586416897063717578345042,
+ -0.865063366688984510732096688423493,
+ -0.930157491355708226001207180059508,
+ -0.973906528517171720077964012084452,
+ -0.995657163025808080735527280689003,
+ ],
+ dtype=self.xp.float64,
+ )
+
+ weights = self.xp.asarray(
+ [
+ 0.011694638867371874278064396062192,
+ 0.032558162307964727478818972459390,
+ 0.054755896574351996031381300244580,
+ 0.075039674810919952767043140916190,
+ 0.093125454583697605535065465083366,
+ 0.109387158802297641899210590325805,
+ 0.123491976262065851077958109831074,
+ 0.134709217311473325928054001771707,
+ 0.142775938577060080797094273138717,
+ 0.147739104901338491374841515972068,
+ 0.149445554002916905664936468389821,
+ 0.147739104901338491374841515972068,
+ 0.142775938577060080797094273138717,
+ 0.134709217311473325928054001771707,
+ 0.123491976262065851077958109831074,
+ 0.109387158802297641899210590325805,
+ 0.093125454583697605535065465083366,
+ 0.075039674810919952767043140916190,
+ 0.054755896574351996031381300244580,
+ 0.032558162307964727478818972459390,
+ 0.011694638867371874278064396062192,
+ ],
+ dtype=self.xp.float64,
+ )
+ elif self.npoints == 15:
+ nodes = self.xp.asarray(
+ [
+ 0.991455371120812639206854697526329,
+ 0.949107912342758524526189684047851,
+ 0.864864423359769072789712788640926,
+ 0.741531185599394439863864773280788,
+ 0.586087235467691130294144838258730,
+ 0.405845151377397166906606412076961,
+ 0.207784955007898467600689403773245,
+ 0.000000000000000000000000000000000,
+ -0.207784955007898467600689403773245,
+ -0.405845151377397166906606412076961,
+ -0.586087235467691130294144838258730,
+ -0.741531185599394439863864773280788,
+ -0.864864423359769072789712788640926,
+ -0.949107912342758524526189684047851,
+ -0.991455371120812639206854697526329,
+ ],
+ dtype=self.xp.float64,
+ )
+
+ weights = self.xp.asarray(
+ [
+ 0.022935322010529224963732008058970,
+ 0.063092092629978553290700663189204,
+ 0.104790010322250183839876322541518,
+ 0.140653259715525918745189590510238,
+ 0.169004726639267902826583426598550,
+ 0.190350578064785409913256402421014,
+ 0.204432940075298892414161999234649,
+ 0.209482141084727828012999174891714,
+ 0.204432940075298892414161999234649,
+ 0.190350578064785409913256402421014,
+ 0.169004726639267902826583426598550,
+ 0.140653259715525918745189590510238,
+ 0.104790010322250183839876322541518,
+ 0.063092092629978553290700663189204,
+ 0.022935322010529224963732008058970,
+ ],
+ dtype=self.xp.float64,
+ )
+
+ return nodes, weights
+
+ @property
+ def lower_nodes_and_weights(self):
+ return self.gauss.nodes_and_weights
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_rules/_gauss_legendre.py b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_gauss_legendre.py
new file mode 100644
index 0000000000000000000000000000000000000000..422cd0e165995f44af0c3a38c927dbd952a1a8a0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_gauss_legendre.py
@@ -0,0 +1,62 @@
+from scipy._lib._array_api import array_namespace, np_compat
+
+from functools import cached_property
+
+from scipy.special import roots_legendre
+
+from ._base import FixedRule
+
+
+class GaussLegendreQuadrature(FixedRule):
+ """
+ Gauss-Legendre quadrature.
+
+ Parameters
+ ----------
+ npoints : int
+ Number of nodes for the higher-order rule.
+
+ xp : array_namespace, optional
+ The namespace for the node and weight arrays. Default is None, where NumPy is
+ used.
+
+ Examples
+ --------
+ Evaluate a 1D integral. Note in this example that ``f`` returns an array, so the
+ estimates will also be arrays.
+
+ >>> import numpy as np
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import GaussLegendreQuadrature
+ >>> def f(x):
+ ... return np.cos(x)
+ >>> rule = GaussLegendreQuadrature(21) # Use 21-point GaussLegendre
+ >>> a, b = np.array([0]), np.array([1])
+ >>> rule.estimate(f, a, b) # True value sin(1), approximately 0.84147
+ array([0.84147098])
+ >>> rule.estimate_error(f, a, b)
+ array([1.11022302e-16])
+ """
+
+ def __init__(self, npoints, xp=None):
+ if npoints < 2:
+ raise ValueError(
+ "At least 2 nodes required for Gauss-Legendre cubature"
+ )
+
+ self.npoints = npoints
+
+ if xp is None:
+ xp = np_compat
+
+ self.xp = array_namespace(xp.empty(0))
+
+ @cached_property
+ def nodes_and_weights(self):
+ # TODO: current converting to/from numpy
+ nodes, weights = roots_legendre(self.npoints)
+
+ return (
+ self.xp.asarray(nodes, dtype=self.xp.float64),
+ self.xp.asarray(weights, dtype=self.xp.float64)
+ )
diff --git a/python_embeded/Lib/site-packages/scipy/integrate/_rules/_genz_malik.py b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_genz_malik.py
new file mode 100644
index 0000000000000000000000000000000000000000..581de9b97642de7895f0cb8e8b8c04f5f6d383c7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/scipy/integrate/_rules/_genz_malik.py
@@ -0,0 +1,210 @@
+import math
+import itertools
+
+from functools import cached_property
+
+from scipy._lib._array_api import array_namespace, np_compat
+
+from scipy.integrate._rules import NestedFixedRule
+
+
+class GenzMalikCubature(NestedFixedRule):
+ """
+ Genz-Malik cubature.
+
+ Genz-Malik is only defined for integrals of dimension >= 2.
+
+ Parameters
+ ----------
+ ndim : int
+ The spatial dimension of the integrand.
+
+ xp : array_namespace, optional
+ The namespace for the node and weight arrays. Default is None, where NumPy is
+ used.
+
+ Attributes
+ ----------
+ higher : Cubature
+ Higher-order rule.
+
+ lower : Cubature
+ Lower-order rule.
+
+ References
+ ----------
+ .. [1] A.C. Genz, A.A. Malik, Remarks on algorithm 006: An adaptive algorithm for
+ numerical integration over an N-dimensional rectangular region, Journal of
+ Computational and Applied Mathematics, Volume 6, Issue 4, 1980, Pages 295-302,
+ ISSN 0377-0427, https://doi.org/10.1016/0771-050X(80)90039-X.
+
+ Examples
+ --------
+ Evaluate a 3D integral:
+
+ >>> import numpy as np
+ >>> from scipy.integrate import cubature
+ >>> from scipy.integrate._rules import GenzMalikCubature
+ >>> def f(x):
+ ... # f(x) = cos(x_1) + cos(x_2) + cos(x_3)
+ ... return np.sum(np.cos(x), axis=-1)
+ >>> rule = GenzMalikCubature(3) # Use 3D Genz-Malik
+ >>> a, b = np.array([0, 0, 0]), np.array([1, 1, 1])
+ >>> rule.estimate(f, a, b) # True value 3*sin(1), approximately 2.5244
+ np.float64(2.5244129547230862)
+ >>> rule.estimate_error(f, a, b)
+ np.float64(1.378269656626685e-06)
+ """
+
+ def __init__(self, ndim, degree=7, lower_degree=5, xp=None):
+ if ndim < 2:
+ raise ValueError("Genz-Malik cubature is only defined for ndim >= 2")
+
+ if degree != 7 or lower_degree != 5:
+ raise NotImplementedError("Genz-Malik cubature is currently only supported"
+ "for degree=7, lower_degree=5")
+
+ self.ndim = ndim
+ self.degree = degree
+ self.lower_degree = lower_degree
+
+ if xp is None:
+ xp = np_compat
+
+ self.xp = array_namespace(xp.empty(0))
+
+ @cached_property
+ def nodes_and_weights(self):
+ # TODO: Currently only support for degree 7 Genz-Malik cubature, should aim to
+ # support arbitrary degree
+ l_2 = math.sqrt(9/70)
+ l_3 = math.sqrt(9/10)
+ l_4 = math.sqrt(9/10)
+ l_5 = math.sqrt(9/19)
+
+ its = itertools.chain(
+ [(0,) * self.ndim],
+ _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
+ _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
+ _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
+ itertools.product((l_5, -l_5), repeat=self.ndim),
+ )
+
+ nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim) + 2**self.ndim
+
+ nodes = self.xp.asarray(
+ list(zip(*its)),
+ dtype=self.xp.float64,
+ )
+
+ nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
+
+ # It's convenient to generate the nodes as a sequence of evaluation points
+ # as an array of shape (npoints, ndim), but nodes needs to have shape
+ # (ndim, npoints)
+ nodes = nodes.T
+
+ w_1 = (
+ (2**self.ndim) * (12824 - 9120*self.ndim + (400 * self.ndim**2)) / 19683
+ )
+ w_2 = (2**self.ndim) * 980/6561
+ w_3 = (2**self.ndim) * (1820 - 400 * self.ndim) / 19683
+ w_4 = (2**self.ndim) * (200 / 19683)
+ w_5 = 6859 / 19683
+
+ weights = self.xp.concat([
+ self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
+ self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
+ self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
+ self.xp.asarray(
+ [w_4] * (2 * (self.ndim - 1) * self.ndim),
+ dtype=self.xp.float64,
+ ),
+ self.xp.asarray([w_5] * (2**self.ndim), dtype=self.xp.float64),
+ ])
+
+ return nodes, weights
+
+ @cached_property
+ def lower_nodes_and_weights(self):
+ # TODO: Currently only support for the degree 5 lower rule, in the future it
+ # would be worth supporting arbitrary degree
+
+ # Nodes are almost the same as the full rule, but there are no nodes
+ # corresponding to l_5.
+ l_2 = math.sqrt(9/70)
+ l_3 = math.sqrt(9/10)
+ l_4 = math.sqrt(9/10)
+
+ its = itertools.chain(
+ [(0,) * self.ndim],
+ _distinct_permutations((l_2,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((-l_2,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((l_3,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((-l_3,) + (0,) * (self.ndim - 1)),
+ _distinct_permutations((l_4, l_4) + (0,) * (self.ndim - 2)),
+ _distinct_permutations((l_4, -l_4) + (0,) * (self.ndim - 2)),
+ _distinct_permutations((-l_4, -l_4) + (0,) * (self.ndim - 2)),
+ )
+
+ nodes_size = 1 + (2 * (self.ndim + 1) * self.ndim)
+
+ nodes = self.xp.asarray(list(zip(*its)), dtype=self.xp.float64)
+ nodes = self.xp.reshape(nodes, (self.ndim, nodes_size))
+ nodes = nodes.T
+
+ # Weights are different from those in the full rule.
+ w_1 = (2**self.ndim) * (729 - 950*self.ndim + 50*self.ndim**2) / 729
+ w_2 = (2**self.ndim) * (245 / 486)
+ w_3 = (2**self.ndim) * (265 - 100*self.ndim) / 1458
+ w_4 = (2**self.ndim) * (25 / 729)
+
+ weights = self.xp.concat([
+ self.xp.asarray([w_1] * 1, dtype=self.xp.float64),
+ self.xp.asarray([w_2] * (2 * self.ndim), dtype=self.xp.float64),
+ self.xp.asarray([w_3] * (2 * self.ndim), dtype=self.xp.float64),
+ self.xp.asarray(
+ [w_4] * (2 * (self.ndim - 1) * self.ndim),
+ dtype=self.xp.float64,
+ ),
+ ])
+
+ return nodes, weights
+
+
+def _distinct_permutations(iterable):
+ """
+ Find the number of distinct permutations of elements of `iterable`.
+ """
+
+ # Algorithm: https://w.wiki/Qai
+
+ items = sorted(iterable)
+ size = len(items)
+
+ while True:
+ # Yield the permutation we have
+ yield tuple(items)
+
+ # Find the largest index i such that A[i] < A[i + 1]
+ for i in range(size - 2, -1, -1):
+ if items[i] < items[i + 1]:
+ break
+
+ # If no such index exists, this permutation is the last one
+ else:
+ return
+
+ # Find the largest index j greater than j such that A[i] < A[j]
+ for j in range(size - 1, i, -1):
+ if items[i] < items[j]:
+ break
+
+ # Swap the value of A[i] with that of A[j], then reverse the
+ # sequence from A[i + 1] to form the new permutation
+ items[i], items[j] = items[j], items[i]
+ items[i+1:] = items[:i-size:-1] # A[i + 1:][::-1]
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..7b7718d29ecb2075088f54c5f2c5fc0d01d9404b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdl-dn-adult-census-l-2-s-act-.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6ec0955788914fa81f698e97a4d1aff773d7a125ed6e769c6271a0b48fc4011d
+size 363
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..3265a7d933efe836193228b86e84c6c7a8b45afd
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/api-v1-jdq-1119.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ef7cbcb58c2edcfea45c058b751faf7783e710462a924e9aacad8d47a7e9f94b
+size 1549
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..8f610044b5cc550df4d4ef18cd2131306dba05be
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1119/data-v1-dl-54002.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6931af256195fcdd2e47dd8b0f9edf16fbf03b198e77b70e3dfd9877cdf09515
+size 1190
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..93289f3064f0d69614a88c2d71922a7a31a92b4a
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jd-1590.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9b105adfedc6b6b82f4695ca9bfe232393034cdf79803523f397a6dc5bf824d1
+size 1544
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..a273bcdfbb3409d37146d32081c82fbc3e7c6e52
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdf-1590.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:046f5e60564693f0f3b8e382725c8012c3e058647139c24685cec984e40fcd00
+size 1032
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d738f893891ff3d747ee71e709301a481d09430e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/api-v1-jdq-1590.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:44b9b0d290a1e339695a431438f84080071c5635161c3977dd17f4c27b00a34a
+size 1507
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..6619336b53b5d71c6bd5c7f2de8e11b88c33ed31
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_1590/data-v1-dl-1595261.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ee1dcdf58f2f1072f7dd1b43388969c51bc6cfe776e3e9465ae6a756e5ddb10a
+size 1152
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..24caf1bf71f829c85f13b7d2b8d0a94e4d27f1b3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jd-2.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a672d435b97a6033dfd1d2a5c823d237ad1865101bd5e403cd99b5be0ba4e03b
+size 1363
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..be96cc72487b20a47142fb8c999ce032d73fba2e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdf-2.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c1b8387a7d08014a1c09807ae458ca7666ab8a3c579cbfb189e09c6d7de892a6
+size 866
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..e1f109fd6086eb97a3be2e7533dc658dac0970d5
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-dv-1.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e900b190795224ff48e46a1c02b10020d4c986ba142880c02c86f0b472ded3c9
+size 309
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d5feb2e1a57bf4ba4d811dbff391977f38122fed
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdl-dn-anneal-l-2-s-act-.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ff6225cb98260ca4ebec015a1a2754f2a7b0dbfb4d0f17dcf6727542154e2a10
+size 346
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..08e36a9fb7d7eb1d95b74eebf7c1b870d4a052c1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/api-v1-jdq-2.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c46f6c5f221d877de604b906403b20cbdf674f1225bcdbb3e15bd1882a69a471
+size 1501
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..b8a4504ee23ee6713dcfa418b7fe0926fde946e3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_2/data-v1-dl-1666876.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d57b2b04cae526306670e3516989dca32c88c155781325ddac42e43dc2322c30
+size 1855
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..83ac698458c7adac8bcda219b26f50cb0b2a2100
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-292.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1e6a38d79d8f9e53a2ce11b68b4153062d4e96ec0b368d02b2e64f1b33c51693
+size 551
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..8015288dcd2399e2c86a4050ce81ec49902d6baf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jd-40981.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c26dcbe30cfb39161f305b2b3d43a9b50adc8b368d0749568c47106cbdb20897
+size 553
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..b3c915315eff5a266c715e3f99584b16ec06ea8f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-292.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:255c16f33ed2967fe100cd8011a7e69f789603724b1ec2ecf91dfeb72067c190
+size 306
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..b3c915315eff5a266c715e3f99584b16ec06ea8f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdf-40981.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:255c16f33ed2967fe100cd8011a7e69f789603724b1ec2ecf91dfeb72067c190
+size 306
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..9c2f6f263750517c2b3ca25942cc4a426bc72de0
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1-s-dact.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8ef6025425fdfc5f736555ea385252af5bcbf62383615db82489366d4f96a0a7
+size 327
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..9cd17f124ef74920b925490ecc8e415dcd59d225
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-dv-1.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9da09e9a6031d060ec416f639a6bf34989e6c88ce641d10621eb906ba1d8c293
+size 99
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..29b93d4214dac84a592173457e4eac04c15bb926
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/api-v1-jdl-dn-australian-l-2-s-act-.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:35890d08165c804526b48aad462d7ccc09e808bd7975ba604bd612b9608797ac
+size 319
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..7bdb62f1628f096b9f91eb2e94ffc413bab4696c
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_292/data-v1-dl-49822.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b7ee24adabd4aaed6419b43fe9d3f86d55fcf4bee0f1698ae21d86c2701314e3
+size 2532
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..65982d59860e015a25a42d8bb57f72bf327c9e0b
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jd-3.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:066a216679b197cc51946e17ee9a2e28215425991b0ceb7f10988c14f7f3f869
+size 2473
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..faf70da9cea25d998883721d679ca9f0030d9575
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdf-3.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ec4f2d6bc4df3882b08bba01571e0792a56f79e0a922d984897773acd284b426
+size 535
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..24537ca9b1e5187b37136b19898ab370dec315d7
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/api-v1-jdq-3.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:09ef19cfad25c5de487ddbaef3c4d068ca3063777730a288dfd6f5096a0c6f46
+size 1407
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..32bdf94f0f4eac4f936d82476fc75917e92317fe
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_3/data-v1-dl-3.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c63fdf8861761f1ca70509f7d2d169a7cc053988c7b7c09c09a6db6124e208be
+size 19485
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..c3454ff8e5a399b14e2033d6122315c4e4b2dbfc
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jd-40589.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:59d1aa6b02d2358c16fa9e4fbeff523a3bd10ebd38c7c371911fa8335e7bdcbf
+size 598
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d9ac42c2bbe778d928f3da1e09e3099962e412ad
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdf-40589.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:826bab057a3929f41189bc51afa0a1752695e63ccf20e128ca6129e9e3321fc2
+size 856
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..ed4efacefc3e856c3ad56407f2d195c65c61e4bb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-dv-3.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:19e6b2a2a8fec5403c146642a4dc2e077d66a3a1ac87e8239bd1dd31c928ab9c
+size 315
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..f8f940438f61ac6fbeaa00c46741c80579af46eb
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdl-dn-emotions-l-2-s-act-.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:4da63a60163340b6e18922abfe7f1f2a7a7da23da63c269324985d61ffaa6075
+size 318
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..49d394f0c458c02f7d9781445ef870cf8f747e0e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/api-v1-jdq-40589.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d0f7973193eb35d19e99d1d8bca3c7f3a8b8d0410508af34ad571aee8ec5ab05
+size 913
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..3c0efffc333c6ef0622ed3d3e3c95d3e319fc05f
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40589/data-v1-dl-4644182.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2c4226550827ceff3509c67179c473e14385cee206536362e57c5e0dfc7751bf
+size 4344
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..b376ef7c9d32dd344e0fff0be5a30ae1e6dda779
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jd-40675.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:a787772d60fbfcc21a0e96fd81906f03542e0b942d19dcc95dae47498953a4fd
+size 323
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d74f6d6f085d991634610476015839faf034ff2d
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdf-40675.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d48d9679789d6baf7d0d3c346e3576d7589b663c3640942f9c1dba76e355faaa
+size 307
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..336782317369c6fdf4d987c6fd3fdee3309a50e1
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1-s-dact.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:21ed1ecc5d874956e951a9361f251afb2165adda92798c89ca5e2f97ae80dd8f
+size 317
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..577840cd46f47e22c75975d855fe21c9b997ee22
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-dv-1.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ad0a4a5477605380f8819ce840dbb928a3d084267c512f6cb50d5be2f7c76bc2
+size 85
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..de6ccfccc5f28d446f34b7ffd7fcf83688cb00cf
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdl-dn-glass2-l-2-s-act-.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:141ba630e039ea44bbaef92a288e2d964fc3aa2ef805a9723b4aac738a26a627
+size 88
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..ed6cf27efa78d576427119132581c3a3fb3b76b3
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/api-v1-jdq-40675.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:88fcdc3a6fed5697f36dc262f69bfffb814767ce336ff28a21def3aac937b08c
+size 886
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..d1d26798a46116abdc22f357615f381a19bccf99
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40675/data-v1-dl-4965250.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:543d0887312f43d9f65a7e1d08be78a2436369f632d7382b4134cebb525a48a3
+size 3000
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..06446ec67eeede9b6d48f044d8ae402fe11bb90e
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jd-40945.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:02882c6b02c4e068ef2b16f37f33ae3d5e9dd17ca29d01662c6924e16427eb5d
+size 437
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..24e0e87d484661242d46a4cf18e2e6695736fa26
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdf-40945.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:95f0938dfdf1b87d0ffc4d526f2c91e097ef7689480b693970126d908f291030
+size 320
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz
new file mode 100644
index 0000000000000000000000000000000000000000..adb1b0a58ae958ab00a906b0287f416a4ab48ace
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/api-v1-jdq-40945.json.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9c7e5a46554ab6a8121832dc0cd9f7a60f5034cef1a5a7d61346bbd912516b54
+size 1042
diff --git a/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz
new file mode 100644
index 0000000000000000000000000000000000000000..5d8d5ae4fd5692b26e281928f6a1baad008f2008
--- /dev/null
+++ b/python_embeded/Lib/site-packages/sklearn/datasets/tests/data/openml/id_40945/data-v1-dl-16826755.arff.gz
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:516e961f519876e5f89b339a0364a08dd64160ac3a4d76d5ec62955bfd6d6ce5
+size 32243