diff --git a/ckpts/universal/global_step80/zero/10.post_attention_layernorm.weight/exp_avg_sq.pt b/ckpts/universal/global_step80/zero/10.post_attention_layernorm.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..5de0e2b1706aaae835e87b4f281fafb911dd4482 --- /dev/null +++ b/ckpts/universal/global_step80/zero/10.post_attention_layernorm.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:afba97a9cc0ee57e8f4a6cae59533d9d46eeee5568890e85f5272182eac0c314 +size 9387 diff --git a/ckpts/universal/global_step80/zero/19.attention.dense.weight/exp_avg.pt b/ckpts/universal/global_step80/zero/19.attention.dense.weight/exp_avg.pt new file mode 100644 index 0000000000000000000000000000000000000000..1594c582edc03d63d6b6d3d525b40f054c932b3f --- /dev/null +++ b/ckpts/universal/global_step80/zero/19.attention.dense.weight/exp_avg.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea702ada56e650a6ba3311f73d9451334a8810b34202670981a4feeb82760cf3 +size 16778396 diff --git a/ckpts/universal/global_step80/zero/19.attention.dense.weight/exp_avg_sq.pt b/ckpts/universal/global_step80/zero/19.attention.dense.weight/exp_avg_sq.pt new file mode 100644 index 0000000000000000000000000000000000000000..436805eacc8e9e286ec0f506645ee60f4a77c2ef --- /dev/null +++ b/ckpts/universal/global_step80/zero/19.attention.dense.weight/exp_avg_sq.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8a58559bf9f84a41bc0bb13926ff6f8fb989de4396e66971b657abe0a06068e1 +size 16778411 diff --git a/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/License.txt b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..b491c70e0aef319022ded661e111ddbd45b8a17f --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/License.txt @@ -0,0 +1,1568 @@ +End User License Agreement +-------------------------- + + +Preface +------- + +The Software License Agreement in Chapter 1 and the Supplement +in Chapter 2 contain license terms and conditions that govern +the use of NVIDIA software. By accepting this agreement, you +agree to comply with all the terms and conditions applicable +to the product(s) included herein. + + +NVIDIA Driver + + +Description + +This package contains the operating system driver and +fundamental system software components for NVIDIA GPUs. + + +NVIDIA CUDA Toolkit + + +Description + +The NVIDIA CUDA Toolkit provides command-line and graphical +tools for building, debugging and optimizing the performance +of applications accelerated by NVIDIA GPUs, runtime and math +libraries, and documentation including programming guides, +user manuals, and API references. + + +Default Install Location of CUDA Toolkit + +Windows platform: + +%ProgramFiles%\NVIDIA GPU Computing Toolkit\CUDA\v#.# + +Linux platform: + +/usr/local/cuda-#.# + +Mac platform: + +/Developer/NVIDIA/CUDA-#.# + + +NVIDIA CUDA Samples + + +Description + +This package includes over 100+ CUDA examples that demonstrate +various CUDA programming principles, and efficient CUDA +implementation of algorithms in specific application domains. + + +Default Install Location of CUDA Samples + +Windows platform: + +%ProgramData%\NVIDIA Corporation\CUDA Samples\v#.# + +Linux platform: + +/usr/local/cuda-#.#/samples + +and + +$HOME/NVIDIA_CUDA-#.#_Samples + +Mac platform: + +/Developer/NVIDIA/CUDA-#.#/samples + + +NVIDIA Nsight Visual Studio Edition (Windows only) + + +Description + +NVIDIA Nsight Development Platform, Visual Studio Edition is a +development environment integrated into Microsoft Visual +Studio that provides tools for debugging, profiling, analyzing +and optimizing your GPU computing and graphics applications. + + +Default Install Location of Nsight Visual Studio Edition + +Windows platform: + +%ProgramFiles(x86)%\NVIDIA Corporation\Nsight Visual Studio Edition #.# + + +1. License Agreement for NVIDIA Software Development Kits +--------------------------------------------------------- + + +Release Date: July 26, 2018 +--------------------------- + + +Important NoticeRead before downloading, installing, +copying or using the licensed software: +------------------------------------------------------- + +This license agreement, including exhibits attached +("Agreement”) is a legal agreement between you and NVIDIA +Corporation ("NVIDIA") and governs your use of a NVIDIA +software development kit (“SDK”). + +Each SDK has its own set of software and materials, but here +is a description of the types of items that may be included in +a SDK: source code, header files, APIs, data sets and assets +(examples include images, textures, models, scenes, videos, +native API input/output files), binary software, sample code, +libraries, utility programs, programming code and +documentation. + +This Agreement can be accepted only by an adult of legal age +of majority in the country in which the SDK is used. + +If you are entering into this Agreement on behalf of a company +or other legal entity, you represent that you have the legal +authority to bind the entity to this Agreement, in which case +“you” will mean the entity you represent. + +If you don’t have the required age or authority to accept +this Agreement, or if you don’t accept all the terms and +conditions of this Agreement, do not download, install or use +the SDK. + +You agree to use the SDK only for purposes that are permitted +by (a) this Agreement, and (b) any applicable law, regulation +or generally accepted practices or guidelines in the relevant +jurisdictions. + + +1.1. License + + +1.1.1. License Grant + +Subject to the terms of this Agreement, NVIDIA hereby grants +you a non-exclusive, non-transferable license, without the +right to sublicense (except as expressly provided in this +Agreement) to: + + 1. Install and use the SDK, + + 2. Modify and create derivative works of sample source code + delivered in the SDK, and + + 3. Distribute those portions of the SDK that are identified + in this Agreement as distributable, as incorporated in + object code format into a software application that meets + the distribution requirements indicated in this Agreement. + + +1.1.2. Distribution Requirements + +These are the distribution requirements for you to exercise +the distribution grant: + + 1. Your application must have material additional + functionality, beyond the included portions of the SDK. + + 2. The distributable portions of the SDK shall only be + accessed by your application. + + 3. The following notice shall be included in modifications + and derivative works of sample source code distributed: + “This software contains source code provided by NVIDIA + Corporation.” + + 4. Unless a developer tool is identified in this Agreement + as distributable, it is delivered for your internal use + only. + + 5. The terms under which you distribute your application + must be consistent with the terms of this Agreement, + including (without limitation) terms relating to the + license grant and license restrictions and protection of + NVIDIA’s intellectual property rights. Additionally, you + agree that you will protect the privacy, security and + legal rights of your application users. + + 6. You agree to notify NVIDIA in writing of any known or + suspected distribution or use of the SDK not in compliance + with the requirements of this Agreement, and to enforce + the terms of your agreements with respect to distributed + SDK. + + +1.1.3. Authorized Users + +You may allow employees and contractors of your entity or of +your subsidiary(ies) to access and use the SDK from your +secure network to perform work on your behalf. + +If you are an academic institution you may allow users +enrolled or employed by the academic institution to access and +use the SDK from your secure network. + +You are responsible for the compliance with the terms of this +Agreement by your authorized users. If you become aware that +your authorized users didn’t follow the terms of this +Agreement, you agree to take reasonable steps to resolve the +non-compliance and prevent new occurrences. + + +1.1.4. Pre-Release SDK + +The SDK versions identified as alpha, beta, preview or +otherwise as pre-release, may not be fully functional, may +contain errors or design flaws, and may have reduced or +different security, privacy, accessibility, availability, and +reliability standards relative to commercial versions of +NVIDIA software and materials. Use of a pre-release SDK may +result in unexpected results, loss of data, project delays or +other unpredictable damage or loss. + +You may use a pre-release SDK at your own risk, understanding +that pre-release SDKs are not intended for use in production +or business-critical systems. + +NVIDIA may choose not to make available a commercial version +of any pre-release SDK. NVIDIA may also choose to abandon +development and terminate the availability of a pre-release +SDK at any time without liability. + + +1.1.5. Updates + +NVIDIA may, at its option, make available patches, workarounds +or other updates to this SDK. Unless the updates are provided +with their separate governing terms, they are deemed part of +the SDK licensed to you as provided in this Agreement. You +agree that the form and content of the SDK that NVIDIA +provides may change without prior notice to you. While NVIDIA +generally maintains compatibility between versions, NVIDIA may +in some cases make changes that introduce incompatibilities in +future versions of the SDK. + + +1.1.6. Third Party Licenses + +The SDK may come bundled with, or otherwise include or be +distributed with, third party software licensed by a NVIDIA +supplier and/or open source software provided under an open +source license. Use of third party software is subject to the +third-party license terms, or in the absence of third party +terms, the terms of this Agreement. Copyright to third party +software is held by the copyright holders indicated in the +third-party software or license. + + +1.1.7. Reservation of Rights + +NVIDIA reserves all rights, title, and interest in and to the +SDK, not expressly granted to you under this Agreement. + + +1.2. Limitations + +The following license limitations apply to your use of the +SDK: + + 1. You may not reverse engineer, decompile or disassemble, + or remove copyright or other proprietary notices from any + portion of the SDK or copies of the SDK. + + 2. Except as expressly provided in this Agreement, you may + not copy, sell, rent, sublicense, transfer, distribute, + modify, or create derivative works of any portion of the + SDK. For clarity, you may not distribute or sublicense the + SDK as a stand-alone product. + + 3. Unless you have an agreement with NVIDIA for this + purpose, you may not indicate that an application created + with the SDK is sponsored or endorsed by NVIDIA. + + 4. You may not bypass, disable, or circumvent any + encryption, security, digital rights management or + authentication mechanism in the SDK. + + 5. You may not use the SDK in any manner that would cause it + to become subject to an open source software license. As + examples, licenses that require as a condition of use, + modification, and/or distribution that the SDK be: + + a. Disclosed or distributed in source code form; + + b. Licensed for the purpose of making derivative works; + or + + c. Redistributable at no charge. + + 6. Unless you have an agreement with NVIDIA for this + purpose, you may not use the SDK with any system or + application where the use or failure of the system or + application can reasonably be expected to threaten or + result in personal injury, death, or catastrophic loss. + Examples include use in avionics, navigation, military, + medical, life support or other life critical applications. + NVIDIA does not design, test or manufacture the SDK for + these critical uses and NVIDIA shall not be liable to you + or any third party, in whole or in part, for any claims or + damages arising from such uses. + + 7. You agree to defend, indemnify and hold harmless NVIDIA + and its affiliates, and their respective employees, + contractors, agents, officers and directors, from and + against any and all claims, damages, obligations, losses, + liabilities, costs or debt, fines, restitutions and + expenses (including but not limited to attorney’s fees + and costs incident to establishing the right of + indemnification) arising out of or related to your use of + the SDK outside of the scope of this Agreement, or not in + compliance with its terms. + + +1.3. Ownership + + 1. NVIDIA or its licensors hold all rights, title and + interest in and to the SDK and its modifications and + derivative works, including their respective intellectual + property rights, subject to your rights described in this + section. This SDK may include software and materials from + NVIDIA’s licensors, and these licensors are intended + third party beneficiaries that may enforce this Agreement + with respect to their intellectual property rights. + + 2. You hold all rights, title and interest in and to your + applications and your derivative works of the sample + source code delivered in the SDK, including their + respective intellectual property rights, subject to + NVIDIA’s rights described in this section. + + 3. You may, but don’t have to, provide to NVIDIA + suggestions, feature requests or other feedback regarding + the SDK, including possible enhancements or modifications + to the SDK. For any feedback that you voluntarily provide, + you hereby grant NVIDIA and its affiliates a perpetual, + non-exclusive, worldwide, irrevocable license to use, + reproduce, modify, license, sublicense (through multiple + tiers of sublicensees), and distribute (through multiple + tiers of distributors) it without the payment of any + royalties or fees to you. NVIDIA will use feedback at its + choice. NVIDIA is constantly looking for ways to improve + its products, so you may send feedback to NVIDIA through + the developer portal at https://developer.nvidia.com. + + +1.4. No Warranties + +THE SDK IS PROVIDED BY NVIDIA “AS IS” AND “WITH ALL +FAULTS.” TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND +ITS AFFILIATES EXPRESSLY DISCLAIM ALL WARRANTIES OF ANY KIND +OR NATURE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, +BUT NOT LIMITED TO, ANY WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE, TITLE, NON-INFRINGEMENT, OR THE +ABSENCE OF ANY DEFECTS THEREIN, WHETHER LATENT OR PATENT. NO +WARRANTY IS MADE ON THE BASIS OF TRADE USAGE, COURSE OF +DEALING OR COURSE OF TRADE. + + +1.5. Limitation of Liability + +TO THE MAXIMUM EXTENT PERMITTED BY LAW, NVIDIA AND ITS +AFFILIATES SHALL NOT BE LIABLE FOR ANY SPECIAL, INCIDENTAL, +PUNITIVE OR CONSEQUENTIAL DAMAGES, OR ANY LOST PROFITS, LOSS +OF USE, LOSS OF DATA OR LOSS OF GOODWILL, OR THE COSTS OF +PROCURING SUBSTITUTE PRODUCTS, ARISING OUT OF OR IN CONNECTION +WITH THIS AGREEMENT OR THE USE OR PERFORMANCE OF THE SDK, +WHETHER SUCH LIABILITY ARISES FROM ANY CLAIM BASED UPON BREACH +OF CONTRACT, BREACH OF WARRANTY, TORT (INCLUDING NEGLIGENCE), +PRODUCT LIABILITY OR ANY OTHER CAUSE OF ACTION OR THEORY OF +LIABILITY. IN NO EVENT WILL NVIDIA’S AND ITS AFFILIATES +TOTAL CUMULATIVE LIABILITY UNDER OR ARISING OUT OF THIS +AGREEMENT EXCEED US$10.00. THE NATURE OF THE LIABILITY OR THE +NUMBER OF CLAIMS OR SUITS SHALL NOT ENLARGE OR EXTEND THIS +LIMIT. + +These exclusions and limitations of liability shall apply +regardless if NVIDIA or its affiliates have been advised of +the possibility of such damages, and regardless of whether a +remedy fails its essential purpose. These exclusions and +limitations of liability form an essential basis of the +bargain between the parties, and, absent any of these +exclusions or limitations of liability, the provisions of this +Agreement, including, without limitation, the economic terms, +would be substantially different. + + +1.6. Termination + + 1. This Agreement will continue to apply until terminated by + either you or NVIDIA as described below. + + 2. If you want to terminate this Agreement, you may do so by + stopping to use the SDK. + + 3. NVIDIA may, at any time, terminate this Agreement if: + + a. (i) you fail to comply with any term of this + Agreement and the non-compliance is not fixed within + thirty (30) days following notice from NVIDIA (or + immediately if you violate NVIDIA’s intellectual + property rights); + + b. (ii) you commence or participate in any legal + proceeding against NVIDIA with respect to the SDK; or + + c. (iii) NVIDIA decides to no longer provide the SDK in + a country or, in NVIDIA’s sole discretion, the + continued use of it is no longer commercially viable. + + 4. Upon any termination of this Agreement, you agree to + promptly discontinue use of the SDK and destroy all copies + in your possession or control. Your prior distributions in + accordance with this Agreement are not affected by the + termination of this Agreement. Upon written request, you + will certify in writing that you have complied with your + commitments under this section. Upon any termination of + this Agreement all provisions survive except for the + license grant provisions. + + +1.7. General + +If you wish to assign this Agreement or your rights and +obligations, including by merger, consolidation, dissolution +or operation of law, contact NVIDIA to ask for permission. Any +attempted assignment not approved by NVIDIA in writing shall +be void and of no effect. NVIDIA may assign, delegate or +transfer this Agreement and its rights and obligations, and if +to a non-affiliate you will be notified. + +You agree to cooperate with NVIDIA and provide reasonably +requested information to verify your compliance with this +Agreement. + +This Agreement will be governed in all respects by the laws of +the United States and of the State of Delaware as those laws +are applied to contracts entered into and performed entirely +within Delaware by Delaware residents, without regard to the +conflicts of laws principles. The United Nations Convention on +Contracts for the International Sale of Goods is specifically +disclaimed. You agree to all terms of this Agreement in the +English language. + +The state or federal courts residing in Santa Clara County, +California shall have exclusive jurisdiction over any dispute +or claim arising out of this Agreement. Notwithstanding this, +you agree that NVIDIA shall still be allowed to apply for +injunctive remedies or an equivalent type of urgent legal +relief in any jurisdiction. + +If any court of competent jurisdiction determines that any +provision of this Agreement is illegal, invalid or +unenforceable, such provision will be construed as limited to +the extent necessary to be consistent with and fully +enforceable under the law and the remaining provisions will +remain in full force and effect. Unless otherwise specified, +remedies are cumulative. + +Each party acknowledges and agrees that the other is an +independent contractor in the performance of this Agreement. + +The SDK has been developed entirely at private expense and is +“commercial items” consisting of “commercial computer +software” and “commercial computer software +documentation” provided with RESTRICTED RIGHTS. Use, +duplication or disclosure by the U.S. Government or a U.S. +Government subcontractor is subject to the restrictions in +this Agreement pursuant to DFARS 227.7202-3(a) or as set forth +in subparagraphs (c)(1) and (2) of the Commercial Computer +Software - Restricted Rights clause at FAR 52.227-19, as +applicable. Contractor/manufacturer is NVIDIA, 2788 San Tomas +Expressway, Santa Clara, CA 95051. + +The SDK is subject to United States export laws and +regulations. You agree that you will not ship, transfer or +export the SDK into any country, or use the SDK in any manner, +prohibited by the United States Bureau of Industry and +Security or economic sanctions regulations administered by the +U.S. Department of Treasury’s Office of Foreign Assets +Control (OFAC), or any applicable export laws, restrictions or +regulations. These laws include restrictions on destinations, +end users and end use. By accepting this Agreement, you +confirm that you are not a resident or citizen of any country +currently embargoed by the U.S. and that you are not otherwise +prohibited from receiving the SDK. + +Any notice delivered by NVIDIA to you under this Agreement +will be delivered via mail, email or fax. You agree that any +notices that NVIDIA sends you electronically will satisfy any +legal communication requirements. Please direct your legal +notices or other correspondence to NVIDIA Corporation, 2788 +San Tomas Expressway, Santa Clara, California 95051, United +States of America, Attention: Legal Department. + +This Agreement and any exhibits incorporated into this +Agreement constitute the entire agreement of the parties with +respect to the subject matter of this Agreement and supersede +all prior negotiations or documentation exchanged between the +parties relating to this SDK license. Any additional and/or +conflicting terms on documents issued by you are null, void, +and invalid. Any amendment or waiver under this Agreement +shall be in writing and signed by representatives of both +parties. + + +2. CUDA Toolkit Supplement to Software License Agreement for +NVIDIA Software Development Kits +------------------------------------------------------------ + + +Release date: August 16, 2018 +----------------------------- + +The terms in this supplement govern your use of the NVIDIA +CUDA Toolkit SDK under the terms of your license agreement +(“Agreement”) as modified by this supplement. Capitalized +terms used but not defined below have the meaning assigned to +them in the Agreement. + +This supplement is an exhibit to the Agreement and is +incorporated as an integral part of the Agreement. In the +event of conflict between the terms in this supplement and the +terms in the Agreement, the terms in this supplement govern. + + +2.1. License Scope + +The SDK is licensed for you to develop applications only for +use in systems with NVIDIA GPUs. + + +2.2. Distribution + +The portions of the SDK that are distributable under the +Agreement are listed in Attachment A. + + +2.3. Operating Systems + +Those portions of the SDK designed exclusively for use on the +Linux or FreeBSD operating systems, or other operating systems +derived from the source code to these operating systems, may +be copied and redistributed for use in accordance with this +Agreement, provided that the object code files are not +modified in any way (except for unzipping of compressed +files). + + +2.4. Audio and Video Encoders and Decoders + +You acknowledge and agree that it is your sole responsibility +to obtain any additional third-party licenses required to +make, have made, use, have used, sell, import, and offer for +sale your products or services that include or incorporate any +third-party software and content relating to audio and/or +video encoders and decoders from, including but not limited +to, Microsoft, Thomson, Fraunhofer IIS, Sisvel S.p.A., +MPEG-LA, and Coding Technologies. NVIDIA does not grant to you +under this Agreement any necessary patent or other rights with +respect to any audio and/or video encoders and decoders. + + +2.5. Licensing + +If the distribution terms in this Agreement are not suitable +for your organization, or for any questions regarding this +Agreement, please contact NVIDIA at +nvidia-compute-license-questions@nvidia.com. + + +2.6. Attachment A + +The following portions of the SDK are distributable under the +Agreement: + +Component + +CUDA Runtime + +Windows + +cudart.dll, cudart_static.lib, cudadevrt.lib + +Mac OSX + +libcudart.dylib, libcudart_static.a, libcudadevrt.a + +Linux + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Android + +libcudart.so, libcudart_static.a, libcudadevrt.a + +Component + +CUDA FFT Library + +Windows + +cufft.dll, cufftw.dll, cufft.lib, cufftw.lib + +Mac OSX + +libcufft.dylib, libcufft_static.a, libcufftw.dylib, +libcufftw_static.a + +Linux + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Android + +libcufft.so, libcufft_static.a, libcufftw.so, +libcufftw_static.a + +Component + +CUDA BLAS Library + +Windows + +cublas.dll, cublasLt.dll + +Mac OSX + +libcublas.dylib, libcublasLt.dylib, libcublas_static.a, +libcublasLt_static.a + +Linux + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Android + +libcublas.so, libcublasLt.so, libcublas_static.a, +libcublasLt_static.a + +Component + +NVIDIA "Drop-in" BLAS Library + +Windows + +nvblas.dll + +Mac OSX + +libnvblas.dylib + +Linux + +libnvblas.so + +Component + +CUDA Sparse Matrix Library + +Windows + +cusparse.dll, cusparse.lib + +Mac OSX + +libcusparse.dylib, libcusparse_static.a + +Linux + +libcusparse.so, libcusparse_static.a + +Android + +libcusparse.so, libcusparse_static.a + +Component + +CUDA Linear Solver Library + +Windows + +cusolver.dll, cusolver.lib + +Mac OSX + +libcusolver.dylib, libcusolver_static.a + +Linux + +libcusolver.so, libcusolver_static.a + +Android + +libcusolver.so, libcusolver_static.a + +Component + +CUDA Random Number Generation Library + +Windows + +curand.dll, curand.lib + +Mac OSX + +libcurand.dylib, libcurand_static.a + +Linux + +libcurand.so, libcurand_static.a + +Android + +libcurand.so, libcurand_static.a + +Component + +CUDA Accelerated Graph Library + +Component + +NVIDIA Performance Primitives Library + +Windows + +nppc.dll, nppc.lib, nppial.dll, nppial.lib, nppicc.dll, +nppicc.lib, nppicom.dll, nppicom.lib, nppidei.dll, +nppidei.lib, nppif.dll, nppif.lib, nppig.dll, nppig.lib, +nppim.dll, nppim.lib, nppist.dll, nppist.lib, nppisu.dll, +nppisu.lib, nppitc.dll, nppitc.lib, npps.dll, npps.lib + +Mac OSX + +libnppc.dylib, libnppc_static.a, libnppial.dylib, +libnppial_static.a, libnppicc.dylib, libnppicc_static.a, +libnppicom.dylib, libnppicom_static.a, libnppidei.dylib, +libnppidei_static.a, libnppif.dylib, libnppif_static.a, +libnppig.dylib, libnppig_static.a, libnppim.dylib, +libnppisu_static.a, libnppitc.dylib, libnppitc_static.a, +libnpps.dylib, libnpps_static.a + +Linux + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Android + +libnppc.so, libnppc_static.a, libnppial.so, +libnppial_static.a, libnppicc.so, libnppicc_static.a, +libnppicom.so, libnppicom_static.a, libnppidei.so, +libnppidei_static.a, libnppif.so, libnppif_static.a +libnppig.so, libnppig_static.a, libnppim.so, +libnppim_static.a, libnppist.so, libnppist_static.a, +libnppisu.so, libnppisu_static.a, libnppitc.so +libnppitc_static.a, libnpps.so, libnpps_static.a + +Component + +NVIDIA JPEG Library + +Linux + +libnvjpeg.so, libnvjpeg_static.a + +Component + +Internal common library required for statically linking to +cuBLAS, cuSPARSE, cuFFT, cuRAND, nvJPEG and NPP + +Mac OSX + +libculibos.a + +Linux + +libculibos.a + +Component + +NVIDIA Runtime Compilation Library and Header + +All + +nvrtc.h + +Windows + +nvrtc.dll, nvrtc-builtins.dll + +Mac OSX + +libnvrtc.dylib, libnvrtc-builtins.dylib + +Linux + +libnvrtc.so, libnvrtc-builtins.so + +Component + +NVIDIA Optimizing Compiler Library + +Windows + +nvvm.dll + +Mac OSX + +libnvvm.dylib + +Linux + +libnvvm.so + +Component + +NVIDIA Common Device Math Functions Library + +Windows + +libdevice.10.bc + +Mac OSX + +libdevice.10.bc + +Linux + +libdevice.10.bc + +Component + +CUDA Occupancy Calculation Header Library + +All + +cuda_occupancy.h + +Component + +CUDA Half Precision Headers + +All + +cuda_fp16.h, cuda_fp16.hpp + +Component + +CUDA Profiling Tools Interface (CUPTI) Library + +Windows + +cupti.dll + +Mac OSX + +libcupti.dylib + +Linux + +libcupti.so + +Component + +NVIDIA Tools Extension Library + +Windows + +nvToolsExt.dll, nvToolsExt.lib + +Mac OSX + +libnvToolsExt.dylib + +Linux + +libnvToolsExt.so + +Component + +NVIDIA CUDA Driver Libraries + +Linux + +libcuda.so, libnvidia-fatbinaryloader.so, +libnvidia-ptxjitcompiler.so + +The NVIDIA CUDA Driver Libraries are only distributable in +applications that meet this criteria: + + 1. The application was developed starting from a NVIDIA CUDA + container obtained from Docker Hub or the NVIDIA GPU + Cloud, and + + 2. The resulting application is packaged as a Docker + container and distributed to users on Docker Hub or the + NVIDIA GPU Cloud only. + + +2.7. Attachment B + + +Additional Licensing Obligations + +The following third party components included in the SOFTWARE +are licensed to Licensee pursuant to the following terms and +conditions: + + 1. Licensee's use of the GDB third party component is + subject to the terms and conditions of GNU GPL v3: + + This product includes copyrighted third-party software licensed + under the terms of the GNU General Public License v3 ("GPL v3"). + All third-party software packages are copyright by their respective + authors. GPL v3 terms and conditions are hereby incorporated into + the Agreement by this reference: http://www.gnu.org/licenses/gpl.txt + + Consistent with these licensing requirements, the software + listed below is provided under the terms of the specified + open source software licenses. To obtain source code for + software provided under licenses that require + redistribution of source code, including the GNU General + Public License (GPL) and GNU Lesser General Public License + (LGPL), contact oss-requests@nvidia.com. This offer is + valid for a period of three (3) years from the date of the + distribution of this product by NVIDIA CORPORATION. + + Component License + CUDA-GDB GPL v3 + + 2. Licensee represents and warrants that any and all third + party licensing and/or royalty payment obligations in + connection with Licensee's use of the H.264 video codecs + are solely the responsibility of Licensee. + + 3. Licensee's use of the Thrust library is subject to the + terms and conditions of the Apache License Version 2.0. + All third-party software packages are copyright by their + respective authors. Apache License Version 2.0 terms and + conditions are hereby incorporated into the Agreement by + this reference. + http://www.apache.org/licenses/LICENSE-2.0.html + + In addition, Licensee acknowledges the following notice: + Thrust includes source code from the Boost Iterator, + Tuple, System, and Random Number libraries. + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + 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, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 4. Licensee's use of the LLVM third party component is + subject to the following terms and conditions: + + ====================================================== + LLVM Release License + ====================================================== + University of Illinois/NCSA + Open Source License + + Copyright (c) 2003-2010 University of Illinois at Urbana-Champaign. + All rights reserved. + + Developed by: + + LLVM Team + + University of Illinois at Urbana-Champaign + + http://llvm.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to + deal with 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: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimers. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimers in the + documentation and/or other materials provided with the distribution. + + * Neither the names of the LLVM Team, University of Illinois at Urbana- + Champaign, nor the names of its contributors may be used to endorse or + promote products derived from this Software without specific prior + written permission. + + 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 CONTRIBUTORS 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 WITH THE SOFTWARE. + + 5. Licensee's use (e.g. nvprof) of the PCRE third party + component is subject to the following terms and + conditions: + + ------------ + PCRE LICENCE + ------------ + PCRE is a library of functions to support regular expressions whose syntax + and semantics are as close as possible to those of the Perl 5 language. + Release 8 of PCRE is distributed under the terms of the "BSD" licence, as + specified below. The documentation for PCRE, supplied in the "doc" + directory, is distributed under the same terms as the software itself. The + basic library functions are written in C and are freestanding. Also + included in the distribution is a set of C++ wrapper functions, and a just- + in-time compiler that can be used to optimize pattern matching. These are + both optional features that can be omitted when the library is built. + + THE BASIC LIBRARY FUNCTIONS + --------------------------- + Written by: Philip Hazel + Email local part: ph10 + Email domain: cam.ac.uk + University of Cambridge Computing Service, + Cambridge, England. + Copyright (c) 1997-2012 University of Cambridge + All rights reserved. + + PCRE JUST-IN-TIME COMPILATION SUPPORT + ------------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2010-2012 Zoltan Herczeg + All rights reserved. + + STACK-LESS JUST-IN-TIME COMPILER + -------------------------------- + Written by: Zoltan Herczeg + Email local part: hzmester + Emain domain: freemail.hu + Copyright(c) 2009-2012 Zoltan Herczeg + All rights reserved. + + THE C++ WRAPPER FUNCTIONS + ------------------------- + Contributed by: Google Inc. + Copyright (c) 2007-2012, Google Inc. + All rights reserved. + + THE "BSD" LICENCE + ----------------- + 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 University of Cambridge nor the name of Google + Inc. nor the names of their 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. + + 6. Some of the cuBLAS library routines were written by or + derived from code written by Vasily Volkov and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2007-2009, Regents of the University of California + + 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 University of California, Berkeley 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 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. + + 7. Some of the cuBLAS library routines were written by or + derived from code written by Davide Barbieri and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2008-2009 Davide Barbieri @ University of Rome Tor Vergata. + + 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. + * 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. + + 8. Some of the cuBLAS library routines were derived from + code developed by the University of Tennessee and are + subject to the Modified Berkeley Software Distribution + License as follows: + + Copyright (c) 2010 The University of Tennessee. + + 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 listed in this license in the documentation and/or + other materials provided with the distribution. + * Neither the name of the copyright holders 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. + + 9. Some of the cuBLAS library routines were written by or + derived from code written by Jonathan Hogg and are subject + to the Modified Berkeley Software Distribution License as + follows: + + Copyright (c) 2012, The Science and Technology Facilities Council (STFC). + + 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 STFC 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 STFC 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. + + 10. Some of the cuBLAS library routines were written by or + derived from code written by Ahmad M. Abdelfattah, David + Keyes, and Hatem Ltaief, and are subject to the Apache + License, Version 2.0, as follows: + + -- (C) Copyright 2013 King Abdullah University of Science and Technology + Authors: + Ahmad Abdelfattah (ahmad.ahmad@kaust.edu.sa) + David Keyes (david.keyes@kaust.edu.sa) + Hatem Ltaief (hatem.ltaief@kaust.edu.sa) + + 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 King Abdullah University of Science and + Technology 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 + HOLDERS 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 + + 11. Some of the cuSPARSE library routines were written by or + derived from code written by Li-Wen Chang and are subject + to the NCSA Open Source License as follows: + + Copyright (c) 2012, University of Illinois. + + All rights reserved. + + Developed by: IMPACT Group, University of Illinois, http://impact.crhc.illinois.edu + + Permission is hereby granted, free of charge, to any person obtaining + a copy of this software and associated documentation files (the + "Software"), to deal with 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: + * 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 + disclaimers in the documentation and/or other materials provided + with the distribution. + * Neither the names of IMPACT Group, University of Illinois, nor + the names of its contributors may be used to endorse or promote + products derived from this Software without specific prior + written permission. + + 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 CONTRIBUTORS 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 WITH THE + SOFTWARE. + + 12. Some of the cuRAND library routines were written by or + derived from code written by Mutsuo Saito and Makoto + Matsumoto and are subject to the following license: + + Copyright (c) 2009, 2010 Mutsuo Saito, Makoto Matsumoto and Hiroshima + University. All rights reserved. + + Copyright (c) 2011 Mutsuo Saito, Makoto Matsumoto, Hiroshima + University and University of Tokyo. 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 Hiroshima University 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. + + 13. Some of the cuRAND library routines were derived from + code developed by D. E. Shaw Research and are subject to + the following license: + + Copyright 2010-2011, D. E. Shaw Research. + + 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 D. E. Shaw Research 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. + + 14. Some of the Math library routines were written by or + derived from code developed by Norbert Juffa and are + subject to the following license: + + Copyright (c) 2015-2017, Norbert Juffa + All rights reserved. + + 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. + + 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. + + 15. Licensee's use of the lz4 third party component is + subject to the following terms and conditions: + + Copyright (C) 2011-2013, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + 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. + + 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. + + 16. The NPP library uses code from the Boost Math Toolkit, + and is subject to the following license: + + Boost Software License - Version 1.0 - August 17th, 2003 + . . . . + + Permission is hereby granted, free of charge, to any person or + organization obtaining a copy of the software and accompanying + documentation covered by this license (the "Software") to use, + reproduce, display, distribute, execute, and transmit the Software, + and to prepare derivative works of the Software, and to permit + third-parties to whom the Software is furnished to do so, all + subject to the following: + + The copyright notices in the Software and this entire statement, + including the above license grant, this restriction and the following + disclaimer, must be included in all copies of the Software, in whole + or in part, and all derivative works of the Software, unless such + copies or derivative works are solely in the form of machine-executable + object code generated by a source language processor. + + 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, TITLE AND + NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR + ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR + OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. + + 17. Portions of the Nsight Eclipse Edition is subject to the + following license: + + The Eclipse Foundation makes available all content in this plug-in + ("Content"). Unless otherwise indicated below, the Content is provided + to you under the terms and conditions of the Eclipse Public License + Version 1.0 ("EPL"). A copy of the EPL is available at http:// + www.eclipse.org/legal/epl-v10.html. For purposes of the EPL, "Program" + will mean the Content. + + If you did not receive this Content directly from the Eclipse + Foundation, the Content is being redistributed by another party + ("Redistributor") and different terms and conditions may apply to your + use of any object code in the Content. Check the Redistributor's + license that was provided with the Content. If no such license exists, + contact the Redistributor. Unless otherwise indicated below, the terms + and conditions of the EPL still apply to any source code in the + Content and such source code may be obtained at http://www.eclipse.org. + + 18. Some of the cuBLAS library routines uses code from + OpenAI, which is subject to the following license: + + License URL + https://github.com/openai/openai-gemm/blob/master/LICENSE + + License Text + The MIT License + + Copyright (c) 2016 OpenAI (http://openai.com), 2016 Google 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. + + 19. Licensee's use of the Visual Studio Setup Configuration + Samples is subject to the following license: + + The MIT License (MIT) + Copyright (C) Microsoft Corporation. All rights reserved. + + 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. + + 20. Licensee's use of linmath.h header for CPU functions for + GL vector/matrix operations from lunarG is subject to the + Apache License Version 2.0. + + 21. The DX12-CUDA sample uses the d3dx12.h header, which is + subject to the MIT license . + +----------------- diff --git a/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/METADATA b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..aa9af815101f2d67ea98b8c381febb35a2ebc7d7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/METADATA @@ -0,0 +1,35 @@ +Metadata-Version: 2.1 +Name: nvidia-cufft-cu12 +Version: 11.0.2.54 +Summary: CUFFT native runtime libraries +Home-page: https://developer.nvidia.com/cuda-zone +Author: Nvidia CUDA Installer Team +Author-email: cuda_installer@nvidia.com +License: NVIDIA Proprietary Software +Keywords: cuda,nvidia,runtime,machine learning,deep learning +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: Other/Proprietary License +Classifier: Natural Language :: English +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.5 +Classifier: Programming Language :: Python :: 3.6 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Topic :: Scientific/Engineering +Classifier: Topic :: Scientific/Engineering :: Mathematics +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Classifier: Topic :: Software Development +Classifier: Topic :: Software Development :: Libraries +Classifier: Operating System :: Microsoft :: Windows +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3 +License-File: License.txt + +CUFFT native runtime libraries diff --git a/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/RECORD b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..a5ea4f4479402c0ba4806d771df9e105a337de65 --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/RECORD @@ -0,0 +1,20 @@ +nvidia/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufft/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufft/include/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/include/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufft/include/cudalibxt.h,sha256=9GDuRiOzJuO61zRDhIpWpF7XHp8FXSOIlHJNoIMwOZQ,4105 +nvidia/cufft/include/cufft.h,sha256=MHsb41y_Lj55kQTeXt5pn9cgia_7u3hSH4jQm08U8k0,12420 +nvidia/cufft/include/cufftXt.h,sha256=0hetmhszhh_RDjw3vmxDvRncX-jrD0NgbWPRq-oJFeA,11746 +nvidia/cufft/include/cufftw.h,sha256=DBrJQf-dnCWD-OYgdhnEzn8OiAX0U3xdteEaNdhs7mU,19412 +nvidia/cufft/lib/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 +nvidia/cufft/lib/__pycache__/__init__.cpython-310.pyc,, +nvidia/cufft/lib/libcufft.so.11,sha256=kgPaQUhKk8HaaEVnv21zJoe5sTB-MJglbLaSJdb1deQ,192713344 +nvidia/cufft/lib/libcufftw.so.11,sha256=qwbZ38-viOwrz7TBa3b_C_OycoNw0hLihgf1Ph1A7_U,1614344 +nvidia_cufft_cu12-11.0.2.54.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +nvidia_cufft_cu12-11.0.2.54.dist-info/License.txt,sha256=rW9YU_ugyg0VnQ9Y1JrkmDDC-Mk_epJki5zpCttMbM0,59262 +nvidia_cufft_cu12-11.0.2.54.dist-info/METADATA,sha256=6txhpGTOdHVhh--CJT3Tk3_RD1Q3OwfmJaJYyWndqjg,1503 +nvidia_cufft_cu12-11.0.2.54.dist-info/RECORD,, +nvidia_cufft_cu12-11.0.2.54.dist-info/WHEEL,sha256=-kQi_VMfvRQozZJT7HUPMfY-5vLo0LVTmAylNJ3Ft98,106 +nvidia_cufft_cu12-11.0.2.54.dist-info/top_level.txt,sha256=fTkAtiFuL16nUrB9ytDDtpytz2t0B4NvYTnRzwAhO14,7 diff --git a/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/WHEEL b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..06e355fe0e3ed7077903f119ae6928a17da8eb6f --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-manylinux1_x86_64 + diff --git a/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..862f7abf232cdfbb928609856247292e81c9decb --- /dev/null +++ b/venv/lib/python3.10/site-packages/nvidia_cufft_cu12-11.0.2.54.dist-info/top_level.txt @@ -0,0 +1 @@ +nvidia diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..609501c8c5930a400204046b9dfa63a8132e9086 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/__init__.py @@ -0,0 +1,133 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from dataproperty import LineBreakHandling + +from .__version__ import __author__, __copyright__, __email__, __license__, __version__ +from ._factory import TableWriterFactory +from ._function import dumps_tabledata +from ._logger import set_logger +from ._table_format import FormatAttr, TableFormat +from .error import ( + EmptyTableDataError, + EmptyTableNameError, + EmptyValueError, + NotSupportedError, + WriterNotFoundError, +) +from .style import Align, Format +from .typehint import ( + Bool, + DateTime, + Dictionary, + Infinity, + Integer, + IpAddress, + List, + Nan, + NoneType, + NullString, + RealNumber, + String, +) +from .writer import ( + AbstractTableWriter, + AsciiDocTableWriter, + BoldUnicodeTableWriter, + BorderlessTableWriter, + CssTableWriter, + CsvTableWriter, + ElasticsearchWriter, + ExcelXlsTableWriter, + ExcelXlsxTableWriter, + HtmlTableWriter, + JavaScriptTableWriter, + JsonLinesTableWriter, + JsonTableWriter, + LatexMatrixWriter, + LatexTableWriter, + LtsvTableWriter, + MarkdownTableWriter, + MediaWikiTableWriter, + NullTableWriter, + NumpyTableWriter, + PandasDataFramePickleWriter, + PandasDataFrameWriter, + PythonCodeTableWriter, + RstCsvTableWriter, + RstGridTableWriter, + RstSimpleTableWriter, + SpaceAlignedTableWriter, + SqliteTableWriter, + TomlTableWriter, + TsvTableWriter, + UnicodeTableWriter, + YamlTableWriter, +) + + +__all__ = ( + "__author__", + "__copyright__", + "__email__", + "__license__", + "__version__", + "LineBreakHandling", + "TableWriterFactory", + "dumps_tabledata", + "set_logger", + "FormatAttr", + "TableFormat", + "Align", + "Format", + "Bool", + "DateTime", + "Dictionary", + "Infinity", + "Integer", + "IpAddress", + "List", + "Nan", + "NoneType", + "NullString", + "RealNumber", + "String", + "EmptyTableDataError", + "EmptyTableNameError", + "EmptyValueError", + "NotSupportedError", + "WriterNotFoundError", + "AbstractTableWriter", + "AsciiDocTableWriter", + "BoldUnicodeTableWriter", + "BorderlessTableWriter", + "CssTableWriter", + "CsvTableWriter", + "ElasticsearchWriter", + "ExcelXlsTableWriter", + "ExcelXlsxTableWriter", + "HtmlTableWriter", + "JavaScriptTableWriter", + "JsonLinesTableWriter", + "JsonTableWriter", + "LatexMatrixWriter", + "LatexTableWriter", + "LtsvTableWriter", + "MarkdownTableWriter", + "MediaWikiTableWriter", + "NullTableWriter", + "NumpyTableWriter", + "PandasDataFramePickleWriter", + "PandasDataFrameWriter", + "PythonCodeTableWriter", + "RstCsvTableWriter", + "RstGridTableWriter", + "RstSimpleTableWriter", + "SpaceAlignedTableWriter", + "SqliteTableWriter", + "TomlTableWriter", + "TsvTableWriter", + "UnicodeTableWriter", + "YamlTableWriter", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a58f2e7385220dc4efb12b5b5c9a70a926c8523c Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/__version__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/__version__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a40dd50f4a83adfb4beacd721dc91cbb629162ec Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/__version__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_converter.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_converter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..274cb96a8db761f9a4dd6d2bf9a35d70f6bd4f8c Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_converter.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_factory.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_factory.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..448c4685097c4faba22b7f6dac10ff4f568e8766 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_factory.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_function.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_function.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1c6cda7a25d58f6a69021e14ffb1ff4bbe8517 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_function.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_table_format.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_table_format.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..37c023765fae5e678466fa450a01d75d262eb0f7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_table_format.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_typing.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_typing.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc8a01bd9d81c2ea23fee254e05b99f51e2bcc52 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/_typing.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/error.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/error.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2b58c01908bc8215d8e073e5edbb2f5eb9e6dfb Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/__pycache__/error.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/__version__.py b/venv/lib/python3.10/site-packages/pytablewriter/__version__.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed8c0e5f4906d9cf0bc7d6a4da939239bba0717 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/__version__.py @@ -0,0 +1,6 @@ +__author__ = "Tsuyoshi Hombashi" +__copyright__ = f"Copyright 2016, {__author__}" +__license__ = "MIT License" +__version__ = "1.2.0" +__maintainer__ = __author__ +__email__ = "tsuyoshi.hombashi@gmail.com" diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_converter.py b/venv/lib/python3.10/site-packages/pytablewriter/_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..2a8d70441a2dd20e4184eda5ab80bc4a5d116960 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_converter.py @@ -0,0 +1,11 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re + + +def strip_quote(text: str, value: str) -> str: + re_replace = re.compile(f"[\"']{value:s}[\"']", re.MULTILINE) + + return re_replace.sub(value, text) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_factory.py b/venv/lib/python3.10/site-packages/pytablewriter/_factory.py new file mode 100644 index 0000000000000000000000000000000000000000..1b404bc0bc54d4a47fe3fd83b41b2e1d407ae53c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_factory.py @@ -0,0 +1,274 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import os +from itertools import chain +from typing import Any, List + +import typepy + +from ._logger import logger +from ._table_format import FormatAttr, TableFormat +from .error import WriterNotFoundError +from .writer import AbstractTableWriter + + +class TableWriterFactory: + """ + A factory class of table writer classes. + """ + + @classmethod + def create_from_file_extension(cls, file_extension: str, **kwargs: Any) -> AbstractTableWriter: + """ + Create a table writer class instance from a file extension. + Supported file extensions are as follows: + + ================== =================================== + Extension Writer Class + ================== =================================== + ``".adoc"`` :py:class:`~.AsciiDocTableWriter` + ``".asciidoc"`` :py:class:`~.AsciiDocTableWriter` + ``".asc"`` :py:class:`~.AsciiDocTableWriter` + ``".css"`` :py:class:`~.CssTableWriter` + ``".csv"`` :py:class:`~.CsvTableWriter` + ``".htm"`` :py:class:`~.HtmlTableWriter` + ``".html"`` :py:class:`~.HtmlTableWriter` + ``".js"`` :py:class:`~.JavaScriptTableWriter` + ``".json"`` :py:class:`~.JsonTableWriter` + ``".jsonl"`` :py:class:`~.JsonLinesTableWriter` + ``".ltsv"`` :py:class:`~.LtsvTableWriter` + ``".ldjson"`` :py:class:`~.JsonLinesTableWriter` + ``".md"`` :py:class:`~.MarkdownTableWriter` + ``".ndjson"`` :py:class:`~.JsonLinesTableWriter` + ``".py"`` :py:class:`~.PythonCodeTableWriter` + ``".rst"`` :py:class:`~.RstGridTableWriter` + ``".tsv"`` :py:class:`~.TsvTableWriter` + ``".xls"`` :py:class:`~.ExcelXlsTableWriter` + ``".xlsx"`` :py:class:`~.ExcelXlsxTableWriter` + ``".sqlite"`` :py:class:`~.SqliteTableWriter` + ``".sqlite3"`` :py:class:`~.SqliteTableWriter` + ``".tsv"`` :py:class:`~.TsvTableWriter` + ``".toml"`` :py:class:`~.TomlTableWriter` + ``".yml"`` :py:class:`~.YamlTableWriter` + ================== =================================== + + :param str file_extension: + File extension string (case insensitive). + :param kwargs: + Keyword arguments that pass to a writer class constructor. + :return: + Writer instance that coincides with the ``file_extension``. + :rtype: + :py:class:`~pytablewriter.writer._table_writer.TableWriterInterface` + :raises pytablewriter.WriterNotFoundError: + |WriterNotFoundError_desc| the file extension. + """ + + ext = os.path.splitext(file_extension)[1] + if typepy.is_null_string(ext): + file_extension = file_extension + else: + file_extension = ext + + file_extension = file_extension.lstrip(".").lower() + + for table_format in TableFormat: + if file_extension not in table_format.file_extensions: + continue + + if table_format.format_attribute & FormatAttr.SECONDARY_EXT: + continue + + logger.debug(f"create a {table_format.writer_class} instance") + + return table_format.writer_class(**kwargs) # type: ignore + + raise WriterNotFoundError( + "\n".join( + [ + f"{file_extension:s} (unknown file extension).", + "", + "acceptable file extensions are: {}.".format(", ".join(cls.get_extensions())), + ] + ) + ) + + @classmethod + def create_from_format_name(cls, format_name: str, **kwargs: Any) -> AbstractTableWriter: + """ + Create a table writer class instance from a format name. + Supported file format names are as follows: + + ============================================= =================================== + Format name Writer Class + ============================================= =================================== + ``"adoc"`` :py:class:`~.AsciiDocTableWriter` + ``"asciidoc"`` :py:class:`~.AsciiDocTableWriter` + ``"css"`` :py:class:`~.CssTableWriter` + ``"csv"`` :py:class:`~.CsvTableWriter` + ``"elasticsearch"`` :py:class:`~.ElasticsearchWriter` + ``"excel"`` :py:class:`~.ExcelXlsxTableWriter` + ``"html"``/``"htm"`` :py:class:`~.HtmlTableWriter` + ``"javascript"``/``"js"`` :py:class:`~.JavaScriptTableWriter` + ``"json"`` :py:class:`~.JsonTableWriter` + ``"json_lines"`` :py:class:`~.JsonLinesTableWriter` + ``"latex_matrix"`` :py:class:`~.LatexMatrixWriter` + ``"latex_table"`` :py:class:`~.LatexTableWriter` + ``"ldjson"`` :py:class:`~.JsonLinesTableWriter` + ``"ltsv"`` :py:class:`~.LtsvTableWriter` + ``"markdown"``/``"md"`` :py:class:`~.MarkdownTableWriter` + ``"mediawiki"`` :py:class:`~.MediaWikiTableWriter` + ``"null"`` :py:class:`~.NullTableWriter` + ``"pandas"`` :py:class:`~.PandasDataFrameWriter` + ``"py"``/``"python"`` :py:class:`~.PythonCodeTableWriter` + ``"rst"``/``"rst_grid"``/``"rst_grid_table"`` :py:class:`~.RstGridTableWriter` + ``"rst_simple"``/``"rst_simple_table"`` :py:class:`~.RstSimpleTableWriter` + ``"rst_csv"``/``"rst_csv_table"`` :py:class:`~.RstCsvTableWriter` + ``"sqlite"`` :py:class:`~.SqliteTableWriter` + ``"ssv"`` :py:class:`~.SpaceAlignedTableWriter` + ``"tsv"`` :py:class:`~.TsvTableWriter` + ``"toml"`` :py:class:`~.TomlTableWriter` + ``"unicode"`` :py:class:`~.UnicodeTableWriter` + ``"yaml"`` :py:class:`~.YamlTableWriter` + ============================================= =================================== + + :param str format_name: + Format name string (case insensitive). + :param kwargs: + Keyword arguments that pass to a writer class constructor. + :return: + Writer instance that coincides with the ``format_name``: + :rtype: + :py:class:`~pytablewriter.writer._table_writer.TableWriterInterface` + :raises pytablewriter.WriterNotFoundError: + |WriterNotFoundError_desc| for the format. + """ + + format_name = format_name.casefold() + + for table_format in TableFormat: + if format_name in table_format.names and not ( + table_format.format_attribute & FormatAttr.SECONDARY_NAME + ): + writer = table_format.writer_class(**kwargs) # type: ignore + logger.debug(f"create a {writer.FORMAT_NAME} instance") + + return writer + + raise WriterNotFoundError( + "\n".join( + [ + f"{format_name} (unknown format name).", + "acceptable format names are: {}.".format(", ".join(cls.get_format_names())), + ] + ) + ) + + @classmethod + def get_format_names(cls) -> List[str]: + """ + :return: Available format names. + :rtype: list + + :Example: + .. code:: python + + >>> import pytablewriter as ptw + >>> for name in ptw.TableWriterFactory.get_format_names(): + ... print(name) + ... + adoc + asciidoc + bold_unicode + borderless + css + csv + elasticsearch + excel + htm + html + javascript + js + json + json_lines + jsonl + latex_matrix + latex_table + ldjson + ltsv + markdown + md + mediawiki + ndjson + null + numpy + pandas + pandas_pickle + py + python + rst + rst_csv + rst_csv_table + rst_grid + rst_grid_table + rst_simple + rst_simple_table + space_aligned + sqlite + ssv + toml + tsv + unicode + yaml + + """ + + return sorted(list(set(chain(*(table_format.names for table_format in TableFormat))))) + + @classmethod + def get_extensions(cls) -> List[str]: + """ + :return: Available file extensions. + :rtype: list + + :Example: + .. code:: python + + >>> import pytablewriter as ptw + >>> for name in ptw.TableWriterFactory.get_extensions(): + ... print(name) + ... + adoc + asc + asciidoc + css + csv + htm + html + js + json + jsonl + ldjson + ltsv + md + ndjson + py + rst + sqlite + sqlite3 + tex + toml + tsv + xls + xlsx + yml + """ + + file_extension_set = set() + for table_format in TableFormat: + for file_extension in table_format.file_extensions: + file_extension_set.add(file_extension) + + return sorted(list(file_extension_set)) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_function.py b/venv/lib/python3.10/site-packages/pytablewriter/_function.py new file mode 100644 index 0000000000000000000000000000000000000000..b8e2bfca7c0c80ce1ff4ffe283e578da91523869 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_function.py @@ -0,0 +1,84 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from datetime import datetime +from enum import Enum +from typing import Any, Optional, Type + +import dataproperty +from pathvalidate import replace_symbol +from tabledata._core import TableData + + +def quote_datetime_formatter(value: datetime) -> str: + return f'"{value.strftime(dataproperty.DefaultValue.DATETIME_FORMAT):s}"' + + +def dateutil_datetime_formatter(value: datetime) -> str: + return 'dateutil.parser.parse("{:s}")'.format( + value.strftime(dataproperty.DefaultValue.DATETIME_FORMAT) + ) + + +def dumps_tabledata(value: TableData, format_name: str = "rst_grid_table", **kwargs: Any) -> str: + """ + :param tabledata.TableData value: Tabular data to dump. + :param str format_name: + Dumped format name of tabular data. + Available formats are described in + :py:meth:`~pytablewriter.TableWriterFactory.create_from_format_name` + + :Example: + .. code:: python + + >>> dumps_tabledata(value) + .. table:: sample_data + + ====== ====== ====== + attr_a attr_b attr_c + ====== ====== ====== + 1 4.0 a + 2 2.1 bb + 3 120.9 ccc + ====== ====== ====== + """ + + from ._factory import TableWriterFactory + + if not value: + raise TypeError("value must be a tabledata.TableData instance") + + writer = TableWriterFactory.create_from_format_name(format_name) + + for attr_name, attr_value in kwargs.items(): + setattr(writer, attr_name, attr_value) + + writer.from_tabledata(value) + + return writer.dumps() + + +def normalize_enum( + value: Any, enum_class: Type[Enum], validate: bool = True, default: Optional[Enum] = None +) -> Any: + if value is None: + return default + + if isinstance(value, enum_class): + return value + + try: + return enum_class[replace_symbol(value.strip(), "_").upper()] + except AttributeError: + if validate: + raise TypeError(f"value must be a {enum_class} or a str: actual={type(value)}") + except KeyError: + if validate: + raise ValueError( + "invalid valid found: expected={}, actual={}".format( + "/".join(item.name for item in enum_class), value + ) + ) + + return value diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_logger/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0ee56daf1215762d2e34ed9899dda89145f1ea3 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_logger/__init__.py @@ -0,0 +1,4 @@ +from ._logger import WriterLogger, logger, set_logger + + +__all__ = ("WriterLogger", "logger", "set_logger") diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_logger/_logger.py b/venv/lib/python3.10/site-packages/pytablewriter/_logger/_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..2d213966e3657d331cedf24575bbb16264e6b67d --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_logger/_logger.py @@ -0,0 +1,117 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from typing import TYPE_CHECKING, List + +import dataproperty +from mbstrdecoder import MultiByteStrDecoder + +from ._null_logger import NullLogger # type: ignore + + +if TYPE_CHECKING: + from ..writer import AbstractTableWriter + +MODULE_NAME = "pytablewriter" + +try: + from loguru import logger + + logger.disable(MODULE_NAME) +except ImportError: + logger = NullLogger() + + +def set_logger(is_enable: bool, propagation_depth: int = 1) -> None: + if is_enable: + logger.enable(MODULE_NAME) + else: + logger.disable(MODULE_NAME) + + if propagation_depth <= 0: + return + + dataproperty.set_logger(is_enable, propagation_depth - 1) + + try: + import simplesqlite + + simplesqlite.set_logger(is_enable, propagation_depth - 1) + except ImportError: + pass + + try: + import pytablereader + + pytablereader.set_logger(is_enable, propagation_depth - 1) + except ImportError: + pass + + +class WriterLogger: + @property + def logger(self): # type: ignore + return self.__logger + + def __init__(self, writer: "AbstractTableWriter") -> None: + self.__writer = writer + self.__logger = logger + + self.logger.debug(f"created WriterLogger: format={writer.format_name}") + + def __enter__(self) -> "WriterLogger": + self.logging_start_write() + return self + + def __exit__(self, *exc): # type: ignore + self.logging_complete_write() + return False + + def logging_start_write(self) -> None: + log_entry_list = [ + self.__get_format_name_message(), + self.__get_table_name_message(), + f"headers={self.__writer.headers}", + ] + + try: + log_entry_list.append(f"rows={len(self.__writer.value_matrix)}") + except (TypeError, AttributeError): + log_entry_list.append("rows=NaN") + + log_entry_list.append(self.__get_typehint_message()) + log_entry_list.extend(self.__get_extra_log_entry_list()) + + self.logger.debug("start write table: {}".format(", ".join(log_entry_list))) + + def logging_complete_write(self) -> None: + log_entry_list = [self.__get_format_name_message(), self.__get_table_name_message()] + log_entry_list.extend(self.__get_extra_log_entry_list()) + + self.logger.debug("complete write table: {}".format(", ".join(log_entry_list))) + + def __get_format_name_message(self) -> str: + return f"format={self.__writer.format_name:s}" + + def __get_table_name_message(self) -> str: + if self.__writer.table_name: + table_name = MultiByteStrDecoder(self.__writer.table_name).unicode_str + else: + table_name = "" + + return f"table-name='{table_name}'" + + def __get_extra_log_entry_list(self) -> List[str]: + if self.__writer._iter_count is None: + return [] + + return [f"iteration={self.__writer._iter_count}/{self.__writer.iteration_length}"] + + def __get_typehint_message(self) -> str: + try: + return "type-hints={}".format( + [type_hint(None).typename for type_hint in self.__writer.type_hints] + ) + except (TypeError, AttributeError): + return "type-hints=[]" diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_logger/_null_logger.py b/venv/lib/python3.10/site-packages/pytablewriter/_logger/_null_logger.py new file mode 100644 index 0000000000000000000000000000000000000000..1de427a45ad4986de92d71eea6a657aceb095766 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_logger/_null_logger.py @@ -0,0 +1,44 @@ +# type: ignore + + +class NullLogger: + level_name = None + + def remove(self, handler_id=None): # pragma: no cover + pass + + def add(self, sink, **kwargs): # pragma: no cover + pass + + def disable(self, name): # pragma: no cover + pass + + def enable(self, name): # pragma: no cover + pass + + def critical(self, __message, *args, **kwargs): # pragma: no cover + pass + + def debug(self, __message, *args, **kwargs): # pragma: no cover + pass + + def error(self, __message, *args, **kwargs): # pragma: no cover + pass + + def exception(self, __message, *args, **kwargs): # pragma: no cover + pass + + def info(self, __message, *args, **kwargs): # pragma: no cover + pass + + def log(self, __level, __message, *args, **kwargs): # pragma: no cover + pass + + def success(self, __message, *args, **kwargs): # pragma: no cover + pass + + def trace(self, __message, *args, **kwargs): # pragma: no cover + pass + + def warning(self, __message, *args, **kwargs): # pragma: no cover + pass diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_table_format.py b/venv/lib/python3.10/site-packages/pytablewriter/_table_format.py new file mode 100644 index 0000000000000000000000000000000000000000..785a3b4a49a5bd5331caf857bf64f1aa46c11965 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_table_format.py @@ -0,0 +1,353 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import enum +from typing import List, Optional, Sequence + +from .writer import ( + AbstractTableWriter, + AsciiDocTableWriter, + BoldUnicodeTableWriter, + BorderlessTableWriter, + CssTableWriter, + CsvTableWriter, + ElasticsearchWriter, + ExcelXlsTableWriter, + ExcelXlsxTableWriter, + HtmlTableWriter, + JavaScriptTableWriter, + JsonLinesTableWriter, + JsonTableWriter, + LatexMatrixWriter, + LatexTableWriter, + LtsvTableWriter, + MarkdownTableWriter, + MediaWikiTableWriter, + NullTableWriter, + NumpyTableWriter, + PandasDataFramePickleWriter, + PandasDataFrameWriter, + PythonCodeTableWriter, + RstCsvTableWriter, + RstGridTableWriter, + RstSimpleTableWriter, + SpaceAlignedTableWriter, + SqliteTableWriter, + TomlTableWriter, + TsvTableWriter, + UnicodeTableWriter, + YamlTableWriter, +) + + +class FormatAttr: + """ + Bitmaps to represent table attributes. + """ + + NONE = 1 << 1 + + #: Can create a file with the format. + FILE = 1 << 2 + + #: Table format that can represent as a text. + TEXT = 1 << 3 + + #: Table format that can represent as a binary file. + BIN = 1 << 4 + + #: Can create a source code (variables definition) + #: one of the programming language. + SOURCECODE = 1 << 5 + + #: Can call API for external service. + API = 1 << 6 + + SECONDARY_EXT = 1 << 10 + SECONDARY_NAME = 1 << 11 + + +@enum.unique +class TableFormat(enum.Enum): + """ + Enum to represent table format attributes. + """ + + ASCIIDOC = ( + [AsciiDocTableWriter.FORMAT_NAME, "adoc"], + AsciiDocTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["adoc", "asciidoc", "asc"], + ) + CSV = ([CsvTableWriter.FORMAT_NAME], CsvTableWriter, FormatAttr.FILE | FormatAttr.TEXT, ["csv"]) + CSS = ( + [CssTableWriter.FORMAT_NAME], + CssTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["css"], + ) + ELASTICSEARCH = ( + [ElasticsearchWriter.FORMAT_NAME], # type: ignore + ElasticsearchWriter, + FormatAttr.API, + [], + ) + EXCEL_XLSX = ( + [ExcelXlsxTableWriter.FORMAT_NAME], + ExcelXlsxTableWriter, + FormatAttr.FILE | FormatAttr.BIN, + ["xlsx"], + ) + EXCEL_XLS = ( + [ExcelXlsTableWriter.FORMAT_NAME], + ExcelXlsTableWriter, + FormatAttr.FILE | FormatAttr.BIN | FormatAttr.SECONDARY_NAME, + ["xls"], + ) + HTML = ( + [HtmlTableWriter.FORMAT_NAME, "htm"], + HtmlTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["html", "htm"], + ) + JAVASCRIPT = ( + [JavaScriptTableWriter.FORMAT_NAME, "js"], + JavaScriptTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE, + ["js"], + ) + JSON = ( + [JsonTableWriter.FORMAT_NAME], + JsonTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["json"], + ) + JSON_LINES = ( + [JsonLinesTableWriter.FORMAT_NAME, "jsonl", "ldjson", "ndjson"], + JsonLinesTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["jsonl", "ldjson", "ndjson"], + ) + LATEX_MATRIX = ( + [LatexMatrixWriter.FORMAT_NAME], + LatexMatrixWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["tex"], + ) + LATEX_TABLE = ( + [LatexTableWriter.FORMAT_NAME], + LatexTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SECONDARY_EXT, + ["tex"], + ) + LTSV = ( + [LtsvTableWriter.FORMAT_NAME], + LtsvTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["ltsv"], + ) + MARKDOWN = ( + [MarkdownTableWriter.FORMAT_NAME, "md"], + MarkdownTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["md"], + ) + MEDIAWIKI = ( + [MediaWikiTableWriter.FORMAT_NAME], # type: ignore + MediaWikiTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + [], + ) + NULL = ( + [NullTableWriter.FORMAT_NAME], # type: ignore + NullTableWriter, + FormatAttr.NONE, + [], + ) + NUMPY = ( + [NumpyTableWriter.FORMAT_NAME], + NumpyTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE | FormatAttr.SECONDARY_EXT, + ["py"], + ) + PANDAS = ( + [PandasDataFrameWriter.FORMAT_NAME], + PandasDataFrameWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE | FormatAttr.SECONDARY_EXT, + ["py"], + ) + PANDAS_PICKLE = ( + [PandasDataFramePickleWriter.FORMAT_NAME], # type: ignore + PandasDataFramePickleWriter, + FormatAttr.FILE | FormatAttr.BIN, + [], + ) + PYTHON = ( + [PythonCodeTableWriter.FORMAT_NAME, "py"], + PythonCodeTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SOURCECODE, + ["py"], + ) + RST_CSV_TABLE = ( + [RstCsvTableWriter.FORMAT_NAME, "rst_csv"], + RstCsvTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SECONDARY_EXT, + ["rst"], + ) + RST_GRID_TABLE = ( + [RstGridTableWriter.FORMAT_NAME, "rst_grid", "rst"], + RstGridTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["rst"], + ) + RST_SIMPLE_TABLE = ( + [RstSimpleTableWriter.FORMAT_NAME, "rst_simple"], + RstSimpleTableWriter, + FormatAttr.FILE | FormatAttr.TEXT | FormatAttr.SECONDARY_EXT, + ["rst"], + ) + SPACE_ALIGNED = ( + [SpaceAlignedTableWriter.FORMAT_NAME, "ssv"], # type: ignore + SpaceAlignedTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + [], + ) + SQLITE = ( + [SqliteTableWriter.FORMAT_NAME], + SqliteTableWriter, + FormatAttr.FILE | FormatAttr.BIN, + ["sqlite", "sqlite3"], + ) + TOML = ( + [TomlTableWriter.FORMAT_NAME], + TomlTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["toml"], + ) + TSV = ([TsvTableWriter.FORMAT_NAME], TsvTableWriter, FormatAttr.FILE | FormatAttr.TEXT, ["tsv"]) + UNICODE = ( + [UnicodeTableWriter.FORMAT_NAME], # type: ignore + UnicodeTableWriter, + FormatAttr.TEXT, + [], + ) + YAML = ( + [YamlTableWriter.FORMAT_NAME], + YamlTableWriter, + FormatAttr.FILE | FormatAttr.TEXT, + ["yml"], + ) + BOLD_UNICODE = ( + [BoldUnicodeTableWriter.FORMAT_NAME], # type: ignore + BoldUnicodeTableWriter, + FormatAttr.TEXT, + [], + ) + BORDERLESS = ( + [BorderlessTableWriter.FORMAT_NAME], # type: ignore + BorderlessTableWriter, + FormatAttr.TEXT, + [], + ) + + @property + def names(self) -> List[str]: + """ + List[str]: Names associated with the table format. + """ + + return self.__names + + @property + def writer_class(self) -> AbstractTableWriter: + """ + Type[AbstractTableWriter]: Table writer class object associated with the table format. + """ + + return self.__writer_class + + @property + def format_attribute(self) -> int: + """ + FormatAttr: Table attributes bitmap. + """ + + return self.__format_attribute + + @property + def file_extensions(self) -> List[str]: + """ + List[str]: File extensions associated with the table format. + """ + + return self.__file_extensions + + def __init__( + self, + names: Sequence[str], + writer_class: AbstractTableWriter, + format_attribute: int, + file_extensions: Sequence[str], + ) -> None: + self.__names = list(names) + self.__writer_class = writer_class + self.__format_attribute = format_attribute + self.__file_extensions = list(file_extensions) + + @classmethod + def find_all_attr(cls, format_attribute: int) -> List["TableFormat"]: + """Searching table formats that have specific attributes. + + Args: + format_attribute (FormatAttr): + Table format attributes to look for. + + Returns: + List[TableFormat]: Table formats that matched the attribute. + """ + + return [ + table_format + for table_format in TableFormat + if table_format.format_attribute & format_attribute + ] + + @classmethod + def from_name(cls, format_name: str) -> Optional["TableFormat"]: + """Get a table format from a format name. + + Args: + format_name (str): Table format specifier. + + Returns: + Optional[TableFormat]: A table format enum value corresponding to the ``format_name``. + """ + + format_name = format_name.casefold().strip() + + for table_format in TableFormat: + if format_name in table_format.names: + return table_format + + return None + + @classmethod + def from_file_extension(cls, file_extension: str) -> Optional["TableFormat"]: + """Get a table format from a file extension. + + Args: + file_extension (str): File extension. + + Returns: + Optional[TableFormat]: + A table format enum value corresponding to the ``file_extension``. + """ + + ext = file_extension.lower().strip().lstrip(".") + + for table_format in TableFormat: + if ext in table_format.file_extensions: + return table_format + + return None diff --git a/venv/lib/python3.10/site-packages/pytablewriter/_typing.py b/venv/lib/python3.10/site-packages/pytablewriter/_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..ff4ec48320d495d703933b282718c6bd8035c3e8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/_typing.py @@ -0,0 +1,2855 @@ +# type: ignore + +""" +source code from: python/typing/typing_extensions/src_py3/typing_extensions.py +tag: 3.10.0.2 + +Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, +2011, 2012, 2013, 2014 Python Software Foundation; All Rights Reserved + +https://github.com/python/typing/blob/3.10.0.2/LICENSE +""" + +import abc +import collections +import contextlib +import sys +import typing +import collections.abc as collections_abc +import operator + +# These are used by Protocol implementation +# We use internal typing helpers here, but this significantly reduces +# code duplication. (Also this is only until Protocol is in typing.) +from typing import Generic, Callable, TypeVar, Tuple + +# After PEP 560, internal typing API was substantially reworked. +# This is especially important for Protocol class which uses internal APIs +# quite extensivelly. +PEP_560 = sys.version_info[:3] >= (3, 7, 0) + +if PEP_560: + GenericMeta = TypingMeta = type + from typing import _GenericAlias +else: + from typing import GenericMeta, TypingMeta +OLD_GENERICS = False +try: + from typing import _type_vars, _next_in_mro, _type_check +except ImportError: + OLD_GENERICS = True +try: + from typing import _subs_tree # noqa + SUBS_TREE = True +except ImportError: + SUBS_TREE = False +try: + from typing import _tp_cache +except ImportError: + def _tp_cache(x): + return x +try: + from typing import _TypingEllipsis, _TypingEmpty +except ImportError: + class _TypingEllipsis: + pass + + class _TypingEmpty: + pass + + +# The two functions below are copies of typing internal helpers. +# They are needed by _ProtocolMeta + + +def _no_slots_copy(dct): + dict_copy = dict(dct) + if '__slots__' in dict_copy: + for slot in dict_copy['__slots__']: + dict_copy.pop(slot, None) + return dict_copy + + +def _check_generic(cls, parameters): + if not cls.__parameters__: + raise TypeError("%s is not a generic class" % repr(cls)) + alen = len(parameters) + elen = len(cls.__parameters__) + if alen != elen: + raise TypeError("Too %s parameters for %s; actual %s, expected %s" % + ("many" if alen > elen else "few", repr(cls), alen, elen)) + + +if hasattr(typing, '_generic_new'): + _generic_new = typing._generic_new +else: + # Note: The '_generic_new(...)' function is used as a part of the + # process of creating a generic type and was added to the typing module + # as of Python 3.5.3. + # + # We've defined '_generic_new(...)' below to exactly match the behavior + # implemented in older versions of 'typing' bundled with Python 3.5.0 to + # 3.5.2. This helps eliminate redundancy when defining collection types + # like 'Deque' later. + # + # See https://github.com/python/typing/pull/308 for more details -- in + # particular, compare and contrast the definition of types like + # 'typing.List' before and after the merge. + + def _generic_new(base_cls, cls, *args, **kwargs): + return base_cls.__new__(cls, *args, **kwargs) + +# See https://github.com/python/typing/pull/439 +if hasattr(typing, '_geqv'): + from typing import _geqv + _geqv_defined = True +else: + _geqv = None + _geqv_defined = False + +if sys.version_info[:2] >= (3, 6): + import _collections_abc + _check_methods_in_mro = _collections_abc._check_methods +else: + def _check_methods_in_mro(C, *methods): + mro = C.__mro__ + for method in methods: + for B in mro: + if method in B.__dict__: + if B.__dict__[method] is None: + return NotImplemented + break + else: + return NotImplemented + return True + + +# Please keep __all__ alphabetized within each category. +__all__ = [ + # Super-special typing primitives. + 'ClassVar', + 'Concatenate', + 'Final', + 'ParamSpec', + 'Type', + + # ABCs (from collections.abc). + # The following are added depending on presence + # of their non-generic counterparts in stdlib: + # 'Awaitable', + # 'AsyncIterator', + # 'AsyncIterable', + # 'Coroutine', + # 'AsyncGenerator', + # 'AsyncContextManager', + # 'ChainMap', + + # Concrete collection types. + 'ContextManager', + 'Counter', + 'Deque', + 'DefaultDict', + 'OrderedDict', + 'TypedDict', + + # Structural checks, a.k.a. protocols. + 'SupportsIndex', + + # One-off things. + 'final', + 'IntVar', + 'Literal', + 'NewType', + 'overload', + 'Text', + 'TypeAlias', + 'TypeGuard', + 'TYPE_CHECKING', +] + +# Annotated relies on substitution trees of pep 560. It will not work for +# versions of typing older than 3.5.3 +HAVE_ANNOTATED = PEP_560 or SUBS_TREE + +if PEP_560: + __all__.extend(["get_args", "get_origin", "get_type_hints"]) + +if HAVE_ANNOTATED: + __all__.append("Annotated") + +# Protocols are hard to backport to the original version of typing 3.5.0 +HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0) + +if HAVE_PROTOCOLS: + __all__.extend(['Protocol', 'runtime', 'runtime_checkable']) + + +# TODO +if hasattr(typing, 'NoReturn'): + NoReturn = typing.NoReturn +elif hasattr(typing, '_FinalTypingBase'): + class _NoReturn(typing._FinalTypingBase, _root=True): + """Special type indicating functions that never return. + Example:: + + from typing import NoReturn + + def stop() -> NoReturn: + raise Exception('no way') + + This type is invalid in other positions, e.g., ``List[NoReturn]`` + will fail in static type checkers. + """ + __slots__ = () + + def __instancecheck__(self, obj): + raise TypeError("NoReturn cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("NoReturn cannot be used with issubclass().") + + NoReturn = _NoReturn(_root=True) +else: + class _NoReturnMeta(typing.TypingMeta): + """Metaclass for NoReturn""" + def __new__(cls, name, bases, namespace, _root=False): + return super().__new__(cls, name, bases, namespace, _root=_root) + + def __instancecheck__(self, obj): + raise TypeError("NoReturn cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("NoReturn cannot be used with issubclass().") + + class NoReturn(typing.Final, metaclass=_NoReturnMeta, _root=True): + """Special type indicating functions that never return. + Example:: + + from typing import NoReturn + + def stop() -> NoReturn: + raise Exception('no way') + + This type is invalid in other positions, e.g., ``List[NoReturn]`` + will fail in static type checkers. + """ + __slots__ = () + + +# Some unconstrained type variables. These are used by the container types. +# (These are not for export.) +T = typing.TypeVar('T') # Any type. +KT = typing.TypeVar('KT') # Key type. +VT = typing.TypeVar('VT') # Value type. +T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers. +V_co = typing.TypeVar('V_co', covariant=True) # Any type covariant containers. +VT_co = typing.TypeVar('VT_co', covariant=True) # Value type covariant containers. +T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant. + + +if hasattr(typing, 'ClassVar'): + ClassVar = typing.ClassVar +elif hasattr(typing, '_FinalTypingBase'): + class _ClassVar(typing._FinalTypingBase, _root=True): + """Special type construct to mark class variables. + + An annotation wrapped in ClassVar indicates that a given + attribute is intended to be used as a class variable and + should not be set on instances of that class. Usage:: + + class Starship: + stats: ClassVar[Dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + ClassVar accepts only types and cannot be further subscribed. + + Note that ClassVar is not a class itself, and should not + be used with isinstance() or issubclass(). + """ + + __slots__ = ('__type__',) + + def __init__(self, tp=None, **kwds): + self.__type__ = tp + + def __getitem__(self, item): + cls = type(self) + if self.__type__ is None: + return cls(typing._type_check(item, + '{} accepts only single type.'.format(cls.__name__[1:])), + _root=True) + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + def _eval_type(self, globalns, localns): + new_tp = typing._eval_type(self.__type__, globalns, localns) + if new_tp == self.__type__: + return self + return type(self)(new_tp, _root=True) + + def __repr__(self): + r = super().__repr__() + if self.__type__ is not None: + r += '[{}]'.format(typing._type_repr(self.__type__)) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__type__)) + + def __eq__(self, other): + if not isinstance(other, _ClassVar): + return NotImplemented + if self.__type__ is not None: + return self.__type__ == other.__type__ + return self is other + + ClassVar = _ClassVar(_root=True) +else: + class _ClassVarMeta(typing.TypingMeta): + """Metaclass for ClassVar""" + + def __new__(cls, name, bases, namespace, tp=None, _root=False): + self = super().__new__(cls, name, bases, namespace, _root=_root) + if tp is not None: + self.__type__ = tp + return self + + def __instancecheck__(self, obj): + raise TypeError("ClassVar cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("ClassVar cannot be used with issubclass().") + + def __getitem__(self, item): + cls = type(self) + if self.__type__ is not None: + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + param = typing._type_check( + item, + '{} accepts only single type.'.format(cls.__name__[1:])) + return cls(self.__name__, self.__bases__, + dict(self.__dict__), tp=param, _root=True) + + def _eval_type(self, globalns, localns): + new_tp = typing._eval_type(self.__type__, globalns, localns) + if new_tp == self.__type__: + return self + return type(self)(self.__name__, self.__bases__, + dict(self.__dict__), tp=self.__type__, + _root=True) + + def __repr__(self): + r = super().__repr__() + if self.__type__ is not None: + r += '[{}]'.format(typing._type_repr(self.__type__)) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__type__)) + + def __eq__(self, other): + if not isinstance(other, ClassVar): + return NotImplemented + if self.__type__ is not None: + return self.__type__ == other.__type__ + return self is other + + class ClassVar(typing.Final, metaclass=_ClassVarMeta, _root=True): + """Special type construct to mark class variables. + + An annotation wrapped in ClassVar indicates that a given + attribute is intended to be used as a class variable and + should not be set on instances of that class. Usage:: + + class Starship: + stats: ClassVar[Dict[str, int]] = {} # class variable + damage: int = 10 # instance variable + + ClassVar accepts only types and cannot be further subscribed. + + Note that ClassVar is not a class itself, and should not + be used with isinstance() or issubclass(). + """ + + __type__ = None + +# On older versions of typing there is an internal class named "Final". +if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7): + Final = typing.Final +elif sys.version_info[:2] >= (3, 7): + class _FinalForm(typing._SpecialForm, _root=True): + + def __repr__(self): + return 'typing_extensions.' + self._name + + def __getitem__(self, parameters): + item = typing._type_check(parameters, + '{} accepts only single type'.format(self._name)) + return _GenericAlias(self, (item,)) + + Final = _FinalForm('Final', + doc="""A special typing construct to indicate that a name + cannot be re-assigned or overridden in a subclass. + For example: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties.""") +elif hasattr(typing, '_FinalTypingBase'): + class _Final(typing._FinalTypingBase, _root=True): + """A special typing construct to indicate that a name + cannot be re-assigned or overridden in a subclass. + For example: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. + """ + + __slots__ = ('__type__',) + + def __init__(self, tp=None, **kwds): + self.__type__ = tp + + def __getitem__(self, item): + cls = type(self) + if self.__type__ is None: + return cls(typing._type_check(item, + '{} accepts only single type.'.format(cls.__name__[1:])), + _root=True) + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + def _eval_type(self, globalns, localns): + new_tp = typing._eval_type(self.__type__, globalns, localns) + if new_tp == self.__type__: + return self + return type(self)(new_tp, _root=True) + + def __repr__(self): + r = super().__repr__() + if self.__type__ is not None: + r += '[{}]'.format(typing._type_repr(self.__type__)) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__type__)) + + def __eq__(self, other): + if not isinstance(other, _Final): + return NotImplemented + if self.__type__ is not None: + return self.__type__ == other.__type__ + return self is other + + Final = _Final(_root=True) +else: + class _FinalMeta(typing.TypingMeta): + """Metaclass for Final""" + + def __new__(cls, name, bases, namespace, tp=None, _root=False): + self = super().__new__(cls, name, bases, namespace, _root=_root) + if tp is not None: + self.__type__ = tp + return self + + def __instancecheck__(self, obj): + raise TypeError("Final cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("Final cannot be used with issubclass().") + + def __getitem__(self, item): + cls = type(self) + if self.__type__ is not None: + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + param = typing._type_check( + item, + '{} accepts only single type.'.format(cls.__name__[1:])) + return cls(self.__name__, self.__bases__, + dict(self.__dict__), tp=param, _root=True) + + def _eval_type(self, globalns, localns): + new_tp = typing._eval_type(self.__type__, globalns, localns) + if new_tp == self.__type__: + return self + return type(self)(self.__name__, self.__bases__, + dict(self.__dict__), tp=self.__type__, + _root=True) + + def __repr__(self): + r = super().__repr__() + if self.__type__ is not None: + r += '[{}]'.format(typing._type_repr(self.__type__)) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__type__)) + + def __eq__(self, other): + if not isinstance(other, Final): + return NotImplemented + if self.__type__ is not None: + return self.__type__ == other.__type__ + return self is other + + class Final(typing.Final, metaclass=_FinalMeta, _root=True): + """A special typing construct to indicate that a name + cannot be re-assigned or overridden in a subclass. + For example: + + MAX_SIZE: Final = 9000 + MAX_SIZE += 1 # Error reported by type checker + + class Connection: + TIMEOUT: Final[int] = 10 + class FastConnector(Connection): + TIMEOUT = 1 # Error reported by type checker + + There is no runtime checking of these properties. + """ + + __type__ = None + + +if hasattr(typing, 'final'): + final = typing.final +else: + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. + """ + return f + + +def IntVar(name): + return TypeVar(name) + + +if hasattr(typing, 'Literal'): + Literal = typing.Literal +elif sys.version_info[:2] >= (3, 7): + class _LiteralForm(typing._SpecialForm, _root=True): + + def __repr__(self): + return 'typing_extensions.' + self._name + + def __getitem__(self, parameters): + return _GenericAlias(self, parameters) + + Literal = _LiteralForm('Literal', + doc="""A type that can be used to indicate to type checkers + that the corresponding value has a value literally equivalent + to the provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to + the value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime + checking verifying that the parameter is actually a value + instead of a type.""") +elif hasattr(typing, '_FinalTypingBase'): + class _Literal(typing._FinalTypingBase, _root=True): + """A type that can be used to indicate to type checkers that the + corresponding value has a value literally equivalent to the + provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to the + value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime checking + verifying that the parameter is actually a value instead of a type. + """ + + __slots__ = ('__values__',) + + def __init__(self, values=None, **kwds): + self.__values__ = values + + def __getitem__(self, values): + cls = type(self) + if self.__values__ is None: + if not isinstance(values, tuple): + values = (values,) + return cls(values, _root=True) + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + def _eval_type(self, globalns, localns): + return self + + def __repr__(self): + r = super().__repr__() + if self.__values__ is not None: + r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__values__)) + + def __eq__(self, other): + if not isinstance(other, _Literal): + return NotImplemented + if self.__values__ is not None: + return self.__values__ == other.__values__ + return self is other + + Literal = _Literal(_root=True) +else: + class _LiteralMeta(typing.TypingMeta): + """Metaclass for Literal""" + + def __new__(cls, name, bases, namespace, values=None, _root=False): + self = super().__new__(cls, name, bases, namespace, _root=_root) + if values is not None: + self.__values__ = values + return self + + def __instancecheck__(self, obj): + raise TypeError("Literal cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("Literal cannot be used with issubclass().") + + def __getitem__(self, item): + cls = type(self) + if self.__values__ is not None: + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + if not isinstance(item, tuple): + item = (item,) + return cls(self.__name__, self.__bases__, + dict(self.__dict__), values=item, _root=True) + + def _eval_type(self, globalns, localns): + return self + + def __repr__(self): + r = super().__repr__() + if self.__values__ is not None: + r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__))) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__values__)) + + def __eq__(self, other): + if not isinstance(other, Literal): + return NotImplemented + if self.__values__ is not None: + return self.__values__ == other.__values__ + return self is other + + class Literal(typing.Final, metaclass=_LiteralMeta, _root=True): + """A type that can be used to indicate to type checkers that the + corresponding value has a value literally equivalent to the + provided parameter. For example: + + var: Literal[4] = 4 + + The type checker understands that 'var' is literally equal to the + value 4 and no other value. + + Literal[...] cannot be subclassed. There is no runtime checking + verifying that the parameter is actually a value instead of a type. + """ + + __values__ = None + + +def _overload_dummy(*args, **kwds): + """Helper for @overload to raise when called.""" + raise NotImplementedError( + "You should not call an overloaded function. " + "A series of @overload-decorated functions " + "outside a stub module should always be followed " + "by an implementation that is not @overload-ed.") + + +def overload(func): + """Decorator for overloaded functions/methods. + + In a stub file, place two or more stub definitions for the same + function in a row, each decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + + In a non-stub file (i.e. a regular .py file), do the same but + follow it with an implementation. The implementation should *not* + be decorated with @overload. For example: + + @overload + def utf8(value: None) -> None: ... + @overload + def utf8(value: bytes) -> bytes: ... + @overload + def utf8(value: str) -> bytes: ... + def utf8(value): + # implementation goes here + """ + return _overload_dummy + + +# This is not a real generic class. Don't use outside annotations. +if hasattr(typing, 'Type'): + Type = typing.Type +else: + # Internal type variable used for Type[]. + CT_co = typing.TypeVar('CT_co', covariant=True, bound=type) + + class Type(typing.Generic[CT_co], extra=type): + """A special construct usable to annotate class objects. + + For example, suppose we have the following classes:: + + class User: ... # Abstract base for User classes + class BasicUser(User): ... + class ProUser(User): ... + class TeamUser(User): ... + + And a function that takes a class argument that's a subclass of + User and returns an instance of the corresponding class:: + + U = TypeVar('U', bound=User) + def new_user(user_class: Type[U]) -> U: + user = user_class() + # (Here we could write the user object to a database) + return user + joe = new_user(BasicUser) + + At this point the type checker knows that joe has type BasicUser. + """ + + __slots__ = () + + +# Various ABCs mimicking those in collections.abc. +# A few are simply re-exported for completeness. + +def _define_guard(type_name): + """ + Returns True if the given type isn't defined in typing but + is defined in collections_abc. + + Adds the type to __all__ if the collection is found in either + typing or collection_abc. + """ + if hasattr(typing, type_name): + __all__.append(type_name) + globals()[type_name] = getattr(typing, type_name) + return False + elif hasattr(collections_abc, type_name): + __all__.append(type_name) + return True + else: + return False + + +class _ExtensionsGenericMeta(GenericMeta): + def __subclasscheck__(self, subclass): + """This mimics a more modern GenericMeta.__subclasscheck__() logic + (that does not have problems with recursion) to work around interactions + between collections, typing, and typing_extensions on older + versions of Python, see https://github.com/python/typing/issues/501. + """ + if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0): + if self.__origin__ is not None: + if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: + raise TypeError("Parameterized generics cannot be used with class " + "or instance checks") + return False + if not self.__extra__: + return super().__subclasscheck__(subclass) + res = self.__extra__.__subclasshook__(subclass) + if res is not NotImplemented: + return res + if self.__extra__ in subclass.__mro__: + return True + for scls in self.__extra__.__subclasses__(): + if isinstance(scls, GenericMeta): + continue + if issubclass(subclass, scls): + return True + return False + + +if _define_guard('Awaitable'): + class Awaitable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta, + extra=collections_abc.Awaitable): + __slots__ = () + + +if _define_guard('Coroutine'): + class Coroutine(Awaitable[V_co], typing.Generic[T_co, T_contra, V_co], + metaclass=_ExtensionsGenericMeta, + extra=collections_abc.Coroutine): + __slots__ = () + + +if _define_guard('AsyncIterable'): + class AsyncIterable(typing.Generic[T_co], + metaclass=_ExtensionsGenericMeta, + extra=collections_abc.AsyncIterable): + __slots__ = () + + +if _define_guard('AsyncIterator'): + class AsyncIterator(AsyncIterable[T_co], + metaclass=_ExtensionsGenericMeta, + extra=collections_abc.AsyncIterator): + __slots__ = () + + +if hasattr(typing, 'Deque'): + Deque = typing.Deque +elif _geqv_defined: + class Deque(collections.deque, typing.MutableSequence[T], + metaclass=_ExtensionsGenericMeta, + extra=collections.deque): + __slots__ = () + + def __new__(cls, *args, **kwds): + if _geqv(cls, Deque): + return collections.deque(*args, **kwds) + return _generic_new(collections.deque, cls, *args, **kwds) +else: + class Deque(collections.deque, typing.MutableSequence[T], + metaclass=_ExtensionsGenericMeta, + extra=collections.deque): + __slots__ = () + + def __new__(cls, *args, **kwds): + if cls._gorg is Deque: + return collections.deque(*args, **kwds) + return _generic_new(collections.deque, cls, *args, **kwds) + + +if hasattr(typing, 'ContextManager'): + ContextManager = typing.ContextManager +elif hasattr(contextlib, 'AbstractContextManager'): + class ContextManager(typing.Generic[T_co], + metaclass=_ExtensionsGenericMeta, + extra=contextlib.AbstractContextManager): + __slots__ = () +else: + class ContextManager(typing.Generic[T_co]): + __slots__ = () + + def __enter__(self): + return self + + @abc.abstractmethod + def __exit__(self, exc_type, exc_value, traceback): + return None + + @classmethod + def __subclasshook__(cls, C): + if cls is ContextManager: + # In Python 3.6+, it is possible to set a method to None to + # explicitly indicate that the class does not implement an ABC + # (https://bugs.python.org/issue25958), but we do not support + # that pattern here because this fallback class is only used + # in Python 3.5 and earlier. + if (any("__enter__" in B.__dict__ for B in C.__mro__) and + any("__exit__" in B.__dict__ for B in C.__mro__)): + return True + return NotImplemented + + +if hasattr(typing, 'AsyncContextManager'): + AsyncContextManager = typing.AsyncContextManager + __all__.append('AsyncContextManager') +elif hasattr(contextlib, 'AbstractAsyncContextManager'): + class AsyncContextManager(typing.Generic[T_co], + metaclass=_ExtensionsGenericMeta, + extra=contextlib.AbstractAsyncContextManager): + __slots__ = () + + __all__.append('AsyncContextManager') +elif sys.version_info[:2] >= (3, 5): + exec(""" +class AsyncContextManager(typing.Generic[T_co]): + __slots__ = () + + async def __aenter__(self): + return self + + @abc.abstractmethod + async def __aexit__(self, exc_type, exc_value, traceback): + return None + + @classmethod + def __subclasshook__(cls, C): + if cls is AsyncContextManager: + return _check_methods_in_mro(C, "__aenter__", "__aexit__") + return NotImplemented + +__all__.append('AsyncContextManager') +""") + + +if hasattr(typing, 'DefaultDict'): + DefaultDict = typing.DefaultDict +elif _geqv_defined: + class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], + metaclass=_ExtensionsGenericMeta, + extra=collections.defaultdict): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if _geqv(cls, DefaultDict): + return collections.defaultdict(*args, **kwds) + return _generic_new(collections.defaultdict, cls, *args, **kwds) +else: + class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT], + metaclass=_ExtensionsGenericMeta, + extra=collections.defaultdict): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if cls._gorg is DefaultDict: + return collections.defaultdict(*args, **kwds) + return _generic_new(collections.defaultdict, cls, *args, **kwds) + + +if hasattr(typing, 'OrderedDict'): + OrderedDict = typing.OrderedDict +elif (3, 7, 0) <= sys.version_info[:3] < (3, 7, 2): + OrderedDict = typing._alias(collections.OrderedDict, (KT, VT)) +elif _geqv_defined: + class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT], + metaclass=_ExtensionsGenericMeta, + extra=collections.OrderedDict): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if _geqv(cls, OrderedDict): + return collections.OrderedDict(*args, **kwds) + return _generic_new(collections.OrderedDict, cls, *args, **kwds) +else: + class OrderedDict(collections.OrderedDict, typing.MutableMapping[KT, VT], + metaclass=_ExtensionsGenericMeta, + extra=collections.OrderedDict): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if cls._gorg is OrderedDict: + return collections.OrderedDict(*args, **kwds) + return _generic_new(collections.OrderedDict, cls, *args, **kwds) + + +if hasattr(typing, 'Counter'): + Counter = typing.Counter +elif (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 1): + assert _geqv_defined + _TInt = typing.TypeVar('_TInt') + + class _CounterMeta(typing.GenericMeta): + """Metaclass for Counter""" + def __getitem__(self, item): + return super().__getitem__((item, int)) + + class Counter(collections.Counter, + typing.Dict[T, int], + metaclass=_CounterMeta, + extra=collections.Counter): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if _geqv(cls, Counter): + return collections.Counter(*args, **kwds) + return _generic_new(collections.Counter, cls, *args, **kwds) + +elif _geqv_defined: + class Counter(collections.Counter, + typing.Dict[T, int], + metaclass=_ExtensionsGenericMeta, extra=collections.Counter): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if _geqv(cls, Counter): + return collections.Counter(*args, **kwds) + return _generic_new(collections.Counter, cls, *args, **kwds) + +else: + class Counter(collections.Counter, + typing.Dict[T, int], + metaclass=_ExtensionsGenericMeta, extra=collections.Counter): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if cls._gorg is Counter: + return collections.Counter(*args, **kwds) + return _generic_new(collections.Counter, cls, *args, **kwds) + + +if hasattr(typing, 'ChainMap'): + ChainMap = typing.ChainMap + __all__.append('ChainMap') +elif hasattr(collections, 'ChainMap'): + # ChainMap only exists in 3.3+ + if _geqv_defined: + class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], + metaclass=_ExtensionsGenericMeta, + extra=collections.ChainMap): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if _geqv(cls, ChainMap): + return collections.ChainMap(*args, **kwds) + return _generic_new(collections.ChainMap, cls, *args, **kwds) + else: + class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT], + metaclass=_ExtensionsGenericMeta, + extra=collections.ChainMap): + + __slots__ = () + + def __new__(cls, *args, **kwds): + if cls._gorg is ChainMap: + return collections.ChainMap(*args, **kwds) + return _generic_new(collections.ChainMap, cls, *args, **kwds) + + __all__.append('ChainMap') + + +if _define_guard('AsyncGenerator'): + class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra], + metaclass=_ExtensionsGenericMeta, + extra=collections_abc.AsyncGenerator): + __slots__ = () + + +if hasattr(typing, 'NewType'): + NewType = typing.NewType +else: + def NewType(name, tp): + """NewType creates simple unique types with almost zero + runtime overhead. NewType(name, tp) is considered a subtype of tp + by static type checkers. At runtime, NewType(name, tp) returns + a dummy function that simply returns its argument. Usage:: + + UserId = NewType('UserId', int) + + def name_by_id(user_id: UserId) -> str: + ... + + UserId('user') # Fails type check + + name_by_id(42) # Fails type check + name_by_id(UserId(42)) # OK + + num = UserId(5) + 1 # type: int + """ + + def new_type(x): + return x + + new_type.__name__ = name + new_type.__supertype__ = tp + return new_type + + +if hasattr(typing, 'Text'): + Text = typing.Text +else: + Text = str + + +if hasattr(typing, 'TYPE_CHECKING'): + TYPE_CHECKING = typing.TYPE_CHECKING +else: + # Constant that's True when type checking, but False here. + TYPE_CHECKING = False + + +def _gorg(cls): + """This function exists for compatibility with old typing versions.""" + assert isinstance(cls, GenericMeta) + if hasattr(cls, '_gorg'): + return cls._gorg + while cls.__origin__ is not None: + cls = cls.__origin__ + return cls + + +if OLD_GENERICS: + def _next_in_mro(cls): # noqa + """This function exists for compatibility with old typing versions.""" + next_in_mro = object + for i, c in enumerate(cls.__mro__[:-1]): + if isinstance(c, GenericMeta) and _gorg(c) is Generic: + next_in_mro = cls.__mro__[i + 1] + return next_in_mro + + +_PROTO_WHITELIST = ['Callable', 'Awaitable', + 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator', + 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', + 'ContextManager', 'AsyncContextManager'] + + +def _get_protocol_attrs(cls): + attrs = set() + for base in cls.__mro__[:-1]: # without object + if base.__name__ in ('Protocol', 'Generic'): + continue + annotations = getattr(base, '__annotations__', {}) + for attr in list(base.__dict__.keys()) + list(annotations.keys()): + if (not attr.startswith('_abc_') and attr not in ( + '__abstractmethods__', '__annotations__', '__weakref__', + '_is_protocol', '_is_runtime_protocol', '__dict__', + '__args__', '__slots__', + '__next_in_mro__', '__parameters__', '__origin__', + '__orig_bases__', '__extra__', '__tree_hash__', + '__doc__', '__subclasshook__', '__init__', '__new__', + '__module__', '_MutableMapping__marker', '_gorg')): + attrs.add(attr) + return attrs + + +def _is_callable_members_only(cls): + return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls)) + + +if hasattr(typing, 'Protocol'): + Protocol = typing.Protocol +elif HAVE_PROTOCOLS and not PEP_560: + + def _no_init(self, *args, **kwargs): + if type(self)._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + class _ProtocolMeta(GenericMeta): + """Internal metaclass for Protocol. + + This exists so Protocol classes can be generic without deriving + from Generic. + """ + if not OLD_GENERICS: + def __new__(cls, name, bases, namespace, + tvars=None, args=None, origin=None, extra=None, orig_bases=None): + # This is just a version copied from GenericMeta.__new__ that + # includes "Protocol" special treatment. (Comments removed for brevity.) + assert extra is None # Protocols should not have extra + if tvars is not None: + assert origin is not None + assert all(isinstance(t, TypeVar) for t in tvars), tvars + else: + tvars = _type_vars(bases) + gvars = None + for base in bases: + if base is Generic: + raise TypeError("Cannot inherit from plain Generic") + if (isinstance(base, GenericMeta) and + base.__origin__ in (Generic, Protocol)): + if gvars is not None: + raise TypeError( + "Cannot inherit from Generic[...] or" + " Protocol[...] multiple times.") + gvars = base.__parameters__ + if gvars is None: + gvars = tvars + else: + tvarset = set(tvars) + gvarset = set(gvars) + if not tvarset <= gvarset: + raise TypeError( + "Some type variables (%s) " + "are not listed in %s[%s]" % + (", ".join(str(t) for t in tvars if t not in gvarset), + "Generic" if any(b.__origin__ is Generic + for b in bases) else "Protocol", + ", ".join(str(g) for g in gvars))) + tvars = gvars + + initial_bases = bases + if (extra is not None and type(extra) is abc.ABCMeta and + extra not in bases): + bases = (extra,) + bases + bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b + for b in bases) + if any(isinstance(b, GenericMeta) and b is not Generic for b in bases): + bases = tuple(b for b in bases if b is not Generic) + namespace.update({'__origin__': origin, '__extra__': extra}) + self = super(GenericMeta, cls).__new__(cls, name, bases, namespace, + _root=True) + super(GenericMeta, self).__setattr__('_gorg', + self if not origin else + _gorg(origin)) + self.__parameters__ = tvars + self.__args__ = tuple(... if a is _TypingEllipsis else + () if a is _TypingEmpty else + a for a in args) if args else None + self.__next_in_mro__ = _next_in_mro(self) + if orig_bases is None: + self.__orig_bases__ = initial_bases + elif origin is not None: + self._abc_registry = origin._abc_registry + self._abc_cache = origin._abc_cache + if hasattr(self, '_subs_tree'): + self.__tree_hash__ = (hash(self._subs_tree()) if origin else + super(GenericMeta, self).__hash__()) + return self + + def __init__(cls, *args, **kwargs): + super().__init__(*args, **kwargs) + if not cls.__dict__.get('_is_protocol', None): + cls._is_protocol = any(b is Protocol or + isinstance(b, _ProtocolMeta) and + b.__origin__ is Protocol + for b in cls.__bases__) + if cls._is_protocol: + for base in cls.__mro__[1:]: + if not (base in (object, Generic) or + base.__module__ == 'collections.abc' and + base.__name__ in _PROTO_WHITELIST or + isinstance(base, TypingMeta) and base._is_protocol or + isinstance(base, GenericMeta) and + base.__origin__ is Generic): + raise TypeError('Protocols can only inherit from other' + ' protocols, got %r' % base) + + cls.__init__ = _no_init + + def _proto_hook(other): + if not cls.__dict__.get('_is_protocol', None): + return NotImplemented + if not isinstance(other, type): + # Same error as for issubclass(1, int) + raise TypeError('issubclass() arg 1 must be a class') + for attr in _get_protocol_attrs(cls): + for base in other.__mro__: + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + annotations = getattr(base, '__annotations__', {}) + if (isinstance(annotations, typing.Mapping) and + attr in annotations and + isinstance(other, _ProtocolMeta) and + other._is_protocol): + break + else: + return NotImplemented + return True + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + def __instancecheck__(self, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if ((not getattr(self, '_is_protocol', False) or + _is_callable_members_only(self)) and + issubclass(instance.__class__, self)): + return True + if self._is_protocol: + if all(hasattr(instance, attr) and + (not callable(getattr(self, attr, None)) or + getattr(instance, attr) is not None) + for attr in _get_protocol_attrs(self)): + return True + return super(GenericMeta, self).__instancecheck__(instance) + + def __subclasscheck__(self, cls): + if self.__origin__ is not None: + if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']: + raise TypeError("Parameterized generics cannot be used with class " + "or instance checks") + return False + if (self.__dict__.get('_is_protocol', None) and + not self.__dict__.get('_is_runtime_protocol', None)): + if sys._getframe(1).f_globals['__name__'] in ['abc', + 'functools', + 'typing']: + return False + raise TypeError("Instance and class checks can only be used with" + " @runtime protocols") + if (self.__dict__.get('_is_runtime_protocol', None) and + not _is_callable_members_only(self)): + if sys._getframe(1).f_globals['__name__'] in ['abc', + 'functools', + 'typing']: + return super(GenericMeta, self).__subclasscheck__(cls) + raise TypeError("Protocols with non-method members" + " don't support issubclass()") + return super(GenericMeta, self).__subclasscheck__(cls) + + if not OLD_GENERICS: + @_tp_cache + def __getitem__(self, params): + # We also need to copy this from GenericMeta.__getitem__ to get + # special treatment of "Protocol". (Comments removed for brevity.) + if not isinstance(params, tuple): + params = (params,) + if not params and _gorg(self) is not Tuple: + raise TypeError( + "Parameter list to %s[...] cannot be empty" % self.__qualname__) + msg = "Parameters to generic types must be types." + params = tuple(_type_check(p, msg) for p in params) + if self in (Generic, Protocol): + if not all(isinstance(p, TypeVar) for p in params): + raise TypeError( + "Parameters to %r[...] must all be type variables" % self) + if len(set(params)) != len(params): + raise TypeError( + "Parameters to %r[...] must all be unique" % self) + tvars = params + args = params + elif self in (Tuple, Callable): + tvars = _type_vars(params) + args = params + elif self.__origin__ in (Generic, Protocol): + raise TypeError("Cannot subscript already-subscripted %s" % + repr(self)) + else: + _check_generic(self, params) + tvars = _type_vars(params) + args = params + + prepend = (self,) if self.__origin__ is None else () + return self.__class__(self.__name__, + prepend + self.__bases__, + _no_slots_copy(self.__dict__), + tvars=tvars, + args=args, + origin=self, + extra=self.__extra__, + orig_bases=self.__orig_bases__) + + class Protocol(metaclass=_ProtocolMeta): + """Base class for protocol classes. Protocol classes are defined as:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing), for example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See PEP 544 for details. Protocol classes decorated with + @typing_extensions.runtime act as simple-minded runtime protocol that checks + only the presence of given attributes, ignoring their type signatures. + + Protocol classes can be generic, they are defined as:: + + class GenProto({bases}): + def meth(self) -> T: + ... + """ + __slots__ = () + _is_protocol = True + + def __new__(cls, *args, **kwds): + if _gorg(cls) is Protocol: + raise TypeError("Type Protocol cannot be instantiated; " + "it can be used only as a base class") + if OLD_GENERICS: + return _generic_new(_next_in_mro(cls), cls, *args, **kwds) + return _generic_new(cls.__next_in_mro__, cls, *args, **kwds) + if Protocol.__doc__ is not None: + Protocol.__doc__ = Protocol.__doc__.format(bases="Protocol, Generic[T]" if + OLD_GENERICS else "Protocol[T]") + + +elif PEP_560: + from typing import _type_check, _collect_type_vars # noqa + + def _no_init(self, *args, **kwargs): + if type(self)._is_protocol: + raise TypeError('Protocols cannot be instantiated') + + class _ProtocolMeta(abc.ABCMeta): + # This metaclass is a bit unfortunate and exists only because of the lack + # of __instancehook__. + def __instancecheck__(cls, instance): + # We need this method for situations where attributes are + # assigned in __init__. + if ((not getattr(cls, '_is_protocol', False) or + _is_callable_members_only(cls)) and + issubclass(instance.__class__, cls)): + return True + if cls._is_protocol: + if all(hasattr(instance, attr) and + (not callable(getattr(cls, attr, None)) or + getattr(instance, attr) is not None) + for attr in _get_protocol_attrs(cls)): + return True + return super().__instancecheck__(instance) + + class Protocol(metaclass=_ProtocolMeta): + # There is quite a lot of overlapping code with typing.Generic. + # Unfortunately it is hard to avoid this while these live in two different + # modules. The duplicated code will be removed when Protocol is moved to typing. + """Base class for protocol classes. Protocol classes are defined as:: + + class Proto(Protocol): + def meth(self) -> int: + ... + + Such classes are primarily used with static type checkers that recognize + structural subtyping (static duck-typing), for example:: + + class C: + def meth(self) -> int: + return 0 + + def func(x: Proto) -> int: + return x.meth() + + func(C()) # Passes static type check + + See PEP 544 for details. Protocol classes decorated with + @typing_extensions.runtime act as simple-minded runtime protocol that checks + only the presence of given attributes, ignoring their type signatures. + + Protocol classes can be generic, they are defined as:: + + class GenProto(Protocol[T]): + def meth(self) -> T: + ... + """ + __slots__ = () + _is_protocol = True + + def __new__(cls, *args, **kwds): + if cls is Protocol: + raise TypeError("Type Protocol cannot be instantiated; " + "it can only be used as a base class") + return super().__new__(cls) + + @_tp_cache + def __class_getitem__(cls, params): + if not isinstance(params, tuple): + params = (params,) + if not params and cls is not Tuple: + raise TypeError( + "Parameter list to {}[...] cannot be empty".format(cls.__qualname__)) + msg = "Parameters to generic types must be types." + params = tuple(_type_check(p, msg) for p in params) + if cls is Protocol: + # Generic can only be subscripted with unique type variables. + if not all(isinstance(p, TypeVar) for p in params): + i = 0 + while isinstance(params[i], TypeVar): + i += 1 + raise TypeError( + "Parameters to Protocol[...] must all be type variables." + " Parameter {} is {}".format(i + 1, params[i])) + if len(set(params)) != len(params): + raise TypeError( + "Parameters to Protocol[...] must all be unique") + else: + # Subscripting a regular Generic subclass. + _check_generic(cls, params) + return _GenericAlias(cls, params) + + def __init_subclass__(cls, *args, **kwargs): + tvars = [] + if '__orig_bases__' in cls.__dict__: + error = Generic in cls.__orig_bases__ + else: + error = Generic in cls.__bases__ + if error: + raise TypeError("Cannot inherit from plain Generic") + if '__orig_bases__' in cls.__dict__: + tvars = _collect_type_vars(cls.__orig_bases__) + # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn]. + # If found, tvars must be a subset of it. + # If not found, tvars is it. + # Also check for and reject plain Generic, + # and reject multiple Generic[...] and/or Protocol[...]. + gvars = None + for base in cls.__orig_bases__: + if (isinstance(base, _GenericAlias) and + base.__origin__ in (Generic, Protocol)): + # for error messages + the_base = 'Generic' if base.__origin__ is Generic else 'Protocol' + if gvars is not None: + raise TypeError( + "Cannot inherit from Generic[...]" + " and/or Protocol[...] multiple types.") + gvars = base.__parameters__ + if gvars is None: + gvars = tvars + else: + tvarset = set(tvars) + gvarset = set(gvars) + if not tvarset <= gvarset: + s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) + s_args = ', '.join(str(g) for g in gvars) + raise TypeError("Some type variables ({}) are" + " not listed in {}[{}]".format(s_vars, + the_base, s_args)) + tvars = gvars + cls.__parameters__ = tuple(tvars) + + # Determine if this is a protocol or a concrete subclass. + if not cls.__dict__.get('_is_protocol', None): + cls._is_protocol = any(b is Protocol for b in cls.__bases__) + + # Set (or override) the protocol subclass hook. + def _proto_hook(other): + if not cls.__dict__.get('_is_protocol', None): + return NotImplemented + if not getattr(cls, '_is_runtime_protocol', False): + if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: + return NotImplemented + raise TypeError("Instance and class checks can only be used with" + " @runtime protocols") + if not _is_callable_members_only(cls): + if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']: + return NotImplemented + raise TypeError("Protocols with non-method members" + " don't support issubclass()") + if not isinstance(other, type): + # Same error as for issubclass(1, int) + raise TypeError('issubclass() arg 1 must be a class') + for attr in _get_protocol_attrs(cls): + for base in other.__mro__: + if attr in base.__dict__: + if base.__dict__[attr] is None: + return NotImplemented + break + annotations = getattr(base, '__annotations__', {}) + if (isinstance(annotations, typing.Mapping) and + attr in annotations and + isinstance(other, _ProtocolMeta) and + other._is_protocol): + break + else: + return NotImplemented + return True + if '__subclasshook__' not in cls.__dict__: + cls.__subclasshook__ = _proto_hook + + # We have nothing more to do for non-protocols. + if not cls._is_protocol: + return + + # Check consistency of bases. + for base in cls.__bases__: + if not (base in (object, Generic) or + base.__module__ == 'collections.abc' and + base.__name__ in _PROTO_WHITELIST or + isinstance(base, _ProtocolMeta) and base._is_protocol): + raise TypeError('Protocols can only inherit from other' + ' protocols, got %r' % base) + cls.__init__ = _no_init + + +if hasattr(typing, 'runtime_checkable'): + runtime_checkable = typing.runtime_checkable +elif HAVE_PROTOCOLS: + def runtime_checkable(cls): + """Mark a protocol class as a runtime protocol, so that it + can be used with isinstance() and issubclass(). Raise TypeError + if applied to a non-protocol class. + + This allows a simple-minded structural check very similar to the + one-offs in collections.abc such as Hashable. + """ + if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol: + raise TypeError('@runtime_checkable can be only applied to protocol classes,' + ' got %r' % cls) + cls._is_runtime_protocol = True + return cls + + +if HAVE_PROTOCOLS: + # Exists for backwards compatibility. + runtime = runtime_checkable + + +if hasattr(typing, 'SupportsIndex'): + SupportsIndex = typing.SupportsIndex +elif HAVE_PROTOCOLS: + @runtime_checkable + class SupportsIndex(Protocol): + __slots__ = () + + @abc.abstractmethod + def __index__(self) -> int: + pass + + +if sys.version_info >= (3, 9, 2): + # The standard library TypedDict in Python 3.8 does not store runtime information + # about which (if any) keys are optional. See https://bugs.python.org/issue38834 + # The standard library TypedDict in Python 3.9.0/1 does not honour the "total" + # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059 + TypedDict = typing.TypedDict +else: + def _check_fails(cls, other): + try: + if sys._getframe(1).f_globals['__name__'] not in ['abc', + 'functools', + 'typing']: + # Typed dicts are only for static structural subtyping. + raise TypeError('TypedDict does not support instance and class checks') + except (AttributeError, ValueError): + pass + return False + + def _dict_new(*args, **kwargs): + if not args: + raise TypeError('TypedDict.__new__(): not enough arguments') + _, args = args[0], args[1:] # allow the "cls" keyword be passed + return dict(*args, **kwargs) + + _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)' + + def _typeddict_new(*args, total=True, **kwargs): + if not args: + raise TypeError('TypedDict.__new__(): not enough arguments') + _, args = args[0], args[1:] # allow the "cls" keyword be passed + if args: + typename, args = args[0], args[1:] # allow the "_typename" keyword be passed + elif '_typename' in kwargs: + typename = kwargs.pop('_typename') + import warnings + warnings.warn("Passing '_typename' as keyword argument is deprecated", + DeprecationWarning, stacklevel=2) + else: + raise TypeError("TypedDict.__new__() missing 1 required positional " + "argument: '_typename'") + if args: + try: + fields, = args # allow the "_fields" keyword be passed + except ValueError: + raise TypeError('TypedDict.__new__() takes from 2 to 3 ' + 'positional arguments but {} ' + 'were given'.format(len(args) + 2)) + elif '_fields' in kwargs and len(kwargs) == 1: + fields = kwargs.pop('_fields') + import warnings + warnings.warn("Passing '_fields' as keyword argument is deprecated", + DeprecationWarning, stacklevel=2) + else: + fields = None + + if fields is None: + fields = kwargs + elif kwargs: + raise TypeError("TypedDict takes either a dict or keyword arguments," + " but not both") + + ns = {'__annotations__': dict(fields)} + try: + # Setting correct module is necessary to make typed dict classes pickleable. + ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + pass + + return _TypedDictMeta(typename, (), ns, total=total) + + _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,' + ' /, *, total=True, **kwargs)') + + class _TypedDictMeta(type): + def __init__(cls, name, bases, ns, total=True): + # In Python 3.4 and 3.5 the __init__ method also needs to support the + # keyword arguments. + # See https://www.python.org/dev/peps/pep-0487/#implementation-details + super(_TypedDictMeta, cls).__init__(name, bases, ns) + + def __new__(cls, name, bases, ns, total=True): + # Create new typed dict class object. + # This method is called directly when TypedDict is subclassed, + # or via _typeddict_new when TypedDict is instantiated. This way + # TypedDict supports all three syntaxes described in its docstring. + # Subclasses and instances of TypedDict return actual dictionaries + # via _dict_new. + ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new + tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns) + + annotations = {} + own_annotations = ns.get('__annotations__', {}) + own_annotation_keys = set(own_annotations.keys()) + msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type" + own_annotations = { + n: typing._type_check(tp, msg) for n, tp in own_annotations.items() + } + required_keys = set() + optional_keys = set() + + for base in bases: + annotations.update(base.__dict__.get('__annotations__', {})) + required_keys.update(base.__dict__.get('__required_keys__', ())) + optional_keys.update(base.__dict__.get('__optional_keys__', ())) + + annotations.update(own_annotations) + if total: + required_keys.update(own_annotation_keys) + else: + optional_keys.update(own_annotation_keys) + + tp_dict.__annotations__ = annotations + tp_dict.__required_keys__ = frozenset(required_keys) + tp_dict.__optional_keys__ = frozenset(optional_keys) + if not hasattr(tp_dict, '__total__'): + tp_dict.__total__ = total + return tp_dict + + __instancecheck__ = __subclasscheck__ = _check_fails + + TypedDict = _TypedDictMeta('TypedDict', (dict,), {}) + TypedDict.__module__ = __name__ + TypedDict.__doc__ = \ + """A simple typed name space. At runtime it is equivalent to a plain dict. + + TypedDict creates a dictionary type that expects all of its + instances to have a certain set of keys, with each key + associated with a value of a consistent type. This expectation + is not checked at runtime but is only enforced by type checkers. + Usage:: + + class Point2D(TypedDict): + x: int + y: int + label: str + + a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK + b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check + + assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') + + The type info can be accessed via the Point2D.__annotations__ dict, and + the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. + TypedDict supports two additional equivalent forms:: + + Point2D = TypedDict('Point2D', x=int, y=int, label=str) + Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) + + The class syntax is only supported in Python 3.6+, while two other + syntax forms work for Python 2.7 and 3.2+ + """ + + +# Python 3.9+ has PEP 593 (Annotated and modified get_type_hints) +if hasattr(typing, 'Annotated'): + Annotated = typing.Annotated + get_type_hints = typing.get_type_hints + # Not exported and not a public API, but needed for get_origin() and get_args() + # to work. + _AnnotatedAlias = typing._AnnotatedAlias +elif PEP_560: + class _AnnotatedAlias(typing._GenericAlias, _root=True): + """Runtime representation of an annotated type. + + At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' + with extra annotations. The alias behaves like a normal typing alias, + instantiating is the same as instantiating the underlying type, binding + it to types is also the same. + """ + def __init__(self, origin, metadata): + if isinstance(origin, _AnnotatedAlias): + metadata = origin.__metadata__ + metadata + origin = origin.__origin__ + super().__init__(origin, origin) + self.__metadata__ = metadata + + def copy_with(self, params): + assert len(params) == 1 + new_type = params[0] + return _AnnotatedAlias(new_type, self.__metadata__) + + def __repr__(self): + return "typing_extensions.Annotated[{}, {}]".format( + typing._type_repr(self.__origin__), + ", ".join(repr(a) for a in self.__metadata__) + ) + + def __reduce__(self): + return operator.getitem, ( + Annotated, (self.__origin__,) + self.__metadata__ + ) + + def __eq__(self, other): + if not isinstance(other, _AnnotatedAlias): + return NotImplemented + if self.__origin__ != other.__origin__: + return False + return self.__metadata__ == other.__metadata__ + + def __hash__(self): + return hash((self.__origin__, self.__metadata__)) + + class Annotated: + """Add context specific metadata to a type. + + Example: Annotated[int, runtime_check.Unsigned] indicates to the + hypothetical runtime_check module that this type is an unsigned int. + Every other consumer of this type can ignore this metadata and treat + this type as int. + + The first argument to Annotated must be a valid type (and will be in + the __origin__ field), the remaining arguments are kept as a tuple in + the __extra__ field. + + Details: + + - It's an error to call `Annotated` with less than two arguments. + - Nested Annotated are flattened:: + + Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] + + - Instantiating an annotated type is equivalent to instantiating the + underlying type:: + + Annotated[C, Ann1](5) == C(5) + + - Annotated can be used as a generic type alias:: + + Optimized = Annotated[T, runtime.Optimize()] + Optimized[int] == Annotated[int, runtime.Optimize()] + + OptimizedList = Annotated[List[T], runtime.Optimize()] + OptimizedList[int] == Annotated[List[int], runtime.Optimize()] + """ + + __slots__ = () + + def __new__(cls, *args, **kwargs): + raise TypeError("Type Annotated cannot be instantiated.") + + @_tp_cache + def __class_getitem__(cls, params): + if not isinstance(params, tuple) or len(params) < 2: + raise TypeError("Annotated[...] should be used " + "with at least two arguments (a type and an " + "annotation).") + msg = "Annotated[t, ...]: t must be a type." + origin = typing._type_check(params[0], msg) + metadata = tuple(params[1:]) + return _AnnotatedAlias(origin, metadata) + + def __init_subclass__(cls, *args, **kwargs): + raise TypeError( + "Cannot subclass {}.Annotated".format(cls.__module__) + ) + + def _strip_annotations(t): + """Strips the annotations from a given type. + """ + if isinstance(t, _AnnotatedAlias): + return _strip_annotations(t.__origin__) + if isinstance(t, typing._GenericAlias): + stripped_args = tuple(_strip_annotations(a) for a in t.__args__) + if stripped_args == t.__args__: + return t + res = t.copy_with(stripped_args) + res._special = t._special + return res + return t + + def get_type_hints(obj, globalns=None, localns=None, include_extras=False): + """Return type hints for an object. + + This is often the same as obj.__annotations__, but it handles + forward references encoded as string literals, adds Optional[t] if a + default value equal to None is set and recursively replaces all + 'Annotated[T, ...]' with 'T' (unless 'include_extras=True'). + + The argument may be a module, class, method, or function. The annotations + are returned as a dictionary. For classes, annotations include also + inherited members. + + TypeError is raised if the argument is not of a type that can contain + annotations, and an empty dictionary is returned if no annotations are + present. + + BEWARE -- the behavior of globalns and localns is counterintuitive + (unless you are familiar with how eval() and exec() work). The + search order is locals first, then globals. + + - If no dict arguments are passed, an attempt is made to use the + globals from obj (or the respective module's globals for classes), + and these are also used as the locals. If the object does not appear + to have globals, an empty dictionary is used. + + - If one dict argument is passed, it is used for both globals and + locals. + + - If two dict arguments are passed, they specify globals and + locals, respectively. + """ + hint = typing.get_type_hints(obj, globalns=globalns, localns=localns) + if include_extras: + return hint + return {k: _strip_annotations(t) for k, t in hint.items()} + +elif HAVE_ANNOTATED: + + def _is_dunder(name): + """Returns True if name is a __dunder_variable_name__.""" + return len(name) > 4 and name.startswith('__') and name.endswith('__') + + # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality + # checks, argument expansion etc. are done on the _subs_tre. As a result we + # can't provide a get_type_hints function that strips out annotations. + + class AnnotatedMeta(typing.GenericMeta): + """Metaclass for Annotated""" + + def __new__(cls, name, bases, namespace, **kwargs): + if any(b is not object for b in bases): + raise TypeError("Cannot subclass " + str(Annotated)) + return super().__new__(cls, name, bases, namespace, **kwargs) + + @property + def __metadata__(self): + return self._subs_tree()[2] + + def _tree_repr(self, tree): + cls, origin, metadata = tree + if not isinstance(origin, tuple): + tp_repr = typing._type_repr(origin) + else: + tp_repr = origin[0]._tree_repr(origin) + metadata_reprs = ", ".join(repr(arg) for arg in metadata) + return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs) + + def _subs_tree(self, tvars=None, args=None): # noqa + if self is Annotated: + return Annotated + res = super()._subs_tree(tvars=tvars, args=args) + # Flatten nested Annotated + if isinstance(res[1], tuple) and res[1][0] is Annotated: + sub_tp = res[1][1] + sub_annot = res[1][2] + return (Annotated, sub_tp, sub_annot + res[2]) + return res + + def _get_cons(self): + """Return the class used to create instance of this type.""" + if self.__origin__ is None: + raise TypeError("Cannot get the underlying type of a " + "non-specialized Annotated type.") + tree = self._subs_tree() + while isinstance(tree, tuple) and tree[0] is Annotated: + tree = tree[1] + if isinstance(tree, tuple): + return tree[0] + else: + return tree + + @_tp_cache + def __getitem__(self, params): + if not isinstance(params, tuple): + params = (params,) + if self.__origin__ is not None: # specializing an instantiated type + return super().__getitem__(params) + elif not isinstance(params, tuple) or len(params) < 2: + raise TypeError("Annotated[...] should be instantiated " + "with at least two arguments (a type and an " + "annotation).") + else: + msg = "Annotated[t, ...]: t must be a type." + tp = typing._type_check(params[0], msg) + metadata = tuple(params[1:]) + return self.__class__( + self.__name__, + self.__bases__, + _no_slots_copy(self.__dict__), + tvars=_type_vars((tp,)), + # Metadata is a tuple so it won't be touched by _replace_args et al. + args=(tp, metadata), + origin=self, + ) + + def __call__(self, *args, **kwargs): + cons = self._get_cons() + result = cons(*args, **kwargs) + try: + result.__orig_class__ = self + except AttributeError: + pass + return result + + def __getattr__(self, attr): + # For simplicity we just don't relay all dunder names + if self.__origin__ is not None and not _is_dunder(attr): + return getattr(self._get_cons(), attr) + raise AttributeError(attr) + + def __setattr__(self, attr, value): + if _is_dunder(attr) or attr.startswith('_abc_'): + super().__setattr__(attr, value) + elif self.__origin__ is None: + raise AttributeError(attr) + else: + setattr(self._get_cons(), attr, value) + + def __instancecheck__(self, obj): + raise TypeError("Annotated cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("Annotated cannot be used with issubclass().") + + class Annotated(metaclass=AnnotatedMeta): + """Add context specific metadata to a type. + + Example: Annotated[int, runtime_check.Unsigned] indicates to the + hypothetical runtime_check module that this type is an unsigned int. + Every other consumer of this type can ignore this metadata and treat + this type as int. + + The first argument to Annotated must be a valid type, the remaining + arguments are kept as a tuple in the __metadata__ field. + + Details: + + - It's an error to call `Annotated` with less than two arguments. + - Nested Annotated are flattened:: + + Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] + + - Instantiating an annotated type is equivalent to instantiating the + underlying type:: + + Annotated[C, Ann1](5) == C(5) + + - Annotated can be used as a generic type alias:: + + Optimized = Annotated[T, runtime.Optimize()] + Optimized[int] == Annotated[int, runtime.Optimize()] + + OptimizedList = Annotated[List[T], runtime.Optimize()] + OptimizedList[int] == Annotated[List[int], runtime.Optimize()] + """ + +# Python 3.8 has get_origin() and get_args() but those implementations aren't +# Annotated-aware, so we can't use those, only Python 3.9 versions will do. +# Similarly, Python 3.9's implementation doesn't support ParamSpecArgs and +# ParamSpecKwargs. +if sys.version_info[:2] >= (3, 10): + get_origin = typing.get_origin + get_args = typing.get_args +elif PEP_560: + try: + # 3.9+ + from typing import _BaseGenericAlias + except ImportError: + _BaseGenericAlias = _GenericAlias + try: + # 3.9+ + from typing import GenericAlias + except ImportError: + GenericAlias = _GenericAlias + + def get_origin(tp): + """Get the unsubscripted version of a type. + + This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar + and Annotated. Return None for unsupported types. Examples:: + + get_origin(Literal[42]) is Literal + get_origin(int) is None + get_origin(ClassVar[int]) is ClassVar + get_origin(Generic) is Generic + get_origin(Generic[T]) is Generic + get_origin(Union[T, int]) is Union + get_origin(List[Tuple[T, T]][int]) == list + get_origin(P.args) is P + """ + if isinstance(tp, _AnnotatedAlias): + return Annotated + if isinstance(tp, (_GenericAlias, GenericAlias, _BaseGenericAlias, + ParamSpecArgs, ParamSpecKwargs)): + return tp.__origin__ + if tp is Generic: + return Generic + return None + + def get_args(tp): + """Get type arguments with all substitutions performed. + + For unions, basic simplifications used by Union constructor are performed. + Examples:: + get_args(Dict[str, int]) == (str, int) + get_args(int) == () + get_args(Union[int, Union[T, int], str][int]) == (int, str) + get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) + get_args(Callable[[], T][int]) == ([], int) + """ + if isinstance(tp, _AnnotatedAlias): + return (tp.__origin__,) + tp.__metadata__ + if isinstance(tp, (_GenericAlias, GenericAlias)): + if getattr(tp, "_special", False): + return () + res = tp.__args__ + if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis: + res = (list(res[:-1]), res[-1]) + return res + return () + + +if hasattr(typing, 'TypeAlias'): + TypeAlias = typing.TypeAlias +elif sys.version_info[:2] >= (3, 9): + class _TypeAliasForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + @_TypeAliasForm + def TypeAlias(self, parameters): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + raise TypeError("{} is not subscriptable".format(self)) + +elif sys.version_info[:2] >= (3, 7): + class _TypeAliasForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + TypeAlias = _TypeAliasForm('TypeAlias', + doc="""Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example + above.""") + +elif hasattr(typing, '_FinalTypingBase'): + class _TypeAliasMeta(typing.TypingMeta): + """Metaclass for TypeAlias""" + + def __repr__(self): + return 'typing_extensions.TypeAlias' + + class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + __slots__ = () + + def __instancecheck__(self, obj): + raise TypeError("TypeAlias cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("TypeAlias cannot be used with issubclass().") + + def __repr__(self): + return 'typing_extensions.TypeAlias' + + TypeAlias = _TypeAliasBase(_root=True) +else: + class _TypeAliasMeta(typing.TypingMeta): + """Metaclass for TypeAlias""" + + def __instancecheck__(self, obj): + raise TypeError("TypeAlias cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("TypeAlias cannot be used with issubclass().") + + def __call__(self, *args, **kwargs): + raise TypeError("Cannot instantiate TypeAlias") + + class TypeAlias(metaclass=_TypeAliasMeta, _root=True): + """Special marker indicating that an assignment should + be recognized as a proper type alias definition by type + checkers. + + For example:: + + Predicate: TypeAlias = Callable[..., bool] + + It's invalid when used anywhere except as in the example above. + """ + __slots__ = () + + +# Python 3.10+ has PEP 612 +if hasattr(typing, 'ParamSpecArgs'): + ParamSpecArgs = typing.ParamSpecArgs + ParamSpecKwargs = typing.ParamSpecKwargs +else: + class _Immutable: + """Mixin to indicate that object should not be copied.""" + __slots__ = () + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + class ParamSpecArgs(_Immutable): + """The args for a ParamSpec object. + + Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. + + ParamSpecArgs objects have a reference back to their ParamSpec: + + P.args.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return "{}.args".format(self.__origin__.__name__) + + class ParamSpecKwargs(_Immutable): + """The kwargs for a ParamSpec object. + + Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. + + ParamSpecKwargs objects have a reference back to their ParamSpec: + + P.kwargs.__origin__ is P + + This type is meant for runtime introspection and has no special meaning to + static type checkers. + """ + def __init__(self, origin): + self.__origin__ = origin + + def __repr__(self): + return "{}.kwargs".format(self.__origin__.__name__) + +if hasattr(typing, 'ParamSpec'): + ParamSpec = typing.ParamSpec +else: + + # Inherits from list as a workaround for Callable checks in Python < 3.9.2. + class ParamSpec(list): + """Parameter specification variable. + + Usage:: + + P = ParamSpec('P') + + Parameter specification variables exist primarily for the benefit of static + type checkers. They are used to forward the parameter types of one + callable to another callable, a pattern commonly found in higher order + functions and decorators. They are only valid when used in ``Concatenate``, + or s the first argument to ``Callable``. In Python 3.10 and higher, + they are also supported in user-defined Generics at runtime. + See class Generic for more information on generic types. An + example for annotating a decorator:: + + T = TypeVar('T') + P = ParamSpec('P') + + def add_logging(f: Callable[P, T]) -> Callable[P, T]: + '''A type-safe decorator to add logging to a function.''' + def inner(*args: P.args, **kwargs: P.kwargs) -> T: + logging.info(f'{f.__name__} was called') + return f(*args, **kwargs) + return inner + + @add_logging + def add_two(x: float, y: float) -> float: + '''Add two numbers together.''' + return x + y + + Parameter specification variables defined with covariant=True or + contravariant=True can be used to declare covariant or contravariant + generic types. These keyword arguments are valid, but their actual semantics + are yet to be decided. See PEP 612 for details. + + Parameter specification variables can be introspected. e.g.: + + P.__name__ == 'T' + P.__bound__ == None + P.__covariant__ == False + P.__contravariant__ == False + + Note that only parameter specification variables defined in global scope can + be pickled. + """ + + # Trick Generic __parameters__. + __class__ = TypeVar + + @property + def args(self): + return ParamSpecArgs(self) + + @property + def kwargs(self): + return ParamSpecKwargs(self) + + def __init__(self, name, *, bound=None, covariant=False, contravariant=False): + super().__init__([self]) + self.__name__ = name + self.__covariant__ = bool(covariant) + self.__contravariant__ = bool(contravariant) + if bound: + self.__bound__ = typing._type_check(bound, 'Bound must be a type.') + else: + self.__bound__ = None + + # for pickling: + try: + def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') + except (AttributeError, ValueError): + def_mod = None + if def_mod != 'typing_extensions': + self.__module__ = def_mod + + def __repr__(self): + if self.__covariant__: + prefix = '+' + elif self.__contravariant__: + prefix = '-' + else: + prefix = '~' + return prefix + self.__name__ + + def __hash__(self): + return object.__hash__(self) + + def __eq__(self, other): + return self is other + + def __reduce__(self): + return self.__name__ + + # Hack to get typing._type_check to pass. + def __call__(self, *args, **kwargs): + pass + + if not PEP_560: + # Only needed in 3.6 and lower. + def _get_type_vars(self, tvars): + if self not in tvars: + tvars.append(self) + + +# Inherits from list as a workaround for Callable checks in Python < 3.9.2. +class _ConcatenateGenericAlias(list): + + # Trick Generic into looking into this for __parameters__. + if PEP_560: + __class__ = typing._GenericAlias + elif sys.version_info[:3] == (3, 5, 2): + __class__ = typing.TypingMeta + else: + __class__ = typing._TypingBase + + # Flag in 3.8. + _special = False + # Attribute in 3.6 and earlier. + if sys.version_info[:3] == (3, 5, 2): + _gorg = typing.GenericMeta + else: + _gorg = typing.Generic + + def __init__(self, origin, args): + super().__init__(args) + self.__origin__ = origin + self.__args__ = args + + def __repr__(self): + _type_repr = typing._type_repr + return '{origin}[{args}]' \ + .format(origin=_type_repr(self.__origin__), + args=', '.join(_type_repr(arg) for arg in self.__args__)) + + def __hash__(self): + return hash((self.__origin__, self.__args__)) + + # Hack to get typing._type_check to pass in Generic. + def __call__(self, *args, **kwargs): + pass + + @property + def __parameters__(self): + return tuple(tp for tp in self.__args__ if isinstance(tp, (TypeVar, ParamSpec))) + + if not PEP_560: + # Only required in 3.6 and lower. + def _get_type_vars(self, tvars): + if self.__origin__ and self.__parameters__: + typing._get_type_vars(self.__parameters__, tvars) + + +@_tp_cache +def _concatenate_getitem(self, parameters): + if parameters == (): + raise TypeError("Cannot take a Concatenate of no types.") + if not isinstance(parameters, tuple): + parameters = (parameters,) + if not isinstance(parameters[-1], ParamSpec): + raise TypeError("The last parameter to Concatenate should be a " + "ParamSpec variable.") + msg = "Concatenate[arg, ...]: each arg must be a type." + parameters = tuple(typing._type_check(p, msg) for p in parameters) + return _ConcatenateGenericAlias(self, parameters) + + +if hasattr(typing, 'Concatenate'): + Concatenate = typing.Concatenate + _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa +elif sys.version_info[:2] >= (3, 9): + @_TypeAliasForm + def Concatenate(self, parameters): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + return _concatenate_getitem(self, parameters) + +elif sys.version_info[:2] >= (3, 7): + class _ConcatenateForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + def __getitem__(self, parameters): + return _concatenate_getitem(self, parameters) + + Concatenate = _ConcatenateForm( + 'Concatenate', + doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """) + +elif hasattr(typing, '_FinalTypingBase'): + class _ConcatenateAliasMeta(typing.TypingMeta): + """Metaclass for Concatenate.""" + + def __repr__(self): + return 'typing_extensions.Concatenate' + + class _ConcatenateAliasBase(typing._FinalTypingBase, + metaclass=_ConcatenateAliasMeta, + _root=True): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + __slots__ = () + + def __instancecheck__(self, obj): + raise TypeError("Concatenate cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("Concatenate cannot be used with issubclass().") + + def __repr__(self): + return 'typing_extensions.Concatenate' + + def __getitem__(self, parameters): + return _concatenate_getitem(self, parameters) + + Concatenate = _ConcatenateAliasBase(_root=True) +# For 3.5.0 - 3.5.2 +else: + class _ConcatenateAliasMeta(typing.TypingMeta): + """Metaclass for Concatenate.""" + + def __instancecheck__(self, obj): + raise TypeError("TypeAlias cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("TypeAlias cannot be used with issubclass().") + + def __call__(self, *args, **kwargs): + raise TypeError("Cannot instantiate TypeAlias") + + def __getitem__(self, parameters): + return _concatenate_getitem(self, parameters) + + class Concatenate(metaclass=_ConcatenateAliasMeta, _root=True): + """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a + higher order function which adds, removes or transforms parameters of a + callable. + + For example:: + + Callable[Concatenate[int, P], int] + + See PEP 612 for detailed information. + """ + __slots__ = () + +if hasattr(typing, 'TypeGuard'): + TypeGuard = typing.TypeGuard +elif sys.version_info[:2] >= (3, 9): + class _TypeGuardForm(typing._SpecialForm, _root=True): + def __repr__(self): + return 'typing_extensions.' + self._name + + @_TypeGuardForm + def TypeGuard(self, parameters): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + item = typing._type_check(parameters, '{} accepts only single type.'.format(self)) + return _GenericAlias(self, (item,)) + +elif sys.version_info[:2] >= (3, 7): + class _TypeGuardForm(typing._SpecialForm, _root=True): + + def __repr__(self): + return 'typing_extensions.' + self._name + + def __getitem__(self, parameters): + item = typing._type_check(parameters, + '{} accepts only a single type'.format(self._name)) + return _GenericAlias(self, (item,)) + + TypeGuard = _TypeGuardForm( + 'TypeGuard', + doc="""Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """) +elif hasattr(typing, '_FinalTypingBase'): + class _TypeGuard(typing._FinalTypingBase, _root=True): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + + __slots__ = ('__type__',) + + def __init__(self, tp=None, **kwds): + self.__type__ = tp + + def __getitem__(self, item): + cls = type(self) + if self.__type__ is None: + return cls(typing._type_check(item, + '{} accepts only a single type.'.format(cls.__name__[1:])), + _root=True) + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + def _eval_type(self, globalns, localns): + new_tp = typing._eval_type(self.__type__, globalns, localns) + if new_tp == self.__type__: + return self + return type(self)(new_tp, _root=True) + + def __repr__(self): + r = super().__repr__() + if self.__type__ is not None: + r += '[{}]'.format(typing._type_repr(self.__type__)) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__type__)) + + def __eq__(self, other): + if not isinstance(other, _TypeGuard): + return NotImplemented + if self.__type__ is not None: + return self.__type__ == other.__type__ + return self is other + + TypeGuard = _TypeGuard(_root=True) +else: + class _TypeGuardMeta(typing.TypingMeta): + """Metaclass for TypeGuard""" + + def __new__(cls, name, bases, namespace, tp=None, _root=False): + self = super().__new__(cls, name, bases, namespace, _root=_root) + if tp is not None: + self.__type__ = tp + return self + + def __instancecheck__(self, obj): + raise TypeError("TypeGuard cannot be used with isinstance().") + + def __subclasscheck__(self, cls): + raise TypeError("TypeGuard cannot be used with issubclass().") + + def __getitem__(self, item): + cls = type(self) + if self.__type__ is not None: + raise TypeError('{} cannot be further subscripted' + .format(cls.__name__[1:])) + + param = typing._type_check( + item, + '{} accepts only single type.'.format(cls.__name__[1:])) + return cls(self.__name__, self.__bases__, + dict(self.__dict__), tp=param, _root=True) + + def _eval_type(self, globalns, localns): + new_tp = typing._eval_type(self.__type__, globalns, localns) + if new_tp == self.__type__: + return self + return type(self)(self.__name__, self.__bases__, + dict(self.__dict__), tp=self.__type__, + _root=True) + + def __repr__(self): + r = super().__repr__() + if self.__type__ is not None: + r += '[{}]'.format(typing._type_repr(self.__type__)) + return r + + def __hash__(self): + return hash((type(self).__name__, self.__type__)) + + def __eq__(self, other): + if not hasattr(other, "__type__"): + return NotImplemented + if self.__type__ is not None: + return self.__type__ == other.__type__ + return self is other + + class TypeGuard(typing.Final, metaclass=_TypeGuardMeta, _root=True): + """Special typing form used to annotate the return type of a user-defined + type guard function. ``TypeGuard`` only accepts a single type argument. + At runtime, functions marked this way should return a boolean. + + ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static + type checkers to determine a more precise type of an expression within a + program's code flow. Usually type narrowing is done by analyzing + conditional code flow and applying the narrowing to a block of code. The + conditional expression here is sometimes referred to as a "type guard". + + Sometimes it would be convenient to use a user-defined boolean function + as a type guard. Such a function should use ``TypeGuard[...]`` as its + return type to alert static type checkers to this intention. + + Using ``-> TypeGuard`` tells the static type checker that for a given + function: + + 1. The return value is a boolean. + 2. If the return value is ``True``, the type of its argument + is the type inside ``TypeGuard``. + + For example:: + + def is_str(val: Union[str, float]): + # "isinstance" type guard + if isinstance(val, str): + # Type of ``val`` is narrowed to ``str`` + ... + else: + # Else, type of ``val`` is narrowed to ``float``. + ... + + Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower + form of ``TypeA`` (it can even be a wider form) and this may lead to + type-unsafe results. The main reason is to allow for things like + narrowing ``List[object]`` to ``List[str]`` even though the latter is not + a subtype of the former, since ``List`` is invariant. The responsibility of + writing type-safe type guards is left to the user. + + ``TypeGuard`` also works with type variables. For more information, see + PEP 647 (User-Defined Type Guards). + """ + __type__ = None diff --git a/venv/lib/python3.10/site-packages/pytablewriter/error.py b/venv/lib/python3.10/site-packages/pytablewriter/error.py new file mode 100644 index 0000000000000000000000000000000000000000..325be5c2e4395d0898fc7d9b3b43acf011ec48b7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/error.py @@ -0,0 +1,34 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + + +class NotSupportedError(Exception): + pass + + +class EmptyTableNameError(Exception): + """ + Exception raised when a table writer class of the |table_name| attribute + is null and the class is not accepted null |table_name|. + """ + + +class EmptyValueError(Exception): + """ + Exception raised when a table writer class of the |value_matrix| attribute + is null, and the class is not accepted null |value_matrix|. + """ + + +class EmptyTableDataError(Exception): + """ + Exception raised when a table writer class of the |headers| and + |value_matrix| attributes are null. + """ + + +class WriterNotFoundError(Exception): + """ + Exception raised when appropriate loader writer found. + """ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/py.typed b/venv/lib/python3.10/site-packages/pytablewriter/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..77203ea9ead92a316d96114872ae681f5c8e3a73 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__init__.py @@ -0,0 +1,21 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +from ._elasticsearch import ElasticsearchIndexNameSanitizer +from ._excel import sanitize_excel_sheet_name, validate_excel_sheet_name +from ._javascript import JavaScriptVarNameSanitizer, sanitize_js_var_name, validate_js_var_name +from ._python import PythonVarNameSanitizer, sanitize_python_var_name, validate_python_var_name + + +__all__ = ( + "ElasticsearchIndexNameSanitizer", + "JavaScriptVarNameSanitizer", + "PythonVarNameSanitizer", + "sanitize_excel_sheet_name", + "sanitize_js_var_name", + "sanitize_python_var_name", + "validate_excel_sheet_name", + "validate_js_var_name", + "validate_python_var_name", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50d6ba453cadf927f7a00d6cb03647f8dba248e0 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_base.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_base.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..504ff9b7dae2d0a205502919570751e83f7dcd51 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_base.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_elasticsearch.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_elasticsearch.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2779088222bc24bca604dfc4077a1e0d55764af Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_elasticsearch.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_excel.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_excel.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b397602c6653d438dcd380a7b4a42b7beb2f55a Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_excel.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_interface.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c39b6de23d813a7c29aa58e147654826a39eeb7 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_interface.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_javascript.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_javascript.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cfce258434a19d72944fe8facfb5079a0d517553 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_javascript.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_python.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_python.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d482d29e7cafbe954559df3222f3c07e36d97ed Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/__pycache__/_python.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_base.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_base.py new file mode 100644 index 0000000000000000000000000000000000000000..459df620e1e0c006d04f3bbe4acd44f12907b2de --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_base.py @@ -0,0 +1,91 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import abc +import re +from typing import Pattern + +from pathvalidate.error import ErrorReason, ValidationError +from typepy import is_null_string + +from ._interface import NameSanitizer + + +def _preprocess(name: str) -> str: + return name.strip() + + +class VarNameSanitizer(NameSanitizer): + @abc.abstractproperty + def _invalid_var_name_head_re(self) -> Pattern[str]: # pragma: no cover + pass + + @abc.abstractproperty + def _invalid_var_name_re(self) -> Pattern[str]: # pragma: no cover + pass + + def validate(self) -> None: + self._validate(self._value) + + def sanitize(self, replacement_text: str = "") -> str: + var_name = self._invalid_var_name_re.sub(replacement_text, self._str) + + # delete invalid char(s) in the beginning of the variable name + is_require_remove_head = any( + [ + is_null_string(replacement_text), + self._invalid_var_name_head_re.search(replacement_text) is not None, + ] + ) + + if is_require_remove_head: + var_name = self._invalid_var_name_head_re.sub("", var_name) + else: + match = self._invalid_var_name_head_re.search(var_name) + if match is not None: + var_name = match.end() * replacement_text + self._invalid_var_name_head_re.sub( + "", var_name + ) + + if not var_name: + return "" + + try: + self._validate(var_name) + except ValidationError as e: + if e.reason == ErrorReason.RESERVED_NAME and e.reusable_name is False: + var_name += "_" + + return var_name + + def _validate(self, value: str) -> None: + self._validate_null_string(value) + + unicode_var_name = _preprocess(value) + + if self._is_reserved_keyword(unicode_var_name): + raise ValidationError( + description=f"{unicode_var_name:s} is a reserved keyword by python", + reason=ErrorReason.RESERVED_NAME, + reusable_name=False, + reserved_name=unicode_var_name, + ) + + match = self._invalid_var_name_re.search(unicode_var_name) + if match is not None: + raise ValidationError( + description="invalid char found in the variable name: '{}'".format( + re.escape(match.group()) + ), + reason=ErrorReason.INVALID_CHARACTER, + ) + + match = self._invalid_var_name_head_re.search(unicode_var_name) + if match is not None: + raise ValidationError( + description="the first character of the variable name is invalid: '{}'".format( + re.escape(match.group()) + ), + reason=ErrorReason.INVALID_CHARACTER, + ) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_elasticsearch.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_elasticsearch.py new file mode 100644 index 0000000000000000000000000000000000000000..d722e317d618cc4b9266b7813fdc79daeaaba954 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_elasticsearch.py @@ -0,0 +1,27 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re +from typing import ClassVar, List, Pattern + +from ._base import VarNameSanitizer + + +class ElasticsearchIndexNameSanitizer(VarNameSanitizer): + __RE_INVALID_INDEX_NAME: ClassVar[Pattern[str]] = re.compile( + "[" + re.escape('\\/*?"<>|,"') + r"\s]+" + ) + __RE_INVALID_INDEX_NAME_HEAD: ClassVar[Pattern[str]] = re.compile("^[_]+") + + @property + def reserved_keywords(self) -> List[str]: + return [] + + @property + def _invalid_var_name_head_re(self) -> Pattern[str]: + return self.__RE_INVALID_INDEX_NAME_HEAD + + @property + def _invalid_var_name_re(self) -> Pattern[str]: + return self.__RE_INVALID_INDEX_NAME diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_excel.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_excel.py new file mode 100644 index 0000000000000000000000000000000000000000..cf5e096c9a77bbda8305f214d81667b92ede8a44 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_excel.py @@ -0,0 +1,75 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re + +from pathvalidate import validate_pathtype +from pathvalidate.error import ErrorReason, ValidationError + +from ._base import _preprocess + + +__MAX_SHEET_NAME_LEN = 31 + +__INVALID_EXCEL_CHARS = "[]:*?/\\" + +__RE_INVALID_EXCEL_SHEET_NAME = re.compile(f"[{re.escape(__INVALID_EXCEL_CHARS):s}]", re.UNICODE) + + +def validate_excel_sheet_name(sheet_name: str) -> None: + """ + :param str sheet_name: Excel sheet name to validate. + :raises pathvalidate.ValidationError (ErrorReason.INVALID_CHARACTER): + If the ``sheet_name`` includes invalid char(s): + |invalid_excel_sheet_chars|. + :raises pathvalidate.ValidationError (ErrorReason.INVALID_LENGTH): + If the ``sheet_name`` is longer than 31 characters. + """ + + validate_pathtype(sheet_name) + + if len(sheet_name) > __MAX_SHEET_NAME_LEN: + raise ValidationError( + description="sheet name is too long: expected<={:d}, actual={:d}".format( + __MAX_SHEET_NAME_LEN, len(sheet_name) + ), + reason=ErrorReason.INVALID_LENGTH, + ) + + unicode_sheet_name = _preprocess(sheet_name) + match = __RE_INVALID_EXCEL_SHEET_NAME.search(unicode_sheet_name) + if match is not None: + raise ValidationError( + description="invalid char found in the sheet name: '{:s}'".format( + re.escape(match.group()) + ), + reason=ErrorReason.INVALID_CHARACTER, + ) + + +def sanitize_excel_sheet_name(sheet_name: str, replacement_text: str = "") -> str: + """ + Replace invalid characters for an Excel sheet name within + the ``sheet_name`` with the ``replacement_text``. + Invalid characters are as follows: + |invalid_excel_sheet_chars|. + The ``sheet_name`` truncate to 31 characters + (max sheet name length of Excel) from the head, if the length + of the name is exceed 31 characters. + + :param str sheet_name: Excel sheet name to sanitize. + :param str replacement_text: Replacement text. + :return: A replacement string. + :rtype: str + :raises ValueError: If the ``sheet_name`` is an invalid sheet name. + """ + + try: + unicode_sheet_name = _preprocess(sheet_name) + except AttributeError as e: + raise ValueError(e) + + modify_sheet_name = __RE_INVALID_EXCEL_SHEET_NAME.sub(replacement_text, unicode_sheet_name) + + return modify_sheet_name[:__MAX_SHEET_NAME_LEN] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_interface.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..fefb5612f12e10e0014dedc6489b5549e93e7e1c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_interface.py @@ -0,0 +1,38 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import abc +from typing import List + +from pathvalidate import validate_pathtype + + +class NameSanitizer(metaclass=abc.ABCMeta): + @abc.abstractproperty + def reserved_keywords(self) -> List[str]: # pragma: no cover + pass + + @abc.abstractmethod + def validate(self) -> None: # pragma: no cover + pass + + @abc.abstractmethod + def sanitize(self, replacement_text: str = "") -> str: # pragma: no cover + pass + + @property + def _str(self) -> str: + return str(self._value) + + def __init__(self, value: str) -> None: + self._validate_null_string(value) + + self._value = value.strip() + + def _is_reserved_keyword(self, value: str) -> bool: + return value in self.reserved_keywords + + @staticmethod + def _validate_null_string(text: str) -> None: + validate_pathtype(text) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_javascript.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_javascript.py new file mode 100644 index 0000000000000000000000000000000000000000..8fe67a65b337421d2b406421c6def39d44ee9b2d --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_javascript.py @@ -0,0 +1,143 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re +from typing import List, Pattern + +from ._base import VarNameSanitizer + + +class JavaScriptVarNameSanitizer(VarNameSanitizer): + __JS_RESERVED_KEYWORDS_ES6 = [ + "break", + "case", + "catch", + "class", + "const", + "continue", + "debugger", + "default", + "delete", + "do", + "else", + "export", + "extends", + "finally", + "for", + "function", + "if", + "import", + "in", + "instanceof", + "new", + "return", + "super", + "switch", + "this", + "throw", + "try", + "typeof", + "var", + "void", + "while", + "with", + "yield", + ] + __JS_RESERVED_KEYWORDS_FUTURE = [ + "enum", + "implements", + "interface", + "let", + "package", + "private", + "protected", + "public", + "static", + "await", + "abstract", + "boolean", + "byte", + "char", + "double", + "final", + "float", + "goto", + "int", + "long", + "native", + "short", + "synchronized", + "throws", + "transient", + "volatile", + ] + __JS_BUILTIN_CONSTANTS = ["null", "true", "false"] + + __RE_INVALID_VAR_NAME = re.compile("[^a-zA-Z0-9_$]") + __RE_INVALID_VAR_NAME_HEAD = re.compile("^[^a-zA-Z$]+") + + @property + def reserved_keywords(self) -> List[str]: + return ( + self.__JS_RESERVED_KEYWORDS_ES6 + + self.__JS_RESERVED_KEYWORDS_FUTURE + + self.__JS_BUILTIN_CONSTANTS + ) + + @property + def _invalid_var_name_head_re(self) -> Pattern[str]: + return self.__RE_INVALID_VAR_NAME_HEAD + + @property + def _invalid_var_name_re(self) -> Pattern[str]: + return self.__RE_INVALID_VAR_NAME + + +def validate_js_var_name(var_name: str) -> None: + """ + :param str var_name: Name to validate. + :raises pathvalidate.ValidationError (ErrorReason.INVALID_CHARACTER): + If the ``var_name`` is invalid as a JavaScript identifier. + :raises pathvalidate.ValidationError (ErrorReason.RESERVED_NAME): + If the ``var_name`` is equals to + `JavaScript reserved keywords + `__. + + .. note:: + + Currently, not supported unicode variable names. + """ + + JavaScriptVarNameSanitizer(var_name).validate() + + +def sanitize_js_var_name(var_name: str, replacement_text: str = "") -> str: + """ + Make a valid JavaScript variable name from ``var_name``. + + To make a valid name: + + - Replace invalid characters for a JavaScript variable name within + the ``var_name`` with the ``replacement_text`` + - Delete invalid chars for the beginning of the variable name + - Append underscore (``"_"``) at the tail of the name if sanitized name + is one of the JavaScript reserved names + + :JavaScriptstr filename: Name to sanitize. + :param str replacement_text: Replacement text. + :return: A replacement string. + :rtype: str + :raises ValueError: If ``var_name`` or ``replacement_text`` is invalid. + + :Example: + :ref:`example-sanitize-var-name` + + .. note:: + Currently, not supported Unicode variable names. + + .. seealso:: + :py:func:`.validate_js_var_name` + """ + + return JavaScriptVarNameSanitizer(var_name).sanitize(replacement_text) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_python.py b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_python.py new file mode 100644 index 0000000000000000000000000000000000000000..956567caf0230b611cfe1a659fff11486c8048e7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/sanitizer/_python.py @@ -0,0 +1,117 @@ +""" +.. codeauthor:: Tsuyoshi Hombashi +""" + +import re +from typing import List, Pattern + +from ._base import VarNameSanitizer + + +class PythonVarNameSanitizer(VarNameSanitizer): + __PYTHON_RESERVED_KEYWORDS = [ + "and", + "del", + "from", + "not", + "while", + "as", + "elif", + "global", + "or", + "with", + "assert", + "else", + "if", + "pass", + "yield", + "break", + "except", + "import", + "print", + "class", + "exec", + "in", + "raise", + "continue", + "finally", + "is", + "return", + "def", + "for", + "lambda", + "try", + ] + __PYTHON_BUILTIN_CONSTANTS = [ + "False", + "True", + "None", + "NotImplemented", + "Ellipsis", + "__debug__", + ] + + __RE_INVALID_VAR_NAME = re.compile("[^a-zA-Z0-9_]") + __RE_INVALID_VAR_NAME_HEAD = re.compile("^[^a-zA-Z]+") + + @property + def reserved_keywords(self) -> List[str]: + return self.__PYTHON_RESERVED_KEYWORDS + self.__PYTHON_BUILTIN_CONSTANTS + + @property + def _invalid_var_name_head_re(self) -> Pattern[str]: + return self.__RE_INVALID_VAR_NAME_HEAD + + @property + def _invalid_var_name_re(self) -> Pattern[str]: + return self.__RE_INVALID_VAR_NAME + + +def validate_python_var_name(var_name: str) -> None: + """ + :param str var_name: Name to validate. + :raises pathvalidate.ValidationError (ErrorReason.INVALID_CHARACTER): + If the ``var_name`` is invalid as + `Python identifier + `__. + :raises pathvalidate.ValidationError (ErrorReason.RESERVED_NAME): + If the ``var_name`` is equals to + `Python reserved keywords + `__ + or + `Python built-in constants + `__. + + :Example: + :ref:`example-validate-var-name` + """ + + PythonVarNameSanitizer(var_name).validate() + + +def sanitize_python_var_name(var_name: str, replacement_text: str = "") -> str: + """ + Make a valid Python variable name from ``var_name``. + + To make a valid name: + + - Replace invalid characters for a Python variable name within + the ``var_name`` with the ``replacement_text`` + - Delete invalid chars for the beginning of the variable name + - Append underscore (``"_"``) at the tail of the name if sanitized name + is one of the Python reserved names + + :param str filename: Name to sanitize. + :param str replacement_text: Replacement text. + :return: A replacement string. + :rtype: str + :raises ValueError: If ``var_name`` or ``replacement_text`` is invalid. + + :Example: + :ref:`example-sanitize-var-name` + + .. seealso:: + :py:func:`.validate_python_var_name` + """ + + return PythonVarNameSanitizer(var_name).sanitize(replacement_text) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/style/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d3448ddae02559bb6523dbad4116d8e68f7123ac --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/__init__.py @@ -0,0 +1,53 @@ +from dataproperty import Align, Format + +from ._cell import Cell +from ._font import FontSize, FontStyle, FontWeight +from ._style import DecorationLine, Style, ThousandSeparator, VerticalAlign +from ._styler import ( + GFMarkdownStyler, + HtmlStyler, + LatexStyler, + MarkdownStyler, + NullStyler, + ReStructuredTextStyler, + TextStyler, + get_align_char, +) +from ._styler_interface import StylerInterface +from ._theme import ( + CheckStyleFilterKeywordArgsFunc, + ColSeparatorStyleFilterFunc, + StyleFilterFunc, + Theme, + fetch_theme, + list_themes, +) + + +__all__ = ( + "Align", + "Format", + "Cell", + "FontSize", + "FontStyle", + "FontWeight", + "Style", + "ThousandSeparator", + "VerticalAlign", + "DecorationLine", + "GFMarkdownStyler", + "HtmlStyler", + "LatexStyler", + "MarkdownStyler", + "NullStyler", + "ReStructuredTextStyler", + "StylerInterface", + "TextStyler", + "CheckStyleFilterKeywordArgsFunc", + "ColSeparatorStyleFilterFunc", + "StyleFilterFunc", + "Theme", + "get_align_char", + "fetch_theme", + "list_themes", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8de8cff38f3625801d5e05349a91509fd8fc7bc1 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_cell.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_cell.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fbbc6f8b3d0e90ad8995011a68ce98dd41a48e9 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_cell.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_font.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_font.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f7958c535bf5e5c39aeefafc443ae9d2d1e524 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_font.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_style.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_style.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..227370a2500fdc83716d1789f39ce893e22b756b Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_style.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5edb3a973b550d6c1f68e47bacedbbee1ee59a04 Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler_interface.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler_interface.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c8b5c9c3dce2283c05f3471e477d95af5dca33e Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_styler_interface.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_theme.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_theme.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7146a315f0783f05f0bf515876f467a36b8040f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/style/__pycache__/_theme.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/_cell.py b/venv/lib/python3.10/site-packages/pytablewriter/style/_cell.py new file mode 100644 index 0000000000000000000000000000000000000000..67f352bbbf24a5a259db456053837e69555e6cb8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/_cell.py @@ -0,0 +1,30 @@ +from dataclasses import dataclass +from typing import Any + +from ._style import Style + + +@dataclass(frozen=True) +class Cell: + """ + A data class representing a cell in a table. + """ + + row: int + """row index. ``-1`` means that the table header row.""" + + col: int + """column index.""" + + value: Any + """data for the cell.""" + + default_style: Style + """default |Style| for the cell.""" + + def is_header_row(self) -> bool: + """ + Return |True| if the cell is a header. + """ + + return self.row < 0 diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/_font.py b/venv/lib/python3.10/site-packages/pytablewriter/style/_font.py new file mode 100644 index 0000000000000000000000000000000000000000..1613721072682180ae8ca8e247067d2906279ee4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/_font.py @@ -0,0 +1,23 @@ +from enum import Enum, unique + + +@unique +class FontSize(Enum): + NONE = "none" + TINY = "tiny" + SMALL = "small" + MEDIUM = "medium" + LARGE = "large" + + +@unique +class FontStyle(Enum): + NORMAL = "normal" + ITALIC = "italic" + TYPEWRITER = "typewriter" + + +@unique +class FontWeight(Enum): + NORMAL = "normal" + BOLD = "bold" diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/_style.py b/venv/lib/python3.10/site-packages/pytablewriter/style/_style.py new file mode 100644 index 0000000000000000000000000000000000000000..d360c5a7281e459b13d066dd342cb790b83b299c --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/_style.py @@ -0,0 +1,376 @@ +import warnings +from enum import Enum, unique +from typing import Any, Dict, Optional, Union + +from dataproperty import Align +from tcolorpy import Color + +from .._function import normalize_enum +from ._font import FontSize, FontStyle, FontWeight + + +@unique +class DecorationLine(Enum): + NONE = "none" + LINE_THROUGH = "line_through" + STRIKE = "strike" + UNDERLINE = "underline" + + +@unique +class ThousandSeparator(Enum): + NONE = "none" #: no thousands separator + COMMA = "comma" #: ``','`` as thousands separator + SPACE = "space" #: ``' '`` as thousands separator + UNDERSCORE = "underscore" #: ``'_'`` as thousands separator + + +@unique +class VerticalAlign(Enum): + BASELINE = (1 << 0, "baseline") + TOP = (1 << 1, "top") + MIDDLE = (1 << 2, "middle") + BOTTOM = (1 << 3, "bottom") + + @property + def align_code(self) -> int: + return self.__align_code + + @property + def align_str(self) -> str: + return self.__align_string + + def __init__(self, code: int, string: str) -> None: + self.__align_code = code + self.__align_string = string + + +_s_to_ts: Dict[str, ThousandSeparator] = { + "": ThousandSeparator.NONE, + ",": ThousandSeparator.COMMA, + " ": ThousandSeparator.SPACE, + "_": ThousandSeparator.UNDERSCORE, +} + + +def _normalize_thousand_separator(value: Union[str, ThousandSeparator]) -> ThousandSeparator: + if isinstance(value, ThousandSeparator): + return value + + thousand_separator = normalize_enum( + value, + ThousandSeparator, + default=ThousandSeparator.NONE, + validate=False, + ) + if isinstance(thousand_separator, ThousandSeparator): + return thousand_separator + + norm_value = _s_to_ts.get(value) + if norm_value is None: + raise ValueError(f"unknown thousand separator: {value}") + + return norm_value + + +class Style: + """Style specifier class for table elements. + + Args: + color (Union[|str|, tcolorpy.Color, |None|]): + Text color for cells. + When using str, specify a color code (``"#XXXXXX"``) or a color name. + + .. note:: + In the current version, only applicable for part of text format writer classes. + + fg_color (Union[|str|, tcolorpy.Color, |None|]): + Alias to :py:attr:`~.color`. + + bg_color (Union[|str|, tcolorpy.Color, |None|]): + Background color for cells. + When using str, specify a color code (``"#XXXXXX"``) or a color name. + + .. note:: + In the current version, only applicable for part of text format writer classes. + + align (|str| / :py:class:`~.style.Align`): + Horizontal text alignment for cells. + This can be only applied for text format writer classes. + Possible string values are: + + - ``"auto"`` (default) + - Detect data type for each column and set alignment that appropriate + for the type automatically + - ``"left"`` + - ``"right"`` + - ``"center"`` + + vertical_align (|str| / :py:class:`~.style.VerticalAlign`): + Vertical text alignment for cells. + This can be only applied for HtmlTableWriter class. + Possible string values are: + + - ``"baseline"`` (default) + - ``"top"`` + - ``"middle"`` + - ``"bottom"`` + + font_size (|str| / :py:class:`~.style.FontSize`): + Font size specification for cells in a column. + This can be only applied for HTML/Latex writer classes. + Possible string values are: + + - ``"tiny"`` + - ``"small"`` + - ``"medium"`` + - ``"large"`` + - ``"none"`` (default: no font size specification) + + font_weight (|str| / :py:class:`~.style.FontWeight`): + Font weight specification for cells in a column. + This can be only applied for HTML/Latex/Markdown writer classes. + Possible string values are: + + - ``"normal"`` (default) + - ``"bold"`` + + font_style (|str| / :py:class:`~.style.FontStyle`): + Font style specification for cells in a column. + This can be applied only for HTML/Latex/Markdown writer classes. + Possible string values are: + + - ``"normal"`` (default) + - ``"italic"`` + - ``"typewriter"`` (only for Latex writer) + + decoration_line (|str| / :py:class:`~.style.DecorationLine`) + + Experiental. + Possible string values are: + + - ``"line-through"`` + - ``"strike"`` (alias for ``"line-through"``) + - ``"underline"`` + - ``"none"`` (default) + + thousand_separator (|str| / :py:class:`~.style.ThousandSeparator`): + Thousand separator specification for numbers in a column. + This can be only applied for text format writer classes. + Possible string values are: + + - ``","``/``"comma"`` + - ``" "``/``"space"`` + - ``"_"``/``"underscore"`` + - ``""``/``"none"`` (default) + + Example: + :ref:`example-style` + """ + + @property + def align(self) -> Align: + return self.__align + + @align.setter + def align(self, value: Align) -> None: + self.__align = value + + @property + def vertical_align(self) -> VerticalAlign: + return self.__valign + + @property + def decoration_line(self) -> DecorationLine: + return self.__decoration_line + + @property + def font_size(self) -> FontSize: + return self.__font_size + + @property + def font_style(self) -> FontStyle: + return self.__font_style + + @property + def font_weight(self) -> FontWeight: + return self.__font_weight + + @property + def color(self) -> Optional[Color]: + return self.__fg_color + + @property + def fg_color(self) -> Optional[Color]: + return self.__fg_color + + @property + def bg_color(self) -> Optional[Color]: + return self.__bg_color + + @property + def thousand_separator(self) -> ThousandSeparator: + return self.__thousand_separator + + @property + def padding(self) -> Optional[int]: + return self.__padding + + @padding.setter + def padding(self, value: Optional[int]) -> None: + self.__padding = value + + def __init__(self, **kwargs: Any) -> None: + self.__kwargs = kwargs + self.__update_color(initialize=True) + self.__update_align(initialize=True) + self.__update_font(initialize=True) + self.__update_misc(initialize=True) + + if self.__kwargs: + warnings.warn(f"unknown style attributes found: {self.__kwargs.keys()}", UserWarning) + + def __repr__(self) -> str: + items = [] + + if self.align: + items.append(f"align={self.align.align_string}") + if self.padding is not None: + items.append(f"padding={self.padding}") + if self.vertical_align: + items.append(f"valign={self.vertical_align.align_str}") + if self.color: + items.append(f"color={self.color}") + if self.bg_color: + items.append(f"bg_color={self.bg_color}") + if self.decoration_line is not DecorationLine.NONE: + items.append(f"decoration_line={self.decoration_line.value}") + if self.font_size is not FontSize.NONE: + items.append(f"font_size={self.font_size.value}") + if self.font_style: + items.append(f"font_style={self.font_style.value}") + if self.font_weight: + items.append(f"font_weight={self.font_weight.value}") + if self.thousand_separator is not ThousandSeparator.NONE: + items.append(f"thousand_separator={self.thousand_separator.value}") + + return "({})".format(", ".join(items)) + + def __eq__(self, other: Any) -> bool: + if self.__class__ is not other.__class__: + return False + + return all( + [ + self.align == other.align, + self.font_size == other.font_size, + self.font_style == other.font_style, + self.font_weight == other.font_weight, + self.thousand_separator == other.thousand_separator, + ] + ) + + def __ne__(self, other: Any) -> bool: + if self.__class__ is not other.__class__: + return True + + return not self.__eq__(other) + + def update(self, **kwargs: Any) -> None: + """Update specified style attributes.""" + self.__kwargs = kwargs + self.__update_color(initialize=False) + self.__update_align(initialize=False) + self.__update_font(initialize=False) + self.__update_misc(initialize=False) + + if self.__kwargs: + warnings.warn(f"unknown style attributes found: {self.__kwargs.keys()}", UserWarning) + + def __update_color(self, initialize: bool) -> None: + fg_color = self.__kwargs.pop("color", None) or self.__kwargs.pop("fg_color", None) + if fg_color: + self.__fg_color: Optional[Color] = Color(fg_color) + elif initialize: + self.__fg_color = None + + bg_color = self.__kwargs.pop("bg_color", None) + if bg_color: + self.__bg_color: Optional[Color] = Color(bg_color) + elif initialize: + self.__bg_color = None + + def __update_font(self, initialize: bool) -> None: + font_size = self.__kwargs.pop("font_size", None) + if font_size: + self.__font_size = normalize_enum( + font_size, + FontSize, + validate=False, + default=FontSize.NONE, + ) + elif initialize: + self.__font_size = FontSize.NONE + self.__validate_attr("font_size", (FontSize, str)) + + font_style = self.__kwargs.pop("font_style", None) + if font_style: + self.__font_style = normalize_enum(font_style, FontStyle, default=FontStyle.NORMAL) + elif initialize: + self.__font_style = FontStyle.NORMAL + self.__validate_attr("font_style", FontStyle) + + font_weight = self.__kwargs.pop("font_weight", None) + if font_weight: + self.__font_weight = normalize_enum(font_weight, FontWeight, default=FontWeight.NORMAL) + elif initialize: + self.__font_weight = FontWeight.NORMAL + self.__validate_attr("font_weight", FontWeight) + + def __update_align(self, initialize: bool) -> None: + align = self.__kwargs.pop("align", None) + if align: + self.__align = normalize_enum(align, Align, default=Align.AUTO) + elif initialize: + self.__align = Align.AUTO + self.__validate_attr("align", Align) + + valign = self.__kwargs.pop("vertical_align", None) + if valign: + self.__valign = normalize_enum(valign, VerticalAlign, default=VerticalAlign.BASELINE) + elif initialize: + self.__valign = VerticalAlign.BASELINE + self.__validate_attr("vertical_align", VerticalAlign) + + def __update_misc(self, initialize: bool) -> None: + padding = self.__kwargs.pop("padding", None) + if padding is not None: + self.__padding = padding + elif initialize: + self.__padding = None + + decoration_line = self.__kwargs.pop("decoration_line", None) + if decoration_line: + self.__decoration_line = normalize_enum( + decoration_line, DecorationLine, default=DecorationLine.NONE + ) + elif initialize: + self.__decoration_line = DecorationLine.NONE + self.__validate_attr("decoration_line", DecorationLine) + + thousand_separator = self.__kwargs.pop("thousand_separator", None) + if thousand_separator: + self.__thousand_separator = _normalize_thousand_separator(thousand_separator) + elif initialize: + self.__thousand_separator = ThousandSeparator.NONE + self.__validate_attr("thousand_separator", ThousandSeparator) + + def __validate_attr(self, attr_name: str, expected_type: Any) -> None: + value = getattr(self, attr_name) + if isinstance(expected_type, (list, tuple)): + expected = " or ".join(c.__name__ for c in expected_type) + else: + expected = expected_type.__name__ + + if not isinstance(value, expected_type): + raise TypeError(f"{attr_name} must be instance of {expected}: actual={type(value)}") diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/_styler.py b/venv/lib/python3.10/site-packages/pytablewriter/style/_styler.py new file mode 100644 index 0000000000000000000000000000000000000000..3f8ff5b07b1641903277feb24a27b9a2553fad09 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/_styler.py @@ -0,0 +1,331 @@ +import re +from typing import TYPE_CHECKING, Any, Dict, Optional + +from dataproperty import Align +from tcolorpy import Color, tcolor + +from ._font import FontSize, FontStyle, FontWeight +from ._style import DecorationLine, Style, ThousandSeparator +from ._styler_interface import StylerInterface + + +if TYPE_CHECKING: + from ..writer._table_writer import AbstractTableWriter + + +_align_char_mapping: Dict[Align, str] = { + Align.AUTO: "<", + Align.LEFT: "<", + Align.RIGHT: ">", + Align.CENTER: "^", +} + + +def get_align_char(align: Align) -> str: + return _align_char_mapping[align] + + +def _to_latex_rgb(color: Color, value: str) -> str: + return r"\textcolor{" + color.color_code + "}{" + value + "}" + + +class AbstractStyler(StylerInterface): + def __init__(self, writer: "AbstractTableWriter") -> None: + self._writer = writer + self._font_size_map = self._get_font_size_map() + + def get_font_size(self, style: Style) -> Optional[str]: + return self._font_size_map.get(style.font_size) + + def get_additional_char_width(self, style: Style) -> int: + return 0 + + def apply(self, value: Any, style: Style) -> str: + return value + + def apply_align(self, value: str, style: Style) -> str: + return value + + def apply_terminal_style(self, value: str, style: Style) -> str: + return value + + def _get_font_size_map(self) -> Dict[FontSize, str]: + return {} + + +class NullStyler(AbstractStyler): + def get_font_size(self, style: Style) -> Optional[str]: + return "" + + +class TextStyler(AbstractStyler): + def apply_terminal_style(self, value: str, style: Style) -> str: + if not self._writer.enable_ansi_escape: + return value + + ansi_styles = [] + + if style.decoration_line in (DecorationLine.STRIKE, DecorationLine.LINE_THROUGH): + ansi_styles.append("strike") + if style.decoration_line == DecorationLine.UNDERLINE: + ansi_styles.append("underline") + + if style.font_weight == FontWeight.BOLD: + ansi_styles.append("bold") + + if self._writer.colorize_terminal: + return tcolor(value, color=style.color, bg_color=style.bg_color, styles=ansi_styles) + + return tcolor(value, styles=ansi_styles) + + def __get_align_format(self, style: Style) -> str: + align_char = get_align_char(style.align) + format_items = ["{:" + align_char] + if style.padding is not None and style.padding > 0: + format_items.append(str(style.padding)) + format_items.append("s}") + + return "".join(format_items) + + def apply_align(self, value: str, style: Style) -> str: + return self.__get_align_format(style).format(value) + + def apply(self, value: str, style: Style) -> str: + if value: + if style.thousand_separator == ThousandSeparator.SPACE: + value = value.replace(",", " ") + elif style.thousand_separator == ThousandSeparator.UNDERSCORE: + value = value.replace(",", "_") + + return value + + +class HtmlStyler(TextStyler): + def _get_font_size_map(self) -> Dict[FontSize, str]: + return { + FontSize.TINY: "font-size:x-small", + FontSize.SMALL: "font-size:small", + FontSize.MEDIUM: "font-size:medium", + FontSize.LARGE: "font-size:large", + } + + +class LatexStyler(TextStyler): + class Command: + BOLD = r"\bf" + ITALIC = r"\it" + TYPEWRITER = r"\tt" + UNDERLINE = r"\underline" + STRIKEOUT = r"\sout" + + def get_additional_char_width(self, style: Style) -> int: + dummy_value = "d" + applied_value = self.apply(dummy_value, style) + + return len(applied_value) - len(dummy_value) + + def apply(self, value: Any, style: Style) -> str: + value = super().apply(value, style) + if not value: + return value + + font_size = self.get_font_size(style) + commands = [] + + if font_size: + commands.append(font_size) + + if style.font_weight == FontWeight.BOLD: + commands.append(self.Command.BOLD) + + if style.font_style == FontStyle.ITALIC: + commands.append(self.Command.ITALIC) + elif style.font_style == FontStyle.TYPEWRITER: + commands.append(self.Command.TYPEWRITER) + + if style.decoration_line in (DecorationLine.STRIKE, DecorationLine.LINE_THROUGH): + commands.append(self.Command.STRIKEOUT) + elif style.decoration_line == DecorationLine.UNDERLINE: + commands.append(self.Command.UNDERLINE) + + for cmd in commands: + value = cmd + "{" + value + "}" + + value = self.__apply_color(value, style) + + return value + + def __apply_color(self, value: str, style: Style) -> str: + if not style.fg_color: + return value + + value = _to_latex_rgb(style.fg_color, value) + + return value + + def _get_font_size_map(self) -> Dict[FontSize, str]: + return { + FontSize.TINY: r"\tiny", + FontSize.SMALL: r"\small", + FontSize.MEDIUM: r"\normalsize", + FontSize.LARGE: r"\large", + } + + +class MarkdownStyler(TextStyler): + def get_additional_char_width(self, style: Style) -> int: + width = 0 + + if style.font_weight == FontWeight.BOLD: + width += 4 + + if style.font_style == FontStyle.ITALIC: + width += 2 + + return width + + def apply(self, value: Any, style: Style) -> str: + value = super().apply(value, style) + if not value: + return value + + value = self._apply_font_weight(value, style) + value = self._apply_font_style(value, style) + + return value + + def _apply_font_weight(self, value: Any, style: Style) -> str: + if style.font_weight == FontWeight.BOLD: + value = f"**{value}**" + + return value + + def _apply_font_style(self, value: Any, style: Style) -> str: + if style.font_style == FontStyle.ITALIC: + value = f"_{value}_" + + return value + + +class GFMarkdownStyler(MarkdownStyler): + """ + A styler class for GitHub Flavored Markdown + """ + + def get_additional_char_width(self, style: Style) -> int: + width = super().get_additional_char_width(style) + + if style.decoration_line in (DecorationLine.STRIKE, DecorationLine.LINE_THROUGH): + width += 4 + + if self.__use_latex(style): + dummy_value = "d" + value = self.apply(dummy_value, style) + width += len(value) - len(dummy_value) + + return width + + def apply(self, value: Any, style: Style) -> str: + value = super().apply(value, style) + if not value: + return value + + use_latex = self.__use_latex(style) + + if use_latex: + value = self.__escape_for_latex(value) + value = LatexStyler.Command.TYPEWRITER + "{" + value + "}" + + value = self.__apply_decoration_line(value, style) + + if use_latex: + value = r"$$" + self.__apply_color(value, style) + r"$$" + + return value + + def __use_latex(self, style: Style) -> bool: + return style.fg_color is not None + + def __escape_for_latex(self, value: str) -> str: + value = re.sub(r"[\s_]", r"\\\\\g<0>", value) + return value.replace("-", r"\text{-}") + + def __apply_decoration_line(self, value: str, style: Style) -> str: + use_latex = self.__use_latex(style) + + if style.decoration_line in (DecorationLine.STRIKE, DecorationLine.LINE_THROUGH): + if use_latex: + value = r"\enclose{horizontalstrike}{" + value + "}" + else: + value = f"~~{value}~~" + elif style.decoration_line == DecorationLine.UNDERLINE: + if use_latex: + value = r"\underline{" + value + "}" + + return value + + def __apply_color(self, value: str, style: Style) -> str: + if not style.fg_color: + return value + + return _to_latex_rgb(style.fg_color, value) + + def _apply_font_weight(self, value: Any, style: Style) -> str: + if not self.__use_latex(style): + return super()._apply_font_weight(value, style) + + if style.font_weight == FontWeight.BOLD: + value = LatexStyler.Command.BOLD + "{" + value + "}" + + return value + + def _apply_font_style(self, value: Any, style: Style) -> str: + if not self.__use_latex(style): + return super()._apply_font_style(value, style) + + if style.font_style == FontStyle.ITALIC: + value = LatexStyler.Command.ITALIC + "{" + value + "}" + + return value + + +class ReStructuredTextStyler(TextStyler): + def get_additional_char_width(self, style: Style) -> int: + from ..writer import RstCsvTableWriter + + width = 0 + + if style.font_weight == FontWeight.BOLD: + width += 4 + elif style.font_style == FontStyle.ITALIC: + width += 2 + + if ( + style.thousand_separator == ThousandSeparator.COMMA + and self._writer.format_name == RstCsvTableWriter.FORMAT_NAME + ): + width += 2 + + return width + + def apply(self, value: Any, style: Style) -> str: + from ..writer import RstCsvTableWriter + + value = super().apply(value, style) + if not value: + return value + + if style.font_weight == FontWeight.BOLD: + value = f"**{value}**" + elif style.font_style == FontStyle.ITALIC: + # in reStructuredText, some custom style definition will be required to + # set for both bold and italic (currently not supported) + value = f"*{value}*" + + if ( + style.thousand_separator == ThousandSeparator.COMMA + and self._writer.format_name == RstCsvTableWriter.FORMAT_NAME + ): + value = f'"{value}"' + + return value diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/_styler_interface.py b/venv/lib/python3.10/site-packages/pytablewriter/style/_styler_interface.py new file mode 100644 index 0000000000000000000000000000000000000000..498e7280b914f781d501fb44df98420b1830c9fe --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/_styler_interface.py @@ -0,0 +1,26 @@ +import abc +from typing import Any, Optional + +from ._style import Style + + +class StylerInterface(metaclass=abc.ABCMeta): + @abc.abstractmethod + def apply(self, value: Any, style: Style) -> str: # pragma: no cover + raise NotImplementedError() + + @abc.abstractmethod + def apply_align(self, value: str, style: Style) -> str: # pragma: no cover + raise NotImplementedError() + + @abc.abstractmethod + def apply_terminal_style(self, value: str, style: Style) -> str: # pragma: no cover + raise NotImplementedError() + + @abc.abstractmethod + def get_font_size(self, style: Style) -> Optional[str]: # pragma: no cover + raise NotImplementedError() + + @abc.abstractmethod + def get_additional_char_width(self, style: Style) -> int: # pragma: no cover + raise NotImplementedError() diff --git a/venv/lib/python3.10/site-packages/pytablewriter/style/_theme.py b/venv/lib/python3.10/site-packages/pytablewriter/style/_theme.py new file mode 100644 index 0000000000000000000000000000000000000000..0993dd9f0c0720bd2b205e6d2aa5dffabf4f6185 --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/style/_theme.py @@ -0,0 +1,101 @@ +import importlib +import pkgutil +import re +from typing import Any, Dict, NamedTuple, Optional, Sequence + +from .._logger import logger +from ..style import Cell, Style + + +try: + from typing import Protocol +except ImportError: + # typing.Protocol is only available starting from Python 3.8. + from .._typing import Protocol # type: ignore + +PLUGIN_NAME_PEFIX = "pytablewriter" +PLUGIN_NAME_SUFFIX = "theme" +KNOWN_PLUGINS = ( + f"{PLUGIN_NAME_PEFIX}_altrow_{PLUGIN_NAME_SUFFIX}", + f"{PLUGIN_NAME_PEFIX}_altcol_{PLUGIN_NAME_SUFFIX}", +) + + +class StyleFilterFunc(Protocol): + def __call__(self, cell: Cell, **kwargs: Any) -> Optional[Style]: + ... + + +class ColSeparatorStyleFilterFunc(Protocol): + def __call__( + self, left_cell: Optional[Cell], right_cell: Optional[Cell], **kwargs: Any + ) -> Optional[Style]: + ... + + +class CheckStyleFilterKeywordArgsFunc(Protocol): + def __call__(self, **kwargs: Any) -> None: + ... + + +class Theme(NamedTuple): + style_filter: Optional[StyleFilterFunc] + col_separator_style_filter: Optional[ColSeparatorStyleFilterFunc] + check_style_filter_kwargs: Optional[CheckStyleFilterKeywordArgsFunc] + + +def list_themes() -> Sequence[str]: + return list(load_ptw_plugins()) + + +def load_ptw_plugins() -> Dict[str, Theme]: + plugin_regexp = re.compile( + rf"^{PLUGIN_NAME_PEFIX}[_-].+[_-]{PLUGIN_NAME_SUFFIX}", re.IGNORECASE + ) + + discovered_plugins = { + name: importlib.import_module(name) + for _finder, name, _ispkg in pkgutil.iter_modules() + if plugin_regexp.search(name) is not None + } + + logger.debug(f"discovered_plugins: {list(discovered_plugins)}") + + themes: Dict[str, Theme] = {} + for theme, plugin in discovered_plugins.items(): + style_filter = plugin.style_filter if hasattr(plugin, "style_filter") else None + col_sep_style_filter = ( + plugin.col_separator_style_filter + if hasattr(plugin, "col_separator_style_filter") + else None + ) + check_kwargs_func = ( + plugin.check_style_filter_kwargs + if hasattr(plugin, "check_style_filter_kwargs") + else None + ) + themes[theme] = Theme(style_filter, col_sep_style_filter, check_kwargs_func) + + return themes + + +def fetch_theme(plugin_name: str) -> Theme: + loaded_themes = load_ptw_plugins() + theme_regexp = re.compile( + rf"^{PLUGIN_NAME_PEFIX}[_-]{plugin_name}[_-]{PLUGIN_NAME_SUFFIX}", re.IGNORECASE + ) + matched_theme = None + + for loaded_theme in loaded_themes: + if theme_regexp.search(loaded_theme): + matched_theme = loaded_theme + break + else: + err_msgs = [f"{plugin_name} theme is not installed."] + + if plugin_name in KNOWN_PLUGINS: + err_msgs.append(f"try 'pip install {plugin_name}' to install the theme.") + + raise RuntimeError(" ".join(err_msgs)) + + return loaded_themes[matched_theme] diff --git a/venv/lib/python3.10/site-packages/pytablewriter/typehint/__init__.py b/venv/lib/python3.10/site-packages/pytablewriter/typehint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fffff8e7cae2f6c4d81e3964b2cdf41a8193fcae --- /dev/null +++ b/venv/lib/python3.10/site-packages/pytablewriter/typehint/__init__.py @@ -0,0 +1,38 @@ +from dataproperty.typing import TypeHint +from typepy import ( + Binary, + Bool, + Bytes, + DateTime, + Dictionary, + Infinity, + Integer, + IpAddress, + List, + Nan, + NoneType, + NullString, + RealNumber, + String, +) +from typepy.type import AbstractType + + +__all__ = ( + "Binary", + "Bool", + "Bytes", + "DateTime", + "Dictionary", + "Infinity", + "Integer", + "IpAddress", + "List", + "Nan", + "NoneType", + "NullString", + "RealNumber", + "String", + "TypeHint", + "AbstractType", +) diff --git a/venv/lib/python3.10/site-packages/pytablewriter/typehint/__pycache__/__init__.cpython-310.pyc b/venv/lib/python3.10/site-packages/pytablewriter/typehint/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9cb7b82fd6e6a29dd4c2ac8272f636baf0c4067f Binary files /dev/null and b/venv/lib/python3.10/site-packages/pytablewriter/typehint/__pycache__/__init__.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/LICENSE b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..81241eca637574fb696620b54200d28a0ff53524 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2011-2020 Sergey Astanin and contributors + +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/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/METADATA b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..3909a0009159614c1805e56722e8b8d285389796 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/METADATA @@ -0,0 +1,1149 @@ +Metadata-Version: 2.1 +Name: tabulate +Version: 0.9.0 +Summary: Pretty-print tabular data +Author-email: Sergey Astanin +License: MIT +Project-URL: Homepage, https://github.com/astanin/python-tabulate +Classifier: Development Status :: 4 - Beta +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Topic :: Software Development :: Libraries +Requires-Python: >=3.7 +Description-Content-Type: text/markdown +License-File: LICENSE +Provides-Extra: widechars +Requires-Dist: wcwidth ; extra == 'widechars' + +python-tabulate +=============== + +Pretty-print tabular data in Python, a library and a command-line +utility. + +The main use cases of the library are: + +- printing small tables without hassle: just one function call, + formatting is guided by the data itself +- authoring tabular data for lightweight plain-text markup: multiple + output formats suitable for further editing or transformation +- readable presentation of mixed textual and numeric data: smart + column alignment, configurable number formatting, alignment by a + decimal point + +Installation +------------ + +To install the Python library and the command line utility, run: + +```shell +pip install tabulate +``` + +The command line utility will be installed as `tabulate` to `bin` on +Linux (e.g. `/usr/bin`); or as `tabulate.exe` to `Scripts` in your +Python installation on Windows (e.g. `C:\Python39\Scripts\tabulate.exe`). + +You may consider installing the library only for the current user: + +```shell +pip install tabulate --user +``` + +In this case the command line utility will be installed to +`~/.local/bin/tabulate` on Linux and to +`%APPDATA%\Python\Scripts\tabulate.exe` on Windows. + +To install just the library on Unix-like operating systems: + +```shell +TABULATE_INSTALL=lib-only pip install tabulate +``` + +On Windows: + +```shell +set TABULATE_INSTALL=lib-only +pip install tabulate +``` + +Build status +------------ + +[![Build status](https://circleci.com/gh/astanin/python-tabulate.svg?style=svg)](https://circleci.com/gh/astanin/python-tabulate/tree/master) [![Build status](https://ci.appveyor.com/api/projects/status/8745yksvvol7h3d7/branch/master?svg=true)](https://ci.appveyor.com/project/astanin/python-tabulate/branch/master) + +Library usage +------------- + +The module provides just one function, `tabulate`, which takes a list of +lists or another tabular data type as the first argument, and outputs a +nicely formatted plain-text table: + +```pycon +>>> from tabulate import tabulate + +>>> table = [["Sun",696000,1989100000],["Earth",6371,5973.6], +... ["Moon",1737,73.5],["Mars",3390,641.85]] +>>> print(tabulate(table)) +----- ------ ------------- +Sun 696000 1.9891e+09 +Earth 6371 5973.6 +Moon 1737 73.5 +Mars 3390 641.85 +----- ------ ------------- +``` + +The following tabular data types are supported: + +- list of lists or another iterable of iterables +- list or another iterable of dicts (keys as columns) +- dict of iterables (keys as columns) +- list of dataclasses (Python 3.7+ only, field names as columns) +- two-dimensional NumPy array +- NumPy record arrays (names as columns) +- pandas.DataFrame + +Tabulate is a Python3 library. + +### Headers + +The second optional argument named `headers` defines a list of column +headers to be used: + +```pycon +>>> print(tabulate(table, headers=["Planet","R (km)", "mass (x 10^29 kg)"])) +Planet R (km) mass (x 10^29 kg) +-------- -------- ------------------- +Sun 696000 1.9891e+09 +Earth 6371 5973.6 +Moon 1737 73.5 +Mars 3390 641.85 +``` + +If `headers="firstrow"`, then the first row of data is used: + +```pycon +>>> print(tabulate([["Name","Age"],["Alice",24],["Bob",19]], +... headers="firstrow")) +Name Age +------ ----- +Alice 24 +Bob 19 +``` + +If `headers="keys"`, then the keys of a dictionary/dataframe, or column +indices are used. It also works for NumPy record arrays and lists of +dictionaries or named tuples: + +```pycon +>>> print(tabulate({"Name": ["Alice", "Bob"], +... "Age": [24, 19]}, headers="keys")) + Age Name +----- ------ + 24 Alice + 19 Bob +``` + +### Row Indices + +By default, only pandas.DataFrame tables have an additional column +called row index. To add a similar column to any other type of table, +pass `showindex="always"` or `showindex=True` argument to `tabulate()`. +To suppress row indices for all types of data, pass `showindex="never"` +or `showindex=False`. To add a custom row index column, pass +`showindex=rowIDs`, where `rowIDs` is some iterable: + +```pycon +>>> print(tabulate([["F",24],["M",19]], showindex="always")) +- - -- +0 F 24 +1 M 19 +- - -- +``` + +### Table format + +There is more than one way to format a table in plain text. The third +optional argument named `tablefmt` defines how the table is formatted. + +Supported table formats are: + +- "plain" +- "simple" +- "github" +- "grid" +- "simple\_grid" +- "rounded\_grid" +- "heavy\_grid" +- "mixed\_grid" +- "double\_grid" +- "fancy\_grid" +- "outline" +- "simple\_outline" +- "rounded\_outline" +- "heavy\_outline" +- "mixed\_outline" +- "double\_outline" +- "fancy\_outline" +- "pipe" +- "orgtbl" +- "asciidoc" +- "jira" +- "presto" +- "pretty" +- "psql" +- "rst" +- "mediawiki" +- "moinmoin" +- "youtrack" +- "html" +- "unsafehtml" +- "latex" +- "latex\_raw" +- "latex\_booktabs" +- "latex\_longtable" +- "textile" +- "tsv" + +`plain` tables do not use any pseudo-graphics to draw lines: + +```pycon +>>> table = [["spam",42],["eggs",451],["bacon",0]] +>>> headers = ["item", "qty"] +>>> print(tabulate(table, headers, tablefmt="plain")) +item qty +spam 42 +eggs 451 +bacon 0 +``` + +`simple` is the default format (the default may change in future +versions). It corresponds to `simple_tables` in [Pandoc Markdown +extensions](http://johnmacfarlane.net/pandoc/README.html#tables): + +```pycon +>>> print(tabulate(table, headers, tablefmt="simple")) +item qty +------ ----- +spam 42 +eggs 451 +bacon 0 +``` + +`github` follows the conventions of GitHub flavored Markdown. It +corresponds to the `pipe` format without alignment colons: + +```pycon +>>> print(tabulate(table, headers, tablefmt="github")) +| item | qty | +|--------|-------| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`grid` is like tables formatted by Emacs' +[table.el](http://table.sourceforge.net/) package. It corresponds to +`grid_tables` in Pandoc Markdown extensions: + +```pycon +>>> print(tabulate(table, headers, tablefmt="grid")) ++--------+-------+ +| item | qty | ++========+=======+ +| spam | 42 | ++--------+-------+ +| eggs | 451 | ++--------+-------+ +| bacon | 0 | ++--------+-------+ +``` + +`simple_grid` draws a grid using single-line box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="simple_grid")) + ┌────────┬───────┐ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + ├────────┼───────┤ + │ eggs │ 451 │ + ├────────┼───────┤ + │ bacon │ 0 │ + └────────┴───────┘ + +`rounded_grid` draws a grid using single-line box-drawing characters with rounded corners: + + >>> print(tabulate(table, headers, tablefmt="rounded_grid")) + ╭────────┬───────╮ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + ├────────┼───────┤ + │ eggs │ 451 │ + ├────────┼───────┤ + │ bacon │ 0 │ + ╰────────┴───────╯ + +`heavy_grid` draws a grid using bold (thick) single-line box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="heavy_grid")) + ┏━━━━━━━━┳━━━━━━━┓ + ┃ item ┃ qty ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ spam ┃ 42 ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ eggs ┃ 451 ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ bacon ┃ 0 ┃ + ┗━━━━━━━━┻━━━━━━━┛ + +`mixed_grid` draws a grid using a mix of light (thin) and heavy (thick) lines box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="mixed_grid")) + ┍━━━━━━━━┯━━━━━━━┑ + │ item │ qty │ + ┝━━━━━━━━┿━━━━━━━┥ + │ spam │ 42 │ + ├────────┼───────┤ + │ eggs │ 451 │ + ├────────┼───────┤ + │ bacon │ 0 │ + ┕━━━━━━━━┷━━━━━━━┙ + +`double_grid` draws a grid using double-line box-drawing characters: + + >>> print(tabulate(table, headers, tablefmt="double_grid")) + ╔════════╦═══════╗ + ║ item ║ qty ║ + ╠════════╬═══════╣ + ║ spam ║ 42 ║ + ╠════════╬═══════╣ + ║ eggs ║ 451 ║ + ╠════════╬═══════╣ + ║ bacon ║ 0 ║ + ╚════════╩═══════╝ + +`fancy_grid` draws a grid using a mix of single and + double-line box-drawing characters: + +```pycon +>>> print(tabulate(table, headers, tablefmt="fancy_grid")) +╒════════╤═══════╕ +│ item │ qty │ +╞════════╪═══════╡ +│ spam │ 42 │ +├────────┼───────┤ +│ eggs │ 451 │ +├────────┼───────┤ +│ bacon │ 0 │ +╘════════╧═══════╛ +``` + +`outline` is the same as the `grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="outline")) + +--------+-------+ + | item | qty | + +========+=======+ + | spam | 42 | + | eggs | 451 | + | bacon | 0 | + +--------+-------+ + +`simple_outline` is the same as the `simple_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="simple_outline")) + ┌────────┬───────┐ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + └────────┴───────┘ + +`rounded_outline` is the same as the `rounded_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="rounded_outline")) + ╭────────┬───────╮ + │ item │ qty │ + ├────────┼───────┤ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + ╰────────┴───────╯ + +`heavy_outline` is the same as the `heavy_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="heavy_outline")) + ┏━━━━━━━━┳━━━━━━━┓ + ┃ item ┃ qty ┃ + ┣━━━━━━━━╋━━━━━━━┫ + ┃ spam ┃ 42 ┃ + ┃ eggs ┃ 451 ┃ + ┃ bacon ┃ 0 ┃ + ┗━━━━━━━━┻━━━━━━━┛ + +`mixed_outline` is the same as the `mixed_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="mixed_outline")) + ┍━━━━━━━━┯━━━━━━━┑ + │ item │ qty │ + ┝━━━━━━━━┿━━━━━━━┥ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + ┕━━━━━━━━┷━━━━━━━┙ + +`double_outline` is the same as the `double_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="double_outline")) + ╔════════╦═══════╗ + ║ item ║ qty ║ + ╠════════╬═══════╣ + ║ spam ║ 42 ║ + ║ eggs ║ 451 ║ + ║ bacon ║ 0 ║ + ╚════════╩═══════╝ + +`fancy_outline` is the same as the `fancy_grid` format but doesn't draw lines between rows: + + >>> print(tabulate(table, headers, tablefmt="fancy_outline")) + ╒════════╤═══════╕ + │ item │ qty │ + ╞════════╪═══════╡ + │ spam │ 42 │ + │ eggs │ 451 │ + │ bacon │ 0 │ + ╘════════╧═══════╛ + +`presto` is like tables formatted by Presto cli: + +```pycon +>>> print(tabulate(table, headers, tablefmt="presto")) + item | qty +--------+------- + spam | 42 + eggs | 451 + bacon | 0 +``` + +`pretty` attempts to be close to the format emitted by the PrettyTables +library: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pretty")) ++-------+-----+ +| item | qty | ++-------+-----+ +| spam | 42 | +| eggs | 451 | +| bacon | 0 | ++-------+-----+ +``` + +`psql` is like tables formatted by Postgres' psql cli: + +```pycon +>>> print(tabulate(table, headers, tablefmt="psql")) ++--------+-------+ +| item | qty | +|--------+-------| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | ++--------+-------+ +``` + +`pipe` follows the conventions of [PHP Markdown +Extra](http://michelf.ca/projects/php-markdown/extra/#table) extension. +It corresponds to `pipe_tables` in Pandoc. This format uses colons to +indicate column alignment: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pipe")) +| item | qty | +|:-------|------:| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`asciidoc` formats data like a simple table of the +[AsciiDoctor](https://docs.asciidoctor.org/asciidoc/latest/syntax-quick-reference/#tables) +format: + +```pycon +>>> print(tabulate(table, headers, tablefmt="asciidoc")) +[cols="8<,7>",options="header"] +|==== +| item | qty +| spam | 42 +| eggs | 451 +| bacon | 0 +|==== +``` + +`orgtbl` follows the conventions of Emacs +[org-mode](http://orgmode.org/manual/Tables.html), and is editable also +in the minor orgtbl-mode. Hence its name: + +```pycon +>>> print(tabulate(table, headers, tablefmt="orgtbl")) +| item | qty | +|--------+-------| +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`jira` follows the conventions of Atlassian Jira markup language: + +```pycon +>>> print(tabulate(table, headers, tablefmt="jira")) +|| item || qty || +| spam | 42 | +| eggs | 451 | +| bacon | 0 | +``` + +`rst` formats data like a simple table of the +[reStructuredText](http://docutils.sourceforge.net/docs/user/rst/quickref.html#tables) +format: + +```pycon +>>> print(tabulate(table, headers, tablefmt="rst")) +====== ===== +item qty +====== ===== +spam 42 +eggs 451 +bacon 0 +====== ===== +``` + +`mediawiki` format produces a table markup used in +[Wikipedia](http://www.mediawiki.org/wiki/Help:Tables) and on other +MediaWiki-based sites: + + ```pycon +>>> print(tabulate(table, headers, tablefmt="mediawiki")) +{| class="wikitable" style="text-align: left;" +|+ +|- +! item !! align="right"| qty +|- +| spam || align="right"| 42 +|- +| eggs || align="right"| 451 +|- +| bacon || align="right"| 0 +|} +``` + +`moinmoin` format produces a table markup used in +[MoinMoin](https://moinmo.in/) wikis: + +```pycon +>>> print(tabulate(table, headers, tablefmt="moinmoin")) +|| ''' item ''' || ''' quantity ''' || +|| spam || 41.999 || +|| eggs || 451 || +|| bacon || || +``` + +`youtrack` format produces a table markup used in Youtrack tickets: + +```pycon +>>> print(tabulate(table, headers, tablefmt="youtrack")) +|| item || quantity || +| spam | 41.999 | +| eggs | 451 | +| bacon | | +``` + +`textile` format produces a table markup used in +[Textile](http://redcloth.org/hobix.com/textile/) format: + +```pycon +>>> print(tabulate(table, headers, tablefmt="textile")) +|_. item |_. qty | +|<. spam |>. 42 | +|<. eggs |>. 451 | +|<. bacon |>. 0 | +``` + +`html` produces standard HTML markup as an html.escape'd str +with a ._repr_html_ method so that Jupyter Lab and Notebook display the HTML +and a .str property so that the raw HTML remains accessible. +`unsafehtml` table format can be used if an unescaped HTML is required: + +```pycon +>>> print(tabulate(table, headers, tablefmt="html")) + + + + + + + +
item qty
spam 42
eggs 451
bacon 0
+``` + +`latex` format creates a `tabular` environment for LaTeX markup, +replacing special characters like `_` or `\` to their LaTeX +correspondents: + +```pycon +>>> print(tabulate(table, headers, tablefmt="latex")) +\begin{tabular}{lr} +\hline + item & qty \\ +\hline + spam & 42 \\ + eggs & 451 \\ + bacon & 0 \\ +\hline +\end{tabular} +``` + +`latex_raw` behaves like `latex` but does not escape LaTeX commands and +special characters. + +`latex_booktabs` creates a `tabular` environment for LaTeX markup using +spacing and style from the `booktabs` package. + +`latex_longtable` creates a table that can stretch along multiple pages, +using the `longtable` package. + +### Column alignment + +`tabulate` is smart about column alignment. It detects columns which +contain only numbers, and aligns them by a decimal point (or flushes +them to the right if they appear to be integers). Text columns are +flushed to the left. + +You can override the default alignment with `numalign` and `stralign` +named arguments. Possible column alignments are: `right`, `center`, +`left`, `decimal` (only for numbers), and `None` (to disable alignment). + +Aligning by a decimal point works best when you need to compare numbers +at a glance: + +```pycon +>>> print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]])) +---------- + 1.2345 + 123.45 + 12.345 +12345 + 1234.5 +---------- +``` + +Compare this with a more common right alignment: + +```pycon +>>> print(tabulate([[1.2345],[123.45],[12.345],[12345],[1234.5]], numalign="right")) +------ +1.2345 +123.45 +12.345 + 12345 +1234.5 +------ +``` + +For `tabulate`, anything which can be parsed as a number is a number. +Even numbers represented as strings are aligned properly. This feature +comes in handy when reading a mixed table of text and numbers from a +file: + +```pycon +>>> import csv ; from StringIO import StringIO +>>> table = list(csv.reader(StringIO("spam, 42\neggs, 451\n"))) +>>> table +[['spam', ' 42'], ['eggs', ' 451']] +>>> print(tabulate(table)) +---- ---- +spam 42 +eggs 451 +---- ---- +``` + +To disable this feature use `disable_numparse=True`. + +```pycon +>>> print(tabulate.tabulate([["Ver1", "18.0"], ["Ver2","19.2"]], tablefmt="simple", disable_numparse=True)) +---- ---- +Ver1 18.0 +Ver2 19.2 +---- ---- +``` + +### Custom column alignment + +`tabulate` allows a custom column alignment to override the above. The +`colalign` argument can be a list or a tuple of `stralign` named +arguments. Possible column alignments are: `right`, `center`, `left`, +`decimal` (only for numbers), and `None` (to disable alignment). +Omitting an alignment uses the default. For example: + +```pycon +>>> print(tabulate([["one", "two"], ["three", "four"]], colalign=("right",)) +----- ---- + one two +three four +----- ---- +``` + +### Number formatting + +`tabulate` allows to define custom number formatting applied to all +columns of decimal numbers. Use `floatfmt` named argument: + +```pycon +>>> print(tabulate([["pi",3.141593],["e",2.718282]], floatfmt=".4f")) +-- ------ +pi 3.1416 +e 2.7183 +-- ------ +``` + +`floatfmt` argument can be a list or a tuple of format strings, one per +column, in which case every column may have different number formatting: + +```pycon +>>> print(tabulate([[0.12345, 0.12345, 0.12345]], floatfmt=(".1f", ".3f"))) +--- ----- ------- +0.1 0.123 0.12345 +--- ----- ------- +``` + +`intfmt` works similarly for integers + + >>> print(tabulate([["a",1000],["b",90000]], intfmt=",")) + - ------ + a 1,000 + b 90,000 + - ------ + +### Text formatting + +By default, `tabulate` removes leading and trailing whitespace from text +columns. To disable whitespace removal, set the global module-level flag +`PRESERVE_WHITESPACE`: + +```python +import tabulate +tabulate.PRESERVE_WHITESPACE = True +``` + +### Wide (fullwidth CJK) symbols + +To properly align tables which contain wide characters (typically +fullwidth glyphs from Chinese, Japanese or Korean languages), the user +should install `wcwidth` library. To install it together with +`tabulate`: + +```shell +pip install tabulate[widechars] +``` + +Wide character support is enabled automatically if `wcwidth` library is +already installed. To disable wide characters support without +uninstalling `wcwidth`, set the global module-level flag +`WIDE_CHARS_MODE`: + +```python +import tabulate +tabulate.WIDE_CHARS_MODE = False +``` + +### Multiline cells + +Most table formats support multiline cell text (text containing newline +characters). The newline characters are honored as line break +characters. + +Multiline cells are supported for data rows and for header rows. + +Further automatic line breaks are not inserted. Of course, some output +formats such as latex or html handle automatic formatting of the cell +content on their own, but for those that don't, the newline characters +in the input cell text are the only means to break a line in cell text. + +Note that some output formats (e.g. simple, or plain) do not represent +row delimiters, so that the representation of multiline cells in such +formats may be ambiguous to the reader. + +The following examples of formatted output use the following table with +a multiline cell, and headers with a multiline cell: + +```pycon +>>> table = [["eggs",451],["more\nspam",42]] +>>> headers = ["item\nname", "qty"] +``` + +`plain` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="plain")) +item qty +name +eggs 451 +more 42 +spam +``` + +`simple` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="simple")) +item qty +name +------ ----- +eggs 451 +more 42 +spam +``` + +`grid` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="grid")) ++--------+-------+ +| item | qty | +| name | | ++========+=======+ +| eggs | 451 | ++--------+-------+ +| more | 42 | +| spam | | ++--------+-------+ +``` + +`fancy_grid` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="fancy_grid")) +╒════════╤═══════╕ +│ item │ qty │ +│ name │ │ +╞════════╪═══════╡ +│ eggs │ 451 │ +├────────┼───────┤ +│ more │ 42 │ +│ spam │ │ +╘════════╧═══════╛ +``` + +`pipe` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pipe")) +| item | qty | +| name | | +|:-------|------:| +| eggs | 451 | +| more | 42 | +| spam | | +``` + +`orgtbl` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="orgtbl")) +| item | qty | +| name | | +|--------+-------| +| eggs | 451 | +| more | 42 | +| spam | | +``` + +`jira` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="jira")) +| item | qty | +| name | | +|:-------|------:| +| eggs | 451 | +| more | 42 | +| spam | | +``` + +`presto` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="presto")) + item | qty + name | +--------+------- + eggs | 451 + more | 42 + spam | +``` + +`pretty` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="pretty")) ++------+-----+ +| item | qty | +| name | | ++------+-----+ +| eggs | 451 | +| more | 42 | +| spam | | ++------+-----+ +``` + +`psql` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="psql")) ++--------+-------+ +| item | qty | +| name | | +|--------+-------| +| eggs | 451 | +| more | 42 | +| spam | | ++--------+-------+ +``` + +`rst` tables: + +```pycon +>>> print(tabulate(table, headers, tablefmt="rst")) +====== ===== +item qty +name +====== ===== +eggs 451 +more 42 +spam +====== ===== +``` + +Multiline cells are not well-supported for the other table formats. + +### Automating Multilines +While tabulate supports data passed in with multilines entries explicitly provided, +it also provides some support to help manage this work internally. + +The `maxcolwidths` argument is a list where each entry specifies the max width for +it's respective column. Any cell that will exceed this will automatically wrap the content. +To assign the same max width for all columns, a singular int scaler can be used. + +Use `None` for any columns where an explicit maximum does not need to be provided, +and thus no automate multiline wrapping will take place. + +The wrapping uses the python standard [textwrap.wrap](https://docs.python.org/3/library/textwrap.html#textwrap.wrap) +function with default parameters - aside from width. + +This example demonstrates usage of automatic multiline wrapping, though typically +the lines being wrapped would probably be significantly longer than this. + +```pycon +>>> print(tabulate([["John Smith", "Middle Manager"]], headers=["Name", "Title"], tablefmt="grid", maxcolwidths=[None, 8])) ++------------+---------+ +| Name | Title | ++============+=========+ +| John Smith | Middle | +| | Manager | ++------------+---------+ +``` + +### Adding Separating lines +One might want to add one or more separating lines to highlight different sections in a table. + +The separating lines will be of the same type as the one defined by the specified formatter as either the +linebetweenrows, linebelowheader, linebelow, lineabove or just a simple empty line when none is defined for the formatter + + + >>> from tabulate import tabulate, SEPARATING_LINE + + table = [["Earth",6371], + ["Mars",3390], + SEPARATING_LINE, + ["Moon",1737]] + print(tabulate(table, tablefmt="simple")) + ----- ---- + Earth 6371 + Mars 3390 + ----- ---- + Moon 1737 + ----- ---- + +### ANSI support +ANSI escape codes are non-printable byte sequences usually used for terminal operations like setting +color output or modifying cursor positions. Because multi-byte ANSI sequences are inherently non-printable, +they can still introduce unwanted extra length to strings. For example: + + >>> len('\033[31mthis text is red\033[0m') # printable length is 16 + 25 + +To deal with this, string lengths are calculated after first removing all ANSI escape sequences. This ensures +that the actual printable length is used for column widths, rather than the byte length. In the final, printable +table, however, ANSI escape sequences are not removed so the original styling is preserved. + +Some terminals support a special grouping of ANSI escape sequences that are intended to display hyperlinks +much in the same way they are shown in browsers. These are handled just as mentioned before: non-printable +ANSI escape sequences are removed prior to string length calculation. The only diifference with escaped +hyperlinks is that column width will be based on the length of the URL _text_ rather than the URL +itself (terminals would show this text). For example: + + >>> len('\x1b]8;;https://example.com\x1b\\example\x1b]8;;\x1b\\') # display length is 7, showing 'example' + 45 + + +Usage of the command line utility +--------------------------------- + + Usage: tabulate [options] [FILE ...] + + FILE a filename of the file with tabular data; + if "-" or missing, read data from stdin. + + Options: + + -h, --help show this message + -1, --header use the first row of data as a table header + -o FILE, --output FILE print table to FILE (default: stdout) + -s REGEXP, --sep REGEXP use a custom column separator (default: whitespace) + -F FPFMT, --float FPFMT floating point number format (default: g) + -I INTFMT, --int INTFMT integer point number format (default: "") + -f FMT, --format FMT set output table format; supported formats: + plain, simple, github, grid, fancy_grid, pipe, + orgtbl, rst, mediawiki, html, latex, latex_raw, + latex_booktabs, latex_longtable, tsv + (default: simple) + +Performance considerations +-------------------------- + +Such features as decimal point alignment and trying to parse everything +as a number imply that `tabulate`: + +- has to "guess" how to print a particular tabular data type +- needs to keep the entire table in-memory +- has to "transpose" the table twice +- does much more work than it may appear + +It may not be suitable for serializing really big tables (but who's +going to do that, anyway?) or printing tables in performance sensitive +applications. `tabulate` is about two orders of magnitude slower than +simply joining lists of values with a tab, comma, or other separator. + +At the same time, `tabulate` is comparable to other table +pretty-printers. Given a 10x10 table (a list of lists) of mixed text and +numeric data, `tabulate` appears to be slower than `asciitable`, and +faster than `PrettyTable` and `texttable` The following mini-benchmark +was run in Python 3.9.13 on Windows 10: + + ================================= ========== =========== + Table formatter time, μs rel. time + ================================= ========== =========== + csv to StringIO 12.5 1.0 + join with tabs and newlines 14.6 1.2 + asciitable (0.8.0) 192.0 15.4 + tabulate (0.9.0) 483.5 38.7 + tabulate (0.9.0, WIDE_CHARS_MODE) 637.6 51.1 + PrettyTable (3.4.1) 1080.6 86.6 + texttable (1.6.4) 1390.3 111.4 + ================================= ========== =========== + + +Version history +--------------- + +The full version history can be found at the [changelog](https://github.com/astanin/python-tabulate/blob/master/CHANGELOG). + +How to contribute +----------------- + +Contributions should include tests and an explanation for the changes +they propose. Documentation (examples, docstrings, README.md) should be +updated accordingly. + +This project uses [pytest](https://docs.pytest.org/) testing +framework and [tox](https://tox.readthedocs.io/) to automate testing in +different environments. Add tests to one of the files in the `test/` +folder. + +To run tests on all supported Python versions, make sure all Python +interpreters, `pytest` and `tox` are installed, then run `tox` in the root +of the project source tree. + +On Linux `tox` expects to find executables like `python3.7`, `python3.8` etc. +On Windows it looks for `C:\Python37\python.exe`, `C:\Python38\python.exe` etc. respectively. + +One way to install all the required versions of the Python interpreter is to use [pyenv](https://github.com/pyenv/pyenv). +All versions can then be easily installed with something like: + + pyenv install 3.7.12 + pyenv install 3.8.12 + ... + +Don't forget to change your `PATH` so that `tox` knows how to find all the installed versions. Something like + + export PATH="${PATH}:${HOME}/.pyenv/shims" + +To test only some Python environments, use `-e` option. For example, to +test only against Python 3.7 and Python 3.10, run: + +```shell +tox -e py37,py310 +``` + +in the root of the project source tree. + +To enable NumPy and Pandas tests, run: + +```shell +tox -e py37-extra,py310-extra +``` + +(this may take a long time the first time, because NumPy and Pandas will +have to be installed in the new virtual environments) + +To fix code formatting: + +```shell +tox -e lint +``` + +See `tox.ini` file to learn how to use to test +individual Python versions. + +Contributors +------------ + +Sergey Astanin, Pau Tallada Crespí, Erwin Marsi, Mik Kocikowski, Bill +Ryder, Zach Dwiel, Frederik Rietdijk, Philipp Bogensberger, Greg +(anonymous), Stefan Tatschner, Emiel van Miltenburg, Brandon Bennett, +Amjith Ramanujam, Jan Schulz, Simon Percivall, Javier Santacruz +López-Cepero, Sam Denton, Alexey Ziyangirov, acaird, Cesar Sanchez, +naught101, John Vandenberg, Zack Dever, Christian Clauss, Benjamin +Maier, Andy MacKinlay, Thomas Roten, Jue Wang, Joe King, Samuel Phan, +Nick Satterly, Daniel Robbins, Dmitry B, Lars Butler, Andreas Maier, +Dick Marinus, Sébastien Celles, Yago González, Andrew Gaul, Wim Glenn, +Jean Michel Rouly, Tim Gates, John Vandenberg, Sorin Sbarnea, +Wes Turner, Andrew Tija, Marco Gorelli, Sean McGinnis, danja100, +endolith, Dominic Davis-Foster, pavlocat, Daniel Aslau, paulc, +Felix Yan, Shane Loretz, Frank Busse, Harsh Singh, Derek Weitzel, +Vladimir Vrzić, 서승우 (chrd5273), Georgy Frolov, Christian Cwienk, +Bart Broere, Vilhelm Prytz, Alexander Gažo, Hugo van Kemenade, +jamescooke, Matt Warner, Jérôme Provensal, Kevin Deldycke, +Kian-Meng Ang, Kevin Patterson, Shodhan Save, cleoold, KOLANICH, +Vijaya Krishna Kasula, Furcy Pin, Christian Fibich, Shaun Duncan, +Dimitri Papadopoulos. + diff --git a/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/RECORD b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..4c9c6ea7b5d25f1db2a02500daefc2d76ae5a7e8 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/RECORD @@ -0,0 +1,12 @@ +../../../bin/tabulate,sha256=kZfcrIrFSADyJATYmebvdJRxJIHwWDVK-j31jOqBPuY,238 +tabulate-0.9.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tabulate-0.9.0.dist-info/LICENSE,sha256=zfq1DTfY6tBkaPt2o6uvzQXBZ0nsihjuv6UP1Ix8stI,1080 +tabulate-0.9.0.dist-info/METADATA,sha256=8oAqreJhIJG0WVHyZa8pF0-QwyNvaMyMzetkaUHmKWk,34132 +tabulate-0.9.0.dist-info/RECORD,, +tabulate-0.9.0.dist-info/WHEEL,sha256=G16H4A3IeoQmnOrYV4ueZGKSjhipXx8zc8nu9FGlvMA,92 +tabulate-0.9.0.dist-info/entry_points.txt,sha256=8DmChBYma2n4UqC1VkkKbD5Nu4MrdZasURoeTtG0JVo,44 +tabulate-0.9.0.dist-info/top_level.txt,sha256=qfqkQ2az7LTxUeRePtX8ggmh294Kf1ERdI-11aWqFZU,9 +tabulate/__init__.py,sha256=X3rwoo_NcTuDDJc4hnWUX6jElQsFtY-NGHyQCldS1X0,95290 +tabulate/__pycache__/__init__.cpython-310.pyc,, +tabulate/__pycache__/version.cpython-310.pyc,, +tabulate/version.py,sha256=QVVpjnTor93ym-Tb6Y_XtL_6pmQ3MtoNy3Q6I0o3Yqg,181 diff --git a/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/WHEEL b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..becc9a66ea739ba941d48a749e248761cc6e658a --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.37.1) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/entry_points.txt b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..1efc880fa41d55743166d009c0a7368ba2493679 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +tabulate = tabulate:_main diff --git a/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5d51591ebf67bc53acb1c8481da364dae742a02 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tabulate-0.9.0.dist-info/top_level.txt @@ -0,0 +1 @@ +tabulate diff --git a/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/INSTALLER b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/INSTALLER new file mode 100644 index 0000000000000000000000000000000000000000..a1b589e38a32041e49332e5e81c2d363dc418d68 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/INSTALLER @@ -0,0 +1 @@ +pip diff --git a/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/LICENSE b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7fa40cf5fe093c0c9246746e07a4f04fbc5b565d --- /dev/null +++ b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020 Tsuyoshi Hombashi + +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/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/METADATA b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/METADATA new file mode 100644 index 0000000000000000000000000000000000000000..5f4f4544db761506805dc3107d59ecc43af87f59 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/METADATA @@ -0,0 +1,162 @@ +Metadata-Version: 2.1 +Name: tcolorpy +Version: 0.1.4 +Summary: tcolopy is a Python library to apply true color for terminal text. +Home-page: https://github.com/thombashi/tcolorpy +Author: Tsuyoshi Hombashi +Author-email: tsuyoshi.hombashi@gmail.com +License: MIT License +Project-URL: Source, https://github.com/thombashi/tcolorpy +Project-URL: Tracker, https://github.com/thombashi/tcolorpy/issues +Keywords: ANSI escape,terminal color,truecolor +Classifier: Development Status :: 4 - Beta +Classifier: Intended Audience :: Information Technology +Classifier: License :: OSI Approved :: MIT License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.7 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Programming Language :: Python :: 3.9 +Classifier: Programming Language :: Python :: 3.10 +Classifier: Programming Language :: Python :: 3.11 +Classifier: Programming Language :: Python :: 3 :: Only +Classifier: Programming Language :: Python :: Implementation :: CPython +Classifier: Programming Language :: Python :: Implementation :: PyPy +Classifier: Topic :: Software Development :: Libraries +Classifier: Topic :: Software Development :: Libraries :: Python Modules +Classifier: Topic :: Terminals +Classifier: Topic :: Text Processing +Requires-Python: >=3.7 +Description-Content-Type: text/x-rst +License-File: LICENSE +Provides-Extra: test +Requires-Dist: pytest >=6.0.1 ; extra == 'test' +Requires-Dist: pytest-md-report >=0.4.1 ; extra == 'test' + +.. contents:: **tcolorpy** + :backlinks: top + :depth: 2 + + +Summary +============================================ +tcolopy is a Python library to apply true color for terminal text. + +.. image:: https://badge.fury.io/py/tcolorpy.svg + :target: https://badge.fury.io/py/tcolorpy + :alt: PyPI package version + +.. image:: https://anaconda.org/conda-forge/tcolorpy/badges/version.svg + :target: https://anaconda.org/conda-forge/tcolorpy + :alt: conda-forge package version + +.. image:: https://img.shields.io/pypi/pyversions/tcolorpy.svg + :target: https://pypi.org/project/tcolorpy + :alt: Supported Python versions + +.. image:: https://img.shields.io/pypi/implementation/tcolorpy.svg + :target: https://pypi.org/project/tcolorpy + :alt: Supported Python implementations + +.. image:: https://github.com/thombashi/tcolorpy/workflows/Tests/badge.svg + :target: https://github.com/thombashi/tcolorpy/actions?query=workflow%3ATests + :alt: Linux/macOS/Windows CI status + +.. image:: https://coveralls.io/repos/github/thombashi/tcolorpy/badge.svg?branch=master + :target: https://coveralls.io/github/thombashi/tcolorpy?branch=master + :alt: Test coverage: coveralls + + +Installation +============================================ + +Installation: pip +------------------------------ +:: + + pip install tcolorpy + +Installation: conda +------------------------------ +:: + + conda install -c conda-forge tcolorpy + + +Usage +============================================ + +Library usage +-------------------------------------------- + +:Sample Code: + .. code-block:: python + + from tcolorpy import tcolor + + print(tcolor("tcolopy example", color="#ee1177", styles=["bold", "italic", "underline"])) + +:Output: + .. figure:: https://cdn.jsdelivr.net/gh/thombashi/tcolorpy@master/ss/oneline.png + :scale: 60% + :alt: https://github.com/thombashi/tcolorpy/blob/master/ss/oneline.png + +You can set the following ``tcolor`` arguments: + +- ``color``/``bg_color`` + - color names (``"red"``, ``"green"``, etc.) or color code (``"#RRGGBB"``) +- ``styles`` + - ``"bold"``, ``"italic"``, etc. + + +Other examples +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Apply true color and styles to text: + +.. figure:: https://cdn.jsdelivr.net/gh/thombashi/tcolorpy@master/ss/styles.png + :scale: 60% + :alt: https://github.com/thombashi/tcolorpy/blob/master/ss/styles.png + + `example source code `__ + +You can also specify colors by name: + +.. figure:: https://cdn.jsdelivr.net/gh/thombashi/tcolorpy@master/ss/ansi_colors.png + :scale: 60% + :alt: https://github.com/thombashi/tcolorpy/blob/master/ss/ansi_colors.png + + `example source code `__ + + +CLI usage +-------------------------------------------- +``tcolorpy`` can be used via CLI: + +:: + + $ python3 -m tcolorpy "tcolopy example" -c "#ee1177" -s bold,italic,underline + +Command help +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +:: + + usage: __main__.py [-h] [-c COLOR] [-b BG_COLOR] [-s STYLES] [--encode ENCODE] string + + positional arguments: + string string to apply styles. + + options: + -h, --help show this help message and exit + -c COLOR, --color COLOR + specify a color code (#XXXXXX) or a name. valid names are: black, red, green, yellow, blue, magenta, cyan, white, lightblack, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, lightwhite + -b BG_COLOR, --bg-color BG_COLOR + specify a background color code (#XXXXXX) or a name. valid names are: black, red, green, yellow, blue, magenta, cyan, white, lightblack, lightred, lightgreen, lightyellow, lightblue, lightmagenta, lightcyan, lightwhite + -s STYLES, --styles STYLES + specify a comma-separated style. valid values are: bold, dim, italic, underline, blink, invert, strike + --encode ENCODE output a text encoded with the specified encoding + + +Dependencies +============================================ +Python 3.7+ +no external dependencies. diff --git a/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/RECORD b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/RECORD new file mode 100644 index 0000000000000000000000000000000000000000..ee34dbd8b70064e4d587b41f5659ec983ccb5242 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/RECORD @@ -0,0 +1,17 @@ +tcolorpy-0.1.4.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4 +tcolorpy-0.1.4.dist-info/LICENSE,sha256=9BoEVtXyu6Jf1NflC1GpXeMEdw_x21p5UV0DOXqRTY0,1074 +tcolorpy-0.1.4.dist-info/METADATA,sha256=rFyw79V_YbDAiIAncjF7kdjKdHq0v7CJAlcy0ImSQFw,5716 +tcolorpy-0.1.4.dist-info/RECORD,, +tcolorpy-0.1.4.dist-info/WHEEL,sha256=yQN5g4mg4AybRjkgi-9yy4iQEFibGQmlz78Pik5Or-A,92 +tcolorpy-0.1.4.dist-info/top_level.txt,sha256=g8LDaQz0FVP61jibPz7OTwQqiseVV9pxUYDeGp2lFAI,9 +tcolorpy/__init__.py,sha256=729PMIfmOYicXFInfS4Uml-uA17tRllqPJ1ZFmSsIQ0,705 +tcolorpy/__main__.py,sha256=gjNpi78hE-X6CpY20ZLMmQ_yaWYIh_eOu2XrLnoGkBE,1701 +tcolorpy/__pycache__/__init__.cpython-310.pyc,, +tcolorpy/__pycache__/__main__.cpython-310.pyc,, +tcolorpy/__pycache__/__version__.cpython-310.pyc,, +tcolorpy/__pycache__/_const.cpython-310.pyc,, +tcolorpy/__pycache__/_truecolor.cpython-310.pyc,, +tcolorpy/__version__.py,sha256=uzTkOQkPBiZDuqTer6QpBlWsMYzrB5PZ-7rn53qkbaQ,201 +tcolorpy/_const.py,sha256=XS2rzsxY7SKxg0HreYTR_kEGeSi_59gOrrntI2_kG1o,1080 +tcolorpy/_truecolor.py,sha256=nzu2GCc6Tu_4no5_Qcksm88-Vm75sCdeOMDQHG_2DhM,7495 +tcolorpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0 diff --git a/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/WHEEL b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/WHEEL new file mode 100644 index 0000000000000000000000000000000000000000..7e688737d490be3643d705bc16b5a77f7bd567b7 --- /dev/null +++ b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/WHEEL @@ -0,0 +1,5 @@ +Wheel-Version: 1.0 +Generator: bdist_wheel (0.41.2) +Root-Is-Purelib: true +Tag: py3-none-any + diff --git a/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/top_level.txt b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..eda2ffb721c9f828b59d81ca04550452a1cde8cc --- /dev/null +++ b/venv/lib/python3.10/site-packages/tcolorpy-0.1.4.dist-info/top_level.txt @@ -0,0 +1 @@ +tcolorpy diff --git a/venv/lib/python3.10/site-packages/typepy/converter/__pycache__/_bytes.cpython-310.pyc b/venv/lib/python3.10/site-packages/typepy/converter/__pycache__/_bytes.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d96f0e1b5d7f4a0c0c1435167492c98a76be549 Binary files /dev/null and b/venv/lib/python3.10/site-packages/typepy/converter/__pycache__/_bytes.cpython-310.pyc differ diff --git a/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/PKG-INFO b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..aef853b67fe31632fd47f3297c1508cd75a9160d --- /dev/null +++ b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/PKG-INFO @@ -0,0 +1,117 @@ +Metadata-Version: 2.1 +Name: word2number +Version: 1.1 +Summary: Convert number words eg. three hundred and forty two to numbers (342). +Home-page: https://github.com/akshaynagpal/w2n +Author: Akshay Nagpal +Author-email: akshay2626@gmail.com +License: The MIT License (MIT) + + Copyright (c) 2016 Akshay Nagpal (https://github.com/akshaynagpal) + + 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. + +Download-URL: https://github.com/akshaynagpal/w2n/tarball/1.1 +Keywords: numbers,convert,words +Platform: UNKNOWN +Classifier: Intended Audience :: Developers +Classifier: Programming Language :: Python +License-File: LICENSE.txt + +|travis_pic| |codecov_pic| + +============== +Word to Number +============== +This is a Python module to convert number words (eg. twenty one) to numeric digits (21). It works for positive numbers upto the range of 999,999,999,999 (i.e. billions). + +++++++++++++ +Installation +++++++++++++ +Please ensure that you have **updated pip** to the latest version before installing word2number. + +You can install the module using Python Package Index using the below command. + +.. code-block:: python + + pip install word2number + +Make sure you install all requirements given in requirements.txt + +.. code-block:: python + + pip install -r requirements.txt + ++++++ +Usage ++++++ +First you have to import the module using the below code. +.. code-block:: python + + from word2number import w2n + +Then you can use the **word_to_num** method to convert a number-word to numeric digits, as shown below. + +.. code-block:: python + + >>> print w2n.word_to_num("two million three thousand nine hundred and eighty four") + 2003984 + + >>> print(w2n.word_to_num('two point three')) + 2.3 + + >>> print(w2n.word_to_num('112')) + 112 + + >>> print(w2n.word_to_num('point one')) + 0.1 + + >>> print(w2n.word_to_num('one hundred thirty-five')) + 135 + + >>> print(w2n.word_to_num('million million')) + Error: Redundant number! Please enter a valid number word (eg. two million twenty three thousand and forty nine) + None + + >>> print(w2n.word_to_num('blah')) + Error: No valid number words found! Please enter a valid number word (eg. two million twenty three thousand and forty nine) + None + ++++++++++++ +Bugs/Errors ++++++++++++ + +Please ensure that you have updated pip to the latest version before installing word2number. + +If you find any bugs/errors in the usage of above code, please raise an issue through `Github `_. If you don't know how to use Github or raise an issue through it, I suggest that you should learn it. Else, send an email to akshay2626@gmail.com with a clear example that can reproduce the issue. + +++++++++++++ +Contributors +++++++++++++ +- Ben Batorsky (`bpben `__) +- Alex (`ledovsky `__) +- Tal Yarkoni (`tyarkoni `__) +- ButteredGroove (`ButteredGroove `__) + +.. |travis_pic| image:: https://travis-ci.org/akshaynagpal/w2n.svg?branch=master + :target: https://travis-ci.org/akshaynagpal/w2n + +.. |codecov_pic| image:: https://codecov.io/gh/akshaynagpal/w2n/branch/master/graph/badge.svg + :target: https://codecov.io/gh/akshaynagpal/w2n + diff --git a/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/SOURCES.txt b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..d2aa5a404a5d2a3f5f1056dcbe2b46f9e8665426 --- /dev/null +++ b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/SOURCES.txt @@ -0,0 +1,12 @@ +LICENSE.txt +MANIFEST.in +README.rst +requirements.txt +setup.cfg +setup.py +word2number/__init__.py +word2number/w2n.py +word2number.egg-info/PKG-INFO +word2number.egg-info/SOURCES.txt +word2number.egg-info/dependency_links.txt +word2number.egg-info/top_level.txt \ No newline at end of file diff --git a/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/dependency_links.txt b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/installed-files.txt b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/installed-files.txt new file mode 100644 index 0000000000000000000000000000000000000000..413048dc850fa47824ecd7a75c066a9400b20fc4 --- /dev/null +++ b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/installed-files.txt @@ -0,0 +1,8 @@ +../word2number/__init__.py +../word2number/__pycache__/__init__.cpython-310.pyc +../word2number/__pycache__/w2n.cpython-310.pyc +../word2number/w2n.py +PKG-INFO +SOURCES.txt +dependency_links.txt +top_level.txt diff --git a/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/top_level.txt b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..b7c664e33c170715d0101175b97770f68b8f82f9 --- /dev/null +++ b/venv/lib/python3.10/site-packages/word2number-1.1.egg-info/top_level.txt @@ -0,0 +1 @@ +word2number