code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
[![PyPI](https://img.shields.io/badge/zotasdk-v1.1.6-blue)](https://pypi.org/project/zotapaysdk/) [![codecov](https://codecov.io/gh/zotapay/python-sdk/branch/master/graph/badge.svg?token=5L1EYONUCU)](https://codecov.io/gh/zotapay/python-sdk) ![Python Matrix Test](https://github.com/zotapay/python-sdk/workflows/Python%20Matrix%20Test/badge.svg) [![Python Versions](https://img.shields.io/badge/python-3.5%20%7C%203.6%20%7C%203.7%20%7C%203.8%20%7C%203.9%20%7C%203.10-blue)](https://pypi.org/project/zotapaysdk/) ![python-github](https://user-images.githubusercontent.com/174284/106497606-f0221600-64c6-11eb-9d98-a6ad1b355e6a.jpg) # Official Python REST API SDK This is the **official** page of the [Zotapay](http://www.zotapay.com) Python SDK. It is intended to be used by developers who run modern Python applications and would like to integrate our next generation payments platform. ## REST API Docs > **[Official Deposit Documentation](https://doc.zotapay.com/deposit/1.0/#introduction)** > **[Official Payout Documentation](https://doc.zotapay.com/payout/1.0/#introduction)** ## Introduction This Python SDK provides all the necessary methods for integrating the Zotapay Merchant API. This SDK is to be used by clients, as well as all the related eCommerce plugins for Python applications. The SDK covers all available functionality that ZotaPay's Merchant API exposes. ### Requirements * A functioning Zotapay Sandbox or Production account and related credentials * Python 3.5 (or higher) ### Installation ```sh pip install zotapaysdk ``` ## Configuration [API CONFIGURATION DOCS](https://doc.zotapay.com/deposit/1.0/?python#before-you-begin) Credentials for the SDK can be passed in 3 different ways: 1. To the `MGClient` itself 2. Through environment variables 3. Through a configuration file This part of the documentation will guide you on how to configure and use this SDK. ### Before you begin To use this API, obtain the following credentials from Zotapay: ``` MerchantID A merchant unique identifier, used for identification. MerchantSecretKey A secret key to keep privately and securely, used for authentication. EndpointID One or more unique endpoint identifiers to use in API requests. ``` Contact [Zotapay](https://zotapay.com/contact/) to start your onboarding process and obtain all the credentials. ### API Url There are two environments to use with the Zotapay API: > Sandbox environment, used for integration and testing purposes. `https://api.zotapay-sandbox.com` > Live environment. `https://api.zotapay.com` ### Configuration in the code The implementation fo the Zotapay API SDK depends on creating an instance of the `MGClient`. First priority configuration is the one passed to the client itself. Example: ```python client = zotapaysdk.MGClient( merchant_id=<MerchantID as received from Zotapay>, merchant_secret_key=<MerchantSecretKey as received from Zotapay>, endpoint_id=<EndpointID as received from Zotapay>, request_url=<MGClient.LIVE_API_URL or MGClient.SANDBOX_API_URL or "https://api.zotapay-sandbox.com"...> ) ``` Passing configuration to the client itself is best when supporting multiple clients. ### Environment variables configuration There are 4 environment variables that need to be set for the API SDK to be configured correctly: ``` ZOTAPAY_MERCHANT_ID - MerchantID as received from Zotapay ZOTAPAY_MERCHANT_SECRET_KEY - MerchantSecretKey as received from Zotapay ZOTAPAY_ENDPOINT_ID - EndpointID as received from Zotapay ZOTAPAY_REQUEST_URL - https://api.zotapay-sandbox.com or https://api.zotapay.com ``` ### Configuration file Configuration parameters can be passed through a `.mg_env` file placed in the user's home directory. The structure of the files follows Python's [configparser](https://docs.python.org/3/library/configparser.html) Example of a '~/.mg_env' : ``` [MG] merchant_id=<MerchantID as received from Zotapay>, merchant_secret_key=<MerchantSecretKey as received from Zotapay>, endpoint_id=<EndpointID as received from Zotapay>, request_url=<MGClient.LIVE_API_URL or MGClient.SANDBOX_API_URL or "https://api.zotapay-sandbox.com"...> ``` ## Usage In order to use the SDK we need to instantiate a client: ```python from zotapaysdk.client import MGClient mg_client = MGClient() ``` ### Deposit A deposit request can be generated in two different ways: ```python from zotapaysdk.mg_requests import MGDepositRequest example_deposit_request_with_kwargs = MGDepositRequest( merchant_order_id="QvE8dZshpKhaOmHY", merchant_order_desc="Test order", order_amount="500.00", order_currency="THB", customer_email="[email protected]", customer_first_name="John", customer_last_name="Doe", customer_address="5/5 Moo 5 Thong Nai Pan Noi Beach, Baan Tai, Koh Phangan", customer_country_code="TH", customer_city="Surat Thani", customer_zip_code="84280", customer_phone="+66-77999110", customer_ip="103.106.8.104", redirect_url="https://www.example-merchant.com/payment-return/", callback_url="https://www.example-merchant.com/payment-callback/", custom_param="{\"UserId\": \"e139b447\"}", checkout_url="https://www.example-merchant.com/account/deposit/?uid=e139b447", ) ``` or alternatively ```python example_deposit_request = MGDepositRequest(). \ set_merchant_order_id("QvE8dZshpKhaOmHY"). \ set_merchant_order_desc("Test order"). \ set_order_amount("500"). \ set_order_currency("USD"). \ set_customer_email("[email protected]"). \ set_customer_first_name("John"). \ set_customer_last_name("Doe"). \ set_customer_address("5/5 Moo 5 Thong Nai Pan Noi Beach, Baan Tai, Koh Phangan"). \ set_customer_country_code("TH"). \ set_customer_city("Surat Thani"). \ set_customer_zip_code("84280"). \ set_customer_phone("+66-66006600"). \ set_customer_ip("103.106.8.104"). \ set_redirect_url("https://www.example-merchant.com/payment-return/"). \ set_callback_url("https://www.example-merchant.com/payment-callback/"). \ set_custom_param("{\"UserId\": \"e139b447\"}"). \ set_checkout_url("https://www.example-merchant.com/account/deposit/?uid=e139b447") ``` Sending the request to Zotapay happens through the client: ```python deposit_response = mg_client.send_deposit_request(example_deposit_request) print("Deposit Request is " + str(deposit_response.is_ok)) ``` In order to send a `Credit Card Deposit` we need to append the appropriate [Credit Card Params](https://doc.zotapay.com/deposit/1.0/?python#card-payment-integration-2) which is achieved through sending a `MGCardDepositRequest` ```python example_cc_deposit_request = MGCardDepositRequest( merchant_order_id="QvE8dZshpKhaOmHY", merchant_order_desc="Test order", order_amount="500.00", order_currency="THB", customer_email="[email protected]", customer_first_name="John", customer_last_name="Doe", customer_address="5/5 Moo 5 Thong Nai Pan Noi Beach, Baan Tai, Koh Phangan", customer_country_code="TH", customer_city="Surat Thani", customer_zip_code="84280", customer_phone="+66-77999110", customer_ip="103.106.8.104", redirect_url="https://www.example-merchant.com/payment-return/", callback_url="https://www.example-merchant.com/payment-callback/", custom_param="{\"UserId\": \"e139b447\"}", checkout_url="https://www.example-merchant.com/account/deposit/?uid=e139b447", # CC PARAMS HERE card_number="3453789023457890", card_holder_name="John Doe", card_expiration_month="08", card_expiration_year="2027", card_cvv="123" ) deposit_response = mg_client.send_deposit_request(example_cc_deposit_request) print("Deposit Request is " + str(deposit_response.is_ok)) ``` ### Working with `Deposit Response` Each deposit attempt against a Zotapay returns either a `MGDepositResponse` or `MGCardDepositResponse`. The above objects are simply a wrapper around the standard HTTP response as described [here](https://doc.zotapay.com/deposit/1.0/?python#issue-a-deposit-request). The response classes contain an additional helper method that validates the signature of the response when provided with a `merchant_secret_key` ## Payout Sending a payout request is almost identical to sending a deposit request. The request is built: ```python from zotapaysdk.mg_requests import MGPayoutRequest example_payout_request = \ MGPayoutRequest(merchant_order_id="TbbQzewLWwDW6goc", merchant_order_desc="Test order", order_amount="500.00", order_currency="MYR", customer_email="[email protected]", customer_first_name="John", customer_last_name="Doe", customer_phone="+66-77999110", customer_ip="103.106.8.104", callback_url="https://www.example-merchant.com/payout-callback/", customer_bank_code="BBL", customer_bank_account_number="100200", customer_bank_account_name="John Doe", customer_bank_branch="Bank Branch", customer_bank_address="Thong Nai Pan Noi Beach, Baan Tai, Koh Phangan", customer_bank_zip_code="84280", customer_bank_province="Bank Province", customer_bank_area="Bank Area / City", customer_bank_routing_number="000", custom_param="{\"UserId\": \"e139b447\"}", checkout_url="https://www.example-merchant.com/account/withdrawal/?uid=e139b447") ``` The client returns `MGPayoutResponse` which is again a wrapper around the standard HTTP response. ## Callbacks `MGCallback` is a class that parses the raw HTTP Request sent from Zotapay to the configured endpoint. It's purpose is to make working with callbacks manageable. ## Validations The `MGRequest` class implements a `validate()` method which can be used for parameter validation of the request offline before the request is being sent. It's purpose is to check whether all the values passsed to the different parameters is in-line with what Zotapay's endpoint expects. See the API DOCS for more info and guidance about the format of the different parameters. ## Test Coverage [![codecov](https://codecov.io/gh/zotapay/python-sdk/graphs/tree.svg?width=650&height=150&src=pr&token=5L1EYONUCU)](https://codecov.io/gh/zotapay/python-sdk/)
zotapaysdk
/zotapaysdk-1.1.6.tar.gz/zotapaysdk-1.1.6/README.md
README.md
# zotero-bibtize Refurbish exported Zotero-BibTex bibliographies into a more ![latex] friendly representation. In the current state exporting the contents of a Zotero database to Bibtex format most special characters are replaced by Zotero internal versions or escaped before written to the output file. This behavior is exceptionally annoying if entries contain code which is meant to be processed by ![latex] (i.e. chemical or mathematical expressions and formulas in the title, etc.). `zotero-bibtize` can be used to post-process the generated Zotero output files and remove added escape sequences (i.e. the output is an identical replica of the raw entry contents stored in the Zotero interface) ## Usage After installing the package `zotero-bibtize` can be invoked via a call to the `zotero-bibtize` command on the command line: ```console $ zotero-bibtize zotero_bibliography.bib bibtized_bibliography.bib ``` which will process the original contents `zotero_bibliography.bib` and writes the processed contents to the new `bibtized_bibliography.bib` file. Note that specifying a target file is optional and the input file will be overwritten if left out. ### Example Original bibtex entry generated by Zotero export: ```console $ cat zotero_bibliography.bib @article{LangCM2015, title = {Lithium {Ion} {Conduction} in {\textbackslash}ce\{{LiTi}2({PO}4)3\} and {Related} {Compounds} {Based} on the \{{NASICON}\} {Structure}: {A} {First}-{Principles} {Study}}, volume = {27}, issn = {0897-4756, 1520-5002}, shorttitle = {Lithium {Ion} {Conduction} in {\textbackslash}ce\{{LiTi}2({PO}4)3\} and {Related} {Compounds} {Based} on the {NASICON} {Structure}}, url = {http://pubs.acs.org/doi/10.1021/acs.chemmater.5b01582}, doi = {10.1021/acs.chemmater.5b01582}, language = {en}, number = {14}, urldate = {2019-02-11}, journal = {Chem. Mater.}, author = {Lang, Britta and Ziebarth, Benedikt and Els{\textbackslash}"\{a\}sser, Christian}, month = jul, year = {2015}, pages = {5040--5048} } ``` After running `zotero-bibtize zotero_bibliography.bib`: ```console $ cat zotero_bibliography.bib @article{LangCM2015, title = {Lithium Ion Conduction in \ce{LiTi2(PO4)3} and Related Compounds Based on the NASICON Structure: A First-Principles Study}, volume = {27}, issn = {0897-4756, 1520-5002}, shorttitle = {Lithium Ion Conduction in \ce{LiTi2(PO4)3} and Related Compounds Based on the NASICON Structure}, url = {http://pubs.acs.org/doi/10.1021/acs.chemmater.5b01582}, doi = {10.1021/acs.chemmater.5b01582}, language = {en}, number = {14}, urldate = {2019-02-11}, journal = {Chem. Mater.}, author = {Lang, Britta and Ziebarth, Benedikt and Els\"{a}sser, Christian}, month = jul, year = {2015}, pages = {5040--5048} } ``` ## Custom BibTex Keys (very experimental) Custom BibTex keys can be defined through the optional `--key-format` option that will be written to the bibliography file instead of the default keys generated by Zotero. The key format defines the way how to combine and format contents taken from the BibTex entry fields to build a custom key format. In general the format key is of the form `[field1:option][field2:option]...` where `field` defines the BibTex entry field to take the contents from and the options defines different format options that will be applied to the contents. Currently the following fields are implemented: #### author Adds the author's lastnames to the key entry\ General format: `[author:num:options]` ##### num Defines the maximal number of author names used for the key ##### options The format options that will be applied to the author names, i.e. * capitalize: Capitalize the names * upper: Transform names uppercase * lower: Transform names to lowercase * abbreviate: Only us the first letter instead of the full name #### title Adds contents of the title string to the key entry\ General format: `[title:num:options]` ##### num Defines the maximal number of words in the title used for the key (Note that [function keys](https://docs.jabref.org/setup/bibtexkeypatterns) will not be taken into account) ##### options The format options that will be applied to the title contents, i.e. * capitalize: Capitalize the names * upper: Transform names uppercase * lower: Transform names to lowercase * abbreviate: Only us the first letter instead of the full name #### journal Adds contents of the journal name to the key entry\ General format: `[journal:options]` ##### options The format options that will be applied to the journal name, i.e. * capitalize: Capitalize the names * upper: Transform names uppercase * lower: Transform names to lowercase * abbreviate: Only us the first letter instead of the full name #### year Add the publication year to the key entry\ General format: `[year:option]` ##### option Adding the year only allows to specify two types of options: * short: Add the year to the key as 2-digit quantity * long: Add the full year to the (i.e. as 4-digit quantitiy) ### Example In the following example we create a custom key containing the first author name and the abbreviated journal name followed by the publication year. The key format defining such a key is of the following form: `[author:1:capitalize][journal:capitalize:abbreviate][year]` The original entry generated by Zotero looks like this: ```console $ cat zotero_bibliography.bib @article{lang_lithium_ion_conduction_2015, title = {Lithium {Ion} {Conduction} in {\textbackslash}ce\{{LiTi}2({PO}4)3\} and {Related} {Compounds} {Based} on the \{{NASICON}\} {Structure}: {A} {First}-{Principles} {Study}}, volume = {27}, issn = {0897-4756, 1520-5002}, shorttitle = {Lithium {Ion} {Conduction} in {\textbackslash}ce\{{LiTi}2({PO}4)3\} and {Related} {Compounds} {Based} on the {NASICON} {Structure}}, url = {http://pubs.acs.org/doi/10.1021/acs.chemmater.5b01582}, doi = {10.1021/acs.chemmater.5b01582}, language = {en}, number = {14}, urldate = {2019-02-11}, journal = {Chem. Mater.}, author = {Lang, Britta and Ziebarth, Benedikt and Els{\textbackslash}"\{a\}sser, Christian}, month = jul, year = {2015}, pages = {5040--5048} } ``` After running `zotero-bibtize zotero_bibliography.bib --key-format [author:1:capitalize][journal:capitalize:abbreviate][year]` the original contents will be processed by `zotero-bibtize` and the original Zotero key will be replaced with the modified version: ```console $ cat zotero_bibliography.bib @article{LangCM2015, title = {Lithium Ion Conduction in \ce{LiTi2(PO4)3} and Related Compounds Based on the NASICON Structure: A First-Principles Study}, volume = {27}, issn = {0897-4756, 1520-5002}, shorttitle = {Lithium Ion Conduction in \ce{LiTi2(PO4)3} and Related Compounds Based on the NASICON Structure}, url = {http://pubs.acs.org/doi/10.1021/acs.chemmater.5b01582}, doi = {10.1021/acs.chemmater.5b01582}, language = {en}, number = {14}, urldate = {2019-02-11}, journal = {Chem. Mater.}, author = {Lang, Britta and Ziebarth, Benedikt and Els\"{a}sser, Christian}, month = jul, year = {2015}, pages = {5040--5048} } ``` [latex]: http://chart.apis.google.com/chart?cht=tx&chl=\LaTeX
zotero-bibtize
/zotero-bibtize-0.1.0.tar.gz/zotero-bibtize-0.1.0/README.md
README.md
import re class KeyFormatter(object): def __init__(self, bibtex_fields): self.bibtex_fields = bibtex_fields self.field_format_map = { 'author': self.format_author_key, 'year': self.format_year_key, 'journal': self.format_journal_key, 'title': self.format_title_key, } def generate_key(self, key_format): """Generate a bibtex key according to the defined format.""" format_list = self.unpack_format_entries(key_format) bibkey = key_format for ((field, format_actions), raw) in format_list: formatted_key = self.field_format_map[field](*format_actions) formatter = "[{}]".format(raw) bibkey = bibkey.replace(formatter, formatted_key) return bibkey def unpack_format_entries(self, key_format): """Extract the format entries from the total key_format string.""" format_regex = r"\[(.*?)\]" format_entries = re.findall(format_regex, key_format) if not format_entries: raise Exception("no valid format entries found in defined key " "format '{}'".format(key_format)) format_list = [] for format_entry in format_entries: entry_type, *format_actions = format_entry.split(':') format_list.append((entry_type, format_actions)) return zip(format_list, format_entries) def apply_format_to_content(self, content, format_action): """ Apply format actions to every word contained in content list :param list content: A list of words describing the content :param str format_action: String describing the format to apply """ if format_action in ['upper']: return [c.upper() for c in content] elif format_action in ['lower']: return [c.lower() for c in content] elif format_action in ['capitalize']: return [c.capitalize() for c in content] elif format_action in ['abbreviate', 'abbr']: return [c[0] for c in content] else: raise Exception("Unknown format action: {}".format(format_action)) def remove_latex_content(self, content_string): """Remove all latex contents from the given string.""" content_string = self.remove_math_environments(content_string) content_string = self.remove_latex_commands(content_string) content_string = self.remove_curly_braces(content_string) return content_string def remove_latex_commands(self, content_string): """ Remove latex commands from the given string. In this case only the latex command will be removed, i.e. a command of the form \command{content} will be replaced by {content} """ latex_command_regex = r"(\\[^\{]+)\{" return re.sub(latex_command_regex, '', content_string).strip() def remove_math_environments(self, content_string): """ Remove a latex math environment from the given string. This function will completely remove latex math environments from the string. It will only remove environments defined by either $ (inline) or $$. (will not remove environments initialized by \begin{equation},...) """ latex_math_regex = r"\$+[\s\S]+?\$+" return re.sub(latex_math_regex, '', content_string).strip() def remove_curly_braces(self, content_string): """Remove curly braces from the given string.""" curly_braces_regex = r"[\{\}]" return re.sub(curly_braces_regex, '', content_string).strip() def remove_function_words(self, content_string): """Remove all function words from the given string.""" # a list of function words as defined by JabRef # (cf. https://docs.jabref.org/setup/bibtexkeypatterns) function_words_list = [ "a", "an", "the", "above", "about", "across", "against", "along", "among", "around", "at", "before", "behind", "below", "beneath", "beside", "between", "beyond", "by", "down", "during", "except", "for", "from", "in", "inside", "into", "like", "near", "of", "off", "on", "onto", "since", "to", "toward", "through", "under", "until", "up", "upon", "with", "within", "without", "and", "but", "for", "nor", "or", "so", "yet" ] # join single words with regex 'or' operator function_words = "|".join(function_words_list) word_regex = r"(?:^|(?<=\s))({})(?:(?=\s)|$)".format(function_words) content_string = re.sub(word_regex, '', content_string).strip() # remove consecutive whitespaces content_string = re.sub(r"\s+", " ", content_string) return content_string def format_author_key(self, *format_args): """Generate formatted author key entry.""" authors = self.bibtex_fields.get('author', 'None') authors = self.remove_latex_content(authors) N_entry = 1 # default number of authors to use for the entry if len(format_args) != 0: if re.match(r"\d+", format_args[0]): N_entry = int(format_args[0]) format_args = format_args[1:] author_list = [lastname.strip() for author in authors.split('and') for lastname in author.split(',')[:1]] # do not use more than N_entry author names for the entry author_list = author_list[:N_entry] for format_arg in format_args: author_list = self.apply_format_to_content(author_list, format_arg) return "".join(author_list) def format_year_key(self, *format_args): """Generate formatted year key entry.""" year = self.bibtex_fields.get('year', '0000') # silently ignore additional format commands if len(format_args) == 0: format_args = "long" else: format_args = format_args[0] # check if arguments are valid if format_args not in ["long", "short"]: raise Exception("unknown format argument {} for year (allowed " "arguments are 'short' or 'long')" .format(format_args)) if format_args == 'short': return year[2:] else: return year def format_journal_key(self, *format_args): """Generate formatted journal key entry.""" journal = self.bibtex_fields.get('journal', 'None') if len(format_args) != 0: if re.match(r"\d+", format_args[0]): raise Exception("cannot define the number of words to use for " "the journal key format") journal = self.remove_latex_content(journal) journal = re.sub(r"[^[A-Za-z0-9\s]", '', journal) journal = self.remove_function_words(journal) journal_list = journal.split(' ') for format_arg in format_args: journal_list = self.apply_format_to_content(journal_list, format_arg) return "".join(journal_list) def format_title_key(self, *format_args): """Generate formatted title key entry.""" title = self.bibtex_fields.get('title', 'None') title = self.remove_latex_content(title) N_entry = 3 # default number of words to use for the entry if len(format_args) != 0: if re.match(r"\d+", format_args[0]): N_entry = int(format_args[0]) format_args = format_args[1:] title = re.sub(r"[^[A-Za-z0-9\s]", '', title) title = self.remove_function_words(title) # do not use more than N_entry title words for the entry title_list = title.split(' ')[:N_entry] for format_arg in format_args: title_list = self.apply_format_to_content(title_list, format_arg) return "".join(title_list)
zotero-bibtize
/zotero-bibtize-0.1.0.tar.gz/zotero-bibtize-0.1.0/zotero_bibtize/bibkey_formatter.py
bibkey_formatter.py
import re import collections from zotero_bibtize.bibkey_formatter import KeyFormatter class BibEntry(object): def __init__(self, bibtex_entry_string, key_format=None): self._raw = bibtex_entry_string entry_type, entry_key, entry_fields = self.entry_fields(self._raw) # set internal variables self.type = entry_type if key_format is not None: self.key = KeyFormatter(entry_fields).generate_key(key_format) else: self.key = entry_key self.fields = entry_fields def entry_fields(self, bibtex_entry_string): """Disassemble the bibtex entry contents.""" # revert zotero escaping etype, ekey, econtent = self.bibtex_entry_contents(bibtex_entry_string) # disassemble the field entries fields = {} for field in econtent: key, content = self.field_label_and_contents(field) fields[key] = content return etype, ekey, fields def field_label_and_contents(self, field): """Extract the field label and the corresponding content.""" field, count = re.subn(r'^(\s*)|(\s*)$', '', field) # needs a separate expression for matching months which are # not exported with surrounding braces... regex = r'^([\s\S]*)\s+\=\s+(?:\{([\s\S]*)\}|([\s\S]*)),*?$' fmatch = re.match(regex, field) field_key = fmatch.group(1) field_content = fmatch.group(2) or fmatch.group(3) return field_key, field_content def bibtex_entry_contents(self, raw_entry_string): """Unescape the entry string and get the contained contents.""" # revert zotero escpaing and remove trailing / leading whitespaces unescaped = self.unescape_bibtex_entry_string(raw_entry_string) unescaped = re.sub(r'^(\s*)|(\s*)$', '', unescaped) entry_match = re.match(r'^\@([\s\S]*?)\{([\s\S]*?)\}$', unescaped) entry_type = entry_match.group(1) entry_content = re.split(',\n', entry_match.group(2)) # return type, original zotero key and the actual content list return (entry_type, entry_content[0], entry_content[1:]) def unescape_bibtex_entry_string(self, entry): """Remove zotero escapes and additional braces.""" entry = self.remove_zotero_escaping(entry) entry = self.remove_special_char_escaping(entry) entry = self.remove_curly_from_capitalized(entry) return entry def remove_zotero_escaping(self, entry): # first we remove the escape sequences defined by Zotero zotero_escaping_map = { r"|": r"\{\\textbar\}", r"<": r"\{\\textless\}", r">": r"\{\\textgreater\}", r"~": r"\{\\textasciitilde\}", r"^": r"\{\\textasciicircum\}", r"\\": r"\{\\textbackslash\}", r"{" : r"\\{\\vphantom{\\}}", r"}" : r"\\vphantom{\\{}\\}" } for (replacement, escape_sequence) in zotero_escaping_map.items(): entry, subs = re.subn(escape_sequence, replacement, entry) return entry def remove_special_char_escaping(self, entry): zotero_special_chars = { r"#": r"\\\#", r"%": r"\\\%", r"&": r"\\\&", r"$": r"\\\$", r"_": r"\\\_", r"{": r"\\\{", r"}": r"\\\}", } for (replacement, escape_sequence) in zotero_special_chars.items(): entry, subs = re.subn(escape_sequence, replacement, entry) return entry def remove_curly_from_capitalized(self, entry): """Remove the implicit curly braces added to capitalized words.""" # next remove the implicit curly braces around capitalized words regex = r"\{[A-Z][\w]*?\}" words = re.findall(regex, entry) for word in words: entry = entry.replace(word, word.lstrip("{").rstrip("}")) return entry def __str__(self): # return bibtex entry as string content = ['@{}{{{}'.format(self.type, self.key)] for (field_key, field_content) in self.fields.items(): content.append(' {} = {{{}}}'.format(field_key, field_content)) return ",\n".join(content) + '\n}\n' class BibTexFile(object): """Bibtext file contents""" def __init__(self, bibtex_file, key_format=None): self.bibtex_file = bibtex_file self.entries = [] self.key_map = collections.defaultdict(list) for (index, entry) in enumerate(self.parse_bibtex_entries()): entry = BibEntry(entry, key_format=key_format) self.entries.append(entry) self.key_map[entry.key].append(index) self.resolve_unambiguous_keys() def parse_bibtex_entries(self): """Parse entries from file.""" bibtex_content_str = self.load_bibtex_contents() entry_locations = self.strip_down_entries(bibtex_content_str) entries = [] for (entry_start, entry_stop) in entry_locations: entry_str = bibtex_content_str[entry_start:entry_stop] entries.append(entry_str) return entries def load_bibtex_contents(self): """Load the file contents into a string.""" with open(self.bibtex_file, 'r') as bibfile: contents = bibfile.read() return contents def strip_down_entries(self, content): """Identify single entries in the bibtex output file.""" content_iterator = enumerate(content) bibtex_entries = [] for (index, char) in content_iterator: if char == '@': start_index = index if char == '{': stack = 1 while stack != 0: next_index, next_char = next(content_iterator) if next_char == '}': stack -= 1 elif next_char == '{': stack += 1 bibtex_entries.append((start_index, next_index+1)) return bibtex_entries def num_to_char(self, number): """ Map the given number on chars a-z. All numbers N for 0 <= N <= 25 will be mapped on the chars a-z and numbers N > 25 will be mapped on the chars aa-zz. :param int number: number transformed to char representation """ offset = ord('a') minor = number % 26 major = number // 26 - 1 return chr(offset + major) * (major >= 0) + chr(offset + minor) def resolve_unambiguous_keys(self): """Resolve ambiguous bibtex keys.""" for (key, indices) in self.key_map.items(): # do nothing if the key is unique already if len(indices) == 1: continue # otherwise append a-z / aa-zz to the key for (i, index) in enumerate(indices): self.entries[index].key = key + self.num_to_char(i)
zotero-bibtize
/zotero-bibtize-0.1.0.tar.gz/zotero-bibtize-0.1.0/zotero_bibtize/zotero_bibtize.py
zotero_bibtize.py
import click import pathlib import shutil from zotero_bibtize import BibTexFile @click.command() @click.argument('input_file', type=click.Path(exists=True), default='.', required=False) @click.argument('output_file', type=click.Path(exists=False), default='.', required=False) @click.option('--key-format', required=False, default=None, help=("Format key to generate custom bibtex keys, for instance " "[author:capitalize][journal:capitalize:abbreviate][year]")) def zotero_bibtize(input_file, output_file, key_format): """ Transform Zotero BibTex files to LaTeX friendly representation. Reads in the bibtex contents of the `input_file` (if undefined the bibtex file in the current working directory will be used) and process its contents. Processed contents are then written back to the `output_file` (if undefined the input file will be overwritten!) """ # check input path input_path = pathlib.Path(input_file).absolute() if input_path.is_dir(): bib_files = list(input_path.glob('*.bib')) if len(bib_files) == 0: raise Exception("No bibtex file found at the given location.") elif len(bib_files) > 1: raise Exception("Multiple bibtex files found at the given " "location, please select an explicit file.") bib_in = bib_files[0] else: # input_path.is_file() if input_path.suffix != '.bib': raise Exception("Given file is not of type bibtex file.") bib_in = input_path # check output path output_path = pathlib.Path(output_file).absolute() bib_backup = bib_in.with_name('.' + bib_in.name).with_suffix('.bib.orig') if output_path.is_dir(): shutil.copyfile(bib_in, bib_backup) bib_out = bib_in else: # output_path.is_file() # check if the same file is specified and backup if yes if output_path == input_path: shutil.copyfile(bib_in, bib_backup) bib_out = output_path # read in and write processed contents back bibliography = BibTexFile(str(bib_in), key_format) with open(bib_out, 'w') as bib_out_file: bib_out_file.write(''.join(map(str, bibliography.entries)))
zotero-bibtize
/zotero-bibtize-0.1.0.tar.gz/zotero-bibtize-0.1.0/zotero_bibtize/cli.py
cli.py
<p align="center"><img src="https://github.com/dhondta/zotero-cli/raw/main/docs/pages/imgs/logo.png"></p> <h1 align="center">Zotero CLI <a href="https://twitter.com/intent/tweet?text=Zotero%20CLI%20-%20A%20Tinyscript%20tool%20for%20sorting,%20ranking%20and%20exporting%20Zotero%20references%20based%20on%20pyzotero.%0D%0Ahttps%3a%2f%2fgithub%2ecom%2fdhondta%2fzotero-cli%0D%0A&hashtags=python,zotero,cli,pyzotero,pagerank"><img src="https://img.shields.io/badge/Tweet--lightgrey?logo=twitter&style=social" alt="Tweet" height="20"/></a></h1> <h3 align="center">Sort and rank your Zotero references easy from your CLI.<br>Ask questions to your Zotero documents with GPT locally.</h3> [![PyPi](https://img.shields.io/pypi/v/zotero-cli-tool.svg)](https://pypi.python.org/pypi/zotero-cli-tool/) ![Platform](https://img.shields.io/badge/platform-linux-yellow.svg) [![Python Versions](https://img.shields.io/pypi/pyversions/peid.svg)](https://pypi.python.org/pypi/zotero-cli-tool/) [![Build Status](https://github.com/dhondta/zotero-cli/actions/workflows/publish-package.yml/badge.svg)](https://github.com/dhondta/zotero-cli/actions/workflows/publish-package.yml) [![Read The Docs](https://readthedocs.org/projects/zotero-cli/badge/?version=latest)](https://zotero-cli.readthedocs.io/en/latest/?badge=latest) [![Known Vulnerabilities](https://snyk.io/test/github/dhondta/zotero-cli/badge.svg?targetFile=requirements.txt)](https://snyk.io/test/github/dhondta/zotero-cli?targetFile=requirements.txt) [![DOI](https://zenodo.org/badge/321932121.svg)](https://zenodo.org/badge/latestdoi/321932121) [![License](https://img.shields.io/pypi/l/zotero-cli-tool.svg)](https://pypi.python.org/pypi/zotero-cli-tool/) This [Tinyscript](https://github.com/dhondta/python-tinyscript) tool relies on [`pyzotero`](https://github.com/urschrei/pyzotero) for communicating with [Zotero's Web API](https://www.zotero.org/support/dev/web_api/v3/start). It allows to list field values, show items in tables in the CLI or also export sorted items to an Excel file. ```session $ pip install zotero-cli-tool ``` ## Quick Start The first time you start it, the tool will ask for your API identifier and key. It will cache it to `~/.zotero/creds.txt` with permissions set to `rw` for your user only. Data is cached to `~/.zotero/cache/`. If you are using a shared group library, you can either pass the "`-g`" ("`--group`") option in your `zotero-cli` command or, for setting it permanently, touch an empty file `~/.zotero/group`. - Manually update cached data ```sh $ zotero-cli reset ``` Note that it could take a while. That's why caching is interesting for further use. - Count items in a collection ```sh $ zotero-cli count --filter "collections:biblio" 123 ``` - List values for a given field ```sh $ zotero-cli list itemType Type ---- computer program conference paper document journal article manuscript thesis webpage ``` - Show entries with the given set of fields, filtered based on multiple critera and limited to a given number of items ```sh $ zotero-cli show year title itemType numPages --filter "collections:biblio" --filter "title:detect" --limit ">date:10" Year Title Type #Pages ---- ----- ---- ------ 2016 Classifying Packed Programs as Malicious Software Detected conference paper 3 2016 Detecting Packed Executable File: Supervised or Anomaly Detection Method? conference paper 5 2016 Entropy analysis to classify unknown packing algorithms for malware detection conference paper 21 2017 Packer Detection for Multi-Layer Executables Using Entropy Analysis journal article 18 2018 Sensitive system calls based packed malware variants detection using principal component initialized MultiLayers neural networks journal article 13 2018 Effective, efficient, and robust packing detection and classification journal article 15 2019 Efficient automatic original entry point detection journal article 14 2019 All-in-One Framework for Detection, Unpacking, and Verification for Malware Analysis journal article 16 2020 Experimental Comparison of Machine Learning Models in Malware Packing Detection conference paper 3 2020 Building a smart and automated tool for packed malware detections using machine learning thesis 99 ``` - Export entries ```sh $ zotero-cli export year title itemType numPages --filter "collections:biblio" --filter "title:detect" --limit ">date:10" $ file export.xlsx export.xlsx: Microsoft Excel 2007+ ``` - Use a predefined query ```sh $ zotero-cli show - --query "top-50-most-relevants" ``` > **Note**: "`-`" is used for the `field` positional argument to tell the tool to select the predefined list of fields included in the query. This is equivalent to: ```sh $ zotero-cli show year title numPages itemType --limit ">rank:50" ``` Available queries: - `no-attachment`: list of all items with no attachment ; displayed fields: `title` - `no-url`: list of all items with no URL ; displayed fields: `year`, `title` - `top-10-most-relevants`: top-10 best ranked items ; displayed fields: `year`, `title`, `numPages`, `itemType` - `top-50-most-relevants`: same as top-10 but with the top-50 Mark items: ```sh $ zotero-cli mark read --filter "title:a nice paper" $ zotero-cli mark unread --filter "title:a nice paper" ``` > **Markers**: > > - `read` / `unread`: by default, items are displayed in bold ; marking an item as read will make it display as normal > - `irrelevant` / `relevant`: this allows to exclude a result from the output list of items > - `ignore` / `unignore`: this allows to completely ignore an item, including in the ranking algorithm ## Local GPT This feature is based on [PrivateGPT](https://github.com/imartinez/privateGPT). It can be used to ingest local Zotero documents and ask questions based on a chosen GPT model. - Install optional dependencies ```sh $ pip install zotero-cli-tool[gpt] ``` - Install a model among the followings: - `ggml-gpt4all-j-v1.3-groovy.bin` (default) - `ggml-gpt4all-l13b-snoozy.bin` - `ggml-mpt-7b-chat.bin` - `ggml-v3-13b-hermes-q5_1.bin` - `ggml-vicuna-7b-1.1-q4_2.bin` - `ggml-vicuna-13b-1.1-q4_2.bin` - `ggml-wizardLM-7B.q4_2.bin` - `ggml-stable-vicuna-13B.q4_2.bin` - `ggml-mpt-7b-base.bin` - `ggml-nous-gpt4-vicuna-13b.bin` - `ggml-mpt-7b-instruct.bin` - `ggml-wizard-13b-uncensored.bin` ```sh $ zotero-cli install ``` The latest installed model gets selected for the `ask` command (see hereafter). - Ingest your documents ```sh $ zotero-cli ingest ``` - Ask questions to your documents ```sh $ zotero-cli ask Using embedded DuckDB with persistence: data will be stored in: /home/morfal/.zotero/db Found model file. [...] Enter a query: ``` ## Special Features Some additional fields can be used for listing/filtering/showing/exporting data. - Computed fields - `authors`: the list of `creators` with `creatorType` equal to `author` - `citations`: the number of relations the item has to other items with a later date - `editors`: the list of `creators` with `creatorType` equal to `editor` - `numAttachments`: the number of child items with `itemType` equal to `attachment` - `numAuthors`: the number of `creators` with `creatorType` equal to `author` - `numCreators`: the number of `creators` - `numEditors`: the number of `creators` with `creatorType` equal to `editor` - `numNotes`: the number of child items with `itemType` equal to `note` - `numPages`: the (corrected) number of pages, either got from the original or `pages` field - `references`: the number of relations the item has to other items with an earlier date - `year`: the year coming from the `datetime` parsing of the `date` field - Extracted fields (from the `extra` field) - `comments`: custom field for adding comments - `results`: custom field for mentioning results related to the item - `what`: custom field for a short description of what the item is about - `zscc`: number of Scholar citations, computed with the [Zotero Google Scholar Citations](https://github.com/beloglazov/zotero-scholar-citations) plugin - PageRank-based reference ranking algorithm - `rank`: computed field aimed to rank references in order of relevance ; this uses an algorithm similar to Google's PageRank while weighting references in function of their year of publication (giving more importance to recent references, which cannot have as much citations as older references anyway)
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/README.md
README.md
from tinyscript import * from .__info__ import __author__, __email__, __source__, __version__ from .__init__ import * try: from .gpt import * __GPT = True except ImportError: __GPT = False __copyright__ = ("A. D'Hondt", 2020) __license__ = "gpl-3.0" __script__ = "zotero-cli" __doc__ = """ This tool aims to inspect, filter, sort and export Zotero references. It works by downloading the whole list of items to perform computations locally. It also uses a modified page rank to sort references to help selecting the most relevant ones. """ __examples__ = [ "count -f \"collections:biblio\" -f \"rank:>1.0\"", "export year title itemType numAuthors numPages zscc references what results comments -f \"collections:biblio\" " \ "-s date -l \">rank:50\"", "list attachments", "list collections", "list citations --desc -f \"citations:>10\"", "show title DOI", "show title date zscc -s date -l '>zscc:10'", ] def _set_arg(subparser, arg, msg=None): """ Shortcut function to set arguments repeated for multiple subparsers. """ if arg == "filter": subparser.add_argument("-f", "--filter", action="extend", nargs="*", default=[], note="format: [field]:[regex]", help=msg or "filter to be applied on field's value") elif arg == "limit": subparser.add_argument("-l", "--limit", help="limit the number of displayed records", note="format: either a " "number or [field]:[number]\n '<' and '>' respectively indicates ascending or " "descending order (default: ascending)") elif arg == "query": subparser.add_argument("-q", "--query", choices=list(QUERIES.keys()), help="use a predefined query", note="this can be combined with additional filters") elif arg == "sort": subparser.add_argument("-s", "--sort", help="field to be sorted on", note="if not defined, the first input " "field is selected\n '<' and '>' respectively indicates ascending or descending order" " (default: ascending)") _set_args = lambda sp, *args: [_set_arg(sp, a) for a in args] and None def main(): """ Tool's main function """ # main parser parser.add_argument("-g", "--group", action="store_true", help="API identifier is a group", note="the default API identifier type is 'user' ; use this option if you modified your library " "to be shared with a group of users, this can be set permanently by touching %s" % GROUP_FILE) parser.add_argument("-i", "--id", help="API identifier", note="if 'id' and 'key' not specified, credentials are obtained from file %s" % CREDS_FILE) parser.add_argument("-k", "--key", help="API key", note="if not specified while 'id' is, 'key' is asked as a password") parser.add_argument("-r", "--reset", action="store_true", help="remove cached collections and items") # commands: count | export | list | plot | reset | show | view sparsers = parser.add_subparsers(dest="command", help="command to be executed") if __GPT: cask = sparsers.add_parser("ask", help="ask questions to your Zotero documents") cask.add_argument("name", default=MODEL_DEFAULT_NAME, choices=MODELS, nargs="?", help="model name") cask.add_argument("-c", "--show-content", action="store_true", help="show content from source documents") cask.add_argument("-m", "--mute-stream", action="store_true", help="disable streaming StdOut callback for LLMs") cask.add_argument("-s", "--show-source", action="store_true", help="show source documents") ccount = sparsers.add_parser("count", help="count items") _set_arg(ccount, "filter", "filter to be applied while counting") _set_arg(ccount, "query") cexpt = sparsers.add_parser("export", help="export items to a file") cexpt.add_argument("field", nargs="+", help="field to be shown") cexpt.add_argument("-l", "--line-format", help="line's format string for outputting as a list") cexpt.add_argument("-o", "--output-format", default="xlsx", help="output format", choices=["csv", "html", "json", "md", "pdf", "rst", "xml", "xlsx", "yaml"]) _set_args(cexpt, "filter", "limit", "query", "sort") if __GPT: cingest = sparsers.add_parser("ingest", help="ingest Zotero documents") cinst = sparsers.add_parser("install", help="install a GPT model") cinst.add_argument("name", default=MODEL_DEFAULT_NAME, choices=MODEL_NAMES, nargs="?", help="model name") cinst.add_argument("-d", "--download", action="store_true", help="download the input model") clist = sparsers.add_parser("list", help="list distinct values for the given field") clist.add_argument("field", help="field whose distinct values are to be listed") _set_args(clist, "filter", "query") clist.add_argument("-l", "--limit", type=ts.pos_int, help="limit the number of displayed records") clist.add_argument("--desc", action="store_true", help="sort results in descending order") cmark = sparsers.add_parser("mark", help="mark items with a marker") cmark.add_argument("marker", choices=[x for p in MARKERS for x in p[:2]], help="marker to be set", note="possible values:\n - {}".format("\n - ".join("%s: %s" % (p[0], p[2]) for p in MARKERS))) _set_args(cmark, "filter", "limit", "query", "sort") cplot = sparsers.add_parser("plot", help="plot various information using Matplotlib") cplot.add_argument("chart", choices=CHARTS, help="chart to be plotted") _set_args(cplot, "filter", "query") creset = sparsers.add_parser("reset", help="reset cached collections and items") creset.add_argument("-r", "--reset-items", action="store_true", help="reset items only") if __GPT: cselect = sparsers.add_parser("select", help="select a GPT model") cselect.add_argument("name", default=MODEL_DEFAULT_NAME, choices=MODELS, nargs="?", help="model name") cshow = sparsers.add_parser("show", help="show a list of items") cshow.add_argument("field", nargs="*", help="field to be shown") _set_args(cshow, "filter", "limit", "query", "sort") cview = sparsers.add_parser("view", help="view a single item") cview.add_argument("name", help="field name for selection") cview.add_argument("value", help="field value to be selected") cview.add_argument("field", nargs="+", help="field to be shown") initialize() args.logger = logger if getattr(args, "query", None): if hasattr(args, "field") and args.field == ["-"]: args.field = QUERIES[args.query].get('fields', ["title"]) args.filter.extend(QUERIES[args.query].get('filter', [])) if args.limit is None: args.limit = QUERIES[args.query].get('limit') if args.sort is None: args.sort = QUERIES[args.query].get('sort') if hasattr(args, "sort"): args.desc = False if args.sort is not None: args.desc = args.sort[0] == ">" if args.sort[0] in "<>": args.sort = args.sort[1:] if args.command == "reset" or args.reset: for k in CACHE_FILES: if getattr(args, "reset_items", False) and k not in ["items"] + OBJECTS or k == "marks": continue CACHE_PATH.joinpath(k + ".json").remove(False) z = ZoteroCLI(args.id, ["user", "group"][args.group or GROUP_FILE.exists()], args.key, logger) if args.command == "count": z.count(args.filter) elif args.command == "export": z.export(args.field, args.filter, args.sort, args.desc, args.limit, args.line_format, args.output_format) elif args.command == "install": install() elif args.command == "list": z.list(args.field, args.filter, args.desc, args.limit) elif args.command == "mark": args.filter.append("numPages:>0") z.mark(args.marker, args.filter, args.sort, args.desc, args.limit) elif args.command == "plot": z.plot(args.chart) elif args.command == "show": z.show(args.field, args.filter, args.sort, args.desc, args.limit) elif args.command == "view": z.view(args.name, args.value, args.field) else: # handle commands from gpt.py globals()[args.command](**vars(args))
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/src/zotero/__main__.py
__main__.py
import _pickle import pdfminer import pptx import requests from chromadb.config import Settings from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler from langchain.chains import RetrievalQA from langchain.docstore.document import Document from langchain.document_loaders import * from langchain.embeddings import HuggingFaceEmbeddings from langchain.llms import GPT4All, LlamaCpp from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import Chroma from multiprocessing import Pool from tinyscript import logging, os, sys from tinyscript.helpers import colored, get_terminal_size, std_input, Path, TempPath from tqdm import tqdm __all__ = ["ask", "ingest", "install", "select", "MODEL_DEFAULT_NAME", "MODEL_NAMES", "MODELS"] # Code hereafter is inspired from: https://github.com/imartinez/privateGPT CHUNK_OVERLAP = 50 CHUNK_SIZE = 500 DB_PATH = Path("~/.zotero/db", create=True, expand=True) EMBEDDINGS = "all-MiniLM-L6-v2" LOADERS = { ".csv": CSVLoader, ".docx": Docx2txtLoader, ".doc": UnstructuredWordDocumentLoader, ".docx": UnstructuredWordDocumentLoader, ".enex": EverNoteLoader, ".eml": UnstructuredEmailLoader, ".epub": UnstructuredEPubLoader, ".html": UnstructuredHTMLLoader, ".md": UnstructuredMarkdownLoader, ".odt": UnstructuredODTLoader, ".pdf": PDFMinerLoader, ".ppt": UnstructuredPowerPointLoader, ".pptx": UnstructuredPowerPointLoader, ".txt": (TextLoader, {"encoding": "utf8"}), # Add more mappings for other file extensions and loaders as needed } MODEL_DEFAULT_NAME = "ggml-gpt4all-j-v1.3-groovy.bin" MODEL_LINK = "https://gpt4all.io/models/" MODEL_N_CTX = 1000 MODEL_NAMES = [ "ggml-gpt4all-j-v1.3-groovy.bin", "ggml-gpt4all-l13b-snoozy.bin", "ggml-mpt-7b-chat.bin", "ggml-v3-13b-hermes-q5_1.bin", "ggml-vicuna-7b-1.1-q4_2.bin", "ggml-vicuna-13b-1.1-q4_2.bin", "ggml-wizardLM-7B.q4_2.bin", "ggml-stable-vicuna-13B.q4_2.bin", "ggml-mpt-7b-base.bin", "ggml-nous-gpt4-vicuna-13b.bin", "ggml-mpt-7b-instruct.bin", "ggml-wizard-13b-uncensored.bin", "ggml-model-q4_0.bin", #https://huggingface.co/Pi3141/alpaca-native-7B-ggml/resolve/397e872bf4c83f4c642317a5bf65ce84a105786e/ ] MODEL_PATH = Path("~/.zotero/models", create=True, expand=True) SRC_PATH = Path("~/Zotero/", expand=True) TARGET_SOURCE_CHUNKS = 4 CHROMA_SETTINGS = Settings( chroma_db_impl="duckdb+parquet", persist_directory=str(DB_PATH), anonymized_telemetry=False, ) if MODEL_PATH.joinpath("default").exists(): MODEL_DEFAULT_NAME = MODEL_PATH.joinpath("default").read_text() MODELS = [m.basename for m in MODEL_PATH.listdir() if m.basename != "default" and m.basename in MODEL_NAMES] def _load_doc(path): """ Load the file from the given path with the relevant loader. """ global logger logger.debug(path) loader, kwargs = LOADERS[Path(path).extension], {} if isinstance(loader, tuple) and len(loader) == 2: loader, kwargs = loader try: return loader(path, **kwargs).load() except Exception as e: logger.error("%s (%s)" % (path, str(e))) def _load_docs(zotero_files=SRC_PATH, ignore=None, chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP,**kw): """ Load text chunks from Zotero documents. """ global logger logger = kw.get('logger', logging.nullLogger) p, r = Path(zotero_files, expand=True).joinpath("storage"), [] files = [f for f in map(str, p.walk(filter_func=lambda p: p.extension in LOADERS.keys())) if f not in ignore] logger.info("Loading Zotero documents...") with Pool(processes=os.cpu_count()) as pool, tqdm(total=len(files), ncols=get_terminal_size()[0]) as pbar: for docs in pool.imap_unordered(_load_doc, files): if docs: r.extend(docs) pbar.update() logger.debug("Splitting text from the loaded documents...") splitter = RecursiveCharacterTextSplitter(chunk_size=chunk_size, chunk_overlap=chunk_overlap) return splitter.split_documents(docs) def ask(embeddings=EMBEDDINGS, target_source_chunks=TARGET_SOURCE_CHUNKS, mute_stream=True, model=MODEL_DEFAULT_NAME, model_type="GPT4All", model_n_ctx=MODEL_N_CTX, verbose=False, show_source=False, show_content=False, logger=logging.nullLogger, **kw): """ Open a prompt for querying Zotero documents. """ m = MODEL_PATH.joinpath(Path(model, expand=True).basename) if not m.exists(): install(model) m = MODEL_PATH.joinpath(Path(model, expand=True).basename) embeddings = HuggingFaceEmbeddings(model_name=embeddings) db = Chroma(persist_directory=str(DB_PATH), embedding_function=embeddings, client_settings=CHROMA_SETTINGS) retriever = db.as_retriever(search_kwargs={'k': target_source_chunks}) callbacks = [] if mute_stream else [StreamingStdOutCallbackHandler()] if model_type == "GPT4All": llm = GPT4All(model=str(m), n_ctx=model_n_ctx, backend="gptj", callbacks=callbacks, verbose=verbose) elif model_type == "LlamaCpp": llm = LlamaCpp(model_path=str(m), n_ctx=model_n_ctx, callbacks=callbacks, verbose=verbose) else: logger.error("Bad model type (should be GPT4All or LlamaCpp)") sys.exit(1) qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=show_source) try: while True: query = std_input("\nEnter a query: ", style=["bold", "cyan"]) if query in ["exit", "x"]: return r = qa(query) answer = r['result'] docs = [] if not show_source else r['source_documents'] if len(docs) > 0: print(colored("\nSource documents: ", style=["bold", "cyan"])) for doc in docs: print("-", doc.metadata["source"]) if show_content: print(colored(doc.page_content, style=["white"])) except EOFError: sys.exit(0) def ingest(zotero_files=SRC_PATH, chunk_size=CHUNK_SIZE, chunk_overlap=CHUNK_OVERLAP, embeddings=EMBEDDINGS, logger=logging.nullLogger, **kw): """ Ingest Zotero documents in the vectorstore. """ embeddings = HuggingFaceEmbeddings(model_name=embeddings) if DB_PATH.joinpath("index").is_dir() and \ DB_PATH.joinpath("chroma-collections.parquet").is_file() and \ DB_PATH.joinpath("chroma-embeddings.parquet").is_file() and \ len(list(DB_PATH.joinpath("index").walk(filter_func=lambda p: p.extension in [".bin", ".pkl"]))): logger.debug("Appending to existing vectorstore...") db = Chroma(persist_directory=str(DB_PATH), embedding_function=embeddings, client_settings=CHROMA_SETTINGS) collection = db.get() texts = load(zotero_files, [m['source'] for m in collection['metadatas']], chunk_size, chunk_overlap) logger.info("Creating embeddings, this may take a while...") db.add_documents(texts) else: logger.info("Creating new vectorstore...") texts = _load_docs(zotero_files, [], chunk_size, chunk_overlap, logger=logger) logger.info("Creating embeddings, this may take a while...") db = Chroma.from_documents(texts, embeddings, persist_directory=str(DB_PATH), client_settings=CHROMA_SETTINGS) db.persist() db = None logger.success("Ingestion of Zotero documents complete.") def install(model=MODEL_DEFAULT_NAME, download=False, logger=logging.nullLogger, **kw): """ Install and select the input model in ~/.zotero folder ; download it if required. """ m, fn = Path(model, expand=True), Path(model).basename if fn not in MODEL_NAMES: logger.warning("Model '%s' is not supported" % fn) sys.exit(0) if not MODEL_PATH.joinpath(fn).exists(): if not m.exists(): if download: link, model = MODEL_LINK + fn, TempPath(fn) logger.info("Downloading model '%s'" % fn) resp = requests.get(link, stream=True) l = resp.headers.get("content-length") with model.open("wb") as f: if l is None: model.write(resp.content) else: with tqdm(total=round(int(l)/4096+.5), ncols=get_terminal_size()[0]) as pbar: for data in resp.iter_content(chunk_size=4096): model.write(data) pbar.update() else: logger.error("Input model '%s' does not exist !" % model) sys.exit(1) logger.info("Installing model '%s'..." % m) m.rename(MODEL_PATH.joinpath(fn)) select(fn) else: logger.warning("Model '%s' already exists in %s" % (fn, MODEL_PATH)) def select(model=MODEL_DEFAULT_NAME, **kw): """ Select the input model from ~/.zotero folder. """ MODEL_PATH.joinpath("default").write_text(model)
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/src/zotero/gpt.py
gpt.py
import matplotlib.dates as mdates import matplotlib.pyplot as plt import operator import xlsxwriter from datetime import datetime from pyzotero import zotero, zotero_errors from tinyscript import * from tinyscript.helpers.text import _indent from tinyscript.report import * __all__ = ["ZoteroCLI", "CACHE_FILES", "CACHE_PATH", "CHARTS", "CREDS_FILE", "GROUP_FILE", "MARKERS", "OBJECTS", "QUERIES"] OBJECTS = ["attachments", "notes", "annotations"] CACHE_FILES = ["collections", "items", "marks"] + OBJECTS CACHE_PATH = ts.Path("~/.zotero/cache", create=True, expand=True) CREDS_FILE = ts.CredentialsPath("~/.zotero") GROUP_FILE = ts.Path("~/.zotero/group", expand=True) OPERATORS = { '==': operator.eq, '<': operator.lt, '<=': operator.le, '>': operator.gt, '>=': operator.ge, } FIELD_ALIASES = { 'itemType': "Type", 'what': "What ?", 'zscc': "#Cited", } FLOAT_FIELDS = [] INTEGER_FIELDS = ["callNumber", "citations", "numAttachments", "numAuthors", "numCreators", "numEditors", "numNotes", "numAnnotations", "numPages", "rank", "references", "year", "zscc"] NOTE_FIELDS = ["comments", "results", "what"] CHARTS = ["software-in-time"] MARKERS = [("read", "unread", "this will display the entry as normal instead of bold"), ("irrelevant", "relevant", "this will exclude the entry from the shown results"), ("ignore", "unignore", "this will totally ignore the entry while getting the filtered items")] QUERIES = { 'no-attachment': {'filter': ["numAttachments:0"], 'fields': ["title"]}, 'no-url': {'filter': ["url:<empty>"], 'sort': "year", 'fields': ["year", "title"]}, 'top-10-most-relevants': {'limit': ">rank:10", 'sort': ">date", 'fields': ["year", "title", "numPages", "itemType"]}, 'top-50-most-relevants': {'limit': ">rank:50", 'sort': ">date", 'fields': ["year", "title", "numPages", "itemType"]}, } STATIC_WORDS = ["Android", "Bochs", "Linux", "Markov", "NsPack", "Windows"] TYPE_EMOJIS = { 'artwork': ":art:", 'audio recording': ":microphone:", 'blog post': ":pushpin:", 'book': ":closed_book:", 'computer program': ":floppy_disk:", 'conference paper': ":notebook:", 'default': ":question:", 'document': ":page_facing_up:", 'email': ":email:", 'encyclopedia article': ":book:", 'forum post': ":pushpin:", 'journal article': ":newspaper:", 'magazine article': ":page_with_curl:", 'manuscript': ":scroll:", 'newspaper article': ":newspaper:", 'podcast': ":video_camera:", 'presentation': ":bar_chart:", 'report': ":clipboard:", 'thesis': ":mortar_board:", 'tv broadcast': ":tv:", 'video recording': ":movie_camera:", 'webpage': ":earth_americas:", } def _lower_title(title): g = lambda p, n=1: p.group(n) for i in range(2): # this regex allows to preserve cased subtitles such as: "First Part: Second Part" => "First part: Second part" title = re.sub(r"([^-:!?]\s+(?:[A-Z][a-z]+(?:[-_]?[A-Z]?[a-z]+)*|[A-Z]{2}[a-z]{3,}))", \ lambda p: g(p) if g(p)[1:].strip() in STATIC_WORDS else g(p)[0] + g(p)[1:].lower(), title) # it requires applying twice the transformation as the first one only catches 1 instance out of 2 ; # "An Example Title: With a Subtitle" # ^^^^^^^^^ ^^^^^^ ^^^^^^^^^^ # ^ # this one is not matched the first time as the last "e" of "Example" was already consumed ! # this one corrects bad case for substrings after a punctuation among -:!? title = re.sub(r"([-:!?]\s+)([a-z]+(?:[-_][A-Z]?[a-z]+)*)", lambda p: g(p) + g(p,2)[0].upper() + g(p,2)[1:], title) # the last one ensures that the very first word has its first letter uppercased return re.sub(r"^([A-Z][a-z]+(?:[-_][A-Z]?[a-z]+)*)", lambda p: g(p)[0] + g(p)[1:].lower(), title) class ZoteroCLI(object): def __init__(self, api_id=None, api_id_type="user", api_key=None, main_logger=None): global logger logger = main_logger if api_id is not None and api_key is not None: CREDS_FILE.id = api_id CREDS_FILE.secret = api_key CREDS_FILE.save() self.__zot = None for k in CACHE_FILES: if k == "marks": continue cached_file = CACHE_PATH.joinpath(k + ".json") if cached_file.exists(): if k == "creds": continue # marks is not saved as self.marks but well self._marks_file ; process it separately with cached_file.open() as f: logger.debug("Getting %s from cache '%s'..." % (k, cached_file)) try: setattr(self, k, json.load(f)) except json.decoder.JSONDecodeError: setattr(self, k, []) else: # acquire credentials and setup a zotero.Zotero instance once self._creds() self.__zot = self.__zot or zotero.Zotero(CREDS_FILE.id, api_id_type, CREDS_FILE.secret) # now get the data from zotero.org logger.debug("Getting %s from zotero.org..." % k) if k == "collections": try: self.collections = list(self.__zot.collections()) except zotero_errors.ResourceNotFound: logger.error("Nothing found for ID %s" % CREDS_FILE.id) logger.warning("Beware to use the --group option if this is the ID of a group") return elif k == "items": self.items = list(self.__zot.everything(self.__zot.top())) elif k in OBJECTS: for attr in OBJECTS: if not hasattr(self, attr): setattr(self, attr, []) for i in self.items[:]: if i['meta'].get('numChildren', 0) > 0: for c in self.__zot.children(i['key']): t = c['data']['itemType'] tpl = "%ss" % t if tpl in OBJECTS: getattr(self, tpl).append(c) else: raise ValueError("Unknown item type '%s'" % t) with cached_file.open('w') as f: logger.debug("Saving %s to cache '%s'..." % (k, cached_file)) json.dump(getattr(self, k), f) # handle marks.json separately self._marks_file = CACHE_PATH.joinpath("marks.json") # on the contrary of other JSON files (which are lists of dictionaries), marks.json is a dictionary if not self._marks_file.exists(): self._marks_file.write_text("{}") with self._marks_file.open() as f: logger.debug("Opening marks from cache '%s'..." % self._marks_file) self.marks = json.load(f) self.__objects = {} for a in CACHE_FILES: d = getattr(self, a) if isinstance(d, list): for x in d: try: self.__objects[x['key']] = x except: print(x) raise self._valid_fields = [] self._valid_tags = [] # parse items, collecting valid fields and tags for i in self.items: tags = i['data'].get('tags') if tags: if ts.is_str(tags): tags = tags.split(";") elif ts.is_list(tags): tags = [t['tag'] for t in tags] for t in tags: if t not in self._valid_tags: self._valid_tags.append(t) for f in i['data'].keys(): if f not in self._valid_fields: self._valid_fields.append(f) # also append computed fields to the list of valid fields for f in ["abstractShortNote", "attachments", "authors", "editors", "firstAuthor", "selected"] + \ INTEGER_FIELDS + NOTE_FIELDS: if f not in self._valid_fields: self._valid_fields.append(f) def _creds(self): """ Get API credentials from a local file or ask the user for it. """ if CREDS_FILE.id == "" and CREDS_FILE.secret == "": CREDS_FILE.load() if CREDS_FILE.id == "" and CREDS_FILE.secret == "": CREDS_FILE.ask("API ID: ", "API key: ") CREDS_FILE.save() def _filter(self, fields=None, filters=None, force=False): """ Apply one or more filters to the items. """ # validate and make filters _filters, raised = {}, False for f in filters or []: try: field, regex = list(map(lambda x: x.strip(), f.split(":", 1))) except ValueError as e: raise ValueError("Bad filter '%s' ; format: [field]:[regex]" % f) if regex == "": raise ValueError("Regex for filter on field '%s' is empty" % field) not_ = field[0] == "~" if not_: field = field[1:] # filter format: (negate, comparison operator, first comparison value's lambda, second comparison value) if field in set(INTEGER_FIELDS) - set(["rank"]) and re.match(r"^(|<|>|<=|>=|==)\d+$", regex): m = re.match(r"^(|<|>|<=|>=|==)(\d+)$", regex) op, v = m.group(1), m.group(2).strip() if op == "": op = "==" filt = (not_, OPERATORS[op], lambda i, f: i['data'][f], int(v)) elif field.startswith("date"): if regex in ["-", "<empty>"]: op, v = "==", "" else: m = re.match(r"^(<|>|<=|>=|==)([^=]*)$", regex) op, v = m.group(1), m.group(2).strip() filt = (not_, OPERATORS[op], lambda i, f: ZoteroCLI.date(i['data'][f], i), ZoteroCLI.date(v)) elif field == "rank": m = re.match(r"^(<|>|<=|>=|==)(\d+|\d*\.\d+)$", regex) op, v = m.group(1), m.group(2).strip() filt = (not_, OPERATORS[op], lambda i, f: self.ranks.get(i['key'], 0), float(v)) # filter format: (negate, lambda, lambda's second arg) elif field == "tags": if regex not in self._valid_tags and regex not in ["-", "<empty>"]: logger.debug("Should be one of:\n- " + \ "\n- ".join(sorted(self._valid_tags, key=ZoteroCLI.sort))) raise ValueError("Tag '%s' does not exist" % regex) filt = (not_, lambda i, r: r in ["-", "<empty>"] and i['data']['tags'] in ["", []] or \ r in (i['data']['tags'].split(";") if ts.is_str(i['data']['tags']) else \ [x['tag'] for x in i['data']['tags']]), regex) # filter format: (negate, lambda) ; lambda's second arg is the field name elif regex in ["-", "<empty>"]: filt = (not_, lambda i, f: i['data'].get(f) == 1900) if field == "year" else \ (not_, lambda i, f: i['data'].get(f) == "") else: filt = (not_, re.compile(regex, re.I), lambda i, f: i['data'].get(f) or "") _filters.setdefault(field, []) _filters[field].append(filt) # validate fields afields = (fields or []) + list(_filters.keys()) for f in afields: if f not in self._valid_fields: logger.debug("Should be one of:\n- " + "\n- ".join(sorted(self._valid_fields, key=ZoteroCLI.sort))) raise ValueError("Bad field name '%s'" % f) # now yield items, applying the filters and only selecting the given fields for i in self.items: # create a temporary item with computed fields (e.g. citations) tmp_i = {k: v for k, v in i.items() if k != 'data'} tmp_i['data'] = d = {k: self._format_value(v, k) for k, v in i['data'].items() if k in afields} d['zscc'] = -1 # set custom fields defined in the special field named "Extra" for l in i['data'].get('extra', "").splitlines(): try: field, value = list(map(lambda x: x.strip(), l.split(": ", 1))) except: continue field = field.lower() if field not in i['data'].keys(): if field == "zscc": try: d[field] = int(value) except: pass else: d[field] = self._format_value(value, field) # compute non-existing fields if required if "abstractShortNote" in afields: asn = re.split(r"\.(\s|$)", i['data']['abstractNote'])[0] d['abstractShortNote'] = re.sub(r"\r?\n", "", asn.strip()) + "." if "attachments" in afields: d['attachments'] = [x['data']['title'] for x in self.attachments if x['data']['parentItem'] == i['key']] if "authors" in afields: d['authors'] = [c for c in i['data']['creators'] if c['creatorType'] in ["author", "presenter"]] if "citations" in afields or "references" in afields: c, r = 0, 0 try: links = i['data']['relations']['dc:relation'] if not ts.is_list(links): links = [links] for link in links: k = self.__objects[link.split("/")[-1]] if "collections" in _filters.keys(): gb = True for n, regex, _ in _filters['collections']: b = regex.search(", ".join(self.__objects[x]['data']['name'] for x in \ k['data']['collections'])) gb = gb and [b, not b][n] if not gb: continue if ZoteroCLI.date(k['data']['date'], k) > ZoteroCLI.date(i['data']['date'], i): c += 1 if ZoteroCLI.date(k['data']['date'], k) <= ZoteroCLI.date(i['data']['date'], i): r += 1 except KeyError: pass d['citations'] = c d['references'] = r if "collections" in afields: d['collections'] = [self.__objects[k]['data']['name'] for k in i['data']['collections']] if "editors" in afields: d['editors'] = [c for c in i['data']['creators'] if c['creatorType'] == "editor"] if "firstAuthor" in afields: a = [c for c in i['data']['creators'] if c['creatorType'] in ["author", "presenter"]] d['firstAuthor'] = a[0] if len(a) > 0 else "" if "numAttachments" in afields: d['numAttachments'] = len([x for x in self.attachments if x['data']['parentItem'] == i['key']]) if "numAuthors" in afields: d['numAuthors'] = len([x for x in i['data']['creators'] if x['creatorType'] in ["author", "presenter"]]) if "numCreators" in afields: d['numCreators'] = len([x for x in i['data']['creators']]) if "numEditors" in afields: d['numEditors'] = len([x for x in i['data']['creators'] if x['creatorType'] == "editor"]) if "numNotes" in afields: d['numNotes'] = len([x for x in self.notes if x['data']['parentItem'] == i['key']]) if "numAnnotations" in afields: d['numAnnotations'] = len([x for x in self.annotations if x['data']['parentItem'] == i['key']]) if "numPages" in afields: p = i['data'].get('numPages', i['data'].get('pages')) or "0" m = re.match(r"(\d+)(?:\s*[\-–]+\s*(\d+))?$", p) if m: s, e = m.groups() d['numPages'] = abs(int(s) - int(e or 0)) or -1 else: logger.warning("Bad pages value '%s'" % p) d['numPages'] = -1 if any(x in NOTE_FIELDS for x in afields): for f in NOTE_FIELDS: d[f] = "" for n in self.notes: if n['data']['parentItem'] == i['key']: t = bs4.BeautifulSoup(n['data']['note']).text try: f, c = t.split(":", 1) except: continue f = f.lower() if f in NOTE_FIELDS: d[f] = c.strip() if "year" in afields: dt = i.get('data', {}).get('date') d['year'] = ZoteroCLI.date(dt, i).year if dt else 1900 # now apply filters pass_item = False for field, tfilters in _filters.items(): for tfilter in tfilters: if isinstance(tfilter[1], re.Pattern): b = tfilter[1].search(self._format_value(tfilter[2](tmp_i, field), field)) elif ts.is_lambda(tfilter[1]) and len(tfilter) == 2: b = tfilter[1](tmp_i, field) elif ts.is_lambda(tfilter[1]) and len(tfilter) == 3: b = tfilter[1](tmp_i, tfilter[2]) elif len(tfilter) == 4: b = tfilter[1](tfilter[2](tmp_i, field), tfilter[3]) else: raise ValueError("Unsupported filter") if [not b, b][tfilter[0]]: pass_item = True break if pass_item: break if not pass_item and (not tmp_i['key'] in self.marks.get('ignore', []) or force): yield tmp_i def _format_value(self, value, field=""): """ Ensure the given value is a string. """ v = value if field == "tags": return v if ts.is_str(v) else ";".join(x['tag'] for x in v) elif field == "itemType": return re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', re.sub(r'(.)([A-Z][a-z]+)', r'\1 \2', v)).lower() elif field == "rank": return "%.3f" % float(v or "0") elif field == "year": return [str(v), "-"][v == 1900] elif ts.is_int(v): return [str(v), "-"][v < 0] elif ts.is_list(v): return [", ", ";"][field == "attachments"].join(self._format_value(x, field) for x in v) elif ts.is_dict(v): if field in ["authors", "creators", "editors", "firstAuthor"]: v = v.get('name') or "{} {}".format(v.get('lastName', ""), v.get('firstName', "")).strip() return str(v) def _items(self, fields=None, filters=None, sort=None, desc=False, limit=None, force=False): """ Get items, computing special fields and applying filters. """ filters = filters or [] sort = sort or fields[0] data = [] age, order = True, 3 # define the order of the damping factor function to be applied to the rank field for f in fields: m = re.match(r"rank(\*|\^[1-9])$", f) if m: break if m: f = m.group() if m.group(1) == "*": age = False else: order = int(m.group(1).lstrip("^")) fields.insert(fields.index(f), "rank") fields.remove(f) # extract the limit field lfield, lfdesc = sort, desc if limit is not None: try: lfield, limit = limit.split(":") lfield = lfield.strip() # handle [<>] as sort orders if lfield[0] in "<>": lfdesc = lfield[0] == ">" lfield = lfield[1:] # handle "rank*" as using the strict rank, that is, with no damping factor relatd to the item's age if lfield == "rank*": age = False lfield = "rank" except ValueError: pass if not str(limit).isdigit() or int(limit) <= 0: raise ValueError("Bad limit number ; sould be a positive integer") limit = int(limit) # select relevant items, including all the fields required for further computations ffields = fields[:] if sort not in ffields: ffields.append(sort) if "rank" in fields or lfield == "rank" or sort == "rank" or \ "rank" in [f.split(":")[0].lstrip("~") for f in filters or []]: for f in ["rank", "citations", "references", "year", "zscc"]: if f not in ffields: ffields.append(f) if lfield not in ffields: ffields.append(lfield) items = {i['key']: i for i in \ self._filter(ffields, [f for f in filters if not re.match(r"\~?rank\:", f)], force)} if len(items) == 0: logger.info("No data") return [], [] # compute ranks similarly to the Page Rank algorithm, if relevant if "rank" in ffields: logger.debug("Computing ranks...") # principle: items with a valid date get a weight, others (with year==1900) do not self.ranks = {k: 1./len(items) if i['data']['year'] > 1900 else 0. for k, i in items.items()} # now we can iterate prev = tuple(self.ranks.values()) for n in range(len(self.ranks)): # at most N iterations are required (N being the number of keys) for k1 in self.ranks.keys(): k1_d = self.__objects[k1]['data'] links = k1_d['relations'].get('dc:relation', []) if not ts.is_list(links): links = [links] if items[k1]['data']['year'] == 1900: continue # now compute the iterated rank self.ranks[k1] = float(len([None for l in links if l.split("/")[-1] in items.keys()]) > 0) for link in links: k2 = link.split("/")[-1] if k2 not in items.keys(): continue k2_d = self.__objects[k2]['data'] if ZoteroCLI.date(k1_d['date'], k1_d) <= ZoteroCLI.date(k2_d['date'], k2_d): k2_d = items.get(k2, {}).get('data') if k2_d: r = k2_d['references'] if r > 0: # consider a damping factor on a per-item basis, taking age into account self.ranks[k1] += self.ranks.get(k2, 0.) / r # check for convergence if tuple(self.ranks.values()) == prev: logger.debug("Ranking algorithm converged after %d iterations" % n) break prev = tuple(self.ranks.values()) # apply the damping factor at the very end if age: dt_zero = ZoteroCLI.date("").timestamp() dt = set(ZoteroCLI.date(i['data']['date']).timestamp() for i in items.values()) - {dt_zero} # min/max years are computed to take item's age into account dt_min, dt_max = min(dt), max(dt) # in order not to get a null damping factor for items with minimum year, we shift y_min by 10% to the left dt_min -= max(1, (dt_max - dt_min) // 10) ddt = float(dt_max - dt_min) # set the damping factor formula relying on the previously defined order (default is order 3) df_func = lambda dt: (float(ZoteroCLI.date(dt).timestamp()-dt_min)/ddt)**order self.ranks = {k: df_func(items[k]['data']['date']) * v for k, v in self.ranks.items()} # finally, we normalize ranks max_rank = max(self.ranks.values()) self.ranks = {k: v / max_rank if max_rank else 0. for k, v in self.ranks.items()} for k, r in sorted(self.ranks.items(), key=lambda x: -x[1]): k_d = items[k]['data'] logger.debug("%.05f - %s (%s)" % (r, k_d['title'], k_d['date'])) # reapply filters, including for fields that were just computed items = {i['key']: i for i in self._filter(ffields, filters, force)} for k, i in items.items(): i['data']['rank'] = self.ranks.get(k) if len(items) == 0: logger.info("No data") return # exclude irrelevant items from the list of items if not force: for k, i in {k: v for k, v in items.items()}.items(): if k in self.marks.get('irrelevant', []): del items[k] # apply the limit on the selected items if limit is not None: if lfield is not None: select_items = sorted(items.values(), key=lambda i: ZoteroCLI.sort(i['data'][lfield], lfield)) else: select_items = list(items.values()) if lfdesc: select_items = select_items[::-1] logger.debug("Limiting to %d items (sorted based on %s in %s order)..." % \ (limit, lfield or sort, ["ascending", "descending"][lfdesc])) items = {i['key']: i for i in select_items[:limit]} # ensure that the rank field is set for every item if "rank" in ffields: for i in items.values(): i['data']['rank'] = self.ranks.get(i['key'], .0) # format the selected items as table data logger.debug("Sorting items based on %s..." % sort) for i in sorted(items.values(), key=lambda i: ZoteroCLI.sort(i['data'].get(sort, "-"), sort)): row = [self._format_value(i['data'].get(f), f) if i['data'].get(f) else "-" for f in fields] if len(row) > 1 and all(x in ".-" for x in row[1:]): # row[0] is the item's key ; shall never be "." or "-" continue data.append(row) if desc: data = data[::-1] return [ZoteroCLI.header(f) for f in fields], data def _marks(self, marker, filters=None, sort=None, desc=False, limit=None): """ Mark the selected items with a specified marker. NB: by convetion, a marker can be submitted as its negation with the "un" prefix ; e.g. read <> unread """ m1, m2, negate = None, None, False for m1, m2, _ in MARKERS: if marker in [m1, m2]: negate = marker == m2 marker = m1 break if m1 is None: raise ValueError("Bad marker (should be one of: {})".format("|".join(x for p in MARKERS for x in p[:2]))) self.marks.setdefault(marker, []) _, data = self._items(["key"], filters, sort, desc, limit, True) for row in data: k = row[0] if negate: try: self.marks[marker].remove(k) logger.debug("Unmarked %s from %s" % (k, marker)) except ValueError: pass elif k not in self.marks[marker]: logger.debug("Marked %s as %s" % (k, marker)) self.marks[marker].append(k) self.marks = {k: l for k, l in self.marks.items() if len(l) > 0} with self._marks_file.open('w') as f: logger.debug("Saving marks to cache '%s'..." % self._marks_file) json.dump(self.marks, f) @ts.try_or_die(exc=ValueError, trace=False) def count(self, filters=None): """ Count items while applying filters. """ _, data = self._items(["title"], filters or []) print(len(data)) @ts.try_or_die(exc=ValueError, trace=False) def export(self, fields=None, filters=None, sort=None, desc=False, limit=None, line_format=None, output_format="xlsx"): """ Export the selected fields of items while applying filters to an Excel file. """ if "{stars}" in (line_format or "") and "rank" not in fields: fields.append("rank") headers, data = self._items(fields, filters, sort, desc, limit) if output_format == "xlsx": c, r = string.ascii_uppercase[len(headers)-1], len(data) + 1 logger.debug("Creating Excel file...") wb = xlsxwriter.Workbook("export.xlsx") ws = wb.add_worksheet() ws.add_table("A1:%s%d" % (c, r), { 'autofilter': 1, 'columns': [{'header': h} for h in headers], 'data': data, }) # center header cells cc = wb.add_format() cc.set_align("center") for i, h in enumerate(headers): ws.write("%s1" % string.ascii_uppercase[i], h, cc) # fix widths max_w = [] wtxt = [False] * len(headers) for i in range(len(headers)): m = max(len(str(row[i])) for row in [headers] + data) w = min(m, 80) wtxt[i] = wtxt[i] or m > 80 max_w.append(w) ws.set_column("{0}:{0}".format(string.ascii_uppercase[i]), w) # wrap text where needed and fix heights tw = wb.add_format() tw.set_text_wrap() for j, row in enumerate(data): for i, v in enumerate(row): if wtxt[i]: ws.write(string.ascii_uppercase[i] + str(j+2), v, tw) wb.close() return elif output_format in ["csv", "json", "xml", "yaml"] or line_format is None: r = Report(Table(data, column_headers=headers)) else: if "{stars}" in line_format: # determine highest rank mr, i_rank = 0., [h.lower() for h in headers].index("rank") for row in data: r = row[i_rank] mr = max(mr, float(r if r != "-" else 0)) lines = [] for row in data: d = {k.lower(): v for k, v in zip(headers, row)} if "Title" in headers and "Url" in headers: d['lower_title'] = t = _lower_title(d['title']) d['link'] = d['title'] if d['url'] in ["", "-"] else "[%s](%s)" % (d['title'], d['url']) d['link_lower'] = t if d['url'] in ["", "-"] else "[%s](%s)" % (t, d['url']) if "link" in d.keys() and "link_with_abstract" in line_format: if "AbstractNote" in headers: d['link_with_abstract'] = d['link'] if d['abstractnote'] == "-" else \ "%s\n\n%s\n\n" % (d['link'], _indent(d['abstractnote'], 2)) elif "AbstractShortNote" in headers: d['link_with_abstract'] = d['link'] if d['abstractshortnote'] == "." else \ "%s - %s" % (d['link'], d['abstractshortnote']) if "{emoji}" in line_format: d['emoji'] = TYPE_EMOJIS.get(d['type'], TYPE_EMOJIS['default']) if "{stars}" in line_format: r = float(d['rank']) if d['rank'] != "-" else 0. s = " :star2:" if r == mr else " :star:" d['stars'] = "" if r < .35 else s if .35 <= r < .65 else 2*s if .65 <= r < .85 else 3*s lines.append(line_format.format(**d)) r = Report(List(*lines)) r.filename = "export" logger.debug("Creating %s file..." % output_format.upper()) getattr(r, output_format)(save_to_file=True) @ts.try_or_die(exc=ValueError, trace=False) def list(self, field, filters=None, desc=False, limit=None): """ List field's values while applying filters. """ if field == "collections": l = [c['data']['name'] for c in self.collections] logger.warning("Filters are not applicable to field: collections") elif field == "fields": l = self._valid_fields logger.warning("Filters are not applicable to field: fields") else: l = [row[0] for row in self._items([field], filters)[1]] if len(l) == 0: return if field in ["attachments", "tags"]: tmp, l = l[:], [] for x in tmp: l.extend(x.split(";")) elif field in ["authors", "creators", "editors"]: tmp, l = l[:], [] for x in tmp: l.extend(x.split(", ")) data = [[x] for x in sorted(set(l), key=lambda x: ZoteroCLI.sort(x, field)) if x != "-"] if desc: data = data[::-1] if limit is not None: data = data[:limit] print(ts.BorderlessTable([[ZoteroCLI.header(field)]] + data)) @ts.try_or_die(exc=ValueError, trace=False) def mark(self, marker, filters=None, sort=None, desc=False, limit=None): """ Mark the selected items as read/unread. """ self._marks(marker, filters, sort, desc, limit) @ts.try_or_die(exc=ValueError, trace=False) def plot(self, name, filters=None): """ Plot a chart given its slug. """ if name == "software-in-time": data = {} for i in self._filter(["title", "date"], ["itemType:computerProgram"] + filters): y = ZoteroCLI.date(i['data']['date'], i).year data.setdefault(y, []) data[y].append(i['data']['title']) for y, t in sorted(data.items(), key=lambda x: x[0]): print(["%d:" % y, "####:"][y == 1900], ", ".join(t)) else: logger.debug("Should be one of:\n- " + "\n- ".join(sorted(CHARTS))) logger.error("Bad chart") raise ValueError @ts.try_or_die(exc=ValueError, trace=False) def show(self, fields=None, filters=None, sort=None, desc=False, limit=None): """ Show the selected fields of items while applying filters. """ # ensure the 'key' field is included for filtering the items ; then do not keep it if not selected output_key = "key" in fields if not output_key: fields = ["key"] + fields headers, data = self._items(fields, filters, sort, desc, limit) keys, data = [row[fields.index("key")] for row in data], [row[int(not output_key):] for row in data] if not output_key: headers = headers[1:] if len(headers) > 0: table = ts.BorderlessTable([headers] + data) t_idx = headers.index("Title") for key, row in zip(keys, table.table_data[2:]): if t_idx > 0: row[t_idx] = "\n".join(ts.txt2italic(l) if len(l) > 0 else "" for l in row[t_idx].split("\n")) if key not in self.marks.get('read', []): for i, v in enumerate(row): row[i] = "\n".join(ts.txt2bold(l) if len(l) > 0 else "" for l in v.split("\n")) print(table) @ts.try_or_die(exc=ValueError, trace=False) def view(self, name, value, fields=None): """ View a single item given a field and its value. """ headers, data = self._items(fields, ["%s:%s" % (name, value)]) for h, d in zip(headers, data[0]): hb = ts.txt2bold(h) if h == "Title": d = ts.txt2italic(d) try: d = ast.literal_eval(d) except: pass if not isinstance(d, dict): print("{: <24}: {}".format(hb, d)) else: if len(d) == 0: print("{: <24}: -".format(hb)) elif h == "Relations": print("{: <24}:".format(hb)) rel = d['dc:relation'] if isinstance(rel, str): rel = [rel] for k in rel: print("- %s" % ts.txt2italic(self.__objects[k.split("/")[-1]]['data']['title'])) else: print("{: <24}:\n".format(hb)) for i in d: print("- %s" % i) @staticmethod def date(date_str, data=None): if date_str == "": return datetime.strptime("1900-01-01", "%Y-%m-%d") dt = ts.dateparse(date_str) if dt: return dt msg = "Bad datetime format: %s" % date_str if data: msg += " for item titled '%s'" % ZoteroCLI.title(data) msg += ". Using default date 1900-01-01." logger.warning(msg) return datetime.strptime("1900-01-01", "%Y-%m-%d") @staticmethod def header(field): h = FIELD_ALIASES.get(field, re.sub(r"^num([A-Z].*)$", r"#\1", field)) return h[0].upper() + h[1:] @staticmethod def sort(value, field=None): field = field or "" if field.startswith("date") or field.endswith("Date"): return ZoteroCLI.date(value.lstrip("-"), "sort per %s" % field).timestamp() elif field in FLOAT_FIELDS or field in INTEGER_FIELDS: try: return float(-1 if value in ["", "-", None] else value) except: logger.warning("Bad value '%s' for field %s" % (value, field)) return -1 elif field == "title": s = str(value).lower() if len(s) > 0 and s.split(maxsplit=1)[0] in ["a", "an", "the"]: s = s.split(maxsplit=1)[-1] s = re.sub(r"^\$", "s", re.sub(r"^\@", "a", s.lstrip())).lstrip(string.punctuation) return s else: return str(value).lower() @staticmethod def title(data=None): return(data or {}).get('data', data).get('title', "undefined")
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/src/zotero/__init__.py
__init__.py
# Zotero CLI ## Introduction This Tinyscript tool aims to manipulate Zotero references, relying on [`pyzotero`](https://github.com/urschrei/pyzotero), applying simple filtering if needed, in order to: - Count items - List field values (e.g. for spotting bad values) - Show items in the terminal, given a set of fields - Export items to an Excel file, given a set of fields - Mark items as read/unread - Get the most relevant items (based on a PageRank-like algorithm) Quick example: ``` sh $ zotero-cli list itemType Type ---- computer program conference paper document journal article manuscript thesis webpage ``` ## System Requirements - **Platform**: Linux - **Python**: 2 or 3 ## Installation This tool is available on [PyPi](https://pypi.python.org/pypi/zotero-cli-tool/) (DO NOT confuse with this [package](https://pypi.python.org/pypi/zotero-cli/) which is another related tool) and can be simply installed using Pip via `pip install zotero-cli-tool`.
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/docs/pages/index.md
index.md
# Usage ## Credentials & data cache The first time you start the tool, there is a chance (unless you used something before that created it) you don't have the cached credentials located at `~/.zotero/cache/`. You can either enter you API identifier and key through the `--id` and `--key` options or wait for the tool to ask for these. In both cases the values will be cached to `~/.zotero/cache/`. This way, you won't have to re-enter them next time. From a security perspective, the only protection is that, once created, the credentials file immediately gets the read-write permissions only for your own user. So, the API key is NOT encrypted or hashed and thus resides in cleartext, only protected from reading by other users by the applied permissions. Also, if the cache files do not exist, they will be downloaded from `zotero.org` using [`pyzotero`](https://github.com/urschrei/pyzotero) and saved in `~/.zotero/cache/`. Four JSON files are cached: - `collections.json`: library's collections, downloaded using `pyzotero`'s `Zotero.collections` method. - `items.json`: library's items, downloaded using `pyzotero`'s `Zotero.items` method with parameter `Zotero.everything()` in order to get everything at once. - `attachments.json` and `notes.json`: computed from the downloaded items. Note that option `--reset-items` (with command `reset`) allows to only re-download items, and therefore also resets `attachments.json` and `notes.json`. There are two different ways to reset cached files: 1. Use `-r` (`--reset`) general option (can be used with any command except `reset`) :::sh $ zotero-cli -r list [...] $ zotero-cli -r show [...] 2. Use the `reset` command (this allows to use `--reset-items`) :::sh $ zotero-cli reset -r $ zotero-cli reset --reset-items ## Computed fields In order to refine the returned data, multiple fields are computed by the tool: - `authors`: the list of `creators` with `creatorType` equal to `author` - `citations`: the number of relations the item has to other items with a later date - `editors`: the list of `creators` with `creatorType` equal to `editor` - `numAttachments`: the number of child items with `itemType` equal to `attachment` - `numAuthors`: the number of `creators` with `creatorType` equal to `author` - `numCreators`: the number of `creators` - `numEditors`: the number of `creators` with `creatorType` equal to `editor` - `numNotes`: the number of child items with `itemType` equal to `note` - `numPages`: the (corrected) number of pages, either got from the original or `pages` field - `references`: the number of relations the item has to other items with an earlier date - `year`: the year coming from the `datetime` parsing of the `date` field Additionaly, some fields are extracted from the (native) `extra` field: - `comments`: custom field for adding comments - `results`: custom field for mentioning results related to the item - `what`: custom field for a short description of what the item is about - `zscc`: number of Scholar citations, computed with the [Zotero Google Scholar Citations](https://github.com/beloglazov/zotero-scholar-citations) plugin A PageRank-based reference ranking algorithm is used to refine the data further for allowing to manipulate records by relevance. - `rank`: computed field aimed to rank references in order of relevance ; this uses an algorithm similar to Google's PageRank while weighting references in function of their year of publication (giving more importance to recent references, which cannot have as much citations as older references anyway given their recent nature) !!! note "Filtering and computed fields" Beware that filters (see next subsection) are applied **BEFORE** computing fields. Therefore, using the `rank` field involves that only the filtered items were considered, which can drastically change results regarding their relevance. ## Filter, sort and limit For multiple commands, it is possible to filter fields, sort them and/or limit the number of records returned. - Filtering is done by using the `-f` or `--filter` option with the following format: `[field]:[regex]` ; it is **case-insensitive** and applies to all commands but `reset`. For instance, let us assume a collection named "*Bibliography*", the following `regex` value will filter items from this collection (given that no other collection starts with "`biblio`", of course): :::sh $ zotero-cli list title -f "collections:biblio" Filters are **AND-based**. So, using multiple times the `-f`/`--filter` will of course narrow the results. For instance, this will filter items from a collection named "*Bibliography*" published in 2020: :::sh $ zotero-cli export title -f "collections:biblio" -f "year:2020" There exists an exception to this regex-based filtering ; the `tags` field. It relies on exact matches among the set of existing tags, which are collected at startup while parsing the items. Consequently, an error will be thrown if a bad tag is entered. :::sh $ zotero-cli show title -f "tags:application" -f "tags:python" - Sorting is done by using the `-s` or `--sort` option with the following format: `[field]` Any valid field can be used to sort records, including computed ones. ## Comparison operators While filtering some particular fields, it is desirable to use operators to cover multiple values (e.g. with integers as for the `year` field). For this purpose, the common comparison operators (`<`, `>`, `<=`, `>=` and `==`) are available for use with the `-f`/`--filter`, `-s`/`--sort` and `-l`/`--limit` options for the following fields: - Integers: `citations`, `numAttachments`, `numAuthors`, `numNotes`, `numPages`, `references`, `year`, `zscc` :::sh $ zotero-cli show title -f "year:<=2015" -f "numPages:>5" - Floats: `rank` :::sh $ zotero-cli show title -f "rank:>=1.5" -f "rank:<2.5" - Dates: `date`, `dateAdded`, `dateModified` :::sh $ zotero-cli show title -f "date:>Sep 2018" !!! note "Supported datetime formats" In order to filter datetimes, the following formats are supported: - `%Y`: e.g. `2020` - `%b %Y`: e.g. `Oct 2019` - `%B %Y`: e.g. `September 2018` - `%Y-%m-%dT%H:%M:%SZ`: e.g. `2019-10-01T12:00:00Z` - `%b %d %Y at %I:%M%p`: e.g. `Jul 01 2015 at 02:01PM` - `%B %d, %Y, %H:%M:%S`: e.g. `April 03, 2016, 13:15:00` ## List field values It can be useful to inspect the values for a particular field, e.g. for correcting or normalizing some values. The `list` command allows to list all the existing values from the library. It is also possible to list the available fields by simply using `fields`: ```sh $ zotero-cli list fields Fields ------ abstractNote accessDate archive archiveLocation [...] ``` Besides valid fields, attached files can also be listed by using `attachments`. Any of the field names can then be used to list available values. ```sh $ zotero-cli list publisher Publisher --------- - ACM [...] IEEE [...] Springer [...] ``` When the empty value also exists for the given field, it is listed as "`-`". Beware that it can be filtered by using `-f "[field]:<empty>"`. ```sh $ zotero-cli show title -f "publisher:<empty>" Title ----- [...] ``` This can be very helpful to identify entries that have missing information. !!! note "List of values" Unless handled in the tool, fields that have lists of values (e.g. `tags` with a list of semicolon-separted values) will be displayed as is. The following fields have this special handling for collecting distinct values: `authors`, `creators`, `editors` and `tags`. ## Count/Show/Export items Library items can be manipulated in different ways, as shown hereafter. - Counting items (filter only): :::sh $ zotero-cli count -f "collections:biblio" -f "date:>Sep 2018" 123 - Showing or exporting items (filter + sort + limit): :::sh $ zotero-cli show year title numPages -f "collections:biblio" -f "date:>Sep 2018" -s date -l ">rank:2" ## Use predefined queries Some queries are predefined for the sake of simplicity. ```sh $ zotero-cli show - --query "top-50-most-relevants" Year Title #Pages Type ---- ----- ------ ---- [...] ``` !!! note "Field argument" Use the "`-`" field argument to use the list of fields to be displayed from the query. If other fields should be displayed, they can be entered instead of "`-`" as normal ; this will override the fields from the query. ```sh $ zotero-cli show year title --query "top-50-most-relevants" Year Title ---- ----- [...] ``` Moreover, using the `--limit` or `--sort` options will override these of the query. ```sh $ zotero-cli show year title --sort title --query "top-10-most-relevants" $ zotero-cli show year title --limit "title:5" --query "top-10-most-relevants" ``` The following queries are currently implemented: - `top-10-most-relevants`: returns the top-10 most relevant references, setting the `rank` field for ranking items according to a PageRank-like algorithm ; the displayed fields are `Year`, `Title`, `#Pages` and `Type`. - `top-50-most-relevants`: identical to the previous query, but with the top-50. - `no-attachment`: returns the list of items with no attachment ; useful for identifying references for which the related document was not attached yet, this only displays the `Title`. - `no-url`: returns the list of items with no URL ; useful for identifying references that have no hyperlink yet, this only displays the `Year` and `Title`, sorted by `Year`. ## Mark items Library items can be marked as read or unread. By default, items are logically considered unread and are therefore displayed in bold. Once marked as read, they are not displayed in bold anymore. ```sh $ zotero-cli mark --filter "key:QZR5QAIW" $ zotero-cli mark --query "top-10-most-relevants" ``` !!! note "Available markers" - `read` / `unread`: by default, items are displayed in bold ; marking an item as read will make it display as normal - `irrelevant` / `relevant`: this allows to exclude a result from the output list of items - `ignore` / `unignore`: this allows to completely ignore an item, including in the ranking algorithm NB: Markers are stored with [other JSON files in the cache](#credentials-data-cache), that is, at `~/.zotero/cache/marks.json`.
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/docs/pages/usage.md
usage.md
# FAQ ## How to enter new credentials ? Reference: [*Credentials & data cache*](usage.html#credentials-data-cache). ```sh $ zotero-cli --id <my-id> --key <my-key> [...] $ zotero-cli -i <my-id> -k <my-key> [...] ``` This will save the new credentials to `~/.zotero/creds.txt`. If you want to immediately re-download library items, use the `reset` command. ```sh $ zotero-cli --id <my-id> --key <my-key> reset $ zotero-cli -i <my-id> -k <my-key> reset ``` ## How to reset the cache ? Reference: [*Credentials & data cache*](usage.html#credentials-data-cache). ```sh $ zotero-cli reset ``` In order to only reset cached items (and therefore attachments and notes), use: ```sh $ zotero-cli reset --reset-items $ zotero-cli reset -r ``` If you want to reset everything while using another command, use `-r` or `--reset`: ```sh $ zotero-cli --reset list title $ zotero-cli -r count $ zotero-cli -r show [...] ``` ## How to list values ? Reference: [*List field values*](usage.html#list-field-values). ```sh $ zotero-cli list title $ zotero-cli list authors $ zotero-cli list collections $ zotero-cli list attachments ``` ## How to show items with filters ? Reference: [*Filter, sort and limit*](usage.html#filter-sort-limit). ```sh $ zotero-cli show title -f "collections:bibliography" $ zotero-cli show year title -f "collections:biblio" -f "date:2020" $ zotero-cli show year title numPages -f "collections:biblio" -f "date:2020" -f "tags:python" ``` !!! note "Filter characteristics" Filters are **case-insensitive** and only **AND**-based. The `tags` field is an exception to regex-based filtering as it uses exact matching with regard to the list of valid tags encountered in the whole library of items. ## How to sort items ? Reference: [*Filter, sort and limit*](usage.html#filter-sort-limit). ```sh $ zotero-cli show title -f "collections:biblio" -s date $ zotero-cli show year title -f "collections:biblio" -s "<date" $ zotero-cli show year title -f "collections:biblio" -s ">date" ``` ## How to limit the number of items ? Reference: [*Filter, sort and limit*](usage.html#filter-sort-limit). ```sh $ zotero-cli show year title -f "collections:biblio" -l "date:10" $ zotero-cli show year title -f "collections:biblio" -l ">date:10" $ zotero-cli show year title -f "collections:biblio" -s date -l "numPages:10" $ zotero-cli show year title -f "collections:biblio" -s date -l ">numPages:10" ``` !!! note "Sorting before applying the limit" Beware that, if `--sort` and `--limit` are used together, a first sorting is applied based on the field name mentioned in `--limit` and items are then sorted with the field from `--sort`. ## How to filter all items for a given author ? References: [*Filter, sort and limit*](usage.html#filter-sort-limit), [*Count/Show/Export items*](usage.html#count-show-export-items). ```sh $ zotero-cli show year title -f "collections:biblio" -f "authors:smith" $ zotero-cli show year title -f "collections:biblio" -f "authors:smith" -f "authors:anderson" ``` ## How to show titles for which the date is not filled in ? References: [*Filter, sort and limit*](usage.html#filter-sort-limit), [*Count/Show/Export items*](usage.html#count-show-export-items). ```sh $ zotero-cli show title -f "date:<empty>" $ zotero-cli show title -f "collections:biblio" -f "date:-" ``` ## How to mark items as read/unread ? Reference: [*Mark items as read/unread*](usage.html#mark-items-as-read-unread) ```sh $ zotero-cli mark --filter "key:QZR5QAIW" $ zotero-cli mark --query "top-10-most-relevants" ```
zotero-cli-tool
/zotero-cli-tool-1.6.3.tar.gz/zotero-cli-tool-1.6.3/docs/pages/faq.md
faq.md
# zotero-cli [![asciicast](http://asciinema.org/a/17n8da33w2gj67pyfwegfmfns.png)](https://asciinema.org/a/17n8da33w2gj67pyfwegfmfns) A simple command-line interface for the Zotero API. Currently the following features are supported: - Search for items in the library - Add/Edit notes for existing items - Launch reader application for item attachments - Edit notes with a text editor of your choice in any format supported by pandoc (markdown, reStructuredText, etc.) ## Installation `zotero-cli` can be trivially installed from PyPi with `pip`: ``` $ pip install zotero-cli ``` If you want to try the bleeding-edge version: ``` $ pip install git+git://github.com/jbaiter/zotero-cli.git@master ``` ## Usage To change the editor on *nix systems, set the `VISUAL` environment variable. If you want to use a markup format other than pandoc's `markdown`, edit the configuration file under `~/.config/zotcli/config.ini` and set the `note_format` field to your desired value (as seen in `pandoc --help`). First, perform the initial configuration to generate an API key for the application: ``` $ zotcli configure ``` Search for an item: ``` $ zotcli query "deep learning" [F5R83K6P] Goodfellow et al.: Deep Learning ``` Query strings with whitespace must be enclosed in quotes. For details on the supported syntax, consult the [SQLite FTS documentation](https://www.sqlite.org/fts3.html#section_3). Briefly, supported are `AND`/`OR`/`NOT` operators and prefix-search via the Kleene operator (e.g. `pref*`). Read an item's attachment: ``` $ zotcli read "deep learning" # Will launch the default PDF viewer with the item's first PDF attachment ``` Add a new note to an item using either the item's ID or a query string to locate it: ``` $ zotcli add-note "deep learning" # Edit note in editor, save and it will be added to the library ``` If more than one item is found for the query string, you will be prompted which one to use. Edit an existing note (you can use a query string instead of an ID, too): ``` $ zotcli edit-note F5R83K6P # Edit note in editor, save and it will be updated in the library ```
zotero-cli
/zotero-cli-0.3.0.tar.gz/zotero-cli-0.3.0/README.md
README.md
from __future__ import print_function import itertools import logging import os import re import click import pathlib import pypandoc import requests from zotero_cli.common import save_config from zotero_cli.backend import ZoteroBackend EXTENSION_MAP = { 'docbook': 'dbk', 'latex': 'tex', } ID_PAT = re.compile(r'[A-Z0-9]{8}') PROFILE_PAT = re.compile(r'([a-z0-9]{8})\.(.*)') def get_extension(pandoc_fmt): """ Get the file extension for a given pandoc format. :param pandoc_fmt: A format as supported by (py)pandoc :returns: The file extension with leading dot """ if 'mark' in pandoc_fmt: return '.md' elif pandoc_fmt in EXTENSION_MAP: return EXTENSION_MAP[pandoc_fmt] else: return '.' + pandoc_fmt def find_storage_directories(): home_dir = pathlib.Path(os.environ['HOME']) firefox_dir = home_dir/".mozilla"/"firefox" zotero_dir = home_dir/".zotero" candidate_iter = itertools.chain(firefox_dir.iterdir(), zotero_dir.iterdir()) for fpath in candidate_iter: if not fpath.is_dir(): continue match = PROFILE_PAT.match(fpath.name) if match: storage_path = fpath/"zotero"/"storage" if storage_path.exists(): yield (match.group(2), storage_path) @click.group(context_settings={'help_option_names': ['-h', '--help']}) @click.option('--verbose', '-v', is_flag=True) @click.option('--api-key', default=None) @click.option('--library-id', default=None) @click.pass_context def cli(ctx, verbose, api_key, library_id): """ Command-line access to your Zotero library. """ logging.basicConfig(level=logging.DEBUG if verbose else logging.WARNING) if ctx.invoked_subcommand != 'configure': try: ctx.obj = ZoteroBackend(api_key, library_id, 'user') except ValueError as e: ctx.fail(e.args[0]) @cli.command() def configure(): """ Perform initial setup. """ config = { 'sync_interval': 300 } generate_key = not click.confirm("Do you already have an API key for " "zotero-cli?") if generate_key: (config['api_key'], config['library_id']) = ZoteroBackend.create_api_key() else: config['api_key'] = click.prompt( "Please enter the API key for zotero-cli") config['library_id'] = click.prompt("Please enter your library ID") sync_method = select( [("local", "Local Zotero storage"), ("zotcoud", "Use Zotero file cloud"), ("webdav", "Use WebDAV storage")], default=1, required=True, prompt="How do you want to access files for reading?") if sync_method == "local": storage_dirs = tuple(find_storage_directories()) if storage_dirs: options = [(name, "{} ({})".format(click.style(name, fg="cyan"), path)) for name, path in storage_dirs] config['storage_dir'] = select( options, required=False, prompt="Please select a storage directory (-1 to enter " "manually)") if config.get('storage_dir') is None: click.echo( "Could not automatically locate a Zotero storage directory.") while True: storage_dir = click.prompt( "Please enter the path to your Zotero storage directory", default='') if not storage_dir: storage_dir = None break elif not os.path.exists(storage_dir): click.echo("Directory does not exist!") elif not re.match(r'.*storage/?', storage_dir): click.echo("Path must point to a `storage` directory!") else: config['storage_dir'] = storage_dir break elif sync_method == "webdav": while True: if not config.get('webdav_path'): config['webdav_path'] = click.prompt( "Please enter the WebDAV URL (without '/zotero'!)") if not config.get('webdav_user'): config['webdav_user'] = click.prompt( "Please enter the WebDAV user name") config['webdav_pass'] = click.prompt( "Please enter the WebDAV password") try: test_resp = requests.get( config['webdav_path'], auth=(config['webdav_user'], config['webdav_pass'])) except requests.ConnectionError: click.echo("Invalid WebDAV URL, could not reach server.") config['webdav_path'] = None continue if test_resp.status_code == 501: break elif test_resp.status_code == 404: click.echo("Invalid WebDAV path, does not exist.") config['webdav_path'] = None elif test_resp.status_code == 401: click.echo("Bad credentials.") config['webdav_user'] = None else: click.echo("Unknown error, please check your settings.") config['webdav_path'] = None config['webdav_user'] = None config['sync_method'] = sync_method markup_formats = pypandoc.get_pandoc_formats()[0] config['note_format'] = select(zip(markup_formats, markup_formats), default=markup_formats.index('markdown'), prompt="Select markup format for notes") save_config(config) zot = ZoteroBackend(config['api_key'], config['library_id'], 'user') click.echo("Initializing local index...") num_synced = zot.synchronize() click.echo("Synchronized {} items.".format(num_synced)) @cli.command() @click.pass_context def sync(ctx): """ Synchronize the local search index. """ num_items = ctx.obj.synchronize() click.echo("Updated {} items.".format(num_items)) @cli.command() @click.argument("query", required=False) @click.option("--limit", "-n", type=int, default=100) @click.pass_context def query(ctx, query, limit): """ Search for items in the Zotero database. """ for item in ctx.obj.search(query, limit): out = click.style(u"[{}] ".format(item.citekey or item.key), fg='green') if item.creator: out += click.style(item.creator + u': ', fg='cyan') out += click.style(item.title, fg='blue') if item.date: out += click.style(" ({})".format(item.date), fg='yellow') click.echo(out) @cli.command() @click.option("--with-note", '-n', required=False, is_flag=True, default=False, help="Open the editor for taking notes while reading.") @click.argument("item-id", required=True) @click.pass_context def read(ctx, item_id, with_note): """ Read an item attachment. """ try: item_id = pick_item(ctx.obj, item_id) except ValueError as e: ctx.fail(e.args[0]) read_att = None attachments = ctx.obj.attachments(item_id) if not attachments: ctx.fail("Could not find an attachment for reading.") elif len(attachments) > 1: click.echo("Multiple attachments available.") read_att = select([(att, att['data']['title']) for att in attachments]) else: read_att = attachments[0] att_path = ctx.obj.get_attachment_path(read_att) click.echo("Opening '{}'.".format(att_path)) click.launch(str(att_path), wait=False) if with_note: existing_notes = list(ctx.obj.notes(item_id)) if existing_notes: edit_existing = click.confirm("Edit existing note?") if edit_existing: note = pick_note(ctx.obj, item_id) else: note = None else: note = None note_body = click.edit( text=note['data']['note']['text'] if note else None, extension=get_extension(ctx.obj.note_format)) if note_body and note is None: ctx.obj.create_note(item_id, note_body) elif note_body: note['data']['note']['text'] = note_body ctx.obj.save_note(note) @cli.command("add-note") @click.argument("item-id", required=True) @click.option("--note-format", "-f", required=False, help=("Markup format for editing notes, see the pandoc docs for " "possible values")) @click.pass_context def add_note(ctx, item_id, note_format): """ Add a new note to an existing item. """ if note_format: ctx.obj.note_format = note_format try: item_id = pick_item(ctx.obj, item_id) except ValueError as e: ctx.fail(e.args[0]) note_body = click.edit(extension=get_extension(ctx.obj.note_format)) if note_body: ctx.obj.create_note(item_id, note_body) @cli.command("edit-note") @click.argument("item-id", required=True) @click.argument("note-num", required=False, type=int) @click.pass_context def edit_note(ctx, item_id, note_num): """ Edit a note. """ try: item_id = pick_item(ctx.obj, item_id) except ValueError as e: ctx.fail(e.args[0]) note = pick_note(ctx.obj, item_id, note_num) updated_text = click.edit(note['data']['note']['text'], extension=get_extension(ctx.obj.note_format)) if updated_text: note['data']['note']['text'] = updated_text ctx.obj.save_note(note) @cli.command("export-note") @click.argument("item-id", required=True) @click.argument("note-num", required=False, type=int) @click.option("--output", '-o', type=click.File(mode='w'), default='-') @click.pass_context def export_note(ctx, item_id, note_num, output): """ Export a note. """ try: item_id = pick_item(ctx.obj, item_id) except ValueError as e: ctx.fail(e.args[0]) note = pick_note(ctx.obj, item_id, note_num) output.write(note['data']['note']['text'].encode('utf8')) def pick_note(zot, item_id, note_num=None): notes = tuple(zot.notes(item_id)) if not notes: zot.fail("The item does not have any notes.") if note_num is None: if len(notes) > 1: note = select( [(n, re.sub("[^\w]", " ", n['data']['note']['text'].split('\n')[0])) for n in notes]) else: note = notes[0] else: note = notes[note_num] return note def pick_item(zot, item_id): if not ID_PAT.match(item_id): items = tuple(zot.search(item_id)) if len(items) > 1: click.echo("Multiple matches available.") item_descriptions = [] for it in items: desc = click.style(it.title, fg='blue') if it.creator: desc = click.style(it.creator + u': ', fg="cyan") + desc if it.date: desc += click.style(" ({})".format(it.date), fg='yellow') item_descriptions.append(desc) return select(zip(items, item_descriptions)).key elif items: return items[0].key else: raise ValueError("Could not find any items for the query.") def select(choices, prompt="Please choose one", default=0, required=True): """ Let the user pick one of several choices. :param choices: Available choices along with their description :type choices: iterable of (object, str) tuples :param default: Index of default choice :type default: int :param required: If true, `None` can be returned :returns: The object the user picked or None. """ choices = list(choices) for idx, choice in enumerate(choices): _, choice_label = choice if '\x1b' not in choice_label: choice_label = click.style(choice_label, fg='blue') click.echo( u"{key} {description}".format( key=click.style(u"[{}]".format(idx), fg='green'), description=choice_label)) while True: choice_idx = click.prompt(prompt, default=default, type=int, err=True) cutoff = -1 if not required else 0 if choice_idx < cutoff or choice_idx >= len(choices): click.echo( "Value must be between {} and {}!" .format(cutoff, len(choices)-1), err=True) elif choice_idx == -1: return None else: return choices[choice_idx][0]
zotero-cli
/zotero-cli-0.3.0.tar.gz/zotero-cli-0.3.0/zotero_cli/cli.py
cli.py
import codecs import json import logging import os import re import tempfile import time import urllib try: import urlparse except ImportError: import urllib.parse as urlparse try: urlencode = urllib.urlencode except AttributeError: urlencode = urlparse.urlencode import zipfile try: from cStringIO import StringIO except ImportError: # Python 3 from io import BytesIO as StringIO import click import pypandoc import requests from pathlib import Path from pyzotero.zotero import Zotero from rauth import OAuth1Service from zotero_cli.common import APP_NAME, Item, load_config from zotero_cli.index import SearchIndex TEMP_DIR = Path(tempfile.mkdtemp(prefix='zotcli')) DATA_PAT = re.compile( r'<div class="zotcli-note">.*<p .*title="([A-Za-z0-9+/=\n ]+)">.*</div>', flags=re.DOTALL | re.MULTILINE) CITEKEY_PAT = re.compile(r'^bibtex: (.*)$', flags=re.MULTILINE) DATA_TMPL = """ <div class="zotcli-note"> <p xmlns="http://www.w3.org/1999/xhtml" id="zotcli-data" style="color: #cccccc;" xml:base="http://www.w3.org/1999/xhtml" title="{data}"> (hidden zotcli data) </p> </div> """ CLIENT_KEY = 'c7d12bbd2c829823ddbc' CLIENT_SECRET = 'c1ffe13aaeaa59ebf293' REQUEST_TOKEN_URL = 'https://www.zotero.org/oauth/request' AUTH_URL = 'https://www.zotero.org/oauth/authorize' ACCESS_TOKEN_URL = 'https://www.zotero.org/oauth/access' BASE_URL = 'https://api.zotero.org' def encode_blob(data): """ Encode a dictionary to a base64-encoded compressed binary blob. :param data: data to encode into a blob :type data: dict :returns: The data as a compressed base64-encoded binary blob """ blob_data = json.dumps(data).encode('utf8') for codec in ('zlib', 'base64'): blob_data = codecs.encode(blob_data, codec) return blob_data def decode_blob(blob_data): """ Decode a base64-encoded, zlib-compressed binary blob to a dictionary. :param blob_data: base64-encoded binary blob, contains zlib-compressed JSON :type blob_data: bytes :returns: The original data as a dictionary """ for codec in ('base64', 'zlib'): blob_data = codecs.decode(blob_data, codec) return json.loads(blob_data.decode('utf8')) class ZoteroBackend(object): @staticmethod def create_api_key(): """ Interactively create a new API key via Zotero's OAuth API. Requires the user to enter a verification key displayed in the browser. :returns: API key and the user's library ID """ auth = OAuth1Service( name='zotero', consumer_key=CLIENT_KEY, consumer_secret=CLIENT_SECRET, request_token_url=REQUEST_TOKEN_URL, access_token_url=ACCESS_TOKEN_URL, authorize_url=AUTH_URL, base_url=BASE_URL) token, secret = auth.get_request_token( params={'oauth_callback': 'oob'}) auth_url = auth.get_authorize_url(token) auth_url += '&' + urlencode({ 'name': 'zotero-cli', 'library_access': 1, 'notes_access': 1, 'write_access': 1, 'all_groups': 'read'}) click.echo("Opening {} in browser, please confirm.".format(auth_url)) click.launch(auth_url) verification = click.prompt("Enter verification code") token_resp = auth.get_raw_access_token( token, secret, method='POST', data={'oauth_verifier': verification}) if not token_resp: logging.debug(token_resp.content) click.fail("Error during API key generation.") access = urlparse.parse_qs(token_resp.text) return access['oauth_token'][0], access['userID'][0] def __init__(self, api_key=None, library_id=None, library_type='user'): """ Service class for communicating with the Zotero API. This is mainly a thin wrapper around :py:class:`pyzotero.zotero.Zotero` that handles things like transparent HTML<->[edit-formt] conversion. :param api_key: API key for the Zotero API, will be loaded from the configuration if not specified :param library_id: Zotero library ID the API key is valid for, will be loaded from the configuration if not specified :param library_type: Type of the library, can be 'user' or 'group' """ self._logger = logging.getLogger() idx_path = os.path.join(click.get_app_dir(APP_NAME), 'index.sqlite') self.config = load_config() self.note_format = self.config['zotcli.note_format'] self.storage_dir = self.config.get('zotcli.storage_dir') api_key = api_key or self.config.get('zotcli.api_key') library_id = library_id or self.config.get('zotcli.library_id') if not api_key or not library_id: raise ValueError( "Please set your API key and library ID by running " "`zotcli configure` or pass them as command-line options.") self._zot = Zotero(library_id=library_id, api_key=api_key, library_type=library_type) self._index = SearchIndex(idx_path) sync_interval = self.config.get('zotcli.sync_interval', 300) since_last_sync = int(time.time()) - self._index.last_modified if since_last_sync >= int(sync_interval): self._logger.info("{} seconds since last sync, synchronizing." .format(since_last_sync)) self.synchronize() def synchronize(self): """ Update the local index to the latest library version. """ new_items = tuple(self.items(since=self._index.library_version)) version = int(self._zot.request.headers.get('last-modified-version')) self._index.index(new_items, version) return len(new_items) def search(self, query, limit=None): """ Search the local index for items. :param query: A sqlite FTS4 query :param limit: Maximum number of items to return :returns: Generator that yields matching items. """ return self._index.search(query, limit=limit) def items(self, query=None, limit=None, recursive=False, since=0): """ Get a list of all items in the library matching the arguments. :param query: Filter items by this query string (targets author and title fields) :type query: str/unicode :param limit: Limit maximum number of returned items :type limit: int :param recursive: Include non-toplevel items (attachments, notes, etc) in output :type recursive: bool :returns: Generator that yields items """ query_args = {'since': since} if query: query_args['q'] = query if limit: query_args['limit'] = limit query_fn = self._zot.items if recursive else self._zot.top items = self._zot.makeiter(query_fn(**query_args)) for chunk in items: for it in chunk: matches = CITEKEY_PAT.finditer(it['data'].get('extra', '')) citekey = next((m.group(1) for m in matches), None) yield Item(key=it['data']['key'], creator=it['meta'].get('creatorSummary'), title=it['data'].get('title', "Untitled"), date=it['data'].get('date'), citekey=citekey) def notes(self, item_id): """ Get a list of all notes for a given item. :param item_id: ID/key of the item to get notes for :returns: Notes for item """ notes = self._zot.children(item_id, itemType="note") for note in notes: note['data']['note'] = self._make_note(note) yield note def attachments(self, item_id): """ Get a list of all attachments for a given item. If a zotero profile directory is specified in the configuration, a resolved local file path will be included, if the file exists. :param item_id: ID/key of the item to get attachments for :returns: Attachments for item """ attachments = self._zot.children(item_id, itemType="attachment") if self.storage_dir: for att in attachments: if not att['data']['linkMode'].startswith("imported"): continue fpath = os.path.join(self.storage_dir, att['key'], att['data']['filename']) if not os.path.exists(fpath): continue att['data']['path'] = fpath return attachments def get_attachment_path(self, attachment): if not attachment['data']['linkMode'].startswith("imported"): raise ValueError( "Attachment is not stored on server, cannot download!") storage_method = self.config['zotcli.sync_method'] if storage_method == 'local': return Path(attachment['data']['path']) out_path = TEMP_DIR/attachment['data']['filename'] if out_path.exists(): return out_path if storage_method == 'zotero': self._zot.dump(attachment['key'], path=unicode(TEMP_DIR)) return out_path elif storage_method == 'webdav': user = self.config['zotcli.webdav_user'] password = self.config['zotcli.webdav_pass'] location = self.config['zotcli.webdav_path'] zip_url = "{}/zotero/{}.zip".format( location, attachment['key']) resp = requests.get(zip_url, auth=(user, password)) zf = zipfile.ZipFile(StringIO(resp.content)) zf.extractall(str(TEMP_DIR)) return out_path def _make_note(self, note_data): """ Converts a note from HTML to the configured markup. If the note was previously edited with zotcli, the original markup will be restored. If it was edited with the Zotero UI, it will be converted from the HTML via pandoc. :param note_html: HTML of the note :param note_version: Library version the note was last edited :returns: Dictionary with markup, format and version """ data = None note_html = note_data['data']['note'] note_version = note_data['version'] blobs = DATA_PAT.findall(note_html) # Previously edited with zotcli if blobs: data = decode_blob(blobs[0]) if 'version' not in data: data['version'] = note_version note_html = DATA_PAT.sub("", note_html) # Not previously edited with zotcli or updated from the Zotero UI if not data or data['version'] < note_version: if data['version'] < note_version: self._logger.info("Note changed on server, reloading markup.") note_format = data['format'] if data else self.note_format data = { 'format': note_format, 'text': pypandoc.convert( note_html, note_format, format='html'), 'version': note_version} return data def _make_note_html(self, note_data): """ Converts the note's text to HTML and adds a dummy element that holds the original markup. :param note_data: dict with text, format and version of the note :returns: Note as HTML """ extra_data = DATA_TMPL.format(data=encode_blob(note_data)) html = pypandoc.convert(note_data['text'], 'html', format=note_data['format']) return html + extra_data def create_note(self, item_id, note_text): """ Create a new note for a given item. :param item_id: ID/key of the item to create the note for :param note_text: Text of the note """ note = self._zot.item_template('note') note_data = {'format': self.note_format, 'text': note_text, 'version': self._zot.last_modified_version(limit=1)+2} note['note'] = self._make_note_html(note_data) try: self._zot.create_items([note], item_id) except Exception as e: self._logger.error(e) with open("note_backup.txt", "w") as fp: fp.write(raw_data['text'].encode('utf-8')) self._logger.warn( "Could not upload note to Zotero. You can find the note " "markup in 'note_backup.txt' in the current directory") def save_note(self, note): """ Update an existing note. :param note: The updated note """ raw_data = note['data']['note'] raw_data['version'] += 1 note['data']['note'] = self._make_note_html(raw_data) try: self._zot.update_item(note) except Exception as e: self._logger.error(e) with open("note_backup.txt", "w") as fp: fp.write(raw_data['text'].encode('utf-8')) self._logger.warn( "Could not upload note to Zotero. You can find the note " "markup in 'note_backup.txt' in the current directory")
zotero-cli
/zotero-cli-0.3.0.tar.gz/zotero-cli-0.3.0/zotero_cli/backend.py
backend.py
import os import sqlite3 import time from contextlib import contextmanager from zotero_cli.common import Item SCHEMA = """ CREATE TABLE IF NOT EXISTS syncinfo ( id INTEGER PRIMARY KEY, last_sync INTEGER, version INTEGER ); CREATE TABLE IF NOT EXISTS items ( id INTEGER PRIMARY KEY, key TEXT UNIQUE, creator TEXT, title TEXT, date TEXT, citekey TEXT UNIQUE ); CREATE VIRTUAL TABLE items_idx USING fts4( key, creator, title, date, citekey, content="items"); CREATE VIRTUAL TABLE items_idx_terms USING fts4aux(items_idx); CREATE TRIGGER items_bu BEFORE UPDATE ON items BEGIN DELETE FROM items_idx WHERE docid=old.rowid; END; CREATE TRIGGER items_bd BEFORE DELETE ON items BEGIN DELETE FROM items_idx WHERE docid=old.rowid; END; CREATE TRIGGER items_au AFTER UPDATE ON items BEGIN INSERT INTO items_idx(docid, key, creator, title, date, citekey) VALUES(new.rowid, new.key, new.creator, new.title, new.date, new.citekey); END; CREATE TRIGGER items_ai AFTER INSERT ON items BEGIN INSERT INTO items_idx(docid, key, creator, title, date, citekey) VALUES(new.rowid, new.key, new.creator, new.title, new.date, new.citekey); END; """ SEARCH_QUERY = """ SELECT items.key, creator, title, date, citekey FROM items JOIN ( SELECT key FROM items_idx WHERE items_idx MATCH :query) AS idx ON idx.key = items.key LIMIT :limit; """ INSERT_ITEMS_QUERY = """ INSERT OR REPLACE INTO items (key, creator, title, date, citekey) VALUES (:key, :creator, :title, :date, :citekey); """ INSERT_META_QUERY = """ INSERT OR REPLACE INTO syncinfo (id, last_sync, version) VALUES (0, :last_sync, :version); """ class SearchIndex(object): def __init__(self, index_path): """ Local full-text search index using SQLite. :param index_path: Path to the index file """ init_db = not os.path.exists(index_path) self.db_path = index_path if init_db: with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() cursor.executescript(SCHEMA) @property @contextmanager def _db(self): with sqlite3.connect(self.db_path) as conn: cursor = conn.cursor() yield cursor @property def last_modified(self): """ Get time of last index modification. :returns: Epoch timestamp of last index modification :rtype: int """ with self._db as cursor: res = cursor.execute( "SELECT last_sync FROM syncinfo LIMIT 1").fetchone() if res: return res[0] else: return 0 @property def library_version(self): """ Get indexed library version. :returns: Version number of indexed library :rtype: int """ with self._db as cursor: res = cursor.execute( "SELECT version FROM syncinfo LIMIT 1").fetchone() if res: return res[0] else: return 0 def index(self, items, version): """ Update the index with new items and set a new version. :param items: Items to update the index with :type items: iterable of :py:class:`zotero_cli.common.Item` """ with self._db as cursor: cursor.executemany(INSERT_ITEMS_QUERY, items) cursor.execute(INSERT_META_QUERY, (int(time.time()), version)) def search(self, query, limit=None): """ Search the index for items matching the query. :param query: A sqlite FTS4 query :param limit: Maximum number of items to return :returns: Generator that yields matching items. """ with self._db as cursor: query = "'{}'".format(query) for itm in cursor.execute(SEARCH_QUERY, (query, limit or -1)): yield Item(*itm)
zotero-cli
/zotero-cli-0.3.0.tar.gz/zotero-cli-0.3.0/zotero_cli/index.py
index.py
import click import subprocess from zotero_sync.api import ApiClient import os from pathlib import Path from dotenv import load_dotenv, find_dotenv from shlex import quote from shutil import copy load_dotenv(find_dotenv(filename='.zoterosync')) @click.group() @click.option('--file_dir', default=os.getenv('ZOTFILE_DIR'), type=click.Path(exists=True)) @click.option('--api_key', default=os.getenv('API_KEY')) @click.option('--user_id', default=os.getenv('USER_ID')) @click.pass_context def cli(ctx, file_dir: click.Path, api_key: str, user_id: str): """A command line tool for cleaning up zotfile directory. Paramaters can be passed as arguments or in a .zoterosync file. Args: ctx: click context file_dir (click.Path): location of zotfile directory api_key (str): zotero api key user_id (str): zotero user id """ ctx.ensure_object(dict) dotfile_explanation = ( "This can be provided as an option or " "in a .zoterozync file as ZOTFILE_DIR") assert(file_dir is not None), ( "No zotfile path was given. " + dotfile_explanation) assert(api_key is not None), ( "No api key was given. " + dotfile_explanation) assert(user_id is not None), ( "No user id was given. " + dotfile_explanation) client = ApiClient(api_key, user_id) ctx.obj['CLIENT'] = client ctx.obj['FILE_DIR'] = Path(file_dir) click.echo(click.style(f"Using {file_dir} as zotfile dir", fg='green')) pass def get_paths(file_dir: Path, client: ApiClient) -> list: """Returns both computer and cloud paths Args: file_dir (Path): location of zotfile directory client (ApiClient) Returns: list: A list of uniqe paths on the computer. """ r = client.get_all_pages('items') cloud_paths = [path["data"]["path"] for path in r if "path" in path["data"]] computer_paths = [path for path in file_dir.glob( "**/*.pdf") if "trash" not in str(path)] computer_unique = [path for path in computer_paths if str( path.absolute()) not in cloud_paths] return computer_unique @cli.command() @click.pass_context def trash(ctx): """ Trash all files existing on system but not on cloud Args: ctx: click context """ computer_unique = get_paths(ctx.obj['FILE_DIR'], ctx.obj['CLIENT']) if click.confirm( f"Are you sure you want to trash {len(computer_unique)} files?"): for path in computer_unique: trash = ctx.obj['FILE_DIR'] / 'trash' trash.mkdir(parents=True, exist_ok=True) path.rename(trash / path.name) click.echo(click.style('Successfully deleted files!', fg='green')) @cli.command() @click.pass_context def upload(ctx): """ Adds all files from local folders to zotero. Args: ctx: click context """ computer_unique = get_paths(ctx.obj['FILE_DIR'], ctx.obj['CLIENT']) if click.confirm( f"Are you sure you upload {len(computer_unique)} files?"): with click.progressbar(computer_unique) as paths: for path in paths: ctx.obj['CLIENT'].create_item(path) click.echo(click.style('Successfully uploaded files!', fg='green')) @cli.command() @click.option('--file_dir', default=os.getenv('ZOTFILE_DIR'), type=click.Path(exists=True)) def optimize(file_dir: click.Path): """ Optimize file size of all pdfs """ click.echo(click.style('Optimizing files...', fg='blue')) process_pdfs(file_dir, ( 'gs -sDEVICE=pdfwrite' ' -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook' ' -dNOPAUSE -dQUIET -dBATCH -sOutputFile={output} {input}')) def process_pdfs(file_dir: click.Path, command: str): """ Run a script on all pdf files in subfolders Args: file_dir (click.Path): Path of pdf files command (str): A string containing command to be exected with {input} and {output} files. """ infile = 'infile.pdf' temp = "temppdf.pdf" count = 0 for path in Path(file_dir).rglob('*.pdf'): if path.name == "infile.pdf": continue count += 1 click.echo(click.style(f"Processed {count} so far\r", fg="blue"), nl=False) click.echo(click.style(f"Processing {path.name}", fg="red")) os.chdir(path.resolve().parent) copy(path.resolve(), infile) try: subprocess.check_call( [item.format(input=infile, output=temp) for item in command.split(' ')]) except subprocess.CalledProcessError: continue # if e.returncode not in [6, 8, 10]: (path.resolve().parent / temp).rename(path.resolve()) click.echo(click.style(f'Finished Processing {count} files!', fg='green')) @cli.command() @click.option('--file_dir', default=os.getenv('ZOTFILE_DIR'), type=click.Path(exists=True)) def ocr(file_dir: click.Path): """ Optimize file size of all pdfs """ click.echo(click.style('Running OCR on files...', fg='blue')) process_pdfs( file_dir, 'python -m ocrmypdf --tesseract-timeout 10 {input} {output}') if __name__ == "__main__": cli()
zotero-sync
/zotero_sync-0.1.6-py3-none-any.whl/zotero_sync/__main__.py
__main__.py
import zipfile import re from pyzotero import zotero def items_from_docx(file): document = zipfile.ZipFile(file) xmldoc = document.read('word/document.xml') r = re.compile(r"zotero.org/(?P<type>[a-z]+)/(?P<library_id>[0-9]+)/items/(?P<id>[A-Za-z0-9]+)") nu_items = [m.groupdict() for m in r.finditer(xmldoc.decode())] items = list({v['id']: v for v in nu_items}.values()) print("Found %s items." % len(items)) return items def zotero_collection_from_items(items, collection_name, **connection): zot = zotero.Zotero(**connection) collection = zot.create_collections([{'name': collection_name}])["success"]["0"] print("Adding to collection %s..." % collection_name) li = len(items) for i, it in enumerate(items): zot.addto_collection(collection, zot.item(it)) print("%i/%i" % (i+1, li)) return def main(): import argparse import os parser = argparse.ArgumentParser( description="Create a collection from items added to a Word .docx file" " via the Word Zotero Integration") parser.add_argument('file', help="The .docx file path.") parser.add_argument("collection", help="Name of new collection to create.") parser.add_argument("--api-key", help="A Zotero API key with write permissions. " "Create here (after login): https://www.zotero.org/settings/keys/new") parser.add_argument("--library-id", default="infer", help="The library ID if different to " "the one used to add the items (See top of table here 'Your userID " "for use in API calls': https://www.zotero.org/settings/keys).") parser.add_argument("--library-type", default="user") parser.add_argument("-n", "--dry-run", action="store_true", default=False, help="Only retrieve items from file and try opening Zotero API connection.") args = parser.parse_args() apikeyfile = os.path.expanduser("~/.zotero_api_key") if os.path.exists(apikeyfile): with open(apikeyfile) as f: args.api_key = f.read().strip() print('Using Zotero API key in %s' % apikeyfile) elif not args.api_key: print("You need to either parse --api-key or put one into %s" % apikeyfile) return items = items_from_docx(args.file) connection = {d: getattr(args, d) for d in ['library_id', 'library_type', 'api_key']} if len(items) > 0: if connection['library_id'] == "infer": lid = [i['library_id'] for i in items][0] connection['library_id'] = lid if args.dry_run: zot = zotero.Zotero(**connection) else: zotero_collection_from_items([i['id'] for i in items], args.collection, **connection) if __name__ == "__main__": main()
zotero-word-items-to-collection
/zotero_word_items_to_collection-0.1.tar.gz/zotero_word_items_to_collection-0.1/zotero_word_items_to_collection.py
zotero_word_items_to_collection.py
# Zotero to Markdown Generate Markdown files from Zotero annotations and notes. With new [Zotero PDF Reader](https://www.zotero.org/support/pdf_reader_preview), all highlights are saved in the Zotero database. The highlights are NOT saved in the PDF file unless you export the highlights in order to save them. If you annotate your files outside the new Zotero PDF reader, this library will not work with your PDF annotations as those are not retrievable from Zotero API. In that case, you may want to use zotfile + mdnotes to extract the annotations and convert them into markdown files. **_This library is for you if you annotate (highlight + note) using the Zotero's PDF reader (including the beta version in iOs)_** # Installation You can install the library by running ```shell pip install zotero2md ``` Note: If you do not have pip installed on your system, you can follow the instructions [here](https://pip.pypa.io/en/stable/installation/). # Usage ```shell python zotero2md/generate.py <zotero_key> <zotero_id> ``` For instance, assuming zotero_key=abcd and zotero_id=1234, you can simply run the following: ```shell python zotero2md/generate.py abcd 1234 ``` ## Custom Output Parameters You can change default parameters by passing the `--config_filepath` option with the path to a JSON file containing the desired configurations. For instance, ```shell python zotero2md/generate.py <zotero_key> <zotero_id> --config_filepath ./sample_params.json ``` | Parameter | type | default value | |-----------------------------------|-----------------|---------------| | `convertTagsToInternalLinks` | bool | true | | `doNotConvertFollowingTagsToLink` | List of strings | \[ \] | | `includeHighlightDate` | bool | true | | `hideHighlightDateInPreview` | bool | true | Any parameter in the JSON file will override the default setting. If a parameter is not provided, then the default value will be used. For example, if you don't want to show the highlight date in the output file, you can simply pass a JSON file with the following content: ```json { "hideHighlightDateInPreview": false } ``` # Features - Generate MD files for all annotations and notes saved in Zotero - The ability to convert Zotero tags to internal links (`[[ ]]`) used in many bidirectional MD editors. - You can even pass certain tags that you don't want to convert to internal links! (using `doNotConvertFollowingTagsToLink` parameter) ## Quick note Since I'm personally using Obsidian as my markdown editor, there are custom parameters to generate MD files that are consistent with Obsidian and I'm planning to add more option there. # Roadmap - [ ] Update existing annotations and notes - [ ] Option to add frontmatter section (particularly useful for Obsidian) - [ ] More flexibility in styling the output files # Request a new feature or report a bug Feel free to request a new feature or report a bug in GitHub issue [here](https://github.com/e-alizadeh/Zotero2MD/issues). ## 📫 How to reach me: <a href="https://ealizadeh.com" target="_blank"><img alt="Personal Website" src="https://img.shields.io/badge/Personal%20Website-%2312100E.svg?&style=for-the-badge&logoColor=white" /></a> <a href="https://www.linkedin.com/in/alizadehesmaeil/" target="_blank"><img alt="LinkedIn" src="https://img.shields.io/badge/linkedin-%230077B5.svg?&style=for-the-badge&logo=linkedin&logoColor=white" /></a> <a href="https://medium.com/@ealizadeh" target="_blank"><img alt="Medium" src="https://img.shields.io/badge/medium-%2312100E.svg?&style=for-the-badge&logo=medium&logoColor=white" /></a> <a href="https://twitter.com/intent/follow?screen_name=es_alizadeh&tw_p=followbutton" target="_blank"><img alt="Twitter" src="https://img.shields.io/badge/twitter-%231DA1F2.svg?&style=for-the-badge&logo=twitter&logoColor=white" /></a> <a href="https://www.buymeacoffee.com/ealizadeh" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
zotero2md
/zotero2md-0.1.0.tar.gz/zotero2md-0.1.0/README.md
README.md
# Zotero ➡️ Readwise `zotero2readwise` is a Python library that retrieves all [Zotero](https://www.zotero.org/) annotations† and notes. Then, It automatically uploads them to your [Readwise](https://readwise.io/)§. This is particularly useful for the new [Zotero PDF Reader](https://www.zotero.org/support/pdf_reader_preview) that stores all highlights in the Zotero database. The new Zotero, also available for [iOS app](https://www.zotero.org/iosbeta) (currently in beta). In the new Zotero, the annotations are NOT saved in the PDF file unless you export the highlights in order to save them. If you annotate your files outside the new Zotero PDF reader, this library may not work with your PDF annotations as those are not retrievable from Zotero API. **_This library is for you if you annotate (highlight + note) using the Zotero's PDF reader (including the Zotero iOS)_** 👉***Updating an existing Zotero annotation or note and re-running this library will update the corresponding Readwise highlight without creating a duplicate!*** † Annotations made in the new Zotero PDF reader and note editor. § Readwise is a _paid_ service/software that integrates your highlights from almost everywhere (Pocket, Instapaper, Twitter, Medium, Apple Books, and many more). It even has an amazing OCR for directly importing your highlights on a physical book/article into Readwise and allowing you to export all your highlights to Obsidian, Notion, Roam, Markdown, etc. Moreover, It has an automated [Spaced Repition](https://en.wikipedia.org/wiki/Spaced_repetition) and [Active Recall](https://en.wikipedia.org/wiki/Testing_effect). --- # Installation You can install the library by running ```shell pip install zotero2readwise ``` Note: If you do not have pip installed on your system, you can follow the instructions [here](https://pip.pypa.io/en/stable/installation/). # Usage Since we have to retrieve the notes from Zotero API and then upload them to the Readwise, the minimum requirements are: * **Readwise access token** [Required]: You can get your access token from https://readwise.io/access_token * **Zotero API key** [Required]: Create a new Zotero Key from [your Zotero settings](https://www.zotero.org/settings/keys/new) * **Zotero personal or group ID** [Required]: * Your **personal library ID** (aka **userID**) can be found [here](https://www.zotero.org/settings/key) next to `Your userID for use in API calls is XXXXXX`. * If you're using a **group library**, you can find the library ID by 1. Go to `https://www.zotero.org/groups/` 2. Click on the interested group. 3. You can find the library ID from the URL link that has format like *https://www.zotero.org/groups/<group_id>/group_name*. The number between `/groups/` and `/group_name` is the libarry ID. * **Zotero library type** [Optional]: *"user"* (default) if using personal library and *"group"* if using group library. Note that if you want to retrieve annotations and notes from a group, you should provide the group ID (`zotero_library_id=<group_id>`) and set the library type to group (`zotero_library_type="group"`). ## Approach 1 (running a python script) For this approach you can download `run.py` script (from [here](https://github.com/e-alizadeh/Zotero2Readwise/blob/master/zotero2readwise/run.py)). Run `python run.py -h` to get more information about all options. You can simply run the script as the following: ```shell python run.py <readwise_token> <zotero_key> <zotero_id> ``` ## Approach 2 (through python terminal) ```python from zotero2readwise.zt2rw import Zotero2Readwise zt_rw = Zotero2Readwise( readwise_token="your_readwise_access_token", # Visit https://readwise.io/access_token) zotero_key="your_zotero_key", # Visit https://www.zotero.org/settings/keys zotero_library_id="your_zotero_id", # Visit https://www.zotero.org/settings/keys zotero_library_type="user", # "user" (default) or "group" include_annotations=True, # Include Zotero annotations -> Default: True include_notes=False, # Include Zotero notes -> Default: False ) zt_rw.run() ``` Just to make sure that all files are created, you can run `save_failed_items_to_json()` from `readwise` attribute of the class object to save any highlight that failed to upload to Readwise. If a file or more failed to create, the filename (item title) and the corresponding Zotero item key will be saved to a txt file. ```python zt_rw.readwise.save_failed_items_to_json("failed_readwise_highlights.json") ``` --- # [Zotero2Readwise-Sync](https://github.com/e-alizadeh/Zotero2Readwise-Sync) ### 👉 Set up a scheduled automation once and forget about it! You can fork my repo [Zotero2Readwise-Sync](https://github.com/e-alizadeh/Zotero2Readwise-Sync) repository that contain the cronjob (time-based Job scheduler) using GitHub actions to automatically retrieve all your Zotero annotations/notes, and then push them to Readwise. You can use the forked repo without even changing a single line (of course if you're happy with the default settings!) # Request a new feature or report a bug Feel free to request a new feature or report a bug in GitHub issue [here](https://github.com/e-alizadeh/Zotero2Readwise/issues). # 📫 How to reach me: <a href="https://ealizadeh.com" target="_blank"><img alt="Personal Website" src="https://img.shields.io/badge/Personal%20Website-%2312100E.svg?&style=for-the-badge&logoColor=white" /></a> <a href="https://www.linkedin.com/in/alizadehesmaeil/" target="_blank"><img alt="LinkedIn" src="https://img.shields.io/badge/linkedin-%230077B5.svg?&style=for-the-badge&logo=linkedin&logoColor=white" /></a> <a href="https://medium.ealizadeh.com/" target="_blank"><img alt="Medium" src="https://img.shields.io/badge/medium-%2312100E.svg?&style=for-the-badge&logo=medium&logoColor=white" /></a> <a href="https://twitter.com/intent/follow?screen_name=es_alizadeh&tw_p=followbutton" target="_blank"><img alt="Twitter" src="https://img.shields.io/badge/twitter-%231DA1F2.svg?&style=for-the-badge&logo=twitter&logoColor=white" /></a> <a href="https://www.buymeacoffee.com/ealizadeh" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
zotero2readwise
/zotero2readwise-0.2.6.tar.gz/zotero2readwise-0.2.6/README.md
README.md
# zotero2wordcloud Create a word cloud based on a specified field of a collection of papers from Zotero. ## Installation instructions 1. Open a terminal window, and create a new virtual environment called `zotero2wordcloud` * Using [Conda](https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-environments.html): `conda create --name zotero2wordcloud` * Using python: `python3.7 -m venv my_env` 2. Activate the new environment * `conda activate zotero2wordcloud` or `source zotero2wordcloud/bin/activate` * Note always work in this virtual environment when working on this project, and deactivate the environment when you're done. 3. Navigate to the folder where you'd like to install this package * `cd <yourpath/GitHub/` * `mkdir zotero2wordcloud` * `cd zotero2wordcloud` 4. Install * Using pip: `pip install zotero2wordcloud` * Using Anaconda: `conda config --add channels conda-forge && conda install zotero2wordcloud` ## Usage instructions: Before starting, you'll need three pieces of information from Zotery: library ID, library type, and API key. * Your personal library ID is available [from Zotero](https://www.zotero.org/settings/keys). * If you're using a group library, the ID is on the group's page `https://www.zotero.org/groups/yourgroupname`. Hover over the `Group Settings` link. * You will likely need to [create a new API key](https://www.zotero.org/settings/keys/new) * If you're having trouble getting access to your Zotero library, check out example #1 in the `/examples` folder. Also see [Pyzotero documentation](https://pyzotero.readthedocs.io/en/latest/) for more information. ### Using terminal: * `from zotero2wordcloud.zoterto2wordcloud import zotero2wordcloud` ### Using Anaconda * `jupyter lab zotero2wordcloud.ipynb` ## Reporting issues If you encounter an error while using this package, please open an issue on its [Github issues page](https://github.com/rgulli/zotero2wordcloud/issues). ## License zotero2wordcloud is licensed under the [GNU General Public License v3.0](https://www.gnu.org/licenses/gpl-3.0.en.html).
zotero2wordcloud
/zotero2wordcloud-0.0.2.tar.gz/zotero2wordcloud-0.0.2/README.md
README.md
import os import rclone import sqlite3 import shutil import subprocess import json class ZoteroSync: """ A class used to sync zotero storage with a rclone remote """ def __init__(self, zotero_path, zoterosync_path): """ Parameters ---------- zotero_path: str Path to zotero zoterosync_path: str Path to zoterosync """ self.zoterosync_path = zoterosync_path self.config_file = self.zoterosync_path+'/zoterosync.conf.json' self.zotero_path = zotero_path self.rclone_config = None self.config = self.load_config() def rclone_configuration(self): result = None with subprocess.Popen(['rclone', 'config', 'file'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc: (out,err) = proc.communicate() result = out.split()[-1].decode('UTF-8') return result def load_config(self): if shutil.which('rclone') is None: print('Error: could not find rclone, please install it') return False else: self.rclone_config = self.rclone_configuration() if os.path.isfile(self.config_file) is False: print('Config file not found, creating one with default values: ') os.makedirs(self.zoterosync_path, exist_ok=True) data = {} data['rclone_cfg_path'] = self.rclone_config data['zoterosync_dirs'] = self.zoterosync_path+"/sync_dirs" data['zoterosync_path'] = self.zoterosync_path data['zotero_path'] = self.zotero_path data['default_remote_path'] = "zotero-storage" data['app_name'] = "zoterosync" with open(self.config_file, 'x') as f: json.dump(data,f, indent=1) f.close() print('configuration file created: '+self.config_file) with open(self.config_file) as json_file: return json.load(json_file) def save_config(self): with open(self.config_file, 'w') as file: json.dump(self.config, file) file.close() def mkdir(self, remote, remote_path): rrp = remote+':'+remote_path print('creating remote path '+rrp) with open(self.config['rclone_cfg_path']) as f: cfg = f.read() result = rclone.with_config(cfg).run_cmd(command='mkdir', extra_args=[rrp]) if result['code'] == 0: return True else: return False def setremote(self, group_name, remote): print('configuring "'+remote+'" as remote of "'+group_name+'"') if group_name not in self.config['groups']: self.config['groups'][group_name] = {} self.config['groups'][group_name]['remote'] = remote self.save_config() self.mkdir(remote, self.config['default_remote_path']) return True def remote_dir(self, group_name): return self.config['groups'][group_name]['remote']+':'+self.config['default_remote_path'] def local_storage(self): return self.config['zotero_path']+'/storage' def list_remotes(self): remotes = None with open(self.config['rclone_cfg_path']) as f: cfg = f.read() result = rclone.with_config(cfg).run_cmd('listremotes') remotes = result['out'].decode('UTF-8').replace(':','') return remotes def get_files_from_sqlite(self, group_name): filenames=[] conn = sqlite3.connect('file:'+self.config['zotero_path']+'/zotero.sqlite?mode=ro', uri=True) c = conn.cursor() sql=""" select l.lastSync, i.key, i.itemID, ia.path from groups as g, libraries as l, items as i, itemAttachments as ia where g.libraryID = l.libraryID AND i.itemID = ia.itemID AND l.libraryID = i.libraryID AND g.name='{group_name}' """ sqlf=sql.format(group_name=group_name) rows = c.execute(sqlf) for row in rows: hash_dir=row[1] if row[3] is not None: filename=row[3].replace('storage:','') file=self.config['zotero_path']+'/storage/'+hash_dir+'/'+filename filenames.append(file) return filenames def list_groups_from_sqlite(self): groups=[] conn = sqlite3.connect('file:'+self.config['zotero_path']+'/zotero.sqlite?mode=ro', uri=True) c = conn.cursor() sql=""" select name from groups """ rows = c.execute(sql) for row in rows: groups.append(row[0]) return groups def list_groups_with_remote(self): groups = dict() for group in self.config['groups'].keys(): groups[group] = self.config['groups'][group]['remote'] return groups # create links to files to be synced def link_files(self, group_name): filenames = self.get_files_from_sqlite(group_name) sync_dir = self.config['zoterosync_dirs']+'/'+group_name.replace(' ','_') for file in filenames: hash_dir = file.split('/')[-2] fname = file.split('/')[-1] dest_dir = sync_dir+'/'+hash_dir dest_link = dest_dir+'/'+fname try: if os.path.isfile(file): os.makedirs(dest_dir, exist_ok=True) if not os.path.isfile(dest_link): # links save disk space # hard links works on same device os.link(file,dest_link) # symbolic links are not working # os.symlink(file,dest_link) else: print('file not exists: '+file) except Exception as e: print(e) return False return sync_dir def copy_files(self, source, dest): result = None with open(self.config['rclone_cfg_path']) as f: cfg = f.read() result = rclone.with_config(cfg).copy(source,dest,flags=['-v']) return result
zoterosync
/zoterosync-0.1.1.tar.gz/zoterosync-0.1.1/zoterosync.py
zoterosync.py
# ZotNote Automatize and manage your reading notes with Zotero & Better Bibtex Plugin (BBT). **Note: ZotNote is still in early development and not production ready** [![PyPI version](https://img.shields.io/pypi/v/zotnote.svg)](https://pypi.python.org/pypi/zotnote/) ![ZotNote demo](assets/demo.gif) --- *Current features* - Simple installation via pipx/pip - Full command-line interface to create, edit, and remove notes - Graphical interface to select a Zotero item - Support for various reading note templates *Planned features* - Annotation of reading notes and individual quotes using tags/keywords - Retrieval of relevant quotes based on these tags and keywords - Analytics based on these tags and keywords - Enrich reading notes with more metadata from Zotero - Simple reports about progress of literature review - (*dreaming*) Automatically export collection of notes as an annotated bibliography. *Long-term vision* A literature review suite that connects to Zotero & BBT. Management of reading notes, reading/writing analytics, and basic qualitative text analysis (export reports as HTML via Jupyter notebooks). Export of reading notes in different formats (e.g., annotated bibliography). You can find a roadmap for ZotNote [here](https://github.com/Bubblbu/zotnote/issues/7). ## Installation ### Requirements - [Python](https://www.python.org/downloads/) 3.6 or higher - [Zotero Standalone](https://www.zotero.org/) with [Better Bibtex plugin](https://github.com/retorquere/zotero-better-bibtex) ### Recommended: Install via pipx The recommended way to install ZotNote is using [pipx](https://pipxproject.github.io/pipx/). Pipx cleanly install the package in an isolated environment (clean uninstalls!) and automagically exposes the CLI-endpoints globally on your system. pipx install zotnote ### Option 2: Install via pip However, you can also simply use pip. Please be aware of the Python version and environments you are using. pip install zotnote ### Option 3: Download from GitHub Download the latest release from Github and unzip. Put the folder containing the scripts into your `PATH`. Alternatively, run [sudo] python3 setup.py install or python3 setup.py install --user ### Option 4: Git clone (for developers) git clone [email protected]:Bubblbu/zotnote.git The project is being developed with [Poetry](https://python-poetry.org/) as a dependency manager. More instructions will follow soon! ## Getting started ``` Usage: zotnote [OPTIONS] COMMAND [ARGS]... CLI for ZotNote. Options: --help Show this message and exit. Commands: add Create a new note. config Configure Zotnote from the command line. edit Open a note in your editor of choice. remove Remove a note templates List all available templates for notes. ``` ### Configuration After installation you should be able to simply run `zotnote` and be prompted to a quick command-line configuration. ZotNote currently asks you for: - A name which is used in all reading notes. - An email address - A folder to store your reading notes ### Usage Some basic use cases: Create a note with the graphical interface (Zotero picker) zotnote add Create for specific citekey zotnote add [citekey] Edit a note (with graphical picker) zotnote edit or zotnote edit [citekey] You can explore each command in detail by adding `--help`. ## Authors Written by [Asura Enkhbayar](https://twitter.com/bubblbu_) while he was quarantined.
zotnote
/zotnote-0.3.4.tar.gz/zotnote-0.3.4/README.md
README.md
.. highlight:: shell ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/airallergy/zotutil/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ ZotUtil could always use more documentation, whether as part of the official ZotUtil docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/airallergy/zotutil/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `zotutil` for local development. 1. Fork the `zotutil` repo on GitHub. 2. Clone your fork locally:: $ git clone [email protected]:your_name_here/zotutil.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv zotutil $ cd zotutil/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 zotutil tests $ python setup.py test or pytest $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 3.5, 3.6, 3.7 and 3.8, and for PyPy. Check https://travis-ci.com/airallergy/zotutil/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ pytest tests.test_zotutil Deploying --------- A reminder for the maintainers on how to deploy. Make sure all your changes are committed (including an entry in HISTORY.rst). Then run:: $ bump2version patch # possible: major / minor / patch $ git push $ git push --tags Travis will then deploy to PyPI if tests pass.
zotutil
/zotutil-0.1.1.tar.gz/zotutil-0.1.1/CONTRIBUTING.rst
CONTRIBUTING.rst
.. highlight:: shell ============ Installation ============ Stable release -------------- To install ZotUtil, run this command in your terminal: .. code-block:: console $ pip install zotutil This is the preferred method to install ZotUtil, as it will always install the most recent stable release. If you don't have `pip`_ installed, this `Python installation guide`_ can guide you through the process. .. _pip: https://pip.pypa.io .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ From sources ------------ The sources for ZotUtil can be downloaded from the `Github repo`_. You can either clone the public repository: .. code-block:: console $ git clone git://github.com/airallergy/zotutil Or download the `tarball`_: .. code-block:: console $ curl -OJL https://github.com/airallergy/zotutil/tarball/master Once you have a copy of the source, you can install it with: .. code-block:: console $ python setup.py install .. _Github repo: https://github.com/airallergy/zotutil .. _tarball: https://github.com/airallergy/zotutil/tarball/master
zotutil
/zotutil-0.1.1.tar.gz/zotutil-0.1.1/docs/installation.rst
installation.rst
[![Build Status](https://travis-ci.org/JohnVinyard/zounds.svg?branch=master)](https://travis-ci.org/JohnVinyard/zounds) [![Coverage Status](https://coveralls.io/repos/github/JohnVinyard/zounds/badge.svg?branch=master)](https://coveralls.io/github/JohnVinyard/zounds?branch=master) ![Python 3](https://img.shields.io/pypi/pyversions/zounds.svg) [![PyPI](https://img.shields.io/pypi/v/zounds.svg)](https://pypi.python.org/pypi/zounds) [![Docs](https://img.shields.io/badge/docs-latest-brightgreen.svg?style=flat&maxAge=86400)](http://zounds.readthedocs.io/en/latest/?badge=latest) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) # Motivation Zounds is a python library for working with sound. Its primary goals are to: - layer semantically meaningful audio manipulations on top of numpy arrays - [help to organize the definition and persistence of audio processing pipelines and machine learning experiments with sound](https://github.com/JohnVinyard/zounds/tree/master/zounds/learn) Audio processing graphs and machine learning pipelines are defined using [featureflow](https://github.com/JohnVinyard/featureflow). # A Quick Example ```python import zounds Resampled = zounds.resampled(resample_to=zounds.SR11025()) @zounds.simple_in_memory_settings class Sound(Resampled): """ A simple pipeline that computes a perceptually weighted modified discrete cosine transform, and "persists" feature data in an in-memory store. """ windowed = zounds.ArrayWithUnitsFeature( zounds.SlidingWindow, needs=Resampled.resampled, wscheme=zounds.HalfLapped(), wfunc=zounds.OggVorbisWindowingFunc(), store=True) mdct = zounds.ArrayWithUnitsFeature( zounds.MDCT, needs=windowed) weighted = zounds.ArrayWithUnitsFeature( lambda x: x * zounds.AWeighting(), needs=mdct) if __name__ == '__main__': # produce some audio to test our pipeline, and encode it as FLAC synth = zounds.SineSynthesizer(zounds.SR44100()) samples = synth.synthesize(zounds.Seconds(5), [220., 440., 880.]) encoded = samples.encode(fmt='FLAC') # process the audio, and fetch features from our in-memory store _id = Sound.process(meta=encoded) sound = Sound(_id) # grab all the frequency information, for a subset of the duration start = zounds.Milliseconds(500) end = start + zounds.Seconds(2) snippet = sound.weighted[start: end, :] # grab a subset of frequency information for the duration of the sound freq_band = slice(zounds.Hertz(400), zounds.Hertz(500)) a440 = sound.mdct[:, freq_band] # produce a new set of coefficients where only the 440hz sine wave is # present filtered = sound.mdct.zeros_like() filtered[:, freq_band] = a440 # apply a geometric scale, which more closely matches human pitch # perception, and apply it to the linear frequency axis scale = zounds.GeometricScale(50, 4000, 0.05, 100) log_coeffs = scale.apply(sound.mdct, zounds.HanningWindowingFunc()) # reconstruct audio from the MDCT coefficients mdct_synth = zounds.MDCTSynthesizer() reconstructed = mdct_synth.synthesize(sound.mdct) filtered_reconstruction = mdct_synth.synthesize(filtered) # start an in-browser REPL that will allow you to listen to and visualize # the variables defined above (and any new ones you create in the session) app = zounds.ZoundsApp( model=Sound, audio_feature=Sound.ogg, visualization_feature=Sound.weighted, globals=globals(), locals=locals()) app.start(9999) ``` Find more inspiration in the [examples folder](https://github.com/JohnVinyard/zounds/tree/master/examples), or on the [blog](http://johnvinyard.github.io/). # Installation ## Libsndfile Issues Installation currently requires you to build lbiflac and libsndfile from source, because of [an outstanding issue](https://github.com/bastibe/PySoundFile/issues/130) that will be corrected when the apt package is updated to `libsndfile 1.0.26`. Download and run [this script](https://raw.githubusercontent.com/JohnVinyard/zounds/master/setup.sh) to handle this step. ## Numpy and Scipy The [Anaconda](https://www.continuum.io/downloads) python distribution is highly recommended. ## Zounds Finally, just: ```bash pip install zounds ```
zounds
/zounds-1.57.0.tar.gz/zounds-1.57.0/README.md
README.md
# Zouqi: A Python CLI Starter Purely Built on argparse. Zouqi (『走起』 in Chinese) is a CLI starter similar to [python-fire]. It is purely built on argparse. ## Why not [python-fire]? - Fire cannot be used to share options between commands easily. - Fire treat all member functions as its command, which is not desirable in many situations. ## Installation ```plain pip install zouqi ``` ## Example ### Code ```python import zouqi from zouqi.parsing import ignored def prettify(something): return f"pretty {something}" class Runner: def __init__(self, who: str): self.who = who # (This is not a command.) def show(self, action, something): print(self.who, action, something) # Decorate the command with the zouqi.command decorator. @zouqi.command def drive(self, something): # Equivalent to: parser.add_argument('something'). # the parsed args will be stored in self.drive.args instead of self.args self.show("drives a", something) @zouqi.command def wash(self, something, hidden_option: ignored = ""): # hidden option will be ignored during parsing but still passable by another function self.show("washes a", something + hidden_option) @zouqi.command def drive_and_wash(self, something: prettify = "car"): # Equivalent to: parser.add_argument('--something', type=prettify, default='car'). # Type hint is used as argument parser (a little bit abuse of type hint here). self.drive(something) self.wash(something, ", good.") class FancyRunner(Runner): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def drive(self, title, *args, **kwargs): # other args are automatically inherited from its parent class print(self.who, "is a", title) super().drive(*args, **kwargs) class SuperFancyRunner(FancyRunner): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @zouqi.command(inherit=True) def drive(self, *args, title: str = "super fancy driver", **kwargs): super().drive(title, *args, **kwargs) if __name__ == "__main__": print("======= Calling in the script ========") SuperFancyRunner("John").drive_and_wash("car") print("======= Calling from the CLI ========") zouqi.start(SuperFancyRunner) ``` ### Runs ```plain $ python3 example.py ======= Calling in the script ======== John is a super fancy driver John drives a car John washes a car, good. ======= Calling from the CLI ======== usage: example.py [-h] [--print-args] {drive,drive_and_wash,wash} who example.py: error: the following arguments are required: command, who ``` ```plain $ python3 example.py drive John car ======= Calling in the script ======== John is a super fancy driver John drives a car John washes a car, good. ======= Calling from the CLI ======== John is a super fancy driver John drives a car ``` ```plain $ python3 example.py drive_and_wash John --something truck --print-args ======= Calling in the script ======== John is a super fancy driver John drives a car John washes a car, good. ======= Calling from the CLI ======== ┌─────────────────────────┐ │ Arguments │ ├─────────────────────────┤ │command: drive_and_wash │ │print_args: True │ │something: pretty truck │ │who: John │ └─────────────────────────┘ John is a super fancy driver John drives a pretty truck John washes a pretty truck, good. ``` [python-fire]: https://github.com/google/python-fire
zouqi
/zouqi-1.0.7.tar.gz/zouqi-1.0.7/README.md
README.md
import sys DEFAULT_VERSION = "0.6c11" DEFAULT_URL = "http://pypi.python.org/packages/%s/s/setuptools/" % sys.version[:3] md5_data = { 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca', 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb', 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b', 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a', 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618', 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac', 'setuptools-0.6b4-py2.3.egg': '62045a24ed4e1ebc77fe039aa4e6f7e5', 'setuptools-0.6b4-py2.4.egg': '4cb2a185d228dacffb2d17f103b3b1c4', 'setuptools-0.6c1-py2.3.egg': 'b3f2b5539d65cb7f74ad79127f1a908c', 'setuptools-0.6c1-py2.4.egg': 'b45adeda0667d2d2ffe14009364f2a4b', 'setuptools-0.6c10-py2.3.egg': 'ce1e2ab5d3a0256456d9fc13800a7090', 'setuptools-0.6c10-py2.4.egg': '57d6d9d6e9b80772c59a53a8433a5dd4', 'setuptools-0.6c10-py2.5.egg': 'de46ac8b1c97c895572e5e8596aeb8c7', 'setuptools-0.6c10-py2.6.egg': '58ea40aef06da02ce641495523a0b7f5', 'setuptools-0.6c11-py2.3.egg': '2baeac6e13d414a9d28e7ba5b5a596de', 'setuptools-0.6c11-py2.4.egg': 'bd639f9b0eac4c42497034dec2ec0c2b', 'setuptools-0.6c11-py2.5.egg': '64c94f3bf7a72a13ec83e0b24f2749b2', 'setuptools-0.6c11-py2.6.egg': 'bfa92100bd772d5a213eedd356d64086', 'setuptools-0.6c2-py2.3.egg': 'f0064bf6aa2b7d0f3ba0b43f20817c27', 'setuptools-0.6c2-py2.4.egg': '616192eec35f47e8ea16cd6a122b7277', 'setuptools-0.6c3-py2.3.egg': 'f181fa125dfe85a259c9cd6f1d7b78fa', 'setuptools-0.6c3-py2.4.egg': 'e0ed74682c998bfb73bf803a50e7b71e', 'setuptools-0.6c3-py2.5.egg': 'abef16fdd61955514841c7c6bd98965e', 'setuptools-0.6c4-py2.3.egg': 'b0b9131acab32022bfac7f44c5d7971f', 'setuptools-0.6c4-py2.4.egg': '2a1f9656d4fbf3c97bf946c0a124e6e2', 'setuptools-0.6c4-py2.5.egg': '8f5a052e32cdb9c72bcf4b5526f28afc', 'setuptools-0.6c5-py2.3.egg': 'ee9fd80965da04f2f3e6b3576e9d8167', 'setuptools-0.6c5-py2.4.egg': 'afe2adf1c01701ee841761f5bcd8aa64', 'setuptools-0.6c5-py2.5.egg': 'a8d3f61494ccaa8714dfed37bccd3d5d', 'setuptools-0.6c6-py2.3.egg': '35686b78116a668847237b69d549ec20', 'setuptools-0.6c6-py2.4.egg': '3c56af57be3225019260a644430065ab', 'setuptools-0.6c6-py2.5.egg': 'b2f8a7520709a5b34f80946de5f02f53', 'setuptools-0.6c7-py2.3.egg': '209fdf9adc3a615e5115b725658e13e2', 'setuptools-0.6c7-py2.4.egg': '5a8f954807d46a0fb67cf1f26c55a82e', 'setuptools-0.6c7-py2.5.egg': '45d2ad28f9750e7434111fde831e8372', 'setuptools-0.6c8-py2.3.egg': '50759d29b349db8cfd807ba8303f1902', 'setuptools-0.6c8-py2.4.egg': 'cba38d74f7d483c06e9daa6070cce6de', 'setuptools-0.6c8-py2.5.egg': '1721747ee329dc150590a58b3e1ac95b', 'setuptools-0.6c9-py2.3.egg': 'a83c4020414807b496e4cfbe08507c03', 'setuptools-0.6c9-py2.4.egg': '260a2be2e5388d66bdaee06abec6342a', 'setuptools-0.6c9-py2.5.egg': 'fe67c3e5a17b12c0e7c541b7ea43a8e6', 'setuptools-0.6c9-py2.6.egg': 'ca37b1ff16fa2ede6e19383e7b59245a', } import sys, os try: from hashlib import md5 except ImportError: from md5 import md5 def _validate_md5(egg_name, data): if egg_name in md5_data: digest = md5(data).hexdigest() if digest != md5_data[egg_name]: print >>sys.stderr, ( "md5 validation of %s failed! (Possible download problem?)" % egg_name ) sys.exit(2) return data def use_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, download_delay=15 ): """Automatically find/download setuptools and make it available on sys.path `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where setuptools will be downloaded, if it is not already available. If `download_delay` is specified, it should be the number of seconds that will be paused before initiating a download, should one be required. If an older version of setuptools is installed, this routine will print a message to ``sys.stderr`` and raise SystemExit in an attempt to abort the calling script. """ was_imported = 'pkg_resources' in sys.modules or 'setuptools' in sys.modules def do_download(): egg = download_setuptools(version, download_base, to_dir, download_delay) sys.path.insert(0, egg) import setuptools; setuptools.bootstrap_install_from = egg try: import pkg_resources except ImportError: return do_download() try: pkg_resources.require("setuptools>="+version); return except pkg_resources.VersionConflict, e: if was_imported: print >>sys.stderr, ( "The required version of setuptools (>=%s) is not available, and\n" "can't be installed while this script is running. Please install\n" " a more recent version first, using 'easy_install -U setuptools'." "\n\n(Currently using %r)" ) % (version, e.args[0]) sys.exit(2) else: del pkg_resources, sys.modules['pkg_resources'] # reload ok return do_download() except pkg_resources.DistributionNotFound: return do_download() def download_setuptools( version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir, delay = 15 ): """Download setuptools from a specified location and return its filename `version` should be a valid setuptools version number that is available as an egg for download under the `download_base` URL (which should end with a '/'). `to_dir` is the directory where the egg will be downloaded. `delay` is the number of seconds to pause before an actual download attempt. """ import urllib2, shutil egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3]) url = download_base + egg_name saveto = os.path.join(to_dir, egg_name) src = dst = None if not os.path.exists(saveto): # Avoid repeated downloads try: from distutils import log if delay: log.warn(""" --------------------------------------------------------------------------- This script requires setuptools version %s to run (even to display help). I will attempt to download it for you (from %s), but you may need to enable firewall access for this script first. I will start the download in %d seconds. (Note: if this machine does not have network access, please obtain the file %s and place it in this directory before rerunning this script.) ---------------------------------------------------------------------------""", version, download_base, delay, url ); from time import sleep; sleep(delay) log.warn("Downloading %s", url) src = urllib2.urlopen(url) # Read/write all in one block, so we don't create a corrupt file # if the download is interrupted. data = _validate_md5(egg_name, src.read()) dst = open(saveto,"wb"); dst.write(data) finally: if src: src.close() if dst: dst.close() return os.path.realpath(saveto) def main(argv, version=DEFAULT_VERSION): """Install or upgrade setuptools and EasyInstall""" try: import setuptools except ImportError: egg = None try: egg = download_setuptools(version, delay=0) sys.path.insert(0,egg) from setuptools.command.easy_install import main return main(list(argv)+[egg]) # we're done here finally: if egg and os.path.exists(egg): os.unlink(egg) else: if setuptools.__version__ == '0.0.1': print >>sys.stderr, ( "You have an obsolete version of setuptools installed. Please\n" "remove it from your system entirely before rerunning this script." ) sys.exit(2) req = "setuptools>="+version import pkg_resources try: pkg_resources.require(req) except pkg_resources.VersionConflict: try: from setuptools.command.easy_install import main except ImportError: from easy_install import main main(list(argv)+[download_setuptools(delay=0)]) sys.exit(0) # try to force an exit else: if argv: from setuptools.command.easy_install import main main(argv) else: print "Setuptools version",version,"or greater has been installed." print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)' def update_md5(filenames): """Update our built-in md5 registry""" import re for name in filenames: base = os.path.basename(name) f = open(name,'rb') md5_data[base] = md5(f.read()).hexdigest() f.close() data = [" %r: %r,\n" % it for it in md5_data.items()] data.sort() repl = "".join(data) import inspect srcfile = inspect.getsourcefile(sys.modules[__name__]) f = open(srcfile, 'rb'); src = f.read(); f.close() match = re.search("\nmd5_data = {\n([^}]+)}", src) if not match: print >>sys.stderr, "Internal error!" sys.exit(2) src = src[:match.start(1)] + repl + src[match.end(1):] f = open(srcfile,'w') f.write(src) f.close() if __name__=='__main__': if len(sys.argv)>2 and sys.argv[1]=='--md5update': update_md5(sys.argv[2:]) else: main(sys.argv[1:])
zourite
/zourite-0.4.0.tar.gz/zourite-0.4.0/ez_setup.py
ez_setup.py
from .exceptions import UnexpectedStatus from .exceptions import RequestFailed from .exceptions import InvalidRequestMethod import requests import urllib3 class RequestHandler: """ Class used to handle HTTP/HTTPS requests. Attributes ---------- session_arguments: dict Zowe SDK session arguments valid_methods: list List of supported request methods """ def __init__(self, session_arguments): """ Construct a RequestHandler object. Parameters ---------- session_arguments The Zowe SDK session arguments """ self.session_arguments = session_arguments self.valid_methods = ["GET", "POST", "PUT", "DELETE"] self.handle_ssl_warnings() def handle_ssl_warnings(self): """Turn off warnings if the SSL verification argument if off.""" if not self.session_arguments['verify']: urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) def perform_request(self, method, request_arguments, expected_code=[200]): """Execute an HTTP/HTTPS requests from given arguments and return validated response (JSON). Parameters ---------- method: str The request method that should be used request_arguments: dict The dictionary containing the required arguments for the execution of the request expected_code: int The list containing the acceptable response codes (default is [200]) Returns ------- normalized_response: json normalized request response in json (dictionary) """ self.method = method self.request_arguments = request_arguments self.expected_code = expected_code self.validate_method() self.send_request() self.validate_response() return self.normalize_response() def validate_method(self): """Check if the input request method for the request is supported. Raises ------ InvalidRequestMethod If the input request method is not supported """ if self.method not in self.valid_methods: raise InvalidRequestMethod(self.method) def send_request(self): """Build a custom session object, prepare it with a custom request and send it.""" session = requests.Session() request_object = requests.Request(method=self.method, **self.request_arguments) prepared = session.prepare_request(request_object) self.response = session.send(prepared, **self.session_arguments) def validate_response(self): """Validate if request response is acceptable based on expected code list. Raises ------ UnexpectedStatus If the response status code is not in the expected code list RequestFailed If the HTTP/HTTPS request fails """ # Automatically checks if status code is between 200 and 400 if self.response: if self.response.status_code not in self.expected_code: raise UnexpectedStatus(self.expected_code, self.response.status_code, self.response.text) else: output_str = str(self.response.request.url) output_str += "\n" + str(self.response.request.headers) output_str += "\n" + str(self.response.request.body) output_str += "\n" + str(self.response.text) raise RequestFailed(self.response.status_code, output_str) def normalize_response(self): """Normalize the response object to a JSON format. Returns ------- json A normalized JSON for the request response """ try: return self.response.json() except: return {"response": self.response.text}
zowe-core-for-zowe-sdk
/zowe_core_for_zowe_sdk-0.5.0.tar.gz/zowe_core_for_zowe_sdk-0.5.0/zowe/core_for_zowe_sdk/request_handler.py
request_handler.py
import base64 import os.path import sys import yaml from .constants import constants from .exceptions import SecureProfileLoadFailed from .connection import ApiConnection HAS_KEYRING = True try: import keyring except ImportError: HAS_KEYRING = False class ZosmfProfile: """ Class used to represent a Zowe z/OSMF profile. Description ----------- This class is only used when there is already a Zowe z/OSMF profile created and the user opted to use the profile instead of passing the credentials directly in the object constructor. Attributes ---------- profile_name: str Zowe z/OSMF profile name """ def __init__(self, profile_name): """ Construct a ZosmfProfile object. Parameters ---------- profile_name The name of the Zowe z/OSMF profile """ self.profile_name = profile_name @property def profiles_dir(self): """Return the os path for the Zowe z/OSMF profiles.""" home_dir = os.path.expanduser("~") return os.path.join(home_dir, ".zowe", "profiles", "zosmf") def load(self): """Load z/OSMF connection details from a z/OSMF profile. Returns ------- zosmf_connection z/OSMF connection object """ profile_file = os.path.join( self.profiles_dir, "{}.yaml".format(self.profile_name) ) with open(profile_file, "r") as fileobj: profile_yaml = yaml.safe_load(fileobj) zosmf_host = profile_yaml["host"] if "port" in profile_yaml: zosmf_host += ":{}".format(profile_yaml["port"]) zosmf_user = profile_yaml["user"] zosmf_password = profile_yaml["password"] if zosmf_user.startswith( constants["SecureValuePrefix"] ) and zosmf_password.startswith(constants["SecureValuePrefix"]): zosmf_user, zosmf_password = self.__load_secure_credentials() zosmf_ssl_verification = True if "rejectUnauthorized" in profile_yaml: zosmf_ssl_verification = profile_yaml["rejectUnauthorized"] return ApiConnection( zosmf_host, zosmf_user, zosmf_password, zosmf_ssl_verification ) def __get_secure_value(self, name): service_name = constants["ZoweCredentialKey"] account_name = "zosmf_{}_{}".format(self.profile_name, name) if sys.platform == "win32": service_name += "/" + account_name secret_value = keyring.get_password(service_name, account_name) if sys.platform == "win32": secret_value = secret_value.encode("utf-16") secret_value = base64.b64decode(secret_value).decode().strip('"') return secret_value def __load_secure_credentials(self): """Load secure credentials for a z/OSMF profile.""" if not HAS_KEYRING: raise SecureProfileLoadFailed( self.profile_name, "Keyring module not installed" ) try: zosmf_user = self.__get_secure_value("user") zosmf_password = self.__get_secure_value("password") except Exception as e: raise SecureProfileLoadFailed(self.profile_name, e) else: return (zosmf_user, zosmf_password) if HAS_KEYRING and sys.platform.startswith("linux"): from contextlib import closing from keyring.backends import SecretService class KeyringBackend(SecretService.Keyring): """ Class used to handle secured profiles. Methods ------- get_password(service, username) Get the decoded password """ def __get_password(self, service, username, collection): items = collection.search_items({"account": username, "service": service}) for item in items: if hasattr(item, "unlock"): if item.is_locked() and item.unlock()[0]: raise keyring.errors.InitError("failed to unlock item") return item.get_secret().decode("utf-8") def get_password(self, service, username): """Get password of the username for the service.""" collection = self.get_preferred_collection() if hasattr(collection, "connection"): with closing(collection.connection): return self.__get_password(service, username, collection) else: return self.__get_password(service, username, collection) keyring.set_keyring(KeyringBackend())
zowe-core-for-zowe-sdk
/zowe_core_for_zowe_sdk-0.5.0.tar.gz/zowe_core_for_zowe_sdk-0.5.0/zowe/core_for_zowe_sdk/zosmf_profile.py
zosmf_profile.py
class InvalidRequestMethod(Exception): """Class used to represent an invalid request method exception.""" def __init__(self, input_method): """ Parameters ---------- input_method: str The invalid HTTP method used """ super().__init__("Invalid HTTP method input {}".format(input_method)) class UnexpectedStatus(Exception): """Class used to represent an unexpected request response status exception.""" def __init__(self, expected, received, request_output): """ Parameters ---------- expected The expected status code received The received status code request_output The output from the request """ super().__init__( "The status code from z/OSMF was {} it was expected {}. \n {}".format( received, expected, request_output ) ) class RequestFailed(Exception): """Class used to represent a request failure exception.""" def __init__(self, status_code, request_output): """ Parameters ---------- status_code The status code from the failed request request_output The output from the request """ super().__init__( "HTTP Request has failed with status code {}. \n {}".format( status_code, request_output ) ) class FileNotFound(Exception): """Class used to represent a file not found exception.""" def __init__(self, input_path): """ Parameters ---------- input_path The invalid input path """ super().__init__("The path {} provided is not a file.".format(input_path)) class MissingConnectionArgs(Exception): """Class used to represent a missing connection argument exception.""" def __init__(self): super().__init__( "You must provide host, user, and password for a z/OSMF " "connection, or the name of a z/OSMF profile that exists on your " "system." ) class SecureProfileLoadFailed(Exception): """Class used to represent a secure profile load failure exception.""" def __init__(self, profile_name, error_msg): """ Parameters ---------- profile_name The name of the profile it failed to load error_msg The error message received while trying to load the profile """ super().__init__( "Failed to load secure profile {}: {}".format(profile_name, error_msg) )
zowe-core-for-zowe-sdk
/zowe_core_for_zowe_sdk-0.5.0.tar.gz/zowe_core_for_zowe_sdk-0.5.0/zowe/core_for_zowe_sdk/exceptions.py
exceptions.py
from zowe.core_for_zowe_sdk import SdkApi import os class Jobs(SdkApi): """ Class used to represent the base z/OSMF Jobs API. Attributes ---------- connection Connection object """ def __init__(self, connection): """ Construct a Jobs object. Parameters ---------- connection The connection object """ super().__init__(connection, "/zosmf/restjobs/jobs/") def get_job_status(self, jobname, jobid): """Retrieve the status of a given job on JES. Parameters ---------- jobname: str The name of the job jobid: str The job id on JES Returns ------- response_json A JSON object containing the status of the job on JES """ custom_args = self.create_custom_request_arguments() job_url = "{}/{}".format(jobname, jobid) request_url = "{}{}".format(self.request_endpoint, job_url) custom_args["url"] = request_url response_json = self.request_handler.perform_request("GET", custom_args) return response_json def list_jobs(self, owner=None, prefix="*", max_jobs=1000, user_correlator=None): """Retrieve list of jobs on JES based on the provided arguments. Parameters ---------- owner: str, optional The job owner (default is None) prefix: str, optional The job name prefix (default is `*`) max_jobs: int, optional The maximum number of jobs in the output (default is 1000) user_correlator: str, optional The z/OSMF user correlator attribute (default is None) Returns ------- json A JSON containing a list of jobs on JES queue based on the given parameters """ custom_args = self.create_custom_request_arguments() params = {"prefix": prefix, "max-jobs": max_jobs} params["owner"] = owner if owner else self.connection.zosmf_user if user_correlator: params["user-correlator"] = user_correlator custom_args["params"] = params response_json = self.request_handler.perform_request("GET", custom_args) return response_json def submit_from_mainframe(self, jcl_path): """Submit a job from a given dataset. Parameters ---------- jcl_path: str The dataset where the JCL is located Returns ------- json A JSON containing the result of the request execution """ custom_args = self.create_custom_request_arguments() request_body = '{"file": "//\'%s\'"}' % (jcl_path) custom_args["data"] = request_body response_json = self.request_handler.perform_request( "PUT", custom_args, expected_code=[201] ) return response_json def submit_from_local_file(self, jcl_path): """Submit a job from local file. This function will internally call the `submit_plaintext` function in order to submit the contents of the given input file Parameters ---------- jcl_path: str Path to the local file where the JCL is located Raises ------ FileNotFoundError If the local file provided is not found Returns ------- json A JSON containing the result of the request execution """ if os.path.isfile(jcl_path): jcl_file = open(jcl_path, "r") file_content = jcl_file.read() jcl_file.close() return self.submit_plaintext(file_content) else: raise FileNotFoundError("Provided argument is not a file path {}".format(jcl_path)) def submit_plaintext(self, jcl): """Submit a job from plain text input. Parameters ---------- jcl: str The plain text JCL to be submitted Returns ------- json A JSON containing the result of the request execution """ custom_args = self.create_custom_request_arguments() custom_args["data"] = str(jcl) custom_args['headers']['Content-Type'] = 'text/plain' response_json = self.request_handler.perform_request( "PUT", custom_args, expected_code=[201] ) return response_json
zowe-zos-jobs-for-zowe-sdk
/zowe_zos_jobs_for_zowe_sdk-0.5.0-py3-none-any.whl/zowe/zos_jobs_for_zowe_sdk/jobs.py
jobs.py
from zowe.core_for_zowe_sdk import SdkApi class Tso(SdkApi): """ Class used to represent the base z/OSMF TSO API. ... Attributes ---------- connection Connection object session_not_found Constant for the session not found tso message id """ def __init__(self, connection): """ Construct a Tso object. Parameters ---------- connection The connection object """ super().__init__(connection, "/zosmf/tsoApp/tso") self.session_not_found = self.constants["TsoSessionNotFound"] def issue_command(self, command): """Issues a TSO command. This function will first initiate a TSO session, retrieve the session key, send the command and finally terminate the session Parameters ---------- command: str TSO command to be executed Returns ------- list A list containing the output from the TSO command """ session_key = self.start_tso_session() command_output = self.send_tso_message(session_key, command) tso_messages = self.retrieve_tso_messages(command_output) self.end_tso_session(session_key) return tso_messages def start_tso_session( self, proc="IZUFPROC", chset="697", cpage="1047", rows="204", cols="160", rsize="4096", acct="DEFAULT", ): """Start a TSO session. Parameters ---------- proc: str, optional Proc parameter for the TSO session (default is "IZUFPROC") chset: str, optional Chset parameter for the TSO session (default is "697") cpage: str, optional Cpage parameter for the TSO session (default is "1047") rows: str, optional Rows parameter for the TSO session (default is "204") cols: str, optional Cols parameter for the TSO session (default is "160") rsize: str, optional Rsize parameter for the TSO session (default is "4096") acctL str, optional Acct parameter for the TSO session (default is "DEFAULT") Returns ------- str The 'servletKey' key for the created session (if successful) """ custom_args = self.create_custom_request_arguments() custom_args["params"] = { "proc": proc, "chset": chset, "cpage": cpage, "rows": rows, "cols": cols, "rsize": rsize, "acct": acct, } response_json = self.request_handler.perform_request("POST", custom_args) return response_json["servletKey"] def send_tso_message(self, session_key, message): """Send a command to an existing TSO session. Parameters ---------- session_key: str The session key of an existing TSO session message: str The message/command to be sent to the TSO session Returns ------- list A non-normalized list from TSO containing the result from the command """ custom_args = self.create_custom_request_arguments() custom_args["url"] = "{}/{}".format(self.request_endpoint, str(session_key)) custom_args["data"] = '{"TSO RESPONSE":{"VERSION":"0100","DATA":"%s"}}' % ( str(message) ) response_json = self.request_handler.perform_request("PUT", custom_args) return response_json["tsoData"] def ping_tso_session(self, session_key): """Ping an existing TSO session and returns if it is still available. Parameters ---------- session_key: str The session key of an existing TSO session Returns ------- str A string informing if the ping was successful or not. Where the options are: 'Ping successful' or 'Ping failed' """ custom_args = self.create_custom_request_arguments() custom_args["url"] = "{}/{}/{}".format( self.request_endpoint, "ping", str(session_key) ) response_json = self.request_handler.perform_request("PUT", custom_args) message_id_list = self.parse_message_ids(response_json) return ( "Ping successful" if self.session_not_found not in message_id_list else "Ping failed" ) def end_tso_session(self, session_key): """Terminates an existing TSO session. Parameters ---------- session_key: str The session key of an existing TSO session Returns ------- str A string informing if the session was terminated successfully or not """ custom_args = self.create_custom_request_arguments() custom_args["url"] = "{}/{}".format(self.request_endpoint, session_key) response_json = self.request_handler.perform_request("DELETE", custom_args) message_id_list = self.parse_message_ids(response_json) return ( "Session ended" if self.session_not_found not in message_id_list else "Session already ended" ) def parse_message_ids(self, response_json): """Parse TSO response and retrieve only the message ids. Parameters ---------- response_json: dict The JSON containing the TSO response Returns ------- list A list containing the TSO response message ids """ return ( [message["messageId"] for message in response_json["msgData"]] if "msgData" in response_json else [] ) def retrieve_tso_messages(self, response_json): """Parse the TSO response and retrieve all messages. Parameters ---------- response_json: dict The JSON containing the TSO response Returns ------- list A list containing the TSO response messages """ return [ message["TSO MESSAGE"]["DATA"] for message in response_json if "TSO MESSAGE" in message ]
zowe-zos-tso-for-zowe-sdk
/zowe_zos_tso_for_zowe_sdk-0.0.1-py3-none-any.whl/zowe/zos_tso_for_zowe_sdk/tso.py
tso.py
import html import regex as re from bs4 import BeautifulSoup emoji_pattern = re.compile( "[" "\U0001F600-\U0001F64F" "\U0001F300-\U0001F5FF" "\U0001F680-\U0001F6FF" "\U0001F1E0-\U0001F1FF" "\U00002702-\U000027B0" "\U0001f926-\U0001f937" "\U00010000-\U0010ffff" "\u200d" "\u2640-\u2642" "\u2600-\u2B55" "\u23cf" "\u23e9" "\u231a" "\u3030" "\ufe0f" "]+", flags=re.UNICODE, ) email_pattern = re.compile( """(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])""" ) ascii_emoji_pattern = re.compile(":\\)|;\\)|:D|;D|:\\(|;\\(|:/|;/|xd|xD") weekday_pattern = re.compile("monday|tuesday|wednesday|thursday|friday|saturday|sunday") # Explanation: # - this will match: http://google.com, www.google.com/a/b/c, www.google.com etc. # - it will also match: google.com/a, google.com/a/b/c etc. # - but it will NOT match: google.com # since we want to avoid false positives like: Please help me.I have a ... # where me.I could be matched as a link url_pattern_base = "[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b[-a-zA-Z0-9()@:%_\\+.~#?&\\/\\/=]" # noqa url_pattern = re.compile( f"(?:(?:https?:\\/\\/|www\\.){url_pattern_base}*|{url_pattern_base}+)" ) def normalize_special(text: str) -> str: text = str(text) text = text.replace("#", "") text = text.replace("&", "and") text = text.replace("’", "'") return text def unescape_html(text: str) -> str: text = str(text) text = html.unescape(text) return text def remove_html(text: str) -> str: soup = BeautifulSoup(text, "html.parser") return soup.get_text() def unify_en_weekday(text: str) -> str: return weekday_pattern.sub("monday", str(text)) def remove_emoji(text: str) -> str: text = str(text) text = remove_unicode_emoji(text) text = remove_ascii_emoji(text) return text def remove_unicode_emoji(text: str) -> str: return emoji_pattern.sub("", str(text)) def remove_ascii_emoji(text: str) -> str: return ascii_emoji_pattern.sub("", str(text)) def unify_url(text: str, replacement: str = "URL") -> str: return url_pattern.sub(replacement, str(text)) def unify_email(text: str, replacement: str = "EMAIL") -> str: return email_pattern.sub(replacement, str(text)) def simplify_punctuation(text: str) -> str: text = str(text) text = re.sub(r"([!?,;])\1+", r"\1", text) text = re.sub(r"\.{2,}", r"...", text) text = re.sub(r" ([,\.\?!])", r"\1", text) text = re.sub(r"^(\s|\.|,|\?|;|:|!)*(.*)$", r"\2", text) return text def normalize_whitespace(text: str) -> str: text = str(text) text = re.sub(r"//t", r"\t", text) text = re.sub(r"( )\1+", r"\1", text) text = re.sub(r"(\n)\1+", r"\1", text) text = re.sub(r"(\r)\1+", r"\1", text) text = re.sub(r"(\t)\1+", r"\1", text) return text.strip(" ") def unify_numbers(text: str) -> str: text = re.sub(r"\d", r"1", str(text)) return text def strip_en_welcome(text: str) -> str: welcomes = [ "good morning", "good afternoon", "good evening", "morning", "evening", "welcome", "dear", "hi", "hey", "hello", ] seps = [",", "!", ".", ""] text = str(text) for sep in seps: for welcome in welcomes: prefix = welcome + sep if text.startswith(prefix): text = text[len(prefix) :].strip() return text
zowie-utils
/zowie-utils-0.9.tar.gz/zowie-utils-0.9/zowie/preprocessing.py
preprocessing.py
Zowie<img width="10%" align="right" src="https://github.com/mhucka/zowie/raw/main/.graphics/zowie-icon.png"> ====== Zowie ("**Zo**tero link **w**r**i**t**e**r") is a command-line program for macOS that writes Zotero _select_ links into the file attachments contained in a Zotero database. [![License](https://img.shields.io/badge/License-BSD%203--Clause-blue.svg?style=flat-square)](https://choosealicense.com/licenses/bsd-3-clause) [![Latest release](https://img.shields.io/github/v/release/mhucka/zowie.svg?style=flat-square&color=b44e88)](https://github.com/mhucka/zowie/releases) [![DOI](https://img.shields.io/badge/dynamic/json.svg?label=DOI&style=flat-square&colorA=gray&colorB=navy&query=$.metadata.doi&uri=https://data.caltech.edu/api/record/1867)](https://data.caltech.edu/records/1867) [![Python](https://img.shields.io/badge/Python-3.6+-brightgreen.svg?style=flat-square)](http://shields.io) [![PyPI](https://img.shields.io/pypi/v/zowie.svg?style=flat-square&color=orange)](https://pypi.org/project/zowie/) Table of contents ----------------- * [Introduction](#introduction) * [Installation](#installation) * [Usage](#usage) * [Known issues and limitations](#known-issues-and-limitations) * [Getting help](#getting-help) * [Contributing](#contributing) * [License](#license) * [Authors and history](#authors-and-history) * [Acknowledgments](#authors-and-acknowledgments) Introduction ------------ When using [Zotero](https://zotero.org), you may on occasion want to work with PDF files and other attachment files outside of Zotero. For example, if you're a [DEVONthink](https://www.devontechnologies.com/apps/devonthink) user, you will at some point discover the power of indexing your local Zotero database from DEVONthink. However, when viewing or manipulating the attachments from outside of Zotero, you may run into the following problem: when looking at a given file, _how do you find out which Zotero entry it belongs to_? Enter Zowie (a loose acronym for _"**Zo**tero link **w**r**i**t**e**r"_, and pronounced like [the interjection](https://www.merriam-webster.com/dictionary/zowie)). Zowie scans through the files in a local Zotero database, looks up the Zotero bibliographic record corresponding to each attachment file found, and writes a [Zotero select link](https://forums.zotero.org/discussion/78053/given-the-pdf-file-of-an-article-how-can-you-find-out-its-uri#latest) into the file and/or certain macOS Finder/Spotlight metadata fields (depending on the user's choice). A Zotero select link has the form `zotero://select/...` and when opened on macOS, causes the Zotero desktop application to open that item in your database. Zowie thus makes it possible to go from a file opened in an application other than Zotero (e.g., DEVONthink, Adobe Acrobat), to the Zotero record corresponding to that file. Zowie uses the Zotero network API to discover the user's shared libraries and groups. This allows it to look up Zotero item URIs for files regardless of whether they belong to the user's personal library or shared libraries, and from there, construct the appropriate Zotero select link for the files. Regretfully, Zowie can only work with Zotero libraries that use normal/local data storage; it cannot work when Zotero is configured to use linked attachments. Installation ------------ Zowie is available as a self-contained executable program for macOS, as well as a program for running within a Python interpreter. The following are alternative ways of installing it. ### _Alternative 1: ready-to-run executable (for macOS <ins>before</ins> 10.15)_ A self-contained, ready-to-run binary version is available for macOS 10.13 (High Sierra) and 10.14 (Mojave); it **does not run on 10.15 (Catalina) or later** due to Apple security issues. The binary is created using [PyInstaller](http://www.pyinstaller.org); it works like any normal command-line program and does **not** require Python. 1. Go to the [releases page](https://github.com/mhucka/zowie/releases). 2. Find the latest release (normally the first one on the page). 3. <img align="right" width="400px" src="https://github.com/mhucka/zowie/raw/main/.graphics/binary-release.png"/>Find the **Assets** section of the release. 4. Click on `zowie.zip` to download it. 5. Unzip the file; this will leave you with a file named `zowie`, which is the program itself. 6. Move `zowie` to a folder where you put other command-line programs (e.g. `/usr/local/bin`). If you want to put it in `/usr/local/bin` but that folder does not exist on your computer yet, you can create it by opening a terminal window and running the following command (_prior_ to moving `zowie` into `/usr/local/bin`): ```shell sudo mkdir /usr/local/bin ``` ### _Alternative 2: Zowie as a Python package_ The instructions below assume you have a Python 3 interpreter installed on your computer. Note that the default on macOS at least through 10.14 (Mojave) is Python **2** &ndash; please first install Python version 3 and familiarize yourself with running Python programs on your system before proceeding further. You should be able to install `zowie` with [`pip`](https://pip.pypa.io/en/stable/installing/) for Python&nbsp;3. To install `zowie` from the [Python package repository (PyPI)](https://pypi.org), run the following command: ``` python3 -m pip install zowie ``` As an alternative to getting it from [PyPI](https://pypi.org), you can use `pip` to install `zowie` directly from GitHub: ```sh python3 -m pip install git+https://github.com/mhucka/zowie.git ``` _If you already installed Zowie once before_, and want to update to the latest version, add `--upgrade` to the end of either command line above. Usage ----- For help with usage at any time, run `zowie` with the option `-h`. The `zowie` command-line program should end up installed in a location where software is normally installed on your computer, if the installation steps described in the previous section proceeded successfully. Running Zowie from a terminal shell then should be as simple as running any other shell command on your system: ```shell zowie -h ``` If you installed it as a Python package, then an alternative method is available to run Zowie from anywhere, namely to use the normal approach for running Python modules: ```shell python3 -m zowie -h ``` ### _Credentials for Zotero access_ Zowie relies on the [Zotero sync API](https://www.zotero.org/support/dev/web_api/v3/start) to get information about your references. If you do not already have a [Zotero sync account](https://www.zotero.org/support/sync), it will be necessary to create one before going any further. To use Zowie, you will also need both an API user identifier (also known as the **userID**) and an **API key**. To find out your Zotero userID and create a new API key, log in to your Zotero account at [Zotero.org](https://www.zotero.org) and visit the [_Feeds/API_ tab of the your _Settings_ page](https://www.zotero.org/settings/keys). On that page you can find your userID and create a new API key for Zowie. The first time you run Zowie, it will ask for this information and (unless the `-K` option is given) store it in your macOS keychain so that it does not have to ask for it again on future occasions. It is also possible to supply the identifier and API key directly on the command line using the `-i` and `-a` options, respectively; the given values will then override any values stored in the keychain and (unless the `-K` option is also given) will be used to update the keychain for the next time. ### _Basic usage_ Zowie can operate on a folder, or one or more individual files, or a mix of both. Suppose your local Zotero database is located in `~/Zotero/`. Perhaps the simplest way to run Zowie is the following command: ```shell zowie ~/Zotero ``` If this is your first run of Zowie, it will ask you for your userID and API key, then search for files recursively under `~/Zotero/`. For each file found, Zowie will contact the Zotero servers over the network and determine the Zotero select link for the bibliographic entry containing that file. Finally, it will use the default method of recording the link, which is to write it into the macOS Finder comments for the file. It will also store your Zotero userID and API key into the system keychain so that it does not have to ask for them in the future. Instead of a folder, you can invoke Zowie on one or more individual files (but be careful to quote pathnames with spaces in them, such as in this example): ```shell zowie "~/Zotero/storage/26GS7CZL/Smith 2020 Paper.pdf" ``` ### _Available methods of writing Zotero links_ Zowie supports multiple methods of writing the Zotero select link. The option `-l` will cause Zowie to print a list of all the methods available, then exit. The option `-m` can be used to select one or more methods when running Zowie. Write the method names separated with commas without spaces. For example, the following command will make Zowie write the Zotero select link into the Finder comments as well as the PDF metadata attribute _Subject_: ```shell zowie -m findercomment,pdfsubject ~/Zotero/storage ``` At this time, the following methods are available: * **`findercomment`**: (**The default method**.) Writes the Zotero select link into the Finder comments of each file, attempting to preserve other parts of the comments. If Zowie finds an existing Zotero select link in the text of the Finder comments attribute, it only updates the link portion and tries to leave the rest of the comment text untouched. Otherwise, Zowie **only** writes into the comments attribute if either the attribute value is empty or Zowie is given the overwrite (`-o`) option. (Note that updating the link text requires rewriting the entire Finder comments attribute on a given file. Finder comments have a reputation for being easy to get into inconsistent states, so if you have existing Finder comments that you absolutely don't want to lose, it may be safest to avoid this method.) * **`pdfproducer`**: (Only applicable to PDF files.) Writes the Zotero select link into the "Producer" metadata field of each PDF file. If the "Producer" field is not empty on a given file, Zowie looks for an existing Zotero link within the value and updates the link if one is found; otherwise, Zowie leaves the field untouched unless given the overwrite flag (`-o`), in which case, it replaces the entire contents of the field with the Zotero select link. For some users, the "Producer" field has not utility, and thus can be usefully hijacked for the purpose of storing the Zotero select link. The value is accessible from macOS Preview, Adobe Acrobat, DEVONthink, and presumably any other application that can display the PDF metadata fields. However, note that some users (archivists, forensics investigators, possibly others) do use the "Producer" field, and overwriting it may be undesirable. * **`pdfsubject`**: (Only applicable to PDF files.) Writes the Zotero select link into the "Subject" metadata field of each PDF file. If the "Subject" field is not empty on a given file, Zowie looks for an existing Zotero link within the value and updates the link if one is found; otherwise, Zowie leaves the field untouched unless given the overwrite flag (`-o`), in which case, it replaces the entire contents of the field with the Zotero select link. Note that the PDF "Subject" field is not the same as the "Title" field. For some users, the "Subject" field is not used for any purpose and thus can be usefully hijacked for storing the Zotero select link. The value is accessible from macOS Preview, Adobe Acrobat, DEVONthink, and presumably any other application that can display the PDF metadata fields. * **`wherefrom`**: Writes the Zotero select link to the "Where from" metadata field of each file (the [`com.apple.metadata:kMDItemWhereFroms`](https://developer.apple.com/documentation/coreservices/kmditemwherefroms) extended attribute). This field is displayed as "Where from" in Finder "Get Info" panels; it is typically used by web browsers to store a file's download origin. The field is a list. If Zowie finds a Zotero select link as the first item in the list, it updates that value; otherwise, Zowie prepends the Zotero select link to the list of existing values, keeping the other values unless the overwrite option (`-o`) is used. When the overwrite option is used, Zowie deletes the existing list of values and writes only the Zotero select link. Note that if macOS Spotlight indexing is turned on for the volume containing the file, the macOS Finder will display the updated "Where from" values in the Get Info panel of the file; if Spotlight is not turned on, the Get info panel will not be updated, but other applications will still be able to read the updated value. Note that, depending on the attribute, it is possible that a file has an attribute value that is not visible in the Finder or other applications. This is especially true for "Where from" values and Finder comments. The implication is that it may not be apparent when a file has a value for a given attribute, which can lead to confusion if Zowie thinks there is a value and refuses to change it without the `-o` option. ### _Filtering by file type_ By default, Zowie acts on all files it finds on the command line, except for certain files that it always ignores: hidden files and files with extensions `.sqlite`, `.bak`, `.csl`, `.css`, `.js`, `.json`, `.pl`, and a few others. If the `-m` option is used to select methods that only apply to specific file types, Zowie will examine each file it finds in turn and only apply the methods that match that particular file's type, but it will still consider every file it finds in the directories it scans and apply the methods that are not limited to specific types. You can use the option `-f` to make Zowie filter the files it finds based on file name extensions. This is useful if you want it to concentrate only on particular file types and ignore other files it might find while scanning folders. For example, ```shell zowie -f pdf,mp4,mov ~/Zotero ``` will cause it to only work on PDF, MP4, and QuickTime format files. You can provide multiple file extensions separated by commas, without spaces and without the leading periods. ### _Filtering by date_ If the `-d` option is given, the files will be filtered to use only those whose last-modified date/time stamp is no older than the given date/time description. Valid descriptors are those accepted by the Python dateparser library. Make sure to enclose descriptions within single or double quotes. Examples: ```shell zowie -d "2 weeks ago" .... zowie -d "2014-08-29" .... zowie -d "12 Dec 2014" .... zowie -d "July 4, 2013" .... ``` ### _Additional command-line arguments_ To make Zowie only print what it would do without actually doing it, use the `-n` "dry run" option. If given the `-q` option, Zowie will not print its usual informational messages while it is working. It will only print messages for warnings or errors. By default messages printed by Zowie are also color-coded. If given the option `-C`, Zowie will not color the text of messages it prints. (This latter option is useful when running Zowie within subshells inside other environments such as Emacs.) If given the `-V` option, this program will print the version and other information, and exit without doing anything else. If given the `-@` argument, this program will output a detailed trace of what it is doing. The debug trace will be sent to the given destination, which can be `-` to indicate console output, or a file path to send the output to a file. When `-@ has` been given, Zowie also installs a signal handler on signal `SIGUSR1` that will drop Zowie into the pdb debugger if the signal is sent to the running process. ### _Summary of command-line options_ The following table summarizes all the command line options available. | Short&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | Long&nbsp;form&nbsp;opt&nbsp;&nbsp;&nbsp;&nbsp; | Meaning | Default | | |---------- |-------------------|--------------------------------------|---------|---| | `-a`_A_ | `--api-key`_A_ | API key to access the Zotero API service | | | | `-C` | `--no-color` | Don't color-code the output | Use colors in the terminal | | | | `-d` | `--after-date`_D_ | Only act on files modified after date "D" | Act on all files found | | | `-f` | `--file-ext`_F_ | Only act on files with extensions in "F" | Act on all files found | ⚑ | | `-h` | `--help` | Display help text and exit | | | | `-i` | `--identifier`_I_ | Zotero user ID for API calls | | | | `-K` | `--no-keyring` | Don't use a keyring/keychain | Store login info in keyring | | | `-l` | `--list` | Display known services and exit | | | | `-m` | `--method`_M_ | Control how Zotero select links are stored | `findercomment` | | | `-n` | `--dry-run` | Report what would be done but don't do it | Do it | | | `-o` | `--overwrite` | Overwrite previous metadata content | Don't write if already present | | | `-q` | `--quiet` | Don't print messages while working | Be chatty while working | | `-V` | `--version` | Display program version info and exit | | | | `-@`_OUT_ | `--debug`_OUT_ | Debugging mode; write trace to _OUT_ | Normal mode | ⬥ | ⚑ &nbsp; Certain files are always ignored: hidden files, macOS aliases, and files with extensions `.sqlite`, `.sqlite-journal`, `.bak`, `.csl`, `.css`, `.js`, `.json`, `.pl`, and `.config_resp`.<br> ⬥ &nbsp; To write to the console, use the character `-` as the value of _OUT_; otherwise, _OUT_ must be the name of a file where the output should be written. ### _Return values_ This program exits with a return code of 0 if no problems are encountered. It returns a nonzero value otherwise. The following table lists the possible return values: | Code | Meaning | |:----:|----------------------------------------------------------| | 0 | success &ndash; program completed normally | | 1 | the user interrupted the program's execution | | 2 | encountered a bad or missing value for an option | | 3 | no network detected &ndash; cannot proceed | | 4 | file error &ndash; encountered a problem with a file | | 5 | server error &ndash; encountered a problem with a server | | 6 | an exception or fatal error occurred | Known issues and limitations ---------------------------- The following is a list of currently-known issues and limitations: * Zowie can only work when Zotero is set to use direct data storage; i.e., where attached files are stored in Zotero. It cannot work if you use [linked attachments](https://www.zotero.org/support/preferences/advanced#files_and_folders), that is, if you set _Linked Attachment Base Directory_ in your Zotero Preferences' _Advanced_ → _Files and Folders_ panel. * For reasons I have not had time to investigate, the binary version of `zowie` takes a very long time to start up on macOS 10.15 (Catalina) and 11.1 (Big Sur). On my test system inside a virtual machine running on a fast iMac, it takes 10 seconds or more before the first output from `zowie` appears. Getting help ------------ If you find an issue, please submit it in [the GitHub issue tracker](https://github.com/mhucka/zowie/issues) for this repository. Contributing ------------ I would be happy to receive your help and participation if you are interested. Everyone is asked to read and respect the [code of conduct](CONDUCT.md) when participating in this project. Development generally takes place on the `development` branch. License ------- This software is Copyright (C) 2020, by Michael Hucka and the California Institute of Technology (Pasadena, California, USA). This software is freely distributed under a 3-clause BSD type license. Please see the [LICENSE](LICENSE) file for more information. Authors and history --------------------------- Copyright (c) 2020 by Michael Hucka and the California Institute of Technology. Acknowledgments --------------- This work is a personal project developed by the author, using computing facilities and other resources of the [California Institute of Technology Library](https://www.library.caltech.edu). The [vector artwork](https://thenounproject.com/term/tag-exclamation-point/326951/) of an exclamation point circled by a zigzag, used as the icon for this repository, was created by [Alfredo @ IconsAlfredo.com](https://thenounproject.com/AlfredoCreates/) from the Noun Project. It is licensed under the Creative Commons [CC-BY 3.0](https://creativecommons.org/licenses/by/3.0/) license. Zowie makes use of numerous open-source packages, without which Zowie could not have been developed. I want to acknowledge this debt. In alphabetical order, the packages are: * [aenum](https://pypi.org/project/aenum/) &ndash; advanced enumerations for Python * [boltons](https://github.com/mahmoud/boltons/) &ndash; package of miscellaneous Python utilities * [biplist](https://bitbucket.org/wooster/biplist/src/master/) &ndash; A binary plist parser/writer for Python * [bun](https://github.com/caltechlibrary/bun) &ndash; a set of basic user interface classes and functions * [commonpy](https://github.com/caltechlibrary/commonpy) &ndash; a collection of commonly-useful Python functions * [ipdb](https://github.com/gotcha/ipdb) &ndash; the IPython debugger * [keyring](https://github.com/jaraco/keyring) &ndash; access the system keyring service from Python * [pdfrw](https://github.com/pmaupin/pdfrw) &ndash; a pure Python library for reading and writing PDFs * [plac](http://micheles.github.io/plac/) &ndash; a command line argument parser * [py-applescript](https://pypi.org/project/py-applescript/) &ndash; a Python interface to AppleScript * [PyInstaller](http://www.pyinstaller.org) &ndash; a packaging program that creates standalone applications from Python programs * [pyobjc](https://github.com/ronaldoussoren/pyobjc) &ndash; Python &rlhar; Objective-C and macOS frameworks bridge * [pyzotero](https://github.com/urschrei/pyzotero) &ndash; a Python API client for Zotero * [pyxattr](https://github.com/iustin/pyxattr) &ndash; access extended file attributes from Python * [setuptools](https://github.com/pypa/setuptools) &ndash; library for `setup.py` * [sidetrack](https://github.com/caltechlibrary/sidetrack) &ndash; simple debug logging/tracing package * [wheel](https://pypi.org/project/wheel/) &ndash; setuptools extension for building wheels The [developers of DEVONthink](https://www.devontechnologies.com/about), especially Jim Neumann and Christian Grunenberg, quickly and consistently replied to my many questions on the [DEVONtechnologies forums](https://discourse.devontechnologies.com).
zowie
/zowie-1.1.2.tar.gz/zowie-1.1.2/README.md
README.md
# Zonda Python Proxy ## Install `pip install zoxy` ## Quick start for cli Default server path: 127.0.0.1:8080 `$ ./zoxy` ### Customize url and port Example: 0.0.0.0:9999 `$ ./zoxy -u 0.0.0.0 -p 9999` ### Allowed access Example: * 127.0.0.1, mask: 255.255.255.255, port 8080 * 127.0.0.0, mask: 255.255.255.0, port: all `$ ./zoxy --allowed_access 127.0.1.1 8080 --allowed_access 127.0.0.0/24 *` ### Blocked access Example: * 127.0.0.1, mask: 255.255.255.255, port: 8080 * 127.0.0.0, mask: 255.255.255.0, port: all `$ ./zoxy --blocked_access 127.0.1.1 8080 --blocked_access 127.0.0.0/24 *` Note: Blocked access setting has higher priority than allowed access. ### Forwarding Example: * 192.168.1.0, mask: 255.255.255.0, port: 1234 to 127.0.0.1, port: 8000 * 0.0.0.0, mask: 0.0.0.0, port: all to 127.0.0.2, port: all `$ ./zoxy --forwarding 192.168.1.0/24 1234 127.0.0.1 8000 --forwarding 0.0.0.0/0 * 127.0.0.2 *` ## Quick start for program ```python import zoxy.server config = { "url": "0.0.0.0", "port": 9999, "allowed_accesses": [ ["127.0.1.1", "8080"], ["127.0.2.0/24", "1234"], ["127.0.0.0/24", "*"], ], "blocked_accesses": [ ["192.0.1.1", "8080"], ["192.0.2.0/24", "1234"], ["192.0.0.0/24", "*"], ], "forwarding": [ ["196.168.2.1", "1234", "127.0.2.1", "8000"], ["196.168.1.0/24", "1234", "127.0.0.1", "8000"], ["0.0.0.0/0", "*", "127.0.0.2", "*"], ], } zoxy.server.ProxyServer(**config).listen() ``` ### Get/Set accesses #### Allowed accesses ```python # Get proxy_server.allowed_accesses ''' [ ["127.0.1.1/32", "8080"], ["127.0.2.0/24", "1234"], ["127.0.0.0/24", "*"], ] ''' # Set proxy_server.allowed_accesses = [ ["111.0.1.1", "8080"], ["111.0.2.0/24", "1234"], ["111.0.0.0/24", "*"], ] ``` #### Blocked accesses ```python # Get proxy_server.blocked_accesses ''' [ ["192.0.1.1/32", "8080"], ["192.0.2.0/24", "1234"], ["192.0.0.0/24", "*"], ] ''' # Set proxy_server.blocked_accesses = [ ["111.0.1.1", "8080"], ["111.0.2.0/24", "1234"], ["111.0.0.0/24", "*"], ] ``` ### Get/Set forwarding ```python # Get proxy_server.forwarding ''' [ ["196.168.2.1/32", "1234", "127.0.2.1", "8000"], ["196.168.1.0/24", "1234", "127.0.0.1", "8000"], ["0.0.0.0/0", "*", "127.0.0.2", "*"] ] ''' # Set proxy_server.forwarding = [ ["176.168.2.1", "1234", "127.0.2.1", "8000"], ["176.168.1.0/24", "1234", "127.0.0.1", "8000"], ["176.0.0.0/8", "*", "127.0.0.2", "*"] ] ``` ## Developer ### Test `python -m unittest` ### Type checking `mypy zoxy`
zoxy
/zoxy-0.0.4.tar.gz/zoxy-0.0.4/README.md
README.md
本模块主要进行数据校验:支持查表法和直接法。支持crc16常用校验法和自定义校验。详细用法可参照代码。 crc32仅仅实现了经典法。 ```python import unittest from zp_pycrc import * class crc_test(unittest.TestCase): def test_crc16(self): datas=b'\x01\x02\x03\x04\x05' print(len(datas),datas) crc=crc16_ccitt() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_ccitt_false() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_xmodem() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_x25() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_ibm() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_usb() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_maxim() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_modbus() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_dnp() print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16( 0,0x8005, True, True, 0) print(crc.__class__.__name__,"%04X"%(crc.cal(datas))) crc=crc16_ibm() print("crc16_ibm __call__",hex(crc(datas))) b=cal_crc16_classcial(datas, 0,0x8005, True, True, 0) print("cal_crc16_classcial",hex(b)) print('*******crc ibm table*****') print([hex(i) for i in crc.crc_table]) def test_crc32(self): datas=b'\x01\x02\x03\x04\x05' r=cal_crc32_classcial(datas, 0xffffffff, 0x04c11db7, True, True, 0xffffffff) print(hex(r)) if __name__ == '__main__': unittest.main()
zp-pycrc
/zp_pycrc-0.0.4.tar.gz/zp_pycrc-0.0.4/README.md
README.md
name='zp_pyCRC' def reverse_data(data,bits=16): reverse_table=[0x0,0x8,0x4,0xc, #0,1,2,3 0x2,0xa,0x6,0xe, #4,5,6,7 0x1,0x9,0x5,0xd, #8,9,a,b 0x3,0xb,0x7,0xf] #c,d,e,f if bits==16 : data&=0xffff return (reverse_table[data&0xf]<<12)+(reverse_table[(data&0xf0)>>4]<<8)+(reverse_table[(data&0xf00)>>8]<<4)+(reverse_table[(data&0xf000)>>12]) if bits==8: data&=0xff return (reverse_table[data&0xf]<<4)+(reverse_table[(data&0xf0)>>4]) if bits==32: a=[] for _ in range(8): a.append(reverse_table[data&0x0f]) data>>=4 data=0 for i in range(8): data<<=4 data+=a[i] return data else : raise ValueError("bits param error ,it must be:8,16,32") def cal_crc16_classcial(datas,init_reg,poly,reverse_input,reverse_output,xorout_reg): reg=init_reg cal_poly=poly for i in datas: if reverse_input: data=reverse_data(i, 8) else: data=i reg^=(data<<8) for _ in range(8) : if reg&0x8000 : reg=reg<<1 reg&=0xffff reg^=cal_poly else : reg=reg<<1 if reverse_output: reg= reverse_data(reg, 16) reg^=xorout_reg return reg def cal_crc32_classcial(datas,init_reg,poly,reverse_input,reverse_output,xorout_reg): reg=init_reg cal_poly=poly for i in datas: if reverse_input: data=reverse_data(i, 8) else: data=i reg^=(data<<24) for _ in range(8) : if reg&0x80000000 : reg=reg<<1 reg&=0xffffffff reg^=cal_poly else : reg=reg<<1 if reverse_output: reg= reverse_data(reg, 32) reg^=xorout_reg return reg class crc16(object): def __init__(self,init_reg,poly,reverse_input,reverse_output,xorout_reg): self.init_reg=init_reg self.xorout_reg=xorout_reg self.poly=poly self.reverse_input=reverse_input self.reverse_output=reverse_output self.crc_table=self.make_crc_table(self.poly,self.reverse_input) pass def make_crc_table(self,poly,reverse_input=False): table=[] if reverse_input: cal_poly=reverse_data(poly) for i in range(256): reg=i for _ in range(8): if reg&0x1 : reg=reg>>1 reg^=cal_poly else : reg=reg>>1 table.append(reg) else: cal_poly=poly for i in range(256): reg=(i<<8) for _ in range(8): if reg&0x8000 : reg=reg<<1 reg&=0xffff reg^=cal_poly else : reg=reg<<1 table.append(reg) return table def _cal_crc(self,datas,reg,table,reverse_input,reverse_output): if reverse_input: for a in datas : reg=(reg>>8)^table[(reg^a)&0xff] else : for a in datas : reg=((reg&0xff)<<8)^table[((reg>>8)^a)&0xff] if reverse_output != reverse_input : reg=reverse_data(reg, 16) return reg def cal(self,datas): return self.__call__(datas) def __call__(self,datas): reg=self.init_reg reg=self._cal_crc(datas, reg, self.crc_table, self.reverse_input,self.reverse_output) reg^=self.xorout_reg return reg class crc16_ccitt(crc16): def __init__(self): crc16.__init__(self, 0x0000, 0x1021, True,True, 0x0000) class crc16_ccitt_false(crc16): def __init__(self): crc16.__init__(self, 0xffff, 0x1021, False,False, 0x0000) class crc16_xmodem(crc16): def __init__(self): crc16.__init__(self, 0x0000, 0x1021, False,False, 0x0000) class crc16_x25(crc16): def __init__(self): crc16.__init__(self, 0xffff, 0x1021, True,True, 0xffff) class crc16_ibm(crc16): def __init__(self): crc16.__init__(self, 0x0000, 0x8005, True,True, 0x0000) class crc16_usb(crc16): def __init__(self): crc16.__init__(self, 0xffff, 0x8005, True,True, 0xffff) class crc16_maxim(crc16): def __init__(self): crc16.__init__(self, 0x0000, 0x8005, True,True, 0xffff) class crc16_modbus(crc16): def __init__(self): crc16.__init__(self, 0xffff, 0x8005, True,True, 0x0000) class crc16_dnp(crc16): def __init__(self): crc16.__init__(self, 0x0000, 0x3d65, True,True, 0xffff)
zp-pycrc
/zp_pycrc-0.0.4.tar.gz/zp_pycrc-0.0.4/zp_pycrc/__init__.py
__init__.py
import json import os import threading import inspect import ctypes import logging import time from .util import * version = sys.version_info.major if version == 2: from .python_2x import * if version == 3: from .python_3x import * # logging.basicConfig() logging.basicConfig(format='%(asctime)s,%(msecs)d %(levelname)-8s [%(filename)s:%(lineno)d] %(message)s', datefmt='%d-%m-%Y:%H:%M:%S', level=logging.DEBUG) class ApolloClient(object): def __init__(self, config_url, app_id, cluster='default', secret='', start_hot_update=True, change_listener=None, namespaces=None, label='', bak_config_url=None): if not config_url: raise Exception("error, config url is required") if config_url[-1] == '/': # 后面会拼接地址,去除多余的斜杠 config_url = config_url[:-1] if not namespaces: namespaces = ['application'] # 核心路由参数 self.config_url = config_url self.cluster = cluster self.app_id = app_id # 非核心参数 self.ip = init_ip() self.label = label self.secret = secret self.namespaces = namespaces # 检查参数变量 # 私有控制变量 self._cycle_time = 2 self._stopping = False self._cache = {} self._no_key = {} self._hash = {} self._pull_timeout = 75 self._cache_file_path = os.path.expanduser('~') + '/data/apollo/cache/' self._long_poll_thread = None self._change_listener = change_listener # "add" "delete" "update" self._notification_map = {'application': -1} self.last_release_key = None # 私有启动方法 self._path_checker() if not self.namespace_check_ok(): if bak_config_url: logging.warning( "error, start with main config url [{}] fail, using bak config url: {}".format(config_url, bak_config_url)) self.config_url = bak_config_url if not self.namespace_check_ok(): logging.error( "error, start with bak config url [{}] fail".format(bak_config_url)) raise Exception('error, namespace_check fail') else: logging.error("error, start with main config url [{}] fail, no bak config url provided".format(config_url)) raise Exception('error, namespace_check fail') if start_hot_update: self._start_hot_update() # 启动心跳线程 heartbeat = threading.Thread(target=self._heartBeat) heartbeat.setDaemon(True) heartbeat.start() def get_json_from_net(self, namespace='application'): url = '{}/configs/{}/{}/{}?releaseKey={}&ip={}&label={}'.format(self.config_url, self.app_id, self.cluster, namespace, "", self.ip, self.label) try: code, body = http_request(url, timeout=3, headers=self._signHeaders(url)) if code == 200: data = json.loads(body) data = data["configurations"] return_data = {CONFIGURATIONS: data} return return_data else: return None except Exception as e: logging.getLogger(__name__).error(str(e)) return None def get(self, key, default=None, namespace='application'): try: # 读取内存配置 namespace_cache = self._cache.get(namespace) val = get_value_from_dict(namespace_cache, key) if val is not None: return val no_key = no_key_cache_key(namespace, key) if no_key in self._no_key: return default # 读取网络配置 namespace_data = self.get_json_from_net(namespace) val = get_value_from_dict(namespace_data, key) if val is not None: self._update_cache_and_file(namespace_data, namespace) return val # 读取文件配置 namespace_cache = self._get_local_cache(namespace) val = get_value_from_dict(namespace_cache, key) if val is not None: self._update_cache_and_file(namespace_cache, namespace) return val # 如果全部没有获取,则把默认值返回,设置本地缓存为None self._set_local_cache_none(namespace, key) return default except Exception as e: logging.getLogger(__name__).error("get_value has error, [key is %s], [namespace is %s], [error is %s], ", key, namespace, e) return default def get_all(self, namespace='application', default=None, allow_cache=True): try: if allow_cache: # 读取内存配置 namespace_cache = self._cache.get(namespace) if namespace_cache is not None: return namespace_cache.get(CONFIGURATIONS, default) # 读取网络配置 namespace_data = self.get_json_from_net(namespace) if namespace_data: self._update_cache_and_file(namespace_data, namespace) return namespace_data.get(CONFIGURATIONS, default) if allow_cache: # 读取文件配置 namespace_cache = self._get_local_cache(namespace) if namespace_cache is not None: self._update_cache_and_file(namespace_cache, namespace) return namespace_cache.get(CONFIGURATIONS, default) return default except Exception as e: logging.getLogger(__name__).error("get_all has error, [namespace is %s], [error is %s], ", namespace, e) return default def namespace_check_ok(self): for ns in self.namespaces: configs = self.get_all(namespace=ns, allow_cache=False) if configs is None: logging.error("namespace [{}] check fail".format(ns)) return False return True # 设置某个namespace的key为none,这里不设置default_val,是为了保证函数调用实时的正确性。 # 假设用户2次default_val不一样,然而这里却用default_val填充,则可能会有问题。 def _set_local_cache_none(self, namespace, key): no_key = no_key_cache_key(namespace, key) self._no_key[no_key] = key def _start_hot_update(self): self._long_poll_thread = threading.Thread(target=self._listener) # 启动异步线程为守护线程,主线程推出的时候,守护线程会自动退出。 self._long_poll_thread.setDaemon(True) self._long_poll_thread.start() def stop(self): self._stopping = True logging.getLogger(__name__).info("Stopping listener...") # 调用设置的回调函数,如果异常,直接try掉 def _call_listener(self, namespace, old_kv, new_kv): if self._change_listener is None: return if old_kv is None: old_kv = {} if new_kv is None: new_kv = {} try: for key in old_kv: new_value = new_kv.get(key) old_value = old_kv.get(key) if new_value is None: # 如果newValue 是空,则表示key,value被删除了。 self._change_listener("delete", namespace, key, old_value) continue if new_value != old_value: self._change_listener("update", namespace, key, new_value) continue for key in new_kv: new_value = new_kv.get(key) old_value = old_kv.get(key) if old_value is None: self._change_listener("add", namespace, key, new_value) except BaseException as e: logging.getLogger(__name__).warning(str(e)) def _path_checker(self): if not os.path.isdir(self._cache_file_path): makedirs_wrapper(self._cache_file_path) # 更新本地缓存和文件缓存 def _update_cache_and_file(self, namespace_data, namespace='application'): # 更新本地缓存 self._cache[namespace] = namespace_data # 更新文件缓存 new_string = json.dumps(namespace_data) new_hash = hashlib.md5(new_string.encode('utf-8')).hexdigest() if self._hash.get(namespace) == new_hash: pass else: with open(os.path.join(self._cache_file_path, '%s_configuration_%s.txt' % (self.app_id, namespace)), 'w') as f: f.write(new_string) self._hash[namespace] = new_hash # 从本地文件获取配置 def _get_local_cache(self, namespace='application'): cache_file_path = os.path.join(self._cache_file_path, '%s_configuration_%s.txt' % (self.app_id, namespace)) if os.path.isfile(cache_file_path): with open(cache_file_path, 'r') as f: result = json.loads(f.readline()) return result return {} def _long_poll(self): notifications = [] for key in self._cache: namespace_data = self._cache[key] notification_id = -1 if NOTIFICATION_ID in namespace_data: notification_id = self._cache[key][NOTIFICATION_ID] notifications.append({ NAMESPACE_NAME: key, NOTIFICATION_ID: notification_id }) try: # 如果长度为0直接返回 if len(notifications) == 0: return url = '{}/notifications/v2'.format(self.config_url) params = { 'appId': self.app_id, 'cluster': self.cluster, 'notifications': json.dumps(notifications, ensure_ascii=False) } param_str = url_encode_wrapper(params) url = url + '?' + param_str code, body = http_request(url, self._pull_timeout, headers=self._signHeaders(url)) http_code = code if http_code == 304: logging.getLogger(__name__).debug('No change, loop...') return if http_code == 200: data = json.loads(body) for entry in data: namespace = entry[NAMESPACE_NAME] n_id = entry[NOTIFICATION_ID] logging.getLogger(__name__).info("%s has changes: notificationId=%d", namespace, n_id) self._get_net_and_set_local(namespace, n_id, call_change=True) return else: logging.getLogger(__name__).warning('Sleep...') except Exception as e: logging.getLogger(__name__).warning(str(e)) def _get_net_and_set_local(self, namespace, n_id, call_change=False): namespace_data = self.get_json_from_net(namespace) namespace_data[NOTIFICATION_ID] = n_id old_namespace = self._cache.get(namespace) self._update_cache_and_file(namespace_data, namespace) if self._change_listener is not None and call_change: old_kv = old_namespace.get(CONFIGURATIONS) new_kv = namespace_data.get(CONFIGURATIONS) self._call_listener(namespace, old_kv, new_kv) def _listener(self): logging.getLogger(__name__).info('start long_poll') while not self._stopping: self._long_poll() time.sleep(self._cycle_time) logging.getLogger(__name__).info("stopped, long_poll") # 给header增加加签需求 def _signHeaders(self, url): headers = {} if self.secret == '': return headers uri = url[len(self.config_url):len(url)] time_unix_now = str(int(round(time.time() * 1000))) headers['Authorization'] = 'Apollo ' + self.app_id + ':' + signature(time_unix_now, uri, self.secret) headers['Timestamp'] = time_unix_now return headers def _heartBeat(self): while not self._stopping: for namespace in self._notification_map: self._do_heartBeat(namespace) time.sleep(60 * 10) # 10分钟 def _do_heartBeat(self, namespace): url = '{}/configs/{}/{}/{}?ip={}'.format(self.config_url, self.app_id, self.cluster, namespace, self.ip) try: code, body = http_request(url, timeout=3, headers=self._signHeaders(url)) if code == 200: data = json.loads(body) if self.last_release_key == data["releaseKey"]: return None self.last_release_key = data["releaseKey"] data = data["configurations"] self._update_cache_and_file(data, namespace) else: return None except Exception as e: logging.getLogger(__name__).error(str(e)) return None
zpapollo
/zpapollo-1.1.0-py3-none-any.whl/apollo/apollo_client.py
apollo_client.py
# zpca PCA analysis # Installation ```bash # clone the repo git clone https://github.com/zavolanlab/zpca.git # create a virtual environment python3 -m venv venv # activate the virtual environment source venv/bin/activate # install zpca scripts pip install . ``` # Run zpca consists of two tools: - zpca-tpm - zpca-counts When you run ```bash zpca-tpm --help ``` The following message should appear ``` usage: zpca-tpm [-h] --tpm FILE [--tpm-filter TPM_FILTER] [--tpm-pseudocount TPM_PSEUDOCOUNT] --out FILE [-v] Perform PCA based on a TPM expression matrix (rows are genes/transcripts, columns are samples). optional arguments: -h, --help show this help message and exit --tpm FILE TPM table (tsv). --tpm-filter TPM_FILTER Filter genes/transcripts with mean expression less than the provided filter. Default: 1 --tpm-pseudocount TPM_PSEUDOCOUNT Pseudocount to add in the tpm table. Default: 1 --out FILE Output directory -v, --verbose Verbose ``` When you run ```bash zpca-counts --help ``` The following message should appear ``` usage: zpca-counts [-h] --counts FILE --lengths FILE [--pseudocount PSEUDOCOUNT] [--filter-not-expressed] --out DIRECTORY [-v] Perform PCA based on an expression matrix (rows are genes/transcripts, columns are samples). optional arguments: -h, --help show this help message and exit --counts FILE Counts table (tsv). The first column should contain the gene/transcript id. The other columns should contain the counts for each sample. --lengths FILE Table of feature lengths (tsv). The file can have two types of formats. First option: The first column should contain the gene/transcript id. The second column should contain the corresponding lengths Second option: The first column should contain the gene/transcript id. The rest of the columns should contain the gene/transcript lengths for each of the samples Note that the sample names should be the same the sample names of the counts. --pseudocount PSEUDOCOUNT Pseudocount to add in the count table. Default: 1 --filter-not-expressed Filter not expressed genes/transcripts (0 counts for all samples). --out DIRECTORY Output directory -v, --verbose Verbose ``` # Docker Pull image ```bash docker pull zavolab/zpca ``` Run ```bash docker run -it zavolab/zpca zpca --help ``` # Singularity Pull image ```bash singularity pull docker://zavolab/zpca ``` Run ```bash singularity exec zpca_latest.sif zpca --help ```
zpca
/zpca-0.8.3.tar.gz/zpca-0.8.3/README.md
README.md
Used ---- To use, simple do:: >>> from zalopaysupport import prepareResourceBeforeUpload, uploadImagesToZPSVN >>> input = './images' >>> output = './output' >>> subFolderOnSVN = 'subfolder' >>> prepareResourceBeforeUpload(input, target) >>> uploadImagesToZPSVN(output, subFolderOnSVN) Functions --------- >>> prepareResourceBeforeUpload >>> uploadImagesToZPSVN >>> renameAllFolderAndFile >>> renameToRemoveResolutionSuffix >>> yes_no >>> choose_environment >>> choose_multi_environment Public python package --------------------- >>> python3 setup.py sdist >>> twine check dist/* >>> twine upload dist/*
zpcpssupport
/zpcpssupport-0.4.tar.gz/zpcpssupport-0.4/README.rst
README.rst
====================================== Zoidberg's Preempting Event Dispatcher ====================================== .. image:: https://img.shields.io/circleci/project/github/ZoidBB/zped/master.svg?style=for-the-badge :target: .. image:: https://img.shields.io/pypi/v/zped.svg?style=for-the-badge :target: -------------------------- Why you shouldn't use this -------------------------- ZPED let's you do some truly silly stuff with event dispatching. There's a built-in decorator that will create and execute pre/post execution events on functions, which is pretty cool! Until you realize that your event listeners can arbitrarily modify the execution of your code by raising exceptions. A pre-execution event can completely modify the data sent to the executing function, or even the data sent to other listeners (since they're executed in serial). The same event can even stop execution entirely and force return a value. A post-execution event can do similar. It's insane, it's terrible, it will make your applications /really/ hard to debug. --------------------- Why I even wrote this --------------------- I'm in the process of writing a static website generator based on Flask, and I needed a good way to let plugins tie into the core system. One of the better days to do this is with event dispatching! So I started writing a simple dispatcher, because using an external library for that seemed silly. Then I thought, "If I were insane and writing a plugin to heavily modify the generator's internals, but didn't want to fork the code or monkeypatch... what would I need?" ZPED is the culmination of that, and entirely too much coffee. -------------------------------------------------------------- Ok, but... I don't /have/ to use the bad parts of this, right? -------------------------------------------------------------- No, but power corrupts. -------------------------- Just tell me how to use it -------------------------- Look at the tests, I'll write some docs later.
zped
/zped-0.1.3.tar.gz/zped-0.1.3/README.rst
README.rst
class ZPED: """ A terribly-architected event dispatcher that lets you do entirely too much weird stuff """ class StopExecution(Exception): """Raise this to stop the execution of a triggerman""" def __init__(self, result=None, trigger_post=True): super(ZPED.StopExecution, self).__init__() self.result = result self.trigger_post = trigger_post class ModifyPayload(Exception): """Raise this to modify the payload passed along the call stack""" def __init__(self, *payload): super(ZPED.ModifyPayload, self).__init__() self.payload = payload def __init__(self): self.__events__ = {} def _validate_event(self, event): if event not in self.__events__: raise NameError( "`%s` is not a valid event for %s" % (event, self.__class__)) def on(self, event, callback=None): """Registers a function as a callback. Can be used as a decorator.""" self._validate_event(event) if not callback: # Assume we're being called as a decorator def decorator(callback): '''actual decorator''' self.on(event, callback) return callback return decorator if callback not in self.__events__[event]['callbacks']: self.__events__[event]['callbacks'].append(callback) def register_event(self, event, triggerman=None): """Registers an event with the event dict""" self.__events__[event] = { "callbacks": [], "triggerman": triggerman } def trigger(self, event, *payload): """Runs the event call stack""" self._validate_event(event) for callback in self.__events__[event]['callbacks']: try: callback(*payload) except self.ModifyPayload as exception: payload = exception.payload return payload def triggerman(self, pre_exec=True, post_exec=True): """ Decorator that triggers pre-execution and post-executon events for decorated function. Auto-generates event names if none are passed. This is kinda nutty. Like, I allow for preempting execution by raising an error? WHY?! This allows for some insane shenanigans, and none of the code in here should ever be used in production, or in any other project. Just don't ok? But use FrostyMug, it's fun. """ def decorator(function): '''actual decorator''' funcpath = ".".join(function.__qualname__.split(".")[-2:]) if pre_exec is True: pre_exec_name = ".".join((funcpath, "pre-exec")) elif isinstance(pre_exec, str): pre_exec_name = pre_exec if post_exec is True: post_exec_name = ".".join((funcpath, "post-exec")) elif isinstance(pre_exec, str): post_exec_name = post_exec if pre_exec: self.register_event(pre_exec_name, function) if post_exec: self.register_event(post_exec_name, function) def decorated(*args, **kwargs): '''decorated function''' stop_exec = False trigger_post = True if pre_exec: try: args, kwargs = self.trigger( pre_exec_name, args, kwargs) except self.StopExecution as exception: result = exception.result trigger_post = exception.trigger_post stop_exec = True # I'm literally checking whether we got an exception in that # if statement, so if we did I can check other bits... wtf? # This is why I love Python. I can do all sorts of really, # really terrible things with it. if not stop_exec: result = function(*args, **kwargs) else: if not trigger_post: return result if post_exec: args, kwargs, result = self.trigger( post_exec_name, args, kwargs, result) return result decorated.__name__ = function.__name__ # clone origin function name return decorated return decorator
zped
/zped-0.1.3.tar.gz/zped-0.1.3/zped.py
zped.py
# zpenv # Langue/Language [English Version](#EN-Informations) # Informations Outil multi-plateforme de gestion d'environnement virtuel Python pour la création, l'édition, la suppression ou le travail avec un environnement virtuel.<br> Tout se passe directement en console.<br> Il est possible de migrer ces anciens environnements virtuels sur cette solution. ## Prerequis - Python 3 <br> # Installation ```console pip install zpenv ``` <br> # Utilisation ## Affichage de toutes les commandes disponibles ```console [user@host ~]$ zpenv -h ``` <br> ## Installation d'un environnement ```console [user@host ~]$ zpenv --install [NomEnvironnement] ``` >- --name = Donner un nom à notre environnement >- --tag = Ajouter des tags (séparés avec ,) >- --comment = Ajouter un commentaire >- --projectfolder = Spécifier le dossier du projet (emplacement du code) (D'autres options sont disponibles) <br> ## Suppression d'un environnement ```console [user@host ~]$ zpenv --remove [NomEnvironnement] ``` > --nopurge = Ne pas supprimer le dossier de l'environnement Le dossier du projet ne sera jamais supprimé <br> ## Migration d'un environnement Permet de récupérer la gestion d'un environnement créé par venv ou virtualenv par exemple. ```console [user@host ~]$ zpenv --migrate [CheminVersEnvironnement] ``` Si aucun chemin n'est spécifié, l'app prendra le répertoire courant. <br><br> ## Lister les environnements disponibles ```console [user@host ~]$ zpenv --list - Project1 - Project2 ``` <br> ## Afficher les informations d'un environnement ```console [user@host ~]$ zpenv --info [NomEnvironnement] Environment name: Project1 Environment path: C:\Users\zephyroff\Desktop\ENV Environment version: 3.10.8 Environment tag: ProjectConsole,TabBar Project Folder: C:\Users\zephyroff\Desktop\ENVCode ``` <br> ## Ouverture d'un environnement Pour activer l'environnement virtuel et commencer à travailler dessus, il faut l'ouvrir. ```console [user@host ~]$ zpenv --open [NomDeLEnvironnement] ``` > --shell = Pour entrer directement dans le shell Python <br> ## Gestion de package ### Installer un package ```console [user@host ~]$ zpenv --installmodule [package] ``` ou pour installer des packages depuis un fichier requirement ```console [user@host ~]$ zpenv --requirement [RequirementFile] ``` ### Supprimer un package ```console [user@host ~]$ zpenv --removemodule [package] ``` ### Mettre à jour un package ```console [user@host ~]$ zpenv --upgrademodule [package] ``` <br><br> # EN - Informations Cross-platform Python virtual environment management tool for creating, editing, deleting, or working with a virtual environment.<br> Everything happens directly in console.<br> It is possible to migrate these old virtual environments to this solution. ## Prerequisites -Python 3 <br> # Installation ```console pip install zpenv ``` <br> # Use ## Showing all available commands ```console [user@host ~]$ zpenv -h ``` <br> ## Installing an environment ```console [user@host ~]$ zpenv --install [EnvironmentName] ``` >- --name = Give a name to our environment >- --tag = Add tags (separated with ,) >- --comment = Add a comment >- --projectfolder = Specify project folder (code location) (Other options are available) <br> ## Deleting an environment ```console [user@host ~]$ zpenv --remove [EnvironmentName] ``` > --nopurge = Don't delete environment folder The project folder will never be deleted <br> ## Migrating an environment Allows to recover the management of an environment created by venv or virtualenv for example. ```console [user@host ~]$ zpenv --migrate [PathToEnvironment] ``` If no path is specified, the app will take the current directory. <br><br> ## List available environments ```console [user@host ~]$ zpenv --list -Project1 -Project2 ``` <br> ## Display environment information ```console [user@host ~]$ zpenv --info [EnvironmentName] Environment name: Project1 Environment path: C:\Users\zephyroff\Desktop\ENV Environment version: 3.10.8 Environment tag: ProjectConsole,TabBar Project Folder: C:\Users\zephyroff\Desktop\ENVCode ``` <br> ## Opening an environment To activate the virtual environment and start working on it, you must open it. ```console [user@host ~]$ zpenv --open [EnvironmentName] ``` > --shell = To enter the Python shell directly <br> ## Package management ### Install a package ```console [user@host ~]$ zpenv --installmodule [package] ``` or to install packages from a requirement file ```console [user@host ~]$ zpenv --requirement [RequirementFile] ``` ### Delete a package ```console [user@host ~]$ zpenv --removemodule [package] ``` ### Update a package ```console [user@host ~]$ zpenv --upgrademodule [package] ```
zpenv
/zpenv-1.0.2.tar.gz/zpenv-1.0.2/README.md
README.md
History ======= 1.0b2 (2016-08-04) ------------------ - Fix: Name of a single transform may contaibn dots. They are now replaced by ``_``. [jensens] - Fix: The root element of a path was not shown on the same level as all other paths. Now it is shown as ``__root__`` [jensens] - Feature: It was not possible to filter by virtual host in environment with more than one site per Zope. A new configuration option ``virtualhost`` was introduced. If set to on, the virtualhost name will be inserted before ``PATH``. [jensens] - Support: In order to make a test installation easier, an example docker-compose setup was added to the Github repository together with some documentation in the README.rst. [jensens] 1.0b1 (2016-08-04) ------------------ - Added subscribers to ``plone.transformchain`` events. New setup extra ``[plone]``. Removed one patch for diazo transform. Made ``publish.beforecommit`` less fuzzy in Plone. [jensens] 1.0a7 (2016-08-03) ------------------ - Fix: virtual path config in ZMetric class. [syzn] 1.0a6 (2016-07-28) ------------------ - Feature: New value publish.commit. Delta time used from publish.beforecommit to request end. [jensens] - Fix: publish.sum shows now overall time of request processing. [jensens] - Fix: Update README to reflect last changes. [jensens] - Use more beautiful paths if VirtualHostMonster is used. [syzn] 1.0a5 (2016-06-28) ------------------ - Fix: Before/after hooks were not assigned correctly. [jensens] 1.0a4 (2016-06-10) ------------------ - Fixes measurements of zope request, also add more detailed metrics. [jensens] 1.0a3 (2016-06-09) ------------------ - Measure time a zope request needs. [jensens] 1.0a2 (2016-03-22) ------------------ - Refactored: ZConfig best practice [jensens] - Fix: Strip trailing dot from prefix [jensens] 1.0a1 (2016-03-22) ------------------ - Fix: README was wrong. [jensens] 1.0a0 (2016-03-22) ------------------ - made it work [jensens, 2016-03-17]
zperfmetrics
/zperfmetrics-1.0b2.tar.gz/zperfmetrics-1.0b2/CHANGES.rst
CHANGES.rst
.. contents:: Table of Contents :depth: 2 Perfmetrics configuration for Zope and Plone ============================================ zperfmetrics works like and depends on `perfmetrics <https://pypi.python.org/pypi/perfmetrics>`_, additional it: - offers a ZConfig configuration for the statsd, - uses the current requests path in the statd dotted path prefix, - also provides a patch to measure plone.app.theming for diazo compile and diazo transform if Plone is available, Installation ============ First get your ``statsd`` configured properly. This is out of scope of this module. Depend on this module in your packages ``setup.py``. Given you use ``zc.builodut`` to set up your Zope2 or Plone, add to your ``[instance]`` section or the section with ``recipe = plone.recipe.zope2instance`` the lines:: [instance01] recipe = plone.recipe.zope2instance ... zope-conf-imports = zperfmetrics zope-conf-additional = <perfmetrics> uri statsd://localhost:8125 before MyFancyProject hostname on virtualhost on after ${:_buildout_section_name_} </perfmetrics> ... Given this runs on a host called ``w-plone1``, this will result in a prefix ``MyFancyProject.w-plone1.instance01``. With ``virtualhost on`` all zperfmetrics will get a prefix like ``MyFancyProject.w-plone1.instance01.www-theater-at`` uri Full URI of statd. before Prefix path before the hostname. hostname Get hostname and insert into prefix. (Boolean: ``on`` or ``off``) virtualhost Get virtualhost and use in ZPerfmetrics after the static prefix. (Boolean: ``on`` or ``off``) after Prefix path after the hostname. Usage ===== You need to decorate your code or use the ``with`` statement to measure a code block. Usage:: from zperfmetrics import ZMetric from zperfmetrics import zmetric from zperfmetrics import zmetricmethod @zmetric def some_function(): # whole functions timing and call counts will be measured pass @ZMetric(stat='a_custom_prefix') def some_other_function(): # set a custom prefix instead of module path and fucntion name. pass class Foo(object): @zmetricmethod def some_method(self): # whole methods timing and call counts will be measured pass @ZMetric(method=True, timing=False): def some_counted_method(self): # whole methods number of calls will be measured, but no times pass @ZMetric(method=True, count=False): def some_timed_method(self): # whole methods timing be measured, but no counts pass def some_method_partly_measured(self): # do something here you dont want to measure with ZMetric(stat='part_of_other_method_time'): # do something to measure # call counts and timing will be measured pass # do something here you dont want to measure @ZMetric(method=True, rate=0.5): def some_random_recorded_method(self): # randomly record 50% of the calls. pass Request Lifecycle Integration ============================= Zope ---- This package provides subscribers to measure the time a request takes, including some points in time between. These subscribers are loaded via zcml and are logging under ``publish.*``: ``publish.traversal`` time needed from publication start until traversal is finished. ``publish.rendering`` time needed from traversal end until before commit begin. ``publish.beforecommit`` time needed from rendering end until database commit begins. This value is a bit fuzzy and should be taken with a grain of salt, because there can be other subscribers to this event which take their time. Since the order of execution of the subscribers is not defined, processing may happen after this measurement Future improvements planned here. ``publish.commit`` time needed from rendering end until database commit is done. ``publish.sum`` whole time needed from publication start until request is completly processed. Plone ----- Installing this package in Plone by depending on ``zperfmetrics[plone]`` forces usage of ``plone.transformchain`` version 1.2 or newer. First, ``publish.beforecommit`` gets less fuzzy because the expensive transforms (also subscribers to publish.beforecommit) are all done. Then it introduces new measurements related to ``plone.transformchain``: ``publish.transforms`` time needed for all transforms in the ``plone.transformchain``. This usually includes Diazo. ``publish.transform.${ORDER}-${TRANSFORMNAME}`` time needed for a specific single transform. transforms are ordered and named, both are replaced. This package patches: ``diazo.setup`` metric ``plone.app.theming.transform.ThemeTransform.setupTransform`` is patched as a basic (path-less) perfmetrics ``Metric``. The setup of the transform happens once on startup and is the time needed to create the Diazo xslt from its rules.xml, index.html and related files. Statd, Graphite & Grafana in Docker =================================== Setting up Statsd, Graphite and Grafana can be complex. For local testing - but also for production environments - firing up some docker containers comes in handy. A very minimal version of such a `Statd, Graphite & Grafana in Docker setup <https://github.com/collective/zperfmetrics/tree/master/docker>`_ (`original <https://github.com/Ennexa/docker-graphite>`_) helps getting things initially up and running. `Install Docker <https://docs.docker.com/engine/installation/>`_ and `install docker-compose <https://docs.docker.com/compose/install/>`_ (just ``pip install docker-compose``), then just clone the repository and in its ``docker`` directory run ``docker-compose up -d``. Let Zperfmetrics point to ``uri statsd://localhost:8125`` and collect some data. Open Grafana in your browser at ``http://localhost:3000``. Go first to `Grafana Getting Started <http://docs.grafana.org/guides/gettingstarted/>`_, the 10 minute video *really helps* to find the hidden part of its UI. Source Code =========== The sources are in a GIT DVCS with its main branches at `github <https://github.com/collective/zperfmetrics>`_. We'd be happy to see many branches, forks and pull-requests to make zperfmetrics even better. Contributors ============ - Jens W. Klein <[email protected]> - Zalán Somogyváry
zperfmetrics
/zperfmetrics-1.0b2.tar.gz/zperfmetrics-1.0b2/README.rst
README.rst
License ======= Copyright (c) 2016, BlueDynamics Alliance, Austria, Germany, Switzerland 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 BlueDynamics Alliance 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 BlueDynamics Alliance ``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 BlueDynamics Alliance 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.
zperfmetrics
/zperfmetrics-1.0b2.tar.gz/zperfmetrics-1.0b2/LICENSE.rst
LICENSE.rst
import logging import threading from contextlib import contextmanager from time import sleep import psycopg2 import psycopg2.extras log = logging.getLogger(__name__) logFormat = logging.Formatter( fmt="%(asctime)s.%(msecs)03d %(levelname).3s | %(name)s | %(message)s", datefmt="%Y/%m/%d %H:%M:%S", ) log.setLevel(logging.WARNING) logHandler = logging.StreamHandler() logHandler.setFormatter(logFormat) log.addHandler(logHandler) # log.setLevel(logging.DEBUG) __VERSION__ = "0.5.0" __AUTHOR__ = "Antonio Zanardo <[email protected]>" _HOST = _PORT = _DB = _USER = _PASS = None _local = threading.local() def config_connection( host: str, port: int, user: str, password: str, database: str ): """ Configures the connection parameters """ log.debug("configuring connection:") log.debug(" host = %s", host) log.debug(" port = %d", port) log.debug(" user = %s", user) log.debug(" db = %s", database) global _HOST, _PORT, _USER, _PASS, _DB _HOST = host _PORT = port _USER = user _PASS = password _DB = database def getdb() -> psycopg2.extensions.connection: """ Returns a database connection handlers. Reuse thread-local connections. """ if not hasattr(_local, "dbh"): log.debug("opening a new database connection") _local.dbh = psycopg2.connect( host=_HOST, port=_PORT, database=_DB, user=_USER, password=_PASS, cursor_factory=psycopg2.extras.DictCursor, ) _local.trans = 0 else: log.debug("reusing database connection %s", id(_local.dbh)) return _local.dbh def deldbh(): """ Forces a database disconnection. """ if hasattr(_local, "dbh"): log.debug("forcing disconnection of %s", id(_local.dbh)) try: _local.dbh.close() except psycopg2.Error: pass del _local.dbh @contextmanager def trans(): """ Wraps a transaction. """ log.debug("starting new trans() context") if not hasattr(_local, "trans"): _local.trans = 0 if _local.trans == 0: # Checking if connection to database is alive. We will reconnect in # case the connection was lost. This will add latency but can deal # with persistent connection problems after PostgreSQL is restarted. tries = 0 while True: try: log.debug("checking if database connection is alive") dbh = getdb() c = dbh.cursor() c.execute("select 1") c.fetchone() except psycopg2.Error: log.debug("database connection is lost") log.exception("exception: ") deldbh() tries += 1 else: break if tries > 10: log.debug("aborting reconnection atempt") break else: log.debug("sleeping for 1 second before trying to reconnect") sleep(1) _local.trans += 1 log.debug("open transactions: %d", _local.trans) # Wrapping a transaction. try: log.debug("entering user context") dbh = getdb() c = dbh.cursor() yield c log.debug("returning from user context") except: log.debug("exception caught, lets rollback") try: dbh.rollback() dbh.close() except psycopg2.Error: log.debug("error trying to rollback") pass deldbh() raise else: _local.trans -= 1 if _local.trans == 0: dbh.commit() log.debug("commiting")
zpgdb
/zpgdb-0.5.0-py3-none-any.whl/zpgdb.py
zpgdb.py
zpl === Python ZPL2 Library generates ZPL2 code which can be sent to Zebra or similar label printers. The library uses only Millimeter as unit and converts them internally according to printer settings. Example use ----------- .. code-block:: python import os from PIL import Image import zpl l = zpl.Label(100,60) height = 0 l.origin(0,0) l.write_text("Problem?", char_height=10, char_width=8, line_width=60, justification='C') l.endorigin() height += 13 image_width = 5 l.origin((l.width-image_width)/2, height) image_height = l.write_graphic( Image.open(os.path.join(os.path.dirname(zpl.__file__), 'trollface-large.png')), image_width) l.endorigin() height += image_height + 5 l.origin(10, height) l.barcode('U', '07000002198', height=70, check_digit='Y') l.endorigin() l.origin(32, height) l.barcode('Q', 'https://github.com/cod3monk/zpl/', magnification=5) l.endorigin() height += 20 l.origin(0, height) l.write_text('Happy Troloween!', char_height=5, char_width=4, line_width=60, justification='C') l.endorigin() print(l.dumpZPL()) l.preview() This will display the following preview image, generated using the `Labelary API <http://labelary.com/>`_: `label preview <http://api.labelary.com/v1/printers/12dpmm/labels/2.362205x2.181102/0/^XA^FO0,0^A0N,120,96^FB720,1,0,C,0^FDProblem?\&^FS^FO330,156^GFA,768,384,8,00003FFFC0000000000600000FF0000000180200C01F8000003008000000600000204080440D10000041080000000C000082420000CC020000840002000102000100200001008000010040000000800002000FF80000010006003F84003E01800C036F8200E100C01402307101FE01202878000E030000A071060200010001504201FC0000007C50821000000106C090A438000001800010A466001E0040115084A183C80070103042107009C044382060104E0800803A20300C40E00700F840380FE03C0003D8001A047021F83C588004027E2021845880020227E021047880020141F82187F8800100C07FFFFFF88001004047FFFFF88000803040FFFFF88000C00880419970800060078001117080001241C00012608000089038C237C08000060401FFF8008000011080000020000000C21040E0044000003863C0010840000006060000104000000180380080400000006000000080000000180000008000000007800001000000000038000600000000000380180000000000003FC000^FS^FO120,264^BUN,70,Y,N,Y^FD07000002198^FS^FO384,264^BQN,2,5,Q,7^FDQA,https://github.com/cod3monk/zpl/^FS^FO0,504^A0N,60,48^FB720,1,0,C,0^FDHappy Troloween!\&^FS^XZ>`_ The generated ZPL2 code is: :: ^XA^FO0,0^A0N,120,96^FB720,1,0,C,0^FDProblem?\&^FS^FO330,156^GFA,768,384,8,00003FFFC0000000000600000FF0000000180200C01F8000003008000000600000204080440D10000041080000000C000082420000CC020000840002000102000100200001008000010040000000800002000FF80000010006003F84003E01800C036F8200E100C01402307101FE01202878000E030000A071060200010001504201FC0000007C50821000000106C090A438000001800010A466001E0040115084A183C80070103042107009C044382060104E0800803A20300C40E00700F840380FE03C0003D8001A047021F83C588004027E2021845880020227E021047880020141F82187F8800100C07FFFFFF88001004047FFFFF88000803040FFFFF88000C00880419970800060078001117080001241C00012608000089038C237C08000060401FFF8008000011080000020000000C21040E0044000003863C0010840000006060000104000000180380080400000006000000080000000180000008000000007800001000000000038000600000000000380180000000000003FC000^FS^FO120,264^BUN,70,Y,N,Y^FD07000002198^FS^FO384,264^BQN,2,5,Q,7^FDQA,https://github.com/cod3monk/zpl/^FS^FO0,504^A0N,60,48^FB720,1,0,C,0^FDHappy Troloween!\&^FS^XZ Installation ------------ :: pip install --user zpl Requirements ------------ * PIL or Pillow
zpl
/zpl-0.1.10.tar.gz/zpl-0.1.10/README.rst
README.rst
import binascii import math try: from PIL import ImageOps except: ImageOps = None try: strcast = unicode except: strcast = str # Constants for the printer configuration management CONF_RELOAD_FACTORY = 'F' CONF_RELOAD_NETWORK_FACTORY = 'N' CONF_RECALL_LAST_SAVED = 'R' CONF_SAVE_CURRENT = 'S' # Command arguments names ARG_FONT = 'font' ARG_HEIGHT = 'height' ARG_WIDTH = 'width' ARG_ORIENTATION = 'orientation' ARG_THICKNESS = 'thickness' ARG_BLOCK_WIDTH = 'block_width' ARG_BLOCK_LINES = 'block_lines' ARG_BLOCK_SPACES = 'block_spaces' ARG_BLOCK_JUSTIFY = 'block_justify' ARG_BLOCK_LEFT_MARGIN = 'block_left_margin' ARG_CHECK_DIGITS = 'check_digits' ARG_INTERPRETATION_LINE = 'interpretation_line' ARG_INTERPRETATION_LINE_ABOVE = 'interpretation_line_above' ARG_STARTING_MODE = 'starting_mode' ARG_SECURITY_LEVEL = 'security_level' ARG_COLUMNS_COUNT = 'columns_count' ARG_ROWS_COUNT = 'rows_count' ARG_TRUNCATE = 'truncate' ARG_MODE = 'mode' ARG_MODULE_WIDTH = 'module_width' ARG_BAR_WIDTH_RATIO = 'bar_width_ratio' ARG_REVERSE_PRINT = 'reverse_print' ARG_IN_BLOCK = 'in_block' ARG_COLOR = 'color' ARG_ROUNDING = 'rounding' ARG_DIAMETER = 'diameter' ARG_DIAGONAL_ORIENTATION = 'diagonal_orientation' ARG_MODEL = 'model' ARG_MAGNIFICATION_FACTOR = 'magnification_factor' ARG_ERROR_CORRECTION = 'error_correction' ARG_MASK_VALUE = 'mask_value' # Model values MODEL_ORIGINAL = 1 MODEL_ENHANCED = 2 # Error Correction ERROR_CORRECTION_ULTRA_HIGH = 'H' ERROR_CORRECTION_HIGH = 'Q' ERROR_CORRECTION_STANDARD = 'M' ERROR_CORRECTION_HIGH_DENSITY = 'L' # Boolean values BOOL_YES = 'Y' BOOL_NO = 'N' # Orientation values ORIENTATION_NORMAL = 'N' ORIENTATION_ROTATED = 'R' ORIENTATION_INVERTED = 'I' ORIENTATION_BOTTOM_UP = 'B' # Diagonal lines orientation values DIAGONAL_ORIENTATION_LEFT = 'L' DIAGONAL_ORIENTATION_RIGHT = 'R' # Justify values JUSTIFY_LEFT = 'L' JUSTIFY_CENTER = 'C' JUSTIFY_JUSTIFIED = 'J' JUSTIFY_RIGHT = 'R' # Font values FONT_DEFAULT = '0' FONT_9X5 = 'A' FONT_11X7 = 'B' FONT_18X10 = 'D' FONT_28X15 = 'E' FONT_26X13 = 'F' FONT_60X40 = 'G' FONT_21X13 = 'H' # Color values COLOR_BLACK = 'B' COLOR_WHITE = 'W' # Barcode types BARCODE_CODE_11 = 'code_11' BARCODE_INTERLEAVED_2_OF_5 = 'interleaved_2_of_5' BARCODE_CODE_39 = 'code_39' BARCODE_CODE_49 = 'code_49' BARCODE_PDF417 = 'pdf417' BARCODE_EAN_8 = 'ean-8' BARCODE_UPC_E = 'upc-e' BARCODE_CODE_128 = 'code_128' BARCODE_EAN_13 = 'ean-13' BARCODE_QR_CODE = 'qr_code' class Zpl2(object): """ ZPL II management class Allows to generate data for Zebra printers """ def __init__(self): self.encoding = 'utf-8' self.initialize() def initialize(self): self._buffer = [] def output(self): """ Return the full contents to send to the printer """ return '\n'.encode(self.encoding).join(self._buffer) def _enforce(self, value, minimum=1, maximum=32000): """ Returns the value, forced between minimum and maximum """ return min(max(minimum, value), maximum) def _write_command(self, data): """ Adds a complete command to buffer """ self._buffer.append(strcast(data).encode(self.encoding)) def _generate_arguments(self, arguments, kwargs): """ Generate a zebra arguments from an argument names list and a dict of values for these arguments @param arguments : list of argument names, ORDER MATTERS @param kwargs : list of arguments values """ command_arguments = [] # Add all arguments in the list, if they exist for argument in arguments: if kwargs.get(argument, None) is not None: if isinstance(kwargs[argument], bool): kwargs[argument] = kwargs[argument] and BOOL_YES or BOOL_NO command_arguments.append(kwargs[argument]) # Return a zebra formatted string, with a comma between each argument return ','.join(map(str, command_arguments)) def print_width(self, label_width): """ Defines the print width setting on the printer """ self._write_command('^PW%d' % label_width) def configuration_update(self, active_configuration): """ Set the active configuration on the printer """ self._write_command('^JU%s' % active_configuration) def label_start(self): """ Adds the label start command to the buffer """ self._write_command('^XA') def label_encoding(self): """ Adds the label encoding command to the buffer Fixed value defined to UTF-8 """ self._write_command('^CI28') def label_end(self): """ Adds the label start command to the buffer """ self._write_command('^XZ') def label_home(self, left, top): """ Define the label top left corner """ self._write_command('^LH%d,%d' % (left, top)) def _field_origin(self, right, down): """ Define the top left corner of the data, from the top left corner of the label """ return '^FO%d,%d' % (right, down) def _font_format(self, font_format): """ Send the commands which define the font to use for the current data """ arguments = [ARG_FONT, ARG_HEIGHT, ARG_WIDTH] # Add orientation in the font name (only place where there is # no comma between values) font_format[ARG_FONT] += font_format.get( ARG_ORIENTATION, ORIENTATION_NORMAL) # Check that the height value fits in the allowed values if font_format.get(ARG_HEIGHT) is not None: font_format[ARG_HEIGHT] = self._enforce( font_format[ARG_HEIGHT], minimum=10) # Check that the width value fits in the allowed values if font_format.get(ARG_WIDTH) is not None: font_format[ARG_WIDTH] = self._enforce( font_format[ARG_WIDTH], minimum=10) # Generate the ZPL II command return '^A' + self._generate_arguments(arguments, font_format) def _field_block(self, block_format): """ Define a maximum width to print some data """ arguments = [ ARG_BLOCK_WIDTH, ARG_BLOCK_LINES, ARG_BLOCK_SPACES, ARG_BLOCK_JUSTIFY, ARG_BLOCK_LEFT_MARGIN, ] return '^FB' + self._generate_arguments(arguments, block_format) def _barcode_format(self, barcodeType, barcode_format): """ Generate the commands to print a barcode Each barcode type needs a specific function """ def _code11(**kwargs): arguments = [ ARG_ORIENTATION, ARG_CHECK_DIGITS, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ] return '1' + self._generate_arguments(arguments, kwargs) def _interleaved2of5(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ARG_CHECK_DIGITS, ] return '2' + self._generate_arguments(arguments, kwargs) def _code39(**kwargs): arguments = [ ARG_ORIENTATION, ARG_CHECK_DIGITS, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ] return '3' + self._generate_arguments(arguments, kwargs) def _code49(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_STARTING_MODE, ] # Use interpretation_line and interpretation_line_above to generate # a specific interpretation_line value if kwargs.get(ARG_INTERPRETATION_LINE) is not None: if kwargs[ARG_INTERPRETATION_LINE]: if kwargs[ARG_INTERPRETATION_LINE_ABOVE]: # Interpretation line after kwargs[ARG_INTERPRETATION_LINE] = 'A' else: # Interpretation line before kwargs[ARG_INTERPRETATION_LINE] = 'B' else: # No interpretation line kwargs[ARG_INTERPRETATION_LINE] = 'N' return '4' + self._generate_arguments(arguments, kwargs) def _pdf417(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_SECURITY_LEVEL, ARG_COLUMNS_COUNT, ARG_ROWS_COUNT, ARG_TRUNCATE, ] return '7' + self._generate_arguments(arguments, kwargs) def _ean8(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ] return '8' + self._generate_arguments(arguments, kwargs) def _upce(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ARG_CHECK_DIGITS, ] return '9' + self._generate_arguments(arguments, kwargs) def _code128(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ARG_CHECK_DIGITS, ARG_MODE, ] return 'C' + self._generate_arguments(arguments, kwargs) def _ean13(**kwargs): arguments = [ ARG_ORIENTATION, ARG_HEIGHT, ARG_INTERPRETATION_LINE, ARG_INTERPRETATION_LINE_ABOVE, ] return 'E' + self._generate_arguments(arguments, kwargs) def _qrcode(**kwargs): arguments = [ ARG_ORIENTATION, ARG_MODEL, ARG_MAGNIFICATION_FACTOR, ARG_ERROR_CORRECTION, ARG_MASK_VALUE, ] return 'Q' + self._generate_arguments(arguments, kwargs) barcodeTypes = { BARCODE_CODE_11: _code11, BARCODE_INTERLEAVED_2_OF_5: _interleaved2of5, BARCODE_CODE_39: _code39, BARCODE_CODE_49: _code49, BARCODE_PDF417: _pdf417, BARCODE_EAN_8: _ean8, BARCODE_UPC_E: _upce, BARCODE_CODE_128: _code128, BARCODE_EAN_13: _ean13, BARCODE_QR_CODE: _qrcode, } return '^B' + barcodeTypes[barcodeType](**barcode_format) def _barcode_field_default(self, barcode_format): """ Add the data start command to the buffer """ arguments = [ ARG_MODULE_WIDTH, ARG_BAR_WIDTH_RATIO, ] return '^BY' + self._generate_arguments(arguments, barcode_format) def _field_data_start(self): """ Add the data start command to the buffer """ return '^FD' def _field_reverse_print(self): """ Allows the printed data to appear white over black, or black over white """ return '^FR' def _field_data_stop(self): """ Add the data stop command to the buffer """ return '^FS' def _field_data(self, data): """ Add data to the buffer, between start and stop commands """ command = '{start}{data}{stop}'.format( start=self._field_data_start(), data=data, stop=self._field_data_stop(), ) return command def font_data(self, right, down, field_format, data): """ Add a full text in the buffer, with needed formatting commands """ reverse = '' if field_format.get(ARG_REVERSE_PRINT, False): reverse = self._field_reverse_print() block = '' if field_format.get(ARG_IN_BLOCK, False): block = self._field_block(field_format) command = '{origin}{font_format}{reverse}{block}{data}'.format( origin=self._field_origin(right, down), font_format=self._font_format(field_format), reverse=reverse, block=block, data=self._field_data(data), ) self._write_command(command) def barcode_data(self, right, down, barcodeType, barcode_format, data): """ Add a full barcode in the buffer, with needed formatting commands """ command = '{default}{origin}{barcode_format}{data}'.format( default=self._barcode_field_default(barcode_format), origin=self._field_origin(right, down), barcode_format=self._barcode_format(barcodeType, barcode_format), data=self._field_data(data), ) self._write_command(command) def graphic_box(self, right, down, graphic_format): """ Send the commands to draw a rectangle """ arguments = [ ARG_WIDTH, ARG_HEIGHT, ARG_THICKNESS, ARG_COLOR, ARG_ROUNDING, ] # Check that the thickness value fits in the allowed values if graphic_format.get(ARG_THICKNESS) is not None: graphic_format[ARG_THICKNESS] = self._enforce( graphic_format[ARG_THICKNESS]) # Check that the width value fits in the allowed values if graphic_format.get(ARG_WIDTH) is not None: graphic_format[ARG_WIDTH] = self._enforce( graphic_format[ARG_WIDTH], minimum=graphic_format[ARG_THICKNESS]) # Check that the height value fits in the allowed values if graphic_format.get(ARG_HEIGHT) is not None: graphic_format[ARG_HEIGHT] = self._enforce( graphic_format[ARG_HEIGHT], minimum=graphic_format[ARG_THICKNESS]) # Check that the rounding value fits in the allowed values if graphic_format.get(ARG_ROUNDING) is not None: graphic_format[ARG_ROUNDING] = self._enforce( graphic_format[ARG_ROUNDING], minimum=0, maximum=8) # Generate the ZPL II command command = '{origin}{data}{stop}'.format( origin=self._field_origin(right, down), data='^GB' + self._generate_arguments(arguments, graphic_format), stop=self._field_data_stop(), ) self._write_command(command) def graphic_diagonal_line(self, right, down, graphic_format): """ Send the commands to draw a rectangle """ arguments = [ ARG_WIDTH, ARG_HEIGHT, ARG_THICKNESS, ARG_COLOR, ARG_DIAGONAL_ORIENTATION, ] # Check that the thickness value fits in the allowed values if graphic_format.get(ARG_THICKNESS) is not None: graphic_format[ARG_THICKNESS] = self._enforce( graphic_format[ARG_THICKNESS]) # Check that the width value fits in the allowed values if graphic_format.get(ARG_WIDTH) is not None: graphic_format[ARG_WIDTH] = self._enforce( graphic_format[ARG_WIDTH], minimum=3) # Check that the height value fits in the allowed values if graphic_format.get(ARG_HEIGHT) is not None: graphic_format[ARG_HEIGHT] = self._enforce( graphic_format[ARG_HEIGHT], minimum=3) # Check the given orientation graphic_format[ARG_DIAGONAL_ORIENTATION] = graphic_format.get( ARG_DIAGONAL_ORIENTATION, DIAGONAL_ORIENTATION_LEFT) # Generate the ZPL II command command = '{origin}{data}{stop}'.format( origin=self._field_origin(right, down), data='^GD' + self._generate_arguments(arguments, graphic_format), stop=self._field_data_stop(), ) self._write_command(command) def graphic_circle(self, right, down, graphic_format): """ Send the commands to draw a circle """ arguments = [ARG_DIAMETER, ARG_THICKNESS, ARG_COLOR] # Check that the diameter value fits in the allowed values if graphic_format.get(ARG_DIAMETER) is not None: graphic_format[ARG_DIAMETER] = self._enforce( graphic_format[ARG_DIAMETER], minimum=3, maximum=4095) # Check that the thickness value fits in the allowed values if graphic_format.get(ARG_THICKNESS) is not None: graphic_format[ARG_THICKNESS] = self._enforce( graphic_format[ARG_THICKNESS], minimum=2, maximum=4095) # Generate the ZPL II command command = '{origin}{data}{stop}'.format( origin=self._field_origin(right, down), data='^GC' + self._generate_arguments(arguments, graphic_format), stop=self._field_data_stop(), ) self._write_command(command) def graphic_field(self, right, down, pil_image): """ Encode a PIL image into an ASCII string suitable for ZPL printers """ if ImageOps is None: # Importing ImageOps from PIL didn't work raise Exception( 'You must install Pillow to be able to use the graphic' ' fields feature') width, height = pil_image.size rounded_width = int(math.ceil(width / 8.) * 8) # Transform the image : # - Invert the colors (PIL uses 0 for black, ZPL uses 0 for white) # - Convert to monochrome in case it is not already # - Round the width to a multiple of 8 because ZPL needs an integer # count of bytes per line (each pixel is a bit) pil_image = ImageOps.invert(pil_image).convert('1').crop( (0, 0, rounded_width, height)) # Convert the image to a two-character hexadecimal values string ascii_data = binascii.hexlify(pil_image.tobytes()).upper() # Each byte is composed of two characters bytes_per_row = rounded_width / 8 total_bytes = bytes_per_row * height graphic_image_command = ( '^GFA,{total_bytes},{total_bytes},{bytes_per_row},{ascii_data}' .format( total_bytes=total_bytes, bytes_per_row=bytes_per_row, ascii_data=ascii_data.decode(self.encoding), ) ) # Generate the ZPL II command command = '{origin}{data}{stop}'.format( origin=self._field_origin(right, down), data=graphic_image_command, stop=self._field_data_stop(), ) self._write_command(command)
zpl2
/zpl2-1.2.1.tar.gz/zpl2-1.2.1/zpl2.py
zpl2.py
# Z-Plane A handful of freqeuntly used plots when working with discrete systems or digital signal processing in Pyton. Z-Plane is built upon the scipy.signal module, using the `TransferFunction` class to pass all required system information to plot functions in a single object. This allows all plots to be executed in a single line of code, while Z-Plane handles the calculations and setup required to get the perfect plot. The following functions are available: - `freq`: Normalized frequency response - `pz`: Pole-Zero plot - `bode`: Bode plot (Gain and Phase), non logarithmic frequency axis possible - `impulse`: Impulse response - `norm`: Normalize transfer function - `fir2tf`: Get FIR transfer function from impulse response ## Installation ```bash pip install zplane ``` ## Use - Import `zplane` - Call any of the available functions, and pass a valid scipy.signal TransferFunction Have a look at the [examples](https://github.com/Attrup/zplane/blob/main/examples/examples.py) for a quick demonstration on how to use the functions. Please look up the `TransferFunction` [documentation](https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.TransferFunction.html), if you are unsure how to create a valid instance of a `TransferFunction`.
zplane
/zplane-0.1.6.tar.gz/zplane-0.1.6/README.md
README.md
zplgen ====== .. image:: https://travis-ci.org/kolonialno/zplgen.svg?branch=master :target: https://travis-ci.org/kolonialno/zplgen zplgen is a utility library to aid in generating ZPL2 code. The core idiom is the `Command` class, which subclasses `bytes`. Another helper is the `Font` class. Example usage ------------- .. code:: python f_default = Font('V', height=30) label = bytes() label += Command.label_start() label += Command.label_home(30, 0) label += Command.graphic_circle(x=550, y=15, diameter=100, border=6) label += Command.field('?', x=560, y=50, font=f_default(45)) label += Command.field(name, x=0, y=135, font=f_default) label += Command.label_end() send_to_printer(label) Running tests ------------- In the base directory, run the following: .. code:: bash python -m unittest discover -s tests License ------- zplgen is released under the `MIT License`_. .. _Mit License: https://opensource.org/licenses/MIT
zplgen
/zplgen-0.0.6.tar.gz/zplgen-0.0.6/README.rst
README.rst
.. image:: https://travis-ci.org/kylemacfarlane/zplgrf.svg?branch=master :target: https://travis-ci.org/kylemacfarlane/zplgrf .. image:: https://coveralls.io/repos/github/kylemacfarlane/zplgrf/badge.svg?branch=master :target: https://coveralls.io/github/kylemacfarlane/zplgrf?branch=master **UPDATE: If you're only interested in the quality of barcodes when printing then first try using the new center of pixel options in cups-filters 1.11.4.** ====== zplgrf ====== This project contains the utils I made to convert to and from GRF images from ZPL while trying to diagnose why barcodes printed from CUPS on Linux and OSX were so blurry/fuzzy/etc. It also contains my attempt at sharpening the barcodes and a CUPS filter you can setup to try for yourself. Barcode Quality =============== The way CUPS (and at least my Windows driver too) prints PDFs to label printers is by converting the PDF to an image and then embedding that image in ZPL. The problem with this is that all PDF converters seem to aim to maintain font quality and don't care much about the quality of vectors. Often this create unscanable barcodes especially at the low 203 dpi of most label printers. There are a couple of ways around this when generating your own PDFs (a barcode font, snap the barcode to round units, etc.) but they all have their downsides and don't help you if you have to print a label generated by someone else. Originally I tried getting a greyscale image from Ghostscript and converting to mono while maintaining barcode quality but I always ended up destroying the font quality. I noticed that GRFs generated by Windows showed similar artifacting on text and a retail OSX driver says in their guide that their driver may also affect text quality so I think this kind of post processing is possibly what others are doing. In the end I opted for getting a mono image from Ghostscript and then searching the image data to find any suspected barcodes and simply widening the white areas. It's very dumb and simple but works for me. You may need to tweak it for your own labels and there's a good chance it could actually make your barcodes worse. UPDATE: I also added support for the center of pixel rule in Ghostscript when converting from PDFs. This improves barcode quality but also decreases the quality of some text. Installation ============ Run ``pip install zplgrf``. Dependencies ============ Normal installation should handle regular Python dependencies but this project also requires Ghostscript (gs) to be installed. I would recommend installing the newest version of Ghostscript. The tests fail due to slight rendering differences on old versions and the current center of pixel implementation isn't compatible with 9.22-9.26. Using the Python API ==================== Some quick demos. Open a PDF, optimise the barcodes, and show the ZPL:: from zplgrf import GRF with open('source.pdf', 'rb') as pdf: pages = GRF.from_pdf(pdf.read(), 'DEMO') for grf in pages: grf.optimise_barcodes() print(grf.to_zpl()) When converting from PDFs you will get better performance and barcodes by using Ghostscript's center of pixel rule instead of my ``optimise_barcodes()`` method:: from zplgrf import GRF with open('source.pdf', 'rb') as pdf: pages = GRF.from_pdf(pdf.read(), 'DEMO', center_of_pixel=True) for grf in pages: print(grf.to_zpl()) To convert an image instead:: from zplgrf import GRF with open('source.png', 'rb') as image: grf = GRF.from_image(image.read(), 'DEMO') grf.optimise_barcodes() print(grf.to_zpl(compression=3, quantity=1)) # Some random options If the ZPL won't print it's possible that your printer doesn't support ZB64 compressed images so try ``compression=2`` instead. Extract all GRFs from ZPL and save them as PNGs:: from zplgrf import GRF with open('source.zpl', 'r') as zpl: grfs = GRF.from_zpl(zpl.read()) for i, grf in enumerate(grfs): grf.to_image().save('output-%s.png' % i, 'PNG') Optimise all barcodes in a ZPL file:: from zplgrf import GRF with open('source.zpl', 'r') as zpl: print(GRF.replace_grfs_in_zpl(zpl.read())) Arguments for the various methods are documented in the source. Some such as ``to_zpl()`` and ``optimise_barcodes()`` have quite a few arguments that may need tweaking for your purposes. Using the CUPS Filter ===================== Install the package normally and then copy ``pdftozpl`` to your CUPS filter directory which is usually ``/usr/lib/cups/filter``. Make sure that the copied file has the same permissions as the other filters in the folder. Now edit the PPD file for your printer which is usually in ``/etc/cups/ppd``. Find the lines containing ``*cupsFilter`` and add the following below them:: *cupsFilter2: "application/pdf application/octet-stream 50 pdftozpl" Now restart CUPS and this new filter will take affect. Note that ``*cupsFilter2`` filters require CUPS 1.5+ and they disable all regular ``*cupsFilter`` filters so you may need to setup more filters for other mimetypes. ``application/octet-stream`` is the mimetype CUPS uses for raw printing which is what we want to send raw ZPL to the printer. Performance =========== Performance of the CUPS filter is pretty bad in comparison to the native filters written in C. On a Raspberry Pi 3 it takes about 2.5s to run but is low 100s of ms on a decent computer.
zplgrf
/zplgrf-1.6.0.tar.gz/zplgrf-1.6.0/README.rst
README.rst
ZPlogger ======= Zpower日志工具 ### Usage > from zplogger.logger import Logger logger = Logger( file=__file__, user='yulong', project="shouma", server="127.0.0.1", debug=True) log_msg = ''' this is a test msg for test logger in multiplelines. Stack messag: xxxx more stack info.. ''' # warning message logger.warn(sys._getframe().f_lineno, log_msg) # info message logger.info(sys._getframe().f_lineno, log_msg) # error message logger.error(sys._getframe().f_lineno, log_msg)
zplogger
/zplogger-0.1.2.tar.gz/zplogger-0.1.2/README.md
README.md
zpm === Supported Python versions: 2.6, 2.7, 3.3, and 3.4. .. image:: http://ci.oslab.cc/job/zpm/badge/icon :alt: Build Status :target: http://ci.oslab.cc/job/zpm/ ZPM is a package manger for ZeroVM_. You use it to create and deploy ZeroVM applications onto ZeroCloud_. .. _ZeroVM: http://zerovm.org/ .. _ZeroCloud: https://github.com/zerovm/zerocloud/ Documentation ------------- The documentation is hosted at `docs.zerovm.org`__. .. __: http://docs.zerovm.org/projects/zerovm-zpm/en/latest/ Installation ------------ You can install ``zpm`` using ``pip``:: $ pip install zpm Contact ------- Please use the `zerovm mailing list`__ on Google Groups for anything related to zpm. You are also welcome to come by `#zerovm on irc.freenode.net`__ where the developers can be found. .. __: https://groups.google.com/forum/#!forum/zerovm .. __: http://webchat.freenode.net/?channels=zerovm Changelog --------- 0.3 (2014-10-22): This release adds new features and fixes bugs. The main change is that it is now possible to leave out the `ui` key from the zapp configuration. Before that would signal that the default web interface should be generated by `zpm deploy`, it now means no web interface. To get the default interface, specify `--with-ui` when running `zpm new`. Issues closed since 0.2.1: * `#109`_: Add web frontend as an option of `zpm new`, don't generate it on `zpm bundle`. * `#131`_: `zpm deploy -l debug` should include request/response data. * `#157`_: Ubuntu package: install requires `python-swiftclient`. * `#158`_: Ubuntu package: update changelog for version 0.2. * `#167`_: `index.html` template rendering was broken. * `#173`_: Deduce auth version from environment variables. * `#177`_: Allow user to force deployment to a non-empty container with `zpm deploy`. * `#180`_: Add X-Nexe-Cdr-Line parsing and display. * `#183`_: Add `zpm auth` command for getting storage url and auth token. 0.2.1 (2014-07-20): This release fixes some minor packaging and distribution issues, as well as some of the behavior of the `deploy` command: * `python-swiftclient` is now an explicit dependency * `setup.py` uses `setuptools` instead of `distutils` * `deploy`: show full URL to the deployed index.html * `deploy`: set correct content type for zapp files * `deploy`: better management of containers (automatically create containers if not existing, don't allow deployment to a non-empty container) 0.2 (2014-06-30): This release drops support for Python 3.2 due to the lack of ``u"..."`` literals in that version. Other issues fixed: * `#20`_: Set up Debian packaging for zpm. * `#31`_: Use ``python-swiftclient`` instead of ``requests`` for interacting with Swift. * `#37`_: Added a ``zpm execute`` command. * `#119`_: ``zpm bundle`` did not raise errors when files in the bundling list don't exist. * `#122`_: Some ``zpm deploy`` references were not rendering correctly in the documentation. * `#132`_: Only process UI files ending in ``.tmpl`` as Jinja2 templates. 0.1 (2014-05-21): First release. .. _#20: https://github.com/zerovm/zpm/issues/20 .. _#31: https://github.com/zerovm/zpm/issues/31 .. _#37: https://github.com/zerovm/zpm/issues/37 .. _#109: https://github.com/zerovm/zpm/issues/109 .. _#119: https://github.com/zerovm/zpm/issues/119 .. _#122: https://github.com/zerovm/zpm/issues/122 .. _#131: https://github.com/zerovm/zpm/issues/131 .. _#132: https://github.com/zerovm/zpm/issues/132 .. _#157: https://github.com/zerovm/zpm/issues/157 .. _#158: https://github.com/zerovm/zpm/issues/158 .. _#167: https://github.com/zerovm/zpm/issues/167 .. _#173: https://github.com/zerovm/zpm/issues/173 .. _#177: https://github.com/zerovm/zpm/issues/177 .. _#180: https://github.com/zerovm/zpm/issues/180 .. _#183: https://github.com/zerovm/zpm/issues/183
zpm
/zpm-0.3.tar.gz/zpm-0.3/README.rst
README.rst
import functools import logging import os import operator import argparse import zpmlib from zpmlib import zpm # List of function that will be the top-level zpm commands. _commands = [] LOG = zpmlib.get_logger(__name__) class SwiftLogFilter(logging.Filter): def filter(self, record): # We want to filter out 404 errors when fetching containers. # In cases where this happens, we already deal with the exception, # so there's no need to constantly show spurious ERROR level messages # to the user. if (record.levelname == 'ERROR' and record.msg.msg == 'Container GET failed' and record.msg.http_status == 404): return False return True def set_up_arg_parser(): parser = argparse.ArgumentParser( description='ZeroVM Package Manager', epilog=("See 'zpm <command> --help' for more information on a specific" " command."), ) parser.add_argument('--version', action='version', help='show the version number and exit', version='zpm version %s' % zpmlib.__version__) subparsers = parser.add_subparsers(description='available subcommands', metavar='COMMAND') for cmd in all_commands(): doclines = cmd.__doc__.splitlines() summary = doclines[0] description = '\n'.join(doclines[1:]) subparser = subparsers.add_parser(cmd.__name__, help=summary, description=description) # Add arguments in reverse order: the last decorator # (bottom-most in the source) is called first, so its # arguments will be at the front of the list. for args, kwargs in reversed(getattr(cmd, '_args', [])): subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=cmd) return parser def command(func): """Register `func` as a top-level zpm command. The name of the function will be the name of the command and any cmdline arguments registered with `arg` will be available. """ _commands.append(func) return func def with_logging(func): """ Decorator for adding the `--log-level` option to a ``zpm`` command. Also takes cares of setting the log level appropriately per the command line option when a command is executed. This should be used as the innermost decorator on a command function. """ log_level_deco = arg( '--log-level', '-l', help="Defaults to 'warn'", choices=['debug', 'info', 'warning', 'error', 'critical'], default='warning' ) @functools.wraps(func) def inner(namespace, *args, **kwargs): """ :param namespace: :class:`argparse.Namespace` instance. This is the only required/expected parameter for a command function. """ log_level = zpmlib.LOG_LEVEL_MAP.get(namespace.log_level) logging.getLogger('zpmlib').setLevel(log_level) # This allows us to see `swiftclient` log messages, specifically HTTP # REQ/RESP swift_log = zpmlib.get_logger('swiftclient') swift_log.setLevel(log_level) swift_log.addFilter(SwiftLogFilter()) return func(namespace, *args, **kwargs) return log_level_deco(inner) def arg(*args, **kwargs): """Decorator for adding command line argument. The `args` and `kwargs` will eventually be passed to `ArgumentParser.add_argument`. If `kwargs` has an `envvar` key, then the default value for the command line argument will be taken from the environment variable with this name. The default value is automatically added to the help string. We do it here instead of using argparse.ArgumentDefaultsHelpFormatter since we format the help in more than one place (cmdline and Sphinx doc). """ envvar = kwargs.get('envvar') if envvar: del kwargs['envvar'] # The default value is shown in the generated documentation. # We therefore only set it if we're not building the # documentation with tox. if '_TOX_SPHINX' not in os.environ: kwargs['default'] = os.environ.get(envvar) kwargs['help'] += ' (default: $%s)' % envvar else: if 'default' in kwargs: kwargs['help'] += ' (default: %s)' % kwargs['default'] def decorator(func): if not hasattr(func, '_args'): func._args = [] func._args.append((args, kwargs)) return func return decorator def group_args(accumulator): """Decorator for grouping command line arguments Use this as the first decorator on a function to turn that function into a decorator that groups the following command line arguments. """ def decorator(func): if not hasattr(func, '_args'): func._args = [] func._args.extend(accumulator._args) return func return decorator @group_args @arg('--auth-version', '-V', choices=['1.0', '2.0'], help='Swift auth version (default: 1.0)') @arg('--auth', '-A', envvar='ST_AUTH', help='(Auth v1.0) URL for obtaining an auth token') @arg('--user', '-U', envvar='ST_USER', help='(Auth v1.0) User name for obtaining an auth token') @arg('--key', '-K', envvar='ST_KEY', help='(Auth v1.0) Key for obtaining an auth token') @arg('--os-auth-url', envvar='OS_AUTH_URL', help='(Auth v2.0) OpenStack auth URL') @arg('--os-tenant-name', envvar='OS_TENANT_NAME', help='(Auth v2.0) OpenStack tenant') @arg('--os-username', envvar='OS_USERNAME', help='(Auth v2.0) OpenStack username') @arg('--os-password', envvar='OS_PASSWORD', help='(Auth v2.0) OpenStack password') def login_args(): """Decorator for adding Swift login command line arguments Use this where you need to add the standard set of command line arguments for Swift login. """ pass def all_commands(): return sorted(_commands, key=operator.attrgetter('__name__')) @command @arg('--with-ui', '-u', help='Include user interface template files', action='store_true') @arg('dir', help='Non-existent or empty directory', metavar='WORKING_DIR', nargs='?', default='.') @with_logging def new(args): """Create template zapp.yaml file Create a default ZeroVM application zapp.yaml specification in the target directory. If no directory is specified, zapp.yaml will be created in the current directory. """ try: project_files = zpm.create_project(args.dir, with_ui=args.with_ui) except RuntimeError as err: print(err) else: for proj_file in project_files: print("Created '%s'" % proj_file) @command @with_logging def bundle(args): """Bundle a ZeroVM application This command creates a Zapp using the instructions in zapp.yaml. The file is read from the project root. """ root = zpm.find_project_root() zpm.bundle_project(root) @command @arg('target', help='Deployment target (Swift container name)') @arg('zapp', help='A ZeroVM application') @arg('--execute', action='store_true', help='Immediately ' 'execute the deployed Zapp (for testing)') @arg('--summary', '-s', action='store_true', help='Show execution summary table (use with `--execute`)') @arg('--force', '-f', action='store_true', help='Force deployment to a non-empty container') @login_args @arg('--no-ui-auth', action='store_true', help='Do not generate any authentication code for the web UI') @with_logging def deploy(args): """Deploy a ZeroVM application This deploys a zapp onto Swift. The zapp can be one you have downloaded or produced yourself with "zpm bundle". You will need to know the Swift authentication URL, username, password, and tenant name. These can be supplied with command line flags (see below) or you can set the corresponding environment variables. The environment variables are the same as the ones used by the Swift command line tool, so if you're already using that to upload files to Swift, you will be ready to go. """ LOG.info('deploying %s' % args.zapp) zpm.deploy_project(args) @command @with_logging @arg('--container', help='Swift container name (containing the zapp)') @arg('--summary', '-s', action='store_true', help='Show execution summary table') @arg('zapp', help='Name of the zapp to execute') @login_args def execute(args): """Remotely execute a ZeroVM application. """ resp = zpm.execute(args) if args.summary: total_time, exec_table = zpm._get_exec_table(resp) print('Execution summary:') print(exec_table) print('Total time: %s' % total_time) @command @arg('command', nargs='?', help='A zpm command') def help(args): """Show this help""" parser = set_up_arg_parser() cmd_names = [c.__name__ for c in _commands] if args.command is None or args.command not in cmd_names: if args.command is not None: print('no such command: %s' % args.command) parser.print_help() else: parser.parse_args([args.command, '-h']) @command def version(args): """Show the version number""" parser = set_up_arg_parser() parser.parse_args(['--version']) @command @login_args def auth(args): """Get auth token and storage URL information""" zpm.auth(args)
zpm
/zpm-0.3.tar.gz/zpm-0.3/zpmlib/commands.py
commands.py
import fnmatch import glob import gzip import json import os import shlex import shutil import tarfile try: import urlparse except ImportError: import urllib.parse as urlparse try: from cStringIO import StringIO as BytesIO except ImportError: from io import BytesIO import jinja2 import prettytable import six import swiftclient import yaml import zpmlib _DEFAULT_UI_TEMPLATES = ['index.html.tmpl', 'style.css', 'zerocloud.js'] _ZAPP_YAML = 'zapp.yaml' _ZAPP_WITH_UI_YAML = 'zapp-with-ui.yaml' LOG = zpmlib.get_logger(__name__) BUFFER_SIZE = 65536 #: path/filename of the system.map (job description) in every zapp SYSTEM_MAP_ZAPP_PATH = 'boot/system.map' #: Message displayed if insufficient auth settings are specified, either on the #: command line or in environment variables. Shamelessly copied from #: ``python-swiftclient``. NO_AUTH_MSG = """\ Auth version 1.0 requires ST_AUTH, ST_USER, and ST_KEY environment variables to be set or overridden with -A, -U, or -K. Auth version 2.0 requires OS_AUTH_URL, OS_USERNAME, OS_PASSWORD, and OS_TENANT_NAME OS_TENANT_ID to be set or overridden with --os-auth-url, --os-username, --os-password, --os-tenant-name or os-tenant-id. Note: adding "-V 2" is necessary for this.""" #: Column labels for the execution summary table EXEC_TABLE_HEADER = [ 'Node', 'Status', 'Retcode', 'NodeT', 'SysT', 'UserT', 'DiskReads', 'DiskBytesR', 'DiskWrites', 'DiskBytesW', 'NetworkReads', 'NetworkBytesR', 'NetworkWrites', 'NetworkBytesW', ] def create_project(location, with_ui=False): """ Create a ZeroVM application project by writing a default `zapp.yaml` in the specified directory `location`. :param location: Directory location to place project files. :param with_ui: Defaults to `False`. If `True`, add basic UI template files as well to ``location``. :returns: Full path to the created `zapp.yaml` file. """ if os.path.exists(location): if not os.path.isdir(location): # target must be an empty directory raise RuntimeError("Target `location` must be a directory") else: os.makedirs(location) return _create_project_files(location, with_ui=with_ui) def render_zapp_yaml(name, template_name='zapp.yaml'): """Load and render the zapp.yaml template.""" loader = jinja2.PackageLoader('zpmlib', 'templates') env = jinja2.Environment(loader=loader) tmpl = env.get_template(template_name) return tmpl.render(name=name) def _create_project_files(location, with_ui=False): """ Create a default `zapp.yaml` file in the specified directory `location`. If `with_ui` is `True`, add template UI files to `location`. Raises a `RuntimeError` if any files would be overwritten in `location`. """ template_dir = os.path.join(os.path.dirname(__file__), 'templates') # Collect a list of the target files target_files = [] zapp_yaml_path = os.path.join(location, 'zapp.yaml') target_files.append(zapp_yaml_path) if with_ui: for template in _DEFAULT_UI_TEMPLATES: dest_path = os.path.join(location, template) target_files.append(dest_path) # Check that none of them already exists; we don't want to overwrite # If any already exists, we don't write anything. for f in target_files: if os.path.exists(f): raise RuntimeError("'%s' already exists!" % f) # Add zapp.yaml template if with_ui: zapp_template = _ZAPP_WITH_UI_YAML else: zapp_template = _ZAPP_YAML with open(os.path.join(location, 'zapp.yaml'), 'w') as fp: name = os.path.basename(os.path.abspath(location)) fp.write(render_zapp_yaml(name, template_name=zapp_template)) # Add UI template files, if specified if with_ui: for template in _DEFAULT_UI_TEMPLATES: src_path = os.path.join(template_dir, template) dest_path = os.path.join(location, template) shutil.copyfile(src_path, dest_path) return target_files def find_project_root(): """ Starting from the `cwd`, search up the file system hierarchy until a ``zapp.yaml`` file is found. Once the file is found, return the directory containing it. If no file is found, raise a `RuntimeError`. """ root = os.getcwd() while not os.path.isfile(os.path.join(root, 'zapp.yaml')): oldroot, root = root, os.path.dirname(root) if root == oldroot: raise RuntimeError("no zapp.yaml file found") return root def _generate_job_desc(zapp): """ Generate the boot/system.map file contents from the zapp config file. :param zapp: `dict` of the contents of a ``zapp.yaml`` file. :returns: `dict` of the job description """ job = [] # TODO(mg): we should eventually reuse zvsh._nvram_escape def escape(value): for c in '\\", \n': value = value.replace(c, '\\x%02x' % ord(c)) return value def translate_args(cmdline): # On Python 2, the yaml module loads non-ASCII strings as # unicode objects. In Python 2.7.2 and earlier, we must give # shlex.split a str -- but it is an error to give shlex.split # a bytes object in Python 3. need_decode = not isinstance(cmdline, str) if need_decode: cmdline = cmdline.encode('utf8') args = shlex.split(cmdline) if need_decode: args = [arg.decode('utf8') for arg in args] return ' '.join(escape(arg) for arg in args) for zgroup in zapp['execution']['groups']: # Copy everything, but handle 'path' and 'args' specially: jgroup = dict(zgroup) jgroup['exec'] = { 'path': zgroup['path'], 'args': translate_args(zgroup['args']), } del jgroup['path'], jgroup['args'] job.append(jgroup) return job def _get_swift_zapp_url(swift_service_url, zapp_path): """ :param str swift_service_url: The Swift service URL returned from a Keystone service catalog. Example: http://localhost:8080/v1/AUTH_469a9cd20b5a4fc5be9438f66bb5ee04 :param str zapp_path: <container>/<zapp-file-name>. Example: test_container/myapp.zapp Here's a typical usage example, with typical input and output: >>> swift_service_url = ('http://localhost:8080/v1/' ... 'AUTH_469a9cd20b5a4fc5be9438f66bb5ee04') >>> zapp_path = 'test_container/myapp.zapp' >>> _get_swift_zapp_url(swift_service_url, zapp_path) 'swift://AUTH_469a9cd20b5a4fc5be9438f66bb5ee04/test_container/myapp.zapp' """ swift_path = urlparse.urlparse(swift_service_url).path # TODO(larsbutler): Why do we need to check if the path contains '/v1/'? # This is here due to legacy reasons, but it's not clear to me why this is # needed. if swift_path.startswith('/v1/'): swift_path = swift_path[4:] return 'swift://%s/%s' % (swift_path, zapp_path) def _prepare_job(tar, zapp, zapp_swift_url): """ :param tar: The application .zapp file, as a :class:`tarfile.TarFile` object. :param dict zapp: Parsed contents of the application `zapp.yaml` specification, as a `dict`. :param str zapp_swift_url: Path of the .zapp in Swift, which looks like this:: 'swift://AUTH_abcdef123/test_container/hello.zapp' See :func:`_get_swift_zapp_url`. :returns: Extracted contents of the boot/system.map with the swift path to the .zapp added to the `devices` for each `group`. So if the job looks like this:: [{'exec': {'args': 'hello.py', 'path': 'file://python2.7:python'}, 'devices': [{'name': 'python2.7'}, {'name': 'stdout'}], 'name': 'hello'}] the output will look like something like this:: [{'exec': {u'args': 'hello.py', 'path': 'file://python2.7:python'}, 'devices': [ {'name': 'python2.7'}, {'name': 'stdout'}, {'name': 'image', 'path': 'swift://AUTH_abcdef123/test_container/hello.zapp'}, ], 'name': 'hello'}] """ fp = tar.extractfile(SYSTEM_MAP_ZAPP_PATH) # NOTE(larsbutler): the `decode` is needed for python3 # compatibility job = json.loads(fp.read().decode('utf-8')) device = {'name': 'image', 'path': zapp_swift_url} for group in job: group['devices'].append(device) return job def bundle_project(root): """ Bundle the project under root. """ zapp_yaml = os.path.join(root, 'zapp.yaml') zapp = yaml.safe_load(open(zapp_yaml)) zapp_name = zapp['meta']['name'] + '.zapp' tar = tarfile.open(zapp_name, 'w:gz') job = _generate_job_desc(zapp) job_json = json.dumps(job) info = tarfile.TarInfo(name='boot/system.map') # This size is only correct because json.dumps uses # ensure_ascii=True by default and we thus have a 1-1 # correspondence between Unicode characters and bytes. info.size = len(job_json) LOG.info('adding %s' % info.name) # In Python 3, we cannot use a str or bytes object with addfile, # we need a BytesIO object. In Python 2, BytesIO is just StringIO. # Since json.dumps produces an ASCII-only Unicode string in Python # 3, it is safe to encode it to ASCII. tar.addfile(info, BytesIO(job_json.encode('ascii'))) _add_file_to_tar(root, 'zapp.yaml', tar) sections = ('bundling', 'ui') # Keep track of the files we add, given the configuration in the zapp.yaml. file_add_count = 0 for section in sections: for pattern in zapp.get(section, []): paths = glob.glob(os.path.join(root, pattern)) if len(paths) == 0: LOG.warning( "pattern '%(pat)s' in section '%(sec)s' matched no files", dict(pat=pattern, sec=section) ) else: for path in paths: _add_file_to_tar(root, path, tar) file_add_count += len(paths) if file_add_count == 0: # None of the files specified in the "bundling" or "ui" sections were # found. Something is wrong. raise zpmlib.ZPMException( "None of the files specified in the 'bundling' or 'ui' sections of" " the zapp.yaml matched anything." ) tar.close() print('created %s' % zapp_name) def _add_file_to_tar(root, path, tar): """ :param root: Root working directory. :param path: File path. :param tar: Open :class:`tarfile.TarFile` object to add the ``files`` to. """ LOG.info('adding %s' % path) relpath = os.path.relpath(path, root) tar.add(relpath, arcname=relpath) def _find_ui_uploads(zapp, tar): matches = set() names = tar.getnames() for pattern in zapp.get('ui', []): matches.update(fnmatch.filter(names, pattern)) return sorted(matches) def _post_job(url, token, data, http_conn=None, response_dict=None, content_type='application/json', content_length=None): # Modelled after swiftclient.client.post_account. headers = {'X-Auth-Token': token, 'X-Zerovm-Execute': '1.0', 'Content-Type': content_type} if content_length: headers['Content-Length'] = str(content_length) if http_conn: parsed, conn = http_conn else: parsed, conn = swiftclient.http_connection(url) conn.request('POST', parsed.path, data, headers) resp = conn.getresponse() body = resp.read() swiftclient.http_log((url, 'POST'), {'headers': headers}, resp, body) swiftclient.store_response(resp, response_dict) print(body) class ZeroCloudConnection(swiftclient.Connection): """ An extension of the `swiftclient.Connection` which has the capability of posting ZeroVM jobs to an instance of ZeroCloud (running on Swift). """ def authenticate(self): """ Authenticate with the provided credentials and cache the storage URL and auth token as `self.url` and `self.token`, respectively. """ self.url, self.token = self.get_auth() def post_job(self, job, response_dict=None): """Start a ZeroVM job, using a pre-uploaded zapp :param object job: Job description. This will be encoded as JSON and sent to ZeroCloud. """ json_data = json.dumps(job) LOG.debug('JOB: %s' % json_data) return self._retry(None, _post_job, json_data, response_dict=response_dict) def post_zapp(self, data, response_dict=None, content_length=None): return self._retry(None, _post_job, data, response_dict=response_dict, content_type='application/x-gzip', content_length=content_length) def _get_zerocloud_conn(args): version = args.auth_version # no version was explicitly requested; try to guess it: if version is None: version = _guess_auth_version(args) if version == '1.0': if any([arg is None for arg in (args.auth, args.user, args.key)]): raise zpmlib.ZPMException( "Version 1 auth requires `--auth`, `--user`, and `--key`." "\nSee `zpm deploy --help` for more information." ) conn = ZeroCloudConnection(args.auth, args.user, args.key) elif version == '2.0': if any([arg is None for arg in (args.os_auth_url, args.os_username, args.os_tenant_name, args.os_password)]): raise zpmlib.ZPMException( "Version 2 auth requires `--os-auth-url`, `--os-username`, " "`--os-password`, and `--os-tenant-name`." "\nSee `zpm deploy --help` for more information." ) conn = ZeroCloudConnection(args.os_auth_url, args.os_username, args.os_password, tenant_name=args.os_tenant_name, auth_version='2.0') else: raise zpmlib.ZPMException(NO_AUTH_MSG) return conn def _deploy_zapp(conn, target, zapp_path, auth_opts, force=False): """Upload all of the necessary files for a zapp. Returns the name an uploaded index file, or the target if no index.html file was uploaded. :param bool force: Force deployment, even if the target container is not empty. This means that files could be overwritten and could cause consistency problems with these objects in Swift. """ base_container = target.split('/')[0] try: _, objects = conn.get_container(base_container) if not len(objects) == 0: if not force: raise zpmlib.ZPMException( "Target container ('%s') is not empty.\nDeploying to a " "non-empty container can cause consistency problems with " "overwritten objects.\nSpecify the flag `--force/-f` to " "overwrite anyway." % base_container ) except swiftclient.exceptions.ClientException: # container doesn't exist; create it LOG.info("Container '%s' not found. Creating it...", base_container) conn.put_container(base_container) # If we get here, everything with the container is fine. index = target + '/' uploads = _generate_uploads(conn, target, zapp_path, auth_opts) for path, data, content_type in uploads: if path.endswith('/index.html'): index = path container, obj = path.split('/', 1) conn.put_object(container, obj, data, content_type=content_type) return index def _generate_uploads(conn, target, zapp_path, auth_opts): """Generate sequence of (container-and-file-path, data, content-type) tuples. """ tar = tarfile.open(zapp_path, 'r:gz') zapp_config = yaml.safe_load(tar.extractfile('zapp.yaml')) remote_zapp_path = '%s/%s' % (target, os.path.basename(zapp_path)) swift_url = _get_swift_zapp_url(conn.url, remote_zapp_path) job = _prepare_job(tar, zapp_config, swift_url) yield (remote_zapp_path, gzip.open(zapp_path).read(), 'application/x-tar') yield ('%s/%s' % (target, SYSTEM_MAP_ZAPP_PATH), json.dumps(job), 'application/json') for path in _find_ui_uploads(zapp_config, tar): output = tar.extractfile(path).read() if path.endswith('.tmpl'): tmpl = jinja2.Template(output.decode('utf-8')) output = tmpl.render(auth_opts=auth_opts, zapp=zapp_config) # drop the .tmpl extension path = os.path.splitext(path)[0] ui_path = '%s/%s' % (target, path) yield (ui_path, output, None) def _prepare_auth(version, args, conn): """ :param str version: Auth version: "0.0", "1.0", or "2.0". "0.0" indicates "no auth". :param args: :class:`argparse.Namespace` instance, with attributes representing the various authentication parameters :param conn: :class:`ZeroCloudConnection` instance. """ version = str(float(version)) auth = {'version': version} if version == '0.0': auth['swiftUrl'] = conn.url elif version == '1.0': auth['authUrl'] = args.auth auth['username'] = args.user auth['password'] = args.key else: # TODO(mg): inserting the username and password in the # uploaded file makes testing easy, but should not be done in # production. See issue #46. auth['authUrl'] = args.os_auth_url auth['tenant'] = args.os_tenant_name auth['username'] = args.os_username auth['password'] = args.os_password return auth def _guess_auth_version(args): """Guess the auth version from first the command line args and/or envvars. Command line arguments override environment variables, so we check those first. Auth v1 arguments: * ``--auth`` * ``--user`` * ``--key`` Auth v2 arguments: * ``--os-auth-url`` * ``--os-username`` * ``--os-password`` * ``--os-tenant-name`` If all of the v1 and v2 arguments are specified, default to 1.0 (this is how ``python-swiftclient`` behaves). If no auth version can be determined from the command line args, we check environment variables. Auth v1 vars: * ``ST_AUTH`` * ``ST_USER`` * ``ST_KEY`` Auth v2 vars: * ``OS_AUTH_URL`` * ``OS_USERNAME`` * ``OS_PASSWORD`` * ``OS_TENANT_NAME`` The same rule above applies; if both sets of variables are specified, default to 1.0. If no auth version can be determined, return `None`. :param args: :class:`argparse.Namespace`, representing the args specified on the command line. :returns: '1.0', '2.0', or ``None`` """ v1 = (args.auth, args.user, args.key) v2 = (args.os_auth_url, args.os_username, args.os_password, args.os_tenant_name) if all(v1) and not all(v2): return '1.0' elif all(v2) and not all(v1): return '2.0' elif all(v1) and all(v2): # All vars for v1 and v2 auth are set, so we follow the # `python-swiftclient` behavior and default to 1.0. return '1.0' else: # deduce from envvars env = os.environ v1_env = (env.get('ST_AUTH'), env.get('ST_USER'), env.get('ST_KEY')) v2_env = (env.get('OS_AUTH_URL'), env.get('OS_USERNAME'), env.get('OS_PASSWORD'), env.get('OS_TENANT_NAME')) if all(v1_env) and not all(v2_env): return '1.0' if all(v2_env) and not all(v1_env): return '2.0' elif all(v1_env) and all(v2_env): # Same as above, if all v1 and v2 vars are set, default to 1.0. return '1.0' else: # Insufficient auth details have been specified. return None def deploy_project(args): conn = _get_zerocloud_conn(args) conn.authenticate() ui_auth_version = conn.auth_version # We can now reset the auth for the web UI, if needed if args.no_ui_auth: ui_auth_version = '0.0' auth = _prepare_auth(ui_auth_version, args, conn) auth_opts = jinja2.Markup(json.dumps(auth)) deploy_index = _deploy_zapp(conn, args.target, args.zapp, auth_opts, force=args.force) print('app deployed to\n %s/%s' % (conn.url, deploy_index)) if args.execute: # for compatibility with the option name in 'zpm execute' args.container = args.target resp = execute(args) if args.summary: total_time, exec_table = _get_exec_table(resp) print('Execution summary:') print(exec_table) print('Total time: %s' % total_time) def _get_exec_table(resp): """Build an execution summary table from a job execution response. :param dict resp: Response dictionary from job execution. Must contain a ``headers`` key at least (and will typically contain ``status`` and ``reason`` as well). :returns: Tuple of total execution time (`str`), ``prettytable.PrettyTable`` containing the summary of all node executions in the job. """ headers = resp['headers'] total_time, table_data = _get_exec_table_data(headers) table = prettytable.PrettyTable(EXEC_TABLE_HEADER) for row in table_data: table.add_row(row) return total_time, table def _get_exec_table_data(headers): """Extract a stats table from execution HTTP response headers. Stats include things like node name, execution time, number of reads/writes, bytes read/written, etc. :param dict headers: `dict` of response headers from a job execution request. It must contain at least ``x-nexe-system``, ``x-nexe-status``, ``x-nexe-retcode``, ``x-nexe-cdr-line``. :returns: Tuple of two items. The first is the total time for the executed job (as a `str`). The second is a table (2d `list`) of execution data extracted from ``X-Nexe-System`` and ``X-Nexe-Cdr-Line`` headers. Each row in the table consists of the following data: * node name * node time * system time * user time * number of disk reads * number of bytes read from disk * number of disk writes * number of bytes written to disk * number of network reads * number of bytes read from network * number of network writes * number of bytes written to network """ node_names = iter(headers['x-nexe-system'].split(',')) statuses = iter(headers['x-nexe-status'].split(',')) retcodes = iter(headers['x-nexe-retcode'].split(',')) cdr = headers['x-nexe-cdr-line'] cdr_data = [x.strip() for x in cdr.split(',')] total_time = cdr_data.pop(0) cdr_data = iter(cdr_data) adviter = lambda x: six.advance_iterator(x) table_data = [] while True: try: node_name = adviter(node_names) status = adviter(statuses) retcode = adviter(retcodes) node_time = adviter(cdr_data) cdr = adviter(cdr_data).split() row = [node_name, status, retcode, node_time] + cdr table_data.append(row) except StopIteration: break return total_time, table_data def execute(args): """Execute a zapp remotely on a ZeroCloud deployment. :returns: A `dict` with response data, including the keys 'status', 'reason', and 'headers'. """ conn = _get_zerocloud_conn(args) resp = dict() if args.container: job_filename = SYSTEM_MAP_ZAPP_PATH try: headers, content = conn.get_object(args.container, job_filename) except swiftclient.ClientException as exc: if exc.http_status == 404: raise zpmlib.ZPMException("Could not find %s" % exc.http_path) else: raise zpmlib.ZPMException(str(exc)) job = json.loads(content) conn.post_job(job, response_dict=resp) LOG.debug('RESP STATUS: %s %s', resp['status'], resp['reason']) LOG.debug('RESP HEADERS: %s', resp['headers']) else: size = os.path.getsize(args.zapp) zapp_file = open(args.zapp, 'rb') data_reader = iter(lambda: zapp_file.read(BUFFER_SIZE), b'') conn.post_zapp(data_reader, response_dict=resp, content_length=size) zapp_file.close() return resp def auth(args): conn = _get_zerocloud_conn(args) conn.authenticate() print('Auth token: %s' % conn.token) print('Storage URL: %s' % conn.url)
zpm
/zpm-0.3.tar.gz/zpm-0.3/zpmlib/zpm.py
zpm.py
function ZeroCloudClient() { this._token = null; } /* * Authenticate to Keystone. Call this before calling other methods * that talk with Swift. * * If Keystone and Swift are served from differnet domains, you must * install a CORS (Cross-Origin Resource Sharing) middleware in Swift. * Otherwise the authentication requests made by this function wont be * allowed by the browser. */ ZeroCloudClient.prototype.auth = function (opts, success) { var defaults = {'version': '2.0', 'success': $.noop}; var args = {'success': success}; var merged = $.extend(defaults, opts, args); switch (merged.version) { case '0.0': this._auth0(merged); break; case '1.0': this._auth1(merged); break; default: this._auth2(merged); break; } }; /* * No authentication. This is used when no authentication is * necessary. * * The opts argument is a plain object with these keys: * * - swiftUrl */ ZeroCloudClient.prototype._auth0 = function (opts) { this._swiftUrl = opts.swiftUrl; opts.success(); }; /* * Swift v1 authentication. * * The opts argument is a plain object with these keys: * * - authURL * - username * - password */ ZeroCloudClient.prototype._auth1 = function (opts) { var self = this; $.ajax({ 'type': 'GET', 'url': opts.authUrl, 'cache': false, 'headers': { 'X-Auth-User': opts.username, 'X-Auth-Key': opts.password }, 'success': function (data, status, xhr) { self._token = xhr.getResponseHeader('X-Auth-Token'); self._swiftUrl = xhr.getResponseHeader('X-Storage-Url'); opts.success(); } }); }; /* * Swift v2 authentication. This will login to Keystone and obtain an * authentication token. * * The opts argument is a plain object with these keys: * * - authURL * - username * - password * - tenant */ ZeroCloudClient.prototype._auth2 = function (opts) { var headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}; var payload = {'auth': {'tenantName': opts.tenant, 'passwordCredentials': {'username': opts.username, 'password': opts.password}}}; var self = this; $.ajax({ 'type': 'POST', 'url': opts.authUrl + '/tokens', 'data': JSON.stringify(payload), 'cache': false, 'success': function (data) { self._token = data.access.token.id; $.each(data.access.serviceCatalog, function (i, service) { if (service.name == 'swift') { self._swiftUrl = service.endpoints[0].publicURL; return false; // break for-each loop } }); opts.success(); }, 'dataType': 'json', 'contentType': 'application/json', 'accepts': 'application/json' }); }; /* * Execute a job. The job description will be serialized as JSON and * sent to Swift. The "stdout" from the job, if any, will be passed to * the success callback function. */ ZeroCloudClient.prototype.execute = function (job, success) { var headers = {'X-Zerovm-Execute': '1.0'}; if (this._token) { headers['X-Auth-Token'] = this._token; } $.ajax({ 'type': 'POST', 'url': this._swiftUrl, 'data': JSON.stringify(job), 'headers': headers, 'cache': false, 'success': (success || $.noop), 'contentType': 'application/json', }); }; /* * Compute a Swift URL. This is a URL of the form * swift://<user>/<relativePath>. */ ZeroCloudClient.prototype.swiftPath = function (relativePath) { var user = this._swiftUrl.slice(this._swiftUrl.lastIndexOf('/') + 1); return 'swift://' + user + '/' + relativePath; }; /* * Escape command line argument. Command line arguments in a job * description should be separated with spaces after being escaped * with this function. */ function escapeArg (value) { function hexencode (match) { return "\\x" + match.charCodeAt(0).toString(16); } return value.replace(/[\\", \n]/g, hexencode); }
zpm
/zpm-0.3.tar.gz/zpm-0.3/zpmlib/templates/zerocloud.js
zerocloud.js
zpov ==== A minimalist note engine ------------------------ * ~500 lines of code * no javascript * usable on any browser, including on mobile * no database, just a bare git repo for storage and sync * http basic auth * pages are markdown files in the git repo. earch "directory" *must* have an ``index.md`` at the top * title of each page is the top line of the markdown file * sub-pages are sorted alphabetically * edition is a text area containing the markdown Usage ----- ``zpov`` is a python application built using ``flask``. refer to the flask documentation to learn about developement and/or debugging. note that you will need a config file named ``zpov.yml`` in the current directory, looking like this .. code-block:: yaml public_access: <true|false> users: # required if public_access is ``false`` <user>: "<hashed password>" repo_path: 'path/to/repo.git where: * ``path/to/repo.git`` is a *bare* git repository containing the markdown files. * ``hashed_password`` was generated with ``nacl.pwhash.str('<password>')``.
zpov
/zpov-1.0.1.tar.gz/zpov-1.0.1/README.rst
README.rst
from io import BytesIO, StringIO from tempfile import NamedTemporaryFile from uuid import uuid1 from re import search class ManagedFile: def __init__(self, filename=None, mode='r', typefile="stringio", encoding=None, closable=True): self.filename = filename self.mode = mode self.encoding = encoding self.closed = False self.closable = closable self.typefile = typefile.lower() self.file = self.init_file() if self.file is None: return self.set_permissions() def init_file(self): try: fuuid = str(uuid1()).replace("-", "") if self.typefile == 'string': #Simulation d'un fichier avec une chaîne self.name = "String"+fuuid self.seeker = 0 return self.init_content() elif self.typefile == 'file': #Ouverture d'un fichier if self.filename is not None: self.name = self.filename return open(self.filename, mode=self.mode, encoding=self.encoding) else: print("Error: filename is not init") return None elif self.typefile == 'bytesio': #Création d'un bytesio self.name = "BytesIO"+fuuid return BytesIO() elif self.typefile == 'stringio': #Création d'un stringio self.name = "StringIO"+fuuid return StringIO() elif self.typefile == 'tempfile': #Création d'un fichier temporaire cp = NamedTemporaryFile(mode=self.mode, encoding=self.encoding) self.name = cp.name return cp except: return None def init_content(self): if "b" in self.mode: self.bytecontent = True return b'' else: self.bytecontent = False return '' def set_permissions(self): if self.typefile == 'stringio' or self.typefile == 'bytesio': self.readable = True self.writable = True else: self.readable = False self.writable = False if "r" in self.mode: self.readable = True if "+" in self.mode: self.writable = True elif "w" in self.mode: self.writable = True if "+" in self.mode: self.readable = True elif "a" in self.mode: self.writable = True if "+" in self.mode: self.readable = True def __enter__(self): return self def __exit__(self, *args): self.close() def __del__(self): if self.closed is False: self.close() def fileno(self): if self.typefile != 'string' and hasattr(self.file, 'fileno'): return self.file.fileno() else: return None def buffer(self): if self.typefile != 'string' and hasattr(self.file, 'buffer'): return self.file.buffer else: return None def flush(self): if self.typefile != 'string' and hasattr(self.file, 'flush'): return self.file.flush() else: return None def isatty(self): if self.typefile != 'string' and hasattr(self.file, 'isatty'): return self.file.isatty() else: return False @property def errors(self): if self.typefile != 'string' and hasattr(self.file, 'errors'): return self.file.errors else: return None @property def newlines(self): if self.typefile == 'string' and hasattr(self.file, 'newlines'): return self.file.newlines else: return None def close(self): if self.closable: self.closed = True if self.typefile != 'string': self.file.close() def write(self,data): if self.closed is False: if self.writable: if self.typefile != 'string': self.file.write(data) else: if self.bytecontent: if isinstance(data, bytes): self.file+=data else: print("Error: data must be a bytes") else: if isinstance(data, str): if self.encoding is not None: self.file+=data.encode(self.encoding) else: self.file+=data else: print("Error: data must be a str") else: print("Error: File is not writable") else: print("Error: File is closed") def read(self, size=None): if self.closed is False: if self.readable: if self.typefile != 'string': return self.file.read(size) else: if size is None: buff = self.file[self.seeker:] self.seeker=len(self.file) return buff elif isinstance(size, int): buff = self.file[self.seeker:size] self.seeker=size return buff else: print("Error: File is not readable") else: print("Error: File is closed") def readline(self, size=None): if self.closed is False: if self.readable: if self.typefile != 'string': if size is None: return self.file.readline() elif isinstance(size, int): return self.file.readline(size) else: if size is None: content = self.file[self.seeker:] elif isinstance(size, int): content = self.file[self.seeker:size] else: return None if self.bytecontent: content = content.decode() r = search('\n',content) if r is None: self.seeker=self.seeker+len(content) return content else: index = r.span()[len(r.span())-1] buff = content[:index] self.seeker=self.seeker+index return buff else: print("Error: File is not readable") else: print("Error: File is closed") def readlines(self): if self.closed is False: if self.readable: if self.typefile != 'string': return self.file.readlines() else: return self.file.split("\n") else: print("Error: File is not readable") else: print("Error: File is closed") def tell(self): if self.closed is False: if self.typefile != 'string': return self.file.tell() else: return self.seeker else: print("Error: File is closed") def seek(self, position, whence=0): if isinstance(whence, int) and whence>=0 and whence<=2: if self.closed is False: if self.typefile != 'string': self.file.seek(position, whence) else: if whence==0: self.seeker=position elif whence==1: self.seeker+=position elif whence==2: self.seeker=len(self.file)-position print(self.seeker) if self.seeker>len(self.file): self.seeker=len(self.file) if self.seeker<0: self.seeker=0 else: print("Error: File is closed") else: print("Error: whence format not acceptable") def truncate(self, size=None): if self.closed is False: if self.writable: if self.typefile != 'string': self.file.truncate(size) else: if size is None: if self.bytecontent: self.file = b'' else: self.file = '' else: self.file = self.file[:size] else: print("Error: File is not readable") else: print("Error: File is closed") def writelines(self, data): if isinstance(data, list): if self.closed is False: if self.writable: if self.typefile != 'string': self.file.writelines(data) else: if self.bytecontent: self.file = ("".join(data)).encode(self.encoding) else: self.file+="".join(data) else: print("Error: File is not readable") else: print("Error: File is closed") else: print("Error: data is not a list") def isClosable(self, action): if isinstance(action, bool): self.closable = action else: print("Error: Bad action")
zpp-ManagedFile
/zpp_ManagedFile-1.0.1-py3-none-any.whl/zpp_ManagedFile/ManagedFile.py
ManagedFile.py
import sys import inspect import re def get_origin_value(): frame = inspect.currentframe() frame = inspect.getouterframes(frame)[2] string = inspect.getframeinfo(frame[0]).code_context[0].strip() args = string[string.find('(') + 1:-1].split(',') names = [] for i in args: if i.find('=') != -1: names.append(i.split('=')[1].strip()) else: names.append(i) return names def digit(x): try: float(x) return True except ValueError: return False class StoreArgument(): def __init__(self): pass def list_all(self): return self.__dict__ def __contains__(self, key): return key in self.__dict__ class parser(): def __init__(self, source=None, error_lock=False): self.available_arg = [] self.available_param = [] self.error_lock = error_lock self.check_parameter = True if source==None: self.command = sys.argv[0] self.source=sys.argv[1:] else: if "sys.argv" in get_origin_value()[0]: self.command = source[0] self.source = source[1:] else: self.command, self.source = self.arg_parse(source) def search(self, option): for element in self.available_arg: if element['longname']==option: return element return None def find_short(self, name): for element in self.available_arg: if element['shortcut']==name: return element return None def set_param(self,option,val,store): if not hasattr(self.argument, option): if store=="digit": if isinstance(val, str): if val.isdigit(): val = int(val) else: val = float(val) elif isinstance(val, int) or isinstance(val, float): pass else: return False setattr(self.argument, option, val) return True else: print(f"Argument {option} already set") return False def set_result(self,option): if option['longname']: name = option['longname'] else: name = option['shortcut'] if option['store']=="value": if len(self.source)>0 and self.source[0].startswith('-')==False: if option['type']!=None: val_arg = self.source.pop(0) if option['type']=="str" or (option['type']=="digit" and digit(val_arg)): if not self.set_param(name,val_arg,option['type']): return None else: print(f"Argument {name}: Bad value type") if "default" in option.keys(): if not self.set_param(name,option['default'],option['type']): return None else: return None else: if not self.set_param(name,self.source.pop(0),option['type']): return None else: print(f"Argument {name}: Missing value") if "default" in option.keys() and option['default']!=None: if not self.set_param(name,option['default'],option['type']): return None else: return None elif option['store']=="bool": if not self.set_param(name,True,option['type']): return None return 1 def load(self): self.parameter = [] self.argument = StoreArgument() msg_error = "\nError: " while(len(self.source)!=0): element = self.source.pop(0) if element.startswith('--'): option = element[2:] if option=="help": self.help() return None, None else: find = self.search(option) if find!=None: status_code = self.set_result(find) if status_code==None and self.error_lock: return None, None else: msg_error += f"\n Argument {option} not available" elif element.startswith('-'): if "h" in element[1:]: self.help() return None, None else: for option in element[1:]: f = self.find_short(option) if f!=None: status_code = self.set_result(f) if status_code==None and self.error_lock: return None, None else: msg_error += f"\n Argument {option} not available" else: self.parameter.append(element) msg="" for ar in self.available_arg: if not (hasattr(self.argument, ar['shortcut']) or hasattr(self.argument, ar['longname'])): if ar['longname']: name = ar['longname'] else: name = ar['shortcut'] if "default" in ar.keys(): self.set_param(name,ar['default'],ar['type']) elif ar['store']=="bool": self.set_param(name,False,"str") if ar['required']==True and not (hasattr(self.argument, ar['shortcut']) or hasattr(self.argument, ar['longname'])): set_default=False if "default" in ar.keys(): if ar['longname']: name = ar['longname'] else: name = ar['shortcut'] if self.set_param(name,ar['default'],ar['type']): set_default=True if set_default==False: if ar['shortcut']=="": n = ar['longname'] else: n = ar['shortcut'] if len(msg)==0: msg=n else: msg+=", "+n if self.check_parameter==True and len(self.available_param)<len(self.parameter): msg_error+=f"Missing parameter ({len(self.available_param)} needed but {len(self.parameter)} received)" if len(msg)!=0: msg_error += f"\n Argument {msg} not initialized" self.help() print(msg_error) return None, None if msg_error!="\nError: ": print(msg_error) if self.error_lock: return None, None return self.parameter, self.argument def arg_parse(self, string): command = string[0] del string[0] array = [] if len(string)>=1: arg = "" lock = None if isinstance(string, list): string = " ".join(string) for i,caracter in enumerate(string): if (caracter=="'" or caracter=='"') and (lock==None or caracter==lock): if lock==None: lock=caracter else: array.append(arg) arg="" lock=None else: if caracter==" " and lock!=None: arg+=caracter elif caracter==" " and len(arg)>=1 and lock==None: array.append(arg) arg="" elif caracter!=" ": arg+=caracter if i==len(string)-1: array.append(arg) arg="" return command, array def already_exist(self,shortcut,longname): for el in self.available_arg: if shortcut!="" and shortcut==el['shortcut']: return True if longname!=None and longname!="" and longname==el['longname']: return True return False def param_exist(self,name): for el in self.available_param: if el['name']==name: return True return False def set_parameter(self, name, description=None): if not self.param_exist(name): insert = {'name': name, 'description': description} self.available_param.append(insert) else: print(f"Parameter {name} already set") def set_argument(self, shortcut="", longname=None, type=None, default="", description=None, required=False, store="bool", category=""): if self.already_exist(shortcut,longname): print("Error for setting argument") else: if shortcut!="" or longname!=None: if shortcut!="h" and longname!="help": insert = {'shortcut': shortcut, 'longname': longname} if default!="": insert['default'] = default insert['description'] = description if type=="str" or type=="digit": insert['type'] = type else: insert['type'] = None if isinstance(required,bool): insert['required'] = required else: insert['required'] = False if store=="value" or store=="bool": insert['store'] = store else: insert['store'] = "bool" insert['category'] = category self.available_arg.append(insert) else: print("Argument h(help) not authorized") else: print("Error for setting argument") def set_description(self, description): if len(description)!=0: self.main_description = description def disable_check(self): self.check_parameter = False def help(self): ### Affichage du usage mm = self.command + " [-h]" for a in self.available_arg: if a['shortcut']!="": val = a['shortcut'] else: val = "-"+a['longname'] if a['required']: if a['store']=="value": mm+=" -"+val+" VALUE" else: mm+=" -"+val else: mm+=" [" if a['store']=="value": mm+="-"+val+" VALUE" else: mm+="-"+val mm+="]" for a in self.available_param: mm+=" "+a['name'].upper() print("\nUsage: "+mm) ### Affichage de la description if hasattr(self, "main_description"): print("\nDescription:\n "+self.main_description) ### Affichage des options if len(self.available_arg)!=0: maxsize = 0 print("\nArguments:") ### Parse by category category = {"":{}} for a in self.available_arg: if a['shortcut']!="": name = a['shortcut'] else: name = a['longname'] if a['category'] not in category: category[a['category']] = {} category[a['category']][name] = a if len(category)>1: padding = " " else: padding = "" ### Calcul maxsize padding for c in category: for a in category[c]: a = category[c][a] ins = '' if a['shortcut']!="": ins=" -"+a['shortcut'] if a['longname']: ins+=", --"+a['longname'] else: ins=" --"+a['longname'] if a['store']=="value": ins+=" VALUE" if len(ins)>maxsize: maxsize = len(ins) ### Display category for c in category: if c!="": print(f" {c}") ar = [] for a in category[c]: a = category[c][a] ins = ["",""] if a['shortcut']!="": ins[0]=" -"+a['shortcut'] if a['longname']: ins[0]+=", --"+a['longname'] else: ins[0]=" --"+a['longname'] if a['store']=="value": ins[0]+=" VALUE" if a['description']: ins[1]+=a['description'] if a['required']: if len(ins[1])!=0: ins[1]+=" " ins[1]+="(Required)" if a['type']=="digit": if len(ins[1])!=0: ins[1]+=" " ins[1]+=" (Type: digit)" if "default" in a.keys() and a['default']: if len(ins[1])!=0: ins[1]+=" " if a['default']==True: ins[1]+=" (Default Value: True)" elif a['default']==False: ins[1]+=" (Default Value: False)" else: ins[1]+=" (Default Value: "+a['default']+")" ar.append(ins) for a in ar: print(padding+a[0]+" "*((maxsize-len(a[0]))+3)+a[1]) if len(self.available_param)!=0: ar = [] maxsize = 0 print("\nParameters:") for a in self.available_param: ar.append([a['name'],a['description']]) if len(a['name'])>maxsize: maxsize = len(a['name']) for a in ar: print(" "+a[0].upper()+" "*((maxsize-len(a[0]))+3)+a[1])
zpp-args
/zpp_args-1.3.1-py3-none-any.whl/zpp_args/args.py
args.py
import os from glob import glob if os.name=="nt": from msvcrt import getch,kbhit else: import sys,tty,os,termios ########################### Getch ########################### def getkey(): if os.name=="nt": c1 = getch() if kbhit(): c2 = getch() if c1 in (b"\x00", b"\xe0"): key_mapping = {72: "up", 80: "down", 77: "right", 75: "left"} return key_mapping.get(ord(c2), c1 + c2) key_mapping = {13: "enter"} return key_mapping.get(ord(c1), c1.decode()) else: old_settings = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) try: while True: b = os.read(sys.stdin.fileno(), 3).decode() if len(b) == 3: k = ord(b[2]) key_mapping = {10: 'enter', 65: 'up', 66: 'down', 67: 'right', 68: 'left'} else: k = ord(b) key_mapping = {10: 'enter'} return key_mapping.get(k, None) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) ########################### Color ########################### class ColorClass(object): def __init__(self, idc): self.ESC = "\x1b[" self.END = "m" self.idc = idc if os.name=="nt": self.terminal_mode() self.color = {"black": "0","red": "1","green": "2","yellow": "3","blue": "4","magenta": "5","cyan": "6","light_gray": "7","dark_gray": "8","light_red": "9","light_green": "10","light_yellow": "11","light_blue": "12","light_magenta": "13","light_cyan": "14","white": "15","grey_0": "16","navy_blue": "17","dark_blue": "18","blue_3a": "19","blue_3b": "20","blue_1": "21","dark_green": "22","deep_sky_blue_4a": "23","deep_sky_blue_4b": "24","deep_sky_blue_4c": "25","dodger_blue_3": "26","dodger_blue_2": "27","green_4": "28","spring_green_4": "29","turquoise_4": "30","deep_sky_blue_3a": "31","deep_sky_blue_3b": "32","dodger_blue_1": "33","green_3a": "34","spring_green_3a": "35","dark_cyan": "36","light_sea_green": "37","deep_sky_blue_2": "38","deep_sky_blue_1": "39","green_3b": "40","spring_green_3b": "41","spring_green_2a": "42","cyan_3": "43","dark_turquoise": "44","turquoise_2": "45","green_1": "46","spring_green_2b": "47","spring_green_1": "48","medium_spring_green": "49","cyan_2": "50","cyan_1": "51","dark_red_1": "52","deep_pink_4a": "53","purple_4a": "54","purple_4b": "55","purple_3": "56","blue_violet": "57","orange_4a": "58","grey_37": "59","medium_purple_4": "60","slate_blue_3a": "61","slate_blue_3b": "62","royal_blue_1": "63","chartreuse_4": "64","dark_sea_green_4a": "65","pale_turquoise_4": "66","steel_blue": "67","steel_blue_3": "68","cornflower_blue": "69","chartreuse_3a": "70","dark_sea_green_4b": "71","cadet_blue_2": "72","cadet_blue_1": "73","sky_blue_3": "74","steel_blue_1a": "75","chartreuse_3b": "76","pale_green_3a": "77","sea_green_3": "78","aquamarine_3": "79","medium_turquoise": "80","steel_blue_1b": "81","chartreuse_2a": "82","sea_green_2": "83","sea_green_1a": "84","sea_green_1b": "85","aquamarine_1a": "86","dark_slate_gray_2": "87","dark_red_2": "88","deep_pink_4b": "89","dark_magenta_1": "90","dark_magenta_2": "91","dark_violet_1a": "92","purple_1a": "93","orange_4b": "94","light_pink_4": "95","plum_4": "96","medium_purple_3a": "97","medium_purple_3b": "98","slate_blue_1": "99","yellow_4a": "100","wheat_4": "101","grey_53": "102","light_slate_grey": "103","medium_purple": "104","light_slate_blue": "105","yellow_4b": "106","dark_olive_green_3a": "107","dark_green_sea": "108","light_sky_blue_3a": "109","light_sky_blue_3b": "110","sky_blue_2": "111","chartreuse_2b": "112","dark_olive_green_3b": "113","pale_green_3b": "114","dark_sea_green_3a": "115","dark_slate_gray_3": "116","sky_blue_1": "117","chartreuse_1": "118","light_green_2": "119","light_green_3": "120","pale_green_1a": "121","aquamarine_1b": "122","dark_slate_gray_1": "123","red_3a": "124","deep_pink_4c": "125","medium_violet_red": "126","magenta_3a": "127","dark_violet_1b": "128","purple_1b": "129","dark_orange_3a": "130","indian_red_1a": "131","hot_pink_3a": "132","medium_orchid_3": "133","medium_orchid": "134","medium_purple_2a": "135","dark_goldenrod": "136","light_salmon_3a": "137","rosy_brown": "138","grey_63": "139","medium_purple_2b": "140","medium_purple_1": "141","gold_3a": "142","dark_khaki": "143","navajo_white_3": "144","grey_69": "145","light_steel_blue_3": "146","light_steel_blue": "147","yellow_3a": "148","dark_olive_green_3": "149","dark_sea_green_3b": "150","dark_sea_green_2": "151","light_cyan_3": "152","light_sky_blue_1": "153","green_yellow": "154","dark_olive_green_2": "155","pale_green_1b": "156","dark_sea_green_5b": "157","dark_sea_green_5a": "158","pale_turquoise_1": "159","red_3b": "160","deep_pink_3a": "161","deep_pink_3b": "162","magenta_3b": "163","magenta_3c": "164","magenta_2a": "165","dark_orange_3b": "166","indian_red_1b": "167","hot_pink_3b": "168","hot_pink_2": "169","orchid": "170","medium_orchid_1a": "171","orange_3": "172","light_salmon_3b": "173","light_pink_3": "174","pink_3": "175","plum_3": "176","violet": "177","gold_3b": "178","light_goldenrod_3": "179","tan": "180","misty_rose_3": "181","thistle_3": "182","plum_2": "183","yellow_3b": "184","khaki_3": "185","light_goldenrod_2a": "186","light_yellow_3": "187","grey_84": "188","light_steel_blue_1": "189","yellow_2": "190","dark_olive_green_1a": "191","dark_olive_green_1b": "192","dark_sea_green_1": "193","honeydew_2": "194","light_cyan_1": "195","red_1": "196","deep_pink_2": "197","deep_pink_1a": "198","deep_pink_1b": "199","magenta_2b": "200","magenta_1": "201","orange_red_1": "202","indian_red_1c": "203","indian_red_1d": "204","hot_pink_1a": "205","hot_pink_1b": "206","medium_orchid_1b": "207","dark_orange": "208","salmon_1": "209","light_coral": "210","pale_violet_red_1": "211","orchid_2": "212","orchid_1": "213","orange_1": "214","sandy_brown": "215","light_salmon_1": "216","light_pink_1": "217","pink_1": "218","plum_1": "219","gold_1": "220","light_goldenrod_2b": "221","light_goldenrod_2c": "222","navajo_white_1": "223","misty_rose1": "224","thistle_1": "225","yellow_1": "226","light_goldenrod_1": "227","khaki_1": "228","wheat_1": "229","cornsilk_1": "230","grey_100": "231","grey_3": "232","grey_7": "233","grey_11": "234","grey_15": "235","grey_19": "236","grey_23": "237","grey_27": "238","grey_30": "239","grey_35": "240","grey_39": "241","grey_42": "242","grey_46": "243","grey_50": "244","grey_54": "245","grey_58": "246","grey_62": "247","grey_66": "248","grey_70": "249","grey_74": "250","grey_78": "251","grey_82": "252","grey_85": "253","grey_89": "254","grey_93": "255"} self.mode = {"bold": "1",1: "1","dim": "2",2: "2","italic": "3",3: "3","underlined": "4",4: "4","blink": "5",5: "5","reverse": "7",7: "7","hidden": "8",8: "8","strikethrough": "9",9: "9","reset": "0",0: "0","res_bold": "21",21: "21","res_dim": "22",22: "22","res_underlined": "24",24: "24","res_blink": "25",25: "25","res_reverse": "27",27: "27","res_hidden": "28",28: "28"} def terminal_mode(self): from ctypes import windll, c_int, byref stdout_handle = windll.kernel32.GetStdHandle(c_int(-11)) mode = c_int(0) windll.kernel32.GetConsoleMode(c_int(stdout_handle), byref(mode)) mode = c_int(mode.value | 4) windll.kernel32.SetConsoleMode(c_int(stdout_handle), mode) def attribute(self): if self.idc=='None' or self.idc==None: return "" else: if self.idc in self.mode: return self.ESC + self.mode[self.idc] + self.END else: return "" def foreground(self): if self.idc=='None' or self.idc==None: return "" else: if str(self.idc).isdigit(): return self.ESC + "38;5;" + str(self.idc) + self.END else: if self.idc in self.color: return self.ESC + "38;5;" + self.color[self.idc] + self.END else: return "" def background(self): if self.idc=='None' or self.idc==None: return "" else: if str(self.idc).isdigit(): return self.ESC + "48;5;" + str(self.idc) + self.END else: if self.idc in self.color: return self.ESC + "48;5;" + self.color[self.idc] + self.END else: return "" def attr(color): return ColorClass(color).attribute() def fg(color): return ColorClass(color).foreground() def bg(color): return ColorClass(color).background() ########################### Cursor ########################## def com(val): print("\033"+val,end="") def cursorTo(x=0): com("["+str(x)+";0H") def cursorSave(): com("7") def cursorRestore(): com("8") def cursorHide(): com("[?25l") def cursorShow(): com("[?25h") def EraseLine(): com("[2K") def clear(): print("\033[2J",end="") ############################ browser ########################### class BrowserClass(): def __init__(self,Path, Filter, ShowHidden, ShowDir, ShowFirst, Color, Pointer, Padding): self.Selected = 0 self.filter = Filter self.ShowHidden = ShowHidden self.ShowDir = ShowDir self.ShowFirst = ShowFirst self.mapping_color(Color) self.path = os.path.abspath(Path).replace("\\","/") cursorHide() self.edgeY = Padding self.pointer = Pointer def __del__(self): cursorShow() clear() def print_path(self): max = os.get_terminal_size().columns size = len(" "*(self.edgeY+len(self.pointer))+"-- "+self.path+" --\n") if size<max: print(" "*(self.edgeY+len(self.pointer))+"-- "+self.path+" --\n") else: path = self.path.split("/") while len(" "*(self.edgeY+len(self.pointer))+"-- ../"+"/".join(path)+" --\n")>max: del path[0] print(" "*(self.edgeY+len(self.pointer))+"-- ../"+"/".join(path)+" --\n") def glob_dir(self): if self.ShowFirst!=None: data_dir = [] data_file = [] data = [] if self.ShowDir: glob_data = [".."] else: glob_data = [] if self.ShowHidden: glob_data += sorted(glob(self.path+"/*") + glob(self.path+"/.*")) else: glob_data += sorted(glob(self.path+"/*")) for element in glob_data: fileName, fileExtension = os.path.splitext(element) if (self.filter!=["*"] and (fileExtension in self.filter or (os.path.isdir(element) and self.ShowDir==True))) or (self.filter==["*"] and ((os.path.isdir(element) and self.ShowDir==True) or (os.path.isdir(element)==False))): if self.ShowFirst!=None: if os.path.isdir(element): data_dir.append(element) else: data_file.append(element) else: data.append(element) if self.ShowFirst=="dir": data = data_dir+data_file elif self.ShowFirst=="file": data = data_file+data_dir return data def load(self): self.Options = self.glob_dir() self.MenuMax = len(self.Options)-1 file_choice = None choice = None while file_choice==None: clear() self.Selected = self.show() file = self.Options[self.Selected] if os.path.isfile(file): file_choice=file elif file=="..": pathtemp = self.path.split("/") self.path = "/".join(pathtemp[0:len(pathtemp)-1]) self.Options = self.glob_dir() self.MenuMax = len(self.Options)-1 elif os.path.isdir(file): self.path = file.replace("\\","/") self.Options = self.glob_dir() self.MenuMax = len(self.Options)-1 return file_choice def show(self): tmax = (os.get_terminal_size().lines)-2 self.print_path() for i,element in enumerate(self.Options): element = element.replace("\\","/").replace(self.path+"/","") fore,back = self.get_color_content(self.Options[i]) if i<tmax-1: if i==0: print(" "*self.edgeY + self.pointer + fg(self.map_color['__selected__']['fore'])+bg(self.map_color['__selected__']['back'])+element+attr(0)) else: if os.path.isdir(element): print(" "*(self.edgeY+len(self.pointer)) + fg(fore)+bg(back)+element+attr(0)) else: print(" "*(self.edgeY+len(self.pointer)) + fg(fore)+bg(back)+element+attr(0)) if tmax<self.MenuMax: self.size = tmax-2 else: self.size = self.MenuMax self.Selected = 0 self.cursor = 2 while True: k = getkey() if k=="up" and len(self.Options)>1: self.Rewrite_line() if self.Selected-1<0: self.Selected=self.MenuMax self.cursor = self.size+2 self.Rewrite_screen("bottom") else: self.Selected-=1 if self.cursor==2 and self.Selected>=0: self.Rewrite_screen("up") else: self.cursor-=1 self.Rewrite_Selected() elif k=="down" and len(self.Options)>1: self.Rewrite_line() if self.Selected+1>self.MenuMax: self.Selected=0 self.cursor=2 self.Rewrite_screen("top") else: self.Selected+=1 if self.cursor==self.size+2 and self.cursor<self.MenuMax and self.Selected<self.MenuMax+1: self.Rewrite_screen("down") else: self.cursor+=1 cursorTo(self.cursor) self.Rewrite_Selected() elif k=="enter": return self.Selected def Rewrite_screen(self,direction): clear() self.print_path() if direction=="down": list_f = self.Options[self.Selected-self.size:self.Selected+1] elif direction=="up": list_f = self.Options[self.Selected:self.Selected+self.size+1] elif direction=="top": list_f = self.Options[0:self.size+1] elif direction=="bottom": list_f = self.Options[self.Selected-self.size:self.Selected] for i in list_f: element = element = i.replace("\\","/").replace(self.path+"/","") fore,back = self.get_color_content(i) if os.path.isdir(i): print(" "*(self.edgeY+len(self.pointer)) + fg(fore)+bg(back)+element+attr(0)) else: print(" "*(self.edgeY+len(self.pointer)) + fg(fore)+bg(back)+element+attr(0)) def Rewrite_line(self): cursorSave() cursorTo(self.cursor+1) EraseLine() fore,back = self.get_color_content(self.Options[self.Selected]) print(" "*(self.edgeY+len(self.pointer)) + fg(fore)+bg(back) + self.Options[self.Selected].replace("\\","/").replace(self.path+"/","")+attr(0),end="") def Rewrite_Selected(self): cursorTo(self.cursor+1) EraseLine() print(" "*self.edgeY + self.pointer + fg(self.map_color['__selected__']['fore'])+bg(self.map_color['__selected__']['back'])+self.Options[self.Selected].replace("\\","/").replace(self.path+"/","")+attr(0)) cursorRestore() def get_color_content(self, element): if os.path.isdir(element): return self.map_color['__dir__']['fore'], self.map_color['__dir__']['back'] else: fileName, fileExtension = os.path.splitext(element) element = element.replace("\\","/").replace(self.path+"/","") if fileExtension in self.map_color.keys(): return self.map_color[fileExtension]['fore'], self.map_color[fileExtension]['back'] elif element.startswith('.'): return self.map_color['__hidden__']['fore'], self.map_color['__hidden__']['back'] else: return self.map_color['__default__']['fore'], self.map_color['__default__']['back'] def mapping_color(self,list_color): if isinstance(list_color, list): self.map_color = {} for line in list_color: if len(line)==3: if "," in line[0]: for ext in line[0].split(","): self.map_color[ext] = {} self.map_color[ext]['fore'] = line[1] self.map_color[ext]['back'] = line[2] else: self.map_color[line[0]] = {} self.map_color[line[0]]['fore'] = line[1] self.map_color[line[0]]['back'] = line[2] default_data = ['__default__','white','black'],['__hidden__','yellow','black'],['__selected__','red','black'],['__dir__','green','black'] for elem in default_data: if elem[0] not in self.map_color.keys(): self.map_color[elem[0]] = {} self.map_color[elem[0]]['fore'] = elem[1] self.map_color[elem[0]]['back'] = elem[2] print(self.map_color['__selected__']['fore']) else: self.map_color = {'__default__': {'fore': 'white', 'back': 'black'}, '__hidden__': {'fore': 'grey', 'back': 'black'}, '__selected__': {'fore': 'red', 'back': 'black'}, '__dir__': {'fore': 'green', 'back': 'black'}} def Browser(Path, Filter=["*"], ShowHidden=True, ShowDir=True, ShowFirst="dir", Color=None, Pointer="> ", Padding=2): return BrowserClass(Path, Filter, ShowHidden, ShowDir, ShowFirst, Color, Pointer, Padding).load()
zpp-browser
/zpp_browser-1.0.1-py3-none-any.whl/zpp_browser/browser.py
browser.py
# zpp-color ## Informations Librairie pour la colorisation de texte dans un terminal.<br> Permet de modifier la couleur du texte, la couleur de fond et le style.<br> Prise en charge de 256 couleurs.<br> Sélection de la couleur avec le nom, l'id ou une combinaison RGB<br> ### Prérequis - Python 3 <br> # Installation ```console pip install zpp_color ``` # Utilisation ### Conseil d'importation du module ```python from zpp_color import fg, bg, attr ``` <br> #### Modification de la couleur du texte ###### Avec le nom ```python print(f"{fg('blue')}Ceci est un texte en bleu{attr(0)}") ``` ###### Avec l'id ```python print(f"{fg(3)}Ceci est un texte en bleu{attr(0)}") ``` ###### Avec un code RGB ```python print(f"{fg('0,0,255')}Ceci est un texte en bleu{attr(0)}") ``` > **_NOTE:_** Toujours rajouter attr(0) à la fin du texte, sinon la couleur s'appliquera pour les lignes suivantes. <br> #### Modification de la couleur de fond ###### Avec le nom ```python print(f"{bg('red')}Ceci est un texte avec un fond rouge{attr(0)}") ``` ###### Avec l'id ```python print(f"{bg(1)}Ceci est un texte avec un fond rouge{attr(0)}") ``` ###### Avec un code RGB ```python print(f"{bg('255,0,0')}Ceci est un texte avec un fond rouge{attr(0)}") ``` <br> #### Modification du style du texte ###### Avec le nom ```python print(f"{attr('italic')}Ceci est un texte en italic{attr(0)}") ``` ###### Avec l'id ```python print(f"{attr(3)}Ceci est un texte en italic{attr(0)}") ``` <br> #### Lister les possibilités ###### Lister les couleurs possibles ```python zpp_color.list_fg() ``` ```python zpp_color.list_bg() ``` ###### Lister les styles possibles ```python zpp_color.list_attr() ```
zpp-color
/zpp_color-1.0.3.tar.gz/zpp_color-1.0.3/README.md
README.md
import os class ColorClass(object): def __init__(self, idc): self.ESC = "\x1b[" self.END = "m" self.idc = idc if os.name=="nt": self.terminal_mode() self.color = {"black": "0","red": "1","green": "2","yellow": "3","blue": "4","magenta": "5","cyan": "6","light_gray": "7","dark_gray": "8","light_red": "9","light_green": "10","light_yellow": "11","light_blue": "12","light_magenta": "13","light_cyan": "14","white": "15","grey_0": "16","navy_blue": "17","dark_blue": "18","blue_3a": "19","blue_3b": "20","blue_1": "21","dark_green": "22","deep_sky_blue_4a": "23","deep_sky_blue_4b": "24","deep_sky_blue_4c": "25","dodger_blue_3": "26","dodger_blue_2": "27","green_4": "28","spring_green_4": "29","turquoise_4": "30","deep_sky_blue_3a": "31","deep_sky_blue_3b": "32","dodger_blue_1": "33","green_3a": "34","spring_green_3a": "35","dark_cyan": "36","light_sea_green": "37","deep_sky_blue_2": "38","deep_sky_blue_1": "39","green_3b": "40","spring_green_3b": "41","spring_green_2a": "42","cyan_3": "43","dark_turquoise": "44","turquoise_2": "45","green_1": "46","spring_green_2b": "47","spring_green_1": "48","medium_spring_green": "49","cyan_2": "50","cyan_1": "51","dark_red_1": "52","deep_pink_4a": "53","purple_4a": "54","purple_4b": "55","purple_3": "56","blue_violet": "57","orange_4a": "58","grey_37": "59","medium_purple_4": "60","slate_blue_3a": "61","slate_blue_3b": "62","royal_blue_1": "63","chartreuse_4": "64","dark_sea_green_4a": "65","pale_turquoise_4": "66","steel_blue": "67","steel_blue_3": "68","cornflower_blue": "69","chartreuse_3a": "70","dark_sea_green_4b": "71","cadet_blue_2": "72","cadet_blue_1": "73","sky_blue_3": "74","steel_blue_1a": "75","chartreuse_3b": "76","pale_green_3a": "77","sea_green_3": "78","aquamarine_3": "79","medium_turquoise": "80","steel_blue_1b": "81","chartreuse_2a": "82","sea_green_2": "83","sea_green_1a": "84","sea_green_1b": "85","aquamarine_1a": "86","dark_slate_gray_2": "87","dark_red_2": "88","deep_pink_4b": "89","dark_magenta_1": "90","dark_magenta_2": "91","dark_violet_1a": "92","purple_1a": "93","orange_4b": "94","light_pink_4": "95","plum_4": "96","medium_purple_3a": "97","medium_purple_3b": "98","slate_blue_1": "99","yellow_4a": "100","wheat_4": "101","grey_53": "102","light_slate_grey": "103","medium_purple": "104","light_slate_blue": "105","yellow_4b": "106","dark_olive_green_3a": "107","dark_green_sea": "108","light_sky_blue_3a": "109","light_sky_blue_3b": "110","sky_blue_2": "111","chartreuse_2b": "112","dark_olive_green_3b": "113","pale_green_3b": "114","dark_sea_green_3a": "115","dark_slate_gray_3": "116","sky_blue_1": "117","chartreuse_1": "118","light_green_2": "119","light_green_3": "120","pale_green_1a": "121","aquamarine_1b": "122","dark_slate_gray_1": "123","red_3a": "124","deep_pink_4c": "125","medium_violet_red": "126","magenta_3a": "127","dark_violet_1b": "128","purple_1b": "129","dark_orange_3a": "130","indian_red_1a": "131","hot_pink_3a": "132","medium_orchid_3": "133","medium_orchid": "134","medium_purple_2a": "135","dark_goldenrod": "136","light_salmon_3a": "137","rosy_brown": "138","grey_63": "139","medium_purple_2b": "140","medium_purple_1": "141","gold_3a": "142","dark_khaki": "143","navajo_white_3": "144","grey_69": "145","light_steel_blue_3": "146","light_steel_blue": "147","yellow_3a": "148","dark_olive_green_3": "149","dark_sea_green_3b": "150","dark_sea_green_2": "151","light_cyan_3": "152","light_sky_blue_1": "153","green_yellow": "154","dark_olive_green_2": "155","pale_green_1b": "156","dark_sea_green_5b": "157","dark_sea_green_5a": "158","pale_turquoise_1": "159","red_3b": "160","deep_pink_3a": "161","deep_pink_3b": "162","magenta_3b": "163","magenta_3c": "164","magenta_2a": "165","dark_orange_3b": "166","indian_red_1b": "167","hot_pink_3b": "168","hot_pink_2": "169","orchid": "170","medium_orchid_1a": "171","orange_3": "172","light_salmon_3b": "173","light_pink_3": "174","pink_3": "175","plum_3": "176","violet": "177","gold_3b": "178","light_goldenrod_3": "179","tan": "180","misty_rose_3": "181","thistle_3": "182","plum_2": "183","yellow_3b": "184","khaki_3": "185","light_goldenrod_2a": "186","light_yellow_3": "187","grey_84": "188","light_steel_blue_1": "189","yellow_2": "190","dark_olive_green_1a": "191","dark_olive_green_1b": "192","dark_sea_green_1": "193","honeydew_2": "194","light_cyan_1": "195","red_1": "196","deep_pink_2": "197","deep_pink_1a": "198","deep_pink_1b": "199","magenta_2b": "200","magenta_1": "201","orange_red_1": "202","indian_red_1c": "203","indian_red_1d": "204","hot_pink_1a": "205","hot_pink_1b": "206","medium_orchid_1b": "207","dark_orange": "208","salmon_1": "209","light_coral": "210","pale_violet_red_1": "211","orchid_2": "212","orchid_1": "213","orange_1": "214","sandy_brown": "215","light_salmon_1": "216","light_pink_1": "217","pink_1": "218","plum_1": "219","gold_1": "220","light_goldenrod_2b": "221","light_goldenrod_2c": "222","navajo_white_1": "223","misty_rose1": "224","thistle_1": "225","yellow_1": "226","light_goldenrod_1": "227","khaki_1": "228","wheat_1": "229","cornsilk_1": "230","grey_100": "231","grey_3": "232","grey_7": "233","grey_11": "234","grey_15": "235","grey_19": "236","grey_23": "237","grey_27": "238","grey_30": "239","grey_35": "240","grey_39": "241","grey_42": "242","grey_46": "243","grey_50": "244","grey_54": "245","grey_58": "246","grey_62": "247","grey_66": "248","grey_70": "249","grey_74": "250","grey_78": "251","grey_82": "252","grey_85": "253","grey_89": "254","grey_93": "255"} self.mode = {"bold": "1",1: "1","dim": "2",2: "2","italic": "3",3: "3","underlined": "4",4: "4","blink": "5",5: "5","reverse": "7",7: "7","hidden": "8",8: "8","strikethrough": "9",9: "9","reset": "0",0: "0","res_bold": "21",21: "21","res_dim": "22",22: "22","res_underlined": "24",24: "24","res_blink": "25",25: "25","res_reverse": "27",27: "27","res_hidden": "28",28: "28"} def terminal_mode(self): import ctypes kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) def attribute(self): if self.idc=='None' or self.idc==None: return "" else: if self.idc in self.mode: return self.ESC + self.mode[self.idc] + self.END else: return "" def foreground(self): if self.idc=='None' or self.idc==None: return "" else: if str(self.idc).isdigit(): return self.ESC + "38;5;" + str(self.idc) + self.END else: if "," in self.idc: self.idc = self.idc.split(",") if len(self.idc)==3: if self.idc[0].isdigit() and self.idc[1].isdigit() and self.idc[2].isdigit(): return self.ESC + "38;2;" + self.idc[0] + ";" + self.idc[1] + ";" + self.idc[2] + self.END else: if self.idc in self.color: return self.ESC + "38;5;" + self.color[self.idc] + self.END else: return "" def background(self): if self.idc=='None' or self.idc==None: return "" else: if str(self.idc).isdigit(): return self.ESC + "48;5;" + str(self.idc) + self.END else: if "," in self.idc: self.idc = self.idc.split(",") if len(self.idc)==3: if self.idc[0].isdigit() and self.idc[1].isdigit() and self.idc[2].isdigit(): return self.ESC + "48;2;" + self.idc[0] + ";" + self.idc[1] + ";" + self.idc[2] + self.END else: if self.idc in self.color: return self.ESC + "48;5;" + self.color[self.idc] + self.END else: return "" def attr(color): return ColorClass(color).attribute() def fg(color): return ColorClass(color).foreground() def bg(color): return ColorClass(color).background() def list_fg(): for color in ColorClass(None).color: print(f"{ColorClass(None).color[color]} : {fg(color)} {color} {attr('reset')}") def list_bg(): for color in ColorClass(None).color: print(f"{ColorClass(None).color[color]} : {bg(color)} {color} {attr('reset')}") def list_attr(): for mode in ColorClass(None).mode: print(f"{ColorClass(None).mode[mode]} : {attr(mode)} {mode} {attr('reset')}")
zpp-color
/zpp_color-1.0.3.tar.gz/zpp_color-1.0.3/zpp_color/color.py
color.py
# zpp-config ## Informations Librairie pour l'utilisation et la modification de fichier de configuration:<br> - Charger un ou plusieurs paramètres - Modifier un paramètre existant - Ajout un paramètre ou une section - Supprimer un paramètre ou une section - Lister les sections disponibles - Lister les paramètres et/ou sections désactivés Prends en compte les paramètres commentés.<br> Compatible avec les fichiers de configuration indentés.<br><br> Traduit les paramètres pour les types str, int, float, bool, list, dict ### Prérequis - Python 3 <br> # Installation ```console pip install zpp_config ``` # Utilisation ### Conseil d'importation du module ```python from zpp_config import Config ``` <br> ### Exemple de fichier de config ```xml [section] value1 = key1 value2 = key2 value3 = key3 [section2] value1 = key1 value2 = key2 value3 = key3 ``` <br> ### Initialisaton d'un fichier de configuration ```python c = Config("conf.ini") ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- separator: Définir le séparateur entre la clé et la valeur dans le fichier. (Par défaut: " = ") >- escape_line: Définir le caractère utilisé pour commenter une valeur ou une section. (Par défaut: "#") >- auto_create: Créer le fichier de configuration s'il n'existe pas. (Par défaut: "False") >- read_only: Ouvrir le fichier de configuration en lecture seule. (Par défaut: "False") <br> ### Chargement de paramètre La fonction renvoie la valeur si un unique paramètre a été trouvé, sinon renvoie un dictionnaire avec les différentes valeurs trouvées (classé par section) Renvoie un tableau vide si aucun paramètre n'a été trouvé #### Chargement de tous les paramètres ```python data = c.load() ``` #### Chargement d'une section du fichier ```python data = c.load(section='section_name') ``` #### Chargement d'une valeur dans tout le fichier ```python data = c.load(val='value_name') ``` #### Chargement d'une valeur dans une section spécifique ```python data = c.load(val='value_name', section='section_name') ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- default: Pour initialiser une valeur par défaut si aucun résultat est trouvé <br> ### Changement de paramètre #### Changement d'une valeur dans tout le fichier ```python c.change(val='value_name', key='key_value') ``` #### Changement d'une valeur dans une section spécifique ```python c.change(val='value_name', key='key_value', section='section_name') ``` <br> ### Ajout de paramètre ou de section Ajoute une section ou un paramètre dans le fichier de configuration. Dans le cas de l'ajout d'un paramètre, rajoute la section si elle n'existe pas. #### Ajout d'une section ```python c.add(section='section_name') ``` #### Ajout d'un paramètre dans une section ```python c.add(val='value_name', key='key_value', section='section_name') ``` > Si aucune section est défini, rajoute le paramètre en dehors des sections. <br> ### Suppression de paramètre ou de section #### Suppression d'une section ```python c.delete(section='section_name') ``` #### Suppression d'un paramètre dans une section ```python c.delete(val='value_name', section='section_name') ``` > Si aucune section est défini, recherche le paramètre en dehors des sections. <br> ### Liste des paramètres non pris en compte Retourne la liste des paramètres qui sont non pris en compte dans le fichier de configuration. ```python data = c.disabled_line() ``` > Possibilité de préciser la section en utilisant le paramètre section <br> ### Liste les sections disponibles ```python data = c.list_section() ```
zpp-config
/zpp_config-1.2.0.tar.gz/zpp_config-1.2.0/README.md
README.md
import re import ast from os.path import isfile, exists class Config(): def __init__(self,file,separator=" = ", escape_line="#", auto_create=False, read_only=False): self.reg = r'\[[0-9A-Za-z-_ ]*\]' self.separator=separator self.escape_line = escape_line self.read_only = read_only if isfile(file) and exists(file): self.file = file else: if auto_create==False: print("Error: File not exists") else: self.file = file #Str to real type def return_data(self, data): if data=="true" or data=="True": return True elif data=="false" or data=="False": return False else: try: return ast.literal_eval(data) except: return data def indent_line(self,line): lineC = line.replace("\t","") return lineC def list_section(self): if hasattr(self,'file'): with open(self.file) as f: sec_array = [] for line in f.readlines(): line = self.indent_line(line.strip()) if re.match(self.reg,line): sec_array.append(line.replace("[","").replace("]","")) return sec_array def load(self,val=None,section=None,default=None): lock=False ban = False data = [] sec = '' dict_data = {} if hasattr(self,'file'): if section!=None and section!="" and section not in self.list_section(): return data with open(self.file) as f: for line in f.readlines(): line = self.indent_line(line.strip()) if ban==True and line.startswith("[") and line.endswith("]"): ban=False if line.startswith(self.escape_line+"[") and line.endswith("]"): ban=True elif line.startswith(self.escape_line): pass else: if ban==False: if section!=None: if section!="" and re.match(self.reg,line): if lock==False: if line=="["+section+"]": lock=True data = [] else: lock=False break else: if lock==True: if len(line)!=0: if val==None: data.append(line) else: line = line.split(self.separator) if line[0]==val: return self.return_data(line[1]) elif section=="": if len(line)!=0: if not line.startswith("[") and not line.endswith("]"): if val==None: data.append(line) else: line = line.split(self.separator) if line[0]==val: return self.return_data(line[1]) else: break elif val!=None: if re.match(self.reg,line): sec = line.replace("[","").replace("]","") if len(line)!=0: line = line.split(self.separator) if line[0]==val: data.append(sec + self.separator + line[1]) else: if len(line)!=0: if not re.match(self.reg,line): line = line.split(self.separator) if sec=='' and sec not in dict_data: dict_data[sec] = {} dict_data[sec][line[0]] = self.return_data(line[1]) else: sec = line.replace("[","").replace("]","") if sec not in dict_data.keys(): dict_data[sec] = {} if val==None and section==None: return dict_data if len(data)!=0: for element in data: element=element.split(self.separator) if len(element)>1: dict_data[element[0]] = self.return_data(element[1]) if dict_data=={} and default!=None: return default else: return dict_data if data==[] and default!=None: return default else: return data if default!=None: return default def edit(self,line,val,key,temp): if len(line)!=0: if val!=None: lineT = line.split(self.separator) if lineT[0]==val: self.new_content.append(temp.replace(self.separator+lineT[1], self.separator+str(key))) return True else: self.new_content.append(temp) return True return False def change(self,val=None,key=None,section=None): if self.read_only==False: if val!=None and key!=None: if isinstance(key,str) or isinstance(key,list) or isinstance(key,int) or isinstance(key,float) or isinstance(key,bool) or isinstance(key,dict): if hasattr(self,'file'): with open(self.file) as f: self.new_content = [] lock=False for line in f.readlines(): temp = line.rstrip() line = self.indent_line(line.strip()) if len(line)!=0: if section!=None: if section!="" and re.match(self.reg,line): if lock==False: if line=="["+section+"]": lock=True else: lock=False else: if lock==True: if self.edit(line,val,key,temp): continue else: if self.edit(line,val,key,temp): continue self.new_content.append(temp) else: self.new_content.append(temp) with open(self.file,"w") as f: f.write("\n".join(self.new_content)) else: print("Read-only mode") def add(self,val=None,key=None,section=None): if self.read_only==False: exist = True new_content=None lock=False if hasattr(self,'file'): if section!=None and section!="" and section not in self.list_section(): exist = False if val!=None and val!="" and key!=None and not (isinstance(key,str) or isinstance(key,list) or isinstance(key,int) or isinstance(key,float) or isinstance(key,bool) or isinstance(key,dict)): print("Key not supported") return with open(self.file) as f: if exist==False: new_content=f.read() if new_content[len(new_content)-1]=="\n": new_content+="\n["+section+"]" else: new_content+="\n\n["+section+"]" if val!=None and val!="" and key!=None: new_content+="\n"+val+self.separator+str(key) else: data = self.load() if section!=None: se_test = section else: se_test = "" if val!=None: se = data[se_test] if val in se.keys(): print("Key already exist") return if val!=None and val!="" and key!=None: if section=="" or section==None: new_content=val+self.separator+str(key)+"\n" new_content+=f.read() else: new_content = [] for line in f.readlines(): line_temp = line.rstrip() line = self.indent_line(line.strip()) if line_temp!="": if section!=None: if section!="" and re.match(self.reg,line): if lock==False: if line=="["+section+"]": if len(se.keys())==0: line_temp+="\n"+val+self.separator+str(key) lock=True else: lock=False else: if lock==True: if "\t" in line_temp: line_temp+="\n"+("\t"*line_temp.count('\t'))+val+self.separator+str(key) lock=False new_content.append(line_temp) new_content = "\n".join(new_content) if new_content!=None: with open(self.file,'w') as f: f.write(new_content) else: print("Read-only mode") def delete(self,val=None,section=None): if self.read_only==False: if hasattr(self,'file'): with open(self.file) as f: lock=False new_content="" sec = "" ban=False for line in f.readlines(): lineT = line line = self.indent_line(line.strip()) if line.startswith("[") and line.endswith("]"): ban=False sec = line.replace("[","").replace("]","") elif line.startswith(self.escape_line+"[") and line.endswith("]"): ban=True sec = line.replace(self.escape_line+"[","").replace("]","") if ban!=True: if section!=None and section!="": if section!="" and re.match(self.reg,line): if lock==False: if line=="["+section+"]": lock=True if val!=None: new_content+=lineT else: new_content+=lineT else: new_content+=lineT lock=False else: if lock==True: if val==None: pass else: line = line.split(self.separator) if line[0]==val: pass else: new_content+=lineT else: new_content+=lineT else: if val!=None and sec=="": line = line.split(self.separator) if line[0]==val: pass else: new_content+=lineT else: new_content+=lineT else: new_content+=lineT if new_content!="": with open(self.file,'w') as f: f.write(new_content) else: print("Read-only mode") def disabled_line(self, section=None): dict_data = {} if hasattr(self,'file'): with open(self.file) as f: ban=False sec = "" for line in f.readlines(): line = self.indent_line(line.strip()) if len(line)!=0: if line.startswith("[") and line.endswith("]"): sec = line.replace("[","").replace("]","") if ban==True: ban=False if line.startswith(self.escape_line+"[") and line.endswith("]"): ban=True sec = line.replace(self.escape_line+"[","").replace("]","") elif line.startswith(self.escape_line): line = line[1:len(line)].split(self.separator) if sec not in dict_data.keys(): dict_data[sec] = {} dict_data[sec][line[0]] = self.return_data(line[1]) else: if ban==True: line = line.split(self.separator) if sec not in dict_data.keys(): dict_data[sec] = {} dict_data[sec][line[0]] = self.return_data(line[1]) return dict_data def disable(self,val=None,section=None): if self.read_only==False: if val!=None: if hasattr(self,'file'): modified = False with open(self.file) as f: self.new_content = [] lock=False for line in f.readlines(): temp = line.rstrip() line = self.indent_line(line.strip()) if len(line)!=0: if section!=None: if section!="" and re.match(self.reg,line): if lock==False: if line=="["+section+"]": lock=True else: lock=False else: if lock==True: lineT = line.split(self.separator) if lineT[0]==val: modified = True self.new_content.append("#"+line) else: self.new_content.append(line) continue else: lineT = line.split(self.separator) if lineT[0]==val: modified = True self.new_content.append("#"+line) else: self.new_content.append(line) continue self.new_content.append(temp) else: self.new_content.append(temp) if modified: with open(self.file,"w") as f: f.write("\n".join(self.new_content)) return True return False else: print("Read-only mode") return False def enable(self,val=None,section=None): if self.read_only==False: if val!=None: val = "#"+val if hasattr(self,'file'): modified = False with open(self.file) as f: self.new_content = [] lock=False for line in f.readlines(): temp = line.rstrip() line = self.indent_line(line.strip()) if len(line)!=0: if section!=None: if section!="" and re.match(self.reg,line): if lock==False: if line=="["+section+"]": lock=True else: lock=False else: if lock==True: lineT = line.split(self.separator) if lineT[0]==val: modified = True self.new_content.append(line[1:]) else: self.new_content.append(line) continue else: lineT = line.split(self.separator) if lineT[0]==val: modified = True self.new_content.append(line[1:]) else: self.new_content.append(line) continue self.new_content.append(temp) else: self.new_content.append(temp) if modified: with open(self.file,"w") as f: f.write("\n".join(self.new_content)) return True return False else: print("Read-only mode") return False
zpp-config
/zpp_config-1.2.0.tar.gz/zpp_config-1.2.0/zpp_config/config.py
config.py
import impmagic reg_foreground = r"fore:(?P<color>\w+)" reg_background = r"back:(?P<color>\w+)" reg_attribute = r"attr:(?P<color>\w+)" reg_date = r"date:(?P<date_format>[^)]*)" reg_action = r"%\((?P<action>[^)]*)\){1}(?P<padding>\d*)%" NOTSET = 0 DEBUG = 10 GOOD = 15 INFO = 20 WARNING = 30 ERROR = 40 CRITICAL = 50 _levelToName = { CRITICAL: 'CRITICAL', ERROR: 'ERROR', WARNING: 'WARNING', INFO: 'INFO', GOOD: 'GOOD', DEBUG: 'DEBUG', NOTSET: 'NOTSET', } _nameToLevel = { 'CRITICAL': CRITICAL, 'ERROR': ERROR, 'WARNING': WARNING, 'INFO': INFO, 'GOOD': GOOD, 'DEBUG': DEBUG, 'NOTSET': NOTSET, } def sizeconvert(size): size = int(size) if size < 1024: return str(round(size / 1024.0)) + " Octets" elif size < 1024**2: return str(round(size / 1024.0, 3)) + " Ko" elif size < 1024**3: return str(round(size / (1024.0**2), 2)) + " Mo" else: return str(round(size / (1024.0**3), 2)) + " Go" @impmagic.loader( {'module': 'psutil'} ) def list_disk(): array = [] for element in psutil.disk_partitions(all=True): if "cdrom" in element.opts: if element.fstype!="": info = psutil.disk_usage(element.device) array.append({"device": element.device, "mountpoint": element.mountpoint, "fstype": element.fstype, "total_size": sizeconvert(info.total), "used_size": sizeconvert(info.used), "free_size": sizeconvert(info.free), "percent": info.percent}) else: info = psutil.disk_usage(element.device) array.append({"device": element.device, "mountpoint": element.mountpoint, "fstype": element.fstype, "total_size": sizeconvert(info.total), "used_size": sizeconvert(info.used), "free_size": sizeconvert(info.free), "percent": info.percent}) return array def get_disk_info(mountpoint): for disk in list_disk(): if mountpoint.startswith(disk['mountpoint']): return disk def compare_level(handler_level, operator, level): if operator==">=" and level>=handler_level: return True elif operator=="!=" and level!=handler_level: return True elif operator=="<" and level<handler_level: return True elif operator==">" and level>handler_level: return True elif operator=="<=" and level<=handler_level: return True elif operator=="==" and level==handler_level: return True return False @impmagic.loader( {'module': '__main__'}, {'module': 'os.path','submodule': ['split', 'abspath', 'join']} ) def split_path(): if split(__file__)[0]=="": return join(abspath('.')) else: return join(split(__file__)[0]) @impmagic.loader( {'module': 'os.path', 'submodule':['isabs', 'abspath', 'join']} ) def path_reg(arg): if isabs(arg): return arg return join(split_path(), arg) class Logger: @impmagic.loader( {'module': 'yaml'}, {'module': 'inspect'}, {'module': 'os.path','submodule': ['abspath', 'exists', 'isfile']} ) def __init__(self, configfile = None): self.__handlers = [] self.__count = { 'CRITICAL': 0, 'ERROR': 0, 'WARNING': 0, 'INFO': 0, 'GOOD': 0, 'DEBUG': 0, 'NOTSET': 0, } #Liste des paramètres qui pourront être convertis en module trigger = ["class", "level", "output", "formatter", "secure", "timeout", "stream"] if configfile: configfile = path_reg(configfile) if exists(configfile) and isfile(configfile): with open(configfile, 'rt') as f: try: config = yaml.safe_load(f.read()) if config!=None and "formatters" in config.keys() and "handlers" in config.keys() and "logger" in config.keys(): config_formatter = {} logger = config['logger'] if logger!=None and "handlers" in logger.keys(): handlers = logger['handlers'] if handlers!=None: #Charge les handlers s'ils sont dans le logger for handler_logger in handlers: if handler_logger in config['handlers']: handler = config['handlers'][handler_logger] if handler!=None and "class" in handler.keys() and "formatter" in handler.keys(): class_hand = impmagic.get(handler['class']) if class_hand!=None: #Parce le fichier de conf et génère le dictionnaire des arguments en fonction des paramètres obligatoires signature = inspect.signature(class_hand) args = {} for name, param in signature.parameters.items(): setted = False if name=="credentials": if "user" in handler.keys() and "password" in handler.keys(): args['credentials'] = (handler['user'], handler['password']) setted = True elif name=="ops": if "ops" in handler and (handler['ops']==">=" or handler['ops']=="!=" or handler['ops']=="<" or handler['ops']==">" or handler['ops']=="<=" or handler['ops']=="=="): args['ops'] = handler['ops'] setted = True else: if name in handler.keys(): #Convertis le string en object si besoin if name in trigger and isinstance(handler[name], str) and "." in handler[name]: handler_param = impmagic.get(handler[name]) if handler_param!=None: args[name] = handler_param else: args[name] = handler[name] else: args[name] = handler[name] setted = True #Vérifie si le paramètre obligatoire a été initialisé if not setted and param.default==inspect.Parameter.empty: print(f"Class {handler['class']}: Missing {name} parameter") return #Création de la classe handler handler_called = class_hand(**args) #Ajout du formatter if handler['formatter'] in config_formatter: handler_called.setFormatter(config_formatter[handler['formatter']]) else: if handler['formatter'] in config['formatters']: formname = handler['formatter'] formatter = config['formatters'][formname] if isinstance(formatter, dict) and "format" in formatter.keys() and isinstance(formatter['format'], str): config_formatter[formname] = Formatter(formatter['format']) handler_called.setFormatter(config_formatter[formname]) #Regarde s'il y a des filtres et les ajoutent au handler if "filters" in handler and 'filters' in config.keys() and config['filters']!=None: filters = config['filters'] for fil in handler['filters']: if fil in filters: filter_conf = impmagic.get(filters[fil]) if filter_conf!=None: handler_called.addFilter(filter_conf) else: handler_called.addFilter(filters[fil]) #Ajoute le handler self.add_handler(handler_called) else: print(f"Handler {handler_logger}: Bad configuration") else: print(f"Handler {handler_logger} not found") #Regarde s'il y a des filtres et les ajoutent au logger if len(self.__handlers) and "filters" in logger.keys() and 'filters' in config.keys() and config['filters']!=None: filters = config['filters'] for fil in logger['filters']: if fil in filters: filter_conf = impmagic.get(filters[fil]) if filter_conf!=None: self.addFilter(filter_conf) else: self.addFilter(filters[fil]) else: print("Handlers not configured") else: print("Handlers not configured in logger") except Exception as e: print(f"{e}") return def add_handler(self, handler): if hasattr(handler, "write"): self.__handlers.append(handler) def remove_handler(self, handler): if handler in self.__handlers: self.__handlers.remove(handler) def addFilter(self, filter): for handler in self.__handlers: handler.addFilter(filter) def removeFilter(self, filter): for handler in self.__handlers: handler.removeFilter(filter) def write(self, message, level=0): if len(self.__handlers): if level in _levelToName: name = _levelToName.get(level) self.__count[name]+=1 for handler in self.__handlers: handler.write(message, level) def count(self): return self.__count def log(self, message): self.write(message) def good(self, message): self.write(message, GOOD) def debug(self, message): self.write(message, DEBUG) def info(self, message): self.write(message, INFO) def warning(self, message): self.write(message, WARNING) def error(self, message): self.write(message, ERROR) def critical(self, message): self.write(message, CRITICAL) ##### SET FORMATTER ##### class Formatter: def __init__(self, pattern): self.pattern = pattern @impmagic.loader( {'module': 'sys'}, {'module': 're'}, {'module': 'os'}, {'module': 'inspect'}, {'module': 'psutil'}, {'module': 'platform'}, {'module': 'os','submodule': ['name'], 'as': 'osname'}, {'module': 'os.path','submodule': ['abspath', 'dirname']}, {'module': 'datetime','submodule': ['datetime']}, {'module': 'zpp_color','submodule': ['fg', 'bg', 'attr']} ) def get(self, message, level): result = self.pattern #Parse les arguments du formatter et remplace les trigger format si besoin for res in re.finditer(reg_action,result): insert=None if "asctime" == res.group("action"): date_now = datetime.now().strftime("%d/%m/%Y %H:%M:%S:%f") insert = date_now if re.findall(reg_date, res.group("action")): for rest in re.finditer(reg_date,res.group("action")): date_now = datetime.now().strftime(rest.group("date_format")) result = result.replace(res.group(), date_now) if "epoch" == res.group("action"): epoch = (datetime.now() - datetime(1970, 1, 1)).total_seconds() insert = str(epoch) if "exc_info" == res.group("action"): insert = sys.exc_info() if "levelname" == res.group("action"): insert = _levelToName.get(level,"") if "levelno" == res.group("action"): insert = str(level) if "msg" == res.group("action"): insert = message if "filename" == res.group("action") or "lineno" == res.group("action") or "functname" == res.group("action") or "filepath" == res.group("action"): stack = inspect.stack() if "filename" == res.group("action"): insert = stack[-1].filename if "lineno" == res.group("action"): insert = stack[-1].lineno if "functname" == res.group("action"): if stack[-1].filename==stack[-2].filename: insert = stack[-2].function else: insert = stack[-1].function if "filepath" == res.group("action"): insert = dirname(stack[-1].filename) if "path" == res.group("action"): insert = abspath(os.getcwd()) if "process" == res.group("action"): insert = psutil.Process().name() if "processid" == res.group("action"): insert = str(psutil.Process().pid) if "username" == res.group("action"): insert = os.getlogin() if "uid" == res.group("action") and osname!="nt": insert = str(os.getuid()) if "os_name" == res.group("action"): insert = platform.system() if "os_version" == res.group("action"): insert = platform.version() if "os_archi" == res.group("action"): insert = platform.architecture()[0] if res.group("action").startswith('mem_'): virtual = psutil.virtual_memory() if "mem_total" == res.group("action"): insert = sizeconvert(virtual.total) if "mem_available" == res.group("action"): insert = sizeconvert(virtual.available) if "mem_used" == res.group("action"): insert = sizeconvert(virtual.used) if "mem_free" == res.group("action"): insert = sizeconvert(virtual.free) if "mem_percent" == res.group("action"): insert = str(virtual.percent) if res.group("action").startswith('swap_'): swap = psutil.swap_memory() if "swap_total" == res.group("action"): insert = sizeconvert(swap.total) if "swap_used" == res.group("action"): insert = sizeconvert(swap.used) if "swap_free" == res.group("action"): insert = sizeconvert(swap.free) if "swap_percent" == res.group("action"): insert = str(swap.percent) if "cpu_count" == res.group("action"): insert = str(psutil.cpu_count(logical=False)) if "cpu_logical_count" == res.group("action"): insert = str(psutil.cpu_count(logical=True)) if "cpu_percent" == res.group("action"): insert = str(psutil.cpu_percent(interval=0.1)) if res.group("action").startswith('current_disk'): stack = inspect.stack() disk_info = get_disk_info(abspath(stack[1].filename)) if "current_disk_device" == res.group("action"): insert = disk_info.get('device', '') if "current_disk_mountpoint" == res.group("action"): insert = disk_info.get('mountpoint', '') if "current_disk_fstype" == res.group("action"): insert = disk_info.get('fstype', '') if "current_disk_total" == res.group("action"): insert = str(disk_info.get('total_size', '')) if "current_disk_used" == res.group("action"): insert = str(disk_info.get('used_size', '')) if "current_disk_free" == res.group("action"): insert = str(disk_info.get('free_size', '')) if "current_disk_percent" == res.group("action"): insert = str(str(disk_info.get('percent', ''))) if re.findall(reg_foreground, res.group("action")): for rest in re.finditer(reg_foreground,res.group("action")): if rest.group("color").isdigit(): result = result.replace(f"%({rest.group()})%", fg(int(rest.group("color")))) else: result = result.replace(f"%({rest.group()})%", fg(rest.group("color"))) if re.findall(reg_background,res.group("action")): for rest in re.finditer(reg_background,res.group("action")): if rest.group("color").isdigit(): result = result.replace(f"%({rest.group()})%", bg(int(rest.group("color")))) else: result = result.replace(f"%({rest.group()})%", bg(rest.group("color"))) if re.findall(reg_attribute,res.group("action")): for rest in re.finditer(reg_attribute,res.group("action")): if rest.group("color").isdigit(): result = result.replace(f"%({rest.group()})%", attr(int(rest.group("color")))) else: result = result.replace(f"%({rest.group()})%", attr(rest.group("color"))) if insert!=None: if res.group("padding")!=None and res.group("padding").isdigit(): insert = insert.ljust(int(res.group("padding")), " ") result = result.replace(res.group(), str(insert)) return result ######################### ##### SET HANDLER ##### class Handler: #Modifie le level du handler def setLevel(self, level, ops="=="): if ops==">=" or ops=="!=" or ops=="<" or ops==">" or ops=="<=" or ops=="==": self.operator = ops else: self.operator = "==" if isinstance(level, int) or level.isdigit(): self.level = int(level) #Ajoute le formatter au handler def setFormatter(self, formatter): if hasattr(formatter, "pattern") and hasattr(formatter, "get"): self.formatter = formatter #Utilise le formatter pour formatter le texte avant de l'envoyer au write def format(self, message, level): if hasattr(self, "formatter"): message = self.formatter.get(message, level) return message def addFilter(self, filter): self.filter.append(filter) def removeFilter(self, filter): if filter in self.filter: self.filter.remove(filter) @impmagic.loader( {'module': 're'} ) def check_filter(self): for fil in self.filter: if callable(fil): result = fil(self.message) if result!=True: return False else: try: compiled = re.compile(fil) if not compiled.findall(self.message): return False except re.error: print("Non valid regex pattern") return False except: return False return True class Console_handler(Handler): def __init__(self, output=impmagic.get('sys').stdout, level=NOTSET, ops="=="): Handler.__init__(self) self.__output = output self.setLevel(level, ops) self.filter = [] def write(self, message, level): self.message = self.format(message, level) if self.check_filter(): if self.operator: if compare_level(self.level, self.operator, level): self.__output.write(self.message+"\n") else: self.__output.write(self.message+"\n") class File_handler(Handler): def __init__(self, filename, rewrite=False, level=NOTSET, ops="=="): self.setLevel(level, ops) self.filename = filename self.rewrite = rewrite self.filter = [] @impmagic.loader( {'module': 'os.path','submodule': ['exists', 'isfile']} ) def set_output(self): #Utilise Formatter pour permettre de créer des noms de fichiers dynamique avec la syntaxe des formatter filename = self.get_filename() try: if exists(filename) and isfile(filename) and not self.rewrite: self.__output = open(filename, "a") else: self.__output = open(filename, "w") except Exception as e: print(e) return @impmagic.loader( {'module': 'os.path','submodule': ['abspath']} ) def get_filename(self): return abspath(Formatter(self.filename).get("", self.level)) def write(self, message, level): self.message = self.format(message, level) if self.check_filter(): if self.operator: if compare_level(self.level, self.operator, level): self.set_output() self.__output.write(self.message+"\n") self.__output.close() else: self.set_output() self.__output.write(self.message+"\n") self.__output.close() del self.message class RotateFile_handler(File_handler): def __init__(self, filename, rewrite=False, level=NOTSET, ops="==", maxBytes=None, backupCount=None): super().__init__(filename, rewrite, level, ops) self.maxBytes = maxBytes self.backupCount = backupCount self.current_count = 0 self.current_file = "" self.filter = [] #Retourne le fichier et rotation de fichier si nécessaire @impmagic.loader( {'module': 'os','submodule': ['remove', 'rename']}, {'module': 'os.path','submodule': ['abspath', 'exists', 'getsize']} ) def get_filename(self): filename = abspath(Formatter(self.filename).get("", self.level)) if self.maxBytes!=None: if exists(filename): valid = False if self.current_file!="": filetest = self.current_file else: filetest = filename while not valid: size = getsize(filetest)+len(self.message) if size>self.maxBytes: if self.current_count>=self.backupCount-1: for i in reversed(range(1, self.backupCount)): if i==1: new = filename old = filename+"."+str(i) else: new = filename+"."+str(i-1) old = filename+"."+str(i) if exists(new) and exists(old): remove(old) print(f"remove: {old}") if exists(new): rename(new, old) print(f"move: {new}") valid = True else: self.current_count+=1 filetest = filename+"."+str(self.current_count) if not exists(filetest): print(f"move: {filename}") rename(filename, filetest) valid = True else: valid = True self.current_file = filename return filename class SMTP_handler(Handler): @impmagic.loader( {'module': 'smtplib'} ) def __init__(self, smtphost, fromaddr, toaddrs, subject, credentials=None, secure=None, timeout=5.0, level=NOTSET, ops="=="): if isinstance(smtphost, (list, tuple)): self.smtphost, self.smtpport = smtphost else: self.smtphost, self.smtpport = smtphost, None if not self.smtpport: self.smtpport = smtplib.SMTP_PORT if isinstance(credentials, (list, tuple)): self.username, self.password = credentials else: self.username = None self.fromaddr = fromaddr if isinstance(toaddrs, str): toaddrs = [toaddrs] self.toaddrs = toaddrs self.subject = subject self.secure = secure self.timeout = timeout self.filter = [] self.setLevel(level, ops) def write(self, message, level): self.message = self.format(message, level) if self.check_filter(): if self.operator: if compare_level(self.level, self.operator, level): self.send_mail(self.message) else: self.send_mail(self.message) @impmagic.loader( {'module': 'smtplib'}, {'module': 'email', 'submodule': ['utils']}, {'module': 'email.message', 'submodule': ['EmailMessage']} ) def send_mail(self, message): try: smtp = smtplib.SMTP(self.smtphost, self.smtpport, timeout=self.timeout) msg = EmailMessage() msg['From'] = self.fromaddr msg['To'] = ','.join(self.toaddrs) msg['Subject'] = Formatter(self.subject).get("", self.level) msg['Date'] = utils.localtime() msg.set_content(message) if self.username: if self.secure is not None: smtp.ehlo() #smtp.starttls(*self.secure) smtp.starttls() smtp.ehlo() smtp.login(self.username, self.password) smtp.send_message(msg) smtp.quit() except Exception as e: print("{} - {}".format(type(e).__name__, e)) ####################### ##### STANDALONE ##### def log(message): ptr = Logger() hand = Console_handler(level=NOTSET) hand.setFormatter(Formatter("(msg)")) ptr.add_handler(hand) ptr.log(message) def good(message): ptr = Logger() hand = Console_handler(level=GOOD) hand.setFormatter(Formatter("(fore:10)(msg)(attr:0)")) ptr.add_handler(hand) ptr.good(message) def debug(message): ptr = Logger() hand = Console_handler(level=DEBUG) hand.setFormatter(Formatter("(fore:116)(msg)(attr:0)")) ptr.add_handler(hand) ptr.debug(message) def info(message): ptr = Logger() hand = Console_handler(level=INFO) hand.setFormatter(Formatter("(fore:6)(msg)(attr:0)")) ptr.add_handler(hand) ptr.info(message) def warning(message): ptr = Logger() hand = Console_handler(level=WARNING) hand.setFormatter(Formatter("(fore:11)(msg)(attr:0)")) ptr.add_handler(hand) ptr.warning(message) def error(message): ptr = Logger() hand = Console_handler(level=ERROR) hand.setFormatter(Formatter("(fore:1)(msg)(attr:0)")) ptr.add_handler(hand) ptr.error(message) def critical(message): ptr = Logger() hand = Console_handler(level=CRITICAL) hand.setFormatter(Formatter("(fore:9)(msg)(attr:0)")) ptr.add_handler(hand) ptr.critical(message) #######################
zpp-logs
/zpp_logs-1.0.0-py3-none-any.whl/zpp_logs/zpp_logs.py
zpp_logs.py
# py-menu ## Informations Générateur d'un menu à touches fléchées.<br> Le choix dans le menu se fait à partir des touches fléchées pour la navigation et de la touche Enter pour la validation.<br> Customisation des couleurs du menu et du curseur possibles.<br> Retourne l'indice du choix sélectionné ### Prérequis - Python 3 <br> ## Installation ```console pip install zpp_menu ``` ## Utilisation ```python choice = zpp_menu.Menu(Title, OptionList) ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- Background = Choisir la couleur de font du choix selectionné >- Foreground = Choisir la couleur du texte du choix selectionné >- Pointer = Choisir un pointeur à afficher avant le choix >- Padding = Choisir la taille du décalage entre le titre et les choix >- Selected = Choisir la position du curseur
zpp-menu
/zpp_menu-1.2.3.tar.gz/zpp_menu-1.2.3/README.md
README.md
import os if os.name=="nt": from msvcrt import getch,kbhit else: import sys,tty,os,termios ########################### Getch ########################### def getkey(): if os.name=="nt": c1 = getch() if kbhit(): c2 = getch() if c1 in (b"\x00", b"\xe0"): key_mapping = {72: "up", 80: "down", 77: "right", 75: "left"} return key_mapping.get(ord(c2), c1 + c2) key_mapping = {13: "enter"} return key_mapping.get(ord(c1), c1.decode()) else: old_settings = termios.tcgetattr(sys.stdin) tty.setcbreak(sys.stdin.fileno()) try: while True: b = os.read(sys.stdin.fileno(), 3).decode() if len(b) == 3: k = ord(b[2]) key_mapping = {10: 'enter', 65: 'up', 66: 'down', 67: 'right', 68: 'left'} else: k = ord(b) key_mapping = {10: 'enter'} return key_mapping.get(k, None) finally: termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings) ########################### Color ########################### class ColorClass(object): def __init__(self, idc): self.ESC = "\x1b[" self.END = "m" self.idc = idc if os.name=="nt": self.terminal_mode() self.color = {"black": "0","red": "1","green": "2","yellow": "3","blue": "4","magenta": "5","cyan": "6","light_gray": "7","dark_gray": "8","light_red": "9","light_green": "10","light_yellow": "11","light_blue": "12","light_magenta": "13","light_cyan": "14","white": "15","grey_0": "16","navy_blue": "17","dark_blue": "18","blue_3a": "19","blue_3b": "20","blue_1": "21","dark_green": "22","deep_sky_blue_4a": "23","deep_sky_blue_4b": "24","deep_sky_blue_4c": "25","dodger_blue_3": "26","dodger_blue_2": "27","green_4": "28","spring_green_4": "29","turquoise_4": "30","deep_sky_blue_3a": "31","deep_sky_blue_3b": "32","dodger_blue_1": "33","green_3a": "34","spring_green_3a": "35","dark_cyan": "36","light_sea_green": "37","deep_sky_blue_2": "38","deep_sky_blue_1": "39","green_3b": "40","spring_green_3b": "41","spring_green_2a": "42","cyan_3": "43","dark_turquoise": "44","turquoise_2": "45","green_1": "46","spring_green_2b": "47","spring_green_1": "48","medium_spring_green": "49","cyan_2": "50","cyan_1": "51","dark_red_1": "52","deep_pink_4a": "53","purple_4a": "54","purple_4b": "55","purple_3": "56","blue_violet": "57","orange_4a": "58","grey_37": "59","medium_purple_4": "60","slate_blue_3a": "61","slate_blue_3b": "62","royal_blue_1": "63","chartreuse_4": "64","dark_sea_green_4a": "65","pale_turquoise_4": "66","steel_blue": "67","steel_blue_3": "68","cornflower_blue": "69","chartreuse_3a": "70","dark_sea_green_4b": "71","cadet_blue_2": "72","cadet_blue_1": "73","sky_blue_3": "74","steel_blue_1a": "75","chartreuse_3b": "76","pale_green_3a": "77","sea_green_3": "78","aquamarine_3": "79","medium_turquoise": "80","steel_blue_1b": "81","chartreuse_2a": "82","sea_green_2": "83","sea_green_1a": "84","sea_green_1b": "85","aquamarine_1a": "86","dark_slate_gray_2": "87","dark_red_2": "88","deep_pink_4b": "89","dark_magenta_1": "90","dark_magenta_2": "91","dark_violet_1a": "92","purple_1a": "93","orange_4b": "94","light_pink_4": "95","plum_4": "96","medium_purple_3a": "97","medium_purple_3b": "98","slate_blue_1": "99","yellow_4a": "100","wheat_4": "101","grey_53": "102","light_slate_grey": "103","medium_purple": "104","light_slate_blue": "105","yellow_4b": "106","dark_olive_green_3a": "107","dark_green_sea": "108","light_sky_blue_3a": "109","light_sky_blue_3b": "110","sky_blue_2": "111","chartreuse_2b": "112","dark_olive_green_3b": "113","pale_green_3b": "114","dark_sea_green_3a": "115","dark_slate_gray_3": "116","sky_blue_1": "117","chartreuse_1": "118","light_green_2": "119","light_green_3": "120","pale_green_1a": "121","aquamarine_1b": "122","dark_slate_gray_1": "123","red_3a": "124","deep_pink_4c": "125","medium_violet_red": "126","magenta_3a": "127","dark_violet_1b": "128","purple_1b": "129","dark_orange_3a": "130","indian_red_1a": "131","hot_pink_3a": "132","medium_orchid_3": "133","medium_orchid": "134","medium_purple_2a": "135","dark_goldenrod": "136","light_salmon_3a": "137","rosy_brown": "138","grey_63": "139","medium_purple_2b": "140","medium_purple_1": "141","gold_3a": "142","dark_khaki": "143","navajo_white_3": "144","grey_69": "145","light_steel_blue_3": "146","light_steel_blue": "147","yellow_3a": "148","dark_olive_green_3": "149","dark_sea_green_3b": "150","dark_sea_green_2": "151","light_cyan_3": "152","light_sky_blue_1": "153","green_yellow": "154","dark_olive_green_2": "155","pale_green_1b": "156","dark_sea_green_5b": "157","dark_sea_green_5a": "158","pale_turquoise_1": "159","red_3b": "160","deep_pink_3a": "161","deep_pink_3b": "162","magenta_3b": "163","magenta_3c": "164","magenta_2a": "165","dark_orange_3b": "166","indian_red_1b": "167","hot_pink_3b": "168","hot_pink_2": "169","orchid": "170","medium_orchid_1a": "171","orange_3": "172","light_salmon_3b": "173","light_pink_3": "174","pink_3": "175","plum_3": "176","violet": "177","gold_3b": "178","light_goldenrod_3": "179","tan": "180","misty_rose_3": "181","thistle_3": "182","plum_2": "183","yellow_3b": "184","khaki_3": "185","light_goldenrod_2a": "186","light_yellow_3": "187","grey_84": "188","light_steel_blue_1": "189","yellow_2": "190","dark_olive_green_1a": "191","dark_olive_green_1b": "192","dark_sea_green_1": "193","honeydew_2": "194","light_cyan_1": "195","red_1": "196","deep_pink_2": "197","deep_pink_1a": "198","deep_pink_1b": "199","magenta_2b": "200","magenta_1": "201","orange_red_1": "202","indian_red_1c": "203","indian_red_1d": "204","hot_pink_1a": "205","hot_pink_1b": "206","medium_orchid_1b": "207","dark_orange": "208","salmon_1": "209","light_coral": "210","pale_violet_red_1": "211","orchid_2": "212","orchid_1": "213","orange_1": "214","sandy_brown": "215","light_salmon_1": "216","light_pink_1": "217","pink_1": "218","plum_1": "219","gold_1": "220","light_goldenrod_2b": "221","light_goldenrod_2c": "222","navajo_white_1": "223","misty_rose1": "224","thistle_1": "225","yellow_1": "226","light_goldenrod_1": "227","khaki_1": "228","wheat_1": "229","cornsilk_1": "230","grey_100": "231","grey_3": "232","grey_7": "233","grey_11": "234","grey_15": "235","grey_19": "236","grey_23": "237","grey_27": "238","grey_30": "239","grey_35": "240","grey_39": "241","grey_42": "242","grey_46": "243","grey_50": "244","grey_54": "245","grey_58": "246","grey_62": "247","grey_66": "248","grey_70": "249","grey_74": "250","grey_78": "251","grey_82": "252","grey_85": "253","grey_89": "254","grey_93": "255"} self.mode = {"bold": "1",1: "1","dim": "2",2: "2","italic": "3",3: "3","underlined": "4",4: "4","blink": "5",5: "5","reverse": "7",7: "7","hidden": "8",8: "8","strikethrough": "9",9: "9","reset": "0",0: "0","res_bold": "21",21: "21","res_dim": "22",22: "22","res_underlined": "24",24: "24","res_blink": "25",25: "25","res_reverse": "27",27: "27","res_hidden": "28",28: "28"} def terminal_mode(self): import ctypes kernel32 = ctypes.windll.kernel32 kernel32.SetConsoleMode(kernel32.GetStdHandle(-11), 7) def attribute(self): if self.idc=='None' or self.idc==None: return "" else: if self.idc in self.mode: return self.ESC + self.mode[self.idc] + self.END else: return "" def foreground(self): if self.idc=='None' or self.idc==None: return "" else: if str(self.idc).isdigit(): return self.ESC + "38;5;" + str(self.idc) + self.END else: if self.idc in self.color: return self.ESC + "38;5;" + self.color[self.idc] + self.END else: return "" def background(self): if self.idc=='None' or self.idc==None: return "" else: if str(self.idc).isdigit(): return self.ESC + "48;5;" + str(self.idc) + self.END else: if self.idc in self.color: return self.ESC + "48;5;" + self.color[self.idc] + self.END else: return "" def attr(color): return ColorClass(color).attribute() def fg(color): return ColorClass(color).foreground() def bg(color): return ColorClass(color).background() ########################### Cursor ########################## def com(val): print("\033"+val,end="") def cursorUp(x=1): com("["+str(x)+"A") def cursorDown(x=1): com("["+str(x)+"B") def cursorReset(): com("[0G") def cursorSave(): com("7") def cursorRestore(): com("8") def cursorHide(): com("[?25l") def cursorShow(): com("[?25h") def EraseLine(): com("[2K") ############################ MENU ########################### class MenuClass(): def __init__(self,Title, Options, Background, Foreground, Pointer, Padding): if isinstance(Options,list): self.MenuMax = len(Options)-1 self.Selected = 0 self.Background = Background self.Foreground = Foreground self.Title = Title self.Options = Options cursorHide() self.edgeY = Padding self.pointer = Pointer def __del__(self): cursorShow() def show(self): print(self.Title) for i,element in enumerate(self.Options): if i==self.Selected: print(" "*self.edgeY + self.pointer + fg(self.Foreground)+bg(self.Background)+element+attr(0)) else: print(" "*(self.edgeY+len(self.pointer)) + element) while True: k = getkey() if k=="up": self.Rewrite_line() if self.Selected-1<0: self.Selected=self.MenuMax cursorDown(self.MenuMax) else: self.Selected-=1 cursorUp(1) self.Rewrite_Selected() elif k=="down": self.Rewrite_line() if self.Selected+1>self.MenuMax: self.Selected=0 cursorUp(self.MenuMax) else: self.Selected+=1 cursorDown(1) self.Rewrite_Selected() elif k=="enter": return self.Selected def Rewrite_line(self): cursorSave() EraseLine() cursorUp((self.MenuMax-self.Selected)+1) print(" "*(self.edgeY+len(self.pointer)) + self.Options[self.Selected],end="") def Rewrite_Selected(self): EraseLine() cursorReset() print(" "*self.edgeY + self.pointer + fg(self.Foreground)+bg(self.Background)+self.Options[self.Selected]+attr(0)) cursorRestore() def Menu(Title, Options, Background="", Foreground="yellow", Pointer="", Padding=2, Selected=None): if Selected==None: return MenuClass(Title, Options, Background, Foreground, Pointer, Padding).show() else: mc = MenuClass(Title, Options, Background, Foreground, Pointer, Padding) if isinstance(Selected, int) and Selected<len(Options): mc.Selected = Selected return mc.show()
zpp-menu
/zpp_menu-1.2.3.tar.gz/zpp_menu-1.2.3/zpp_menu/menu.py
menu.py
import re import os import hashlib from bitstring import BitArray def SHat(box, input): result = "" for i in range(32): result = result + SBoxBitstring[box%8][input[4*i:4*(i+1)]] return result def SHatInverse(box, output): result = "" for i in range(32): result = result + SBoxBitstringInverse[box%8][output[4*i:4*(i+1)]] return result def LT(input): if len(input) != 128: raise ValueError("input to LT is not 128 bit long") result = "" for i in range(len(LTTable)): outputBit = "0" for j in LTTable[i]: outputBit = xor(outputBit, input[j]) result = result + outputBit return result def LTInverse(output): if len(output) != 128: raise ValueError("input to inverse LT is not 128 bit long") result = "" for i in range(len(LTTableInverse)): inputBit = "0" for j in LTTableInverse[i]: inputBit = xor(inputBit, output[j]) result = result + inputBit return result def applyPermutation(permutationTable, input): if len(input) != len(permutationTable): raise ValueError("input size (%d) doesn't match perm table size (%d)"% (len(input), len(permutationTable))) result = "" for i in range(len(permutationTable)): result = result + input[permutationTable[i]] return result def R(i, BHati, KHat): xored = xor(BHati, KHat[i]) SHati = SHat(i, xored) if 0 <= i <= r-2: BHatiPlus1 = LT(SHati) elif i == r-1: BHatiPlus1 = xor(SHati, KHat[r]) else: raise ValueError("round %d is out of 0..%d range" % (i, r-1)) return BHatiPlus1 def RInverse(i, BHatiPlus1, KHat): if 0 <= i <= r-2: SHati = LTInverse(BHatiPlus1) elif i == r-1: SHati = xor(BHatiPlus1, KHat[r]) else: raise ValueError("round %d is out of 0..%d range" % (i, r-1)) xored = SHatInverse(i, SHati) BHati = xor(xored, KHat[i]) return BHati def encrypt(plainText, userKey): K, KHat = makeSubkeys(userKey) BHat = applyPermutation(IPTable, plainText) for i in range(r): BHat = R(i, BHat, KHat) C = applyPermutation(FPTable, BHat) return C def decrypt(cipherText, userKey): K, KHat = makeSubkeys(userKey) BHat = applyPermutation(IPTable, cipherText) for i in range(r-1, -1, -1): BHat = RInverse(i, BHat, KHat) plainText = applyPermutation(FPTable, BHat) return plainText def encrypt_ECB(plainText,userKey,hash_type='sha256',lvl=2): salt = os.urandom(SALT_SIZE) key = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=KEY_SIZE) key = BitArray(key).bin cleartext = BitArray(plainText).bin result=BitArray(bin=encrypt(BitArray(salt).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes if len(cleartext)<=128: lvl=1 bloclist = [] bloclist.append(cleartext) else: bloclist = re.findall('.{1,128}', cleartext) if lvl==1: liste = bloclist[0:len(bloclist)-1] elif lvl==2: liste = bloclist[0:len(bloclist)-2] for bloc in liste: encrypted = encrypt(bloc, key) result += BitArray(bin=encrypted).bytes if lvl==1: bloc = bloclist[len(bloclist)-1] if len(bloc)!=128: bloc = add_rembour(bloc) encrypted = encrypt(bloc, key) result += BitArray(bin=encrypted).bytes elif lvl==2: blocA = encrypt(bloclist[len(bloclist)-2],key) blocB = bloclist[len(bloclist)-1] sbreak = 128-len(blocB) blocA2 = blocA[0:len(blocA)-sbreak] blocAdd = blocA[len(blocA)-sbreak:len(blocA)] blocB2 = encrypt(blocB+blocAdd,key) result += BitArray(bin=blocB2).bytes result += BitArray(bin=blocA2).bytes return result def encrypt_CBC(plainText,userKey,hash_type='sha256',lvl=2): salt = os.urandom(SALT_SIZE) derived = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=IV_SIZE + KEY_SIZE) key = BitArray(derived[IV_SIZE:]).bin cleartext = BitArray(plainText).bin iv = BitArray(derived[0:IV_SIZE]).bin result=BitArray(bin=encrypt(BitArray(salt).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes if len(cleartext)<=128: lvl=1 bloclist = [] bloclist.append(cleartext) else: bloclist = re.findall('.{1,128}', cleartext) if lvl==1: liste = bloclist[0:len(bloclist)-1] elif lvl==2: liste = bloclist[0:len(bloclist)-2] for bloc in liste: bloc = binaryXor(bloc,iv) encrypted = encrypt(bloc, key) iv = encrypted result += BitArray(bin=encrypted).bytes if lvl==1: bloc = bloclist[len(bloclist)-1] if len(bloc)!=128: bloc = add_rembour(bloc) bloc = binaryXor(bloc,iv) encrypted = encrypt(bloc, key) result += BitArray(bin=encrypted).bytes elif lvl==2: blocA = binaryXor(bloclist[len(bloclist)-2], iv) blocA = encrypt(blocA,key) blocB = bloclist[len(bloclist)-1] sbreak = 128-len(blocB) blocA2 = blocA[0:len(blocA)-sbreak] blocB += "0"*sbreak blocB = binaryXor(blocA, blocB) blocB2 = encrypt(blocB,key) result += BitArray(bin=blocB2).bytes result += BitArray(bin=blocA2).bytes return result def encrypt_CFB(plainText,userKey,hash_type='sha256'): salt = os.urandom(SALT_SIZE) derived = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=IV_SIZE + KEY_SIZE) key = BitArray(derived[IV_SIZE:]).bin cleartext = BitArray(plainText).bin iv = BitArray(derived[0:IV_SIZE]).bin liste = re.findall('.{1,128}', cleartext) result=BitArray(bin=encrypt(BitArray(salt).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes for bloc in liste: if len(bloc)!=128: bloc = add_rembour(bloc) encrypted = encrypt(iv, key) bloc = binaryXor(bloc,encrypted) iv = bloc result += BitArray(bin=bloc).bytes return result def encrypt_PCBC(plainText,userKey,hash_type='sha256'): salt = os.urandom(SALT_SIZE) derived = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=IV_SIZE + KEY_SIZE) key = BitArray(derived[IV_SIZE:]).bin cleartext = BitArray(plainText).bin iv = BitArray(derived[0:IV_SIZE]).bin liste = re.findall('.{1,128}', cleartext) result=BitArray(bin=encrypt(BitArray(salt).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes for bloc in liste: if len(bloc)!=128: bloc = add_rembour(bloc) blocxor = binaryXor(bloc,iv) encrypted = encrypt(blocxor, key) iv = binaryXor(bloc,encrypted) result += BitArray(bin=encrypted).bytes return result def decrypt_ECB(cipherText,userKey,hash_type='sha256',lvl=2): salt = BitArray(bin=decrypt(BitArray(cipherText[0:SALT_SIZE]).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes key = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=KEY_SIZE) key = BitArray(key).bin cipherText = BitArray(cipherText[SALT_SIZE:]).bin result=b"" if len(cipherText)<=128: lvl=1 bloclist = [] bloclist.append(cipherText) else: bloclist = re.findall('.{1,128}', cipherText) if lvl==1: liste = bloclist[0:len(bloclist)-1] elif lvl==2: liste = bloclist[0:len(bloclist)-2] for bloc in liste: encrypted = decrypt(bloc, key) result += BitArray(bin=encrypted).bytes if lvl==1: last_bloc = decrypt(bloclist[len(bloclist)-1], key) result+=del_rembour(last_bloc) elif lvl==2: blocA = decrypt(bloclist[len(bloclist)-2],key) blocB = bloclist[len(bloclist)-1] sbreak = 128-len(blocB) blocA2 = blocA[0:len(blocA)-sbreak] blocAdd = blocA[len(blocA)-sbreak:len(blocA)] blocB2 = decrypt(blocB+blocAdd,key) result += BitArray(bin=blocB2).bytes result += BitArray(bin=blocA2).bytes return result def decrypt_CBC(cipherText,userKey,hash_type='sha256',lvl=2): salt = BitArray(bin=decrypt(BitArray(cipherText[0:SALT_SIZE]).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes derived = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=IV_SIZE + KEY_SIZE) key = BitArray(derived[IV_SIZE:]).bin cipherText = BitArray(cipherText[SALT_SIZE:]).bin iv = BitArray(derived[0:IV_SIZE]).bin result=b"" if len(cipherText)<=128: lvl=1 bloclist = [] bloclist.append(cipherText) else: bloclist = re.findall('.{1,128}', cipherText) if lvl==1: liste = bloclist[0:len(bloclist)-1] elif lvl==2: liste = bloclist[0:len(bloclist)-2] for bloc in liste: encrypted = decrypt(bloc, key) encrypted = binaryXor(encrypted,iv) result += BitArray(bin=encrypted).bytes iv = bloc if lvl==1: last_bloc = decrypt(bloclist[len(bloclist)-1], key) last_bloc = binaryXor(last_bloc,iv) result+=del_rembour(last_bloc) elif lvl==2: blocA = bloclist[len(bloclist)-2] blocB = bloclist[len(bloclist)-1] sbreak = 128-len(blocB) blocA = decrypt(blocA, key) blocB+=blocA[len(blocA)-sbreak:len(blocA)] blocA = binaryXor(blocA,blocB) blocB = decrypt(blocB,key) blocB = binaryXor(blocB,iv) result += BitArray(bin=blocB).bytes result += BitArray(bin=blocA).bytes return result def decrypt_CFB(cipherText,userKey,hash_type='sha256'): salt = BitArray(bin=decrypt(BitArray(cipherText[0:SALT_SIZE]).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes derived = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=IV_SIZE + KEY_SIZE) key = BitArray(derived[IV_SIZE:]).bin cipherText = BitArray(cipherText[SALT_SIZE:]).bin iv = BitArray(derived[0:IV_SIZE]).bin liste = re.findall('.{1,128}', cipherText) result=b"" for bloc in liste[0:len(liste)-1]: encrypted = encrypt(iv, key) encrypted = binaryXor(encrypted,bloc) result += BitArray(bin=encrypted).bytes iv = bloc encrypted = encrypt(iv, key) last_bloc = binaryXor(encrypted,liste[len(liste)-1]) result+=del_rembour(last_bloc) return result def decrypt_PCBC(cipherText,userKey,hash_type='sha256'): salt = BitArray(bin=decrypt(BitArray(cipherText[0:SALT_SIZE]).bin,BitArray(hashlib.sha256(userKey).digest()).bin)).bytes derived = hashlib.pbkdf2_hmac(hash_type, userKey, salt, 100000,dklen=IV_SIZE + KEY_SIZE) key = BitArray(derived[IV_SIZE:]).bin cipherText = BitArray(cipherText[SALT_SIZE:]).bin iv = BitArray(derived[0:IV_SIZE]).bin liste = re.findall('.{1,128}', cipherText) result=b"" for bloc in liste[0:len(liste)-1]: encrypted = decrypt(bloc, key) encrypted = binaryXor(encrypted,iv) iv = binaryXor(encrypted,bloc) result += BitArray(bin=encrypted).bytes encrypted = decrypt(liste[len(liste)-1], key) last_bloc = binaryXor(encrypted,iv) result+=del_rembour(last_bloc) return result def add_rembour(bloc): rep = round((128-len(bloc))/8) if rep<10: bour="0"+str(rep) else: bour=str(rep) pattern = (BitArray(hex=bour).bin)*rep bloc += pattern return bloc def del_rembour(bloc): for i in range(32,0,-1): if i<10: bour="0"+str(i) else: bour=str(i) pattern = (BitArray(hex=bour).bin)*i if bloc.endswith(pattern): return BitArray(bin=bloc[:-(i*8)]).bytes return BitArray(bin=bloc).bytes def makeSubkeys(userKey): w = {} for i in range(-8, 0): w[i] = userKey[(i+8)*32:(i+9)*32] for i in range(132): w[i] = rotateLeft(xor(w[i-8], w[i-5], w[i-3], w[i-1],bitstring(phi, 32), bitstring(i,32)),11) k = {} for i in range(r+1): whichS = (r + 3 - i) % r k[0+4*i] = "" k[1+4*i] = "" k[2+4*i] = "" k[3+4*i] = "" for j in range(32): input = w[0+4*i][j] + w[1+4*i][j] + w[2+4*i][j] + w[3+4*i][j] output = SBoxBitstring[whichS%8][input] for l in range(4): k[l+4*i] = k[l+4*i] + output[l] K = [] for i in range(33): K.append(k[4*i] + k[4*i+1] + k[4*i+2] + k[4*i+3]) KHat = [] for i in range(33): KHat.append(applyPermutation(IPTable, K[i])) return K, KHat def bitstring(n, minlen=1): if minlen < 1: raise ValueError("a bitstring must have at least 1 char") if n < 0: raise ValueError("bitstring representation undefined for neg numbers") result = "" while n > 0: if n & 1: result = result + "1" else: result = result + "0" n = n >> 1 if len(result) < minlen: result = result + "0" * (minlen - len(result)) return result def binaryXor(n1, n2): if len(n1) != len(n2): raise ValueError("can't xor bitstrings of different " + "lengths (%d and %d)" % (len(n1), len(n2))) result = "" for i in range(len(n1)): if n1[i] == n2[i]: result = result + "0" else: result = result + "1" return result def xor(*args): if args == []: raise ValueError("at least one argument needed") result = args[0] for arg in args[1:]: result = binaryXor(result, arg) return result def rotateLeft(input, places): p = places % len(input) return input[-p:] + input[:-p] # Constants IV_SIZE = 16 KEY_SIZE = 32 SALT_SIZE = 16 phi = 2654435769 r = 32 # Data tables SBoxDecimalTable = [[ 3, 8,15, 1,10, 6, 5,11,14,13, 4, 2, 7, 0, 9,12 ],[15,12, 2, 7, 9, 0, 5,10, 1,11,14, 8, 6,13, 3, 4 ],[ 8, 6, 7, 9, 3,12,10,15,13, 1,14, 4, 0,11, 5, 2 ],[ 0,15,11, 8,12, 9, 6, 3,13, 1, 2, 4,10, 7, 5,14 ],[ 1,15, 8, 3,12, 0,11, 6, 2, 5, 4,10, 9,14, 7,13 ],[15, 5, 2,11, 4,10, 9,12, 0, 3,14, 8,13, 6, 7, 1 ],[ 7, 2,12, 5, 8, 4, 6,11,14, 9, 1,15,13, 3,10, 0 ],[ 1,13,15, 0,14, 8, 2,11, 7, 4,12,10, 9, 3, 5, 6 ]] SBoxBitstring = [] SBoxBitstringInverse = [] for line in SBoxDecimalTable: dict = {} inverseDict = {} for i in range(len(line)): index = bitstring(i, 4) value = bitstring(line[i], 4) dict[index] = value inverseDict[value] = index SBoxBitstring.append(dict) SBoxBitstringInverse.append(inverseDict) IPTable = [0, 32, 64, 96, 1, 33, 65, 97, 2, 34, 66, 98, 3, 35, 67, 99,4, 36, 68, 100, 5, 37, 69, 101, 6, 38, 70, 102, 7, 39, 71, 103,8, 40, 72, 104, 9, 41, 73, 105, 10, 42, 74, 106, 11, 43, 75, 107,12, 44, 76, 108, 13, 45, 77, 109, 14, 46, 78, 110, 15, 47, 79, 111,16, 48, 80, 112, 17, 49, 81, 113, 18, 50, 82, 114, 19, 51, 83, 115,20, 52, 84, 116, 21, 53, 85, 117, 22, 54, 86, 118, 23, 55, 87, 119,24, 56, 88, 120, 25, 57, 89, 121, 26, 58, 90, 122, 27, 59, 91, 123,28, 60, 92, 124, 29, 61, 93, 125, 30, 62, 94, 126, 31, 63, 95, 127] FPTable = [0, 4, 8, 12, 16, 20, 24, 28, 32, 36, 40, 44, 48, 52, 56, 60,64, 68, 72, 76, 80, 84, 88, 92, 96, 100, 104, 108, 112, 116, 120, 124,1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53, 57, 61,65, 69, 73, 77, 81, 85, 89, 93, 97, 101, 105, 109, 113, 117, 121, 125,2, 6, 10, 14, 18, 22, 26, 30, 34, 38, 42, 46, 50, 54, 58, 62,66, 70, 74, 78, 82, 86, 90, 94, 98, 102, 106, 110, 114, 118, 122, 126,3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47, 51, 55, 59, 63,67, 71, 75, 79, 83, 87, 91, 95, 99, 103, 107, 111, 115, 119, 123, 127] LTTable = [[16, 52, 56, 70, 83, 94, 105],[72, 114, 125],[2, 9, 15, 30, 76, 84, 126],[36, 90, 103],[20, 56, 60, 74, 87, 98, 109],[1, 76, 118],[2, 6, 13, 19, 34, 80, 88],[40, 94, 107],[24, 60, 64, 78, 91, 102, 113],[5, 80, 122],[6, 10, 17, 23, 38, 84, 92],[44, 98, 111],[28, 64, 68, 82, 95, 106, 117],[9, 84, 126],[10, 14, 21, 27, 42, 88, 96],[48, 102, 115],[32, 68, 72, 86, 99, 110, 121],[2, 13, 88],[14, 18, 25, 31, 46, 92, 100],[52, 106, 119],[36, 72, 76, 90, 103, 114, 125],[6, 17, 92],[18, 22, 29, 35, 50, 96, 104],[56, 110, 123],[1, 40, 76, 80, 94, 107, 118],[10, 21, 96],[22, 26, 33, 39, 54, 100, 108],[60, 114, 127],[5, 44, 80, 84, 98, 111, 122],[14, 25, 100],[26, 30, 37, 43, 58, 104, 112],[3, 118],[9, 48, 84, 88, 102, 115, 126],[18, 29, 104],[30, 34, 41, 47, 62, 108, 116],[7, 122],[2, 13, 52, 88, 92, 106, 119],[22, 33, 108],[34, 38, 45, 51, 66, 112, 120],[11, 126],[6, 17, 56, 92, 96, 110, 123],[26, 37, 112],[38, 42, 49, 55, 70, 116, 124],[2, 15, 76],[10, 21, 60, 96, 100, 114, 127],[30, 41, 116],[0, 42, 46, 53, 59, 74, 120],[6, 19, 80],[3, 14, 25, 100, 104, 118],[34, 45, 120],[4, 46, 50, 57, 63, 78, 124],[10, 23, 84],[7, 18, 29, 104, 108, 122],[38, 49, 124],[0, 8, 50, 54, 61, 67, 82],[14, 27, 88],[11, 22, 33, 108, 112, 126],[0, 42, 53],[4, 12, 54, 58, 65, 71, 86],[18, 31, 92],[2, 15, 26, 37, 76, 112, 116],[4, 46, 57],[8, 16, 58, 62, 69, 75, 90],[22, 35, 96],[6, 19, 30, 41, 80, 116, 120],[8, 50, 61],[12, 20, 62, 66, 73, 79, 94],[26, 39, 100],[10, 23, 34, 45, 84, 120, 124],[12, 54, 65],[16, 24, 66, 70, 77, 83, 98],[30, 43, 104],[0, 14, 27, 38, 49, 88, 124],[16, 58, 69],[20, 28, 70, 74, 81, 87, 102],[34, 47, 108],[0, 4, 18, 31, 42, 53, 92],[20, 62, 73],[24, 32, 74, 78, 85, 91, 106],[38, 51, 112],[4, 8, 22, 35, 46, 57, 96],[24, 66, 77],[28, 36, 78, 82, 89, 95, 110],[42, 55, 116],[8, 12, 26, 39, 50, 61, 100],[28, 70, 81],[32, 40, 82, 86, 93, 99, 114],[46, 59, 120],[12, 16, 30, 43, 54, 65, 104],[32, 74, 85],[36, 90, 103, 118],[50, 63, 124],[16, 20, 34, 47, 58, 69, 108],[36, 78, 89],[40, 94, 107, 122],[0, 54, 67],[20, 24, 38, 51, 62, 73, 112],[40, 82, 93],[44, 98, 111, 126],[4, 58, 71],[24, 28, 42, 55, 66, 77, 116],[44, 86, 97],[2, 48, 102, 115],[8, 62, 75],[28, 32, 46, 59, 70, 81, 120],[48, 90, 101],[6, 52, 106, 119],[12, 66, 79],[32, 36, 50, 63, 74, 85, 124],[52, 94, 105],[10, 56, 110, 123],[16, 70, 83],[0, 36, 40, 54, 67, 78, 89],[56, 98, 109],[14, 60, 114, 127],[20, 74, 87],[4, 40, 44, 58, 71, 82, 93],[60, 102, 113],[3, 18, 72, 114, 118, 125],[24, 78, 91],[8, 44, 48, 62, 75, 86, 97],[64, 106, 117],[1, 7, 22, 76, 118, 122],[28, 82, 95],[12, 48, 52, 66, 79, 90, 101],[68, 110, 121],[5, 11, 26, 80, 122, 126],[32, 86, 99],] LTTableInverse = [[53, 55, 72],[1, 5, 20, 90],[15, 102],[3, 31, 90],[57, 59, 76],[5, 9, 24, 94],[19, 106],[7, 35, 94],[61, 63, 80],[9, 13, 28, 98],[23, 110],[11, 39, 98],[65, 67, 84],[13, 17, 32, 102],[27, 114],[1, 3, 15, 20, 43, 102],[69, 71, 88],[17, 21, 36, 106],[1, 31, 118],[5, 7, 19, 24, 47, 106],[73, 75, 92],[21, 25, 40, 110],[5, 35, 122],[9, 11, 23, 28, 51, 110],[77, 79, 96],[25, 29, 44, 114],[9, 39, 126],[13, 15, 27, 32, 55, 114],[81, 83, 100],[1, 29, 33, 48, 118],[2, 13, 43],[1, 17, 19, 31, 36, 59, 118],[85, 87, 104],[5, 33, 37, 52, 122],[6, 17, 47],[5, 21, 23, 35, 40, 63, 122],[89, 91, 108],[9, 37, 41, 56, 126],[10, 21, 51],[9, 25, 27, 39, 44, 67, 126],[93, 95, 112],[2, 13, 41, 45, 60],[14, 25, 55],[2, 13, 29, 31, 43, 48, 71],[97, 99, 116],[6, 17, 45, 49, 64],[18, 29, 59],[6, 17, 33, 35, 47, 52, 75],[101, 103, 120],[10, 21, 49, 53, 68],[22, 33, 63],[10, 21, 37, 39, 51, 56, 79],[105, 107, 124],[14, 25, 53, 57, 72],[26, 37, 67],[14, 25, 41, 43, 55, 60, 83],[0, 109, 111],[18, 29, 57, 61, 76],[30, 41, 71],[18, 29, 45, 47, 59, 64, 87],[4, 113, 115],[22, 33, 61, 65, 80],[34, 45, 75],[22, 33, 49, 51, 63, 68, 91],[8, 117, 119],[26, 37, 65, 69, 84],[38, 49, 79],[26, 37, 53, 55, 67, 72, 95],[12, 121, 123],[30, 41, 69, 73, 88],[42, 53, 83],[30, 41, 57, 59, 71, 76, 99],[16, 125, 127],[34, 45, 73, 77, 92],[46, 57, 87],[34, 45, 61, 63, 75, 80, 103],[1, 3, 20],[38, 49, 77, 81, 96],[50, 61, 91],[38, 49, 65, 67, 79, 84, 107],[5, 7, 24],[42, 53, 81, 85, 100],[54, 65, 95],[42, 53, 69, 71, 83, 88, 111],[9, 11, 28],[46, 57, 85, 89, 104],[58, 69, 99],[46, 57, 73, 75, 87, 92, 115],[13, 15, 32],[50, 61, 89, 93, 108],[62, 73, 103],[50, 61, 77, 79, 91, 96, 119],[17, 19, 36],[54, 65, 93, 97, 112],[66, 77, 107],[54, 65, 81, 83, 95, 100, 123],[21, 23, 40],[58, 69, 97, 101, 116],[70, 81, 111],[58, 69, 85, 87, 99, 104, 127],[25, 27, 44],[62, 73, 101, 105, 120],[74, 85, 115],[3, 62, 73, 89, 91, 103, 108],[29, 31, 48],[66, 77, 105, 109, 124],[78, 89, 119],[7, 66, 77, 93, 95, 107, 112],[33, 35, 52],[0, 70, 81, 109, 113],[82, 93, 123],[11, 70, 81, 97, 99, 111, 116],[37, 39, 56],[4, 74, 85, 113, 117],[86, 97, 127],[15, 74, 85, 101, 103, 115, 120],[41, 43, 60],[8, 78, 89, 117, 121],[3, 90],[19, 78, 89, 105, 107, 119, 124],[45, 47, 64],[12, 82, 93, 121, 125],[7, 94],[0, 23, 82, 93, 109, 111, 123],[49, 51, 68],[1, 16, 86, 97, 125],[11, 98],[4, 27, 86, 97, 113, 115, 127],]
zpp-serpent
/zpp_serpent-2.2.2-py3-none-any.whl/zpp_serpent/serpent.py
serpent.py
# zpp This is zpp, the Z Pre-Processor. Zpp transforms bash in a pre-processor for F90 source files. It offers a set of functions specifically tailored to build clean Fortran90 interfaces by generating code for all types, kinds, and array ranks supported by a given compiler. ## Syntax Zpp files are typically named `*.F90.zpp`. In these files, the lines that start with `!$SH` are interpreted as bash lines. Other lines are copied as-is, except that variable substitution is operated as in a double-quoted string, including bash commands `${VAR}` or `$(command)`. If inside a bash control block (`if`, `for`, etc.), the output generation obeys the control statement. For example, this code: ``` !$SH for GREETED in world universe multiverse ; do print *, "Hello ${GREETED}" !$SH done ``` Would produce the following result: ``` print *, "Hello world" print *, "Hello universe" print *, "Hello multiverse" ``` ### Support functions Predefined bash functions, variable and code can be provided in `.zpp.sh` files that can be included with `#!SH source <filename>.zpp.sh`. **Beware**: a file NEEDs to have the `.zpp.sh` extension to be included from zpp. Zpp provides a standard library of functions tailored to build clean Fortran90 interfaces by generating code for all types, kinds, and array ranks supported by a given compiler. #### zpp_str_repeat Found in `base.zpp.sh` Outputs a string multiple times. Parameters: 1. the string to Repeat 2. the lower bound of the iterations (inclusive) 3. the upper bound of the iterations (inclusive) 4. the string separator 5. the string starter 6. the string ender Repeats string `$1` (`$3`-`$2`+1) times, separated by string `$4` inside `$5` `$6`. * If the number of repetitions is negative, the result is empty. * If `$1` contains the '@N' substring, it will be replaced by the iteration number (from `$2` to `$3`). example: ``` #!SH source base.zpp.sh zpp_str_repeat v@N 5 7 '...' '<<' '>>' zpp_str_repeat w@N 1 1 '...' '<<' '>>' zpp_str_repeat x@N 1 0 '...' '<<' '>>' ``` output: ``` <<v5...v6...v7>> <<w1>> ``` #### zpp_str_repeat_reverse Found in `base.zpp.sh` Outputs a string multiple times in reverse order. Parameters: 1. the string to Repeat 2. the upper bound of the iterations (inclusive) 3. the lower bound of the iterations (inclusive) 4. the string separator 5. the string starter 6. the string ender Repeats string `$1` (`$2`-`$3`+1) times, separated by string `$4` inside `$5` `$6`. * If the number of repetitions is negative, the result is empty. * If `$1` contains the '@N' substring, it will be replaced by the iteration number (from `$2` to `$3`, i.e. upper to lower). example: ``` #!SH source base.zpp.sh zpp_str_repeat_reverse v@N 5 7 '...' '<<' '>>' zpp_str_repeat_reverse w@N 1 1 '...' '<<' '>>' zpp_str_repeat_reverse x@N 1 0 '...' '<<' '>>' ``` output: ``` <<v7...v6...v5>> <<w1>> ``` #### ZPP_FORT_TYPES Found in `fortran.zpp.sh` The list of types supported by the fortran compiler as zpp:typeIDs. The compiler ID should be provided in `ZPP_CONFIG` as `config.<ID>`. The supported predefined IDs are: `Gnu`, `Intel`, `PGI` and `XL`. You can also provide definitions for an additional compiler by defining `ZPP_FORT_TYPES` in a file named `config.<ID>.zpp.sh`. If you use cmake, it will automatically generate such a file for your compiler and define `ZPP_CONFIG` so you don't have to handle it. ### zpp_fort_array_desc Found in `fortran.zpp.sh` Outputs an assumed shaped array descriptor of the provided size. Parameters: 1. the size of the assumed shaped array example: ``` #!SH source fortran.zpp.sh integer:: scalar$(zpp_fort_array_desc 0) integer:: array1d$(zpp_fort_array_desc 1) integer:: array2d$(zpp_fort_array_desc 2) ``` output: ``` integer:: scalar integer:: array1d(:) integer:: array2d(:,:) ``` ### zpp_fort_ptype Found in `fortran.zpp.sh` Outputs the type associated to a zpp:typeID. Parameters: 1. a zpp:typeID example: ``` #!SH source fortran.zpp.sh !$SH for T in ${ZPP_FORT_TYPES} ; do $(zpp_fort_ptype $1) !$SH done ``` example output: ``` CHARACTER COMPLEX COMPLEX INTEGER INTEGER INTEGER INTEGER LOGICAL REAL REAL ``` ### zpp_fort_kind Found in `fortran.zpp.sh` Outputs the kind associated to a zpp:typeID. Parameters: 1. a zpp:typeID example: ``` #!SH source fortran.zpp.sh !$SH for T in ${ZPP_FORT_TYPES} ; do $(zpp_fort_kind $1) !$SH done ``` example output: ``` 1 4 8 1 2 4 8 1 4 8 ``` ### zpp_fort_type Found in `fortran.zpp.sh` Outputs the full type (with kind included) associated to a zpp:typeID. Parameters: 1. a zpp:typeID 2. additional attributes for the type example: ``` #!SH source fortran.zpp.sh !$SH for T in ${MY_CHAR_TYPES} ; do $(zpp_fort_type $1) $(zpp_fort_type $1 "len=5") !$SH done ``` example output: ``` CHARACTER(KIND=1) CHARACTER(KIND=1,len=5) ``` ### zpp_fort_sizeof Found in `fortran.zpp.sh` Outputs the size in bits associated to a zpp:typeID. Parameters: 1. a zpp:typeID ### zpp_fort_io_format Found in `fortran.zpp.sh` Outputs an IO descriptor suitable for a zpp:typeID. Parameters: 1. a zpp:typeID ### ZPP_HDF5F_TYPES Found in `hdf5_fortran.zpp.sh` A list of zpp:typeIDs supported by HDF5. ### hdf5_constant Found in `hdf5_fortran.zpp.sh` Outputs the HDF5 type constant associated to a zpp:typeID. Parameters: 1. a zpp:typeID example: ``` #!SH source hdf5_fortran.zpp.sh !$SH for T in ${ZPP_HDF5F_TYPES} ; do $(hdf5_constant $1) !$SH done ``` example output: ``` H5T_NATIVE_INTEGER H5T_NATIVE_REAL H5T_NATIVE_REAL H5T_NATIVE_CHARACTER ``` ## Command-line interface Zpp basic usage is as follow: ``` Usage: zpp [Options...] <source> [<destination>] use `zpp -h' for more info Preprocesses BASH in-line commands in a source file Options: --version show program's version number and exit -h, --help show this help message and exit -I DIR Add DIR to search list for source directives -o FILE Place the preprocessed code in file FILE. -D OPTION=VALUE Set the value of OPTION to VALUE ``` ## CMake interface Support is provided for using zpp from CMake based projects, but you can use it from plain Makefiles too. There are two ways you can use zpp from your CMake project: * with `add_subdirectory`: include zpp in your project and use it directly from there, * with `find_package`: install zpp and use it as an external dependency of your project. #### CMake subdirectory usage Using zpp with `add_subdirectory` is very simple. Just copy the `zpp` directory in your source and point to it with `add_subdirectory(zpp)`. The `zpp_preprocess` then becomes available to process zpp files. This is demonstrated in `example/cmake_subdirectory`. #### CMake find usage Using zpp with `find_package` is no more complex. If zpp is installed, just add a `find_package(zpp REQUIRED)`. The `zpp_preprocess` then becomes available to process zpp files. This is demonstrated in `example/cmake_find`. ## GMake usage Using zpp from a GNU Makefile is slightly less powerful than from CMake. The types and kinds supported by the Fortran compiler will not be automatically detected. Predefined lists of supported types for well known compilers are provided instead. To use zpp from a Makefile, include the `share/zpp/zpp.mk` file (either from an installed location or from a subdirectory in your project). You can then set the `zpp_COMPILER_ID` variable to the compiler you use and `.F90` files will be automatically generated from their `.F90.zpp` equivalent. The `zppFLAGS` variable is automatically passed to zpp similarly to `CFLAGS` or `CXXFLAGS` for `cc` and `cxx`. This is demonstrated in `example/cmake_makefile`. ## Installation Zpp can be installed using the usual python way with `setup.py`. ``` ./setup.py --help ``` The cmake approach is deprecated. ## FAQ Q. Isn't zpp redundant with assumed type parameters? A. The assumed type parameters functionality allows to implement part of what can be done with zpp (support for all kinds of a type). However as of 2013 it was not correctly supported on most compilers installed on the supercomputers. In addition, many things can be done with zpp but not with assumed type parameters, such as support for variable array rank or small variations of the code depending on the kind.
zpp
/zpp-1.0.16.tar.gz/zpp-1.0.16/README.md
README.md
# zpp-args ## Informations Module pour le traitement des arguments d'une ligne de commande. <br>Trois sources possibles: - sys.argv - une chaîne de caractère - une liste ### Prérequis - Python 3 <br> # Installation ```console pip install zpp_args ``` # Utilisation ### Conseil d'importation du module ```python from zpp_args import parser ``` <br> ### Initialisation du parser ```python parse = parser(SOURCE, error_lock=False) ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- error_lock: Purge le retour de la fonction si une erreur s'est produite (Par défaut: False) <br> ### Initialisation des arguments ```python parse.set_argument(NAME) ``` L'initialisation doit prendre au moins un des deux paramètres suivants: - shortcut: Pour les arguments courts (1 caractère) - longname: Pour les arguments explicites (1 mot ou ensemble de mots séparés par le symbole \_) _Si non précisé, la fonction initialise shortcut_ >En paramètre supplémentaire, nous pouvons mettre:<br/> >- error_lock: Purge le retour de la fonction si une erreur s'est produite (Par défaut: ) >- type: Pour forcer l'argument reçu à un str ou un digit (Par défaut: None) >- default: Pour choisir une valeur par défaut(Par défaut: None) >- description: Pour ajouter une description à l'argument à afficher lors de l'appel de la commande help(Par défaut: None) >- required: Choisir si cet argument est nécessaire (Par défaut: False) >- store: Choisir si l'argument' est un simple True/False ou s'il attends une variable (Par défaut: bool) >- category: Choisir une catégorie pour l'affichage du help <br> ### Initialisation des paramètres L'initialisation des paramètres va permettre d'agrémenter la commande help et de fixer une limite minimum lors de la récupération des paramètres ```python parse.set_argument(NAME) ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- description: Pour ajouter une description au paramètre à afficher lors de l'appel de la commande help(Par défaut: None) <br> ### Execution du parseur ```python argument, parameter = parse.load() ``` Retourne une liste avec les paramètres et une classe (StoreArgument) avec les arguments La StoreArgument peut retourner un dictionnaire en appelant argument.list_all() <br> ### Initialisation de la description de la commande ```python parse.set_description(DESCRIPTION) ``` <br> ### Affichage de l'aide ```python parse.help() ``` <br> ### Désactiver le check sur les paramètres Pour désactiver le check du nombre de paramètres à envoyer, il suffit d'appeler la fonction suivante. ```python parse.disable_check() ```
zpp_args
/zpp_args-1.3.2.tar.gz/zpp_args-1.3.2/README.md
README.md
# zpp-config ## Informations Librairie pour l'utilisation et la modification de fichier de configuration:<br> - Charger un ou plusieurs paramètres - Modifier un paramètre existant - Ajout un paramètre ou une section - Supprimer un paramètre ou une section - Lister les sections disponibles - Lister les paramètres et/ou sections désactivés Prends en compte les paramètres commentés.<br> Compatible avec les fichiers de configuration indentés.<br><br> Traduit les paramètres pour les types str, int, float, bool, list, dict ### Prérequis - Python 3 <br> # Installation ```console pip install zpp_config ``` # Utilisation ### Conseil d'importation du module ```python from zpp_config import Config ``` <br> ### Exemple de fichier de config ```xml [section] value1 = key1 value2 = key2 value3 = key3 [section2] value1 = key1 value2 = key2 value3 = key3 ``` <br> ### Initialisaton d'un fichier de configuration ```python c = Config("conf.ini") ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- separator: Définir le séparateur entre la clé et la valeur dans le fichier. (Par défaut: " = ") >- escape_line: Définir le caractère utilisé pour commenter une valeur ou une section. (Par défaut: "#") >- auto_create: Créer le fichier de configuration s'il n'existe pas. (Par défaut: "False") >- read_only: Ouvrir le fichier de configuration en lecture seule. (Par défaut: "False") <br> ### Chargement de paramètre La fonction renvoie la valeur si un unique paramètre a été trouvé, sinon renvoie un dictionnaire avec les différentes valeurs trouvées (classé par section) Renvoie un tableau vide si aucun paramètre n'a été trouvé #### Chargement de tous les paramètres ```python data = c.load() ``` #### Chargement d'une section du fichier ```python data = c.load(section='section_name') ``` #### Chargement d'une valeur dans tout le fichier ```python data = c.load(val='value_name') ``` #### Chargement d'une valeur dans une section spécifique ```python data = c.load(val='value_name', section='section_name') ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- default: Pour initialiser une valeur par défaut si aucun résultat est trouvé <br> ### Changement de paramètre #### Changement d'une valeur dans tout le fichier ```python c.change(val='value_name', key='key_value') ``` #### Changement d'une valeur dans une section spécifique ```python c.change(val='value_name', key='key_value', section='section_name') ``` <br> ### Ajout de paramètre ou de section Ajoute une section ou un paramètre dans le fichier de configuration. Dans le cas de l'ajout d'un paramètre, rajoute la section si elle n'existe pas. #### Ajout d'une section ```python c.add(section='section_name') ``` #### Ajout d'un paramètre dans une section ```python c.add(val='value_name', key='key_value', section='section_name') ``` > Si aucune section est défini, rajoute le paramètre en dehors des sections. <br> ### Suppression de paramètre ou de section #### Suppression d'une section ```python c.delete(section='section_name') ``` #### Suppression d'un paramètre dans une section ```python c.delete(val='value_name', section='section_name') ``` > Si aucune section est défini, recherche le paramètre en dehors des sections. <br> ### Liste des paramètres non pris en compte Retourne la liste des paramètres qui sont non pris en compte dans le fichier de configuration. ```python data = c.disabled_line() ``` > Possibilité de préciser la section en utilisant le paramètre section <br> ### Liste les sections disponibles ```python data = c.list_section() ```
zpp_config
/zpp_config-1.2.0.tar.gz/zpp_config-1.2.0/README.md
README.md
# py-menu ## Informations Générateur d'un menu à touches fléchées.<br> Le choix dans le menu se fait à partir des touches fléchées pour la navigation et de la touche Enter pour la validation.<br> Customisation des couleurs du menu et du curseur possibles.<br> Retourne l'indice du choix sélectionné ### Prérequis - Python 3 <br> ## Installation ```console pip install zpp_menu ``` ## Utilisation ```python choice = zpp_menu.Menu(Title, OptionList) ``` >En paramètre supplémentaire, nous pouvons mettre:<br/> >- Background = Choisir la couleur de font du choix selectionné >- Foreground = Choisir la couleur du texte du choix selectionné >- Pointer = Choisir un pointeur à afficher avant le choix >- Padding = Choisir la taille du décalage entre le titre et les choix >- Selected = Choisir la position du curseur
zpp_menu
/zpp_menu-1.2.3.tar.gz/zpp_menu-1.2.3/README.md
README.md
![tests](https://github.com/collective/zpretty/workflows/tests/badge.svg) [![image](https://coveralls.io/repos/github/collective/zpretty/badge.svg?branch=master)](https://coveralls.io/github/collective/zpretty?branch=master) [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/collective/zpretty/master.svg)](https://results.pre-commit.ci/latest/github/collective/zpretty/master) A tool to format in a **very opinionated** way HTML, XML and text containing XML snippets. It satisfies a primary need: decrease the pain of diffing HTML/XML. For this reason `zpretty` formats the markup following these rules of thumb: - maximize the vertical space/decrease the line length - attributes should be sorted consistently - attribute sorting is first semantic and then alphabetic This tool understands the [TAL language](https://en.wikipedia.org/wiki/Template_Attribute_Language) and has some features dedicated to it. This tool is not a linter! If you are looking for linters safe bets are [Tidy](https://www.html-tidy.org/) and [xmllint](http://xmlsoft.org/xmllint.html). You may have parsing problems! `zpretty` will close for you some known self closing tags, like `input` and `img`, that are allowed to be open in HTML. `zpretty` is not clever enough to understand correctly valueless attributes! Some work is ongoing, but it works best with \"normal\" attributes. Lack of feature/slowness are a known issue. For the moment the development focused in having a working tool. So it works fast enough: less than a second to format a \~100k file. New features are planned and also huge perfomance boost can be easily obtained. Anyway `zpretty` is not your option for formatting large files (\> 1 MB). See [TODO section](#todo_section) to know what is forecast for the future. The source code and the issue tracker are hosted on [GitHub](https://github.com/collective/zpretty). # INSTALL The suggested installation method is using [pip](https://pypi.python.org/pypi/pip/): ```bash python3 -m pip install --user zpretty ``` The latest release of `zpretty` requires Python3. If you need to use Python2.7 use `zpretty` 0.9.x. # USAGE Basic usage: ```console $ zpretty -h usage: zpretty [-h] [--encoding ENCODING] [-i] [-v] [-x] [-z] [--check] [--include INCLUDE] [--exclude EXCLUDE] [--extend-exclude EXTEND_EXCLUDE] [paths ...] positional arguments: paths The list of files or directory to prettify (defaults to stdin). If a directory is passed, all files and directories matching the regular expression passed to --include will be prettified. options: -h, --help show this help message and exit --encoding ENCODING The file encoding (defaults to utf8) -i, --inplace Format files in place (overwrite existing file) -v, --version Show zpretty version number -x, --xml Treat the input file(s) as XML -z, --zcml Treat the input file(s) as XML. Follow the ZCML styleguide --check Return code 0 if nothing would be changed, 1 if some files would be reformatted --include INCLUDE A regular expression that matches files and directories that should be included on recursive searches. An empty value means all files are included regardless of the name. Use forward slashes for directories on all platforms (Windows, too). Exclusions are calculated first, inclusions later. [default: \.(html|pt|xml|zcml)$] --exclude EXCLUDE A regular expression that matches files and directories that should be excluded on recursive searches. An empty value means no paths are excluded. Use forward slashes for directories on all platforms (Windows, too). Exclusions are calculated first, inclusions later. [default: /(\.direnv|\.eggs|\.git|\.hg|\.mypy_cache|\.no x|\.tox|\.venv|venv|\.svn|\.ipynb_checkpoints|_build|buc k-out|build|dist|__pypackages__)/] --extend-exclude EXTEND_EXCLUDE Like --exclude, but adds additional files and directories on top of the excluded ones. (Useful if you simply want to add to the default) The default exclude pattern is: `/(\.direnv|\.eggs|\.git|\.hg|\.mypy_cache|\.nox |\.tox|\.venv|venv|\.svn|\.ipynb_checkpoints|_build|buck- out|build|dist|__pypackages__)/` ``` Without parameters constraining the file type (e.g. `-x`, `-z`, \...) `zpretty` will try to guess the right options for you. Example: ```console zpretty hello_world.html ``` # pre-commit support `zpretty` can be used as a [pre-commit](https://pre-commit.com/) hook. To do so, add the following to your `.pre-commit-config.yaml`: ```yaml - repo: https://github.com/collective/zpretty rev: FIXME hooks: - id: zpretty ``` # VSCode extension There is a VSCode extension that uses `zpretty`: - [https://marketplace.visualstudio.com/items?itemName=erral.erral-zcmlLanguageConfiguration](https://marketplace.visualstudio.com/items?itemName=erral.erral-zcmlLanguageConfiguration) Thanks to @erral for the work! # DEVELOP ```bash git clone ... cd zpretty make ``` # RUNNING TESTS ```bash make test ```
zpretty
/zpretty-3.1.0a1.tar.gz/zpretty-3.1.0a1/README.md
README.md
# Changelog ## 3.1.0a1 (2023-05-04) - Add command line parameters to include/exclude files and folders (Implements #96) [ale-rt] - Be tolerant with characters forbidden in XML when dealing with tal attributes (See #125) [ale-rt] ## 3.0.4 (2023-04-20) - Fix bogus ampersands in attributes (Fixes #116) [ale-rt] ## 3.0.3 (2023-03-26) - Handle HTML files with an XML preamble before the doctype. (Fixes #118) [ale-rt] ## 3.0.2 (2023-02-26) - Handle forbidden characters in attributes properly (Fixes #110) [ale-rt] - Fix attribute with a value containing double quotes (Fixes #109) [ale-rt] ## 3.0.1 (2023-02-09) - Fix an issue with empty lines inside an attribute. (Fixes #106) [ale-rt] ## 3.0.0 (2023-02-09) - The pre-commit hook now modifies fixes the files instead of just checking if they should be fixed [ale-rt] - Fix the check behavior when multiple files are passed [ale-rt] - Improve the check that sniffs html files (Fixes #89) [ale-rt] ## 2.4.1 (2022-10-25) - XML files with newlines between attributes are properly formatted (Fixes #84) [ale-rt] - Do not tamper attributes in XML as if they were a page template attribute (Fixes #85) [ale-rt] ## 2.4.0 (2022-10-22) - Prevent fiddling around with custom entity declaration (Fixes #80) [ale-rt] - Add support for Python 3.11. [ale-rt] - Drop support for Python 3.6. [ale-rt] ## 2.3.1 (2022-09-30) - Do not try to do anything on CDATAs (Fixes #76) [ale-rt] ## 2.3.0 (2022-09-26) - Added a -v/--version option [ale-rt] ## 2.3.0a4 (2022-09-24) - Remove custom tree builder which is not used anymore [ale-rt] - Fix entity sustitution in XML (Fixes #48, Refs #71) [ale-rt] ## 2.3.0a3 (2022-07-08) - Do not escape entities inside the script and style tags (Fixes #57) [ale-rt] ## 2.3.0a2 (2022-07-08) - Fix release ## 2.3.0a1 (2022-07-08) - Preserve whitespace in XML documents and `pre` elements (Fixes #64) [ale-rt] - Improve doctype handling [ale-rt] - Do not kill XML documents with a doctype (Fixes #47) [ale-rt] - Support Python 3.10 [ale-rt] ## 2.2.0 (2021-12-06) - Add a `--check` command line parameter (Fixes #49) [ale-rt] - Now the package is `pre-commit` compatibile (Fixes #50) [ale-rt] ## 2.1.0 (2021-02-12) - Remove unused `autofix` method [ale-rt] - Do not render a spurious `=""` when new lines appear inside a tag (Refs. #35) [ale-rt] - The attributes renderer knows about the element indentation and for indents the attributes consequently [ale-rt] - The ZCML element has now its custom tag templates, this simplifies the code [ale-rt] - Attributes content spanning multiple lines is not indented anymore (Refs. #17) [ale-rt] - Improved sorting for zcml attributes (Refs. #11) [ale-rt] - Code is compliant with black 20.8b1 [ale-rt] - Switch to pytest for running tests [ale-rt] - Upgrade dev requirements [ale-rt] - Support Python 3.9 [ale-rt] ## 2.0.0 (2020-05-28) - Updated the list of self closing elements and boolean attributes [ale-rt] ## 1.0.3 (2020-05-22) - Fix unwanted newlines (#20) ## 1.0.2 (2019-11-03) - In Python3.8 quotes in attributes were escaped - Fix output again on file and stdout [ale-rt] ## 1.0.1 (2019-10-28) - Fix output on file [ale-rt] ## 1.0.0 (2019-10-27) - Support Python3 only [ale-rt] ## 0.9.3 (2017-05-06) - Last release that supports Python2.7 - Fix text method - Preserve entities in text - Added an `--encoding` parameter - Added an `--xml` parameter to force xml parsing - Choose the better parser according to the given filename if no parser is forced - Process stdin if `-` is in the arguments or no arguments are passed [ale-rt] ## 0.9.2 (2017-02-27) - Small modification for the order of the zcml attributes - Auto add a new line to the end of the prettified files - Self heal open self closing tag. [ale-rt] ## 0.9.1.1 (2017-02-18) - Fixed bad release. [ale-rt] ## 0.9.1 (2017-02-18) - Initial support for zcml style guide (\#3). [ale-rt] ## 0.9.0 (2017-02-11) - Initial release. [ale-rt]
zpretty
/zpretty-3.1.0a1.tar.gz/zpretty-3.1.0a1/HISTORY.md
HISTORY.md
import sys import datetime #lineNumber = sys._getframe().f_back.f_lineno #sys._getframe().f_code.co_filename def get_filename(): name=[] a=sys._getframe() while a is not None: name.append(a.f_code.co_filename) a=a.f_back #print name return name[-1] def get_tree(): #filename=sys._getframe().f_code.co_filename filename=get_filename() name=[] a = sys._getframe() linenum=a.f_back.f_lineno #filename+='(line-'+str(linenum)+')' #while a is not None and a.f_back is not None: while a is not None: #name.append(a.f_code.co_name+'(%s line:'%(filename)+str(a.f_back.f_lineno)+')') name.append(a.f_code.co_name+'(line:'+str(a.f_lineno)+')') a=a.f_back #print(100*'*') #print len(name) #print name funclist='%s main'%(filename) spacelist=4*' ' for i in range(-1,-len(name)+1,-1): #print name[i] funclist+=' - '+name[i] #print name return funclist,'%s %s %s'%(filename,(len(name)-2)*' - ',name[2]) def addinfo(message,flag=1): funclist,spacelist=get_tree() flist=(funclist,spacelist)[flag] nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') info="[%s] %s :: %s"%(nowTime,flist,message) return info def zprintr(message,flag=1): info=addinfo(message,flag) sys.stdout.write(info+'\r') sys.stdout.flush() def zprint(message,flag=1): #funclist,spacelist=get_tree() #flist=(funclist,spacelist)[flag] #nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #info="[%s] %s :: %s"%(nowTime,flist,message) info=addinfo(message,flag) sys.stdout.write(info+'\n') #print info def eprint(message,flag=1): #funclist,spacelist=get_tree() #flist=(funclist,spacelist)[flag] #nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') #info="[%s] %s :: %s"%(nowTime,flist,message) info=addinfo(message,flag) sys.stderr.write(info+'\n') def pprint(i,i_all,width,outstr=sys._getframe().f_code.co_name): # process print nn=i%width #sys.stdout.write('\r %s:'+nn*"#"+(30-nn)*' '+'%.2f%%'%(sys._getframe().f_code.co_name,float(i)/float(len(imglist))*100)) #sys.stdout.write('\r %s: '%(sys._getframe().f_code.co_name)+nn*"#"+(width-nn)*' '+'%.2f%%'%(float(i)/float(i_all)*100)) sys.stdout.write('\r %s: '%(outstr)+nn*"#"+(width-nn)*' '+'%.2f%%'%(float(i)/float(i_all)*100)) sys.stdout.flush() def zhelp(): sys.stdout.write(" # pip install zprint -i https://pypi.python.org/simple\n") sys.stdout.write(" from zprint import *\n") sys.stdout.write(" \n") sys.stdout.write(" def fun2():\n") sys.stdout.write(" zprint(\" I am in fun2\",1)\n") sys.stdout.write(" zprint(\" I am in fun2\",0)\n") sys.stdout.write(" \n") sys.stdout.write(" def fun1():\n") sys.stdout.write(" zprint(\" I am in fun1\")\n") sys.stdout.write(" fun2()\n") sys.stdout.write(" \n") sys.stdout.write(" if __name__==\"__main__\":\n") sys.stdout.write(" fun1()\n") def fun2(): zprint(" I am in fun2",1) zprint(" I am in fun2",0) def fun1(): zprint(" I am in fun1") fun2() if __name__=="__main__": fun1() zhelp() zprint("main")
zprint
/zprint-0.0.11.tar.gz/zprint-0.0.11/zprint.py
zprint.py
Info ==== `zprint 2018-08-20` `Author: Zhao Mingming <[email protected]>` `Copyright: This module has been placed in the public domain.` `version:0.0.4` - `add func zprint, print out the function list and time into stdout` - `add func eprint, print out the function list and time into stderr` - `add func zhelp, print demo script` `version:0.0.7` - `add func zprintr` `version:0.0.7` - `add func sys.stdout.flush()` Functions: - `add func zprint, print out the function list and time into stdout` - `add func eprint, print out the function list and time into stderr` How To Use This Module ====================== .. image:: funny.gif :height: 100px :width: 100px :alt: funny cat picture :align: center 1. example code: .. code:: python from zprint import * def fun2(): zprint(" I am in fun2",0) def fun1(): zprint(" I am in fun1") fun2() if __name__=="__main__": print 1 fun1() Refresh ======== 20180820
zprint
/zprint-0.0.11.tar.gz/zprint-0.0.11/README.md
README.md
<img src="https://i.imgur.com/sJARxXD.png" /> *ZProc lets you do shared-state multitasking without the perils of having shared-memory.* **Behold, the power of ZProc:** ```python # Some initialization import zproc ctx = zproc.Context(wait=True) # wait for processes in this context ctx.state["cookies"] = 0 # Define "atomic" operations @zproc.atomic def eat_cookie(state): """Eat a cookie.""" state["cookies"] -= 1 print("nom nom nom") @zproc.atomic def bake_cookie(state): """Bake a cookie.""" state["cookies"] += 1 print("Here's a cookie!") # Fire up processes @ctx.call_when_change('cookies') def cookie_eater(_, state): """Eat cookies as they're baked.""" eat_cookie(state) for i in range(5): bake_cookie(ctx.state) ``` **Result:** ``` Here's a cookie! Here's a cookie! nom nom nom Here's a cookie! nom nom nom Here's a cookie! nom nom nom Here's a cookie! nom nom nom nom nom nom ``` (baker and eater run in different processes) ## The core idea ZProc tries to breathe new life into the archaic idea of shared-state multitasking by protecting application state with logic and reason. Shared state is frowned upon by almost everyone, (mostly) due to the fact that memory is inherently dumb. Like memory doesn't really care who's writing to it. ZProc's state tries to keep a track of who's doing what. ## The Goal ZProc aims to make building multi-taking applications easier and faster for everyone, in a pythonic way. It started out from the core idea of having a *smart* state -- eventually wanting to turn into a full-fledged framework for all things multitasking. ## Install ``` $ pip install zproc ``` **Or, from the development branch** ``` $ pip install git+https://github.com/pycampers/zproc.git@next#egg=zproc ``` License: MIT License (MIT)<br> Requires: Python >=3.5 ## Documentation ( [![Documentation Status](https://readthedocs.org/projects/zproc/badge/?version=latest)](https://zproc.readthedocs.io/) ) #### [Read the docs](http://zproc.readthedocs.io/en/latest/) #### [Examples](examples) ## Features - 🌠 &nbsp; Process management - [Process Factory](https://zproc.readthedocs.io/en/latest/api.html#zproc.Context.process_factory) - Remembers to kill processes when exiting, for general peace. (even when they're nested) - Keeps a record of processes created using ZProc. - [🔖](https://zproc.readthedocs.io/en/latest/api.html#context) - 🌠 &nbsp; Process Maps - Automatically manages worker processes, and delegates tasks to them. - [🔖](https://zproc.readthedocs.io/en/latest/api.html#context) - 🌠 &nbsp; Asynchronous paradigms without `async def` - Build a combination of synchronous and asynchronous systems, with ease. - By _watching_ for changes in state, without [Busy Waiting](https://en.wikipedia.org/wiki/Busy_waiting). - [🔖](https://zproc.readthedocs.io/en/latest/api.html#state) - 🌠 &nbsp; Atomic Operations - Perform an arbitrary number of operations on state as a single, atomic operation. - [🔖](https://zproc.readthedocs.io/en/latest/user/atomicity.html) ## Caveats - The state only gets updated if you do it directly.<br> This means that if you mutate objects inside the state, they wont get reflected in the global state. - The state should be pickle-able. - It runs an extra Process for managing the state.<br> Its fairly lightweight though, and shouldn't add too much weight to your application. ## FAQ - Fast? - Above all, ZProc is written for safety and the ease of use. - However, since its written using ZMQ, it's plenty fast for most stuff. - Run -> [🔖](eamples/async_vs_zproc.py) for a taste. - Stable? - Mostly. However, since it's still in the `0.x.x` stage, you can expect some API changes. - Production ready? - Please don't use it in production right now. - Windows compatible? - Probably? ## Local development ``` git clone https://github.com/pycampers/zproc.git cd zproc pipenv install pipenv install -d   pipenv shell pip install -e . pytest ``` ## Build documentation Assuming you have sphinx installed (Linux) ``` cd docs ./build.sh ./build.sh loop # starts a build loop. ``` ## ZProc in the wild - [Oscilloscope](https://github.com/pycampers/oscilloscope) - [Muro](https://github.com/pycampers/muro) ## Thanks - Thanks to [open logos](https://github.com/arasatasaygin/openlogos) for providing the wonderful ZProc logo. - Thanks to [pieter hintjens](http://hintjens.com/), for his work on the [ZeroMQ](http://zeromq.org/) library and for his [amazing book](http://zguide.zeromq.org/). - Thanks to [tblib](https://github.com/ionelmc/python-tblib), ZProc can raise First-class Exceptions from the zproc server! - Thanks to [psutil](https://github.com/giampaolo/psutil), ZProc can handle nested procesess! - Thanks to Kennith Rietz. His setup.py was used to host this project on pypi. Plus a lot of documentation structure is blatantly copied from his documentation on requests --- ZProc is short for [Zero](http://zguide.zeromq.org/page:all#The-Zen-of-Zero) Process. --- [🐍🏕️](http://www.pycampers.com/)
zproc
/zproc-1.0.0a2.tar.gz/zproc-1.0.0a2/README.md
README.md
# zprocess [![Build Status](https://travis-ci.com/chrisjbillington/zprocess.svg?branch=master)](https://travis-ci.com/chrisjbillington/zprocess) [![codecov](https://codecov.io/gh/chrisjbillington/zprocess/branch/master/graph/badge.svg)](https://codecov.io/gh/chrisjbillington/zprocess) A set of utilities for multiprocessing using zeromq. Includes process creation and management, output redirection, message passing, inter-process locks, logging, and a process-tree-wide event system. ( [view on pypi](https://pypi.python.org/pypi/zprocess/); [view on Github](https://github.com/chrisjbillington/zprocess) ) * Install `python setup.py install`.
zprocess
/zprocess-2.20.1.tar.gz/zprocess-2.20.1/README.md
README.md
======================== zprocess |release| ======================== `Chris Billington <mailto:[email protected]>`_, |today| .. contents:: :local: TODO: Summary `View on PyPI <http://pypi.python.org/pypi/zprocess>`_ | `View on BitBucket <https://bitbucket.org/cbillington/zprocess>`_ | `Read the docs <http://zprocess.readthedocs.org>`_ ------------ Installation ------------ to install ``zprocess``, run: .. code-block:: bash $ pip3 install zprocess or to install from source: .. code-block:: bash $ python3 setup.py install .. note:: Also works with Python 2.7 ------------ Introduction ------------ TODO: introduction ------------- Example usage ------------- .. code-block:: python :name: example.py def todo(): print('example') todo() .. code-block:: bash :name: output $ python3 example.py example Description of examples ---------------- Module reference ---------------- .. autoclass:: zprocess.clientserver.ZMQServer :members: .. autoclass:: zprocess.clientserver.ZMQClient :members: .. autofunction:: zprocess.utils.start_daemon
zprocess
/zprocess-2.20.1.tar.gz/zprocess-2.20.1/doc/index.rst
index.rst
INTRODUCTION ============ This project is a suite of tools designed to ease the process of developing assembly language apps for the TI-83 Plus series of calculators. Currently, it contains the following tools: - zmake (inspired by qmake of qt), which produces a Makefile that describes the build process for a TI-83 Plus assembly language application, and - zabc (Z80 Application Boilerplate Compiler), which generates an assembly language file that can be assembled into an application. It also includes some assembly language libraries and a sample application to build. INSTALLATION AND DEPENDENCIES ============================= Currently, this project is only supported on Unix-like operating systems. It is a Python project located on PyPI, and can therefore be installed by running some variation of ``pip install zproj`` (perhaps with root access). The following dependencies are required to use this project: - Python 3. The tools are written in Python, and have not been designed with Python 2 in mind. - peeker. This is a small Python package used by the tools included in this project. - GNU make or equivalent. This program must be installed in order to use the Makefile generated by zmake. - spasm. This is the assembler currently used and supported by the project, and must therefore be installed to perform builds. - rabbitsign. TI-83 Plus applications must be digitally signed in order to be loaded onto calculators, and rabbitsign is the application signer currently supported by this project. EXAMPLE ======= This project ships with an example "Hello World" application that can be built using the tools contained in this project. After installing the project and the above dependencies, changing directories into ``examples/hello`` and running ``zmake`` followed by ``make`` should build a .8xk file that can be loaded onto an actual or simulated TI-83 Plus series calculator.
zproj
/zproj-1.0.10.tar.gz/zproj-1.0.10/README.rst
README.rst
# Scrapy settings for monetSpider project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # https://docs.scrapy.org/en/latest/topics/settings.html # https://docs.scrapy.org/en/latest/topics/downloader-middleware.html # https://docs.scrapy.org/en/latest/topics/spider-middleware.html BOT_NAME = 'monetSpider' SPIDER_MODULES = ['monetSpider.spiders'] NEWSPIDER_MODULE = 'monetSpider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent #USER_AGENT = 'monetSpider (+http://www.yourdomain.com)' # Obey robots.txt rules ROBOTSTXT_OBEY = False # Configure maximum concurrent requests performed by Scrapy (default: 16) #CONCURRENT_REQUESTS = 32 # Configure a delay for requests for the same website (default: 0) # See https://docs.scrapy.org/en/latest/topics/settings.html#download-delay # See also autothrottle settings and docs #DOWNLOAD_DELAY = 3 # The download delay setting will honor only one of: #CONCURRENT_REQUESTS_PER_DOMAIN = 16 #CONCURRENT_REQUESTS_PER_IP = 16 # Disable cookies (enabled by default) COOKIES_ENABLED = False # Disable Telnet Console (enabled by default) #TELNETCONSOLE_ENABLED = False # Override the default request headers: DEFAULT_REQUEST_HEADERS = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Accept-Language': 'en', } # Enable or disable spider middlewares # See https://docs.scrapy.org/en/latest/topics/spider-middleware.html #SPIDER_MIDDLEWARES = { # 'monetSpider.middlewares.MyspiderSpiderMiddleware': 543, #} # Enable or disable downloader middlewares # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html DOWNLOADER_MIDDLEWARES = { 'monetSpider.middlewares.RandomUserAgentMiddleware': 544, 'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None, } # Enable or disable extensions # See https://docs.scrapy.org/en/latest/topics/extensions.html EXTENSIONS = { # 'scrapy.extensions.telnet.TelnetConsole': None, # 'scrapy_jsonrpc.webservice.WebService': 500, } IMAGES_STORE = '../data/images' FILES_STORE = '../data/files' # Configure item pipelines # See https://docs.scrapy.org/en/latest/topics/item-pipeline.html ITEM_PIPELINES = { 'monetSpider.pipelines.ImagePipeline': 310, 'monetSpider.pipelines.ZFilePipeline': 312, 'monetSpider.pipelines.MysqlPipeline': 320, #'monetSpider.pipelines.MongoPipeline': 322, # 'scrapy_redis.pipelines.RedisPipeline': 400, } IMAGES_THUMBS = { 'small': (50, 50), 'big': (270, 270), } # IMAGES_MIN_HEIGHT = 110 # IMAGES_MIN_WIDTH = 110 # Enable and configure the AutoThrottle extension (disabled by default) # See https://docs.scrapy.org/en/latest/topics/autothrottle.html #AUTOTHROTTLE_ENABLED = True # The initial download delay #AUTOTHROTTLE_START_DELAY = 5 # The maximum download delay to be set in case of high latencies #AUTOTHROTTLE_MAX_DELAY = 60 # The average number of requests Scrapy should be sending in parallel to # each remote server #AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0 # Enable showing throttling stats for every response received: #AUTOTHROTTLE_DEBUG = False # Enable and configure HTTP caching (disabled by default) # See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings #HTTPCACHE_ENABLED = True #HTTPCACHE_EXPIRATION_SECS = 0 #HTTPCACHE_DIR = 'httpcache' #HTTPCACHE_IGNORE_HTTP_CODES = [] #HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage' MAX_PAGE = 2 MYSQL_HOST = 'localhost' MYSQL_DATABASE = 'images360' MYSQL_PORT = 3306 MYSQL_USER = 'root' MYSQL_PASSWORD = 'monetware' JSONRPC_ENABLED = True REDIS_HOST = 'localhost' REDIS_PARAMS = { 'password': '', } REDIS_PORT = 6379 ################ scrapy-redis配置 ################# # Enables scheduling storing requests queue in redis. SCHEDULER = "scrapy_redis.scheduler.Scheduler" # # # Ensure all spiders share same duplicates filter through redis. DUPEFILTER_CLASS = "scrapy_redis.dupefilter.RFPDupeFilter" # SCHEDULER_PERSIST = True # FEED_EXPORT_ENCODING = 'utf-8' ### ## slave 端 子爬虫的settings ##REDIS_URL = 'redis://root:[email protected]:6379' ##REDIS_PORT = 6379 ############### 持久化 Job # JOBDIR = '../jobs/xspider/1' #####反爬虫配置
zpspider
/zpspider-0.1.tar.gz/zpspider-0.1/monetSpider/settings.py
settings.py
# Define here the models for your spider middleware # # See documentation in: # https://docs.scrapy.org/en/latest/topics/spider-middleware.html import json import time import requests from fake_useragent import UserAgent from scrapy import signals class MonetspiderSpiderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the spider middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_spider_input(self, response, spider): # Called for each response that goes through the spider # middleware and into the spider. # Should return None or raise an exception. return None def process_spider_output(self, response, result, spider): # Called with the results returned from the Spider, after # it has processed the response. # Must return an iterable of Request, dict or Item objects. for i in result: yield i def process_spider_exception(self, response, exception, spider): # Called when a spider or process_spider_input() method # (from other spider middleware) raises an exception. # Should return either None or an iterable of Request, dict # or Item objects. pass def process_start_requests(self, start_requests, spider): # Called with the start requests of the spider, and works # similarly to the process_spider_output() method, except # that it doesn’t have a response associated. # Must return only requests (not items). for r in start_requests: yield r def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class MonetspiderDownloaderMiddleware(object): # Not all methods need to be defined. If a method is not defined, # scrapy acts as if the downloader middleware does not modify the # passed objects. @classmethod def from_crawler(cls, crawler): # This method is used by Scrapy to create your spiders. s = cls() crawler.signals.connect(s.spider_opened, signal=signals.spider_opened) return s def process_request(self, request, spider): # Called for each request that goes through the downloader # middleware. # Must either: # - return None: continue processing this request # - or return a Response object # - or return a Request object # - or raise IgnoreRequest: process_exception() methods of # installed downloader middleware will be called return None def process_response(self, request, response, spider): # Called with the response returned from the downloader. # Must either; # - return a Response object # - return a Request object # - or raise IgnoreRequest return response def process_exception(self, request, exception, spider): # Called when a download handler or a process_request() # (from other downloader middleware) raises an exception. # Must either: # - return None: continue processing this exception # - return a Response object: stops process_exception() chain # - return a Request object: stops process_exception() chain pass def spider_opened(self, spider): spider.logger.info('Spider opened: %s' % spider.name) class RandomUserAgentMiddleware(object): def __init__(self, crawler): super(RandomUserAgentMiddleware, self).__init__() self.ua = UserAgent() @classmethod def from_crawler(cls, crawler): return cls(crawler) def process_request(self, request, spider): request.headers.setdefault('User-Agent', self.ua.random) class RandomProxyMiddleware(object): def get_ip(self): ret = requests.get(url='http://xxx/proxy/getProxies') data = json.loads(ret.text) while data['code'] != 0: time.sleep(1) ret = requests.get(url='http://xxx/proxy/getProxies') data = json.loads(ret.text) return data['proxy']['ip'] + ':' + str(data['proxy']['port']) def process_request(self, request, spider): request.meta['proxy'] = { 'http': self.get_ip(), 'https': self.get_ip() }
zpspider
/zpspider-0.1.tar.gz/zpspider-0.1/monetSpider/middlewares.py
middlewares.py
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html import pymongo import pymysql from scrapy.pipelines.files import FilesPipeline class MongoPipeline(object): def __init__(self, mongo_uri, mongo_db): self.mongo_uri = mongo_uri self.mongo_db = mongo_db @classmethod def from_crawler(cls, crawler): return cls( mongo_uri=crawler.settings.get('MONGO_URI'), mongo_db=crawler.settings.get('MONGO_DB') ) def open_spider(self, spider): self.client = pymongo.Connection(self.mongo_uri) self.db = self.client[self.mongo_db] def process_item(self, item, spider): self.db[item.collection].insert(dict(item)) return item def close_spider(self, spider): self.client.close() class MysqlPipeline(): def __init__(self, host, database, user, password, port): self.host = host self.database = database self.user = user self.password = password self.port = port print("host mysql ======.text") @classmethod def from_crawler(cls, crawler): return cls( host=crawler.settings.get('MYSQL_HOST'), database=crawler.settings.get('MYSQL_DATABASE'), user=crawler.settings.get('MYSQL_USER'), password=crawler.settings.get('MYSQL_PASSWORD'), port=crawler.settings.get('MYSQL_PORT'), ) def open_spider(self, spider): self.db = pymysql.connect(self.host, self.user, self.password, self.database, charset='utf8', port=self.port) self.cursor = self.db.cursor() def close_spider(self, spider): self.db.close() def process_item(self, item, spider): data = dict(item) keys = ', '.join(data.keys()) values = ', '.join(['%s'] * len(data)) sql = 'insert into %s (%s) values (%s)' % (item.table, keys, values) self.cursor.execute(sql, tuple(data.values())) self.db.commit() return item from scrapy import Request from scrapy.exceptions import DropItem from scrapy.pipelines.images import ImagesPipeline class ImagePipeline(ImagesPipeline): def file_path(self, request, response=None, info=None): url = request.url file_name = url.split('/')[-1] return file_name def item_completed(self, results, item, info): if item.get('download_imgurl'): item.__delitem__("download_imgurl") image_paths = [x['path'] for ok, x in results if ok] # if not image_paths: # raise DropItem('Image Downloaded Failed') return item def get_media_requests(self, item, info): if item.get('download_imgurl'): yield Request(item['download_imgurl']) class ZFilePipeline(FilesPipeline): def file_path(self, request, response=None, info=None): url = request.url file_name = url.split('/')[-1] return file_name def item_completed(self, results, item, info): if item.get('download_fileurl'): item.__delitem__("download_fileurl") image_paths = [x['path'] for ok, x in results if ok] # if not image_paths: # raise DropItem('files Downloaded Failed') return item def get_media_requests(self, item, info): if item.get('download_fileurl'): yield Request(item['download_fileurl'])
zpspider
/zpspider-0.1.tar.gz/zpspider-0.1/monetSpider/pipelines.py
pipelines.py
import datetime import re from collections import OrderedDict from urllib.parse import urlencode, urljoin from scrapy import Spider, Request import json from scrapy_redis.spiders import RedisSpider from monetSpider.items import NewsItem from scrapy.loader import ItemLoader from scrapy.loader.processors import Join from monetSpider.loaders import NewsLoader class XspiderSpider(RedisSpider): name = 'xspider' #lpush xspider:start_urls https://baidu.com/s?rtt=1&bsst=1&cl=2&tn=news&rsv_dl=ns_pc&word=site:(www.people.com.cn)两会 redis_key = 'xspider:start_urls' allowed_domains = ['baidu.com', 'people.com.cn'] # start_urls = ['https://image.so.com/z?ch=beauty'] # 系统配置 custom_settings = {} def __init__(self, xspider=None, *args, **kwargs): super(XspiderSpider, self).__init__(*args, **kwargs) # TODO 从xspider解析得到所需的参数 self.makeurl_settings = xspider.makeurl_settings self.parse_settings = xspider.parse_settings # self.datastructure = xspider.datastructure self.notNullColNameList = xspider.getNotNullColName() def start_requests(self): entryurls=self.makeurl_settings.get("entryUrls") if entryurls is not None: for entryurl in self.dicttolist(entryurls.get('entryUrl')): if not re.match(r'^https?:/{2}\w.+$', entryurl): continue dict = self.paramdict(entryurl) print(entryurl) for param in self.makeurl_settings["params"]["param"]: if dict.__contains__(param["@name"]): # TODO 首先解析系统变量 # 解析一般变量 dict[param.get("@name")] = param.get("@value") or param.get('@defaultValue') if dict: url = entryurl.split("?")[0] + "?" + urlencode(dict) else: url = entryurl yield Request(url, self.parse) def paramdict(self, url): from urllib.parse import urlsplit split_result = urlsplit(url) dict = {} if split_result.query is None: return dict for key_value in split_result.query.split('&'): if not str(key_value).__contains__("="): continue print(key_value.split('=')) k, v = key_value.split('=') dict[k] = v return dict def abshref(self, url, link): return urljoin(url, link) def okpageextractors(self, pageextractors, url): for pageextractor in pageextractors: if re.match(pageextractor["@urlRegex"], url): yield pageextractor def genxpath(self, regionxpath, colxpath): xpath = regionxpath if str(colxpath).startswith("//"): return xpath + str(colxpath) elif str(colxpath).startswith("/"): return xpath + "/" + str(colxpath) else: return xpath + "//" + str(colxpath) def parse(self, response): print("当前页:" + response.url) print("下一页:" + self.abshref(response.url, str(response.xpath("//a[contains(./text(),'下一页')]/@href").extract_first()))) rnewsitem = NewsItem() if response.meta.__contains__("item"): rnewsitem.update(response.meta["item"]) # 正则选择合适的处理器 pageextractors = self.parse_settings["pageextractor"] # 获取符合条件的处理器列表 for index, pageextractor in enumerate(self.okpageextractors(pageextractors, response.url)): # parse = pageextractor["parse"] datastored = pageextractor["@dataStored"].__eq__("true") last = index == len(pageextractors) - 1 tosave = last or datastored hasregion = False self.parse_col(response, response, pageextractor, rnewsitem) for link in self.parse_link(response, response, pageextractor, rnewsitem, datastored, False): yield link regionlist = self.dicttolist(pageextractor.get("region")) if regionlist.__len__() > 0: hasregion = True for oregion in regionlist: # for osetcol in osetcol["setcols"]: # self.genxpath(oregion.get("xpath", ""),osetcol.get("setcols").get("xpath")) for region in response.xpath(oregion.get("@xpath", "")): newsitem = NewsItem() newsitem.update(rnewsitem) self.parse_col(response, region, oregion, newsitem) for link in self.parse_link(response, region, oregion, newsitem, datastored, True): yield link if tosave and not self.hasNoneCol(newsitem): newsitem["missing_data"] = "1" if nonecol else "0" yield self.save(newsitem, response) nonecol = self.hasNoneCol(rnewsitem) if not hasregion and tosave and not nonecol: rnewsitem["missing_data"] = "1" if nonecol else "0" yield self.save(rnewsitem, response) def save(self, newsitem=NewsItem, response=None): newsitem["URL"] = response.url # newsitem["TIMESTAMP"] = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') newsitem["download_fileurl"] = response.url for col in str(newsitem): if col.endswith("url"): newsitem[col] = self.abshref(response.url, newsitem[col]) # newsitem["download_imgurl"]=self.abshref(response.url,newsitem["download_imgurl"]) loader = NewsLoader(item=newsitem, response=response) return loader.load_item() def parse_link(self, response, selector, extract, newsitem, datastored=False, isinner=False): url = response.url for olink in self.dicttolist(extract.get("link")): link = selector.xpath(olink["@xpath"]).extract_first() if not datastored and isinner: yield Request(self.abshref(url, link), callback=self.parse, meta={"item": newsitem}) else: yield Request(self.abshref(url, link), callback=self.parse) def parse_col(self, response, selector, extract, newsitem): for osetcol in self.dicttolist(extract.get("setcol")): # tidyText() allText()等同功能 setcol = '\n'.join(selector.xpath(osetcol.get("@xpath", "")).getall()) if setcol is not None: setcol = self.clear(setcol, osetcol) print(osetcol["@ref"] + setcol) newsitem[osetcol["@ref"]] = setcol else: newsitem[osetcol["@ref"]] = None def clear(self, str, selector): regex = selector.get("@regex", "") if regex.__len__() == 0: return str str = re.sub("\\n", "", str) gs = re.match(regex, str) format = selector.get("@format", "{0}") if gs: if (re.match("{\d+}", format)): format = format.replace("{0}", gs.group()) for i, group in enumerate(gs.groups()): format = format.replace("{" + (i + 1).__str__() + "}", group) return format else: return gs.group() return str def hasNoneCol(self, newsitem): for col in self.notNullColNameList: if newsitem.get(col,None) is None: return True return False def dicttolist(self, dict): if isinstance(dict, list): return dict elif dict: return [dict] else: return []
zpspider
/zpspider-0.1.tar.gz/zpspider-0.1/monetSpider/spiders/XspiderSpider.py
XspiderSpider.py
import xml.etree.ElementTree as ET from monetSpider.utils.xml import * class Head: def __init__(self,xsid,name,description): self.xsid=xsid self.name=name self.description=description class Param: def __init__(self,name="",label="",type="string",format=None,size=None,value=None,defaultValue=None,notNull=True,begin=None,end=None,step=None): self.name=name self.label=label self.type=type self.format=format self.value=value self.defaultValue=defaultValue self.notNull=notNull self.begin=begin self.end=end self.step=step class DataCol: def __init__(self,name="",label="",type="string",defaultValue=None,size=None,format=None,notNull=True): self.name=name self.label=label self.type=type self.defaultValue=defaultValue self.size=size self.format=format self.notNull=notNull pass class Pageextractor: def __init__(self,name="",dataStored=True,jsonRegex=None,sampleUrl=None,type="html",urlRegex=None,links=None,setcols=None,regions=None): self.name=name self.dataStored=dataStored self.jsonRegex=jsonRegex self.sampleUrl=sampleUrl self.type=type self.urlRegex=urlRegex self.link=links self.setcol=setcols self.region=regions class Region: def __init__(self,name,label,xpath,regex,setcols,links): self.name=name self.label=label self.xpath=xpath self.regex=regex self.setcols=setcols self.links=links class Node: def __init__(self, xpath,regex, format ): self.xpath=xpath self.regex=regex self.format=format class SetCol(Node): def __init__(self,ref,xpath,regex,format): super(SetCol,self).__init__(xpath,regex,format) self.ref=ref class Link(Node): def __init__(self,name,label,xpath,regex,format): super(Link,self).__init__(xpath,regex,format) self.name=name self.label=label class Config: def __init__(self,agent=0,cookie="",urlcharset="utf-8",charset="utf-8",sleepInterval="1000",antiVerfiedCodeType="auto",poolSize=2,threadNum=5,timeOut=10000,retryTimes=2,cycleRetryTimes=2,incrementParam=None): self.agent=agent self.cookie=cookie self.urlcharset=urlcharset self.charset=charset self.sleepInterval=sleepInterval self.antiVerfiedCodeType=antiVerfiedCodeType self.poolSize=poolSize self.threadNum=threadNum self.retryTimes=retryTimes self.cycleRetryTimes=cycleRetryTimes self.incrementParam=incrementParam # def __setattr__(self, key, value): # # self.__dict__[key] = value # print("k:"+key ) class IncrementParam: def __init__(self,key=None,value=None): self.key=key self.value=value class Xspider(): # def __init__(self, root): # self.root = root # self.__head() # self.__params() # self.__entryUrls() # self.__datastructures() # self.__pageextractors() # self.__config() # TODO 从xspider解析得到scrapy spider所需的参数 def __init__(self, path): self.str=read_file_as_str(path) tree=readfromxml(path) self.root = tree.getroot() self.__head() self.__params() self.__entryUrls() self.__datastructures() self.__pageextractors() self.__config() self.dict=xmlstrtodict(self.str) self.makeurl_settings = self.dict["xspider"]["body"]["entry"] self.parse_settings = self.dict["xspider"]["body"]["pageextractors"] self.datastructure=self.dict["xspider"]["body"]["datastructure"] # self.notNullColNameList=self.getNotNullColName() #TODO 解析获取start_url的功能 ''' head ''' def __findhead(self): return find_node(self.root, "head") def __head(self): self.head=Head(self.__xsid(),self.__name(),self.__description()) def __xsid(self): return find_node(self.__findhead(), "xsid") def __name(self): return find_node(self.__findhead(), "name") def __description(self): return find_node(self.__findhead(), "description") ''' body ''' def __findbody(self): return find_node(self.root, "body") ''' entry ''' def __findentry(self): return find_node(self.root, "body/entry") def __entryUrls(self): self.entryUrls=[] for entry in find_nodes(self.__findentry(),"entryUrls/entryUrl"): self.entryUrls.append(entry.text) def __params(self): self.params=[] for node in find_nodes(self.__findentry(), "params/param"): self.params.append(Param(node.attrib.get("name",""),label=node.attrib.get("label",None))) ''' datastructure ''' def __datastructures(self): self.datacol=[] for node in find_nodes(self.__findbody(), "datastructure/col"): self.datacol.append(DataCol(node.attrib.get("name",""),label=node.attrib.get("label",None))) def getNotNullColName(self): list=[] for col in self.datastructure.get("col"): if str(col.get("@notNull",False)).__eq__("true"): list.append(col.get("@name")) return list ''' pageextractors ''' def __findpageextractors(self): return find_node(self.root, "body/pageextractors") def __pageextractors(self): self.pageextractors=[] for node in find_nodes(self.__findpageextractors(), "pageextractor"): regions=self.__regions(node) setcols=self.__setcols(node) links=self.__links(node) self.pageextractors.append(Pageextractor(name=node.attrib.get("name",""),dataStored=node.attrib.get("dataStored",True), jsonRegex=node.attrib.get("jsonRegex",None),sampleUrl=node.attrib.get("sampleUrl",None), type=node.attrib.get("type","html"),urlRegex=node.attrib.get("urlRegex",None), links=links,setcols=setcols,regions=regions)) ''' ''' def __regions(self,element): regions=[] for node in find_nodes(element, "region"): setcols = self.__setcols(node) links = self.__links(node) regions.append(Region(node.attrib.get("name",None),node.attrib.get("label",None),node.attrib.get("xpath",None),node.attrib.get("regex",None),setcols=setcols,links=links)) return regions def __setcols(self,element): setcols = [] for node in find_nodes(element, "setcol"): setcols.append(SetCol(node.attrib.get("ref",None),node.attrib.get("xpath",None),node.attrib.get("regex",None),node.attrib.get("format",None))) return setcols def __links(self,element): links = [] for node in find_nodes(element, "link"): links.append(Link(node.attrib.get("name",""),node.attrib.get("label",""), node.attrib.get("xpath",""), node.attrib.get("regex",""), node.attrib.get("format",""))) return links ''' config ''' def __config(self): node=find_node(self.root, "body/config") self.config=Config(agent=node.find("agent").text,urlcharset=node.find("urlcharset").text, charset=node.find("charset").text,sleepInterval=node.find("sleep").text,antiVerfiedCodeType=node.attrib.get("anti-verified-code","auto"), poolSize=node.find("poolSize").text,threadNum=node.find("threadNum").text,timeOut=node.find("timeOut").text, retryTimes=node.find("retryTimes").text,cycleRetryTimes=node.find("cycleRetryTimes").text, incrementParam=IncrementParam(node.attrib.get("key",None),node.attrib.get("value",None))) # def __setattr__(self, key, value): # # self.__dict__[key] = value # print("k:"+key ) # pass def elementstr(self): return str(ET.tostring(self.root, encoding='utf-8', method='xml'), "utf-8") # def json(self): # return xmltojson(self.elementstr()) if __name__ == "__main__": # tree = readfromxml("./a.xml") # root = tree.getroot() # treestr=tostring(tree, encoding='utf8', method='xml') # print(str(ET.tostring(root, encoding='utf-8', method='xml'), "utf-8")) xspider=Xspider("../../xml/a.xml") # print(xspider.xsid()) # print(xspider.entryUrls()) print(xspider.entryUrls) print(xspider.params[1].name) print(xspider.params[1].label) print(xspider.datacol) print(xspider.pageextractors[0].name) print(xspider.pageextractors[0].link) print(xspider.pageextractors[0].region) print(xspider.pageextractors[0].region[0].setcols[0].ref) print(xspider.config.poolSize) xspider.config.poolSize = 100 print(xspider.config.poolSize) # print(xspider.elementstr())
zpspider
/zpspider-0.1.tar.gz/zpspider-0.1/monetSpider/xspider/Xspider.py
Xspider.py
import os from xml.etree.ElementTree import ElementTree, Element, tostring,fromstring import xmltodict import json def readfromxml(in_path): '''读取并解析xml文件 in_path: xml路径 return: ElementTree''' tree = ElementTree() tree.parse(in_path) return tree def readfromstr(str): '''解析xml字符串 str: 字符串 return: ElementTree''' return ElementTree(fromstring(str)) def write_xml(tree, out_path): '''将xml文件写出 tree: xml树 out_path: 写出路径''' tree.write(out_path, encoding="utf-8", xml_declaration=True) def if_match(node, kv_map): '''判断某个节点是否包含所有传入参数属性 node: 节点 kv_map: 属性及属性值组成的map''' for key in kv_map: if node.get(key) != kv_map.get(key): return False return True # ---------------search ----- def find_nodes(tree, path): '''查找某个路径匹配的所有节点 tree: xml树 path: 节点路径''' return tree.findall(path) def find_node(tree, path): '''查找某个路径匹配的所有节点 tree: xml树 path: 节点路径''' return tree.find(path) def get_node_by_keyvalue(nodelist, kv_map): '''根据属性及属性值定位符合的节点,返回节点 nodelist: 节点列表 kv_map: 匹配属性及属性值map''' result_nodes = [] for node in nodelist: if if_match(node, kv_map): result_nodes.append(node) return result_nodes # ---------------change ----- def change_node_properties(nodelist, kv_map, is_delete=False): '''修改/增加 /删除 节点的属性及属性值 nodelist: 节点列表 kv_map:属性及属性值map''' for node in nodelist: for key in kv_map: if is_delete: if key in node.attrib: del node.attrib[key] else: node.set(key, kv_map.get(key)) def change_node_text(nodelist, text, is_add=False, is_delete=False): '''改变/增加/删除一个节点的文本 nodelist:节点列表 text : 更新后的文本''' for node in nodelist: if is_add: node.text += text elif is_delete: node.text = "" else: node.text = text def create_node(tag, property_map, content): '''新造一个节点 tag:节点标签 property_map:属性及属性值map content: 节点闭合标签里的文本内容 return 新节点''' element = Element(tag, property_map) element.text = content return element def add_child_node(nodelist, element): '''给一个节点添加子节点 nodelist: 节点列表 element: 子节点''' for node in nodelist: node.append(element) def del_node_by_tagkeyvalue(nodelist, tag, kv_map): '''同过属性及属性值定位一个节点,并删除之 nodelist: 父节点列表 tag:子节点标签 kv_map: 属性及属性值列表''' for parent_node in nodelist: children = list(parent_node) for child in children: if child.tag == tag and if_match(child, kv_map): parent_node.remove(child) #定义xml转json的函数 def xmlstrtojson(xmlstr): #parse是的xml解析器 xmlparse = xmltodict.parse(xmlstr) #json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。 #dumps()方法的ident=1,格式化json jsonstr = json.dumps(xmlparse,ensure_ascii=False,check_circular=False,indent=1) return jsonstr def xmlstrtodict(xmlstr): return xmltodict.parse(xmlstr) def jsontoxml(jsonstr): #xmltodict库的unparse()json转xml return xmltodict.unparse(jsonstr) def read_file_as_str(file_path): # 判断路径文件存在 if not os.path.isfile(file_path): raise TypeError(file_path + " does not exist") all_the_text = open(file_path).read() # print type(all_the_text) return all_the_text
zpspider
/zpspider-0.1.tar.gz/zpspider-0.1/monetSpider/utils/xml.py
xml.py
# zptess Command line utility to calibrate TESS-W at LICA ## Installation ```bash git clone https://github.com/STARS4ALL/zptess.git sudo python setup.py install ``` or ```bash pip install --user zptess ``` ## Run See `python -m zptess --help` for help ## The calibration process Samples from the reference TESS-W and the new TESS-W are taken and stored in circular buffers (default: 25 samples). An estimator of central tendency of frequencies is taken on each buffer (default estimator: median). The standard deviation from this estimator is also computed to asses the quality of readings. If this standard deviation is zero on either buffer, the whole process is discarded. Otherwise, we keep the estimated central tendency of reference and test frequencies and compute a candidate Zero Point. This process is repeated in a series of rounds (default: 5 rounds) and we select the "best" estimation of frequencies and Zero Point. The best freequency estimation is chosen as the *mode* with a fallback to *median* if mode does not exists. #### Formulae ``` Mag[ref] = ZP[fict] - 2.5*log10(Freq[ref]) Mag[tst] = ZP[fict] - 2.5*log10(Freq[tst]) Offset = 2.5*log10(Freq[tst]/Freq[ref]) ZP[calibrated] = ZP[ref] + Offset where ZP[fict] is a ficticios zero point of 20.50 to compare readings with the TESS Windows utility by Cristobal García. ZP[ref] is the absolute Zero Point of the calibrated TESS-W (20.44) determined by LICA. ```
zptess
/zptess-2.1.3.tar.gz/zptess-2.1.3/README.md
README.md
from __future__ import print_function try: import configparser except ImportError: import ConfigParser as configparser import errno import json import os import re import subprocess import sys class VersioneerConfig: pass def get_root(): # we require that all commands are run from the project root, i.e. the # directory that contains setup.py, setup.cfg, and versioneer.py . root = os.path.realpath(os.path.abspath(os.getcwd())) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): # allow 'python path/to/setup.py COMMAND' root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0]))) setup_py = os.path.join(root, "setup.py") versioneer_py = os.path.join(root, "versioneer.py") if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)): err = ("Versioneer was unable to run the project root directory. " "Versioneer requires setup.py to be executed from " "its immediate directory (like 'python setup.py COMMAND'), " "or in a way that lets it use sys.argv[0] to find the root " "(like 'python path/to/setup.py COMMAND').") raise VersioneerBadRootError(err) try: # Certain runtime workflows (setup.py install/develop in a setuptools # tree) execute all dependencies in a single python process, so # "versioneer" may be imported multiple times, and python's shared # module-import table will cache the first one. So we can't use # os.path.dirname(__file__), as that will find whichever # versioneer.py was first imported, even in later projects. me = os.path.realpath(os.path.abspath(__file__)) if os.path.splitext(me)[0] != os.path.splitext(versioneer_py)[0]: print("Warning: build in %s is using versioneer.py from %s" % (os.path.dirname(me), versioneer_py)) except NameError: pass return root def get_config_from_root(root): # This might raise EnvironmentError (if setup.cfg is missing), or # configparser.NoSectionError (if it lacks a [versioneer] section), or # configparser.NoOptionError (if it lacks "VCS="). See the docstring at # the top of versioneer.py for instructions on writing your setup.cfg . setup_cfg = os.path.join(root, "setup.cfg") parser = configparser.SafeConfigParser() with open(setup_cfg, "r") as f: parser.readfp(f) VCS = parser.get("versioneer", "VCS") # mandatory def get(parser, name): if parser.has_option("versioneer", name): return parser.get("versioneer", name) return None cfg = VersioneerConfig() cfg.VCS = VCS cfg.style = get(parser, "style") or "" cfg.versionfile_source = get(parser, "versionfile_source") cfg.versionfile_build = get(parser, "versionfile_build") cfg.tag_prefix = get(parser, "tag_prefix") cfg.parentdir_prefix = get(parser, "parentdir_prefix") cfg.verbose = get(parser, "verbose") return cfg class NotThisMethod(Exception): pass # these dictionaries contain VCS-specific tools LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator def decorate(f): if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %s" % dispcmd) print(e) return None else: if verbose: print("unable to find command, tried %s" % (commands,)) return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %s (error)" % dispcmd) return None return stdout LONG_VERSION_PY['git'] = ''' # This file helps to compute a version number in source trees obtained from # git-archive tarball (such as those provided by githubs download-from-tag # feature). Distribution tarballs (built by setup.py sdist) and build # directories (produced by setup.py build) will contain a much shorter file # that just contains the computed version number. # This file is released into the public domain. Generated by # versioneer-0.15 (https://github.com/warner/python-versioneer) import errno import os import re import subprocess import sys def get_keywords(): # these strings will be replaced by git during git-archive. # setup.py/versioneer.py will grep for the variable names, so they must # each be defined on a line of their own. _version.py will just call # get_keywords(). git_refnames = "%(DOLLAR)sFormat:%%d%(DOLLAR)s" git_full = "%(DOLLAR)sFormat:%%H%(DOLLAR)s" keywords = {"refnames": git_refnames, "full": git_full} return keywords class VersioneerConfig: pass def get_config(): # these strings are filled in when 'setup.py versioneer' creates # _version.py cfg = VersioneerConfig() cfg.VCS = "git" cfg.style = "%(STYLE)s" cfg.tag_prefix = "%(TAG_PREFIX)s" cfg.parentdir_prefix = "%(PARENTDIR_PREFIX)s" cfg.versionfile_source = "%(VERSIONFILE_SOURCE)s" cfg.verbose = False return cfg class NotThisMethod(Exception): pass LONG_VERSION_PY = {} HANDLERS = {} def register_vcs_handler(vcs, method): # decorator def decorate(f): if vcs not in HANDLERS: HANDLERS[vcs] = {} HANDLERS[vcs][method] = f return f return decorate def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False): assert isinstance(commands, list) p = None for c in commands: try: dispcmd = str([c] + args) # remember shell=False, so use git.cmd on windows, not just git p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE, stderr=(subprocess.PIPE if hide_stderr else None)) break except EnvironmentError: e = sys.exc_info()[1] if e.errno == errno.ENOENT: continue if verbose: print("unable to run %%s" %% dispcmd) print(e) return None else: if verbose: print("unable to find command, tried %%s" %% (commands,)) return None stdout = p.communicate()[0].strip() if sys.version_info[0] >= 3: stdout = stdout.decode() if p.returncode != 0: if verbose: print("unable to run %%s (error)" %% dispcmd) return None return stdout def versions_from_parentdir(parentdir_prefix, root, verbose): # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%%s', but '%%s' doesn't start with " "prefix '%%s'" %% (root, dirname, parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None} @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): if not keywords: raise NotThisMethod("no keywords at all, weird") refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %%d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%%s', no digits" %% ",".join(refs-tags)) if verbose: print("likely tags: %%s" %% ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %%s" %% r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags"} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' keywords were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %%s" %% root) raise NotThisMethod("no .git directory") GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # if there is a tag, this yields TAG-NUM-gHEX[-dirty] # if there are no tags, this yields HEX[-dirty] (no NUM) describe_out = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long"], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%%s'" %% describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%%s' doesn't start with prefix '%%s'" print(fmt %% (full_tag, tag_prefix)) pieces["error"] = ("tag '%%s' doesn't start with prefix '%%s'" %% (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits return pieces def plus_or_dot(pieces): if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): # now build up version string, with post-release "local version # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty # exceptions: # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%%d.g%%s" %% (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): # TAG[.post.devDISTANCE] . No -dirty # exceptions: # 1: no tags. 0.post.devDISTANCE if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%%d" %% pieces["distance"] else: # exception #1 rendered = "0.post.dev%%d" %% pieces["distance"] return rendered def render_pep440_post(pieces): # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that # .dev0 sorts backwards (a dirty tree will appear "older" than the # corresponding clean one), but you shouldn't be releasing software with # -dirty anyways. # exceptions: # 1: no tags. 0.postDISTANCE[.dev0] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%%s" %% pieces["short"] else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%%s" %% pieces["short"] return rendered def render_pep440_old(pieces): # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. # exceptions: # 1: no tags. 0.postDISTANCE[.dev0] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%%d" %% pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty # --always' # exceptions: # 1: no tags. HEX[-dirty] (note: no 'g' prefix) if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty # --always -long'. The distance/hash is unconditional. # exceptions: # 1: no tags. HEX[-dirty] (note: no 'g' prefix) if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%%d-g%%s" %% (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%%s'" %% style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None} def get_versions(): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which # case we can only use expanded keywords. cfg = get_config() verbose = cfg.verbose try: return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose) except NotThisMethod: pass try: root = os.path.realpath(__file__) # versionfile_source is the relative path from the top of the source # tree (where the .git directory might live) to this file. Invert # this to find the root from __file__. for i in cfg.versionfile_source.split('/'): root = os.path.dirname(root) except NameError: return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to find root of source tree"} try: pieces = git_pieces_from_vcs(cfg.tag_prefix, root, verbose) return render(pieces, cfg.style) except NotThisMethod: pass try: if cfg.parentdir_prefix: return versions_from_parentdir(cfg.parentdir_prefix, root, verbose) except NotThisMethod: pass return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version"} ''' @register_vcs_handler("git", "get_keywords") def git_get_keywords(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # keywords. When used from setup.py, we don't want to import _version.py, # so we do it with a regexp instead. This function is not used from # _version.py. keywords = {} try: f = open(versionfile_abs, "r") for line in f.readlines(): if line.strip().startswith("git_refnames ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["refnames"] = mo.group(1) if line.strip().startswith("git_full ="): mo = re.search(r'=\s*"(.*)"', line) if mo: keywords["full"] = mo.group(1) f.close() except EnvironmentError: pass return keywords @register_vcs_handler("git", "keywords") def git_versions_from_keywords(keywords, tag_prefix, verbose): if not keywords: raise NotThisMethod("no keywords at all, weird") refnames = keywords["refnames"].strip() if refnames.startswith("$Format"): if verbose: print("keywords are unexpanded, not using") raise NotThisMethod("unexpanded keywords, not a git-archive tarball") refs = set([r.strip() for r in refnames.strip("()").split(",")]) # starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of # just "foo-1.0". If we see a "tag: " prefix, prefer those. TAG = "tag: " tags = set([r[len(TAG):] for r in refs if r.startswith(TAG)]) if not tags: # Either we're using git < 1.8.3, or there really are no tags. We use # a heuristic: assume all version tags have a digit. The old git %d # expansion behaves like git log --decorate=short and strips out the # refs/heads/ and refs/tags/ prefixes that would let us distinguish # between branches and tags. By ignoring refnames without digits, we # filter out many common branch names like "release" and # "stabilization", as well as "HEAD" and "master". tags = set([r for r in refs if re.search(r'\d', r)]) if verbose: print("discarding '%s', no digits" % ",".join(refs-tags)) if verbose: print("likely tags: %s" % ",".join(sorted(tags))) for ref in sorted(tags): # sorting will prefer e.g. "2.0" over "2.0rc1" if ref.startswith(tag_prefix): r = ref[len(tag_prefix):] if verbose: print("picking %s" % r) return {"version": r, "full-revisionid": keywords["full"].strip(), "dirty": False, "error": None } # no suitable tags, so version is "0+unknown", but full hex is still there if verbose: print("no suitable tags, using unknown + full revision id") return {"version": "0+unknown", "full-revisionid": keywords["full"].strip(), "dirty": False, "error": "no suitable tags"} @register_vcs_handler("git", "pieces_from_vcs") def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' keywords were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. if not os.path.exists(os.path.join(root, ".git")): if verbose: print("no .git in %s" % root) raise NotThisMethod("no .git directory") GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] # if there is a tag, this yields TAG-NUM-gHEX[-dirty] # if there are no tags, this yields HEX[-dirty] (no NUM) describe_out = run_command(GITS, ["describe", "--tags", "--dirty", "--always", "--long"], cwd=root) # --long was added in git-1.5.5 if describe_out is None: raise NotThisMethod("'git describe' failed") describe_out = describe_out.strip() full_out = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) if full_out is None: raise NotThisMethod("'git rev-parse' failed") full_out = full_out.strip() pieces = {} pieces["long"] = full_out pieces["short"] = full_out[:7] # maybe improved later pieces["error"] = None # parse describe_out. It will be like TAG-NUM-gHEX[-dirty] or HEX[-dirty] # TAG might have hyphens. git_describe = describe_out # look for -dirty suffix dirty = git_describe.endswith("-dirty") pieces["dirty"] = dirty if dirty: git_describe = git_describe[:git_describe.rindex("-dirty")] # now we have TAG-NUM-gHEX or HEX if "-" in git_describe: # TAG-NUM-gHEX mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe) if not mo: # unparseable. Maybe git-describe is misbehaving? pieces["error"] = ("unable to parse git-describe output: '%s'" % describe_out) return pieces # tag full_tag = mo.group(1) if not full_tag.startswith(tag_prefix): if verbose: fmt = "tag '%s' doesn't start with prefix '%s'" print(fmt % (full_tag, tag_prefix)) pieces["error"] = ("tag '%s' doesn't start with prefix '%s'" % (full_tag, tag_prefix)) return pieces pieces["closest-tag"] = full_tag[len(tag_prefix):] # distance: number of commits since tag pieces["distance"] = int(mo.group(2)) # commit: short hex revision ID pieces["short"] = mo.group(3) else: # HEX: no tags pieces["closest-tag"] = None count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root) pieces["distance"] = int(count_out) # total number of commits return pieces def do_vcs_install(manifest_in, versionfile_source, ipy): GITS = ["git"] if sys.platform == "win32": GITS = ["git.cmd", "git.exe"] files = [manifest_in, versionfile_source] if ipy: files.append(ipy) try: me = __file__ if me.endswith(".pyc") or me.endswith(".pyo"): me = os.path.splitext(me)[0] + ".py" versioneer_file = os.path.relpath(me) except NameError: versioneer_file = "versioneer.py" files.append(versioneer_file) present = False try: f = open(".gitattributes", "r") for line in f.readlines(): if line.strip().startswith(versionfile_source): if "export-subst" in line.strip().split()[1:]: present = True f.close() except EnvironmentError: pass if not present: f = open(".gitattributes", "a+") f.write("%s export-subst\n" % versionfile_source) f.close() files.append(".gitattributes") run_command(GITS, ["add", "--"] + files) def versions_from_parentdir(parentdir_prefix, root, verbose): # Source tarballs conventionally unpack into a directory that includes # both the project name and a version string. dirname = os.path.basename(root) if not dirname.startswith(parentdir_prefix): if verbose: print("guessing rootdir is '%s', but '%s' doesn't start with " "prefix '%s'" % (root, dirname, parentdir_prefix)) raise NotThisMethod("rootdir doesn't start with parentdir_prefix") return {"version": dirname[len(parentdir_prefix):], "full-revisionid": None, "dirty": False, "error": None} SHORT_VERSION_PY = """ # This file was generated by 'versioneer.py' (0.15) from # revision-control system data, or from the parent directory name of an # unpacked source archive. Distribution tarballs contain a pre-generated copy # of this file. import json import sys version_json = ''' %s ''' # END VERSION_JSON def get_versions(): return json.loads(version_json) """ def versions_from_file(filename): try: with open(filename) as f: contents = f.read() except EnvironmentError: raise NotThisMethod("unable to read _version.py") mo = re.search(r"version_json = '''\n(.*)''' # END VERSION_JSON", contents, re.M | re.S) if not mo: raise NotThisMethod("no version_json in _version.py") return json.loads(mo.group(1)) def write_to_version_file(filename, versions): os.unlink(filename) contents = json.dumps(versions, sort_keys=True, indent=1, separators=(",", ": ")) with open(filename, "w") as f: f.write(SHORT_VERSION_PY % contents) print("set %s to '%s'" % (filename, versions["version"])) def plus_or_dot(pieces): if "+" in pieces.get("closest-tag", ""): return "." return "+" def render_pep440(pieces): # now build up version string, with post-release "local version # identifier". Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you # get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty # exceptions: # 1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += "%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" else: # exception #1 rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"]) if pieces["dirty"]: rendered += ".dirty" return rendered def render_pep440_pre(pieces): # TAG[.post.devDISTANCE] . No -dirty # exceptions: # 1: no tags. 0.post.devDISTANCE if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += ".post.dev%d" % pieces["distance"] else: # exception #1 rendered = "0.post.dev%d" % pieces["distance"] return rendered def render_pep440_post(pieces): # TAG[.postDISTANCE[.dev0]+gHEX] . The ".dev0" means dirty. Note that # .dev0 sorts backwards (a dirty tree will appear "older" than the # corresponding clean one), but you shouldn't be releasing software with # -dirty anyways. # exceptions: # 1: no tags. 0.postDISTANCE[.dev0] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += plus_or_dot(pieces) rendered += "g%s" % pieces["short"] else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" rendered += "+g%s" % pieces["short"] return rendered def render_pep440_old(pieces): # TAG[.postDISTANCE[.dev0]] . The ".dev0" means dirty. # exceptions: # 1: no tags. 0.postDISTANCE[.dev0] if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += ".post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" else: # exception #1 rendered = "0.post%d" % pieces["distance"] if pieces["dirty"]: rendered += ".dev0" return rendered def render_git_describe(pieces): # TAG[-DISTANCE-gHEX][-dirty], like 'git describe --tags --dirty # --always' # exceptions: # 1: no tags. HEX[-dirty] (note: no 'g' prefix) if pieces["closest-tag"]: rendered = pieces["closest-tag"] if pieces["distance"]: rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render_git_describe_long(pieces): # TAG-DISTANCE-gHEX[-dirty], like 'git describe --tags --dirty # --always -long'. The distance/hash is unconditional. # exceptions: # 1: no tags. HEX[-dirty] (note: no 'g' prefix) if pieces["closest-tag"]: rendered = pieces["closest-tag"] rendered += "-%d-g%s" % (pieces["distance"], pieces["short"]) else: # exception #1 rendered = pieces["short"] if pieces["dirty"]: rendered += "-dirty" return rendered def render(pieces, style): if pieces["error"]: return {"version": "unknown", "full-revisionid": pieces.get("long"), "dirty": None, "error": pieces["error"]} if not style or style == "default": style = "pep440" # the default if style == "pep440": rendered = render_pep440(pieces) elif style == "pep440-pre": rendered = render_pep440_pre(pieces) elif style == "pep440-post": rendered = render_pep440_post(pieces) elif style == "pep440-old": rendered = render_pep440_old(pieces) elif style == "git-describe": rendered = render_git_describe(pieces) elif style == "git-describe-long": rendered = render_git_describe_long(pieces) else: raise ValueError("unknown style '%s'" % style) return {"version": rendered, "full-revisionid": pieces["long"], "dirty": pieces["dirty"], "error": None} class VersioneerBadRootError(Exception): pass def get_versions(verbose=False): # returns dict with two keys: 'version' and 'full' if "versioneer" in sys.modules: # see the discussion in cmdclass.py:get_cmdclass() del sys.modules["versioneer"] root = get_root() cfg = get_config_from_root(root) assert cfg.VCS is not None, "please set [versioneer]VCS= in setup.cfg" handlers = HANDLERS.get(cfg.VCS) assert handlers, "unrecognized VCS '%s'" % cfg.VCS verbose = verbose or cfg.verbose assert cfg.versionfile_source is not None, \ "please set versioneer.versionfile_source" assert cfg.tag_prefix is not None, "please set versioneer.tag_prefix" versionfile_abs = os.path.join(root, cfg.versionfile_source) # extract version from first of: _version.py, VCS command (e.g. 'git # describe'), parentdir. This is meant to work for developers using a # source checkout, for users of a tarball created by 'setup.py sdist', # and for users of a tarball/zipball created by 'git archive' or github's # download-from-tag feature or the equivalent in other VCSes. get_keywords_f = handlers.get("get_keywords") from_keywords_f = handlers.get("keywords") if get_keywords_f and from_keywords_f: try: keywords = get_keywords_f(versionfile_abs) ver = from_keywords_f(keywords, cfg.tag_prefix, verbose) if verbose: print("got version from expanded keyword %s" % ver) return ver except NotThisMethod: pass try: ver = versions_from_file(versionfile_abs) if verbose: print("got version from file %s %s" % (versionfile_abs, ver)) return ver except NotThisMethod: pass from_vcs_f = handlers.get("pieces_from_vcs") if from_vcs_f: try: pieces = from_vcs_f(cfg.tag_prefix, root, verbose) ver = render(pieces, cfg.style) if verbose: print("got version from VCS %s" % ver) return ver except NotThisMethod: pass try: if cfg.parentdir_prefix: ver = versions_from_parentdir(cfg.parentdir_prefix, root, verbose) if verbose: print("got version from parentdir %s" % ver) return ver except NotThisMethod: pass if verbose: print("unable to compute version") return {"version": "0+unknown", "full-revisionid": None, "dirty": None, "error": "unable to compute version"} def get_version(): return get_versions()["version"] def get_cmdclass(): if "versioneer" in sys.modules: del sys.modules["versioneer"] # this fixes the "python setup.py develop" case (also 'install' and # 'easy_install .'), in which subdependencies of the main project are # built (using setup.py bdist_egg) in the same python process. Assume # a main project A and a dependency B, which use different versions # of Versioneer. A's setup.py imports A's Versioneer, leaving it in # sys.modules by the time B's setup.py is executed, causing B to run # with the wrong versioneer. Setuptools wraps the sub-dep builds in a # sandbox that restores sys.modules to it's pre-build state, so the # parent is protected against the child's "import versioneer". By # removing ourselves from sys.modules here, before the child build # happens, we protect the child from the parent's versioneer too. # Also see https://github.com/warner/python-versioneer/issues/52 cmds = {} # we add "version" to both distutils and setuptools from distutils.core import Command class cmd_version(Command): description = "report generated version string" user_options = [] boolean_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): vers = get_versions(verbose=True) print("Version: %s" % vers["version"]) print(" full-revisionid: %s" % vers.get("full-revisionid")) print(" dirty: %s" % vers.get("dirty")) if vers["error"]: print(" error: %s" % vers["error"]) cmds["version"] = cmd_version # we override "build_py" in both distutils and setuptools # # most invocation pathways end up running build_py: # distutils/build -> build_py # distutils/install -> distutils/build ->.. # setuptools/bdist_wheel -> distutils/install ->.. # setuptools/bdist_egg -> distutils/install_lib -> build_py # setuptools/install -> bdist_egg ->.. # setuptools/develop -> ? from distutils.command.build_py import build_py as _build_py class cmd_build_py(_build_py): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() _build_py.run(self) # now locate _version.py in the new build/ directory and replace # it with an updated value if cfg.versionfile_build: target_versionfile = os.path.join(self.build_lib, cfg.versionfile_build) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) cmds["build_py"] = cmd_build_py if "cx_Freeze" in sys.modules: # cx_freeze enabled? from cx_Freeze.dist import build_exe as _build_exe class cmd_build_exe(_build_exe): def run(self): root = get_root() cfg = get_config_from_root(root) versions = get_versions() target_versionfile = cfg.versionfile_source print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, versions) _build_exe.run(self) os.unlink(target_versionfile) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) cmds["build_exe"] = cmd_build_exe del cmds["build_py"] # we override different "sdist" commands for both environments if "setuptools" in sys.modules: from setuptools.command.sdist import sdist as _sdist else: from distutils.command.sdist import sdist as _sdist class cmd_sdist(_sdist): def run(self): versions = get_versions() self._versioneer_generated_versions = versions # unless we update this, the command will keep using the old # version self.distribution.metadata.version = versions["version"] return _sdist.run(self) def make_release_tree(self, base_dir, files): root = get_root() cfg = get_config_from_root(root) _sdist.make_release_tree(self, base_dir, files) # now locate _version.py in the new base_dir directory # (remembering that it may be a hardlink) and replace it with an # updated value target_versionfile = os.path.join(base_dir, cfg.versionfile_source) print("UPDATING %s" % target_versionfile) write_to_version_file(target_versionfile, self._versioneer_generated_versions) cmds["sdist"] = cmd_sdist return cmds CONFIG_ERROR = """ setup.cfg is missing the necessary Versioneer configuration. You need a section like: [versioneer] VCS = git style = pep440 versionfile_source = src/myproject/_version.py versionfile_build = myproject/_version.py tag_prefix = "" parentdir_prefix = myproject- You will also need to edit your setup.py to use the results: import versioneer setup(version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), ...) Please read the docstring in ./versioneer.py for configuration instructions, edit setup.cfg, and re-run the installer or 'python versioneer.py setup'. """ SAMPLE_CONFIG = """ # See the docstring in versioneer.py for instructions. Note that you must # re-run 'versioneer.py setup' after changing this section, and commit the # resulting files. [versioneer] #VCS = git #style = pep440 #versionfile_source = #versionfile_build = #tag_prefix = #parentdir_prefix = """ INIT_PY_SNIPPET = """ from ._version import get_versions __version__ = get_versions()['version'] del get_versions """ def do_setup(): root = get_root() try: cfg = get_config_from_root(root) except (EnvironmentError, configparser.NoSectionError, configparser.NoOptionError) as e: if isinstance(e, (EnvironmentError, configparser.NoSectionError)): print("Adding sample versioneer config to setup.cfg", file=sys.stderr) with open(os.path.join(root, "setup.cfg"), "a") as f: f.write(SAMPLE_CONFIG) print(CONFIG_ERROR, file=sys.stderr) return 1 print(" creating %s" % cfg.versionfile_source) with open(cfg.versionfile_source, "w") as f: LONG = LONG_VERSION_PY[cfg.VCS] f.write(LONG % {"DOLLAR": "$", "STYLE": cfg.style, "TAG_PREFIX": cfg.tag_prefix, "PARENTDIR_PREFIX": cfg.parentdir_prefix, "VERSIONFILE_SOURCE": cfg.versionfile_source, }) ipy = os.path.join(os.path.dirname(cfg.versionfile_source), "__init__.py") if os.path.exists(ipy): try: with open(ipy, "r") as f: old = f.read() except EnvironmentError: old = "" if INIT_PY_SNIPPET not in old: print(" appending to %s" % ipy) with open(ipy, "a") as f: f.write(INIT_PY_SNIPPET) else: print(" %s unmodified" % ipy) else: print(" %s doesn't exist, ok" % ipy) ipy = None # Make sure both the top-level "versioneer.py" and versionfile_source # (PKG/_version.py, used by runtime code) are in MANIFEST.in, so # they'll be copied into source distributions. Pip won't be able to # install the package without this. manifest_in = os.path.join(root, "MANIFEST.in") simple_includes = set() try: with open(manifest_in, "r") as f: for line in f: if line.startswith("include "): for include in line.split()[1:]: simple_includes.add(include) except EnvironmentError: pass # That doesn't cover everything MANIFEST.in can do # (http://docs.python.org/2/distutils/sourcedist.html#commands), so # it might give some false negatives. Appending redundant 'include' # lines is safe, though. if "versioneer.py" not in simple_includes: print(" appending 'versioneer.py' to MANIFEST.in") with open(manifest_in, "a") as f: f.write("include versioneer.py\n") else: print(" 'versioneer.py' already in MANIFEST.in") if cfg.versionfile_source not in simple_includes: print(" appending versionfile_source ('%s') to MANIFEST.in" % cfg.versionfile_source) with open(manifest_in, "a") as f: f.write("include %s\n" % cfg.versionfile_source) else: print(" versionfile_source already in MANIFEST.in") # Make VCS-specific changes. For git, this means creating/changing # .gitattributes to mark _version.py for export-time keyword # substitution. do_vcs_install(manifest_in, cfg.versionfile_source, ipy) return 0 def scan_setup_py(): found = set() setters = False errors = 0 with open("setup.py", "r") as f: for line in f.readlines(): if "import versioneer" in line: found.add("import") if "versioneer.get_cmdclass()" in line: found.add("cmdclass") if "versioneer.get_version()" in line: found.add("get_version") if "versioneer.VCS" in line: setters = True if "versioneer.versionfile_source" in line: setters = True if len(found) != 3: print("") print("Your setup.py appears to be missing some important items") print("(but I might be wrong). Please make sure it has something") print("roughly like the following:") print("") print(" import versioneer") print(" setup( version=versioneer.get_version(),") print(" cmdclass=versioneer.get_cmdclass(), ...)") print("") errors += 1 if setters: print("You should remove lines like 'versioneer.VCS = ' and") print("'versioneer.versionfile_source = ' . This configuration") print("now lives in setup.cfg, and should be removed from setup.py") print("") errors += 1 return errors if __name__ == "__main__": cmd = sys.argv[1] if cmd == "setup": errors = do_setup() errors += scan_setup_py() if errors: sys.exit(1)
zptess
/zptess-2.1.3.tar.gz/zptess-2.1.3/versioneer.py
versioneer.py
zptlint ======= Script that runs the pagetemplate parser and output errors Installation ============ Because `zptlint` depends on `zope.pagetemplate`, it depends on a lot of other zope eggs. To avoid polluting you system python, you can install `zptlint` in a `virtualenv`:: $ virtualenv --no-site-packages zptlint $ cd zptlint/ $ bin/easy_install zptlint Then make a link to the right script:: $ ln -s MYPATH/zptlint/bin/zptlint Configuration in .vimrc ======================= :: "page templates configuration autocmd BufNewFile,BufRead *.pt,*.cpt,*.zpt setfiletype zpt autocmd FileType zpt set makeprg=zptlint\ % autocmd FileType zpt set errorformat=%+P***\ Error\ in:\ %f,%Z%*\\s\\,\ at\ line\ %l\\,\ column\ %c,%E%*\\s%m,%-Q augroup filetype au BufWritePost,FileWritePost *.pt make au BufWritePost,FileWritePost *.cpt make au BufWritePost,FileWritePost *.zpt make augroup END Because zpt is defined as a new file type, you may want to copy `syntax/html.vim` to `syntax/zpt.vim` and `ftplugin/html.vim` to `ftplugin/zpt.vim`. or usage from command-line in vim:: set makeprg=zptlint\ % set errorformat=%+P***\ Error\ in:\ %f,%Z%*\\s\\,\ at\ line\ %l\\,\ column\ %c,%E%*\\s%m,%-Q Credits ======= * code by Balazs Ree, Greenfinity * eggified by Godefroid Chapelle, BubbleNet
zptlint
/zptlint-0.2.4.tar.gz/zptlint-0.2.4/README.txt
README.txt
import os, shutil, sys, tempfile, urllib2 from optparse import OptionParser tmpeggs = tempfile.mkdtemp() is_jython = sys.platform.startswith('java') # parsing arguments parser = OptionParser() parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="distribute", default=False, help="Use Disribute rather than Setuptools.") parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout' main function if options.config_file is not None: args += ['-c', options.config_file] if options.version is not None: VERSION = '==%s' % options.version else: VERSION = '' USE_DISTRIBUTE = options.distribute args = args + ['bootstrap'] to_reload = False try: import pkg_resources if not hasattr(pkg_resources, '_distribute'): to_reload = True raise ImportError except ImportError: ez = {} if USE_DISTRIBUTE: exec urllib2.urlopen('http://python-distribute.org/distribute_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0, no_fake=True) else: exec urllib2.urlopen('http://peak.telecommunity.com/dist/ez_setup.py' ).read() in ez ez['use_setuptools'](to_dir=tmpeggs, download_delay=0) if to_reload: reload(pkg_resources) else: import pkg_resources if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: def quote (c): return c cmd = 'from setuptools.command.easy_install import main; main()' ws = pkg_resources.working_set if USE_DISTRIBUTE: requirement = 'distribute' else: requirement = 'setuptools' if is_jython: import subprocess assert subprocess.Popen([sys.executable] + ['-c', quote(cmd), '-mqNxd', quote(tmpeggs), 'zc.buildout' + VERSION], env=dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ).wait() == 0 else: assert os.spawnle( os.P_WAIT, sys.executable, quote (sys.executable), '-c', quote (cmd), '-mqNxd', quote (tmpeggs), 'zc.buildout' + VERSION, dict(os.environ, PYTHONPATH= ws.find(pkg_resources.Requirement.parse(requirement)).location ), ) == 0 ws.add_entry(tmpeggs) ws.require('zc.buildout' + VERSION) import zc.buildout.buildout zc.buildout.buildout.main(args) shutil.rmtree(tmpeggs)
zptlint
/zptlint-0.2.4.tar.gz/zptlint-0.2.4/bootstrap.py
bootstrap.py
<p align="center"> <a href="https://github.com/NoeCruzMW/zpy-flask-msc-docs"><img width="150" src="https://lh3.googleusercontent.com/a-/AOh14GjLO5qYYR5nQl5hgavUKz4Dv3LVzWDvGtV4xNam=s600-k-no-rp-mo" alt="Zurck'z"></a> </p> <p align="center"> <em>ZPy Core, Layer for build microservices</em> </p> <p align="center"></p> --- # ZPy Core > Zurck'z Py Flask Micro Services Core This package contains some helpers features for build python microservices using Flask framework ZPy use the following packages: - Flask - marshmallow - marshmallow_objects - requests - aws-lambda-wsgi ## Requirements - Python 3.6+ ## Installation Use the package manager [pip](https://pip.pypa.io/en/stable/) to install py flask micro service core . ```bash pip install zpy-api-core ``` ## Features Contains some helper features. - Api - Api Builder - Response Builder - Models - Hooks - Middlewares - Exceptions - Cloud Implementations - Aws Handler decorators - [See: AWS Package](https://pypi.org/project/zpy-cloud-utils) - CLI - DDD Project structure generator - Bounded Context Generator - UseCases generator - Database - [See: SQL Oracle & MySQL](https://pypi.org/project/zpy-db-core) - Logger - Stream - Utils - Collections - element finder - Dates - Time zones - Transforms - Ciphers - [See: Crypto Wrappers](https://pypi.org/project/zpy-ciphers-utils) - Functions - Parallel - map parallel - run parallel - Objects - gzip ## Basic Usage Generate project using _zpy CLI_ ```shell # Generate project with basic information. for more type: zpy --help zpy make -p awesome-api -d "My awsome users api" -c Users -uc UserSearcher -op ... cd awesome-api ``` zpy will generate the project with the following structure ``` awesome-api │ .env │ .gitignore │ CHANGELOG.md │ CHANGELOG.md │ README.md │ requirements.txt │ └───src │ │ di.py │ │ handler.py │ │ local_deploy.py │ │ │ └───┬api │ │ routes.py │ │ ... │ └contexts │ │ ... │ └───users │ │ ... │ └───┬application │ │ │ ... │ └───┬domain │ │ │ ... │ └───┬infraestructure │ │ ... └───tests │ user_searcher_test.py ``` Dependencies file ```python # 🛸 Generated by zPy from zpy.utils import get_env_or_throw as var from zpy.app.usecase import UseCase from typing import Any # * Setup Dependencies 📃 from contexts.users.domain.repositories import UserRepository from contexts.users.infraestructure.payment_repository import AwesomeUserRepository from contexts.users.application.user_searcher import UserSearcher repository: UserRepository = AwesomeUserRepository() # Setup UseCases user_searcher_uc: UseCase[Any, None] = UserSearcher(repository) print("🚀 Dependencies loaded successfully...") ``` routes.py ```python # 🛸 Generated by zPy from di import user_searcher_uc from flask import Flask from zpy.api.http.response import response_builder from zpy.api.flask import create_app app: Flask = create_app() @app.route("/api/users", methods=["GET"]) @response_builder def users(): return user_searcher_uc.execute(None) ``` Use Case ```python # 🛸 Generated by zPy from typing import Any from zpy.app.usecase import UseCase from ..domain.repositories import UserRepository class UserSearcher(UseCase[Any, Any]): """ Use Case description. """ def __init__(self, repository: PaymentRepository) -> None: self.repository = repository def execute(self, data: Any, *args, **kwargs) -> None: # TODO Do magic with business rules 😁 return self.repository.user_searcher(data) ``` Local Dev Deploy ```python # 🛸 Generated by zPy from dotenv import load_dotenv load_dotenv( dotenv_path="|3:\\projects\\demos\\awesome-api\\.env" ) from api.routes import app if __name__ == "__main__": app.run(host="127.0.0.1", port=5050, debug=True) ``` handler.py configure for aws lambda and api gateway ```python # 🛸 Generated by zPy from zpy.api.flask.cloud_handlers import aws_lambda from api.routes import app import aws_lambda_wsgi as awsgi @aws_lambda() def handle(event: dict, context: dict) -> any: return awsgi.response(app, event, context) ``` ## Contributing Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate. ## License [MIT](https://choosealicense.com/licenses/mit/) ## Authors [Noé Cruz](https://www.linkedin.com/in/zurckz/)
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/README.md
README.md
import dataclasses from functools import wraps from inspect import isclass, signature from typing import Callable, Optional, Any, Tuple, TypeVar from zpy.logger import ZLogger from zpy.utils.values import if_null_get from zpy.app import zapp_context as ctx import time T = TypeVar("T") @dataclasses.dataclass class DLazy: type: Any initializer: Callable[[Any], Any] class DIContainer: """ Basic Dependency Container """ def __init__(self, timeit: bool = False, x_logger: ZLogger = None, notifier: Callable[[Any, Optional[Any]], None] = None) -> None: self.container: dict = dict() self.logger: ZLogger = if_null_get(x_logger, ctx().logger) self.timeit: bool = timeit self.notifier: Callable[[Any, Optional[Any]], None] = notifier self.throw_ex = True self.error_message_prefix = "Fatal" self.max_time_allowed = 5 def with_notifier(self, notifier): self.notifier = notifier @classmethod def create(cls, timeit: bool = False, logger: ZLogger = None) -> 'DIContainer': return cls(timeit, logger) def setup(self, init_fn: Callable[['DIContainer'], None]) -> 'DIContainer': try: te = time.time() init_fn(self) ts = time.time() self.logger.info(f"🚀 Dependencies loaded successfully... {(ts - te) * 1000:2.2f} ms.") except Exception as e: self.logger.err("Failed to load dependencies...") if self.notifier: self.notifier(f"{self.error_message_prefix} - Failed to load dependencies: {str(e)}") if self.throw_ex: raise return self def __getitem__(self, item: T) -> T: return self.get(item) def __setitem__(self, key, value): self.container[key] = value def register(self, x_type: Any, value: Any) -> None: """ Register object or instance of any type in the container. @param x_type: Object type to register @param value: instance or value to register @return: None """ self[x_type] = value def factory_register(self, x_type: Any, initializer: Callable[[Any], Any]) -> None: """ Register object or instance of any type in the container using factory strategy. This method evaluates the load time, if the load time exceeds the allowed time, the notifier is invoked @param x_type: Object type to register @param initializer: Loader function @return: None """ self[x_type] = self.__timeit__(self.timeit, initializer, x_type, self) def lazy_register(self, x_type, initializer: Callable[[Any], Any]) -> None: """ Register object or instance of any type in the container using lazy strategy. This method evaluates the load time, if the load time exceeds the allowed time, the notifier is invoked @param x_type: Object type to register @param initializer: Loader function @return: None """ self[x_type] = DLazy(x_type, initializer) def get(self, x_type: T, default=None) -> Optional[T]: """ Retrieve object registered in the container @param x_type: Object type @param default: If object not registered return this value @return: Optional object registered or default value """ dependency = self.container.get(x_type, default) if isinstance(dependency, DLazy): self.container[x_type] = self.__timeit__(self.timeit, dependency.initializer, x_type, self) return self.container[x_type] return dependency def take(self, key: Any, x_type: T, default=None) -> Optional[T]: """ Retrieve object registered in the container @param key: key used in registration @param x_type: type of value registered @param default: if the value registered not exist this value will be returned @return: value registered or default """ return self.get(key, default) def __timeit__(self, timeit: bool, fn: Any, x_type: Any, *args): if not timeit: return fn(args[0]) te = time.time() result = fn(args[0]) ts = time.time() taken = ts - te self.logger.info(f"Dependency load time: {x_type} :: {taken * 1000:2.2f} ms.") if taken >= self.max_time_allowed: msg = f"The dependency: {str(x_type)} is exceeding the allowed time. Taken: {taken:2.2f} - Max: {self.max_time_allowed}s." self.logger.warn(msg) if self.notifier: self.notifier(msg) return result def __getattr__(self, item: T) -> T: return self.get(item) zdi = DIContainer().create() def populate(initializer, container): print(initializer) parameters_name: Tuple[str, ...] = tuple(signature(initializer).parameters.keys()) parameters: Tuple[str, ...] = tuple(signature(initializer).parameters.items()) print(parameters_name) print(parameters) @wraps(initializer) def _decorated(*args, **kwargs): # all arguments were passed # if len(args) == len(parameters_name): # return service(*args, **kwargs) # if parameters_name == tuple(kwargs.keys()): # return service(**kwargs) # all_kwargs = _resolve_kwargs(args, kwargs) return initializer(1, 2, 3) return _decorated def inject(container: DIContainer = zdi): def _decorator(_service: Any) -> Any: if isclass(_service): setattr( _service, "__init__", populate(getattr(_service, "__init__"), container) ) return _service return _service return _decorator
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/containers/di_container.py
di_container.py
import json from abc import ABC, abstractmethod from datetime import timedelta from functools import wraps from timeit import default_timer as timer from typing import Any, Optional, List, Dict, Tuple from typing import Callable from zpy.api.http.errors import ZHttpError from zpy.api.http.response import _useAwsRequestId from zpy.api.http.status_codes import HttpMethods from zpy.app import zapp_context as api from zpy.app import zapp_context as ctx from zpy.containers import shared_container from zpy.logger import zL from zpy.utils.values import if_null_get DEFAULT_RESPONSE = {'statusCode': '500', 'headers': {'Content-Type': 'application/json', 'Content-Length': '120', 'Access-Control-Allow-Origin': '*'}, 'isBase64Encoded': False, 'body': '{"code":"INTERNAL SERVER ERROR","details":["The execution of a hook failed before reaching the main process."],"message":"The process could not be completed due to a semantics error."}'} class AWSEventStep(ABC): """ Event Step """ name: str raise_fails: Any response: dict def __init__(self, name: str, raise_fails: bool = True, response: dict = None): self.name = name self.raise_fails = raise_fails self.response = if_null_get(response, DEFAULT_RESPONSE) @abstractmethod def before(self, event: dict, contex: dict, *args, **kwargs) -> Tuple[Dict, Dict]: ... @abstractmethod def after(self, response: dict, *args, **kwargs) -> dict: """""" ... class EventMapper(ABC): @abstractmethod def configure(self, *args, **kwargs) -> None: pass @abstractmethod def execute(self, *args, **kwargs) -> Any: pass class RequestEventMapper(EventMapper): @abstractmethod def configure(self, event: dict, context: Any, *args, **kwargs) -> None: pass @abstractmethod def execute(self, event: dict, context: Any, *args, **kwargs) -> Tuple[Any, Any]: pass class ResponseEventMapper(EventMapper): @abstractmethod def configure(self, response: dict, *args, **kwargs) -> None: pass @abstractmethod def execute(self, response: dict, *args, **kwargs) -> Any: pass class RouteEventMapper: """ """ def __init__(self, route: str, http_method: HttpMethods = HttpMethods.GET, full_request_mapper: Optional[RequestEventMapper] = None, request: EventMapper = None, response: ResponseEventMapper = None, headers: EventMapper = None, query: EventMapper = None, path: EventMapper = None, *args, **kwargs) -> None: self.route = route self.http_method = http_method self.full_request_mapper: RequestEventMapper = full_request_mapper self.request_mappers: Dict[str, EventMapper] = { 'request': request, 'headers': headers, 'query_params': query, 'path_params': path } self.response_mapper: ResponseEventMapper = response self.extra_args = args self.extra_kwargs = kwargs def for_request(self, mapper: RequestEventMapper): self.request_mappers['request'] = mapper return self def for_response(self, mapper: ResponseEventMapper): self.response_mapper = mapper return self def for_headers(self, mapper: RequestEventMapper): self.request_mappers['headers'] = mapper return self def for_params(self, mapper: RequestEventMapper): self.request_mappers['query_params'] = mapper return self def for_path(self, mapper: RequestEventMapper): self.request_mappers['path_params'] = mapper return self def with_method(self, method: HttpMethods): self.http_method = method return self def with_meta(self, key: str, value: Any): self.extra_kwargs[key] = value return self def with_post(self): """ Configure POST http method @return: """ self.http_method = HttpMethods.POST return self def with_get(self): """ Configure GET http method @return: """ self.http_method = HttpMethods.GET return self def with_put(self): """ Configure GET http method @return: """ self.http_method = HttpMethods.PUT return self def with_patch(self): """ Configure PATCH http method @return: """ self.http_method = HttpMethods.PATCH return self def with_delete(self): """ Configure DELETE http method @return: """ self.http_method = HttpMethods.DELETE return self def configure_request_mappers(self, event: Dict, context: Any, *args, **kwargs): if self.full_request_mapper: self.full_request_mapper.configure(event, context, *(args + self.extra_args), **{**kwargs, **self.extra_kwargs}) for k in self.request_mappers: if self.request_mappers[k] and self.request_mappers[k] != self.full_request_mapper: self.request_mappers[k].configure(event, context, *(args + self.extra_args), **{**kwargs, **self.extra_kwargs}) def configure_response_mappers(self, response: Any, *args, **kwargs): if self.response_mapper: self.response_mapper.configure(response, *(args + self.extra_args), **{**kwargs, **self.extra_kwargs}) @classmethod def from_dict(cls, config: Dict[str, Dict[str, Any]], key: str = None): if not config: raise ValueError('Config cannot be null.') keys: List[str] = list(config.keys()) if not keys: raise ValueError('Config should be a key') str_route: str = if_null_get(key, keys[0]) def get_map(x): return x.get('mapper', None) def get(x, k) -> Dict: return x.get(k, {}) spec = get(config, str_route) default_mapper = get(spec, 'default').get('mapper', None) return cls(route=str_route, full_request_mapper=default_mapper, request=get_map(get(spec, 'request')), response=get_map(get(spec, 'response')), headers=get_map(get(spec, 'headers')), query=get_map(get(spec, 'query_params')), path=get_map(get(spec, 'path_params'))) class RouteEventMapperManager(AWSEventStep): def __init__(self, configs: List[RouteEventMapper] = None, name: str = 'RouteEventMapperManager', strict: bool = False, initializer: Callable[[Any, Any, Any, Any], None] = None, *args, **kwargs): super().__init__(name) if not configs: configs = [] self.configs: Dict[str, RouteEventMapper] = {f'{k.route}:{k.http_method.value}': k for k in configs} self.current: Optional[RouteEventMapper] = None self.config_found = False self.strict = strict self.extra_args = args self.extra_kwargs = kwargs self.initializer = initializer def add(self, route_config: RouteEventMapper) -> 'RouteEventMapperManager': self.configs[f'{route_config.route}:{route_config.http_method.value}'] = route_config return self def add_meta(self, key: str, value: Any) -> 'RouteEventMapperManager': self.extra_kwargs[key] = value return self @classmethod def from_dict(cls, configs: Dict, name: str): configurations = [RouteEventMapper.from_dict(configs, k) for k in configs.keys()] return cls(configurations, name) def before(self, event: dict, context: dict, *args, **kwargs) -> Tuple[Dict, Any]: if not event: return event, context if 'resource' not in event or 'httpMethod' not in event: return event, context current_route = f'{event["resource"]}:{event["httpMethod"]}' self.config_found = False if current_route in self.configs: if self.initializer: self.initializer(event, context, *self.extra_args, **self.extra_kwargs) self.current = self.configs[current_route] self.current.configure_request_mappers(event, context, *self.extra_args, **self.extra_kwargs) self.config_found = True if self.current.full_request_mapper: event, context = self.current.full_request_mapper.execute(event=event, context=context, *self.extra_args, **self.extra_kwargs) for x_mapper in self.current.request_mappers.values(): if x_mapper is not None: event, context = x_mapper.execute(event, context=context, *self.extra_args, **self.extra_kwargs) return event, context def after(self, response: dict, *args, **kwargs) -> dict: if self.config_found and self.current.response_mapper is not None: self.current.configure_response_mappers(response, *self.extra_args, **self.extra_kwargs) return self.current.response_mapper.execute(response=response, *self.extra_args, **self.extra_kwargs) return response def prepare_event_pipe_exception(e: ZHttpError) -> dict: body = {"code": f"{e.get_str_code()}", "details": e.details, "message": f"{e.get_message()}"} body = json.dumps(body) return {'statusCode': f'{e.get_http_code()}', 'headers': {'Content-Type': 'application/json', 'Content-Length': len(body), 'Access-Control-Allow-Origin': '*'}, 'isBase64Encoded': False, 'body': body} def lambda_event_pipe(event: dict, context: dict, processor: Callable[[Dict, Dict], Dict], steps: Optional[List[AWSEventStep]] = None): logger = ctx().logger response = None if not steps: steps = [] for mw in steps: try: event, context = mw.before(event, context) except ZHttpError as e: logger.exception(f"An error occurred when execute before: {mw.name}. ", exc_info=e) return prepare_event_pipe_exception(e) except Exception as e: logger.exception(f"An error occurred when execute before: {mw.name}. ", exc_info=e) if mw.raise_fails: return mw.response try: response = processor(event, context) except Exception as e: logger.exception(f"An error occurred when execute processor... ", exc_info=e) return DEFAULT_RESPONSE for mw in reversed(steps): try: response = mw.after(response) except ZHttpError as e: logger.exception(f"An error occurred when execute after: {mw.name}. ", exc_info=e) return prepare_event_pipe_exception(e) except Exception as e: logger.exception(f"An error occurred when execute after: {mw.name}. ", exc_info=e) if mw.raise_fails: return mw.response return response class LambdaEventPipe: def __init__(self, event: dict, context: Any): self.event = event self.context = context self.steps = [] def add(self, step: AWSEventStep) -> 'LambdaEventPipe': self.steps.append(step) return self def run(self, event_processor: Callable[[Dict, Any], Dict]) -> dict: return lambda_event_pipe(self.event, self.context, event_processor, self.steps) def store_request_id(context) -> Optional[str]: """Extract aws request id from context Args: context ([type]): Lambda context """ try: shared_container["aws_request_id"] = context.aws_request_id return context.aws_request_id except Exception as e: zL.ex("An error occurred while extracting aws request id", exc_info=e) return None def event_processors(storage: dict, use_id: bool, logs: bool, send_logs: bool, *args, **kwargs): """Lambda event processors Args: @param storage: @param use_id: @param logs: @param send_logs: """ try: if len(args) >= 2: event = args[0] storage['request'] = event if logs: api().logger.info(f"Request: {event}", shippable=send_logs) if _useAwsRequestId or use_id: storage['request_id'] = store_request_id(args[1]) else: if "event" in kwargs: storage['request'] = kwargs['event'] if logs: api().logger.info(f"Request: {kwargs['event']}", shippable=send_logs) if "context" in kwargs: if _useAwsRequestId or use_id: storage['request_id'] = store_request_id(args[1]) except Exception as e: api().logger.ex("An error occurred while processing event!", exc_info=e) def aws_lambda(logs: bool = True, save_id: bool = False, measure_time: bool = True, send_logs: bool = False, event_sender: Optional[Callable[[dict], Any]] = None): """Lambda Handler Args: @param event_sender: @param logs: (bool, optional): Logging request and response. Defaults to False. @param save_id: (bool, optional): Register aws lambda request id. Defaults to True. @param measure_time: (bool, optional): Measure elapsed execution time. Defaults to True. @param send_logs: Send event logs by log sender configured """ api().release_logger() event = {'request_id': '-'} def callable_fn(invoker: Callable): @wraps(invoker) def wrapper(*args, **kwargs): event_processors(event, save_id, logs, send_logs, *args, **kwargs) start = 0.0 if if_null_get(measure_time, False): start = timer() result = invoker(*args, **kwargs) event['response'] = result if logs: api().logger.info(f"Response: {result}", shippable=send_logs) if if_null_get(measure_time, False): end = timer() api().logger.info(f"Elapsed execution time: {timedelta(seconds=end - start)}", shippable=send_logs) if event_sender: event_sender(event) return result return wrapper return callable_fn
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/api/flask/cloud_handlers.py
cloud_handlers.py
from typing import Any, List, Optional, Dict from flask_cors import CORS from flask import Flask from zpy.api.flask.zhooks import ZHook from zpy.api.flask.zmiddlewares import ZMiddleware def create_flask_app( config: dict, path_cors_allow: str = None, origins: List[str] = None ) -> Flask: """ Flask app builder """ app = Flask(__name__, instance_relative_config=True) app.config.from_object(config) path_allow = "/*" if path_cors_allow is None or path_cors_allow == '' else path_cors_allow _origins = '*' if origins is None or len(origins) <= 0 else origins CORS(app, resources={path_allow: {"origins": _origins}}) return app def create_app(app: Optional[Flask] = None, mw: Optional[List[ZMiddleware]] = None, mw_args: Optional[List[Any]] = None, hk: Optional[List[ZHook]] = None, hk_args: Optional[List[Any]] = None, shared_data: Dict[Any, Any] = None, path_cors_allow: str = None, origins_cors: List[str] = None ) -> Flask: """ API App Builder @param app: Flask application instance. @param mw: Middlewares @param mw_args: Middleware arguments @param hk: Hooks @param hk_args: hooks arguments @param shared_data: data for setup in flask context @param path_cors_allow: Path for configure cors origins. Default: '/*' @param origins_cors: Origins for configure cors. Default '*' @return: flask instance """ if hk_args is None: hk_args = [] if mw_args is None: mw_args = [] if shared_data is None: shared_data = {} if hk is None: hk = [] if mw is None: mw = [] if app is None: app = create_flask_app(shared_data, path_cors_allow, origins_cors) for i, m in enumerate(mw): args = mw_args[i] if i < len(mw_args) else {} args.update(shared_data) app.wsgi_app = m(app.wsgi_app, **args) for i, h in enumerate(hk): args = hk_args[i] if i < len(hk_args) else {} args.update(shared_data) h().execute(app, **args) return app
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/api/flask/__init__.py
__init__.py
import logging from typing import Any, Callable, Tuple, Optional from .serializers import serialize_object_value from zpy.api.http.errors import ZHttpError from zpy.api.http.status_codes import HttpStatus from zpy.containers import shared_container from zpy.utils.objects import ZObjectModel from zpy.utils.values import if_null_get _useAwsRequestId = False _custom_request_id_key: Optional[str] = None _wrapPayloadKey = None _useStatusFields = False _custom_status_key: Optional[str] = None _custom_message_key: Optional[str] = None _custom_builder: Optional[Callable[[dict, HttpStatus, dict], Tuple[dict, int, dict]]] = None _custom_error_builder: Optional[Callable[[dict, HttpStatus, dict], Tuple[dict, int, dict]]] = None _custom_err_code_key: Optional[str] = None _custom_err_message_key: Optional[str] = None _custom_err_details_key: Optional[str] = None _custom_err_meta_key: Optional[str] = None def setup_error_response( custom_code_key: Optional[str] = None, custom_message_key: Optional[str] = None, custom_details_key: Optional[str] = None, custom_metadata_key: Optional[str] = None ): global _custom_err_code_key _custom_err_code_key = custom_code_key global _custom_err_message_key _custom_err_message_key = custom_message_key global _custom_err_details_key _custom_err_details_key = custom_details_key global _custom_err_meta_key _custom_err_meta_key = custom_metadata_key def setup_response_builder( use_aws_request_id: bool = False, wrap_payload_key: Optional[str] = None, use_status_fields: bool = False, custom_builder: Callable = None, custom_error_builder: Callable = None, custom_request_id_key: Optional[str] = None, custom_status_key: Optional[str] = None, custom_message_key: Optional[str] = None ) -> None: """ Configure response builder according you need it @param use_aws_request_id: True if you work with aws services and need add aws request id into your response @param wrap_payload_key: Pass string key for wrap your payload @param use_status_fields: True if you need add 'status' and 'message' fields into response @param custom_builder: Function to update or build response according you need it @param custom_error_builder: Function to update or build error response according you need it @param custom_request_id_key: Custom name for request id @param custom_message_key: Custom key name for message prop @param custom_status_key: Custom key name for message prop @return: None """ global _useAwsRequestId _useAwsRequestId = use_aws_request_id global _wrapPayloadKey _wrapPayloadKey = wrap_payload_key global _useStatusFields _useStatusFields = use_status_fields global _custom_builder _custom_builder = custom_builder global _custom_error_builder _custom_error_builder = custom_error_builder global _custom_request_id_key _custom_request_id_key = custom_request_id_key global _custom_status_key _custom_status_key = custom_status_key global _custom_message_key _custom_message_key = custom_message_key class SuccessResponse(object): def __init__(self, status: HttpStatus = HttpStatus.SUCCESS) -> None: self._http_status_ = status @property def http_status(self): return self._http_status_ @staticmethod def empty(status: HttpStatus = HttpStatus.SUCCESS): res = ZTResponse() res._http_status_ = status return res class ZTResponse(ZObjectModel, SuccessResponse): def __init__(self, **kwargs): ZObjectModel.__init__(self, use_native_dumps=True, **kwargs) SuccessResponse.__init__(self) def update_error_response(response: dict, status: HttpStatus = HttpStatus.INTERNAL_SERVER_ERROR, headers: Optional[dict] = None) -> Tuple[dict, int, dict]: """ Http error response updater @param response: error response content @param status: http status @param headers: headers @return: tuple with response data @contact https://www.linkedin.com/in/zurckz @author Noé Cruz | Zurck'z 20 @since 16-05-2020 """ http_status_code: int = status.value[0] if _useAwsRequestId is True: if type(response) is dict and "aws_request_id" in shared_container: response.update({f"{if_null_get(_custom_request_id_key, 'requestId')}": shared_container["aws_request_id"]}) if _custom_error_builder is not None: response, code, headers = _custom_error_builder(response, status, headers) http_status_code = code return response, http_status_code, headers def update_response( payload: dict, status: HttpStatus = HttpStatus.SUCCESS, headers: Optional[dict] = None ) -> Tuple[dict, int, dict]: """ Http response updater @param payload: @param status: @param headers: @return: tuple with reponse data @contact https://www.linkedin.com/in/zurckz @author Noé Cruz | Zurck'z 20 @since 16-05-2020 """ http_status_code = status.value[0] if _wrapPayloadKey is not None and _wrapPayloadKey != "": payload = {_wrapPayloadKey: payload} if _useStatusFields is True: if type(payload) is dict: _key_m = if_null_get(_custom_message_key, 'message') _key_s = if_null_get(_custom_status_key, 'status') payload.update({f"{_key_s}": status.value[1], f"{_key_m}": status.value[2]}) if _useAwsRequestId is True: _key = if_null_get(_custom_request_id_key, 'request_id') payload.update({f"{_key}": None}) if type(payload) is dict and "aws_request_id" in shared_container: payload.update({f"{_key}": shared_container["aws_request_id"]}) if _custom_builder is not None: payload, code, headers = _custom_builder(payload, status, headers) http_status_code = code return payload, http_status_code, headers def response_builder(content_type: Optional[str] = 'application/json', headers: Optional[dict] = None): """ HTTP Response builder, build response from data provided @param content_type: Response content type. Default: application/json @param headers: Extra headers @return: None @contact https://www.linkedin.com/in/zurckz @author Noé Cruz | Zurck'z 20 @since 16-05-2020 """ extra_headers = {'Content-Type': content_type} def z_inner_builder(invoker: Callable): def wrapper_handler(*args, **kwargs): try: payload: Any = invoker(*args, **kwargs) if issubclass(payload.__class__, ZObjectModel) and issubclass( payload.__class__, SuccessResponse ): return update_response(payload.sdump(), payload.http_status) if issubclass(payload.__class__, ZObjectModel): return update_response(payload.sdump()) if issubclass(payload.__class__, SuccessResponse): return update_response( serialize_object_value(payload), payload.http_status ) return update_response(serialize_object_value(payload), headers=extra_headers) except ZHttpError as e: logging.exception("[ZCE] - An error was generated when processing request.") http_status: HttpStatus = e.status if e.reason is not None: e.details = [e.reason] + if_null_get(e.details, []) err_response = { f"{if_null_get(_custom_err_message_key, 'message')}": if_null_get(e.message, http_status.value[2]), f"{if_null_get(_custom_err_code_key, 'code')}": http_status.value[1], f"{if_null_get(_custom_err_details_key, 'details')}": e.details, } if e.metadata is not None: err_response[f'{if_null_get(_custom_err_meta_key, "metadata")}'] = e.metadata return update_error_response( err_response, http_status ) except Exception as e: logging.exception( "[UCE] - An unexpected error was generated when processing request.", exc_info=e ) code: HttpStatus = HttpStatus.INTERNAL_SERVER_ERROR return update_error_response( {f"{if_null_get(_custom_err_message_key, 'message')}": code.value[2], f"{if_null_get(_custom_err_code_key, 'code')}": code.value[1], f"{if_null_get(_custom_err_details_key, 'details')}": None}, code ) wrapper_handler.__name__ = invoker.__name__ return wrapper_handler return z_inner_builder
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/api/http/response.py
response.py
from enum import Enum from dataclasses import dataclass from typing import Tuple, Union @dataclass class DynamicHttpStatus: value: Tuple[int, str, str] class HttpMethods(Enum): GET = 'GET' POST = 'POST' PUT = 'PUT' PATCH = 'PATCH' DELETE = 'DELETE' OPTIONS = 'OPTIONS' class HttpStatus(Enum): """ Common HTTP status codes CODE | SHORT DESCRIPTION | STATUS DETAILS """ SUCCESS = (200, "SUCCEEDED", "The request has succeeded") CREATED = (201, "CREATED","The request has been fulfilled and resulted in a new resource being created.") ACCEPTED = (202, "ACCEPTED","The request has been accepted for processing, but the processing has not been completed.") NO_CONTENT = (204, "NO CONTENT","The request has been completed successfully but your response has no content, although the headers can be useful.",) PARTIAL_CONTENT = (206, "PARTIAL CONTENT", "Partial content") BAD_REQUEST = (400, "BAD REQUEST","The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.",) UNAUTHORIZED = (401, "UNAUTHORIZED", "The request requires user authentication.") FORBIDDEN = (403, "FORBIDDEN","The server understood the request, but is refusing to fulfill it.") NOT_FOUND = (404, "NOT FOUND","The server has not found anything matching the Request-URI.",) METHOD_NOT_ALLOWED = (405, "METHOD NOT ALLOWED","The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.",) CONTENT_NOT_ACCEPTABLE = (406, "METHOD NOT ACCEPTABLE","The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.",) REQUEST_TIMEOUT = (408, "REQUEST TIMEOUT", "Time out") PRE_CONDITION_FAILED = (412, "PRECONDITION FAILED","The client has indicated preconditions in their headers which the server does not meet.",) UNSUPPORTED_MEDIA_TYPE = (415, "UNSUPPORTED MEDIA TYPE","The multimedia format of the requested data is not supported by the server, therefore the server rejects the request.",) IM_A_TEAPOT = (418, "IM A TEAPOT","The server refuses to try to make coffee with a kettle.",) CONFLICT = (409, "CONFLICT", "The server found conflict with request supplied.") UNPROCESSABLE = (422, "UNPROCESSABLE ENTITY","The process could not be completed due to a semantics error.",) LOCKED = (423, "LOCKED","The source or destination resource of a method is locked.",) INTERNAL_SERVER_ERROR = (500, "INTERNAL SERVER ERROR","The server encountered an unexpected condition which prevented it from fulfilling the request.",) NOT_IMPLEMENTED = (501, "NOT IMPLEMENTED","The server does not support the functionality required to fulfill the request",) SERVICE_UNAVAIBLE = (503, "SERVICE UNAVAIBLE","The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.",) GATEWAY_TIMEOUT = (503, "GATEWAY TIMEOUT", "Timeout") LOOP_DETECTED = (508, "LOOP DETECTED","The server encountered an infinite loop while processing the request. ",) @staticmethod def dynamic(code: int, status: str, message: str) -> Union['HttpStatus', DynamicHttpStatus]: """ Build custom http status from values @param code: http status code @param status: status description @param message: status message @return: DynamicHttpStatus """ return DynamicHttpStatus((code, status, message))
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/api/http/status_codes.py
status_codes.py
from typing import Optional, List from zpy.api.http.status_codes import HttpStatus class ZError(Exception): """Base Error Args: Exception ([type]): [description] """ def __init__( self, message: str, reason: str, details: Optional[List[str]], meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, *args) self.reason = reason self.message = message self.details = details self.metadata = meta self.internal_exception = parent_ex def add_detail(self, message: str) -> None: if self.details is None: self.details = [] self.details.append(message) def set_metadata(self, value: dict): self.metadata = value def __str__(self): return f'[ZCE] - {self.message}\n\t - {self.reason}' class ZHttpError(ZError): """Http Base Error Args: ZError ([type]): [description] """ def __init__( self, message: str = None, reason: str = None, details: Optional[List[str]] = None, status: HttpStatus = HttpStatus.INTERNAL_SERVER_ERROR, meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, reason, details, meta, parent_ex, *args) self.status = status def get_http_code(self) -> int: return self.status.value[0] def get_http_message(self) -> str: return self.status.value[2] def get_str_code(self) -> str: return self.status.value[1] def get_message(self): return self.get_http_message() if not self.message else self.message class BadRequest(ZHttpError): """BadRequest Args: ZError ([type]): [description] """ def __init__( self, message: str = None, reason: str = None, details: Optional[List[str]] = None, meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, reason, details, HttpStatus.BAD_REQUEST, meta, parent_ex, *args) class Unauthorized(ZHttpError): """Unauthorized Args: ZError ([type]): [description] """ def __init__( self, message: str = None, reason: str = None, details: Optional[List[str]] = None, meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, reason, details, HttpStatus.UNAUTHORIZED, meta, parent_ex, *args) class NotFound(ZHttpError): """BadRequest Args: ZError ([type]): [description] """ def __init__( self, message: str = None, reason: str = None, details: Optional[List[str]] = None, meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, reason, details, HttpStatus.NOT_FOUND, meta, parent_ex, *args) class UnprocessableEntity(ZHttpError): """UnprocessableEntity Args: ZError ([type]): [description] """ def __init__( self, message: str = None, reason: str = None, details: Optional[List[str]] = None, meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, reason, details, HttpStatus.UNPROCESSABLE, meta, parent_ex, *args) class Forbidden(ZHttpError): """Forbidden Args: ZError ([type]): [description] """ def __init__( self, message: str = None, reason: str = None, details: Optional[List[str]] = None, meta: Optional[dict] = None, parent_ex: Exception = None, *args: object ) -> None: super().__init__(message, reason, details, HttpStatus.FORBIDDEN, meta, parent_ex, *args)
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/api/http/errors.py
errors.py
from abc import abstractmethod from typing import List, Tuple, Union, Any, TypeVar from marshmallow.exceptions import ValidationError from zpy.api.http.errors import BadRequest, ZHttpError from zpy.utils.objects import ZObjectModel R = TypeVar('R') class ZRequest: @abstractmethod def verify(self, *args, **kwargs): """ Execute extra validations over data @param args: @param kwargs: @return: """ pass @abstractmethod def patch(self, *args, **kwargs): """ Update properties values @param args: @param kwargs: @return: """ pass def query(queries: dict, name: str, default: Any = None, raise_errors=True, type_data: Any = None): """ Extract query param from dict @param queries: @param name: @param default: @param raise_errors: @param type_data: @return: """ def raise_or_return(msg: str): if raise_errors: raise BadRequest(reason=msg) return default if not queries or name not in queries: return raise_or_return(f"Missing query param: {name}") value = queries.get(name, None) if not value: return raise_or_return(f"Missing value query param: {name}") if type_data and not isinstance(value, type_data): return raise_or_return( f"Unexpected type data for query param value: {name}. Expected type: {type_data.__name__}") return value def parse_request( request: dict, model: Union[R, Any], raise_err: bool = True ) -> Tuple[Union[R, Any], ZHttpError]: """ Parse and validate request according model specification. @param request: @param model: @param raise_err: @return: """ model_result: Union[List, ZObjectModel, Any] = None errors: Union[List, None, BadRequest] = None try: if request is None or len(request.items()) == 0: error = BadRequest( "The request was not provided, validation request error", f"Missing fields {model().__missing_fields__} not provided", ) if raise_err: raise error return None, error model_result = model(**request) except ValidationError as e: model_result = e.valid_data # if isinstance(e.messages, Dict): # errors = [e.messages] # else: # errors = e.messages errors = BadRequest(None, f"{e.messages}") if raise_err: raise errors return model_result, errors
zpy-api-core
/zpy-api-core-1.8.0.tar.gz/zpy-api-core-1.8.0/zpy/api/http/request.py
request.py